filament-cli 0.6.1

P2P file transfer between terminals and browsers, no upload, no account. The terminal end of filament.autumated.com.
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
// filament, anywhere-to-anywhere P2P file transfer, CLI end.
//
// Speaks the exact same wire protocol as the browser app at
// https://filament.autumated.com: Socket.IO signaling, perfect-negotiation
// WebRTC, one-time pairing codes, and sid-framed chunk transfer with
// offset-based resume. A browser is a first-class peer: `filament send` can
// deliver straight to a phone with nothing installed on it.
//
//   filament send video.mp4 --code          mint a speakable one-time code
//   filament recv clever-lynx-63            claim it on the other machine
//   filament send ./dir --room demo         directories are tarred on the fly
//   tar c logs | filament send - --name logs.tar --code
//   filament recv -y --dir ~/Drops          auto-accept into a directory
//
// Failure-mode ledger: ../docs/cli-resilience.md, every resilience behavior
// in this file carries its ledger number (C1..C17 / F1..F4).

mod codeentry;
mod ctl;
mod diag;
mod direct;
mod doctor;
/// `filament expose`: publish a local port on the L3 overlay. The CLI/config side
/// is portable; the daemon listeners (Exposer) are Linux-gated with L3.
mod expose;
mod holepunch;
mod interact;
mod l2;
mod mount;
mod mount_proto;
#[cfg(target_os = "linux")]
mod mount_fuse;
#[cfg(all(target_os = "windows", feature = "mount-windows"))]
mod mount_winfsp;
mod backup;
mod net;
mod overlay;
mod platform;
mod pake;
mod pake_ceremony;
mod ping;
mod sdnotify;
mod protocol;
mod resilience;
mod session;
mod settings;
/// L3 TUN data plane (serve_tun). Linux-only: it uses /dev/net/tun + TUNSETIFF,
/// which macOS (also `unix`) lacks, so gate on `target_os`, not `unix`.
#[cfg(l3)]
mod tun;
/// L3 overlay manager (routes IP packets across peer links); Linux-only.
#[cfg(l3)]
mod l3;
mod shutdown;
mod sshd;
mod sshkeys;
mod local;
mod ui;

use anyhow::{anyhow, bail, Context, Result};
use clap::{Parser, Subcommand};
use net::{Ev, Peer, Transport};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::io::{IsTerminal, Read, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use tokio::sync::{mpsc, oneshot};

/// Positional write at an absolute offset, used by concurrent spawn_blocking
/// writer tasks for out-of-order multi-stream reassembly (no seek, atomic per
/// call). Cross-platform: `FileExt::write_at` on Unix, `seek_write` on Windows —
/// both write at `offset` without moving the shared handle's cursor.
#[cfg(unix)]
fn pwrite_at(file: &std::fs::File, buf: &[u8], offset: u64) -> std::io::Result<usize> {
    use std::os::unix::fs::FileExt;
    file.write_at(buf, offset)
}
#[cfg(windows)]
fn pwrite_at(file: &std::fs::File, buf: &[u8], offset: u64) -> std::io::Result<usize> {
    use std::os::windows::fs::FileExt;
    file.seek_write(buf, offset)
}

const DEFAULT_SERVER: &str = "https://api.filament.autumated.com";
/// C7: content identity for resume, sha256 over the first 256 KiB.
const HEAD_BYTES: u64 = 256 * 1024;
/// C4/C6/C21: how long we wait for a vanished peer to rejoin. UNWARNED is the
/// blind default; a peer that announced `brb` (e.g. the browser opening a
/// mobile file picker suspends the whole tab) gets its declared ttl instead,
/// informed waits are both longer when promised and shorter when not.
const REJOIN_WINDOW: Duration = Duration::from_secs(120);
fn rejoin_unwarned() -> Duration {
    std::env::var("FILAMENT_REJOIN_SECS") // test knob (gate 15)
        .ok()
        .and_then(|v| v.parse().ok())
        .map(Duration::from_secs)
        .unwrap_or(Duration::from_secs(45))
}
/// G-k: how long the recv quiet-check must hold (everything done, nobody
/// attached, no questions) before exiting without a `peer-left`. The 10 s
/// default is overridable for tests (gate 18).
fn quiet_exit_window() -> Duration {
    std::env::var("FILAMENT_QUIET_EXIT_SECS") // test knob (gate 18)
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .map(Duration::from_secs)
        .unwrap_or(Duration::from_secs(10))
}
/// C3/C4: connection (re)establishment attempts before failing honestly.
const MAX_ATTEMPTS: u32 = 5;

/// Test/injection hooks, env-gated fault injectors used ONLY by the resilience
/// gates (runner/sim/*) to drive deterministic failure modes. They are compiled
/// in ONLY under `--features test-hooks`; a default/release build strips them
/// entirely (no env reads, no injection logic in the shipped binary). Each hook
/// has a `not(feature = "test-hooks")` twin that returns the production value
/// (the no-hook path), so the surrounding real logic compiles and behaves
/// EXACTLY as if the hook were absent. See cli/Cargo.toml [features].test-hooks.
#[cfg(feature = "test-hooks")]
mod test_hooks {
    /// gate 17b: connect but never send our SPAKE2 element so the ceremony budget fires.
    pub fn pair_stall() -> bool {
        std::env::var("FILAMENT_TEST_PAIR_STALL").is_ok()
    }
    /// P1: force every WebRTC link relay-only (models a hard-NAT peer).
    pub fn webrtc_relay_only() -> bool {
        std::env::var("FILAMENT_TEST_WEBRTC_RELAY_ONLY").map(|v| v == "1").unwrap_or(false)
    }
    /// gate 18b: revert the mode-B post-completion drop to reconnect-always.
    pub fn disable_modeb_drop() -> bool {
        std::env::var("FILAMENT_TEST_DISABLE_MODEB_DROP").is_ok()
    }
    /// #28: revert the deferred peer-left drop to unconditional-drop.
    pub fn no_defer() -> bool {
        std::env::var("FILAMENT_TEST_NO_DEFER").is_ok()
    }
    /// #28: synthesize a peer-left for the active sid once N file-data bytes are sent.
    pub fn inject_peer_left_at() -> Option<u64> {
        std::env::var("FILAMENT_TEST_INJECT_PEER_LEFT").ok().and_then(|v| v.parse::<u64>().ok())
    }
    /// signaling-drop gate: revert the daemon acceptor to the no-outer-loop path.
    pub fn no_signaling_reconnect() -> bool {
        std::env::var("FILAMENT_TEST_NO_SIGNALING_RECONNECT").is_ok()
    }
    /// shutdown-hang gate: deterministically reproduce the multi-link shutdown
    /// hang by WEDGING the event loop forever (simulating a peer transport whose
    /// inline write never returns). With the wedge active, the graceful
    /// Ev::Interrupted is never processed; only the signal-owned force-exit
    /// watchdog can still terminate the process. Proves the A/B: a build whose
    /// watchdog is defeated hangs to the systemd timeout, the shipped one exits
    /// within the bounded grace.
    pub fn wedge_loop_on_shutdown() -> bool {
        std::env::var("FILAMENT_TEST_WEDGE_LOOP").is_ok()
    }
    /// warm-standby gate: churn surviving links after completion to force the C4 flap.
    pub fn churn_after_complete() -> bool {
        std::env::var("FILAMENT_TEST_CHURN_AFTER_COMPLETE").is_ok()
    }
    /// gate 18: drop the file-end control frame so the completion sweep must finalize.
    pub fn drop_file_end() -> bool {
        std::env::var("FILAMENT_TEST_DROP_FILE_END").is_ok()
    }
    /// gate 18: drop a peer-left event so the quiet-exit fallback is exercised.
    pub fn drop_peer_left() -> bool {
        std::env::var("FILAMENT_TEST_DROP_PEER_LEFT").is_ok()
    }
    /// P4 silent-data-loss gate: the receiver finalizes the file INTACT but
    /// suppresses the outbound `delivery-ack`, faithfully simulating an ack that
    /// never reaches the sender on an otherwise-healthy link (the black-hole-on-
    /// the-ack case). The sender must then re-probe and end UNCONFIRMED, never a
    /// false "delivered + verified". Distinct from corrupt-recv (which drives the
    /// re-request loop): here the bytes are whole, only the ack is withheld.
    pub fn suppress_delivery_ack() -> bool {
        std::env::var("FILAMENT_TEST_SUPPRESS_ACK").is_ok()
    }

    /// BUG-ACKLOSS reproducer (test-only): `FILAMENT_TEST_PREMATURE_CLOSE=1` tears
    /// the link DOWN at the exact moment the delivery-ack is due, so the ack never
    /// reaches the sender and the sender's transport observes ApplicationClosed(0,"").
    /// QUIC has no flush-on-close (RFC 9000 s10.2), so this is precisely the
    /// self-inflicted teardown race the multi-stream push otherwise hit only ~1-in-5
    /// on 10GB cross-machine transfers -- made DETERMINISTIC on a 1MB localhost
    /// transfer. The sender then sits in AWAIT_ACK on a dead link (the corpse
    /// cascade). Models `premature_close` in proofs/transport_lifecycle_model.py.
    /// No-op on default/release (compiled out). `=1` fires on EVERY completion;
    /// `=once` fires exactly once then falls through to a normal ack -- so an `up`
    /// daemon receiver (which stays alive) can be re-dialed and RECOVER (deliver on
    /// the second attempt) instead of looping drop -> re-dial -> drop. The latch is
    /// a process-global AtomicBool, mirroring corrupt_once.
    pub fn premature_close_after_ack() -> bool {
        matches!(std::env::var("FILAMENT_TEST_PREMATURE_CLOSE").as_deref(), Ok("1") | Ok("once"))
    }
    static PREMATURE_FIRED: std::sync::atomic::AtomicBool =
        std::sync::atomic::AtomicBool::new(false);
    pub fn premature_close_once() -> bool {
        std::env::var("FILAMENT_TEST_PREMATURE_CLOSE").as_deref() == Ok("once")
    }
    pub fn premature_already_fired() -> bool {
        PREMATURE_FIRED.load(std::sync::atomic::Ordering::SeqCst)
    }
    pub fn premature_mark_fired() {
        PREMATURE_FIRED.store(true, std::sync::atomic::Ordering::SeqCst);
    }

    /// truncation/ack gate corruption injector. `FILAMENT_TEST_CORRUPT_RECV=<id>`
    /// flips the last on-disk byte of the matching transfer; `_CORRUPT_ONCE=1`
    /// fires exactly once (proving auto-recovery). The "already fired" latch is a
    /// process-global AtomicBool, no env mutation (the old code did an unsafe
    /// `set_var` of `FILAMENT_TEST_CORRUPT_FIRED` inside the async runtime).
    static CORRUPT_FIRED: std::sync::atomic::AtomicBool =
        std::sync::atomic::AtomicBool::new(false);

    /// The configured corrupt-recv target id, if any.
    pub fn corrupt_recv_target() -> Option<String> {
        std::env::var("FILAMENT_TEST_CORRUPT_RECV").ok()
    }
    pub fn corrupt_recv_once() -> bool {
        std::env::var("FILAMENT_TEST_CORRUPT_ONCE").map(|v| v == "1").unwrap_or(false)
    }
    pub fn corrupt_already_fired() -> bool {
        CORRUPT_FIRED.load(std::sync::atomic::Ordering::SeqCst)
    }
    pub fn corrupt_mark_fired() {
        CORRUPT_FIRED.store(true, std::sync::atomic::Ordering::SeqCst);
    }
}

/// Production twins of the test hooks: each returns the no-hook value so the real
/// logic is byte-for-byte the shipped behavior when `test-hooks` is off.
#[cfg(not(feature = "test-hooks"))]
mod test_hooks {
    #[inline] pub fn pair_stall() -> bool { false }
    #[inline] pub fn webrtc_relay_only() -> bool { false }
    #[inline] pub fn disable_modeb_drop() -> bool { false }
    #[inline] pub fn no_defer() -> bool { false }
    #[inline] pub fn inject_peer_left_at() -> Option<u64> { None }
    #[inline] pub fn no_signaling_reconnect() -> bool { false }
    #[inline] pub fn wedge_loop_on_shutdown() -> bool { false }
    #[inline] pub fn churn_after_complete() -> bool { false }
    #[inline] pub fn drop_file_end() -> bool { false }
    #[inline] pub fn drop_peer_left() -> bool { false }
    #[inline] pub fn suppress_delivery_ack() -> bool { false }
    #[inline] pub fn premature_close_after_ack() -> bool { false }
    #[inline] pub fn premature_close_once() -> bool { false }
    #[inline] pub fn premature_already_fired() -> bool { false }
    #[inline] pub fn premature_mark_fired() {}
    #[inline] pub fn corrupt_recv_target() -> Option<String> { None }
}

/// P1 (GAP-4): process-global "the user forbade relay" flag, set once from the
/// `--no-relay` CLI flag at startup. Read by `Conn::relay_forbidden` so the
/// stall ladder knows, at `Rung::Exhausted`, whether it MAY auto-escalate to a
/// TURN relay (the never-flaky promise) or must FAIL CLEANLY (the hard
/// direct-only promise the user asked for). A global rather than a threaded
/// param so the many `Conn` construction sites stay untouched; written exactly
/// once, before the runtime spawns any worker (mirrors the `FILAMENT_NAME`
/// single-threaded-set pattern in `run`).
static NO_RELAY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// True when the user passed `--no-relay`: relay fallback is forbidden.
fn relay_forbidden() -> bool {
    NO_RELAY.load(std::sync::atomic::Ordering::Relaxed)
}

/// Set once in `run`, before any worker spawns, from the global `--no-interactive`
/// flag (mirrors NO_RELAY). The guided code entry NEVER opens when this is set.
static NO_INTERACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// App-wide UI capability resolved once from flags + env. Controls how every
/// command renders: interactive vs steer, human vs JSON, color vs plain.
pub struct UiCapability {
    pub interactive: bool,
    pub json: bool,
    pub yes: bool,
    pub color: bool,
}

impl UiCapability {
    pub(crate) fn from_cli(cli: &Cli) -> Self {
        let interactive = std::io::stdin().is_terminal()
            && !cli.no_interactive
            && std::env::var_os("FILAMENT_NONINTERACTIVE").is_none();
        let color = match cli.color.as_deref() {
            Some("always") => true,
            Some("never") => false,
            _ => std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none(),
        };
        UiCapability { interactive, json: cli.json, yes: cli.yes, color }
    }

    pub fn confirm(&self, action: &str) -> Result<()> {
        if self.yes { return Ok(()); }
        if self.interactive {
            use std::io::Write;
            eprint!("{action} [y/N] ");
            let _ = std::io::stderr().flush();
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).ok();
            if !matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes") {
                anyhow::bail!("cancelled");
            }
        } else {
            anyhow::bail!("refusing {action} without --yes (non-interactive)");
        }
        Ok(())
    }
}

/// THE interactivity GATE, scripts/automation are safe BY DEFAULT. Three layers:
///   1. stdin is not a TTY  -> never interactive (pipes, CI, `< /dev/null`).
///   2. TTY but opted out    -> never interactive: `--no-interactive` OR the env
///                              var `FILAMENT_NONINTERACTIVE` (any value).
///   3. TTY and not opted out -> interactive (the guided entry may open).
/// When this returns false, callers MUST keep exactly today's behavior (a clear
/// parse error + expected format and non-zero exit for a malformed arg, or the
/// existing non-interactive default for a missing-but-optional code). NEVER block.
fn interactive_allowed() -> bool {
    std::io::stdin().is_terminal()
        && !NO_INTERACTIVE.load(std::sync::atomic::Ordering::Relaxed)
        && std::env::var_os("FILAMENT_NONINTERACTIVE").is_none()
}

/// The one honest CLI line shown whenever a transfer/connection is actually on
/// the TURN relay route (rung d). Relay is still end-to-end encrypted, but it is
/// NOT a direct link, the "no middleman on the wire" property is gone, so we say
/// so, loudly (amber ⚠), reusing `ui::Tone::Warn`. §3.3 of the design.
fn relay_banner() -> String {
    ui::paint(
        ui::Tone::Warn,
        "⚠ on relay, via a TURN server, not a direct link (still end-to-end encrypted)",
    )
}

/// P0 (GAP-1): stall-correction ladder bound. Attempt 0 is rung (a) (resume on
/// the same transport); attempts 1..STALL_MAX_REPAIRS are rung (c) (repair the
/// transport in place, a fresh direct dial / ICE-restart). At the ceiling the
/// ladder is exhausted (P1's relay fallback is the next rung, a clean hook).
/// Slightly above MAX_ATTEMPTS because a fresh direct dial needs BOTH ends to
/// re-offer within one race budget, which can take a couple of aligned ticks;
/// a re-dial is cheap, so a few extra are worth a deterministic recovery.
const STALL_MAX_REPAIRS: u32 = 5;

/// P5 (GAP-6): reserved sid for the relay->direct upgrade VERIFY heartbeat. A
/// real DATA frame on this sid lets the prober confirm the new direct path is
/// actually MOVING data (not just connected) before cutting over. It lives in the
/// non-L2 sid space and far above any file-transfer counter, so it never collides;
/// the receiver has no `by_sid` entry for it, so the inbound chunk is dropped
/// harmlessly (after stamping inbound activity, which is the point: symmetric
/// verify). See `Conn::judge_upgrade_standby`.
const VERIFY_PROBE_SID: u32 = 0x7FFF_FFFF;

/// P4 (GAP-5): how many times the receiver re-requests a transfer whose
/// whole-file sha256 didn't match on completion (truncated/corrupt) before it
/// gives up and fails CLEARLY (kept partial, no silent bad file). A transient
/// truncation recovers on the first resume; this bound only catches a payload
/// that is genuinely, repeatedly corrupt, never a hang, never a silent accept.
const MAX_VERIFY_FAILS: u32 = 3;

/// Gate-18 Mode B: the single predicate that decides whether a stuck/lost link
/// should be DROPPED (transfer is complete; nothing left to fetch) rather than
/// reconnected. Pulled out as a pure function so the gate-2 / gate-11c fence
/// (mid-transfer links must NEVER be dropped) is unit-testable without a live
/// WebRTC peer. The recv loop computes `conn.recv_done` from exactly this each
/// tick; `on_stuck` then reads the flag.
///
/// The pure file-transfer decisions `recv_transfer_done` and `decide_ack_fallback`
/// (+ the `AckFallback` enum) now live in `protocol.rs` (the Rust mirror of the JS
/// net/protocol layer); the send/recv loops call `protocol::...`.

/// Bug 5: after repeated stuck-while-connecting on establishment, the user has
/// no clue WHY. The dominant single-host cause is a browser publishing mDNS
/// (`*.local`) ICE candidates the CLI can't resolve when both ends share one
/// machine, the candidate pair never nominates and the link wedges silently.
/// Print this hint at most once per command. `shown` is the caller's one-shot
/// latch so the hint never repeats and never fires on a normal first blip.
fn maybe_hint_local_wedge(shown: &mut bool) {
    if *shown {
        return;
    }
    *shown = true;
    ui::say(&ui::paint(
        ui::Tone::Dim,
        "  still can't connect, if both ends are on the SAME machine, a browser's \
         mDNS (.local) ICE candidates can block this; try a different network path, \
         or disable mDNS ICE in the browser (chrome://flags → \"Anonymize local IPs\").",
    ));
}

const VERSION: &str = env!("FILAMENT_BUILD_INFO"); // stamped by build.rs

const EXAMPLES: &str = "\
EXAMPLES:
  filament video.mp4                 send it; mints a speakable one-time code + QR
  filament clever-lynx-63            claim a code and receive
  filament recv <code> -o - | tar x  stream straight into a pipe
  filament pair --name phone         remember a device (no file transfer)
  filament send big.iso --to laptop  send to a remembered device, no code
  filament up --install              always-on drop target (trusted devices only)

  The other end never needs anything installed: https://filament.autumated.com

  More commands (run `filament <cmd> --help`):
    ssh · forward         remote shell / port-forward to a device
    set tun-addr auto     join the encrypted L3 overlay mesh (`filament addr`)
    ping · doctor         diagnose a link; introduce · grant · serve-tun · netcat";

#[derive(Parser)]
#[command(name = "filament", version = VERSION, about = "P2P file transfer between terminals and browsers, no upload, no account", after_help = EXAMPLES)]
struct Cli {
    /// Signaling server (self-hosters: point at your own instance)
    #[arg(long, global = true, env = "FILAMENT_SERVER", default_value = DEFAULT_SERVER)]
    server: String,
    /// Force TURN relay (testing/privacy; hides your IP from the peer)
    #[arg(long, global = true)]
    relay: bool,
    /// Forbid relay: keep a hard direct-only promise. The never-flaky guarantee
    /// is traded for "no middleman, ever", a path that can't go direct FAILS
    /// CLEANLY (a clear error, a kept partial) instead of falling back to a TURN
    /// relay. Conflicts with --relay (which forces relay).
    #[arg(long, global = true, conflicts_with = "relay")]
    no_relay: bool,
    /// Display name shown to peers (default: config file, then user@host)
    #[arg(long, global = true)]
    name_as: Option<String>,
    /// Verbose output: -v shows resilience internals (stalls, repairs,
    /// reconnects, upgrade probes); -vv adds ICE/per-frame trace. The
    /// value-prop lines (route, relay banner) always print. Overridden by
    /// FILAMENT_LOG=<critical|info|debug|trace>.
    #[arg(short = 'v', long = "verbose", global = true, action = clap::ArgAction::Count)]
    verbose: u8,
    /// Quiet: print only the must-see lines (route label, relay banner, P1/P5
    /// path changes, fatal errors). Conflicts with -v. Overridden by
    /// FILAMENT_LOG.
    #[arg(short = 'q', long = "quiet", global = true, conflicts_with = "verbose")]
    quiet: bool,
    /// Never drop into the guided interactive code entry, fail fast instead.
    /// Use in scripts/automation. A non-TTY stdin is ALWAYS non-interactive even
    /// without this; the env var FILAMENT_NONINTERACTIVE=1 does the same thing.
    #[arg(long, global = true)]
    no_interactive: bool,
    /// Colorize output: auto (default; only at a TTY), always, or never. A flag
    /// overrides NO_COLOR/TERM. Equivalent to FILAMENT_COLOR.
    #[arg(long, global = true, value_name = "WHEN", value_parser = ["auto", "always", "never"])]
    color: Option<String>,
    /// JSON output for every command (structured, parseable). Independent of
    /// TTY: a pipe still gets human text unless --json is set.
    #[arg(long, global = true)]
    json: bool,
    /// Auto-confirm destructive actions (revoke, unmount, unexpose).
    /// Required from a non-TTY; a TTY prompts instead.
    #[arg(short = 'y', long = "yes", global = true)]
    yes: bool,
    #[command(subcommand)]
    cmd: Option<Cmd>,
}

#[derive(Subcommand)]
enum Cmd {
    /// Send files or directories to a peer (browser or CLI).
    ///
    /// In a terminal with no --code/--word this offers to mint a shareable code
    /// (or press enter for the local network). Scripts are safe by default: a
    /// non-TTY uses the local network; under a TTY set FILAMENT_NONINTERACTIVE=1
    /// or pass --no-interactive to skip the prompt.
    Send {
        /// Files or directories to send; '-' reads stdin
        paths: Vec<String>,
        /// Mint a speakable one-time code the receiver claims
        #[arg(long)]
        code: bool,
        /// Choose the one-time code word yourself (implies --code)
        #[arg(long)]
        word: Option<String>,
        /// After a code pairing, remember the other device under this name
        #[arg(long)]
        remember: Option<String>,
        /// Join an explicit room instead of the same-network auto room
        #[arg(long)]
        room: Option<String>,
        /// Only connect to a peer whose display name contains this (C13)
        #[arg(long)]
        to: Option<String>,
        /// Override the offered file name (for stdin '-', or a single file)
        #[arg(long)]
        name: Option<String>,
    },
    /// Receive files from a peer (browser or CLI).
    ///
    /// In a terminal with no code this opens a guided code entry (or press enter
    /// for the local-network auto room). Scripts are safe by default: a non-TTY
    /// uses the auto room; under a TTY set FILAMENT_NONINTERACTIVE=1 or pass
    /// --no-interactive to skip the prompt.
    Recv {
        /// One-time code spoken by the sender (omit to use the auto room)
        code: Option<String>,
        /// Directory to write received files into
        #[arg(long, default_value = ".")]
        dir: PathBuf,
        /// Accept every offer without prompting
        #[arg(long, short = 'y')]
        yes: bool,
        /// Join an explicit room instead of the same-network auto room
        #[arg(long)]
        room: Option<String>,
        /// Only accept a sender whose display name contains this (C13)
        #[arg(long)]
        to: Option<String>,
        /// Keep listening after a sender disconnects
        #[arg(long)]
        keep_open: bool,
        /// After a code pairing, remember the other device under this name
        #[arg(long)]
        remember: Option<String>,
        /// Rename the (single) received file; '-' streams it to stdout
        #[arg(long, short = 'o')]
        output: Option<String>,
    },
    /// Remember a device (a pairing ceremony, no file transfer).
    ///
    /// Mints a code (or claims one) and exchanges the pair secret with consent on
    /// both ends.
    /// In a terminal with no code (or a malformed one) this opens a guided,
    /// color-coded code entry. Scripts are safe by default: a non-TTY never
    /// prompts; under a TTY set FILAMENT_NONINTERACTIVE=1 or pass --no-interactive
    /// to fail fast instead of prompting.
    Pair {
        /// A code from the other device; omit to mint one for them
        code: Option<String>,
        /// What to call them (asked interactively if omitted)
        #[arg(long)]
        name: Option<String>,
        /// Choose your own pairing words instead of minting (the SPAKE2
        /// password; the connect number is still machine-assigned). Use at
        /// least two words, e.g. --word "gigantic element".
        #[arg(long)]
        word: Option<String>,
    },
    /// List known devices (trusted for --to and auto-accept)
    Devices {
        #[command(subcommand)]
        action: Option<DevicesAction>,
        /// Machine-readable JSON (for scripts): [{name, channel, caps}].
        #[arg(long)]
        json: bool,
    },
    /// Always-on receiver: trusted known devices only, invisible to strangers
    Up {
        /// Install + start a systemd user service instead of running attached
        #[arg(long)]
        install: bool,
        /// With --install: install a SYSTEM service (root, one-time sudo) that gets
        /// CAP_NET_ADMIN from systemd via AmbientCapabilities. The overlay's kernel
        /// TUN then needs NO setcap on the binary, so `filament update` never prompts
        /// for a password again. Recommended for the kernelspace (kernel-TUN) path.
        #[arg(long)]
        system: bool,
        /// Force the ZERO-PRIVILEGE userspace overlay (an in-process smoltcp netstack
        /// instead of a kernel TUN): no CAP_NET_ADMIN, no /dev/net/tun, works in a
        /// container. Note: host firewall rules do not apply and native tools reach
        /// <peer>.mesh only via `filament proxy`/`dial`. Default is auto (kernel TUN
        /// when available, userspace otherwise).
        #[arg(long)]
        userspace: bool,
        /// Drop directory (default: `filament config dir`, else ~/Filament)
        #[arg(long)]
        dir: Option<PathBuf>,
        /// Accept seamless `filament ssh` from ANY paired (proof-verified) device,
        /// no per-device `grant` needed. Enables the tunnel acceptor too, so you
        /// don't also need FILAMENT_L2=1. Strangers still can't get in (pairing is
        /// required). Prints a security banner.
        #[arg(long)]
        shell: bool,
        /// Like --shell but ONLY for these devices (comma-separated petnames);
        /// every other device still needs an explicit `grant <dev> shell`.
        #[arg(long, value_name = "DEVICES")]
        shell_only: Option<String>,
        /// The shell program to spawn for PTY sessions (overrides platform default).
        /// Can carry args: `--shell-program "bash -l"`, `"pwsh -NoLogo"`.
        /// Persistent: use `filament set shell-program "<program>"` for the daemon.
        /// Env: `FILAMENT_SHELL`.
        #[arg(long, value_name = "PROGRAM")]
        shell_program: Option<String>,
        /// Drop the web-shell / ssh PTY to this non-root account (via
        /// `runuser -l <user>`). STRONGLY recommended when `up` runs as root:
        /// without it, a granted device gets a shell as the up-process user
        /// (often root). Requires `up` to run as root (runuser is setuid).
        #[arg(long, value_name = "USER")]
        shell_user: Option<String>,
        /// Internal: re-invoked after elevation to do the system-level install.
        #[arg(long, hide = true)]
        install_system: bool,
        /// When kernel TUN is unavailable, auto-start a SOCKS5 proxy on port
        /// 1080 so native tools (curl, ssh) can reach <peer>.mesh. Opt out
        /// with --no-proxy-fallback or `filament set auto-proxy off`.
        #[arg(long)]
        no_proxy_fallback: bool,
    },
    /// Show whether the daemon runs and what it received recently
    Status {
        /// Machine-readable JSON (for scripts): {running, pid, devices, exposed, recent}.
        #[arg(long)]
        json: bool,
    },
    /// Stop the daemon
    Down,
    /// Vouch between two known devices: mints a fresh secret and delivers it
    /// to both over verified channels (run on the device that knows both)
    #[command(hide = true)]
    Introduce { a: String, b: String },
    /// Show or change settings (no args = show all).
    ///
    /// No args prints all settings with their value, scope, and where each came
    /// from (env > peer > config > default). Strictly imperative: `set` only
    /// changes the key you name.
    #[command(after_help = "\x1b[1mExamples:\x1b[0m\n  \
        filament set                          show every setting + where it came from\n  \
        filament set auto-extract on          change one setting (partial, never resets others)\n  \
        filament set shell on --peer laptop   per-device override\n  \
        filament get drop-dir --show-origin   read one value (bare value on stdout)\n  \
        filament unset relay                  revert one setting to its default\n\n\
        Keys: name, server, drop-dir, relay, auto-extract, shell, shell-user")]
    Set {
        /// Setting name (run `filament set` to list them all)
        key: Option<String>,
        /// New value; omit to read the current value
        value: Option<String>,
        /// Scope this change to one or more known devices (per-peer settings
        /// only). Comma-separated or repeatable: --peer a,b  or  --peer a --peer b
        #[arg(long, value_name = "DEVICE", value_delimiter = ',')]
        peer: Vec<String>,
        /// Show what would change without writing
        #[arg(long)]
        dry_run: bool,
        /// Reset ALL settings to their defaults (clears global + per-peer)
        #[arg(long)]
        reset: bool,
        /// Skip the confirmation prompt (required for --reset in a pipe/CI)
        #[arg(long)]
        yes: bool,
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
        /// Prefer strength: hard (always prefer, even if slower)
        #[arg(long, conflicts_with = "soft")]
        hard: bool,
        /// Prefer strength: soft (prefer unless much faster) — default
        #[arg(long, conflicts_with = "hard")]
        soft: bool,
    },
    /// Show this machine's overlay address, or a device's info (addresses, caps, last seen).
    ///
    /// Derived from its Ed25519 overlay key; stable across restarts. Creates the
    /// key on first use. `--v4` prints the dual-stack IPv4 overlay address instead
    /// (also key-derived, in the reserved 198.18.0.0/15 range).
    ///
    /// With a device name: shows that device's overlay addresses, capabilities,
    /// and last-seen time. Use `filament devices` to list all known devices.
    Addr {
        /// Device name to show info for (omit for this machine's address).
        device: Option<String>,
        /// Print the IPv4 overlay address (dual-stack) instead of the IPv6 one.
        #[arg(long)]
        v4: bool,
    },
    /// Read one setting's effective value (bare value on stdout, for scripts)
    #[command(hide = true)]
    Get {
        /// Setting name
        key: String,
        /// Resolve as it applies to this device (per-peer settings)
        #[arg(long, value_name = "DEVICE")]
        peer: Option<String>,
        /// Append where the value came from (env/peer/config/default)
        #[arg(long)]
        show_origin: bool,
        /// Value to print if the setting is empty/unset
        #[arg(long, value_name = "VALUE")]
        default: Option<String>,
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Reset a setting to its default (remove the override)
    #[command(hide = true)]
    Unset {
        /// Setting name
        key: String,
        /// Remove the per-peer override for one or more devices (comma-separated
        /// or repeatable). Omit to clear the global value.
        #[arg(long, value_name = "DEVICE", value_delimiter = ',')]
        peer: Vec<String>,
    },
    /// L3 point-to-point overlay between two KNOWN endpoints, no signaling or
    /// pairing (the WireGuard model): a TUN whose IP packets ride QUIC datagrams.
    /// One side `--listen <bind>`, the other `--connect <host:port>`; both share
    /// `--psk`. Linux-only. (The `up` daemon's `tun-addr` is the signaling-based
    /// mesh; this is the static two-endpoint case the lab and simple VPNs use.)
    #[command(hide = true)]
    ServeTun {
        /// This side's overlay address as IP/PREFIX, e.g. 10.9.0.1/24
        #[arg(long, value_name = "CIDR")]
        tun_addr: String,
        /// Bind a listener here (e.g. 0.0.0.0:51820); the peer --connects to it
        #[arg(long, value_name = "BIND", conflicts_with = "connect")]
        listen: Option<String>,
        /// Dial the peer's listener (e.g. 10.79.0.1:51820)
        #[arg(long, value_name = "HOST:PORT")]
        connect: Option<String>,
        /// Shared secret both ends must match (channel-binding auth)
        #[arg(long)]
        psk: String,
        /// TUN interface name
        #[arg(long, default_value = "filament0")]
        dev: String,
        /// TUN MTU (under the link datagram size; ~1280 is safe)
        #[arg(long, default_value_t = 1280)]
        mtu: u32,
    },
    /// Raw config escape hatch (key value lines in ~/.config/filament/config).
    /// Prefer `filament set`; this is kept for scripts that wrote it directly.
    #[command(hide = true)]
    Config { key: Option<String>, value: Option<String> },
    /// Update filament to the latest release
    Update {
        /// Check only; don't install
        #[arg(long)]
        check: bool,
        /// Include prerelease (beta) builds
        #[arg(long)]
        beta: bool,
    },
    /// Generate shell completions (bash, zsh, fish, elvish, powershell)
    #[command(hide = true)]
    Completions {
        shell: clap_complete::Shell,
    },
    /// Print the manual. On a TTY, shows readable help; piped, emits roff
    /// (for `filament man > filament.1`). `filament man routing` shows the
    /// connection & interface selection model.
    #[command(hide = true)]
    Man {
        /// Manual page: routing, or omit for the full man page
        page: Option<String>,
    },
    /// Tunnel: wire stdio to one TCP stream on a known peer's localhost (the
    /// ssh ProxyCommand primitive). Off by default; FILAMENT_L2=1 enables the
    /// acceptor side in `up`/`recv`.
    #[command(hide = true)]
    Netcat {
        /// Known device (petname) to tunnel through
        peer: String,
        /// Remote port on the peer's localhost
        rport: u16,
    },
    /// Connect stdio to a service a peer EXPOSED on its overlay address, over L3.
    ///
    /// The overlay-port counterpart of `netcat` (which reaches the peer's localhost):
    /// `dial` reaches a port the peer published with `filament expose`, and is the
    /// way a userspace node (no kernel route) reaches `<peer>.mesh:<port>`.
    Dial {
        /// Known device (petname) whose overlay service to reach
        peer: String,
        /// Port the peer exposed on its overlay address
        port: u16,
    },
    /// Open a PTY shell on a known device and bridge it to this terminal (the CLI
    /// sibling of the browser web-shell). The peer must run `up --shell` (or grant
    /// shell). Off by default; FILAMENT_L2=1 / --shell enables the acceptor.
    Pty {
        /// Known device (petname) to open a shell on
        peer: String,
        /// Optional one-shot command to run and return (no interactive shell)
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        cmd: Vec<String>,
    },
    /// Forward a local port to a known peer's port.
    ///
    /// Local TCP listener; each connection becomes one stream to the peer's
    /// localhost:<rport>.
    Forward {
        /// Local port to listen on (127.0.0.1)
        lport: u16,
        /// Known device (petname) to tunnel through
        peer: String,
        /// Remote port on the peer's localhost
        rport: u16,
    },
    /// Publish a local port on this device's mesh address (peers reach it at
    /// <this-device>.mesh:<port>), like a Tailscale-served port.
    ///
    /// The daemon binds the overlay address (a private ULA, reachable only over
    /// the mesh) and forwards each connection to a local target. Needs L3 up
    /// (`filament set tun-addr auto`). Persists across restarts.
    Expose {
        /// Port to publish on the overlay. Omit together with --list.
        port: Option<u16>,
        /// Local target: host:port, a bare port (127.0.0.1:PORT), or a bare host
        /// (HOST:<port>). Default: 127.0.0.1:<port>.
        #[arg(long, value_name = "HOST:PORT")]
        to: Option<String>,
        /// Restrict to these paired devices (petnames, comma-separated). Default: any.
        #[arg(long, value_name = "DEVICE", value_delimiter = ',')]
        peer: Vec<String>,
        /// List exposed ports and exit.
        #[arg(long)]
        list: bool,
    },
    /// Stop exposing a port (see `filament expose --list`).
    Unexpose {
        /// Port to stop exposing.
        port: u16,
    },
    /// Reach mesh peers by name from any app - no TUN, no sudo. Runs a local SOCKS5
    /// proxy; point a browser/curl at it and `<peer>.mesh:<port>` rides the mesh.
    ///
    /// The userspace path (like Tailscale's userspace mode): works in containers and
    /// locked-down boxes with zero privilege. Non-.mesh hosts are dialed directly.
    Proxy {
        /// Port to listen on (SOCKS5).
        #[arg(long, default_value_t = 1080)]
        port: u16,
        /// Address to bind (default: loopback only).
        #[arg(long, default_value = "127.0.0.1")]
        bind: String,
        /// HTTP CONNECT proxy port (0 = disabled). Serves HTTP CONNECT tunnel
        /// and PAC file at http://127.0.0.1:PORT/proxy.pac for browser config.
        #[arg(long, default_value_t = 0)]
        http_port: u16,
    },
    /// SSH into a known device over filament.
    ///
    /// Runs your real `ssh` over the data channel via ProxyCommand (reuses your
    /// keys, known_hosts, and ~/.ssh/config).
    Ssh {
        /// Known device (petname) to ssh into
        peer: String,
        /// Extra args passed through to ssh (user@host, commands, -p, ...)
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Ping a known device: show the live route, RTT, and whether `ssh`/`pty`
    /// will be instant. Like `tailscale ping`, plus what it can't show - warm vs
    /// cold (is a link already held?) and verified identity (paired + proven).
    /// A warm direct link reports quinn's RTT and the real remote IP:port; with no
    /// live link it reports the cold establish cost instead.
    #[command(hide = true)]
    Ping {
        /// Known device (petname) to ping
        peer: String,
        /// How many pings to send (a warm link is re-sampled each round)
        #[arg(long, default_value_t = 1)]
        count: u32,
        /// Machine-readable JSON output (for scripting)
        #[arg(long)]
        json: bool,
    },
    /// Diagnose connect health: where SSH/L2 establishment is slow or stalls.
    ///
    /// With a device: run an "establish then drop" probe (the same bring-up a
    /// real connect does, torn down immediately) and print the per-phase ladder
    /// + a verdict. `--repeat N` / `--watch` run it many times and show a
    /// distribution (the tool for the intermittent "fails on the first try"
    /// case). With NO device: an environment preflight (signaling reachability,
    /// one STUN binding, local interfaces) plus a history digest of past
    /// connects. `--json` emits machine-readable output for scripting.
    #[command(hide = true)]
    Doctor {
        /// Known device (petname) to probe; omit for environment preflight
        device: Option<String>,
        /// Repeat the probe until interrupted-ish (a bounded default count)
        #[arg(long)]
        watch: bool,
        /// Run the probe N times and print a distribution summary
        #[arg(long)]
        repeat: Option<u32>,
        /// Machine-readable JSON output (for scripting)
        #[arg(long)]
        json: bool,
    },
    /// Grant a known device a capability (deny-by-default). `shell` permits
    /// seamless `filament ssh` into THIS machine, a separate consent from
    /// file transfer; pairing alone never yields a shell.
    /// (Prefer `filament set shell on --peer <device>`.)
    #[command(hide = true)]
    Grant {
        /// Known device (petname)
        device: String,
        /// Capability to grant (e.g. `shell`)
        capability: String,
    },
    /// Revoke a capability from a known device. Revoking `shell` also strips the
    /// device's filament-managed block from this machine's authorized_keys.
    #[command(hide = true)]
    Revoke {
        /// Known device (petname)
        device: String,
        /// Capability to revoke (e.g. `shell`)
        capability: String,
    },
    /// Mount a remote directory over the mesh via sshfs.
    ///
    /// Requires sshfs on both ends. Uses the same transport as `filament ssh`
    /// (L3 overlay preferred, L2 tunnel fallback). The peer must have sshd
    /// running and shell access granted.
    ///
    /// By default runs in background with auto-recovery. Use --foreground to
    /// run sshfs in the foreground (blocks the terminal).
    Mount {
        /// Known device (petname) to mount from
        peer: Option<String>,
        /// Remote directory path
        remote: Option<String>,
        /// Local mount point (default: basename of remote path)
        local: Option<String>,
        /// Mount read-only
        #[arg(long)]
        read_only: bool,
        /// Extra sshfs options (comma-separated)
        #[arg(long)]
        options: Option<String>,
        /// Run sshfs in the foreground (blocks terminal)
        #[arg(long)]
        foreground: bool,
        /// Auto-restore this mount on daemon start (off by default)
        #[arg(long)]
        save_auto: bool,
        /// List all filament mounts and their status
        #[arg(long)]
        list: bool,
        /// Check if a mount is healthy
        #[arg(long, value_name = "PATH")]
        check: Option<String>,
        /// Save current mounts as a named profile
        #[arg(long = "save-profile", alias = "save", value_name = "NAME")]
        save_profile: Option<String>,
        /// Apply a saved mount profile
        #[arg(long = "apply-profile", alias = "apply", value_name = "NAME")]
        apply_profile: Option<String>,
        /// List saved mount profiles
        #[arg(long)]
        profiles: bool,
        /// Delete a saved mount profile
        #[arg(long, value_name = "NAME")]
        delete_profile: Option<String>,
    },
    /// Unmount a filament mount point.
    Unmount {
        /// Local mount point to unmount
        path: String,
    },
    /// Sync files to/from a peer via rsync over the mesh.
    ///
    /// Requires rsync on both ends. Uses `filament ssh` as the remote shell,
    /// so the same transport and bootstrap logic applies.
    Backup {
        /// Known device (petname) to back up from/to
        peer: String,
        /// Source path (local or remote as peer:path)
        source: String,
        /// Destination path (local or remote as peer:path)
        dest: String,
        /// Exclude files matching pattern (repeatable)
        #[arg(long)]
        exclude: Vec<String>,
        /// Show what would be transferred without doing it
        #[arg(long)]
        dry_run: bool,
        /// Delete extraneous files in destination
        #[arg(long)]
        delete: bool,
        /// Extra rsync options (space-separated)
        #[arg(long)]
        options: Option<String>,
    },
}

/// Petname management (C12): names are LOCAL aliases for pair secrets, the
/// secret is the identity, the name is yours to fix when you mislabel one.
#[derive(Subcommand)]
enum DevicesAction {
    /// Forget a device: deletes the secret; it can no longer find you
    Forget { name: String },
    /// Rename your local alias (the other side is unaffected)
    Rename { old: String, new: String },
}

/// Looks like a speakable CODE of the shape `word-word-DIGITS` (3 segments: two
/// lowercase words then a numeric trailing group of >= 2 digits). BOTH a minted
/// transfer code (`adj-animal-NNN`, 3-digit) and a minted pairing code
/// (`adj-animal-NNNN`, 4-digit) now share this shape, the pairing-vs-transfer
/// HINT is by trailing-number WIDTH (see `looks_like_pake_code`), not segment
/// count. This is the claimable-code structural test (used by the `up` prompt).
fn regex_lite_code(s: &str) -> bool {
    let parts: Vec<&str> = s.split('-').collect();
    parts.len() == 3
        && parts[0].chars().all(|c| c.is_ascii_lowercase())
        && parts[1].chars().all(|c| c.is_ascii_lowercase())
        && !parts[0].is_empty()
        && !parts[1].is_empty()
        && parts[2].len() >= 2
        && parts[2].chars().all(|c| c.is_ascii_digit())
}

/// The trailing numeric group's width (digit count), or 0 if the last segment
/// isn't all digits. The pairing-vs-transfer hint keys off this: minted pairing
/// nameplates are 4-digit; minted transfer codes are 3-digit.
fn trailing_num_width(s: &str) -> usize {
    match s.rsplit('-').next() {
        Some(t) if !t.is_empty() && t.chars().all(|c| c.is_ascii_digit()) => t.len(),
        _ => 0,
    }
}

/// ADVISORY hint that a typed code is a PAIRING code (vs a one-time transfer
/// code). Both are now `word-word-DIGITS`; the only structural difference is the
/// trailing-number WIDTH, a 4-digit nameplate is what `filament pair` / the
/// browser "create code" mints, whereas a transfer code ends in 3 digits. This
/// is UX-only, it NEVER authenticates (PAKE/SPAKE2 does), so it's safe to be
/// approximate; a mismatch still fails LOUDLY with the right next command.
fn looks_like_pake_code(s: &str) -> bool {
    regex_lite_code(s) && trailing_num_width(s) >= 4
}

/// STEERING (min-strength floor): count the WORD tokens in a normalized password,
/// maximal runs of >= 2 ASCII letters. A user-chosen password must contain at
/// least 2 such tokens. WHY: a minted 2-word code is ~12 bits and online
/// guessing is bounded by claim-burn + the 5/min rate-limit (≈1 guess per code,
/// no offline attack); a single word like `cat` falls below that floor. Digits
/// and 1-letter fragments don't count.
pub(crate) fn password_word_tokens(normalized_password: &str) -> usize {
    let mut tokens = 0;
    let mut run = 0;
    for c in normalized_password.chars() {
        if c.is_ascii_lowercase() {
            run += 1;
            if run == 2 {
                tokens += 1; // crossed the >=2-letter threshold
            }
        } else {
            run = 0;
        }
    }
    tokens
}

// --------------------------------------------------------------- utilities --

/// Persistent per-install identity (shared by every process using this
/// config dir). Lets a sender recognize, and never target, its OWN daemon
/// when both sit on the same pair-presence channels.
fn install_id() -> String {
    let p = devices_path().with_file_name("device.id");
    if let Ok(id) = std::fs::read_to_string(&p) {
        let id = id.trim().to_string();
        if !id.is_empty() {
            return id;
        }
    }
    let id: String = fresh_secret()[..8].to_string();
    let _ = crate::platform::SecretFile::write_str(&p, &id);
    id
}

pub(crate) fn mk_uid(prefix: &str) -> String {
    // Test hook (gate 11): a pinned uid lets the harness exercise the
    // same-device-rejoined supersede path (C6). The cli-s-/cli-r- role prefix
    // must survive the override or same-role skip (C13) breaks.
    if let Ok(forced) = std::env::var("FILAMENT_UID") {
        return format!("cli-{prefix}-{forced}");
    }
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.subsec_nanos())
        .unwrap_or(0);
    format!("cli-{prefix}-{}-{:x}{:x}", install_id(), std::process::id(), nanos)
}

/// Same install (our own daemon / another process of this device)?
pub(crate) fn is_self_uid(my_uid: &str, peer_uid: Option<&str>) -> bool {
    if std::env::var("FILAMENT_UID").is_ok() {
        return false; // test hook pins uids; don't second-guess it
    }
    let id = install_id();
    let _ = my_uid;
    peer_uid.map(|p| p.contains(&format!("-{id}-"))).unwrap_or(false)
}

fn config_path() -> PathBuf {
    devices_path().with_file_name("config")
}

/// Tiny `key value` per-line config; no toml dependency for three keys.
fn config_get(key: &str) -> Option<String> {
    std::fs::read_to_string(config_path()).ok()?.lines().find_map(|l| {
        let (k, v) = l.split_once(char::is_whitespace)?;
        (k == key && !v.trim().is_empty()).then(|| v.trim().to_string())
    })
}

fn config_set(key: &str, value: &str) -> Result<()> {
    let p = config_path();
    if let Some(d) = p.parent() {
        std::fs::create_dir_all(d)?;
    }
    let mut lines: Vec<String> = std::fs::read_to_string(&p)
        .unwrap_or_default()
        .lines()
        .filter(|l| l.split_whitespace().next() != Some(key))
        .map(|l| l.to_string())
        .collect();
    lines.push(format!("{key} {value}"));
    std::fs::write(&p, lines.join("\n") + "\n")?;
    Ok(())
}

pub(crate) fn display_name() -> String {
    if let Ok(n) = std::env::var("FILAMENT_NAME") {
        return n;
    }
    if let Some(n) = config_get("name") {
        return n;
    }
    default_display_name()
}

/// The computed display name when nothing is configured (user@host). Kept
/// separate so the settings readout can show the true default.
pub(crate) fn default_display_name() -> String {
    let user = std::env::var("USER").unwrap_or_else(|_| "user".into());
    let host = std::fs::read_to_string("/etc/hostname")
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|_| "cli".into());
    format!("{user}@{host}")
}

fn sha256_hex(data: &[u8]) -> String {
    let mut h = Sha256::new();
    h.update(data);
    h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}

pub(crate) fn human(bytes: u64) -> String {
    const U: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
    let mut v = bytes as f64;
    let mut i = 0;
    while v >= 1024.0 && i < U.len() - 1 {
        v /= 1024.0;
        i += 1;
    }
    if i == 0 { format!("{bytes} B") } else { format!("{v:.1} {}", U[i]) }
}

/// C7: hash of the first min(256 KiB, len) bytes, cheap content identity
/// carried in file-offer so resume can detect a different file wearing the
/// same name + size.
fn head_hash(path: &Path) -> Option<String> {
    let mut f = std::fs::File::open(path).ok()?;
    let mut buf = vec![0u8; HEAD_BYTES as usize];
    let mut got = 0usize;
    while got < buf.len() {
        match f.read(&mut buf[got..]) {
            Ok(0) => break,
            Ok(n) => got += n,
            Err(_) => return None,
        }
    }
    let mut h = Sha256::new();
    h.update(&buf[..got]);
    Some(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
}

/// P4 (GAP-5): sha256 over the WHOLE file, the end-to-end content digest the
/// receiver compares against on completion so a truncated/corrupt transfer can
/// never be declared "done" (the runner had to bolt this above the transport;
/// P4 makes it a core guarantee). Streamed in 1 MiB reads so a large payload
/// doesn't have to be slurped into RAM. `None` if the file can't be read, the
/// offer then omits `full` and the receiver degrades to the legacy size-only
/// check (backward-compat; bounded, never a hang).
fn full_hash(path: &Path) -> Option<String> {
    let mut f = std::fs::File::open(path).ok()?;
    let mut h = Sha256::new();
    let mut buf = vec![0u8; 1 << 20];
    loop {
        match f.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => h.update(&buf[..n]),
            Err(_) => return None,
        }
    }
    Some(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
}

/// Sidecar metadata for a partial receive (`<name>.part.meta`).
/// JSON {"size":N,"head":"hex","full":"hex"}; legacy files hold a bare size string.
/// `full` is the whole-file sha256 the sender offered (P4), persisted so a
/// resume after a process restart can still verify-on-completion.
struct PartMeta {
    size: u64,
    head: Option<String>,
    full: Option<String>,
}

impl PartMeta {
    fn load(path: &Path) -> Option<PartMeta> {
        let raw = std::fs::read_to_string(path).ok()?;
        if let Ok(v) = serde_json::from_str::<Value>(&raw) {
            if let Some(size) = v["size"].as_u64() {
                return Some(PartMeta {
                    size,
                    head: v["head"].as_str().map(|s| s.to_string()),
                    full: v["full"].as_str().map(|s| s.to_string()),
                });
            }
        }
        raw.trim().parse::<u64>().ok().map(|size| PartMeta { size, head: None, full: None })
    }
    fn store(&self, path: &Path) -> std::io::Result<()> {
        std::fs::write(path, json!({ "size": self.size, "head": self.head, "full": self.full }).to_string())
    }
}

fn unique_path(dir: &Path, name: &str) -> PathBuf {
    let candidate = dir.join(name);
    if !candidate.exists() {
        return candidate;
    }
    for i in 1..1000 {
        let c = dir.join(format!("{name}.{i}"));
        if !c.exists() {
            return c;
        }
    }
    dir.join(format!("{name}.dup"))
}

// ------------------------------------------------------- known devices (C12) --
// Persistent pairing: during a code-paired session, both sides exchange a
// 32-byte secret END-TO-END over the DataChannel (the server never sees it)
// and store it under a local nickname. Presence: subscribe with
// sha256("filament-pair:" + secret), the server learns only meeting points.
// Trust: an HMAC(secret) proof exchanged after connect, so the server cannot
// impersonate a known device. Full PAKE remains roadmap (ledger C15).

/// Should THIS acceptor session take the rung-1 direct-QUIC path (answer the
/// initiator's transport-offer instead of building a colliding WebRTC peer)?
///
/// True when the env gate is set (`direct_enabled`), OR this is the L2/ssh
/// acceptor (`l2_enabled`), OR this is the long-lived `up` daemon (`daemon`).
///
/// The daemon case is the anti-glare fix for a PLAIN `filament up` (no `--shell`,
/// no `FILAMENT_L2`): two such daemons that are known devices to each other each
/// fire a KnownPeer for the other and each tries to be the WebRTC initiator. The
/// two offers collide (GLARE); the polite side drops and rebuilds as a responder,
/// the supersede churn loops ("appeared, connecting" repeatedly, "reconnecting...")
/// and never settles to one stable link. Answering the direct-QUIC dial instead is
/// sequential (one `direct_pending` per peer, one race, one link) and authenticated
/// by the pair-secret MAC, so it neither glares nor depends on cross-NAT ICE.
///
/// One-shot `send`/`recv`/`pair` pass `daemon=false` and so keep their WebRTC
/// default (`direct_enabled()` only): they are deliberately left unchanged.
fn direct_ok_for(daemon: bool, l2_enabled: bool) -> bool {
    direct::direct_enabled() || l2_enabled || daemon
}

fn devices_path() -> PathBuf {
    crate::platform::Paths::config_path("devices.json")
}

pub(crate) fn devices_load() -> Vec<(String, String)> {
    let Ok(raw) = std::fs::read_to_string(devices_path()) else { return Vec::new() };
    serde_json::from_str::<Value>(&raw)
        .ok()
        .and_then(|v| {
            v.as_array().map(|a| {
                a.iter()
                    .filter_map(|d| Some((d["name"].as_str()?.to_string(), d["secret"].as_str()?.to_string())))
                    .collect()
            })
        })
        .unwrap_or_default()
}

/// Check if a petname is already taken by another device (case-insensitive).
fn devices_name_taken(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    devices_load().iter().any(|(n, _)| n.to_ascii_lowercase() == lower)
}

/// Strip terminal escape sequences and control characters from a device petname
/// before it is stored. A name typed or pasted in a terminal can capture the
/// terminal's own device-attributes reply (`ESC[?1;2c...`); that junk then never
/// matches `--to <name>`, silently breaking targeting (observed live: a `send
/// --to pixel` whose stored name was `...escapes...pixel` fell back to the local
/// room and the Pixel never received). Keep only printable, non-control chars.
fn sanitize_device_name(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    let mut chars = name.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\u{1b}' {
            // ESC: drop a CSI escape (`ESC [ ... final-letter`) wholesale.
            if chars.peek() == Some(&'[') {
                chars.next();
                while let Some(&n) = chars.peek() {
                    chars.next();
                    if n.is_ascii_alphabetic() {
                        break;
                    }
                }
            }
            continue; // also drops a lone/other ESC
        }
        if !c.is_control() {
            out.push(c);
        }
    }
    out.trim().to_string()
}

fn devices_store(name: &str, secret: &str) -> Result<()> {
    let clean = sanitize_device_name(name);
    let name = clean.as_str();
    let p = devices_path();
    if let Some(dir) = p.parent() {
        std::fs::create_dir_all(dir)?;
    }
    // Operate on the raw JSON so OTHER records keep their v2 fields (caps,
    // addedAt) verbatim. Going through the (name, secret) tuples of
    // devices_load() silently rewrote every other device as bare
    // {name, secret}, wiping their `shell` grants on any store (pairing,
    // introduce, rename), a quiet privilege-loss bug.
    let mut arr: Vec<Value> = std::fs::read_to_string(&p)
        .ok()
        .and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
        .and_then(|v| v.as_array().cloned())
        .unwrap_or_default();
    // Check for name collision and auto-suffix if needed
    let final_name = if arr.iter().any(|d| d["name"].as_str() == Some(name)) {
        let mut suffix = 2;
        let mut new_name = format!("{name}-{suffix}");
        while arr.iter().any(|d| d["name"].as_str() == Some(&new_name)) {
            suffix += 1;
            new_name = format!("{name}-{suffix}");
        }
        eprintln!("  note: '{name}' already exists, pairing as '{new_name}'");
        new_name
    } else {
        name.to_string()
    };
    match arr.iter_mut().find(|d| d["name"].as_str() == Some(&final_name)) {
        // Re-storing an existing name: only the secret rotates; keep its caps.
        Some(existing) => existing["secret"] = json!(secret),
        None => arr.push(json!({"name": &final_name, "secret": secret})),
    }
    crate::platform::SecretFile::write_str(&p, &serde_json::to_string_pretty(&arr)?)?;
    Ok(())
}

/// L1-a (spec §8): store a v2 device record with its agreed capability set.
/// `caps` is deny-by-default; "transfer" is the L0 baseline. The on-disk shape
/// grows `v` and `caps` but the existing `{name, secret}` fields are unchanged,
/// so the reconnect path (`devices_load`, which reads only name+secret) keeps
/// working byte-for-byte, no regression.
fn devices_store_v2(name: &str, secret: &str, caps: &[String]) -> Result<()> {
    let clean = sanitize_device_name(name);
    let name = clean.as_str();
    let p = devices_path();
    if let Some(dir) = p.parent() {
        std::fs::create_dir_all(dir)?;
    }
    // Preserve other records verbatim (including their v/caps if present).
    let mut arr: Vec<Value> = std::fs::read_to_string(&p)
        .ok()
        .and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
        .and_then(|v| v.as_array().cloned())
        .unwrap_or_default();
    // Check for name collision and auto-suffix if needed
    let final_name = if arr.iter().any(|d| d["name"].as_str() == Some(name)) {
        let mut suffix = 2;
        let mut new_name = format!("{name}-{suffix}");
        while arr.iter().any(|d| d["name"].as_str() == Some(&new_name)) {
            suffix += 1;
            new_name = format!("{name}-{suffix}");
        }
        eprintln!("  note: '{name}' already exists, pairing as '{new_name}'");
        new_name
    } else {
        name.to_string()
    };
    arr.retain(|d| d["name"].as_str() != Some(&final_name));
    arr.push(json!({"name": &final_name, "secret": secret, "v": 2, "caps": caps,
                    "addedAt": SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)}));
    crate::platform::SecretFile::write_str(&p, &serde_json::to_string_pretty(&arr)?)?;
    Ok(())
}

/// Update the `lastSeen` timestamp and overlay addresses for a known device.
/// Called on each connect so `filament addr <device>` can show recency and addresses.
fn devices_touch(name: &str, v6: Option<std::net::Ipv6Addr>, v4: Option<std::net::Ipv4Addr>) {
    let p = devices_path();
    let Ok(raw) = std::fs::read_to_string(&p) else { return };
    let Ok(val) = serde_json::from_str::<Value>(&raw) else { return };
    let Some(arr) = val.as_array() else { return };
    let mut arr = arr.clone();
    let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
    for d in arr.iter_mut() {
        if d["name"].as_str() == Some(name) {
            d["lastSeen"] = json!(now);
            if let Some(v6) = v6 { d["overlayV6"] = json!(v6.to_string()); }
            if let Some(v4) = v4 { d["overlayV4"] = json!(v4.to_string()); }
            break;
        }
    }
    let _ = crate::platform::SecretFile::write_str(&p, &serde_json::to_string_pretty(&arr).unwrap_or_default());
}

/// Read the `lastSeen` timestamp and overlay addresses for a known device.
fn devices_info(name: &str) -> Option<(u64, Option<String>, Option<String>)> {
    let p = devices_path();
    let raw = std::fs::read_to_string(p).ok()?;
    let arr: Vec<Value> = serde_json::from_str(&raw).ok()?;
    let d = arr.iter().find(|d| d["name"].as_str() == Some(name))?;
    let last_seen = d["lastSeen"].as_u64();
    let v6 = d["overlayV6"].as_str().map(|s| s.to_string());
    let v4 = d["overlayV4"].as_str().map(|s| s.to_string());
    Some((last_seen.unwrap_or(0), v6, v4))
}

/// True if ANY known device has been granted the `shell` capability. The daemon
/// uses this to switch L2/shell ON even for a plain `filament up`: otherwise
/// `filament grant <dev> shell` writes a grant the running daemon never consults
/// (l2_enabled was set only by --shell/--shell-only at startup), so the grant
/// silently did nothing and `filament ssh` timed out. With this, a grant alone is
/// enough; the per-device cap gate (auto_allows || device_allows) still denies
/// every non-granted device, so this does NOT broaden access, it only honors the
/// grants that already exist.
fn any_shell_grant() -> bool {
    any_shell_grant_at(&devices_path())
}

fn any_shell_grant_at(path: &Path) -> bool {
    let Ok(raw) = std::fs::read_to_string(path) else { return false };
    let Ok(arr) = serde_json::from_str::<Value>(&raw) else { return false };
    arr.as_array()
        .map(|a| {
            a.iter().any(|d| {
                d.get("caps")
                    .and_then(|c| c.as_array())
                    .map(|list| list.iter().any(|c| c.as_str() == Some("shell")))
                    .unwrap_or(false)
            })
        })
        .unwrap_or(false)
}

/// Whether to serve an `l2-open` (TCP tunnel / ssh data link) from a peer.
/// Blanket modes (`--shell` / `--shell-only` / `FILAMENT_L2`) keep their existing
/// trusted-gated behavior. But when L2 is on ONLY because some device was
/// `grant`ed shell, the OPENING peer must itself hold that grant: otherwise a
/// grant for ONE device would let EVERY trusted device open loopback tunnels.
/// `trusted` is still required upstream; this is the additional per-device gate.
fn l2_open_allowed(blanket: bool, peer_has_shell: bool) -> bool {
    blanket || peer_has_shell
}

/// Opt-in non-loopback forward allowlist: `{config_dir}/l2-allow.json`. Absent or
/// malformed file => no entries => loopback-only (the default SSRF posture). Lets
/// an operator deliberately turn the daemon into a gateway to SPECIFIC hosts for
/// SPECIFIC devices, without opening blanket SSRF. Shape:
///   { "laptop": ["10.0.0.5:5432", "192.168.1.10:*"], "*": ["db.internal:5432"] }
/// A "*" device key applies to any authorized device; "host:*" allows any port.
fn l2_allow_path() -> PathBuf {
    devices_path().with_file_name("l2-allow.json")
}

fn l2_allow_load() -> Value {
    std::fs::read_to_string(l2_allow_path())
        .ok()
        .and_then(|s| serde_json::from_str::<Value>(&s).ok())
        .unwrap_or(Value::Null)
}

/// True if `allow` lists `host:port` (or `host:*`) for `device` or for "*". Pure,
/// so the matching logic is unit-testable without the filesystem. Host match is
/// case-insensitive; the device key must match the proven `verified_name` exactly
/// (or be "*").
fn l2_target_allowed_in(allow: &Value, device: &str, host: &str, port: u16) -> bool {
    let matches = |list: &Value| -> bool {
        list.as_array()
            .map(|a| {
                a.iter().any(|e| {
                    let s = e.as_str().unwrap_or("");
                    match s.rsplit_once(':') {
                        Some((h, "*")) => h.eq_ignore_ascii_case(host),
                        Some((h, p)) => {
                            h.eq_ignore_ascii_case(host) && p.parse::<u16>().ok() == Some(port)
                        }
                        None => false,
                    }
                })
            })
            .unwrap_or(false)
    };
    allow.get(device).map(&matches).unwrap_or(false) || allow.get("*").map(&matches).unwrap_or(false)
}

fn l2_target_allowed(device: &str, host: &str, port: u16) -> bool {
    l2_target_allowed_in(&l2_allow_load(), device, host, port)
}

/// L1-a (spec §8): read a device's granted capabilities. v1 records (no `caps`)
#[allow(dead_code)] // enforcement hook (gate 5); exercised by the capability gate
/// read as `["transfer"]` for backward compatibility; deny-by-default otherwise.
/// Returns None if the device isn't known.
fn device_caps(name: &str) -> Option<Vec<String>> {
    device_caps_at(&devices_path(), name)
}

/// Path-explicit core of `device_caps` (testable without touching the global
/// config-dir env var).
#[allow(dead_code)]
fn device_caps_at(path: &Path, name: &str) -> Option<Vec<String>> {
    let raw = std::fs::read_to_string(path).ok()?;
    let arr = serde_json::from_str::<Value>(&raw).ok()?;
    for d in arr.as_array()? {
        if d["name"].as_str() == Some(name) {
            return Some(match d.get("caps").and_then(|c| c.as_array()) {
                Some(list) => list.iter().filter_map(|c| c.as_str().map(String::from)).collect(),
                None => vec!["transfer".to_string()], // v1 record
            });
        }
    }
    None
}

/// Path-explicit deny-by-default check (testable).
#[allow(dead_code)]
fn device_allows_at(path: &Path, name: &str, capability: &str) -> bool {
    if capability == "transfer" {
        return true; // L0 baseline, never gated (spec §8)
    }
    device_caps_at(path, name).map(|c| c.iter().any(|g| g == capability)).unwrap_or(false)
}

/// L1-a (spec §8 / gate 5): deny-by-default capability enforcement hook. A
/// gated action is allowed only if the device's record grants the capability.
/// "transfer" is the L0 baseline (always allowed, even for empty caps) so this
/// never regresses existing send/recv. Wired now; future L-layers add caps.
#[allow(dead_code)] // enforcement hook (gate 5); exercised by the capability gate
fn device_allows(name: &str, capability: &str) -> bool {
    if capability == "transfer" {
        return true; // L0 baseline, never gated (spec §8)
    }
    device_caps(name).map(|c| c.iter().any(|g| g == capability)).unwrap_or(false)
}

/// Grant or revoke a capability on an EXISTING known device, preserving its
/// secret and any other caps. Promotes a v1 record (no `caps`) to v2 with the
/// back-compat baseline `["transfer"]` first, so granting `shell` never silently
/// drops `transfer`. Deny-by-default consent for `filament grant`/`revoke`.
/// Returns Err if the device is unknown (you can't grant a stranger a shell).
fn device_set_cap(name: &str, capability: &str, grant: bool) -> Result<()> {
    let p = devices_path();
    let raw = std::fs::read_to_string(&p)
        .map_err(|_| anyhow::anyhow!("no known device named '{name}', pair first"))?;
    let mut arr: Vec<Value> = serde_json::from_str::<Value>(&raw)
        .ok()
        .and_then(|v| v.as_array().cloned())
        .unwrap_or_default();
    let mut found = false;
    for d in arr.iter_mut() {
        if d["name"].as_str() != Some(name) {
            continue;
        }
        found = true;
        // Current caps: v1 (absent) reads as the transfer baseline.
        let mut caps: Vec<String> = match d.get("caps").and_then(|c| c.as_array()) {
            Some(list) => list.iter().filter_map(|c| c.as_str().map(String::from)).collect(),
            None => vec!["transfer".to_string()],
        };
        caps.retain(|c| c != capability);
        if grant {
            caps.push(capability.to_string());
        }
        if let Some(obj) = d.as_object_mut() {
            obj.insert("v".into(), json!(2));
            obj.insert("caps".into(), json!(caps));
        }
    }
    if !found {
        return Err(anyhow::anyhow!(
            "no known device named '{name}', run `filament devices` to see who you've paired"
        ));
    }
    crate::platform::SecretFile::write_str(&p, &serde_json::to_string_pretty(&arr)?)?;
    Ok(())
}

fn devices_remove(name: &str) -> Result<()> {
    let p = devices_path();
    if let Some(dir) = p.parent() {
        std::fs::create_dir_all(dir)?;
    }
    // Raw-array filter so the REMAINING devices keep their v2 fields (caps,
    // addedAt). The old tuple round-trip rewrote every survivor as bare
    // {name, secret}, silently wiping their `shell` grants on any forget.
    let mut arr: Vec<Value> = std::fs::read_to_string(&p)
        .ok()
        .and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
        .and_then(|v| v.as_array().cloned())
        .unwrap_or_default();
    arr.retain(|d| d["name"].as_str() != Some(name));
    crate::platform::SecretFile::write_str(&p, &serde_json::to_string_pretty(&arr)?)?;
    Ok(())
}

pub(crate) fn channel_of(secret: &str) -> String {
    let mut h = Sha256::new();
    h.update(b"filament-pair:");
    h.update(secret.as_bytes());
    h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}

/// HMAC-SHA256 (manual: avoids a hmac-crate version dance with sha2 0.11).
fn hmac_sha256(key: &[u8], msg: &[u8]) -> String {
    let mut k = [0u8; 64];
    if key.len() > 64 {
        let mut h = Sha256::new();
        h.update(key);
        k[..32].copy_from_slice(&h.finalize());
    } else {
        k[..key.len()].copy_from_slice(key);
    }
    let ipad: Vec<u8> = k.iter().map(|b| b ^ 0x36).collect();
    let opad: Vec<u8> = k.iter().map(|b| b ^ 0x5c).collect();
    let mut inner = Sha256::new();
    inner.update(&ipad);
    inner.update(msg);
    let mut outer = Sha256::new();
    outer.update(&opad);
    outer.update(inner.finalize());
    outer.finalize().iter().map(|b| format!("{b:02x}")).collect()
}

/// C20: the proof binds the pair secret to the DTLS session. uids are
/// order-normalized (direction-tagged by the prover's uid prefix) and BOTH
/// certificate fingerprints are mixed in sorted order, a channel MITM'd by
/// anyone (including the signaling server) has different fingerprints, so
/// the proof fails and auto-accept refuses.
pub(crate) fn proof_for(secret: &str, prover_uid: &str, a_uid: &str, b_uid: &str, fp1: &str, fp2: &str) -> String {
    let (lo, hi) = if a_uid < b_uid { (a_uid, b_uid) } else { (b_uid, a_uid) };
    let (f_lo, f_hi) = if fp1 < fp2 { (fp1, fp2) } else { (fp2, fp1) };
    hmac_sha256(
        secret.as_bytes(),
        format!("filament-proof2:{prover_uid}|{lo}|{hi}|{f_lo}|{f_hi}").as_bytes(),
    )
}

pub(crate) fn fresh_secret() -> String {
    let mut buf = [0u8; 32];
    // std-only CSPRNG is unavailable; derive from getrandom via std::fs on unix
    if std::fs::File::open("/dev/urandom")
        .and_then(|mut f| f.read_exact(&mut buf))
        .is_err()
    {
        // fallback (non-unix): hash of time+pid noise, still unpredictable enough
        let mut h = Sha256::new();
        h.update(format!("{:?}{}", SystemTime::now(), std::process::id()));
        buf.copy_from_slice(&h.finalize()[..32]);
    }
    buf.iter().map(|b| format!("{b:02x}")).collect()
}

// ------------------------------------------------------------- daemon (C19) --

fn drop_dir(flag: Option<PathBuf>) -> PathBuf {
    flag.or_else(|| config_get("dir").map(PathBuf::from)).unwrap_or_else(default_drop_dir)
}

/// The built-in drop directory when nothing is configured (~/Filament). Shared
/// with the settings readout so it shows the true default.
pub(crate) fn default_drop_dir() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
    PathBuf::from(home).join("Filament")
}

/// True when an `up` daemon is currently running (drives the "takes effect on
/// next up" hint after a settings change).
pub(crate) fn daemon_running() -> bool {
    daemon_alive().is_some()
}

/// Minimal `YYYY-MM-DD HH:MM` UTC stamp (civil-from-days; avoids chrono).
fn chrono_now() -> String {
    let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
    let (days, rem) = (secs / 86400, secs % 86400);
    let (hh, mm) = (rem / 3600, (rem % 3600) / 60);
    // Howard Hinnant's civil_from_days
    let z = days as i64 + 719_468;
    let era = z / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}")
}

fn pidfile() -> PathBuf {
    devices_path().with_file_name("up.pid")
}
fn up_log() -> PathBuf {
    devices_path().with_file_name("up.log")
}

fn daemon_alive() -> Option<u32> {
    let pid: u32 = std::fs::read_to_string(pidfile()).ok()?.trim().parse().ok()?;
    let cmd = std::fs::read_to_string(format!("/proc/{pid}/cmdline")).ok()?;
    cmd.contains("filament").then_some(pid)
}

/// The argv for a web-shell PTY.
///
/// M-1 (privilege-drop): when `--shell-user <name>` is set, drop the PTY to that
/// account via `runuser -l <user>` (a clean setuid+login-shell wrapper available
/// on every systemd distro). `runuser` does no PAM password prompt, so it only
/// works when `up` itself runs as root, which is exactly the case the flag is
/// meant to de-fang (a root daemon should hand out a NON-root shell). Without the
/// flag the PTY runs as the up-process user (often root on a server); this is an
/// ACCEPTED RISK documented in docs/security/web-shell-review.md (M-1) and in the
/// `up --shell` help. Operators are urged to pass `--shell-user`.
fn shell_argv(shell_program: Option<&str>, shell_user: Option<&str>) -> Vec<String> {
    let shell_config = settings::get_str("shell-program", None);
    let (argv, _can_user) = platform::Paths::shell_argv(shell_program, shell_config.as_deref(), shell_user);
    argv
}

/// #4: bridge ONE link's PTY stream to a persistent session. Inbound data frames
/// (`rx`, the mux's per-sid pipe) become keystrokes; resize events (`rrx`, the
/// mux resizer) become window-size changes. When the channel drops, `rx` closes
/// and this pump exits, but it does NOT end the session: a drop is a DETACH (the
/// PcState handler does that), so the shell keeps running for a reattach. Spawned
/// fresh on every open/reattach against that open's sid.
fn spawn_session_pumps(
    sess: l2::PtySessionHandle,
    mut rx: tokio::sync::mpsc::Receiver<Option<bytes::Bytes>>,
    mut rrx: tokio::sync::mpsc::UnboundedReceiver<(u16, u16)>,
) {
    // input pump: PTY keystrokes for THIS attachment
    let s_in = sess.clone();
    tokio::spawn(async move {
        while let Some(item) = rx.recv().await {
            match item {
                Some(bytes) => s_in.feed_input(bytes.to_vec()),
                None => break, // clean FIN for this stream; channel-drop also lands here
            }
        }
    });
    // resize pump: SIGWINCH for THIS attachment
    tokio::spawn(async move {
        while let Some((c, r)) = rrx.recv().await {
            sess.resize(c, r);
        }
    });
}

/// Auto-shell policy for the `up`/`recv` acceptor: which proof-verified devices
/// may `filament ssh` in WITHOUT a per-device `grant`. Trust (pair-proof) is
/// always enforced separately, this is purely the capability side.
#[derive(Clone, Debug)]
enum ShellPolicy {
    /// Default: only devices explicitly `grant`ed the `shell` cap.
    Granted,
    /// `up --shell`: any paired device. M-2: this INTENTIONALLY grants every
    /// proof-verified paired device, including ones introduced later via
    /// pair-intro. Use `Only`/`--shell-only` to scope it.
    All,
    /// `up --shell-only a,b`: only these petnames auto-shell; others need a grant.
    Only(std::collections::HashSet<String>),
}

impl ShellPolicy {
    fn auto_allows(&self, name: &str) -> bool {
        match self {
            ShellPolicy::Granted => false,
            ShellPolicy::All => true,
            ShellPolicy::Only(set) => set.contains(name),
        }
    }
    /// Active policy implies the L2 tunnel acceptor is on (you can't ssh without it).
    fn enables_l2(&self) -> bool {
        !matches!(self, ShellPolicy::Granted)
    }
}

/// Install a SYSTEM systemd unit that receives CAP_NET_ADMIN from systemd
/// (`AmbientCapabilities`), so the overlay's kernel TUN needs NO file capability on
/// the binary. That is what kills the recurring sudo: a file cap is lost when
/// `filament update` replaces the binary, but an ambient cap is granted afresh by
/// systemd on every (re)start, so updates never need `setcap` (hence never a
/// password). Writes `/etc/systemd/system/filament.service`, drops any stale file
/// cap, retires a pre-existing --user service, and enables it, using ONE `sudo` for
/// the privileged steps (a single interactive prompt, NOT a per-update one). If it
/// cannot elevate, it prints the exact unit + commands to run by hand.
#[cfg(target_os = "linux")]
fn install_system_service(shell: bool, shell_only: &Option<String>, shell_user: &Option<String>) -> Result<()> {
    let exe = std::env::current_exe()?.display().to_string();
    let user = std::env::var("USER")
        .or_else(|_| std::env::var("LOGNAME"))
        .unwrap_or_else(|_| "root".into());
    let home = std::env::var("HOME").unwrap_or_else(|_| format!("/home/{user}"));

    // Carry the same shell posture the user asked for into the unit's ExecStart.
    let mut up_args = String::from(" up");
    if let Some(csv) = shell_only {
        up_args.push_str(&format!(" --shell-only {csv}"));
    } else if shell {
        up_args.push_str(" --shell");
    }
    if let Some(u) = shell_user {
        up_args.push_str(&format!(" --shell-user {u}"));
    }

    let unit = format!(
        "[Unit]\n\
         Description=Filament drop target (trusted devices only)\n\
         After=network-online.target\n\
         Wants=network-online.target\n\n\
         [Service]\n\
         Type=notify\n\
         User={user}\n\
         Environment=HOME={home}\n\
         Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n\
         ExecStart={exe}{up_args}\n\
         AmbientCapabilities=CAP_NET_ADMIN\n\
         CapabilityBoundingSet=CAP_NET_ADMIN\n\
         Restart=always\n\
         RestartSec=2\n\
         WatchdogSec=45\n\n\
         [Install]\n\
         WantedBy=multi-user.target\n"
    );
    let unit_path = "/etc/systemd/system/filament.service";
    let am_root = unsafe { libc::geteuid() } == 0;
    // Run a privileged command, using sudo only when not already root.
    let run_priv = |args: &[&str]| -> bool {
        let mut cmd = if am_root {
            std::process::Command::new(args[0])
        } else {
            let mut c = std::process::Command::new("sudo");
            c.arg(args[0]);
            c
        };
        cmd.args(&args[1..]).status().map(|s| s.success()).unwrap_or(false)
    };

    ui::say(&format!("filament: installing system service at {unit_path}"));
    if !am_root {
        ui::say("  (one-time sudo for the system unit; updates afterward need none)");
    }
    // Write the unit as root by PIPING it to `tee` under the privileged runner.
    // Deliberately NO on-disk staging: a predictable, world-writable temp file
    // (e.g. /tmp/filament.service.tmp) is a TOCTOU - another local user could
    // swap or symlink it between our write and the privileged copy, yielding an
    // attacker-controlled ROOT-owned systemd unit (root code execution). Piping to
    // `tee` has no intermediary to race; sudo still reads its password from the tty,
    // not our stdin, so the small unit content flows to tee uncontended.
    let wrote = {
        use std::io::Write;
        use std::process::Stdio;
        let mut cmd = if am_root {
            std::process::Command::new("tee")
        } else {
            let mut c = std::process::Command::new("sudo");
            c.arg("tee");
            c
        };
        match cmd.arg(unit_path).stdin(Stdio::piped()).stdout(Stdio::null()).spawn() {
            Ok(mut child) => {
                if let Some(mut si) = child.stdin.take() {
                    let _ = si.write_all(unit.as_bytes());
                    // si drops here, closing stdin so tee finalizes the file.
                }
                child.wait().map(|s| s.success()).unwrap_or(false)
            }
            Err(_) => false,
        }
    };
    if wrote {
        // tee creates with the (root) umask; pin the mode explicitly.
        let _ = run_priv(&["chmod", "644", unit_path]);
    }
    if !wrote {
        ui::say("filament: could not elevate; install the system unit by hand:");
        ui::say(&format!("  sudo tee {unit_path} >/dev/null <<'UNIT'\n{unit}UNIT"));
        ui::say(&format!("  sudo setcap -r {exe} 2>/dev/null || true"));
        ui::say("  sudo systemctl daemon-reload && sudo systemctl enable --now filament");
        return Ok(());
    }
    // Drop any stale file cap (ambient replaces it; keeps updates clean); retire a
    // pre-existing --user service so the two don't fight over the mesh. Best-effort.
    let _ = run_priv(&["setcap", "-r", &exe]);
    let _ = std::process::Command::new("systemctl").args(["--user", "disable", "--now", "filament"]).status();
    let enabled =
        run_priv(&["systemctl", "daemon-reload"]) && run_priv(&["systemctl", "enable", "--now", "filament"]);
    if enabled {
        ui::say(&format!(
            "  {} system service enabled; CAP_NET_ADMIN comes from systemd, so no setcap on update",
            ui::paint(ui::Tone::Ok, ui::glyph_ok())
        ));
        ui::say("  logs: journalctl -u filament");
    } else {
        ui::say("  wrote the unit; enable it with: sudo systemctl enable --now filament");
    }

    // Belt-and-suspenders: a NOPASSWD sudoers drop-in scoped to JUST restarting this
    // one service, so any fallback `sudo systemctl restart filament` (e.g. when the
    // reload op is unavailable) is password-free too. Written the same TOCTOU-safe
    // way (piped to tee, no world-writable staging), mode 0440, and validated with
    // visudo - a malformed sudoers drop-in must NEVER be left in place, so it is
    // removed if it does not parse.
    let systemctl = ["/usr/bin/systemctl", "/bin/systemctl"]
        .iter()
        .find(|p| std::path::Path::new(p).exists())
        .copied()
        .unwrap_or("/usr/bin/systemctl");
    let sudoers_path = "/etc/sudoers.d/filament";
    let sudoers = format!(
        "{user} ALL=(root) NOPASSWD: {systemctl} restart filament, {systemctl} daemon-reload\n"
    );
    let wrote_sudoers = {
        use std::io::Write;
        use std::process::Stdio;
        let mut cmd = if am_root {
            std::process::Command::new("tee")
        } else {
            let mut c = std::process::Command::new("sudo");
            c.arg("tee");
            c
        };
        match cmd.arg(sudoers_path).stdin(Stdio::piped()).stdout(Stdio::null()).spawn() {
            Ok(mut ch) => {
                if let Some(mut si) = ch.stdin.take() {
                    let _ = si.write_all(sudoers.as_bytes());
                }
                ch.wait().map(|s| s.success()).unwrap_or(false)
            }
            Err(_) => false,
        }
    };
    if wrote_sudoers {
        let _ = run_priv(&["chmod", "0440", sudoers_path]);
        if run_priv(&["visudo", "-cf", sudoers_path]) {
            ui::say(&format!(
                "  {} passwordless `systemctl restart filament` for {user}",
                ui::paint(ui::Tone::Ok, ui::glyph_ok())
            ));
        } else {
            let _ = run_priv(&["rm", "-f", sudoers_path]);
            ui::say("  (skipped the restart sudoers rule: visudo validation failed)");
        }
    }
    Ok(())
}

#[cfg(not(target_os = "linux"))]
fn install_system_service(_shell: bool, _shell_only: &Option<String>, _shell_user: &Option<String>) -> Result<()> {
    let hint = platform::ServiceHost::detect().install_instructions();
    bail!("--install --system (ambient-cap system service) is not supported on this platform. {hint}");
}

async fn up_cmd(
    server: &str,
    install: bool,
    system: bool,
    dir: Option<PathBuf>,
    relay: bool,
    shell: bool,
    shell_only: Option<String>,
    shell_program: Option<String>,
    shell_user: Option<String>,
    install_system_flag: bool,
    no_proxy_fallback: bool,
) -> Result<()> {
    // Internal: re-invoked after elevation. Do the system-level install directly
    // and return. The privileged backend registers the service/daemon/task and exits.
    if install_system_flag {
        let host = platform::ServiceHost::detect();
        let exe = std::env::current_exe()?;
        // Build shell args from the current flag carried by the elevated process.
        let mut up_args = String::new();
        if let Some(csv) = &shell_only {
            up_args.push_str(&format!(" --shell-only {csv}"));
        } else if shell {
            up_args.push_str(" --shell");
        }
        if let Some(u) = &shell_user {
            up_args.push_str(&format!(" --shell-user {u}"));
        }
        host.install_system(&exe, &up_args)?;
        return Ok(());
    }
    // --shell-program -- persist it so the daemon picks it up (shell_argv reads
    // this from config). The env var FILAMENT_SHELL is also checked independently.
    if let Some(ref prog) = shell_program {
        settings::set("shell-program", prog, None).ok();
    }
    let shell_policy = match &shell_only {
        Some(csv) => ShellPolicy::Only(
            csv.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(),
        ),
        None if shell => ShellPolicy::All,
        None => ShellPolicy::Granted,
    };
    // --shell-user is Unix-only (uses runuser). Warn early on Windows.
    if shell_user.is_some() && cfg!(windows) {
        ui::say(&format!(
            "  {} --shell-user is not supported on Windows.\n\
             \n\
             Windows requires CreateProcessAsUser or CreateProcessWithLogonW to run\n\
             a process as another user. CreateProcessAsUser needs SE_INCREASE_QUOTA_NAME\n\
             and SE_ASSIGNPRIMARYTOKEN_NAME privileges (typically requires admin).\n\
             CreateProcessWithLogonW needs the target user's credentials (username +\n\
             password), which is a security risk if stored or passed via CLI.\n\
             \n\
             The PTY will run as the current user. To run as a different user,\n\
             start filament from that user's session, or use 'runas /user:<name> filament'.",
            ui::paint(ui::Tone::Warn, "WARNING:")
        ));
    }
    if install && system {
        return install_system_service(shell, &shell_only, &shell_user);
    }
    if install {
        // Gate --install on a detected service manager.
        let host = platform::ServiceHost::detect();
        if !host.supports_install() {
            let hint = host.install_instructions();
            eprintln!("filament: --install is not supported on this platform. {hint}");
            return Ok(());
        }
        let exe = std::env::current_exe()?;
        let mut up_args = String::new();
        if let Some(csv) = &shell_only {
            up_args.push_str(&format!(" --shell-only {csv}"));
        } else if shell {
            up_args.push_str(" --shell");
        }
        if let Some(u) = &shell_user {
            up_args.push_str(&format!(" --shell-user {u}"));
        }
        // Try privileged system install (elevation popup). On decline, fall
        // back to user-level autostart. Never fail hard.
        match host.install_system(&exe, &up_args) {
            Ok(platform::InstallResult::System) => {
                ui::say(&format!("  {} installed as a system service (autostart at boot)", ui::paint(ui::Tone::Ok, ui::glyph_ok())));
            }
            Ok(platform::InstallResult::User) | Err(_) => {
                // Elevation declined: user-level autostart
                host.install_user(&exe, &up_args)?;
                ui::say(&format!("  {} installed as a user-level autostart", ui::paint(ui::Tone::Ok, ui::glyph_ok())));
                ui::say(&format!("  {} run `filament up --install` again to grant admin for kernel overlay",
                    ui::paint(ui::Tone::Dim, "note:")));
            }
        }
        #[cfg(target_os = "windows")]
        platform::add_firewall_rule(&exe);
        return Ok(());
    }
    if let Some(pid) = daemon_alive() {
        eprintln!("[up] already-up: pidfile={:?} pid={pid} cmdline={:?}", pidfile(), std::fs::read_to_string(format!("/proc/{pid}/cmdline")).unwrap_or_default());
        bail!("already up (pid {pid}), `filament status` / `filament down`");
    }
    let dir = drop_dir(dir);
    std::fs::create_dir_all(&dir)?;
    std::fs::write(pidfile(), std::process::id().to_string())?;
    match &shell_policy {
        // M-2: --shell intentionally grants ALL proof-verified paired devices
        // (current AND any introduced later via pair-intro). This is a broad,
        // deliberate over-grant; --shell-only is the scoped, safer alternative.
        ShellPolicy::All => ui::say(&format!(
            "  {} seamless shell ON, ANY paired device (now or paired later) can `filament ssh` into this machine",
            ui::paint(ui::Tone::Warn, "!"),
        )),
        ShellPolicy::Only(set) => {
            let mut names: Vec<&String> = set.iter().collect();
            names.sort();
            let list = names.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
            ui::say(&format!(
                "  {} seamless shell ON for: {list}, they can `filament ssh` into this machine",
                ui::paint(ui::Tone::Warn, "!"),
            ));
        }
        ShellPolicy::Granted => {}
    }
    // M-1: warn loudly when a shell policy is active but the PTY is NOT dropped to
    // a non-root account. The granted device would get a shell as the up-process
    // user (often root on a server). `--shell-user <name>` de-fangs this.
    if shell_policy.enables_l2() && shell_user.is_none() {
        ui::say(&format!(
            "  {} shell PTYs run as THIS user (root if the daemon is root), pass `--shell-user <name>` to drop to a non-root account",
            ui::paint(ui::Tone::Warn, "!"),
        ));
    }
    // Pre-resolve our public IP off the critical path so the FIRST incoming
    // connect answers the transport-offer without an inline `/api/whoami` round
    // trip (the acceptor's gather is what the initiator waits on during
    // establishing). Best-effort, backgrounded so it never delays daemon start.
    {
        let server = server.to_string();
        tokio::spawn(async move { direct::warm_public_ip(&server).await; });
    }
    let res = recv_cmd(server, None, dir, false, None, None, true, relay, None, true, None, shell_policy, shell_user, no_proxy_fallback).await;
    let _ = std::fs::remove_file(pidfile());
    res
}

/// Bare-command tour: what filament is, the current state, and the two or three
/// things you'd actually do next, adapted to whether you've paired anyone yet. No
/// flags to learn; `--help` still has the full surface. (CLI-UX work, point #2.)
fn tour_cmd() -> Result<()> {
    let color = ui::stdout_color();
    ui::say(&format!(
        "  {}  {}",
        ui::paint_when(color, ui::Tone::Brand, "filament"),
        ui::paint_when(color, ui::Tone::Dim, "· send files and reach your devices, no account"),
    ));
    ui::say("");
    match daemon_alive() {
        Some(pid) => ui::say(&format!("  {} daemon up (pid {pid})", ui::paint_when(color, ui::Tone::Ok, ui::glyph_ok()))),
        None => ui::say(&format!("  {} daemon not running", ui::paint_when(color, ui::Tone::Dim, "·"))),
    }
    let n = devices_load().len();
    ui::say(&format!("  {n} known device{}", if n == 1 { "" } else { "s" }));
    ui::say("");
    ui::say(&ui::paint_when(color, ui::Tone::Dim, "  do this:"));
    let act = |cmd: &str, desc: &str| ui::say(&format!("    {:<24} {}", cmd, desc));
    act("filament send <file>", "send files (to a browser or a paired device)");
    if n == 0 {
        act("filament pair", "remember a device (unlocks ssh + expose)");
    } else {
        act("filament <device>", "shell into a paired device (e.g. filament dovm)");
        act("filament expose <port>", "publish a local port on the mesh");
    }
    act("filament up", "receive in the background");
    ui::say(&ui::paint_when(color, ui::Tone::Dim, "  more:  filament --help  ·  filament status  ·  filament devices"));
    Ok(())
}

fn status_cmd(json: bool) -> Result<()> {
    if json {
        let pid = daemon_alive();
        let exposed: Vec<Value> = expose::load()
            .iter()
            .map(|b| json!({ "port": b.port, "target": b.target, "peers": b.peers.clone().unwrap_or_default() }))
            .collect();
        let mut recent: Vec<String> = std::fs::read_to_string(up_log())
            .map(|log| log.lines().rev().take(8).map(str::to_string).collect())
            .unwrap_or_default();
        recent.reverse();
        println!(
            "{}",
            serde_json::to_string_pretty(&json!({
                "running": pid.is_some(),
                "pid": pid,
                "devices": devices_load().len(),
                "exposed": exposed,
                "recent": recent,
            }))?
        );
        return Ok(());
    }
    match daemon_alive() {
        Some(pid) => ui::say(&format!("  {} up (pid {pid})", ui::paint(ui::Tone::Ok, ui::glyph_ok()))),
        None => ui::say(&format!("  {} not running, start with: filament up", ui::paint(ui::Tone::Dim, "·"))),
    }
    let n = devices_load().len();
    ui::say(&format!("  {} known device{}", n, if n == 1 { "" } else { "s" }));
    let exposed = expose::load();
    if !exposed.is_empty() {
        ui::say(&ui::paint(ui::Tone::Dim, "  exposed on .mesh:"));
        for b in exposed {
            let scope = match &b.peers {
                Some(p) if !p.is_empty() => p.join(","),
                _ => "any".into(),
            };
            ui::say(&format!("    :{} {} {}  ({})", b.port, ui::glyph_arrow(), b.target, scope));
        }
    }
    if let Ok(log) = std::fs::read_to_string(up_log()) {
        let recent: Vec<&str> = log.lines().rev().take(8).collect();
        if !recent.is_empty() {
            ui::say(&ui::paint(ui::Tone::Dim, "  recent receives:"));
            for l in recent.iter().rev() {
                ui::say(&format!("    {l}"));
            }
        }
    }
    Ok(())
}

fn down_cmd() -> Result<()> {
    match daemon_alive() {
        Some(pid) => {
            std::process::Command::new("kill").arg(pid.to_string()).status()?;
            let _ = std::fs::remove_file(pidfile());
            ui::say(&format!("  {} stopped (pid {pid})", ui::paint(ui::Tone::Ok, ui::glyph_ok())));
            Ok(())
        }
        None => {
            ui::say("  not running");
            Ok(())
        }
    }
}

// ------------------------------------------------------------ introduce ----
// Vouched pairing: the hub (which already trusts A and B) mints a fresh
// secret and delivers it to both over channels it has PROVEN itself on
// (fingerprint-bound, C20). Receivers only honor pair-intro from a verified
// link, so a stranger, or the server, can't inject trust.

async fn introduce_cmd(server: &str, a: &str, b: &str, relay: bool) -> Result<()> {
    let store = devices_load();
    let find = |n: &str| store.iter().find(|(name, _)| name.eq_ignore_ascii_case(n)).cloned();
    let (a_name, a_sec) = find(a).ok_or_else(|| anyhow!("'{a}' is not a known device (see: filament devices)"))?;
    let (b_name, b_sec) = find(b).ok_or_else(|| anyhow!("'{b}' is not a known device"))?;

    let my_uid = mk_uid("s");
    let (tx, mut rx) = mpsc::unbounded_channel::<Ev>();
    let sio = net::connect_signaling(server, tx.clone()).await?;
    let solo = format!("intro-{}", fresh_secret());
    // C30: the session repairs whatever these emits lose, and under gate L
    // they are the emits the loss shim adversarially drops.
    let mut sess = session::Session::new(&display_name(), &my_uid);
    sess.room = Some(solo.clone());
    sess.channels = vec![channel_of(&a_sec), channel_of(&b_sec)];
    sess.emit(&sio, "join", json!({ "room": solo, "name": display_name(), "uid": my_uid })).await;
    sess.emit(&sio, "subscribe", json!({ "channels": [channel_of(&a_sec), channel_of(&b_sec)] })).await;
    ui::say(&format!("  waiting for {} and {} to be online...", ui::paint(ui::Tone::Bold, &a_name), ui::paint(ui::Tone::Bold, &b_name)));

    let mut conn = Conn {
        server: server.to_string(),
        sio: sio.clone(),
        tx: tx.clone(),
        my_uid: my_uid.clone(),
        my_id: String::new(),
        relay_only: relay,
        to_filter: None,
        links: HashMap::new(),
        roster: HashMap::new(),
        active: None,
        next_gen: 0,
        rejoin: RejoinState { waiting_rejoin: None, rejoin_window: REJOIN_WINDOW, away: None },
        chunk_size: net::MAX_DC_PAYLOAD,
        deferred_left: HashMap::new(),
        recv_done: false,
    direct_pending: HashMap::new(),
    resil: ResilienceState {
        stall_repairs: HashMap::new(),
        relay_committed: std::collections::HashSet::new(),
        warm_standby: net::warm_standby_override().unwrap_or(false),
        warm_cutover: std::collections::HashSet::new(),
        upgrade_probe: HashMap::new(),
        iface_snapshot: Vec::new(),
    },
    direct_ok: direct::direct_enabled(),
    local_port: None,
    local_listener: None,
    direct_endpoint: None,
    warm_hold: WarmHold::default(),
    worker_port_tx: HashMap::new(),
    };
    // sid -> which device (false = a, true = b)
    let mut who: HashMap<String, bool> = HashMap::new();
    let mut sent: [bool; 2] = [false, false];
    let fresh = fresh_secret();
    let deadline = Instant::now() + Duration::from_secs(120);

    loop {
        if Instant::now() > deadline {
            bail!("timed out, both devices must be online (e.g. running `filament up`)");
        }
        let ev = match tokio::time::timeout(Duration::from_secs(2), rx.recv()).await {
            Ok(Some(ev)) => ev,
            Ok(None) => bail!("signaling closed"),
            Err(_) => continue,
        };
        sess.tick(&sio).await; // C30: converge every iteration (incl. ticks)
        conn.reap_deferred(); // #28: discharge deferred peer-left when idle/dead
        match ev {
            Ev::Welcome(v) => {
                conn.my_id = v["id"].as_str().unwrap_or_default().to_string();
                // C30 (dissolves the C28 belt): fresh sid, re-assert via session.
                sess.invalidate();
            }
            Ev::Synced(v) => { sess.on_synced(&v); }
            Ev::KnownPeer(v) => {
                if is_self_uid(&conn.my_uid, v["uid"].as_str()) {
                    continue; // our own processes share these channels
                }
                let ch = v["channel"].as_str().unwrap_or_default().to_string();
                let pid = v["id"].as_str().unwrap_or_default().to_string();
                let is_b = if ch == channel_of(&a_sec) { false } else if ch == channel_of(&b_sec) { true } else { continue };
                conn.maybe_adopt(&v, false).await?;
                if let Some(l) = conn.link_mut(&pid) {
                    l.expected_secret = Some(if is_b { (b_name.clone(), b_sec.clone()) } else { (a_name.clone(), a_sec.clone()) });
                }
                who.insert(pid, is_b);
            }
            Ev::Signal(v) => {
                let from = v["from"].as_str().unwrap_or_default().to_string();
                let data = v["data"].clone();
                conn.ensure_responder(&from, &data).await?;
                conn.apply_signal(&from, data).await;
            }
            Ev::ChannelReady(pid, t) => {
                if let Some(l) = conn.link_mut(&pid) {
                    l.transport = Some(t.clone());
                    l.presence = Presence::Ready;
                }
                let Some(&is_b) = who.get(&pid) else { continue };
                let (dev_name, sec) = if is_b { (&b_name, &b_sec) } else { (&a_name, &a_sec) };
                let other_name = if is_b { &a_name } else { &b_name };
                if let Some(l) = conn.link(&pid) {
                    if let Some((my_fp, their_fp)) = match &l.peer { Some(p) => p.fingerprints().await, None => None } {
                        // prove ourselves, then vouch
                        t.send_control(&json!({
                            "type": "pair-proof",
                            "mac": proof_for(sec, &conn.my_uid, &conn.my_uid, l.uid.as_deref().unwrap_or(""), &my_fp, &their_fp),
                        })).await?;
                        t.send_control(&json!({
                            "type": "pair-intro", "name": other_name, "secret": fresh,
                        })).await?;
                        sent[is_b as usize] = true;
                        ui::say(&format!("  {} vouched to {}", ui::paint(ui::Tone::Ok, ui::glyph_ok()), ui::paint(ui::Tone::Bold, dev_name)));
                    }
                }
                if sent[0] && sent[1] {
                    tokio::time::sleep(Duration::from_millis(800)).await; // let intros flush
                    ui::say(&format!(
                        "  {} {} and {} now know each other (no codes needed)",
                        ui::paint(ui::Tone::Ok, ui::glyph_ok()),
                        a_name, b_name,
                    ));
                    let _ = sio.disconnect().await;
                    return Ok(());
                }
            }
            Ev::Stuck(pid, g) => { conn.on_stuck(&pid, g, "stuck").await?; }
            Ev::GraceExpired(pid, g) => { conn.on_stuck(&pid, g, "lost").await?; }
            Ev::PcState(pid, st) => conn.on_pc_state(&pid, &st).await,
            Ev::PeerLeft(v) => { conn.on_peer_left(&v); }
            Ev::Interrupted => bail!("interrupted"),
            _ => {}
        }
    }
}

// ----------------------------------------------------------------- pair ----
// L1-a (PAKE v2): remembering a device is a first-class ceremony, no file
// transfer to pretend through. The first-pairing now runs a real SPAKE2 PAKE
// over the SPOKEN code so a malicious signaling server cannot MITM enrollment.
//
// The load-bearing change vs v1:
//   - The CLIENT mints the words locally (server sees only the numeric
//     nameplate); the password (words) NEVER reaches the server.
//   - SPAKE2 runs over the opaque `signal` relay BEFORE any secret exists.
//   - A key-confirmation MAC folds in the SORTED DTLS fingerprints + caps, so a
//     server that substitutes a DTLS cert OR rewrites caps is DETECTED → abort.
//   - The 32-byte pinned secret is HKDF(K), AGREED, never transmitted. The old
//     `pair-keep` secret-over-DataChannel step is GONE from the v2 path.
//   - Downgrade is structurally impossible: a v2 client NEVER sends pair-keep
//     and NEVER stores a secret from a received pair-keep. A received pair-keep
//     means the peer is v1 → abort with "update to pair securely". A server
//     stripping `v:2` therefore cannot force the readable-secret path.
//
// The opaque PAKE payloads carried on `signal` (the 33-byte SPAKE2 element and
// the 32-byte confirmation MAC) are encoded/decoded by the shared
// `pake_ceremony` module, which also owns the ceremony state machine that BOTH
// `pair` and the transfer path (`send --code` / `recv`) now run.
use pake_ceremony::{pair_v2_caps, Ceremony, Inbound as PakeInbound};

/// The one-line dim banner shown right before we open the guided entry on a
/// MALFORMED arg, so the user knows WHY the prompt appeared and how to make it
/// fail fast in scripts.
fn malformed_entry_banner(arg: &str) {
    ui::say(&ui::paint(
        ui::Tone::Dim,
        &format!(
            "couldn't parse '{arg}', opening guided entry · set FILAMENT_NONINTERACTIVE=1 to fail fast in scripts"
        ),
    ));
}

/// Map a codeentry Outcome::Cancelled into a clean error (used by the wired
/// commands so a cancel exits non-zero without a stack-y message).
fn cancelled() -> anyhow::Error {
    anyhow!("cancelled")
}

async fn pair_cmd(server: &str, mut code: Option<String>, name: Option<String>, mut word: Option<String>, relay: bool) -> Result<()> {
    // INTERACTIVE GATE (scripts safe by default, see `interactive_allowed`).
    //   * `pair` with no code AND no --word -> guided CREATE entry. Empty submit
    //     falls back to today's auto-mint; typed words become the chosen password.
    //   * `pair <malformed>` (a positional that isn't a valid claim shape) ->
    //     banner, then guided CLAIM entry PRE-FILLED with the normalized input.
    // When the gate is closed we keep EXACTLY today's behavior below.
    //
    // If the guided CREATE entry runs, it mints the nameplate ONCE here and shows
    // it in the preview; we carry it forward so the code we actually create uses
    // the SAME number the user saw (no shown-one-number, got-another mismatch).
    let mut preview_nameplate: Option<String> = None;
    if word.is_none() && interactive_allowed() {
        let malformed = code.as_deref().filter(|c| {
            // A "valid claim shape" is words + a trailing dash-group; anything that
            // split_code can't peel into (nameplate, non-empty words) is malformed.
            let normalized = crate::pake::norm_code(c);
            let (np, pw) = crate::pake::split_code(&normalized);
            pw.is_empty() || np.is_empty()
        });
        match (&code, malformed) {
            // No code at all -> CREATE entry.
            (None, _) => {
                let auto_np = crate::pake::words::mint_nameplate();
                match codeentry::run("  pair · choose words  ", codeentry::Mode::Create, "", &auto_np)? {
                    codeentry::Outcome::Submitted(words) => {
                        word = Some(words);
                        // Reuse the SAME nameplate we just previewed, so the code
                        // we mint matches the number the user saw.
                        preview_nameplate = Some(auto_np);
                    }
                    // Empty submit -> fall through to auto-mint, but still keep the
                    // previewed nameplate so an empty (auto-words) create reuses it.
                    codeentry::Outcome::Empty => preview_nameplate = Some(auto_np),
                    codeentry::Outcome::Cancelled => return Err(cancelled()),
                }
            }
            // Malformed positional -> banner + prefilled CLAIM entry.
            (Some(raw), Some(_)) => {
                malformed_entry_banner(raw);
                let prefill = crate::pake::norm_code(raw);
                match codeentry::run("  pair · code  ", codeentry::Mode::Claim, &prefill, "")? {
                    codeentry::Outcome::Submitted(c) => code = Some(c),
                    // Empty submit on a claim-fix means "give up on this code".
                    codeentry::Outcome::Empty => return Err(cancelled()),
                    codeentry::Outcome::Cancelled => return Err(cancelled()),
                }
            }
            // A well-formed positional -> no prompt, proceed as today.
            (Some(_), None) => {}
        }
    }
    // STEERING: --word lets the creator choose the SPAKE2 password. The positional
    // `code` arg still means "claim", so --word + a code is contradictory.
    if word.is_some() && code.is_some() {
        bail!("--word chooses your OWN pairing words (creator); it can't be combined with a code to claim. Drop one.");
    }
    // A custom phrase must clear the min-strength floor BEFORE we touch the
    // network. Normalize with the SHARED norm_code so the echoed/created code is
    // exactly what SPAKE2 will hash, then require >= 2 word tokens.
    let custom_words: Option<String> = match &word {
        Some(w) => {
            // The nameplate is ALWAYS machine-minted, so discard any number the
            // user typed; keep only the words half. `split_chosen_code` (unlike
            // `split_code`) only strips a trailing 3-5 digit nameplate, so a
            // two-word phrase like "gigantic element" keeps BOTH words.
            let (words, _np) =
                crate::pake::split_chosen_code(&crate::pake::norm_code(w));
            if password_word_tokens(&words) < 2 {
                bail!(
                    "'{w}' is too weak. Use at least two words, e.g. gigantic-element \
                     (easier to say, harder to guess). A single word falls below the \
                     strength floor the rate-limit relies on."
                );
            }
            Some(words)
        }
        None => None,
    };
    let my_uid = mk_uid("p");
    let (tx, mut rx) = mpsc::unbounded_channel::<Ev>();
    let sio = net::connect_signaling(server, tx.clone()).await?;
    // Meta must exist for pairing; an unguessable solo room keeps strangers
    // out (the daemon's trick), the pair-claim moves people, not the room.
    let solo = format!("pairc-{}", fresh_secret());
    // C30: the session repairs the solo-room membership/lease if the join dies.
    let mut sess = session::Session::new(&display_name(), &my_uid);
    sess.room = Some(solo.clone());
    sess.emit(&sio, "join", json!({ "room": solo, "name": display_name(), "uid": my_uid })).await;
    // A code that looks like a one-time TRANSFER code (word-word-NNN, 2-3 digit
    // trailing) typed into `pair`, which runs the PAKE pairing ceremony,
    // redirect clearly before the handshake stalls against a peer that isn't
    // pairing. ADVISORY only (by trailing-number width); PAKE still authenticates.
    if let Some(c) = &code {
        if regex_lite_code(c) && !looks_like_pake_code(c) {
            bail!(
                "'{c}' looks like a one-time TRANSFER code (from `filament send --code`), not a pairing code.\n  \
                 To receive that transfer: run `filament {c}` (or `filament recv {c}`)\n  \
                 A pairing code ends in a 4-digit number, e.g. `brave-otter-3141`."
            );
        }
    }
    let creator = code.is_none();
    // L1-a: the spoken code is split CLIENT-SIDE into (nameplate, password). The
    // password (words) NEVER leaves this process; only the nameplate is sent.
    let mut my_words; // the password (creator mints; claimer types)
    let mut my_nameplate;
    match &code {
        Some(c) => {
            // Claimer: normalize the typed code, split, send ONLY the nameplate.
            let normalized = crate::pake::norm_code(c);
            let (np, pw) = crate::pake::split_code(&normalized);
            if pw.is_empty() || np.is_empty() {
                bail!("that code doesn't look right, expected something like brave-otter-ruby-3141");
            }
            my_words = pw;
            my_nameplate = np.clone();
            ui::say(&format!("  claiming {}...", ui::paint(ui::Tone::Brand, c)));
            sio.emit("pair-claim", json!({ "nameplate": np, "v": 2 })).await.ok();
        }
        None => {
            // Creator: use the user's chosen words (--word) or mint them; the
            // nameplate is ALWAYS machine-minted. Ask the server to allocate ONLY
            // the nameplate. The full code is displayed from our own words when
            // pair-ok arrives (the server never echoes any words).
            my_words = custom_words.clone().unwrap_or_else(crate::pake::words::mint_words);
            // Reuse the nameplate the guided entry already previewed (if any), so
            // the created code matches what the user saw; otherwise mint fresh.
            my_nameplate = preview_nameplate
                .clone()
                .unwrap_or_else(crate::pake::words::mint_nameplate);
            // STEERING: echo the normalized code we're about to create so the
            // creator sees EXACTLY what their peer must type (== what SPAKE2 hashes).
            if custom_words.is_some() {
                ui::say(&format!(
                    "  using your words: {}",
                    ui::paint(ui::Tone::Brand, &format!("{my_words}-{my_nameplate}"))
                ));
            }
            sio.emit("pair-create", json!({ "nameplate": my_nameplate, "v": 2 })).await.ok();
        }
    }

    let mut conn = Conn::for_command(
        server,
        sio.clone(),
        tx.clone(),
        my_uid.clone(),
        relay,        // relay_only
        None,         // to_filter
        false,        // warm_standby default (pair is one-shot)
        direct::direct_enabled(), // direct_ok: env gate only (no L2 acceptor here)
    );
    {
        let tx = tx.clone();
        tokio::spawn(async move {
            let _ = tokio::signal::ctrl_c().await;
            // Bounded force-exit guarantee: the Interrupted bail unwinds and drops
            // the peers, and a webrtc/quinn drop can itself deadlock. Arm a
            // watchdog so Ctrl-C always exits promptly regardless.
            shutdown::arm_force_exit(130, shutdown::grace());
            let _ = tx.send(Ev::Interrupted);
        });
    }

    let mut petname = name; // resolved --name, prompt answer, or peer's display name
    let mut prompted = false;
    let mut peer: Option<(String, String)> = None; // (pid, display name)

    // ---- L1-a PAKE state (shared ceremony) ----------------------------------
    // The agreed pinned secret (HKDF(K)); set ONLY after key confirmation passes.
    // `pair` PERSISTS it (a known device); the transfer path runs the SAME
    // ceremony but DISCARDS it. The ceremony state machine lives in
    // `pake_ceremony::Ceremony` and is driven identically by both flows.
    let mut agreed_secret: Option<String> = None;
    // Peer signaling sid we run the PAKE with (set when the link is adopted).
    let mut pake_peer: Option<String> = None;
    let caps = pair_v2_caps();
    // Start our SPAKE2 ceremony immediately: identity = nameplate, password =
    // words. Both sides MUST pass identical password AND nameplate (spec §3.1).
    let mut cer = Ceremony::new(&my_words, &my_nameplate, caps.clone());
    let deadline = Instant::now() + Duration::from_secs(600); // code TTL
    // The pairing peer left before the ceremony finished. Give a short grace
    // for a transient reconnect, then FAIL FAST, don't orphan in the room
    // for the full 10-min TTL (the D3/D5 divergence the monitor kept
    // catching: creator's connect failed, it quit, claimer sat silent).
    // Once the code is CLAIMED, the ceremony must finish in seconds. Bound it:
    // if it hasn't completed within this budget, the peer disconnected or could
    // never connect, fail fast instead of orphaning in the room for the full
    // 600s TTL (the D3/D5 divergence the monitor kept catching). 60s is generous
    // (covers a slow cross-NAT WebRTC with its 3×15s establishment retries);
    // FILAMENT_PAIR_GRACE_SECS shortens it for gate 17b.
    let ceremony_budget = Duration::from_secs(
        std::env::var("FILAMENT_PAIR_GRACE_SECS").ok().and_then(|v| v.parse().ok()).unwrap_or(60),
    );
    let mut ceremony_deadline: Option<Instant> = None;
    // Gate 17b hook: connect but never complete, so the ceremony budget fires
    // deterministically (same-machine pairs otherwise finish in ~1s).
    let stall = test_hooks::pair_stall();

    loop {
        // Done when the petname is settled AND the PAKE agreed a secret (key
        // confirmation passed). The secret is HKDF(K), never transmitted, the
        // same on both sides; it drops straight into devices.json.
        if let Some(n) = petname.clone() {
            if let Some(sec) = agreed_secret.clone() {
                // caps_v2 (spec §8): record GRANTED caps, deny-by-default.
                // devices_store_v2 handles name collisions via auto-suffix.
                devices_store_v2(&n, &sec, &caps)?;
                ui::say(&format!(
                    "  {} {} mutually remembered, verified end-to-end (no key ever crossed the server)",
                    ui::paint(ui::Tone::Ok, ui::glyph_ok()),
                    ui::paint(ui::Tone::Bold, &n),
                ));
                ui::say(&ui::paint(ui::Tone::Dim, &format!("  try: filament send <file> --to {n}   ·   filament up")));
                tokio::time::sleep(Duration::from_millis(300)).await; // let acks flush
                let _ = sio.disconnect().await;
                return Ok(());
            }
        }
        if Instant::now() > deadline {
            bail!("timed out, the code was never used (codes expire after 10 minutes)");
        }
        // Fail fast: the code was claimed but the ceremony didn't finish in
        // time, the peer disconnected or never connected.
        if let Some(dl) = ceremony_deadline {
            if Instant::now() > dl {
                bail!("the other device disconnected or could not connect before pairing finished, make sure both run `filament pair` at the same time, then try again");
            }
        }
        sess.tick(&sio).await; // C30: converge every iteration (incl. ticks)
        conn.reap_deferred(); // #28: discharge deferred peer-left when idle/dead

        // ---- L1-a PAKE progression (runs every iteration) ------------------
        // 1) Once we know the peer's signaling sid, send our SPAKE2 element over
        //    the opaque `signal` relay (the server cannot read it).
        if let Some(pid) = pake_peer.clone() {
            // gate 17b (FILAMENT_TEST_PAIR_STALL): never send our SPAKE2 element,
            // so the exchange can't complete on either side and the ceremony's
            // fail-fast `ceremony_deadline` fires, proving the no-10-min-orphan
            // guard. Test-only: `stall` is set solely by that env var.
            if !stall {
                if let Some(data) = cer.take_msg_payload() {
                    sio.emit("signal", json!({ "to": pid, "data": data })).await.ok();
                }
            }
            // 2) Once K is derived AND both DTLS fingerprints are known, send the
            //    key-confirmation MAC over K + sorted fingerprints + caps. The MAC
            //    is gated on the fingerprints so a server that substitutes a DTLS
            //    cert produces a different fingerprint → the peer's verify fails.
            if cer.has_k() {
                if let Some(l) = conn.link(&pid) {
                    if let Some((my_fp, their_fp)) = match &l.peer { Some(p) => p.fingerprints().await, None => None } {
                        if let Some(data) = cer.take_confirm_payload(&my_fp, &their_fp) {
                            sio.emit("signal", json!({ "to": pid, "data": data })).await.ok();
                        }
                    }
                }
            }
        }

        let ev = match tokio::time::timeout(Duration::from_secs(2), rx.recv()).await {
            Ok(Some(ev)) => ev,
            Ok(None) => bail!("signaling closed"),
            Err(_) => continue,
        };
        match ev {
            Ev::Welcome(v) => {
                conn.my_id = v["id"].as_str().unwrap_or_default().to_string();
                if let Some(peers) = v["peers"].as_array() {
                    for p in peers {
                        conn.maybe_adopt(p, true).await?;
                    }
                }
                sess.invalidate(); // C30: fresh sid, re-assert next tick
            }
            Ev::Synced(v) => { sess.on_synced(&v); }
            Ev::PairOk(_v) => {
                // L1-a: the server allocated our nameplate. Display the FULL code
                // from OUR OWN local mint (the server never echoed any words).
                let full = format!("{my_words}-{my_nameplate}");
                ui::clipboard(&full);
                ui::say("");
                ui::say(&format!("      {}", ui::paint(ui::Tone::Brand, &full.to_uppercase())));
                ui::say("");
                ui::say(&ui::paint(ui::Tone::Dim, "  on the other device: type it into the web app, or `filament pair <code>`"));
                ui::say(&ui::paint(ui::Tone::Dim, "  one claim · expires in 10 min · paired end-to-end (no key crosses the server)"));
            }
            Ev::PairCode(v) => {
                // v1 server (shouldn't happen for a v2 create, but be safe): a
                // legacy server-minted code means the peer can't PAKE-pair.
                let c = v["code"].as_str().unwrap_or("?");
                let _ = c;
                bail!("this server returned a legacy code. Update the server (or the peer) to pair securely.");
            }
            Ev::PairUsed(_) => {
                ui::say(&ui::paint(ui::Tone::Dim, "  code claimed, connecting..."));
                ceremony_deadline.get_or_insert_with(|| Instant::now() + ceremony_budget);
            }
            Ev::PairMatched(v) => {
                let room = v["room"].as_str().unwrap_or_default().to_string();
                ceremony_deadline.get_or_insert_with(|| Instant::now() + ceremony_budget);
                ui::say(&format!("  {} code accepted, connecting", ui::paint(ui::Tone::Ok, ui::glyph_ok())));
                sess.room = Some(room.clone()); // C30: desire moves with us
                sess.touch();
                sess.emit(&sio, "join", json!({ "room": room, "name": display_name(), "uid": my_uid })).await;
            }
            Ev::PairError(v) => {
                // Creator nameplate collision: re-mint a FRESH nameplate (and
                // fresh words) and retry, never reuse a burned code.
                if creator && v["error"].as_str() == Some("taken") {
                    // Re-mint a FRESH nameplate; KEEP the creator's chosen words
                    // (--word), only mint fresh words when we minted them.
                    if custom_words.is_none() {
                        my_words = crate::pake::words::mint_words();
                    }
                    my_nameplate = crate::pake::words::mint_nameplate();
                    cer.restart(&my_words, &my_nameplate);
                    sio.emit("pair-create", json!({ "nameplate": my_nameplate, "v": 2 })).await.ok();
                    continue;
                }
                let hint = match v["why"].as_str() {
                    Some("sender-gone") => "that code's creator already left, ask them for a fresh one".to_string(),
                    _ => format!("{}, codes burn after one use; a failed pairing needs a FRESH code (re-run `filament pair`)", v["error"].as_str().unwrap_or("?")),
                };
                bail!("code rejected: {hint}");
            }
            Ev::PeerJoined(v) => {
                conn.maybe_adopt(&v, true).await?;
            }
            Ev::Signal(v) => {
                let from = v["from"].as_str().unwrap_or_default().to_string();
                let data = v["data"].clone();
                // L1-a: PAKE messages ride the opaque `signal` relay. Branch them
                // OUT of the WebRTC signal path (SDP/ICE) into the shared ceremony.
                // A `pake-confirm` verify ⇒ wrong password OR a server that
                // substituted a DTLS cert OR rewrote caps ⇒ ABORT, agree NOTHING.
                if matches!(data["type"].as_str(), Some("pake-msg") | Some("pake-confirm")) {
                    pake_peer.get_or_insert(from.clone());
                    let fps = match conn.link(&from) {
                        Some(l) => match &l.peer { Some(p) => p.fingerprints().await, None => None },
                        None => None,
                    };
                    let fp_ref = fps.as_ref().map(|(a, b)| (a.as_str(), b.as_str()));
                    match cer.on_signal(&data, fp_ref) {
                        PakeInbound::Consumed => {
                            if let Some(sec) = cer.secret() {
                                agreed_secret = Some(sec.clone());
                            }
                        }
                        PakeInbound::Abort(why) => {
                            bail!("pairing REFUSED: {why}. Nothing was stored; ask for a FRESH code.");
                        }
                        PakeInbound::Ignored => {}
                    }
                    continue;
                }
                conn.ensure_responder(&from, &data).await?;
                conn.apply_signal(&from, data).await;
            }
            Ev::ChannelReady(pid, t) => {
                let display = match conn.link_mut(&pid) {
                    Some(l) => {
                        l.transport = Some(t.clone());
                        l.presence = Presence::Ready;
                        l.name.clone()
                    }
                    None => continue,
                };
                ui::say(&format!("  {} {}", ui::paint(ui::Tone::Ok, ui::glyph_ok()), ui::paint(ui::Tone::Bold, &display)));
                peer = Some((pid.clone(), display.clone()));
                let _ = &t; // transport not used on the v2 path (no secret over DC)
                if stall {
                    continue; // gate 17b: connected, but deliberately never complete
                }
                // L1-a: the link is up and SDP fingerprints exist. Mark this peer
                // as our PAKE counterpart; the progression block (top of the loop)
                // sends our SPAKE2 element and, once K + fingerprints are known,
                // the key-confirmation MAC. NO secret is sent over the DataChannel.
                pake_peer.get_or_insert(pid.clone());
                // Settle the petname: --name wins; otherwise ask (tty) or
                // default to their display name (scripts, pipes).
                if petname.is_none() && !prompted {
                    prompted = true;
                    if std::io::stdin().is_terminal() {
                        eprint!("  remember this device as [{display}]: ");
                        let tx = tx.clone();
                        tokio::spawn(async move {
                            use tokio::io::AsyncBufReadExt;
                            let mut line = String::new();
                            let mut reader = tokio::io::BufReader::new(tokio::io::stdin());
                            if reader.read_line(&mut line).await.is_ok() {
                                let _ = tx.send(Ev::StdinLine(line.trim().to_string()));
                            }
                        });
                    } else {
                        petname = Some(display.clone());
                    }
                }
            }
            Ev::StdinLine(line) => {
                if petname.is_none() && prompted {
                    let n = if line.is_empty() {
                        peer.as_ref().map(|(_, d)| d.clone()).unwrap_or_else(|| "device".into())
                    } else {
                        line
                    };
                    petname = Some(n);
                }
            }
            Ev::Control(pid, v) if stall => {
                let _ = (pid, v); // gate 17b: connected, but ignore all ceremony control
            }
            Ev::Control(_pid, v) => match v["type"].as_str() {
                // L1-a downgrade-refusal (spec §6.1): a v2 client NEVER stores a
                // secret handed over the DataChannel. Receiving a `pair-keep` means
                // the PEER is a legacy v1 client. We refuse, pairing securely
                // requires v2 on both ends. A malicious server stripping `v:2`
                // cannot exploit this: there is no path here that stores a
                // server-readable secret.
                Some("pair-keep") => {
                    bail!("the other device uses an older version and can't pair securely. Update it (or this CLI) so first-pairing runs the encrypted handshake. Nothing was stored.");
                }
                _ => {}
            },
            Ev::Stuck(pid, g) => {
                conn.on_stuck(&pid, g, "stuck").await?;
            }
            Ev::GraceExpired(pid, g) => {
                conn.on_stuck(&pid, g, "lost").await?;
            }
            Ev::PcState(pid, st) => conn.on_pc_state(&pid, &st).await,
            Ev::PeerLeft(v) => {
                // A faster, friendlier signal than the ceremony budget when it
                // arrives: the pairing peer left the room. (The budget is the
                // hard backstop, server peer-left can lag behind a hard kill.)
                let gone = v["id"].as_str().and_then(|p| conn.link(p)).map(|l| l.name.clone());
                conn.on_peer_left(&v);
                let n = gone.unwrap_or_else(|| "the other device".into());
                ui::say(&ui::paint(ui::Tone::Dim, &format!("  {n} disconnected, waiting briefly in case it reconnects...")));
            }
            Ev::Interrupted => bail!("interrupted"),
            _ => {}
        }
    }
}

// ---------------------------------------------------------- link machinery --
// One peer at a time, but with the browser's survival rules: establishment
// watchdog (C3), disconnected-grace + ICE restart + reconnect attempts (C4),
// fresh ICE config per attempt (C5), uid supersede on rejoin (C6), and a
// rejoin window when the peer's socket dies entirely.

struct Link {
    /// WebRTC peer connection. `None` for a rung-1 direct link (no ICE/DTLS
    /// negotiation, it rides authenticated QUIC), so every WebRTC-only call
    /// site (`handle_signal`, `fingerprints`, `restart_ice`, the watchdog's
    /// `is_connected`) is reachable only when this is `Some`.
    peer: Option<Arc<Peer>>,
    info: Value, // {id,name,uid} as last seen, enough to re-establish
    name: String,
    uid: Option<String>,
    transport: Option<Arc<dyn Transport>>,
    generation: u32,
    attempts: u32,
    /// C12: proof-verified known device (per link, not global)
    trusted: bool,
    /// (name, secret) hypothesis to prove/verify on this link
    expected_secret: Option<(String, String)>,
    /// The devices.json PETNAME this link proved as (the cap-store key). Set on a
    /// verified `pair-proof` (WebRTC) or at birth for a direct link (already
    /// identity-bound). `None` until proven. Capability lookups (e.g. the `shell`
    /// gate) MUST key on this, NOT on `name` (a presence display string that may
    /// not match a stored record).
    verified_name: Option<String>,
    /// C26: what the status roster shows for this peer
    presence: Presence,
    /// rung-1 (FILAMENT_DIRECT): this link's transport is an authenticated direct
    /// QUIC connection, its pair-secret MAC already proved identity, so the
    /// post-channel DTLS pair-proof is skipped and the link is born trusted.
    direct: bool,
    /// Route label for a direct link (no WebRTC `route()` to query): `direct-quic`
    /// for rung-1, `holepunched` for rung-2. Ignored for WebRTC links.
    direct_route: &'static str,
    /// Parallel QUIC transports for multi-stream file transfer
    /// (`FILAMENT_DIRECT_STREAMS` > 1). Empty when striping is disabled
    /// or when the link uses a non-QUIC transport.
    workers: Vec<Arc<dyn Transport>>,
    /// When this link was established (for the warm-hold pair-proof grace).
    /// `warm_hold_tick` skips re-establish for a live link within this window,
    /// preventing churn while pair-proof verification completes.
    established_at: Option<Instant>,
}

impl Link {
    /// The name to SHOW for this peer. A known device proves into its local
    /// petname (`verified_name`); show that, so one device reads consistently as
    /// (e.g.) `dovm` everywhere instead of flipping between the petname and the
    /// peer's broadcast display name (`name`, e.g. `Abdul's server`). The
    /// broadcast name is the fallback only for an unverified / unknown peer.
    fn shown(&self) -> &str {
        self.verified_name.as_deref().unwrap_or(&self.name)
    }
}

/// C26: per-peer presence for the static status roster.
#[derive(Clone, Copy, PartialEq)]
enum Presence {
    Connecting,
    Ready,
    Away,
    Reconnecting,
}

fn presence_glyph(p: Presence) -> (&'static str, ui::Tone, &'static str) {
    match p {
        Presence::Ready => (ui::glyph_ok(), ui::Tone::Ok, ""),
        Presence::Away => ("", ui::Tone::Warn, "away"),
        Presence::Reconnecting => ("", ui::Tone::Warn, "reconnecting..."),
        Presence::Connecting => ("", ui::Tone::Dim, "connecting..."),
    }
}

/// C18: browsers are mesh peers, they connect to EVERY room member. The CLI
/// must answer every offer politely or unanswered browsers wedge at
/// "connecting" (and their retry storms degrade the whole room). So: a links
/// MAP, every peer answered; SEND still aims transfers at one `active`
/// target; RECV accepts from any link, gated per-link by consent/trust.
const MAX_LINKS: usize = 16;

/// RESILIENCE state, split out of the `Conn` god-struct so the stall/relay/
/// warm-standby/upgrade-probe bookkeeping is one named bag, not mixed in with
/// signaling + protocol state. The pure decisions live in `resilience.rs`.
#[derive(Default)]
struct ResilienceState {
    /// P0 (GAP-1): per-peer stall-repair bookkeeping for the bytes-moved
    /// watchdog. Tracks how many correction-ladder repairs we've already run for
    /// the current stall episode (bounded by MAX_ATTEMPTS) and whether a repair
    /// is in flight, so a single stall can't re-fire the ladder every tick while
    /// a repair is converging. Reset once the link starts flowing again.
    stall_repairs: HashMap<String, StallState>,
    /// P1 (GAP-4): peers this session has COMMITTED to the relay route after the
    /// direct ladder exhausted (rung d). Once a pid is in here, we stop dialing /
    /// answering direct-QUIC for it (the direct path is what just failed and would
    /// only re-freeze, racing the relay link); all (re)establishment for it goes
    /// over relay-only WebRTC. Survives link drops (keyed by pid, not stored on the
    /// Link), so a re-establish never bounces back to the known-bad direct path.
    relay_committed: std::collections::HashSet<String>,
    /// P3 (GAP-3): the WARM-REDUNDANCY selectivity gate. TRUE only for long-lived
    /// / interactive sessions (the `up`/`up --shell` daemon acceptor; a transfer
    /// flagged interactive via `FILAMENT_WARM_STANDBY=1` standing in for a tunnel),
    /// the sessions §2.4 says a mid-session drop is intolerable for. When set,
    /// `correct_stall` keeps the relay path as a pre-designated WARM standby and
    /// CUTS OVER to it on the FIRST stall (rung b) instead of grinding through the
    /// slow direct-repair rung (c)'s up-to-MAX_ATTEMPTS cold re-dials, so the
    /// failover is near-instant rather than a perceptible gap. FALSE for one-shot
    /// file `send` (the 90% case): the on-disk partial + C7 resume make the cold
    /// repair ladder correct and bounded, and a warm standby isn't worth a second
    /// socket / NAT mapping / keepalive for a single transfer (the honest cost
    /// tradeoff, §2.4 / §6). Defaulted by session kind at construction, overridable
    /// by `net::warm_standby_override()` (`FILAMENT_WARM_STANDBY`).
    warm_standby: bool,
    /// P3: per-peer warm-standby bookkeeping, peers whose relay standby has
    /// already been cut over to in the current stall episode, so a flapping relay
    /// path can't re-fire the instant cutover every tick (it falls through to the
    /// bounded relay-stalled `Exhausted` honesty instead). Cleared by
    /// `note_progress` once bytes move again.
    warm_cutover: std::collections::HashSet<String>,
    /// P5 (GAP-6): per-peer relay->direct UPGRADE-PROBE bookkeeping. Present only
    /// for peers currently committed to relay (`relay_committed`) on a session
    /// where the prober is eligible (warm_standby/daemon, relay permitted). Drives
    /// the backoff schedule (probe soon, then steady cadence) and the
    /// verify-before-upgrade window for a connected direct standby. Removed on a
    /// successful upgrade (cutover) or when the peer leaves.
    upgrade_probe: HashMap<String, UpgradeProbe>,
    /// P5: a snapshot of the local interface set (sorted IP strings) at the last
    /// probe schedule. A change (new/removed interface, wifi<->cellular,
    /// default-route move surfacing a new local IP) is the "walked home onto wifi"
    /// signal, we re-probe IMMEDIATELY. Polled cheaply each tick (no platform
    /// netlink dependency); the portable best-effort trigger the plan asks for.
    iface_snapshot: Vec<String>,
}

/// ORCHESTRATION: peer-absence / rejoin-grace bookkeeping, split out of the Conn
/// god-struct. Tracks the reconnect window we hold open for a vanished peer and a
/// peer's declared absence (C21 `brb`).
struct RejoinState {
    /// when set, we are holding a reconnect window open for a vanished peer.
    waiting_rejoin: Option<Instant>,
    /// How long the current rejoin window runs (set when it opens; depends on
    /// whether the peer declared `brb`).
    rejoin_window: Duration,
    /// (peer sid, until), the peer told us it's stepping away (C21).
    away: Option<(String, Instant)>,
}

/// WARM-HOLD state: keeps connections alive to recently-used and explicitly
/// configured peers so `filament ping`/`ssh` is instant.
///
/// Design:
/// - EXPLICIT peers: from `filament set warm-peers dovm,popos` (always connected)
/// - RECENT peers: LRU of last 5 peers used for send/ssh/ping (auto-connected)
/// - RECONNECT: exponential backoff (1s, 2s, 4s, 8s, 16s, 30s cap) on drop
/// - DORMANT: go dormant after 5 failed attempts; resume on peer presence
const WARM_RECENT_CAP: usize = 5;
const WARM_MAX_BACKOFF: Duration = Duration::from_secs(30);
const WARM_DORMANT_THRESHOLD: u32 = 5;
/// A dormant peer is retried this often (instead of never). Presence re-announce
/// still resumes it immediately; this is the floor for a peer whose announces we
/// keep missing.
const WARM_DORMANT_RETRY: Duration = Duration::from_secs(300);

/// Auto-warm size guard: warm at most this many roster peers (see `warm-max`).
/// Must stay under MAX_LINKS (16) so warm-all can never starve on-demand,
/// inbound, or upgrade-probe links of link-table slots.
fn warm_max() -> usize {
    settings::get_str("warm-max", None)
        .and_then(|s| s.trim().parse::<usize>().ok())
        .filter(|n| *n > 0)
        .unwrap_or(12)
        .min(MAX_LINKS - 2)
}

#[derive(Default)]
struct WarmHold {
    /// Explicitly configured peers (from `warm-peers` setting)
    configured: std::collections::HashSet<String>,
    /// AUTO-WARM tier: ALL online paired peers (from the live roster), synced each
    /// warm_hold_tick. ON by default (`auto-warm` setting); also forced on while the
    /// L3 overlay is up (L3 needs live links to route). Bounded by `warm-max`
    /// (Change 4), not by the recent LRU cap.
    auto: std::collections::HashSet<String>,
    /// Recently-used peers in LRU order (most recent at back, capped at 5)
    recent: std::collections::VecDeque<String>,
    /// Per-peer last-use timestamp
    last_use: HashMap<String, Instant>,
    /// Per-peer reconnect backoff state
    backoff: HashMap<String, WarmBackoff>,
}

#[derive(Clone)]
struct WarmBackoff {
    /// Current backoff duration
    duration: Duration,
    /// Number of consecutive failures
    failures: u32,
    /// When we last tried to connect
    last_attempt: Option<Instant>,
    /// True if we've given up (dormant) after too many failures
    dormant: bool,
}

impl Default for WarmBackoff {
    fn default() -> Self {
        Self {
            duration: Duration::from_secs(1),
            failures: 0,
            last_attempt: None,
            dormant: false,
        }
    }
}

impl WarmHold {
    /// Record that a peer was just used (transfer, ssh, ping)
    fn note_use(&mut self, peer: &str) {
        let peer = peer.to_string();
        self.last_use.insert(peer.clone(), Instant::now());
        // Move to back of LRU (most recent)
        self.recent.retain(|p| p != &peer);
        self.recent.push_back(peer.clone());
        // Trim to cap
        while self.recent.len() > WARM_RECENT_CAP {
            self.recent.pop_front();
        }
        // Clear dormant flag and reset backoff on use
        if let Some(b) = self.backoff.get_mut(&peer) {
            b.dormant = false;
            b.failures = 0;
            b.duration = Duration::from_secs(1);
        }
    }

    /// Mark a connection attempt failed (exponential backoff)
    fn note_failure(&mut self, peer: &str) {
        let b = self.backoff.entry(peer.to_string()).or_default();
        b.failures += 1;
        b.last_attempt = Some(Instant::now());
        // Exponential backoff with cap
        b.duration = (b.duration * 2).min(WARM_MAX_BACKOFF);
        // Go dormant after too many failures
        if b.failures >= WARM_DORMANT_THRESHOLD {
            b.dormant = true;
        }
    }

    /// Mark a connection succeeded (reset backoff)
    fn note_success(&mut self, peer: &str) {
        if let Some(b) = self.backoff.get_mut(peer) {
            b.failures = 0;
            b.duration = Duration::from_secs(1);
            b.dormant = false;
        }
    }

    /// Check if a peer should be connected (configured OR auto OR recently used, not dormant)
    fn should_connect(&self, peer: &str) -> bool {
        if self.configured.contains(peer) {
            return true;
        }
        if self.auto.contains(peer) {
            return true;
        }
        if self.recent.contains(&peer.to_string()) {
            // Check if dormant
            if let Some(b) = self.backoff.get(peer) {
                return !b.dormant;
            }
            return true;
        }
        false
    }

    /// Get all peers that should be connected
    fn peers_to_connect(&self) -> Vec<String> {
        let mut peers: Vec<String> = self.configured.iter().cloned().collect();
        // Add auto-warm peers (all online paired peers)
        for p in &self.auto {
            if !peers.contains(p) {
                peers.push(p.clone());
            }
        }
        // Add recent peers (capped at 5, not dormant)
        for p in &self.recent {
            if !peers.contains(p) {
                if let Some(b) = self.backoff.get(p) {
                    if !b.dormant {
                        peers.push(p.clone());
                    }
                } else {
                    peers.push(p.clone());
                }
            }
        }
        peers
    }

    /// Check if a peer is dormant (too many failures)
    fn is_dormant(&self, peer: &str) -> bool {
        self.backoff.get(peer).map(|b| b.dormant).unwrap_or(false)
    }

    /// Is this peer due for a (re)connect attempt this tick? Dormant peers get one
    /// probe per WARM_DORMANT_RETRY; non-dormant peers honor their exponential
    /// backoff window (duration since last_attempt).
    fn due(&self, peer: &str) -> bool {
        match self.backoff.get(peer) {
            None => true,
            Some(b) => {
                let since = b.last_attempt.map(|t| t.elapsed());
                if b.dormant {
                    since.map_or(true, |d| d >= WARM_DORMANT_RETRY)
                } else {
                    since.map_or(true, |d| d >= b.duration)
                }
            }
        }
    }

    /// Resume a dormant peer (e.g., when it reappears in signaling presence)
    fn resume(&mut self, peer: &str) {
        if let Some(b) = self.backoff.get_mut(peer) {
            b.dormant = false;
            b.failures = 0;
            b.duration = Duration::from_secs(1);
        }
    }
}

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

    #[test]
    fn should_connect_configured() {
        let mut wh = WarmHold::default();
        wh.configured.insert("dovm".into());
        assert!(wh.should_connect("dovm"));
        assert!(!wh.should_connect("popos"));
    }

    #[test]
    fn should_connect_l3() {
        let mut wh = WarmHold::default();
        wh.auto.insert("dovm".into());
        assert!(wh.should_connect("dovm"));
        assert!(!wh.should_connect("popos"));
    }

    #[test]
    fn should_connect_recent_not_dormant() {
        let mut wh = WarmHold::default();
        wh.note_use("dovm");
        assert!(wh.should_connect("dovm"));
    }

    #[test]
    fn should_connect_false_for_dormant() {
        let mut wh = WarmHold::default();
        for _ in 0..WARM_DORMANT_THRESHOLD {
            wh.note_failure("dovm");
        }
        assert!(!wh.should_connect("dovm"));
    }

    #[test]
    fn should_connect_false_for_unknown() {
        let wh = WarmHold::default();
        assert!(!wh.should_connect("unknown"));
    }

    #[test]
    fn recent_lru_caps_at_5() {
        let mut wh = WarmHold::default();
        for i in 0..7 {
            wh.note_use(&format!("peer{i}"));
        }
        // Should only have last 5: peer2, peer3, peer4, peer5, peer6
        assert_eq!(wh.recent.len(), WARM_RECENT_CAP);
        assert!(!wh.recent.contains(&"peer0".to_string()));
        assert!(!wh.recent.contains(&"peer1".to_string()));
        assert!(wh.recent.contains(&"peer2".to_string()));
        assert!(wh.recent.contains(&"peer6".to_string()));
    }

    #[test]
    fn recent_evicts_oldest() {
        let mut wh = WarmHold::default();
        wh.note_use("a");
        wh.note_use("b");
        wh.note_use("c");
        wh.note_use("d");
        wh.note_use("e");
        // All 5 present
        assert_eq!(wh.recent.len(), 5);
        // Add 6th - "a" should be evicted
        wh.note_use("f");
        assert_eq!(wh.recent.len(), 5);
        assert!(!wh.recent.contains(&"a".to_string()));
        assert!(wh.recent.contains(&"f".to_string()));
    }

    #[test]
    fn auto_set_is_unbounded() {
        let mut wh = WarmHold::default();
        // Add 10 peers to auto set
        for i in 0..10 {
            wh.auto.insert(format!("peer{i}"));
        }
        // All 10 should be in peers_to_connect
        let peers = wh.peers_to_connect();
        for i in 0..10 {
            assert!(peers.contains(&format!("peer{i}")), "peer{i} missing");
        }
    }

    #[test]
    fn auto_disabled_clears_set() {
        let mut wh = WarmHold::default();
        wh.auto.insert("dovm".into());
        wh.auto.insert("popos".into());
        assert!(wh.should_connect("dovm"));
        // Simulate auto-warm disabled
        wh.auto.clear();
        assert!(!wh.should_connect("dovm"));
        assert!(!wh.should_connect("popos"));
    }

    #[test]
    fn note_failure_backoff_doubling() {
        let mut wh = WarmHold::default();
        wh.note_failure("dovm");
        assert_eq!(wh.backoff["dovm"].duration, Duration::from_secs(2));
        wh.note_failure("dovm");
        assert_eq!(wh.backoff["dovm"].duration, Duration::from_secs(4));
        wh.note_failure("dovm");
        assert_eq!(wh.backoff["dovm"].duration, Duration::from_secs(8));
    }

    #[test]
    fn note_failure_caps_at_30s() {
        let mut wh = WarmHold::default();
        for _ in 0..10 {
            wh.note_failure("dovm");
        }
        assert_eq!(wh.backoff["dovm"].duration, WARM_MAX_BACKOFF);
    }

    #[test]
    fn note_failure_dormant_after_threshold() {
        let mut wh = WarmHold::default();
        for _ in 0..WARM_DORMANT_THRESHOLD {
            wh.note_failure("dovm");
        }
        assert!(wh.backoff["dovm"].dormant);
        assert!(wh.is_dormant("dovm"));
    }

    #[test]
    fn note_use_clears_backoff() {
        let mut wh = WarmHold::default();
        for _ in 0..WARM_DORMANT_THRESHOLD {
            wh.note_failure("dovm");
        }
        assert!(wh.is_dormant("dovm"));
        wh.note_use("dovm");
        assert!(!wh.is_dormant("dovm"));
        assert_eq!(wh.backoff["dovm"].duration, Duration::from_secs(1));
        assert_eq!(wh.backoff["dovm"].failures, 0);
    }

    #[test]
    fn resume_clears_dormant() {
        let mut wh = WarmHold::default();
        for _ in 0..WARM_DORMANT_THRESHOLD {
            wh.note_failure("dovm");
        }
        assert!(wh.is_dormant("dovm"));
        wh.resume("dovm");
        assert!(!wh.is_dormant("dovm"));
    }

    /// CI GUARDRAIL: warm peers should be instantly connectable.
    /// This is a LOGICAL test (no network) - verifies the warm-hold state
    /// machine would allow instant connection for a warm peer.
    #[test]
    fn warm_peer_allows_instant_connection() {
        let mut wh = WarmHold::default();
        // Simulate a warm peer (configured + auto)
        wh.configured.insert("dovm".into());
        wh.auto.insert("dovm".into());
        wh.note_use("dovm");
        // All paths should return true
        assert!(wh.should_connect("dovm"));
        assert!(!wh.is_dormant("dovm"));
        // Peer is in warm sets
        assert!(wh.configured.contains("dovm"));
        assert!(wh.auto.contains("dovm"));
    }

    #[test]
    fn due_respects_backoff_window() {
        let mut wh = WarmHold::default();
        // No backoff entry -> always due
        assert!(wh.due("unknown"));
        // After one failure, not due until backoff window passes
        wh.note_failure("dovm");
        assert!(!wh.due("dovm")); // 1s window, just failed
    }

    #[test]
    fn dormant_peer_retries_after_interval() {
        let mut wh = WarmHold::default();
        // Make peer dormant
        for _ in 0..WARM_DORMANT_THRESHOLD {
            wh.note_failure("dovm");
        }
        assert!(wh.is_dormant("dovm"));
        // Not due immediately
        assert!(!wh.due("dovm"));
        // After WARM_DORMANT_RETRY, would be due (can't easily test Instant::elapsed
        // without injecting time, so just verify the dormant flag is set)
        assert!(wh.backoff["dovm"].dormant);
    }
}

struct Conn {
    server: String,
    sio: rust_socketio::asynchronous::Client,
    tx: mpsc::UnboundedSender<Ev>,
    my_uid: String,
    my_id: String,
    relay_only: bool,
    to_filter: Option<String>,
    links: HashMap<String, Link>,
    roster: HashMap<String, Value>, // sid -> {id,name,uid} from welcome/peer-joined
    active: Option<String>,        // the transfer-target sid (send side)
    next_gen: u32,
    /// Peer-absence / rejoin-grace state (the reconnect window + declared brb).
    rejoin: RejoinState,
    chunk_size: usize,
    /// #28 (deferred drop): sids that got a peer-left while their data channel
    /// was still FLOWING. The signaling socket left the room, but the WebRTC
    /// link is independent and may be a cosmetic reconnect mid-transfer. We do
    /// NOT drop immediately (that kills a live transfer) and do NOT drop never
    /// (a hard-killed peer reads flowing for a beat and would strand the
    /// sender). Instead we stash the original peer-left payload here and
    /// re-check on every main-loop tick: once the link goes idle past the
    /// flowing threshold (or its channel is dead), we re-inject the stored
    /// peer-left so the normal handler runs verbatim, now dropping it. A live
    /// reconnect never goes idle (the transfer completes on it), so its entry
    /// is reaped harmlessly once done. Cleared in drop_link so a supersede of a
    /// deferred sid can't leave a stale blocker.
    deferred_left: HashMap<String, Value>,
    /// Gate-18 Mode B: set TRUE by the recv loop, each tick, exactly when the
    /// transfer is COMPLETE and nothing is in flight (`completed>0 &&
    /// by_sid.is_empty() && !keep_open`). When it holds, `on_stuck` DROPS a
    /// stuck/lost link instead of re-establishing it: there is nothing left to
    /// fetch, so reconnect attempts are pointless and a sender that departs
    /// AFTER delivering every byte would otherwise FLAP the link forever
    /// (establish → connect → die → Stuck → establish ...), each cycle resetting
    /// `attempts` (so MAX_ATTEMPTS never caps it) and re-arming `expected_secret`
    /// (so `digest_says_alone` never holds), `conn.links` never empties and the
    /// quiet-exit never fires → RC=124 hang. Dropping the link empties
    /// `conn.links` and lets the quiet-exit fire. Recomputed PER TICK (never
    /// sticky) so a mid-transfer link (`by_sid` non-empty) always reconnects
    /// normally, kill-resume (gate 2) and the #28 deferred-drop (gate 11c)
    /// reconnect paths are untouched. Defaults false, so the send-side and
    /// connecting-phase `on_stuck` callers are unaffected.
    recv_done: bool,
    /// rung-1 (FILAMENT_DIRECT): in-flight direct-QUIC attempts, keyed by peer
    /// sid. While an attempt is pending we do NOT establish WebRTC for that peer
    /// (sequential, per the design review, avoids two transports racing to
    /// ChannelReady). On deadline expiry with no DirectReady the entry is
    /// dropped and the normal WebRTC `establish` runs; the fallback is unchanged.
    direct_pending: HashMap<String, DirectPending>,
    /// RESILIENCE bookkeeping (stall/relay/warm/upgrade); see ResilienceState.
    resil: ResilienceState,
    /// Is the rung-1 direct-QUIC path allowed for THIS session? Normally this is
    /// just `direct::direct_enabled()` (the FILAMENT_DIRECT/FILAMENT_L2 env gate),
    /// but ANY long-lived acceptor must ALSO take it even when those env vars are
    /// unset: the L2/ssh ACCEPTOR (`up --shell`) AND the plain `up` daemon. An
    /// acceptor that doesn't silently drops the initiator's `transport-offer` AND
    /// builds its own WebRTC peer dialing back, colliding with the initiator's
    /// offer (GLARE), which for `up --shell` stalls at "stuck while connecting" and
    /// for a plain `up` (two mutually-known daemons) loops the supersede churn and
    /// never settles to one link. Answering the direct dial instead is sequential,
    /// authenticated, and rides the reachable host candidate (e.g. the Tailscale
    /// link), so it neither glares nor depends on cross-NAT ICE. Set via
    /// `direct_ok_for`; `start_direct_inner` gates on this instead of the bare env
    /// check. One-shot send/recv/pair keep the bare `direct_enabled()` default.
    direct_ok: bool,
    /// Local transport for same-machine peers.
    local_port: Option<u16>,
    local_listener: Option<Arc<tokio::net::TcpListener>>,
    /// Shared direct-QUIC endpoint, cloned from the originating Endpoint so that
    /// worker connections for multi-stream transfers can be dialled (sender side)
    /// or accepted (receiver side) without racing the winner's keepalive closure.
    /// Set once in `start_direct_inner`; `None` when direct is not in use, or
    /// when multi-streaming is disabled (`direct_streams() == 1`).
    direct_endpoint: Option<quinn::Endpoint>,
    /// WARM-HOLD: keeps connections alive to recently-used and explicitly
    /// configured peers so `filament ping`/`ssh` is instant. Tracked per-peer
    /// with LRU eviction and exponential backoff on failures.
    warm_hold: WarmHold,
    /// Oneshot senders for per-endpoint worker port negotiation, keyed by pid.
    /// The dialer-side `spawn_direct_workers` stores a sender here; the
    /// `worker-ports` control message handler delivers the acceptor's port list
    /// through it. Removed by the receiver on delivery (one-shot).
    worker_port_tx: HashMap<String, oneshot::Sender<Vec<u16>>>,
}

/// P0: one peer's stall-repair episode state.
#[derive(Default)]
struct StallState {
    /// Repairs attempted in the current episode (rung a is the first).
    attempts: u32,
    /// `true` between firing the ladder and the next observed byte of progress,
    /// so the per-tick watchdog doesn't re-arm while a repair is converging.
    pending: bool,
    /// P1 (GAP-4): `true` once this episode escalated to relay (rung d) and a
    /// FRESH relay WebRTC link is establishing (no transport yet). The new link
    /// isn't tracked by `direct_pending`, so without this latch `detect_stall`
    /// would keep seeing the (transport-less) link idle and re-fire the ladder
    /// into a premature `Exhausted` before relay even connects. Cleared by
    /// `note_progress` on the first byte over the relay path.
    relayed: bool,
}

/// P5 (GAP-6): one peer's relay->direct UPGRADE-PROBE state. Lifecycle:
///   IDLE  : armed (relay-committed); `next_at` is when the next probe fires,
///            `attempt` drives the exponential backoff (first_ms → steady_ms).
///   PROBING: a direct dial is in flight (a `DirectPending{probe:true}` exists);
///            we don't re-fire until it resolves (win → VERIFYING, or expiry →
///            back to IDLE with a longer backoff).
///   VERIFYING: a direct standby CONNECTED (`standby` set). It must move data
///            CONTINUOUSLY for `verify_ms` before we cut over; `verify_started`
///            marks when it connected. If it goes idle past `verify_idle_ms` or
///            never reaches `verify_ms` of sustained progress, it is DISCARDED
///            and we go back to IDLE (stay on relay, the no-flap guard).
struct UpgradeProbe {
    /// failed-probe count; each failure backs the cadence off toward steady_ms.
    attempt: u32,
    /// when the next probe may fire (None ⇒ probe ASAP, e.g. just armed or a
    /// network-change re-probe).
    next_at: Option<Instant>,
    /// the connected-but-unverified direct standby transport (VERIFYING state).
    standby: Option<Arc<dyn Transport>>,
    /// the route label of the standby (`direct-quic` / `holepunched`).
    standby_route: &'static str,
    /// when the standby connected, the start of the verify window.
    verify_started: Option<Instant>,
    /// the standby's `idle_ms()` floor observed so far in the verify window, used
    /// to require SUSTAINED progress (it must keep moving, not just connect).
    verify_last_idle: u64,
}

impl UpgradeProbe {
    fn armed() -> Self {
        UpgradeProbe {
            attempt: 0,
            next_at: None, // first probe is scheduled by the prober tick
            standby: None,
            standby_route: "direct-quic",
            verify_started: None,
            verify_last_idle: u64::MAX,
        }
    }
}

/// P0: which correction rung the stall ladder took (see `Conn::correct_stall`).
#[derive(Debug, PartialEq)]
enum Rung {
    /// (a) re-offer unfinished transfers on the SAME transport (resume:true).
    Resume,
    /// (c) the transport was repaired in place (fresh direct dial / ICE-restart).
    Repaired,
    /// (d) P1: direct rungs a→c spent → the link was RE-ESTABLISHED over the TURN
    /// relay (relay-only ICE), preserving the on-disk partial. The fresh relay
    /// transport's ChannelReady re-offers the unfinished transfers (resume:true)
    /// and prints the honest relay banner.
    Relayed,
    /// rungs a→d unavailable: direct rungs spent AND relay is forbidden
    /// (`--no-relay`) or we were already on relay. The caller FAILS CLEANLY, a
    /// kept partial, a clear error, never a hang.
    Exhausted,
}

/// rung-1: state for one in-flight direct-QUIC attempt.
struct DirectPending {
    /// (name, secret) for the known device, gates the attempt and keys the MAC.
    secret: (String, String),
    /// budget deadline; on expiry with no DirectReady we fall back to WebRTC.
    deadline: Instant,
    /// set once the peer's transport-offer arrived and we spawned the racer, so
    /// a duplicate offer doesn't spawn a second race.
    racing: bool,
    /// kept alive so the bound UDP port stays ours until the race consumes it.
    endpoint: Option<quinn::Endpoint>,
    /// rung-2 (FILAMENT_HOLEPUNCH): a SECOND raw UDP socket, already STUN'd, kept
    /// raw (not connected) so its NAT mapping is the one we punch + run QUIC on.
    /// Consumed by the chained ladder in `on_transport_offer` only if rung-1
    /// fails. None when hole-punch is off or STUN discovery failed.
    punch_sock: Option<std::net::UdpSocket>,
    /// rung-2: our advertised srflx (logged at offer time; kept for diagnostics).
    #[allow(dead_code)]
    my_srflx: Option<std::net::SocketAddr>,
    /// P5 (GAP-6): this is a relay->direct UPGRADE probe, a direct dial run
    /// ALONGSIDE a live relay link (not the cold establishment path). When the
    /// race wins, `on_transport_offer` posts `Ev::DirectUpgradeReady` (verify-
    /// before-upgrade) instead of `Ev::DirectReady` (which would clobber the
    /// serving relay link). When the budget expires with no winner, `expired_direct`
    /// just DROPS the pending (no WebRTC fallback, the relay link is still serving)
    /// and the prober schedules the next backoff.
    probe: bool,
}

impl Conn {
    /// Single constructor for the `pair`/`send`/`recv` command event loops, which
    /// built the identical ~17-field `Conn` literal three times (the only
    /// per-command differences are `relay_only`, `to_filter`, and the
    /// warm-standby default). Everything else is the fixed fresh-session state.
    /// `warm_standby_default` is the per-session-kind default that the
    /// `FILAMENT_WARM_STANDBY` override (via `net::warm_standby_override`) can
    /// still force either way. NOTE: the long-lived `up` daemon loop keeps its
    /// own literal on purpose, it is a different (non-command) session.
    fn for_command(
        server: &str,
        sio: rust_socketio::asynchronous::Client,
        tx: mpsc::UnboundedSender<Ev>,
        my_uid: String,
        relay_only: bool,
        to_filter: Option<String>,
        warm_standby_default: bool,
        direct_ok: bool,
    ) -> Self {
        Conn {
            server: server.to_string(),
            sio,
            tx,
            my_uid,
            my_id: String::new(),
            relay_only,
            to_filter,
            links: HashMap::new(),
            roster: HashMap::new(),
            active: None,
            next_gen: 0,
            rejoin: RejoinState { waiting_rejoin: None, rejoin_window: REJOIN_WINDOW, away: None },
            chunk_size: net::MAX_DC_PAYLOAD,
            deferred_left: HashMap::new(),
            recv_done: false,
            direct_pending: HashMap::new(),
            resil: ResilienceState {
                stall_repairs: HashMap::new(),
                relay_committed: std::collections::HashSet::new(),
                warm_standby: net::warm_standby_override().unwrap_or(warm_standby_default),
                warm_cutover: std::collections::HashSet::new(),
                upgrade_probe: HashMap::new(),
                iface_snapshot: Vec::new(),
            },
            direct_ok,
            local_port: None,
            local_listener: None,
            direct_endpoint: None,
            warm_hold: WarmHold::default(),
            worker_port_tx: HashMap::new(),
        }
    }

    fn link(&self, pid: &str) -> Option<&Link> {
        self.links.get(pid)
    }
    fn link_mut(&mut self, pid: &str) -> Option<&mut Link> {
        self.links.get_mut(pid)
    }
    fn active_link(&self) -> Option<&Link> {
        self.active.as_ref().and_then(|a| self.links.get(a))
    }
    fn is_active(&self, pid: &str) -> bool {
        self.active.as_deref() == Some(pid)
    }
    fn transport(&self) -> Option<Arc<dyn Transport>> {
        self.active_link().and_then(|l| l.transport.clone())
    }
    fn transport_of(&self, pid: &str) -> Option<Arc<dyn Transport>> {
        self.links.get(pid).and_then(|l| l.transport.clone())
    }

    /// Whether this link has ANY live transport (primary or workers) that can
    /// actually carry bytes. False when the link entry exists but all transports
    /// are dead — the "corpse" state the liveness guard must purge.
    fn has_live_transport(&self, pid: &str) -> bool {
        self.links.get(pid)
            .map(|l| {
                let primary_ok = l.transport.as_ref().map(|t| !t.is_dead()).unwrap_or(false);
                let workers_ok = l.workers.iter().any(|w| !w.is_dead());
                primary_ok || workers_ok
            })
            .unwrap_or(false)
    }

    /// #28: is the link keyed by `pid` actively moving transfer bytes right now?
    /// The data channel is independent of the signaling socket, so when a
    /// same-uid reconnect arrives as a new sid, superseding must NOT tear down
    /// an old link that's still flowing. A frozen-alive peer (gate 11's
    /// SIGSTOP'd receiver) stops stamping activity, so it reads as not-flowing
    /// and the supersede proceeds as before. Threshold is overridable for
    /// deterministic gating (FILAMENT_ADOPT_ACTIVE_MS); the 3 s default sits
    /// well above a healthy sub-100 ms inter-frame gap so a transient ICE blip
    /// can't masquerade as idle and let a spurious supersede through.
    fn link_flowing(&self, pid: &str) -> bool {
        let threshold = std::env::var("FILAMENT_ADOPT_ACTIVE_MS")
            .ok()
            .and_then(|v| v.parse::<u64>().ok())
            .unwrap_or(3000);
        self.transport_of(pid)
            .map(|t| t.idle_ms() < threshold)
            .unwrap_or(false)
    }

    /// May this peer become the TRANSFER TARGET? (Filters gate targeting,
    /// never answering, every peer still gets a polite link.)
    fn targetable(&self, name: &str, peer_uid: Option<&str>) -> bool {
        if let Some(filter) = &self.to_filter {
            if !name.to_lowercase().contains(&filter.to_lowercase()) {
                return false;
            }
        }
        // Same-role CLI peers never transfer to each other (gate 7).
        if let (Some(pu), Some(my_role)) = (peer_uid, self.my_uid.get(..6)) {
            if pu.starts_with(my_role) {
                return false;
            }
        }
        true
    }

    /// Track a roster entry and (re)connect to it. `want_active` marks it as
    /// the intended transfer target if it passes the target filters and no
    /// target exists yet. Returns true if this peer is (now) the active one.
    async fn maybe_adopt(&mut self, v: &Value, want_active: bool) -> Result<bool> {
        let peer_id = v["id"].as_str().unwrap_or_default().to_string();
        let peer_uid = v["uid"].as_str().map(|s| s.to_string());
        let name = v["name"].as_str().unwrap_or("peer").to_string();
        if peer_id.is_empty() || peer_id == self.my_id {
            return Ok(false);
        }
        // NOTE: same-install peers (our own daemon) are filtered at the
        // KnownPeer call sites, NOT here, room discovery must keep working
        // between two processes of one machine (loopback self-send is the
        // first thing every new user tries).
        self.roster.insert(peer_id.clone(), v.clone());

        // C6: same device on a NEW sid, supersede the stale link.
        let stale: Option<String> = self
            .links
            .iter()
            .find(|(sid, l)| l.uid.is_some() && l.uid == peer_uid && **sid != peer_id)
            .map(|(sid, _)| sid.clone());
        if let Some(old_sid) = stale {
            // #28: the same device reconnected its signaling socket (fresh sid).
            // If its existing data channel is still flowing, the reconnect is
            // cosmetic, superseding would tear down an active transfer. Keep the
            // old link; once it goes idle a later roster/presence event supersedes.
            if self.link_flowing(&old_sid) {
                // Observable so a gate can assert the keep happened (true
                // positive), not merely that no supersede line appeared.
                ui::debug(&format!("{name} reconnected, keeping active link"));
                return Ok(self.is_active(&old_sid));
            }
            ui::debug(&format!("{name} reconnected, superseding old link"));
            let was_active = self.is_active(&old_sid);
            let secret = self.links.get(&old_sid).and_then(|l| l.expected_secret.clone());
            self.drop_link(&old_sid);
            self.establish(v.clone()).await?;
            if let Some(l) = self.links.get_mut(&peer_id) {
                l.expected_secret = secret;
            }
            if was_active {
                self.active = Some(peer_id.clone());
            }
            return Ok(self.is_active(&peer_id));
        }

        if !self.links.contains_key(&peer_id) {
            if self.links.len() >= MAX_LINKS {
                return Ok(false);
            }
            self.establish(v.clone()).await?;
        }
        // #28: a deferred-active slot is claimable. When the active link got a
        // peer-left but is still flowing, we keep `active` pointing at it (so a
        // same-uid reconnect's supersede still sees it active, and the live
        // transfer's offer/exit machinery is undisturbed). But a DIFFERENT-uid
        // replacement (gate 2: hard-killed receiver, fresh recv) must still be
        // able to take over, otherwise the deferred link squats the slot until
        // the reap, and the replacement (whose ChannelReady already fired) never
        // gets promoted or offered the file. Treating a deferred active as
        // "claimable" promotes the replacement at peer-joined, before its
        // ChannelReady, so the offer goes out on the same baseline path.
        let active_deferred = self
            .active
            .as_ref()
            .is_some_and(|a| self.deferred_left.contains_key(a));
        if want_active && (self.active.is_none() || active_deferred) && self.targetable(&name, peer_uid.as_deref()) {
            // Claiming the slot from a deferred link: discharge that link now
            // (it left the room and is being replaced) so reap doesn't later
            // re-inject a stale peer-left against the slot the new peer holds.
            if active_deferred {
                if let Some(old) = self.active.clone() {
                    if old != peer_id {
                        self.drop_link(&old);
                    }
                }
            }
            self.active = Some(peer_id.clone());
            self.rejoin.waiting_rejoin = None;
        }
        Ok(self.is_active(&peer_id))
    }

    fn drop_link(&mut self, pid: &str) {
        // #28: dropping a link also discharges any deferred peer-left for it,
        // so a supersede (maybe_adopt) of a deferred same-uid sid can't leave a
        // stale entry blocking adoption. Invariant: deferred_left only ever
        // holds sids that are still live links.
        self.deferred_left.remove(pid);
        if let Some(old) = self.links.remove(pid) {
            // Never await close in the event loop (F8): mark + spawn. A direct
            // link has no WebRTC peer; dropping the Link drops its QUIC transport
            // (the keepalive task observes conn.closed() and tears down).
            if let Some(p) = old.peer.clone() {
                p.mark_closed();
                tokio::spawn(async move { p.close().await });
            }
        }
        if self.is_active(pid) {
            self.active = None;
        }
    }

    // --- WARM-HOLD: proactive connection management ---

    /// Record that a peer was just used (transfer, ssh, ping). This updates the
    /// LRU and marks the peer as warm so the daemon proactively connects/reconnects.
    fn note_warm_use(&mut self, peer: &str) {
        self.warm_hold.note_use(peer);
    }

    /// Load configured warm-peers from settings. Called at daemon startup and
    /// at the top of each warm_hold_tick to stay in sync with runtime changes.
    fn load_warm_peers_config(&mut self) {
        if let Some(setting) = settings::get_str("warm-peers", None) {
            self.warm_hold.configured.clear();
            for p in setting.split(',') {
                let p = p.trim().to_string();
                if !p.is_empty() {
                    self.warm_hold.configured.insert(p);
                }
            }
        }
    }

    /// Check for warm peers that need connections and establish them.
    /// Called periodically from the daemon event loop. Returns the list of
    /// peers we attempted to connect to.
    ///
    /// `auto_warm`: sync the auto tier (ALL online paired peers) from the roster.
    /// Default ON (`auto-warm` setting); forced on while L3 is up. When off, the
    /// auto tier is cleared and only configured + recent peers stay warm.
    async fn warm_hold_tick(&mut self, auto_warm: bool) -> Vec<String> {
        // Reload configured peers from settings to stay in sync
        self.load_warm_peers_config();
        if auto_warm {
            let mut online: Vec<(String, Option<Instant>)> = self.roster.values()
                .filter_map(|v| v["name"].as_str())
                .map(|s| (s.to_string(), self.warm_hold.last_use.get(s).copied()))
                .collect();
            // Change 4 size guard: over warm-max, keep the most recently USED peers
            // warm (never-used peers rank last; name tie-break keeps it deterministic).
            let cap = warm_max();
            if online.len() > cap {
                online.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
                online.truncate(cap);
            }
            let current: std::collections::HashSet<String> =
                online.into_iter().map(|(n, _)| n).collect();
            for name in &current {
                if !self.warm_hold.auto.contains(name) {
                    self.warm_hold.auto.insert(name.clone());
                    ui::debug(&format!("warm-hold: auto-warming peer '{name}'"));
                }
            }
            // Drop peers that went offline (or fell over the warm-max recency cut)
            self.warm_hold.auto.retain(|name| current.contains(name));
        } else {
            if !self.warm_hold.auto.is_empty() {
                ui::debug("warm-hold: auto-warm off, clearing auto tier");
                self.warm_hold.auto.clear();
            }
        }
        let mut connected = Vec::new();
        let peers = self.warm_hold.peers_to_connect();
        for peer in peers {
            // Skip re-establish if a link to this pid exists AND is alive AND
            // (verified OR within the pair-proof grace window).  Dead links and
            // alive-but-unverified-past-grace (stuck) links still re-establish.
            // The grace prevents churn during the normal pair-proof verification
            // window while ensuring stuck links are eventually replaced.
            const WARM_PAIR_PROOF_GRACE: std::time::Duration = std::time::Duration::from_secs(30);
            let skip = self.links.iter().any(|(_, l)| {
                // Match by name (peers_to_connect returns names, not IDs)
                l.name.eq_ignore_ascii_case(&peer)
                    // Link is alive: transport alive, OR WebRTC peer exists, OR direct link exists
                    && (l.transport.as_ref().map(|t| t.is_alive()).unwrap_or(false)
                        || l.peer.is_some()
                        || l.direct)
                    && (
                        l.verified_name.is_some()                    // verified: warm-usable, skip
                        || l.established_at                          // within grace: pair-proof expected
                            .map(|t| t.elapsed() < WARM_PAIR_PROOF_GRACE)
                            .unwrap_or(false)
                    )
            });
            if skip {
                ui::debug(&format!("warm-hold: skip '{peer}' (link alive, within grace)"));
                continue;
            } else {
                ui::debug(&format!("warm-hold: will establish '{peer}' (no alive link found)"));
            }
            // Honor per-peer backoff; a dormant peer still gets one probe per
            // WARM_DORMANT_RETRY so an online-but-unlucky peer cannot stay cold forever.
            if !self.warm_hold.due(&peer) {
                continue;
            }
            // Find peer info from roster
            if let Some(info) = self.roster.values().find(|v| {
                v["name"].as_str().map(|n| n.eq_ignore_ascii_case(&peer)).unwrap_or(false)
                    || v["id"].as_str().map(|id| id.eq_ignore_ascii_case(&peer)).unwrap_or(false)
            }) {
                let info = info.clone();
                let _peer_id = info["id"].as_str().unwrap_or_default().to_string();
                // Try to establish connection
                match self.establish(info).await {
                    Ok(()) => {
                        self.warm_hold.note_success(&peer);
                        ui::debug(&format!("warm-hold: established connection to '{peer}'"));
                        connected.push(peer);
                    }
                    Err(e) => {
                        self.warm_hold.note_failure(&peer);
                        ui::debug(&format!("warm-hold: failed to connect to '{peer}': {e}"));
                    }
                }
            }
        }
        connected
    }

    /// Resume a dormant warm peer (e.g., when it reappears in signaling presence)
    fn resume_warm_peer(&mut self, peer: &str) {
        self.warm_hold.resume(peer);
    }

    async fn establish(&mut self, info: Value) -> Result<()> {
        self.establish_as(info, None).await
    }

    /// `force_polite: Some(true)` builds a pure responder link (no local offer)
    /// regardless of uid comparison, required when the link exists to ANSWER
    /// an incoming offer (ensure_responder / glare rebuild). The uid-based role
    /// can come out impolite there (especially on the bare `{id}` roster-miss
    /// fallback, which compares sids), making the "responder" offer too: glare.
    async fn establish_as(&mut self, info: Value, force_polite: Option<bool>) -> Result<()> {
        let peer_id = info["id"].as_str().unwrap_or_default().to_string();
        // rung-1: a direct-QUIC attempt owns this peer until its budget expires.
        // Suppress the WebRTC offer so the path stays SEQUENTIAL (no two
        // transports racing to ChannelReady). `expired_direct` removes the
        // pending before calling us for the fallback, so this never blocks it.
        if self.direct_pending.contains_key(&peer_id) {
            return Ok(());
        }
        // P1 (GAP-4): once a peer is committed to relay, a live link already
        // carries (or is converging on) the relay route. Re-establish events
        // (KnownPeer re-announce, expired_direct fallback, a watchdog tick) must
        // NOT tear it down and rebuild mid-handshake, that thrash is exactly why
        // the relay link got "stuck while connecting". A genuinely failed link is
        // removed by the normal drop path (on_pc_state/GraceExpired) FIRST, so when
        // no link is present here we DO proceed to (re)build the relay link.
        if self.resil.relay_committed.contains(&peer_id) && self.links.contains_key(&peer_id) {
            return Ok(());
        }
        self.drop_link(&peer_id); // re-establish replaces any same-sid link
        let peer_uid = info["uid"].as_str().map(|s| s.to_string());
        let name = info["name"].as_str().unwrap_or("peer").to_string();
        // C5: fresh ICE config (TURN creds are expiry-stamped HMACs) for
        // every attempt, not just the first.
        let mut cfg = net::fetch_config(&self.server).await?;
        self.chunk_size = cfg.chunk_size;
        let polite = force_polite.unwrap_or_else(|| {
            net::polite_role(&self.my_uid, peer_uid.as_deref(), &self.my_id, &peer_id)
        });
        self.next_gen += 1;
        let generation = self.next_gen;
        // P1 relay-fallback gate (test-only): FILAMENT_TEST_WEBRTC_RELAY_ONLY=1
        // models a peer with NO direct WebRTC path (hard NAT), every WebRTC link
        // is relay-only, so when the direct-QUIC ladder freezes/exhausts the
        // transfer can ONLY complete over the TURN relay. Faithful to the real
        // "direct can't, relay can" condition the auto-fallback exists for; never a
        // product knob. OR'd with the real relay_only (set by --relay or by an
        // auto escalate_to_relay).
        let relay_ice = self.relay_only || test_hooks::webrtc_relay_only();
        // P1 (GAP-4): --no-relay is a HARD direct-only promise, never traverse a
        // relay. Strip TURN servers from the ICE config so no relay candidate can
        // ever be gathered. A peer reachable ONLY via relay then simply fails to
        // connect, honestly, by the user's own choice, instead of silently using
        // a middleman. (The ICE policy is left as-is: a relay-only policy with no
        // relay servers has no candidates and fails cleanly, which is the point.)
        if relay_forbidden() {
            cfg.ice_servers.retain(|s| net::is_stun_only(s));
        }
        let peer = Peer::connect(
            peer_id.clone(),
            polite,
            cfg.ice_servers,
            relay_ice,
            self.sio.clone(),
            self.tx.clone(),
            generation,
        )
        .await?;
        self.links.insert(
            peer_id,
            Link {
                peer: Some(peer),
                info,
                name,
                uid: peer_uid,
                transport: None,
                workers: vec![],
                generation,
                attempts: 0,
                trusted: false,
                expected_secret: None,
                verified_name: None,
                presence: Presence::Connecting,
                direct: false,
                direct_route: "direct-quic", // unused for WebRTC links (peer.is_some())
                established_at: Some(Instant::now()),
            },
        );
        Ok(())
    }

    // --- rung-1 direct-QUIC path (FILAMENT_DIRECT) ---------------------------
    //
    // Sequential by design: when both peers are CLIs and a pair secret is known,
    // try a direct authenticated QUIC connection FIRST and only fall back to the
    // WebRTC `establish` above if no authenticated connection lands within the
    // budget. The whole thing is gated on `direct::direct_enabled()`, so with the
    // flag OFF none of this runs and the WebRTC path is byte-for-byte unchanged.

    /// Begin a direct attempt against `pid`: bind a quinn endpoint, advertise our
    /// candidates via a relayed `transport-offer`, and stash the pending state.
    /// No Link is created yet, it is born (with `peer: None`, pre-trusted) only
    /// when an authenticated connection wins (Ev::DirectReady). Idempotent per
    /// peer (a second call while pending is a no-op). The peer's own
    /// transport-offer (Ev::TransportOffer) drives the race.
    async fn start_direct(&mut self, pid: &str, name: &str, secret: &str) {
        self.start_direct_inner(pid, name, secret, false).await
    }

    /// P5 (GAP-6): arm a relay->direct UPGRADE probe, a direct dial run
    /// ALONGSIDE the live relay link. Bypasses the `relay_committed` /
    /// already-linked early-returns of `start_direct` (the whole POINT is to dial
    /// direct while a relay link serves), and marks the `DirectPending` as a
    /// probe so the winner posts `Ev::DirectUpgradeReady` (verify-before-upgrade)
    /// rather than clobbering the serving relay link. A no-op if a probe is
    /// already in flight for this peer.
    async fn start_upgrade_probe(&mut self, pid: &str, name: &str, secret: &str) {
        // A probe already in flight (its own DirectPending), don't double-dial.
        if self.direct_pending.contains_key(pid) {
            return;
        }
        self.start_direct_inner(pid, name, secret, true).await
    }

    /// Ensure we have a TCP listener for local connections.
    async fn ensure_local_listener(&mut self) -> u16 {
        if let Some(p) = self.local_port {
            return p;
        }
        let (listener, port) = crate::local::listen_local().await.unwrap();
        self.local_listener = Some(Arc::new(listener));
        self.local_port = Some(port);
        port
    }

    async fn start_direct_inner(&mut self, pid: &str, name: &str, secret: &str, probe: bool) {
        // Gate on the per-session flag, not the bare env check: the L2/ssh
        // acceptor (`up --shell`) sets `direct_ok` true even with the env unset,
        // so it answers the initiator's transport-offer (rung-1 direct-QUIC over
        // the reachable host candidate) instead of building a colliding WebRTC
        // peer that glares with the initiator's offer.
        if !self.direct_ok {
            return;
        }
        if !probe && self.resil.relay_committed.contains(pid) {
            // P1: this peer escalated to relay, never re-dial direct (it would
            // only re-freeze and race the relay link). If a link already exists
            // (the relay link that escalate_to_relay built, possibly still
            // converging), DON'T rebuild it, repeated KnownPeer/`appeared` events
            // would otherwise tear it down and re-establish mid-handshake, so it
            // never connects ("stuck while connecting"). Only (re)establish over
            // relay when there is no link at all to carry the session.
            // P5 (GAP-6): a `probe` deliberately bypasses this guard, it dials
            // direct ALONGSIDE the serving relay link (warm direct standby) and
            // never touches `links`, so it cannot disturb the relay path.
            if !self.links.contains_key(pid) {
                let info = json!({ "id": pid, "name": name });
                let _ = self.establish(info).await;
            }
            return;
        }
        // A probe expects a relay link to be present (it's the one we'd upgrade
        // AWAY from); only the cold path bails when a link already exists.
        let link_dead = self.links.get(pid)
            .map(|l| l.transport.as_ref().map(|t| t.is_dead()).unwrap_or(true) && l.workers.iter().all(|w| w.is_dead()))
            .unwrap_or(false);
        if link_dead {
            self.direct_pending.remove(pid);
            self.drop_link(pid);
        }
        let link_alive = self.has_live_transport(pid);
        if self.direct_pending.contains_key(pid) || (!probe && link_alive) {
            return; // already trying, or already linked via a live transport
        }

        // Check if target is same-machine peer (local transport).
        let peer_uid = self.roster.get(pid).and_then(|info| info["uid"].as_str());
        let is_local = is_self_uid(&self.my_uid, peer_uid);

        let (ep, port) = if is_local {
            // For local peers, we don't need a QUIC endpoint.
            (None, 0u16)
        } else {
            match direct::bind_endpoint() {
                Ok(v) => {
                    // Clone for multi-stream worker connections before the
                    // original is consumed by the race in on_transport_offer.
                    if net::direct_streams() > 1 {
                        self.direct_endpoint = Some(v.0.clone());
                    }
                    (Some(v.0), v.1)
                }
                Err(e) => {
                    ui::trace(&format!("filament: direct disabled (endpoint bind failed: {e})"));
                    return;
                }
            }
        };
        // #1 (parallelism): gather the host/public candidates (incl. the
        // /api/whoami HTTP) and the rung-2 STUN srflx CONCURRENTLY. Both are
        // independent network round-trips that must finish before the
        // transport-offer can go out, and the initiator's "establishing" phase
        // waits on exactly that offer, so overlapping them shaves a round-trip off
        // every cold connect. Both borrow &self immutably, so join! is sound.
        //
        // rung-2 (FILAMENT_HOLEPUNCH): bind a SECOND raw socket and STUN it so we
        // can advertise a server-reflexive candidate. This socket is kept RAW
        // (not handed to quinn), its NAT mapping is the one we'll punch + run
        // QUIC on if rung-1's host-candidate race fails. STUN failure is graceful:
        // no srflx is advertised and rung-2 simply won't fire for this peer.

        let (cands, srflx) = if is_local {
            // For local peers, ensure we have a listener and return TCP candidate.
            if self.local_port.is_none() {
                let (listener, port) = crate::local::listen_local().await.unwrap();
                self.local_listener = Some(Arc::new(listener));
                self.local_port = Some(port);
            }
            let cands = vec![format!("{{\"type\":\"tcp-localhost\",\"port\":{}}}", self.local_port.unwrap())];
            (cands, None)
        } else {
            let srflx_fut = async {
                if holepunch::holepunch_enabled() {
                    self.gather_srflx().await
                } else {
                    None
                }
            };
            tokio::join!(direct::gather_candidates(&self.server, port), srflx_fut)
        };

        let (punch_sock, my_srflx) = match srflx {
            Some((sock, srflx)) => (Some(sock), Some(srflx)),
            None => (None, None),
        };

        // transport-offer rides the OPAQUE signaling relay (same channel as ICE
        // signals); the server cannot read or forge it without failing the MAC.
        let mut offer = json!({ "type": "transport-offer", "v": 1, "addrs": cands });
        if let Some(s) = my_srflx {
            offer["srflx"] = json!(s.to_string());
        }
        // P5 (GAP-6): tag a probe offer so the PEER races it as an upgrade probe
        // too, its winning side then posts Ev::DirectUpgradeReady (verify-before-
        // upgrade) instead of clobbering ITS serving relay link. Both ends must
        // treat the new direct path as a standby until verified, or one end would
        // tear down its relay link unilaterally.
        if probe {
            offer["probe"] = json!(true);
        }
        let _ = self
            .sio
            .emit("signal", json!({ "to": pid, "data": offer.clone() }))
            .await;
        // TRACE, direct-offer / signaling detail.
        ui::trace(&format!(
            "filament: {} sent to {name} ({pid}), port {} srflx {}",
            if probe { "UPGRADE-PROBE-OFFER" } else { "DIRECT-OFFER" },
            port,
            my_srflx.map(|s| s.to_string()).unwrap_or_else(|| "-".into())
        ));
        // Re-send the offer periodically. The L2 initiator (netcat/ssh) subscribes
        // to the channel AFTER us, so on a late join it can miss BOTH our single
        // fire-once offer AND its own KnownPeer for us (presence delivery is racy),
        // the cross-machine stall. Re-emitting lets it catch a later offer and
        // dial our (reachable) candidates; the initiator only races the FIRST
        // offer it gets, so the extra emits are harmless once linked.
        {
            let sio = self.sio.clone();
            let pid_c = pid.to_string();
            tokio::spawn(async move {
                for _ in 0..6 {
                    tokio::time::sleep(Duration::from_millis(1200)).await;
                    let _ = sio
                        .emit("signal", json!({ "to": pid_c, "data": offer.clone() }))
                        .await;
                }
            });
        }
        // The WebRTC fallback reaper (`expired_direct`) fires at this deadline.
        // rung-1's race always burns the full DIRECT_BUDGET when it can't win
        // (its acceptor future never self-completes), so with hole-punch enabled
        // the deadline MUST cover the WHOLE ladder, rung-1 budget + punch budget
        // + QUIC handshake slack, or the reaper would race WebRTC against an
        // in-flight punch and the route would be a coin flip. Flag-gated, so
        // rung-1-only timing is byte-identical.
        let deadline = if holepunch::holepunch_enabled() {
            Instant::now() + direct::DIRECT_BUDGET + holepunch::PUNCH_BUDGET + Duration::from_secs(3)
        } else {
            Instant::now() + direct::DIRECT_BUDGET
        };
        self.direct_pending.insert(
            pid.to_string(),
            DirectPending {
                secret: (name.to_string(), secret.to_string()),
                deadline,
                racing: false,
                endpoint: ep,
                punch_sock,
                my_srflx,
                probe,
            },
        );
    }

    /// rung-2: bind a raw punch socket and discover its srflx via STUN against
    /// the ICE config's STUN server. Returns (raw socket, srflx) or None.
    async fn gather_srflx(&self) -> Option<(std::net::UdpSocket, std::net::SocketAddr)> {
        let cfg = net::fetch_config(&self.server).await.ok()?;
        let stun_urls: Vec<String> = cfg
            .ice_servers
            .iter()
            .flat_map(|s| s.urls.iter().cloned())
            .collect();
        // #3 (parallelism): race ALL configured STUN servers so a slow/dead one
        // never stalls gathering (the offer the initiator waits on).
        let stun_addrs = holepunch::stun_server_addrs(&stun_urls);
        if stun_addrs.is_empty() {
            return None;
        }
        let sock = holepunch::bind_punch_socket().ok()?;
        // STUN is blocking UDP I/O, run it off the reactor.
        tokio::task::spawn_blocking(move || {
            holepunch::stun_srflx_any(&sock, &stun_addrs).map(|srflx| (sock, srflx))
        })
        .await
        .ok()?
        .ok()
    }

    /// The peer advertised its candidates. If we have a matching pending attempt
    /// and haven't started the race yet, consume the endpoint and spawn the
    /// simultaneous-open + auth race; the winner posts Ev::DirectReady (or, for an
    /// upgrade probe, Ev::DirectUpgradeReady, verify-before-upgrade).
    fn on_transport_offer(&mut self, pid: &str, peer_cands: Vec<String>, peer_srflx: Option<String>) {
        let Some(p) = self.direct_pending.get_mut(pid) else { return };
        if p.racing {
            return;
        }
        let Some(ep) = p.endpoint.take() else { return };
        p.racing = true;
        let secret = p.secret.1.clone();
        // P5 (GAP-6): is THIS the upgrade-probe pending? Then the winner posts
        // DirectUpgradeReady (verify-before-upgrade) so the serving relay link is
        // never clobbered. A cold pending posts DirectReady as before.
        let is_probe = p.probe;
        // rung-2: hand the punch socket + peer's srflx to the chained ladder.
        let punch_sock = p.punch_sock.take();
        let peer_srflx_addr = peer_srflx
            .as_deref()
            .and_then(|s| s.parse::<std::net::SocketAddr>().ok());
        let tx = self.tx.clone();
        let pid_s = pid.to_string();
        let mk = move |pid: String, t: Arc<dyn Transport>, route: &'static str| {
            if is_probe {
                Ev::DirectUpgradeReady(pid, t, route)
            } else {
                Ev::DirectReady(pid, t, route)
            }
        };
        tokio::spawn(async move {
            // Check for TCP localhost candidate (same-machine peer).
            for cand in &peer_cands {
                if let Ok(v) = serde_json::from_str::<serde_json::Value>(cand) {
                    if v["type"] == "tcp-localhost" {
                        if let Some(port) = v["port"].as_u64() {
                            let addr = format!("127.0.0.1:{port}");
                            ui::trace(&format!("filament: trying TCP localhost to {addr}"));
                            match crate::local::LocalTransport::connect(&addr).await {
                                Ok(t) => {
                                    let _ = tx.send(mk(pid_s, Arc::new(t), "local-tcp"));
                                    return;
                                }
                                Err(e) => {
                                    ui::trace(&format!("filament: TCP localhost failed: {e}"));
                                }
                            }
                        }
                    }
                }
            }
            // rung-1: direct-dial QUIC over host candidates. answerer=true: this
            // is on_transport_offer (the side whose daemon received the offer), so
            // it allocates from the high L2 sid half (the connector side uses the
            // low half) - keeps the two ends' sids disjoint.
            if let Some(t) =
                direct::race_connect(ep, peer_cands, &secret, pid_s.clone(), tx.clone(), true).await
            {
                let _ = tx.send(mk(pid_s, t, "direct-quic"));
                return;
            }
            // rung-2: UDP hole-punch, then rung-1's QUIC race over the punched
            // socket. Only fires with the flag on, a punch socket bound, and a
            // peer srflx to punch toward. On failure (e.g. symmetric NAT) we fall
            // through to the WebRTC step-down via the per-tick reaper.
            if holepunch::holepunch_enabled() {
                if let (Some(sock), Some(peer_srflx)) = (punch_sock, peer_srflx_addr) {
                    // TRACE, direct/hole-punch detail.
                    ui::trace(&format!("filament: rung-1 failed, attempting hole-punch to {peer_srflx}"));
                    if let Some(t) = holepunch::connect(
                        sock,
                        peer_srflx,
                        &secret,
                        pid_s.clone(),
                        tx.clone(),
                        true, // answerer (same on_transport_offer/acceptor side)
                    )
                    .await
                    {
                        let _ = tx.send(mk(pid_s, t, "holepunched"));
                        return;
                    }
                }
            }
            // On None the per-tick reaper handles the WebRTC fallback at deadline.
        });
    }

    /// P5 (GAP-6): a relay-committed peer received an UPGRADE-PROBE transport-
    /// offer (`probe:true`) from the other end while we have no probe pending of
    /// our own yet. ARM a matching upgrade probe so the symmetric direct dial can
    /// complete (both ends must offer their candidates for the QUIC simultaneous-
    /// open race). Only fires for a peer we are actually serving on relay
    /// (`relay_committed` + a live link) and only when the prober is enabled and
    /// relay isn't forbidden, otherwise the probe offer is ignored.
    async fn answer_upgrade_probe(&mut self, pid: &str) {
        if !net::upgrade_prober_enabled() || relay_forbidden() {
            return;
        }
        if !self.resil.relay_committed.contains(pid) || !self.links.contains_key(pid) {
            return;
        }
        if self.direct_pending.contains_key(pid) {
            return; // our own probe is already in flight, its race will consume the offer
        }
        let known = self.links.get(pid).and_then(|l| l.expected_secret.clone());
        if let Some((name, secret)) = known {
            self.start_upgrade_probe(pid, &name, &secret).await;
        }
    }

    /// Create the Link for a direct connection that won the race. `peer: None`
    /// (no WebRTC), `direct: true`, `trusted: true` (the pair-secret MAC already
    /// proved identity, at least as strong as the DTLS pair-proof it replaces).
    fn adopt_direct(&mut self, pid: &str, t: Arc<dyn Transport>, route: &'static str) {
        let pend = self.direct_pending.remove(pid);
        let (name, secret) = match pend {
            Some(p) => p.secret,
            None => ("peer".to_string(), String::new()),
        };
        let info = self
            .roster
            .get(pid)
            .cloned()
            .unwrap_or_else(|| json!({ "id": pid, "name": name }));
        let uid = info["uid"].as_str().map(|s| s.to_string());
        let expected_secret = if secret.is_empty() {
            None
        } else {
            Some((name.clone(), secret))
        };
        self.next_gen += 1;
        let generation = self.next_gen;
        // If a Link already exists for this pid (e.g. from a stall-watchdog
        // repair re-dial), UPDATE its transport + workers in place instead of
        // full-insert replacing the old Link (which would drop the primary
        // transport Arc → quinn ApplicationClosed → primary death at K>1).
        // Workers stay intact; only the primary transport is swapped.
        let _existing_generation = self.links.get(pid).map(|l| l.generation).unwrap_or(0);
        if let Some(existing) = self.links.get_mut(pid) {
            if existing.transport.as_ref().map(|t2| t2.is_dead()).unwrap_or(true) { existing.transport = Some(t); }
            existing.direct = true;
            existing.direct_route = route;
            existing.generation = generation;
            existing.attempts = 0;
            existing.trusted = true;
            if let Some((n, _)) = &expected_secret {
                existing.verified_name = Some(n.clone());
            }
            if expected_secret.is_some() {
                existing.expected_secret = expected_secret;
            }
        } else {
            // Mesh reuse: spawn accept loop before t moves into Link.
            direct::spawn_mesh_accept(pid.to_string(), &t, self.tx.clone());
            self.links.insert(
                pid.to_string(),
                Link {
                peer: None,
                info,
                name,
                uid,
                transport: Some(t),
                workers: vec![],
                generation,
                attempts: 0,
                trusted: true,
                // A direct link is born identity-bound (its pair-secret MAC
                // already proved who it is), so the petname is known up front.
                verified_name: expected_secret.as_ref().map(|(n, _)| n.clone()),
                expected_secret,
                presence: Presence::Ready,
                direct: true,
                direct_route: route,
                established_at: Some(Instant::now()),
            },
        );
        }
    }

    /// Spawn K-1 parallel QUIC worker transports in a background task after
    /// the primary direct connection wins.  The non-answerer side dials; the
    /// answerer side accepts.  Each worker gets its OWN quinn::Endpoint (own
    /// UDP socket, own driver task) so packet I/O parallelises across cores.
    /// Workers arrive asynchronously via `Ev::DirectWorkersReady` and are
    /// populated on the Link.  File send (`stream_one`) gracefully degrades
    /// to fewer streams if workers are not yet ready.
    fn spawn_direct_workers(
        &mut self,
        pid: &str,
        primary: &Arc<dyn Transport>,
        _tkey: [u8; 32],
    ) {
        let k = net::direct_streams();
        if k <= 1 {
            return;
        }
        let Some(_peer_addr) = primary.remote_addr() else { return };
        // BUGFIX: `primary.sid_answerer()` is TRUE on BOTH ends of a symmetric
        // simultaneous-open (both peers establish via on_transport_offer, which
        // hardcodes answerer=true), so it cannot split the worker roles — both
        // sides would `accept_workers` and nobody dials. Use the deterministic
        // polite-role tie-break: it compares (uid, then session-id) so exactly
        // one side is "polite" and the other is not, giving opposite roles.
        // Polite side accepts; the other dials.
        let peer_uid = self.roster.get(pid).and_then(|i| i["uid"].as_str());
        let answerer = net::polite_role(&self.my_uid, peer_uid, &self.my_id, pid);
        #[cfg(debug_assertions)]
        eprintln!("[T] spawn_direct_workers: pid={pid} my_uid={} peer_uid={peer_uid:?} my_id={} answerer={answerer} k={k}", self.my_uid, self.my_id);
        let count = k - 1;

        let pid = pid.to_string();
        let tx = self.tx.clone();
        let primary = primary.clone();

        // Only the ACCEPTOR creates workers (opens mesh streams on the primary).
        // The DIALER side's accept loop (spawned by adopt_direct) picks up the
        // incoming streams and delivers them via Ev::DirectWorkersReady.
        if !answerer {
            #[cfg(debug_assertions)]
            eprintln!("[T] worker DIALER branch: mesh streams accepted by background loop");
            return;
        }

        tokio::spawn(async move {
            let mut workers = Vec::with_capacity(count);
            #[cfg(debug_assertions)]
            eprintln!("[T] worker ACCEPTOR branch: opening {count} mesh streams on primary");
            for _ in 0..count {
                if let Some((send, recv, conn)) = primary.open_stream().await {
                    let worker = direct::make_transport(pid.clone(), conn, send, recv, tx.clone(), true, None);
                    workers.push(worker);
                }
            }
            #[cfg(debug_assertions)]
            eprintln!("[T] acceptor mesh streams: {} workers", workers.len());
            if !workers.is_empty() {
                let _ = tx.send(net::Ev::DirectWorkersReady(pid, workers));
            }
        });
    }

    /// Per-tick: a direct attempt whose budget expired without an authenticated
    /// connection falls back to the WebRTC `establish` (unchanged). Returns the
    /// list of (pid, info) to establish, caller awaits establish outside the
    /// borrow. Also drops any pending whose Link already exists.
    fn expired_direct(&mut self) -> Vec<(String, Value, (String, String))> {
        let now = Instant::now();
        let mut fell_back = Vec::new();
        // P5 (GAP-6): an UPGRADE-PROBE pending whose budget expired with no winner
        // must NOT fall back to WebRTC, the relay link is still serving and the
        // whole point of the probe was to find a DIRECT path. Just DROP it and let
        // the prober's backoff schedule the next attempt (mark_probe_failed). The
        // cold (non-probe) pendings keep their existing WebRTC-fallback behavior.
        let expired_probes: Vec<String> = self
            .direct_pending
            .iter()
            .filter(|(_, p)| p.probe && now >= p.deadline)
            .map(|(pid, _)| pid.clone())
            .collect();
        for pid in expired_probes {
            self.direct_pending.remove(&pid);
            // DEBUG, resilience internal (upgrade probe found no path).
            ui::debug(&format!("filament: UPGRADE-PROBE for {pid} found no direct path in budget, staying on relay"));
            self.mark_probe_failed(&pid);
        }
        let expired: Vec<String> = self
            .direct_pending
            .iter()
            .filter(|(pid, p)| !p.probe && now >= p.deadline && !self.links.contains_key(*pid))
            .map(|(pid, _)| pid.clone())
            .collect();
        for pid in expired {
            if let Some(p) = self.direct_pending.remove(&pid) {
                let info = self
                    .roster
                    .get(&pid)
                    .cloned()
                    .unwrap_or_else(|| json!({ "id": pid, "name": p.secret.0 }));
                // DEBUG, resilience internal (direct→WebRTC fallback).
                ui::debug(&format!(
                    "filament: DIRECT-FALLBACK for {}, no authenticated QUIC in budget, using WebRTC",
                    p.secret.0
                ));
                fell_back.push((pid, info, p.secret));
            }
        }
        // Drop pendings whose link landed by another route (cleanup). P5 (GAP-6):
        // EXCLUDE upgrade probes, a probe pending ALWAYS coexists with the serving
        // relay link (that's the point), so this cleanup must not reap it before its
        // race runs; a probe is reaped only by its own deadline (above) or by the
        // upgrade cutover consuming it.
        let linked: Vec<String> = self
            .direct_pending
            .iter()
            .filter(|(pid, p)| !p.probe && self.links.contains_key(*pid))
            .map(|(pid, _)| pid.clone())
            .collect();
        for pid in linked {
            self.direct_pending.remove(&pid);
        }
        fell_back
    }

    /// C3/C4: watchdog or grace expiry, retry that LINK with fresh config,
    /// up to MAX_ATTEMPTS, then drop it. Returns true when the exhausted link
    /// was the active transfer target (send decides whether that is fatal).
    async fn on_stuck(&mut self, pid: &str, generation: u32, why: &str) -> Result<bool> {
        // C21: don't burn retry attempts against a peer that told us it's
        // away, re-dialing a suspended tab is wasted attrition.
        if self.is_away(pid) {
            return Ok(false);
        }
        let Some(l) = self.links.get(pid) else { return Ok(false) };
        // rung-1: a direct link has no WebRTC watchdog (no Peer::connect timer),
        // so on_stuck can't fire for it; defensively no-op if it ever does.
        if l.direct {
            return Ok(false);
        }
        if l.generation != generation || l.peer.as_ref().map(|p| p.is_connected()).unwrap_or(true) {
            return Ok(false); // stale timer from a superseded attempt
        }
        // Gate-18 Mode B: the transfer is COMPLETE (recv_done; recomputed per
        // tick by the recv loop, so this can only be true with by_sid empty and
        // !keep_open) and this link just went stuck/lost. Reconnecting would
        // fetch nothing and merely FLAP the link, resetting attempts and
        // re-arming expected_secret each cycle, so conn.links never empties and
        // the quiet-exit can't fire (RC=124 hang under contention). DROP it
        // instead: links empties, quiet-exit fires. Fenced to complete-only, so
        // a mid-transfer link (recv_done=false) reconnects normally (gate 2/11c).
        // FILAMENT_TEST_DISABLE_MODEB_DROP reverts to the old reconnect-always
        // behaviour so the gate proves A/B with ONE binary: baseline (toggle set)
        // hangs to RC=124 under the churn hook; fix (toggle unset) exits cleanly.
        if self.recv_done && !test_hooks::disable_modeb_drop() {
            let was_active = self.is_active(pid);
            ui::debug(&ui::paint(ui::Tone::Dim, &format!("dropping peer (connection {why} after completion, nothing left to fetch)")));
            self.drop_link(pid);
            return Ok(was_active);
        }
        let attempts = l.attempts + 1;
        if attempts >= MAX_ATTEMPTS {
            let was_active = self.is_active(pid);
            ui::debug(&ui::paint(ui::Tone::Dim, &format!("dropping peer (connection {why} after {attempts} attempts)")));
            self.drop_link(pid);
            return Ok(was_active);
        }
        // DEBUG, resilience internal (link retry).
        ui::debug(&format!("connection {why}, retrying ({}/{})", attempts + 1, MAX_ATTEMPTS));
        let info = l.info.clone();
        let secret = l.expected_secret.clone();
        // C26: a link that was ever up is *re*connecting; one that never
        // connected is still just connecting, keeps "recovered" honest.
        let prev = match l.presence {
            Presence::Connecting => Presence::Connecting,
            _ => Presence::Reconnecting,
        };
        let was_active = self.is_active(pid);
        // Add exponential backoff between retries to avoid burning through attempts instantly.
        let backoff = std::cmp::min(
            Duration::from_secs(2u64.pow(attempts - 1)),
            Duration::from_secs(10),
        );
        tokio::time::sleep(backoff).await;
        self.establish(info).await?;
        if let Some(nl) = self.links.get_mut(pid) {
            nl.attempts = attempts;
            nl.expected_secret = secret;
            nl.presence = prev;
        }
        if was_active {
            self.active = Some(pid.to_string());
        }
        Ok(false)
    }

    // --- P0 (GAP-1): the bytes-moved STALL watchdog + correction ladder ------
    //
    // The single byte-flow primitive `Transport::idle_ms()` already exists
    // (net.rs) and is stamped at the unambiguous "a data byte moved" point on
    // both send and receive. #28 wired it ONLY to the supersede decision; this
    // is the second consumer the audit calls the core gap: a watchdog that
    // declares an OPEN, ALIVE link bad when an in-flight transfer moves zero
    // bytes, the "stuck at 0%" hang, and drives the least-disruptive
    // correction. Run from the main event loop's tick (no new concurrency: F8).

    /// Per-tick check: if a transfer is in flight (`in_flight`) on a link whose
    /// `idle_ms()` has crossed the stall threshold, return its (pid, idle_ms) so
    /// the loop can emit `Ev::TransferStalled`. Returns `None` for a flowing or
    /// idle-but-empty link. Resetting bookkeeping on observed progress lives in
    /// `note_progress`, so a slow-but-MOVING link (which keeps advancing
    /// idle_ms's baseline) never trips, the threshold is on time-since-last-byte,
    /// never on throughput.
    fn detect_stall(&mut self, pid: &str, in_flight: bool) -> Option<u64> {
        let in_episode = self.resil.stall_repairs.get(pid).map(|s| s.pending).unwrap_or(false);
        // The liveness PHASE is the single source of truth (resilience::classify):
        // it pairs each phase with its own clock, so an ESTABLISHING link (no first
        // byte yet) is judged by the generous grace and a FLOWING one by the tight
        // stall threshold. This makes "judge a still-establishing link by the 6 s
        // flowing threshold" - the high-RTT relay repair loop - unrepresentable.
        // See docs/transfer-state-machine.md.
        // Aggregate across primary + worker transports: during multi-stream
        // transfers data rides the workers, so the primary can appear idle.
        // Liveness is measured by the MOST recently active transport.
        let link = self.links.get(pid);
        let transport = link.and_then(|l| l.transport.as_ref());
        let workers: Vec<Arc<dyn Transport>> = link.map(|l| l.workers.clone()).unwrap_or_default();
        let transport_up = transport.is_some() || !workers.is_empty();
        let flowed = transport.map(|t| t.has_flowed()).unwrap_or(false)
            || workers.iter().any(|w| w.has_flowed());
        let idle_ms = transport.map(|t| t.idle_ms()).into_iter()
            .chain(workers.iter().map(|w| w.idle_ms()))
            .min()
            .unwrap_or(u64::MAX);
        #[cfg(debug_assertions)]
        eprintln!("[STALL] pid={pid} in_flight={in_flight} transport_up={transport_up} flowed={flowed} idle_ms={idle_ms} workers={} cluster={:?}",
            workers.len(),
            transport.map(|t| t.idle_ms()).into_iter().chain(workers.iter().map(|w| w.idle_ms())).collect::<Vec<_>>()
        );
        let obs = resilience::LiveObs {
            in_flight,
            transport_up,
            flowed,
            idle_ms,
            grace_ms: net::establish_grace_ms(),
            stall_ms: net::stall_ms(),
        };
        match resilience::classify(&obs) {
            // Flowing, or still establishing within grace: bytes are (or may yet
            // be) moving. note_progress clears any open episode, so the brief
            // windows during a repair (new transport not yet flowing) do NOT reset
            // the attempt counter and re-arm rung (a).
            resilience::Liveness::Flowing | resilience::Liveness::Establishing => {
                self.note_progress(pid);
                None
            }
            // Nothing in flight: drop stray bookkeeping.
            resilience::Liveness::Idle => {
                self.resil.stall_repairs.remove(pid);
                None
            }
            // No progress past the phase threshold. Open a new episode, or (if one
            // is already open) re-fire the ladder UNLESS a repair is converging -
            // re-emitting every tick would thrash while the replacement transport
            // is still establishing.
            resilience::Liveness::Stalled => {
                if in_episode && self.repair_in_flight(pid) {
                    None
                } else {
                    Some(obs.idle_ms)
                }
            }
        }
    }

    /// Is a repair for this peer's stall episode currently converging (a re-dial
    /// in flight or the ladder mid-step)? Used to avoid re-firing every tick.
    fn repair_in_flight(&self, pid: &str) -> bool {
        // A direct re-dial is pending, OR the ladder just acted and we're waiting
        // on the next observation. We treat `direct_pending` as the convergence
        // signal for rung (c)'s fresh dial. P1: a relay escalation (rung d) builds
        // a fresh WebRTC link NOT tracked by `direct_pending`, so the per-episode
        // `relayed` latch is its convergence signal, both keep the watchdog from
        // re-firing while the replacement transport is still establishing.
        if self.direct_pending.contains_key(pid) {
            return true;
        }
        self.resil.stall_repairs.get(pid).map(|s| s.relayed).unwrap_or(false)
    }

    /// Clear a peer's stall episode, called when bytes are observed moving
    /// again (the link recovered) or nothing is in flight.
    fn note_progress(&mut self, pid: &str) {
        self.resil.stall_repairs.remove(pid);
        // P3: a fresh byte means the (warm-cut-over) path is healthy again, let a
        // FUTURE episode warm-cut-over once more if it too stalls.
        self.resil.warm_cutover.remove(pid);
    }

    /// P0 liveness cross-check: is the link's CONTROL path still answering? A
    /// black-holed *data* path (the case we recover) still carries reliable,
    /// ordered control frames, so a successful control send distinguishes
    /// "data wedged, link alive" (→ correction ladder) from "link dead" (→ the
    /// established C3/C4 establishment-retry path, which already handles it).
    /// We send a cheap `ping` control frame; success ⇒ alive. We do NOT await a
    /// pong (F8: the event loop must never block on something a remote controls),
    /// a send that returns Ok over a reliable channel is sufficient evidence
    /// the transport itself is up; a dead transport errors or is flagged dead and
    /// returns Err here.
    async fn link_alive(&self, pid: &str) -> bool {
        match self.transport_of(pid) {
            Some(t) => t
                .send_control(&json!({ "type": "ping", "v": 1, "reason": "stall-probe" }))
                .await
                .is_ok(),
            None => false,
        }
    }

    /// Decide the correction RUNG for the current stall episode and (for rung c)
    /// repair the transport in place WITHOUT tearing the session down. Returns:
    ///   `Rung::Resume`: rung (a): caller re-offers unfinished transfers with
    ///                     resume:true on the SAME transport (cheapest).
    ///   `Rung::Repaired`: rung (c): the transport was repaired in place
    ///                     (direct: fresh QUIC dial of the known device;
    ///                     WebRTC: restart_ice), caller re-offers once it's back.
    ///   `Rung::Relayed`, rung (b)/(d): re-established over the TURN relay. P3
    ///                     reaches this on the FIRST stall for a warm-standby
    ///                     (interactive) session, instant failover to the
    ///                     pre-designated warm alternate; P1 reaches it at the
    ///                     ladder ceiling for a one-shot transfer.
    ///   `Rung::Exhausted`: rungs a→c spent (MAX_ATTEMPTS) AND relay unavailable
    ///                     (forbidden / already on relay), fail clean, kept partial.
    /// Bounds the episode by MAX_ATTEMPTS, reusing the same ceiling as on_stuck.
    async fn correct_stall(&mut self, pid: &str) -> Rung {
        // P3 (GAP-3): once this episode has CUT OVER to the warm relay standby, a
        // SECOND Ev::TransferStalled that was already QUEUED before the cutover ran
        // (the loops emit one per tick while the stall holds) must NOT re-enter the
        // ladder and run a COLD in-place repair on top of the converging cutover,
        // that tore the fresh relay link down ("ICE Agent can not be restarted when
        // gathering"). Swallow it as a no-op (`Repaired` is the benign "in flight,
        // nothing to do" for both handlers). This guard is keyed on `warm_cutover`,
        // which is ONLY ever set on the warm path, so the COLD ladder (P0/P1) is
        // byte-for-byte unchanged and still climbs rung a→c→d normally. Cleared by
        // `note_progress` when the relay path moves a byte.
        if self.resil.warm_cutover.contains(pid) {
            return Rung::Repaired;
        }
        let st = self.resil.stall_repairs.entry(pid.to_string()).or_default();
        st.pending = true;
        let attempt = st.attempts;
        st.attempts += 1;

        // P3 (GAP-3): WARM-REDUNDANCY instant failover (rung b). For a long-lived
        // / interactive session (`warm_standby`), the relay is a PRE-DESIGNATED
        // WARM standby kept ready alongside the primary direct path. On the FIRST
        // detected stall we CUT OVER to it IMMEDIATELY rather than grinding through
        // the slow direct-repair rungs, rung (a)'s resume-and-wait-another-stall,
        // then rung (c)'s up-to-MAX_ATTEMPTS cold re-dials, each of which costs a
        // full stall threshold before it gives up. Those rungs are correct for a
        // one-shot file (the on-disk partial makes a cold repair fine), but for an
        // interactive session every one of those windows is a visible, intolerable
        // gap. Cutting straight to the warm relay collapses N×stall_ms of cold
        // re-establish into a single relay cutover (rung d's machinery, but reached
        // on stall #1 instead of stall #~6), preserving the on-disk partial / PTY
        // stream / tunnel state via the same C7 resume seam.
        //
        // Gated tightly so we never pay this on the wrong session:
        //   - `warm_standby` (session-kind selectivity) must be on;
        //   - relay must be PERMITTED (`--no-relay` keeps the hard direct-only
        //     promise → fall through to the normal ladder, which fails clean);
        //   - we must not be ON relay already (`relay_only`), then relay is the
        //     PRIMARY that stalled, so there's no warmer alternate; fall through to
        //     the ladder, which lands on the honest "still stalled on relay" exit;
        //   - we cut over at most ONCE per episode (`warm_cutover`), a flapping
        //     relay can't re-fire instant cutover every tick; the second stall on
        //     the relay path falls through to the bounded relay-stalled honesty.
        let warm_eligible = self.resil.warm_standby
            && !relay_forbidden()
            && !self.relay_only
            && !self.resil.warm_cutover.contains(pid);
        // The ladder DECISION (which rung) is pure and lives in resilience.rs; this
        // method owns the state mutation + the rung's side effect.
        match resilience::decide_stall_action(
            attempt,
            STALL_MAX_REPAIRS,
            warm_eligible,
            relay_forbidden(),
            self.relay_only,
        ) {
            resilience::StallAction::WarmCutover => {
                // P3 (GAP-3) WARM-REDUNDANCY instant failover (rung b): cut straight
                // to the pre-designated warm relay standby instead of grinding the
                // slow direct-repair rungs (intolerable for an interactive session).
                // DEBUG, resilience internal; visible at -v / FILAMENT_LOG=debug.
                ui::debug(&ui::paint(
                    ui::Tone::Warn,
                    "  transfer stalled, cutting over to the warm relay standby (instant failover)",
                ));
                self.resil.warm_cutover.insert(pid.to_string());
                // Latch the episode as relaying so detect_stall waits for the fresh
                // relay path to move a byte (clearing the episode) instead of
                // re-firing the ladder while the cutover converges.
                if let Some(st) = self.resil.stall_repairs.get_mut(pid) {
                    st.relayed = true;
                }
                self.escalate_to_relay(pid).await;
                Rung::Relayed
            }
            resilience::StallAction::Resume => {
                // Rung (a): cheapest, re-issue on the same transport. The caller
                // owns `outgoing` and does the actual re-offer; we just classify.
                // DEBUG, resilience internal (rung (a) resume on the same link).
                ui::debug(&ui::paint(ui::Tone::Warn, "  transfer stalled, resuming on the same link"));
                Rung::Resume
            }
            resilience::StallAction::ExhaustedRelayForbidden => {
                // The hard direct-only promise: never silently fall to a relay.
                // CRITICAL, a clean fatal path-decision the user must see (-q too).
                ui::critical(&ui::paint(
                    ui::Tone::Warn,
                    "  couldn't establish a direct path; relay disabled (--no-relay), \
                    partial kept on disk. Re-run to resume, or drop --no-relay to \
                     allow relay fallback.",
                ));
                Rung::Exhausted
            }
            resilience::StallAction::ExhaustedAlreadyRelay => {
                // We already re-established over relay and it ALSO stalled: no harder
                // rung. Stop honestly with the partial preserved.
                // CRITICAL, a terminal honesty line the user must see (-q too).
                ui::critical(&ui::paint(
                    ui::Tone::Warn,
                    "  transfer still stalled on the relay route, partial kept on disk. \
                     Re-run to resume.",
                ));
                Rung::Exhausted
            }
            resilience::StallAction::RelayEscalate => {
                // Rung (d): re-establish over the TURN relay, preserving the on-disk
                // partial (C7 resume). Bounded: one escalation per episode.
                // CRITICAL, P1's value-prop: the never-flaky promise kicking in.
                ui::critical(&ui::paint(
                    ui::Tone::Warn,
                    "  direct paths exhausted, falling back to the TURN relay",
                ));
                if let Some(st) = self.resil.stall_repairs.get_mut(pid) {
                    st.relayed = true;
                }
                self.escalate_to_relay(pid).await;
                Rung::Relayed
            }
            resilience::StallAction::Repair => {
                // Rung (c): repair the transport IN PLACE under the live session.
                // DEBUG, resilience internal (in-place repair).
                ui::debug(&ui::paint(
                    ui::Tone::Warn,
                    &format!("  transfer stalled, repairing the link in place (attempt {}/{})", attempt, STALL_MAX_REPAIRS),
                ));
                self.repair_link_in_place(pid).await;
                Rung::Repaired
            }
        }
    }

    /// Rung (c): rebuild a path under the LIVE session, preserving the on-disk
    /// partial (C7 resume re-offers from the saved offset on the new transport).
    /// - direct-QUIC link: drop the wedged transport and re-arm the known-device
    ///   direct dial (`start_direct`), which re-advertises candidates; the peer's
    ///   matching re-dial (it runs the same watchdog) completes a FRESH
    ///   authenticated QUIC connection → `Ev::DirectReady` → `adopt_direct` swaps
    ///   in the new transport → ChannelReady re-offers the unfinished transfers.
    /// - WebRTC link: `restart_ice()`, keeps the RTCPeerConnection + DTLS keys;
    ///   only ICE re-gathers, so transfers resume on the same channel once ICE
    ///   re-converges (no re-key, the preferred repair when available).
    async fn repair_link_in_place(&mut self, pid: &str) {
        let Some(l) = self.links.get(pid) else { return };
        if l.direct {
            // Fresh QUIC dial of the known device. Pull the (name,secret) the
            // link was born with so the re-dial re-authenticates to the SAME pair
            // secret (session identity is stable across the swap; only the wire
            // keys rotate, documented in §2.5).
            let known = l.expected_secret.clone();
            let info = l.info.clone();
            let was_active = self.is_active(pid);
            self.drop_link(pid); // tears down the wedged transport (frees the port)
            if let Some((name, secret)) = known {
                self.start_direct(pid, &name, &secret).await;
                if was_active {
                    // start_direct creates no Link yet; keep the slot pointed here
                    // so adopt_direct's ChannelReady re-offers to the right target.
                    self.active = Some(pid.to_string());
                }
            } else {
                // No stored secret to re-dial direct, fall back to a WebRTC
                // re-establish under the session (still preserves the partial).
                let _ = self.establish(info).await;
                if was_active {
                    self.active = Some(pid.to_string());
                }
            }
        } else if let Some(p) = l.peer.clone() {
            // WebRTC: ICE-restart in place, no teardown, no re-key.
            p.restart_ice().await;
        }
    }

    /// Rung (d), P1 (GAP-4): the direct/in-place ladder is exhausted, so
    /// RE-ESTABLISH this transfer over the TURN relay (relay-only ICE), the
    /// automatic version of the manual `--relay` the Pixel delivery and the runner
    /// both had to perform by hand. The on-disk partial is preserved at the seam:
    /// we re-establish a fresh WebRTC link with `RTCIceTransportPolicy::Relay`, and
    /// its ChannelReady re-offers the unfinished transfers with `resume:true` from
    /// the saved `.part` offset (no restart-from-zero, C7). Flipping the
    /// connection-wide `relay_only` flag also makes any subsequent repair on this
    /// session relay-only, so we don't bounce back to a known-bad direct path.
    /// Session identity (the pair secret / verified petname) is stable across the
    /// swap, only the wire keys rotate (§2.5). Bounded: one escalation per stall
    /// episode (the caller returns `Rung::Relayed` and the `stall_repairs` counter
    /// is already at the ceiling, so the ladder can't re-fire until progress
    /// resumes and resets it).
    async fn escalate_to_relay(&mut self, pid: &str) {
        // Latch the whole connection onto relay-only ICE: the re-establish below
        // and every later (re)establish for this session now forces TURN.
        self.relay_only = true;
        // Commit THIS peer to relay: stop dialing/answering direct-QUIC for it, so
        // the known-bad direct path can't keep winning the race and re-freezing
        // while the relay link tries to form (the exact thrash the sim exposed).
        self.resil.relay_committed.insert(pid.to_string());
        let Some(l) = self.links.get(pid) else { return };
        let info = l.info.clone();
        let known = l.expected_secret.clone();
        let was_active = self.is_active(pid);
        // Tear down the wedged (direct) transport, then re-establish over WebRTC
        // relay-only. We deliberately do NOT re-arm the direct-QUIC dial here even
        // if a secret is known: direct is what just failed, and relay is a WebRTC
        // path, so we go straight to `establish` (relay-only ICE).
        self.drop_link(pid);
        // Clear any stray pending direct attempt so `establish` (which early-
        // returns while a direct attempt owns the peer, to keep the ladder
        // sequential) is never suppressed for the relay re-establish.
        self.direct_pending.remove(pid);
        // Carry the proven identity into the fresh relay link so the post-channel
        // pair-proof still binds to the same device (set after establish creates
        // the Link below).
        let _ = self.establish(info).await;
        if let (Some(l), Some(ks)) = (self.links.get_mut(pid), known) {
            l.expected_secret = Some(ks);
        }
        if was_active {
            self.active = Some(pid.to_string());
        }
        // Honest, loud: the user must know this session is now on a relay.
        // CRITICAL, the value-prop path label; shown even under -q.
        ui::critical(&format!("  {}", relay_banner()));
        // P5 (GAP-6): ARM the relay->direct upgrade prober for this peer. Relay is
        // a way-station, not a destination: while we serve on relay we keep probing
        // for a direct path and upgrade back the moment one is confirmed stable.
        // Eligibility mirrors warm redundancy (long-lived/interactive sessions +
        // the daemon, a one-shot send that already completed doesn't need it) and
        // requires relay to be PERMITTED. The kill switch (`FILAMENT_UPGRADE_PROBE=0`)
        // and `--no-relay` both make this a no-op.
        if self.upgrade_eligible() {
            self.resil.upgrade_probe
                .entry(pid.to_string())
                .or_insert_with(UpgradeProbe::armed);
            ui::say(&ui::paint(
                ui::Tone::Dim,
                "  on relay, will keep trying for a direct path and upgrade automatically",
            ));
        }
    }

    /// P5 (GAP-6): is this session eligible to run the relay->direct prober?
    /// Selective like P3's warm redundancy: ON for long-lived / interactive
    /// sessions (the `up`/`up --shell` daemon acceptor; a transfer flagged
    /// interactive via `FILAMENT_WARM_STANDBY=1`). Gated off by the kill switch
    /// and by `--no-relay` (which never reaches relay anyway).
    fn upgrade_eligible(&self) -> bool {
        self.resil.warm_standby && net::upgrade_prober_enabled() && !relay_forbidden()
    }

    /// P5 (GAP-6): a portable network-change-ish event fired (a signaling
    /// reconnect / fresh welcome). Re-probe every relay-committed peer IMMEDIATELY
    /// (reset its backoff to fire now), unless it's already mid-verify on a standby.
    /// Cheap and idempotent, the prober tick does the actual dialing.
    fn reprobe_on_network_event(&mut self) {
        if !net::upgrade_prober_enabled() || relay_forbidden() {
            return;
        }
        for up in self.resil.upgrade_probe.values_mut() {
            if up.standby.is_none() {
                up.next_at = Some(Instant::now());
            }
        }
    }

    /// P5 (GAP-6): record a failed/expired probe and back the cadence off toward
    /// the steady cadence (exponential, capped at steady_ms). Also clears any
    /// stale standby/verify state so the next probe starts clean.
    fn mark_probe_failed(&mut self, pid: &str) {
        let Some(up) = self.resil.upgrade_probe.get_mut(pid) else { return };
        up.attempt = up.attempt.saturating_add(1);
        up.standby = None;
        up.verify_started = None;
        up.verify_last_idle = u64::MAX;
        // Backoff: first failure → first_ms; then double toward steady_ms (cap).
        let first = net::upgrade_first_ms();
        let steady = net::upgrade_steady_ms();
        let backoff = first.saturating_mul(1u64 << up.attempt.min(8)).min(steady);
        up.next_at = Some(Instant::now() + Duration::from_millis(backoff));
    }

    /// P5 (GAP-6): the per-tick prober. Run from each live-session event loop's
    /// tick (no new concurrency, F8). For every peer currently committed to relay
    /// with an armed `UpgradeProbe`: (1) if a direct standby is mid-VERIFY, judge
    /// it (cut over if it has sustained progress for verify_ms; discard + back off
    /// if it regressed); (2) else if a probe is due (`next_at`), fire a fresh
    /// direct dial ALONGSIDE the relay link (warm direct standby) without
    /// disturbing it. Also detects a local interface change (`iface_snapshot`) and
    /// re-probes IMMEDIATELY, the "walked home onto wifi" trigger.
    async fn tick_upgrade_prober(&mut self) {
        if !net::upgrade_prober_enabled() || relay_forbidden() {
            return;
        }
        if self.resil.upgrade_probe.is_empty() {
            return;
        }
        // Network-change trigger: a change to the local interface set is the
        // strongest "a new direct path may exist NOW" signal we can read without a
        // platform netlink dependency. On change, reset every armed probe's
        // backoff to fire immediately (catches the wifi/cellular handoff instantly).
        let snap = direct::local_ip_snapshot();
        if snap != self.resil.iface_snapshot {
            if !self.resil.iface_snapshot.is_empty() {
                // DEBUG, resilience internal (upgrade-probe trigger).
                ui::debug(&ui::paint(
                    ui::Tone::Dim,
                    "  network changed, re-probing for a direct path now",
                ));
                for up in self.resil.upgrade_probe.values_mut() {
                    if up.standby.is_none() {
                        up.next_at = Some(Instant::now()); // fire ASAP
                    }
                }
            }
            self.resil.iface_snapshot = snap;
        }

        let now = Instant::now();
        let pids: Vec<String> = self.resil.upgrade_probe.keys().cloned().collect();
        for pid in pids {
            // A peer that is no longer relay-committed (already upgraded or gone)
            // shouldn't be probed; drop its entry.
            if !self.resil.relay_committed.contains(&pid) || !self.links.contains_key(&pid) {
                self.resil.upgrade_probe.remove(&pid);
                self.direct_pending.remove(&pid);
                continue;
            }
            // VERIFYING: a standby connected, judge it before scheduling anything.
            let verifying = self
                .resil.upgrade_probe
                .get(&pid)
                .map(|u| u.standby.is_some())
                .unwrap_or(false);
            if verifying {
                self.judge_upgrade_standby(&pid).await;
                continue;
            }
            // PROBING: a direct dial is in flight (its DirectPending), wait for it
            // to win (→ DirectUpgradeReady) or expire (→ expired_direct backoff).
            if self.direct_pending.contains_key(&pid) {
                continue;
            }
            // IDLE: schedule / fire the next probe per the backoff.
            let due = match self.resil.upgrade_probe.get(&pid).and_then(|u| u.next_at) {
                None => true,            // armed but unscheduled → schedule first probe
                Some(at) => now >= at,   // due
            };
            if let Some(up) = self.resil.upgrade_probe.get_mut(&pid) {
                if up.next_at.is_none() {
                    // First scheduling after arming: probe after first_ms.
                    up.next_at = Some(now + Duration::from_millis(net::upgrade_first_ms()));
                    continue;
                }
            }
            if !due {
                continue;
            }
            // Fire a probe: dial direct ALONGSIDE the relay link.
            let known = self.links.get(&pid).and_then(|l| l.expected_secret.clone());
            let Some((name, secret)) = known else {
                // No stored secret to authenticate a direct dial, can't probe;
                // disarm so we don't spin.
                self.resil.upgrade_probe.remove(&pid);
                continue;
            };
            // DEBUG, resilience internal (upgrade probe attempt).
            ui::debug(&ui::paint(
                ui::Tone::Dim,
                "  probing for a direct path (alongside the relay)...",
            ));
            // Pre-set the NEXT backoff deadline so a probe that silently makes no
            // progress still re-schedules (expired_direct also calls
            // mark_probe_failed on budget expiry; whichever fires first wins).
            self.start_upgrade_probe(&pid, &name, &secret).await;
        }
    }

    /// P5 (GAP-6): VERIFY-before-upgrade. A direct standby has connected for
    /// `pid`. Decide whether it is STABLE enough to cut over to:
    ///   - if it has been moving data (idle_ms stays low) CONTINUOUSLY for
    ///     `verify_ms`, perform the upgrade (clear relay_committed/relay_only, cut
    ///     over to the direct transport, tear down relay, re-offer transfers);
    ///   - if it goes idle past `verify_idle_ms` before that, DISCARD it and stay
    ///     on relay (back off), the mandatory no-flap guard against a flaky direct
    ///     path that connects then immediately re-stalls.
    /// We drive a tiny VERIFY heartbeat over the standby (a control ping) so a
    /// healthy path keeps stamping its `idle_ms()` low even before the session's
    /// real transfer bytes are re-routed onto it.
    async fn judge_upgrade_standby(&mut self, pid: &str) {
        let verify_ms = net::upgrade_verify_ms();
        let verify_idle_ms = net::upgrade_verify_idle_ms();
        // Heartbeat the standby with a real DATA frame (reserved verify sid) so a
        // healthy path advances its activity clock (`idle_ms()` stays low) while a
        // stalled/flaky standby, which black-holes the DATA path, not the control
        // path, either errors here or lets idle climb. A control ping would wrongly
        // pass on a flaky standby (whose control path stays alive), so we MUST probe
        // the data path. The peer drops the unknown-sid chunk harmlessly but stamps
        // its inbound activity, so its side's idle drops too (symmetric verify).
        let standby = self.resil.upgrade_probe.get(pid).and_then(|u| u.standby.clone());
        let Some(standby) = standby else { return };
        // BOUND the heartbeat (F8: never block the event loop on something a remote
        // / a wedged path controls). A flaky standby's data path black-holes, the
        // send_frame would park forever, so a timeout reads as "didn't hold".
        let beat_ok = matches!(
            tokio::time::timeout(
                Duration::from_millis(500),
                standby.send_frame(VERIFY_PROBE_SID, 0, b"upgrade-verify"),
            )
            .await,
            Ok(Ok(()))
        );
        let idle = standby.idle_ms();
        let Some(up) = self.resil.upgrade_probe.get_mut(pid) else { return };
        let started = match up.verify_started {
            Some(t) => t,
            None => {
                up.verify_started = Some(Instant::now());
                up.verify_last_idle = idle;
                return;
            }
        };
        // Regressed: control send failed OR the path went idle past the guard.
        // Discard the standby, stay on relay, back off (the no-flap guard).
        if !beat_ok || idle >= verify_idle_ms {
            // DEBUG, resilience internal (no-flap guard rejecting a standby).
            ui::debug(&ui::paint(
                ui::Tone::Warn,
                "  direct path connected but didn't hold, staying on relay (no flap)",
            ));
            self.direct_pending.remove(pid);
            self.mark_probe_failed(pid);
            return;
        }
        up.verify_last_idle = up.verify_last_idle.min(idle);
        // Sustained: moved data continuously for the whole verify window → upgrade.
        if started.elapsed() >= Duration::from_millis(verify_ms) {
            let t = standby;
            let route = self.resil.upgrade_probe.get(pid).map(|u| u.standby_route).unwrap_or("direct-quic");
            self.perform_upgrade(pid, t, route).await;
        }
    }

    /// P5 (GAP-6): the upgrade cutover. The direct standby is CONFIRMED stable,
    /// commit it as the session's transport, preserving the session (the same
    /// cutover seam P1/P3 use): clear `relay_committed` + `relay_only` so direct
    /// may win again, swap the verified direct transport into the link (the relay
    /// link/transport is dropped), and re-offer any unfinished transfers
    /// (resume:true) on the new direct path. Honest + loud, mirroring the relay
    /// banner: the user is told they're back on a direct path.
    async fn perform_upgrade(&mut self, pid: &str, t: Arc<dyn Transport>, route: &'static str) {
        let was_active = self.is_active(pid);
        let known = self.links.get(pid).and_then(|l| l.expected_secret.clone());
        // Clear the relay commitment FIRST so the new direct link isn't treated as
        // a known-bad path and so a future stall can escalate cleanly again.
        self.resil.relay_committed.remove(pid);
        self.relay_only = false;
        self.resil.upgrade_probe.remove(pid);
        self.direct_pending.remove(pid);
        // Swap the verified direct transport into the link, dropping the relay
        // link/transport (drop_link tears down the WebRTC peer). adopt the new
        // transport via the same direct-link shape adopt_direct builds, but reusing
        // the existing identity so the session is preserved across the swap.
        self.drop_link(pid);
        self.adopt_direct_transport(pid, t.clone(), route, known);
        if was_active {
            self.active = Some(pid.to_string());
        }
        // CRITICAL, P5's value-prop line: relay released, back on a direct path.
        ui::critical(&ui::paint(
            ui::Tone::Ok,
            &format!("  upgraded back to a direct path (route: {route}), relay released"),
        ));
        // Re-offer unfinished transfers on the new direct transport (resume:true);
        // the ChannelReady re-emit drives the same path for the send loop.
        let _ = self.tx.send(Ev::ChannelReady(pid.to_string(), t));
    }

    /// P5 (GAP-6): build the post-upgrade DIRECT link from a verified standby
    /// transport, reusing the known identity (so the session/petname is stable
    /// across the relay->direct swap, only the wire path changes). Mirrors
    /// `adopt_direct` but takes an already-connected transport and a carried
    /// (name,secret) instead of consuming a `DirectPending`.
    fn adopt_direct_transport(
        &mut self,
        pid: &str,
        t: Arc<dyn Transport>,
        route: &'static str,
        known: Option<(String, String)>,
    ) {
        let info = self
            .roster
            .get(pid)
            .cloned()
            .unwrap_or_else(|| json!({ "id": pid, "name": known.as_ref().map(|(n, _)| n.clone()).unwrap_or_else(|| "peer".into()) }));
        let name = known
            .as_ref()
            .map(|(n, _)| n.clone())
            .or_else(|| info["name"].as_str().map(String::from))
            .unwrap_or_else(|| "peer".into());
        let uid = info["uid"].as_str().map(|s| s.to_string());
        self.next_gen += 1;
        let generation = self.next_gen;
        self.links.insert(
            pid.to_string(),
            Link {
                peer: None,
                info,
                name,
                uid,
                transport: Some(t),
                workers: vec![],
                generation,
                attempts: 0,
                trusted: true,
                verified_name: known.as_ref().map(|(n, _)| n.clone()),
                expected_secret: known,
                presence: Presence::Ready,
                direct: true,
                direct_route: route,
                established_at: Some(Instant::now()),
            },
        );
    }

    /// P5 (GAP-6): a relay->direct upgrade probe's direct standby CONNECTED. Stash
    /// it on the peer's `UpgradeProbe` and START the verify window. Crucially, do
    /// NOT touch `links`, the relay link keeps serving until the standby is proven
    /// stable. If we have no armed probe for this peer (it upgraded/left while the
    /// race was in flight), just drop the transport (it closes on drop). Idempotent:
    /// a second DirectUpgradeReady for an already-stashed standby is ignored.
    fn stash_upgrade_standby(&mut self, pid: &str, t: Arc<dyn Transport>, route: &'static str) {
        // Consume any probe DirectPending so expired_direct doesn't reap/backoff it
        // out from under the verify (the race already won).
        self.direct_pending.remove(pid);
        let Some(up) = self.resil.upgrade_probe.get_mut(pid) else {
            // No armed probe, the transport is unowned; dropping it tears it down.
            return;
        };
        if up.standby.is_some() {
            return; // already verifying a standby; ignore the duplicate.
        }
        up.standby = Some(t);
        up.standby_route = route;
        up.verify_started = None; // judge_upgrade_standby stamps it on first look
        up.verify_last_idle = u64::MAX;
        // DEBUG, resilience internal (upgrade verify window opening).
        ui::debug(&ui::paint(
            ui::Tone::Dim,
            "  direct path connected, verifying it holds before upgrading...",
        ));
    }

    /// C4: transient `disconnected`, nudge ICE from the impolite side and
    /// give it grace before treating it as failure. C21: a peer that said
    /// `brb` gets its declared window instead of the 6 s blip grace, and no
    /// scary message.
    async fn on_pc_state(&mut self, pid: &str, s: &str) {
        let away = self.is_away(pid);
        let Some(l) = self.links.get_mut(pid) else { return };
        // C26: collect the announcement, print after the borrow ends so the
        // roster can read every link.
        let mut announce: Option<(&'static str, ui::Tone, &'static str)> = None;
        match s {
            "connected" => {
                if l.presence == Presence::Reconnecting {
                    announce = Some((ui::glyph_ok(), ui::Tone::Ok, "recovered"));
                }
                l.presence = Presence::Ready;
                l.attempts = 0;
            }
            "disconnected" => {
                let grace = if away {
                    l.presence = Presence::Away;
                    if let Some((_, until)) = &self.rejoin.away {
                        until.duration_since(Instant::now()) + Duration::from_secs(15)
                    } else {
                        Duration::from_secs(6)
                    }
                } else {
                    l.presence = Presence::Reconnecting;
                    announce = Some(("", ui::Tone::Warn, "reconnecting..."));
                    Duration::from_secs(6)
                };
                if let Some(p) = &l.peer {
                    if !p.polite && !away {
                        p.restart_ice().await;
                    }
                }
                let tx = self.tx.clone();
                let pid = pid.to_string();
                let generation = l.generation;
                tokio::spawn(async move {
                    tokio::time::sleep(grace).await;
                    let _ = tx.send(Ev::GraceExpired(pid, generation));
                });
            }
            _ => {}
        }
        if let Some((mark, tone, note)) = announce {
            ui::say(&self.roster(pid, mark, tone, note, "peer"));
        }
    }

    /// A peer's socket died. Drop its link; if it was the active target, open
    /// the rejoin window (their client auto-rejoins; C6 supersede completes
    /// the recovery). Returns true if the ACTIVE peer left.
    ///
    /// #28 DEFERRED DROP: peer-left fires when a sid LEAVES THE ROOM, but the
    /// WebRTC data channel is independent and may still be flowing, either a
    /// cosmetic signaling reconnect mid-transfer (keep it!) or a hard-killed
    /// peer whose channel reads flowing for a beat before DTLS notices (must
    /// still drop, or the sender strands). We can't tell the two apart at this
    /// instant, so we DEFER: stash the payload and re-check each tick
    /// (`reap_deferred`). If it goes idle/dead it gets re-injected here with a
    /// force marker and dropped then; if it keeps flowing the transfer
    /// completes on the live channel and the idle link is reaped harmlessly.
    /// The roster entry is removed immediately (the sid truly left); only the
    /// LINK drop is deferred.
    fn on_peer_left(&mut self, v: &Value) -> bool {
        let Some(pid) = v["id"].as_str() else { return false };
        let pid = pid.to_string();
        self.roster.remove(&pid);
        if !self.links.contains_key(&pid) {
            return false;
        }
        // Defer the drop while the data channel is still moving bytes, unless
        // this is the force re-injection from reap_deferred (the link has since
        // gone idle/dead and must drop now). FILAMENT_TEST_NO_DEFER reverts to
        // the old unconditional-drop behaviour so an A/B repro can prove the
        // deferral is what saves the live transfer (baseline must FAIL).
        let forced = v["__fil_force_drop"].as_bool() == Some(true);
        let defer_disabled = test_hooks::no_defer();
        if !forced && !defer_disabled && self.link_flowing(&pid) {
            // Idempotent: first peer-left for this sid records the original
            // payload; a duplicate is swallowed (no double-defer, no drop).
            self.deferred_left.entry(pid.clone()).or_insert_with(|| v.clone());
            let name = self.link(&pid).map(|l| l.name.clone()).unwrap_or_else(|| "peer".into());
            // DEBUG, resilience internal (deferred drop while channel flowing).
            ui::debug(&format!("{name} signaling left, data channel still flowing, deferring drop"));
            return false;
        }
        let was_active = self.is_active(&pid);
        self.drop_link(&pid);
        if was_active {
            // C21: informed waits, a peer that declared `brb` gets its
            // promised window (plus slack); an unannounced vanish gets the
            // short default. Their client auto-rejoins; C6 supersede or a
            // fresh adopt completes the recovery.
            self.rejoin.rejoin_window = match &self.rejoin.away {
                Some((apid, until)) if *apid == pid && *until > Instant::now() => {
                    until.duration_since(Instant::now()) + Duration::from_secs(15)
                }
                _ => rejoin_unwarned(),
            };
            self.rejoin.waiting_rejoin = Some(Instant::now());
        }
        was_active
    }

    /// #28: re-check every deferred peer-left. Called on every main-loop tick
    /// (idempotent, cheap). A deferred sid is discharged when it is no longer
    /// flowing, its data channel went idle past the threshold OR died
    /// (idle_ms == u64::MAX). We then re-inject the ORIGINAL peer-left payload
    /// (flagged force) so the normal Ev::PeerLeft handler runs verbatim, same
    /// loop-side flush/messaging/rejoin behaviour as a non-deferred leave, with
    /// the link now correctly dropped. A sid that vanished from `links` (e.g. a
    /// supersede dropped it; drop_link already cleared its entry, but belt-and-
    /// braces) is forgotten silently. A still-flowing sid is left to keep
    /// flowing, the reconnect case, where the transfer completes on the live
    /// channel and the all-done exit reaps it.
    fn reap_deferred(&mut self) {
        if self.deferred_left.is_empty() {
            return;
        }
        let ready: Vec<(String, Value)> = self
            .deferred_left
            .iter()
            .filter(|(sid, _)| !self.links.contains_key(*sid) || !self.link_flowing(sid))
            .map(|(sid, v)| (sid.clone(), v.clone()))
            .collect();
        for (sid, mut payload) in ready {
            self.deferred_left.remove(&sid);
            if !self.links.contains_key(&sid) {
                continue; // link already gone (superseded); nothing to drop
            }
            // Force the drop this time (the channel is now idle/dead).
            if let Some(obj) = payload.as_object_mut() {
                obj.insert("__fil_force_drop".into(), Value::Bool(true));
            }
            let name = self.link(&sid).map(|l| l.name.clone()).unwrap_or_else(|| "peer".into());
            // DEBUG, resilience internal (deferred-leave reap).
            ui::debug(&format!("{name} link went idle after deferred leave, dropping now"));
            // Re-inject so the loop's own peer-left branch handles partials,
            // messaging and the rejoin window exactly as a fresh leave would.
            let _ = self.tx.send(Ev::PeerLeft(payload));
        }
    }

    /// #28 exit reconciliation: true when every remaining link is one we're only
    /// holding open for its deferred-drop reap (vacuously true with no links). A
    /// link in `deferred_left` is a peer whose signaling already left; once all
    /// transfers are complete it protects nothing, so it must not delay exit by
    /// the full deferral window.
    fn only_deferred_links(&self) -> bool {
        self.links.keys().all(|k| self.deferred_left.contains_key(k))
    }

    /// C21: any traffic from a peer cancels its declared absence.
    fn note_alive(&mut self, pid: &str) {
        if matches!(&self.rejoin.away, Some((apid, _)) if apid == pid) {
            self.rejoin.away = None;
        }
    }

    /// C26: set a link's roster presence; returns its name for the announce.
    fn link_presence(&mut self, pid: &str, p: Presence) -> String {
        match self.links.get_mut(pid) {
            Some(l) => {
                l.presence = p;
                l.name.clone()
            }
            None => String::new(),
        }
    }

    fn is_away(&self, pid: &str) -> bool {
        matches!(&self.rejoin.away, Some((apid, until)) if apid == pid && *until > Instant::now())
    }

    /// C26: one static colored status line showing EVERY peer, the changed
    /// one carrying the note, `✓ daring-wombat   ● deft-gibbon  away...`.
    /// `fallback_name` covers a peer already dropped from the map (peer-left).
    fn roster(&self, pid: &str, mark: &str, tone: ui::Tone, note: &str, fallback_name: &str) -> String {
        let mut links: Vec<(&String, &Link)> = self.links.iter().collect();
        links.sort_by(|a, b| a.1.name.cmp(&b.1.name));
        let mut parts = Vec::new();
        let mut seen = false;
        for (id, l) in links {
            if id == pid {
                seen = true;
                parts.push(peer_entry(l.shown(), mark, tone, note));
            } else {
                let (m, t, n) = presence_glyph(l.presence);
                parts.push(peer_entry(l.shown(), m, t, n));
            }
        }
        if !seen {
            parts.push(peer_entry(fallback_name, mark, tone, note));
        }
        format!("  {}", parts.join("   "))
    }

    /// #7 for the CLI: an offer from a roster peer we haven't linked yet
    /// creates a polite responder link. Stray signals from unknowns drop.
    /// Apply a relayed signal to `from`'s link. Never fatal (F6): the
    /// watchdog/grace machinery owns failed negotiations. On polite-side
    /// glare (webrtc-rs can't roll back out of have-local-offer) the link is
    /// rebuilt as a pure responder and the colliding offer re-applied.
    async fn apply_signal(&mut self, from: &str, data: Value) {
        let peer = match self.link(from).and_then(|l| l.peer.clone()) {
            Some(p) => p,
            None => return,
        };
        match peer.handle_signal(data).await {
            Ok(net::SignalOutcome::Handled) => {}
            Ok(net::SignalOutcome::Glare(offer)) => {
                self.drop_link(from);
                if let Err(e) = self.ensure_responder(from, &offer).await {
                    ui::trace(&format!("signal: glare rebuild failed: {e} (recovering)"));
                    return;
                }
                if let Some(p) = self.link(from).and_then(|l| l.peer.clone()) {
                    if let Err(e) = p.handle_signal(offer).await {
                        ui::trace(&format!("signal failed to apply: {e} (recovering)"));
                    }
                }
            }
            Err(e) => ui::trace(&format!("signal failed to apply: {e} (recovering)")),
        }
    }

    async fn ensure_responder(&mut self, from: &str, data: &Value) -> Result<()> {
        if self.links.contains_key(from) {
            return Ok(());
        }
        if data["type"].as_str() == Some("description")
            && data["description"]["type"].as_str() == Some("offer")
        {
            // Answer a WebRTC offer from a channel-peer EVEN IF we never got its
            // known-peer. The existing-member known-peer notification is
            // unreliable on prod (proven via the signaling harness: the NEW
            // joiner is reliably notified, but the EXISTING member often is NOT),
            // which left the acceptor ignoring a valid initiator's offer and
            // looking like "stuck connecting". One-sided discovery is now enough:
            // whoever discovers drives, the other answers. SAFE: trust still
            // gates entirely on the pair-proof MAC (an attacker without the
            // secret fails it and is never trusted), we only answer the offer
            // and let the proof decide. A later known-peer refreshes name/uid.
            let info = self
                .roster
                .get(from)
                .cloned()
                .unwrap_or_else(|| json!({ "id": from }));
            if self.links.len() < MAX_LINKS {
                // Forced responder: this link exists to answer THEIR offer.
                self.establish_as(info, Some(true)).await?;
            }
        }
        Ok(())
    }
}

/// Receive the next event; while a rejoin window is open, tick every second
/// so the window can expire AND the countdown stays visible (C22, "45s"
/// frozen on screen reads as broken).
async fn next_ev(
    rx: &mut mpsc::UnboundedReceiver<Ev>,
    conn: &Conn,
    suppress_countdown: bool,
) -> Result<Option<Ev>> {
    if let Some(since) = conn.rejoin.waiting_rejoin {
        if since.elapsed() > conn.rejoin.rejoin_window {
            ui::clear_sticky();
            bail!(
                "peer did not come back within {}s (partial state kept for resume)",
                conn.rejoin.rejoin_window.as_secs()
            );
        }
        if !suppress_countdown {
            let left = conn.rejoin.rejoin_window.saturating_sub(since.elapsed()).as_secs();
            ui::sticky(&ui::paint(
                ui::Tone::Dim,
                &format!("  {} holding the line, {left}s for them to come back (Ctrl-C to stop)", ui::spinner_frame()),
            ));
        }
        match tokio::time::timeout(Duration::from_secs(1), rx.recv()).await {
            Ok(Some(ev)) => Ok(Some(ev)),
            Ok(None) => Err(anyhow!("signaling channel closed")),
            Err(_) => Ok(None), // tick
        }
    } else {
        // C30: never block indefinitely, a 2s tick lets the convergent
        // session repair lost emits even when no events arrive.
        match tokio::time::timeout(Duration::from_secs(2), rx.recv()).await {
            Ok(Some(ev)) => Ok(Some(ev)),
            Ok(None) => Err(anyhow!("signaling channel closed")),
            Err(_) => Ok(None), // tick
        }
    }
}

/// Per-peer-link map keyed by warm-pty `session` -> (pid, sid), so a later
/// `pty-resize` op can relay to the right stream. Shared between the event loop
/// (lookup) and the spawned bridge tasks (insert/remove). Inert on non-unix.
type WarmPtys = std::sync::Arc<std::sync::Mutex<HashMap<String, (String, u32)>>>;

struct DaemonMountEntry {
    local: String,
    peer: String,
    remote: String,
    pid: u32,
    read_only: bool,
    auto_restore: bool,
    created: String,
}

struct DaemonMounts {
    entries: HashMap<String, DaemonMountEntry>,
    children: HashMap<String, tokio::process::Child>,
}

/// Dispatch one warm-reuse control request to the right handler. Warm reuse is
/// unix-only (the control socket is a unix-domain socket); on non-unix `ctl::Req`
/// is uninhabited so this is never reached - it only keeps the event loop portable.
#[cfg(not(unix))]
async fn handle_warm_req(
    _conn: &Conn,
    _l2_muxes: &mut HashMap<String, Arc<l2::Mux>>,
    _warm_ptys: &WarmPtys,
    _tx: &mpsc::UnboundedSender<Ev>,
    req: ctl::Req,
) {
    match req {}
}

#[cfg(unix)]
async fn handle_warm_req(
    conn: &Conn,
    l2_muxes: &mut HashMap<String, Arc<l2::Mux>>,
    warm_ptys: &WarmPtys,
    tx: &mpsc::UnboundedSender<Ev>,
    req: ctl::Req,
) {
    match &req.kind {
        ctl::ReqKind::Open { .. } => handle_warm_open(conn, l2_muxes, tx, req).await,
        // Dial is handled inline in the daemon loop (it needs the L3 manager);
        // answer defensively if it ever reaches here.
        ctl::ReqKind::Dial { .. } => req.reject("dial not handled here").await,
        ctl::ReqKind::Pty { .. } => handle_warm_pty(conn, l2_muxes, warm_ptys, tx, req).await,
        ctl::ReqKind::Resize { .. } => handle_warm_resize(l2_muxes, warm_ptys, req).await,
        ctl::ReqKind::Ping { .. } => handle_warm_ping(conn, req).await,
        // Bootstrap is dispatched before this (it defers its reply), so it never
        // reaches here; reject defensively so a future caller falls back to cold.
        ctl::ReqKind::Bootstrap { .. } => req.reject("bootstrap not handled here").await,
        // Reconfigure is handled inline in the daemon loop (it mutates loop state),
        // so it never reaches this dispatcher; answer defensively if it ever does.
        ctl::ReqKind::Reconfigure { .. } => req.reply(&json!({ "ok": true, "live": false })).await,
        // ReloadExpose is likewise handled inline in the daemon loop (it owns the
        // Exposer); answer defensively if it ever reaches here.
        ctl::ReqKind::ReloadExpose => req.reply(&json!({ "ok": true, "live": false, "count": 0 })).await,
        // Reload is handled inline in the daemon loop (it self-SIGTERMs); answer
        // defensively if it ever reaches here.
        ctl::ReqKind::Reload => req.reply(&json!({ "ok": true, "reloading": false })).await,
        // Mount/Unmount/ListMounts/MountHealth are handled inline in the daemon
        // loop (they need access to DaemonMounts); answer defensively if reached.
        ctl::ReqKind::Mount { .. } => req.reject("mount not handled here").await,
        ctl::ReqKind::Unmount { .. } => req.reject("unmount not handled here").await,
        ctl::ReqKind::ListMounts => req.reject("list-mounts not handled here").await,
        ctl::ReqKind::MountHealth { .. } => req.reject("mount-health not handled here").await,
    }
}

/// Handle a mount request: spawn sshfs directly and track the child process
/// centrally so `handle_unmount` can kill it.
#[cfg(unix)]
async fn handle_mount(
    req: ctl::Req,
    server: &str,
    relay: bool,
    daemon_mounts: &mut DaemonMounts,
    last_mount_check: &mut Instant,
) {
    let ctl::ReqKind::Mount { peer, remote, local, read_only, auto_restore, port } = &req.kind else { return };
    let peer = peer.clone();
    let remote = remote.clone();
    let local = local.clone();
    let read_only = *read_only;
    let auto_restore = *auto_restore;
    let port = *port;

    // Ensure mount point exists.
    if !Path::new(&local).exists() {
        if let Err(e) = std::fs::create_dir_all(&local) {
            req.reject(&format!("failed to create mount point: {e}")).await;
            return;
        }
        crate::ui::say(&format!("created mount point: {local}"));
    }

    // Check sshfs is available.
    if std::process::Command::new("which")
        .arg("sshfs")
        .output()
        .map(|o| !o.status.success())
        .unwrap_or(true)
    {
        req.reject("sshfs not found").await;
        return;
    }

    // Bootstrap peer connection info.
    let info = match crate::l2::ensure_peer_bootstrap_port(server, &peer, relay, port).await {
        Ok(info) => info,
        Err(e) => {
            req.reject(&format!("bootstrap failed: {e}")).await;
            return;
        }
    };
    let peer_name = peer.strip_suffix(".mesh").unwrap_or(&peer);

    // Build the sshfs command args directly.
    let mut args: Vec<String> = Vec::new();

    // Common SSH options.
    args.extend_from_slice(&[
        "-o".into(), format!("IdentityFile={}", info.key_path.display()),
        "-o".into(), "IdentitiesOnly=yes".into(),
        "-o".into(), format!("UserKnownHostsFile={}", info.known_hosts_path.display()),
        "-o".into(), "GlobalKnownHostsFile=/dev/null".into(),
        "-o".into(), "StrictHostKeyChecking=accept-new".into(),
        "-o".into(), "ConnectTimeout=10".into(),
        "-o".into(), "ServerAliveInterval=15".into(),
        "-o".into(), "ServerAliveCountMax=4".into(),
    ]);

    // L3 preferred, L2 fallback.
    let dest = if let Some(d) = crate::l2::l3_dest(&info) {
        d  // L3 direct: user@peer.mesh, no ProxyCommand
    } else {
        // L2 fallback: user@filament-peer with ProxyCommand
        let exe = std::env::current_exe().unwrap();
        let exe = exe.to_string_lossy();
        let mut proxy = format!("{exe} --server {server}");
        if relay {
            proxy.push_str(" --relay");
        }
        proxy.push_str(&format!(" netcat {peer_name} {}", info.rport));
        args.push("-o".into());
        args.push(format!("ProxyCommand={proxy}"));
        format!("{}@{}", info.login, info.host)
    };

    args.push(format!("{dest}:{remote}"));
    args.push(local.clone());
    if read_only {
        args.push("-o".into());
        args.push("ro".into());
    }

    // Spawn sshfs via tokio so we get a Child we can kill later.
    let child = match tokio::process::Command::new("sshfs")
        .args(&args)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            req.reject(&format!("failed to spawn sshfs: {e}")).await;
            return;
        }
    };

    let pid = child.id().unwrap_or(0);
    let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
    let mount_id = mount::unique_mount_id();
    let parent_id = mount::find_parent_mount(&local);

    // Record in persistent mount tracking.
    let _ = mount::add_mount(mount::MountEntry {
        id: mount_id.clone(),
        parent_id,
        local: local.clone(),
        peer: peer_name.to_string(),
        remote: remote.clone(),
        pid,
        read_only,
        auto_restore,
        created: now.clone(),
    });

    // Store in daemon in-memory tracking.
    let entry = DaemonMountEntry {
        local: local.clone(),
        peer: peer_name.to_string(),
        remote: remote.clone(),
        pid,
        read_only,
        auto_restore,
        created: now,
    };
    daemon_mounts.entries.insert(local.clone(), entry);
    daemon_mounts.children.insert(local.clone(), child);

    *last_mount_check = Instant::now();
    crate::ui::say(&format!("mounted {peer_name}:{remote} at {local} (id: {mount_id})"));
    req.reply(&json!({ "ok": true })).await;
}

/// Handle an unmount request: kill the sshfs process and remove tracking.
#[cfg(unix)]
async fn handle_unmount(req: ctl::Req, daemon_mounts: &mut DaemonMounts) {
    let ctl::ReqKind::Unmount { target } = &req.kind else { return };
    let target = target.clone();

    // Kill the child process if tracked by the daemon.
    if let Some(mut child) = daemon_mounts.children.remove(&target) {
        let _ = child.kill().await;
    }
    daemon_mounts.entries.remove(&target);

    // Also remove from persistent tracking (async-safe, no block_on).
    match mount::unmount_cmd_async(&target).await {
        Ok(()) => req.reply(&json!({ "ok": true })).await,
        Err(e) => req.reject(&format!("unmount failed: {e}")).await,
    }
}

/// Handle a list-mounts request: return all tracked mounts and their status.
#[cfg(unix)]
async fn handle_list_mounts(req: ctl::Req, daemon_mounts: &DaemonMounts) {
    let mounts: Vec<Value> = daemon_mounts.entries.values().map(|e| {
        let is_alive = mount::is_mount_point(&e.local);
        let status = if is_alive { "healthy" } else { "dead" };
        json!({
            "local": e.local,
            "peer": e.peer,
            "remote": e.remote,
            "read_only": e.read_only,
            "auto_restore": e.auto_restore,
            "created": e.created,
            "status": status,
        })
    }).collect();
    req.reply(&json!({ "ok": true, "mounts": mounts })).await;
}

/// Handle a mount-health request: check health of a specific mount.
#[cfg(unix)]
async fn handle_mount_health(req: ctl::Req, daemon_mounts: &DaemonMounts) {
    let ctl::ReqKind::MountHealth { target } = &req.kind else { return };
    let target = target.clone();

    // Find the entry by local path or ID.
    let entry = daemon_mounts.entries.get(&target);
    match entry {
        Some(e) => {
            let is_alive = mount::is_mount_point(&e.local);
            let path_exists = Path::new(&e.local).exists();
            let status = if !path_exists {
                "missing"
            } else if !is_alive {
                "dead"
            } else {
                match std::fs::metadata(&e.local) {
                    Ok(_) => "healthy",
                    Err(_) => "stale",
                }
            };
            req.reply(&json!({ "ok": true, "status": status, "local": e.local, "peer": e.peer, "remote": e.remote })).await;
        }
        None => {
            // Not tracked by daemon, but check if it's a live mount anyway.
            if mount::is_mount_point(&target) {
                req.reply(&json!({ "ok": true, "status": "untracked", "local": target })).await;
            } else {
                req.reject(&format!("no mount found for '{target}'")).await;
            }
        }
    }
}

/// Is something listening on this host's own loopback `port` - i.e. an sshd a
/// `filament ssh` initiator could actually reach? A fast connect probe: a
/// successful connect means a listener (we close it at once); refused/timeout
/// means nothing is there. Reported in the shell-bootstrap ack so the initiator
/// fails fast with a clear message instead of ssh hanging on a dead port.
async fn sshd_listening(port: u16) -> bool {
    // Probe localhost first (covers the common case: sshd bound to localhost or
    // all interfaces). Then also try ::1 for dual-stack daemons that only bind
    // IPv6 localhost.
    let addrs: [(&str, std::net::SocketAddr); 2] = [
        ("127.0.0.1", (std::net::Ipv4Addr::LOCALHOST, port).into()),
        ("[::1]", (std::net::Ipv6Addr::LOCALHOST, port).into()),
    ];
    let rt = tokio::runtime::Handle::current();
    for (_label, addr) in addrs {
        let ok = rt
            .spawn_blocking(move || {
                std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(400))
                    .is_ok()
            })
            .await
            .unwrap_or(false);
        if ok {
            return true;
        }
    }
    false
}

/// Answer a `filament ping`: report the daemon's warm link to `peer` (route,
/// remote address, RTT, verified name). Synchronous - every fact is local (quinn
/// already measured the RTT/addr; the route is the link's own label/ICE state), so
/// nothing is awaited from the peer and the F8 event-loop rule is not in play. A
/// miss `reject`s so the client falls back to a cold establish-probe.
#[cfg(unix)]
async fn handle_warm_ping(conn: &Conn, req: ctl::Req) {
    let ctl::ReqKind::Ping { peer } = &req.kind else { return };
    let peer = peer.clone();
    let Some((pid, t)) = warm_link_for(conn, &peer) else {
        req.reject("no warm link").await;
        return;
    };
    // WARM-HOLD: ping succeeded, mark peer as warm (note: we can't call
    // note_warm_use here because conn is &Conn; the warm-hold tick will
    // connect to this peer on the next cycle if it drops)
    let link = conn.link(&pid);
    let direct = link.map(|l| l.direct).unwrap_or(false);
    let route = if direct {
        link.map(|l| l.direct_route.to_string()).unwrap_or_else(|| "direct".into())
    } else if let Some(p) = link.and_then(|l| l.peer.clone()) {
        p.route().await.unwrap_or_else(|| "relay".into())
    } else {
        "relay".to_string()
    };
    // Path detail: name the interface the link's local end sits on, classify the
    // remote address, and (for webrtc) report the candidate types + whether the
    // path is relayed. The daemon holds the link AND runs on the same box as the
    // ping client, so it resolves local-ip -> interface locally; ping.rs just
    // renders the fields. This is the data that answers "is it the tailnet?"
    // (e.g. local 100.x on a tailscale0 iface) instead of inferring it.
    let peer_ref = link.and_then(|l| l.peer.clone());
    let path = net::describe_path(t.as_ref(), peer_ref.as_deref()).await.to_json();
    let reply = json!({
        "ok": true,
        "warm": true,
        "direct": direct,
        "route": route,
        "remote_addr": t.remote_addr().map(|a| a.to_string()),
        "rtt_ms": t.rtt_ms(),
        "verified": link.and_then(|l| l.verified_name.clone()),
        "path": path,
    });
    req.reply(&reply).await;
}

#[cfg(unix)]
/// A non-direct (relay/WebRTC) link has no QUIC keepalive, so an idle one may be
/// silently NAT/relay-evicted while `is_alive()`/`is_dead()` still lag (the read
/// loop hasn't seen the EOF yet). Container/DERP paths evict ~10s; reusing such a
/// link would open a stream into a black hole and hang. So past this idle window
/// we refuse to warm-reuse a non-direct link and fall back to a fresh establish
/// (correct, just not free). Direct links are exempt: the 5s keepalive keeps them
/// genuinely alive across idle gaps, and their `idle_ms()` is unreliable here
/// anyway (quinn keepalive frames don't stamp last_activity).
/// The net.rs 5s relay keepalive keeps idle_ms under this gate on healthy links;
/// tripping it means the keepalive stopped, so a fresh establish is the right answer.
const WARM_RELAY_STALE_MS: u64 = 8_000;

#[cfg(unix)]
/// Resolve `peer` (matched case-insensitively on the PROVEN `verified_name`, the
/// same key the L2 cap gate uses) to a warm, trusted, alive link, preferring a
/// direct one. The single resolver for every warm-reuse op (open + pty), so the
/// eligibility rule lives in exactly one place. A miss means the caller falls
/// back to a fresh establish, which is correct.
fn warm_link_for(conn: &Conn, peer: &str) -> Option<(String, Arc<dyn net::Transport>)> {
    conn.links
        .iter()
        .filter(|(_, l)| {
            l.trusted
                && l.verified_name.as_deref().map(|n| n.eq_ignore_ascii_case(peer)).unwrap_or(false)
                && l.transport.as_ref().map(|t| {
                    // Alive, AND (direct OR a relay link that hasn't been idle long
                    // enough to be a silently-evicted zombie).
                    t.is_alive() && (l.direct || t.idle_ms() < WARM_RELAY_STALE_MS)
                }).unwrap_or(false)
        })
        .max_by_key(|(_, l)| l.direct as u8)
        .map(|(pid, l)| (pid.clone(), l.transport.clone().unwrap()))
}

/// DEBUG: dump every link's warm-reuse eligibility so a miss-despite-a-live-link
/// is diagnosable (visible at `-v` / FILAMENT_LOG=debug only).
#[cfg(unix)]
fn log_warm_miss(conn: &Conn, peer: &str) {
    for (p, l) in conn.links.iter() {
        ui::debug(&format!(
            "warm-miss '{peer}': pid={p} name={:?} verified={:?} trusted={} has_transport={} alive={} direct={}",
            l.name, l.verified_name, l.trusted,
            l.transport.is_some(),
            l.transport.as_ref().map(|t| t.is_alive()).unwrap_or(false),
            l.direct,
        ));
    }
}

/// Warm-reuse: open a raw L2 stream to `peer:rport` over its existing link and
/// bridge it to the client's unix socket (netcat/ssh/forward fast path).
#[cfg(unix)]
async fn handle_warm_open(
    conn: &Conn,
    l2_muxes: &mut HashMap<String, Arc<l2::Mux>>,
    tx: &mpsc::UnboundedSender<Ev>,
    req: ctl::Req,
) {
    let ctl::ReqKind::Open { peer, rport } = &req.kind else { return };
    let (peer, rport) = (peer.clone(), *rport);
    let Some((pid, t)) = warm_link_for(conn, &peer) else {
        log_warm_miss(conn, &peer);
        req.reject("no warm link to that peer").await;
        return;
    };
    // Reuse the SAME per-peer mux the event loop routes inbound L2 frames to.
    let mux = l2_muxes.entry(pid.clone()).or_insert_with(|| l2::Mux::new(t)).clone();
    let tx = tx.clone();
    // SELF-HEALING warm-reuse: VERIFY the held link still delivers BEFORE committing
    // the client. Open the stream and wait for the first inbound frame (sshd's
    // banner - the byte we needed anyway, so a healthy link pays ~1 RTT and nothing
    // extra), then accept. A zombie link (alive at the QUIC layer but black-holing
    // new streams - the popos hang) yields nothing within the window, so we DROP it
    // (the loop re-forms a healthy one, keeping warm-reuse fast) and REJECT, which
    // makes the client's `try_open` return None and fall straight through to a fresh
    // establish. Verifying before accepting is what makes the fallback INSTANT: an
    // accepted-then-dead connection would instead stall the client until ITS own
    // timeout (the 25s ssh ConnectTimeout we measured). Spawned so the verify wait
    // never blocks the event loop (F8).
    tokio::spawn(async move {
        match l2::open_stream_verified(&mux, rport, l2::warm_verify_window()).await {
            Ok((sid, first, rx)) => {
                let sock = req.accept().await;
                l2::serve_verified_stream(mux, sid, sock, first, rx).await;
            }
            Err(e) => {
                ui::debug(&format!(
                    "filament: warm link to '{peer}' is a zombie ({e}); dropping + establishing fresh"
                ));
                let _ = tx.send(Ev::DropLink(pid));
                req.reject("warm link unresponsive; establishing fresh").await;
            }
        }
    });
}

/// Warm-reuse: open a PTY on `peer` over its existing link and bridge it to the
/// client's stdio socket (the `filament pty` fast path). Records the session->sid
/// so a later `pty-resize` can find it; the entry is dropped when the bridge ends.
#[cfg(unix)]
async fn handle_warm_pty(
    conn: &Conn,
    l2_muxes: &mut HashMap<String, Arc<l2::Mux>>,
    warm_ptys: &WarmPtys,
    tx: &mpsc::UnboundedSender<Ev>,
    req: ctl::Req,
) {
    let ctl::ReqKind::Pty { peer, session, cols, rows, term, cmd } = &req.kind else { return };
    let (peer, session, cols, rows, term, cmd) = (peer.clone(), session.clone(), *cols, *rows, term.clone(), cmd.clone());
    let Some((pid, t)) = warm_link_for(conn, &peer) else {
        log_warm_miss(conn, &peer);
        req.reject("no warm link to that peer").await;
        return;
    };
    let mux = l2_muxes.entry(pid.clone()).or_insert_with(|| l2::Mux::new(t)).clone();
    let warm_ptys = warm_ptys.clone();
    let tx = tx.clone();
    let verify = l2::warm_verify_window();
    // SELF-HEALING warm pty, same shape as handle_warm_open: VERIFY the held link
    // delivers (the shell prompt / replayed buffer, sent unprompted, is the first
    // frame) BEFORE recording the session and accepting the terminal. On a zombie
    // link we DROP it and REJECT, so the client falls straight through to a cold
    // pty rather than getting a dead terminal. Spawned so the verify wait never
    // blocks the event loop (F8).
    tokio::spawn(async move {
        match l2::open_pty_stream_verified(&mux, &session, cols, rows, &term, &cmd, verify).await {
            Ok((sid, first, rx_pipe)) => {
                if let Ok(mut m) = warm_ptys.lock() {
                    m.insert(session.clone(), (pid, sid));
                }
                let sock = req.accept().await;
                l2::serve_verified_stream(mux, sid, sock, first, rx_pipe).await;
                // Bridge ended (shell exit / client gone / link drop): drop our
                // entry, but only if it is still ours (a reconnect may have
                // replaced it).
                if let Ok(mut m) = warm_ptys.lock() {
                    if m.get(&session).map(|(_, s)| *s == sid).unwrap_or(false) {
                        m.remove(&session);
                    }
                }
            }
            Err(e) => {
                ui::debug(&format!(
                    "filament: warm pty link to '{peer}' is a zombie ({e}); dropping + establishing fresh"
                ));
                let _ = tx.send(Ev::DropLink(pid));
                req.reject("warm link unresponsive; establishing fresh").await;
            }
        }
    });
}

/// Warm-reuse: relay a window-size change to an already-open warm PTY (by session).
#[cfg(unix)]
async fn handle_warm_resize(
    l2_muxes: &HashMap<String, Arc<l2::Mux>>,
    warm_ptys: &WarmPtys,
    req: ctl::Req,
) {
    let ctl::ReqKind::Resize { session, cols, rows } = &req.kind else { return };
    let (cols, rows) = (*cols, *rows);
    let target = warm_ptys.lock().ok().and_then(|m| m.get(session).cloned());
    if let Some((pid, sid)) = target {
        if let Some(mux) = l2_muxes.get(&pid) {
            let _ = mux
                .transport()
                .send_control(&json!({ "type": "pty-resize", "sid": sid, "cols": cols, "rows": rows }))
                .await;
        }
    }
    req.accept().await; // close the client's short connection cleanly
}

/// Deferred ssh-bootstrap replies, keyed by the peer's link pid. A `Bootstrap`
/// request can't be answered inline: the daemon sends `shell-bootstrap` over the
/// warm link and the peer's `shell-bootstrap-ack` arrives LATER via this same
/// event loop, so blocking here would deadlock. We stash the reply socket (with a
/// deadline) and complete it from the `shell-bootstrap-ack`/`-deny` control arms,
/// or reap it on timeout. A `Vec` per pid handles concurrent ssh to one peer (the
/// ack is identical, so every waiter gets the same answer).
#[cfg(unix)]
type PendingBootstraps =
    HashMap<String, Vec<(tokio::net::UnixStream, std::time::Instant)>>;

/// Warm-reuse the ssh `shell-bootstrap`: install the client's managed `pubkey` on
/// `peer` over the daemon's EXISTING link instead of a fresh cold establish, the
/// big win for `filament ssh` (pty already rode the warm link; the bootstrap was
/// the last cold-establish left). Sends `shell-bootstrap` and STASHES the reply
/// socket; the ack/deny handler completes it. A miss falls the client back to the
/// cold `shell_bootstrap`.
#[cfg(unix)]
async fn handle_warm_bootstrap(conn: &Conn, pending: &mut PendingBootstraps, req: ctl::Req) {
    let (peer, pubkey, ssh_port) = match &req.kind {
        ctl::ReqKind::Bootstrap { peer, pubkey, ssh_port } => (peer.clone(), pubkey.clone(), *ssh_port),
        _ => return,
    };
    let Some((pid, t)) = warm_link_for(conn, &peer) else {
        log_warm_miss(conn, &peer);
        req.reject("no warm link to that peer").await;
        return;
    };
    if t.send_control(&json!({ "type": "shell-bootstrap", "v": 1, "pubkey": pubkey, "ssh_port": ssh_port }))
        .await
        .is_err()
    {
        req.reject("warm link send failed").await;
        return;
    }
    let deadline = std::time::Instant::now() + Duration::from_secs(12);
    pending.entry(pid).or_default().push((req.sock, deadline));
}

/// Complete every stashed `Bootstrap` waiter for `pid` with `reply`. Called from
/// the `shell-bootstrap-ack`/`-deny` arms; a no-op if none are pending (e.g. the
/// peer re-acked, or the waiter was already reaped).
#[cfg(unix)]
async fn complete_warm_bootstrap(pending: &mut PendingBootstraps, pid: &str, reply: &Value) {
    if let Some(waiters) = pending.remove(pid) {
        for (mut sock, _) in waiters {
            ctl::send_reply(&mut sock, reply).await;
        }
    }
}

/// Drop expired bootstrap waiters (peer never answered): closing the socket gives
/// the client an EOF, which it reads as a miss and falls back to the cold path.
#[cfg(unix)]
fn reap_warm_bootstraps(pending: &mut PendingBootstraps) {
    if pending.is_empty() {
        return;
    }
    let now = std::time::Instant::now();
    for waiters in pending.values_mut() {
        waiters.retain(|(_, deadline)| *deadline > now);
    }
    pending.retain(|_, waiters| !waiters.is_empty());
}

#[tokio::main]
async fn main() -> Result<()> {
    // F2: both ring (webrtc) and aws-lc (reqwest) end up in the dep tree;
    // rustls refuses to guess between two providers, so pick ring explicitly
    // BEFORE anything touches TLS.
    rustls::crypto::ring::default_provider().install_default().ok();
    // Migrate state from legacy cwd-relative .config/filament (the broken
    // Windows fallback when HOME was unset) to the platform-correct path.
    platform::Paths::migrate_legacy();
    // Bare-arg comfort dispatch: `filament <path>` sends it with a code;
    // `filament <something-like-a-code>` claims it. Subcommands still win.
    let mut argv: Vec<String> = std::env::args().collect();
    if let Some(first) = argv.get(1) {
        // The real subcommand set, derived from clap so it can NEVER go stale. A
        // hardcoded list drifted (it missed proxy/expose/pair/set/pty/... and the
        // unknown-token branch below then wrongly rejected them). Includes hidden
        // commands + aliases, so every real verb is recognized.
        use clap::CommandFactory;
        let cmd_names: std::collections::HashSet<String> = {
            let c = Cli::command();
            let mut s = std::collections::HashSet::new();
            for sc in c.get_subcommands() {
                s.insert(sc.get_name().to_string());
                s.extend(sc.get_all_aliases().map(str::to_string));
            }
            s
        };
        if !first.starts_with('-') && !cmd_names.contains(first.as_str()) {
            if std::path::Path::new(first).exists() {
                argv.insert(1, "send".into());
                argv.push("--code".into());
            } else if looks_like_pake_code(first) {
                // L1-a unification: a `word-word-NNNN` (4-digit) code now drives
                // the SAME ephemeral SPAKE2 ceremony whether the verb is `pair`
                // or `recv`; a bare code is ambiguous. We keep routing it to
                // `pair` (the long-standing bare-code behavior, 4-digit codes
                // were always pairing codes), so existing muscle memory is
                // preserved. To RECEIVE a transfer code, run `filament recv
                // <code>` explicitly (the `send --code` output prints exactly
                // that hint), or `filament pair <code>` to remember the device.
                argv.insert(1, "pair".into());
            } else if regex_lite_code(first) {
                // A legacy `word-word-NNN` (2-3 digit) transfer code from an old
                // sender, receive it (no v2 ceremony; the recv path fails loudly
                // if the peer can't run the handshake).
                argv.insert(1, "recv".into());
            } else if devices_load().iter().any(|(n, _)| n == first) {
                // Bare device name = shell in. `filament dovm` opens an interactive
                // PTY. `filament dovm <cmd...>` runs a one-shot command over PTY
                // (no sshd needed; the PTY protocol handles it).
                argv.insert(1, "pty".into());
            } else {
                // Not a command, path, code, or paired device. Give a filament-native
                // error with a did-you-mean over BOTH commands and device names,
                // instead of clap's bare "unrecognized subcommand" (smart errors).
                let first = first.clone();
                let mut cands: Vec<String> = cmd_names.iter().cloned().collect();
                cands.extend(devices_load().into_iter().map(|(n, _)| n));
                let hint = cands
                    .iter()
                    .map(|c| (settings::levenshtein(&first, c), c))
                    .filter(|(d, _)| *d <= 2)
                    .min_by_key(|(d, _)| *d)
                    .map(|(_, c)| c.clone());
                eprintln!("filament: unknown command or device '{first}'");
                if let Some(h) = hint {
                    eprintln!("  did you mean '{h}'?");
                }
                eprintln!("  see what you can do:  filament  ·  filament --help  ·  filament devices");
                std::process::exit(2);
            }
        }
    }
    let cli = Cli::parse_from(argv);
    let ui_caps = UiCapability::from_cli(&cli);
    // Resolve the global output verbosity ONCE, before any worker spawns:
    // FILAMENT_LOG (if set) overrides the -v/-q flags. Default = info.
    ui::init_verbosity(cli.verbose, cli.quiet);
    if let Some(n) = &cli.name_as {
        // single-threaded at this point (before the runtime spawns workers)
        unsafe { std::env::set_var("FILAMENT_NAME", n) };
    }
    // A --color flag overrides the NO_COLOR/TERM env contract (flags win); record
    // it before any output so both stdout (readout) and stderr (caps) honor it.
    if let Some(when) = &cli.color {
        unsafe { std::env::set_var("FILAMENT_COLOR", when) };
    }
    // P1 (GAP-4): record the hard direct-only choice before any worker spawns.
    // Precedence: an explicit --relay/--no-relay flag always wins; otherwise the
    // persistent `relay` setting (always|never|auto) decides.
    let relay = if cli.no_relay {
        NO_RELAY.store(true, std::sync::atomic::Ordering::Relaxed);
        false
    } else if cli.relay {
        true
    } else {
        match settings::get_str("relay", None).as_deref() {
            Some("always") => true,
            Some("never") => {
                NO_RELAY.store(true, std::sync::atomic::Ordering::Relaxed);
                false
            }
            _ => false,
        }
    };
    // Record the global --no-interactive opt-out before any command runs (the
    // gate also honors FILAMENT_NONINTERACTIVE and a non-TTY stdin).
    if cli.no_interactive {
        NO_INTERACTIVE.store(true, std::sync::atomic::Ordering::Relaxed);
    }
    let server = if cli.server == DEFAULT_SERVER {
        config_get("server").unwrap_or(cli.server.clone())
    } else {
        cli.server.clone()
    };
    let server = server.trim_end_matches('/').to_string();
    // Bare `filament` (no subcommand): a short, state-aware tour of what you'd do
    // next, instead of clap's wall of subcommands. Power users still get --help.
    let Some(cmd) = cli.cmd else {
        return tour_cmd();
    };
    match cmd {
        Cmd::Send { paths, code, word, room, to, name, remember } => {
            send_cmd(&server, paths, code || word.is_some(), word, room, to, name, relay, remember).await
        }
        Cmd::Recv { code, dir, yes, room, to, keep_open, remember, output } => {
            recv_cmd(&server, code, dir, yes, room, to, keep_open, relay, remember, false, output, ShellPolicy::Granted, None, false).await
        }
        Cmd::Set { key, value, peer, dry_run, reset, hard, .. } => settings::run_set(
            key.as_deref(),
            value.as_deref(),
            &peer,
            dry_run,
            reset,
            hard,
            ui_caps.yes,
            ui_caps.json || cli.json,
        ).await,
        Cmd::Get { key, peer, show_origin, default, json } => {
            settings::run_get(&key, peer.as_deref(), show_origin, default.as_deref(), json)
        }
        Cmd::Addr { device, v4 } => {
            if let Some(name) = device {
                // Show a specific device's info.
                let all = devices_load();
                let entry = all.iter().find(|(n, _)| n == &name);
                let Some((_, secret)) = entry else {
                    bail!("no device named '{name}', see `filament devices`");
                };
                let caps = device_caps(&name).unwrap_or_else(|| vec!["transfer".to_string()]);
                let channel = channel_of(secret);
                // Load lastSeen and overlay addresses from the device store.
                let (last_seen, stored_v6, stored_v4) = devices_info(&name).unwrap_or((0, None, None));
                let last_seen_str = if last_seen == 0 { "never".to_string() } else {
                    let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
                    let ago = now.saturating_sub(last_seen);
                    if ago < 60 { "just now".to_string() }
                    else if ago < 3600 { format!("{}m ago", ago / 60) }
                    else if ago < 86400 { format!("{}h ago", ago / 3600) }
                    else { format!("{}d ago", ago / 86400) }
                };
                println!("  {}", ui::paint(ui::Tone::Bold, &name));
                println!("  channel:  {}", &channel[..12.min(channel.len())]);
                // Show overlay addresses if we have them.
                if let Some(v6) = &stored_v6 {
                    let v4_str = stored_v4.as_ref().map(|a| format!(" / {a}")).unwrap_or_default();
                    println!("  overlay:  {v6}{v4_str}");
                    println!("  mesh:     {name}.mesh");
                }
                // "granted" (not "caps") makes clear this is the LOCAL GRANT RECORD
                // (what THIS machine authorized the peer to do), NOT what the peer offers.
                println!("  granted:  {}", caps.join(", "));
                println!("  last seen: {last_seen_str}");
            } else {
                // Show this machine's address.
                let id = overlay::Identity::load_or_create()?;
                let my_name = config_get("name").unwrap_or_else(|| l3::hostname());
                let mesh_name = l3::sanitize_host(&my_name);
                if v4 {
                    println!("{}", id.addr_v4());
                } else {
                    println!("  {}", ui::paint(ui::Tone::Bold, &mesh_name));
                    println!("  overlay:  {} (v4) / {} (v6)", id.addr_v4(), id.addr());
                    println!("  mesh:     {mesh_name}.mesh");
                }
            }
            Ok(())
        }
        Cmd::Unset { key, peer } => settings::run_unset(&key, &peer).await,
        Cmd::ServeTun { tun_addr, listen, connect, psk, dev, mtu } => {
            #[cfg(l3)]
            {
                let mut h = Sha256::new();
                h.update(psk.as_bytes());
                let secret: [u8; 32] = h.finalize().into();
                let conn = match (listen, connect) {
                    (Some(b), None) => {
                        ui::say(&format!("  serve-tun: listening on {b} (dev {dev}, {tun_addr})"));
                        direct::serve_tun_listen(b.parse().context("bad --listen address")?, &secret).await?
                    }
                    (None, Some(p)) => {
                        ui::say(&format!("  serve-tun: connecting to {p} (dev {dev}, {tun_addr})"));
                        direct::serve_tun_connect(p.parse().context("bad --connect address")?, &secret).await?
                    }
                    _ => bail!("serve-tun needs exactly one of --listen <bind> or --connect <host:port>"),
                };
                ui::say(&format!("  {} serve-tun link up", ui::paint(ui::Tone::Ok, ui::glyph_ok())));
                l3::run_point_to_point(conn, &dev, &tun_addr, mtu).await
            }
            #[cfg(not(l3))]
            {
                let _ = (tun_addr, listen, connect, psk, dev, mtu);
                bail!("serve-tun (L3) is Linux-only")
            }
        }
        Cmd::Config { key, value } => {
            match (key, value) {
                (Some(k), Some(v)) => {
                    config_set(&k, &v)?;
                    println!("{k} = {v}");
                }
                (Some(k), None) => println!("{}", config_get(&k).unwrap_or_default()),
                (None, _) => {
                    for k in ["name", "server", "dir"] {
                        if let Some(v) = config_get(k) {
                            println!("{k} {v}");
                        }
                    }
                }
            }
            Ok(())
        }
        Cmd::Up { install, system, userspace, dir, shell, shell_only, shell_program, shell_user, install_system, no_proxy_fallback } => {
            // `--userspace` forces the netstack backend; L3::start reads this env, so
            // set it before the daemon brings L3 up (same process). Safe: single
            // threaded at this point (the daemon's tasks are not spawned yet).
            if userspace {
                unsafe { std::env::set_var("FILAMENT_L3_USERSPACE", "1") };
            }
            // Flags win; otherwise fall back to persistent settings. Per-peer
            // `shell on` overrides fold into the shell-only allowlist so
            // `filament set shell on --peer laptop` unifies with --shell-only.
            let shell = shell || settings::get_bool("shell", None);
            let shell_user = shell_user.or_else(|| settings::get_str("shell-user", None));
            let peer_shell = settings::peers_with("shell", "on");
            let shell_only = match (shell_only, peer_shell.is_empty()) {
                (existing, true) => existing,
                (Some(list), false) => Some(format!("{list},{}", peer_shell.join(","))),
                (None, false) => Some(peer_shell.join(",")),
            };
            up_cmd(&server, install, system, dir, relay, shell, shell_only, shell_program, shell_user, install_system, no_proxy_fallback).await
        }
        Cmd::Status { json } => status_cmd(json),
        Cmd::Down => { ui_caps.confirm("shut down the daemon")?; down_cmd() },
        Cmd::Introduce { a, b } => introduce_cmd(&server, &a, &b, relay).await,
        Cmd::Pair { code, name, word } => pair_cmd(&server, code, name, word, relay).await,
        Cmd::Devices { action, json } => {
            match action {
                None => {
                    let all = devices_load();
                    if json {
                        let arr: Vec<Value> = all
                            .iter()
                            .map(|(n, s)| {
                                let (last_seen, v6, v4) = devices_info(n).unwrap_or((0, None, None));
                                let addr = v6.clone().or_else(|| v4.clone()).unwrap_or_default();
                                let mesh = format!("{n}.mesh");
                                json!({
                                    "name": n,
                                    "channel": channel_of(s),
                                    "caps": device_caps(n).unwrap_or_else(|| vec!["transfer".to_string()]),
                                    "lastSeen": last_seen,
                                    "address": addr,
                                    "mesh": mesh,
                                })
                            })
                            .collect();
                        println!("{}", serde_json::to_string_pretty(&arr)?);
                    } else {
                        if all.is_empty() {
                            println!("no known devices yet, run `filament pair` to add one");
                        } else {
                            let mut table = ui::Table::new(&["NAME", "ADDRESS", "GRANTED", "LAST SEEN"]);
                            for (n, _) in &all {
                                let (last_seen, v6, v4) = devices_info(n).unwrap_or((0, None, None));
                                let addr = v6.as_deref().or(v4.as_deref()).unwrap_or("-");
                                let caps = device_caps(n).unwrap_or_else(|| vec!["transfer".to_string()]);
                                let last_seen_str = if last_seen == 0 {
                                    "never".to_string()
                                } else {
                                    let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
                                    let ago = now.saturating_sub(last_seen);
                                    if ago < 60 { "just now".to_string() }
                                    else if ago < 3600 { format!("{}m ago", ago / 60) }
                                    else if ago < 86400 { format!("{}h ago", ago / 3600) }
                                    else { format!("{}d ago", ago / 86400) }
                                };
                                table.row(&[n, addr, &caps.join(", "), &last_seen_str]);
                            }
                            table.print();
                        }
                    }
                }
                Some(DevicesAction::Forget { name }) => {
                    let had = devices_load().iter().any(|(n, _)| n == &name);
                    if !had {
                        bail!("no device named '{name}', see `filament devices`");
                    }
                    devices_remove(&name)?;
                    println!("forgot '{name}', it can no longer find or auto-connect to this machine");
                    println!("(their side still holds its half; it will hear \"never met you\" on the next proof)");
                }
                Some(DevicesAction::Rename { old, new }) => {
                    // Rename in place on the raw record so caps/v2 fields ride
                    // along (remove+store dropped the renamed device's caps).
                    let p = devices_path();
                    let mut arr: Vec<Value> = std::fs::read_to_string(&p)
                        .ok()
                        .and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
                        .and_then(|v| v.as_array().cloned())
                        .unwrap_or_default();
                    if !arr.iter().any(|d| d["name"].as_str() == Some(old.as_str())) {
                        bail!("no device named '{old}', see `filament devices`");
                    }
                    if arr.iter().any(|d| d["name"].as_str() == Some(new.as_str())) {
                        bail!("'{new}' already exists, forget it first or pick another name");
                    }
                    for d in arr.iter_mut() {
                        if d["name"].as_str() == Some(old.as_str()) {
                            d["name"] = json!(new);
                        }
                    }
                    crate::platform::SecretFile::write_str(&p, &serde_json::to_string_pretty(&arr)?)?;
                    println!("renamed '{old}' -> '{new}' (local alias only, the secret, and the other side, are unchanged)");
                }
            }
            Ok(())
        }
        Cmd::Update { check, beta } => update_cmd(check, beta).await,
        Cmd::Completions { shell } => {
            use clap::CommandFactory;
            clap_complete::generate(shell, &mut Cli::command(), "filament", &mut std::io::stdout());
            Ok(())
        }
        Cmd::Man { page } => {
            if let Some(p) = page {
                if p == "routing" {
                    println!("{}", include_str!("../docs/filament-routing.md"));
                    return Ok(());
                }
                // Unknown page: print clear message instead of falling through to roff
                if std::io::stdout().is_terminal() {
                    eprintln!("no manual page '{p}'; available: routing");
                    eprintln!("try `filament man` for the full help, or `filament man routing` for the connection model.");
                } else {
                    // Piped: still emit roff for backward compatibility
                    use clap::CommandFactory;
                    clap_mangen::Man::new(Cli::command()).render(&mut std::io::stdout())?;
                }
                return Ok(());
            }
            // Bare `filament man`: readable on TTY, roff when piped
            if std::io::stdout().is_terminal() {
                use clap::CommandFactory;
                Cli::command().print_long_help()?;
            } else {
                use clap::CommandFactory;
                clap_mangen::Man::new(Cli::command()).render(&mut std::io::stdout())?;
            }
            Ok(())
        }
        Cmd::Netcat { peer, rport } => l2::netcat_cmd(&server, &peer, rport, relay).await,
        Cmd::Dial { peer, port } => l2::dial_cmd(&peer, port).await,
        Cmd::Pty { peer, cmd } => l2::pty_cmd(&server, &peer, relay, cmd).await,
        Cmd::Forward { lport, peer, rport } => l2::forward_cmd(&server, lport, &peer, rport, relay).await,
        Cmd::Expose { port, to, peer, list } => expose::expose_cmd(port, to, peer, list).await,
        Cmd::Unexpose { port } => { ui_caps.confirm("unexpose a port")?; expose::unexpose_cmd(port).await },
        Cmd::Proxy { port, bind, http_port } => l2::proxy_cmd(&server, &bind, port, http_port, relay).await,
        Cmd::Ssh { peer, args } => l2::ssh_cmd(&server, &peer, &args, relay).await,
        Cmd::Ping { peer, count, json } => ping::ping_cmd(&server, &peer, count, json, relay).await,
        Cmd::Doctor { device, watch, repeat, json } => {
            doctor::doctor_cmd(&server, device, watch, repeat, json, relay).await
        }
        Cmd::Grant { device, capability } => {
            device_set_cap(&device, &capability, true)?;
            println!(
                "granted '{capability}' to '{device}'. {}",
                if capability == "shell" {
                    "they can now `filament ssh` into this machine (their key is installed on first connect)."
                } else {
                    ""
                }
            );
            Ok(())
        }
        Cmd::Revoke { device, capability } => {
            ui_caps.confirm(&format!("revoke {capability} from {device}"))?;
            device_set_cap(&device, &capability, false)?;
            if capability == "shell" {
                sshkeys::remove_authorized_key(&device)?;
                println!("revoked 'shell' from '{device}' and removed its filament-managed authorized_keys block.");
            } else {
                println!("revoked '{capability}' from '{device}'.");
            }
            Ok(())
        }
        Cmd::Mount { peer, remote, local, read_only: _, options: _, foreground: _, save_auto, list, check, save_profile, apply_profile, profiles, delete_profile } => {
            if let Some(name) = save_profile {
                mount::save_profile_cmd(&name)
            } else if let Some(name) = apply_profile {
                mount::apply_profile_cmd(&name, &server, relay).await
            } else if profiles {
                mount::profiles_cmd()
            } else if let Some(name) = delete_profile {
                mount::delete_profile_cmd(&name)
            } else if list {
                mount::list_cmd()
            } else if let Some(path) = check {
                mount::check_cmd(&path)
            } else if peer.is_none() && remote.is_none() {
                // No arguments: interactive mode for TTY, help for machines
                if std::io::stdin().is_terminal() {
                    mount::interactive_mount_fancy(&server, relay).await
                } else {
                    mount::print_mount_help();
                    Ok(())
                }
            } else {
                let peer = peer.ok_or_else(|| anyhow::anyhow!("peer is required"))?;
                let remote = remote.ok_or_else(|| anyhow::anyhow!("remote path is required"))?;
                let _auto_restore = save_auto;
                let mut client = l2::mount_cmd(&server, &peer, relay, &remote).await?;
                if let Some(local) = local {
                    #[cfg(any(target_os = "linux", all(target_os = "macos", feature = "mount-macos"), all(target_os = "windows", feature = "mount-windows")))]
                    {
                        return mount_fuse_cmd(client, &peer, &remote, &local).await;
                    }
                    #[cfg(not(any(target_os = "linux", all(target_os = "macos", feature = "mount-macos"), all(target_os = "windows", feature = "mount-windows"))))]
                    {
                        let _ = &local;
                        ui::say(&format!(
                            "  {} mesh-native mount protocol connected to {peer}:{remote}",
                            ui::paint(ui::Tone::Ok, ui::glyph_ok())
                        ));
                        ui::say(&format!(
                            "  {} local mount adapter not available on this OS; listing directory instead",
                            ui::paint(ui::Tone::Warn, "!")
                        ));
                    }
                }
                // List the root directory
                use crate::mount_proto::MountOp;
                let root_enc = mount_proto::path_encode(std::path::Path::new("."));
                let resp = client.call(MountOp::Open { path: root_enc, flags: 0 }).await?;
                match resp.result {
                    crate::mount_proto::MountResult::Ok(v) => {
                        let fh = v["fh"].as_u64().unwrap_or(0);
                        ui::say(&format!("  {} {}", ui::paint(ui::Tone::Ok, ui::glyph_ok()), remote));
                        let entries = client.call(MountOp::ReadDir { fh, offset: 0 }).await?;
                        match entries.result {
                            crate::mount_proto::MountResult::Ok(v) => {
                                if let Some(arr) = v.as_array() {
                                    for entry in arr {
                                        let name_enc = entry["name"].as_str().unwrap_or("?");
                                        let name = mount_proto::path_decode(name_enc)
                                            .map(|p| p.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "?".into()))
                                            .unwrap_or_else(|_| "?".into());
                                        let kind = entry["stat"]["kind"].as_str().unwrap_or("file");
                                        let size = entry["stat"]["size"].as_u64().unwrap_or(0);
                                        ui::say(&format!("    {name}  ({kind}, {size}B)"));
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                    crate::mount_proto::MountResult::Err(e) => {
                        ui::say(&format!("  {} {}: {}", ui::paint(ui::Tone::Err, ui::glyph_err()), remote, e.msg));
                    }
                }
                Ok(())
            }
        }
        Cmd::Unmount { path } => { ui_caps.confirm(&format!("unmount {path}"))?; mount::unmount_cmd(&path) },
        Cmd::Backup { peer, source, dest, exclude, dry_run, delete, options } => {
            backup::backup_cmd(&server, &peer, &source, &dest, exclude, dry_run, delete, options, relay).await
        }
    }
}

// ------------------------------------------------------------------ mount --
// Mount a peer directory locally over the mesh-native mount protocol, presented
// through FUSE. Linux only for now (macOS/Windows adapters are a later round).

/// Present the connected `client` as a local FUSE mount at `local`.
///
/// Before touching the filesystem we run a connection-honesty probe: one
/// GetAttr on the mount root under a timeout. An untrusted or refused peer
/// (the acceptor replies l2-close, which EOFs the stream) surfaces here as one
/// clean pre-mount error, instead of a cryptic failure on the first `ls` after
/// the kernel has already accepted the mount. On any failure we leave no stale
/// mountpoint behind (the #22 contract).
#[cfg(any(target_os = "linux", all(target_os = "macos", feature = "mount-macos"), all(target_os = "windows", feature = "mount-windows")))]
async fn mount_fuse_cmd(
    mut client: crate::mount_proto::MountClient,
    peer: &str,
    remote: &str,
    local: &str,
) -> Result<()> {
    use crate::mount_proto::{MountOp, MountResult};

    // 1. Probe the link before we mount anything.
    let root_enc = mount_proto::path_encode(std::path::Path::new("."));
    let probe = tokio::time::timeout(
        Duration::from_secs(10),
        client.call(MountOp::GetAttr { path: root_enc }),
    )
    .await;
    match probe {
        Ok(Ok(resp)) => match resp.result {
            MountResult::Ok(_) => {}
            MountResult::Err(e) => bail!(
                "mount refused by {peer}: {} (remote path {remote})",
                e.msg
            ),
        },
        Ok(Err(e)) => bail!(
            "mount to {peer} failed before it started: {e} \
             (peer may be untrusted or the link dropped; nothing was mounted)"
        ),
        Err(_) => bail!(
            "mount to {peer} timed out waiting for the remote filesystem \
             (no response in 10s; nothing was mounted)"
        ),
    }

    // 2. Create the mountpoint. Track whether WE created it so a failed mount
    //    cleans up after itself and never leaves a stale empty dir.
    let mnt = std::path::PathBuf::from(local);
    let created_dir = !mnt.exists();
    if created_dir {
        std::fs::create_dir_all(&mnt)
            .with_context(|| format!("failed to create mount point {local}"))?;
    }

    ui::say(&format!(
        "  {} mesh-native mount: {peer}:{remote} -> {local} (FUSE, no sshd/sshfs)",
        ui::paint(ui::Tone::Ok, ui::glyph_ok())
    ));
    ui::say(&format!(
        "  {} mounted. unmount with `filament unmount {local}` or ctrl-c",
        ui::paint(ui::Tone::Ok, ui::glyph_ok())
    ));

    // 3. Run the blocking FUSE session on a dedicated thread so the tokio mux
    //    pump keeps draining the transport. ctrl-c triggers an unmount, which
    //    makes the blocking session loop return.
    let mnt_run = mnt.clone();
    #[cfg(target_os = "linux")]
    let session = tokio::task::spawn_blocking(move || crate::mount_fuse::run_mount(client, &mnt_run));
    #[cfg(all(target_os = "windows", feature = "mount-windows"))]
    let session = tokio::task::spawn_blocking(move || crate::mount_winfsp::run_mount(client, &mnt_run));

    let result: Result<()> = tokio::select! {
        joined = session => {
            match joined {
                Ok(Ok(())) => Ok(()),
                Ok(Err(e)) => Err(e),
                Err(e) => Err(anyhow::anyhow!("mount session panicked: {e}")),
            }
        }
        _ = tokio::signal::ctrl_c() => {
            ui::say("\n  unmounting...");
            let _ = unmount_fuse(local);
            Ok(())
        }
    };

    // 4. On any error, remove the mountpoint we created (leave a pre-existing
    //    dir alone). A clean unmount leaves the empty dir in place, matching the
    //    legacy behaviour.
    if result.is_err() && created_dir {
        let _ = unmount_fuse(local);
        let _ = std::fs::remove_dir(&mnt);
    }
    result
}

/// Unmount a FUSE/macFUSE mountpoint. Tries fusermount3 then fusermount on Linux,
/// falling back to a lazy unmount so a busy mount still detaches. On macOS,
/// uses umount or diskutil unmount.
#[cfg(any(target_os = "linux", all(target_os = "macos", feature = "mount-macos")))]
fn unmount_fuse(local: &str) -> std::io::Result<()> {
    #[cfg(target_os = "linux")]
    {
        for bin in ["fusermount3", "fusermount"] {
            if std::process::Command::new(bin)
                .args(["-u", local])
                .status()
                .map(|s| s.success())
                .unwrap_or(false)
            {
                return Ok(());
            }
        }
        // Linux last resort: lazy unmount so a busy handle does not wedge teardown.
        let _ = std::process::Command::new("fusermount3")
            .args(["-uz", local])
            .status();
    }
    #[cfg(target_os = "macos")]
    {
        // Try diskutil first (more reliable for macFUSE), fall back to umount.
        if std::process::Command::new("diskutil")
            .args(["unmount", "force", local])
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
        {
            return Ok(());
        }
        let _ = std::process::Command::new("umount")
            .args([local])
            .status();
    }
    Ok(())
}

/// Windows: WinFsp handles unmount through its own control path; this is a no-op
/// placeholder so the Linux/macOS cleanup flow compiles on Windows.
#[cfg(all(target_os = "windows", feature = "mount-windows"))]
fn unmount_fuse(_local: &str) -> std::io::Result<()> {
    Ok(())
}

// ----------------------------------------------------------------- update --
// Self-update against GitHub releases (tags cli-vX.Y.Z). Downloads the
// archive for this platform, verifies it against SHA256SUMS, and atomically
// replaces the current executable.

const REPO: &str = "Abdk4Moura/filament";

fn release_target() -> Option<&'static str> {
    match (std::env::consts::OS, std::env::consts::ARCH) {
        ("linux", "x86_64") => Some("x86_64-unknown-linux-musl"),
        ("macos", "aarch64") => Some("aarch64-apple-darwin"),
        ("macos", "x86_64") => Some("x86_64-apple-darwin"),
        ("windows", "x86_64") => Some("x86_64-pc-windows-msvc"),
        _ => None,
    }
}

async fn update_cmd(check_only: bool, beta: bool) -> Result<()> {
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(60))
        .user_agent(format!("filament/{}", env!("CARGO_PKG_VERSION")))
        .build()?;

    // Latest cli-v* release via the API (releases/latest may point at a web
    // release tag, so filter explicitly). Prereleases are SKIPPED unless the
    // user opted in (--beta) or is already running a prerelease, a beta tag
    // must never be pushed onto stable users.
    let beta_ok = beta || env!("CARGO_PKG_VERSION").contains('-');
    let releases: Value = client
        .get(format!("https://api.github.com/repos/{REPO}/releases?per_page=20"))
        .send()
        .await?
        .json()
        .await?;
    // semver-aware: never "update" to an older or equal release (betas of
    // the next version outrank the previous release; -pre < its release;
    // beta.2 > beta.1, the prerelease NUMBER counts, found live when
    // `--beta` kept offering beta.1 to beta.2).
    fn key(v: &str) -> (u64, u64, u64, bool, u64) {
        let (core, pre) = v.split_once('-').map(|(c, p)| (c, Some(p))).unwrap_or((v, None));
        let mut it = core.split('.').map(|p| p.parse::<u64>().unwrap_or(0));
        let pre_num = pre.and_then(|p| p.rsplit('.').next()).and_then(|n| n.parse().ok()).unwrap_or(0);
        (it.next().unwrap_or(0), it.next().unwrap_or(0), it.next().unwrap_or(0), pre.is_none(), pre_num)
    }
    // Pick the HIGHEST eligible version, not the first listed, the API's
    // order is not newest-tag-first (observed live: cli-v0.2.0 listed above
    // cli-v0.2.1-beta.1, which made --beta serve stable).
    let latest = releases
        .as_array()
        .and_then(|a| {
            a.iter()
                .filter(|r| {
                    r["tag_name"].as_str().is_some_and(|t| t.starts_with("cli-v"))
                        && (beta_ok || !r["prerelease"].as_bool().unwrap_or(false))
                })
                .max_by_key(|r| key(r["tag_name"].as_str().unwrap_or_default().trim_start_matches("cli-v")))
        })
        .ok_or_else(|| anyhow!("no CLI release found"))?;
    let tag = latest["tag_name"].as_str().unwrap_or_default().to_string();
    let latest_ver = tag.trim_start_matches("cli-v").to_string();
    let current = env!("CARGO_PKG_VERSION");
    if key(&latest_ver) <= key(current) {
        println!("filament {current} is already the latest (released: {latest_ver})");
        return Ok(());
    }
    println!("update available: {current} -> {latest_ver}");
    if check_only {
        return Ok(());
    }

    // Package-manager installs (brew, winget, scoop, cargo) must be updated
    // via their manager, not by writing over the binary.
    let source = platform::InstallSource::detect();
    if source != platform::InstallSource::SelfInstalled {
        let hint = source.upgrade_hint();
        println!("filament was installed via a package manager — update with: {hint}");
        return Ok(());
    }

    let target = release_target().ok_or_else(|| anyhow!("no prebuilt binary for this platform; build from source"))?;
    let (asset, inner) = if cfg!(windows) {
        (format!("filament-{target}.zip"), "filament.exe")
    } else {
        (format!("filament-{target}.tar.gz"), "filament")
    };
    let base = format!("https://github.com/{REPO}/releases/download/{tag}");

    ui::say(&format!("downloading {asset} ..."));
    let bytes = client.get(format!("{base}/{asset}")).send().await?.error_for_status()?.bytes().await?;
    let sums = client.get(format!("{base}/SHA256SUMS")).send().await?.error_for_status()?.text().await?;
    let got = sha256_hex(&bytes);
    let expected = sums
        .lines()
        .find(|l| l.contains(&asset))
        .and_then(|l| l.split_whitespace().next())
        .ok_or_else(|| anyhow!("{asset} missing from SHA256SUMS"))?;
    if got != expected {
        bail!("checksum mismatch for {asset}: got {got}, expected {expected}");
    }
    ui::say("checksum ok");

    // Unpack the single binary.
    let new_bin: Vec<u8> = if asset.ends_with(".tar.gz") {
        let gz = flate2::read::GzDecoder::new(std::io::Cursor::new(&bytes[..]));
        let mut ar = tar::Archive::new(gz);
        let mut out = None;
        for entry in ar.entries()? {
            let mut e = entry?;
            if e.path()?.file_name().map(|n| n == inner).unwrap_or(false) {
                let mut v = Vec::new();
                e.read_to_end(&mut v)?;
                out = Some(v);
                break;
            }
        }
        out.ok_or_else(|| anyhow!("{inner} not found in archive"))?
    } else {
        // Windows: unpack the .zip archive. Use the zip crate for a pure-Rust
        // reader (no system dependency on tar/powershell).
        use std::io::Read;
        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(&bytes))
            .map_err(|e| anyhow!("zip reader: {e}"))?;
        let mut found = None;
        for i in 0..archive.len() {
            let mut entry = archive
                .by_index(i)
                .map_err(|e| anyhow!("zip entry {i}: {e}"))?;
            if entry.name().ends_with(inner) {
                let mut v = Vec::new();
                entry.read_to_end(&mut v)?;
                found = Some(v);
                break;
            }
        }
        found.ok_or_else(|| anyhow!("{inner} not found in zip archive"))?
    };

    // Atomic replace: write staging file next to current exe, then swap.
    let me = std::env::current_exe()?;
    let staging = me.with_extension("update-staging");
    std::fs::write(&staging, &new_bin)?;
    // Preserve any CAP_NET_ADMIN grant across the update (Linux only).
    #[cfg(target_os = "linux")]
    let had_cap = std::process::Command::new("getcap")
        .arg(&me)
        .output()
        .ok()
        .map(|o| String::from_utf8_lossy(&o.stdout).contains("cap_net_admin"))
        .unwrap_or(false);
    // On Unix, rename over the running binary (the kernel keeps the old inode
    // alive for the running process). On Windows, rename the running exe out of
    // the way first (MoveFile on the same volume succeeds even on an in-use .exe),
    // then put the new binary in place. The .old file is cleaned up on next update.
    #[cfg(windows)]
    {
        let old = me.with_extension("old");
        let _ = std::fs::remove_file(&old);
        std::fs::rename(&me, &old)
            .with_context(|| format!("renaming {} -> {}", me.display(), old.display()))?;
        std::fs::rename(&staging, &me)
            .with_context(|| format!("installing new {}", me.display()))?;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&staging, std::fs::Permissions::from_mode(0o755))?;
        std::fs::rename(&staging, &me)
            .with_context(|| format!("replacing {}", me.display()))?;
    }
    println!("updated to {latest_ver} -> {}", me.display());
    #[cfg(target_os = "linux")]
    if had_cap {
        // Re-grant: directly if root, else via sudo (interactive on a TTY). If it
        // can't, tell the user the one command so L3 isn't silently broken.
        let is_root = unsafe { libc::geteuid() } == 0;
        let ok = if is_root {
            std::process::Command::new("setcap").args(["cap_net_admin+eip"]).arg(&me).status().map(|s| s.success()).unwrap_or(false)
        } else {
            std::process::Command::new("sudo").args(["setcap", "cap_net_admin+eip"]).arg(&me).status().map(|s| s.success()).unwrap_or(false)
        };
        if ok {
            println!("re-applied CAP_NET_ADMIN (L3 overlay)");
        } else {
            println!("note: re-grant L3's capability:\n    sudo setcap cap_net_admin+eip {}", me.display());
        }
        // A non-root L3 node also needs write on /etc/hosts to publish MagicDNS
        // names; grant the narrow per-file ACL here too so a plain `filament
        // update` is all it takes (no separate `set tun-addr` step). No-op for
        // root or if already granted.
        crate::tun::ensure_hosts_writable();
    }
    // Reload a running daemon onto the new binary with no manual restart. A
    // supervised daemon (systemd) takes the graceful SIGTERM path - which cleanly
    // closes the QUIC links so peers re-establish and L3 recovers - and its
    // supervisor restarts it with fresh ambient caps: no sudo. If it isn't
    // supervised (or predates this op), tell the user to restart it.
    #[cfg(unix)]
    {
        let reloading = matches!(ctl::try_reload().await, Some(ref v) if v["reloading"].as_bool() == Some(true));
        if reloading {
            println!("reloading the daemon onto the new binary (graceful restart, no sudo)");
        } else if daemon_alive().is_some() {
            println!("restart the daemon to run the new binary: `systemctl restart filament` (or `filament down` then `filament up ...`)");
        }
    }
    Ok(())
}

// ------------------------------------------------------------------- send --

struct Outgoing {
    id: String,
    sid: u32,
    name: String,
    size: u64,
    head: Option<String>,
    /// P4 (GAP-5): sha256 of the WHOLE file, carried in file-offer as `full`. The
    /// receiver compares its received bytes against this on completion and only
    /// accepts (and acks) on a match, so no transfer can "complete" truncated or
    /// corrupt. `None` only when the digest couldn't be computed (degrades to the
    /// legacy size-only check on the receiver, bounded, never a hang).
    full: Option<String>,
    path: PathBuf,
    temp: bool,          // delete after sending (tar spools, stdin spools)
    accepted_once: bool, // re-offers carry resume:true after first accept
    /// P4: the bytes left this side (stream finished / file-end sent). NOT the
    /// same as `done`: a transfer is `sent` once but is only `done` after the
    /// receiver's whole-file-verified `delivery-ack` lands (the no-ack window
    /// NEVER sets `done`, it re-probes then fails the send, silent-data-loss fix).
    sent: bool,
    /// P4: the receiver returned a verified `delivery-ack` for this id. This is
    /// the deterministic "it landed intact" signal, the ONLY thing that completes
    /// a send. (Exception: an un-hashable file with no `full` digest has nothing
    /// to verify-and-ack, so it is `done` on send, the legacy size-only path.)
    acked: bool,
    done: bool,
}

#[allow(clippy::too_many_arguments)]
async fn send_cmd(
    server: &str,
    paths: Vec<String>,
    mut use_code: bool,
    mut word: Option<String>,
    room: Option<String>,
    mut to: Option<String>,
    name: Option<String>,
    relay: bool,
    remember: Option<String>,
) -> Result<()> {
    if paths.is_empty() {
        bail!("nothing to send, pass files, directories, or '-' for stdin");
    }
    // INTERACTIVE GATE: `send <files>` with no --code/--word/--to and not piping
    // from stdin. First offer to pick a PAIRED DEVICE (arrow-key list); the last
    // item / Esc drops to the code path: Enter = local network, typed words mint a
    // shareable code. Skipped when reading payload from stdin ('-').
    if !use_code && to.is_none() && !paths.iter().any(|p| p == "-") && interactive_allowed() {
        let names: Vec<String> = devices_load().into_iter().map(|(n, _)| n).collect();
        let mut chose_device = false;
        if !names.is_empty() {
            let mut items = names.clone();
            items.push("shareable code / local network".into());
            let header = ui::paint(ui::Tone::Dim, "  send to which device?  (up/down, enter, esc)");
            if let Some(i) = codeentry::pick(&header, &items)? {
                if i < names.len() {
                    ui::say(&format!("  {} sending to {}", ui::paint(ui::Tone::Ok, ui::glyph_ok()), names[i]));
                    to = Some(names[i].clone());
                    chose_device = true;
                }
            }
        }
        if !chose_device {
            ui::say(&ui::paint(
                ui::Tone::Dim,
                "  press enter to send over the local network, or type words to create a shareable code",
            ));
            let auto_np = crate::pake::words::mint_nameplate();
            match codeentry::run("  send · code  ", codeentry::Mode::Create, "", &auto_np)? {
                codeentry::Outcome::Submitted(words) => {
                    use_code = true;
                    word = Some(words);
                }
                codeentry::Outcome::Empty => { /* fall through to local-network send */ }
                codeentry::Outcome::Cancelled => return Err(cancelled()),
            }
        }
    }
    // --name overrides the offered name, but only makes sense for a SINGLE
    // payload (stdin, or one regular file). With multiple paths or a directory
    // there is no single name to override, so warn that it's ignored.
    if name.is_some() && paths.len() > 1 {
        ui::say(&ui::paint(ui::Tone::Warn, "--name is ignored when sending multiple paths"));
    }
    let single = paths.len() == 1;
    let my_uid = mk_uid("s");
    let mut outgoing: Vec<Outgoing> = Vec::new();
    for (i, p) in paths.iter().enumerate() {
        let sid = (i + 1) as u32;
        let id = format!("{}-{}", my_uid, sid);
        if p == "-" {
            let spool = std::env::temp_dir().join(format!("filament-stdin-{}", std::process::id()));
            let mut f = std::fs::File::create(&spool)?;
            let n = std::io::copy(&mut std::io::stdin().lock(), &mut f)?;
            drop(f);
            let head = head_hash(&spool);
            let full = full_hash(&spool);
            let offered = name.clone().filter(|_| single).unwrap_or_else(|| "stdin.bin".into());
            outgoing.push(Outgoing { id, sid, name: offered, size: n, head, full, path: spool, temp: true, accepted_once: false, sent: false, acked: false, done: false });
        } else {
            let path = PathBuf::from(p);
            let meta = std::fs::metadata(&path).with_context(|| format!("stat {p}"))?;
            if meta.is_dir() {
                if name.is_some() && single {
                    ui::say(&ui::paint(ui::Tone::Warn, "--name is ignored for a directory (it's tarred under the directory name)"));
                }
                let dirname = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "dir".into());
                let spool = std::env::temp_dir().join(format!("filament-tar-{}-{}.tar", std::process::id(), i));
                ui::say(&format!("packing {p} -> {dirname}.tar ..."));
                {
                    let f = std::fs::File::create(&spool)?;
                    let mut b = tar::Builder::new(f);
                    b.append_dir_all(&dirname, &path)?;
                    b.finish()?;
                }
                let size = std::fs::metadata(&spool)?.len();
                let head = head_hash(&spool);
                let full = full_hash(&spool);
                outgoing.push(Outgoing { id, sid, name: format!("{dirname}.tar"), size, head, full, path: spool, temp: true, accepted_once: false, sent: false, acked: false, done: false });
            } else {
                // A single regular file with --name uses the override; otherwise
                // the basename. With multiple files --name was already warned off.
                let offered = name.clone().filter(|_| single).unwrap_or_else(|| {
                    path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.clone())
                });
                let head = head_hash(&path);
                let full = full_hash(&path);
                outgoing.push(Outgoing { id, sid, name: offered, size: meta.len(), head, full, path, temp: false, accepted_once: false, sent: false, acked: false, done: false });
            }
        }
    }
    for o in &outgoing {
        ui::say(&format!("send: {} ({})", o.name, human(o.size)));
    }

    let room = match room {
        Some(r) => r,
        None => net::fetch_auto_room(server).await?,
    };
    let (tx, mut rx) = mpsc::unbounded_channel::<Ev>();
    let sio = net::connect_signaling(server, tx.clone()).await?;
    // C30: the convergent session repairs room/channel/lease state the
    // one-shot emits lose (the fast path stays for old servers + latency);
    // under gate L these initial emits are exactly what the shim drops.
    let mut sess = session::Session::new(&display_name(), &my_uid);
    sess.room = Some(room.clone());
    sess.emit(&sio, "join", json!({ "room": room, "name": display_name(), "uid": my_uid })).await;

    // C12: --to matching a remembered device switches to identity mode,
    // subscribe to its presence channel and wait for known-peer.
    let known_target: Option<(String, String)> =
        to.as_ref().and_then(|t| devices_load().into_iter().find(|(n, _)| n.eq_ignore_ascii_case(t)));
    // L1-a: `send --code` now mints a v2 nameplate (client-minted words, the
    // server allocates ONLY the numeric nameplate) and runs the SAME ephemeral
    // SPAKE2 ceremony as `pair` before any byte flows, then DISCARDS the secret
    // (transfer = "link with mutual auth, then forget"). The words NEVER cross
    // the server; only the nameplate does. The full `words-nameplate` code is
    // displayed from our own local mint when pair-ok arrives.
    let mut send_words = String::new(); // the SPAKE2 password (only when use_code)
    let mut send_nameplate = String::new();
    if let Some((n, sec)) = &known_target {
        ui::say(&format!("  waiting for known device {}", ui::paint(ui::Tone::Bold, n)));
        sess.channels = vec![channel_of(sec)];
        sess.emit(&sio, "subscribe", json!({ "channels": [channel_of(sec)] })).await;
    } else if use_code {
        // The words are the user's chosen phrase (--word) or a fresh mint; the
        // nameplate is ALWAYS machine-minted. `split_chosen_code` keeps both
        // words of a two-word phrase (it only strips a trailing 3-5 digit group).
        send_words = match &word {
            Some(w) => {
                let (words, _np) =
                    crate::pake::split_chosen_code(&crate::pake::norm_code(w));
                if password_word_tokens(&words) < 2 {
                    bail!(
                        "'{w}' is too weak. Use at least two words, e.g. gigantic-element \
                         (easier to say, harder to guess). A single word falls below the \
                         strength floor the rate-limit relies on."
                    );
                }
                words
            }
            None => crate::pake::words::mint_words(),
        };
        send_nameplate = crate::pake::words::mint_nameplate();
        sio.emit("pair-create", json!({ "nameplate": send_nameplate, "v": 2 })).await.ok();
    } else {
        ui::say(&format!("waiting for a peer in room {room} (same network auto-discovers; or use --code)"));
    }
    // Live spinner while nothing is connected yet (tty only; stops at adopt).
    let waiting = Arc::new(std::sync::atomic::AtomicBool::new(true));
    {
        let waiting = waiting.clone();
        tokio::spawn(async move {
            while waiting.load(std::sync::atomic::Ordering::Relaxed) {
                ui::status(&format!("  {} waiting...", ui::spinner_frame()));
                tokio::time::sleep(Duration::from_millis(120)).await;
            }
        });
    }

    let mut conn = Conn::for_command(
        server,
        sio.clone(),
        tx.clone(),
        my_uid,
        relay,        // relay_only
        to,           // to_filter
        false,        // warm_standby default (one-shot send)
        direct::direct_enabled(), // direct_ok: env gate only (file transfer keeps WebRTC default)
    );
    if known_target.is_some() {
        conn.to_filter = None; // identity supersedes name matching
    }
    let mut code_used = !use_code && known_target.is_none();
    // L1-a ephemeral PAKE on the transfer path. When `--code` is used, run the
    // SAME SPAKE2 ceremony `pair` runs, then DISCARD the secret (auth only). The
    // file-offers are GATED on the ceremony agreeing a secret (`pake_done`); a
    // local-network send (no code) and a known-device send (already proven via
    // channel_of/proof_for) keep the existing, unchanged path (`pake_done` set
    // true up front so they offer immediately). `send_cer` is the ceremony; it
    // is only ever populated on the code path.
    let mut send_cer: Option<Ceremony> = if use_code {
        Some(Ceremony::new(&send_words, &send_nameplate, pair_v2_caps()))
    } else {
        None
    };
    let mut pake_peer: Option<String> = None;
    // The transfer is allowed to offer once auth is settled: immediately for
    // local / known-device sends; only after the ephemeral PAKE confirms for the
    // code path. The agreed secret is then DISCARDED (never stored).
    let mut pake_done = !use_code;
    // Interop / downgrade: a code-path peer that never runs the v2 ceremony is on
    // an older build. Once the channel is up, give the ceremony a bounded budget;
    // if it doesn't confirm, fail LOUDLY ("update to transfer securely") rather
    // than hang. Mirrors `pair`'s ceremony_deadline.
    let pake_budget = Duration::from_secs(
        std::env::var("FILAMENT_PAIR_GRACE_SECS").ok().and_then(|v| v.parse().ok()).unwrap_or(60),
    );
    let mut pake_deadline: Option<Instant> = None;
    // C30 phase 3: link mini-sync, pings out, divergence corrections in.
    let mut last_state_ping = Instant::now();
    let mut reproved: std::collections::HashSet<String> = Default::default();
    {
        let tx = tx.clone();
        tokio::spawn(async move {
            let _ = tokio::signal::ctrl_c().await;
            // Bounded force-exit guarantee (see the acceptor path): Ctrl-C must
            // exit promptly even if the unwind/peer-drop deadlocks.
            shutdown::arm_force_exit(130, shutdown::grace());
            let _ = tx.send(Ev::Interrupted);
        });
    }
    let outgoing = Arc::new(tokio::sync::Mutex::new(outgoing));
    let started = Instant::now();
    let claim_deadline = Duration::from_secs(600);
    // Bug 6: bound ESTABLISHMENT. netcat/ssh cap how long they hunt for a peer;
    // `send` had no such bound, so an ICE wedge (no candidate pair ever
    // nominates) hung unbounded with the spinner spinning. Cap the time to the
    // FIRST live data channel (ChannelReady); once a channel is up, a long
    // legitimate transfer is never interrupted by this. Overridable / disablable
    // (0 = off) via FILAMENT_SEND_TIMEOUT.
    let establish_deadline = std::env::var("FILAMENT_SEND_TIMEOUT")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .map(Duration::from_secs)
        .unwrap_or(Duration::from_secs(60));
    let mut established = false;
    // Bug 5: count stuck-while-connecting events to hint at the mDNS wedge once.
    let mut stuck_while_connecting = 0u32;
    let mut wedge_hint_shown = false;
    let mut saw_known_peer: HashSet<String> = HashSet::new();
    // P4 (delivery-ack window): when every transfer's bytes have been `sent` but
    // the whole-file `delivery-ack` hasn't landed, we wait up to this bound for
    // the ack. CRITICAL (silent-data-loss fix): elapsing this window does NOT mean
    // "declare done". The bytes draining out of the send buffer proves nothing, a
    // path that black-holes without QUIC noticing drains while NOTHING arrives and
    // no ack comes. So on no-ack we re-probe once (re-send file-end to prompt a
    // possibly-lost ack), and if the ack still never lands we FAIL the send
    // (nonzero, partial kept resumable), never a false "delivered + verified".
    // Overridable via FILAMENT_ACK_TIMEOUT (seconds). The never-hangs property
    // holds: we reach a terminal state in bounded time, just an honest one.
    let ack_wait = std::env::var("FILAMENT_ACK_TIMEOUT")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .map(Duration::from_secs)
        .unwrap_or(Duration::from_secs(15));
    // After the first window with no ack we re-send file-end and wait this much
    // longer for a (possibly lost) ack before giving up. Short: the ack is a tiny
    // control message, on a healthy link it returns within a round-trip.
    let ack_reprobe = Duration::from_secs(5);
    let mut sent_all_at: Option<Instant> = None;
    let mut ack_reprobed = false; // re-sent file-end once for the no-ack window?
    let mut reprobed_at: Option<Instant> = None;

    loop {
        // Bug 6: no data channel has come up within the establishment window,
        // an ICE wedge or a peer that claimed the code but never connected. Fail
        // honestly instead of spinning forever. A non-zero deadline only; a live
        // channel (established) disarms it so big transfers are never cut off.
        if !established
            && !establish_deadline.is_zero()
            && started.elapsed() >= establish_deadline
        {
            ui::clear_sticky();
            bail!(
                "no peer connected within {}s, is a receiver running / the page open? \
                 (set FILAMENT_SEND_TIMEOUT to change or 0 to disable)",
                establish_deadline.as_secs()
            );
        }
        // The wait-for-peer deadline only applies while we have no peer (F3).
        let ev = if conn.active.is_none() && conn.rejoin.waiting_rejoin.is_none() {
            // C30: read in ≤2s slices, a blocking full-deadline read starves
            // the session tick, so a dropped initial subscribe was never
            // repaired and the wait could NEVER succeed (found by gate L's
            // seed-16 choreography: the daemon healed, the sender starved).
            if started.elapsed() >= claim_deadline {
                bail!("timed out waiting for a peer, is the other device online and on the same server? (--code makes pairing explicit)");
            }
            let slice = Duration::from_secs(2).min(claim_deadline.saturating_sub(started.elapsed()));
            match tokio::time::timeout(slice, rx.recv()).await {
                Ok(Some(ev)) => Some(ev),
                Ok(None) => bail!("signaling channel closed"),
                Err(_) => None, // tick
            }
        } else {
            next_ev(&mut rx, &conn, false).await?
        };
        // C30: converge session state every iteration (incl. ticks).
        sess.tick(&sio).await;
        // #28: discharge any deferred peer-left whose channel has gone idle/dead.
        conn.reap_deferred();
        // L1-a ephemeral PAKE progression (code path only). Once the link to our
        // PAKE counterpart is up: send our SPAKE2 element, then (once K + both
        // DTLS fingerprints exist) the key-confirmation MAC. The secret is
        // DISCARDED after auth (`pake_done`), never stored.
        if let (Some(cer), Some(pid)) = (send_cer.as_mut(), pake_peer.clone()) {
            if let Some(data) = cer.take_msg_payload() {
                sio.emit("signal", json!({ "to": pid, "data": data })).await.ok();
            }
            if cer.has_k() {
                if let Some(l) = conn.link(&pid) {
                    if let Some((my_fp, their_fp)) = match &l.peer { Some(p) => p.fingerprints().await, None => None } {
                        if let Some(data) = cer.take_confirm_payload(&my_fp, &their_fp) {
                            sio.emit("signal", json!({ "to": pid, "data": data })).await.ok();
                        }
                    }
                }
            }
        }
        // Interop / downgrade: the ephemeral ceremony must confirm within budget
        // once the channel is up, a peer that never runs it is an older build.
        if !pake_done {
            if let Some(dl) = pake_deadline {
                if Instant::now() > dl {
                    ui::clear_sticky();
                    bail!("the other device uses an older version and can't receive securely over a code. Update it (or this CLI) so the transfer runs the encrypted handshake. Nothing was sent.");
                }
            }
        }
        // rung-1: a direct attempt that timed out without an authenticated QUIC
        // connection falls back to the WebRTC establish (unchanged path).
        for (pid, info, (n, sec)) in conn.expired_direct() {
            conn.establish(info).await?;
            if let Some(l) = conn.link_mut(&pid) {
                l.expected_secret = Some((n, sec));
            }
            if conn.to_filter.is_none() && conn.active.is_none() {
                conn.active = Some(pid.clone());
            }
        }
        // C30 phase 3: tell every link our truth every ~10s (sender side has
        // no receive-partials; the ping mainly carries trusted/away and keeps
        // the peer's away-mark honest).
        if last_state_ping.elapsed() >= Duration::from_secs(10) {
            last_state_ping = Instant::now();
            for l in conn.links.values() {
                if let Some(t) = &l.transport {
                    let _ = t
                        .send_control(&json!({
                            "type": "state", "v": 1,
                            "transfers": {},
                            "trusted": l.trusted,
                            "away": false,
                        }))
                        .await;
                }
            }
        }
        // P0 (GAP-1): bytes-moved STALL watchdog (send side). A transfer is in
        // flight once the active peer accepted an offer that isn't done; if that
        // link then moves zero bytes past the stall threshold (a black-holed data
        // path, the 0% hang) we emit Ev::TransferStalled, which drives the
        // correction ladder below. The control-channel liveness probe gates it so
        // a genuinely DEAD link falls to the C3/C4 path instead.
        if let Some(active) = conn.active.clone() {
            let in_flight = {
                let out = outgoing.lock().await;
                out.iter().any(|o| o.accepted_once && !o.sent)
            };
            if let Some(idle) = conn.detect_stall(&active, in_flight) {
                if conn.link_alive(&active).await {
                    let _ = tx.send(Ev::TransferStalled(active, idle));
                } else {
                    // Control path also dead → not a data-only stall; let the
                    // establishment watchdog (C3/C4) own it. Clear the episode.
                    conn.note_progress(&active);
                }
            }
        }
        // P5 (GAP-6): relay->direct upgrade prober (send side). Probe for a direct
        // path while serving on relay; verify-before-upgrade cuts over only when a
        // direct standby is confirmed stable. No-op unless a peer is relay-committed
        // on an eligible session.
        conn.tick_upgrade_prober().await;
        let Some(ev) = ev else { continue };

        match ev {
            Ev::Welcome(v) => {
                conn.my_id = v["id"].as_str().unwrap_or_default().to_string();
                // P5 (GAP-6): a fresh signaling welcome (reconnect) is a moment a
                // new direct path may have appeared, re-probe immediately for any
                // relay-committed peer rather than waiting out the backoff.
                conn.reprobe_on_network_event();
                if let Some(peers) = v["peers"].as_array() {
                    for p in peers {
                        conn.maybe_adopt(p, code_used).await?;
                    }
                }
                // C30 (dissolves the C28 belt): fresh sid = everything
                // sid-keyed is gone; invalidate and let the session re-assert.
                sess.invalidate();
            }
            // C30: server confirmed our session digest.
            Ev::Synced(v) => { sess.on_synced(&v); }
            // L1-a: the server allocated our v2 nameplate. Display the FULL
            // `words-nameplate` code assembled from OUR OWN local mint (the
            // server never echoes any words). The receiver runs the SAME
            // ephemeral SPAKE2 ceremony before any byte flows.
            Ev::PairOk(v) => {
                let ttl = v["ttl"].as_u64().unwrap_or(600);
                let full = format!("{send_words}-{send_nameplate}");
                let site = if server == DEFAULT_SERVER { "https://filament.autumated.com".to_string() } else { server.to_string() };
                ui::clipboard(&full);
                ui::say("");
                ui::say(&format!("  code   {}   {}", ui::paint(ui::Tone::Brand, &full), ui::paint(ui::Tone::Dim, "(copied to clipboard)")));
                ui::say(&format!("         {}", ui::paint(ui::Tone::Dim, &format!("terminal: filament recv {full}   browser: {} (RECEIVE WITH CODE)", ui::link(&site, &site.replace("https://", ""))))));
                ui::say(&format!("         {}", ui::paint(ui::Tone::Dim, &format!("one claim · expires in {} min · authenticated end-to-end (no key crosses the server)", ttl / 60))));
                ui::say("");
            }
            // A legacy server (or a v2-stripping one) minted a whole code: it
            // can't run the secure ceremony. Refuse rather than fall back to an
            // unauthenticated transfer (mirrors `pair`'s downgrade-refusal).
            Ev::PairCode(_v) => {
                bail!("this server returned a legacy transfer code and can't authenticate the transfer. Update the server (or the peer) to transfer securely.");
            }
            Ev::PairError(v) => {
                // Nameplate collision on create: re-mint a FRESH nameplate (and
                // fresh words when we minted them) and retry, never reuse a
                // burned code. The ephemeral ceremony restarts with the new pair.
                if use_code && v["error"].as_str() == Some("taken") {
                    if word.is_none() {
                        send_words = crate::pake::words::mint_words();
                    }
                    send_nameplate = crate::pake::words::mint_nameplate();
                    if let Some(cer) = send_cer.as_mut() {
                        cer.restart(&send_words, &send_nameplate);
                    }
                    sio.emit("pair-create", json!({ "nameplate": send_nameplate, "v": 2 })).await.ok();
                    continue;
                }
                bail!("pairing failed: {}", v["error"].as_str().unwrap_or("?"));
            }
            Ev::PairUsed(_) => {
                ui::say("code claimed, connecting...");
                code_used = true;
            }
            Ev::PeerJoined(v) => {
                conn.maybe_adopt(&v, code_used).await?;
            }
            Ev::KnownPeer(v) => {
                if is_self_uid(&conn.my_uid, v["uid"].as_str()) {
                    continue; // our own daemon shares this channel
                }
                if let Some((n, sec)) = &known_target {
                    if v["channel"].as_str() == Some(channel_of(sec).as_str()) {
                        let pid = v["id"].as_str().unwrap_or_default().to_string();
                        // Liveness-aware: skip only if a healthy link already exists.
                        // If the link is dead or absent, re-establish (reconnect-after-loss).
                        let link_alive = conn.link(&pid)
                            .and_then(|l| l.transport.as_ref())
                            .map(|t| !t.is_dead())
                            .unwrap_or(false);
                        if link_alive {
                            if !saw_known_peer.contains(n) {
                                saw_known_peer.insert(n.clone());
                            }
                            continue;
                        }
                        if !saw_known_peer.contains(n) {
                            ui::say(&format!("known device '{n}' is online, connecting"));
                        }
                        saw_known_peer.insert(n.clone());
                        // rung-1: both ends are CLIs (known device), try direct
                        // QUIC FIRST. start_direct records the pending so the
                        // maybe_adopt->establish below skips the WebRTC offer
                        // until the budget expires (then it falls back).
                        let (n, sec) = (n.clone(), sec.clone());
                        conn.start_direct(&pid, &n, &sec).await;
                        conn.maybe_adopt(&v, true).await?;
                        if let Some(l) = conn.link_mut(&pid) {
                            l.expected_secret = Some((n.clone(), sec.clone()));
                        }
                    }
                }
            }
            Ev::Signal(v) => {
                let from = v["from"].as_str().unwrap_or_default().to_string();
                let data = v["data"].clone();
                // rung-1: a relayed transport-offer carries the peer's direct
                // candidates, kick off the simultaneous-open + auth race.
                if data["type"].as_str() == Some("transport-offer") {
                    let cands: Vec<String> = data["addrs"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect())
                        .unwrap_or_default();
                    // rung-2: optional server-reflexive candidate for hole-punch.
                    let srflx = data["srflx"].as_str().map(String::from);
                    // P5 (GAP-6): a `probe:true` offer is a relay->direct UPGRADE
                    // probe from the other end. If we're serving this peer on relay
                    // and have no probe of our own yet, ARM one so the symmetric
                    // direct dial can complete (a later re-send of the offer, the
                    // peer re-emits 6x, is consumed by our now-armed pending). The
                    // winner posts DirectUpgradeReady (verify-before-upgrade), never
                    // clobbering the serving relay link.
                    if data["probe"].as_bool() == Some(true) {
                        conn.answer_upgrade_probe(&from).await;
                    }
                    conn.on_transport_offer(&from, cands, srflx);
                    continue;
                }
                // L1-a: PAKE messages ride the opaque `signal` relay. Route them
                // OUT of the WebRTC path into the ephemeral ceremony (code path).
                // On confirm the secret is agreed; we record auth done and then
                // DISCARD the secret (transfer never persists it).
                if matches!(data["type"].as_str(), Some("pake-msg") | Some("pake-confirm")) {
                    if let Some(cer) = send_cer.as_mut() {
                        pake_peer.get_or_insert(from.clone());
                        let fps = match conn.link(&from) {
                            Some(l) => match &l.peer { Some(p) => p.fingerprints().await, None => None },
                            None => None,
                        };
                        let fp_ref = fps.as_ref().map(|(a, b)| (a.as_str(), b.as_str()));
                        match cer.on_signal(&data, fp_ref) {
                            PakeInbound::Consumed => {
                                if cer.secret().is_some() && !pake_done {
                                    // Authenticated. DISCARD the secret (auth only).
                                    pake_done = true;
                                    ui::say(&ui::paint(ui::Tone::Dim, "  authenticated, sending"));
                                    // --remember on the code path: hand over a FRESH
                                    // long-lived pair secret only NOW, after the link
                                    // is mutually authenticated (not the pre-PAKE
                                    // channel). A SEPARATE explicit trust grant, not
                                    // the ephemeral transfer secret (which is discarded).
                                    if let (Some(name), Some(t)) = (&remember, conn.transport_of(&from)) {
                                        let sec = fresh_secret();
                                        let _ = t.send_control(&json!({ "type": "pair-keep", "secret": sec })).await;
                                        devices_store(name, &sec)?;
                                        ui::say(&format!("remembered this device as '{name}' (they must also pass --remember)"));
                                    }
                                    // Re-drive the canonical offer path for this peer by
                                    // re-emitting ChannelReady (now that pake_done gates
                                    // it open), reuses the proven offer/resume logic.
                                    if let Some(t) = conn.transport_of(&from) {
                                        let _ = tx.send(Ev::ChannelReady(from.clone(), t));
                                    }
                                }
                            }
                            PakeInbound::Abort(why) => {
                                ui::clear_sticky();
                                bail!("transfer REFUSED: {why}. Nothing was sent; ask for a FRESH code.");
                            }
                            PakeInbound::Ignored => {}
                        }
                        continue;
                    }
                }
                // C18: an offer from an unlinked roster peer creates a polite
                // responder link (browsers mesh-dial everyone, fix #7 rules).
                conn.ensure_responder(&from, &data).await?;
                conn.apply_signal(&from, data).await;
            }
            // rung-1: the authenticated direct-QUIC connection won the race.
            // Create the (pre-trusted) Link, then funnel into the SAME ready
            // handler the WebRTC path uses (announce + offers) by re-emitting
            // ChannelReady, the transfer logic rides the trait unchanged.
            Ev::DirectReady(pid, t, route) => {
                let tkey = conn.direct_pending.get(&pid)
                    .map(|p| direct::transport_key(&p.secret.1));
                conn.adopt_direct(&pid, t.clone(), route);
                if let Some(k) = tkey {
                    conn.spawn_direct_workers(&pid, &t, k);
                }
                let _ = tx.send(Ev::ChannelReady(pid, t));
            }
            Ev::DirectWorkersReady(pid, workers) => {
                if let Some(link) = conn.link_mut(&pid) {
                    link.workers = workers;
                    crate::ui::debug(&format!("worker transports ready: {pid} {} workers", link.workers.len()));
                }
            }
            // P5 (GAP-6): a relay->direct upgrade probe's direct standby connected
            // ALONGSIDE the live relay link. Do NOT adopt it (that would clobber the
            // serving relay link); stash it as a warm standby and enter VERIFY. The
            // per-tick prober (judge_upgrade_standby) decides whether to cut over
            // (sustained progress) or discard (no flap).
            Ev::DirectUpgradeReady(pid, t, route) => {
                conn.stash_upgrade_standby(&pid, t, route);
            }
            Ev::ChannelReady(pid, t) => {
                if let Some(l) = conn.link_mut(&pid) {
                    l.transport = Some(t.clone());
                    l.presence = Presence::Ready;
                }
                // Responder links stop here: connected, polite, idle. Only
                // the active target gets announcements + offers.
                if !conn.is_active(&pid) {
                    continue;
                }
                // Bug 6: a live channel to the active peer disarms the
                // establishment timeout, the rest of the transfer is unbounded.
                established = true;
                waiting.store(false, std::sync::atomic::Ordering::Relaxed);
                if let Some(l) = conn.link(&pid) {
                    ui::say(&format!("  {} {}", ui::paint(ui::Tone::Ok, ui::glyph_ok()), ui::paint(ui::Tone::Bold, l.shown())));
                    let is_direct = l.direct;
                    let direct_route = l.direct_route;
                    if let Some(p) = l.peer.clone() {
                        tokio::spawn(async move {
                            // ICE may renominate; retry briefly (mirrors the
                            // browser's _detectRoute attempts) so fast transfers
                            // still get a route line before the process exits.
                            for _ in 0..6 {
                                tokio::time::sleep(Duration::from_millis(400)).await;
                                if let Some(r) = p.route().await {
                                    // CRITICAL: the route label is the value-prop,
                                    // direct vs relayed. Always shown, even under -q.
                                    ui::debug(&format!("    {}", ui::paint(ui::Tone::Dim, &format!("route: {r}"))));
                                    // Relay honesty (§3.3): the quiet `route:` line
                                    // is legible but not loud. When the route is
                                    // actually the TURN relay, print the honest
                                    // one-line banner so the user is never unaware
                                    // they're on a middleman path. CRITICAL.
                                    if r == "relayed" {
                                        ui::critical(&format!("    {}", relay_banner()));
                                    }
                                    break;
                                }
                            }
                        });
                    } else if is_direct {
                        ui::debug(&format!("    {}", ui::paint(ui::Tone::Dim, &format!("route: {direct_route}"))));
                    }
                    // L1-a: on the `--code` path, run the ephemeral SPAKE2
                    // ceremony BEFORE offering any byte. While auth is pending,
                    // mark this peer as our PAKE counterpart, arm the bounded
                    // budget, and DEFER offers. The progression block (top of
                    // loop) drives the ceremony; on confirm the Signal handler
                    // sets `pake_done` and re-emits ChannelReady to fall through
                    // here and offer. The secret is DISCARDED after auth.
                    if use_code && !is_direct && !pake_done {
                        pake_peer.get_or_insert(pid.clone());
                        pake_deadline.get_or_insert_with(|| Instant::now() + pake_budget);
                        ui::say(&ui::paint(ui::Tone::Dim, "  authenticating..."));
                        continue; // offers/remember wait for PAKE confirm
                    }
                    // C12: prove identity to a known device (their daemon
                    // auto-accepts only after verifying); or hand over a new
                    // pair secret when the user asked to --remember. A DIRECT
                    // link already proved the secret via the QUIC keying-material
                    // MAC (>= the DTLS pair-proof), so it skips this dance.
                    if is_direct {
                        // pre-authenticated; nothing to prove over the channel.
                    } else if let Some((_n, sec)) = &l.expected_secret {
                        if let Some((my_fp, their_fp)) = match &l.peer { Some(p) => p.fingerprints().await, None => None } {
                            t.send_control(&json!({
                                "type": "pair-proof",
                                "mac": proof_for(sec, &conn.my_uid, &conn.my_uid, l.uid.as_deref().unwrap_or(""), &my_fp, &their_fp),
                            })).await?;
                        } else {
                            ui::say(&ui::paint(ui::Tone::Warn, "no DTLS fingerprints available, skipping identity proof"));
                        }
                    }
                    // (Re-)offer everything unfinished; resume:true after a
                    // prior accept so receivers continue from their partial.
                    // (The `--code` path offers later, post-PAKE; this is the
                    // local-network / known-device / direct path.)
                    for o in outgoing.lock().await.iter() {
                        if o.done {
                            continue;
                        }
                        let offer = protocol::offer_msg(
                            &o.id, o.sid, &o.name, o.size,
                            o.head.as_deref(), o.full.as_deref(), o.accepted_once,
                        );
                        t.send_control(&offer).await?;
                    }
                }
            }
            Ev::Control(pid, v) => match v["type"].as_str() {
                Some("worker-ports") => {
                    let pid = v["for"].as_str().unwrap_or_default();
                    eprintln!("[T:SERVE] worker-ports handler: looking up key={pid}");
                    if let Some(tx) = conn.worker_port_tx.remove(pid) {
                        eprintln!("[T:SERVE] worker-ports handler: FOUND key={pid}");
                        let ports: Vec<u16> = v["ports"]
                            .as_array()
                            .map(|a| {
                                a.iter()
                                    .filter_map(|p| p.as_u64().map(|x| x as u16))
                                    .collect()
                            })
                            .unwrap_or_default();
                        let _ = tx.send(ports);
                    }
                }
                _ if !conn.is_active(&pid) => {}
                Some("brb") => {
                    let ttl = v["ttl"].as_u64().unwrap_or(120).min(300);
                    conn.rejoin.away = Some((pid.clone(), Instant::now() + Duration::from_secs(ttl)));
                    let n = conn.link_presence(&pid, Presence::Away);
                    ui::say(&conn.roster(&pid, "", ui::Tone::Warn, "away, holding the line", &n));
                }
                Some("back") => {
                    let was_away = conn.is_away(&pid);
                    conn.note_alive(&pid);
                    if was_away {
                        let n = conn.link_presence(&pid, Presence::Ready);
                        ui::say(&conn.roster(&pid, ui::glyph_ok(), ui::Tone::Ok, "back", &n));
                    }
                }
                // C30 phase 3: the peer's periodic truth, correct one-sided
                // beliefs instead of letting them persist.
                Some("state") => {
                    let was_away = conn.is_away(&pid);
                    conn.note_alive(&pid); // a state ping proves they're not frozen
                    if was_away {
                        let n = conn.link_presence(&pid, Presence::Ready);
                        ui::say(&conn.roster(&pid, ui::glyph_ok(), ui::Tone::Ok, "back", &n));
                    }
                    // Transfer divergence: I believe it complete; the peer
                    // holds fewer bytes, the END/tail was lost. Re-offer.
                    if let Some(obj) = v["transfers"].as_object() {
                        let mut out = outgoing.lock().await;
                        for o in out.iter_mut() {
                            if let Some(b) = obj.get(&o.id).and_then(|x| x.as_u64()) {
                                if o.done && b < o.size {
                                    o.done = false; // not actually done
                                    // DEBUG, resilience internal (state-divergence re-offer).
                                    ui::debug(&ui::paint(ui::Tone::Warn, &format!("  state-diverged: {}, peer holds {b}/{}; re-offering", o.name, o.size)));
                                    if let Some(t) = conn.transport_of(&pid) {
                                        let offer = protocol::offer_msg(
                                            &o.id, o.sid, &o.name, o.size,
                                            o.head.as_deref(), o.full.as_deref(), true,
                                        );
                                        let _ = t.send_control(&offer).await;
                                    }
                                }
                            }
                        }
                    }
                    // Trust divergence: they don't recognize us but we hold a
                    // pair secret for them, re-prove ONCE per link.
                    if v["trusted"].as_bool() == Some(false) && !reproved.contains(&pid) {
                        let proof = match conn.link(&pid) {
                            Some(l) => match &l.expected_secret {
                                Some((_n, sec)) => (match &l.peer { Some(p) => p.fingerprints().await, None => None })
                                    .map(|(my_fp, their_fp)| proof_for(sec, &conn.my_uid, &conn.my_uid, l.uid.as_deref().unwrap_or(""), &my_fp, &their_fp)),
                                None => None,
                            },
                            None => None,
                        };
                        if let Some(mac) = proof {
                            if let Some(t) = conn.transport_of(&pid) {
                                let _ = t.send_control(&json!({ "type": "pair-proof", "mac": mac })).await;
                                reproved.insert(pid.clone());
                                ui::debug(&ui::paint(ui::Tone::Dim, "  state-diverged: re-proving identity"));
                            }
                        }
                    }
                }
                // C27: the human on the other side answered our remember offer.
                Some("pair-keep-ack") => {
                    if let Some(name) = &remember {
                        let n = conn.link(&pid).map(|l| l.name.clone()).unwrap_or_default();
                        if v["ok"].as_bool() == Some(false) {
                            devices_remove(name)?;
                            ui::say(&conn.roster(&pid, ui::glyph_err(), ui::Tone::Warn, "declined to be remembered, nothing stored", &n));
                        } else {
                            ui::say(&conn.roster(&pid, ui::glyph_ok(), ui::Tone::Ok, "mutually remembered, you'll reconnect automatically", &n));
                        }
                    }
                }
                // C27: their verdict on our identity proof. false = they have
                // no memory of us, stop acting like a known device.
                Some("pair-proof-ack") => {
                    if v["ok"].as_bool() == Some(false) {
                        let n = conn.link(&pid).map(|l| l.name.clone()).unwrap_or_default();
                        if let Some(l) = conn.link_mut(&pid) {
                            l.expected_secret = None;
                        }
                        ui::say(&conn.roster(&pid, ui::glyph_err(), ui::Tone::Warn, "doesn't recognize this device, re-pair with --remember", &n));
                    }
                }
                Some("file-accept") => {
                    let Some(t) = conn.transport() else { continue };
                    // Build transport list: primary + any parallel QUIC workers.
                    let workers = conn.link(&pid)
                        .map(|l| l.workers.clone())
                        .unwrap_or_default();
                    let mut transports = vec![t];
                    transports.extend(workers);
                    let offset = v["offset"].as_u64().unwrap_or(0);
                    let id = v["id"].as_str().unwrap_or_default().to_string();
                    {
                        let mut out = outgoing.lock().await;
                        if let Some(o) = out.iter_mut().find(|o| o.id == id) {
                            o.accepted_once = true;
                        }
                    }
                    let out = outgoing.clone();
                    // Use the transport's OWN max payload, not conn.chunk_size:
                    // chunk_size is pinned to the 60 KiB WebRTC DataChannel limit
                    // (MAX_DC_PAYLOAD), which needlessly throttled the direct-QUIC
                    // path to tiny chunks. On QUIC max_payload() is far larger, so
                    // far fewer chunks pass through the receiver's single event-loop
                    // consumer (record_range + seek + write) per byte.
                    let chunk = transports[0].max_payload();
                    let tx2 = tx.clone();
                    // #28 test hook: the active peer's sid, so the streamer can
                    // synthesize a peer-left for it mid-flight (see stream_one).
                    let active_sid = conn.active.clone();
                    tokio::spawn(async move {
                        match stream_one(out, transports, id.clone(), offset, chunk, active_sid, tx2.clone()).await {
                            Ok(()) => {
                                let _ = tx2.send(Ev::TransferDone(id));
                            }
                            Err(e) => {
                                // C10: surface through the loop; the transfer
                                // stays pending and re-offers on reconnect.
                                let _ = tx2.send(Ev::TransferFailed { id, err: e.to_string() });
                            }
                        }
                    });
                }
                Some("file-decline") => {
                    let id = v["id"].as_str().unwrap_or_default();
                    let mut out = outgoing.lock().await;
                    if let Some(o) = out.iter_mut().find(|o| o.id == id) {
                        ui::say(&format!("declined: {}", o.name));
                        o.done = true;
                    }
                }
                // P4 (delivery-ack): the receiver computed the whole-file sha256
                // of every byte it received and it MATCHED our offered digest,
                // the bytes landed INTACT. Only now is the transfer truly `done`
                // (vs the old fire-and-forget where `file-end` alone "completed"
                // it). This closes the loop the runner had to fake above the
                // transport: the sender deterministically KNOWS it landed whole.
                Some("delivery-ack") => {
                    let id = v["id"].as_str().unwrap_or_default();
                    let mut out = outgoing.lock().await;
                    if let Some(o) = out.iter_mut().find(|o| o.id == id) {
                        if !o.acked {
                            o.acked = true;
                            o.done = true;
                            ui::say(&ui::paint(ui::Tone::Dim, &format!("    {} delivered + verified (whole-file sha256 matched)", o.name)));
                        }
                    }
                }
                _ => {}
            },
            Ev::TransferFailed { id, err } => {
                let out = outgoing.lock().await;
                let name = out.iter().find(|o| o.id == id).map(|o| o.name.as_str()).unwrap_or("?");
                // DEBUG, resilience internal (transfer interrupted, will resume).
                ui::debug(&format!("{name}: interrupted ({err}), will resume on reconnect"));
            }
            // P0 (GAP-1): the bytes-moved watchdog declared this transfer stalled.
            // Drive the least-disruptive correction ladder, preserving the on-disk
            // partial at every rung (C7 resume).
            Ev::TransferStalled(pid, idle_ms) => {
                if !conn.is_active(&pid) {
                    continue; // only the transfer-target peer's stall matters
                }
                // DEBUG, resilience internal (stall detection).
                ui::debug(&ui::paint(ui::Tone::Warn, &format!("  stall detected: {idle_ms}ms with no data, correcting")));
                match conn.correct_stall(&pid).await {
                    Rung::Resume => {
                        // Rung (a): re-issue every unfinished transfer with
                        // resume:true on the SAME transport. The receiver's
                        // file-accept carries its `.part` offset, so streaming
                        // continues from where it stalled (no restart-from-zero).
                        // If the link has no live transport, Resume is futile.
                        if conn.transport_of(&pid).is_none() {
                            ui::debug(&format!("  resume skipped: no live transport for {pid}, awaiting next repair cycle"));
                        } else if let Some(t) = conn.transport_of(&pid) {
                            let out = outgoing.lock().await;
                            for o in out.iter().filter(|o| o.accepted_once && !o.done) {
                                let offer = protocol::offer_msg(
                                    &o.id, o.sid, &o.name, o.size,
                                    o.head.as_deref(), o.full.as_deref(), true,
                                );
                                let _ = t.send_control(&offer).await;
                            }
                        }
                    }
                    // Rung (c): the transport was repaired in place inside
                    // correct_stall (fresh direct dial / ICE-restart). The new
                    // transport's ChannelReady re-offers the unfinished transfers
                    // (resume:true), nothing more to do here.
                    Rung::Repaired => {}
                    // Rung (d) P1: correct_stall re-established this transfer over
                    // the TURN relay (relay-only ICE), preserving the partial. The
                    // fresh relay link's ChannelReady re-offers the unfinished
                    // transfers (resume:true) and prints the route, nothing more
                    // to do here.
                    Rung::Relayed => {}
                    // Direct rungs spent AND relay forbidden (--no-relay) or relay
                    // itself stalled: the ladder failed CLEANLY (a kept partial, the
                    // clear cause already shown in correct_stall). PROMPTLY end the
                    // send rather than letting the frozen transfer hang to a timeout,
                    // the hard direct-only promise is "fail clean, fast", never a
                    // hang. The receiver kept its `.part`, so re-running resumes.
                    Rung::Exhausted => {
                        // The hard direct-only promise is "fail clean AND FAST", never
                        // a hang. A signaling socket wedged by the same frozen path can
                        // make `disconnect()` itself block, so BOUND it: a 2s cap keeps
                        // the exit prompt (we're tearing down anyway; the OS reaps the
                        // socket). This only affects the already-failing path, it can
                        // never delay or alter a successful send.
                        let _ = tokio::time::timeout(Duration::from_secs(2), sio.disconnect()).await;
                        if relay_forbidden() {
                            bail!("couldn't establish a direct path and relay is disabled (--no-relay), partial kept; re-run to resume, or drop --no-relay");
                        }
                        bail!("transfer stalled and no usable path remains, partial kept; re-run to resume");
                    }
                }
            }
            Ev::Interrupted => {
                ui::say(&format!("  {} interrupted, the receiver keeps its partial; re-run the same command to resume", ui::paint(ui::Tone::Warn, "!")));
                let _ = sio.disconnect().await;
                std::process::exit(130);
            }
            Ev::Stuck(pid, generation) => {
                // Bug 5: if we keep getting stuck BEFORE a channel ever came up,
                // surface the single-host mDNS hint once.
                if !established {
                    stuck_while_connecting += 1;
                    if stuck_while_connecting >= 2 {
                        maybe_hint_local_wedge(&mut wedge_hint_shown);
                    }
                }
                if conn.on_stuck(&pid, generation, "stuck while connecting").await? {
                    bail!("lost the receiving peer after {} attempts; the partial is kept, re-run the same `filament send` to resume", MAX_ATTEMPTS);
                }
            }
            Ev::GraceExpired(pid, generation) => {
                if conn.on_stuck(&pid, generation, "lost").await? {
                    bail!("lost the receiving peer after {} attempts; the partial is kept, re-run the same `filament send` to resume", MAX_ATTEMPTS);
                }
            }
            Ev::PcState(pid, s) => conn.on_pc_state(&pid, &s).await,
            Ev::PeerLeft(v) => {
                let gone = v["id"].as_str().and_then(|p| conn.link(p)).map(|l| l.name.clone());
                if conn.on_peer_left(&v) {
                    let all_done = outgoing.lock().await.iter().all(|o| o.done);
                    if !all_done {
                        let secs = REJOIN_WINDOW.as_secs();
                        let gid = v["id"].as_str().unwrap_or_default();
                        match gone {
                            Some(n) => ui::say(&conn.roster(gid, "", ui::Tone::Dim, &format!("disconnected, waiting up to {secs}s"), &n)),
                            // DEBUG, resilience internal (peer-disconnect wait).
                            None => ui::debug(&format!("peer disconnected, waiting up to {secs}s for them to come back")),
                        }
                    }
                }
            }
            _ => {}
        }
        // P4 (silent-data-loss fix): every transfer's BYTES have left this side
        // (`sent`), but a transfer is only truly `done` once the receiver returns a
        // whole-file-verified `delivery-ack`. Drain the wire first, then WAIT for
        // the ack, bounded by `ack_wait`. If the window elapses with no ack we do
        // NOT declare success (the old bug): we decide via decide_ack_fallback,
        // re-probe ONCE (re-send file-end to prompt a possibly-lost ack), and if
        // the ack still never lands we FAIL the send below (nonzero, partial kept
        // resumable). Only the real `delivery-ack` handler may set `o.done`.
        {
            let all_sent;
            let all_acked;
            let mut do_flush = false;
            let mut do_reprobe = false;
            let mut give_up = false;
            {
                let out = outgoing.lock().await;
                all_sent = !out.is_empty() && out.iter().all(|o| o.sent);
                all_acked = !out.is_empty() && out.iter().all(|o| o.done);
                if all_sent && !all_acked {
                    if sent_all_at.is_none() {
                        sent_all_at = Some(Instant::now());
                        do_flush = true;
                    }
                    let window_elapsed = sent_all_at.map(|t| t.elapsed() >= ack_wait).unwrap_or(false);
                    let reprobe_elapsed = reprobed_at.map(|t| t.elapsed() >= ack_reprobe).unwrap_or(false);
                    // Only act once a window has elapsed: the first ack_wait, or
                    // (after a re-probe) the shorter ack_reprobe window.
                    if (!ack_reprobed && window_elapsed) || (ack_reprobed && reprobe_elapsed) {
                        // A live transport attached is the "link alive" signal
                        // (mirrors the browser's data-channel-open check). A
                        // black-hole that QUIC hasn't noticed still reports a
                        // transport, so the re-probe path is what catches it.
                        let link_alive = conn.transport().is_some();
                        match protocol::decide_ack_fallback(link_alive, ack_reprobed) {
                            protocol::AckFallback::Reprobe => do_reprobe = true,
                            protocol::AckFallback::FailUnconfirmed => give_up = true,
                        }
                    }
                }
            }
            if do_flush {
                // Flush (NOT drain_finish) on first reaching the all-sent point:
                // push the wire so the receiver can finish + verify + ack. We do
                // NOT call drain_finish here because on direct-QUIC that ends the
                // send half (`finish()`), which would block a corrupt-case
                // RE-FETCH that needs to stream more bytes. The final exit block
                // does the authoritative drain_finish once the ack lands (no more
                // re-fetch possible by then). On a DataChannel both are just
                // flush(); on QUIC this keeps the stream open for a resume.
                if let Some(t) = conn.transport() {
                    let _ = t.flush().await;
                }
            }
            if do_reprobe {
                // The ack may have been lost on a still-alive link. Re-send file-end
                // for every unacked transfer to prompt the receiver to re-ack, then
                // wait one more (shorter) window. Never completes anything.
                ack_reprobed = true;
                reprobed_at = Some(Instant::now());
                let pending: Vec<(String, u32, String)> = {
                    let out = outgoing.lock().await;
                    out.iter().filter(|o| !o.done).map(|o| (o.id.clone(), o.sid, o.name.clone())).collect()
                };
                if let Some(t) = conn.transport() {
                    for (id, sid, name) in &pending {
                        ui::debug(&format!("  {name}: no delivery-ack yet, re-probing (re-sending file-end)"));
                        let _ = t.send_control(&protocol::end_msg(id, *sid)).await;
                    }
                    let _ = t.flush().await;
                }
            }
            if give_up {
                // No delivery-ack after the window + re-probe (or the link is gone).
                // Do NOT claim success: the receiver may have gotten nothing. Fail
                // honestly. The on-disk source is untouched and the outgoing entry
                // is preserved for resume; a fresh `send`/reconnect re-offers it.
                let names: Vec<String> = {
                    let out = outgoing.lock().await;
                    out.iter().filter(|o| !o.done).map(|o| o.name.clone()).collect()
                };
                for name in &names {
                    ui::critical(&ui::paint(ui::Tone::Warn, &format!(
                        "  {name}: delivery not confirmed (no whole-file delivery-ack), the receiver may have gotten nothing; NOT marking complete"
                    )));
                }
                let _ = sio.disconnect().await;
                bail!(
                    "delivery not confirmed: {} file(s) sent but never delivery-acked by the receiver (treating as unconfirmed, not delivered)",
                    names.len().max(1)
                );
            }
        }
        // Exit when every transfer reached a terminal state (`done` = acked, or the
        // bounded-fallback / un-hashable cases above).
        {
            let out = outgoing.lock().await;
            if !out.is_empty() && out.iter().all(|o| o.done) {
                if let Some(t) = conn.transport() {
                    // Block until the peer has acked every byte before we exit,
                    // a torn-down QUIC connection drops un-acked send-buffer bytes
                    // and truncates the last file (no-op on DataChannel, which
                    // already drained in flush()). Surface a drain failure rather
                    // than silently reporting "done" on a partial transfer.
                    if let Err(e) = t.drain_finish().await {
                        // CRITICAL, a possibly-incomplete delivery; must-see even under -q.
                        ui::critical(&ui::paint(ui::Tone::Warn, &format!("warning: transfer may be incomplete, {e}")));
                    }
                }
                for o in out.iter().filter(|o| o.temp) {
                    let _ = std::fs::remove_file(&o.path);
                }
                ui::say("done.");
                tokio::time::sleep(Duration::from_millis(300)).await;
                let _ = sio.disconnect().await;
                return Ok(());
            }
        }
    }
}

async fn stream_one(
    outgoing: Arc<tokio::sync::Mutex<Vec<Outgoing>>>,
    transports: Vec<Arc<dyn Transport>>,
    id: String,
    offset: u64,
    chunk: usize,
    active_sid: Option<String>,
    tx: mpsc::UnboundedSender<Ev>,
) -> Result<()> {
    let (sid, name, size, path) = {
        let out = outgoing.lock().await;
        let o = out.iter().find(|o| o.id == id).ok_or_else(|| anyhow!("unknown transfer {id}"))?;
        (o.sid, o.name.clone(), o.size, o.path.clone())
    };
    if offset > 0 {
        // DEBUG, resilience internal (transfer resuming from a saved offset).
        ui::debug(&format!("{name}: resuming at {} ({:.0}%)", human(offset), offset as f64 / size.max(1) as f64 * 100.0));
    }
    // #28 deterministic test hook: once we cross this byte offset, synthesize a
    // peer-left for the ACTIVE peer WITHOUT touching the data channel, exactly
    // the "signaling reconnect mid-transfer, channel stays alive" case. The
    // deferred-drop path must keep the link and let the transfer finish on it.
    // Injecting the active sid is critical: a wrong id makes on_peer_left
    // return early (link-not-found) and the test would falsely pass.
    use tokio::io::{AsyncSeekExt, AsyncReadExt};
    let inject_at: Option<u64> = test_hooks::inject_peer_left_at();
    let num = transports.len().max(1);
    // Split the remaining bytes [offset, size) into `num` contiguous ranges and
    // stream each over its OWN transport in a CONCURRENT task. The previous
    // round-robin ran on one task and awaited each send_frame, so it stalled on
    // whichever connection's flow-control window filled first and never used the
    // links in parallel. One task per connection lets every link drain at once,
    // which is the actual multi-stream win. The receiver reassembles by absolute
    // offset (positional writes), so range order does not matter.
    let bar = std::sync::Arc::new(tokio::sync::Mutex::new(ui::Progress::new(&name, size)));
    let progress = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(offset));
    let injected = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let remaining = size.saturating_sub(offset);
    let per = remaining / num as u64;
    let mut handles = Vec::with_capacity(num);
    for i in 0..num {
        let start = offset + i as u64 * per;
        let end = if i == num - 1 { size } else { start + per };
        if start >= end {
            continue;
        }
        let t = transports[i].clone();
        let path = path.clone();
        let bar = bar.clone();
        let progress = progress.clone();
        let injected = injected.clone();
        let tx = tx.clone();
        let active_sid = active_sid.clone();
        handles.push(tokio::spawn(async move {
            let mut f = tokio::fs::File::open(&path).await?;
            f.seek(SeekFrom::Start(start)).await?;
            let mut pos = start;
            let mut buf = vec![0u8; chunk];
            while pos < end {
                let want = std::cmp::min(chunk as u64, end - pos) as usize;
                let n = f.read(&mut buf[..want]).await?;
                if n == 0 {
                    break;
                }
                t.send_frame(sid, pos, &buf[..n]).await?;
                pos += n as u64;
                let total =
                    progress.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed) + n as u64;
                bar.lock().await.tick(total);
                if let (Some(at), Some(asid)) = (inject_at, active_sid.as_ref()) {
                    if total >= at
                        && !injected.swap(true, std::sync::atomic::Ordering::SeqCst)
                    {
                        eprintln!("[test] injecting synthetic peer-left for active sid at {total} bytes");
                        let _ = tx.send(Ev::PeerLeft(json!({ "id": asid })));
                    }
                }
            }
            t.flush().await?;
            Ok::<(), anyhow::Error>(())
        }));
    }
    for h in handles {
        h.await.map_err(|e| anyhow!("stream task join: {e}"))??;
    }
    // End frame on primary transport; flush all transports.
    transports[0].send_control(&protocol::end_msg(&id, sid)).await?;
    for t in &transports {
        t.flush().await?;
    }
    bar.lock().await.done(size.saturating_sub(offset));
    let mut out = outgoing.lock().await;
    if let Some(o) = out.iter_mut().find(|o| o.id == id) {
        // P4: the bytes + file-end left this side, but the transfer is NOT
        // `done` yet. It is `done` only once the receiver returns a whole-file-
        // verified `delivery-ack` (or the bounded no-ack fallback fires). A peer
        // that has nothing more to send for THIS file is `sent`; the all-done
        // exit waits on `acked`. If this file carries no `full` digest (we
        // couldn't hash it), there's nothing for the receiver to verify-and-ack,
        // so it's done on send, the legacy fire-and-forget behaviour, scoped to
        // exactly the un-hashable case.
        o.sent = true;
        if o.full.is_none() {
            o.acked = true;
            o.done = true;
        }
    }
    Ok(())
}

// ------------------------------------------------------------------- recv --

struct IncomingFile {
    id: String,
    name: String,
    size: u64,
    /// Atomic counter so background writer tasks can publish received bytes
    /// without locking. The event loop polls this for progress updates.
    received: Arc<AtomicU64>,
    /// Disjoint sorted byte intervals [start, end) received so far, for
    /// out-of-order reassembly from multi-stream transports. Shared via
    /// Mutex so concurrent spawn_blocking writer tasks can update safely.
    ranges: Arc<std::sync::Mutex<Vec<(u64, u64)>>>,
    /// Raw file handle shared across concurrent spawn_blocking writer tasks.
    /// Positional writes go through `pwrite_at` (write_at on Unix, seek_write on
    /// Windows) which is atomic per call — no seek needed, safe for concurrent
    /// access.
    file: Arc<std::fs::File>,
    part_path: PathBuf,
    /// P4 (GAP-5): the whole-file sha256 the SENDER offered (`full`). On
    /// completion we hash the received `.part` and compare, only a match
    /// finalizes + acks. `None` = the sender offered no digest (old peer / an
    /// un-hashable source); we fall back to the legacy size-only acceptance and
    /// do NOT ack (nothing to verify), which the sender's bounded fallback covers.
    full: Option<String>,
    /// Number of inflight spawn_blocking write tasks. The event loop uses
    /// this to decide when a file is ready for finalization:
    ///   inflight == 0 && end_seen → finalize
    inflight: Arc<AtomicI64>,
    /// Set by the file-end handler when the sender reports end-of-file, even
    /// if inflight writes are still pending. The last finishing writer checks
    /// this flag and emits Ev::MaybeComplete if both conditions are met.
    end_seen: Arc<AtomicBool>,
    /// The sid to use in the delivery-ack message. Set from the file-end
    /// control frame; read by the MaybeComplete handler for the ack.
    ack_sid: u32,
    /// Tracks the last received value used for progress display (to avoid
    /// re-ticking the same value). Not atomic — only accessed from the event loop.
    last_tick: u64,
    bar: ui::Progress,
}

/// Record a received byte interval [pos, pos+len) in the disjoint sorted range
/// list, merging overlapping/adjacent intervals. Returns the total unique bytes
/// covered by all ranges — the authoritative `received` for multi-stream OOO
/// reassembly. Single-stream (no ranges) callers can skip this entirely.
fn record_range(ranges: &mut Vec<(u64, u64)>, pos: u64, len: usize) -> u64 {
    let end = pos + len as u64;
    // Skip past ranges that end before this one starts.
    let mut i = 0;
    while i < ranges.len() && ranges[i].1 < pos {
        i += 1;
    }
    // Merge all overlapping / adjacent ranges.
    let mut new_s = pos;
    let mut new_e = end;
    while i < ranges.len() && ranges[i].0 <= end {
        let (s, e) = ranges.remove(i);
        new_s = new_s.min(s);
        new_e = new_e.max(e);
    }
    ranges.insert(i, (new_s, new_e));
    // Sum all ranges: total unique bytes received.
    ranges.iter().map(|(s, e)| e - s).sum()
}

/// Build the live shell policy from the persistent settings (global `shell` +
/// per-peer `shell on` overrides). Mirrors `up_cmd`'s startup construction so a
/// `set shell ...` reconfigure lands the daemon in the same state a restart would.
fn shell_policy_from_settings() -> ShellPolicy {
    if settings::get_bool("shell", None) {
        return ShellPolicy::All;
    }
    let peers = settings::peers_with("shell", "on");
    if peers.is_empty() {
        ShellPolicy::Granted
    } else {
        ShellPolicy::Only(peers.into_iter().collect())
    }
}

/// Apply a `filament set <key>` change to the LIVE daemon state, the heart of
/// live-reconfigure. Returns whether the change took effect without a restart.
/// Keys woven into startup (relay/server force, or arming the L2 acceptor from
/// cold) return `false`, so the client tells the user to run `filament up`.
#[allow(clippy::too_many_arguments)]
async fn apply_reconfigure(
    key: &str,
    dir: &mut PathBuf,
    shell_policy: &mut ShellPolicy,
    shell_user: &mut Option<String>,
    l2_enabled: bool,
    sess: &mut session::Session,
    sio: &rust_socketio::asynchronous::Client,
    my_uid: &str,
) -> bool {
    match key {
        "drop-dir" => {
            let nd = settings::get_str("drop-dir", None)
                .map(PathBuf::from)
                .unwrap_or_else(default_drop_dir);
            let _ = std::fs::create_dir_all(&nd);
            *dir = nd;
            true
        }
        "shell-user" => {
            *shell_user = settings::get_str("shell-user", None);
            true
        }
        // auto-extract is re-read on every received file (finalize_incoming), so
        // it is already live; nothing to mutate here.
        "auto-extract" => true,
        "shell" => {
            *shell_policy = shell_policy_from_settings();
            // The per-request accept check consults `shell_policy` live, so a
            // narrow/disable applies instantly. But going from no-shell to shell
            // needs the L2 acceptor that was wired at startup: live only if it was
            // already armed (`l2_enabled`).
            l2_enabled || !shell_policy.enables_l2()
        }
        "name" => {
            // Re-announce presence with the fresh name. Same uid + room, so peers
            // update the label without minting a new presence identity (no ghost).
            if let Some(room) = sess.room.clone() {
                sess.emit(sio, "join", json!({ "room": room, "name": display_name(), "uid": my_uid })).await;
            }
            true
        }
        // relay/server are bound into the establishment + signaling setup at
        // startup; changing them safely needs a fresh `filament up`.
        _ => false,
    }
}

#[allow(clippy::too_many_arguments)]
async fn recv_cmd(
    server: &str,
    mut code: Option<String>,
    mut dir: PathBuf,
    yes: bool,
    room: Option<String>,
    to: Option<String>,
    keep_open: bool,
    relay: bool,
    remember: Option<String>,
    daemon: bool,
    output: Option<String>,
    mut shell_policy: ShellPolicy,
    // M-1: optional non-root account the web-shell/ssh PTY is dropped to. `None`
    // means the PTY runs as the up-process user (documented root risk).
    mut shell_user: Option<String>,
    no_proxy_fallback: bool,
) -> Result<()> {
    let to_stdout = output.as_deref() == Some("-");
    // INTERACTIVE GATE (CLI `recv` only, never the daemon/`up`). With no code,
    // offer: type a code to connect to a specific person, or press Enter on an
    // empty buffer to use the local network (today's default). When the gate is
    // closed we fall straight through to the auto-room default below.
    if !daemon && code.is_none() && interactive_allowed() {
        ui::say(&ui::paint(
            ui::Tone::Dim,
            "  enter a code to connect to a specific person, or press enter to use the local network",
        ));
        match codeentry::run("  recv · code  ", codeentry::Mode::Claim, "", "")? {
            codeentry::Outcome::Submitted(c) => code = Some(c),
            codeentry::Outcome::Empty => { /* fall through to the local-network auto room */ }
            codeentry::Outcome::Cancelled => return Err(cancelled()),
        }
    }
    // L1-a unification: a transfer code and a pairing code now have the SAME
    // shape (`words-NNNN`) and run the SAME ephemeral SPAKE2 ceremony, the verb
    // (`recv` vs `pair`) decides whether the agreed secret is discarded or kept.
    // So `recv` no longer redirects a 4-digit code away (the old width-based
    // hint is obsolete); any well-formed code is a valid claim here.
    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
    let my_uid = mk_uid("r");
    let (tx, mut rx) = mpsc::unbounded_channel::<Ev>();
    // P2 (GAP-2): `mut` so the long-lived acceptor's outer reconnect loop can
    // swap in a freshly-dialed signaling client after a drop (see below). The
    // short-lived `recv`/`send` paths never reconnect, they re-invoke fresh,
    // so this is only exercised by the daemon (`up`/`up --dir`).
    let mut sio = net::connect_signaling(server, tx.clone()).await?;

    let mut paired = code.is_some();
    // C24: at most one typed claim in flight, a second typed code while one
    // is pending was silently dropped in live use; now it queues a message.
    let mut claim_in_flight = false;
    // C29: an in-session pairing ceremony (daemon mode): typed code or a
    // minted one, exactly ONE side hands over a fresh secret (creator
    // initiates; a claimer waits 3 s for the creator, then takes over,
    // browsers never initiate). Some(true) = we minted; Some(false) = we
    // claimed; None = no ceremony pending.
    let mut ceremony: Option<bool> = None;
    let mut ceremony_pid: Option<String> = None;
    let mut ceremony_secret = fresh_secret();
    // C25: when the current question appeared (answers sooner than 300ms are
    // buffered keystrokes, not decisions)
    let mut question_shown = Instant::now();
    let mut devices = devices_load(); // channel -> identity lookup for proofs
    // C30: the convergent session repairs whatever the one-shot emits below
    // lose, room membership, channel subscriptions, the lease. The emits
    // stay as the fast path (and old-server compat); the session is truth.
    let mut sess = session::Session::new(&display_name(), &my_uid);
    sess.channels = devices.iter().map(|(_, s)| channel_of(s)).collect();
    // L1-a: the ephemeral SPAKE2 ceremony for a `recv <code>` claim. The typed
    // code is split CLIENT-SIDE; only the numeric nameplate is sent (pair-claim
    // {nameplate, v:2}). The words feed SPAKE2 and never reach the server. After
    // mutual auth the agreed secret is DISCARDED (transfer never persists it).
    //
    // PER-PEER ceremonies (shared-auto-room fix): the receiver joins the sender's
    // room, which (for a `send --code`) is the sender's AUTO room, shared with any
    // other local peers sitting in it. We therefore CANNOT latch onto the first
    // peer that appears: an unrelated decoy must not be allowed to consume our one
    // ceremony, run it to the budget, and bail the whole receive. Instead we run
    // an INDEPENDENT ephemeral ceremony per candidate peer, each built from the
    // SAME claimed code (words + nameplate). The FIRST peer whose ceremony agrees
    // K and verifies the confirm MAC becomes the authenticated sender; from then
    // on we accept file-offers ONLY from that peer. A peer whose ceremony fails
    // (wrong words) or whose per-peer budget expires is dropped INDIVIDUALLY and
    // never bails the receive. Only an OVERALL deadline with NO peer authenticated
    // fails the whole `recv` (so a genuinely absent/old sender still fails loudly
    // rather than hanging). `recv_code_path` is the "this is a code claim" sentinel
    // (was `recv_cer.is_some()`); `recv_pake_template` mints each per-peer ceremony.
    let recv_code_path = code.is_some();
    let recv_pake_template: Option<(String, String)>; // (words, nameplate)
    // Each candidate peer's own ephemeral ceremony, keyed by peer id.
    let mut recv_cers: HashMap<String, Ceremony> = HashMap::new();
    // Each candidate peer's own bounded budget (armed when its channel comes up).
    let mut recv_deadlines: HashMap<String, Instant> = HashMap::new();
    // The peer that WON authentication (its ceremony confirmed). Once set, only
    // this peer may offer files. `None` until someone authenticates.
    let mut recv_pake_peer: Option<String> = None;
    // A file-offer can race ahead of auth: the sender offers as soon as IT has our
    // confirm, which can land a tick BEFORE we finish verifying ITS confirm (the
    // two confirms cross on the wire, and the shared-room mesh widens that gap). We
    // must not silently drop that offer, the sender offers it only once. So we
    // BUFFER the most recent pre-auth offer per candidate peer and REPLAY it the
    // instant that peer authenticates. Bounded by RECV_MAX_CANDIDATES (same keys).
    let mut recv_pending_offers: HashMap<String, Value> = HashMap::new();
    let mut recv_pake_done = code.is_none(); // only the code path runs the PAKE
    let recv_pake_budget = Duration::from_secs(
        std::env::var("FILAMENT_PAIR_GRACE_SECS").ok().and_then(|v| v.parse().ok()).unwrap_or(60),
    );
    // Overall bound: once we are matched into the sender's room, SOMEONE must
    // authenticate within this window or the whole `recv` fails loudly. Per-peer
    // budgets only drop individual mis-latch candidates; this is the backstop for
    // a genuinely absent / old sender. Armed on the first candidate channel.
    let mut recv_pake_overall_deadline: Option<Instant> = None;
    // Memory bound: a crowded room cannot blow us up. We mint at most this many
    // concurrent candidate ceremonies; further candidates are ignored (the real
    // sender is, in practice, among the first to share the room with the claimer).
    const RECV_MAX_CANDIDATES: usize = 8;
    match &code {
        Some(c) => {
            // Split the typed code into (nameplate, words); send ONLY the
            // nameplate. The words become the SPAKE2 password held locally.
            let normalized = crate::pake::norm_code(c);
            let (np, pw) = crate::pake::split_code(&normalized);
            if pw.is_empty() || np.is_empty() {
                bail!("that code doesn't look right, expected something like brave-otter-371");
            }
            // Held to mint a fresh per-peer ceremony for each candidate. The words
            // live ONLY here and inside each Ceremony's SPAKE2 state; never sent.
            recv_pake_template = Some((pw.clone(), np.clone()));
            sio.emit("pair-claim", json!({ "nameplate": np, "v": 2 })).await.ok();
        }
        None if daemon => {
            recv_pake_template = None; // no code claim, no ephemeral PAKE
            // C19: the daemon joins NO room. Presence-channel subscriptions
            // only, strangers can't see it, probe it, or offer to it.
            // (We still `join` an unguessable solo room so the registry holds
            // our meta for known-peer events, but nobody else can land there.)
            let solo = format!("up-{}", fresh_secret());
            sess.room = Some(solo.clone());
            sess.emit(&sio, "join", json!({ "room": solo, "name": display_name(), "uid": my_uid })).await;
            // C29: an interactive up can START empty and pair in-session.
            // When shell (--shell / --shell-only) is enabled, the daemon
            // explicitly accepts devices paired later, so do NOT bail just
            // because the device list is empty at startup — the live-pairing
            // scan (below) will pick them up from devices.json.
            if devices.is_empty() && !std::io::stdin().is_terminal() && !shell_policy.enables_l2() {
                bail!("no known devices, run `filament pair` once, or `filament up` in a terminal to pair interactively");
            }
            let chans: Vec<String> = devices.iter().map(|(_, s)| channel_of(s)).collect();
            sess.emit(&sio, "subscribe", json!({ "channels": chans })).await;
            ui::say(&format!(
                "  {} filament up, {} known device{} {} {}",
                ui::paint(ui::Tone::Brand, ""),
                devices.len(),
                if devices.len() == 1 { "" } else { "s" },
                ui::glyph_arrow(),
                ui::paint(ui::Tone::Bold, &dir.display().to_string()),
            ));
            ui::say(&ui::paint(ui::Tone::Dim, "  trusted devices only · invisible to strangers · Ctrl-C or `filament down` to stop"));
            // C29: this is a SESSION, like a browser tab, pairing and petname
            // management happen right here.
            if std::io::stdin().is_terminal() {
                ui::say(&ui::paint(
                    ui::Tone::Dim,
                    "  type a code to pair a new device · `pair` mints one · `devices` · `forget <name>`",
                ));
            }
        }
        None => {
            recv_pake_template = None; // local-network listen, no ephemeral PAKE
            let room = match &room {
                Some(r) => r.clone(),
                None => net::fetch_auto_room(server).await?,
            };
            // C22: proactive affordance, tell the user what they CAN do,
            // cargo-style gutter, before they have to guess.
            ui::say(&format!(
                "  {} listening, same-network devices appear automatically  {}",
                ui::paint(ui::Tone::Brand, ""),
                ui::paint(ui::Tone::Dim, &format!("(room {room} · dir {})", dir.display())),
            ));
            ui::say(&ui::paint(
                ui::Tone::Dim,
                "  have a code? just type it here (like brave-otter-123) and press Enter",
            ));
            sess.room = Some(room.clone());
            sess.emit(&sio, "join", json!({ "room": room, "name": display_name(), "uid": my_uid })).await;
            // C12: announce on every known device's presence channel
            if !devices.is_empty() {
                let chans: Vec<String> = devices.iter().map(|(_, s)| channel_of(s)).collect();
                ui::say(&format!("watching for {} known device(s)", devices.len()));
                sess.emit(&sio, "subscribe", json!({ "channels": chans })).await;
            }
        }
    }

    // L2 acceptor posture (computed here so it also gates the direct-QUIC path).
    // OFF unless FILAMENT_L2=1 (opt-in) OR an active `up --shell` policy turns it
    // on (you can't ssh in without the acceptor). See its second use below.
    // L2/shell is ON when: an `--shell`/`--shell-only` policy turns it on, the
    // FILAMENT_L2 opt-in is set, OR any known device has been `grant`ed shell (so
    // `filament grant <dev> shell` works on a plain `up` without restarting with a
    // flag, matching what the grant command tells the user). The per-device gate
    // below still denies every non-granted device, so this never widens access.
    let l2_enabled = shell_policy.enables_l2()
        || std::env::var("FILAMENT_L2").map(|v| v == "1").unwrap_or(false)
        || any_shell_grant();

    let mut conn = Conn::for_command(
        server,
        sio.clone(),
        tx.clone(),
        my_uid.clone(),
        relay,        // relay_only
        to,           // to_filter
        // P3 (GAP-3): the `up`/`up --shell` daemon acceptor is the canonical
        // long-lived / interactive session, so warm redundancy defaults ON for it
        // (a one-shot `recv` keeps daemon=false -> OFF).
        daemon,       // warm_standby default
        // rung-1 direct-QUIC: take it when the env gate is set, when this is an
        // L2/ssh acceptor, OR when this is the long-lived `up` daemon. Any acceptor
        // MUST answer the initiator's transport-offer (direct-QUIC over the
        // reachable host candidate, e.g. Tailscale) rather than build a colliding
        // WebRTC peer (glare). For `up --shell` this kills the `filament ssh`
        // "stuck while connecting" failure; for a plain `up` it kills the up<->up
        // glare/supersede churn (two known daemons each racing to be the WebRTC
        // initiator). See `direct_ok_for`. One-shot send/recv/pair (daemon=false)
        // are unaffected and keep their WebRTC default.
        direct_ok_for(daemon, l2_enabled),
    );
    // WARM-HOLD: load configured warm-peers at daemon startup
    if daemon {
        conn.load_warm_peers_config();
    }
    // SIGINT/SIGTERM: route a graceful Ev::Interrupted through the loop AND arm a
    // signal-owned force-exit watchdog. The watchdog is the guarantee: if the
    // event loop is wedged on a stuck peer transport (a WebRTC data-channel write
    // against a frozen/half-open peer, or a send_frame parked on backpressure that
    // never drains), the graceful Interrupted is never processed and the daemon
    // would otherwise ignore the signal until systemd SIGKILLs it ~90s later. The
    // watchdog force-exits within the bounded grace regardless of loop state; a
    // dropped link is an ordinary disconnect to the peer's resilience layer.
    {
        let tx = tx.clone();
        tokio::spawn(async move {
            let _ = tokio::signal::ctrl_c().await;
            shutdown::arm_force_exit(130, shutdown::grace());
            let _ = tx.send(Ev::Interrupted);
        });
    }
    #[cfg(unix)]
    {
        let tx = tx.clone();
        tokio::spawn(async move {
            if let Ok(mut term) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
                term.recv().await;
                shutdown::arm_force_exit(130, shutdown::grace());
                let _ = tx.send(Ev::Interrupted);
            }
        });
    }
    // A listening recv accepts a code typed straight into it, the first
    // thing real users try (observed live). C22: stdin runs RAW (cbreak) on a
    // tty so an open y/N question resolves on a single keypress, no Enter;
    // outside a question, bytes accumulate into lines (echoed manually since
    // raw mode disables terminal echo).
    let question_open = Arc::new(std::sync::atomic::AtomicBool::new(false));
    // C29: the stdin owner also runs for an INTERACTIVE daemon (a terminal-
    // attached `filament up` is a session); `up --install` under systemd has
    // no tty, so headless daemons stay stdin-free.
    let interactive = !daemon || std::io::stdin().is_terminal();
    let tty_guard = if interactive && std::io::stdin().is_terminal() { Some(TtyGuard::raw()) } else { None };
    if interactive {
        let tx = tx.clone();
        let q = question_open.clone();
        tokio::spawn(async move {
            use tokio::io::AsyncReadExt;
            let mut stdin = tokio::io::stdin();
            let mut buf = [0u8; 1];
            let mut line = String::new();
            while stdin.read(&mut buf).await.map(|n| n == 1).unwrap_or(false) {
                let c = buf[0] as char;
                if q.load(std::sync::atomic::Ordering::Relaxed) && "yYnN".contains(c) && line.is_empty() {
                    ui::answer_echo(c); // raw mode is no-echo; land it cleanly (C23)
                    let _ = tx.send(Ev::StdinLine(c.to_lowercase().to_string()));
                    continue;
                }
                match buf[0] {
                    b'\n' | b'\r' => {
                        eprintln!();
                        let _ = tx.send(Ev::StdinLine(line.trim().to_string()));
                        line.clear();
                    }
                    0x7f | 0x08 => {
                        if line.pop().is_some() {
                            eprint!("\x08 \x08");
                        }
                    }
                    _ if !c.is_control() => {
                        eprint!("{c}");
                        line.push(c);
                    }
                    _ => {}
                }
            }
        });
    }
    // L3 (serve_tun mesh): the up daemon opens a TUN and routes IP packets across
    // its peer links when `tun-addr` is set. `auto` (recommended) derives a stable,
    // self-certifying overlay address from this device's Ed25519 overlay key; peers
    // learn+trust it via a signed `l3-announce` (below). A manual CIDR is the
    // advanced/PSK case (no announce). Off otherwise; Linux-only.
    // `l3_seen`: last announce received per pid, replayed once a datagram-capable
    // transport is installed, so a hello that races ahead of the link is not lost
    // (review fix #3).
    #[cfg(l3)]
    let mut l3_seen: HashMap<String, overlay::Announce> = HashMap::new();
    #[cfg(l3)]
    let l3: Option<std::sync::Arc<l3::L3>> = if daemon {
        match settings::get_str("tun-addr", None) {
            Some(setting) => {
                let (cidr, identity) = if setting == "auto" {
                    match overlay::Identity::load_or_create() {
                        Ok(id) => (format!("{}/128", id.addr()), Some(id)),
                        Err(e) => {
                            ui::say(&ui::paint(ui::Tone::Warn, &format!("  L3 disabled: {e}")));
                            (String::new(), None)
                        }
                    }
                } else {
                    (setting.clone(), None) // manual/PSK address, no crypto announce
                };
                if cidr.is_empty() {
                    None
                } else {
                    // Endpoint selection: `l3-mode` setting (kernel|userspace|auto),
                    // default Auto; FILAMENT_L3_USERSPACE / `up --userspace` force
                    // userspace (handled inside L3::start via the env).
                    let mode = match settings::get_str("l3-mode", None).as_deref() {
                        Some("kernel") => l3::L3Mode::Kernel,
                        Some("userspace") => l3::L3Mode::Userspace,
                        _ => l3::L3Mode::Auto,
                    };
                    match l3::L3::start(&cidr, 1280, identity, mode) {
                        Ok(m) => {
                            let addr = m.my_addr().map(|a| a.to_string()).unwrap_or(cidr);
                            if m.is_userspace() {
                                ui::say(&format!(
                                    "  {} L3 overlay {} (userspace, zero privilege)",
                                    ui::paint(ui::Tone::Brand, ""),
                                    addr
                                ));
                                ui::say(&ui::paint(ui::Tone::Warn,
                                    "    host firewall/nftables are NOT enforced here; only mesh membership + the expose allowlist gate access"));
                                ui::say("    native tools reach <peer>.mesh via `filament proxy` / `filament dial` (no kernel route in userspace)");
                                // Auto-start SOCKS5 proxy when kernel TUN is unavailable.
                                // Opt-out via --no-proxy-fallback or `filament set auto-proxy off`.
                                let auto_proxy = settings::get_bool("auto-proxy", None)
                                    && !no_proxy_fallback;
                                if auto_proxy {
                                    let server = server.to_string();
                                    tokio::spawn(async move {
                                        if let Err(e) = l2::proxy_cmd(&server, "127.0.0.1", 1080, 0, relay).await {
                                            // Port already in use is expected (user started proxy manually);
                                            // only log unexpected errors.
                                            let msg = e.to_string();
                                            if !msg.contains("already in use") {
                                                ui::debug(&format!("auto-proxy: {e}"));
                                            }
                                        }
                                    });
                                    ui::say(&format!(
                                        "  {} started SOCKS5 proxy on 127.0.0.1:1080 (set your tools' proxy to this)",
                                        ui::paint(ui::Tone::Ok, ui::glyph_ok())
                                    ));
                                    ui::say(&format!(
                                        "    e.g.  curl --socks5-hostname 127.0.0.1:1080 http://<peer>.mesh:8080/"
                                    ));
                                }
                            } else {
                            // Kernel mode is dual-stack: show the v4 address too
                                // (userspace has no v4 endpoint yet, so it is omitted
                                // above to avoid implying a route that does not exist).
                                let v4 = m.my_addr_v4().map(|a| format!(" / {a}")).unwrap_or_default();
                                ui::say(&format!(
                                    "  {} L3 overlay {}{} on filament0",
                                    ui::paint(ui::Tone::Brand, ""),
                                    addr,
                                    v4
                                ));
                                // Show the .mesh name that resolves to this machine.
                                let my_name = l3::hostname();
                                ui::say(&format!(
                                    "    this machine resolves as {}{}",
                                    l3::sanitize_host(&my_name),
                                    ".mesh"
                                ));
                            }
                            // Add this machine's own address to MagicDNS so
                            // `<name>.mesh` resolves locally (not just peers).
                            // Uses the filament device name (from `filament set name`
                            // or hostname if unset), sanitized for DNS.
                            if let Some(id) = m.identity_ref() {
                                let my_name = config_get("name").unwrap_or_else(|| l3::hostname());
                                let v6 = id.addr();
                                let v4 = Some(id.addr_v4());
                                m.names_insert("__self__", &l3::sanitize_host(&my_name), v6, v4).await;
                                if !m.is_userspace() {
                                    m.refresh_hosts().await;
                                }
                                // Configure sshd to listen on overlay addresses if enabled.
                                if settings::get_bool("sshd-overlay", None) {
                                    let v6_str = id.addr().to_string();
                                    let v4_str = id.addr_v4().to_string();
                                    if let Err(e) = sshd::configure_sshd_overlay(&v6_str, &v4_str) {
                                        ui::say(&ui::paint(ui::Tone::Warn, &format!("  sshd-overlay: {e}")));
                                    }
                                }
                            }
                            Some(m)
                        }
                        Err(e) => {
                            ui::say(&ui::paint(ui::Tone::Warn, &format!("  L3 disabled: {e}")));
                            None
                        }
                    }
                }
            }
            None => None,
        }
    } else {
        None
    };
    // `filament expose`: once the overlay is up, bind the persisted ports on the
    // overlay address and forward each to its local target. Reconciled live on a
    // ReloadExpose control request (expose/unexpose without a restart).
    #[cfg(l3)]
    let exposer: Option<std::sync::Arc<expose::Exposer>> = match l3.as_ref() {
        Some(m) => {
            // POSTURE (user decision): a node that SILENTLY fell back to userspace
            // (Auto, no explicit opt-in) must NOT auto-honor expose.json, because
            // userspace bypasses host firewall/nftables on filament0 - an operator
            // who assumed kernel-mode scoping would silently lose it. Only honor
            // expose in userspace when the user opted in (`--userspace` / the env /
            // `l3-mode=userspace`). Kernel mode always honors it.
            let userspace_opt_in = std::env::var("FILAMENT_L3_USERSPACE").as_deref() == Ok("1")
                || settings::get_str("l3-mode", None).as_deref() == Some("userspace");
            if m.is_userspace() && !userspace_opt_in {
                if !expose::load().is_empty() {
                    ui::say(&ui::paint(ui::Tone::Warn,
                        "  expose.json NOT honored: L3 fell back to userspace (host firewall is bypassed there)."));
                    ui::say("    opt in with `filament up --userspace` or `filament set l3-mode userspace` to expose in userspace mode");
                }
                let ex = expose::Exposer::new(m.clone());
                Some(ex) // held so a later live opt-in via ReloadExpose can still bind
            } else {
                let ex = expose::Exposer::new(m.clone());
                let n = ex.reconcile().await;
                if n > 0 {
                    ui::say(&format!(
                        "  {} exposing {} port{} on the overlay",
                        ui::paint(ui::Tone::Brand, ""),
                        n,
                        if n == 1 { "" } else { "s" }
                    ));
                }
                Some(ex)
            }
        }
        None => None,
    };
    let mut by_sid: HashMap<(String, u32), IncomingFile> = HashMap::new();
    // P4 (GAP-5): per-transfer count of whole-file-verify FAILURES (the digest
    // didn't match on completion). Each failure re-requests a resume (truncated)
    // or a from-zero re-fetch (corrupt body); bounded so a genuinely
    // unrecoverable corruption fails CLEARLY after a few rounds rather than
    // looping forever. Keyed by transfer id.
    let mut verify_fails: HashMap<String, u32> = HashMap::new();
    // C22: offers awaiting consent, exactly ONE stdin owner (the reader
    // task); answers arrive as StdinLine events, never via a competing
    // blocking read racing for the user's "y".
    let mut pending: std::collections::VecDeque<(String, Value)> = Default::default();
    let mut completed = 0usize;
    // G-k: peer-left delivery is best-effort, a browser can close having
    // delivered every byte yet never emit its leave (observed under load,
    // gate 6). Tick the loop on a 2s timeout so a fallback quiet-check can
    // exit cleanly instead of idling to the connect-timeout.
    let mut last_quiet: Option<Instant> = None;
    let quiet_window = quiet_exit_window();
    // C30 phase 2: roster reconciliation from sync digests, a missed
    // peer-joined/left self-corrects. Absence must hold for TWO consecutive
    // digests before a drop (one digest can race a join in flight).
    let mut digest_absent: HashMap<String, u8> = HashMap::new();
    let mut digest_alone = false;
    // C30 phase 3: link mini-sync, state pings every ~10s per link.
    let mut last_state_ping = Instant::now();
    // L2 (ssh/TCP tunnel) acceptor: one mux per link, created on the first
    // l2-open seen on that link. `l2_enabled` is computed once above (it also
    // gates the direct-QUIC path); reused here for the mux/cap machinery.
    let mut l2_muxes: HashMap<String, Arc<l2::Mux>> = HashMap::new();
    // Warm-pty session -> (pid, sid), so a `pty-resize` op relays to the right stream.
    let warm_ptys: WarmPtys = std::sync::Arc::new(std::sync::Mutex::new(HashMap::new()));
    // Warm ssh-bootstrap reply sockets awaiting the peer's ack (see PendingBootstraps).
    #[cfg(unix)]
    let mut pending_bootstrap: PendingBootstraps = HashMap::new();
    // Warm-link reuse: ONLY the registered `up` daemon exposes the local control
    // socket (a short-lived `recv`/`send` must never bind it and steal the
    // daemon's path). When a sibling `filament ssh`/`netcat`/`forward` asks to
    // reach a peer we already hold a link to, we open a new L2 stream over that
    // warm link instead of making the sibling establish a fresh one. `ctl_tx` is
    // held for the loop's life so the channel stays open (recv pends, never spins)
    // even when we are not the daemon and `serve` was not spawned.
    let (ctl_tx, mut ctl_rx) = mpsc::unbounded_channel::<ctl::Req>();
    // The control socket is a unix-domain socket, so warm-link reuse is unix-only.
    #[cfg(unix)]
    {
        if daemon_alive() == Some(std::process::id()) {
            let ctl_tx = ctl_tx.clone();
            tokio::spawn(async move {
                if let Err(e) = ctl::serve(ctl_tx).await {
                    crate::ui::trace(&format!("filament: control socket disabled: {e}"));
                }
            });
        }
    }
    // Hold `ctl_tx` for the loop's life so `ctl_rx` stays open (recv pends, never
    // spins) even when `serve` was not spawned (non-unix, or not the daemon).
    #[cfg(not(unix))]
    let _ = &ctl_tx;
    // web-shell (#4): persistent PTY sessions, keyed by a stable browser-chosen
    // session id, OUTLIVE the link that opened them. A dropped data channel
    // DETACHES (does not kill) the shell; a reconnect with the same session id
    // reattaches and replays buffered output. Process-wide for the whole loop.
    let pty_sessions = l2::PtySessions::new();
    // Per-link map of the PTY sids currently bound to a session on that link, so
    // a link drop can DETACH exactly those sessions (and a clean l2-close ends
    // the right one). pid -> (sid -> session_id).
    let mut pty_bindings: HashMap<String, HashMap<u32, String>> = HashMap::new();
    // web-shell: per-sid resize senders are now owned by each Mux (l2.rs) so they
    // are freed on every teardown path (H-1: closes the prior pty_resizers leak).
    // Bug 5: surface the single-host mDNS wedge hint once after repeated stuck.
    let mut stuck_while_connecting = 0u32;
    let mut wedge_hint_shown = false;
    let _saw_known_peer: HashSet<String> = HashSet::new();
    let mut ever_received = false;
    // C12 live-pairing: the roster (`devices`) is loaded ONCE at startup, and
    // KnownPeer events only fire for channels we've SUBSCRIBED. A device paired
    // into the shared store by a SEPARATE `filament pair` process AFTER the
    // daemon is up was therefore invisible until restart, it never got a
    // subscription, so its "appeared, connecting" flow never fired and it
    // could not connect (no transfer, no web-shell). We now re-scan the store
    // on a modest cadence and subscribe to any NEW device's channel live; the
    // session digest (which includes `sess.channels`) repairs a lost subscribe
    // on the next tick. Existing channels and live links are untouched.
    let mut known_channels: std::collections::HashSet<String> =
        devices.iter().map(|(_, s)| channel_of(s)).collect();
    let mut last_devices_scan = Instant::now();

    // Daemon-managed mount state: the daemon holds the sshfs child processes and
    // monitors their health centrally instead of spawning per-mount threads.
    let mut daemon_mounts = DaemonMounts {
        entries: HashMap::new(),
        children: HashMap::new(),
    };
    let mut last_mount_check = Instant::now();

    // WARM-HOLD: periodic check for warm peers that need connections
    let mut last_warm_hold_tick = Instant::now();

    // P2 (GAP-2): outer reconnect / re-announce loop state for the long-lived
    // acceptor. `reconnect(false)` means a severed signaling TCP leaves the
    // socket dead with NO further events, the acceptor zombies and the sender
    // can't rediscover it (the documented `no peer connected` failure that
    // up_supervisor.sh patched from outside the binary). We close it IN-CORE:
    //  - `last_signaling`  : monotonic time of the last inbound signaling event;
    //                        any inbound Ev that originates from the socket bumps
    //                        it (welcome/synced/peer-*/signal/known-peer/...).
    //  - silence watchdog  : if it goes silent past `signaling_silence_ms` (and
    //                        a forced `sync` emit doesn't restore it), the link
    //                        is dead, re-dial. This is the AUTHORITATIVE trigger
    //                        because a hard TCP sever fires no close callback.
    //  - Ev::SignalingDown : the socket.io close/error fast-path accelerant.
    // Only the daemon acceptor self-heals (`signaling_self_heal`); the one-shot
    // recv/send paths re-invoke fresh, so they keep failing fast (unchanged).
    // FILAMENT_TEST_NO_SIGNALING_RECONNECT reverts to the OLD no-outer-loop path
    // so the signaling-drop gate's A/B baseline can prove the acceptor ZOMBIES
    // without the fix (the detector/loop is load-bearing, not incidental).
    let signaling_self_heal = daemon && !test_hooks::no_signaling_reconnect();
    let mut last_signaling = Instant::now();
    let mut signaling_down_since: Option<Instant> = None;
    let mut reconnect_attempt: u32 = 0;
    let mut last_reconnect_try = Instant::now();
    let mut probed_silence = false; // fired one forced sync before declaring down
    let mut last_watchdog = Instant::now();
    // Link self-heal cadence (the multi-minute-outage fix, #3). A transport that
    // died past the QUIC idle timeout lingers in `links` as a zombie and SUPPRESSES
    // the KnownPeer re-dial (start_direct early-returns when a link exists), so the
    // overlay never recovers. We DROP dead links here (so the next KnownPeer
    // re-push re-establishes, single-driver + glare-safe = the model's proven
    // disconnect->recover) but do NOT re-dial ourselves - a timer-based re-dial on
    // BOTH ends caused a supersede storm. The L3 route is intentionally KEPT
    // (continuity), so the re-establish's add_peer swaps the transport under the
    // same overlay IP and the session resumes.
    let mut last_link_health = Instant::now();

    // systemd Type=notify: announce readiness once the serving loop is about to
    // run, then ping the watchdog below. No-op when not run under systemd.
    if daemon {
        sdnotify::ready();
        sdnotify::status("up - serving");
    }

    // Restore mounts that were marked with auto_restore.
    if let Err(e) = mount::restore_mounts(server, relay).await {
        crate::ui::say(&format!("warning: failed to restore mounts: {e}"));
    }

    loop {
        // systemd liveness watchdog: ping on a throttle (well under WatchdogSec).
        // If this loop WEDGES on an await, the pings stop and systemd restarts us
        // - the backstop for the stall that also freezes the reconnect code.
        if daemon && last_watchdog.elapsed() >= Duration::from_secs(5) {
            sdnotify::watchdog();
            last_watchdog = Instant::now();
        }
        // Shutdown-hang repro hook: once links are live, freeze the event loop
        // forever, faithfully simulating a peer transport whose inline write
        // never returns. The graceful Ev::Interrupted can no longer be processed;
        // only the signal-owned force-exit watchdog can still terminate us. No-op
        // unless FILAMENT_TEST_WEDGE_LOOP is set (test-hooks builds only).
        if test_hooks::wedge_loop_on_shutdown() && !conn.links.is_empty() {
            std::future::pending::<()>().await;
        }
        let ev = tokio::select! {
            biased;
            // Warm-link reuse request from a sibling process. Handle it inline
            // (we own `conn`/`l2_muxes` here), then fall through like a tick. For
            // a non-daemon this branch pends forever (ctl_tx held, serve unspawned).
            req = ctl_rx.recv() => {
                if let Some(req) = req {
                    // Bootstrap defers its reply (awaits the peer's ack via this
                    // loop), so it can't go through the inline handle_warm_req; it
                    // stashes the socket in pending_bootstrap instead.
                    #[cfg(unix)]
                    {
                        // `filament set` live-reconfigure: re-read the changed key
                        // into this loop's live state, then report whether it took
                        // without a restart. Handled here (we own dir/policy/sess).
                        if let ctl::ReqKind::Reconfigure { key } = &req.kind {
                            let key = key.clone();
                            let live = apply_reconfigure(
                                &key, &mut dir, &mut shell_policy, &mut shell_user,
                                l2_enabled, &mut sess, &sio, &my_uid,
                            ).await;
                            req.reply(&json!({ "ok": true, "live": live })).await;
                        } else if matches!(&req.kind, ctl::ReqKind::ReloadExpose) {
                            // `filament expose`/`unexpose`: reconcile overlay
                            // listeners from expose.json. live:true only if L3 is up.
                            let (live, count): (bool, usize) = {
                                #[cfg(l3)]
                                {
                                    match exposer.as_ref() {
                                        Some(ex) => (true, ex.reconcile().await),
                                        None => (false, 0),
                                    }
                                }
                                #[cfg(not(l3))]
                                {
                                    (false, 0)
                                }
                            };
                            req.reply(&json!({ "ok": true, "live": live, "count": count })).await;
                        } else if matches!(&req.kind, ctl::ReqKind::Reload) {
                            // `filament update` reload: only safe when a supervisor
                            // will bring us back (systemd sets INVOCATION_ID). Reply
                            // FIRST (the shutdown closes the ctl socket), then take the
                            // SAME graceful path SIGTERM does - which cleanly closes the
                            // QUIC links so peers re-establish and L3 recovers - by
                            // raising SIGTERM on ourselves. systemd's Restart=always
                            // then starts the new binary with fresh ambient caps: no
                            // manual restart, no sudo. Unsupervised, we decline (exiting
                            // would just leave the node down).
                            let supervised = std::env::var("INVOCATION_ID").is_ok();
                            req.reply(&json!({ "ok": true, "reloading": supervised })).await;
                            if supervised {
                                ui::say("filament: reloading onto the updated binary (graceful restart)");
                                #[cfg(unix)]
                                unsafe { libc::raise(libc::SIGTERM); }
                            }
                        } else if matches!(&req.kind, ctl::ReqKind::Dial { .. }) {
                            // Overlay dial (proxy `.mesh` fallback): resolve the peer
                            // to its VERIFIED overlay address ourselves, dial it over
                            // L3, and bridge the ctl socket to it. Spawned so the
                            // long-lived splice never blocks the event loop.
                            #[cfg(l3)]
                            if let ctl::ReqKind::Dial { peer, port } = &req.kind {
                                let (peer, port) = (peer.clone(), *port);
                                match l3.as_ref() {
                                    Some(m) => {
                                        let m = m.clone();
                                        tokio::spawn(async move {
                                            let Some(addr) = m.addr_of(&peer).await else {
                                                req.reject("unknown overlay peer").await;
                                                return;
                                            };
                                            match m.dial(addr, port).await {
                                                Ok(mut stream) => {
                                                    let mut sock = req.accept().await;
                                                    let _ = tokio::io::copy_bidirectional(&mut sock, &mut stream).await;
                                                }
                                                Err(e) => req.reject(&format!("overlay dial failed: {e}")).await,
                                            }
                                        });
                                    }
                                    None => req.reject("L3 overlay is not up").await,
                                }
                            }
                            #[cfg(not(l3))]
                            req.reject("L3 overlay not supported on this build").await;
                        } else if matches!(&req.kind, ctl::ReqKind::Bootstrap { .. }) {
                            handle_warm_bootstrap(&conn, &mut pending_bootstrap, req).await;
                        } else if matches!(&req.kind, ctl::ReqKind::Mount { .. }) {
                            handle_mount(req, &server, relay, &mut daemon_mounts, &mut last_mount_check).await;
                        } else if matches!(&req.kind, ctl::ReqKind::Unmount { .. }) {
                            handle_unmount(req, &mut daemon_mounts).await;
                        } else if matches!(&req.kind, ctl::ReqKind::ListMounts) {
                            handle_list_mounts(req, &daemon_mounts).await;
                        } else if matches!(&req.kind, ctl::ReqKind::MountHealth { .. }) {
                            handle_mount_health(req, &daemon_mounts).await;
                        } else {
                            // Auto-warm: feed LRU for pty sessions (bounded, no leak).
                            if let ctl::ReqKind::Pty { peer, .. } = &req.kind {
                                conn.note_warm_use(peer);
                            }
                            handle_warm_req(&conn, &mut l2_muxes, &warm_ptys, &tx, req).await;
                        }
                    }
                    #[cfg(not(unix))]
                    handle_warm_req(&conn, &mut l2_muxes, &warm_ptys, &tx, req).await;
                }
                None
            }
            res = tokio::time::timeout(
                Duration::from_secs(2),
                next_ev(&mut rx, &conn, !pending.is_empty()),
            ) => match res {
                Ok(res) => res?,
                Err(_) => None, // 2s tick, run the fallback quiet-check below
            },
        };

        // C30: converge session state (no-op unless diverged/stale/unconfirmed).
        sess.tick(&sio).await;

        // L1-a ephemeral PAKE progression (recv code path), PER CANDIDATE PEER.
        // For each candidate's ceremony whose link is up: send our SPAKE2 element,
        // then (once K + both DTLS fingerprints exist) the key-confirmation MAC.
        // Each ceremony is independent, so a decoy peer that never replies just
        // sits until ITS budget expires (dropped below), never blocking the real
        // sender's ceremony. The agreed secret is DISCARDED after auth, never
        // stored. Once one peer authenticates (`recv_pake_done`) we stop driving
        // candidates: the sender is settled.
        if recv_code_path && !recv_pake_done {
            let pids: Vec<String> = recv_cers.keys().cloned().collect();
            for pid in pids {
                let send_msg = recv_cers.get_mut(&pid).and_then(|c| c.take_msg_payload());
                if let Some(data) = send_msg {
                    sio.emit("signal", json!({ "to": pid, "data": data })).await.ok();
                }
                let has_k = recv_cers.get(&pid).map(|c| c.has_k()).unwrap_or(false);
                if has_k {
                    let fps = match conn.link(&pid) {
                        Some(l) => match &l.peer { Some(p) => p.fingerprints().await, None => None },
                        None => None,
                    };
                    if let Some((my_fp, their_fp)) = fps {
                        let conf = recv_cers
                            .get_mut(&pid)
                            .and_then(|c| c.take_confirm_payload(&my_fp, &their_fp));
                        if let Some(data) = conf {
                            sio.emit("signal", json!({ "to": pid, "data": data })).await.ok();
                        }
                    }
                }
            }
        }
        // Per-peer budgets: a candidate whose ceremony never completes within its
        // own budget is dropped INDIVIDUALLY (an unrelated decoy, or an old peer
        // that won't run v2). Dropping it never bails the receive; the real sender
        // keeps its own live budget. Only relevant before someone authenticates.
        if recv_code_path && !recv_pake_done {
            let now = Instant::now();
            let expired: Vec<String> = recv_deadlines
                .iter()
                .filter(|(_, dl)| now > **dl)
                .map(|(pid, _)| pid.clone())
                .collect();
            for pid in expired {
                recv_deadlines.remove(&pid);
                recv_cers.remove(&pid);
                recv_pending_offers.remove(&pid);
                ui::debug(&format!("recv: candidate {pid} did not authenticate in budget, dropped"));
            }
        }
        // Overall deadline: the backstop. Once we are matched into the sender's
        // room a candidate channel arms this; if NO peer authenticates within it,
        // fail the whole `recv` loudly (a genuinely absent / old sender, mirroring
        // the previous single-budget intent and FILAMENT_PAIR_GRACE_SECS) rather
        // than hanging forever.
        if recv_code_path && !recv_pake_done {
            if let Some(dl) = recv_pake_overall_deadline {
                if Instant::now() > dl {
                    bail!("the other device uses an older version and can't send securely over a code. Update it (or this CLI) so the transfer runs the encrypted handshake. Nothing was received.");
                }
            }
        }

        // P2 (GAP-2): the OUTER RECONNECT / RE-ANNOUNCE loop for the long-lived
        // acceptor. Runs only in the daemon path; the one-shot recv/send paths
        // re-invoke fresh on failure and so never need it.
        if signaling_self_heal {
            // (1) Liveness accounting. Any inbound signaling event proves the
            // socket is alive; a successful `sync` ack (Ev::Synced) is the
            // strongest signal (the server answered). The fast-path close/error
            // callback marks the link down immediately.
            let mut saw_down = false;
            match &ev {
                Some(Ev::SignalingDown(_)) => saw_down = true,
                Some(
                    Ev::Welcome(_) | Ev::Synced(_) | Ev::SignalingAlive | Ev::PeerJoined(_)
                    | Ev::PeerLeft(_) | Ev::Signal(_) | Ev::KnownPeer(_) | Ev::KnownPeerLeft(_)
                    | Ev::PairMatched(_) | Ev::PairOk(_) | Ev::PairCode(_) | Ev::PairUsed(_)
                    | Ev::PairError(_),
                ) => {
                    last_signaling = Instant::now();
                    signaling_down_since = None;
                    probed_silence = false;
                    reconnect_attempt = 0;
                }
                _ => {}
            }

            // (2) Silence watchdog, the AUTHORITATIVE trigger. A hard TCP sever
            // fires no close callback, so we watch the inbound gap. Once it
            // exceeds the threshold, fire ONE forced `sync` (the heartbeat); if
            // the socket is alive the server's `synced` ack lands within a tick
            // and resets the gap. If a second threshold passes with still no
            // event, the socket is dead, declare it down.
            let silence = net::signaling_silence_ms();
            let silent_ms = last_signaling.elapsed().as_millis() as u64;
            if signaling_down_since.is_none() {
                if saw_down {
                    signaling_down_since = Some(Instant::now());
                    last_reconnect_try = Instant::now() - Duration::from_secs(60); // re-dial now
                    // Visible (not just debug): a node dropping off signaling was
                    // previously silent until it bit someone. Surface it + reflect
                    // it in `systemctl status` so it's diagnosable at a glance.
                    ui::say(&ui::paint(ui::Tone::Warn, "signaling link closed, reconnecting..."));
                    sdnotify::status("signaling down - reconnecting");
                } else if silent_ms >= silence {
                    if !probed_silence {
                        // Heartbeat probe: an ACK'd `sync` round-trip, the only
                        // liveness signal that works for a room-less idle
                        // acceptor. `sess.tick()` can't serve here: it returns
                        // early when there is no room (the `up` case) AND when
                        // the session is already confirmed-fresh, so on a quiet
                        // link it emitted nothing and the watchdog falsely
                        // reconnected every ~30 s, churning presence. The server
                        // acks `sync` unconditionally; the ack wakes the loop as
                        // Ev::SignalingAlive, which resets the gap below.
                        probed_silence = true;
                        net::heartbeat(&sio, sess.heartbeat_payload(), tx.clone()).await;
                    } else if silent_ms >= silence.saturating_mul(2) {
                        signaling_down_since = Some(Instant::now());
                        last_reconnect_try = Instant::now() - Duration::from_secs(60);
                        // Visible: a silent (half-open) signaling link is the exact
                        // way a node falls off presence without anyone noticing.
                        ui::say(&ui::paint(ui::Tone::Warn, &format!("signaling silent for {silent_ms}ms, reconnecting...")));
                        sdnotify::status("signaling silent - reconnecting");
                    }
                }
            }

            // (3) Re-dial with backoff + jitter. Idempotent: a fresh `welcome`
            // re-asserts room + channel subscriptions through the C30 session
            // (sess.invalidate forces it next tick). Live DATA links are NOT torn
            // down, they ride independent WebRTC/QUIC transports and keep
            // flowing across the cosmetic signaling reconnect (the #28 contract).
            if let Some(down_at) = signaling_down_since {
                // backoff: 0.5s, 1s, 2s, 4s ... capped at 8s, +/-25% jitter.
                let base = 500u64.saturating_mul(1 << reconnect_attempt.min(4)).min(8_000);
                let jitter = (down_at.elapsed().as_nanos() as u64 % (base / 2 + 1)) as i64 - (base as i64 / 4);
                let backoff = Duration::from_millis((base as i64 + jitter).max(100) as u64);
                if last_reconnect_try.elapsed() >= backoff {
                    last_reconnect_try = Instant::now();
                    reconnect_attempt = reconnect_attempt.saturating_add(1);
                    let _ = sio.disconnect().await; // drop the dead client (no-op if already gone)
                    match net::reconnect_signaling(server, tx.clone()).await {
                        Ok(new_sio) => {
                            sio = new_sio;
                            conn.sio = sio.clone();
                            // C30: a fresh sid voids everything the server held,
                            // re-assert room + channels on the next tick. Re-fire
                            // the fast-path join/subscribe immediately too.
                            sess.invalidate();
                            if let Some(room) = sess.room.clone() {
                                sess.emit(&sio, "join", json!({ "room": room, "name": display_name(), "uid": my_uid })).await;
                            }
                            if !sess.channels.is_empty() {
                                let chans = sess.channels.clone();
                                sess.emit(&sio, "subscribe", json!({ "channels": chans })).await;
                            }
                            sess.tick(&sio).await;
                            // optimistic: a clean connect proves reachability; let
                            // the welcome confirm it (which resets the counters).
                            last_signaling = Instant::now();
                            signaling_down_since = None;
                            probed_silence = false;
                            // Visible: pairs with the "reconnecting..." line so the
                            // recovery is observable end to end.
                            ui::say(&ui::paint(ui::Tone::Ok, "signaling reconnected, re-announcing presence"));
                            sdnotify::status("up - serving");
                        }
                        Err(e) => {
                            // DEBUG, resilience internal (signaling reconnect retry).
                            ui::debug(&ui::paint(ui::Tone::Dim, &format!("  signaling reconnect failed ({e}), retrying with backoff")));
                        }
                    }
                }
            }
        }

        // Link self-heal (#3): drop links whose transport has DIED so the KnownPeer
        // re-dial (re-pushed on signaling reconnect + periodic sync) can rebuild
        // them. Same action as the on-demand DropLink handler, just proactive; the
        // L3 route is intentionally NOT retracted (continuity), so the re-establish's
        // add_peer swaps the fresh transport under the same overlay IP. We do NOT
        // re-dial here on purpose (single-driver = the model's proven, churn-free
        // recovery; a both-ends timer re-dial storms).
        if daemon && last_link_health.elapsed() >= Duration::from_secs(8) {
            last_link_health = Instant::now();
            let dead: Vec<String> = conn
                .links
                .iter()
                .filter(|(_, l)| l.transport.as_ref().is_some_and(|t| !t.is_alive()))
                .map(|(pid, _)| pid.clone())
                .collect();
            for pid in dead {
                ui::debug(&format!("filament: link to '{pid}' died, dropping so it can re-connect"));
                conn.drop_link(&pid);
                l2_muxes.remove(&pid);
            }
        }

        // Daemon-managed mount health check: periodically check all tracked
        // mounts and remove dead/stale entries. Runs every 30s, daemon-only.
        if daemon && last_mount_check.elapsed() >= Duration::from_secs(30) {
            last_mount_check = Instant::now();
            let dead_locals: Vec<String> = daemon_mounts.entries.iter()
                .filter_map(|(local, _entry)| {
                    let is_alive = mount::is_mount_point(local);
                    let path_exists = Path::new(local).exists();
                    if !path_exists {
                        Some(local.clone())
                    } else if !is_alive {
                        Some(local.clone())
                    } else {
                        None
                    }
                })
                .collect();
            for local in dead_locals {
                if let Some(entry) = daemon_mounts.entries.remove(&local) {
                    ui::say(&format!("mount {local} is gone, removing from daemon tracking (was {}:{})", entry.peer, entry.remote));
                    // Kill the child process if still tracked.
                    if let Some(mut child) = daemon_mounts.children.remove(&local) {
                        let _ = child.kill().await;
                    }
                    let _ = mount::remove_mount(&local);
                }
            }
        }

        // WARM-HOLD: periodically check for warm peers that need connections.
        // This keeps recently-used and explicitly configured peers connected
        // so `filament ping`/`ssh` is instant. Runs every 10s, daemon-only.
        if daemon && last_warm_hold_tick.elapsed() >= Duration::from_secs(10) {
            last_warm_hold_tick = Instant::now();
            // Warm-all is the DEFAULT (auto-warm setting, opt-out). L3 forces it on:
            // the overlay routes over these links, opting out must not break L3.
            let auto_warm = l3.is_some() || settings::get_bool("auto-warm", None);
            let _ = conn.warm_hold_tick(auto_warm).await;
        }

        // C12 live-pairing: pick up devices paired AFTER we started (a separate
        // `filament pair` writes them into the shared store atomically). Re-read
        // every ~2s, subscribe to any channel we don't already watch, and feed
        // them into `devices` so the KnownPeer handler recognizes them. We never
        // re-subscribe existing channels or touch live links. Daemon-only: a
        // one-shot `recv`/`send` has a fixed roster for its short lifetime.
        if daemon && last_devices_scan.elapsed() >= Duration::from_secs(2) {
            last_devices_scan = Instant::now();
            let mut new_chans: Vec<String> = Vec::new();
            for (n, s) in devices_load() {
                let ch = channel_of(&s);
                if known_channels.insert(ch.clone()) {
                    ui::say(&format!("new device '{n}' paired, now reachable"));
                    devices.push((n, s));
                    new_chans.push(ch);
                }
            }
            if !new_chans.is_empty() {
                // Fast-path emit now; the session digest carries the durable
                // subscription so a dropped emit self-repairs on the next tick.
                for ch in &new_chans {
                    if !sess.channels.contains(ch) {
                        sess.channels.push(ch.clone());
                    }
                }
                sess.emit(&sio, "subscribe", json!({ "channels": new_chans })).await;
            }
        }
        // #28: discharge any deferred peer-left whose channel has gone idle/dead.
        conn.reap_deferred();
        // Drop warm-bootstrap waiters whose peer never acked; the client's read
        // hits EOF and falls back to the cold establish.
        #[cfg(unix)]
        reap_warm_bootstraps(&mut pending_bootstrap);
        // rung-1: direct attempt timed out → fall back to WebRTC (unchanged).
        for (pid, info, (n, sec)) in conn.expired_direct() {
            conn.maybe_adopt(&info, true).await?;
            if let Some(l) = conn.link_mut(&pid) {
                l.expected_secret = Some((n, sec));
            }
        }

        // C30 phase 3: state pings, each open link hears our transfer/away
        // truth every ~10s, so one-sided beliefs between PEERS can't persist.
        if last_state_ping.elapsed() >= Duration::from_secs(10) {
            last_state_ping = Instant::now();
            for (pid, l) in &conn.links {
                if let Some(t) = &l.transport {
                    let mut transfers = serde_json::Map::new();
                    for ((p0, _), inc) in &by_sid {
                        if p0 == pid {
                            transfers.insert(inc.id.clone(), json!(inc.received.load(Ordering::Relaxed)));
                        }
                    }
                    // BOUNDED: this runs inline in the event loop for EVERY link.
                    // A WebRTC data-channel write against a frozen / half-open peer
                    // can block (write_data_channel().await never returns), which
                    // would starve the whole loop, including the signal-driven
                    // Interrupted handler, the multi-link shutdown hang. The state
                    // ping is best-effort, so cap it and move on.
                    let _ = tokio::time::timeout(
                        Duration::from_secs(2),
                        t.send_control(&json!({
                            "type": "state", "v": 1,
                            "transfers": Value::Object(transfers),
                            "trusted": l.trusted,
                            "away": false,
                        })),
                    )
                    .await;
                }
            }
        }

        // G-k completion sweep (top-of-loop): see sweep_completed_streams.
        sweep_completed_streams(&mut by_sid, &conn, &dir, &output, to_stdout, daemon, &mut completed).await?;

        // Gate-18 Mode B: recompute the completion flag AFTER the sweep, every
        // tick (never sticky). When true, a stuck/lost link is DROPPED in
        // on_stuck instead of re-established, see Conn::recv_done. Refreshing it
        // here, where `completed`/`by_sid` were just settled, makes the gate-2/
        // gate-11c fence exact: a mid-transfer link (by_sid non-empty) sees
        // recv_done=false and reconnects unchanged.
        conn.recv_done = protocol::recv_transfer_done(completed, keep_open, by_sid.is_empty());
        // WARM-HOLD: when a transfer completes, mark the peer as warm so we
        // proactively reconnect if the link drops.
        if completed > 0 {
            let warm_peers: Vec<String> = by_sid.keys()
                .filter_map(|(pid, _)| conn.links.get(pid)?.verified_name.clone())
                .collect();
            for name in &warm_peers {
                conn.note_warm_use(name);
            }
        }
        if completed > 0 || !by_sid.is_empty() {
            ever_received = true; // a channel was up; Bug-5 wedge hint no longer applies
        }

        // P0 (GAP-1): bytes-moved STALL watchdog (RECEIVE side). The receiver is
        // the peer that visibly hangs at 0%: when an inbound transfer is in
        // flight (`by_sid` non-empty for a link) but no data byte has arrived
        // past the stall threshold, its transport's idle_ms() climbs. The
        // RECEIVER must also act so a direct-QUIC repair is SYMMETRIC, a fresh
        // authenticated QUIC connection needs both ends to re-dial. We emit
        // Ev::TransferStalled for each such link (liveness-gated), whose handler
        // re-arms this side's direct dial (rung c). The on-disk `.part` is kept,
        // so the resumed stream continues from the saved offset.
        {
            // Per-link: in_flight = this peer has an inbound file mid-transfer
            // (a by_sid entry) OR a stall episode is already open for it (the
            // .part was flushed to disk mid-repair, so by_sid is momentarily
            // empty, detect_stall keeps the episode alive until fresh progress).
            let all_pids: Vec<String> = conn.links.keys().cloned().collect();
            for pid in all_pids {
                let in_flight = by_sid.keys().any(|(p, _)| *p == pid);
                if let Some(idle) = conn.detect_stall(&pid, in_flight) {
                    if conn.link_alive(&pid).await {
                        let _ = tx.send(Ev::TransferStalled(pid, idle));
                    } else {
                        conn.note_progress(&pid);
                    }
                }
            }
        }

        // P5 (GAP-6): relay->direct upgrade prober (receive side). The `up` daemon
        // acceptor is the canonical long-lived session, so the prober defaults ON
        // here. Probe for a direct path while serving on relay; verify-before-
        // upgrade cuts over only on a confirmed-stable direct standby.
        conn.tick_upgrade_prober().await;

        // Gate-18 Mode B DETERMINISTIC repro hook: simulate the post-completion
        // FLAP that contention triggers in the wild (the sender's departure puts
        // the receiver's link into the C4 reconnect loop). Once everything is on
        // disk, force each surviving link to go stuck repeatedly, reset its
        // attempts (mirroring the real flap's attempts-reset, so MAX_ATTEMPTS
        // can never cap it) and re-inject Ev::Stuck. On the BASELINE (no fix)
        // on_stuck re-establishes → link persists → conn.links never empties →
        // hang to timeout (RC=124). WITH the fix on_stuck drops on recv_done →
        // links empties → no link to churn next tick → quiet-exit fires. Driven
        // at LOOP level (not inside on_stuck) so the A/B tests the fix, not
        // itself.
        if conn.recv_done && test_hooks::churn_after_complete() {
            let churn: Vec<(String, u32)> = conn
                .links
                .iter()
                .map(|(pid, l)| (pid.clone(), l.generation))
                .collect();
            for (pid, generation) in churn {
                if let Some(l) = conn.links.get_mut(&pid) {
                    l.attempts = 0; // mirror the real flap: cap never accumulates
                    // Tear the data channel down so on_stuck's is_connected()
                    // guard sees a dead link and the Stuck isn't swallowed.
                    if let Some(p) = &l.peer {
                        p.close().await;
                    }
                }
                let _ = conn.tx.send(Ev::Stuck(pid, generation));
            }
        }

        // #28 exit reconciliation: once everything is received and the only links
        // left are ones held open purely for their deferred-drop reap (their
        // sender's signaling left AFTER the transfer finished), there is nothing
        // in flight to protect, exit promptly instead of paying the full
        // FILAMENT_ADOPT_ACTIVE_MS deferral. Restores the pre-#28 prompt exit; an
        // in-progress reconnect keeps `by_sid` non-empty and so is unaffected.
        if completed > 0 && !keep_open && by_sid.is_empty() && pending.is_empty()
            && !conn.links.is_empty() && conn.only_deferred_links()
        {
            ui::say(&format!("done ({completed} file{}).", if completed == 1 { "" } else { "s" }));
            let _ = sio.disconnect().await;
            return Ok(());
        }

        // Bug 2: the transfer is COMPLETE and the sender's link is fully GONE
        // (dropped via peer-left, or via the grace/Mode-B path when peer-left
        // was lost). With no live link and nothing left to fetch there is
        // nothing to wait for, exit at once instead of holding out the full
        // rejoin window (peer-left case) or the quiet-exit window (lost-peer-left
        // case). Fenced exactly like the exits above: by_sid empty + no pending
        // questions, so a mid-transfer reconnect (which keeps `by_sid`
        // non-empty) is untouched, and --keep-open still lingers by design.
        if completed > 0 && !keep_open && by_sid.is_empty() && pending.is_empty()
            && conn.links.is_empty()
        {
            conn.rejoin.waiting_rejoin = None;
            ui::clear_sticky();
            ui::say(&format!("done ({completed} file{}).", if completed == 1 { "" } else { "s" }));
            let _ = sio.disconnect().await;
            return Ok(());
        }

        // G-k fallback: everything done, nobody attached, no questions
        // outstanding, if that holds quietly for the quiet-exit window (10s
        // default, FILAMENT_QUIET_EXIT_SECS overrides), the peer-left we were
        // counting on for a clean exit never arrived; exit anyway. C30 ph2:
        // ALSO satisfied when the server's digest says the room is empty and
        // no room-independent (channel) link remains, lingering dead links
        // can't block the exit when the server knows nobody's there.
        let digest_says_alone = digest_alone && conn.links.values().all(|l| l.expected_secret.is_none());
        // #28 Mode B: a dead link that keeps FLAPPING, on_stuck reconnect, or a
        // roster/session reconcile re-adopting the gone sender and re-arming
        // `expected_secret` so `digest_says_alone` never holds, must NOT block
        // this fallback once everything is received; `conn.links` may never
        // empty under churn (the RC=124 hang). Surgical: discriminate on link
        // HEALTH, not existence, a churning/reconnecting/dead link (never
        // `Ready`) does not block exit, but a healthy `Ready` link (e.g. a
        // bystander between two human-paced sends, gate 6) STILL does. So this is
        // a no-op for healthy peers, not a behaviour change, only a peer we've
        // lost contact with stops blocking. FILAMENT_TEST_DISABLE_MODEB_DROP
        // restores the old links-gated behaviour so gate 18b proves the A/B
        // (baseline hangs, fix exits) with one binary.
        let no_healthy_link = conn.links.values().all(|l| !matches!(l.presence, Presence::Ready));
        let links_clear = if !test_hooks::disable_modeb_drop() {
            no_healthy_link
        } else {
            conn.links.is_empty() || digest_says_alone
        };
        if completed > 0 && !keep_open && by_sid.is_empty() && pending.is_empty() && links_clear {
            match last_quiet {
                None => last_quiet = Some(Instant::now()),
                Some(since) if since.elapsed() > quiet_window => {
                    ui::say(&ui::paint(ui::Tone::Dim, "  (peer-left never arrived, exiting on quiet)"));
                    ui::say(&format!("done ({completed} file{}).", if completed == 1 { "" } else { "s" }));
                    let _ = sio.disconnect().await;
                    return Ok(());
                }
                Some(_) => {}
            }
        } else {
            last_quiet = None;
        }

        let Some(ev) = ev else { continue };

        // C23: questions from links that died (supersede/peer-left) are
        // moot, the sender re-offers on its new link. Purge them so a 'y'
        // can never accept a ghost (the duplicate-stream ENOENT crash).
        if !pending.is_empty() {
            let front_id = pending.front().map(|(_, v)| v["id"].clone());
            pending.retain(|(p, _)| conn.links.contains_key(p));
            if pending.front().map(|(_, v)| v["id"].clone()) != front_id {
                ui::clear_sticky();
                if let Some((qpid, qv)) = pending.front() {
                    let s = conn.link(qpid).map(|l| l.name.clone()).unwrap_or_default();
                    {
                        let q = offer_question(&s, qv["name"].as_str().unwrap_or("file"), qv["size"].as_u64().unwrap_or(0), paired);
                        ui::say(&q); // permanent: a new question fronted (C25)
                        ui::sticky(&q);
                        question_shown = Instant::now();
                    }
                } else {
                    question_open.store(false, std::sync::atomic::Ordering::Relaxed);
                }
            }
        }

        match ev {
            // A warm-reuse open found this held link black-holing new streams
            // (zombie: alive at QUIC, dead for data). Drop it so the proactive
            // re-connect forms a fresh, healthy held link and warm-reuse goes
            // back to instant. Live DATA links are untouched (each ssh/pty op
            // rides its own stream; the dropped link had no working stream).
            Ev::DropLink(pid) => {
                if conn.links.contains_key(&pid) {
                    ui::debug(&format!("filament: dropping zombie warm link to '{pid}' (black-holed a stream)"));
                    conn.drop_link(&pid);
                    l2_muxes.remove(&pid);
                    // CONTINUITY: do NOT retract the L3 route here. A dropped link
                    // is almost always followed by a repair (a fresh transport for
                    // the same peer), whose add_peer atomically swaps the route. If
                    // we retracted now, the overlay IP would be briefly unroutable
                    // and a live ssh/L3 session could reset across the repair. The
                    // stale route just drops datagrams (the inner TCP pauses) until
                    // the swap. The cached announce is dropped so the peer's next
                    // announce is treated fresh.
                    #[cfg(l3)]
                    l3_seen.remove(&pid);
                }
            }
            Ev::PairMatched(v) => {
                claim_in_flight = false;
                let room = v["room"].as_str().unwrap_or_default().to_string();
                ui::say(&format!("  {} code accepted, joining sender", ui::paint(ui::Tone::Ok, ui::glyph_ok())));
                sess.room = Some(room.clone()); // C30: desire moves; session repairs if the join dies
                sess.touch();
                sess.emit(&sio, "join", json!({ "room": room, "name": display_name(), "uid": my_uid })).await;
            }
            // C30: server confirmed our session digest. Phase 2: reconcile
            // the roster it carries, missed peer-joined/left self-correct.
            Ev::Synced(v) => {
                if let Some(peers) = sess.on_synced(&v) {
                    digest_alone = peers.is_empty();
                    let present: std::collections::HashSet<String> = peers
                        .iter()
                        .filter_map(|p| p["id"].as_str().map(String::from))
                        .collect();
                    // unknown in digest → a peer-joined we never received
                    for p in &peers {
                        let id = p["id"].as_str().unwrap_or_default();
                        if !id.is_empty() && !conn.links.contains_key(id) {
                            ui::debug(&ui::paint(ui::Tone::Dim, "  (digest: adopting a peer we never heard join)"));
                            conn.maybe_adopt(p, true).await?;
                        }
                    }
                    // known room-sourced link absent ×2 → a peer-left we
                    // never received (channel-introduced links are exempt:
                    // room-independent by design)
                    let mut gone: Vec<String> = Vec::new();
                    for (pid, l) in &conn.links {
                        if l.expected_secret.is_none() && !present.contains(pid) {
                            let c = digest_absent.entry(pid.clone()).or_insert(0);
                            *c += 1;
                            if *c >= 2 {
                                gone.push(pid.clone());
                            }
                        } else {
                            digest_absent.remove(pid);
                        }
                    }
                    for pid in gone {
                        digest_absent.remove(&pid);
                        let name = conn.link(&pid).map(|l| l.name.clone()).unwrap_or_default();
                        conn.drop_link(&pid);
                        ui::say(&conn.roster(&pid, "", ui::Tone::Dim, "left (digest reconcile), still listening", &name));
                    }
                }
            }
            // C29: a code minted in-session (`pair` typed into up).
            Ev::PairCode(v) => {
                let c = v["code"].as_str().unwrap_or("?");
                ui::clipboard(c);
                ui::say("");
                ui::say(&format!("      {}", ui::paint(ui::Tone::Brand, &c.to_uppercase())));
                ui::say("");
                ui::say(&ui::paint(ui::Tone::Dim, "  say it aloud, they type it in the web app or `filament pair <code>` · one claim · 10 min"));
            }
            Ev::PairUsed(_) => {
                ui::say(&ui::paint(ui::Tone::Dim, "  code claimed, connecting..."));
            }
            Ev::PairError(v) => {
                let why = v["error"].as_str().unwrap_or("?").to_string();
                // The server distinguishes (additively) a dead creator from a
                // typo'd/expired code, say the actionable thing for each.
                let hint = match v["why"].as_str() {
                    Some("sender-gone") => "the sender who made that code already left, ask them for a fresh one".to_string(),
                    _ => format!("{why}, codes burn after one use and expire after 10 min"),
                };
                if code.is_some() && conn.links.is_empty() && completed == 0 {
                    // started WITH a code that failed: nothing else to do
                    bail!("code rejected: {hint}");
                }
                // a TYPED claim failing must not kill a listening session
                paired = false;
                claim_in_flight = false;
                ui::say(&format!(
                    "  {} code rejected: {hint}; still listening",
                    ui::paint(ui::Tone::Err, ui::glyph_err()),
                ));
            }
            Ev::Welcome(v) => {
                conn.my_id = v["id"].as_str().unwrap_or_default().to_string();
                // P5 (GAP-6): a fresh welcome (signaling reconnect) may mean the
                // network just changed under us, re-probe relay-committed peers for
                // a direct path immediately instead of waiting out the backoff.
                conn.reprobe_on_network_event();
                if let Some(peers) = v["peers"].as_array() {
                    for p in peers {
                        conn.maybe_adopt(p, true).await?;
                    }
                }
                // C30 (dissolves the C28 belt): a welcome means a fresh sid,
                // everything sid-keyed (subscriptions, lease) died with the
                // old one. Invalidate; the next tick re-asserts everything.
                sess.invalidate();
            }
            Ev::KnownPeer(v) => {
                if is_self_uid(&conn.my_uid, v["uid"].as_str()) {
                    continue; // our own sender/daemon shares these channels
                }
                if let Some((n, sec)) = devices.iter().find(|(_, s)| channel_of(s) == v["channel"].as_str().unwrap_or("")) {
                    let pid = v["id"].as_str().unwrap_or_default().to_string();
                    // WARM-HOLD: a known peer just came online. Under auto-warm, adopt it
                    // into the auto tier NOW (don't wait up to 10s for the tick) and clear
                    // any dormancy/backoff so the reconnect loop owns it from t=0. The
                    // start_direct/maybe_adopt below already dial immediately; this makes
                    // warm-hold RETRY if that first dial fails or the link later drops.
                    // Do NOT add to recent-LRU (that's for ACTUAL use only).
                    let auto_warm = l3.is_some() || settings::get_bool("auto-warm", None);
                    if auto_warm {
                        conn.warm_hold.auto.insert(n.clone());
                    }
                    if conn.warm_hold.should_connect(n) {
                        conn.warm_hold.resume(n);
                        // Pull the next warm tick forward: the event loop wakes at least every
                        // 2s (next_ev timeout, :8957-8960), so a failed eager dial is retried
                        // within ~2s instead of ~10s.
                        last_warm_hold_tick = Instant::now()
                            .checked_sub(Duration::from_secs(10))
                            .unwrap_or_else(Instant::now);
                    }
                    // Only announce a FRESH connect. The server re-pushes the
                    // known-peer roster on every (re)subscribe and C30 sync tick, so
                    // a peer we already hold a link to (or are already dialing) would
                    // otherwise reprint "appeared, connecting" on a loop, reading
                    // like a flap even though `start_direct` below no-ops for an
                    // existing link (start_direct_inner early-return). A real
                    // reconnect removes the link first, so it still announces.
                    let fresh = !conn.links.contains_key(&pid)
                        && !conn.direct_pending.contains_key(&pid);
                    // Also re-announce if the existing link's transport is dead
                    let link_dead = conn.links.get(&pid)
                        .and_then(|l| l.transport.as_ref())
                        .map(|t| t.is_dead())
                        .unwrap_or(false);
                    if fresh || link_dead {
                        ui::say(&format!("known device '{n}' appeared, connecting"));
                        devices_touch(n, None, None);  // track last_seen; addresses filled on ChannelReady
                    } else {
                        ui::trace(&format!("known device '{n}' re-announced (link already up)"));
                    }
                    // rung-1: known device = both CLIs; try direct QUIC first.
                    let (n, sec) = (n.clone(), sec.clone());
                    conn.start_direct(&pid, &n, &sec).await;
                    conn.maybe_adopt(&v, true).await?;
                    if let Some(l) = conn.link_mut(&pid) {
                        l.expected_secret = Some((n.clone(), sec.clone()));
                    }
                }
            }
            Ev::PeerJoined(v) => {
                let had_partials = !by_sid.is_empty();
                if conn.maybe_adopt(&v, true).await? && had_partials {
                    // Stale per-link sid routing dies with the old link; the
                    // .part files live on and the sender's resume re-offers.
                    flush_inflight(&mut by_sid).await;
                }
            }
            Ev::Signal(v) => {
                let from = v["from"].as_str().unwrap_or_default().to_string();
                let data = v["data"].clone();
                // rung-1: a relayed transport-offer carries the peer's direct
                // candidates, start the simultaneous-open + auth race.
                if data["type"].as_str() == Some("transport-offer") {
                    let cands: Vec<String> = data["addrs"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect())
                        .unwrap_or_default();
                    // rung-2: optional server-reflexive candidate for hole-punch.
                    let srflx = data["srflx"].as_str().map(String::from);
                    // P5 (GAP-6): a `probe:true` offer is a relay->direct UPGRADE
                    // probe from the other end. If we're serving this peer on relay
                    // and have no probe of our own yet, ARM one so the symmetric
                    // direct dial can complete (a later re-send of the offer, the
                    // peer re-emits 6x, is consumed by our now-armed pending). The
                    // winner posts DirectUpgradeReady (verify-before-upgrade), never
                    // clobbering the serving relay link.
                    if data["probe"].as_bool() == Some(true) {
                        conn.answer_upgrade_probe(&from).await;
                    }
                    conn.on_transport_offer(&from, cands, srflx);
                    continue;
                }
                // L1-a: PAKE messages ride the opaque `signal` relay. Route them
                // into THAT `from` peer's own ephemeral ceremony (recv code path).
                // On confirm the secret is agreed; that peer becomes the
                // authenticated sender and we DISCARD the secret. A failed/aborted
                // ceremony drops ONLY that candidate (a decoy / wrong-words peer),
                // it never bails the receive: the real sender's ceremony is
                // independent and still live.
                if recv_code_path
                    && matches!(data["type"].as_str(), Some("pake-msg") | Some("pake-confirm"))
                {
                    // Already authenticated a sender? Ignore stray PAKE traffic
                    // from anyone else, including a late decoy.
                    if recv_pake_done {
                        continue;
                    }
                    // Mint this peer's ceremony on first sight (bounded), or route
                    // into its existing one. If the peer was already dropped (budget
                    // expired) or we are at the candidate cap, ignore its traffic.
                    if !recv_cers.contains_key(&from) {
                        if recv_cers.len() >= RECV_MAX_CANDIDATES {
                            ui::debug("recv: candidate cap reached, ignoring extra peer's PAKE");
                            continue;
                        }
                        if let Some((pw, np)) = &recv_pake_template {
                            recv_cers.insert(from.clone(), Ceremony::new(pw, np, pair_v2_caps()));
                            recv_deadlines
                                .entry(from.clone())
                                .or_insert_with(|| Instant::now() + recv_pake_budget);
                            recv_pake_overall_deadline
                                .get_or_insert_with(|| Instant::now() + recv_pake_budget);
                        }
                    }
                    let fps = match conn.link(&from) {
                        Some(l) => match &l.peer { Some(p) => p.fingerprints().await, None => None },
                        None => None,
                    };
                    let fp_ref = fps.as_ref().map(|(a, b)| (a.as_str(), b.as_str()));
                    if let Some(cer) = recv_cers.get_mut(&from) {
                        match cer.on_signal(&data, fp_ref) {
                            PakeInbound::Consumed => {
                                if cer.secret().is_some() {
                                    // This peer authenticated. Record it as THE
                                    // sender, DISCARD the secret (auth only), and
                                    // forget the other candidates.
                                    recv_pake_peer = Some(from.clone());
                                    recv_pake_done = true;
                                    recv_cers.clear();
                                    recv_deadlines.clear();
                                    ui::say(&ui::paint(ui::Tone::Dim, "  authenticated, receiving"));
                                    // Replay any offer this peer sent while we were
                                    // still authenticating (the offer that raced the
                                    // confirm), and drop the others' buffered offers.
                                    let buffered = recv_pending_offers.remove(&from);
                                    recv_pending_offers.clear();
                                    if let Some(offer) = buffered {
                                        let _ = tx.send(Ev::Control(from.clone(), offer));
                                    }
                                }
                            }
                            PakeInbound::Abort(why) => {
                                // Drop THIS candidate only; the receive lives on.
                                recv_cers.remove(&from);
                                recv_deadlines.remove(&from);
                                recv_pending_offers.remove(&from);
                                ui::debug(&format!("recv: candidate {from} refused ({why}), dropped"));
                            }
                            PakeInbound::Ignored => {}
                        }
                    }
                    continue;
                }
                // C18: an offer from an unlinked roster peer creates a polite
                // responder link (browsers mesh-dial everyone, fix #7 rules).
                conn.ensure_responder(&from, &data).await?;
                conn.apply_signal(&from, data).await;
            }
            // rung-1: authenticated direct-QUIC won the race, adopt as a
            // pre-trusted Link, then funnel into the normal ChannelReady handler.
            Ev::DirectReady(pid, t, route) => {
                let tkey = conn.direct_pending.get(&pid)
                    .map(|p| direct::transport_key(&p.secret.1));
                conn.adopt_direct(&pid, t.clone(), route);
                if let Some(k) = tkey {
                    conn.spawn_direct_workers(&pid, &t, k);
                }
                let _ = tx.send(Ev::ChannelReady(pid, t));
            }
            Ev::DirectWorkersReady(pid, workers) => {
                if let Some(link) = conn.link_mut(&pid) {
                    link.workers = workers;
                    crate::ui::debug(&format!("worker transports ready: {pid} {} workers", link.workers.len()));
                }
            }
            // P5 (GAP-6): relay->direct upgrade standby connected (receiver side).
            // Stash + VERIFY rather than adopt, see the send-loop twin.
            Ev::DirectUpgradeReady(pid, t, route) => {
                conn.stash_upgrade_standby(&pid, t, route);
            }
            Ev::ChannelReady(pid, t) => {
                // web-shell discovery: tell the peer whether this receiver offers a
                // terminal (l2_enabled = `up --shell` / FILAMENT_L2). The browser
                // shows its per-device shell button ONLY when this is true; the
                // actual pty-open is still gated server-side by the cap/policy.
                let _ = t.send_control(&json!({ "type": "caps", "shell": l2_enabled })).await;
                // L3 (serve_tun mesh): on a datagram-capable (direct) link, send a
                // SIGNED announce of our overlay address, bound to THIS link's
                // channel binding so it can't be replayed elsewhere. Both ends
                // announce on their own ChannelReady, so each learns the other.
                // Also replay any announce that arrived BEFORE this transport was
                // installed (fix #3), now that the link can carry datagrams.
                #[cfg(l3)]
                if let Some(l3) = l3.as_ref() {
                    if let Some(cb) = t.channel_binding() {
                        if let Some(ann) = l3.make_announce(&cb) {
                            let _ = t.send_control(&ann.to_json()).await;
                        }
                        if let Some(pending) = l3_seen.get(&pid) {
                            if let Ok(ip) = pending.verify(&cb) {
                                let who = conn.link(&pid).map(|l| l.shown()).unwrap_or_default();
                                let v4 = pending.addr_v4();
                                l3.add_peer(&pid, &who, ip.into(), Some(v4.into()), t.clone()).await;
                                // Store overlay addresses for `filament addr <device>`
                                devices_touch(&who, Some(ip), Some(v4));
                            }
                        }
                    }
                }
                if let Some(l) = conn.link_mut(&pid) {
                    ui::say(&format!("  {} {}", ui::paint(ui::Tone::Ok, ui::glyph_ok()), ui::paint(ui::Tone::Bold, l.shown())));
                    l.transport = Some(t.clone());
                    l.presence = Presence::Ready;
                    let is_direct = l.direct;
                    let direct_route = l.direct_route;
                    if let Some(p) = l.peer.clone() {
                        tokio::spawn(async move {
                            // ICE may renominate; retry briefly (mirrors the
                            // browser's _detectRoute attempts) so fast transfers
                            // still get a route line before the process exits.
                            for _ in 0..6 {
                                tokio::time::sleep(Duration::from_millis(400)).await;
                                if let Some(r) = p.route().await {
                                    // CRITICAL: the route label is the value-prop,
                                    // direct vs relayed. Always shown, even under -q.
                                    ui::debug(&format!("    {}", ui::paint(ui::Tone::Dim, &format!("route: {r}"))));
                                    // Relay honesty (§3.3): the quiet `route:` line
                                    // is legible but not loud. When the route is
                                    // actually the TURN relay, print the honest
                                    // one-line banner so the user is never unaware
                                    // they're on a middleman path. CRITICAL.
                                    if r == "relayed" {
                                        ui::critical(&format!("    {}", relay_banner()));
                                    }
                                    break;
                                }
                            }
                        });
                    } else if is_direct {
                        ui::debug(&format!("    {}", ui::paint(ui::Tone::Dim, &format!("route: {direct_route}"))));
                    }
                }
                // Warm-reuse readiness: proactively prove our identity to a KNOWN
                // peer on a RELAY/WebRTC link (a DIRECT link is born-verified at
                // adoption, so it skips this). `send_cmd` already does this on its
                // active transfer link (the ChannelReady proof ~5205); the daemon
                // must too, otherwise a passively-held link reaches `✓` but neither
                // end ever sets `verified_name`, so `warm_link_for` rejects it and
                // the FIRST ssh/pty/netcat to an idle paired peer eats a full cold
                // establish. Symmetric by construction: both daemons send, both
                // verify (the `pair-proof` handler below), both can then warm-reuse.
                // No guard, mirroring send_cmd: re-proving on a reconnect is
                // harmless and just refreshes trust.
                let proof_creds = conn.link(&pid).and_then(|l| {
                    if l.direct {
                        return None;
                    }
                    let (_n, sec) = l.expected_secret.clone()?;
                    Some((sec, l.uid.clone().unwrap_or_default(), l.peer.clone()))
                });
                if let Some((sec, uid, peer)) = proof_creds {
                    if let Some((my_fp, their_fp)) = match peer {
                        Some(p) => p.fingerprints().await,
                        None => None,
                    } {
                        let mac = proof_for(&sec, &conn.my_uid, &conn.my_uid, &uid, &my_fp, &their_fp);
                        let _ = t.send_control(&json!({ "type": "pair-proof", "mac": mac })).await;
                    }
                }
                // L1-a: on the `recv <code>` path, this peer is a CANDIDATE sender.
                // Mint its own ephemeral ceremony (bounded) and arm its per-peer
                // budget plus the overall backstop. The progression block (top of
                // loop) drives every candidate independently; file-offers are not
                // accepted until ONE peer's ceremony confirms (`recv_pake_done`),
                // and then only from that authenticated peer. A direct link is
                // already authenticated (its pair-secret MAC bound the QUIC key,
                // `trusted`), so it skips the PAKE.
                if recv_code_path && !recv_pake_done {
                    let (is_direct, is_trusted) = conn
                        .link(&pid)
                        .map(|l| (l.direct, l.trusted))
                        .unwrap_or((false, false));
                    if is_direct && is_trusted {
                        // A secret-bound direct link is the sender (known device).
                        recv_pake_peer = Some(pid.clone());
                        recv_pake_done = true; // pre-authenticated transport
                        recv_cers.clear();
                        recv_deadlines.clear();
                        let buffered = recv_pending_offers.remove(&pid);
                        recv_pending_offers.clear();
                        if let Some(offer) = buffered {
                            let _ = tx.send(Ev::Control(pid.clone(), offer));
                        }
                    } else if recv_cers.contains_key(&pid) {
                        // Ceremony already minted (its PAKE traffic arrived first);
                        // just make sure its budgets are armed.
                        recv_deadlines
                            .entry(pid.clone())
                            .or_insert_with(|| Instant::now() + recv_pake_budget);
                        recv_pake_overall_deadline
                            .get_or_insert_with(|| Instant::now() + recv_pake_budget);
                    } else if recv_cers.len() < RECV_MAX_CANDIDATES {
                        if let Some((pw, np)) = &recv_pake_template {
                            recv_cers.insert(pid.clone(), Ceremony::new(pw, np, pair_v2_caps()));
                            recv_deadlines
                                .insert(pid.clone(), Instant::now() + recv_pake_budget);
                            recv_pake_overall_deadline
                                .get_or_insert_with(|| Instant::now() + recv_pake_budget);
                            ui::say(&ui::paint(ui::Tone::Dim, "  authenticating..."));
                        }
                    }
                }
                // C29: an in-session pairing, exactly one side hands over a
                // secret; consent (pair-keep-ack / our store) completes it.
                // Only links that aren't ALREADY known are candidates.
                let fresh_link = conn.link(&pid).map(|l| l.expected_secret.is_none()).unwrap_or(false);
                if fresh_link {
                    match ceremony {
                        Some(true) => {
                            // we minted the code, initiate now
                            ceremony = None;
                            ceremony_pid = Some(pid.clone());
                            t.send_control(&json!({ "type": "pair-keep", "secret": ceremony_secret })).await.ok();
                        }
                        Some(false) => {
                            // we claimed, give a CLI creator 3 s to initiate
                            // (browsers never do), then take over.
                            let tx = tx.clone();
                            let pid = pid.clone();
                            tokio::spawn(async move {
                                tokio::time::sleep(Duration::from_secs(3)).await;
                                let _ = tx.send(Ev::Control(pid, json!({ "type": "__pair_fallback" })));
                            });
                        }
                        None => {}
                    }
                }
            }
            Ev::Control(pid, v) => match v["type"].as_str() {
                // L3 (serve_tun): the peer announced its overlay IP. Route that IP
                // to this link and start pumping its datagrams into our TUN. Only
                // when we run an overlay ourselves; ignored otherwise.
                // Check BEFORE the catch-all guard so announces that race ahead of
                // link creation are cached in l3_seen for replay on ChannelReady.
                #[cfg(l3)]
                Some("l3-announce") if l3.is_some() => {
                    match overlay::Announce::from_json(&v) {
                        Ok(ann) => {
                            l3_seen.insert(pid.clone(), ann.clone());
                            // Try to process immediately if transport is available.
                            if let Some(l3) = l3.as_ref() {
                                match conn.transport_of(&pid).and_then(|t| t.channel_binding().map(|cb| (t, cb))) {
                                    Some((t, cb)) => match ann.verify(&cb) {
                                        Ok(ip) => {
                                            let who = conn.link(&pid).map(|l| l.shown()).unwrap_or_default();
                                            let v4 = ann.addr_v4();
                                            l3.add_peer(&pid, &who, ip.into(), Some(v4.into()), t).await;
                                            ui::say(&format!("  {} L3 peer {who}.mesh ({ip} / {v4})", ui::paint(ui::Tone::Ok, ui::glyph_ok())));
                                            devices_touch(&who, Some(ip), Some(v4));
                                        }
                                        Err(e) => ui::debug(&ui::paint(ui::Tone::Warn, &format!("  L3 announce rejected: {e}"))),
                                    },
                                    // Transport not installed yet: kept in l3_seen, replayed on ChannelReady.
                                    None => {}
                                }
                            }
                        }
                        Err(e) => ui::debug(&format!("  L3 malformed announce: {e}")),
                    }
                }
                Some("worker-ports") => {
                    let pid = v["for"].as_str().unwrap_or_default();
                    eprintln!("[T:CLI] worker-ports handler: looking up key={pid}");
                    if let Some(tx) = conn.worker_port_tx.remove(pid) {
                        eprintln!("[T:CLI] worker-ports handler: FOUND key={pid}");
                        let ports: Vec<u16> = v["ports"]
                            .as_array()
                            .map(|a| {
                                a.iter()
                                    .filter_map(|p| p.as_u64().map(|x| x as u16))
                                    .collect()
                            })
                            .unwrap_or_default();
                        let _ = tx.send(ports);
                    }
                }
                _ if !conn.links.contains_key(&pid) => {}
                // Warm-reuse liveness: the acceptor confirmed a stream WE initiated
                // (a warm `open`) is connected end to end. Route it to the mux so
                // verify_first_frame passes even for a client-speaks-first service
                // (HTTP, DB clients) that sends no bytes until we do, instead of the
                // verify window expiring and a HEALTHY link being dropped as a zombie
                // (which made every warm `forward` fall to a cold link). See
                // l2::Mux::on_open_ack.
                Some("l2-open-ack") if l2_enabled => {
                    if let Some(sid) = v["sid"].as_u64() {
                        if let Some(mux) = l2_muxes.get(&pid) {
                            mux.on_open_ack(sid as u32).await;
                        }
                    }
                }
                // L2 (ssh/TCP tunnel) acceptor. Opt-in (FILAMENT_L2=1). The
                // capability gate is the proof-verified `trusted` flag on this
                // link (placeholder for L1-a caps); localhost-only is enforced in
                // accept_control. A non-trusted or non-loopback open is refused.
                Some("l2-open") | Some("l2-close") if l2_enabled => {
                    // TODO(diag acceptor): emit a diag::Attempt with role
                    // "acceptor" for this l2-open->l2-open-ack round trip. Deferred
                    // because the acceptor has no per-connect span here: this fires
                    // on an ALREADY-established shared link inside the big up/recv
                    // loop (the link's bring-up lives in the file-transfer/recv
                    // machinery upstream), so a clean span would mean threading an
                    // Attempt through the whole loop. The initiator path (l2.rs) is
                    // fully instrumented and is the side that exhibits the stall.
                    let Some(t) = conn.transport_of(&pid) else { continue };
                    let trusted = conn.link(&pid).map(|l| l.trusted).unwrap_or(false);
                    // Per-device authorization for a NEW open (an l2-close just
                    // tears a stream down, so it is never gated here). In a blanket
                    // mode any trusted peer may open; in grant-only mode the opening
                    // peer must hold the shell grant itself.
                    let authorized = v["type"].as_str() != Some("l2-open") || {
                        let blanket = shell_policy.enables_l2()
                            || std::env::var("FILAMENT_L2").map(|x| x == "1").unwrap_or(false);
                        let peer_has_shell = conn
                            .link(&pid)
                            .and_then(|l| l.verified_name.as_deref())
                            .map(|n| device_allows(n, "shell"))
                            .unwrap_or(false);
                        l2_open_allowed(blanket, peer_has_shell)
                    };
                    if !authorized {
                        let sid = v["sid"].as_u64().unwrap_or(0) as u32;
                        ui::say(&format!("l2: refused stream {sid:#x}: device not granted shell"));
                        let _ = t
                            .send_control(&json!({ "type": "l2-close", "sid": sid, "err": "not authorized: device lacks shell grant" }))
                            .await;
                    } else {
                        // Opt-in gateway: if the target is non-loopback, allow it
                        // only when the operator's l2-allow.json lists it for this
                        // device (or "*"). Loopback ignores this (always allowed).
                        let allow_nonloopback = {
                            let host = v["host"].as_str().unwrap_or("127.0.0.1");
                            let port = v["rport"].as_u64().or_else(|| v["port"].as_u64()).unwrap_or(0) as u16;
                            let name = conn
                                .link(&pid)
                                .and_then(|l| l.verified_name.clone())
                                .unwrap_or_default();
                            l2_target_allowed(&name, host, port)
                        };
                        let mux = l2_muxes
                            .entry(pid.clone())
                            .or_insert_with(|| l2::Mux::new(t.clone()))
                            .clone();
                        match mux.accept_control(&v, trusted, allow_nonloopback).await {
                            l2::OpenVerdict::Accept { sid, host, port, rx } => {
                                tokio::spawn(mux.clone().dial_and_serve(sid, host, port, rx));
                            }
                            l2::OpenVerdict::Deny { sid, err } => {
                                // Log refused dials at INFO (visible by default,
                                // suppressed under -q) - a refused SSRF/port-scan or
                                // untrusted/over-cap open is a security event the
                                // operator should see, mirroring the
                                // shell-bootstrap-deny path (`ui::say`). Normal
                                // initiators always dial 127.0.0.1, so this is silent
                                // in normal operation and only fires on an anomaly.
                                ui::say(&format!("l2: refused stream {sid:#x}: {err}"));
                                let _ = t
                                    .send_control(&json!({ "type": "l2-close", "sid": sid, "err": err }))
                                    .await;
                            }
                            l2::OpenVerdict::Ignore => {}
                        }
                    }
                    // A PTY stream closing frees its resize channel, handled by
                    // the mux's `on_close`/`drop_stream` (H-1: resizer is owned by
                    // the mux now, so it can't leak past the stream).
                }
                // Seamless-shell bootstrap (acceptor). Opt-in (FILAMENT_L2=1).
                // DENY-BY-DEFAULT: install the initiator's managed pubkey ONLY
                // when the link is proof-verified (`trusted`) AND the proven
                // device holds the NEW `shell` capability, distinct from
                // `transfer`, so pairing for file transfer never yields a shell.
                // The write happens only here (over the authenticated channel)
                // into a clearly-marked, removable authorized_keys block.
                // Warm-bootstrap (INITIATOR side): the peer answered a
                // `shell-bootstrap` we relayed over its warm link for a `filament
                // ssh`. Complete the stashed reply socket(s) for this pid; the
                // client then pins these host keys and skips the cold establish.
                #[cfg(unix)]
                Some("shell-bootstrap-ack") => {
                    let reply = json!({
                        "ok": true,
                        "hostkeys": v["hostkeys"].clone(),
                        "user": v["user"].clone(),
                        "sshd": v["sshd"].clone(),
                    });
                    complete_warm_bootstrap(&mut pending_bootstrap, &pid, &reply).await;
                }
                #[cfg(unix)]
                Some("shell-bootstrap-deny") => {
                    let reply = json!({
                        "ok": false,
                        "err": v["reason"].as_str().unwrap_or("shell bootstrap denied"),
                    });
                    complete_warm_bootstrap(&mut pending_bootstrap, &pid, &reply).await;
                }
                Some("shell-bootstrap") if l2_enabled => {
                    let Some(t) = conn.transport_of(&pid) else { continue };
                    let trusted = conn.link(&pid).map(|l| l.trusted).unwrap_or(false);
                    // Cap lookup keys on the PROVEN petname, not the presence name.
                    let dev = conn.link(&pid).and_then(|l| l.verified_name.clone());
                    // Granted if the device was explicitly `grant`ed shell OR an
                    // active `up --shell[-only]` policy auto-allows it. Trust
                    // (pair-proof) is still required either way.
                    let granted = trusted
                        && dev
                            .as_deref()
                            .map(|n| shell_policy.auto_allows(n) || device_allows(n, "shell"))
                            .unwrap_or(false);
                    if !granted {
                        let who = dev.as_deref().unwrap_or("<unverified>");
                        ui::say(&format!("l2: shell bootstrap refused: {who} (no shell cap / untrusted)"));
                        let _ = t
                            .send_control(&json!({
                                "type": "shell-bootstrap-deny",
                                "reason": "shell capability not granted"
                            }))
                            .await;
                        continue;
                    }
                    let device = dev.unwrap();
                    let pubkey = v["pubkey"].as_str().unwrap_or_default().to_string();
                    // M-3 (authorized_keys injection): a single, well-formed key
                    // line ONLY. validate_pubkey rejects interior newlines / CR /
                    // control chars and multi-line payloads, so a trusted+shell
                    // peer can't inject extra authorized_keys lines. Enforced here
                    // AND again inside install_authorized_key (defense in depth).
                    let pubkey = match sshkeys::validate_pubkey(&pubkey) {
                        Ok(k) => k,
                        Err(e) => {
                            ui::say(&format!("l2: shell bootstrap refused: malformed pubkey from '{device}': {e}"));
                            let _ = t
                                .send_control(&json!({
                                    "type": "shell-bootstrap-deny",
                                    "reason": "malformed pubkey"
                                }))
                                .await;
                            continue;
                        }
                    };
                    match sshkeys::install_authorized_key(&device, &pubkey) {
                        Ok(()) => {
                            let hostkeys = sshkeys::host_pubkeys();
                            let login = std::env::var("USER").unwrap_or_else(|_| "root".into());
                            // Tell the initiator whether an sshd is actually
                            // listening on the port `filament ssh` will dial here,
                            // so it can fail fast with a clear message instead of
                            // spawning ssh into a refused/black-holed connection.
                            let ssh_port = v["ssh_port"].as_u64().and_then(|n| u16::try_from(n).ok()).unwrap_or(22);
                            let sshd = sshd_listening(ssh_port).await;
                            ui::say(&format!("l2: shell granted to '{device}', installed managed key (filament-managed block)"));
                            let _ = t
                                .send_control(&json!({
                                    "type": "shell-bootstrap-ack",
                                    "hostkeys": hostkeys,
                                    "user": login,
                                    "sshd": sshd,
                                    "ssh_port": ssh_port
                                }))
                                .await;
                        }
                        Err(e) => {
                            ui::say(&format!("l2: shell bootstrap install failed for '{device}': {e}"));
                            let _ = t
                                .send_control(&json!({
                                    "type": "shell-bootstrap-deny",
                                    "reason": "install failed"
                                }))
                                .await;
                        }
                    }
                }
                // web-shell (browser terminal): spawn a login shell in a PTY and
                // bridge it to a sid stream. Same deny-by-default gate as
                // shell-bootstrap, a PTY is a superset of ssh-key access, so it
                // reuses the `shell` cap / --shell policy and requires `trusted`.
                Some("pty-open") if l2_enabled => {
                    let Some(t) = conn.transport_of(&pid) else { continue };
                    let sid = v["sid"].as_u64().unwrap_or(0) as u32;
                    if !l2::is_l2_sid(sid) {
                        continue;
                    }
                    let trusted = conn.link(&pid).map(|l| l.trusted).unwrap_or(false);
                    let dev = conn.link(&pid).and_then(|l| l.verified_name.clone());
                    let granted = trusted
                        && dev
                            .as_deref()
                            .map(|n| shell_policy.auto_allows(n) || device_allows(n, "shell"))
                            .unwrap_or(false);
                    if !granted {
                        let who = dev.as_deref().unwrap_or("<unverified>");
                        ui::say(&format!("l2: pty refused: {who} (no shell cap / untrusted)"));
                        let _ = t
                            .send_control(&json!({ "type": "l2-close", "sid": sid, "err": "shell capability not granted" }))
                            .await;
                        continue;
                    }
                    let cols = v["cols"].as_u64().unwrap_or(80) as u16;
                    let rows = v["rows"].as_u64().unwrap_or(24) as u16;
                    // #4: a stable, client-chosen session id binds reconnects to
                    // the same persistent PTY. DEVICE-SCOPED: prefixed with the
                    // verified device so a client id from device A can never
                    // address device B's session (no cross-device collision or
                    // hijack) - the random per-invocation client id then only
                    // needs to be unique per device. Absent (older client) -> a
                    // per-sid id that never reattaches (old behavior).
                    let session_id = match v["session"].as_str().filter(|s| !s.is_empty() && s.len() <= 128) {
                        Some(s) => format!("{}\u{1}{}", dev.as_deref().unwrap_or(&pid), s),
                        None => format!("{pid}:{sid:#x}"),
                    };
                    // $TERM forwarded by the client (so the remote matches the
                    // user's actual terminal); validated + capped, sane default.
                    let term = v["term"]
                        .as_str()
                        .filter(|s| !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_graphic()))
                        .unwrap_or("xterm-256color")
                        .to_string();
                    // One-shot command (non-empty when pty one-shot was requested).
                    let pty_cmd = v["cmd"]
                        .as_str()
                        .unwrap_or("")
                        .to_string();
                    // RESUME-ONLY (warm-drop fall-through): the client wants to
                    // REATTACH an existing session and never start a fresh shell, so a
                    // clean warm exit can't turn into a surprise re-login.
                    let resume = v["resume"].as_bool().unwrap_or(false);
                    let mux = l2_muxes
                        .entry(pid.clone())
                        .or_insert_with(|| l2::Mux::new(t.clone()))
                        .clone();
                    // #4 REATTACH: a live session for this id means a reconnect.
                    // Rebind its output to THIS link+sid and replay its buffer; do
                    // not spawn a new shell. Register the input pump + resizer for
                    // the new sid so typing and SIGWINCH reach the surviving PTY.
                    if let Some(sess) = pty_sessions.get_live(&session_id).await {
                        if mux.at_stream_cap().await {
                            ui::say("l2: pty reattach refused: too many streams on this link");
                            let _ = t.send_control(&json!({ "type": "l2-close", "sid": sid, "err": "too many streams" })).await;
                            continue;
                        }
                        let rx = mux.register_stream(sid).await;
                        let (rtx, rrx) = tokio::sync::mpsc::unbounded_channel::<(u16, u16)>();
                        mux.register_resizer(sid, rtx).await;
                        let _ = t.send_control(&json!({ "type": "pty-open-ack", "sid": sid })).await;
                        sess.attach(t.clone(), sid);
                        sess.resize(cols, rows);
                        pty_bindings.entry(pid.clone()).or_default().insert(sid, session_id.clone());
                        spawn_session_pumps(sess.clone(), rx, rrx);
                        ui::say(&format!("l2: pty REATTACHED to '{}', {cols}x{rows}", dev.unwrap_or_default()));
                        continue;
                    }
                    // Resume-only + no live session: the client is a warm-drop
                    // fall-through and the session is gone (the shell exited cleanly).
                    // Close instead of spawning a fresh shell, so the client exits
                    // cleanly rather than getting a surprise re-login.
                    if resume {
                        let _ = t.send_control(&json!({ "type": "l2-close", "sid": sid, "err": "no such session" })).await;
                        continue;
                    }
                    // H-1 (DoS): refuse over the per-link stream cap or the global
                    // PTY cap BEFORE spawning a shell. A flaky/hostile paired
                    // device can otherwise flood `pty-open` and exhaust threads.
                    if mux.at_stream_cap().await {
                        ui::say("l2: pty refused: too many streams on this link");
                        let _ = t.send_control(&json!({ "type": "l2-close", "sid": sid, "err": "too many streams" })).await;
                        continue;
                    }
                    let Some(pty_guard) = l2::PtyGuard::try_acquire() else {
                        ui::say(&format!("l2: pty refused: too many PTYs (global cap {})", l2::MAX_PTYS_GLOBAL));
                        let _ = t.send_control(&json!({ "type": "l2-close", "sid": sid, "err": "too many streams" })).await;
                        continue;
                    };
                    let rx = mux.register_stream(sid).await; // before spawn (race fix)
                    let (rtx, rrx) = tokio::sync::mpsc::unbounded_channel::<(u16, u16)>();
                    // Resizer is owned by the mux so it is freed on EVERY teardown
                    // path (inbound l2-close, link death), H-1.
                    mux.register_resizer(sid, rtx).await;
                    let _ = t.send_control(&json!({ "type": "pty-open-ack", "sid": sid })).await;
                    // #4: spawn the PTY as a PERSISTENT session keyed by session_id,
                    // not a link-bound serve_pty. It outlives this link; a drop
                    // detaches it, a reconnect reattaches above.
                    // Resolve the shell and build interactive or one-shot argv.
                    let shell_argv = shell_argv(None, shell_user.as_deref());
                    let host = platform::ShellHost::new(&shell_argv);
                    let argv = if pty_cmd.is_empty() {
                        host.interactive_args()
                    } else {
                        host.exec_cmd_args(&pty_cmd)
                    };
                    match l2::spawn_pty_session(
                        pty_sessions.clone(),
                        session_id.clone(),
                        t.clone(),
                        sid,
                        cols,
                        rows,
                        &term,
                        argv,
                        pty_guard,
                    )
                    .await
                    {
                        Some(sess) => {
                            pty_bindings.entry(pid.clone()).or_default().insert(sid, session_id.clone());
                            spawn_session_pumps(sess, rx, rrx);
                            ui::say(&format!("l2: pty granted to '{}', {cols}x{rows}", dev.unwrap_or_default()));
                        }
                        None => {
                            // spawn already sent an l2-close{err}; free the stream.
                            mux.drop_pty(sid).await;
                        }
                    }
                }
                Some("mount-open") if l2_enabled => {
                    let Some(t) = conn.transport_of(&pid) else { continue };
                    let sid = v["sid"].as_u64().unwrap_or(0) as u32;
                    if !l2::is_l2_sid(sid) { continue; }
                    let trusted = conn.link(&pid).map(|l| l.trusted).unwrap_or(false);
                    if !trusted {
                        let _ = t.send_control(&json!({ "type": "l2-close", "sid": sid, "err": "mount: untrusted peer" })).await;
                        continue;
                    }
                    let root_encoded = v["root"].as_str().unwrap_or(".");
                    let root_path = mount_proto::path_decode(root_encoded).unwrap_or_else(|_| std::path::PathBuf::from("."));
                    let caps = mount_proto::mount_caps_for_root(&root_path);
                    let mux = l2_muxes.entry(pid.clone())
                        .or_insert_with(|| l2::Mux::new(t.clone()))
                        .clone();
                    if mux.at_stream_cap().await {
                        let _ = t.send_control(&json!({ "type": "l2-close", "sid": sid, "err": "too many streams" })).await;
                        continue;
                    }
                    let rx = mux.register_stream(sid).await;
                    let _ = t.send_control(&json!({ "type": "mount-open-ack", "sid": sid, "caps": caps })).await;
                    let transport = t.clone();
                    let spawn_sid = sid;
                    let proto_version = caps.protocol_version;
                    mount_proto::spawn_mount_server(root_path, transport, spawn_sid, rx, proto_version);
                }
                Some("pty-resize") if l2_enabled => {
                    let sid = v["sid"].as_u64().unwrap_or(0) as u32;
                    let cols = v["cols"].as_u64().unwrap_or(80) as u16;
                    let rows = v["rows"].as_u64().unwrap_or(24) as u16;
                    // #4: resize the persistent session bound to this sid (not a
                    // link-local serve_pty). Falls back to the mux resizer if the
                    // sid isn't a known session binding (defensive).
                    if let Some(sid_map) = pty_bindings.get(&pid) {
                        if let Some(session_id) = sid_map.get(&sid) {
                            if let Some(sess) = pty_sessions.get_live(session_id).await {
                                sess.resize(cols, rows);
                            }
                        }
                    }
                    if let Some(mux) = l2_muxes.get(&pid) {
                        mux.resize_pty(sid, cols, rows).await;
                    }
                }
                // #4: explicit end of a persistent PTY session (the ✕ / unmount).
                // Distinct from a bare channel drop, which only DETACHES. Kills the
                // shell and removes the session so a later open spawns fresh.
                Some("pty-close") if l2_enabled => {
                    if let Some(session_id) = v["session"].as_str() {
                        if let Some(sess) = pty_sessions.get_live(session_id).await {
                            sess.end(); // kill the shell now
                        }
                        pty_sessions.remove(session_id).await;
                        if let Some(sid_map) = pty_bindings.get_mut(&pid) {
                            sid_map.retain(|_, v| v != session_id);
                        }
                    }
                }
                // Client confirmed the protocol version advertised in mount-open-ack.
                // The server is already running in that version; this control is
                // received and consumed here to prevent it from hitting the catch-all.
                Some("mount-cap-ack") if l2_enabled => {}
                Some("brb") => {
                    // C21: the peer announces a benign absence (mobile file
                    // picker suspends the tab). Hold the line that long.
                    let ttl = v["ttl"].as_u64().unwrap_or(120).min(300);
                    conn.rejoin.away = Some((pid.clone(), Instant::now() + Duration::from_secs(ttl)));
                    let n = conn.link_presence(&pid, Presence::Away);
                    ui::say(&conn.roster(&pid, "", ui::Tone::Warn, "away, choosing a file · holding the line", &n));
                }
                Some("back") => {
                    let was_away = conn.is_away(&pid);
                    conn.note_alive(&pid);
                    if was_away {
                        let n = conn.link_presence(&pid, Presence::Ready);
                        ui::say(&conn.roster(&pid, ui::glyph_ok(), ui::Tone::Ok, "back", &n));
                    }
                }
                // C30 phase 3: a state ping proves the peer is alive, clear
                // any away-mark (the receiver side has no sender corrections).
                Some("state") => {
                    let was_away = conn.is_away(&pid);
                    conn.note_alive(&pid);
                    if was_away {
                        let n = conn.link_presence(&pid, Presence::Ready);
                        ui::say(&conn.roster(&pid, ui::glyph_ok(), ui::Tone::Ok, "back", &n));
                    }
                }
                Some("pair-keep") => {
                    let sec = v["secret"].as_str().unwrap_or_default().to_string();
                    if sec.len() == 64 {
                        let kept = if let Some(name) = &remember {
                            devices_store(name, &sec)?;
                            ui::say(&format!("remembered this device as '{name}', future sends auto-accept after proof"));
                            true
                        } else if ceremony == Some(false) {
                            // C29: we typed their code into this session, the
                            // creator initiated first; that's our ceremony.
                            ceremony = None;
                            let n = conn.link(&pid).map(|l| l.name.clone()).unwrap_or_else(|| "device".into());
                            devices_store(&n, &sec)?;
                            devices.push((n.clone(), sec.clone()));
                            sess.channels.push(channel_of(&sec)); // C30: desire grows; session repairs
                            sess.touch();
                            sio.emit("subscribe", json!({ "channels": [channel_of(&sec)] })).await.ok();
                            ui::say(&format!(
                                "  {} {} mutually remembered, rename anytime: filament devices rename {n} <new>",
                                ui::paint(ui::Tone::Ok, ui::glyph_ok()),
                                ui::paint(ui::Tone::Bold, &n),
                            ));
                            true
                        } else {
                            ui::say("(sender offered to be remembered; re-run with --remember <name> to keep it)");
                            false
                        };
                        // C27: answer either way, a declined sender discards
                        // its half instead of waving at a dead meeting point.
                        if let Some(t) = conn.transport_of(&pid) {
                            t.send_control(&json!({ "type": "pair-keep-ack", "ok": kept })).await.ok();
                        }
                    }
                }
                // C29: claimer fallback, the creator never initiated
                // (browsers don't); hand over OUR secret instead.
                Some("__pair_fallback") => {
                    if ceremony == Some(false) {
                        ceremony = None;
                        ceremony_pid = Some(pid.clone());
                        if let Some(t) = conn.transport_of(&pid) {
                            t.send_control(&json!({ "type": "pair-keep", "secret": ceremony_secret })).await.ok();
                        }
                    }
                }
                // C29: their answer to OUR in-session remember offer.
                Some("pair-keep-ack") => {
                    if ceremony_pid.as_deref() == Some(pid.as_str()) {
                        ceremony_pid = None;
                        let n = conn.link(&pid).map(|l| l.name.clone()).unwrap_or_else(|| "device".into());
                        if v["ok"].as_bool() == Some(false) {
                            ui::say(&conn.roster(&pid, ui::glyph_err(), ui::Tone::Warn, "declined to be remembered, nothing stored", &n));
                        } else {
                            devices_store(&n, &ceremony_secret)?;
                            devices.push((n.clone(), ceremony_secret.clone()));
                            sess.channels.push(channel_of(&ceremony_secret)); // C30
                            sess.touch();
                            sio.emit("subscribe", json!({ "channels": [channel_of(&ceremony_secret)] })).await.ok();
                            ceremony_secret = fresh_secret(); // never reuse across devices
                            ui::say(&format!(
                                "  {} {} mutually remembered, rename anytime: filament devices rename {n} <new>",
                                ui::paint(ui::Tone::Ok, ui::glyph_ok()),
                                ui::paint(ui::Tone::Bold, &n),
                            ));
                        }
                    }
                }
                Some("pair-proof") => {
                    let mac = v["mac"].as_str().unwrap_or_default();
                    let peer_uid = conn.link(&pid).and_then(|l| l.uid.clone()).unwrap_or_default();
                    let fps = match conn.link(&pid) {
                        Some(l) => match &l.peer { Some(p) => p.fingerprints().await, None => None },
                        None => None,
                    };
                    let Some((my_fp, their_fp)) = fps else {
                        ui::debug("pair-proof received before fingerprints known, ignoring");
                        continue;
                    };
                    // #9: pair secrets are symmetric, our own install holds
                    // every secret we do, so a same-host process could prove
                    // "pop2" and tunnel callers into the WRONG machine. Refuse.
                    let hit = if is_self_uid(&conn.my_uid, Some(peer_uid.as_str())) {
                        ui::debug("pair-proof from our own install, refusing (self-connect)");
                        None
                    } else {
                        devices
                            .iter()
                            .find(|(_, s)| proof_for(s, &peer_uid, &peer_uid, &conn.my_uid, &my_fp, &their_fp) == mac)
                    };
                    let ok = if let Some((n, _)) = hit {
                        if let Some(l) = conn.link_mut(&pid) {
                            l.trusted = true;
                            // Record the proven devices.json petname, the cap
                            // store key (the `shell` bootstrap gate looks up caps
                            // under exactly this, not the presence display name).
                            l.verified_name = Some(n.clone());
                        }
                        ui::say(&format!("identity verified: '{n}' (auto-accepting)"));
                        true
                    } else {
                        // CRITICAL, a security verdict the user must see (-q too).
                        ui::critical(&ui::paint(ui::Tone::Warn, "pair-proof FAILED verification, treating peer as untrusted"));
                        false
                    };
                    // C27: tell the prover the verdict, a rejected prover
                    // learns we never met and stops claiming acquaintance.
                    if let Some(t) = conn.transport_of(&pid) {
                        t.send_control(&json!({ "type": "pair-proof-ack", "ok": ok })).await.ok();
                    }
                }
                Some("pair-intro") => {
                    // C19/C20: only a fingerprint-verified known device may
                    // vouch new trust into this store.
                    let trusted = conn.link(&pid).map(|l| l.trusted).unwrap_or(false);
                    let iname = v["name"].as_str().unwrap_or_default().to_string();
                    let isec = v["secret"].as_str().unwrap_or_default().to_string();
                    let hub = conn.link(&pid).map(|l| l.name.clone()).unwrap_or_default();
                    if trusted && isec.len() == 64 && !iname.is_empty() {
                        devices_store(&iname, &isec)?;
                        devices.push((iname.clone(), isec.clone()));
                        sess.channels.push(channel_of(&isec)); // C30
                        sess.touch();
                        sio.emit("subscribe", json!({ "channels": [channel_of(&isec)] })).await.ok();
                        ui::say(&format!(
                            "  {} introduced to '{}' by {}, now a known device",
                            ui::paint(ui::Tone::Ok, ui::glyph_ok()), iname, hub
                        ));
                    } else {
                        ui::say(&ui::paint(ui::Tone::Warn, &format!("  ignored pair-intro from unverified peer {hub}")));
                    }
                }
                Some("file-offer") => {
                    let Some(t) = conn.transport_of(&pid) else { continue };
                    // L1-a (shared-room hardened): on the code path, accept bytes
                    // ONLY from the peer whose ephemeral SPAKE2 ceremony confirmed
                    // (the authenticated sender). Anything else, a pre-auth offer, a
                    // decoy / unrelated room peer, or an offer from a DIFFERENT peer
                    // than the one that authenticated, is refused. (Previously this
                    // only gated the single latched peer, so a decoy could slip an
                    // offer past while we were still authenticating; now it cannot.)
                    // If no peer has authenticated yet, the overall watchdog still
                    // fails loudly should the real sender never confirm.
                    if recv_code_path
                        && (!recv_pake_done || recv_pake_peer.as_deref() != Some(pid.as_str()))
                    {
                        // A pre-auth offer from a peer we are STILL authenticating
                        // (it has a live ceremony) is buffered, not lost: the offer
                        // and the sender's confirm crossed on the wire. If that peer
                        // wins auth we replay it; if its ceremony is dropped, the
                        // buffered offer dies with it. A confirmed-but-different peer
                        // (a decoy that authenticated nothing) is simply ignored.
                        if !recv_pake_done && recv_cers.contains_key(&pid) {
                            recv_pending_offers.insert(pid.clone(), v.clone());
                            ui::debug("buffering a pre-auth file-offer until its ceremony confirms");
                        } else {
                            ui::debug("ignoring file-offer from a peer that has not authenticated via ephemeral PAKE");
                        }
                        continue;
                    }
                    let id = v["id"].as_str().unwrap_or_default().to_string();
                    let sid = v["sid"].as_u64().unwrap_or(0) as u32;
                    // Never trust a remote name with path separators.
                    let raw = v["name"].as_str().unwrap_or("file.bin");
                    let name = Path::new(raw)
                        .file_name()
                        .map(|n| n.to_string_lossy().into_owned())
                        .unwrap_or_else(|| "file.bin".into());
                    let size = v["size"].as_u64().unwrap_or(0);
                    let offer_head = v["head"].as_str().map(|s| s.to_string());
                    // P4 (GAP-5): the sender's whole-file sha256 (absent for an old
                    // peer). Used to verify-on-completion + drive the delivery-ack.
                    let offer_full = v["full"].as_str().map(|s| s.to_string());
                    let is_resume = v["resume"].as_bool().unwrap_or(false);

                    let part_path = dir.join(format!("{name}.part"));
                    let meta_path = dir.join(format!("{name}.part.meta"));
                    // C7: a partial counts only if size matches AND the
                    // content head matches (when both sides have one).
                    let mut offset = 0u64;
                    // P4: the whole-file digest persisted with the partial, so a
                    // resume after a process restart can still verify-on-completion
                    // even if this particular re-offer omits `full`.
                    let mut prior_full: Option<String> = None;
                    if part_path.is_file() {
                        let prior = std::fs::metadata(&part_path).map(|m| m.len()).unwrap_or(0);
                        match PartMeta::load(&meta_path) {
                            Some(m) if m.size == size && prior <= size => {
                                let head_ok = match (&m.head, &offer_head) {
                                    (Some(a), Some(b)) => a == b,
                                    _ => true, // legacy peer, size-only fallback
                                };
                                if head_ok {
                                    offset = prior;
                                    prior_full = m.full;
                                } else {
                                    // DEBUG, resilience internal (resume mismatch, restart).
                                    ui::debug(&format!("{name}: same name+size but different content, restarting from 0"));
                                }
                            }
                            _ => {}
                        }
                    }

                    // C14/C22: consent. -y accepts everything; a resume of a
                    // partial we already said yes to auto-accepts; a verified
                    // device auto-accepts; otherwise the question joins the
                    // pending queue and the answer arrives via StdinLine, a
                    // per-process token marks re-enqueued offers so a remote
                    // peer can't forge "already consented".
                    let sender_name = conn.link(&pid).map(|l| l.name.clone()).unwrap_or_default();
                    let link_trusted = conn.link(&pid).map(|l| l.trusted).unwrap_or(false);
                    let consented = v["__consent"].as_str() == Some(consent_token());
                    let ok = if daemon {
                        link_trusted
                    } else {
                        yes || consented || link_trusted || (is_resume && offset > 0)
                    };
                    if !ok {
                        if !daemon && std::io::stdin().is_terminal() {
                            pending.push_back((pid.clone(), v.clone()));
                            question_open.store(true, std::sync::atomic::Ordering::Relaxed);
                            if pending.len() == 1 {
                                // C25: the question is a PERMANENT line first
                                // (nothing can be asked invisibly), with the
                                // sticky as the live answer tail.
                                let q = offer_question(&sender_name, &name, size, paired);
                                ui::say(&q);
                                ui::sticky(&q);
                                question_shown = Instant::now();
                            }
                            continue; // decision arrives later via StdinLine
                        }
                        ui::say(&ui::paint(ui::Tone::Dim, &format!(
                            "  declined {name} from {sender_name} ({})",
                            if daemon { "unverified peer" } else { "no tty, use -y to auto-accept" }
                        )));
                        t.send_control(&protocol::decline_msg(&id)).await?;
                        continue;
                    }

                    // C23: never run two streams into one .part, a rejoin
                    // can re-offer a file whose first stream is still live;
                    // accepting both corrupted the path and crashed on the
                    // second rename. First stream wins.
                    //
                    // P0 (GAP-1) exception: a STALL repair re-offers the same file
                    // (resume:true) on a FRESH transport while the OLD stream's
                    // by_sid entry may still linger (its data path went dark). If
                    // the existing stream's transport is itself STALLED past the
                    // threshold, the "first stream" is the wedged one, flush it to
                    // its .part and accept the resume on the live link instead of
                    // declining (a decline would mark the SENDER's transfer done
                    // and abort the recovery). A genuinely FLOWING duplicate still
                    // wins as before.
                    let want_part = dir.join(format!("{name}.part"));
                    if !to_stdout {
                        let dup_keys: Vec<(String, u32)> = by_sid
                            .iter()
                            .filter(|(_, inc)| inc.part_path == want_part)
                            .map(|(k, _)| k.clone())
                            .collect();
                        if !dup_keys.is_empty() {
                            // Is ANY existing stream for this file still flowing?
                            let any_flowing = dup_keys.iter().any(|(p, _)| {
                                conn.transport_of(p)
                                    .map(|t| t.idle_ms() < net::stall_ms())
                                    .unwrap_or(false)
                            });
                            if any_flowing {
                                // A real concurrent duplicate, first (flowing)
                                // stream wins. Ignore WITHOUT marking the sender
                                // done (a benign skip, not a user decline).
                                ui::say(&ui::paint(ui::Tone::Dim, &format!("  (duplicate offer for {name} ignored, already receiving it)")));
                                continue;
                            }
                            // The lingering stream(s) are STALLED, flush their
                            // partials to disk and drop them so the resume below
                            // re-opens the .part from its saved offset.
                            for k in dup_keys {
                                if let Some(inc) = by_sid.remove(&k) {
                                    let f = inc.file.clone();
                                    let _ = tokio::task::spawn_blocking(move || { let _ = f.sync_all(); }).await;
                                }
                            }
                        }
                    }

                    if to_stdout {
                        // Pipe mode: no part files, no resume, pure stream.
                        // Write through a dup'd stdout fd so dropping the
                        // writer never closes the process's real fd 1; the
                        // /dev/stdout open is the portable-unix way to dup.
                        // (Windows: -o - is not supported yet; see G-e.)
                        #[cfg(unix)]
                        let out = tokio::fs::OpenOptions::new().write(true).open("/dev/stdout").await?;
                        #[cfg(not(unix))]
                        {
                            bail!("-o - (stdout streaming) is not supported on this platform yet");
                        }
                        #[cfg(unix)]
                        {
                            by_sid.insert((pid.clone(), sid), IncomingFile {
                                id: id.clone(),
                                name,
                                size,
                                received: Arc::new(AtomicU64::new(0)),
                                ranges: Arc::new(std::sync::Mutex::new(vec![])),
                                file: Arc::new(out.into_std().await),
                                part_path: PathBuf::new(),
                                // Pipe mode streams to a fd we can't re-read, so we
                                // can't recompute the digest, no verify, no ack
                                // (the sender's bounded fallback covers it).
                                full: None,
                                inflight: Arc::new(AtomicI64::new(0)),
                                end_seen: Arc::new(AtomicBool::new(false)),
                                ack_sid: 0,
                                last_tick: 0,
                                bar: ui::Progress::new("(stdout)", size),
                            });
                            t.send_control(&protocol::accept_msg(&id, 0)).await?;
                            continue;
                        }
                    }
                    // P4: the digest to verify against on completion, the current
                    // offer's, else the one persisted with the partial (resume).
                    let effective_full = offer_full.clone().or(prior_full);
                    let file = if offset > 0 {
                        // DEBUG, resilience internal (receiver resuming from offset).
                        ui::debug(&format!("{name}: resuming at {} ({:.0}%)", human(offset), offset as f64 / size.max(1) as f64 * 100.0));
                        // Open with write mode (not append) so we can seek to any
                        // position for multi-stream out-of-order writes.
                        tokio::fs::OpenOptions::new().write(true).open(&part_path).await?
                    } else {
                        PartMeta { size, head: offer_head, full: effective_full.clone() }.store(&meta_path)?;
                        tokio::fs::File::create(&part_path).await?
                    };
                    let bar = ui::Progress::new(&name, size);
                    let file = Arc::new(file.into_std().await);
                    let received = Arc::new(AtomicU64::new(offset));
                    let ranges = Arc::new(std::sync::Mutex::new(
                        if offset > 0 { vec![(0, offset)] } else { vec![] }
                    ));
                    by_sid.insert((pid.clone(), sid), IncomingFile {
                        id: id.clone(),
                        name,
                        size,
                        received,
                        ranges,
                        file,
                        part_path,
                        full: effective_full,
                        inflight: Arc::new(AtomicI64::new(0)),
                        end_seen: Arc::new(AtomicBool::new(false)),
                        ack_sid: 0,
                        last_tick: 0,
                        bar,
                    });
                    t.send_control(&protocol::accept_msg(&id, offset)).await?;
                }
                Some("file-end") => {
                    // Test hook (gate 18 standalone repro): drop the file-end
                    // control frame so a fully-received stream is stranded in
                    // by_sid, mirrors a sender whose PC tears down before the
                    // best-effort file-end is delivered.
                    if test_hooks::drop_file_end() {
                        continue;
                    }
                    let sid = v["sid"].as_u64().unwrap_or(0) as u32;
                    // If background writes are still in-flight, defer to
                    // Ev::MaybeComplete from the last finishing writer.
                    let process_now = {
                        match by_sid.get_mut(&(pid.clone(), sid)) {
                            None => false, // unknown stream
                            Some(inc) => {
                                inc.ack_sid = sid;
                                if inc.inflight.load(Ordering::Relaxed) > 0 {
                                    inc.end_seen.store(true, Ordering::Relaxed);
                                    false // deferred to MaybeComplete
                                } else {
                                    true // inflight == 0, process now
                                }
                            }
                        }
                    };
                    if !process_now { continue; }
                    // No inflight writes — process inline (fast path).
                    let sid = v["sid"].as_u64().unwrap_or(0) as u32;
                    let mut inc = match by_sid.remove(&(pid.clone(), sid)) {
                        Some(i) => i,
                        None => continue,
                    };
                    let f = inc.file.clone();
                    let _ = tokio::task::spawn_blocking(move || { let _ = f.sync_all(); }).await;
                    if to_stdout {
                        completed += 1;
                        continue;
                    }
                    let id = inc.id.clone();
                    if inc.full.is_some() {
                        let verdict = verify_incoming(&inc).await;
                        match verdict {
                            protocol::VerifyResult::Match => {
                                verify_fails.remove(&id);
                                let rename_to = if completed == 0 { output.clone() } else { None };
                                let from = conn.link(&pid).map(|l| l.name.clone()).unwrap_or_default();
                                let nm = inc.name.clone();
                                if finalize_incoming(inc, &dir, rename_to.as_deref(), daemon, &from).await? {
                                    completed += 1;
                                    if test_hooks::suppress_delivery_ack() {
                                        ui::say(&ui::paint(ui::Tone::Warn, &format!("    [test] {nm} verified but SUPPRESSING delivery-ack")));
                                    } else if let Some(t) = conn.transport_of(&pid) {
                                        let _ = t.send_control(&protocol::delivery_ack_msg(&id, sid)).await;
                                        let _ = t.flush().await;
                                        ui::say(&ui::paint(ui::Tone::Dim, &format!("    {nm} verified (whole-file sha256 matched), acked")));
                                    }
                                }
                            }
                            protocol::VerifyResult::Mismatch { restart_from_zero } => {
                                let fails = verify_fails.entry(id.clone()).or_insert(0);
                                *fails += 1;
                                if *fails > MAX_VERIFY_FAILS {
                                    ui::critical(&ui::paint(ui::Tone::Err, &format!(
                                        "  {}: whole-file checksum still wrong after {MAX_VERIFY_FAILS} re-fetches, refusing to accept a corrupt file (partial kept)",
                                        inc.name
                                    )));
                                    verify_fails.remove(&id);
                                    continue;
                                }
                                let mut req_offset = inc.received.load(Ordering::Relaxed);
                                if restart_from_zero {
                                    let _ = tokio::fs::File::create(&inc.part_path).await;
                                    inc.received.store(0, Ordering::Relaxed);
                                    inc.ranges.lock().unwrap().clear();
                                    req_offset = 0;
                                    ui::debug(&ui::paint(ui::Tone::Warn, &format!(
                                        "  {}: received all bytes but whole-file checksum FAILED (corrupt), re-fetching from 0 (attempt {})",
                                        inc.name, *fails
                                    )));
                                } else {
                                    ui::debug(&ui::paint(ui::Tone::Warn, &format!(
                                        "  {}: TRUNCATED ({}/{}), checksum can't match yet; re-requesting the rest (attempt {})",
                                        inc.name, human(req_offset), human(inc.size), *fails
                                    )));
                                }
                                let f = inc.file.clone();
                                let _ = tokio::task::spawn_blocking(move || { let _ = f.sync_all(); }).await;
                                if req_offset == 0 {
                                    if let Ok(f) = tokio::fs::OpenOptions::new().write(true).open(&inc.part_path).await {
                                        inc.file = Arc::new(f.into_std().await);
                                    }
                                }
                                inc.end_seen.store(false, Ordering::Relaxed);
                                by_sid.insert((pid.clone(), sid), inc);
                                if let Some(t) = conn.transport_of(&pid) {
                                    let _ = t.send_control(&protocol::accept_msg(&id, req_offset)).await;
                                }
                            }
                        }
                    } else {
                        let rename_to = if completed == 0 { output.clone() } else { None };
                        let from = conn.link(&pid).map(|l| l.name.clone()).unwrap_or_default();
                        if finalize_incoming(inc, &dir, rename_to.as_deref(), daemon, &from).await? {
                            completed += 1;
                        }
                    }
                }
                _ => {}
            },
            Ev::MaybeComplete(pid, sid) => {
                // A background writer task finished and was the last inflight,
                // and end_seen was already set. Finalize (verify + delv ack).
                let ack_sid = {
                    by_sid.get(&(pid.clone(), sid)).map(|inc| inc.ack_sid).unwrap_or(0)
                };
                if let Some(mut inc) = by_sid.remove(&(pid.clone(), sid)) {
                    if to_stdout {
                        completed += 1;
                        continue;
                    }
                    let id = inc.id.clone();
                    if inc.full.is_some() {
                        let verdict = verify_incoming(&inc).await;
                        match verdict {
                            protocol::VerifyResult::Match => {
                                verify_fails.remove(&id);
                                let rename_to = if completed == 0 { output.clone() } else { None };
                                let from = conn.link(&pid).map(|l| l.name.clone()).unwrap_or_default();
                                let nm = inc.name.clone();
                                if finalize_incoming(inc, &dir, rename_to.as_deref(), daemon, &from).await? {
                                    completed += 1;
                                    if test_hooks::suppress_delivery_ack() {
                                        ui::say(&ui::paint(ui::Tone::Warn, &format!("    [test] {nm} verified but SUPPRESSING delivery-ack")));
                                    } else if let Some(t) = conn.transport_of(&pid) {
                                        let _ = t.send_control(&protocol::delivery_ack_msg(&id, ack_sid)).await;
                                        ui::say(&ui::paint(ui::Tone::Dim, &format!("    {nm} verified (whole-file sha256 matched), acked")));
                                    }
                                }
                            }
                            protocol::VerifyResult::Mismatch { restart_from_zero } => {
                                let fails = verify_fails.entry(id.clone()).or_insert(0);
                                *fails += 1;
                                if *fails > MAX_VERIFY_FAILS {
                                    ui::critical(&ui::paint(ui::Tone::Err, &format!(
                                        "  {}: whole-file checksum still wrong after {MAX_VERIFY_FAILS} re-fetches, refusing to accept a corrupt file (partial kept)",
                                        inc.name
                                    )));
                                    verify_fails.remove(&id);
                                    continue;
                                }
                                let mut req_offset = inc.received.load(Ordering::Relaxed);
                                if restart_from_zero {
                                    let _ = tokio::fs::File::create(&inc.part_path).await;
                                    if let Ok(f) = tokio::fs::OpenOptions::new().write(true).open(&inc.part_path).await {
                                        inc.file = Arc::new(f.into_std().await);
                                    }
                                    inc.received.store(0, Ordering::Relaxed);
                                    inc.ranges.lock().unwrap().clear();
                                    req_offset = 0;
                                    ui::debug(&ui::paint(ui::Tone::Warn, &format!(
                                        "  {}: received all bytes but whole-file checksum FAILED (corrupt), re-fetching from 0 (attempt {})",
                                        inc.name, *fails
                                    )));
                                } else {
                                    ui::debug(&ui::paint(ui::Tone::Warn, &format!(
                                        "  {}: TRUNCATED ({}/{}), checksum can't match yet; re-requesting the rest (attempt {})",
                                        inc.name, human(req_offset), human(inc.size), *fails
                                    )));
                                }
                                let f = inc.file.clone();
                                let _ = tokio::task::spawn_blocking(move || { let _ = f.sync_all(); }).await;
                                inc.end_seen.store(false, Ordering::Relaxed);
                                by_sid.insert((pid.clone(), sid), inc);
                                if let Some(t) = conn.transport_of(&pid) {
                                    let _ = t.send_control(&protocol::accept_msg(&id, req_offset)).await;
                                }
                            }
                        }
                    } else {
                        let rename_to = if completed == 0 { output.clone() } else { None };
                        let from = conn.link(&pid).map(|l| l.name.clone()).unwrap_or_default();
                        if finalize_incoming(inc, &dir, rename_to.as_deref(), daemon, &from).await? {
                            completed += 1;
                        }
                    }
                }
            }
            Ev::Chunk(pid, sid, offset, data) => {
                // L2 streams live in the HIGH half of the sid space, route them
                // to the tunnel mux, never the file-transfer table (the pure
                // high-bit prefix check keeps file send/recv byte-identical).
                if l2_enabled && l2::is_l2_sid(sid) {
                    if let Some(mux) = l2_muxes.get(&pid) {
                        mux.on_frame(sid, data).await;
                    }
                } else if let Some(inc) = by_sid.get_mut(&(pid.clone(), sid)) {
                    // Determine the write position: absolute offset from
                    // the sender (QUIC multi-stream) or current file end
                    // (DataChannel, via the received counter).
                    let pos = offset.unwrap_or_else(|| inc.received.load(Ordering::Relaxed));
                    inc.inflight.fetch_add(1, Ordering::Relaxed);
                    let file = Arc::clone(&inc.file);
                    let ranges = offset.map(|_| Arc::clone(&inc.ranges));
                    let received = Arc::clone(&inc.received);
                    let inflight = Arc::clone(&inc.inflight);
                    let end_seen = Arc::clone(&inc.end_seen);
                    let tx = tx.clone();
                    let pid = pid.clone();
                    tokio::task::spawn_blocking(move || {
                        let _ = pwrite_at(&file, &data, pos);
                        if let Some(ranges) = ranges {
                            let total = {
                                let mut r = ranges.lock().unwrap();
                                record_range(&mut *r, pos, data.len())
                            };
                            received.store(total, Ordering::Relaxed);
                        } else {
                            received.fetch_add(data.len() as u64, Ordering::Relaxed);
                        }
                        let prev = inflight.fetch_sub(1, Ordering::Relaxed);
                        if prev == 1 && end_seen.load(Ordering::Relaxed) {
                            let _ = tx.send(Ev::MaybeComplete(pid, sid));
                        }
                    });
                    let r = inc.received.load(Ordering::Relaxed);
                    if r != inc.last_tick {
                        inc.bar.tick(r);
                        inc.last_tick = r;
                    }
                } else {
                    // Chunk arrived for unknown (pid, sid) - log instead of silently dropping.
                    // This happens during transport supersede or stall repair when old chunks
                    // arrive after the by_sid entry was removed.
                    ui::debug(&format!("  dropping chunk for unknown sid {sid} from {pid} ({} bytes)", data.len()));
                }
            }
            Ev::StdinLine(line) => {
                let ans = line.to_lowercase();
                if !pending.is_empty() {
                    // C22/C25: an open question owns stdin, but ONLY explicit
                    // answers count. An empty line (stray CR, idle Enter) used
                    // to default-decline an offer the user never saw; and any
                    // keypress within 300ms of the question appearing is a
                    // buffered stroke, not a decision.
                    if question_shown.elapsed() < Duration::from_millis(300) {
                        continue;
                    }
                    let mut answered = false;
                    if ans == "y" || ans == "yes" {
                        answered = true;
                        let (qpid, mut qv) = pending.pop_front().unwrap();
                        ui::clear_sticky();
                        qv["__consent"] = json!(consent_token());
                        let _ = tx.send(Ev::Control(qpid, qv)); // re-enter the offer path, consented
                    } else if ans == "n" || ans == "no" {
                        answered = true;
                        let (qpid, qv) = pending.pop_front().unwrap();
                        ui::clear_sticky();
                        ui::say(&ui::paint(ui::Tone::Dim, &format!("  declined {}", qv["name"].as_str().unwrap_or("file"))));
                        if let Some(t) = conn.transport_of(&qpid) {
                            t.send_control(&protocol::decline_msg(qv["id"].as_str().unwrap_or_default())).await?;
                        }
                    }
                    // show the next queued question (or re-show on gibberish)
                    if let Some((qpid, qv)) = pending.front() {
                        let s = conn.link(qpid).map(|l| l.name.clone()).unwrap_or_default();
                        let q = offer_question(&s, qv["name"].as_str().unwrap_or("file"), qv["size"].as_u64().unwrap_or(0), paired);
                        if answered {
                            ui::say(&q); // a NEW question fronted, permanent line (C25)
                            question_shown = Instant::now();
                        }
                        ui::sticky(&q);
                    } else {
                        question_open.store(false, std::sync::atomic::Ordering::Relaxed);
                    }
                } else if ans == "devices" {
                    // C29: session commands, `up` is a place you live in.
                    if devices.is_empty() {
                        ui::say(&ui::paint(ui::Tone::Dim, "  no known devices yet, type a code or `pair` to add one"));
                    }
                    for (n, s) in &devices {
                        ui::say(&format!("  {}  {}", ui::paint(ui::Tone::Bold, n), ui::paint(ui::Tone::Dim, &format!("(channel {})", &channel_of(s)[..12]))));
                    }
                } else if let Some(n) = ans.strip_prefix("forget ") {
                    let n = n.trim();
                    if devices.iter().any(|(dn, _)| dn == n) {
                        devices_remove(n)?;
                        devices.retain(|(dn, _)| dn != n);
                        ui::say(&format!("  {} forgot '{n}', it can no longer find this machine", ui::paint(ui::Tone::Ok, ui::glyph_ok())));
                    } else {
                        ui::say(&ui::paint(ui::Tone::Dim, &format!("  no device named '{n}' (try `devices`)")));
                    }
                } else if ans == "pair" || ans == "code" {
                    // C29: mint a code; whoever claims it gets the remember
                    // ceremony on connect (we created it, so WE initiate).
                    if daemon {
                        ceremony = Some(true);
                    }
                    sio.emit("pair-create", json!({})).await.ok();
                } else if regex_lite_code(&line) {
                    if claim_in_flight {
                        ui::say(&ui::paint(ui::Tone::Dim, "  (a claim is already in flight, wait for it to resolve)"));
                    } else {
                        ui::say(&format!("  claiming {}...", ui::paint(ui::Tone::Brand, &line)));
                        paired = true;
                        claim_in_flight = true;
                        if daemon {
                            ceremony = Some(false); // C29: in a session, pairing means remembering
                        }
                        sio.emit("pair-claim", json!({ "code": line.to_lowercase() })).await.ok();
                    }
                } else if !line.is_empty() {
                    ui::say(&ui::paint(ui::Tone::Dim, "  (type a code like brave-otter-123 to claim it · `pair` · `devices` · `forget <name>`)"));
                }
            }
            Ev::Interrupted => {
                flush_inflight(&mut by_sid).await;
                ui::say(&format!("  {} interrupted, partials kept; run the same command to resume", ui::paint(ui::Tone::Warn, "!")));
                if let Some(g) = &tty_guard {
                    g.restore(); // process::exit skips Drop
                }
                // Best-effort, BOUNDED: a wedged signaling socket must not turn the
                // graceful exit into the very hang the watchdog exists to catch.
                // The signal task already armed a force-exit; cap the disconnect so
                // we exit cleanly on our own well inside that grace.
                let _ = tokio::time::timeout(Duration::from_secs(1), sio.disconnect()).await;
                std::process::exit(130);
            }
            // P0 (GAP-1): the inbound transfer stalled (zero bytes, link alive).
            // The receiver participates in the SYMMETRIC direct-QUIC repair: it
            // re-arms its own direct dial so the fresh authenticated connection
            // can form. The `.part` stays on disk; the sender re-offers
            // resume:true on the new transport, so the file continues from its
            // saved offset (no restart-from-zero). For a WebRTC link the repair
            // is the impolite-side ICE-restart inside correct_stall.
            Ev::TransferStalled(pid, idle_ms) => {
                // DEBUG, resilience internal (inbound stall detection).
                ui::debug(&ui::paint(ui::Tone::Warn, &format!("  inbound stall: {idle_ms}ms with no data from peer, repairing link")));
                // P0 partial-preservation: flush THIS peer's in-flight partials
                // to their `.part` on disk and release the in-memory handles, so
                // the C23 "already receiving" guard doesn't reject the sender's
                // resume-offer on the FRESH repair link. The `.part` + `.meta`
                // stay on disk; the resume re-opens them from the saved offset
                // (no restart-from-zero). Only this peer's streams are dropped,
                // other links keep flowing.
                let stale: Vec<(String, u32)> =
                    by_sid.keys().filter(|(p, _)| *p == pid).cloned().collect();
                for key in stale {
                    if let Some(inc) = by_sid.remove(&key) {
                        let f = inc.file.clone();
                        let _ = tokio::task::spawn_blocking(move || { let _ = f.sync_all(); }).await;
                        ui::debug(&format!("{}: parked at {} for resume", inc.name, human(inc.received.load(Ordering::Relaxed))));
                    }
                }
                match conn.correct_stall(&pid).await {
                    // Receiver has nothing to re-offer; the sender owns the offer.
                    // Rung (a) is a no-op here, wait for the sender's re-offer.
                    Rung::Resume => {}
                    Rung::Repaired => {}
                    // Rung (d) P1: the receiver re-established over the TURN relay
                    // (relay-only ICE), preserving its `.part`. The sender re-offers
                    // resume:true on the fresh relay link, the file continues from
                    // its saved offset. Nothing to do here.
                    Rung::Relayed => {}
                    // Direct rungs spent AND relay forbidden / already on relay:
                    // failed CLEANLY, partial kept on disk (message already shown).
                    Rung::Exhausted => {}
                }
            }
            // Losing the sender is only an ERROR when nothing completed,
            // after a successful transfer it's just closure (the quiet-exit
            // prints the same `done (N files).` the peer-left path would).
            Ev::Stuck(pid, generation) => {
                // Bug 5: repeated stuck before ANY byte arrived → hint at the
                // single-host mDNS wedge once.
                if !ever_received {
                    stuck_while_connecting += 1;
                    if stuck_while_connecting >= 2 {
                        maybe_hint_local_wedge(&mut wedge_hint_shown);
                    }
                }
                if conn.on_stuck(&pid, generation, "stuck while connecting").await? && paired && !keep_open {
                    // G-k: the dropped link may have delivered every byte but
                    // lost its file-end, finalize before deciding it's fatal.
                    sweep_completed_streams(&mut by_sid, &conn, &dir, &output, to_stdout, daemon, &mut completed).await?;
                    if completed == 0 {
                        bail!("lost the sender after {} attempts; the partial is kept, re-run `filament recv <code>` to resume", MAX_ATTEMPTS);
                    }
                }
            }
            Ev::GraceExpired(pid, generation) => {
                if conn.on_stuck(&pid, generation, "lost").await? && paired && !keep_open {
                    sweep_completed_streams(&mut by_sid, &conn, &dir, &output, to_stdout, daemon, &mut completed).await?;
                    if completed == 0 {
                        bail!("lost the sender after {} attempts; the partial is kept, re-run `filament recv <code>` to resume", MAX_ATTEMPTS);
                    }
                }
            }
            Ev::PcState(pid, s) => {
                // L2: a dead/closed link must abort every tunnel stream it
                // carried so no pump hangs on a peer that's gone (design §3.5).
                if l2_enabled && (s == "failed" || s == "closed" || s == "disconnected") {
                    if let Some(mux) = l2_muxes.remove(&pid) {
                        mux.shutdown_all().await;
                    }
                    // #4: a genuinely DEAD link (failed/closed) DETACHES its PTY
                    // sessions, it does NOT kill them. The shell keeps running and
                    // buffering output; a reconnect with the same session id
                    // reattaches and replays. We deliberately skip `disconnected`:
                    // that is usually a transient ICE blip the SAME data channel
                    // rides out (no new pty-open follows), so detaching there would
                    // wedge a still-working session. The detached-idle / lifetime
                    // caps in the session task reap a session nobody returns to.
                    if (s == "failed" || s == "closed") && !pty_bindings.is_empty() {
                        if let Some(sid_map) = pty_bindings.remove(&pid) {
                            for session_id in sid_map.values() {
                                if let Some(sess) = pty_sessions.get_live(session_id).await {
                                    sess.detach();
                                }
                            }
                        }
                    }
                }
                conn.on_pc_state(&pid, &s).await;
            }
            Ev::PeerLeft(v) => {
                // Test hook (gate 18): peer-left delivery is best-effort in the
                // real world; this simulates the loss deterministically so the
                // quiet-exit fallback (G-k) can be exercised. SIGSTOP can't do
                // it, engine.io's ping timeout reaps a frozen client in ~30s
                // and the legit peer-left wins the race.
                if test_hooks::drop_peer_left() {
                    continue;
                }
                let gone = v["id"].as_str().and_then(|p| conn.link(p)).map(|l| l.name.clone());
                if conn.on_peer_left(&v) {
                    let secs = conn.rejoin.rejoin_window.as_secs();
                    if !by_sid.is_empty() {
                        // Keep partials writable-but-parked; resume comes via
                        // rejoin (C6) or a later re-offer against the .part.
                        ui::say(&ui::paint(ui::Tone::Dim, &format!("  sender disconnected mid-transfer, waiting up to {secs}s")));
                        flush_inflight(&mut by_sid).await;
                    } else if completed > 0 && !keep_open {
                        ui::say(&format!("done ({completed} file{}).", if completed == 1 { "" } else { "s" }));
                        let _ = sio.disconnect().await;
                        return Ok(());
                    } else if paired && !keep_open {
                        // C21: NOT fatal, a phone opening its file picker
                        // suspends the whole tab and drops the socket. Hold
                        // the line; their client rejoins on refocus.
                        let gid = v["id"].as_str().unwrap_or_default();
                        let n = gone.unwrap_or_else(|| "sender".into());
                        ui::say(&conn.roster(gid, "", ui::Tone::Warn, &format!("stepped away, holding the line up to {secs}s (Ctrl-C to stop)"), &n));
                    } else {
                        conn.rejoin.waiting_rejoin = None; // open listener: keep going
                        let gid = v["id"].as_str().unwrap_or_default();
                        match gone {
                            Some(n) => ui::say(&conn.roster(gid, "", ui::Tone::Dim, "left, still listening", &n)),
                            None => ui::say(&ui::paint(ui::Tone::Dim, "  peer left, still listening")),
                        }
                    }
                }
            }
            _ => {}
        }
    }
}

/// P4 (GAP-5): recompute the whole-file sha256 of the received `.part` and
/// compare against the digest the sender offered (`inc.full`, guaranteed Some by
/// the caller). Flushes first so every buffered byte is on disk. This is the
/// CORE whole-file integrity guarantee the runner used to bolt on above the
/// transport, now every `recv` gets it.
///
/// Test hook (the truncation/ack gate): `FILAMENT_TEST_CORRUPT_RECV=<id>` flips
/// a byte of the on-disk `.part` for the matching transfer id right before the
/// hash is computed, deterministically inducing the corrupt-receive case so the
/// gate can prove reject + recover. `FILAMENT_TEST_CORRUPT_ONCE=1` makes it fire
/// exactly once (the re-fetch then succeeds), proving auto-recovery.
/// Recompute the whole-file sha256 and compare against the sender's offered
/// digest. Flushes (syncs) first. This is the receiver-side core of P4 integrity.
async fn verify_incoming(inc: &IncomingFile) -> protocol::VerifyResult {
    let want = match &inc.full { Some(w) => w.clone(), None => return protocol::VerifyResult::Match };
    // Sync file to disk before hashing.
    let f = inc.file.clone();
    let _ = tokio::task::spawn_blocking(move || { let _ = f.sync_all(); }).await;

    let recvd = inc.received.load(Ordering::Relaxed);

    // Test-only corruption injection (deterministic; gate proof). Compiled out
    // entirely on default/release builds, the `corrupt_recv_target` twin returns
    // None there, so this whole block strips to nothing.
    if let Some(target) = test_hooks::corrupt_recv_target() {
        #[cfg(feature = "test-hooks")]
        {
            let once = test_hooks::corrupt_recv_once();
            let already = test_hooks::corrupt_already_fired();
            if target == inc.id && recvd == inc.size && !(once && already) {
                if let Ok(mut bytes) = std::fs::read(&inc.part_path) {
                    if let Some(b) = bytes.last_mut() {
                        *b ^= 0xFF;
                        let _ = std::fs::write(&inc.part_path, &bytes);
                        eprintln!("[test] CORRUPT-RECV: flipped the last byte of {} (id {})", inc.name, inc.id);
                        if once { test_hooks::corrupt_mark_fired(); }
                    }
                }
            }
        }
        let _ = &target;
    }

    if recvd < inc.size {
        return protocol::decide_verify(recvd, inc.size, None);
    }
    let path = inc.part_path.clone();
    let got = tokio::task::spawn_blocking(move || full_hash(&path)).await.ok().flatten();
    protocol::decide_verify(recvd, inc.size, Some(got.as_deref() == Some(want.as_str())))
}

/// Finalize a fully-received incoming file: sync, rename `.part` → final,
/// clean up the meta sidecar, and (in daemon mode) append to the upload log.
/// Returns true if the file was placed. Takes `IncomingFile` by value and drops it.
async fn finalize_incoming(
    inc: IncomingFile,
    dir: &Path,
    rename_to: Option<&str>,
    daemon: bool,
    from_name: &str,
) -> Result<bool> {
    // Sync then drop file handle before rename (file is closed for the rename on Linux).
    let f = inc.file.clone();
    let _ = tokio::task::spawn_blocking(move || { let _ = f.sync_all(); }).await;
    drop(inc.file);
    let final_path = unique_path(dir, rename_to.unwrap_or(&inc.name));
    if let Err(e) = tokio::fs::rename(&inc.part_path, &final_path).await {
        ui::say(&ui::paint(ui::Tone::Dim, &format!("  (stream for {} already finalized, duplicate discarded: {e})", inc.name)));
        return Ok(false);
    }
    let _ = tokio::fs::remove_file(dir.join(format!("{}.part.meta", inc.name))).await;
    let recvd = inc.received.load(Ordering::Relaxed);
    let ok = recvd == inc.size;
    inc.bar.done(recvd);
    let shown = final_path.display().to_string();
    ui::say(&format!(
        "    {} {}{}",
        ui::paint(ui::Tone::Dim, ui::glyph_arrow()),
        ui::link(&format!("file://{shown}"), &shown),
        if ok { String::new() } else { ui::paint(ui::Tone::Err, "  SIZE MISMATCH") },
    ));
    if ok {
        let lname = final_path
            .file_name()
            .map(|n| n.to_string_lossy().to_ascii_lowercase())
            .unwrap_or_default();
        let is_archive =
            lname.ends_with(".tar") || lname.ends_with(".tar.gz") || lname.ends_with(".tgz");
        let peer = (!from_name.is_empty()).then_some(from_name);
        if is_archive && settings::get_bool("auto-extract", peer) {
            match settings::extract_archive(&final_path, dir) {
                Ok(n) => ui::say(&format!(
                    "    {} extracted {n} file{} into {}",
                    ui::paint(ui::Tone::Ok, ui::glyph_ok()),
                    if n == 1 { "" } else { "s" },
                    dir.display()
                )),
                Err(e) => ui::say(&ui::paint(
                    ui::Tone::Warn,
                    &format!("    auto-extract skipped ({e}); the archive is kept as-is"),
                )),
            }
        }
    }
    if daemon {
        use std::io::Write as _;
        if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(up_log()) {
            let _ = writeln!(f, "{}  {}  {}  from {}", chrono_now(), inc.name, human(recvd), from_name);
        }
    }
    Ok(true)
}

/// G-k completion sweep: file-end delivery is best-effort. A stream can
/// receive every expected byte yet have its file-end LOST when the sender's
/// PeerConnection tears down first (observed under load). The bytes are whole
/// (held in `inc.received`; `finalize_incoming` flushes the BufWriter before
/// rename so the on-disk file is complete), but the stream is stranded in
/// `by_sid` with no live link to ever deliver file-end, and that non-empty
/// `by_sid` plus `completed == 0` blocks the quiet-exit while the dead link
/// spins through the reconnect-retry loop to the 120s ceiling. Finalize any
/// fully received stream whose link is gone. `received == size` is exactly the
/// bar the file-end handler itself checks, so this can never claim a genuine
/// partial (received < size stays parked for resume, gate 2) and never
/// touches the offer-stage corruption guard (gate 3). Called both at top-of-
/// loop and right after a link is dropped in the Stuck/GraceExpired handlers,
/// so the bail on `completed == 0` sees the finalized file.
async fn sweep_completed_streams(
    by_sid: &mut HashMap<(String, u32), IncomingFile>,
    conn: &Conn,
    dir: &Path,
    output: &Option<String>,
    to_stdout: bool,
    daemon: bool,
    completed: &mut usize,
) -> Result<()> {
    let done_sids: Vec<(String, u32)> = by_sid
        .iter()
        .filter(|((pid, _), inc)| inc.received.load(Ordering::Relaxed) == inc.size && !conn.links.contains_key(pid))
        .map(|(k, _)| k.clone())
        .collect();
    for key in done_sids {
        if let Some(inc) = by_sid.remove(&key) {
            if to_stdout {
                let f = inc.file.clone();
                let _ = tokio::task::spawn_blocking(move || { let _ = f.sync_all(); }).await;
                *completed += 1;
                continue;
            }
            let rename_to = if *completed == 0 { output.clone() } else { None };
            ui::say(&ui::paint(ui::Tone::Dim, &format!("  ({} fully received, sender left before file-end; finalizing)", inc.name)));
            if finalize_incoming(inc, dir, rename_to.as_deref(), daemon, "").await? {
                *completed += 1;
            }
        }
    }
    Ok(())
}

/// Park in-flight receives: sync so the .part files are complete up
/// to the last byte received, then drop the per-link routing. Resume picks
/// them up from disk.
async fn flush_inflight(by_sid: &mut HashMap<(String, u32), IncomingFile>) {
    for (_sid, inc) in by_sid.drain() {
        let f = inc.file.clone();
        let _ = tokio::task::spawn_blocking(move || { let _ = f.sync_all(); }).await;
        ui::debug(&format!("{}: parked at {} for resume", inc.name, human(inc.received.load(Ordering::Relaxed))));
    }
}

/// C22: cbreak-mode guard, single-keypress answers without losing line
/// input. `stty` keeps us dependency-free; Drop restores the terminal (and
/// the Interrupted path calls restore() explicitly since process::exit skips
/// Drop).
struct TtyGuard {
    saved: Option<String>,
}

impl TtyGuard {
    fn raw() -> TtyGuard {
        let saved = std::process::Command::new("stty")
            .arg("-g")
            .stdin(std::process::Stdio::inherit())
            .output()
            .ok()
            .filter(|o| o.status.success())
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());
        if saved.is_some() {
            let _ = std::process::Command::new("stty")
                .args(["-icanon", "-echo", "min", "1", "time", "0"])
                .stdin(std::process::Stdio::inherit())
                .status();
        }
        TtyGuard { saved }
    }
    fn restore(&self) {
        if let Some(s) = &self.saved {
            let _ = std::process::Command::new("stty")
                .arg(s)
                .stdin(std::process::Stdio::inherit())
                .status();
        }
    }
}

impl Drop for TtyGuard {
    fn drop(&mut self) {
        self.restore();
    }
}

/// C22: per-process token marking a locally re-enqueued (consented) offer.
/// A remote peer cannot know it, so it cannot forge consent in a control msg.
fn consent_token() -> &'static str {
    static T: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    T.get_or_init(fresh_secret)
}

/// C26: one-line colored peer status, static scrollback lines, the CLI's
/// equivalent of the web UI's amber 'away' tile.
///   ✓ deft-gibbon                    (connected)
///   ● deft-gibbon  away, choosing a file
///   ◌ deft-gibbon  reconnecting...
fn peer_entry(name: &str, mark: &str, tone: ui::Tone, note: &str) -> String {
    let mut s = format!("{} {}", ui::paint(tone, mark), ui::paint(ui::Tone::Bold, name));
    if !note.is_empty() {
        s.push_str(&format!("  {}", ui::paint(ui::Tone::Dim, note)));
    }
    s
}

fn offer_question(sender: &str, name: &str, size: u64, paired: bool) -> String {
    let sender = if sender.is_empty() { "unknown peer" } else { sender };
    let hint = if paired { " [paired]" } else { "" };
    format!(
        "  {}{} offers {} ({}), accept? [y/N] ",
        ui::paint(ui::Tone::Bold, sender),
        hint,
        name,
        human(size)
    )
}

// -------------------------------------------------------------------- tests --

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

    #[test]
    fn sanitize_device_name_strips_escape_junk() {
        // The exact corruption observed on the snapshot: a terminal
        // device-attributes reply captured ahead of the real name.
        let dirty = "\u{1b}[?1;2c\u{1b}[?1;2c\u{1b}[>0;276;0cpixel";
        assert_eq!(sanitize_device_name(dirty), "pixel");
        // Lone control chars dropped; surrounding whitespace trimmed.
        assert_eq!(sanitize_device_name("  lap\u{7}top \n"), "laptop");
        // A clean name is unchanged.
        assert_eq!(sanitize_device_name("agboola@pop-os"), "agboola@pop-os");
    }

    #[test]
    fn capability_deny_by_default() {
        // GATE 5: deny-by-default. A device with empty caps is refused any gated
        // action; "transfer" is the always-allowed L0 baseline; a v1 record
        // (no caps) reads as ["transfer"]; future caps must be explicitly
        // granted (i.e. agreed under K at re-enrollment), not escalatable.
        let dir = std::env::temp_dir().join(format!("fil-caps-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let p = dir.join("devices.json");
        let sec = "a".repeat(64);
        std::fs::write(
            &p,
            serde_json::to_string(&json!([
                {"name": "empty",   "secret": sec, "v": 2, "caps": []},
                {"name": "xfer",    "secret": sec, "v": 2, "caps": ["transfer"]},
                {"name": "execcap", "secret": sec, "v": 2, "caps": ["transfer", "remote-exec"]},
                {"name": "legacy",  "secret": sec}  // v1 record: reads as ["transfer"]
            ]))
            .unwrap(),
        )
        .unwrap();

        // transfer is the L0 baseline, allowed even for empty caps.
        assert!(device_allows_at(&p, "empty", "transfer"), "transfer is the L0 baseline");
        assert!(device_allows_at(&p, "xfer", "transfer"));
        // A v1 record reads as caps:["transfer"] (back-compat, spec §8).
        assert_eq!(device_caps_at(&p, "legacy"), Some(vec!["transfer".to_string()]));
        assert!(device_allows_at(&p, "legacy", "transfer"));
        // Deny-by-default: a gated future cap is REFUSED unless explicitly granted.
        assert!(!device_allows_at(&p, "empty", "remote-exec"), "empty caps must deny remote-exec");
        assert!(!device_allows_at(&p, "xfer", "remote-exec"), "transfer-only must deny remote-exec");
        assert!(!device_allows_at(&p, "legacy", "remote-exec"), "v1 record must deny remote-exec");
        // Only a device explicitly granted the cap (under K, at enrollment) is allowed.
        assert!(device_allows_at(&p, "execcap", "remote-exec"), "explicitly granted cap is allowed");
        // An unknown device grants no GATED cap (but transfer is the universal
        // L0 baseline, so it is allowed regardless, never regresses send/recv).
        assert!(!device_allows_at(&p, "ghost", "remote-exec"));
        assert!(device_allows_at(&p, "ghost", "transfer"), "transfer baseline is universal");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn any_shell_grant_detects_a_shell_cap() {
        let dir = std::env::temp_dir().join(format!("fil-anyshell-{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let p = dir.join("devices.json");
        let sec = "b".repeat(64);
        // No shell grant anywhere -> false (a plain `up` stays L2-off).
        std::fs::write(
            &p,
            serde_json::to_string(&json!([
                {"name": "xfer",   "secret": sec, "v": 2, "caps": ["transfer"]},
                {"name": "legacy", "secret": sec}
            ]))
            .unwrap(),
        )
        .unwrap();
        assert!(!any_shell_grant_at(&p), "no shell cap -> L2 stays off");
        // One device granted shell -> true (the daemon turns L2 on).
        std::fs::write(
            &p,
            serde_json::to_string(&json!([
                {"name": "xfer",  "secret": sec, "v": 2, "caps": ["transfer"]},
                {"name": "popos", "secret": sec, "v": 2, "caps": ["transfer", "shell"]}
            ]))
            .unwrap(),
        )
        .unwrap();
        assert!(any_shell_grant_at(&p), "a shell grant enables L2");
        // A missing/garbage file is false, never a panic.
        assert!(!any_shell_grant_at(&dir.join("nope.json")));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn l2_open_gate_scopes_grant_mode() {
        // Blanket mode (--shell / --shell-only / FILAMENT_L2): any trusted peer
        // may open, regardless of its own per-device grant (unchanged behavior).
        assert!(l2_open_allowed(true, false));
        assert!(l2_open_allowed(true, true));
        // Grant-only mode (L2 on solely because SOME device has a shell grant):
        // the opening peer must itself hold the grant.
        assert!(l2_open_allowed(false, true), "granted device may open");
        assert!(!l2_open_allowed(false, false), "ungranted device denied in grant mode");
    }

    #[test]
    fn l2_target_allowlist_matches() {
        let allow = json!({
            "laptop": ["10.0.0.5:5432", "192.168.1.10:*"],
            "*": ["db.internal:5432"]
        });
        // Exact host:port for the named device.
        assert!(l2_target_allowed_in(&allow, "laptop", "10.0.0.5", 5432));
        // host:* allows any port for that host.
        assert!(l2_target_allowed_in(&allow, "laptop", "192.168.1.10", 9999));
        // "*" device entry applies to any device.
        assert!(l2_target_allowed_in(&allow, "phone", "db.internal", 5432));
        // Wrong port (no wildcard) is denied.
        assert!(!l2_target_allowed_in(&allow, "laptop", "10.0.0.5", 22));
        // Host not listed is denied.
        assert!(!l2_target_allowed_in(&allow, "laptop", "10.0.0.9", 5432));
        // A device with no entry (and not matching "*") is denied.
        assert!(!l2_target_allowed_in(&allow, "phone", "10.0.0.5", 5432));
        // No allowlist at all (null) denies everything (loopback-only default).
        assert!(!l2_target_allowed_in(&Value::Null, "laptop", "10.0.0.5", 5432));
        // Host match is case-insensitive.
        assert!(l2_target_allowed_in(&allow, "phone", "DB.INTERNAL", 5432));
    }

    #[test]
    fn shell_policy_gates_auto_shell() {
        // `up` default: NOTHING auto-shells, a device needs an explicit grant.
        let g = ShellPolicy::Granted;
        assert!(!g.auto_allows("popos"));
        assert!(!g.enables_l2(), "default must not silently enable the L2 acceptor");
        // `up --shell`: every paired device auto-shells, and L2 is on.
        let a = ShellPolicy::All;
        assert!(a.auto_allows("popos") && a.auto_allows("anything"));
        assert!(a.enables_l2());
        // `up --shell-only popos,laptop`: only the listed petnames; others don't.
        let o = ShellPolicy::Only(["popos".to_string(), "laptop".to_string()].into_iter().collect());
        assert!(o.auto_allows("popos") && o.auto_allows("laptop"));
        assert!(!o.auto_allows("stranger"), "shell-only must not auto-shell unlisted devices");
        assert!(o.enables_l2());
    }

    #[test]
    fn direct_ok_for_covers_daemon_and_l2_acceptors() {
        // Anti-glare gate (`recv_cmd` builds `direct_ok` from this). Clear the env
        // gates so the daemon/l2 BRANCHES are what we're asserting, not the env.
        // SAFETY: single-threaded within this test; the asserts that depend on the
        // env-unset state are the (false,false) and (false,false,daemon=false) ones.
        unsafe {
            std::env::remove_var("FILAMENT_DIRECT");
            std::env::remove_var("FILAMENT_L2");
        }
        // A plain `up` daemon (no --shell, no env): MUST take the direct path so it
        // answers the peer's transport-offer instead of glaring with a WebRTC dial.
        assert!(direct_ok_for(true, false), "plain `up` daemon must answer direct-QUIC (anti-glare)");
        // The L2/ssh acceptor (`up --shell`) keeps taking it (the prior fix).
        assert!(direct_ok_for(true, true));
        assert!(direct_ok_for(false, true), "L2 acceptor must take direct even when not a daemon");
        // A one-shot command (daemon=false) with no L2 now defaults to direct-ON
        // (the default changed from opt-in to opt-out). FILAMENT_DIRECT=0 restores WebRTC.
        assert!(direct_ok_for(false, false), "default direct-ON for any session");
        unsafe { std::env::set_var("FILAMENT_DIRECT", "0") };
        assert!(!direct_ok_for(false, false), "FILAMENT_DIRECT=0 disables direct");
        unsafe { std::env::remove_var("FILAMENT_DIRECT") };
    }

    #[test]
    fn forget_and_store_preserve_other_devices_caps() {
        // Regression: forgetting/pairing a device must NOT wipe the `shell`
        // (or any v2) caps of the OTHER devices. The old (name, secret) tuple
        // round-trip rewrote every survivor as bare {name, secret}, silently
        // dropping their grants, a remembered device lost its shell on the
        // next `forget`/`pair`.
        let dir = std::env::temp_dir().join(format!("fil-store-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        // Serialize: these tests mutate the process-global FILAMENT_CONFIG_DIR.
        unsafe { std::env::set_var("FILAMENT_CONFIG_DIR", &dir) };
        let p = dir.join("devices.json");
        let sec = "b".repeat(64);
        std::fs::write(
            &p,
            serde_json::to_string(&json!([
                {"name": "shellbox", "secret": sec, "v": 2, "caps": ["transfer", "shell"]},
                {"name": "dupe",     "secret": sec, "v": 2, "caps": ["transfer"]},
            ]))
            .unwrap(),
        )
        .unwrap();

        // Forgetting 'dupe' must leave 'shellbox' with its shell cap intact.
        devices_remove("dupe").unwrap();
        assert!(device_allows_at(&p, "shellbox", "shell"), "forget wiped a survivor's shell cap");
        assert!(device_caps_at(&p, "dupe").is_none(), "dupe should be gone");

        // Storing a NEW pairing must also preserve 'shellbox''s caps.
        devices_store("newpeer", &sec).unwrap();
        assert!(device_allows_at(&p, "shellbox", "shell"), "store wiped a survivor's shell cap");
        // And re-storing an existing name keeps its caps (only the secret rotates).
        devices_store("shellbox", &"c".repeat(64)).unwrap();
        assert!(device_allows_at(&p, "shellbox", "shell"), "re-store dropped the device's own caps");

        unsafe { std::env::remove_var("FILAMENT_CONFIG_DIR") };
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn proof_matches_browser() {
        // Pinned to the SAME external vector as frontend devices.js (computed
        // with `printf 'filament-proof2:u1|u1|u2|FPA|FPB' | openssl dgst
        // -sha256 -hmac s3cret`). If either implementation drifts, browsers
        // and CLIs silently stop recognizing each other as known devices.
        // The JS half of this byte-identity proof asserts the IDENTICAL vectors:
        // cli/tests/l1a/gate8_byte_identity.mjs (channelOf/proofFor).
        let want = "f98c3b6b7a70ebdf4b200680e83383881bdb1a11476283507359c55ef03a8474";
        // deliberately unsorted inputs, proof_for must normalize
        assert_eq!(proof_for("s3cret", "u1", "u2", "u1", "FPB", "FPA"), want);
        assert_eq!(proof_for("s3cret", "u1", "u1", "u2", "FPA", "FPB"), want);
        // channel derivation, same cross-check (sha256 of "filament-pair:"+secret)
        assert_eq!(
            channel_of("topsecret"),
            "1e32e46e93691c29d9c0305545a10c86a00ae9f3c43d4eea3c7423c1528f9b5d"
        );
    }

    #[test]
    fn polite_role_matches_browser() {
        // uid comparison wins, string-lexicographic, mirrors webrtc.js politeRole
        assert!(net::polite_role("b", Some("a"), "x", "y")); // myUid > peerUid -> polite
        assert!(!net::polite_role("a", Some("b"), "x", "y"));
        // identical/missing uids fall back to sids
        assert!(net::polite_role("a", Some("a"), "y", "x"));
        assert!(!net::polite_role("a", None, "x", "y"));
        // exactly one side of any pair is impolite
        for (a, b) in [("a", "b"), ("cli-1", "cli-2"), ("zz", "aa")] {
            let p1 = net::polite_role(a, Some(b), "s1", "s2");
            let p2 = net::polite_role(b, Some(a), "s2", "s1");
            assert_ne!(p1, p2, "{a} vs {b} must disagree");
        }
    }

    #[test]
    fn part_meta_roundtrip_and_legacy() {
        let dir = std::env::temp_dir().join(format!("filament-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let p = dir.join("x.part.meta");
        PartMeta { size: 42, head: Some("abc".into()), full: Some("deadbeef".into()) }.store(&p).unwrap();
        let m = PartMeta::load(&p).unwrap();
        assert_eq!(m.size, 42);
        assert_eq!(m.head.as_deref(), Some("abc"));
        // P4: the whole-file digest survives the round-trip too.
        assert_eq!(m.full.as_deref(), Some("deadbeef"));
        // legacy plain-size format still parses
        std::fs::write(&p, "1234").unwrap();
        let m = PartMeta::load(&p).unwrap();
        assert_eq!(m.size, 1234);
        assert!(m.head.is_none());
        assert!(m.full.is_none());
        // garbage does not
        std::fs::write(&p, "{not json").unwrap();
        assert!(PartMeta::load(&p).is_none());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn head_hash_is_prefix_stable() {
        let dir = std::env::temp_dir().join(format!("filament-test-h-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let a = dir.join("a.bin");
        let b = dir.join("b.bin");
        // same first 256 KiB, different tails -> same head (by design: head is
        // a prefix identity, full integrity is the per-chunk-hash backlog)
        let mut base = vec![7u8; (HEAD_BYTES + 10) as usize];
        std::fs::write(&a, &base).unwrap();
        base[(HEAD_BYTES + 5) as usize] = 9;
        std::fs::write(&b, &base).unwrap();
        assert_eq!(head_hash(&a), head_hash(&b));
        // different first bytes -> different head
        base[0] = 1;
        std::fs::write(&b, &base).unwrap();
        assert_ne!(head_hash(&a), head_hash(&b));
        // short files hash their whole content
        std::fs::write(&a, b"tiny").unwrap();
        std::fs::write(&b, b"tinY").unwrap();
        assert_ne!(head_hash(&a), head_hash(&b));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn full_hash_whole_file_integrity() {
        // P4 (GAP-5): full_hash digests the WHOLE file (not just the 256 KiB
        // head), so a difference PAST the head, exactly the truncation/corrupt
        // case the head-hash can't see, produces a different digest.
        let dir = std::env::temp_dir().join(format!("filament-test-fh-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let a = dir.join("a.bin");
        let b = dir.join("b.bin");
        let mut base = vec![3u8; (HEAD_BYTES + 4096) as usize];
        std::fs::write(&a, &base).unwrap();
        // identical head, byte flipped well PAST the head: head_hash agrees but
        // full_hash MUST differ (this is the whole-file guarantee).
        base[(HEAD_BYTES + 2048) as usize] = 4;
        std::fs::write(&b, &base).unwrap();
        assert_eq!(head_hash(&a), head_hash(&b), "tails past the head don't change the head hash");
        assert_ne!(full_hash(&a), full_hash(&b), "full_hash sees the whole file");
        // a truncated file (same prefix, shorter) also differs.
        std::fs::write(&b, &base[..base.len() - 100]).unwrap();
        assert_ne!(full_hash(&a), full_hash(&b), "truncation changes the full hash");
        // full_hash matches a one-shot sha256 of the bytes.
        assert_eq!(full_hash(&a), Some(sha256_hex(&vec![3u8; (HEAD_BYTES + 4096) as usize])));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn unique_path_suffixes() {
        let dir = std::env::temp_dir().join(format!("filament-test-u-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        assert_eq!(unique_path(&dir, "f.txt"), dir.join("f.txt"));
        std::fs::write(dir.join("f.txt"), b"x").unwrap();
        assert_eq!(unique_path(&dir, "f.txt"), dir.join("f.txt.1"));
        std::fs::write(dir.join("f.txt.1"), b"x").unwrap();
        assert_eq!(unique_path(&dir, "f.txt"), dir.join("f.txt.2"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn route_address_classification() {
        // C2: the badge means "bytes never leave your network", an address
        // property, not a candidate-type property.
        for a in ["127.0.0.1", "10.1.2.3", "192.168.1.9", "172.16.0.1", "169.254.1.1", "100.99.1.2", "::1", "fe80::1", "fd00::5"] {
            assert!(net::is_private_addr(a), "{a} should be private");
        }
        for a in ["1.2.3.4", "165.22.207.231", "2606:4700::1", "8.8.8.8", "not-an-ip", ""] {
            assert!(!net::is_private_addr(a), "{a} should be public/invalid");
        }
    }


    #[test]
    fn filename_sanitization() {
        // the recv path strips directories from remote names
        let evil = "../../etc/passwd";
        let name = Path::new(evil).file_name().map(|n| n.to_string_lossy().into_owned());
        assert_eq!(name.as_deref(), Some("passwd"));
        let evil2 = "/absolute/path.bin";
        let name2 = Path::new(evil2).file_name().map(|n| n.to_string_lossy().into_owned());
        assert_eq!(name2.as_deref(), Some("path.bin"));
    }

    // Bug 1: `send --name X` is honored for a SINGLE regular file (offer name =
    // override), the basename otherwise, and "stdin.bin" for bare stdin. This
    // mirrors the send_cmd offer-name decision as a pure check.
    #[test]
    fn send_name_override_for_single_file() {
        let offered = |name: Option<&str>, single: bool, basename: &str| -> String {
            name.map(String::from)
                .filter(|_| single)
                .unwrap_or_else(|| basename.to_string())
        };
        // single file + --name → the override wins
        assert_eq!(offered(Some("renamed.bin"), true, "original.txt"), "renamed.bin");
        // single file, no --name → basename
        assert_eq!(offered(None, true, "original.txt"), "original.txt");
        // multiple paths (single=false) + --name → ignored, basename used
        assert_eq!(offered(Some("renamed.bin"), false, "original.txt"), "original.txt");
        // stdin default
        let stdin = |name: Option<&str>, single: bool| {
            name.map(String::from).filter(|_| single).unwrap_or_else(|| "stdin.bin".into())
        };
        assert_eq!(stdin(Some("logs.tar"), true), "logs.tar");
        assert_eq!(stdin(None, true), "stdin.bin");
    }

    // 3-seg codes: both transfer (word-word-NNN) and pairing (word-word-NNNN)
    // share the shape now, so the pairing-vs-transfer HINT is by trailing-number
    // WIDTH. `looks_like_pake_code` (4-digit) is a strict SUBSET of
    // `regex_lite_code` (3-seg word-word-DIGITS) by design, the hint is
    // advisory, never an authenticator.
    #[test]
    fn transfer_and_pairing_codes_are_distinguishable() {
        // minted transfer code: word-word-NNN (3-digit), claimable, NOT pairing.
        assert!(regex_lite_code("brave-otter-371"));
        assert!(!looks_like_pake_code("brave-otter-371"));
        // minted pairing code: word-word-NNNN (4-digit), claimable AND pairing.
        assert!(regex_lite_code("brave-otter-3141"));
        assert!(looks_like_pake_code("brave-otter-3141"));
        // The redirect predicates the commands actually use:
        //   `recv` bails on a pairing-looking code:        looks_like_pake_code
        //   `pair` bails on a transfer-looking code: regex && !looks_like_pake
        let transfer_hint = |s: &str| regex_lite_code(s) && !looks_like_pake_code(s);
        assert!(transfer_hint("brave-otter-371"));   // -> "use recv"
        assert!(!transfer_hint("brave-otter-3141")); // a pairing code, no bail
        assert!(looks_like_pake_code("brave-otter-3141"));  // -> "use pair"
        assert!(!looks_like_pake_code("brave-otter-37"));   // 2-digit transfer
        // width boundary: 2-3 digits => transfer hint, >=4 => pairing hint.
        assert!(trailing_num_width("brave-otter-37") == 2);
        assert!(!looks_like_pake_code("brave-otter-37"));
        assert!(looks_like_pake_code("calm-lynx-1000"));
        // junk / malformed match neither.
        assert!(!regex_lite_code("hello"));
        assert!(!looks_like_pake_code("hello"));
        assert!(!regex_lite_code("a-b-c-d"));               // 4 segments
        assert!(!regex_lite_code("brave-otter-ruby-3141")); // 4 segments (old shape)
        assert!(!looks_like_pake_code("Brave-otter-3141")); // uppercase
    }

    // STEERING floor: --word must contain >= 2 word tokens (letter-runs >= 2).
    #[test]
    fn password_word_tokens_counts_real_words() {
        // single word, too weak (refused).
        assert_eq!(password_word_tokens("cat"), 1);
        assert_eq!(password_word_tokens("gigantic"), 1);
        // two+ words, ok.
        assert_eq!(password_word_tokens("gigantic-element"), 2);
        assert_eq!(password_word_tokens("brave-otter"), 2);
        assert_eq!(password_word_tokens("brave-strong-otter"), 3);
        // 1-letter fragments and digits don't count as words.
        assert_eq!(password_word_tokens("a-b-c"), 0);
        assert_eq!(password_word_tokens("ok1234"), 1);
        // normalized spaces become dashes upstream; here we only see lowercase.
        assert_eq!(password_word_tokens(""), 0);
    }

    #[test]
    fn devices_store_collision_auto_suffixes() {
        // When a name collision occurs, the new device gets auto-suffixed.
        // This prevents two devices from silently shadowing each other.
        let mut arr: Vec<serde_json::Value> = serde_json::from_str(
            r#"[{"name":"host1","secret":"aaa"}]"#
        ).unwrap();
        let new_secret = "bbb";
        let name = "host1";
        // Simulate collision handling (same logic as devices_store)
        let final_name = if arr.iter().any(|d| d["name"].as_str() == Some(name)) {
            let mut suffix = 2;
            let mut new_name = format!("{name}-{suffix}");
            while arr.iter().any(|d| d["name"].as_str() == Some(&new_name)) {
                suffix += 1;
                new_name = format!("{name}-{suffix}");
            }
            new_name
        } else {
            name.to_string()
        };
        arr.push(serde_json::json!({"name": &final_name, "secret": new_secret}));
        // Verify auto-suffix was applied
        assert_eq!(arr.len(), 2, "both entries preserved");
        assert_eq!(arr[0]["name"].as_str().unwrap(), "host1", "original unchanged");
        assert_eq!(arr[1]["name"].as_str().unwrap(), "host1-2", "new device auto-suffixed");
    }

    #[test]
    fn devices_store_collision_increments_suffix() {
        // Multiple collisions should increment the suffix.
        let mut arr: Vec<serde_json::Value> = serde_json::from_str(
            r#"[{"name":"host1","secret":"aaa"},{"name":"host1-2","secret":"bbb"}]"#
        ).unwrap();
        let name = "host1";
        let final_name = if arr.iter().any(|d| d["name"].as_str() == Some(name)) {
            let mut suffix = 2;
            let mut new_name = format!("{name}-{suffix}");
            while arr.iter().any(|d| d["name"].as_str() == Some(&new_name)) {
                suffix += 1;
                new_name = format!("{name}-{suffix}");
            }
            new_name
        } else {
            name.to_string()
        };
        arr.push(serde_json::json!({"name": &final_name, "secret": "ccc"}));
        assert_eq!(arr[2]["name"].as_str().unwrap(), "host1-3", "suffix incremented");
    }

    // --- KnownPeer idempotency regression tests ---
    // These guard against P0 churn: repeated KnownPeer presence events must NOT
    // re-fire establishment on an already-seen/live peer. The real handler uses
    // a HashSet<device_name>; these tests verify the idempotency contract.

    #[test]
    fn known_peer_first_event_connects() {
        let mut saw: HashSet<String> = HashSet::new();
        let n = "popos";
        assert!(!saw.contains(n), "first event should connect");
        saw.insert(n.to_string());
        assert!(saw.contains(n));
    }

    #[test]
    fn known_peer_repeat_while_seen_is_ignored() {
        let mut saw: HashSet<String> = HashSet::new();
        let n = "dovm";
        saw.insert(n.to_string());
        for _ in 0..5 {
            assert!(saw.contains(n), "repeat KnownPeer must be ignored");
        }
    }

    #[test]
    fn known_peer_uses_device_name_not_pid() {
        let mut saw: HashSet<String> = HashSet::new();
        let n = "other-do";
        assert!(!saw.contains(n));
        saw.insert(n.to_string());
        // Same device name with different pids should still be skipped
        assert!(saw.contains(n), "should skip regardless of signaling pid");
    }

    #[test]
    fn known_peer_different_devices_not_skipped() {
        let mut saw: HashSet<String> = HashSet::new();
        saw.insert("dovm".to_string());
        assert!(!saw.contains("popos"), "different device must not be skipped");
        saw.insert("popos".to_string());
        assert!(saw.contains("popos"));
    }

    #[test]
    fn confirm_yes_passes() {
        let caps = UiCapability { interactive: false, json: false, yes: true, color: false };
        assert!(caps.confirm("delete it").is_ok());
    }

    #[test]
    fn confirm_non_interactive_without_yes_fails() {
        let caps = UiCapability { interactive: false, json: false, yes: false, color: false };
        assert!(caps.confirm("delete it").is_err());
    }

    #[test]
    fn known_peer_liveness_allows_reconnect() {
        let mut saw: HashSet<String> = HashSet::new();
        let n = "peer";
        assert!(!saw.contains(n));
        saw.insert(n.to_string());
        // Link dies: clear to allow reconnect
        saw.remove(n);
        assert!(!saw.contains(n), "dead link must be reconnectable");
    }
}