zc2 0.0.45

P2P compute broker with credit-based billing, WAL, and broker mesh support
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
//! Process supervision for `zc agent` (spec §6.5): spawn the broker and the
//! workers in their own process groups, observe them, drain and stop them,
//! and re-adopt them after an agent restart.

use crate::agent::config::AgentConfig;
use crate::agent::files::{ensure_dir, ChildRecord, Children, WORKER_LOG_DIR};
use crate::agent::merge::LocalView;
use crate::agent::plan::{self, Action, BrokerObs, Desired, Observed, WorkerObs};
use crate::agent::summary::{Problem, Requests, WorkerCounts};
use crate::vpn::RouteKind;
use std::collections::{BTreeMap, HashSet};
use std::io::{Read as _, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

pub const WORKER_LOG_MAX_BYTES: u64 = 5 * 1024 * 1024;
/// How long a `drain_timeout` stays on the problem list after it happened.
const DRAIN_TIMEOUT_SHOWN_FOR: Duration = Duration::from_secs(300);
/// A slot or the broker is considered "stable" (its crash-backoff counter
/// resets to zero) once it has run continuously for this long without
/// crashing. Same five-minute window `plan::is_crashloop` uses.
const CRASH_STABLE_AFTER: Duration = Duration::from_secs(300);
/// How long a live broker process may go without answering `/health` before
/// the agent kills and restarts it. Without this limit such a broker stayed
/// `Starting` forever. One that had run out of file descriptors reset every
/// request for two days, and `zc ls` could neither reach it nor replace it.
const BROKER_UNRESPONSIVE_AFTER: Duration = Duration::from_secs(120);
/// `plan::is_crashloop` only looks at failures within this window; failure
/// timestamps older than this are pruned so the lists don't grow forever.
const CRASHLOOP_WINDOW: Duration = Duration::from_secs(300);

/// The timeout of every HTTP call to the local broker (`/health`, `GET
/// /workers`, drain, delete). A reconcile tick already running when the agent
/// shuts down can still spend two of these on its broker checks before it
/// next looks at the stop flag.
pub(crate) const BROKER_CHECK_TIMEOUT: Duration = Duration::from_secs(2);

/// One entry of the broker's `GET /workers`, the fields the agent uses.
#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
pub struct BrokerWorker {
    pub id: String,
    pub name: String,
    pub status: String,
    #[serde(default)]
    pub active_requests: u32,
    #[serde(default)]
    pub requests_5h: u64,
    #[serde(default)]
    pub requests_1w: u64,
}

/// The slice of the local broker the supervisor talks to.
pub trait BrokerApi {
    /// `/health` answers and identifies as `zakuro-broker`.
    fn is_broker(&self) -> bool;
    fn workers(&self) -> Result<Vec<BrokerWorker>, String>;
    fn drain(&self, id: &str) -> Result<(), String>;
    fn delete(&self, id: &str) -> Result<(), String>;

    /// `/health` at an arbitrary port answers and identifies as
    /// `zakuro-broker`. `is_broker()` is really `is_broker_at(self.port)`;
    /// `observe` also calls this directly at the *preferred* broker port
    /// (always 9000, regardless of any fallback already in use), to decide
    /// `Unmanaged` before ever choosing a fallback. `HttpBrokerApi` overrides
    /// this with a real `/health` GET, so the conservative "no" default below
    /// is never used in production; `FakeBroker` overrides it too, to drive
    /// `a_foreign_broker_on_the_preferred_port_is_unmanaged`.
    fn is_broker_at(&self, _port: u16) -> bool {
        false
    }
    /// True when the broker could actually bind `port` right now. No default:
    /// this does real socket I/O, so a fake that forgets to override it must
    /// fail to compile rather than silently binding real ports from the test
    /// binary. See `HttpBrokerApi::port_free` for the real implementation and
    /// why a loopback-only check is not enough on macOS.
    fn port_free(&self, port: u16) -> bool;
    /// Bind an OS-assigned port, read it back, and drop the socket
    /// immediately so the caller can bind it again itself. No default, for
    /// the same reason as `port_free`.
    fn os_assigned_port(&self) -> Option<u16>;
}

/// The broker falls back to this range (9001..=9010, the same range zc
/// clients scan for a local broker -- see `src/autobroker.rs`) when the
/// preferred port (9000) is held by something that isn't our broker. With the
/// preferred port it is exactly what the proxy route's relay carries
/// (`vpn::relay_covers`), so a fallback stays reachable from the mesh there.
pub const BROKER_FALLBACK_START: u16 = 9001;
pub const BROKER_FALLBACK_END: u16 = 9010;

/// Pure port choice: prefer `preferred`; else the first free port in
/// `fallback_start..=fallback_end`; else whatever `os_pick` returns; else
/// `None` when nothing at all is available.
pub fn choose_broker_port(
    preferred: u16,
    fallback_start: u16,
    fallback_end: u16,
    mut is_free: impl FnMut(u16) -> bool,
    os_pick: impl FnOnce() -> Option<u16>,
) -> Option<u16> {
    if is_free(preferred) {
        return Some(preferred);
    }
    for p in fallback_start..=fallback_end {
        if is_free(p) {
            return Some(p);
        }
    }
    os_pick()
}

pub struct HttpBrokerApi {
    pub port: u16,
    pub worker_key: Option<String>,
}

impl HttpBrokerApi {
    fn base(&self) -> String {
        format!("http://127.0.0.1:{}", self.port)
    }
    fn http() -> ureq::Agent {
        ureq::Agent::new_with_config(
            ureq::Agent::config_builder()
                .timeout_global(Some(BROKER_CHECK_TIMEOUT))
                .http_status_as_error(false)
                .build(),
        )
    }
}

/// A 2xx status counts as success; anything else — including no response at
/// all — is an error the caller must not read as "zero workers" or "idle".
fn is_success_status(status: u16) -> bool {
    (200..300).contains(&status)
}

impl BrokerApi for HttpBrokerApi {
    fn is_broker(&self) -> bool {
        self.is_broker_at(self.port)
    }
    fn is_broker_at(&self, port: u16) -> bool {
        Self::http()
            .get(&format!("http://127.0.0.1:{port}/health"))
            .call()
            .ok()
            .filter(|r| r.status().as_u16() == 200)
            .and_then(|r| r.into_body().read_to_string().ok())
            .is_some_and(|b| b.contains("zakuro-broker"))
    }
    /// A specific-address bind (`127.0.0.1:port`) succeeds on macOS/BSD even
    /// when another socket already listens on the wildcard `*:port`, because
    /// Rust std sets `SO_REUSEADDR` on Unix. The broker binds the wildcard
    /// address (`host: "0.0.0.0"`), so that blind spot would let the agent
    /// pick a port its own broker then fails to bind, crash-looping forever
    /// instead of moving on to the next candidate. A port is free only when
    /// BOTH hold: nothing accepts a loopback connection (catches a
    /// loopback-only holder, e.g. another program on the host listening on
    /// `127.0.0.1:9000` only) AND a wildcard bind of our own would actually
    /// succeed (catches a `*:port` holder, which the loopback check alone
    /// would miss).
    fn port_free(&self, port: u16) -> bool {
        !crate::up::is_port_open(port) && std::net::TcpListener::bind(("0.0.0.0", port)).is_ok()
    }
    fn os_assigned_port(&self) -> Option<u16> {
        std::net::TcpListener::bind(("127.0.0.1", 0))
            .ok()
            .and_then(|l| l.local_addr().ok())
            .map(|a| a.port())
    }
    fn workers(&self) -> Result<Vec<BrokerWorker>, String> {
        #[derive(serde::Deserialize)]
        struct List {
            workers: Vec<BrokerWorker>,
        }
        let resp = Self::http()
            .get(&format!("{}/workers", self.base()))
            .call()
            .map_err(|e| e.to_string())?;
        let status = resp.status().as_u16();
        if !is_success_status(status) {
            return Err(format!("workers: HTTP {status}"));
        }
        let body = resp
            .into_body()
            .read_to_string()
            .map_err(|e| e.to_string())?;
        serde_json::from_str::<List>(&body)
            .map(|l| l.workers)
            .map_err(|e| e.to_string())
    }
    fn drain(&self, id: &str) -> Result<(), String> {
        let resp = Self::http()
            .post(&format!("{}/workers/{id}/drain", self.base()))
            .send_empty()
            .map_err(|e| e.to_string())?;
        match resp.status().as_u16() {
            200 => Ok(()),
            s => Err(format!("drain {id}: HTTP {s}")),
        }
    }
    fn delete(&self, id: &str) -> Result<(), String> {
        let mut req = Self::http().delete(&format!("{}/workers/{id}", self.base()));
        if let Some(k) = &self.worker_key {
            req = req.header("X-Worker-Key", k.as_str());
        }
        let resp = req.call().map_err(|e| e.to_string())?;
        match resp.status().as_u16() {
            200 | 404 => Ok(()),
            s => Err(format!("delete {id}: HTTP {s}")),
        }
    }
}

/// Replace `{port}` and `{name}` in every argument.
pub fn render_argv(template: &[String], port: u16, name: &str) -> Vec<String> {
    template
        .iter()
        .map(|a| {
            a.replace("{port}", &port.to_string())
                .replace("{name}", name)
        })
        .collect()
}

/// Spawn `argv` in its own process group (so a signal to the group reaches
/// python under `uv`), appending stdout+stderr to `log`.
pub fn spawn_in_group(
    argv: &[String],
    cwd: Option<&Path>,
    env: &[(String, String)],
    log: &Path,
) -> std::io::Result<Child> {
    use std::os::unix::fs::OpenOptionsExt;
    use std::os::unix::process::CommandExt;
    let (prog, rest) = argv
        .split_first()
        .ok_or_else(|| std::io::Error::other("empty command"))?;
    if let Some(parent) = log.parent() {
        ensure_dir(parent)?;
    }
    let out = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .mode(0o644)
        .open(log)?;
    let err = out.try_clone()?;
    let mut cmd = Command::new(prog);
    cmd.args(rest)
        .stdin(Stdio::null())
        .stdout(Stdio::from(out))
        .stderr(Stdio::from(err))
        .process_group(0);
    if let Some(d) = cwd {
        cmd.current_dir(d);
    }
    for (k, v) in env {
        cmd.env(k, v);
    }
    cmd.spawn()
}

/// Signal the process group led by `pid` (our children lead their own
/// group). Refuses `pid <= 1`: we must never signal the whole session or PID 1.
pub fn signal_group(pid: u32, sig: libc::c_int) -> bool {
    if pid <= 1 {
        return false;
    }
    unsafe { libc::killpg(pid as libc::pid_t, sig) == 0 }
}

/// A process's state character: Linux `/proc/<pid>/stat` field 3 (`Z` for a
/// zombie), or macOS's `ps -o state=` (also `Z`). `None` when it can't be
/// determined — the process is gone, or we're on neither platform — callers
/// must not read `None` as "zombie", only as "unknown".
fn process_state(pid: u32) -> Option<char> {
    #[cfg(target_os = "linux")]
    {
        let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
        let after = &stat[stat.rfind(')')? + 1..];
        after.split_whitespace().next()?.chars().next()
    }
    #[cfg(target_os = "macos")]
    {
        let out = Command::new("ps")
            .args(["-o", "state=", "-p", &pid.to_string()])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        String::from_utf8_lossy(&out.stdout).trim().chars().next()
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        let _ = pid;
        None
    }
}

/// `(pid, pgid, state)` for every process this OS reports right now. Linux
/// reads `/proc` directly; macOS shells out to `ps`, the only portable way
/// to get pgid and state together. Empty (not necessarily an error) if the
/// listing can't be produced at all, e.g. an unsupported OS.
fn all_processes() -> Vec<(u32, u32, char)> {
    #[cfg(target_os = "linux")]
    {
        let mut out = Vec::new();
        if let Ok(entries) = std::fs::read_dir("/proc") {
            for entry in entries.flatten() {
                let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
                    continue;
                };
                let Ok(pid) = name.parse::<u32>() else {
                    continue;
                };
                let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else {
                    continue;
                };
                let Some(after) = stat.rfind(')').map(|i| &stat[i + 1..]) else {
                    continue;
                };
                let mut fields = after.split_whitespace();
                let Some(state) = fields.next().and_then(|s| s.chars().next()) else {
                    continue;
                };
                // `state` was field 3 (just consumed); field 4 is ppid,
                // field 5 is pgrp — `nth(1)` skips ppid and lands on pgrp.
                let Some(pgrp) = fields.nth(1).and_then(|s| s.parse::<u32>().ok()) else {
                    continue;
                };
                out.push((pid, pgrp, state));
            }
        }
        out
    }
    #[cfg(target_os = "macos")]
    {
        let mut out = Vec::new();
        if let Ok(o) = Command::new("ps")
            .args(["-axo", "pid=,pgid=,state="])
            .output()
        {
            if o.status.success() {
                for line in String::from_utf8_lossy(&o.stdout).lines() {
                    let mut it = line.split_whitespace();
                    let pid = it.next().and_then(|s| s.parse::<u32>().ok());
                    let pgid = it.next().and_then(|s| s.parse::<u32>().ok());
                    let state = it.next().and_then(|s| s.chars().next());
                    if let (Some(pid), Some(pgid), Some(state)) = (pid, pgid, state) {
                        out.push((pid, pgid, state));
                    }
                }
            }
        }
        out
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        Vec::new()
    }
}

/// True while any *non-zombie* process remains in the group led by `pid`
/// (our children lead their own group). A zombie has already exited and
/// holds no resources, runs no code, and answers no requests — only its
/// exit status is unclaimed — so counting one as "alive" just because
/// `killpg(pid, 0)` still finds its pgid makes a drain/kill poll loop
/// (`terminate`, `terminate_all`) wait forever for something that is
/// already gone. That is exactly the no-PID-1-reaper container case (#277):
/// a SIGKILLed group leader is never reaped and stays a zombie forever.
fn group_alive(pid: u32) -> bool {
    if pid <= 1 {
        return false;
    }
    // Nothing bears this pgid at all — cheapest answer, and the usual one
    // once a child has exited and been reaped.
    if unsafe { libc::killpg(pid as libc::pid_t, 0) } != 0 {
        return false;
    }
    // Something is in the group. Almost always that is the leader, still
    // running: one `/proc` read on Linux, one `ps -p` on macOS. Enumerating
    // every process to learn that would cost a full `ps -ax` on each of the
    // agent's 2-second reconcile ticks, for every child, forever.
    match process_state(pid) {
        Some(state) if state != 'Z' => return true,
        None => {
            // The leader is gone but the group is not: fall through and look
            // for a surviving member.
        }
        Some(_) => {
            // The leader is a zombie. Only now is a full listing worth it,
            // to see whether a group member that trapped the signal is still
            // running.
        }
    }
    let procs = all_processes();
    if procs.is_empty() {
        // Couldn't enumerate anything at all (unsupported OS, or /proc and
        // `ps` both unavailable): degrade to the old existence-only probe
        // rather than claim a group is gone when we simply can't tell.
        return true;
    }
    procs
        .iter()
        .any(|&(_, pgrp, state)| pgrp == pid && state != 'Z')
}

/// The process exists and is not a zombie. Zombies count as dead: in a CI
/// container PID 1 may never reap orphaned grandchildren.
pub fn is_alive(pid: u32) -> bool {
    if unsafe { libc::kill(pid as libc::pid_t, 0) } != 0 {
        return false;
    }
    process_state(pid) != Some('Z')
}

#[cfg(target_os = "linux")]
fn linux_start_ticks(pid: u32) -> Option<String> {
    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    // Field 22 (starttime); fields after the ")" that ends comm start at field 3.
    let after = &stat[stat.rfind(')')? + 1..];
    after
        .split_whitespace()
        .nth(19)
        .map(|t| format!("ticks:{t}"))
}

/// A process's start time: with its pid, identifies it across agent restarts
/// (pids are reused). `/proc` on Linux, `ps -o lstart=` elsewhere.
pub fn proc_start_time(pid: u32) -> Option<String> {
    #[cfg(target_os = "linux")]
    {
        if let Some(t) = linux_start_ticks(pid) {
            return Some(t);
        }
    }
    let out = Command::new("ps")
        .args(["-o", "lstart=", "-p", &pid.to_string()])
        .output()
        .ok()?;
    let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (out.status.success() && !s.is_empty()).then_some(s)
}

/// Truncate `path` to empty once it passes `max` bytes. Children write with
/// O_APPEND, so they keep writing at the new end.
pub fn truncate_if_large(path: &Path, max: u64) -> std::io::Result<bool> {
    match std::fs::metadata(path) {
        Ok(m) if m.len() > max => {
            std::fs::OpenOptions::new()
                .write(true)
                .truncate(true)
                .open(path)?;
            Ok(true)
        }
        _ => Ok(false),
    }
}

/// The last `n` lines of `path`. Seeks to the last 64 KiB before reading, so
/// this never pulls a large log file fully into memory.
pub fn tail_lines(path: &Path, n: usize) -> String {
    const CAP: u64 = 64 * 1024;
    let mut f = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(_) => return String::new(),
    };
    let len = f.metadata().map(|m| m.len()).unwrap_or(0);
    let start = len.saturating_sub(CAP);
    if start > 0 && f.seek(SeekFrom::Start(start)).is_err() {
        return String::new();
    }
    let mut buf = Vec::new();
    let _ = f.read_to_end(&mut buf);
    let text = String::from_utf8_lossy(&buf).to_string();
    let lines: Vec<&str> = text.lines().collect();
    lines[lines.len().saturating_sub(n)..].join("\n")
}

/// The slice of the Docker CLI worker supervision needs: run one `docker …`
/// argv, hand back its stdout, or its stderr as an error. Deliberately one
/// method and no semantics of its own -- every argv the supervisor runs is
/// built by `crate::up`'s builders, the same ones `zc share` already uses --
/// so a fake that records argv and answers canned stdout drives every
/// container path in the tests, on a machine with no Docker at all.
pub trait DockerCli: Send + Sync {
    fn run(&self, argv: &[String]) -> Result<String, String>;
}

/// The real one: shells out, exactly like `mesh.rs`'s own `docker` helper.
pub struct DockerShell;

impl DockerCli for DockerShell {
    fn run(&self, argv: &[String]) -> Result<String, String> {
        let (prog, rest) = argv.split_first().ok_or("empty docker command")?;
        let out = Command::new(prog)
            .args(rest)
            .output()
            .map_err(|e| format!("docker not available: {e}"))?;
        if out.status.success() {
            Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
        } else {
            Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
        }
    }
}

/// What an agent's workers actually run as.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WorkerBackend {
    /// The default everyone gets: `uv run … python -m zakuro.worker.server`
    /// in its own process group on this host.
    Host,
    /// Chosen by `ZAKURO_SHARE_RUNTIME` (issues #263, #387): one Docker container per
    /// worker slot, from `image`, so the worker cannot drift with whatever a
    /// `zak-zakuro` checkout resolves to on this Mac.
    Container { image: String },
}

/// How to launch the broker and the workers.
#[derive(Debug, Clone)]
pub struct SpawnSpec {
    /// The broker command line, with `{port}` still a placeholder: it is
    /// rendered at spawn time with whatever port was actually chosen for
    /// this start (see `Supervisor::broker_port`), not a fixed one baked in
    /// up front.
    pub broker_argv: Vec<String>,
    /// Broker environment, minus `ZAKURO_AGENT_CHILD_PORT`: that is added at
    /// spawn time too, for the same reason. So is `ZAKURO_P2P`, from the mesh
    /// route of that start, unless `child_env` already set it here.
    pub broker_env: Vec<(String, String)>,
    pub worker_template: Vec<String>,
    pub worker_env: Vec<(String, String)>,
    pub worker_cwd: Option<PathBuf>,
    /// What a worker runs as. `Host` unless the agent's environment opts into
    /// containers; `worker_template`, `worker_env` and `worker_cwd` are the
    /// host backend's business and are not used by the container one, whose
    /// command line lives in `up::worker_exec_argv` instead.
    pub worker_backend: WorkerBackend,
    /// `ZAKURO_PRICE_PER_HOUR` for a worker, when this agent's environment
    /// sets one. Only the container backend needs it spelled out: a host
    /// worker is a child process and inherits it for free, while a container
    /// inherits nothing, so without this the same setting would price one
    /// backend and silently not the other (see `up::worker_price_env`).
    pub worker_price: Option<String>,
    pub base_worker_port: u16,
    /// The broker port to prefer (spec default 9000, or `ZAKURO_AGENT_PORT`'s
    /// broker counterpart). Tried first on every start; the supervisor falls
    /// back from here when it is held by something else.
    pub preferred_broker_port: u16,
    pub fp8: String,
    /// The agent dir: `broker.log` and `workers/w<i>.log` live here.
    pub log_dir: PathBuf,
    pub kill_grace: Duration,
    pub broker_stop_wait: Duration,
    pub drain_timeout: Duration,
}

impl SpawnSpec {
    /// The broker env matches `zc up -d` (`up.rs:213-236`); `child_env` comes
    /// last so tests can override any of it. The agent itself never calls
    /// `crate::broker::apply_user_broker_defaults()` — that would mutate the
    /// agent's own process environment. The spawned `<zc> broker <port>`
    /// child applies it on its own (`start_broker`, src/main.rs).
    pub fn from_config(cfg: &AgentConfig) -> Self {
        Self::from_config_with(
            cfg,
            &crate::up::docker_cli_available,
            &crate::up::docker_image_present,
        )
    }

    /// [`Self::from_config`] with the Docker and image probes injected, so the
    /// `auto` runtime can be tested without depending on the host's Docker.
    pub(crate) fn from_config_with(
        cfg: &AgentConfig,
        docker_available: &dyn Fn() -> bool,
        image_present: &dyn Fn(&str) -> bool,
    ) -> Self {
        let scan_end = cfg.base_worker_port as u32 + cfg.max_workers + 19;
        let mut broker_env = vec![
            (
                "ZAKURO_SCAN_RANGE".to_string(),
                format!("{}-{scan_end}", cfg.base_worker_port),
            ),
            ("ZAKURO_SCAN_INTERVAL".to_string(), "3".to_string()),
        ];
        broker_env.extend(cfg.child_env.iter().cloned());
        let mut worker_env = vec![
            ("ZAKURO_WORKER_TYPE".to_string(), "zakuro".to_string()),
            ("UV_NO_PROGRESS".to_string(), "1".to_string()),
        ];
        worker_env.extend(cfg.child_env.iter().cloned());
        // Workers inherit the agent's env with `child_env` on top.
        let effective = |k: &str| {
            cfg.child_env
                .iter()
                .rev()
                .find(|(ek, _)| ek == k)
                .map(|(_, v)| v.clone())
                .or_else(|| std::env::var(k).ok())
        };
        if let Some((k, v)) = crate::up::worker_bind_env(&effective) {
            worker_env.push((k.to_string(), v.to_string()));
        }
        // The backend is chosen once, here, from the same effective
        // environment the bind guard reads -- not per spawn, and never from
        // the live process environment inside the supervisor.
        let image = crate::up::worker_container_image(&effective);
        let image_available = || docker_available() && image_present(&image);
        let runtime =
            match crate::up::select_share_runtime(&effective, docker_available, &image_available) {
                Ok(choice) => {
                    if let Some(w) = &choice.warning {
                        eprintln!("zc agent: {w}");
                    }
                    choice.runtime
                }
                // Forced container without Docker: stay on the container
                // backend so `docker_missing` is raised and shown, rather than
                // quietly running host processes the owner opted out of.
                Err(e) if e.starts_with("ZAKURO_SHARE_RUNTIME=container") => {
                    crate::up::ShareRuntime::Container
                }
                Err(e) => {
                    eprintln!("zc agent: {e}; using the host process");
                    crate::up::ShareRuntime::Host
                }
            };
        let worker_backend = if runtime == crate::up::ShareRuntime::Container {
            WorkerBackend::Container {
                image: crate::up::worker_container_image(&effective),
            }
        } else {
            WorkerBackend::Host
        };
        Self {
            broker_argv: cfg.broker_argv.clone(),
            broker_env,
            worker_template: cfg.worker_template.clone(),
            worker_env,
            worker_cwd: None,
            worker_backend,
            worker_price: crate::up::worker_price_env(&effective, None).map(|(_, v)| v),
            base_worker_port: cfg.base_worker_port,
            preferred_broker_port: cfg.broker_port,
            fp8: cfg.node_fp8(),
            log_dir: cfg.dir.clone(),
            kill_grace: cfg.timings.kill_grace,
            broker_stop_wait: cfg.timings.broker_stop_wait,
            drain_timeout: cfg.timings.drain_timeout,
        }
    }
}

/// A host child process; `child` is None for one adopted after an agent restart.
struct HostProc {
    pid: u32,
    started_at: String,
    child: Option<Child>,
}

/// A Docker container running one worker (opt-in, issue #263). `name` is the
/// deterministic container name from `up::worker_container_name` -- the
/// analogue of a pid -- and `started_at` is that container's
/// `.State.StartedAt`, the analogue of the pid start time that keeps adoption
/// after an agent restart from latching onto a different thing with the same
/// identity.
struct ContainerProc {
    name: String,
    started_at: String,
    docker: Arc<dyn DockerCli>,
    /// The last liveness answer and when it was taken; see
    /// [`CONTAINER_LIVENESS_TTL`]. `None` until the first probe, so a worker
    /// that was just spawned (or just adopted) is asked about on the very
    /// next tick rather than assumed well.
    last_alive: Option<(Instant, bool)>,
}

/// How often a container is re-checked while `terminate`/`terminate_all` wait
/// for it: each check is a round trip to the Docker daemon, where the host
/// path's equivalent is a `killpg(pid, 0)`. The host path keeps its own
/// (much tighter) intervals; see `Proc::poll_interval`.
const CONTAINER_POLL: Duration = Duration::from_millis(250);

/// How many log lines a `worker_crashloop` problem's detail carries.
const CRASH_LOG_LINES: usize = 20;

/// How long a container worker's liveness answer is reused before it is
/// probed again. The host path's `try_wait`/`kill(pid, 0)` is a syscall and
/// runs on every 2 s reconcile tick; a container's is a `docker exec`, which
/// on this project's own hardware costs 0.1-0.6 s (measured: 103 ms for a
/// bare `docker inspect`, 589 ms for the `docker exec` probe against
/// `zakuro-image-compute` on an arm64 Mac, where the amd64 image's `sh` is
/// emulated). Probing every worker every tick would leave the reconcile loop
/// shelling out to Docker most of the time it is alive, holding the
/// supervisor lock while it does. Five seconds costs at most that much extra
/// delay in noticing a crash, against a restart backoff that starts at one
/// second and a crash-loop verdict that needs three failures in five minutes:
/// nothing downstream can tell the difference.
const CONTAINER_LIVENESS_TTL: Duration = Duration::from_secs(5);

/// A supervised child, whatever it actually runs as. Both backends answer the
/// same handful of questions -- is it alive, stop it, has it stopped, kill
/// it, what does its log say -- so `observe`, `terminate`, `terminate_all`
/// and `adopt` are written once over this rather than forked per backend.
enum Proc {
    /// The default everyone gets: an OS process leading its own process group.
    Host(HostProc),
    /// A Docker container (`ZAKURO_SHARE_RUNTIME`).
    Container(ContainerProc),
}

impl Proc {
    fn spawned(child: Child) -> Self {
        let pid = child.id();
        Proc::Host(HostProc {
            pid,
            started_at: proc_start_time(pid).unwrap_or_default(),
            child: Some(child),
        })
    }

    /// The pid for a host child; 0 for a container-backed one, which is
    /// identified by name rather than by pid.
    fn pid(&self) -> u32 {
        match self {
            Proc::Host(h) => h.pid,
            Proc::Container(_) => 0,
        }
    }

    /// Is the thing this agent supervises still running? For a container that
    /// is deliberately the *worker process inside it*, not the container:
    /// `zakuro-image-compute` keeps s6-overlay as PID 1 running its own
    /// services, so `.State.Running` stays true long after the worker died.
    ///
    /// `now` is the reconcile tick's clock, and only the container backend
    /// uses it: its answer is cached for [`CONTAINER_LIVENESS_TTL`], because
    /// asking costs a Docker round trip where the host path costs a syscall.
    fn alive(&mut self, now: Instant) -> bool {
        match self {
            Proc::Host(h) => match &mut h.child {
                Some(c) => matches!(c.try_wait(), Ok(None)),
                None => is_alive(h.pid),
            },
            Proc::Container(c) => {
                if let Some((at, answer)) = c.last_alive {
                    if now.saturating_duration_since(at) < CONTAINER_LIVENESS_TTL {
                        return answer;
                    }
                }
                let answer = c.docker.run(&crate::up::worker_alive_argv(&c.name)).is_ok();
                c.last_alive = Some((now, answer));
                answer
            }
        }
    }

    /// `port` is `Some` only for the broker's own record: workers' ports are
    /// already deterministic (`base_worker_port + index`) so they carry `None`.
    fn record(&self, port: Option<u16>) -> ChildRecord {
        match self {
            Proc::Host(h) => ChildRecord {
                pid: h.pid,
                started_at: h.started_at.clone(),
                port,
                container: None,
            },
            Proc::Container(c) => ChildRecord {
                pid: 0,
                started_at: c.started_at.clone(),
                port,
                container: Some(c.name.clone()),
            },
        }
    }

    /// Ask it to stop: SIGTERM to the process group, or to the container's
    /// PID 1.
    fn signal_term(&self) {
        match self {
            Proc::Host(h) => {
                signal_group(h.pid, libc::SIGTERM);
            }
            Proc::Container(c) => {
                let _ = c
                    .docker
                    .run(&crate::up::docker_signal_argv(&c.name, "TERM"));
            }
        }
    }

    /// Has it finished stopping? Reaps our own host leader on the way past,
    /// so an exited-but-unreaped zombie doesn't read as "still alive". For a
    /// container, an inspect that fails at all (it was removed) counts as
    /// gone, but one that cannot be parsed does not -- see
    /// `up::parse_container_state`.
    fn is_gone(&mut self) -> bool {
        match self {
            Proc::Host(h) => {
                if let Some(c) = h.child.as_mut() {
                    let _ = c.try_wait();
                }
                !group_alive(h.pid)
            }
            Proc::Container(c) => match c.docker.run(&crate::up::docker_state_argv(&c.name)) {
                Ok(out) => crate::up::parse_container_state(&out).is_none_or(|s| !s.running),
                Err(_) => true,
            },
        }
    }

    /// Stop being polite about it — only ever called once the grace period
    /// has run out.
    fn force_kill(&self) {
        match self {
            Proc::Host(h) => {
                if group_alive(h.pid) {
                    signal_group(h.pid, libc::SIGKILL);
                }
            }
            Proc::Container(c) => {
                let _ = c
                    .docker
                    .run(&crate::up::docker_signal_argv(&c.name, "KILL"));
            }
        }
    }

    /// Collect the exit status of a child we are the parent of. Nothing to do
    /// for a container: the daemon is its parent, and `--rm` clears it away.
    fn reap(&mut self) {
        if let Proc::Host(h) = self {
            if let Some(c) = h.child.as_mut() {
                let _ = c.wait();
            }
        }
    }

    /// How long to sleep between `is_gone` checks, given the caller's own
    /// interval. The host path keeps exactly the interval it asks for; a
    /// container is never polled faster than [`CONTAINER_POLL`].
    fn poll_interval(&self, base: Duration) -> Duration {
        match self {
            Proc::Host(_) => base,
            Proc::Container(_) => base.max(CONTAINER_POLL),
        }
    }

    /// Whatever outlived the thing we were supervising and would still be
    /// holding this worker's port. For a host worker that is a group member
    /// that outlived its leader (a python child of a crashed `uv`); for a
    /// container it is the container itself, which publishes the port and
    /// goes on doing so after the worker inside it dies.
    fn kill_stragglers(&self) {
        match self {
            Proc::Host(h) => {
                if group_alive(h.pid) {
                    signal_group(h.pid, libc::SIGKILL);
                }
            }
            Proc::Container(c) => {
                let _ = c.docker.run(&crate::up::docker_rm_argv(&c.name));
            }
        }
    }

    /// The log tail to keep for a crash that just happened, when the backend's
    /// log will not outlive the process. `None` for a host worker, whose log
    /// file stays on disk and is therefore read fresh at report time, exactly
    /// as before. `Some` for a container, which `kill_stragglers` is about to
    /// remove along with everything the worker wrote inside it.
    fn captured_log_tail(&self, n: usize) -> Option<String> {
        match self {
            Proc::Host(_) => None,
            Proc::Container(c) => {
                // One extra inspect, on the crash path only (never in the
                // steady state): what the container itself did is half of
                // why a worker is gone, and it is the half a log tail can't
                // tell you. None of these lines carries a word
                // `cli.rs::failure_line` treats as a failure marker, so a
                // real error line further down the tail still wins the
                // one-line summary; when the tail has nothing error-shaped
                // in it, this is what the status screen shows instead of a
                // stray `INFO:` line.
                let headline = match container_state(&c.docker, &c.name) {
                    Some(s) if s.running => format!(
                        "the worker process is gone from container {}, which is still up",
                        c.name
                    ),
                    Some(s) => format!("container {} stopped, exit code {}", c.name, s.exit_code),
                    None => format!("container {} no longer exists", c.name),
                };
                let tail = container_log_tail(&c.docker, &c.name, n);
                Some(format!("{headline}\n{tail}").trim_end().to_string())
            }
        }
    }
}

/// The last `n` lines of a container-backed worker's own output, falling back
/// to the container's log stream when it can no longer be `exec`'d into (it
/// stopped, so the worker's `/tmp/worker.log` is out of reach). Empty when
/// neither answers -- a detail with nothing in it is still better than a
/// supervisor that can't report the crash at all.
fn container_log_tail(docker: &Arc<dyn DockerCli>, name: &str, n: usize) -> String {
    docker
        .run(&crate::up::worker_log_tail_argv(name, n))
        .ok()
        .filter(|s| !s.trim().is_empty())
        .or_else(|| docker.run(&crate::up::docker_logs_argv(name, n)).ok())
        .unwrap_or_default()
}

/// `docker inspect` for one container, parsed. `None` when the container is
/// gone, or the daemon's answer wasn't the three fields we asked for.
fn container_state(docker: &Arc<dyn DockerCli>, name: &str) -> Option<crate::up::ContainerState> {
    let out = docker.run(&crate::up::docker_state_argv(name)).ok()?;
    crate::up::parse_container_state(&out)
}

/// SIGTERM the group, wait up to `grace` for every member to exit, then
/// SIGKILL the group if any member is still around. `killpg(pid, 0)` checks
/// the whole group, not just the leader, so a member that outlives the
/// leader (e.g. a backgrounded grandchild after its parent shell exits) is
/// still caught. While polling we opportunistically reap our own leader
/// (non-blocking) so a leader that already exited doesn't keep reading as
/// "the group is still alive" just because it is an unreaped zombie. Once
/// the group is confirmed gone we never probe or signal that pid again — a
/// freed pgid can be reused by an unrelated process.
///
/// `stop` is checked on every poll: once it is set (the agent is shutting
/// down), this returns `Some(p)` — the group untouched, still only
/// SIGTERMed, never SIGKILLed — instead of running out the rest of `grace`.
/// That keeps a reconcile tick from holding the supervisor lock for the
/// whole grace period while the agent is trying to exit, WITHOUT turning
/// what was meant to be a graceful stop (the broker flushing its WAL, say)
/// into an instant kill: the caller must give `p` back to `self.broker` or
/// its worker slot, so `terminate_all` — which honors its own full
/// SIGTERM/wait/SIGKILL sequence — is the one that finishes it off.
///
/// Returns `None` once the group is actually done, either because every
/// member exited on its own within `grace` or because `grace` ran out and
/// the group was SIGKILLed.
///
/// A container-backed worker takes the identical path with the identical
/// meaning, one layer up: SIGTERM and SIGKILL go to the container's PID 1
/// (`docker kill --signal`), "gone" is `.State.Running` turning false, and
/// the same stop-flag hand-back applies. `docker stop -t N` would have been
/// the obvious call and is not used, because it blocks for the whole grace
/// period inside one uninterruptible command -- exactly what the stop flag
/// exists to avoid.
fn terminate(mut p: Proc, grace: Duration, stop: &AtomicBool) -> Option<Proc> {
    p.signal_term();
    let deadline = Instant::now() + grace;
    let poll = p.poll_interval(Duration::from_millis(50));
    let mut gone = false;
    while Instant::now() < deadline {
        if stop.load(Ordering::Relaxed) {
            return Some(p);
        }
        if p.is_gone() {
            gone = true;
            break;
        }
        std::thread::sleep(poll);
    }
    if !gone {
        p.force_kill();
    }
    p.reap();
    None
}

#[derive(Default)]
struct Slot {
    proc_: Option<Proc>,
    draining_since: Option<Instant>,
    failures: Vec<Instant>,
    consecutive: u32,
    restart_at: Option<Instant>,
    /// When this slot's current process was last (re)confirmed running. Once
    /// a slot has run for `CRASH_STABLE_AFTER` without crashing, its
    /// `consecutive` failure count resets, so a later, unrelated crash starts
    /// back at the 1 s backoff instead of continuing to escalate.
    up_since: Option<Instant>,
    /// The log tail captured the moment this slot's last crash was detected,
    /// for a backend whose log does not outlive the process that wrote it.
    /// `None` for a host worker: its log file stays on disk, so
    /// `worker_crashloop`'s detail is read fresh from it at report time, as
    /// it always has been. `Some` for a container, which is removed (with
    /// everything the worker wrote inside it) as soon as the crash is seen.
    /// It survives the slot's next spawn on purpose (see `spawn_worker`): a
    /// crash loop spends most of its five-minute window running again, and
    /// that is when someone reads it.
    crash_log: Option<String>,
}

pub struct Supervisor {
    spec: SpawnSpec,
    broker: Option<Proc>,
    /// The port this run's broker is on while it's up: `spec.preferred_broker_port`
    /// until an observe tick finds it held by something else and picks a
    /// fallback (see `choose_broker_port`), or a value restored by `adopt`.
    /// While idle this still holds the last-used value, but that's not a
    /// preview of the next port: a fresh start re-probes from
    /// `spec.preferred_broker_port` rather than resuming the fallback.
    broker_port: u16,
    broker_stopping: bool,
    /// The broker's own crash-backoff/crashloop bookkeeping, mirroring a
    /// worker `Slot`'s `failures`/`consecutive`/`restart_at`/`up_since`.
    broker_failures: Vec<Instant>,
    broker_consecutive: u32,
    broker_restart_at: Option<Instant>,
    broker_up_since: Option<Instant>,
    /// Since when the live broker process has failed `/health`, every tick in
    /// a row. See [`BROKER_UNRESPONSIVE_AFTER`].
    broker_unanswered_since: Option<Instant>,
    /// The route the running broker was started on; `None` while no broker
    /// runs. A broker adopted after an agent restart takes the route of the
    /// first tick that sees it.
    broker_route: Option<RouteKind>,
    slots: BTreeMap<u32, Slot>,
    /// The broker's last-known worker list (also the source of each worker's
    /// broker-assigned id, for `DrainWorker`/`KillWorker`'s DELETE). Replaced
    /// only when the tick is fresh (see `workers_fresh`); otherwise it is
    /// left as-is, since an unknown observation — the broker still
    /// `Starting`/`Stopping`, or a failed `GET /workers` — must never read as
    /// "idle" for a draining worker or lose track of its id. It is cleared
    /// (to reflect a real fact, not an unknown) only once the broker is
    /// confirmed `Stopped`, `Unmanaged` or `PortBlocked`.
    last_workers: Vec<BrokerWorker>,
    /// True exactly when this tick's `last_workers` is a fresh observation:
    /// the broker was `Running` and `GET /workers` just succeeded, or the
    /// broker is confirmed gone (so "no workers" is a fact, not a guess).
    /// `false` while `Starting`/`Stopping` or after a failed fetch.
    workers_fresh: bool,
    /// Whether the current `GET /workers` failure streak has already been
    /// logged, so a persistent failure logs once, not every reconcile tick.
    workers_err_streak: bool,
    last_broker: BrokerObs,
    last_drain_timeout: Option<Instant>,
    /// Set from outside the mutex (see `stop_flag`) when the agent is
    /// shutting down. The `terminate` waits an in-flight reconcile tick may
    /// be blocked in (stopping the broker, killing a worker) check this and
    /// return early instead of running out their full grace period, so the
    /// tick releases the supervisor lock quickly and `shutdown_children` can
    /// take over.
    stop: Arc<AtomicBool>,
    /// The mesh route this tick runs on: `Core::reconcile_once` sets it from
    /// `vpn::route()` every tick. A broker start takes its `ZAKURO_P2P` from
    /// it (see `apply`), and on the proxy route its port must be one the
    /// sidecar relays (mesh-routes §5).
    route: RouteKind,
    /// How container-backed workers are reached. The real [`DockerShell`]
    /// unless a test swapped in a fake (see [`Supervisor::set_docker`]);
    /// never used at all on the host backend, which builds no
    /// `Proc::Container`.
    docker: Arc<dyn DockerCli>,
}

fn broker_label(b: BrokerObs) -> &'static str {
    match b {
        BrokerObs::Running => "running",
        BrokerObs::Starting => "starting",
        BrokerObs::Stopping => "stopping",
        BrokerObs::Stopped => "stopped",
        BrokerObs::Unmanaged => "unmanaged",
        BrokerObs::PortBlocked => "error",
    }
}

impl Supervisor {
    pub fn new(spec: SpawnSpec) -> Self {
        let broker_port = spec.preferred_broker_port;
        Self {
            spec,
            broker: None,
            broker_port,
            broker_stopping: false,
            broker_failures: vec![],
            broker_consecutive: 0,
            broker_restart_at: None,
            broker_up_since: None,
            broker_unanswered_since: None,
            broker_route: None,
            slots: BTreeMap::new(),
            last_workers: vec![],
            workers_fresh: true,
            workers_err_streak: false,
            last_broker: BrokerObs::Stopped,
            last_drain_timeout: None,
            stop: Arc::new(AtomicBool::new(false)),
            route: RouteKind::None,
            docker: Arc::new(DockerShell),
        }
    }

    /// Swap in another `DockerCli`: the tests' fake, so every container path
    /// runs in CI without a Docker daemon.
    pub(crate) fn set_docker(&mut self, docker: Arc<dyn DockerCli>) {
        self.docker = docker;
    }

    /// A handle to this supervisor's stop flag, so the owner can request an
    /// early exit from any in-flight `terminate` wait without needing the
    /// supervisor mutex.
    pub fn stop_flag(&self) -> Arc<AtomicBool> {
        self.stop.clone()
    }

    /// The port this run's broker is on while it's up: `spec.preferred_broker_port`
    /// until a fallback is chosen, or a value restored by `adopt`. The caller
    /// builds its `BrokerApi` against this port so `/health`, `GET /workers`,
    /// drain and delete all reach the broker actually running, wherever it
    /// landed. While idle this still reports the last port used, not the
    /// next one: a fresh start re-picks from `spec.preferred_broker_port`
    /// rather than resuming the fallback.
    pub fn broker_port(&self) -> u16 {
        self.broker_port
    }

    /// Update the directory a newly spawned worker's process runs in. Called
    /// once per reconcile tick (a cheap file check upstream resolved it
    /// fresh), so a zakuro dir that appears after the agent started is
    /// picked up by the very next worker spawn, without a restart.
    pub fn set_worker_cwd(&mut self, dir: Option<PathBuf>) {
        self.spec.worker_cwd = dir;
    }

    /// The mesh route for the coming tick (see `Supervisor::route`).
    pub fn set_route(&mut self, route: RouteKind) {
        self.route = route;
    }

    fn worker_name(&self, i: u32) -> String {
        crate::up::worker_name(&self.spec.fp8, i as usize)
    }

    fn worker_log(&self, i: u32) -> PathBuf {
        self.spec
            .log_dir
            .join(WORKER_LOG_DIR)
            .join(format!("w{i}.log"))
    }

    fn broker_log(&self) -> PathBuf {
        self.spec.log_dir.join("broker.log")
    }

    /// Re-attach to recorded children whose pid is alive and whose start time
    /// still matches (spec §6.5 "Agent restart").
    ///
    /// A container-backed worker is re-attached on exactly the same terms,
    /// with the container's name standing in for the pid and its
    /// `.State.StartedAt` for the pid's start time: still running, and still
    /// the same *run*. A container recreated under the same name since the
    /// record was written is a different thing and is left alone, the way a
    /// reused pid is.
    pub fn adopt(&mut self, recorded: &Children, start_time: &dyn Fn(u32) -> Option<String>) {
        let docker = self.docker.clone();
        let adopted = |r: &ChildRecord| -> Option<Proc> {
            match &r.container {
                None => (is_alive(r.pid)
                    && start_time(r.pid).as_deref() == Some(r.started_at.as_str()))
                .then(|| {
                    Proc::Host(HostProc {
                        pid: r.pid,
                        started_at: r.started_at.clone(),
                        child: None,
                    })
                }),
                Some(name) => {
                    let state = container_state(&docker, name)?;
                    (state.running && state.started_at == r.started_at).then(|| {
                        Proc::Container(ContainerProc {
                            name: name.clone(),
                            started_at: state.started_at,
                            docker: docker.clone(),
                            last_alive: None,
                        })
                    })
                }
            }
        };
        if let Some(b) = recorded.broker.as_ref() {
            if let Some(p) = adopted(b) {
                self.broker = Some(p);
                self.broker_port = b.port.unwrap_or(self.spec.preferred_broker_port);
            }
        }
        for (k, r) in &recorded.workers {
            if let (Ok(i), Some(p)) = (k.parse::<u32>(), adopted(r)) {
                self.slots.entry(i).or_default().proc_ = Some(p);
            }
        }
    }

    /// Orphan sweep (issue #388), run once at agent start right after
    /// [`Self::adopt`]: remove every container labelled `zakuro.share=1`
    /// that this supervisor did not just adopt, so a reinstall or a lost
    /// `children.json` cannot leave unsupervised workers running (and
    /// holding their published ports). A container is "known" exactly when
    /// adoption attached it (same name); anything else, including a slot the
    /// agent will manage later, is removed -- spawning would `docker rm -f`
    /// that name first anyway. Containers without the label are never
    /// listed, so never touched. Best effort throughout: no Docker, or a
    /// failed listing, skips the sweep silently; one failed removal is
    /// logged and the rest still go. Returns the names removed.
    pub fn sweep_orphans(&self) -> Vec<String> {
        let listing = match self.docker.run(&crate::up::docker_ps_share_argv()) {
            Ok(o) => o,
            Err(_) => return vec![],
        };
        let known: Vec<&str> = self
            .slots
            .values()
            .filter_map(|s| match s.proc_.as_ref() {
                Some(Proc::Container(c)) => Some(c.name.as_str()),
                _ => None,
            })
            .collect();
        let mut removed = vec![];
        for (id, name) in crate::up::parse_share_ps(&listing) {
            if known.contains(&name.as_str()) {
                continue;
            }
            let short: String = id.chars().take(12).collect();
            match self.docker.run(&crate::up::docker_rm_argv(&id)) {
                Ok(_) => {
                    eprintln!("  [AGENT] removed orphaned share container {name} ({short})");
                    removed.push(name);
                }
                Err(e) => eprintln!(
                    "  [AGENT] could not remove orphaned share container {name} ({short}): {e}"
                ),
            }
        }
        removed
    }

    pub fn children(&self) -> Children {
        let broker_port = self.broker_port;
        Children {
            broker: self.broker.as_ref().map(|p| p.record(Some(broker_port))),
            workers: self
                .slots
                .iter()
                .filter_map(|(i, s)| s.proc_.as_ref().map(|p| (i.to_string(), p.record(None))))
                .collect(),
        }
    }

    pub fn broker_unmanaged(&self) -> bool {
        self.last_broker == BrokerObs::Unmanaged
    }

    /// The broker answered `/health` on the last tick.
    pub fn broker_running(&self) -> bool {
        self.last_broker == BrokerObs::Running
    }

    fn observe(
        &mut self,
        api: &dyn BrokerApi,
        prerequisites_ok: bool,
        sharing: bool,
        now: Instant,
    ) -> Observed {
        let mut broker_alive = self.broker.as_mut().map(|b| b.alive(now));
        let answers = broker_alive == Some(true) && !self.broker_stopping && api.is_broker();
        if broker_alive == Some(true) && !self.broker_stopping && !answers {
            let since = *self.broker_unanswered_since.get_or_insert(now);
            if now.saturating_duration_since(since) >= BROKER_UNRESPONSIVE_AFTER {
                eprintln!(
                    "  [AGENT] the broker has not answered /health for {}s; restarting it",
                    BROKER_UNRESPONSIVE_AFTER.as_secs()
                );
                if let Some(b) = self.broker.take() {
                    // `Some` back: the agent is shutting down, and
                    // `terminate_all` stops it.
                    self.broker = terminate(b, self.spec.broker_stop_wait, &self.stop);
                }
                if self.broker.is_none() {
                    // Handled below as a crash: backoff, then `StartBroker`.
                    broker_alive = Some(false);
                }
            }
        }
        if answers || broker_alive != Some(true) {
            self.broker_unanswered_since = None;
        }
        // A broker adopted after an agent restart was started on a route this
        // run never saw: take the current one instead of restarting it blind.
        if self.broker.is_some() && self.broker_route.is_none() {
            self.broker_route = Some(self.route);
        }
        let broker = match broker_alive {
            Some(true) if self.broker_stopping => BrokerObs::Stopping,
            Some(true) if answers => {
                // Reset the crash-backoff counter once the broker has run
                // stably for a while, mirroring a worker slot (below).
                match self.broker_up_since {
                    None => self.broker_up_since = Some(now),
                    Some(since) if now.saturating_duration_since(since) >= CRASH_STABLE_AFTER => {
                        self.broker_consecutive = 0;
                    }
                    _ => {}
                }
                BrokerObs::Running
            }
            Some(true) => BrokerObs::Starting,
            Some(false) | None => {
                if broker_alive == Some(false) {
                    // The leader is gone. A surviving group member (e.g. a
                    // python child that outlived a crashed `uv`) must not
                    // keep holding the broker port.
                    if let Some(b) = self.broker.as_ref() {
                        b.kill_stragglers();
                    }
                    if !self.broker_stopping {
                        // It died without being asked to: a crash.
                        self.broker_failures.push(now);
                        self.broker_failures
                            .retain(|t| now.saturating_duration_since(*t) <= CRASHLOOP_WINDOW);
                        self.broker_consecutive += 1;
                        self.broker_restart_at =
                            Some(now + plan::restart_backoff(self.broker_consecutive));
                    }
                }
                self.broker = None;
                self.broker_stopping = false;
                self.broker_up_since = None;
                self.broker_route = None;
                // The preferred port (always 9000, regardless of any
                // fallback already chosen) is checked directly: a zakuro
                // broker the agent doesn't own on 9000 is `Unmanaged`
                // whatever fallback port a previous run may have used.
                let preferred = self.spec.preferred_broker_port;
                // Computed here, after any crash just detected above has
                // already updated `broker_restart_at` for this tick: gating
                // the port probe on a stale, pre-crash value wouldn't cause
                // an immediate restart — the plan below recomputes
                // `broker_restart_ready` fresh from the updated
                // `broker_restart_at` (~809), so backoff is still honoured.
                // The only cost of using the stale value here would be one
                // wasted port probe this tick.
                let restart_ready = self.broker_restart_at.is_none_or(|t| now >= t);
                if api.is_broker_at(preferred) {
                    // A connect, not a listen: safe to do on every tick,
                    // whatever `sharing` is, and needed to report
                    // `unmanaged_broker` even while paused.
                    BrokerObs::Unmanaged
                } else if sharing && restart_ready {
                    // Only probed/chosen on a tick that is actually about to
                    // plan `StartBroker` (review N3): `choose_broker_port`'s
                    // `is_free` binds real sockets (`HttpBrokerApi::port_free`,
                    // `os_assigned_port`), and doing that every 2 s while
                    // idle -- sharing off, or the broker still in crash
                    // backoff -- can raise the macOS "accept incoming
                    // connections?" prompt long before sharing is ever
                    // turned on. `apply`'s `Action::StartBroker` arm is the
                    // only place that logs the fallback, so this stays
                    // "once per start" too.
                    // The proxy route relays only the broker range into this
                    // Mac (`vpn::relay_covers`, mesh-routes §3), so any other
                    // port there is one no peer can reach: no preferred port
                    // outside it, and no OS-assigned fallback, on that route.
                    let relayed_only = self.route == RouteKind::Proxy;
                    match choose_broker_port(
                        preferred,
                        BROKER_FALLBACK_START,
                        BROKER_FALLBACK_END,
                        |p| (!relayed_only || crate::vpn::relay_covers(p)) && api.port_free(p),
                        || {
                            if relayed_only {
                                None
                            } else {
                                api.os_assigned_port()
                            }
                        },
                    ) {
                        Some(p) => {
                            self.broker_port = p;
                            BrokerObs::Stopped
                        }
                        None => BrokerObs::PortBlocked,
                    }
                } else {
                    // Idle: nothing is going to start this tick, so nothing
                    // is bound. `broker_port` is left as whatever it was
                    // (the preferred port initially, or wherever the last
                    // real start landed) -- irrelevant until the next tick
                    // that actually probes, which always tries the
                    // preferred port first regardless of this stale value.
                    BrokerObs::Stopped
                }
            }
        };
        self.last_broker = broker;
        match broker {
            BrokerObs::Running => match api.workers() {
                Ok(list) => {
                    if self.workers_err_streak {
                        eprintln!("  [AGENT] GET /workers: recovered");
                        self.workers_err_streak = false;
                    }
                    self.last_workers = list;
                    self.workers_fresh = true;
                }
                Err(e) => {
                    if !self.workers_err_streak {
                        eprintln!("  [AGENT] GET /workers: {e}");
                        self.workers_err_streak = true;
                    }
                    self.workers_fresh = false;
                    // `last_workers` is left as-is: see its doc comment.
                }
            },
            BrokerObs::Stopped | BrokerObs::Unmanaged | BrokerObs::PortBlocked => {
                // The broker is confirmed gone (or not ours): there really
                // are no workers now, which is a fact, not an unknown.
                self.last_workers = vec![];
                self.workers_fresh = true;
                self.workers_err_streak = false;
            }
            BrokerObs::Starting | BrokerObs::Stopping => {
                // The leader is there but `/health` hasn't answered yet (or
                // is flushing on the way down): keep the last good list —
                // see `last_workers`'s doc comment — but this tick is not fresh.
                self.workers_fresh = false;
            }
        }

        let broker_restart_ready = self.broker_restart_at.is_none_or(|t| now >= t);

        // The broker runs on a route that no longer fits it: drain and stop
        // it like a pause; the next tick starts it again on the current
        // route. Two cases: the route's kind changed since this broker
        // started (`route_change_needs_restart`), or it's on the proxy route
        // holding a port the relay doesn't cover (adopted after an agent
        // restart on the host route, with an OS-assigned port).
        let route_restart = self.broker.is_some()
            && (self
                .broker_route
                .is_some_and(|r| plan::route_change_needs_restart(r, self.route))
                || (self.route == RouteKind::Proxy && !crate::vpn::relay_covers(self.broker_port)));

        let fresh = self.workers_fresh;
        let Self {
            slots,
            last_workers,
            spec,
            ..
        } = self;
        let mut workers = Vec::with_capacity(slots.len());
        for (&i, slot) in slots.iter_mut() {
            let running = slot.proc_.as_mut().is_some_and(|p| p.alive(now));
            if !running {
                if let Some(p) = slot.proc_.take() {
                    if slot.draining_since.is_none() {
                        // Read the log BEFORE the cleanup below: a container
                        // is removed along with everything the worker wrote
                        // inside it, so a crash detail read at report time
                        // would come back empty. A host worker's log file
                        // outlives it, and is still read fresh later.
                        slot.crash_log = p.captured_log_tail(CRASH_LOG_LINES);
                    }
                    // The leader is gone. A surviving group member must not
                    // keep holding port `base_worker_port + i` -- nor must
                    // the container that published it.
                    p.kill_stragglers();
                    if slot.draining_since.is_none() {
                        // It died without being asked to: a crash.
                        slot.failures.push(now);
                        slot.failures
                            .retain(|t| now.saturating_duration_since(*t) <= CRASHLOOP_WINDOW);
                        slot.consecutive += 1;
                        slot.restart_at = Some(now + plan::restart_backoff(slot.consecutive));
                        slot.up_since = None;
                    }
                }
            } else {
                // A slot that has run stably for a while drops back to a
                // fresh backoff (see `Slot::up_since`'s doc comment).
                match slot.up_since {
                    None => slot.up_since = Some(now),
                    Some(since) if now.saturating_duration_since(since) >= CRASH_STABLE_AFTER => {
                        slot.consecutive = 0;
                    }
                    _ => {}
                }
            }
            let name = crate::up::worker_name(&spec.fp8, i as usize);
            let seen = last_workers.iter().find(|w| w.name == name);
            // A draining worker on a non-fresh tick must never look idle: it
            // reports at least 1 active request (never 0) until a fresh
            // observation says otherwise, or its drain has expired.
            let active_requests = if slot.draining_since.is_some() && !fresh {
                seen.map_or(1, |w| w.active_requests.max(1))
            } else {
                seen.map_or(0, |w| w.active_requests)
            };
            workers.push(WorkerObs {
                index: i,
                running,
                draining: slot.draining_since.is_some(),
                active_requests,
                drain_expired: slot
                    .draining_since
                    .is_some_and(|t| now.saturating_duration_since(t) >= spec.drain_timeout),
                restart_ready: slot.restart_at.is_none_or(|t| now >= t),
            });
        }
        Observed {
            broker,
            workers,
            prerequisites_ok,
            broker_restart_ready,
            route_restart,
        }
    }

    fn spawn_worker(&mut self, i: u32, now: Instant) -> Result<(), String> {
        let port = self.spec.base_worker_port + i as u16;
        let name = self.worker_name(i);
        let proc_ = match self.spec.worker_backend.clone() {
            WorkerBackend::Host => {
                let argv = render_argv(&self.spec.worker_template, port, &name);
                let mut env = self.spec.worker_env.clone();
                env.push(("ZAKURO_AGENT_CHILD_PORT".to_string(), port.to_string()));
                env.push(("ZAKURO_AGENT_CHILD_NAME".to_string(), name));
                let child = spawn_in_group(
                    &argv,
                    self.spec.worker_cwd.as_deref(),
                    &env,
                    &self.worker_log(i),
                )
                .map_err(|e| e.to_string())?;
                Proc::spawned(child)
            }
            WorkerBackend::Container { image } => {
                self.spawn_container_worker(port, &name, &image)?
            }
        };
        let slot = self.slots.entry(i).or_default();
        slot.proc_ = Some(proc_);
        slot.draining_since = None;
        slot.up_since = Some(now);
        // `crash_log` is deliberately NOT cleared here. A crash loop is
        // reported for as long as three failures sit inside the five-minute
        // window, and most of that window is time the slot spends running
        // again -- which is exactly when someone reads the status screen. A
        // host worker answers there from a log file that outlived its
        // crashes; a container-backed one has only this snapshot, so
        // clearing it at the next spawn left a flapping worker with nothing
        // to say for itself. The next crash overwrites it, and `problems`
        // only ever reads it while `is_crashloop` (which windows the failure
        // list itself) is true, so it can never outlive the crashes it
        // describes.
        Ok(())
    }

    /// Start one worker as a Docker container, from the very argv `zc share`
    /// already uses (`up::docker_run_argv` + `up::worker_exec_argv`), so the
    /// agent and the foreground command cannot drift apart in what they run.
    ///
    /// The `docker rm -f` first is what makes a restart idempotent: the
    /// container name is deterministic, so a leftover from a crash the agent
    /// never got to clean up (an agent SIGKILLed mid-run, a host that lost
    /// power) would otherwise win the name AND go on publishing
    /// `base_worker_port + i`, and every restart from here on would fail.
    fn spawn_container_worker(&self, port: u16, name: &str, image: &str) -> Result<Proc, String> {
        let docker = self.docker.clone();
        let container = crate::up::worker_container_name(name);
        let network = crate::up::worker_network_name(name);
        let _ = docker.run(&crate::up::docker_rm_argv(&container));
        // Idempotent; a real Docker problem surfaces from the run below,
        // which needs this network to exist.
        let _ = docker.run(&crate::up::docker_network_create_argv(&network));
        docker.run(&crate::up::docker_run_argv(
            port, image, &container, &network, name,
        ))?;
        if let Err(e) = docker.run(&crate::up::worker_exec_argv(
            &container,
            port,
            name,
            self.spec.worker_price.as_deref(),
        )) {
            // Never leave a container running with no worker in it: it would
            // look alive to `docker ps` and hold the port for nothing.
            let _ = docker.run(&crate::up::docker_rm_argv(&container));
            return Err(e);
        }
        // The start time is read back rather than taken as "now": it is what
        // a later `adopt` compares against, so it has to be the daemon's own
        // value, byte for byte.
        let started_at = container_state(&docker, &container)
            .map(|s| s.started_at)
            .unwrap_or_default();
        Ok(Proc::Container(ContainerProc {
            name: container,
            started_at,
            docker,
            last_alive: None,
        }))
    }

    /// The broker's id for slot `i`, from the last *good* `GET /workers`
    /// observation (see `last_workers`'s doc comment).
    fn broker_id(&self, i: u32) -> Option<String> {
        let name = self.worker_name(i);
        self.last_workers
            .iter()
            .find(|w| w.name == name)
            .map(|w| w.id.clone())
    }

    fn apply(
        &mut self,
        actions: &[Action],
        observed: &Observed,
        api: &dyn BrokerApi,
        now: Instant,
    ) {
        for action in actions {
            match *action {
                Action::StartBroker => {
                    // Logged here, not where the port is chosen (`observe`):
                    // this is the one place that actually starts something,
                    // so the line prints exactly once per start, never on a
                    // tick where sharing is off or the broker is still in
                    // crash backoff.
                    if self.broker_port != self.spec.preferred_broker_port {
                        let preferred = self.spec.preferred_broker_port;
                        let why = if self.route == RouteKind::Proxy
                            && !crate::vpn::relay_covers(preferred)
                        {
                            "isn't a port the mesh relay carries"
                        } else {
                            "is held by another program"
                        };
                        eprintln!(
                            "  [AGENT] broker: 127.0.0.1:{preferred} {why}; starting the broker on 127.0.0.1:{}",
                            self.broker_port
                        );
                    }
                    let log = self.broker_log();
                    let argv = render_argv(&self.spec.broker_argv, self.broker_port, "");
                    let mut env = self.spec.broker_env.clone();
                    env.push((
                        "ZAKURO_AGENT_CHILD_PORT".to_string(),
                        self.broker_port.to_string(),
                    ));
                    // P2P follows the mesh route this start runs on, not the
                    // one the agent launched on: either route peers, no route
                    // doesn't. An explicit `ZAKURO_P2P` (`child_env`) wins.
                    if !env.iter().any(|(k, _)| k == "ZAKURO_P2P") {
                        env.push((
                            "ZAKURO_P2P".to_string(),
                            (self.route != RouteKind::None).to_string(),
                        ));
                    }
                    match spawn_in_group(&argv, None, &env, &log) {
                        Ok(c) => {
                            self.broker = Some(Proc::spawned(c));
                            self.broker_up_since = Some(now);
                            self.broker_route = Some(self.route);
                        }
                        Err(e) => eprintln!("  [AGENT] could not start the broker: {e}"),
                    }
                }
                Action::StopBroker => {
                    if let Some(b) = self.broker.take() {
                        if observed.route_restart {
                            eprintln!(
                                "  [AGENT] mesh route changed ({} → {}); restarting the broker",
                                self.broker_route.map_or("?", RouteKind::label),
                                self.route.label()
                            );
                        }
                        self.broker_stopping = true;
                        // `Some(b)` back means shutdown interrupted the wait:
                        // give the broker back so `terminate_all` finishes
                        // stopping it with its own full grace period, rather
                        // than this tick cutting the stop short.
                        let leftover = terminate(b, self.spec.broker_stop_wait, &self.stop);
                        self.broker_stopping = false;
                        self.broker_up_since = None;
                        self.broker = leftover;
                        if self.broker.is_none() {
                            self.broker_route = None;
                        }
                    }
                }
                Action::StartWorker(i) | Action::RestartWorker(i) => {
                    if let Err(e) = self.spawn_worker(i, now) {
                        eprintln!("  [AGENT] could not start worker {i}: {e}");
                    }
                }
                Action::DrainWorker(i) => {
                    if let Some(id) = self.broker_id(i) {
                        if let Err(e) = api.drain(&id) {
                            eprintln!("  [AGENT] drain {id}: {e}");
                        }
                    }
                    self.slots.entry(i).or_default().draining_since = Some(now);
                }
                Action::KillWorker(i) => {
                    if observed
                        .workers
                        .iter()
                        .any(|w| w.index == i && w.drain_expired && w.active_requests > 0)
                    {
                        self.last_drain_timeout = Some(now);
                    }
                    if let Some(mut slot) = self.slots.remove(&i) {
                        if let Some(p) = slot.proc_.take() {
                            if let Some(p) = terminate(p, self.spec.kill_grace, &self.stop) {
                                // Shutdown interrupted the kill: give the
                                // slot back so `terminate_all` handles it
                                // with its own grace period, instead of
                                // deleting it from the broker and
                                // forgetting it below as if it were already
                                // gone.
                                slot.proc_ = Some(p);
                                self.slots.insert(i, slot);
                                continue;
                            }
                        }
                    }
                    if let Some(id) = self.broker_id(i) {
                        if let Err(e) = api.delete(&id) {
                            eprintln!("  [AGENT] delete {id}: {e}");
                        }
                    }
                    // Forget this worker's entry in the retained list too:
                    // otherwise a later StartWorker(i) during a `GET
                    // /workers` error streak would inherit the dead worker's
                    // stale stats and id by name.
                    let name = self.worker_name(i);
                    self.last_workers.retain(|w| w.name != name);
                }
            }
        }
    }

    /// A slot's first `POST /workers/{id}/drain` can miss: the worker hadn't
    /// registered yet (no id to send), the POST failed, or the broker
    /// restarted and re-registered it as healthy. While a fresh observation
    /// shows the broker not treating a draining slot as `draining`, send the
    /// drain again, so the broker stops routing jobs to a worker the agent is
    /// about to stop. Slots this tick kills are skipped, and a tick that
    /// didn't just read `GET /workers` sends nothing: its list is stale.
    fn resend_drains(&self, api: &dyn BrokerApi, actions: &[Action]) {
        if !self.workers_fresh || self.last_broker != BrokerObs::Running {
            return;
        }
        for (&i, slot) in &self.slots {
            if slot.draining_since.is_none() || actions.contains(&Action::KillWorker(i)) {
                continue;
            }
            let name = self.worker_name(i);
            let Some(w) = self.last_workers.iter().find(|w| w.name == name) else {
                continue;
            };
            if w.status != "draining" {
                if let Err(e) = api.drain(&w.id) {
                    eprintln!("  [AGENT] drain {} (again): {e}", w.id);
                }
            }
        }
    }

    /// One reconcile tick: observe, decide (`plan_actions`), act.
    pub fn reconcile(
        &mut self,
        desired: &Desired,
        api: &dyn BrokerApi,
        prerequisites_ok: bool,
        now: Instant,
    ) -> Vec<Action> {
        let observed = self.observe(api, prerequisites_ok, desired.sharing, now);
        let actions = plan::plan_actions(desired, &observed);
        self.resend_drains(api, &actions);
        self.apply(&actions, &observed, api, now);
        let logs: Vec<PathBuf> = self.slots.keys().map(|&i| self.worker_log(i)).collect();
        for log in logs {
            let _ = truncate_if_large(&log, WORKER_LOG_MAX_BYTES);
        }
        let _ = truncate_if_large(&self.broker_log(), WORKER_LOG_MAX_BYTES);
        actions
    }

    pub fn problems(&self, now: Instant) -> Vec<Problem> {
        let mut out = Vec::new();
        match self.last_broker {
            BrokerObs::Unmanaged => out.push(Problem::new("unmanaged_broker")),
            // On the proxy route only the relayed ports were candidates.
            BrokerObs::PortBlocked if self.route == RouteKind::Proxy => {
                out.push(Problem::new("broker_port_unrelayable"))
            }
            BrokerObs::PortBlocked => out.push(Problem::new("port_in_use")),
            _ => {}
        }
        if plan::is_crashloop(&self.broker_failures, now) {
            let log = self.broker_log();
            let mut p = Problem::new("broker_crashloop");
            if log.exists() {
                p = p.with_detail(tail_lines(&log, 20));
            }
            out.push(p);
        }
        for (&i, slot) in &self.slots {
            if plan::is_crashloop(&slot.failures, now) {
                // A host worker's log file is still on disk, so it is read
                // fresh here, exactly as before; a container-backed one is
                // read from the snapshot taken when the crash was detected,
                // because the container it lived in is gone by now.
                let detail = slot
                    .crash_log
                    .clone()
                    .unwrap_or_else(|| tail_lines(&self.worker_log(i), CRASH_LOG_LINES));
                out.push(Problem::new("worker_crashloop").with_detail(detail));
            }
        }
        if self
            .last_drain_timeout
            .is_some_and(|t| now.saturating_duration_since(t) < DRAIN_TIMEOUT_SHOWN_FOR)
        {
            out.push(Problem::new("drain_timeout"));
        }
        out
    }

    /// This node's own workers as the broker last listed them, or `None`
    /// when this tick's observation is not fresh (see `workers_fresh`): the
    /// jobs journal must not read "unknown" as "idle".
    pub fn observed_workers(&self) -> Option<Vec<BrokerWorker>> {
        if !self.workers_fresh {
            return None;
        }
        let names: HashSet<String> = self.slots.keys().map(|&i| self.worker_name(i)).collect();
        Some(
            self.last_workers
                .iter()
                .filter(|w| names.contains(&w.name))
                .cloned()
                .collect(),
        )
    }

    pub fn local_view(&self, desired: &Desired, max: u32) -> LocalView {
        let names: HashSet<String> = self.slots.keys().map(|&i| self.worker_name(i)).collect();
        let mine: Vec<&BrokerWorker> = self
            .last_workers
            .iter()
            .filter(|w| names.contains(&w.name))
            .collect();
        let count = |f: &dyn Fn(&Slot) -> bool| self.slots.values().filter(|s| f(s)).count() as u32;
        LocalView {
            sharing: desired.sharing,
            broker: broker_label(self.last_broker).to_string(),
            workers: WorkerCounts {
                desired: desired.workers,
                running: count(&|s| s.proc_.is_some() && s.draining_since.is_none()),
                busy: mine.iter().filter(|w| w.active_requests > 0).count() as u32,
                draining: count(&|s| s.proc_.is_some() && s.draining_since.is_some()),
                max,
            },
            requests: Requests {
                last_5h: mine.iter().map(|w| w.requests_5h).sum(),
                last_1w: mine.iter().map(|w| w.requests_1w).sum(),
            },
        }
    }

    /// Agent SIGTERM (spec §6.5): SIGTERM every child group, wait up to `wait`,
    /// SIGKILL what is left. No drain. There is no `Drop` equivalent of this:
    /// a `Supervisor` that is merely dropped (e.g. across an agent restart)
    /// must leave its children running so they can later be `adopt`ed.
    pub fn terminate_all(&mut self, wait: Duration) {
        let mut procs: Vec<Proc> = self
            .slots
            .values_mut()
            .filter_map(|s| s.proc_.take())
            .collect();
        procs.extend(self.broker.take());
        for p in &procs {
            p.signal_term();
        }
        // Once a group is confirmed gone we stop probing (and would never
        // signal) that pid again: a freed pgid can be reused by an unrelated
        // process while another group in this same call is still exiting.
        let mut gone = vec![false; procs.len()];
        // One interval for the whole batch: the host path's own 100 ms
        // unless a container is in it, which must not be inspected that
        // often (see `Proc::poll_interval`).
        let poll = procs
            .iter()
            .map(|p| p.poll_interval(Duration::from_millis(100)))
            .max()
            .unwrap_or(Duration::from_millis(100));
        let deadline = Instant::now() + wait;
        while Instant::now() < deadline && gone.iter().any(|g| !g) {
            for (p, g) in procs.iter_mut().zip(gone.iter_mut()) {
                if *g {
                    continue;
                }
                if p.is_gone() {
                    *g = true;
                }
            }
            if gone.iter().any(|g| !g) {
                std::thread::sleep(poll);
            }
        }
        for (p, g) in procs.iter_mut().zip(gone.iter_mut()) {
            if !*g {
                p.force_kill();
            }
            p.reap();
        }
        self.slots.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::files::tests::tmp;
    use std::cell::{Cell, RefCell};
    use std::ops::{Deref, DerefMut};

    #[derive(Default)]
    struct FakeBroker {
        up: Cell<bool>,
        /// Overrides `is_broker()` independently of `up`, to simulate a
        /// `/health` timeout while the broker's process stays as `up` says.
        health_override: Cell<Option<bool>>,
        workers: RefCell<Vec<BrokerWorker>>,
        /// When set, `workers()` returns `Err` instead of the list below,
        /// simulating a `GET /workers` timeout or a non-2xx response.
        workers_err: Cell<bool>,
        /// When set, `drain()` records the attempt but answers `Err`, as a
        /// broker that times out or rejects the POST would.
        drain_fails: Cell<bool>,
        drained: RefCell<Vec<String>>,
        deleted: RefCell<Vec<String>>,
        /// When set, `is_broker_at(p)` is true only for this port: simulates
        /// a foreign zakuro broker holding the preferred port.
        foreign_broker_port: Cell<Option<u16>>,
        /// Ports considered occupied (by anything) for the fallback-port
        /// search; empty by default, so `port_free` says yes to everything
        /// and the very first `StartBroker` always lands on the preferred
        /// port, matching every test that doesn't care about fallback.
        blocked_ports: RefCell<std::collections::HashSet<u16>>,
        /// `os_assigned_port()`'s canned answer.
        os_pick: Cell<Option<u16>>,
        /// How many times `port_free`/`os_assigned_port` were called: the
        /// real implementations do socket I/O (a wildcard bind), so a test
        /// asserting an idle tick never probes counts these instead of
        /// mocking a real listener (review N3).
        port_free_calls: RefCell<u32>,
        os_assigned_port_calls: RefCell<u32>,
    }
    impl BrokerApi for FakeBroker {
        fn is_broker(&self) -> bool {
            self.health_override.get().unwrap_or_else(|| self.up.get())
        }
        fn is_broker_at(&self, port: u16) -> bool {
            self.foreign_broker_port.get() == Some(port)
        }
        fn port_free(&self, port: u16) -> bool {
            *self.port_free_calls.borrow_mut() += 1;
            !self.blocked_ports.borrow().contains(&port)
        }
        fn os_assigned_port(&self) -> Option<u16> {
            *self.os_assigned_port_calls.borrow_mut() += 1;
            self.os_pick.get()
        }
        fn workers(&self) -> Result<Vec<BrokerWorker>, String> {
            if self.workers_err.get() {
                return Err("simulated GET /workers failure".into());
            }
            Ok(self.workers.borrow().clone())
        }
        fn drain(&self, id: &str) -> Result<(), String> {
            self.drained.borrow_mut().push(id.into());
            if self.drain_fails.get() {
                return Err("simulated POST /drain failure".into());
            }
            Ok(())
        }
        fn delete(&self, id: &str) -> Result<(), String> {
            self.deleted.borrow_mut().push(id.into());
            Ok(())
        }
    }

    fn sh(script: &str) -> Vec<String> {
        vec!["sh".into(), "-c".into(), script.into()]
    }

    fn spec(dir: &Path, worker: Vec<String>) -> SpawnSpec {
        SpawnSpec {
            broker_argv: sh("exec sleep 60"),
            broker_env: vec![],
            worker_template: worker,
            worker_env: vec![],
            worker_cwd: None,
            worker_backend: WorkerBackend::Host,
            worker_price: None,
            base_worker_port: 3960,
            preferred_broker_port: 9000,
            fp8: "testfp00".into(),
            log_dir: dir.to_path_buf(),
            kill_grace: Duration::from_secs(2),
            broker_stop_wait: Duration::from_secs(2),
            drain_timeout: Duration::from_secs(300),
        }
    }

    fn bw_n(id: &str, name: &str, active_requests: u32) -> BrokerWorker {
        BrokerWorker {
            id: id.into(),
            name: name.into(),
            status: "healthy".into(),
            active_requests,
            requests_5h: 1,
            requests_1w: 2,
        }
    }

    fn bw(id: &str, name: &str) -> BrokerWorker {
        bw_n(id, name, 0)
    }

    /// Polls (for up to 5 s) until `pred()` is true. Used instead of a fixed
    /// sleep so CI load can't turn a slow process exit into a flaky test.
    fn wait_until(mut pred: impl FnMut() -> bool) -> bool {
        for _ in 0..100 {
            if pred() {
                return true;
            }
            std::thread::sleep(Duration::from_millis(50));
        }
        pred()
    }

    /// Polls (up to 5 s) until the supervisor's own bookkeeping has reaped
    /// worker slot `i`'s process and sees it as no longer running. A raw
    /// `kill(pid, 0)` (as `is_alive` uses) can't tell an exited-but-unreaped
    /// zombie from a live process on macOS, but `Proc::alive`'s `try_wait`
    /// can, since it is the process's real parent.
    fn wait_until_worker_exited(sup: &mut Supervisor, i: u32) -> bool {
        wait_until(|| {
            sup.slots
                .get_mut(&i)
                .and_then(|s| s.proc_.as_mut())
                .map(|p| !p.alive(Instant::now()))
                .unwrap_or(true)
        })
    }

    /// As `wait_until_worker_exited`, for the broker.
    fn wait_until_broker_exited(sup: &mut Supervisor) -> bool {
        wait_until(|| {
            sup.broker
                .as_mut()
                .map(|p| !p.alive(Instant::now()))
                .unwrap_or(true)
        })
    }

    /// Every test that spawns a real process group must reap or kill it, even
    /// on assertion failure, so the suite leaves no orphans (see task rules).
    /// Killing an already-terminated group is a harmless no-op.
    struct PgGuard(u32);
    impl Drop for PgGuard {
        fn drop(&mut self) {
            signal_group(self.0, libc::SIGKILL);
        }
    }

    /// Kills and reaps a raw, ungrouped-through-`Supervisor` `Child` on drop,
    /// even on panic.
    struct ChildGuard(Child);
    impl ChildGuard {
        fn id(&self) -> u32 {
            self.0.id()
        }
    }
    impl Drop for ChildGuard {
        fn drop(&mut self) {
            let pid = self.0.id();
            let leader_reaped = matches!(self.0.try_wait(), Ok(Some(_)));
            // Skip the SIGKILL only once BOTH the leader is already reaped
            // (the success path's own cleanup got there first) AND the
            // whole group is gone: a reaped leader can still have a live
            // group member (e.g. a backgrounded grandchild), and a freed
            // pgid can be reused by an unrelated process once truly empty.
            if leader_reaped && !group_alive(pid) {
                return;
            }
            signal_group(pid, libc::SIGKILL);
            let _ = self.0.wait();
        }
    }

    /// Kills and reaps a bare `Proc` on drop, even on panic. `terminate`
    /// already leaves the process dead in the success path; this is a
    /// backstop for when an assertion fails first.
    struct ProcGuard(Proc);
    impl ProcGuard {
        /// Hand the guarded `Proc` to something that will finish handling it
        /// (like `terminate`, which now takes it by value), without this
        /// guard's `Drop` racing that handoff. Anything that panics before
        /// this is called is still covered by the guard as usual.
        fn into_inner(self) -> Proc {
            let this = std::mem::ManuallyDrop::new(self);
            unsafe { std::ptr::read(&this.0) }
        }
    }
    impl Drop for ProcGuard {
        fn drop(&mut self) {
            // See `ChildGuard::drop`: a reaped leader can still have a live
            // group member, so only skip once the whole group is gone too --
            // which is exactly what `is_gone` answers (it reaps our own
            // leader on the way past).
            if self.0.is_gone() {
                return;
            }
            self.0.force_kill();
            self.0.reap();
        }
    }

    /// Kills and reaps a pid we no longer hold a `Child`/`Proc` handle for
    /// (e.g. after the `Supervisor` that owned it has already been dropped).
    struct PidReapGuard(u32);
    impl Drop for PidReapGuard {
        fn drop(&mut self) {
            signal_group(self.0, libc::SIGKILL);
            unsafe {
                libc::waitpid(self.0 as libc::pid_t, std::ptr::null_mut(), 0);
            }
        }
    }

    /// A `Supervisor` is not itself kill-on-drop (spec §6.5: children must
    /// survive an agent restart so they can be `adopt`ed, and the broker
    /// needs its full `broker_stop_wait` to flush). Every test uses this
    /// guard instead, so a test that spawns real children still cleans them
    /// up even when an assertion fails first.
    struct SupGuard(Supervisor);
    impl Deref for SupGuard {
        type Target = Supervisor;
        fn deref(&self) -> &Supervisor {
            &self.0
        }
    }
    impl DerefMut for SupGuard {
        fn deref_mut(&mut self) -> &mut Supervisor {
            &mut self.0
        }
    }
    impl Drop for SupGuard {
        fn drop(&mut self) {
            self.0.terminate_all(Duration::from_secs(2));
        }
    }

    #[test]
    fn dropping_a_plain_supervisor_leaves_its_child_running() {
        let dir = tmp("plain-drop");
        let pid = {
            let mut sup = Supervisor::new(spec(&dir, sh("exec sleep 60")));
            sup.spawn_worker(0, Instant::now()).unwrap();
            sup.children().workers["0"].pid
        }; // a plain (unguarded) Supervisor drops here
        let _reap = PidReapGuard(pid); // clean up regardless of the assertion below
        assert!(
            is_alive(pid),
            "a plain Supervisor must not kill its children on drop"
        );
    }

    #[test]
    fn reconcile_starts_scales_drains_and_pauses_real_processes() {
        use Action::*;
        let dir = tmp("sup");
        let api = FakeBroker::default();
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let t = Instant::now();
        let on2 = Desired {
            sharing: true,
            workers: 2,
        };

        assert_eq!(sup.reconcile(&on2, &api, true, t), vec![StartBroker]);
        api.up.set(true); // the broker now answers /health
        assert_eq!(
            sup.reconcile(&on2, &api, true, t),
            vec![StartWorker(0), StartWorker(1)]
        );
        *api.workers.borrow_mut() = vec![bw("id0", "testfp00-w0"), bw("id1", "testfp00-w1")];
        assert_eq!(sup.reconcile(&on2, &api, true, t), vec![]);
        let view = sup.local_view(&on2, 5);
        assert_eq!(
            (
                view.workers.running,
                view.workers.desired,
                view.broker.as_str()
            ),
            (2, 2, "running")
        );
        assert_eq!(
            view.requests,
            Requests {
                last_5h: 2,
                last_1w: 4
            }
        );
        assert_eq!(sup.children().workers.len(), 2);
        assert!(sup.children().broker.is_some());

        let on1 = Desired {
            sharing: true,
            workers: 1,
        };
        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![DrainWorker(1)]);
        assert_eq!(*api.drained.borrow(), vec!["id1".to_string()]);
        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![KillWorker(1)]);
        assert_eq!(*api.deleted.borrow(), vec!["id1".to_string()]);
        assert_eq!(
            sup.children().workers.keys().cloned().collect::<Vec<_>>(),
            vec!["0".to_string()]
        );

        let off = Desired {
            sharing: false,
            workers: 1,
        };
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![DrainWorker(0)]);
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![KillWorker(0)]);
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![StopBroker]);
        assert!(sup.children().broker.is_none());
        assert!(sup.children().workers.is_empty());
    }

    #[test]
    fn a_crashing_worker_backs_off_and_is_flagged_as_a_crashloop() {
        use Action::*;
        let dir = tmp("crash");
        let api = FakeBroker::default();
        api.up.set(true);
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("echo boom; exit 1"))));
        let t = Instant::now();
        let at = |ms: u64| t + Duration::from_millis(ms);
        let on1 = Desired {
            sharing: true,
            workers: 1,
        };
        // Adopt a fake running broker so the plan goes straight to workers.
        let broker_child =
            spawn_in_group(&sh("exec sleep 60"), None, &[], &dir.join("b.log")).unwrap();
        let _guard = PgGuard(broker_child.id()); // belt-and-braces: terminate_all reaps it below
        sup.broker = Some(Proc::spawned(broker_child));

        assert_eq!(sup.reconcile(&on1, &api, true, at(0)), vec![StartWorker(0)]);
        assert!(
            wait_until_worker_exited(&mut sup, 0),
            "worker slot 0 did not exit in time"
        );
        assert_eq!(
            sup.reconcile(&on1, &api, true, at(100)),
            vec![],
            "1st failure: 1 s backoff"
        );
        assert_eq!(
            sup.reconcile(&on1, &api, true, at(1200)),
            vec![RestartWorker(0)]
        );
        assert!(
            wait_until_worker_exited(&mut sup, 0),
            "worker slot 0 did not exit in time"
        );
        assert_eq!(
            sup.reconcile(&on1, &api, true, at(1300)),
            vec![],
            "2nd failure: 2 s backoff"
        );
        assert_eq!(
            sup.reconcile(&on1, &api, true, at(3400)),
            vec![RestartWorker(0)]
        );
        assert!(
            wait_until_worker_exited(&mut sup, 0),
            "worker slot 0 did not exit in time"
        );
        sup.reconcile(&on1, &api, true, at(3500));

        let problems = sup.problems(at(3500));
        let crash = problems
            .iter()
            .find(|p| p.code == "worker_crashloop")
            .expect("3 failures in 5 min");
        assert!(
            crash.detail.as_deref().unwrap_or("").contains("boom"),
            "detail carries the log tail"
        );
    }

    #[test]
    fn a_crashing_worker_that_stabilizes_resets_its_backoff() {
        use Action::*;
        let dir = tmp("worker-stable-reset");
        let api = FakeBroker::default();
        api.up.set(true);
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let t = Instant::now();
        let at = |ms: u64| t + Duration::from_millis(ms);
        let on1 = Desired {
            sharing: true,
            workers: 1,
        };
        // Adopt a fake running broker so the plan goes straight to workers.
        let broker_child =
            spawn_in_group(&sh("exec sleep 60"), None, &[], &dir.join("b.log")).unwrap();
        let _guard = PgGuard(broker_child.id());
        sup.broker = Some(Proc::spawned(broker_child));

        // 1. Crash a child once.
        assert_eq!(sup.reconcile(&on1, &api, true, at(0)), vec![StartWorker(0)]);
        let pid0 = sup.children().workers["0"].pid;
        signal_group(pid0, libc::SIGKILL);
        assert!(
            wait_until_worker_exited(&mut sup, 0),
            "worker slot 0 did not exit in time"
        );
        assert_eq!(
            sup.reconcile(&on1, &api, true, at(100)),
            vec![],
            "1st failure: 1 s backoff"
        );

        // 2. Let it restart.
        assert_eq!(
            sup.reconcile(&on1, &api, true, at(1200)),
            vec![RestartWorker(0)]
        );

        // 3. Tick at +301 s while it's alive: this crosses CRASH_STABLE_AFTER
        // and resets `consecutive` back to 0.
        assert_eq!(sup.reconcile(&on1, &api, true, at(1200 + 301_000)), vec![]);

        // 4. SIGKILL the pid from `sup.children()`: a second, independent crash.
        let pid1 = sup.children().workers["0"].pid;
        signal_group(pid1, libc::SIGKILL);
        assert!(
            wait_until_worker_exited(&mut sup, 0),
            "worker slot 0 did not exit in time"
        );
        let t2 = at(1200 + 301_000 + 100);
        assert_eq!(
            sup.reconcile(&on1, &api, true, t2),
            vec![],
            "post-reset failure: backoff restarts at 1 s"
        );

        // 5. The next restart backoff must be 1 s, not 2 s.
        assert_eq!(
            sup.reconcile(&on1, &api, true, t2 + Duration::from_millis(900)),
            vec![],
            "not ready yet at 0.9 s"
        );
        assert_eq!(
            sup.reconcile(&on1, &api, true, t2 + Duration::from_millis(1100)),
            vec![RestartWorker(0)],
            "ready at 1.1 s: proves the backoff reset to 1 s, not 2 s"
        );
    }

    #[test]
    fn killpg_reaches_the_whole_process_group() {
        let dir = tmp("pg");
        let log = dir.join("pg.log");
        let child = spawn_in_group(&sh("sleep 30 & echo $!; wait"), None, &[], &log).unwrap();
        let p = ProcGuard(Proc::spawned(child));
        let pid = p.0.pid();
        let grandchild = (0..40)
            .find_map(|_| {
                std::thread::sleep(Duration::from_millis(50));
                std::fs::read_to_string(&log)
                    .ok()?
                    .trim()
                    .parse::<u32>()
                    .ok()
            })
            .expect("sh printed the sleep pid");
        assert!(is_alive(grandchild));
        let leftover = terminate(
            p.into_inner(),
            Duration::from_secs(2),
            &AtomicBool::new(false),
        );
        assert!(
            leftover.is_none(),
            "an uninterrupted terminate always finishes the group off"
        );
        assert!(!is_alive(pid));
        let gone = wait_until(|| !is_alive(grandchild));
        assert!(
            gone,
            "SIGTERM to the group must reach the grandchild, as python under uv"
        );
    }

    #[test]
    fn a_group_member_that_ignores_term_is_sigkilled() {
        let dir = tmp("ignore-term");
        let log = dir.join("ignore.log");
        let child = spawn_in_group(
            &sh("sh -c 'trap \"\" TERM; echo $$; exec sleep 30' & wait"),
            None,
            &[],
            &log,
        )
        .unwrap();
        let p = ProcGuard(Proc::spawned(child));
        let pid = p.0.pid();
        let grandchild = (0..40)
            .find_map(|_| {
                std::thread::sleep(Duration::from_millis(50));
                std::fs::read_to_string(&log)
                    .ok()?
                    .trim()
                    .parse::<u32>()
                    .ok()
            })
            .expect("sh printed the sleep pid");
        assert!(is_alive(grandchild));
        // A short grace forces the SIGKILL escalation path.
        let leftover = terminate(
            p.into_inner(),
            Duration::from_millis(300),
            &AtomicBool::new(false),
        );
        assert!(
            leftover.is_none(),
            "an uninterrupted terminate always finishes the group off"
        );
        assert!(!is_alive(pid));
        let gone = wait_until(|| !is_alive(grandchild));
        assert!(gone, "SIGKILL must reach a group member that ignores TERM");
    }

    /// The stop flag must never turn an in-flight graceful stop into an
    /// instant kill: when it is set mid-wait, `terminate` hands the
    /// still-alive group back untouched, and only `terminate_all` (with its
    /// own full grace period) actually finishes it off.
    #[test]
    fn a_stop_flag_set_mid_wait_hands_the_group_back_instead_of_sigkilling_it() {
        let dir = tmp("interrupt-terminate");
        let log = dir.join("ignore.log");
        let child = spawn_in_group(
            &sh("sh -c 'trap \"\" TERM; echo $$; exec sleep 30' & wait"),
            None,
            &[],
            &log,
        )
        .unwrap();
        let p = ProcGuard(Proc::spawned(child));
        let pid = p.0.pid();
        let grandchild = (0..40)
            .find_map(|_| {
                std::thread::sleep(Duration::from_millis(50));
                std::fs::read_to_string(&log)
                    .ok()?
                    .trim()
                    .parse::<u32>()
                    .ok()
            })
            .expect("sh printed the sleep pid");
        assert!(is_alive(grandchild));

        let stop = Arc::new(AtomicBool::new(false));
        let setter = stop.clone();
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(50));
            setter.store(true, Ordering::Relaxed);
        });

        let began = Instant::now();
        // A grace far longer than the return-time bound just below, so a
        // slow return can only be explained by the flag being ignored.
        let leftover = terminate(p.into_inner(), Duration::from_secs(30), &stop);
        let elapsed = began.elapsed();
        // Re-guard the handed-back `Proc` immediately, before any assertion
        // below gets a chance to panic and leak the still-alive group: `Proc`
        // itself has no `Drop`, so nothing else here kills it on a failure.
        let mut leftover = leftover.map(ProcGuard);
        assert!(
            elapsed < Duration::from_secs(2),
            "terminate took {elapsed:?} to notice the stop flag \
             (still far below the 30 s grace this must interrupt)"
        );
        let leftover = leftover
            .take()
            .expect("an interrupted terminate must hand the group back, not kill it");
        assert!(
            group_alive(pid),
            "an interrupted terminate must not SIGKILL the group \
             (the leader itself may already have exited on the plain SIGTERM \
             it never trapped; the group member that traps it must survive)"
        );
        assert!(
            is_alive(grandchild),
            "an interrupted terminate must not touch a group member either"
        );

        // terminate_all is what actually finishes it off, with its own
        // grace; SupGuard's own Drop is a second backstop in case anything
        // between here and the end of the test panics first.
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exit 0"))));
        sup.broker = Some(leftover.into_inner());
        sup.terminate_all(Duration::from_secs(2));
        // SIGKILL is asynchronous: poll rather than assert instantly, exactly
        // as `terminate_all_also_reaches_a_group_member_that_ignores_term`
        // does below.
        assert!(
            wait_until(|| !group_alive(pid)),
            "terminate_all must still finish off a group terminate() handed back"
        );
        let gone = wait_until(|| !is_alive(grandchild));
        assert!(
            gone,
            "terminate_all must still finish off a group terminate() handed back"
        );
    }

    /// A zombie holds no resources, runs no code and answers no requests —
    /// it has already exited, only its exit status is unclaimed. In a
    /// container with no PID 1 reaper that status is never claimed, so a
    /// `group_alive` that treats a zombie as "still there" (because
    /// `killpg(pid, 0)` still finds its pgid) makes `terminate`/`terminate_all`
    /// poll forever for something that already died (#277). This creates a
    /// real zombie — spawn a child, SIGKILL it directly, and deliberately
    /// never reap it — and asserts both helpers already call it gone.
    #[test]
    fn group_alive_and_is_alive_treat_an_unreaped_zombie_as_gone() {
        let dir = tmp("zombie-alive");
        let log = dir.join("z.log");
        let mut child = spawn_in_group(&sh("exec sleep 30"), None, &[], &log).unwrap();
        let pid = child.id();
        // Kill the leader directly (not via signal_group/terminate) and
        // never call try_wait/wait: exactly how an orphaned grandchild ends
        // up a permanent zombie when nothing ever reaps it.
        unsafe {
            libc::kill(pid as libc::pid_t, libc::SIGKILL);
        }
        // Confirm it is specifically a zombie, not merely gone: the pid still
        // answers `kill(pid, 0)` (its table entry is still there) while
        // `is_alive` — already zombie-aware — says it is not alive.
        let became_zombie = (0..200).any(|_| {
            std::thread::sleep(Duration::from_millis(20));
            (unsafe { libc::kill(pid as libc::pid_t, 0) } == 0) && !is_alive(pid)
        });
        assert!(
            became_zombie,
            "the killed, unreaped child must become a zombie before we assert on it \
             (if this fails, the platform's zombie detection route needs a look)"
        );
        assert!(
            !group_alive(pid),
            "a group whose only member is an unreaped zombie must read as gone"
        );
        assert!(
            !is_alive(pid),
            "is_alive must already treat a zombie leader as gone"
        );
        // Reap it for real so the zombie doesn't leak into the rest of the suite.
        unsafe {
            libc::waitpid(pid as libc::pid_t, std::ptr::null_mut(), 0);
        }
        let _ = child.try_wait();
    }

    #[test]
    fn terminate_all_also_reaches_a_group_member_that_ignores_term() {
        use Action::*;
        let dir = tmp("ignore-term-all");
        let api = FakeBroker::default();
        api.up.set(true);
        let mut sup = SupGuard(Supervisor::new(spec(
            &dir,
            sh("sh -c 'trap \"\" TERM; echo $$; exec sleep 30' & wait"),
        )));
        let on1 = Desired {
            sharing: true,
            workers: 1,
        };
        // Adopt a fake running broker so the plan goes straight to workers.
        let broker_child =
            spawn_in_group(&sh("exec sleep 60"), None, &[], &dir.join("b.log")).unwrap();
        let _guard = PgGuard(broker_child.id());
        sup.broker = Some(Proc::spawned(broker_child));

        assert_eq!(
            sup.reconcile(&on1, &api, true, Instant::now()),
            vec![StartWorker(0)]
        );
        let log = sup.worker_log(0);
        let grandchild = (0..40)
            .find_map(|_| {
                std::thread::sleep(Duration::from_millis(50));
                std::fs::read_to_string(&log)
                    .ok()?
                    .trim()
                    .parse::<u32>()
                    .ok()
            })
            .expect("worker script printed the sleep pid");
        assert!(is_alive(grandchild));
        sup.terminate_all(Duration::from_millis(300));
        let gone = wait_until(|| !is_alive(grandchild));
        assert!(
            gone,
            "terminate_all's SIGKILL must reach a group member that ignores TERM"
        );
    }

    #[test]
    fn adoption_needs_a_live_pid_with_the_same_start_time() {
        let dir = tmp("adopt");
        let mut child = ChildGuard(
            spawn_in_group(&sh("exec sleep 30"), None, &[], &dir.join("a.log")).unwrap(),
        );
        let pid = child.id();
        let started = proc_start_time(pid).expect("ps/proc reports a start time");
        assert_eq!(
            proc_start_time(pid).as_deref(),
            Some(started.as_str()),
            "stable"
        );

        let mut recorded = Children::default();
        recorded.workers.insert(
            "0".into(),
            ChildRecord {
                pid,
                started_at: started.clone(),
                port: None,
                container: None,
            },
        );
        recorded.workers.insert(
            "1".into(),
            ChildRecord {
                pid,
                started_at: "reused pid".into(),
                port: None,
                container: None,
            },
        );
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        sup.adopt(&recorded, &proc_start_time);
        assert_eq!(
            sup.children().workers.keys().cloned().collect::<Vec<_>>(),
            vec!["0".to_string()]
        );

        sup.terminate_all(Duration::from_secs(2));
        // `wait` blocks until the (already SIGTERMed) process actually exits,
        // so there's no need for a fixed sleep here.
        let _ = child.0.wait();
        assert_eq!(proc_start_time(pid), None, "a dead pid has no start time");
    }

    #[test]
    fn logs_are_truncated_past_the_cap_and_tailed() {
        let dir = tmp("logs");
        std::fs::create_dir_all(&dir).unwrap();
        let log = dir.join("w0.log");
        std::fs::write(&log, "a\nb\nc\nd\n").unwrap();
        assert_eq!(tail_lines(&log, 2), "c\nd");
        assert!(!truncate_if_large(&log, 1024).unwrap());
        assert!(truncate_if_large(&log, 3).unwrap());
        assert_eq!(std::fs::metadata(&log).unwrap().len(), 0);
    }

    #[test]
    fn argv_templates_and_broker_env_follow_the_spec() {
        let t: Vec<String> = ["uv", "--port", "{port}", "--worker-name", "{name}"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert_eq!(
            render_argv(&t, 3961, "fp-w1"),
            vec!["uv", "--port", "3961", "--worker-name", "fp-w1"]
        );

        let mut cfg = crate::agent::config::AgentConfig::for_dirs(tmp("spec"));
        cfg.max_workers = 5;
        let s = SpawnSpec::from_config(&cfg);
        assert!(s
            .broker_env
            .contains(&("ZAKURO_SCAN_RANGE".into(), "3960-3984".into())));
        assert!(s
            .broker_env
            .contains(&("ZAKURO_SCAN_INTERVAL".into(), "3".into())));
        assert!(
            !s.broker_env.iter().any(|(k, _)| k == "ZAKURO_P2P"),
            "ZAKURO_P2P is added at each broker start, from the mesh route of that moment"
        );
        assert!(
            !s.broker_env
                .iter()
                .any(|(k, _)| k == "ZAKURO_AGENT_CHILD_PORT"),
            "the broker's port env is added at spawn time, once the port is chosen"
        );
        // `broker_argv` is a template (`{port}` unrendered) until spawn time,
        // so a fallback port picked at start doesn't require re-deriving the
        // whole SpawnSpec.
        assert_eq!(
            &s.broker_argv[1..],
            &["broker".to_string(), "{port}".to_string()]
        );
        assert_eq!(s.preferred_broker_port, 9000);
        assert!(s
            .worker_env
            .contains(&("ZAKURO_WORKER_TYPE".into(), "zakuro".into())));
        assert!(s
            .worker_env
            .contains(&("UV_NO_PROGRESS".into(), "1".into())));
    }

    #[test]
    fn workers_bind_loopback_unless_the_config_picks_a_host_or_caller_auth() {
        use crate::agent::config::AgentConfig;
        // The value a worker ends up with: the last ZAKURO_HOST wins.
        let host = |cfg: &AgentConfig| {
            SpawnSpec::from_config(cfg)
                .worker_env
                .iter()
                .rev()
                .find(|(k, _)| k == "ZAKURO_HOST")
                .map(|(_, v)| v.clone())
        };
        let plain = AgentConfig::for_dirs(tmp("bind-plain"));
        assert_eq!(host(&plain).as_deref(), Some("127.0.0.1"));

        let mut insecure = AgentConfig::for_dirs(tmp("bind-insecure"));
        insecure
            .child_env
            .push(("ZAKURO_INSECURE_BIND".into(), "1".into()));
        assert_eq!(host(&insecure), None);

        let mut chosen = AgentConfig::for_dirs(tmp("bind-host"));
        chosen
            .child_env
            .push(("ZAKURO_HOST".into(), "0.0.0.0".into()));
        assert_eq!(host(&chosen).as_deref(), Some("0.0.0.0"));
    }

    // --- Broker crash backoff and crashloop (mirrors the worker slot machinery) ---

    #[test]
    fn a_crashing_broker_backs_off_then_restarts() {
        use Action::*;
        let dir = tmp("brk-backoff");
        let api = FakeBroker::default();
        let mut s = spec(&dir, sh("exec sleep 60"));
        s.broker_argv = sh("echo boom; exit 1");
        let mut sup = SupGuard(Supervisor::new(s));
        let t = Instant::now();
        let at = |ms: u64| t + Duration::from_millis(ms);
        let on = Desired {
            sharing: true,
            workers: 0,
        };

        assert_eq!(sup.reconcile(&on, &api, true, at(0)), vec![StartBroker]);
        assert!(
            wait_until_broker_exited(&mut sup),
            "the broker did not exit in time"
        );
        assert_eq!(
            sup.reconcile(&on, &api, true, at(100)),
            vec![],
            "1st failure: 1 s backoff, broker_restart_ready must be false"
        );
        assert_eq!(
            sup.reconcile(&on, &api, true, at(1200)),
            vec![StartBroker],
            "backoff elapsed: broker_restart_ready is true again"
        );
    }

    /// A broker whose process lives but whose `/health` never answers (the fd
    /// exhaustion case) is killed after `BROKER_UNRESPONSIVE_AFTER` and then
    /// restarted like a crash, instead of sitting in `Starting` forever.
    #[test]
    fn a_live_broker_that_stops_answering_is_killed_and_restarted() {
        use Action::*;
        let dir = tmp("brk-wedged");
        let api = FakeBroker::default();
        let mut s = spec(&dir, sh("exec sleep 60"));
        s.broker_argv = sh("exec sleep 60");
        let mut sup = SupGuard(Supervisor::new(s));
        let t = Instant::now();
        let at = |d: Duration| t + d;
        let on = Desired {
            sharing: true,
            workers: 0,
        };

        assert_eq!(
            sup.reconcile(&on, &api, true, at(Duration::ZERO)),
            vec![StartBroker]
        );
        let pid = match sup.broker.as_ref() {
            Some(Proc::Host(h)) => h.pid,
            _ => panic!("no host broker"),
        };
        let _g = PgGuard(pid);
        // `api.up` stays false: the process is alive, `/health` never answers.
        let early = at(Duration::from_secs(1));
        assert_eq!(sup.reconcile(&on, &api, true, early), vec![]);
        assert!(sup.broker.is_some(), "killed before the grace period");

        let late = early + BROKER_UNRESPONSIVE_AFTER;
        assert_eq!(sup.reconcile(&on, &api, true, late), vec![]);
        assert!(sup.broker.is_none(), "the unresponsive broker was kept");
        assert!(!is_alive(pid), "the unresponsive broker still runs");
        assert_eq!(
            sup.reconcile(&on, &api, true, late + Duration::from_secs(2)),
            vec![StartBroker],
            "restarted after the crash backoff"
        );
    }

    /// One `/health` that answers resets the clock: a broker that is merely
    /// slow now and then is never killed.
    #[test]
    fn an_answer_resets_the_unresponsive_clock() {
        use Action::*;
        let dir = tmp("brk-flaky");
        let api = FakeBroker::default();
        let mut s = spec(&dir, sh("exec sleep 60"));
        s.broker_argv = sh("exec sleep 60");
        let mut sup = SupGuard(Supervisor::new(s));
        let t = Instant::now();
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        assert_eq!(sup.reconcile(&on, &api, true, t), vec![StartBroker]);
        let pid = match sup.broker.as_ref() {
            Some(Proc::Host(h)) => h.pid,
            _ => panic!("no host broker"),
        };
        let _g = PgGuard(pid);
        let half = BROKER_UNRESPONSIVE_AFTER / 2 + Duration::from_secs(1);
        sup.reconcile(&on, &api, true, t + half);
        api.up.set(true);
        sup.reconcile(&on, &api, true, t + half * 2);
        api.up.set(false);
        sup.reconcile(&on, &api, true, t + half * 3);
        assert!(
            sup.broker.is_some() && is_alive(pid),
            "killed despite answering"
        );
    }

    #[test]
    fn three_broker_crashes_within_five_minutes_raise_a_crashloop_problem() {
        use Action::*;
        let dir = tmp("brk-crashloop");
        let api = FakeBroker::default();
        let mut s = spec(&dir, sh("exec sleep 60"));
        s.broker_argv = sh("echo boom; exit 1");
        let mut sup = SupGuard(Supervisor::new(s));
        let t = Instant::now();
        let at = |ms: u64| t + Duration::from_millis(ms);
        let on = Desired {
            sharing: true,
            workers: 0,
        };

        assert_eq!(sup.reconcile(&on, &api, true, at(0)), vec![StartBroker]);
        assert!(
            wait_until_broker_exited(&mut sup),
            "the broker did not exit in time"
        );
        assert_eq!(
            sup.reconcile(&on, &api, true, at(100)),
            vec![],
            "1st failure: 1 s backoff"
        );
        assert_eq!(sup.reconcile(&on, &api, true, at(1200)), vec![StartBroker]);
        assert!(
            wait_until_broker_exited(&mut sup),
            "the broker did not exit in time"
        );
        assert_eq!(
            sup.reconcile(&on, &api, true, at(1300)),
            vec![],
            "2nd failure: 2 s backoff"
        );
        assert_eq!(sup.reconcile(&on, &api, true, at(3400)), vec![StartBroker]);
        assert!(
            wait_until_broker_exited(&mut sup),
            "the broker did not exit in time"
        );
        sup.reconcile(&on, &api, true, at(3500)); // 3rd failure

        let problems = sup.problems(at(3500));
        let crash = problems
            .iter()
            .find(|p| p.code == "broker_crashloop")
            .expect("3 failures in 5 min");
        assert!(
            crash.detail.as_deref().unwrap_or("").contains("boom"),
            "detail carries the broker log tail"
        );
    }

    #[test]
    fn a_crashing_broker_that_stabilizes_resets_its_backoff() {
        use Action::*;
        let dir = tmp("broker-stable-reset");
        let api = FakeBroker::default();
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let t = Instant::now();
        let at = |ms: u64| t + Duration::from_millis(ms);
        let on = Desired {
            sharing: true,
            workers: 0,
        };

        // 1. Crash a child once.
        assert_eq!(sup.reconcile(&on, &api, true, at(0)), vec![StartBroker]);
        api.up.set(true);
        let pid0 = sup.children().broker.unwrap().pid;
        signal_group(pid0, libc::SIGKILL);
        assert!(
            wait_until_broker_exited(&mut sup),
            "the broker did not exit in time"
        );
        api.up.set(false);
        assert_eq!(
            sup.reconcile(&on, &api, true, at(100)),
            vec![],
            "1st failure: 1 s backoff"
        );

        // 2. Let it restart.
        assert_eq!(sup.reconcile(&on, &api, true, at(1200)), vec![StartBroker]);
        api.up.set(true);

        // 3. Tick at +301 s while it's alive: resets `broker_consecutive`.
        assert_eq!(sup.reconcile(&on, &api, true, at(1200 + 301_000)), vec![]);

        // 4. SIGKILL the pid from `sup.children()`: a second, independent crash.
        let pid1 = sup.children().broker.unwrap().pid;
        signal_group(pid1, libc::SIGKILL);
        assert!(
            wait_until_broker_exited(&mut sup),
            "the broker did not exit in time"
        );
        api.up.set(false);
        let t2 = at(1200 + 301_000 + 100);
        assert_eq!(
            sup.reconcile(&on, &api, true, t2),
            vec![],
            "post-reset failure: backoff restarts at 1 s"
        );

        // 5. The next restart backoff must be 1 s, not 2 s.
        assert_eq!(
            sup.reconcile(&on, &api, true, t2 + Duration::from_millis(900)),
            vec![],
            "not ready yet at 0.9 s"
        );
        assert_eq!(
            sup.reconcile(&on, &api, true, t2 + Duration::from_millis(1100)),
            vec![StartBroker],
            "ready at 1.1 s: proves the backoff reset to 1 s, not 2 s"
        );
    }

    #[test]
    fn a_deliberate_broker_stop_is_not_counted_as_a_crash_failure() {
        use Action::*;
        let dir = tmp("brk-stop");
        let api = FakeBroker::default();
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let t = Instant::now();
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        let off = Desired {
            sharing: false,
            workers: 0,
        };

        assert_eq!(sup.reconcile(&on, &api, true, t), vec![StartBroker]);
        api.up.set(true);
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![StopBroker]);
        api.up.set(false); // the broker's /health stops answering once its process is gone
        assert!(sup.children().broker.is_none());
        let problems = sup.problems(t);
        assert!(
            !problems.iter().any(|p| p.code == "broker_crashloop"),
            "a clean stop is not a failure"
        );

        // No backoff was recorded, so starting it again is immediate.
        assert_eq!(sup.reconcile(&on, &api, true, t), vec![StartBroker]);
    }

    // --- An unknown `GET /workers` state must never read as "idle" ---

    /// A one-shot loopback HTTP server, in the idiom already used by
    /// src/broker/server.rs, src/enroll.rs and src/mesh_dir.rs: answers a
    /// single request with `status`/`body`, then the thread exits.
    fn stub_http_once(status: u16, body: &'static str) -> u16 {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            if let Ok((mut s, _)) = listener.accept() {
                let mut buf = [0u8; 1024];
                let _ = s.read(&mut buf);
                let _ = write!(
                    s,
                    "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
            }
        });
        port
    }

    #[test]
    fn workers_over_http_errs_on_a_non_2xx_response() {
        // A body that would parse just fine as a (trivially empty) worker
        // list, so this only fails if the status is actually checked.
        let port = stub_http_once(500, r#"{"workers":[]}"#);
        let api = HttpBrokerApi {
            port,
            worker_key: None,
        };
        assert!(
            api.workers().is_err(),
            "a non-2xx GET /workers must be an error, not an empty list"
        );
    }

    #[test]
    fn workers_over_http_parses_a_valid_2xx_response() {
        let body = r#"{"workers":[{"id":"id0","name":"fp-w0","status":"healthy","active_requests":1,"requests_5h":2,"requests_1w":3}]}"#;
        let port = stub_http_once(200, body);
        let api = HttpBrokerApi {
            port,
            worker_key: None,
        };
        let list = api.workers().expect("a 2xx body should parse");
        assert_eq!(list.len(), 1);
        assert_eq!(list[0].id, "id0");
        assert_eq!(list[0].active_requests, 1);
    }

    /// (a) A draining worker whose last GOOD entry already showed 0 active
    /// requests must not be read as idle just because the very next tick's
    /// `GET /workers` fails — that observation is unknown, not "confirmed
    /// idle". Only a FRESH tick (or drain-expiry) may complete the drain.
    #[test]
    fn a_workers_fetch_error_keeps_a_zero_reading_drain_from_completing() {
        use Action::*;
        let dir = tmp("stale-workers-zero");
        let api = FakeBroker::default();
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let t = Instant::now();
        let on1 = Desired {
            sharing: true,
            workers: 1,
        };

        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![StartBroker]);
        api.up.set(true);
        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![StartWorker(0)]);
        *api.workers.borrow_mut() = vec![bw("id0", "testfp00-w0")]; // active_requests = 0
        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![]);

        let off = Desired {
            sharing: false,
            workers: 1,
        };
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![DrainWorker(0)]);
        assert_eq!(*api.drained.borrow(), vec!["id0".to_string()]);

        // The last GOOD reading already showed 0; a fetch error on the very
        // next tick must still not complete the drain.
        api.workers_err.set(true);
        assert_eq!(
            sup.reconcile(&off, &api, true, t),
            vec![],
            "an unknown observation must not read a zero-reading drain as idle"
        );
        assert_eq!(
            sup.broker_id(0).as_deref(),
            Some("id0"),
            "the retained id must survive the fetch-error tick"
        );

        // The next FRESH tick, still showing 0, completes the drain and
        // DELETEs the retained id.
        api.workers_err.set(false);
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![KillWorker(0)]);
        assert_eq!(*api.deleted.borrow(), vec!["id0".to_string()]);
    }

    /// (b) Same, but the unknown tick comes from a `/health` timeout (the
    /// broker is observed `Starting`, not from a `GET /workers` error): the
    /// retained list and id must survive that too.
    #[test]
    fn a_health_check_timeout_keeps_a_busy_drain_from_completing() {
        use Action::*;
        let dir = tmp("stale-workers-health-timeout");
        let api = FakeBroker::default();
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let t = Instant::now();
        let on1 = Desired {
            sharing: true,
            workers: 1,
        };

        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![StartBroker]);
        api.up.set(true);
        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![StartWorker(0)]);
        *api.workers.borrow_mut() = vec![bw_n("id0", "testfp00-w0", 2)];
        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![]);

        let off = Desired {
            sharing: false,
            workers: 1,
        };
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![DrainWorker(0)]);
        assert_eq!(*api.drained.borrow(), vec!["id0".to_string()]);

        // `/health` times out: the broker leader and the worker are both
        // still alive, but the tick is observed `Starting`, not `Running`.
        api.health_override.set(Some(false));
        assert_eq!(
            sup.reconcile(&off, &api, true, t),
            vec![],
            "a health-check timeout must not read the drain as idle"
        );
        assert_eq!(
            sup.broker_id(0).as_deref(),
            Some("id0"),
            "the retained id must survive the Starting tick"
        );

        // `/health` recovers; GET /workers still reports 2 active: still no kill.
        api.health_override.set(None);
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![]);

        // Once a FRESH tick reports 0, the drain completes using the id
        // retained across the Starting tick.
        *api.workers.borrow_mut() = vec![bw("id0", "testfp00-w0")];
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![KillWorker(0)]);
        assert_eq!(*api.deleted.borrow(), vec!["id0".to_string()]);
    }

    /// A killed worker's `last_workers` entry (its id and stats) must be
    /// forgotten, or a later `StartWorker` on the same slot would inherit
    /// the dead worker's id and stats by name during an error streak.
    #[test]
    fn killing_a_worker_during_an_error_streak_forgets_its_retained_entry() {
        use Action::*;
        let dir = tmp("kill-forgets-entry");
        let api = FakeBroker::default();
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let t = Instant::now();
        let on1 = Desired {
            sharing: true,
            workers: 1,
        };

        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![StartBroker]);
        api.up.set(true);
        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![StartWorker(0)]);
        *api.workers.borrow_mut() = vec![bw_n("dead-id", "testfp00-w0", 9)];
        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![]);

        // Scale down to 0 (sharing stays on, so the broker is untouched)
        // to drain the one live worker.
        let scale0 = Desired {
            sharing: true,
            workers: 0,
        };
        assert_eq!(sup.reconcile(&scale0, &api, true, t), vec![DrainWorker(0)]);
        assert_eq!(*api.drained.borrow(), vec!["dead-id".to_string()]);

        // Start a GET /workers error streak, then let the drained worker's
        // process actually exit: the drain still completes (the process is
        // simply gone), independent of freshness.
        api.workers_err.set(true);
        let pid0 = sup.children().workers["0"].pid;
        signal_group(pid0, libc::SIGKILL);
        assert!(wait_until_worker_exited(&mut sup, 0));
        assert_eq!(sup.reconcile(&scale0, &api, true, t), vec![KillWorker(0)]);
        assert_eq!(*api.deleted.borrow(), vec!["dead-id".to_string()]);

        // The dead entry must be gone now, even though the fetch is still
        // failing.
        assert_eq!(
            sup.broker_id(0),
            None,
            "the dead worker's id must not linger"
        );

        // Restart the same slot while the error streak continues: the new
        // worker must not inherit the dead worker's stats or id.
        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![StartWorker(0)]);
        let view = sup.local_view(&on1, 5);
        assert_eq!(
            view.requests,
            Requests {
                last_5h: 0,
                last_1w: 0
            },
            "no stale stats for the new worker"
        );
        assert_eq!(view.workers.busy, 0, "no stale busy count");
        assert_eq!(
            sup.broker_id(0),
            None,
            "no stale id for the new worker either"
        );

        // A later drain must not target the dead id: no new entry is added
        // to the drained list (it still holds only the earlier, correct
        // "dead-id" drain from before the kill).
        assert_eq!(sup.reconcile(&scale0, &api, true, t), vec![DrainWorker(0)]);
        assert_eq!(
            *api.drained.borrow(),
            vec!["dead-id".to_string()],
            "no id to drain yet: the dead id must not be reused for the new worker"
        );
    }

    /// A drain that didn't take is sent again on every fresh tick until the
    /// broker itself reports the worker `draining`: the worker hadn't
    /// registered yet (no id to send), the POST failed, or the broker
    /// restarted and re-registered it as healthy. Otherwise the broker keeps
    /// routing jobs to a worker the agent is about to stop.
    #[test]
    fn a_drain_is_resent_until_the_broker_reports_the_worker_draining() {
        use Action::*;
        let dir = tmp("drain-resend");
        let api = FakeBroker::default();
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let t = Instant::now();
        let on1 = Desired {
            sharing: true,
            workers: 1,
        };
        let off = Desired {
            sharing: false,
            workers: 1,
        };
        let drained = || api.drained.borrow().clone();
        let with_status = |id: &str, status: &str| BrokerWorker {
            status: status.into(),
            // Busy, so the drain can't complete while this test watches it.
            ..bw_n(id, "testfp00-w0", 1)
        };

        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![StartBroker]);
        api.up.set(true);
        assert_eq!(sup.reconcile(&on1, &api, true, t), vec![StartWorker(0)]);

        // Paused before the worker registered: there is no id to send yet.
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![DrainWorker(0)]);
        assert!(drained().is_empty());

        // It registers, and the drain POST fails.
        *api.workers.borrow_mut() = vec![with_status("id0", "healthy")];
        api.drain_fails.set(true);
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![]);
        assert_eq!(drained(), vec!["id0".to_string()], "sent once it has an id");

        // The broker still reports it healthy: sent again.
        api.drain_fails.set(false);
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![]);
        assert_eq!(drained().len(), 2, "re-sent after the failed POST");

        // The broker now reports it draining: nothing more is sent.
        *api.workers.borrow_mut() = vec![with_status("id0", "draining")];
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![]);
        assert_eq!(drained().len(), 2);

        // The broker restarted and re-registered it as healthy, under a new id.
        *api.workers.borrow_mut() = vec![with_status("id0-b", "healthy")];
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![]);
        assert_eq!(
            drained().last().map(String::as_str),
            Some("id0-b"),
            "re-sent after a broker restart"
        );

        // An unknown tick (GET /workers failed) sends nothing.
        let before = drained().len();
        api.workers_err.set(true);
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![]);
        assert_eq!(drained().len(), before);
    }

    // --- A leader found dead has its process group killed ---

    #[test]
    fn a_worker_leader_that_exits_early_has_its_surviving_group_member_killed() {
        use Action::*;
        let dir = tmp("leader-exits-early");
        let api = FakeBroker::default();
        api.up.set(true);
        // The leader backgrounds a member, prints that member's own pid, then
        // exits, leaving it as the sole survivor in the group. We poll the
        // member's own pid with `is_alive` (not `group_alive` on the pgid):
        // on Linux, `group_alive` (`killpg(pg, 0)`) still counts an unreaped
        // zombie member as "the group is alive", where `is_alive` treats a
        // zombie as dead.
        let mut sup = SupGuard(Supervisor::new(spec(
            &dir,
            sh("sleep 30 & echo $!; exit 0"),
        )));
        let on1 = Desired {
            sharing: true,
            workers: 1,
        };
        // Adopt a fake running broker so the plan goes straight to workers.
        let broker_child =
            spawn_in_group(&sh("exec sleep 60"), None, &[], &dir.join("b.log")).unwrap();
        let _guard = PgGuard(broker_child.id());
        sup.broker = Some(Proc::spawned(broker_child));

        assert_eq!(
            sup.reconcile(&on1, &api, true, Instant::now()),
            vec![StartWorker(0)]
        );
        let pid0 = sup.children().workers["0"].pid; // the leader's pid == the group's pgid
                                                    // Guard the whole group so a failing assertion below can't orphan
                                                    // the backgrounded `sleep 30`.
        let _pg_guard = PgGuard(pid0);
        let log = sup.worker_log(0);
        let member = (0..40)
            .find_map(|_| {
                std::thread::sleep(Duration::from_millis(50));
                std::fs::read_to_string(&log)
                    .ok()?
                    .trim()
                    .parse::<u32>()
                    .ok()
            })
            .expect("the worker script printed the backgrounded sleep's pid");
        assert!(
            wait_until_worker_exited(&mut sup, 0),
            "the leader exits on its own almost immediately"
        );
        assert!(
            is_alive(member),
            "the backgrounded `sleep 30` must still be alive right after the leader exits"
        );

        // The next tick observes the dead leader and must kill the whole
        // group, not just note the crash.
        sup.reconcile(&on1, &api, true, Instant::now());
        assert!(
            wait_until(|| !is_alive(member)),
            "the surviving group member must be killed once the leader is found dead"
        );
    }

    // --- Broker port fallback (zc#agent-ports) ---

    /// A wildcard holder (`*:P`, exactly how the broker itself binds) must
    /// never read as free: a specific-address (`127.0.0.1:P`) bind succeeds
    /// right past it on macOS/BSD because Rust std sets `SO_REUSEADDR`, so a
    /// naive probe would hand the agent a port its own broker then fails to
    /// bind, crash-looping forever (review A1).
    #[test]
    fn port_free_is_false_when_something_holds_the_wildcard_address() {
        let holder = std::net::TcpListener::bind(("0.0.0.0", 0)).unwrap();
        let port = holder.local_addr().unwrap().port();
        let api = HttpBrokerApi {
            port: 0,
            worker_key: None,
        };
        assert!(
            !api.port_free(port),
            "a *:{port} holder must not read as free"
        );
        drop(holder);
    }

    mod choose_broker_port_tests {
        use super::choose_broker_port;

        #[test]
        fn preferred_free() {
            assert_eq!(
                choose_broker_port(9000, 9001, 9010, |p| p == 9000, || None),
                Some(9000)
            );
        }

        #[test]
        fn preferred_held_falls_back_to_9001() {
            assert_eq!(
                choose_broker_port(9000, 9001, 9010, |p| p == 9001, || None),
                Some(9001)
            );
        }

        #[test]
        fn preferred_and_9001_through_9003_held_falls_back_to_9004() {
            assert_eq!(
                choose_broker_port(9000, 9001, 9010, |p| p == 9004, || None),
                Some(9004)
            );
        }

        #[test]
        fn the_whole_range_held_falls_back_to_an_os_pick() {
            assert_eq!(
                choose_broker_port(9000, 9001, 9010, |_| false, || Some(54321)),
                Some(54321)
            );
        }

        #[test]
        fn nothing_available_is_none() {
            assert_eq!(
                choose_broker_port(9000, 9001, 9010, |_| false, || None),
                None
            );
        }
    }

    /// A zakuro broker the agent doesn't own on the *preferred* port (9000)
    /// is always `Unmanaged`, even though nothing has tried to start our own
    /// broker yet.
    #[test]
    fn a_foreign_broker_on_the_preferred_port_is_unmanaged() {
        let dir = tmp("foreign-preferred");
        let api = FakeBroker::default();
        api.foreign_broker_port.set(Some(9000));
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let on = Desired {
            sharing: true,
            workers: 1,
        };
        assert_eq!(sup.reconcile(&on, &api, true, Instant::now()), vec![]);
        assert!(sup.broker_unmanaged());
        assert_eq!(sup.broker_port(), 9000, "never relocated: never touched");
    }

    /// The preferred port is held by something that isn't a zakuro broker:
    /// the supervisor relocates to the first free fallback port and starts
    /// the broker there, rendering argv and env with that port.
    #[test]
    fn a_blocked_preferred_port_falls_back_and_renders_the_chosen_port() {
        use Action::*;
        let dir = tmp("fallback-9001");
        let api = FakeBroker::default();
        api.blocked_ports.borrow_mut().insert(9000);
        let mut spawn_spec = spec(&dir, sh("exec sleep 60"));
        spawn_spec.broker_argv = vec!["sh".into(), "-c".into(), "exec sleep 60 {port}".into()];
        let mut sup = SupGuard(Supervisor::new(spawn_spec));
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![StartBroker]
        );
        assert_eq!(sup.broker_port(), 9001);
        assert_eq!(sup.children().broker.unwrap().port, Some(9001));
    }

    /// N3: an idle agent (sharing off) must never probe or bind a fallback
    /// port at all -- `port_free`/`os_assigned_port` do real socket I/O
    /// (`HttpBrokerApi`'s wildcard bind), and doing that every reconcile
    /// tick while nothing is ever going to start can raise the macOS
    /// "accept incoming connections?" prompt long before sharing is turned
    /// on. `broker_port` stays at the preferred port (unused, since nothing
    /// starts); a foreign broker on the preferred port is still detected
    /// (`is_broker_at` is a connect, not a listen, so it's fine to keep
    /// doing that every tick).
    #[test]
    fn an_idle_tick_never_probes_or_binds_a_fallback_port() {
        let dir = tmp("fallback-while-paused");
        let api = FakeBroker::default();
        api.blocked_ports.borrow_mut().insert(9000); // something (not us) holds 9000
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let off = Desired {
            sharing: false,
            workers: 0,
        };
        assert_eq!(sup.reconcile(&off, &api, true, Instant::now()), vec![]);
        assert_eq!(
            *api.port_free_calls.borrow(),
            0,
            "an idle tick must never probe a fallback port"
        );
        assert_eq!(
            *api.os_assigned_port_calls.borrow(),
            0,
            "an idle tick must never bind an OS-assigned port either"
        );
        assert_eq!(
            sup.broker_port(),
            9000,
            "nothing was chosen, so it stays at the preferred port"
        );
    }

    /// The same idle tick still correctly detects a foreign zakuro broker on
    /// the preferred port (a connect, not a listen -- safe every tick).
    #[test]
    fn an_idle_tick_still_detects_an_unmanaged_broker_on_the_preferred_port() {
        let dir = tmp("unmanaged-while-paused");
        let api = FakeBroker::default();
        api.foreign_broker_port.set(Some(9000));
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let off = Desired {
            sharing: false,
            workers: 0,
        };
        sup.reconcile(&off, &api, true, Instant::now());
        assert!(sup.broker_unmanaged());
    }

    /// Once sharing turns on, the very next tick DOES probe (exactly the
    /// `choose_broker_port` wiring the earlier fallback tests already cover)
    /// -- this pins that the gate is "about to start", not "sharing was ever
    /// turned on in the past".
    #[test]
    fn turning_sharing_on_probes_and_starts_on_the_very_next_tick() {
        use Action::*;
        let dir = tmp("fallback-then-share-on");
        let api = FakeBroker::default();
        api.blocked_ports.borrow_mut().insert(9000);
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let off = Desired {
            sharing: false,
            workers: 0,
        };
        sup.reconcile(&off, &api, true, Instant::now());
        assert_eq!(*api.port_free_calls.borrow(), 0);

        let on = Desired {
            sharing: true,
            workers: 0,
        };
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![StartBroker]
        );
        assert!(*api.port_free_calls.borrow() > 0);
        assert_eq!(sup.broker_port(), 9001);
    }

    /// The preferred port and the whole 9001..=9010 fallback range are all
    /// held, and there is no OS-assigned port either: `port_in_use`, not a
    /// silent standstill.
    #[test]
    fn everything_blocked_and_no_os_pick_is_port_in_use() {
        let dir = tmp("all-blocked");
        let api = FakeBroker::default();
        for p in 9000..=9010 {
            api.blocked_ports.borrow_mut().insert(p);
        }
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        sup.reconcile(&on, &api, true, Instant::now());
        let problems = sup.problems(Instant::now());
        assert!(problems.iter().any(|p| p.code == "port_in_use"));
    }

    /// Once 9000..=9010 are all held, a random OS-assigned port is used
    /// instead of giving up.
    #[test]
    fn everything_blocked_falls_back_to_an_os_assigned_port() {
        use Action::*;
        let dir = tmp("os-pick");
        let api = FakeBroker::default();
        for p in 9000..=9010 {
            api.blocked_ports.borrow_mut().insert(p);
        }
        api.os_pick.set(Some(54321));
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![StartBroker]
        );
        assert_eq!(sup.broker_port(), 54321);
    }

    /// `adopt` restores the broker's port from its recorded `ChildRecord`; a
    /// record without a `port` (written before this field existed) means
    /// 9000.
    #[test]
    fn adopt_restores_the_brokers_recorded_port_defaulting_to_9000() {
        let dir = tmp("adopt-port");
        let broker_child =
            spawn_in_group(&sh("exec sleep 60"), None, &[], &dir.join("b.log")).unwrap();
        let _guard = PgGuard(broker_child.id());
        let pid = broker_child.id();
        let started = proc_start_time(pid).unwrap_or_default();
        let child_guard = ChildGuard(broker_child);

        let recorded = Children {
            broker: Some(ChildRecord {
                pid,
                started_at: started.clone(),
                port: Some(9007),
                container: None,
            }),
            ..Default::default()
        };
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        sup.adopt(&recorded, &proc_start_time);
        assert_eq!(sup.broker_port(), 9007);

        let recorded_no_port = Children {
            broker: Some(ChildRecord {
                pid,
                started_at: started,
                port: None,
                container: None,
            }),
            ..Default::default()
        };
        let mut sup2 = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        sup2.adopt(&recorded_no_port, &proc_start_time);
        assert_eq!(sup2.broker_port(), 9000, "a missing port field means 9000");
        drop(child_guard);
    }

    /// `set_worker_cwd` is what lets the agent resolve the zakuro dir fresh
    /// on every reconcile tick (`Core::reconcile_once`) instead of once at
    /// startup: a newly spawned worker must run in whatever directory was
    /// set just before this tick, without restarting the agent.
    #[test]
    fn set_worker_cwd_changes_where_the_next_spawned_worker_runs() {
        use Action::*;
        let dir = tmp("worker-cwd");
        let cwd_a = dir.join("cwd-a");
        let cwd_b = dir.join("cwd-b");
        std::fs::create_dir_all(&cwd_a).unwrap();
        std::fs::create_dir_all(&cwd_b).unwrap();
        let api = FakeBroker::default();
        api.up.set(true);
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("pwd"))));
        let broker_child =
            spawn_in_group(&sh("exec sleep 60"), None, &[], &dir.join("b.log")).unwrap();
        let _guard = PgGuard(broker_child.id());
        sup.broker = Some(Proc::spawned(broker_child));

        sup.set_worker_cwd(Some(cwd_a.clone()));
        assert_eq!(
            sup.reconcile(
                &Desired {
                    sharing: true,
                    workers: 1
                },
                &api,
                true,
                Instant::now()
            ),
            vec![StartWorker(0)]
        );

        sup.set_worker_cwd(Some(cwd_b.clone()));
        assert_eq!(
            sup.reconcile(
                &Desired {
                    sharing: true,
                    workers: 2
                },
                &api,
                true,
                Instant::now()
            ),
            vec![StartWorker(1)]
        );

        assert!(wait_until_worker_exited(&mut sup, 0));
        assert!(wait_until_worker_exited(&mut sup, 1));
        let printed_a = std::fs::read_to_string(sup.worker_log(0)).unwrap();
        let printed_b = std::fs::read_to_string(sup.worker_log(1)).unwrap();
        assert_eq!(
            printed_a.trim(),
            cwd_a.canonicalize().unwrap().to_str().unwrap()
        );
        assert_eq!(
            printed_b.trim(),
            cwd_b.canonicalize().unwrap().to_str().unwrap()
        );
    }

    /// A broker that prints the `ZAKURO_P2P` it was started with, then sleeps.
    const PRINTS_ZAKURO_P2P: &str = r#"echo "ZAKURO_P2P=${ZAKURO_P2P-unset}"; exec sleep 60"#;

    /// The broker log's lines, once it holds at least `n` whole ones (up to 5 s).
    fn broker_log_lines(sup: &Supervisor, n: usize) -> Vec<String> {
        let log = sup.broker_log();
        let text = || std::fs::read_to_string(&log).unwrap_or_default();
        assert!(
            wait_until(|| text().matches('\n').count() >= n),
            "the broker should have printed {n} line(s)"
        );
        text().lines().map(str::to_string).collect()
    }

    /// Starts `s`'s broker (sharing on, no workers) on `route` and returns
    /// what it printed.
    fn p2p_of_a_broker_started_on(route: RouteKind, s: SpawnSpec) -> String {
        let api = FakeBroker::default();
        let mut sup = SupGuard(Supervisor::new(s));
        sup.set_route(route);
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![Action::StartBroker]
        );
        broker_log_lines(&sup, 1).remove(0)
    }

    fn p2p_printing_spec(tag: &str) -> SpawnSpec {
        let mut s = spec(&tmp(tag), sh("exec sleep 60"));
        s.broker_argv = sh(PRINTS_ZAKURO_P2P);
        s
    }

    /// The broker peers on either mesh route, the proxy's included, and not
    /// without one.
    #[test]
    fn a_started_broker_runs_p2p_on_either_mesh_route_only() {
        for (route, want) in [
            (RouteKind::Proxy, "ZAKURO_P2P=true"),
            (RouteKind::Host, "ZAKURO_P2P=true"),
            (RouteKind::None, "ZAKURO_P2P=false"),
        ] {
            let tag = format!("p2p-{}", route.label());
            assert_eq!(
                p2p_of_a_broker_started_on(route, p2p_printing_spec(&tag)),
                want,
                "{route:?}"
            );
        }
    }

    /// An explicit `ZAKURO_P2P` in the agent's `child_env` wins over the
    /// route, either way.
    #[test]
    fn an_explicit_zakuro_p2p_in_child_env_wins_over_the_route() {
        for (route, explicit) in [(RouteKind::Proxy, "false"), (RouteKind::None, "true")] {
            let mut cfg = crate::agent::config::AgentConfig::for_dirs(tmp("p2p-explicit"));
            cfg.broker_argv = sh(PRINTS_ZAKURO_P2P);
            cfg.child_env = vec![("ZAKURO_P2P".to_string(), explicit.to_string())];
            assert_eq!(
                p2p_of_a_broker_started_on(route, SpawnSpec::from_config(&cfg)),
                format!("ZAKURO_P2P={explicit}"),
                "{route:?}"
            );
        }
    }

    /// The flag is the route's at each start, not the agent's at launch: a
    /// broker first started with no route peers once it starts again on one.
    #[test]
    fn each_broker_start_takes_zakuro_p2p_from_the_route_of_that_moment() {
        use Action::*;
        let api = FakeBroker::default();
        let mut sup = SupGuard(Supervisor::new(p2p_printing_spec("p2p-each-start")));
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        let off = Desired {
            sharing: false,
            workers: 0,
        };
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![StartBroker]
        );
        assert_eq!(broker_log_lines(&sup, 1), ["ZAKURO_P2P=false"]);
        assert_eq!(
            sup.reconcile(&off, &api, true, Instant::now()),
            vec![StopBroker]
        );

        sup.set_route(RouteKind::Host);
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![StartBroker]
        );
        assert_eq!(
            broker_log_lines(&sup, 2),
            ["ZAKURO_P2P=false", "ZAKURO_P2P=true"]
        );
    }

    /// On the proxy route the sidecar relays 9000..=9010 only; the last
    /// relayed port is still a valid choice.
    #[test]
    fn on_the_proxy_route_the_last_relayed_port_is_still_used() {
        use Action::*;
        let dir = tmp("proxy-range-end");
        let api = FakeBroker::default();
        for p in 9000..=9009 {
            api.blocked_ports.borrow_mut().insert(p);
        }
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        sup.set_route(RouteKind::Proxy);
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![StartBroker]
        );
        assert_eq!(sup.broker_port(), 9010);
    }

    /// With 9000..=9010 all taken, the proxy route never falls back to an
    /// OS-assigned port, which no peer could reach, and says why. The host
    /// route does fall back: `everything_blocked_falls_back_to_an_os_assigned_port`.
    #[test]
    fn on_the_proxy_route_a_full_relay_range_is_broker_port_unrelayable() {
        let dir = tmp("proxy-range-full");
        let api = FakeBroker::default();
        for p in 9000..=9010 {
            api.blocked_ports.borrow_mut().insert(p);
        }
        api.os_pick.set(Some(54321));
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        sup.set_route(RouteKind::Proxy);
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        let now = Instant::now();
        assert_eq!(sup.reconcile(&on, &api, true, now), vec![]);
        assert_eq!(
            *api.os_assigned_port_calls.borrow(),
            0,
            "no OS-assigned port on the proxy route"
        );
        let codes: Vec<String> = sup.problems(now).into_iter().map(|p| p.code).collect();
        assert_eq!(codes, vec!["broker_port_unrelayable".to_string()]);
    }

    #[test]
    fn the_broker_port_range_is_the_relay_range() {
        assert_eq!(
            crate::agent::config::DEFAULT_BROKER_PORT,
            crate::vpn::RELAY_FIRST_PORT
        );
        assert_eq!(BROKER_FALLBACK_START, crate::vpn::RELAY_FIRST_PORT + 1);
        assert_eq!(BROKER_FALLBACK_END, crate::vpn::RELAY_LAST_PORT);
    }

    /// Only the relay range is forwarded, so on the proxy route a preferred
    /// port outside it is skipped, however free. The other routes still use it.
    #[test]
    fn on_the_proxy_route_an_unrelayed_preferred_port_is_skipped() {
        use Action::*;
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        for route in [RouteKind::Proxy, RouteKind::Host, RouteKind::None] {
            let api = FakeBroker::default();
            let mut s = spec(&tmp("unrelayed-preferred"), sh("exec sleep 60"));
            s.preferred_broker_port = 4000;
            let mut sup = SupGuard(Supervisor::new(s));
            sup.set_route(route);
            assert_eq!(
                sup.reconcile(&on, &api, true, Instant::now()),
                vec![StartBroker],
                "{route:?}"
            );
            let port = sup.broker_port();
            if route == RouteKind::Proxy {
                assert!(crate::vpn::relay_covers(port), "{port} on {route:?}");
            } else {
                assert_eq!(port, 4000, "{route:?}");
            }
        }
    }

    /// The agent's own `ZAKURO_P2P` (read by `from_env`) reaches a broker
    /// started on the proxy route and wins over it.
    #[test]
    fn the_agents_own_zakuro_p2p_false_wins_on_the_proxy_route() {
        let mut cfg = crate::agent::config::AgentConfig::from_env_with(|k| {
            (k == "ZAKURO_P2P").then(|| "false".to_string())
        })
        .unwrap();
        // The node key and broker.log go to this test's own scratch dir.
        cfg.state_dir = tmp("p2p-agent-env");
        cfg.dir = cfg.state_dir.join("agent");
        cfg.broker_argv = sh(PRINTS_ZAKURO_P2P);
        assert_eq!(
            p2p_of_a_broker_started_on(RouteKind::Proxy, SpawnSpec::from_config(&cfg)),
            "ZAKURO_P2P=false"
        );
    }

    /// Any change of route kind restarts the broker — its P2P flag, QUIC
    /// choice, port range and advertised endpoint are all fixed at start —
    /// but a change of address within one kind is only re-advertised by the
    /// broker's own node-sync tick.
    #[test]
    fn route_kind_changes_restart_the_broker_address_changes_dont() {
        use Action::*;
        for (from, to, restarts) in [
            (RouteKind::None, RouteKind::Host, true),
            (RouteKind::Host, RouteKind::None, true),
            (RouteKind::Host, RouteKind::Proxy, true),
            (RouteKind::Proxy, RouteKind::Host, true),
            (RouteKind::Proxy, RouteKind::None, true),
            (RouteKind::Host, RouteKind::Host, false),
            (RouteKind::Proxy, RouteKind::Proxy, false),
        ] {
            let tag = format!("route-kind-{}-{}", from.label(), to.label());
            let dir = tmp(&tag);
            let api = FakeBroker::default();
            let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
            let on = Desired {
                sharing: true,
                workers: 0,
            };
            sup.set_route(from);
            assert_eq!(
                sup.reconcile(&on, &api, true, Instant::now()),
                vec![StartBroker],
                "{tag}"
            );
            api.up.set(true);
            assert_eq!(
                sup.reconcile(&on, &api, true, Instant::now()),
                vec![],
                "{tag}"
            );

            sup.set_route(to);
            let want = if restarts { vec![StopBroker] } else { vec![] };
            assert_eq!(
                sup.reconcile(&on, &api, true, Instant::now()),
                want,
                "{tag}"
            );
        }
    }

    /// Moving onto the proxy route restarts the broker (no QUIC, a relayed
    /// port); the next tick starts it again there.
    #[test]
    fn a_route_change_onto_the_proxy_route_restarts_the_broker() {
        use Action::*;
        let dir = tmp("route-change-proxy");
        let api = FakeBroker::default();
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        sup.set_route(RouteKind::Host);
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![StartBroker]
        );
        api.up.set(true);
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![],
            "running on the host route"
        );

        sup.set_route(RouteKind::Proxy);
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![StopBroker]
        );
        api.up.set(false);
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![StartBroker],
            "started again, on the proxy route"
        );
        assert!(crate::vpn::relay_covers(sup.broker_port()));
    }

    /// A broker adopted after an agent restart — started on the host route
    /// with an OS-assigned port, then found running again on the proxy
    /// route — restarts even though `broker_route` never saw the host route:
    /// its port isn't one the mesh relay carries.
    #[test]
    fn an_adopted_broker_on_an_unrelayed_port_restarts_on_the_proxy_route() {
        use Action::*;
        let dir = tmp("adopt-unrelayed");
        let broker_child =
            spawn_in_group(&sh("exec sleep 60"), None, &[], &dir.join("b.log")).unwrap();
        let _guard = PgGuard(broker_child.id());
        let pid = broker_child.id();
        let started = proc_start_time(pid).unwrap_or_default();
        let child_guard = ChildGuard(broker_child);

        let recorded = Children {
            broker: Some(ChildRecord {
                pid,
                started_at: started,
                port: Some(54321),
                container: None,
            }),
            ..Default::default()
        };
        let api = FakeBroker::default();
        api.up.set(true);
        let mut sup = SupGuard(Supervisor::new(spec(&dir, sh("exec sleep 60"))));
        sup.adopt(&recorded, &proc_start_time);
        assert_eq!(sup.broker_port(), 54321);

        sup.set_route(RouteKind::Proxy);
        let on = Desired {
            sharing: true,
            workers: 0,
        };
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![StopBroker],
            "the adopted port isn't relayed"
        );
        api.up.set(false);
        assert_eq!(
            sup.reconcile(&on, &api, true, Instant::now()),
            vec![StartBroker]
        );
        assert!(crate::vpn::relay_covers(sup.broker_port()));
        drop(child_guard);
    }

    // --- container-backed workers (opt-in; issue #263) ---------------------

    /// A `DockerCli` that answers from a script instead of a daemon, and
    /// records every argv it was asked to run. Every container path in the
    /// supervisor is argv in, stdout out (the argv all built by
    /// `crate::up`'s builders, the same ones `zc share` uses), so this drives
    /// all of them in CI on a machine with no Docker at all.
    #[derive(Default)]
    struct FakeDocker {
        calls: std::sync::Mutex<Vec<Vec<String>>>,
        /// The container's `.State.*`, as `docker inspect -f` would print it;
        /// `None` once it has been removed ("No such object").
        state: std::sync::Mutex<Option<String>>,
        /// Whether the in-container `kill -0` probe finds the worker.
        worker_alive: std::sync::Mutex<bool>,
        /// What the worker's own log tail (`/tmp/worker.log`, inside the
        /// container) answers.
        log: std::sync::Mutex<String>,
        /// What `docker logs` answers -- the *image's* output, which is a
        /// different stream entirely, and deliberately different text here so
        /// a test can tell which one a detail came from.
        image_log: std::sync::Mutex<String>,
        /// Whether SIGTERM actually stops this container, or only SIGKILL
        /// does (a worker wedged in a signal handler).
        term_stops: std::sync::Mutex<bool>,
        /// When set, `docker run` fails, as it would with no image pulled.
        run_fails: std::sync::Mutex<bool>,
    }

    impl FakeDocker {
        /// A container that is up with a live worker inside it.
        fn healthy() -> Self {
            let d = Self::default();
            *d.state.lock().unwrap() = Some("true|2026-09-18T07:00:00Z|0".into());
            *d.worker_alive.lock().unwrap() = true;
            *d.term_stops.lock().unwrap() = true;
            *d.log.lock().unwrap() = "worker log line\n".into();
            *d.image_log.lock().unwrap() = "s6-rc: service legacy-services started\n".into();
            d
        }
        fn stop(&self) {
            *self.state.lock().unwrap() = Some("false|2026-09-18T07:00:00Z|137".into());
            *self.worker_alive.lock().unwrap() = false;
        }
        /// Every argv run so far, as space-joined strings.
        fn calls(&self) -> Vec<String> {
            self.calls
                .lock()
                .unwrap()
                .iter()
                .map(|a| a.join(" "))
                .collect()
        }
        fn ran(&self, needle: &str) -> bool {
            self.calls().iter().any(|c| c.contains(needle))
        }
        fn count(&self, needle: &str) -> usize {
            self.calls().iter().filter(|c| c.contains(needle)).count()
        }
    }

    impl DockerCli for FakeDocker {
        fn run(&self, argv: &[String]) -> Result<String, String> {
            self.calls.lock().unwrap().push(argv.to_vec());
            let joined = argv.join(" ");
            let rest: Vec<&str> = argv[1..].iter().map(String::as_str).collect();
            match rest.first().copied() {
                Some("inspect") => self
                    .state
                    .lock()
                    .unwrap()
                    .clone()
                    .ok_or_else(|| "Error: No such object".to_string()),
                Some("network") => Ok(String::new()),
                Some("rm") => {
                    *self.state.lock().unwrap() = None;
                    *self.worker_alive.lock().unwrap() = false;
                    Ok(String::new())
                }
                Some("run") => {
                    if *self.run_fails.lock().unwrap() {
                        return Err("Unable to find image".into());
                    }
                    *self.state.lock().unwrap() = Some("true|2026-09-18T07:00:00Z|0".into());
                    Ok("deadbeef".into())
                }
                Some("logs") => Ok(self.image_log.lock().unwrap().clone()),
                Some("kill") => {
                    let sig = rest.get(2).copied().unwrap_or("");
                    if self.state.lock().unwrap().is_none() {
                        return Err("No such container".into());
                    }
                    if sig == "KILL" || *self.term_stops.lock().unwrap() {
                        self.stop();
                    }
                    Ok(String::new())
                }
                Some("exec") if joined.contains("-d ") => {
                    *self.worker_alive.lock().unwrap() = true;
                    Ok(String::new())
                }
                // Anything exec'd into a stopped/absent container fails the
                // way the real daemon fails it.
                Some("exec")
                    if !self
                        .state
                        .lock()
                        .unwrap()
                        .as_deref()
                        .is_some_and(|s| s.starts_with("true")) =>
                {
                    Err("Container is not running".into())
                }
                Some("exec") if joined.contains("kill -0") => {
                    if *self.worker_alive.lock().unwrap() {
                        Ok(String::new())
                    } else {
                        Err("exit status 1".into())
                    }
                }
                Some("exec") if joined.contains("tail -n") => Ok(self.log.lock().unwrap().clone()),
                _ => Ok(String::new()),
            }
        }
    }

    /// Answers `docker ps` with a canned listing and records every argv;
    /// `rm` of an id in `rm_fails` errors, `fail_all` makes every call fail.
    #[derive(Default)]
    struct SweepDocker {
        ps: String,
        rm_fails: Vec<String>,
        fail_all: bool,
        calls: std::sync::Mutex<Vec<String>>,
    }

    impl DockerCli for SweepDocker {
        fn run(&self, argv: &[String]) -> Result<String, String> {
            let joined = argv.join(" ");
            self.calls.lock().unwrap().push(joined.clone());
            if self.fail_all {
                return Err("docker not available: no such file".into());
            }
            match argv.get(1).map(String::as_str) {
                Some("ps") => Ok(self.ps.clone()),
                Some("inspect") => Ok("true|2026-09-18T07:00:00Z|0".into()),
                Some("rm") if self.rm_fails.iter().any(|id| joined.ends_with(id.as_str())) => {
                    Err("removal in progress".into())
                }
                _ => Ok(String::new()),
            }
        }
    }

    fn removed_ids(d: &SweepDocker) -> Vec<String> {
        d.calls
            .lock()
            .unwrap()
            .iter()
            .filter(|c| c.starts_with("docker rm -f "))
            .map(|c| c.trim_start_matches("docker rm -f ").to_string())
            .collect()
    }

    fn sweeper(dir: &Path, d: Arc<SweepDocker>, adopt: &[&str]) -> Supervisor {
        let mut sup = Supervisor::new(container_spec(dir));
        sup.set_docker(d);
        let mut c = Children::default();
        for (i, name) in adopt.iter().enumerate() {
            c.workers.insert(
                i.to_string(),
                ChildRecord {
                    pid: 0,
                    started_at: "2026-09-18T07:00:00Z".into(),
                    port: None,
                    container: Some((*name).into()),
                },
            );
        }
        sup.adopt(&c, &proc_start_time);
        sup
    }

    #[test]
    fn sweep_removes_an_orphaned_share_container() {
        let dir = tmp("sweep-orphan");
        let d = Arc::new(SweepDocker {
            ps: "aaaa1111bbbb2222cccc\tzc-share-old-w0\n".into(),
            ..Default::default()
        });
        let sup = sweeper(&dir, d.clone(), &[]);
        assert_eq!(sup.sweep_orphans(), vec!["zc-share-old-w0".to_string()]);
        assert_eq!(removed_ids(&d), vec!["aaaa1111bbbb2222cccc".to_string()]);
    }

    #[test]
    fn sweep_keeps_an_adopted_container() {
        let dir = tmp("sweep-adopted");
        let d = Arc::new(SweepDocker {
            ps: "id-kept\tzc-share-testfp00-w0\nid-orphan\tzc-share-testfp00-w1\n".into(),
            ..Default::default()
        });
        let sup = sweeper(&dir, d.clone(), &["zc-share-testfp00-w0"]);
        assert_eq!(sup.children().workers.len(), 1);
        assert_eq!(
            sup.sweep_orphans(),
            vec!["zc-share-testfp00-w1".to_string()]
        );
        assert_eq!(removed_ids(&d), vec!["id-orphan".to_string()]);
    }

    #[test]
    fn sweep_only_lists_by_the_share_label_so_unlabelled_containers_are_untouched() {
        let dir = tmp("sweep-label");
        // The daemon applies the label filter; the fake lists nothing, as
        // it would for a host with only unlabelled containers.
        let d = Arc::new(SweepDocker::default());
        let sup = sweeper(&dir, d.clone(), &[]);
        assert!(sup.sweep_orphans().is_empty());
        assert!(removed_ids(&d).is_empty());
        let calls = d.calls.lock().unwrap().clone();
        let ps = calls.iter().find(|c| c.starts_with("docker ps")).unwrap();
        assert!(ps.contains("label=zakuro.share=1"), "{ps}");
    }

    #[test]
    fn sweep_is_skipped_without_docker() {
        let dir = tmp("sweep-nodocker");
        let d = Arc::new(SweepDocker {
            fail_all: true,
            ..Default::default()
        });
        let sup = sweeper(&dir, d.clone(), &[]);
        assert!(sup.sweep_orphans().is_empty());
        assert!(removed_ids(&d).is_empty());
    }

    #[test]
    fn a_failed_removal_does_not_stop_the_sweep() {
        let dir = tmp("sweep-rmfail");
        let d = Arc::new(SweepDocker {
            ps: "id-a\tzc-share-x-w0\nid-b\tzc-share-x-w1\n".into(),
            rm_fails: vec!["id-a".into()],
            ..Default::default()
        });
        let sup = sweeper(&dir, d.clone(), &[]);
        assert_eq!(sup.sweep_orphans(), vec!["zc-share-x-w1".to_string()]);
        assert_eq!(removed_ids(&d).len(), 2);
    }

    /// A spec whose workers are containers. The worker template is empty on
    /// purpose: nothing on this path may reach `spawn_in_group`.
    fn container_spec(dir: &Path) -> SpawnSpec {
        let mut s = spec(dir, vec![]);
        s.worker_backend = WorkerBackend::Container {
            image: "zakuro-image-compute:latest".into(),
        };
        s.kill_grace = Duration::from_millis(400);
        s
    }

    /// A supervisor on the container backend with `docker` faked, and a
    /// running (host) broker adopted so plans go straight to the workers.
    fn container_sup(dir: &Path, docker: Arc<FakeDocker>) -> (SupGuard, PgGuard) {
        let mut sup = SupGuard(Supervisor::new(container_spec(dir)));
        sup.set_docker(docker);
        let broker_child =
            spawn_in_group(&sh("exec sleep 60"), None, &[], &dir.join("b.log")).unwrap();
        let guard = PgGuard(broker_child.id());
        sup.broker = Some(Proc::spawned(broker_child));
        (sup, guard)
    }

    const ON1: Desired = Desired {
        sharing: true,
        workers: 1,
    };

    /// Starting a container-backed worker runs exactly the argv `zc share`
    /// already runs (`src/up.rs`), in that order, and records the container
    /// as the child -- name and start time instead of pid and start time.
    #[test]
    fn a_container_backed_worker_starts_from_the_argv_zc_share_already_uses() {
        let dir = tmp("ctr-start");
        let docker = Arc::new(FakeDocker::healthy());
        let mut sup = SupGuard(Supervisor::new(container_spec(&dir)));
        sup.set_docker(docker.clone());

        sup.spawn_worker(0, Instant::now()).unwrap();

        let calls = docker.calls();
        assert_eq!(
            calls,
            vec![
                // A leftover container from a crash the agent never got to
                // clean up would own the name and the published port.
                "docker rm -f zc-share-testfp00-w0".to_string(),
                "docker network create zc-worker-testfp00".to_string(),
                crate::up::docker_run_argv(
                    3960,
                    "zakuro-image-compute:latest",
                    "zc-share-testfp00-w0",
                    "zc-worker-testfp00",
                    "testfp00-w0"
                )
                .join(" "),
                crate::up::worker_exec_argv("zc-share-testfp00-w0", 3960, "testfp00-w0", None)
                    .join(" "),
                crate::up::docker_state_argv("zc-share-testfp00-w0").join(" "),
            ]
        );
        assert_eq!(
            sup.children().workers["0"],
            ChildRecord {
                pid: 0,
                started_at: "2026-09-18T07:00:00Z".into(),
                port: None,
                container: Some("zc-share-testfp00-w0".into()),
            }
        );
    }

    /// A `docker run` that fails leaves nothing behind, and is an error the
    /// caller sees -- not a slot that looks started.
    #[test]
    fn a_container_that_cannot_start_leaves_no_slot_and_no_container() {
        let dir = tmp("ctr-start-fail");
        let docker = Arc::new(FakeDocker::healthy());
        *docker.run_fails.lock().unwrap() = true;
        let mut sup = SupGuard(Supervisor::new(container_spec(&dir)));
        sup.set_docker(docker.clone());

        assert!(sup.spawn_worker(0, Instant::now()).is_err());
        assert!(sup.children().workers.is_empty());
        assert!(!docker.ran("docker exec -d"), "{:?}", docker.calls());
    }

    /// Liveness is the *worker process* inside the container, not the
    /// container: `zakuro-image-compute` keeps s6-overlay as PID 1 with its
    /// own services, so `.State.Running` stays true long after the worker
    /// this agent supervises has died. Seeing that as healthy is exactly the
    /// crash-loop outage #263 exists to prevent, one layer down.
    #[test]
    fn a_worker_that_dies_inside_a_still_running_container_is_a_crash() {
        use Action::*;
        let dir = tmp("ctr-crash");
        let docker = Arc::new(FakeDocker::healthy());
        let (mut sup, _pg) = container_sup(&dir, docker.clone());
        let api = FakeBroker::default();
        api.up.set(true);
        let t = Instant::now();
        let at = |ms: u64| t + Duration::from_millis(ms);

        assert_eq!(sup.reconcile(&ON1, &api, true, at(0)), vec![StartWorker(0)]);
        assert_eq!(
            sup.reconcile(&ON1, &api, true, at(100)),
            vec![],
            "the worker is alive inside the container"
        );

        // The worker dies; the container stays up, as it would. Noticed on
        // the first tick past CONTAINER_LIVENESS_TTL -- see the test below.
        *docker.worker_alive.lock().unwrap() = false;
        let removals_before = docker.count("docker rm -f");
        assert_eq!(
            sup.reconcile(&ON1, &api, true, at(5200)),
            vec![],
            "1st failure: 1 s backoff, not an instant restart"
        );
        assert_eq!(
            docker.count("docker rm -f"),
            removals_before + 1,
            "a container whose worker died must not keep publishing the \
             worker's port: {:?}",
            docker.calls()
        );
        assert_eq!(
            sup.reconcile(&ON1, &api, true, at(6300)),
            vec![RestartWorker(0)]
        );
    }

    /// A container's liveness answer costs a Docker round trip, so it is
    /// cached for `CONTAINER_LIVENESS_TTL` rather than asked on every 2 s
    /// reconcile tick -- but never cached across a restart, so a worker that
    /// dies immediately after being spawned is still caught on the next tick.
    #[test]
    fn a_container_is_not_re_probed_on_every_reconcile_tick() {
        let dir = tmp("ctr-probe-rate");
        let docker = Arc::new(FakeDocker::healthy());
        let (mut sup, _pg) = container_sup(&dir, docker.clone());
        let api = FakeBroker::default();
        api.up.set(true);
        let t = Instant::now();
        let at = |ms: u64| t + Duration::from_millis(ms);

        sup.reconcile(&ON1, &api, true, at(0)); // StartWorker(0)
        let probes = |d: &FakeDocker| d.count("kill -0");
        for ms in [100, 2100, 4100] {
            sup.reconcile(&ON1, &api, true, at(ms));
        }
        assert_eq!(
            probes(&docker),
            1,
            "four ticks inside one TTL ask Docker once: {:?}",
            docker.calls()
        );

        sup.reconcile(&ON1, &api, true, at(5200));
        assert_eq!(probes(&docker), 2, "and again once the TTL has passed");
    }

    /// Three crashes in five minutes is a crash loop for a container-backed
    /// worker too, and its detail is the worker's own log -- captured when
    /// the crash is detected, because by report time the container that held
    /// it has been removed.
    #[test]
    fn a_container_crashloop_reports_the_workers_own_log_tail() {
        let dir = tmp("ctr-crashloop");
        let docker = Arc::new(FakeDocker::healthy());
        *docker.log.lock().unwrap() =
            "Traceback (most recent call last)\nRuntimeError: bind refused\n".into();
        let (mut sup, _pg) = container_sup(&dir, docker.clone());
        let api = FakeBroker::default();
        api.up.set(true);
        let t = Instant::now();
        let at = |ms: u64| t + Duration::from_millis(ms);

        // Three start/die rounds, each past the previous backoff.
        for (n, ms) in [0u64, 1300, 3500].iter().enumerate() {
            *docker.worker_alive.lock().unwrap() = true;
            *docker.state.lock().unwrap() = Some("true|2026-09-18T07:00:00Z|0".into());
            sup.reconcile(&ON1, &api, true, at(*ms));
            *docker.worker_alive.lock().unwrap() = false;
            sup.reconcile(&ON1, &api, true, at(ms + 100));
            assert!(n < 3);
        }

        let problems = sup.problems(at(4000));
        let crash = problems
            .iter()
            .find(|p| p.code == "worker_crashloop")
            .expect("3 failures in 5 min");
        let detail = crash.detail.as_deref().unwrap_or("");
        assert!(
            detail.contains("RuntimeError: bind refused"),
            "detail carries the worker's own log, captured before the \
             container that held it was removed: {detail:?}"
        );
        assert!(
            !detail.contains("s6-rc"),
            "and not `docker logs`, which is the image's stream: {detail:?}"
        );
        assert!(
            detail.contains("still up"),
            "and says what the container itself was doing: {detail:?}"
        );
    }

    /// A crash loop is reported for as long as three failures sit inside the
    /// five-minute window, which is mostly time the slot spends *running*
    /// again -- a flapping worker is up between its crashes, and that is
    /// exactly when an owner goes looking at the status screen. A host
    /// worker answers there from a log file that outlived every one of its
    /// crashes. A container-backed one has only the snapshot taken when the
    /// crash was seen, so clearing that snapshot at the next spawn leaves
    /// the crash loop with nothing at all to say for itself in the window
    /// where it is most likely to be read.
    #[test]
    fn a_container_crashloop_still_says_why_once_the_slot_has_restarted() {
        let dir = tmp("ctr-crashloop-up");
        let docker = Arc::new(FakeDocker::healthy());
        *docker.log.lock().unwrap() =
            "Traceback (most recent call last)\nRuntimeError: bind refused\n".into();
        let (mut sup, _pg) = container_sup(&dir, docker.clone());
        let api = FakeBroker::default();
        api.up.set(true);
        let t = Instant::now();
        let at = |ms: u64| t + Duration::from_millis(ms);

        // Three start/die rounds, each past the previous backoff, and then a
        // fourth start that succeeds: the slot is up again, still inside the
        // five-minute crash-loop window.
        for ms in [0u64, 1300, 3500] {
            *docker.worker_alive.lock().unwrap() = true;
            *docker.state.lock().unwrap() = Some("true|2026-09-18T07:00:00Z|0".into());
            sup.reconcile(&ON1, &api, true, at(ms));
            *docker.worker_alive.lock().unwrap() = false;
            sup.reconcile(&ON1, &api, true, at(ms + 100));
        }
        *docker.worker_alive.lock().unwrap() = true;
        *docker.state.lock().unwrap() = Some("true|2026-09-18T07:00:00Z|0".into());
        sup.reconcile(&ON1, &api, true, at(8000));
        assert!(
            sup.slots[&0].proc_.is_some(),
            "the slot must be running again for this test to be about anything"
        );

        let problems = sup.problems(at(8100));
        let crash = problems
            .iter()
            .find(|p| p.code == "worker_crashloop")
            .expect("3 failures in 5 min is still a crash loop while the slot is back up");
        let detail = crash.detail.as_deref().unwrap_or("");
        assert!(
            detail.contains("RuntimeError: bind refused"),
            "a crash loop that has restarted must still carry the last crash's \
             log, not an empty detail: {detail:?}"
        );
    }

    /// When the container dies outright rather than just the worker inside
    /// it, the detail says so and names the exit code -- the one thing
    /// neither log stream can tell you, and often the whole story (137 is a
    /// SIGKILL, usually the host's OOM killer).
    #[test]
    fn a_container_that_died_outright_reports_its_exit_code() {
        let dir = tmp("ctr-exitcode");
        let docker = Arc::new(FakeDocker::healthy());
        let (mut sup, _pg) = container_sup(&dir, docker.clone());
        let api = FakeBroker::default();
        api.up.set(true);
        let t = Instant::now();
        let at = |ms: u64| t + Duration::from_millis(ms);

        for ms in [0u64, 1300, 3500] {
            *docker.state.lock().unwrap() = Some("true|2026-09-18T07:00:00Z|0".into());
            *docker.worker_alive.lock().unwrap() = true;
            sup.reconcile(&ON1, &api, true, at(ms));
            // The whole container is gone this time, not just the worker.
            *docker.state.lock().unwrap() = Some("false|2026-09-18T07:00:00Z|137".into());
            *docker.worker_alive.lock().unwrap() = false;
            sup.reconcile(&ON1, &api, true, at(ms + 100));
        }

        let detail = sup
            .problems(at(4000))
            .into_iter()
            .find(|p| p.code == "worker_crashloop")
            .and_then(|p| p.detail)
            .expect("3 failures in 5 min");
        assert!(detail.contains("exit code 137"), "{detail:?}");
        assert!(
            detail.contains("s6-rc"),
            "a stopped container can't be exec'd into, so the tail falls \
             back to `docker logs`: {detail:?}"
        );
    }

    /// Stopping a container-backed worker keeps the host path's shape:
    /// SIGTERM, wait out the grace period, and only then SIGKILL -- sent to
    /// the container rather than to a process group.
    #[test]
    fn killing_a_container_worker_sigterms_it_and_deletes_it_from_the_broker() {
        use Action::*;
        let dir = tmp("ctr-kill");
        let docker = Arc::new(FakeDocker::healthy());
        let (mut sup, _pg) = container_sup(&dir, docker.clone());
        let api = FakeBroker::default();
        api.up.set(true);
        let t = Instant::now();

        assert_eq!(sup.reconcile(&ON1, &api, true, t), vec![StartWorker(0)]);
        *api.workers.borrow_mut() = vec![bw("id0", "testfp00-w0")];
        let off = Desired {
            sharing: false,
            workers: 1,
        };
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![DrainWorker(0)]);
        assert_eq!(*api.drained.borrow(), vec!["id0".to_string()]);
        assert_eq!(sup.reconcile(&off, &api, true, t), vec![KillWorker(0)]);

        assert!(
            docker.ran("docker kill --signal TERM zc-share-testfp00-w0"),
            "{:?}",
            docker.calls()
        );
        assert!(
            !docker.ran("--signal KILL"),
            "a container that stops on TERM is never SIGKILLed: {:?}",
            docker.calls()
        );
        assert_eq!(*api.deleted.borrow(), vec!["id0".to_string()]);
        assert!(sup.children().workers.is_empty());
    }

    /// ... and a container that does not stop on TERM is SIGKILLed once the
    /// grace period runs out, exactly as a process group that traps SIGTERM
    /// is.
    #[test]
    fn a_container_that_ignores_term_is_sigkilled_after_the_grace_period() {
        let dir = tmp("ctr-stubborn");
        let docker = Arc::new(FakeDocker::healthy());
        *docker.term_stops.lock().unwrap() = false;
        let (mut sup, _pg) = container_sup(&dir, docker.clone());

        sup.spawn_worker(0, Instant::now()).unwrap();
        sup.terminate_all(Duration::from_millis(300));

        assert!(
            docker.ran("docker kill --signal TERM zc-share-testfp00-w0"),
            "{:?}",
            docker.calls()
        );
        assert!(
            docker.ran("docker kill --signal KILL zc-share-testfp00-w0"),
            "{:?}",
            docker.calls()
        );
    }

    /// The agent is shutting down mid-kill: the container is handed back
    /// still only SIGTERMed, for `terminate_all` to finish with its own grace
    /// period, instead of this tick cutting the stop short with a SIGKILL.
    /// Same contract the host path has.
    #[test]
    fn a_stop_flag_set_mid_wait_hands_a_container_back_instead_of_sigkilling_it() {
        let dir = tmp("ctr-stopflag");
        let docker = Arc::new(FakeDocker::healthy());
        *docker.term_stops.lock().unwrap() = false;
        let mut sup = SupGuard(Supervisor::new(container_spec(&dir)));
        sup.set_docker(docker.clone());
        let stop = sup.stop_flag();
        stop.store(true, Ordering::Relaxed);

        sup.spawn_worker(0, Instant::now()).unwrap();
        let p = sup.0.slots.get_mut(&0).unwrap().proc_.take().unwrap();
        let handed_back = terminate(p, Duration::from_secs(30), &stop);

        assert!(handed_back.is_some(), "the container is handed back");
        assert!(docker.ran("--signal TERM"), "{:?}", docker.calls());
        assert!(
            !docker.ran("--signal KILL"),
            "a shutdown must not turn a graceful stop into a kill: {:?}",
            docker.calls()
        );
        sup.0.slots.get_mut(&0).unwrap().proc_ = handed_back;
    }

    /// After an agent restart a container-backed worker is re-adopted when it
    /// is the same *run* of the same container -- the analogue of a live pid
    /// with an unchanged start time. A container recreated under the same
    /// name, or one that has stopped, is not adopted.
    #[test]
    fn a_container_worker_is_re_adopted_only_when_it_is_the_same_run() {
        let dir = tmp("ctr-adopt");
        let recorded = |started_at: &str| {
            let mut c = Children::default();
            c.workers.insert(
                "0".into(),
                ChildRecord {
                    pid: 0,
                    started_at: started_at.into(),
                    port: None,
                    container: Some("zc-share-testfp00-w0".into()),
                },
            );
            c
        };
        let adopted = |docker: Arc<FakeDocker>, started_at: &str| {
            let mut sup = Supervisor::new(container_spec(&dir));
            sup.set_docker(docker);
            sup.adopt(&recorded(started_at), &proc_start_time);
            sup.children().workers.len()
        };

        let up = Arc::new(FakeDocker::healthy());
        assert_eq!(adopted(up.clone(), "2026-09-18T07:00:00Z"), 1);
        assert_eq!(
            adopted(up, "2026-09-18T06:00:00Z"),
            0,
            "a container restarted under the same name is not the one we recorded"
        );

        let stopped = Arc::new(FakeDocker::healthy());
        stopped.stop();
        assert_eq!(adopted(stopped, "2026-09-18T07:00:00Z"), 0);

        let gone = Arc::new(FakeDocker::healthy());
        *gone.state.lock().unwrap() = None;
        assert_eq!(adopted(gone, "2026-09-18T07:00:00Z"), 0);
    }

    /// An agent SIGTERM stops container workers too: nothing this agent
    /// started keeps running (and keeps billing) once it is gone.
    #[test]
    fn terminate_all_stops_container_workers_too() {
        let dir = tmp("ctr-termall");
        let docker = Arc::new(FakeDocker::healthy());
        let mut sup = Supervisor::new(container_spec(&dir));
        sup.set_docker(docker.clone());
        sup.spawn_worker(0, Instant::now()).unwrap();
        sup.spawn_worker(1, Instant::now()).unwrap();

        sup.terminate_all(Duration::from_millis(500));

        assert_eq!(
            docker.count("docker kill --signal TERM"),
            2,
            "{:?}",
            docker.calls()
        );
        assert!(sup.children().workers.is_empty());
    }

    /// The backend is chosen once, from the agent's effective environment, in
    /// the same place the bind-guard env is (`SpawnSpec::from_config`) -- and
    /// `host` is honoured without probing Docker; unset means auto (a
    /// container when Docker is usable), which depends on the machine and so
    /// is covered by `up::select_share_runtime`'s own tests.
    /// Unset means auto: a container when Docker is reachable, the host
    /// process otherwise. The probe is injected, so this never depends on the
    /// machine running the test (`for_dirs` pins `host`, hence the clear).
    #[test]
    fn auto_runtime_picks_the_container_only_when_docker_is_available() {
        let mut cfg = AgentConfig::for_dirs(tmp("ctr-auto"));
        cfg.child_env.clear();
        assert_eq!(
            SpawnSpec::from_config_with(&cfg, &|| true, &|_| true).worker_backend,
            WorkerBackend::Container {
                image: "zakuro-image-compute:latest".into()
            }
        );
        assert_eq!(
            SpawnSpec::from_config_with(&cfg, &|| false, &|_| true).worker_backend,
            WorkerBackend::Host
        );
        // Docker up, image never built: host workers, not a container that
        // fails to start on every tick.
        assert_eq!(
            SpawnSpec::from_config_with(&cfg, &|| true, &|_| false).worker_backend,
            WorkerBackend::Host
        );
    }

    #[test]
    fn the_worker_backend_follows_zakuro_share_runtime() {
        let dir = tmp("ctr-cfg");
        let mut cfg = AgentConfig::for_dirs(dir.clone());
        cfg.child_env
            .push(("ZAKURO_SHARE_RUNTIME".into(), "host".into()));
        assert_eq!(
            SpawnSpec::from_config(&cfg).worker_backend,
            WorkerBackend::Host
        );

        cfg.child_env
            .push(("ZAKURO_SHARE_RUNTIME".into(), "container".into()));
        assert_eq!(
            SpawnSpec::from_config(&cfg).worker_backend,
            WorkerBackend::Container {
                image: "zakuro-image-compute:latest".into()
            }
        );

        cfg.child_env.push((
            "ZC_SHARE_WORKER_IMAGE".into(),
            "zakuroai/compute@sha256:deadbeef".into(),
        ));
        assert_eq!(
            SpawnSpec::from_config(&cfg).worker_backend,
            WorkerBackend::Container {
                image: "zakuroai/compute@sha256:deadbeef".into()
            }
        );

        cfg.child_env
            .push(("ZAKURO_PRICE_PER_HOUR".into(), "0.75".into()));
        assert_eq!(
            SpawnSpec::from_config(&cfg).worker_price.as_deref(),
            Some("0.75")
        );
    }

    /// A host worker is a child process and inherits the agent's
    /// `ZAKURO_PRICE_PER_HOUR`; a container inherits nothing at all, so
    /// without this an agent that priced its machine would have priced only
    /// one of its two backends and quietly left the other on the Python
    /// worker's own 3.6/hour default.
    #[test]
    fn a_container_backed_workers_price_is_written_into_its_exec_line() {
        let dir = tmp("ctr-price");
        let docker = Arc::new(FakeDocker::healthy());
        let mut spec = container_spec(&dir);
        spec.worker_price = Some("0.75".into());
        let mut sup = SupGuard(Supervisor::new(spec));
        sup.set_docker(docker.clone());

        sup.spawn_worker(0, Instant::now()).unwrap();

        assert!(
            docker.ran("ZAKURO_PRICE_PER_HOUR=0.75"),
            "{:?}",
            docker.calls()
        );
    }

    // --- end to end against a real Docker daemon (issue #263) --------------
    //
    // Everything above this line runs anywhere: the container paths are
    // driven by `FakeDocker`, which is exactly what lets them run in CI on a
    // machine with no daemon. These two do the opposite. They drive the real
    // `Supervisor` against the real daemon, the real image and a real `zc
    // broker`, because #301's one acknowledged gap was that nobody had
    // watched the whole loop -- spawn, crash, restart, re-adopt -- actually
    // happen. A fake cannot close that gap by construction: it answers what
    // it was told to answer.
    //
    // They are `#[ignore]`d, so no CI run and no `cargo test` on a developer
    // machine picks them up, and they read their scratch identity from the
    // environment rather than inventing one: `scripts/verify-container-supervision.sh`
    // owns the ports, the fingerprint and the cleanup, and this file owns
    // what is asserted about the supervisor.
    //
    // They are two tests rather than one because the gap *between* them is
    // the point. Phase one leaves its broker and its container running and
    // lets the process exit; phase two is a different OS process that has to
    // re-adopt both from `children.json`. That is what an agent restart is,
    // and running it in one process would not be it.

    fn e2e_var(key: &str) -> String {
        std::env::var(key).unwrap_or_else(|_| {
            panic!(
                "{key} is not set -- these tests are driven by \
                 scripts/verify-container-supervision.sh, not run directly"
            )
        })
    }

    fn e2e_dir() -> PathBuf {
        PathBuf::from(e2e_var("ZC_E2E_DIR"))
    }

    fn e2e_port(key: &str) -> u16 {
        e2e_var(key)
            .parse()
            .unwrap_or_else(|e| panic!("{key} is not a port number: {e}"))
    }

    /// The spec both phases build, identical in both so phase two adopts
    /// what phase one left. Everything that could collide with the agent
    /// already installed on the developer's machine -- both ports, the
    /// fingerprint the container and network names are derived from, the
    /// state directory -- comes from the harness, never from a default.
    fn e2e_spec() -> SpawnSpec {
        let dir = e2e_dir();
        let base_worker_port = e2e_port("ZC_E2E_WORKER_PORT");
        SpawnSpec {
            broker_argv: vec![e2e_var("ZC_E2E_ZC_BIN"), "broker".into(), "{port}".into()],
            broker_env: vec![
                (
                    "ZAKURO_SCAN_RANGE".into(),
                    format!("{base_worker_port}-{}", base_worker_port + 4),
                ),
                ("ZAKURO_SCAN_INTERVAL".into(), "3".into()),
                // No peering: this is a supervision test, and the broker it
                // starts must not go looking for the mesh this Mac is on.
                ("ZAKURO_P2P".into(), "false".into()),
                // The broker is a real `zc` binary, not this test binary, so
                // nothing redirects its state for it: say where it goes, or
                // it writes the developer's own `~/.zakuro`.
                ("ZAKURO_HOME".into(), dir.display().to_string()),
                (
                    "ZAKURO_WAL_PATH".into(),
                    dir.join("wal.jsonl").display().to_string(),
                ),
            ],
            // Empty on purpose: nothing on this backend may reach
            // `spawn_in_group` for a worker.
            worker_template: vec![],
            worker_env: vec![],
            worker_cwd: None,
            worker_backend: WorkerBackend::Container {
                image: e2e_var("ZC_E2E_IMAGE"),
            },
            worker_price: None,
            base_worker_port,
            preferred_broker_port: e2e_port("ZC_E2E_BROKER_PORT"),
            fp8: e2e_var("ZC_E2E_FP8"),
            log_dir: dir,
            // s6-overlay takes about 4.5 s to bring the image down on a
            // SIGTERM (#301 measured it); the spec default is 10 s and this
            // is the same generosity with room for an emulated image.
            kill_grace: Duration::from_secs(30),
            broker_stop_wait: Duration::from_secs(20),
            drain_timeout: Duration::from_secs(300),
        }
    }

    /// One line per assertion, in the harness script's own voice, so a
    /// failing run reads as one story across the shell and the test. Stamped
    /// with seconds since the phase started, because how long the real thing
    /// takes -- an emulated image booting, a liveness answer coming out of
    /// its cache -- is half of what a run of this is evidence of.
    fn e2e_step(what: &str) {
        static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
        let t = START.get_or_init(Instant::now).elapsed().as_secs_f32();
        println!("  [e2e] {t:6.1}s  {what}");
    }

    /// The daemon, through the very `DockerCli` the supervisor shells out
    /// with -- so what the harness sees and what the supervisor sees cannot
    /// be two different things.
    fn e2e_docker(args: &[&str]) -> Result<String, String> {
        let argv: Vec<String> = std::iter::once("docker")
            .chain(args.iter().copied())
            .map(str::to_string)
            .collect();
        DockerShell.run(&argv)
    }

    /// Every container whose name starts with this run's own prefix, and
    /// only those: the machine this runs on has other people's containers on
    /// it.
    fn e2e_containers(prefix: &str) -> Vec<String> {
        e2e_docker(&["ps", "-a", "--format", "{{.Names}}"])
            .unwrap_or_default()
            .lines()
            .map(str::trim)
            .filter(|n| n.starts_with(prefix))
            .map(str::to_string)
            .collect()
    }

    /// Does the worker itself answer? Not the container, not the published
    /// port -- both of those outlive the worker, which is the whole reason
    /// this PR exists.
    fn e2e_health(port: u16) -> bool {
        ureq::Agent::new_with_config(
            ureq::Agent::config_builder()
                .timeout_global(Some(Duration::from_secs(3)))
                .http_status_as_error(false)
                .build(),
        )
        .get(&format!("http://127.0.0.1:{port}/health"))
        .call()
        .is_ok_and(|r| r.status().as_u16() == 200)
    }

    /// One real reconcile tick. The broker API is rebuilt against whatever
    /// port this run's broker actually landed on, exactly as
    /// `Core::reconcile_once` does, and the prerequisites are the real
    /// `plan::prerequisite_problems` over the real cached `docker info`
    /// probe. `logged_in` is the one thing asserted rather than read: the
    /// scratch `ZAKURO_HOME` deliberately holds no credentials, and the hub
    /// is not what this is testing.
    fn e2e_tick(sup: &mut Supervisor) -> Vec<Action> {
        let api = HttpBrokerApi {
            port: sup.broker_port(),
            worker_key: None,
        };
        let prerequisites_ok = plan::prerequisite_problems(
            false,
            false,
            None,
            true,
            false,
            Some(crate::up::docker_cli_available_cached()),
        )
        .is_empty();
        sup.reconcile(&ON1, &api, prerequisites_ok, Instant::now())
    }

    /// Tick until `done`, or fail saying what the last tick planned. Real
    /// ticks at a real interval: the container liveness answer is cached
    /// against the tick's own clock, so time has to actually pass here.
    fn e2e_tick_until(
        sup: &mut Supervisor,
        within: Duration,
        what: &str,
        mut done: impl FnMut(&mut Supervisor, &[Action]) -> bool,
    ) {
        let deadline = Instant::now() + within;
        loop {
            let actions = e2e_tick(sup);
            if !actions.is_empty() {
                println!("  [e2e]   tick planned {actions:?}");
            }
            if done(sup, &actions) {
                return;
            }
            assert!(
                Instant::now() < deadline,
                "timed out after {within:?} waiting for {what}; last tick planned {actions:?}"
            );
            std::thread::sleep(Duration::from_millis(500));
        }
    }

    /// Phase one of the harness: a container-backed worker is started by the
    /// real supervisor, reaches `/health`, and -- when the worker process is
    /// killed *inside* a container that goes on running -- is noticed and
    /// restarted. Leaves the broker and the container running for phase two.
    #[test]
    #[ignore = "real Docker daemon and image; driven by scripts/verify-container-supervision.sh"]
    fn a_container_backed_worker_is_spawned_and_restarted_when_the_worker_dies_inside_its_container(
    ) {
        let spec = e2e_spec();
        let worker_port = spec.base_worker_port;
        let name = crate::up::worker_name(&spec.fp8, 0);
        let container = crate::up::worker_container_name(&name);
        let prefix = format!("zc-share-{}", spec.fp8);
        // Deliberately not a `SupGuard`: phase two is a different process and
        // has to find this broker and this container still running. The
        // harness script is what cleans up if this test fails part way.
        let mut sup = Supervisor::new(spec);

        e2e_step("ASSERT the supervisor starts a broker that answers /health");
        e2e_tick_until(&mut sup, Duration::from_secs(90), "the broker", |s, _| {
            s.broker_running()
        });
        assert!(!sup.broker_unmanaged(), "this broker must be ours to stop");

        e2e_step("ASSERT the worker slot comes up as a container that answers /health");
        e2e_tick_until(
            &mut sup,
            Duration::from_secs(240),
            "the container worker's /health",
            |_, _| e2e_health(worker_port),
        );
        assert_eq!(
            e2e_containers(&prefix),
            vec![container.clone()],
            "exactly one container, named the way `zc share` names it"
        );
        let first = sup.children().workers["0"].clone();
        assert_eq!(first.container.as_deref(), Some(container.as_str()));
        assert_eq!(
            first.pid, 0,
            "a container-backed worker is identified by name, not by pid"
        );
        assert!(
            !first.started_at.is_empty(),
            "the daemon's own StartedAt must be recorded: it is what adoption compares against"
        );

        // Three crash/restart rounds. One would show that the supervisor
        // notices; three is what `plan::is_crashloop` needs, and a crash loop
        // is what #263 was actually filed about, so a harness that stops at
        // one has not been where the bug lives.
        let mut previous_run = first.started_at.clone();
        for round in 1..=3u32 {
            e2e_step(&format!(
                "ASSERT round {round}: killing the worker INSIDE the container leaves the container itself running"
            ));
            let pid = e2e_docker(&["exec", &container, "cat", crate::up::WORKER_CONTAINER_PID])
                .expect("read the worker's recorded pid inside the container");
            let pid = pid.trim().to_string();
            assert!(!pid.is_empty(), "the exec line must have recorded a pid");
            e2e_docker(&["exec", &container, "kill", "-9", &pid])
                .expect("kill the worker process inside the container");
            let raw = e2e_docker(
                &crate::up::docker_state_argv(&container)[1..]
                    .iter()
                    .map(String::as_str)
                    .collect::<Vec<_>>(),
            )
            .expect("inspect the container");
            let state =
                crate::up::parse_container_state(&raw).expect("a parseable container state");
            assert!(
                state.running,
                "the container must still be running after the worker inside it died: \
                 that is precisely the case a `.State.Running` liveness check misses"
            );
            assert!(
                !e2e_health(worker_port),
                "...while the worker itself answers nothing, on a port the container \
                 still publishes"
            );

            e2e_step(&format!(
                "ASSERT round {round}: the supervisor sees the crash and keeps the worker's OWN log"
            ));
            // Tick until the crash is *detected* -- the tick that takes the
            // slot's process away -- rather than until the restart, so the
            // snapshot is read at the moment it is taken.
            e2e_tick_until(
                &mut sup,
                Duration::from_secs(120),
                "the crash to be detected",
                |s, _| s.slots.get(&0).is_some_and(|slot| slot.proc_.is_none()),
            );
            let detail = sup.slots[&0].crash_log.clone().unwrap_or_default();
            assert!(
                detail.contains(&format!(
                    "the worker process is gone from container {container}, which is still up"
                )),
                "the detail must say what the container itself was doing: {detail:?}"
            );
            assert!(
                detail.contains("Uvicorn running on"),
                "...and carry the worker's own /tmp/worker.log, read back with \
                 `docker exec tail` before the container is removed: {detail:?}"
            );
            assert!(
                !detail.contains("s6-rc"),
                "...which is a different stream from `docker logs`, the image's own: {detail:?}"
            );

            e2e_step(&format!(
                "ASSERT round {round}: the slot restarts and answers /health from a new container run"
            ));
            let mut restarted = false;
            e2e_tick_until(
                &mut sup,
                Duration::from_secs(180),
                "a RestartWorker(0)",
                |_, actions| {
                    restarted |= actions.contains(&Action::RestartWorker(0));
                    restarted
                },
            );
            e2e_tick_until(
                &mut sup,
                Duration::from_secs(240),
                "the restarted worker's /health",
                |_, _| e2e_health(worker_port),
            );
            let now_up = sup.children().workers["0"].clone();
            assert_eq!(now_up.container.as_deref(), Some(container.as_str()));
            assert_ne!(
                now_up.started_at, previous_run,
                "a restart is a new run of that container, not the old one re-read"
            );
            assert_eq!(
                e2e_containers(&prefix),
                vec![container.clone()],
                "the restart must leave no second container behind"
            );
            previous_run = now_up.started_at;
        }

        e2e_step(
            "ASSERT three crashes in five minutes are reported as a crash loop that can say why",
        );
        let problems = sup.problems(Instant::now());
        let crash = problems
            .iter()
            .find(|p| p.code == "worker_crashloop")
            .unwrap_or_else(|| panic!("three failures inside five minutes: {problems:?}"));
        let detail = crash.detail.as_deref().unwrap_or("");
        assert!(
            detail.contains("Uvicorn running on"),
            "a crash loop is read while the slot is back up between its crashes, and it \
             must still carry the last crash's log there, not an empty detail: {detail:?}"
        );

        e2e_step(
            "hand over to phase two: write children.json and exit without terminating anything",
        );
        let dir = e2e_dir();
        ensure_dir(&dir).expect("the scratch dir");
        crate::agent::files::save_json(
            &dir.join(crate::agent::files::CHILDREN_FILE),
            &sup.children(),
        )
        .expect("write children.json");
    }

    /// Phase two: a *different process*, which is what an agent restart is.
    /// It re-adopts the broker and the container phase one left running,
    /// starts nothing a second time, and then tears everything down.
    #[test]
    #[ignore = "real Docker daemon and image; driven by scripts/verify-container-supervision.sh"]
    fn a_restarted_agent_re_adopts_the_container_it_left_running_and_then_tears_it_down() {
        let dir = e2e_dir();
        let recorded: Children =
            crate::agent::files::load_json(&dir.join(crate::agent::files::CHILDREN_FILE))
                .expect("phase one's children.json");
        let spec = e2e_spec();
        let worker_port = spec.base_worker_port;
        let name = crate::up::worker_name(&spec.fp8, 0);
        let container = crate::up::worker_container_name(&name);
        let prefix = format!("zc-share-{}", spec.fp8);
        let was = recorded.workers["0"].clone();
        let mut sup = Supervisor::new(spec);

        e2e_step("ASSERT a fresh supervisor re-adopts the container the last one left running");
        sup.adopt(&recorded, &proc_start_time);
        let adopted = sup.children();
        assert_eq!(
            adopted.workers.get("0").and_then(|r| r.container.clone()),
            Some(container.clone()),
            "the container must be re-adopted, not orphaned"
        );
        assert_eq!(
            adopted.workers["0"].started_at, was.started_at,
            "and it must be the same run of it"
        );
        assert!(
            adopted.broker.is_some(),
            "the broker must be re-adopted too, or this agent would start a second one"
        );

        e2e_step("ASSERT a reconcile tick starts nothing a second time");
        let actions = e2e_tick(&mut sup);
        assert!(
            sup.broker_running(),
            "the re-adopted broker must answer /health (unmanaged={})",
            sup.broker_unmanaged()
        );
        assert!(
            !actions
                .iter()
                .any(|a| matches!(a, Action::StartWorker(_) | Action::RestartWorker(_))),
            "a re-adopted worker must not be started again: {actions:?}"
        );
        assert_eq!(
            e2e_containers(&prefix),
            vec![container.clone()],
            "still exactly one container"
        );
        assert!(
            e2e_health(worker_port),
            "the re-adopted worker must still be the one answering /health"
        );

        e2e_step("ASSERT terminate_all leaves no container and nothing on either port");
        let broker_port = sup.broker_port();
        sup.terminate_all(Duration::from_secs(90));
        assert!(
            wait_until(|| e2e_containers(&prefix).is_empty()),
            "containers left behind: {:?}",
            e2e_containers(&prefix)
        );
        assert!(
            wait_until(|| !crate::up::is_port_open(worker_port)),
            "something still holds the worker port {worker_port}"
        );
        assert!(
            wait_until(|| !crate::up::is_port_open(broker_port)),
            "something still holds the broker port {broker_port}"
        );
    }
}