zc2 0.0.53

P2P compute broker with yen-denominated 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
//! Worker launcher for `zc up --workers n`.
//!
//! Starts n Zakuro Python workers on consecutive ports, spins up a local
//! broker, and blocks until Ctrl-C — cleaning up all child processes on exit.

use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};
use std::time::{Duration, Instant};

use colored::Colorize;

pub(crate) const BASE_WORKER_PORT: u16 = 3960;
const DEFAULT_BROKER_PORT: u16 = 9000;
const WORKER_STARTUP_TIMEOUT_SECS: u64 = 20;

struct WorkerHandle {
    port: u16,
    name: String,
    backend: WorkerBackend,
}

impl WorkerHandle {
    /// A human-readable process identity for status lines: the PID for a
    /// host worker, the container name for a container-backed one.
    fn identity(&self) -> String {
        match &self.backend {
            WorkerBackend::Host(c) => format!("PID {}", c.id()),
            WorkerBackend::Container(name) => format!("container {name}"),
        }
    }

    /// Non-blocking: has this worker already exited/stopped? `Some(desc)`
    /// with a short description if so.
    fn exited(&mut self) -> Option<String> {
        match &mut self.backend {
            WorkerBackend::Host(c) => match c.try_wait() {
                Ok(Some(status)) => Some(status.to_string()),
                _ => None,
            },
            WorkerBackend::Container(name) => {
                // `docker inspect -f {{.State.Running}}` is false (or the
                // command errors, e.g. the container is already gone) once
                // it has stopped. `--rm` means a stopped container also
                // disappears, so a lookup failure counts as "exited" too.
                let out = engine_command(&["inspect", "-f", "{{.State.Running}}", name])
                    .and_then(|mut c| c.output().map_err(|e| e.to_string()));
                match out {
                    Ok(o) if o.status.success() => {
                        let running = String::from_utf8_lossy(&o.stdout).trim() == "true";
                        (!running).then(|| "container stopped".to_string())
                    }
                    _ => Some("container no longer exists".to_string()),
                }
            }
        }
    }
}

impl Drop for WorkerHandle {
    fn drop(&mut self) {
        // A container must never outlive its supervisor by accident: this
        // Drop is what makes `zc share`/`zc up` (foreground) stop the
        // container the same moment it would kill a host process. Daemon
        // mode (`zc up -d`) intentionally skips this via `mem::forget`, for
        // both backends alike, so a background share keeps running exactly
        // like it does today for host workers.
        match &mut self.backend {
            WorkerBackend::Host(child) => {
                let _ = child.kill();
            }
            WorkerBackend::Container(name) => {
                if let Ok(mut c) = engine_command(&["stop", "-t", "5", name]) {
                    let _ = c
                        .stdout(std::process::Stdio::null())
                        .stderr(std::process::Stdio::null())
                        .status();
                }
            }
        }
    }
}

/// Parse args for `zc up [--workers N] [--port BASE] [--broker-port PORT] [-d]`.
/// Returns (workers, base_port, broker_port, daemon).
pub fn parse_args(args: &[String]) -> (usize, u16, u16, bool) {
    let mut workers = 1usize;
    let mut base_port = BASE_WORKER_PORT;
    let mut broker_port = DEFAULT_BROKER_PORT;
    let mut daemon = false;

    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--workers" | "-w" | "-n" => {
                if let Some(v) = args.get(i + 1) {
                    workers = v.parse().unwrap_or(1);
                    i += 2;
                    continue;
                }
            }
            "--port" | "-p" => {
                if let Some(v) = args.get(i + 1) {
                    base_port = v.parse().unwrap_or(BASE_WORKER_PORT);
                    i += 2;
                    continue;
                }
            }
            "--broker-port" | "-b" => {
                if let Some(v) = args.get(i + 1) {
                    broker_port = v.parse().unwrap_or(DEFAULT_BROKER_PORT);
                    i += 2;
                    continue;
                }
            }
            "-d" | "--daemon" | "--background" => {
                daemon = true;
            }
            // Short forms: `--workers=N`
            s if s.starts_with("--workers=") => {
                workers = s.trim_start_matches("--workers=").parse().unwrap_or(1);
            }
            _ => {}
        }
        i += 1;
    }

    (workers, base_port, broker_port, daemon)
}

/// Check whether a TCP port is open (i.e. something is listening).
pub fn is_port_open(port: u16) -> bool {
    TcpStream::connect_timeout(
        &format!("127.0.0.1:{}", port).parse().unwrap(),
        Duration::from_millis(150),
    )
    .is_ok()
}

/// A `ZAKURO_WORKER_DIR` setting (from the process environment or the zc
/// dir's `env` file) that pointed at a directory missing
/// `zakuro/worker/server.py`. `None` when no such setting was present at all
/// (the search just came up empty).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZakuroDirMissing {
    pub invalid_setting: Option<String>,
}

impl ZakuroDirMissing {
    /// The `summary.rs` problem detail: `null` when no `ZAKURO_WORKER_DIR`
    /// setting was present, otherwise naming the bad one.
    pub fn detail(&self) -> Option<String> {
        self.invalid_setting
            .as_ref()
            .map(|p| format!("ZAKURO_WORKER_DIR={p} has no zakuro/worker/server.py"))
    }
}

fn is_valid_zakuro_dir(p: &Path) -> bool {
    p.join("zakuro/worker/server.py").exists()
}

/// Pure lookup, in order:
///   1. `env_worker_dir` (`ZAKURO_WORKER_DIR` from the process environment).
///   2. `file_worker_dir` (the same key from `<zc dir>/env`).
///   3. `<zc_dir>/zak-zakuro`.
///   4. `legacy_candidates`, in order (normally `../zak-zakuro` next to the
///      cwd, `/opt/code/ZAK/zak-zakuro`, then `<home>/zak-zakuro` -- see
///      [`legacy_zakuro_dir_candidates_from_env`]).
///
/// An invalid `ZAKURO_WORKER_DIR` setting (1 or 2) does not stop the search:
/// later candidates are still tried. If nothing is found, the first invalid
/// setting seen (env before file) is carried in the error, so the caller can
/// say which one was wrong.
///
/// Every input is a value, not a live lookup: nothing here reads `$HOME`,
/// the cwd or any environment variable, so a caller (a test, in particular)
/// controls every candidate this can possibly find.
pub fn resolve_zakuro_dir(
    env_worker_dir: Option<String>,
    file_worker_dir: Option<String>,
    zc_dir: Option<&Path>,
    legacy_candidates: &[PathBuf],
) -> Result<PathBuf, ZakuroDirMissing> {
    let mut invalid_setting = None;
    for v in [env_worker_dir, file_worker_dir].into_iter().flatten() {
        if v.is_empty() {
            continue;
        }
        let p = PathBuf::from(&v);
        if is_valid_zakuro_dir(&p) {
            return Ok(p);
        }
        invalid_setting.get_or_insert(v);
    }
    if let Some(zc) = zc_dir {
        let p = zc.join("zak-zakuro");
        if is_valid_zakuro_dir(&p) {
            return Ok(p);
        }
    }
    legacy_candidates
        .iter()
        .find(|c| is_valid_zakuro_dir(c))
        .cloned()
        .ok_or(ZakuroDirMissing { invalid_setting })
}

/// The three legacy candidates, in their original order: `../zak-zakuro`
/// next to the cwd, `/opt/code/ZAK/zak-zakuro`, then `<home>/zak-zakuro`.
///
/// This is the ONLY place that reads the real `$HOME` and cwd for the
/// worker-dir lookup, and it is called once, when `AgentConfig::from_env`
/// builds the config -- not on every reconcile tick. Per-tick freshness
/// still holds, because [`resolve_zakuro_dir`] re-checks each candidate
/// path's contents on every call; only the set of *paths* to check is fixed
/// at startup, which is what makes `AgentConfig::for_dirs` (and therefore
/// every test that doesn't call `from_env`) immune to the host's real
/// `$HOME`, cwd or `/opt/code/ZAK` checkout.
pub fn legacy_zakuro_dir_candidates_from_env() -> Vec<PathBuf> {
    let mut out = Vec::new();
    if let Some(parent) = std::env::current_dir()
        .ok()
        .and_then(|d| d.parent().map(PathBuf::from))
    {
        out.push(parent.join("zak-zakuro"));
    }
    out.push(PathBuf::from("/opt/code/ZAK/zak-zakuro"));
    if let Some(h) = std::env::var_os("HOME") {
        out.push(PathBuf::from(h).join("zak-zakuro"));
    }
    out
}

/// The real lookup that feeds [`resolve_zakuro_dir`] for a given zc dir.
///
/// `env_worker_dir` (`ZAKURO_WORKER_DIR` from the process environment),
/// `zc_dir` (`crate::credentials::dir()` for `zc up`, `AgentConfig::state_dir`
/// for the agent) and `legacy_candidates` (see
/// [`legacy_zakuro_dir_candidates_from_env`]) are all values the caller
/// already resolved -- never re-derived here, and never re-read from the
/// live environment on each call. That is what lets `Core::reconcile_once`
/// call this every reconcile tick without depending on whatever the host
/// process happens to export: `AgentConfig::from_env` captures
/// `env_worker_dir` once, and `for_dirs` leaves it `None`.
///
/// `<zc_dir>/env` (only the `ZAKURO_WORKER_DIR` key -- the agent must never
/// load credentials into its own environment) IS still read live, every
/// call: that file is meant to be hand-editable while the agent runs.
pub(crate) fn resolve_zakuro_dir_for(
    env_worker_dir: Option<String>,
    zc_dir: Option<&Path>,
    legacy_candidates: &[PathBuf],
) -> Result<PathBuf, ZakuroDirMissing> {
    let file_worker_dir = zc_dir
        .and_then(|d| std::fs::read_to_string(d.join("env")).ok())
        .and_then(|text| {
            crate::credentials::parse(&text)
                .get("ZAKURO_WORKER_DIR")
                .cloned()
        });
    resolve_zakuro_dir(env_worker_dir, file_worker_dir, zc_dir, legacy_candidates)
}

/// Locate the zak-zakuro Python package directory, for `zc up`. See
/// [`resolve_zakuro_dir`] for the lookup order.
pub(crate) fn find_zakuro_dir() -> Option<PathBuf> {
    let zc_dir = crate::credentials::dir();
    resolve_zakuro_dir_for(
        std::env::var("ZAKURO_WORKER_DIR").ok(),
        zc_dir.as_deref(),
        &legacy_zakuro_dir_candidates_from_env(),
    )
    .ok()
}

/// `{fp8}-w{i}`: stable per index, unique across a user's Macs (the hub keys
/// worker rows by `(user_id, worker_id)` and `worker_id` is this name).
pub(crate) fn worker_name(node_fingerprint: &str, index: usize) -> String {
    let fp8: String = node_fingerprint.chars().take(8).collect();
    format!("{fp8}-w{index}")
}

/// The Python worker command line, shared with `zc agent`'s supervisor.
/// `zakuro.worker.server` imports fastapi, which (with uvicorn, aioquic,
/// PyJWT, psutil and bsdiff4) is only in the zakuro repo's optional `worker`
/// extra, and a plain `uv run` doesn't install extras.
pub(crate) fn worker_argv(port: u16, name: &str) -> Vec<String> {
    [
        "uv",
        "run",
        "--extra",
        "worker",
        "python",
        "-m",
        "zakuro.worker.server",
        "--port",
    ]
    .iter()
    .map(|s| s.to_string())
    .chain([
        port.to_string(),
        "--worker-name".to_string(),
        name.to_string(),
    ])
    .collect()
}

/// The env a spawned zakuro worker needs to start at all. Since zakuro#248
/// the worker refuses a non-loopback bind unless something authenticates its
/// callers, and its default host is `0.0.0.0`, so a worker started with no
/// caller auth binds `127.0.0.1`, where the broker on this machine reaches
/// it. An operator's own `ZAKURO_HOST`, caller auth or
/// `ZAKURO_INSECURE_BIND=1` (a trusted mesh) is left alone. The checks mirror
/// `zakuro/worker/posture.py`.
pub(crate) fn worker_bind_env(
    get: &dyn Fn(&str) -> Option<String>,
) -> Option<(&'static str, &'static str)> {
    let val = |k: &str| get(k).map(|v| v.trim().to_lowercase()).unwrap_or_default();
    let truthy = |k: &str| matches!(val(k).as_str(), "1" | "true" | "yes");
    let chosen = !val("ZAKURO_HOST").is_empty()
        || truthy("ZAKURO_INSECURE_BIND")
        || truthy("ZAKURO_AUTH_REQUIRED")
        || !val("ZAKURO_CERT_DIR").is_empty()
        || val("ZAKURO_WIRE") == "v1";
    (!chosen).then_some(("ZAKURO_HOST", "127.0.0.1"))
}

/// Parse `--price <yen/hour>` (or `--price=<v>`) out of `zc up` / `zc share`
/// args.
///
/// Fallible on purpose, unlike everything in [`parse_args`], which resolves a
/// bad value to its default with `unwrap_or`. That is fine for `--workers
/// abc`: you get one worker and can see it. It is not fine for a price --
/// silently falling back would share the machine at a rate its owner did not
/// choose and has no reason to suspect, which is the one mistake this flag
/// exists to prevent.
///
/// Zero is allowed: donating compute is a legitimate choice. Negative and
/// non-finite are not.
pub fn parse_price_arg(args: &[String]) -> Result<Option<f64>, String> {
    let mut raw: Option<&str> = None;
    let mut i = 0;
    while i < args.len() {
        let a = args[i].as_str();
        if a == "--price" {
            raw = Some(args.get(i + 1).map(String::as_str).unwrap_or(""));
            i += 2;
            continue;
        }
        if let Some(v) = a.strip_prefix("--price=") {
            raw = Some(v);
        }
        i += 1;
    }
    let Some(raw) = raw else { return Ok(None) };
    let v: f64 = raw
        .trim()
        .parse()
        .map_err(|_| format!("invalid --price {raw:?}: expected a number of yen per hour"))?;
    if !v.is_finite() || v < 0.0 {
        return Err(format!("invalid --price {raw:?}: must be zero or more"));
    }
    Ok(Some(v))
}

/// Resolve `--price` for the workers this process is about to spawn, and
/// publish it so both backends see it: a host worker inherits this process's
/// environment, and [`worker_exec_argv`] reads the same variable to write it
/// into a container's exec line.
///
/// Exits on a malformed price rather than sharing the machine at a rate its
/// owner did not pick. Prints the rate on success, because the whole point of
/// the flag is that the owner can see what they are advertising -- the
/// previous behaviour advertised a per-hour default from the Python
/// worker, which nothing in this CLI mentioned.
pub fn apply_price_arg(args: &[String]) -> Option<f64> {
    match parse_price_arg(args) {
        Err(msg) => {
            eprintln!("{msg}");
            std::process::exit(2);
        }
        Ok(None) => None,
        Ok(Some(v)) => {
            std::env::set_var("ZAKURO_PRICE_PER_HOUR", format!("{v}"));
            println!("Offering this machine at {v} yen/hour.");
            Some(v)
        }
    }
}

/// The price a shared worker should advertise, as an env pair, or `None` to
/// leave the worker's own default alone.
///
/// An explicit `--price` wins; otherwise a `ZAKURO_PRICE_PER_HOUR` already in
/// the environment is passed through. That pass-through is not redundant: a
/// host worker is a child process and inherits it for free, but a container
/// worker inherits nothing, so without this the same env var silently priced
/// one backend and not the other.
///
/// The value is what `zakuro/worker/server.py`'s `/info` reads (it defaults to
/// `3.6` when unset, which is where every unpriced worker's rate comes from).
pub(crate) fn worker_price_env(
    get: &dyn Fn(&str) -> Option<String>,
    flag: Option<f64>,
) -> Option<(&'static str, String)> {
    let key = "ZAKURO_PRICE_PER_HOUR";
    if let Some(v) = flag {
        return Some((key, format!("{v}")));
    }
    get(key)
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
        .map(|v| (key, v))
}

/// Where a `zc share` / `zc up` worker runs. The seam #388 (container
/// supervision) builds on: everything that differs between the two lives
/// behind this enum, and [`select_share_runtime`] is the only place that
/// chooses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ShareRuntime {
    /// A host `uv run` process from the zakuro checkout.
    Host,
    /// A container from the same image `zc mesh up` runs.
    Container,
}

/// The outcome of [`select_share_runtime`]: the runtime, plus the one-line
/// warning to print when it is the host process *because* a container was
/// not possible or was opted out of.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RuntimeChoice {
    pub runtime: ShareRuntime,
    pub warning: Option<String>,
}

/// Pick the worker runtime (issue #387, part of #263, zc#578). Pure: the
/// environment is `get`, and the container backend is probed through
/// `backend_available` (any isolating backend: Incus, Docker, see
/// [`crate::sandbox::engine`]), called only when the answer depends on it.
///
/// `ZAKURO_SHARE_RUNTIME`:
/// - unset / `auto`: the container when a backend is usable and the worker
///   image is in it (`image_available`). Otherwise an ERROR that says what to
///   install or build: `auto` never degrades to a host process, which has no
///   cpu or memory cap and no boundary. The worker image is built locally,
///   not pulled, so "backend up, image missing" is an error too;
/// - `host`: the host process, with a loud warning that nothing isolates it
///   (the owner's own work only);
/// - `container`: the container, `Err` when no backend is usable.
///
/// The earlier opt-in `ZC_SHARE_CONTAINER` still works when
/// `ZAKURO_SHARE_RUNTIME` is unset: truthy forces `container`, `0`/`false`/
/// `no` forces `host`.
pub(crate) fn select_share_runtime(
    get: &dyn Fn(&str) -> Option<String>,
    backend_available: &dyn Fn() -> bool,
    image_available: &dyn Fn() -> bool,
) -> Result<RuntimeChoice, String> {
    let norm = |k: &str| {
        get(k)
            .map(|v| v.trim().to_lowercase())
            .filter(|v| !v.is_empty())
    };
    let mode = match norm("ZAKURO_SHARE_RUNTIME").as_deref() {
        Some("auto") => "auto",
        Some("host") => "host",
        Some("container") => "container",
        Some(other) => {
            return Err(format!(
                "ZAKURO_SHARE_RUNTIME={other:?} is not one of auto, host, container"
            ))
        }
        None => match norm("ZC_SHARE_CONTAINER").as_deref() {
            Some("1") | Some("true") | Some("yes") => "container",
            Some("0") | Some("false") | Some("no") => "host",
            _ => "auto",
        },
    };
    match mode {
        "host" => Ok(RuntimeChoice {
            runtime: ShareRuntime::Host,
            warning: Some(
                "worker runtime: HOST PROCESS, NO ISOLATION and no cpu/memory cap                  (ZAKURO_SHARE_RUNTIME=host); for the owner's own work only"
                    .to_string(),
            ),
        }),
        "container" => {
            if backend_available() {
                Ok(RuntimeChoice {
                    runtime: ShareRuntime::Container,
                    warning: None,
                })
            } else {
                Err(container_worker_refusal_message())
            }
        }
        _ => {
            if !backend_available() {
                Err(no_backend_refusal_message())
            } else if !image_available() {
                Err(format!(
                    "the worker image {} is not in the container backend and pulling it failed \
                     (see above), and `auto` does not fall back to a host process. Check the \
                     backend can reach its registry, point ZC_SHARE_WORKER_IMAGE at an image it \
                     has, or set ZAKURO_SHARE_RUNTIME=host to run with no isolation",
                    worker_container_image(get)
                ))
            } else {
                Ok(RuntimeChoice {
                    runtime: ShareRuntime::Container,
                    warning: None,
                })
            }
        }
    }
}

/// `auto` found no isolating backend: what to install, and the explicit,
/// loudly-labelled escape.
pub(crate) fn no_backend_refusal_message() -> String {
    format!(
        "worker runtime: {}",
        crate::sandbox::engine::no_backend_message(&crate::sandbox::Selection {
            chosen: None,
            tried: vec![],
        })
    )
}

/// `docker …` on the active container backend (see [`crate::sandbox::engine`]).
fn engine_command(args: &[&str]) -> Result<Command, String> {
    let argv: Vec<String> = args.iter().map(|a| a.to_string()).collect();
    crate::sandbox::engine::command(&argv)
}

/// Whether `image` is in the active container backend (`docker image
/// inspect`). [`worker_image_ready`] pulls a missing one.
pub(crate) fn docker_image_present(image: &str) -> bool {
    engine_command(&["image", "inspect", "--format", "{{.Id}}", image])
        .and_then(|mut c| {
            c.stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status()
                .map_err(|e| e.to_string())
        })
        .is_ok_and(|s| s.success())
}

/// How the worker image got into the sandbox ([`ensure_image_in_sandbox`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ImageLoad {
    AlreadyThere,
    /// `docker save` on the host, `nerdctl load` in the sandbox.
    LoadedFromHostDocker,
    /// Pulled from its registry inside the sandbox.
    Pulled,
}

/// Get `image` into the shared LXC sandbox when it is not there (zc#593): the
/// opt-in T1 sandbox has its own image store, and the worker image is built
/// on the host, so a `docker save | nerdctl load` is the way in when host
/// Docker has it, else a pull from the image's registry. Pure: every probe
/// and action is injected. Only the LXC sandbox is loaded into; Docker and the
/// VM backends keep the "build it there" error.
pub(crate) fn ensure_image_in_sandbox(
    image: &str,
    sandbox_is_lxc: bool,
    present: &dyn Fn(&str) -> bool,
    host_docker_has: &dyn Fn(&str) -> bool,
    save_load: &dyn Fn(&str) -> Result<(), String>,
    pull: &dyn Fn(&str) -> Result<(), String>,
) -> Result<ImageLoad, String> {
    if present(image) {
        return Ok(ImageLoad::AlreadyThere);
    }
    if !sandbox_is_lxc {
        return Err(format!("{image} is not in the container backend"));
    }
    let (how, r) = if host_docker_has(image) {
        (ImageLoad::LoadedFromHostDocker, save_load(image))
    } else {
        (ImageLoad::Pulled, pull(image))
    };
    r.map_err(|e| format!("loading {image} into the sandbox failed: {e}"))?;
    if present(image) {
        Ok(how)
    } else {
        Err(format!(
            "{image} is still not in the sandbox after loading it"
        ))
    }
}

/// [`docker_image_present`], getting the image into the backend first when it
/// is missing: loaded into the shared LXC sandbox from host Docker or pulled
/// there (zc#593), and pulled from its registry on every other backend. What
/// `auto` asks, so a fresh install (the Desktop app on a Mac, whose Lima VM
/// starts with an empty image store) never needs a manual `docker pull`.
pub(crate) fn worker_image_ready(image: &str) -> bool {
    let lxc = crate::sandbox::engine::active()
        .engine
        .as_ref()
        .is_some_and(|e| e.is_lxc());
    if docker_image_present(image) {
        return true;
    }
    if !lxc {
        eprintln!("  Worker image {image} is not in the container backend; pulling it (first run only) ...");
        return match pull_image(image, APPLE_SILICON, &engine_pull) {
            Ok(()) if docker_image_present(image) => {
                eprintln!("  Worker image {image} pulled.");
                true
            }
            Ok(()) => {
                eprintln!("  {image} is still not in the container backend after pulling it");
                false
            }
            Err(e) => {
                eprintln!("  pulling {image} failed: {e}");
                false
            }
        };
    }
    eprintln!("  Worker image {image} is not in the sandbox; loading it (first run only) ...");
    match ensure_image_in_sandbox(
        image,
        true,
        &docker_image_present,
        &crate::sandbox::engine::host_docker_has_image,
        &crate::sandbox::engine::host_docker_save_into_sandbox,
        &|i| engine_pull(&["pull", i]),
    ) {
        Ok(how) => {
            eprintln!("  Worker image ready in the sandbox ({how:?}).");
            true
        }
        Err(e) => {
            eprintln!("  {e}");
            false
        }
    }
}

/// An Apple-silicon Mac: every container backend here (Lima and Colima with
/// Rosetta, Docker Desktop) runs `linux/amd64` images under emulation.
const APPLE_SILICON: bool = cfg!(all(target_os = "macos", target_arch = "aarch64"));

/// The platform a backend that can emulate it falls back to when an image
/// has no build for the machine's own architecture.
pub(crate) const EMULATED_PLATFORM: &str = "linux/amd64";

/// `docker <args>` on the active backend; `Err` carries what it printed, so
/// [`pull_image`] can tell a platform mismatch from any other failure.
fn engine_pull(args: &[&str]) -> Result<(), String> {
    let out = engine_command(args)?
        .stdin(std::process::Stdio::null())
        .output()
        .map_err(|e| e.to_string())?;
    if out.status.success() {
        Ok(())
    } else {
        let msg = String::from_utf8_lossy(&out.stderr).trim().to_string();
        Err(if msg.is_empty() {
            format!("`{}` failed", args.join(" "))
        } else {
            msg
        })
    }
}

/// Pull `image`, retrying as [`EMULATED_PLATFORM`] when the registry has no
/// build for this machine's architecture and the backend can emulate one
/// (`can_emulate`: an Apple-silicon Mac). The published compute image is
/// amd64-only, and nerdctl in the Lima VM refuses it outright ("no match for
/// platform in manifest") unless asked for that platform.
pub(crate) fn pull_image(
    image: &str,
    can_emulate: bool,
    pull: &dyn Fn(&[&str]) -> Result<(), String>,
) -> Result<(), String> {
    match pull(&["pull", image]) {
        Err(e) if can_emulate && is_platform_mismatch(&e) => {
            pull(&["pull", "--platform", EMULATED_PLATFORM, image])
        }
        r => r,
    }
}

/// nerdctl's and Docker's ways of saying the image has no build for the
/// requested (default: native) platform.
pub(crate) fn is_platform_mismatch(e: &str) -> bool {
    e.contains("no match for platform") || e.contains("no matching manifest")
}

/// The image a container-backed worker runs: [`DEFAULT_SHARE_WORKER_IMAGE`],
/// the published compute image, so any backend can pull it on a fresh
/// install. It used to be `zakuro-image-compute:latest`, the tag `zc mesh up`
/// builds locally: nothing publishes that name, so on a machine that never
/// built it (every Desktop install) the pull went to Docker Hub's `library/`
/// namespace and was refused, and no worker ever started.
/// `ZC_SHARE_WORKER_IMAGE` overrides it -- a locally built tag, or
/// `name@sha256:...` to pin a digest instead of trusting a moving tag.
/// The published CPU build of the compute image (`zakuro-image`'s release
/// tag on Docker Hub). Share workers never get a GPU off Linux, and on Linux
/// `ZC_SHARE_WORKER_IMAGE` picks a GPU build where one is wanted.
pub(crate) const DEFAULT_SHARE_WORKER_IMAGE: &str = "zakuroai/compute:cpu";

pub(crate) fn worker_container_image(get: &dyn Fn(&str) -> Option<String>) -> String {
    get("ZC_SHARE_WORKER_IMAGE").unwrap_or_else(|| DEFAULT_SHARE_WORKER_IMAGE.to_string())
}

/// Deterministic, namespaced container name for worker `name`: lets the
/// launching process (and a human running `docker ps`/`docker stop` by hand)
/// find this container unambiguously, and keeps it out of the way of any
/// container `zc mesh up` starts.
pub(crate) fn worker_container_name(name: &str) -> String {
    format!("zc-share-{name}")
}

/// Deterministic per-node network name: the same one every worker on this
/// machine shares (idempotent create via [`docker_network_create_argv`]),
/// derived from `name`'s leading fp8 by convention (see `worker_name`) so it
/// doesn't churn across restarts.
///
/// Not the default bridge: `zakuro-wg` and every `zc mesh up` compute node
/// already sit there, so a worker container joining it by default would be
/// reachable -- unauthenticated `/execute` and all -- from anything else
/// running on the host, not just from this host's own loopback publish.
/// That is exactly the surface zakuro#248's bind guard exists to close, and
/// `ZAKURO_INSECURE_BIND=1` (see [`worker_exec_argv`]) is only a defensible
/// trade for it when the container's network is actually this narrow.
pub(crate) fn worker_network_name(name: &str) -> String {
    let fp8: String = name.chars().take(8).collect();
    format!("zc-worker-{fp8}")
}

/// `docker network create <name>`: run before [`docker_run_argv`], ignoring
/// failure (the network may already exist from a previous worker on this
/// machine; a real Docker problem surfaces from the `docker run` that
/// follows instead).
pub(crate) fn docker_network_create_argv(name: &str) -> Vec<String> {
    vec![
        "docker".to_string(),
        "network".to_string(),
        "create".to_string(),
        name.to_string(),
    ]
}

/// The `docker run` argv that starts the container itself, *without*
/// overriding its command. `zakuro-image-compute` boots its own s6-managed
/// entrypoint (dashboard, Ray, Spark, Jupyter -- see `mesh.rs::up`, which
/// runs this same image); overriding CMD with the worker's own argv (as an
/// earlier version of this function did) fights that entrypoint instead of
/// using it, and a manual `docker run` against the real image confirms it:
/// the container comes up with its own services, not the worker. The worker
/// itself is started afterwards with [`worker_exec_argv`], exactly the way
/// `zc mesh up` already does it via `docker exec -d`.
///
/// Reachability (issue #263): published only to `127.0.0.1:<port>` on the
/// host -- never `0.0.0.0:<port>`, which would expose it to the LAN -- and
/// the container runs on `network_name` (see [`worker_network_name`]), a
/// network scoped to this one worker, not the shared default bridge every
/// other zc container sits on. Deliberately *not* `--internal`: verified by
/// hand against Docker Desktop for Mac that `-p 127.0.0.1:...` does not
/// publish anything at all on a `--internal` network there (no gateway, so
/// no NAT path in) -- the worker was healthy from inside the container but
/// unreachable from the host. A plain user-defined network is the fallback
/// that actually publishes, while still keeping the worker off the default
/// bridge (see the PR body for the caller-auth alternative this trades
/// against).
///
/// No `--init`: a manual `docker run --init` against the real image fails
/// outright (`s6-overlay-suexec: fatal: can only run as pid 1`) because
/// s6-overlay insists on being PID 1 itself. That is fine for zombie
/// reaping (zc#277's concern for the *host* worker process, not this
/// container): s6-overlay is itself an init that reaps its children,
/// including the `docker exec`'d worker from [`worker_exec_argv`]. Do not
/// add `--init` back here.
pub(crate) fn docker_run_argv(
    port: u16,
    image: &str,
    container_name: &str,
    network_name: &str,
    worker_name: &str,
    limits: &crate::sandbox::Limits,
) -> Vec<String> {
    let mut argv = vec!["docker".to_string()];
    argv.extend(crate::sandbox::docker::run_argv(&share_start_spec(
        port,
        image,
        container_name,
        network_name,
        worker_name,
        limits,
    )));
    argv
}

/// The backend-neutral start of one share worker container (see
/// [`docker_run_argv`] for why each part is what it is). `limits` is this
/// worker's slice of the node budget ([`share_worker_limits`]): always a cpu
/// and memory cap, and a GPU only when the budget passes one through
/// (zc#510, ZC-0018).
/// s6-overlay's limit on bringing the image's services up (see
/// [`share_start_spec`]).
pub(crate) const S6_WAIT_ENV: &str = "S6_CMD_WAIT_FOR_SERVICES_MAXTIME";

pub(crate) fn share_start_spec(
    port: u16,
    image: &str,
    container_name: &str,
    network_name: &str,
    worker_name: &str,
    limits: &crate::sandbox::Limits,
) -> crate::sandbox::StartSpec {
    crate::sandbox::StartSpec {
        name: container_name.to_string(),
        image: image.to_string(),
        network: Some(network_name.to_string()),
        create_network: true,
        labels: vec![
            ("zakuro.share".to_string(), "1".to_string()),
            ("zakuro.worker".to_string(), worker_name.to_string()),
        ],
        mounts: Vec::new(),
        publish: vec![format!("127.0.0.1:{port}:{port}")],
        // No deadline on the image's own s6 service start: under emulation
        // (the amd64 image on an Apple-silicon Mac) its services take longer
        // than s6-overlay's default, s6-rc times out and stops the container
        // (exit 2) before the worker is ever exec'd -- a crash loop. The
        // worker's own health probe is what decides readiness.
        env: vec![(S6_WAIT_ENV.to_string(), "0".to_string())],
        cmd: Vec::new(),
        limits: limits.clone(),
        remove_on_exit: true,
        hardened: false,
    }
}

/// One share worker's slice of the node budget: the budget (from `get`, see
/// [`crate::sandbox::Budget::from_env`]) split evenly across `workers`
/// slots, so the containers together never exceed what the owner lends.
/// `Err` (an invalid budget, or a percentage of an unknown memory size)
/// refuses the container start: there is no unlimited fallback.
pub(crate) fn share_worker_limits(
    get: &dyn Fn(&str) -> Option<String>,
    workers: u32,
) -> Result<crate::sandbox::Limits, String> {
    Ok(share_limits_for_os(
        crate::sandbox::node_limits_from(get)?.split(workers),
        cfg!(target_os = "linux"),
    ))
}

/// A share worker gets a GPU only where a container can be handed one: Linux.
/// On macOS no backend passes a GPU to a Linux container (Lima and Colima
/// refuse, Docker Desktop has none), and `budget.gpu` there means the Metal
/// GPU the host Atelier runner uses (design D2), not a container device.
fn share_limits_for_os(mut limits: crate::sandbox::Limits, linux: bool) -> crate::sandbox::Limits {
    if !linux {
        limits.gpus = crate::sandbox::Gpus::None;
    }
    limits
}

/// Where a container-backed worker's own stdout/stderr lands, inside the
/// container. `docker exec -d` discards the exec'd process's output, so it is
/// redirected to a file and read back with [`worker_log_tail_argv`]. Note
/// that this is NOT what `docker logs` shows: that stream belongs to the
/// image's own s6-overlay services (dashboard, Ray, Spark, Jupyter).
pub(crate) const WORKER_CONTAINER_LOG: &str = "/tmp/worker.log";

/// Where that same shell records the pid the worker runs as, inside the
/// container. The supervisor's liveness probe ([`worker_alive_argv`]) reads
/// it: a container's `.State.Running` says nothing about the worker, because
/// s6-overlay stays PID 1 whether the worker is alive or not.
pub(crate) const WORKER_CONTAINER_PID: &str = "/tmp/worker.pid";

/// The `docker exec -d` argv that starts the worker process inside an
/// already-running container from [`docker_run_argv`]. Mirrors
/// `mesh.rs::up`'s `ZAKURO_WORKER_NAME=... python -m zakuro.worker.server
/// --host 0.0.0.0 --port {p} --worker-name {n}` exec line.
///
/// The shell records its own pid in [`WORKER_CONTAINER_PID`] and then
/// `exec`s, so that pid *becomes* the worker's: no wrapper process sits in
/// between, and [`worker_alive_argv`]'s `kill -0` is therefore asking about
/// the worker itself. `exec env VAR=... python` rather than `VAR=... exec
/// python`, because a variable assignment in front of a special builtin is
/// not portable.
///
/// The process binds `--host 0.0.0.0` inside the container, which would
/// normally trip zakuro#248's bind guard (see `worker_bind_env`); that is
/// satisfied here via the guard's own trusted-mesh escape hatch,
/// `ZAKURO_INSECURE_BIND=1`, applied *deliberately* rather than by accident:
/// the container's network namespace only reaches the host's loopback (via
/// the `-p 127.0.0.1:...` publish in `docker_run_argv`) and other containers
/// on the same non-published bridge network, never the LAN, so the trust
/// boundary the guard exists to protect is still intact.
pub(crate) fn worker_exec_argv(
    container_name: &str,
    port: u16,
    name: &str,
    price: Option<&str>,
) -> Vec<String> {
    let mut argv = vec![
        "docker".to_string(),
        "exec".to_string(),
        "-d".to_string(),
        container_name.to_string(),
    ];
    argv.extend(worker_exec_cmd(port, name, price));
    argv
}

/// The command [`worker_exec_argv`] runs inside the container, for a
/// [`crate::sandbox::Runtime::exec`] (which adds `docker exec -d <name>`).
pub(crate) fn worker_exec_cmd(port: u16, name: &str, price: Option<&str>) -> Vec<String> {
    // A container inherits none of this process's environment, so the price
    // has to be written into the exec line or the worker falls back to its
    // own default and the owner's `--price` is quietly ignored.
    let price_prefix = price
        .map(|v| format!("ZAKURO_PRICE_PER_HOUR={v} "))
        .unwrap_or_default();
    let inner = format!(
        "echo $$ >{WORKER_CONTAINER_PID}; \
         exec env {price_prefix}ZAKURO_WORKER_NAME={name} ZAKURO_INSECURE_BIND=1 \
         python -m zakuro.worker.server \
         --host 0.0.0.0 --port {port} --worker-name {name} >{WORKER_CONTAINER_LOG} 2>&1"
    );
    vec!["sh".to_string(), "-c".to_string(), inner]
}

/// What `docker inspect` reports about a container: the three fields a
/// supervisor needs, and the analogue of a host process's `(alive, start
/// time, exit status)`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ContainerState {
    pub running: bool,
    /// `.State.StartedAt`, an RFC-3339 instant. With the container's name
    /// this identifies one *run* of that container, the way `(pid, start
    /// time)` identifies one run of a process: a container recreated under
    /// the same name is a different thing, and must not be adopted as if it
    /// were the one the agent recorded.
    pub started_at: String,
    pub exit_code: i64,
}

/// `docker inspect -f …` for the three [`ContainerState`] fields at once:
/// one round trip to the daemon instead of three.
pub(crate) fn docker_state_argv(container_name: &str) -> Vec<String> {
    vec![
        "docker".to_string(),
        "inspect".to_string(),
        "-f".to_string(),
        "{{.State.Running}}|{{.State.StartedAt}}|{{.State.ExitCode}}".to_string(),
        container_name.to_string(),
    ]
}

/// Parse [`docker_state_argv`]'s output. `None` for anything that isn't
/// exactly those three fields — never a default: a supervisor that read a
/// garbled or empty answer as `running: false` would tear down a healthy
/// worker, and as `running: true` would adopt a container that isn't there.
pub(crate) fn parse_container_state(out: &str) -> Option<ContainerState> {
    let mut fields = out.trim().splitn(3, '|');
    let running = match fields.next()?.trim() {
        "true" => true,
        "false" => false,
        _ => return None,
    };
    let started_at = fields.next()?.trim().to_string();
    let exit_code = fields.next()?.trim().parse::<i64>().ok()?;
    (!started_at.is_empty()).then_some(ContainerState {
        running,
        started_at,
        exit_code,
    })
}

/// `docker kill --signal <SIG>`: the container analogue of `killpg(pid,
/// SIG)`. The signal goes to the container's PID 1 (s6-overlay), which is
/// what shuts the whole container down. Used instead of `docker stop` so the
/// supervisor keeps its own SIGTERM / wait / SIGKILL shape, with its own
/// stop-flag checks between the two — `docker stop -t N` would block for the
/// whole grace period inside one uninterruptible call.
pub(crate) fn docker_signal_argv(container_name: &str, signal: &str) -> Vec<String> {
    vec![
        "docker".to_string(),
        "kill".to_string(),
        "--signal".to_string(),
        signal.to_string(),
        container_name.to_string(),
    ]
}

/// `docker rm -f`: remove the container whatever state it is in. Two uses,
/// both about the deterministic container name and the port it publishes:
/// before a (re)start, so a leftover from a crash the agent never got to
/// clean up can't win the name or keep holding `base_worker_port + i`; and
/// after a worker dies inside a container that is still up, which is the
/// container analogue of "a surviving group member must not keep holding the
/// port".
pub(crate) fn docker_rm_argv(container_name: &str) -> Vec<String> {
    vec![
        "docker".to_string(),
        "rm".to_string(),
        "-f".to_string(),
        container_name.to_string(),
    ]
}

/// `docker ps -a` over every container labelled `zakuro.share=1` (what
/// [`docker_run_argv`] stamps on a share worker), one `id<TAB>name` line each.
/// `-a` so a stopped leftover is listed too. The label is the only selector:
/// a container without it is never in the output.
pub(crate) fn docker_ps_share_argv() -> Vec<String> {
    [
        "docker",
        "ps",
        "-a",
        "--no-trunc",
        "--filter",
        "label=zakuro.share=1",
        "--format",
        "{{.ID}}\t{{.Names}}",
    ]
    .into_iter()
    .map(str::to_string)
    .collect()
}

/// Parse [`docker_ps_share_argv`]'s output into `(id, name)` pairs.
pub(crate) fn parse_share_ps(out: &str) -> Vec<(String, String)> {
    out.lines()
        .filter_map(|l| {
            let (id, name) = l.split_once('\t')?;
            let (id, name) = (id.trim(), name.trim());
            (!id.is_empty() && !name.is_empty()).then(|| (id.to_string(), name.to_string()))
        })
        .collect()
}

/// Is the worker process itself still alive inside the container? `kill -0`
/// on the pid [`worker_exec_argv`] recorded — no `pgrep`, no `/proc`
/// parsing, nothing the image has to ship beyond a shell. A non-zero exit
/// (no pidfile, dead pid, or a container that can no longer be `exec`'d into
/// at all) means "not alive".
///
/// The recorded pid could in principle be reused by another process in the
/// container's namespace, which would read as alive. That namespace holds
/// one s6 supervision tree and a handful of long-lived services, so it is
/// remote; the alternative (matching the cmdline in `/proc`) costs a
/// portability assumption on every image for it.
pub(crate) fn worker_alive_argv(container_name: &str) -> Vec<String> {
    vec![
        "docker".to_string(),
        "exec".to_string(),
        container_name.to_string(),
        "sh".to_string(),
        "-c".to_string(),
        format!("kill -0 \"$(cat {WORKER_CONTAINER_PID} 2>/dev/null)\" 2>/dev/null"),
    ]
}

/// The last `n` lines the worker itself wrote ([`WORKER_CONTAINER_LOG`]) —
/// the container's stand-in for `tail_lines(worker_log(i))`, and what a
/// `worker_crashloop` problem's detail is made of. Only works while the
/// container is still up; [`docker_logs_argv`] is the fallback once it isn't.
pub(crate) fn worker_log_tail_argv(container_name: &str, n: usize) -> Vec<String> {
    vec![
        "docker".to_string(),
        "exec".to_string(),
        container_name.to_string(),
        "sh".to_string(),
        "-c".to_string(),
        format!("tail -n {n} {WORKER_CONTAINER_LOG} 2>/dev/null"),
    ]
}

/// `docker logs --tail n`: the image's own output (s6-overlay and the
/// services it runs), not the worker's. Second best, but it still works on a
/// container that has stopped, where [`worker_log_tail_argv`] cannot run at
/// all — a container that died on startup has nothing else to say for itself.
pub(crate) fn docker_logs_argv(container_name: &str, n: usize) -> Vec<String> {
    vec![
        "docker".to_string(),
        "logs".to_string(),
        "--tail".to_string(),
        n.to_string(),
        container_name.to_string(),
    ]
}

/// Shown when the container runtime is forced
/// (`ZAKURO_SHARE_RUNTIME=container`) but no isolating backend is usable on
/// this host. A clear refusal, not a silent fallback to the host process: the
/// whole point of asking for a container is reproducibility.
pub(crate) fn container_worker_refusal_message() -> String {
    "ZAKURO_SHARE_RUNTIME=container but no container backend is available on this host \
     (Incus or Docker; `zc doctor` says why each was skipped). Install/start one, or set \
     ZAKURO_SHARE_RUNTIME=host to share with the host process (NO isolation)."
        .to_string()
}

/// Best-effort: is `docker` usable right now (CLI present *and* daemon
/// reachable)? Not unit tested -- it shells out for real -- see
/// `container_worker_enabled`/`container_worker_refusal_message` for the
/// decision logic this feeds, which is.
pub(crate) fn docker_cli_available() -> bool {
    crate::sandbox::engine::available()
}

/// How long a [`docker_cli_available`] answer is reused before being probed
/// again. `docker info` is a full round trip to the daemon (hundreds of
/// milliseconds on Docker Desktop), and the agent reconciles every 2 s.
const DOCKER_PROBE_TTL: Duration = Duration::from_secs(30);

/// [`docker_cli_available`] for a caller on a hot loop: the agent's reconcile
/// tick, which needs it only to decide whether to raise `docker_missing`.
/// Cached for [`DOCKER_PROBE_TTL`], so starting Docker clears the problem
/// within half a minute without a restart, and a machine with no Docker
/// doesn't pay a daemon probe every two seconds. Not unit tested -- it shells
/// out for real -- see `plan::prerequisite_problems` for the decision logic
/// it feeds, which is.
pub(crate) fn docker_cli_available_cached() -> bool {
    static CACHE: std::sync::Mutex<Option<(Instant, bool)>> = std::sync::Mutex::new(None);
    let mut cache = match CACHE.lock() {
        Ok(c) => c,
        Err(poisoned) => poisoned.into_inner(),
    };
    if let Some((at, ok)) = *cache {
        if at.elapsed() < DOCKER_PROBE_TTL {
            return ok;
        }
    }
    let ok = docker_cli_available();
    *cache = Some((Instant::now(), ok));
    ok
}

/// Cold start: if `image` isn't local, pull it now with docker's own progress
/// on stderr, so a first `zc share` doesn't look hung inside `docker run`.
/// Synchronous (a background pull is the follow-up listed in #387).
fn pull_image_if_missing(image: &str) -> Result<(), String> {
    let present = engine_command(&["image", "inspect", image])
        .and_then(|mut c| {
            c.stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status()
                .map_err(|e| e.to_string())
        })
        .map(|s| s.success())
        .unwrap_or(false);
    if present {
        return Ok(());
    }
    eprintln!("  Pulling {image} (first run only; this can take a few minutes) ...");
    let ok = engine_command(&["pull", image])
        .and_then(|mut c| {
            c.stdout(std::process::Stdio::null())
                .status()
                .map_err(|e| e.to_string())
        })
        .map(|s| s.success())
        .unwrap_or(false);
    if ok {
        Ok(())
    } else {
        Err(format!("docker pull {image} failed"))
    }
}

/// Spawn a worker as a Docker container (see [`select_share_runtime`]).
/// Two steps, matching `mesh.rs::up`: start the container from the image
/// unmodified, then `docker exec -d` the worker process into it.
fn spawn_container_worker(
    port: u16,
    name: String,
    limits: &crate::sandbox::Limits,
) -> Result<WorkerHandle, String> {
    if !docker_cli_available() {
        return Err(container_worker_refusal_message());
    }
    // The active backend: the shared LXC sandbox (ports proxied to the host)
    // or Docker; admission is read through it either way.
    let rt = crate::sandbox::engine::runtime()?;
    let image = worker_container_image(&|k| std::env::var(k).ok());
    pull_image_if_missing(&image)?;
    rt.verify_image(&image, None)?;
    let container_name = worker_container_name(&name);
    let network_name = worker_network_name(&name);
    // Admitted against everything already running on the node (the agent's
    // jobs, the broker's leases), under the node-wide lock, like the agent's
    // own share workers.
    {
        let _admission = crate::sandbox::admission_lock();
        let budget = crate::sandbox::node_limits()?;
        let running = rt
            .allocations()
            .map_err(|e| format!("budget: cannot read the node's allocations: {e}"))?;
        crate::sandbox::admit(&budget, &running, limits).map_err(|e| format!("budget: {e}"))?;
        rt.start(&share_start_spec(
            port,
            &image,
            &container_name,
            &network_name,
            &name,
            limits,
        ))
        .map_err(|e| format!("container start failed for worker {name}: {e}"))?;
    }
    let price = worker_price_env(&|k| std::env::var(k).ok(), None).map(|(_, v)| v);
    if let Err(e) = rt.exec(
        &container_name,
        &worker_exec_cmd(port, &name, price.as_deref()),
        true,
    ) {
        // Don't leave a container running with no worker inside it.
        let _ = rt.stop(&container_name);
        return Err(format!("container exec failed for worker {name}: {e}"));
    }
    Ok(WorkerHandle {
        port,
        name,
        backend: WorkerBackend::Container(container_name),
    })
}

/// How a spawned worker is actually running.
enum WorkerBackend {
    /// The default: a host `uv run` process, in its own OS process.
    Host(Child),
    /// A detached Docker container, identified by its `--name`.
    Container(String),
}

/// Spawn a single worker, as a host process or a Docker container.
fn spawn_worker(
    port: u16,
    name: String,
    zakuro_dir: &PathBuf,
    runtime: ShareRuntime,
    limits: Option<&crate::sandbox::Limits>,
) -> Result<WorkerHandle, String> {
    if runtime == ShareRuntime::Container {
        let limits = limits.ok_or("no resource limits for a container worker")?;
        return spawn_container_worker(port, name, limits);
    }
    let argv = worker_argv(port, &name);
    let mut cmd = Command::new(&argv[0]);
    cmd.args(&argv[1..])
        .current_dir(zakuro_dir)
        .env("ZAKURO_WORKER_TYPE", "zakuro")
        // Suppress uv deprecation warnings in worker output
        .env("UV_NO_PROGRESS", "1")
        // Workers run job code and never register themselves: the broker's
        // worker key stays out of their environment.
        .env_remove(crate::worker_key::ENV)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    if let Some((k, v)) = worker_bind_env(&|k| std::env::var(k).ok()) {
        cmd.env(k, v);
    }
    let child = cmd
        .spawn()
        .map_err(|e| format!("Failed to spawn worker on port {}: {}", port, e))?;

    Ok(WorkerHandle {
        port,
        name,
        backend: WorkerBackend::Host(child),
    })
}

/// Poll until the worker's /health returns 200 or timeout.
fn wait_for_worker(port: u16, timeout_secs: u64) -> bool {
    let deadline = Instant::now() + Duration::from_secs(timeout_secs);
    let url = format!("http://127.0.0.1:{}/health", port);

    while Instant::now() < deadline {
        if let Ok(resp) = ureq::get(&url)
            .config()
            .timeout_global(Some(Duration::from_millis(500)))
            .build()
            .call()
        {
            if resp.status().as_u16() == 200 {
                return true;
            }
        }
        std::thread::sleep(Duration::from_millis(300));
    }
    false
}

/// Main entry point for `zc up`.
pub fn start_up(workers: usize, base_port: u16, broker_port: u16, daemon: bool) {
    println!();
    if daemon {
        println!(
            "  {}  {} worker(s) + broker on :{} {}\n",
            "zc up".bold().cyan(),
            workers,
            broker_port,
            "(background)".dimmed()
        );
    } else {
        println!(
            "  {}  {} worker(s) + broker on :{}\n",
            "zc up".bold().cyan(),
            workers,
            broker_port
        );
    }

    let runtime =
        match select_share_runtime(&|k| std::env::var(k).ok(), &docker_cli_available, &|| {
            worker_image_ready(&worker_container_image(&|k| std::env::var(k).ok()))
        }) {
            Ok(choice) => {
                if let Some(w) = &choice.warning {
                    eprintln!("  {} {w}", "Warning:".yellow());
                }
                choice.runtime
            }
            Err(e) => {
                eprintln!("  {} {e}", "Error:".red());
                return;
            }
        };

    // Each container worker gets an equal slice of the node budget (zc#510):
    // resolved once, up front, so a bad budget fails here and not per worker.
    let share_limits = if runtime == ShareRuntime::Container {
        match share_worker_limits(&|k| std::env::var(k).ok(), workers as u32) {
            Ok(l) => {
                println!("  {}  {l} per worker", "Limits:".bold());
                Some(l)
            }
            Err(e) => {
                eprintln!("  {} {e}", "Error:".red());
                return;
            }
        }
    } else {
        None
    };

    // --- Locate zakuro worker package (host runtime only: the container
    // image carries its own) ---
    let zakuro_dir = if runtime == ShareRuntime::Host {
        match find_zakuro_dir() {
            Some(d) => {
                println!("  {}  {}", "Worker src:".bold(), d.display());
                d
            }
            None => {
                eprintln!(
                    "  {} Cannot find zak-zakuro directory.\n  Clone it into ~/.zakuro/zak-zakuro, or set ZAKURO_WORKER_DIR",
                    "Error:".red()
                );
                return;
            }
        }
    } else {
        PathBuf::new()
    };

    // --- Start broker ---
    let broker_already_up = is_port_open(broker_port);
    if broker_already_up {
        println!(
            "  {}  Broker already running on :{} (reusing)",
            "Broker:".bold(),
            broker_port
        );
    } else {
        let scan_end = base_port + (workers as u16).max(1) + 19;
        let scan_range = format!("{}-{}", base_port, scan_end);
        // Vouchers on when billing creds exist (the child inherits the env).
        broker::apply_user_broker_defaults();
        // The broker takes worker registrations only with a key: the configured
        // one, else this node's own (`worker_key`), which `zc serve` also reads.
        // Set in this process so the daemon child inherits it and the
        // foreground broker thread reads it. Not handed to the workers.
        let worker_key = crate::credentials::dir().and_then(|d| {
            crate::worker_key::ensure(std::env::var(crate::worker_key::ENV).ok(), &d).ok()
        });
        if let Some(k) = worker_key {
            std::env::set_var(crate::worker_key::ENV, k);
            if std::env::var_os("ZAKURO_REQUIRE_WORKER_KEY").is_none() {
                std::env::set_var("ZAKURO_REQUIRE_WORKER_KEY", "1");
            }
        }

        if daemon {
            // In daemon mode spawn the broker as a subprocess so it survives
            // std::process::exit(0). A thread would die with the parent process.
            let exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("zc"));
            let broker_child = Command::new(&exe)
                .args(["broker", &broker_port.to_string()])
                .env("ZAKURO_SCAN_RANGE", &scan_range)
                .env("ZAKURO_SCAN_INTERVAL", "3")
                .env(
                    "ZAKURO_P2P",
                    if broker::p2p_default() {
                        "true"
                    } else {
                        "false"
                    },
                )
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn();
            match broker_child {
                Ok(_child) => { /* forget below along with workers */ }
                Err(e) => {
                    eprintln!(
                        "  {} Failed to spawn broker subprocess: {}",
                        "Error:".red(),
                        e
                    );
                    return;
                }
            }
        } else {
            // Foreground mode: run broker in a thread (process will block anyway).
            let discovery = broker::DiscoveryConfig {
                worker_port: base_port,
                extra_ports: vec![],
                scan_port_range: Some((base_port, scan_end)),
                enable_scan: true,
                enable_dns: false,
                interval_secs: 5,
                ..Default::default()
            };
            let config = broker::BrokerConfig {
                host: "0.0.0.0".to_string(),
                port: broker_port,
                daemon: true,
                verbose: false,
                enable_discovery: true,
                discovery,
                enable_p2p: broker::p2p_default(),
                ..Default::default()
            };
            std::thread::Builder::new()
                .name("broker".into())
                .spawn(move || {
                    if let Err(e) = broker::start_server(config) {
                        eprintln!("  [BROKER] Error: {}", e);
                    }
                })
                .expect("Failed to spawn broker thread");
        }

        // Wait for broker to bind
        print!("  {}  Starting...", "Broker:".bold());
        let start = Instant::now();
        loop {
            if is_port_open(broker_port) {
                println!(
                    "\r  {}  http://127.0.0.1:{}{}",
                    "Broker:".bold(),
                    broker_port,
                    " ".repeat(20)
                );
                break;
            }
            if start.elapsed().as_secs() > 5 {
                println!();
                eprintln!("  {} Broker didn't start in time", "Error:".red());
                return;
            }
            std::thread::sleep(Duration::from_millis(100));
        }
    }

    // --- Spawn Python workers ---
    println!();
    let node_fp = broker::node_identity::NodeKey::load_or_create().fingerprint();
    let mut handles: Vec<WorkerHandle> = Vec::with_capacity(workers);
    let mut ready_from_existing: usize = 0;

    for i in 0..workers {
        let port = base_port + i as u16;

        if is_port_open(port) {
            print!(
                "  {}  Port {} already in use — checking ...",
                format!("Worker {}:", i).bold(),
                port
            );
            if wait_for_worker(port, 3) {
                println!(" {}", "ready".green());
                ready_from_existing += 1;
            } else {
                println!(" {}", "no response (not a worker?)".yellow());
            }
            continue;
        }

        match spawn_worker(
            port,
            worker_name(&node_fp, i),
            &zakuro_dir,
            runtime,
            share_limits.as_ref(),
        ) {
            Ok(handle) => {
                println!(
                    "  {}  Spawned on :{} ({})",
                    format!("Worker {}:", i).bold(),
                    port,
                    handle.identity()
                );
                handles.push(handle);
            }
            Err(e) => {
                eprintln!("  {} Failed to start worker {}: {}", "Error:".red(), i, e);
            }
        }
    }

    // --- Wait for all spawned workers to be healthy ---
    println!();
    let mut ready = ready_from_existing;
    for handle in &handles {
        print!(
            "  Waiting for {} on :{} ...",
            handle.name.cyan(),
            handle.port
        );
        if wait_for_worker(handle.port, WORKER_STARTUP_TIMEOUT_SECS) {
            println!(" {}", "ready".green());
            ready += 1;
        } else {
            println!(" {}", "timeout".red());
        }
    }

    if ready == 0 && (workers > 0) {
        eprintln!(
            "\n  {} No workers became healthy. Aborting.",
            "Error:".red()
        );
        return;
    }

    // Brief pause for discovery loop to pick up the workers
    std::thread::sleep(Duration::from_secs(2));

    // --- Summary ---
    println!();
    println!(
        "  {}",
        "─────────────────────────────────────────────".dimmed()
    );
    println!("  {}  {}/{} ready", "Workers:".bold(), ready, workers);
    println!(
        "  {}  http://127.0.0.1:{} (route requests here)",
        "Broker:".bold(),
        broker_port
    );
    println!();
    println!(
        "  Benchmark: {}",
        format!("zc bench http://127.0.0.1:{}", broker_port).cyan()
    );

    if daemon {
        // --- Daemon mode: detach and exit ---
        // We call std::process::exit(0) which bypasses all Drop implementations,
        // so WorkerHandle::drop() never runs and the child processes keep running
        // as orphans (reparented to init/systemd on Linux).
        println!("  Stop with:  {}", "zc down".cyan());
        println!("  Monitor:    {}", "zc workers".cyan());
        println!(
            "  {}",
            "─────────────────────────────────────────────".dimmed()
        );
        println!();
        // Forget handles so Drop doesn't kill children when we exit
        for handle in handles {
            std::mem::forget(handle);
        }
        std::process::exit(0);
    } else {
        // --- Foreground mode: block until Ctrl-C ---
        println!(
            "  Press {} to stop all workers + broker.",
            "Ctrl+C".yellow().bold()
        );
        println!(
            "  {}",
            "─────────────────────────────────────────────".dimmed()
        );
        println!();

        let running = Arc::new(AtomicBool::new(true));
        let r = running.clone();

        #[cfg(unix)]
        unsafe {
            libc_sigint(r);
        }
        #[cfg(not(unix))]
        {
            let _ = r;
        } // Windows uses the default console Ctrl+C handler.

        while running.load(Ordering::SeqCst) {
            for handle in &mut handles {
                if let Some(desc) = handle.exited() {
                    eprintln!(
                        "\n  {} Worker {} (:{}) exited unexpectedly: {}",
                        "Warning:".yellow(),
                        handle.name,
                        handle.port,
                        desc
                    );
                }
            }
            std::thread::sleep(Duration::from_secs(2));
        }

        println!("\n  Shutting down {} worker(s)...", handles.len());
        drop(handles);
        println!("  Done.");
    }
}

// Minimal SIGINT handler using std::sync — no external crate needed.
// Sets AtomicBool to false on first Ctrl-C, which exits the main loop.
// Unix-only: on Windows the default console handler terminates the
// process, which is acceptable for a foreground CLI.
#[cfg(unix)]
unsafe fn libc_sigint(flag: Arc<AtomicBool>) {
    use std::sync::Mutex;
    // Store the flag in a global so the signal handler can access it.
    static HANDLER: std::sync::OnceLock<Mutex<Option<Arc<AtomicBool>>>> =
        std::sync::OnceLock::new();

    HANDLER.get_or_init(|| Mutex::new(None));
    if let Some(m) = HANDLER.get() {
        *m.lock().unwrap() = Some(flag);
    }

    extern "C" fn handler(_: libc::c_int) {
        use std::sync::OnceLock;
        static HANDLER: OnceLock<Mutex<Option<Arc<AtomicBool>>>> = OnceLock::new();
        // We can't reach the outer HANDLER here, so use a separate channel.
        // This is simpler than the shared-static approach — just print and exit.
        println!("\n  Received Ctrl+C");
        std::process::exit(0);
    }

    libc::signal(libc::SIGINT, handler as *const () as libc::sighandler_t);
}

/// Tear down a running cluster started by `zc up`.
///
/// Kills:
/// 1. Any process listening on the broker port (default 9000)
/// 2. Any Zakuro worker processes on the worker port range (3960-3999 by default)
///    — detected by calling GET /health to confirm they are Zakuro workers before killing
pub fn stop_up(broker_port: u16, worker_port_start: u16, worker_port_end: u16) {
    println!();
    println!("  {}  Stopping cluster...", "zc down".bold().cyan());
    println!();

    let mut killed = 0usize;

    // Phase 1 — find open ports in the worker range in parallel (same fast-scan as discovery)
    let open_ports: Vec<u16> = {
        let (tx, rx) = std::sync::mpsc::channel();
        let mut handles = Vec::new();
        for port in worker_port_start..=worker_port_end {
            let tx = tx.clone();
            handles.push(std::thread::spawn(move || {
                let addr: std::net::SocketAddr = format!("127.0.0.1:{}", port).parse().unwrap();
                if TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok() {
                    let _ = tx.send(port);
                }
            }));
        }
        drop(tx);
        let mut open: Vec<u16> = rx.iter().collect();
        for h in handles {
            let _ = h.join();
        }
        open.sort_unstable();
        open
    };

    // Phase 2 — for each open port, check if it's a Zakuro worker (/health responds)
    // then kill the process listening on that port
    for port in open_ports {
        if port == broker_port {
            continue;
        } // handled separately below
        let url = format!("http://127.0.0.1:{}/health", port);
        let is_worker = ureq::get(&url)
            .config()
            .timeout_global(Some(Duration::from_millis(300)))
            .build()
            .call()
            .map(|r| r.status().as_u16() == 200)
            .unwrap_or(false);

        if is_worker {
            print!("  Stopping worker on :{} ...", port);
            if kill_port(port) {
                println!(" {}", "done".green());
                killed += 1;
            } else {
                println!(" {}", "failed (not found)".yellow());
            }
        }
    }

    // Phase 3 — stop the broker
    if is_port_open(broker_port) {
        print!("  Stopping broker on :{} ...", broker_port);
        if kill_port(broker_port) {
            println!(" {}", "done".green());
            killed += 1;
        } else {
            println!(" {}", "failed (not found)".yellow());
        }
    }

    println!();
    if killed > 0 {
        println!("  {} {} process(es) stopped.", "✓".green(), killed);
    } else {
        println!(
            "  {} Nothing was running on the expected ports.",
            "Info:".bold()
        );
    }
    println!();
}

/// Kill the process listening on a given port using `fuser -k`.
/// Falls back to `lsof + kill` on systems without fuser.
fn kill_port(port: u16) -> bool {
    // Try fuser first (Linux)
    let status = std::process::Command::new("fuser")
        .args(["-k", &format!("{}/tcp", port)])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();

    if status.map(|s| s.success()).unwrap_or(false) {
        return true;
    }

    // Fallback: lsof + kill (macOS / BSD)
    let lsof = std::process::Command::new("lsof")
        .args(["-ti", &format!("tcp:{}", port)])
        .output();

    if let Ok(out) = lsof {
        let pids = String::from_utf8_lossy(&out.stdout);
        for pid_str in pids.split_whitespace() {
            if let Ok(pid) = pid_str.parse::<u32>() {
                let _ = std::process::Command::new("kill")
                    .arg(pid.to_string())
                    .status();
                return true;
            }
        }
    }

    false
}

use crate::broker;

#[cfg(test)]
mod tests {
    use super::{
        container_worker_refusal_message, docker_logs_argv, docker_network_create_argv,
        docker_rm_argv, docker_run_argv, docker_signal_argv, docker_state_argv,
        is_platform_mismatch, parse_container_state, parse_price_arg, pull_image,
        resolve_zakuro_dir, select_share_runtime, worker_alive_argv, worker_argv, worker_bind_env,
        worker_container_image, worker_container_name, worker_exec_argv, worker_log_tail_argv,
        worker_name, worker_network_name, worker_price_env, ContainerState, ShareRuntime,
        ZakuroDirMissing,
    };
    use crate::agent::files::tests::tmp;
    use crate::broker::node_identity::NodeKey;
    use std::path::PathBuf;

    /// A fresh temp dir containing a valid `zakuro/worker/server.py`.
    fn test_limits() -> crate::sandbox::Limits {
        crate::sandbox::Limits::new(1.5, 2.0, crate::sandbox::Gpus::None)
    }

    #[test]
    fn share_workers_split_the_budget_and_never_run_unlimited() {
        let env = |k: &str| match k {
            "ZAKURO_BUDGET_CPU" => Some("2".to_string()),
            "ZAKURO_BUDGET_MEMORY" => Some("4g".to_string()),
            "ZAKURO_BUDGET_GPU" => Some("1".to_string()),
            _ => None,
        };
        let l = super::share_worker_limits(&env, 4).unwrap();
        // Two cores and 4 GiB over four slots, unless the slot has fewer
        // cores than that (then the budget is capped at the host).
        let host = std::thread::available_parallelism().map_or(1, |n| n.get()) as f64;
        assert_eq!(l.cpus(), 2.0_f64.min(host) / 4.0);
        assert_eq!(l.memory_flag(), "1024m");
        // The GPU is only passed through on Linux (see
        // `share_workers_never_ask_for_a_gpu_off_linux`).
        let linux = cfg!(target_os = "linux");
        assert_eq!(
            l.gpus,
            if linux {
                crate::sandbox::Gpus::All
            } else {
                crate::sandbox::Gpus::None
            }
        );
        let argv = docker_run_argv(3960, "img", "c", "n", "w", &l).join(" ");
        assert!(argv.contains("--memory-swap 1024m"), "{argv}");
        assert_eq!(argv.contains("--gpus all"), linux, "{argv}");
        let bad = |k: &str| (k == "ZAKURO_BUDGET_CPU").then(|| "lots".to_string());
        assert!(super::share_worker_limits(&bad, 1).is_err());
    }

    #[test]
    fn share_workers_never_ask_for_a_gpu_off_linux() {
        let l = crate::sandbox::Limits::new(2.0, 4.0, crate::sandbox::Gpus::All);
        assert_eq!(
            super::share_limits_for_os(l.clone(), false).gpus,
            crate::sandbox::Gpus::None
        );
        assert_eq!(
            super::share_limits_for_os(l, true).gpus,
            crate::sandbox::Gpus::All
        );
    }

    fn valid_dir(tag: &str) -> PathBuf {
        let d = tmp(&format!("up-{tag}"));
        std::fs::create_dir_all(d.join("zakuro/worker")).unwrap();
        std::fs::write(d.join("zakuro/worker/server.py"), b"").unwrap();
        d
    }

    #[test]
    fn env_var_wins_when_valid() {
        let d = valid_dir("env");
        assert_eq!(
            resolve_zakuro_dir(Some(d.display().to_string()), None, None, &[]),
            Ok(d)
        );
    }

    #[test]
    fn an_invalid_env_setting_falls_through_to_the_file_setting() {
        let d = valid_dir("file");
        assert_eq!(
            resolve_zakuro_dir(
                Some("/nonexistent/bogus".to_string()),
                Some(d.display().to_string()),
                None,
                &[]
            ),
            Ok(d)
        );
    }

    #[test]
    fn both_settings_invalid_falls_through_to_the_zc_dir() {
        let zc = valid_dir("zc-dir-parent");
        let zak = zc.join("zak-zakuro");
        std::fs::create_dir_all(zak.join("zakuro/worker")).unwrap();
        std::fs::write(zak.join("zakuro/worker/server.py"), b"").unwrap();
        assert_eq!(
            resolve_zakuro_dir(
                Some("/nonexistent/a".to_string()),
                Some("/nonexistent/b".to_string()),
                Some(&zc),
                &[]
            ),
            Ok(zak)
        );
    }

    /// The legacy candidates are tried in the order given, past a zc dir
    /// that doesn't have `zak-zakuro` either.
    #[test]
    fn legacy_candidates_are_tried_in_the_given_order() {
        let zc = valid_dir("zc-dir-no-zak");
        let first = tmp("legacy-first"); // exists, but not a valid zakuro dir
        std::fs::create_dir_all(&first).unwrap();
        let second_parent = valid_dir("legacy-second");
        let second = second_parent.join("zak-zakuro");
        std::fs::create_dir_all(second.join("zakuro/worker")).unwrap();
        std::fs::write(second.join("zakuro/worker/server.py"), b"").unwrap();
        let third_parent = valid_dir("legacy-third");
        let third = third_parent.join("zak-zakuro");
        std::fs::create_dir_all(third.join("zakuro/worker")).unwrap();
        std::fs::write(third.join("zakuro/worker/server.py"), b"").unwrap();

        assert_eq!(
            resolve_zakuro_dir(
                None,
                None,
                Some(&zc),
                &[first.clone(), second.clone(), third.clone()]
            ),
            Ok(second),
            "the first candidate is invalid, so the second (not the third) wins"
        );
    }

    #[test]
    fn nothing_found_reports_the_first_invalid_setting() {
        assert_eq!(
            resolve_zakuro_dir(
                Some("/nonexistent/env-val".to_string()),
                Some("/nonexistent/file-val".to_string()),
                None,
                &[]
            ),
            Err(ZakuroDirMissing {
                invalid_setting: Some("/nonexistent/env-val".to_string())
            })
        );
    }

    #[test]
    fn nothing_found_and_no_setting_given_has_no_detail() {
        let missing = resolve_zakuro_dir(None, None, None, &[]).unwrap_err();
        assert_eq!(missing.invalid_setting, None);
        assert_eq!(missing.detail(), None);
    }

    #[test]
    fn an_invalid_setting_produces_the_expected_detail_text() {
        let missing =
            resolve_zakuro_dir(Some("/bad/path".to_string()), None, None, &[]).unwrap_err();
        assert_eq!(
            missing.detail().as_deref(),
            Some("ZAKURO_WORKER_DIR=/bad/path has no zakuro/worker/server.py")
        );
    }

    #[test]
    fn legacy_zakuro_dir_candidates_from_env_orders_cwd_dev_path_then_home() {
        let candidates = super::legacy_zakuro_dir_candidates_from_env();
        // /opt/code/ZAK/zak-zakuro is always present (the hard-coded dev
        // path); cwd's sibling and $HOME's are present whenever those exist.
        assert!(candidates.contains(&PathBuf::from("/opt/code/ZAK/zak-zakuro")));
        let dev_path_index = candidates
            .iter()
            .position(|p| p == &PathBuf::from("/opt/code/ZAK/zak-zakuro"))
            .unwrap();
        if let Some(home) = std::env::var_os("HOME") {
            let home_path = PathBuf::from(home).join("zak-zakuro");
            if let Some(home_index) = candidates.iter().position(|p| p == &home_path) {
                assert!(
                    dev_path_index < home_index,
                    "the dev path comes before $HOME/zak-zakuro"
                );
            }
        }
    }

    #[test]
    fn worker_name_is_fp8_dash_index() {
        assert_eq!(worker_name("a1b2c3d4e5f60718", 0), "a1b2c3d4-w0");
        assert_eq!(worker_name("a1b2c3d4e5f60718", 12), "a1b2c3d4-w12");
    }

    #[test]
    fn two_macs_never_share_a_worker_name() {
        let (a, b) = (NodeKey::generate(), NodeKey::generate());
        assert_ne!(
            worker_name(&a.fingerprint(), 0),
            worker_name(&b.fingerprint(), 0)
        );
    }

    #[test]
    fn worker_argv_is_the_python_entrypoint() {
        assert_eq!(
            worker_argv(3961, "a1b2c3d4-w1"),
            vec![
                "uv",
                "run",
                "--extra",
                "worker",
                "python",
                "-m",
                "zakuro.worker.server",
                "--port",
                "3961",
                "--worker-name",
                "a1b2c3d4-w1",
            ]
        );
    }

    #[test]
    fn a_worker_with_no_caller_auth_binds_loopback() {
        let unset = |_: &str| None;
        assert_eq!(worker_bind_env(&unset), Some(("ZAKURO_HOST", "127.0.0.1")));
        // Values the worker does not treat as switching anything on, and a
        // blank host, which the worker would try to bind as ''.
        for (k, v) in [
            ("ZAKURO_HOST", "  "),
            ("ZAKURO_INSECURE_BIND", "0"),
            ("ZAKURO_AUTH_REQUIRED", "off"),
            ("ZAKURO_CERT_DIR", " "),
            ("ZAKURO_WIRE", "legacy"),
        ] {
            let env = move |q: &str| (q == k).then(|| v.to_string());
            assert_eq!(
                worker_bind_env(&env),
                Some(("ZAKURO_HOST", "127.0.0.1")),
                "{k}={v:?}"
            );
        }
    }

    #[test]
    fn an_operator_host_or_caller_auth_is_left_alone() {
        for (k, v) in [
            ("ZAKURO_HOST", "0.0.0.0"),
            ("ZAKURO_INSECURE_BIND", "1"),
            ("ZAKURO_INSECURE_BIND", "YES"),
            ("ZAKURO_AUTH_REQUIRED", "true"),
            ("ZAKURO_CERT_DIR", "/etc/zakuro/certs"),
            ("ZAKURO_WIRE", "v1"),
        ] {
            let env = move |q: &str| (q == k).then(|| v.to_string());
            assert_eq!(worker_bind_env(&env), None, "{k}={v:?}");
        }
    }

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

    fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
        let m: std::collections::HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        move |k: &str| m.get(k).cloned()
    }

    #[test]
    fn runtime_auto_picks_the_container_when_docker_is_up() {
        let c = select_share_runtime(&env_of(&[]), &|| true, &|| true).unwrap();
        assert_eq!(c.runtime, ShareRuntime::Container);
        assert_eq!(c.warning, None);
        let c = select_share_runtime(
            &env_of(&[("ZAKURO_SHARE_RUNTIME", "AUTO")]),
            &|| true,
            &|| true,
        )
        .unwrap();
        assert_eq!(c.runtime, ShareRuntime::Container);
    }

    /// A backend but no worker image (the pull failed too): an error that
    /// says what to check, not a host process (zc#578). An explicit
    /// `container` still means container.
    #[test]
    fn runtime_auto_refuses_when_the_worker_image_is_missing() {
        let e = select_share_runtime(&env_of(&[]), &|| true, &|| false).unwrap_err();
        assert!(e.contains("zakuroai/compute:cpu"), "{e}");
        assert!(e.contains("pulling it failed"), "says the pull failed: {e}");
        assert!(
            e.contains("ZC_SHARE_WORKER_IMAGE"),
            "names the override: {e}"
        );
        assert!(
            e.contains("ZAKURO_SHARE_RUNTIME=host"),
            "names the escape: {e}"
        );
        let env = env_of(&[("ZAKURO_SHARE_RUNTIME", "container")]);
        let c = select_share_runtime(&env, &|| true, &|| false).unwrap();
        assert_eq!(c.runtime, ShareRuntime::Container);
    }

    #[test]
    fn the_worker_image_is_loaded_into_the_lxc_sandbox_from_host_docker_else_pulled() {
        use super::{ensure_image_in_sandbox, ImageLoad};
        use std::cell::{Cell, RefCell};
        let calls = RefCell::new(Vec::<String>::new());
        let loaded = Cell::new(false);
        let present = |_: &str| loaded.get();
        let save = |i: &str| {
            calls.borrow_mut().push(format!("save {i}"));
            loaded.set(true);
            Ok(())
        };
        let pull = |i: &str| {
            calls.borrow_mut().push(format!("pull {i}"));
            loaded.set(true);
            Ok(())
        };
        // Host Docker has it: save | load.
        let got = ensure_image_in_sandbox("w:1", true, &present, &|_| true, &save, &pull);
        assert_eq!(got, Ok(ImageLoad::LoadedFromHostDocker));
        assert_eq!(*calls.borrow(), vec!["save w:1"]);
        // Already there: nothing is done.
        calls.borrow_mut().clear();
        let got = ensure_image_in_sandbox("w:1", true, &present, &|_| true, &save, &pull);
        assert_eq!(got, Ok(ImageLoad::AlreadyThere));
        assert!(calls.borrow().is_empty());
        // No host Docker image: pulled from its registry.
        loaded.set(false);
        let got = ensure_image_in_sandbox("w:1", true, &present, &|_| false, &save, &pull);
        assert_eq!(got, Ok(ImageLoad::Pulled));
        assert_eq!(*calls.borrow(), vec!["pull w:1"]);
        // Not the LXC sandbox (Docker, a VM): the old "build it there" error.
        loaded.set(false);
        calls.borrow_mut().clear();
        let e =
            ensure_image_in_sandbox("w:1", false, &present, &|_| true, &save, &pull).unwrap_err();
        assert!(e.contains("not in the container backend"), "{e}");
        assert!(calls.borrow().is_empty());
        // A failed pull says why; a load that leaves it missing is an error too.
        let e = ensure_image_in_sandbox("w:1", true, &|_| false, &|_| false, &save, &|_| {
            Err("manifest unknown".into())
        })
        .unwrap_err();
        assert!(
            e.contains("manifest unknown") && e.contains("into the sandbox"),
            "{e}"
        );
        let e = ensure_image_in_sandbox("w:1", true, &|_| false, &|_| true, &|_| Ok(()), &pull)
            .unwrap_err();
        assert!(e.contains("still not in the sandbox"), "{e}");
    }

    #[test]
    fn runtime_auto_without_a_backend_fails_naming_what_to_install_and_the_escape() {
        let e = select_share_runtime(&env_of(&[]), &|| false, &|| true).unwrap_err();
        assert!(e.contains("apt install incus"), "{e}");
        assert!(e.contains("Docker"), "{e}");
        assert!(e.contains("ZAKURO_SHARE_RUNTIME=host"), "{e}");
        assert!(
            e.contains("NO isolation") || e.contains("no isolation"),
            "{e}"
        );
        // Both legacy spellings of "auto" behave the same.
        let auto = env_of(&[("ZAKURO_SHARE_RUNTIME", "auto")]);
        assert!(select_share_runtime(&auto, &|| false, &|| false).is_err());
    }

    #[test]
    fn runtime_host_opt_out_never_probes_docker() {
        let probe = || -> bool { panic!("must not probe docker when opted out") };
        let c = select_share_runtime(&env_of(&[("ZAKURO_SHARE_RUNTIME", "host")]), &probe, &probe)
            .unwrap();
        assert_eq!(c.runtime, ShareRuntime::Host);
        let w = c.warning.unwrap();
        assert!(w.contains("ZAKURO_SHARE_RUNTIME=host"), "{w}");
        assert!(w.contains("NO ISOLATION"), "loudly labelled: {w}");
    }

    #[test]
    fn runtime_container_forces_it_and_fails_clearly_without_docker() {
        let env = env_of(&[("ZAKURO_SHARE_RUNTIME", "container")]);
        let c = select_share_runtime(&env, &|| true, &|| true).unwrap();
        assert_eq!(c.runtime, ShareRuntime::Container);
        let e = select_share_runtime(&env, &|| false, &|| true).unwrap_err();
        assert!(e.contains("ZAKURO_SHARE_RUNTIME=container"), "{e}");
    }

    #[test]
    fn runtime_rejects_an_unknown_value() {
        let e = select_share_runtime(
            &env_of(&[("ZAKURO_SHARE_RUNTIME", "podman")]),
            &|| true,
            &|| true,
        )
        .unwrap_err();
        assert!(e.contains("podman"), "{e}");
    }

    #[test]
    fn legacy_zc_share_container_still_works_and_the_new_var_wins() {
        let on = env_of(&[("ZC_SHARE_CONTAINER", "yes")]);
        assert!(select_share_runtime(&on, &|| false, &|| true).is_err());
        let off = env_of(&[("ZC_SHARE_CONTAINER", "0")]);
        assert_eq!(
            select_share_runtime(&off, &|| true, &|| true)
                .unwrap()
                .runtime,
            ShareRuntime::Host
        );
        let both = env_of(&[
            ("ZC_SHARE_CONTAINER", "1"),
            ("ZAKURO_SHARE_RUNTIME", "host"),
        ]);
        assert_eq!(
            select_share_runtime(&both, &|| true, &|| true)
                .unwrap()
                .runtime,
            ShareRuntime::Host
        );
    }

    #[test]
    fn container_worker_is_loopback_only_and_binds_deliberately() {
        let run = docker_run_argv(
            3960,
            "img",
            "zc-share-x-w0",
            "zc-worker-x",
            "x-w0",
            &test_limits(),
        );
        // Published on loopback only, never a bare/0.0.0.0 mapping.
        let p = run.iter().position(|a| a == "-p").unwrap();
        assert_eq!(run[p + 1], "127.0.0.1:3960:3960");
        assert!(!run.iter().any(|a| a.starts_with("0.0.0.0")));
        let exec = worker_exec_argv("zc-share-x-w0", 3960, "x-w0", None).join(" ");
        // Binds all interfaces *inside* the container so the publish works,
        // and satisfies zakuro#248's guard on purpose.
        assert!(exec.contains("--host 0.0.0.0"), "{exec}");
        assert!(exec.contains("ZAKURO_INSECURE_BIND=1"), "{exec}");
    }

    #[test]
    fn worker_container_image_defaults_to_the_published_compute_image() {
        let env = |_: &str| None;
        assert_eq!(worker_container_image(&env), "zakuroai/compute:cpu");
    }

    #[test]
    fn a_pull_with_no_native_build_retries_as_amd64_where_it_can_be_emulated() {
        let calls = std::cell::RefCell::new(Vec::<String>::new());
        let pull = |a: &[&str]| {
            calls.borrow_mut().push(a.join(" "));
            if a.contains(&"--platform") {
                Ok(())
            } else {
                Err("no match for platform in manifest sha256:3a74: not found".to_string())
            }
        };
        pull_image("zakuroai/compute:cpu", true, &pull).unwrap();
        assert_eq!(
            *calls.borrow(),
            vec![
                "pull zakuroai/compute:cpu",
                "pull --platform linux/amd64 zakuroai/compute:cpu"
            ]
        );
        // No emulation (Linux): the mismatch is the answer, no amd64 retry.
        calls.borrow_mut().clear();
        let e = pull_image("zakuroai/compute:cpu", false, &pull).unwrap_err();
        assert!(is_platform_mismatch(&e), "{e}");
        assert_eq!(calls.borrow().len(), 1);
    }

    #[test]
    fn a_pull_that_fails_for_another_reason_is_not_retried() {
        let calls = std::cell::RefCell::new(0);
        let pull = |_: &[&str]| {
            *calls.borrow_mut() += 1;
            Err("pull access denied: insufficient_scope".to_string())
        };
        let e = pull_image("nope:latest", true, &pull).unwrap_err();
        assert!(e.contains("insufficient_scope"), "{e}");
        assert_eq!(*calls.borrow(), 1);
        assert!(is_platform_mismatch(
            "no matching manifest for linux/arm64/v8"
        ));
    }

    #[test]
    fn worker_container_image_is_overridable_for_pinning() {
        let env = |k: &str| {
            (k == "ZC_SHARE_WORKER_IMAGE").then(|| "zakuroai/compute@sha256:deadbeef".to_string())
        };
        assert_eq!(
            worker_container_image(&env),
            "zakuroai/compute@sha256:deadbeef"
        );
    }

    #[test]
    fn worker_container_name_is_deterministic_and_namespaced() {
        assert_eq!(worker_container_name("a1b2c3d4-w0"), "zc-share-a1b2c3d4-w0");
    }

    #[test]
    fn docker_run_argv_publishes_only_to_loopback_and_does_not_override_cmd() {
        // No worker command here: `zakuro-image-compute` owns its own
        // entrypoint (dashboard/Ray/Spark/Jupyter, s6-managed -- see
        // mesh.rs::up), confirmed by hand against the real image. Overriding
        // CMD would fight that entrypoint instead of using it.
        let argv = docker_run_argv(
            3960,
            "zakuro-image-compute:latest",
            "zc-share-a1b2c3d4-w0",
            "zc-worker-a1b2c3d4",
            "a1b2c3d4-w0",
            &test_limits(),
        );
        assert_eq!(
            argv,
            vec![
                "docker",
                "run",
                "--rm",
                "-d",
                "--name",
                "zc-share-a1b2c3d4-w0",
                // No --init: it fatally conflicts with this image's own
                // s6-overlay init, which insists on being PID 1 (confirmed
                // by hand: "s6-overlay-suexec: fatal: can only run as pid
                // 1"). s6-overlay reaps children itself, so it is not needed
                // for the zc#277 zombie concern either.
                //
                // A dedicated per-node network, not the default bridge:
                // `zakuro-wg` and every `zc mesh up` compute node sit on the
                // default bridge, so a worker container joining it by
                // default would be reachable (unauthenticated /execute) from
                // anything else already on this host, not just from the
                // host's own loopback. `--network zc-worker-<fp8>` is
                // created idempotently (see `docker_network_create_argv`)
                // and nothing else is ever attached to it.
                "--network",
                "zc-worker-a1b2c3d4",
                "--label",
                "zakuro.share=1",
                "--label",
                "zakuro.worker=a1b2c3d4-w0",
                // What it holds of the node budget, summed back (zc#565).
                "--label",
                "zakuro.budget=1500m,2147483648",
                // The worker's slice of the node budget, always (zc#510).
                "--cpus",
                "1.5",
                "--memory",
                "2048m",
                "--memory-swap",
                "2048m",
                "-p",
                "127.0.0.1:3960:3960",
                // No s6 service-start deadline (emulated amd64 on a Mac).
                "-e",
                "S6_CMD_WAIT_FOR_SERVICES_MAXTIME=0",
                "zakuro-image-compute:latest",
            ]
        );
    }

    #[test]
    fn worker_network_name_is_scoped_per_node_fingerprint() {
        // First 8 chars of `name` are the node's fp8 by convention
        // (`worker_name`), so workers from the same machine share one
        // network across restarts instead of leaking a fresh one each time.
        assert_eq!(worker_network_name("a1b2c3d4-w0"), "zc-worker-a1b2c3d4");
        assert_eq!(worker_network_name("a1b2c3d4-w1"), "zc-worker-a1b2c3d4");
    }

    #[test]
    fn docker_network_create_argv_is_a_plain_idempotent_create() {
        // Not `--internal`: verified by hand against Docker Desktop for Mac
        // that `-p 127.0.0.1:...` silently fails to publish anything (no
        // NAT/gateway) on a `--internal` network -- `docker port` on such a
        // container reports no mapping at all, even though the worker
        // itself is healthy from inside. A plain user-defined bridge, used
        // by nothing but this one container, is the fallback: it still
        // keeps the worker off the shared default bridge (see
        // `docker_run_argv`'s doc comment), and `-p` publishes correctly on
        // it (confirmed by hand: /health answered over 127.0.0.1).
        assert_eq!(
            docker_network_create_argv("zc-worker-a1b2c3d4"),
            vec!["docker", "network", "create", "zc-worker-a1b2c3d4"]
        );
    }

    #[test]
    fn no_price_flag_leaves_the_worker_default_alone() {
        assert_eq!(parse_price_arg(&[]).unwrap(), None);
        assert_eq!(
            parse_price_arg(&["--workers".into(), "2".into()]).unwrap(),
            None
        );
    }

    #[test]
    fn a_price_is_read_in_both_spellings() {
        let split = vec!["--price".to_string(), "0.75".to_string()];
        let joined = vec!["--price=0.75".to_string()];
        assert_eq!(parse_price_arg(&split).unwrap(), Some(0.75));
        assert_eq!(parse_price_arg(&joined).unwrap(), Some(0.75));
    }

    #[test]
    fn free_is_allowed_but_negative_is_not() {
        assert_eq!(
            parse_price_arg(&["--price=0".to_string()]).unwrap(),
            Some(0.0)
        );
        assert!(parse_price_arg(&["--price=-1".to_string()]).is_err());
    }

    /// The reason this parse is fallible at all: `--workers abc` silently
    /// becoming 1 is visible, but a price silently becoming 3.6 is money.
    #[test]
    fn a_malformed_price_is_an_error_not_a_default() {
        for bad in ["0.5o", "", "abc", "NaN", "inf"] {
            assert!(
                parse_price_arg(&[format!("--price={bad}")]).is_err(),
                "{bad:?} should be refused, not defaulted"
            );
        }
    }

    #[test]
    fn the_flag_beats_the_environment() {
        let env = |k: &str| (k == "ZAKURO_PRICE_PER_HOUR").then(|| "9.9".to_string());
        assert_eq!(
            worker_price_env(&env, Some(0.5)),
            Some(("ZAKURO_PRICE_PER_HOUR", "0.5".to_string()))
        );
    }

    /// A container inherits nothing, so the env var has to be passed through
    /// explicitly or the same variable prices a host worker and not a
    /// containerised one.
    #[test]
    fn an_environment_price_is_passed_through_for_the_container() {
        let env = |k: &str| (k == "ZAKURO_PRICE_PER_HOUR").then(|| " 2.5 ".to_string());
        assert_eq!(
            worker_price_env(&env, None),
            Some(("ZAKURO_PRICE_PER_HOUR", "2.5".to_string()))
        );
        let unset = |_: &str| None;
        assert_eq!(worker_price_env(&unset, None), None);
    }

    #[test]
    fn the_container_exec_line_carries_the_price() {
        let argv = worker_exec_argv("zc-share-a1b2c3d4-w0", 3960, "a1b2c3d4-w0", Some("0.75"));
        let inner = argv.last().unwrap();
        // Not at the very start of the line any more: the shell records the
        // worker's pid first (see `worker_exec_argv_records_the_pid_the_worker_runs_as`),
        // and the price rides on the `exec env` that follows it.
        assert!(
            inner.contains("exec env ZAKURO_PRICE_PER_HOUR=0.75 "),
            "price must reach the container: {inner}"
        );
        let unpriced = worker_exec_argv("zc-share-a1b2c3d4-w0", 3960, "a1b2c3d4-w0", None);
        assert!(!unpriced.last().unwrap().contains("ZAKURO_PRICE_PER_HOUR"));
    }

    #[test]
    fn worker_exec_argv_binds_0_0_0_0_inside_via_the_trusted_mesh_escape_hatch() {
        let argv = worker_exec_argv("zc-share-a1b2c3d4-w0", 3960, "a1b2c3d4-w0", None);
        assert_eq!(argv[0], "docker");
        assert_eq!(argv[1], "exec");
        assert_eq!(argv[2], "-d");
        assert_eq!(argv[3], "zc-share-a1b2c3d4-w0");
        assert_eq!(argv[4], "sh");
        assert_eq!(argv[5], "-c");
        let inner = &argv[6];
        // Binding 0.0.0.0 inside the container would normally trip
        // zakuro#248's bind guard; it is deliberately opted into here (not
        // left to drift) because docker_run_argv's `-p 127.0.0.1:...`
        // confines the published port to this host's loopback, never the
        // LAN — see the PR body's "Reachability" note.
        assert!(inner.contains("ZAKURO_INSECURE_BIND=1"), "{inner}");
        assert!(inner.contains("--host 0.0.0.0"), "{inner}");
        assert!(inner.contains("--port 3960"), "{inner}");
        assert!(inner.contains("--worker-name a1b2c3d4-w0"), "{inner}");
        assert!(inner.contains("zakuro.worker.server"), "{inner}");
    }

    #[test]
    fn container_worker_refusal_message_names_the_fix() {
        let msg = container_worker_refusal_message();
        assert!(msg.contains("Docker"), "{msg}");
        assert!(msg.contains("ZAKURO_SHARE_RUNTIME"), "{msg}");
    }

    // --- supervising a container-backed worker (issue #263) ----------------

    /// The exec'd shell records the pid the worker ends up running as before
    /// `exec`ing into it, which is what lets a supervisor tell "the worker
    /// died inside a container that is still up" from "everything is fine".
    /// `docker inspect .State.Running` cannot: the image's s6-overlay
    /// entrypoint stays PID 1 whether or not the worker is still there.
    #[test]
    fn worker_exec_argv_records_the_pid_the_worker_runs_as() {
        let argv = worker_exec_argv("zc-share-a1b2c3d4-w0", 3960, "a1b2c3d4-w0", None);
        let inner = &argv[6];
        assert!(inner.contains("echo $$ >/tmp/worker.pid"), "{inner}");
        // `exec` (not a plain call) is what makes the recorded pid the
        // worker's own pid rather than a wrapper shell's.
        assert!(inner.contains("exec env "), "{inner}");
        assert!(inner.contains(">/tmp/worker.log 2>&1"), "{inner}");
        // Everything #279 pinned is still true.
        assert!(inner.contains("ZAKURO_INSECURE_BIND=1"), "{inner}");
        assert!(inner.contains("--host 0.0.0.0"), "{inner}");
    }

    #[test]
    fn docker_state_argv_asks_for_running_started_at_and_exit_code() {
        assert_eq!(
            docker_state_argv("zc-share-a1b2c3d4-w0"),
            vec![
                "docker",
                "inspect",
                "-f",
                "{{.State.Running}}|{{.State.StartedAt}}|{{.State.ExitCode}}",
                "zc-share-a1b2c3d4-w0",
            ]
        );
    }

    #[test]
    fn a_containers_state_parses_into_running_started_at_and_exit_code() {
        assert_eq!(
            parse_container_state("true|2026-09-18T07:01:02.3456789Z|0\n"),
            Some(ContainerState {
                running: true,
                started_at: "2026-09-18T07:01:02.3456789Z".to_string(),
                exit_code: 0,
            })
        );
        assert_eq!(
            parse_container_state("false|2026-09-18T07:01:02Z|137"),
            Some(ContainerState {
                running: false,
                started_at: "2026-09-18T07:01:02Z".to_string(),
                exit_code: 137,
            })
        );
    }

    /// Anything that isn't the three fields we asked for is `None`, never a
    /// default: a supervisor that read a garbled/absent answer as "running:
    /// false" would kill a healthy worker, and as "running: true" would adopt
    /// a container that is not there.
    #[test]
    fn an_unparseable_container_state_is_none_not_a_default() {
        for out in ["", "\n", "true", "true|2026-09-18T07:01:02Z", "yes|t|0"] {
            assert_eq!(parse_container_state(out), None, "{out:?}");
        }
    }

    #[test]
    fn docker_signal_argv_sends_one_named_signal_to_the_container() {
        assert_eq!(
            docker_signal_argv("zc-share-a1b2c3d4-w0", "TERM"),
            vec!["docker", "kill", "--signal", "TERM", "zc-share-a1b2c3d4-w0"]
        );
        assert_eq!(
            docker_signal_argv("zc-share-a1b2c3d4-w0", "KILL"),
            vec!["docker", "kill", "--signal", "KILL", "zc-share-a1b2c3d4-w0"]
        );
    }

    #[test]
    fn docker_rm_argv_force_removes_the_container_by_name() {
        assert_eq!(
            docker_rm_argv("zc-share-a1b2c3d4-w0"),
            vec!["docker", "rm", "-f", "zc-share-a1b2c3d4-w0"]
        );
    }

    /// `kill -0` on the recorded pid, run inside the container: no `pgrep`,
    /// no `/proc` parsing, nothing the image has to ship beyond a shell.
    #[test]
    fn worker_alive_argv_probes_the_recorded_pid_inside_the_container() {
        let argv = worker_alive_argv("zc-share-a1b2c3d4-w0");
        assert_eq!(argv[..4], ["docker", "exec", "zc-share-a1b2c3d4-w0", "sh"]);
        assert_eq!(argv[4], "-c");
        let inner = &argv[5];
        assert!(inner.contains("/tmp/worker.pid"), "{inner}");
        assert!(inner.contains("kill -0"), "{inner}");
    }

    /// The crash-loop tail comes from the worker's own redirected output, not
    /// from `docker logs`: `docker exec -d` discards the exec'd process's
    /// output entirely, so the container's log stream carries the image's
    /// s6-overlay services and never a line the worker wrote.
    #[test]
    fn worker_log_tail_argv_reads_the_workers_own_log_inside_the_container() {
        let argv = worker_log_tail_argv("zc-share-a1b2c3d4-w0", 20);
        assert_eq!(argv[..3], ["docker", "exec", "zc-share-a1b2c3d4-w0"]);
        let inner = argv.last().unwrap();
        assert!(inner.contains("tail -n 20"), "{inner}");
        assert!(inner.contains("/tmp/worker.log"), "{inner}");
    }

    /// The fallback for a container that can no longer be `exec`'d into (it
    /// stopped): better the image's own last words than nothing.
    #[test]
    fn docker_logs_argv_is_the_fallback_tail() {
        assert_eq!(
            docker_logs_argv("zc-share-a1b2c3d4-w0", 20),
            vec!["docker", "logs", "--tail", "20", "zc-share-a1b2c3d4-w0"]
        );
    }
}