supermachine 0.7.2

Run any OCI/Docker image as a hardware-isolated microVM on macOS HVF (Linux KVM and Windows WHP in progress). Single library API, zero flags for the common case, sub-100 ms cold-restore from snapshot.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
// The CLI lives in `src/bin/cli.rs` so cargo can produce both a
// library (`cargo add supermachine`) and a binary (`cargo install
// supermachine`) from the same package. Anything the CLI shares
// with the library — image bake, asset paths — lives in the lib
// (re-exposed below) so a binary in `src/bin/` can reach it across
// the lib boundary.
use supermachine::bake;

use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

struct Args {
    image: Option<String>,
    name: Option<String>,
    connect: bool,
    detach: bool,
    stop: bool,
    http_port: u16,
    guest_port: u16,
    memory_mib: u32,
    /// Number of vCPUs to allocate in the guest. Default 1.
    /// Multi-vCPU re-opened after benching showed single-vCPU
    /// saturation as the c=32+ HTTP-serving bottleneck.
    /// docs/design/concurrency-floor-2026-05-04.md.
    vcpus: u32,
    runtime: String,
    snapshots_dir: PathBuf,
    workers_per_snapshot: u32,
    pull_policy: String,
    do_push: bool,
    /// `docker run --rm` analog: when the daemon stops, also wipe
    /// the snapshot dir and any temp state so the next `run` of
    /// the same image starts from scratch. Honored by `run --stop`.
    rm_on_stop: bool,
    /// Grace window after `--stop`'s SIGTERM before the worker
    /// is force-killed. The TERM is delivered both to the
    /// in-guest workload (via the exec agent's CONTROL frame)
    /// and to the host worker process; we wait this long for the
    /// workload to clean up before falling back to SIGKILL.
    /// Mirrors `docker stop -t SECONDS` (default 10 s).
    stop_grace_ms: u64,
    pid_file: PathBuf,
    log_file: PathBuf,
    ready_timeout_ms: u64,
    probe_path: Option<String>,
    cmd_override: Option<String>,
    push_args: Vec<String>,
}

fn home_join(path: &str) -> PathBuf {
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."))
        .join(path)
}

fn trace_enabled() -> bool {
    std::env::var_os("SUPERMACHINE_RUN_TRACE").is_some()
}

fn elapsed_ms(t0: Instant) -> u128 {
    t0.elapsed().as_millis()
}

const VERSION: &str = env!("CARGO_PKG_VERSION");

fn print_version() {
    println!("supermachine {VERSION}");
}

fn usage() {
    eprintln!(
        "supermachine {VERSION} — run any OCI image as a microVM on macOS HVF.\n\
         \n\
         USAGE:\n  \
           supermachine <COMMAND> [OPTIONS]\n\
         \n\
         COMMANDS:\n  \
           run IMAGE            Pull from registry, bake on first use, then run.\n  \
           run oci-layout:PATH  Bake from a local OCI image layout dir.\n  \
           run oci-archive:PATH Bake from a local OCI archive tar.\n  \
           run --connect        Probe the running daemon, print its endpoint.\n  \
           run --stop           Stop the background daemon for --http-port.\n  \
           pull IMAGE           Bake IMAGE to a snapshot, then exit (no router).\n  \
           images               List baked snapshots.\n  \
           rmi NAME             Remove a baked snapshot by name (or image ref).\n  \
           ps                   List running supermachine daemons.\n  \
           logs [TARGET] [-f]   Tail router log; TARGET = port, snapshot name, or image.\n  \
           exec [TARGET] [-t] -- cmd args...\n  \
                                Run a process inside a running guest (docker exec).\n  \
           setup                Re-sign the supermachine-worker binary with the HVF\n  \
                                entitlement (re-run after every `cargo build`).\n  \
           codesign BINARY      Sign BINARY with the bundled HVF entitlement so it\n  \
                                can call hv_vm_create. Use this on your own Rust app\n  \
                                that embeds the supermachine library.\n  \
                                Pass --identity \"Developer ID Application: ...\" for\n  \
                                distribution; default is ad-hoc signing for dev.\n  \
           bundle --into DIR    Copy kernel + init shim into DIR (typically\n  \
                                YourApp.app/Contents/Resources/) so the embedded\n  \
                                supermachine library finds them at runtime.\n  \
           entitlements-path    Print the path to a temp file containing the bundled\n  \
                                entitlements plist (for use with `codesign`).\n  \
           assets-path          Print the directory supermachine looked up for\n  \
                                kernel + init assets (debug helper).\n  \
           --version, -V        Print version and exit.\n  \
           --help, -h           Show this help.\n\
         \n\
         RUN OPTIONS:\n  \
           (no flags)           Foreground, like `docker run`. Ctrl-C stops it.\n  \
           --detach             Background. Like `docker run -d`. CLI returns\n  \
                                once the workload answers on / (max 8s).\n  \
           --http-port PORT     Edge HTTP port to bind (default: 8080).\n  \
           --name NAME          Snapshot name (default: derived from image).\n  \
           --port PORT          Guest service port to bridge to (default: 80).\n  \
           --memory MIB         Guest RAM for the snapshot (default: 256 MiB).\n  \
           --vcpus N            Number of vCPUs (default: 1). N=2 unlocks\n  \
                                ~1.5x sustained concurrent HTTP throughput.\n  \
                                Higher N (up to 16) further scales CPU-bound\n  \
                                workloads; pause-and-capture rendezvous makes\n  \
                                snapshot/restore reliable across all counts.\n  \
           --workers-per-snapshot N    Pool size per snapshot.\n  \
           --snapshots-dir DIR  Where to store baked snapshots.\n  \
           --pull POLICY        missing | always | never (default: missing).\n  \
           --no-push            Skip bake, reuse existing snapshot.\n  \
           --volume HOST:GUEST  Persistent volume. HOST is a name (resolves to\n  \
                                ~/.local/supermachine/volumes/NAME.img) or an\n  \
                                absolute path. GUEST is the mount point inside\n  \
                                the guest. ext4, 1 GiB by default. Repeatable.\n  \
           --entrypoint EP      Replace the image's ENTRYPOINT.\n  \
           --workdir DIR        Set the workload's working directory.\n  \
           --user USER          Run the workload as USER (uid:gid or name).\n  \
           --hostname NAME      Set the guest hostname.\n  \
           --restart POLICY     no | on-failure | always | unless-stopped.\n  \
                                Default: no. Watchdog uses this on worker death.\n  \
           --health-cmd CMD     Probe inside the guest. Empty = no check.\n  \
           --health-interval N  Run health-cmd every N seconds (default 30).\n  \
                                Note: TSI doesn't loop back inside the guest,\n  \
                                so use process checks (`pgrep ...`) or filesystem\n  \
                                checks rather than `curl http://localhost:...`.\n  \
           --rm                 docker-style: wipe the snapshot dir on stop.\n  \
           --stop-grace, -t SEC docker stop -t analog: SIGTERM grace window\n  \
                                before SIGKILL. Default 10s. Forwarded to the\n  \
                                workload via the in-guest agent.\n  \
           --env KEY=VAL        Pass env var to the guest workload (repeatable).\n  \
           --cmd CMD            Override the image's CMD (JSON array string).\n  \
           --enable-egress | --no-egress\n  \
           --egress-policy POLICY    deny_private | allowlist:CIDRS | denylist:...\n  \
           --probe-path PATH    Strict-mode readiness check (require 200 on PATH).\n  \
                                Default is any HTTP response on /; only set this\n  \
                                if you specifically want to gate startup on 200.\n\
         \n\
         EXAMPLES:\n  \
           supermachine setup                           # one-time after cargo build\n  \
           supermachine run nginx:1.27-alpine            # foreground; Ctrl-C to stop\n  \
           supermachine run nginx:1.27-alpine --detach   # background, then:\n  \
           curl http://127.0.0.1:8080/\n  \
           supermachine run --stop                       # tear down --detach daemon"
    );
}

fn parse_args() -> Result<Args, String> {
    let mut it = std::env::args().skip(1);
    let Some(cmd) = it.next() else {
        usage();
        std::process::exit(0);
    };
    if cmd == "--help" || cmd == "-h" || cmd == "help" {
        usage();
        std::process::exit(0);
    }
    if cmd == "--version" || cmd == "-V" || cmd == "version" {
        print_version();
        std::process::exit(0);
    }
    if cmd == "setup" {
        match run_setup() {
            Ok(()) => std::process::exit(0),
            Err(e) => {
                eprintln!("supermachine setup: {e}");
                std::process::exit(1);
            }
        }
    }
    if cmd == "codesign" {
        let argv: Vec<String> = it.collect();
        match run_codesign(&argv) {
            Ok(()) => std::process::exit(0),
            Err(e) => {
                eprintln!("supermachine codesign: {e}");
                std::process::exit(1);
            }
        }
    }
    if cmd == "bundle" {
        let argv: Vec<String> = it.collect();
        match run_bundle(&argv) {
            Ok(()) => std::process::exit(0),
            Err(e) => {
                eprintln!("supermachine bundle: {e}");
                std::process::exit(1);
            }
        }
    }
    if cmd == "entitlements-path" {
        match run_entitlements_path() {
            Ok(()) => std::process::exit(0),
            Err(e) => {
                eprintln!("supermachine entitlements-path: {e}");
                std::process::exit(1);
            }
        }
    }
    if cmd == "assets-path" {
        run_assets_path();
        std::process::exit(0);
    }
    if cmd == "pull" {
        let argv: Vec<String> = it.collect();
        match run_pull(&argv) {
            Ok(()) => std::process::exit(0),
            Err(e) => {
                eprintln!("supermachine pull: {e}");
                std::process::exit(1);
            }
        }
    }
    if cmd == "images" {
        let argv: Vec<String> = it.collect();
        match run_images(&argv) {
            Ok(()) => std::process::exit(0),
            Err(e) => {
                eprintln!("supermachine images: {e}");
                std::process::exit(1);
            }
        }
    }
    if cmd == "rmi" {
        let argv: Vec<String> = it.collect();
        match run_rmi(&argv) {
            Ok(()) => std::process::exit(0),
            Err(e) => {
                eprintln!("supermachine rmi: {e}");
                std::process::exit(1);
            }
        }
    }
    if cmd == "ps" {
        let argv: Vec<String> = it.collect();
        match run_ps(&argv) {
            Ok(()) => std::process::exit(0),
            Err(e) => {
                eprintln!("supermachine ps: {e}");
                std::process::exit(1);
            }
        }
    }
    if cmd == "logs" {
        let argv: Vec<String> = it.collect();
        match run_logs(&argv) {
            Ok(()) => std::process::exit(0),
            Err(e) => {
                eprintln!("supermachine logs: {e}");
                std::process::exit(1);
            }
        }
    }
    if cmd == "exec" {
        let argv: Vec<String> = it.collect();
        match run_exec(&argv) {
            Ok(code) => std::process::exit(code),
            Err(e) => {
                eprintln!("supermachine exec: {e}");
                std::process::exit(1);
            }
        }
    }
    if cmd != "run" {
        return Err(format!("unknown command: {cmd}"));
    }

    let mut image = None;
    let mut name = None;
    let mut connect = false;
    let mut detach = false;
    let mut stop = false;
    let mut http_port = std::env::var("SUPERMACHINE_HTTP_PORT")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(8080);
    let mut guest_port = 80;
    let mut memory_mib = 256;
    let mut vcpus: u32 = 1;
    // The --runtime/--backend CLI flag was a transient knob from the
    // Earlier rename transition. There's only one VMM now; the
    // value the rest of the code passes around is "supermachine" for
    // back-compat with the router's snapshot metadata format. It
    // should be `Some(())` morally — kept as a string for the
    // router's metadata.json round-trip until that's cleaned up.
    let mut runtime = "supermachine".to_owned();
    let mut snapshots_dir = std::env::var_os("SUPERMACHINE_SNAPSHOTS")
        .map(PathBuf::from)
        .unwrap_or_else(|| home_join(".local/supermachine-snapshots"));
    let mut workers_per_snapshot = std::env::var("SUPERMACHINE_WORKERS_PER_SNAPSHOT")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(1);
    let mut pull_policy =
        std::env::var("SUPERMACHINE_PULL_POLICY").unwrap_or_else(|_| "missing".to_owned());
    let mut do_push = true;
    let mut rm_on_stop = false;
    let mut stop_grace_ms: u64 = std::env::var("SUPERMACHINE_STOP_GRACE_MS")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(10_000);
    let state_dir = std::env::var_os("SUPERMACHINE_STATE_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|| home_join(".local/supermachine/run"));
    let mut pid_file = None;
    let mut log_file = None;
    let mut ready_timeout_ms = std::env::var("SUPERMACHINE_READY_TIMEOUT_MS")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(30000);
    let mut probe_path = None;
    let mut cmd_override = None;
    let mut push_args = Vec::new();

    while let Some(arg) = it.next() {
        match arg.as_str() {
            "--connect" => {
                connect = true;
                do_push = false;
            }
            "--detach" => {
                detach = true;
            }
            "--stop" => {
                stop = true;
                do_push = false;
            }
            "--http-port" => {
                let value = it
                    .next()
                    .ok_or_else(|| "missing --http-port value".to_owned())?;
                http_port = value.parse().map_err(|e| format!("--http-port: {e}"))?;
            }
            "--probe-path" => {
                let value = it
                    .next()
                    .ok_or_else(|| "missing --probe-path value".to_owned())?;
                if !value.starts_with('/') || value.contains('\r') || value.contains('\n') {
                    return Err("--probe-path must start with '/' and not contain CR/LF".to_owned());
                }
                probe_path = Some(value);
            }
            "--name" => {
                name = Some(it.next().ok_or_else(|| "missing --name value".to_owned())?);
            }
            "--port" => {
                let value = it.next().ok_or_else(|| "missing --port value".to_owned())?;
                guest_port = value.parse().map_err(|e| format!("--port: {e}"))?;
            }
            "--memory" => {
                let value = it
                    .next()
                    .ok_or_else(|| "missing --memory value".to_owned())?;
                memory_mib = value.parse().map_err(|e| format!("--memory: {e}"))?;
            }
            "--vcpus" | "--cpus" => {
                let value = it
                    .next()
                    .ok_or_else(|| "missing --vcpus value".to_owned())?;
                let n: u32 = value.parse().map_err(|e| format!("--vcpus: {e}"))?;
                // The original deferral
                // (docs/design/multi-vcpu-snapshot-intermittency-2026-04-27.md)
                // claimed 4+ vCPUs were ~50% reliable on HVF due to
                // the `ICH_LR_EL2` round-trip bug. With the
                // pause-and-capture rendezvous + 50ms quiesce window
                // (see vmm/coord.rs), the captured GIC blob is clean
                // because every secondary lands in WFI before the
                // snapshot fires. 2026-05-04 re-test:
                //   4-vCPU nginx: 25/25 cold-restore
                //   4-vCPU compat battery: 6/6 viable workloads 5/5
                //   4-vCPU under c=128 sustained: 10/10
                //   8-vCPU nginx: 15/15 cold-restore
                // No gate needed; just bound to a sane upper limit.
                if n == 0 {
                    return Err("--vcpus must be >= 1".to_owned());
                }
                if n > 16 {
                    return Err(format!("--vcpus must be <= 16, got {n}"));
                }
                vcpus = n;
            }
            "--runtime" | "--backend" => {
                // Accepted for back-compat (used to be a backend name vs
                // the VMM had alternative backends. They're gone; the value is ignored
                // beyond a friendly error if someone passes the old
                // backend.
                let value = it.next().ok_or_else(|| format!("missing {arg} value"))?;
                if value == "spike14" || value == "spike22" {  // legacy backend names
                    return Err(
                        "that --runtime value is from a previous backend split that has since collapsed; supermachine is the only VMM now"
                            .to_owned(),
                    );
                }
                runtime = value;
            }
            "--workers-per-snapshot" => {
                let value = it
                    .next()
                    .ok_or_else(|| "missing --workers-per-snapshot value".to_owned())?;
                workers_per_snapshot = value
                    .parse()
                    .map_err(|e| format!("--workers-per-snapshot: {e}"))?;
            }
            "--snapshots-dir" => {
                snapshots_dir = PathBuf::from(
                    it.next()
                        .ok_or_else(|| "missing --snapshots-dir value".to_owned())?,
                );
            }
            "--pull" => {
                pull_policy = it.next().ok_or_else(|| "missing --pull value".to_owned())?;
            }
            "--pid-file" => {
                pid_file = Some(PathBuf::from(
                    it.next()
                        .ok_or_else(|| "missing --pid-file value".to_owned())?,
                ));
            }
            "--log-file" => {
                log_file = Some(PathBuf::from(
                    it.next()
                        .ok_or_else(|| "missing --log-file value".to_owned())?,
                ));
            }
            "--ready-timeout-ms" => {
                let value = it
                    .next()
                    .ok_or_else(|| "missing --ready-timeout-ms value".to_owned())?;
                ready_timeout_ms = value
                    .parse()
                    .map_err(|e| format!("--ready-timeout-ms: {e}"))?;
            }
            "--cmd" => {
                let value = it.next().ok_or_else(|| "missing --cmd value".to_owned())?;
                cmd_override = Some(value.clone());
                push_args.push(arg);
                push_args.push(value);
            }
            "--volume" | "-v" => {
                // --volume HOST:GUEST — HOST is either a name (resolved
                // to ~/.local/supermachine/volumes/<name>.img) or an
                // absolute path to a host file. The bake pipeline
                // accepts these via --volume; init-oci mounts them
                // post-pivot. Format-on-first-use happens on the host
                // before the worker spawns. See VolumeSpec.
                let value = it.next().ok_or_else(|| "missing --volume value".to_owned())?;
                push_args.push("--volume".to_owned());
                push_args.push(value);
            }
            "--health-cmd" => {
                let value = it.next().ok_or_else(|| "missing --health-cmd value".to_owned())?;
                push_args.push("--health-cmd".to_owned());
                push_args.push(value);
            }
            "--health-interval" => {
                let value = it.next().ok_or_else(|| "missing --health-interval value".to_owned())?;
                let n: u64 = value
                    .parse()
                    .map_err(|e| format!("--health-interval (seconds): {e}"))?;
                if n == 0 || n > 3600 {
                    return Err(format!("--health-interval must be 1..=3600s, got {n}"));
                }
                push_args.push("--health-interval".to_owned());
                push_args.push(n.to_string());
            }
            "--restart" => {
                // docker run --restart=no|on-failure|always.
                // Stored in snapshot metadata; the router daemon's
                // watchdog reads it and decides whether to respawn
                // a dead worker. `unless-stopped` is accepted as
                // an alias for `always` since our daemon goes
                // away on `--stop` anyway.
                let value = it.next().ok_or_else(|| "missing --restart value".to_owned())?;
                let normalized = match value.as_str() {
                    "no" | "always" | "on-failure" => value.clone(),
                    "unless-stopped" => "always".to_owned(),
                    s => return Err(format!("--restart must be no|on-failure|always|unless-stopped, got {s:?}")),
                };
                push_args.push("--restart".to_owned());
                push_args.push(normalized);
            }
            "--entrypoint" | "--workdir" | "--user" | "--hostname" => {
                // docker-style runtime overrides. `--workdir` and `--user`
                // override the image's WORKDIR / USER (init-oci already
                // honors `.supermachine-workdir` / `.supermachine-user`
                // in the delta squashfs; bake plumbing reads these
                // flags from extra_args). `--entrypoint` replaces the
                // image's ENTRYPOINT — final argv becomes
                // [entrypoint, ...effective_cmd]. `--hostname` writes
                // `.supermachine-hostname` so init-oci can `sethostname`
                // before exec'ing the workload.
                //
                // No short forms: docker's `-h` clashes with --help and
                // `-w` / `-u` are infrequently used with `docker run`.
                let value = it.next().ok_or_else(|| format!("missing {arg} value"))?;
                push_args.push(arg);
                push_args.push(value);
            }
            "--supermachine-snapshot-after-ms"
            | "--supermachine-listener-settle-ms"
            | "--extra-file"
            | "--env"
            | "--egress-policy"
            | "--inbound-tls-cert"
            | "--inbound-tls-key" => {
                let value = it.next().ok_or_else(|| format!("missing {arg} value"))?;
                push_args.push(arg);
                push_args.push(value);
            }
            "--rm" => {
                rm_on_stop = true;
            }
            "--stop-grace" | "-t" => {
                // Seconds (matches `docker stop -t`); convert to ms.
                let value = it
                    .next()
                    .ok_or_else(|| "missing --stop-grace value".to_owned())?;
                let secs: f64 = value
                    .parse()
                    .map_err(|e| format!("--stop-grace: {e}"))?;
                if secs < 0.0 || secs > 600.0 {
                    return Err(format!("--stop-grace must be 0..=600s, got {secs}"));
                }
                stop_grace_ms = (secs * 1000.0) as u64;
            }
            "--no-push" | "--enable-egress" | "--no-egress" | "--inbound-tls-autogen" => {
                if arg == "--no-push" {
                    do_push = false;
                } else {
                    push_args.push(arg);
                }
            }
            "--help" | "-h" => {
                usage();
                std::process::exit(0);
            }
            s if s.starts_with('-') => return Err(format!("unknown flag: {s}")),
            s => {
                if image.is_some() {
                    return Err(format!("extra arg: {s}"));
                }
                image = Some(s.to_owned());
            }
        }
    }

    if !connect && !stop && image.is_none() {
        return Err("missing image".to_owned());
    }

    if runtime != "supermachine" {
        return Err(format!(
            "unknown runtime: {runtime} (the only supported runtime is supermachine)"
        ));
    }
    if !matches!(pull_policy.as_str(), "missing" | "always" | "never") {
        return Err(format!("unknown --pull policy: {pull_policy}"));
    }
    let pid_file = pid_file.unwrap_or_else(|| state_dir.join(format!("router-{http_port}.pid")));
    let log_file = log_file.unwrap_or_else(|| state_dir.join(format!("router-{http_port}.log")));

    Ok(Args {
        image,
        name,
        connect,
        detach,
        stop,
        http_port,
        guest_port,
        memory_mib,
        vcpus,
        runtime,
        snapshots_dir,
        workers_per_snapshot,
        pull_policy,
        do_push,
        rm_on_stop,
        stop_grace_ms,
        pid_file,
        log_file,
        ready_timeout_ms,
        probe_path,
        cmd_override,
        push_args,
    })
}

struct HttpResponse {
    status: u16,
    bytes: Vec<u8>,
}

fn http_get(port: u16, path: &str) -> std::io::Result<HttpResponse> {
    let mut stream = TcpStream::connect(("127.0.0.1", port))?;
    stream.set_read_timeout(Some(Duration::from_millis(200)))?;
    stream.set_write_timeout(Some(Duration::from_millis(200)))?;
    write!(
        stream,
        "GET {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"
    )?;

    let mut buf = Vec::with_capacity(1024);
    let mut tmp = [0u8; 1024];
    loop {
        match stream.read(&mut tmp) {
            Ok(0) => break,
            Ok(n) => {
                buf.extend_from_slice(&tmp[..n]);
            }
            Err(e)
                if e.kind() == std::io::ErrorKind::WouldBlock
                    || e.kind() == std::io::ErrorKind::TimedOut =>
            {
                break
            }
            Err(e) => return Err(e),
        }
    }
    let status = parse_status(&buf).unwrap_or(0);
    Ok(HttpResponse { status, bytes: buf })
}

fn parse_status(buf: &[u8]) -> Option<u16> {
    let first_line_end = buf.windows(2).position(|w| w == b"\r\n")?;
    let first_line = std::str::from_utf8(&buf[..first_line_end]).ok()?;
    let mut parts = first_line.split_ascii_whitespace();
    let version = parts.next()?;
    if !version.starts_with("HTTP/") {
        return None;
    }
    parts.next()?.parse().ok()
}

fn health_ok(port: u16) -> std::io::Result<bool> {
    let response = http_get(port, "/_health")?;
    Ok(response.status == 200
        && response
            .bytes
            .windows(br#""status":"ok""#.len())
            .any(|w| w == br#""status":"ok""#))
}

fn probe_200(port: u16, path: &str) -> std::io::Result<bool> {
    Ok(http_get(port, path)?.status == 200)
}

/// Workload readiness probe. Customer doesn't have to know the
/// content of `/`: any HTTP response (2xx/3xx/4xx) means the worker
/// is wired through and the guest workload is answering. We only
/// keep retrying when:
///   - TCP refused/timed out (router not up yet)
///   - 502 from the router (worker can't reach the guest's listener)
///   - 503/504 (transient unavailable)
/// Returns Ok(true) on workload-responding, Ok(false) on persistent
/// error after `total_timeout_ms`, Err on unrecoverable I/O.
fn workload_responding(port: u16, total_timeout_ms: u64) -> std::io::Result<bool> {
    let deadline =
        std::time::Instant::now() + std::time::Duration::from_millis(total_timeout_ms);
    let mut last_err: Option<std::io::Error> = None;
    while std::time::Instant::now() < deadline {
        match http_get(port, "/") {
            Ok(resp) => {
                // 502/503/504 mean upstream isn't ready — keep waiting.
                // Any other status (200, 301, 404, ...) is the workload
                // answering.
                if matches!(resp.status, 502 | 503 | 504) {
                    last_err = Some(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("upstream {}: {}", resp.status, String::from_utf8_lossy(&resp.bytes).chars().take(120).collect::<String>()),
                    ));
                } else {
                    return Ok(true);
                }
            }
            Err(e) => last_err = Some(e),
        }
        // Tight poll: cold-boot is on the order of ~100 ms total, so
        // a 50 ms sleep here would add up to half the wall-clock as
        // unnecessary slop. Match `wait_ready`'s 5 ms cadence.
        std::thread::sleep(std::time::Duration::from_millis(5));
    }
    if let Some(e) = last_err {
        Err(e)
    } else {
        Ok(false)
    }
}

/// Resolve a "root" the helpers below can hang absolute paths off.
/// Honoured in this order:
///   1. $SUPERMACHINE_ROOT — user's explicit override
///   2. dev-tree marker: walk binary's ancestors for `tools/supermachine-push`
///   3. installed-tree marker: walk binary's ancestors for `share/supermachine/kernel`
///      and return the parent (so `<root>/share/supermachine/kernel` resolves)
///   4. cwd, as a last-resort fallback
fn repo_root() -> Result<PathBuf, String> {
    if let Some(root) = std::env::var_os("SUPERMACHINE_ROOT") {
        return Ok(PathBuf::from(root));
    }

    let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
    // Dev-tree: cargo build target/release tree under a checkout.
    for ancestor in exe.ancestors() {
        if ancestor.join("tools/supermachine-push").is_file() {
            return Ok(ancestor.to_path_buf());
        }
    }
    // Installed-tree: <prefix>/bin/supermachine + <prefix>/share/supermachine/.
    for ancestor in exe.ancestors() {
        if ancestor.join("share/supermachine/kernel").is_file() {
            return Ok(ancestor.to_path_buf());
        }
    }
    std::env::current_dir().map_err(|e| format!("current_dir: {e}"))
}



/// `supermachine setup` — explicit force-resign of the worker
/// binary + asset extraction sanity check. Most users never call
/// this: the CLI auto-signs on first invocation (see
/// `supermachine::codesign::ensure_worker_signed`). Run this when
/// you want to force the work eagerly (e.g. immediately after
/// `cargo build` strips the entitlement on a dev tree, before
/// shipping a tarball).
fn run_setup() -> Result<(), String> {
    let mut errors = Vec::new();
    let mut ok_steps = Vec::new();

    #[cfg(target_os = "macos")]
    {
        // Force re-sign by invalidating the in-process cache; the
        // sentinel-on-disk check still applies, but with --force
        // codesign re-signs even if previously signed. We just
        // call ensure_worker_signed which is idempotent.
        match supermachine::codesign::locate_worker_bin() {
            Some(bin) => match supermachine::codesign::ensure_worker_signed(&bin) {
                Ok(()) => ok_steps.push(format!("signed {}", bin.display())),
                Err(e) => errors.push(format!("codesign: {e}")),
            },
            None => errors.push(
                "supermachine-worker not found. \
                 If you `cargo install`d, the worker should be a sibling \
                 of supermachine in ~/.cargo/bin/. If you `cargo build`d, \
                 it lives at target/release/supermachine-worker."
                    .to_owned(),
            ),
        }
    }

    let assets = supermachine::AssetPaths::discover();
    match assets.kernel.as_deref() {
        Some(k) => ok_steps.push(format!("kernel ready at {}", k.display())),
        None => errors.push(
            "kernel asset not found. The supermachine-kernel crate ships \
             the kernel bytes inside this binary; first AssetPaths::discover() \
             call extracts them to $XDG_DATA_HOME/supermachine/v{VERSION}/. \
             If extraction failed, check that ~/.local/share/supermachine/ \
             is writable."
                .to_owned(),
        ),
    }
    match assets.init_oci_bin.as_deref() {
        Some(p) => ok_steps.push(format!("init-oci ready at {}", p.display())),
        None => errors.push(
            "init-oci asset not found (same root cause as kernel; see above).".to_owned(),
        ),
    }

    println!("supermachine setup:");
    for s in &ok_steps {
        println!("  ok: {s}");
    }
    for e in &errors {
        println!("  err: {e}");
    }
    if errors.is_empty() {
        println!("  (ready — try `supermachine run python:3.12-alpine ...`)");
        Ok(())
    } else {
        Err(format!("{} step(s) failed", errors.len()))
    }
}

/// `supermachine codesign BINARY [--identity IDENTITY]` — sign a
/// binary with the bundled HVF entitlements plist, so it can call
/// `hv_vm_create`. Default is ad-hoc signing (`-s -`); pass
/// `--identity "Developer ID Application: ..."` for distribution.
///
/// The bundled plist is dropped to a temp file (it lives inside
/// the supermachine binary as a compile-time `include_str!`), used
/// once for the codesign call, then unlinked.
fn run_codesign(argv: &[String]) -> Result<(), String> {
    let mut binary: Option<&str> = None;
    let mut identity: String = "-".to_owned();   // ad-hoc by default
    let mut i = 0;
    while i < argv.len() {
        match argv[i].as_str() {
            "--identity" | "-s" => {
                i += 1;
                identity = argv
                    .get(i)
                    .ok_or_else(|| "missing --identity value".to_owned())?
                    .clone();
            }
            "--help" | "-h" => {
                eprintln!(
                    "usage: supermachine codesign BINARY [--identity IDENTITY]\n\
                     \n\
                     Default IDENTITY is `-` (ad-hoc).  For a distributable .app,\n\
                     pass `--identity \"Developer ID Application: Name (TEAMID)\"`."
                );
                std::process::exit(0);
            }
            s if s.starts_with('-') => {
                return Err(format!("unknown flag: {s}"));
            }
            s => {
                if binary.is_some() {
                    return Err(format!("extra arg: {s}"));
                }
                binary = Some(s);
            }
        }
        i += 1;
    }
    let binary = binary.ok_or_else(|| "missing BINARY argument".to_owned())?;

    // Drop the bundled plist to a temp file so codesign can read it.
    let plist_dir = std::env::temp_dir();
    let plist_path = plist_dir.join(format!("supermachine-entitlements-{}.plist", std::process::id()));
    std::fs::write(&plist_path, supermachine::assets::ENTITLEMENTS_PLIST)
        .map_err(|e| format!("write temp plist {}: {e}", plist_path.display()))?;

    let result = (|| {
        let mut cmd = Command::new("codesign");
        cmd.args(["-s", &identity, "--entitlements"])
            .arg(&plist_path)
            .arg("--force");
        if identity != "-" {
            // For real Developer ID signing, also enable Hardened Runtime
            // (required for notarization).
            cmd.args(["--options", "runtime"]);
        }
        cmd.arg(binary);
        let status = cmd.status().map_err(|e| format!("spawn codesign: {e}"))?;
        if status.success() {
            Ok(())
        } else {
            Err(format!("codesign exit {:?}", status.code()))
        }
    })();
    let _ = std::fs::remove_file(&plist_path);
    result?;
    println!("signed {binary}  (identity: {identity})");
    Ok(())
}

/// `supermachine bundle --into DIR [--image NAME]` — produce a
/// self-contained dir an embedder can ship inside their `.app`.
///
/// Two modes:
///
/// - **Asset-only** (no `--image`): copy kernel + init shim into
///   DIR. Use when you bake at runtime in your embedder. DIR
///   is typically `MyApp.app/Contents/Resources/`.
/// - **Snapshot bundle** (`--image NAME`): copy the kernel,
///   `restore.snap`, `metadata.json` (with paths relativized),
///   `delta.squashfs`, and every layer `.squashfs` referenced by
///   the snapshot. The result is a stand-alone restorable set.
///   Embedder calls
///   `Image::from_snapshot("Contents/Resources/<name>/")` and
///   doesn't need supermachine installed on the user's machine.
fn run_bundle(argv: &[String]) -> Result<(), String> {
    let mut into: Option<PathBuf> = None;
    let mut image: Option<String> = None;
    let mut snapshots_dir = default_snapshots_dir();
    let mut i = 0;
    while i < argv.len() {
        match argv[i].as_str() {
            "--into" => {
                i += 1;
                into = Some(PathBuf::from(
                    argv.get(i)
                        .ok_or_else(|| "missing --into value".to_owned())?,
                ));
            }
            "--image" => {
                i += 1;
                image = Some(
                    argv.get(i)
                        .ok_or_else(|| "missing --image value".to_owned())?
                        .clone(),
                );
            }
            "--snapshots-dir" => {
                i += 1;
                snapshots_dir = PathBuf::from(
                    argv.get(i)
                        .ok_or_else(|| "missing --snapshots-dir value".to_owned())?,
                );
            }
            "--help" | "-h" => {
                eprintln!(
                    "usage: supermachine bundle --into DIR [--image NAME]\n\
                     \x20                          [--snapshots-dir DIR]\n\
                     \n\
                     Without --image: copies the kernel image and init shim into\n\
                     DIR (typically `YourApp.app/Contents/Resources/`).\n\
                     \n\
                     With --image NAME: produces a self-contained snapshot bundle\n\
                     at DIR/NAME/ containing the kernel, restore.snap, metadata.json\n\
                     (with paths relativized), delta.squashfs, and every layer\n\
                     squashfs referenced by the snapshot. The embedder loads it via\n\
                     `Image::from_snapshot(\"...Resources/NAME/\")` — no supermachine\n\
                     install needed on the end user's machine.\n\
                     \n\
                     NAME accepts either a snapshot dir name (as shown by\n\
                     `supermachine images`) or an image ref (`nginx:1.27-alpine`,\n\
                     auto-sanitized)."
                );
                std::process::exit(0);
            }
            s => return Err(format!("unknown arg: {s}")),
        }
        i += 1;
    }
    let into = into.ok_or_else(|| "missing --into DIR".to_owned())?;
    std::fs::create_dir_all(&into)
        .map_err(|e| format!("mkdir {}: {e}", into.display()))?;

    if let Some(image) = image {
        return bundle_snapshot(&into, &image, &snapshots_dir);
    }

    let assets = supermachine::assets::AssetPaths::discover();
    let mut copied = 0;

    if let Some(kernel) = &assets.kernel {
        let dst = into.join("kernel");
        std::fs::copy(kernel, &dst)
            .map_err(|e| format!("copy kernel {}{}: {e}", kernel.display(), dst.display()))?;
        println!("  kernel:    {}{}", kernel.display(), dst.display());
        copied += 1;
    } else {
        return Err(
            "no kernel found in any standard location — set $SUPERMACHINE_ASSETS_DIR or rebuild from source".to_owned(),
        );
    }

    if let Some(init_bin) = &assets.init_oci_bin {
        let dst = into.join("init-oci");
        std::fs::copy(init_bin, &dst)
            .map_err(|e| format!("copy init-oci {}{}: {e}", init_bin.display(), dst.display()))?;
        // preserve executable bit
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&dst)
                .map_err(|e| format!("stat {}: {e}", dst.display()))?
                .permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&dst, perms)
                .map_err(|e| format!("chmod {}: {e}", dst.display()))?;
        }
        println!("  init-oci:  {}{}", init_bin.display(), dst.display());
        copied += 1;
    }

    if let Some(init_src) = &assets.init_oci_src {
        let dst = into.join("init-oci.c");
        std::fs::copy(init_src, &dst)
            .map_err(|e| format!("copy init-oci.c {}{}: {e}", init_src.display(), dst.display()))?;
        println!("  init-oci.c:{}{}", init_src.display(), dst.display());
        copied += 1;
    }

    println!("bundled {copied} asset(s) into {}", into.display());
    Ok(())
}

/// Snapshot-bundle layout (under `<into>/<name>/`):
///
/// ```text
/// kernel                       # bundled kernel image
/// restore.snap                 # snapshot file (CoW-mapped at restore)
/// metadata.json                # paths rewritten to ./layers/... etc.
/// delta.squashfs               # writable overlay layer (if any)
/// layers/<sha>.squashfs ...    # all layers referenced by metadata
/// ```
///
/// The result is `cp -r`-able to any Mac with HVF + entitlement. No
/// other files on the host are touched at restore time.
fn bundle_snapshot(into: &Path, image: &str, snapshots_dir: &Path) -> Result<(), String> {
    // Resolve `image` to a snapshot dir under `snapshots_dir`. Accept
    // either a literal dir name or an image ref.
    let candidate = snapshots_dir.join(image);
    let snap_dir = if candidate.is_dir() {
        candidate
    } else {
        let derived = snapshots_dir.join(supermachine::bake::snapshot_name_for_image(image));
        if !derived.is_dir() {
            return Err(format!(
                "no snapshot for {image} (looked in {} and {})",
                candidate.display(),
                derived.display(),
            ));
        }
        derived
    };
    let name = snap_dir
        .file_name()
        .and_then(|s| s.to_str())
        .ok_or_else(|| format!("snapshot dir has no name: {}", snap_dir.display()))?
        .to_owned();
    let metadata_src = snap_dir.join("metadata.json");
    if !metadata_src.is_file() {
        return Err(format!("missing {}", metadata_src.display()));
    }
    let restore_src = snap_dir.join("restore.snap");
    if !restore_src.is_file() {
        return Err(format!("missing {}", restore_src.display()));
    }

    let bundle_dir = into.join(&name);
    std::fs::create_dir_all(&bundle_dir)
        .map_err(|e| format!("mkdir {}: {e}", bundle_dir.display()))?;
    let layers_dir = bundle_dir.join("layers");
    std::fs::create_dir_all(&layers_dir)
        .map_err(|e| format!("mkdir {}: {e}", layers_dir.display()))?;

    let mut total_bytes: u64 = 0;

    // Kernel — from the host's discovered AssetPaths, NOT from the
    // snapshot's metadata.json (which points at the bake-time
    // location, often a per-developer cargo target dir).
    let assets = supermachine::assets::AssetPaths::discover();
    let kernel = assets.kernel.as_ref().ok_or_else(|| {
        "no kernel found in any standard location — set $SUPERMACHINE_ASSETS_DIR or rebuild from source"
            .to_owned()
    })?;
    let kernel_dst = bundle_dir.join("kernel");
    let kernel_bytes = std::fs::copy(kernel, &kernel_dst)
        .map_err(|e| format!("copy kernel {}{}: {e}", kernel.display(), kernel_dst.display()))?;
    total_bytes += kernel_bytes;
    println!("  kernel:        {} ({})", kernel_dst.display(), human_bytes(kernel_bytes));

    // Snapshot file.
    let restore_dst = bundle_dir.join("restore.snap");
    let restore_bytes = std::fs::copy(&restore_src, &restore_dst)
        .map_err(|e| format!("copy restore.snap: {e}"))?;
    total_bytes += restore_bytes;
    println!("  restore.snap:  {} ({})", restore_dst.display(), human_bytes(restore_bytes));

    // Read source metadata, rewrite paths to relative.
    let meta_text = std::fs::read_to_string(&metadata_src)
        .map_err(|e| format!("read {}: {e}", metadata_src.display()))?;
    let mut meta: serde_json::Value = serde_json::from_str(&meta_text)
        .map_err(|e| format!("parse {}: {e}", metadata_src.display()))?;

    // Rewrite metadata.kernel to match the bundled layout. The
    // runtime restore path picks up the kernel via
    // `<bundle_dir>/kernel` discovery in `Image::from_snapshot`,
    // not via this field — but tooling reading metadata.json
    // shouldn't be misled by a stale absolute path.
    if let Some(obj) = meta.as_object_mut() {
        obj.insert(
            "kernel".to_owned(),
            serde_json::Value::String("kernel".to_owned()),
        );
    }

    // Layers: copy each into <bundle>/layers/<basename>, rewrite
    // metadata.layers to a relative path.
    if let Some(layers) = meta.get("layers").cloned().and_then(|v| match v {
        serde_json::Value::Array(a) => Some(a),
        _ => None,
    }) {
        let mut new_layers: Vec<serde_json::Value> = Vec::with_capacity(layers.len());
        for layer in &layers {
            let src = layer
                .as_str()
                .ok_or_else(|| "layer path is not a string".to_owned())?;
            let src_path = PathBuf::from(src);
            if !src_path.is_file() {
                return Err(format!(
                    "layer file missing: {} (referenced by {})",
                    src_path.display(),
                    metadata_src.display()
                ));
            }
            let basename = src_path
                .file_name()
                .ok_or_else(|| format!("layer path has no filename: {}", src_path.display()))?;
            let dst = layers_dir.join(basename);
            let bytes = std::fs::copy(&src_path, &dst).map_err(|e| {
                format!("copy layer {}{}: {e}", src_path.display(), dst.display())
            })?;
            total_bytes += bytes;
            // Relative form: "layers/<basename>".
            new_layers.push(serde_json::Value::String(format!(
                "layers/{}",
                basename.to_string_lossy()
            )));
        }
        if let Some(obj) = meta.as_object_mut() {
            obj.insert("layers".to_owned(), serde_json::Value::Array(new_layers));
        }
        println!("  layers:        {} files ({})", layers.len(), human_bytes(total_bytes - kernel_bytes - restore_bytes));
    }

    // Delta squashfs (writable overlay) — optional.
    if let Some(delta) = meta.get("delta_squashfs").and_then(|v| v.as_str()).map(PathBuf::from) {
        if delta.is_file() {
            let dst = bundle_dir.join("delta.squashfs");
            let bytes = std::fs::copy(&delta, &dst)
                .map_err(|e| format!("copy delta.squashfs: {e}"))?;
            total_bytes += bytes;
            if let Some(obj) = meta.as_object_mut() {
                obj.insert(
                    "delta_squashfs".to_owned(),
                    serde_json::Value::String("delta.squashfs".to_owned()),
                );
            }
            println!("  delta.squashfs:{} ({})", dst.display(), human_bytes(bytes));
        }
    }

    // init.cpio.gz — boot-time initramfs. Some snapshots reference
    // it; copy if present so an embedder running fresh-bake on the
    // same workload wouldn't be surprised by a missing file.
    let init_cpio = snap_dir.join("init.cpio.gz");
    if init_cpio.is_file() {
        let dst = bundle_dir.join("init.cpio.gz");
        let bytes = std::fs::copy(&init_cpio, &dst)
            .map_err(|e| format!("copy init.cpio.gz: {e}"))?;
        total_bytes += bytes;
        if let Some(obj) = meta.as_object_mut() {
            obj.insert(
                "init_cpio".to_owned(),
                serde_json::Value::String("init.cpio.gz".to_owned()),
            );
        }
    }

    // Drop the rewritten metadata into the bundle. Keep the original
    // pretty-printing style — it's user-readable.
    let metadata_dst = bundle_dir.join("metadata.json");
    let pretty = serde_json::to_string_pretty(&meta)
        .map_err(|e| format!("serialize metadata: {e}"))?;
    std::fs::write(&metadata_dst, pretty)
        .map_err(|e| format!("write {}: {e}", metadata_dst.display()))?;
    println!("  metadata.json: {}", metadata_dst.display());

    println!(
        "bundled {} ({}) into {}",
        name,
        human_bytes(total_bytes),
        bundle_dir.display()
    );
    println!(
        "  load it from Rust: Image::from_snapshot(\"{}\")",
        bundle_dir.display()
    );
    Ok(())
}

/// `supermachine entitlements-path` — write the bundled plist to a
/// temp file and print the path. Useful for CI scripts that want
/// to call `codesign --entitlements $(supermachine entitlements-path)`
/// directly without going through `supermachine codesign`.
///
/// Note: the file is left on disk. The caller is responsible for
/// cleanup if they care; otherwise the OS reaps `/tmp` on its own
/// schedule. Path includes the PID so concurrent invocations don't
/// collide.
fn run_entitlements_path() -> Result<(), String> {
    let path = std::env::temp_dir()
        .join(format!("supermachine-entitlements-{}.plist", std::process::id()));
    std::fs::write(&path, supermachine::assets::ENTITLEMENTS_PLIST)
        .map_err(|e| format!("write temp plist {}: {e}", path.display()))?;
    println!("{}", path.display());
    Ok(())
}

/// `supermachine assets-path` — print where supermachine looks for
/// kernel + init shim. Debug helper for users who can't figure out
/// why their VM isn't starting.
fn run_assets_path() {
    let assets = supermachine::assets::AssetPaths::discover();
    println!("kernel:       {}",
        assets.kernel.as_ref().map(|p| p.display().to_string()).unwrap_or_else(|| "(not found)".to_owned())
    );
    println!("init-oci bin: {}",
        assets.init_oci_bin.as_ref().map(|p| p.display().to_string()).unwrap_or_else(|| "(not found)".to_owned())
    );
    println!("init-oci src: {}",
        assets.init_oci_src.as_ref().map(|p| p.display().to_string()).unwrap_or_else(|| "(not found)".to_owned())
    );
    if let Ok(d) = std::env::var("SUPERMACHINE_ASSETS_DIR") {
        println!("(SUPERMACHINE_ASSETS_DIR override: {d})");
    }
}

fn router_bin(root: &Path) -> Result<PathBuf, String> {
    // Tried in order:
    //   - sibling of the running binary (`cargo install` layout —
    //     ~/.cargo/bin/supermachine-router next to ~/.cargo/bin/supermachine)
    //   - dev tree:        <root>/target/release/supermachine-router
    //   - tarball install: <root>/bin/supermachine-router
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            let sibling = dir.join("supermachine-router");
            if sibling.is_file() {
                return Ok(sibling);
            }
        }
    }
    for candidate in [
        "target/release/supermachine-router",
        "bin/supermachine-router",
    ] {
        let p = root.join(candidate);
        if p.is_file() {
            return Ok(p);
        }
    }
    Err(format!(
        "missing router binary at {} (run `cargo build --release`)",
        root.join("target/release/supermachine-router").display()
    ))
}

fn run_push(args: &Args, run_t0: Instant) -> Result<(), String> {
    if !args.do_push {
        if trace_enabled() {
            eprintln!(
                "supermachine: push skipped after {}ms",
                elapsed_ms(run_t0)
            );
        }
        return Ok(());
    }
    let root = repo_root()?;
    let image = args
        .image
        .clone()
        .ok_or_else(|| "missing image".to_owned())?;
    let request = bake::BakeRequest {
        image,
        name: args.name.clone(),
        runtime: args.runtime.clone(),
        guest_port: args.guest_port,
        memory_mib: args.memory_mib,
        vcpus: args.vcpus,
        pull_policy: args.pull_policy.clone(),
        snapshots_dir: args.snapshots_dir.clone(),
        cmd_override: args.cmd_override.clone(),
        extra_args: args.push_args.clone(),
    };
    bake::run_push(&request, run_t0, &root)
}

fn process_alive(pid: u32) -> bool {
    Command::new("kill")
        .arg("-0")
        .arg(pid.to_string())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

fn signal_process(pid: u32, signal: &str) {
    let _ = Command::new("kill")
        .arg(format!("-{signal}"))
        .arg(pid.to_string())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
}

fn router_sidecar_path(pid_file: &Path, suffix: &str) -> PathBuf {
    // pid_file is `<state>/router-<port>.pid` — replace the
    // extension to land sidecar files next to it.
    let mut p = pid_file.to_path_buf();
    p.set_extension(suffix);
    p
}

fn stop_router(args: &Args) -> Result<(), String> {
    let pid_text = match std::fs::read_to_string(&args.pid_file) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            // Even with no live daemon, honor --rm so the user can
            // clean up snapshots from previous foreground runs.
            if args.rm_on_stop {
                rm_snapshot_for_args(args)?;
            }
            return Ok(());
        }
        Err(e) => return Err(format!("read pid file {}: {e}", args.pid_file.display())),
    };
    let pid: u32 = match pid_text.trim().parse() {
        Ok(pid) => pid,
        Err(e) => {
            let _ = std::fs::remove_file(&args.pid_file);
            return Err(format!("invalid pid file {}: {e}", args.pid_file.display()));
        }
    };
    if process_alive(pid) {
        // docker-stop semantics: send SIGTERM to the workload via
        // the in-guest agent first so the workload's own cleanup
        // hooks run (db flush, AOF rewrite, etc). Then signal the
        // router/worker. Wait up to args.stop_grace_ms for a clean
        // exit, fall back to SIGKILL.
        //
        // Best-effort: if the agent isn't reachable (older snapshot
        // baked before agent shipped, or workload not yet spawned),
        // we still proceed to host-level TERM. The volume data
        // path is still safe via virtio-blk MS_SYNC on FLUSH.
        let snapshot_sidecar_early = router_sidecar_path(&args.pid_file, "snapshot");
        if let Ok(snap_name) = std::fs::read_to_string(&snapshot_sidecar_early) {
            let snap_name = snap_name.trim();
            if !snap_name.is_empty() {
                let exec_sock = PathBuf::from(format!(
                    "/tmp/supermachine-router-socks/{snap_name}-w0.sock-exec"
                ));
                if exec_sock.exists() {
                    let body = serde_json::json!({
                        "action": "signal",
                        "signum": 15,  // SIGTERM
                    });
                    if let Err(e) = supermachine::exec::send_control(&exec_sock, &body) {
                        if std::env::var_os("SUPERMACHINE_RUN_TRACE").is_some() {
                            eprintln!("supermachine: workload SIGTERM via agent: {e}");
                        }
                    }
                }
            }
        }
        signal_process(pid, "TERM");
        let grace_iters = (args.stop_grace_ms / 50).max(1);
        for _ in 0..grace_iters {
            if !process_alive(pid) {
                break;
            }
            std::thread::sleep(Duration::from_millis(50));
        }
        if process_alive(pid) {
            signal_process(pid, "KILL");
        }
    }
    // Read sidecar before deleting so we know which snapshot to wipe
    // and whether --rm was sticky from the original `run --detach`.
    let snapshot_sidecar = router_sidecar_path(&args.pid_file, "snapshot");
    let rm_sidecar = router_sidecar_path(&args.pid_file, "rm");
    let sticky_rm = rm_sidecar.exists();
    let snapshot_name = std::fs::read_to_string(&snapshot_sidecar)
        .ok()
        .map(|s| s.trim().to_owned())
        .filter(|s| !s.is_empty());

    let _ = std::fs::remove_file(&args.pid_file);
    let _ = std::fs::remove_file(&snapshot_sidecar);
    let _ = std::fs::remove_file(&rm_sidecar);

    if args.rm_on_stop || sticky_rm {
        // Prefer the sidecar's name (recorded at start time) so a
        // bare `supermachine run --stop --rm` still wipes the right
        // snapshot without having to repeat the image ref.
        let name = snapshot_name
            .or_else(|| derive_default_snapshot_name(args))
            .ok_or_else(|| {
                "--rm on stop: cannot determine which snapshot to remove (no sidecar, no image, no --name)"
                    .to_owned()
            })?;
        rm_snapshot(&args.snapshots_dir, &name)?;
    }
    Ok(())
}

/// Wipe the snapshot dir at `<snapshots_dir>/<name>`. Used by `rmi`
/// and by `--rm` cleanup. Cached layer blobs in
/// `~/.local/supermachine-layer-cache/` are intentionally left
/// behind: they're shared across snapshots and re-downloading
/// layers is the expensive bit. `supermachine rmi` only removes
/// the per-image bake artifacts.
fn rm_snapshot(snapshots_dir: &Path, name: &str) -> Result<(), String> {
    if name.is_empty() || name.contains('/') || name.contains('\\') {
        return Err(format!("invalid snapshot name: {name:?}"));
    }
    let dir = snapshots_dir.join(name);
    match std::fs::remove_dir_all(&dir) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            Err(format!("no such snapshot: {name}"))
        }
        Err(e) => Err(format!("remove {}: {e}", dir.display())),
    }
}

fn rm_snapshot_for_args(args: &Args) -> Result<(), String> {
    let name = derive_default_snapshot_name(args).ok_or_else(|| {
        "--rm: cannot determine which snapshot to remove (need image or --name)".to_owned()
    })?;
    // Treat "snapshot already gone" as success in the cleanup path —
    // the user's intent is "make sure it's gone."
    match rm_snapshot(&args.snapshots_dir, &name) {
        Ok(()) | Err(_) => Ok(()),
    }
}

fn wait_ready(port: u16, timeout_ms: u64) -> bool {
    let deadline = Instant::now() + Duration::from_millis(timeout_ms);
    loop {
        if health_ok(port).unwrap_or(false) {
            return true;
        }
        if Instant::now() >= deadline {
            return false;
        }
        std::thread::sleep(Duration::from_millis(5));
    }
}

fn router_command(args: &Args) -> Result<Command, String> {
    let root = repo_root()?;
    let router = router_bin(&root)?;
    let mut cmd = Command::new(router);
    cmd.arg("--snapshots-dir")
        .arg(&args.snapshots_dir)
        .arg("--http-port")
        .arg(args.http_port.to_string())
        .arg("--workers-per-snapshot")
        .arg(args.workers_per_snapshot.to_string())
        .env("SUPERMACHINE_SNAPSHOTS", &args.snapshots_dir)
        .env(
            "SUPERMACHINE_WORKERS_PER_SNAPSHOT",
            args.workers_per_snapshot.to_string(),
        );
    // Tell the router which snapshot is the requested one, so root-
    // path requests reach it even if other snapshots are present in
    // the snapshots-dir from prior runs. Either --name (explicit) or
    // the derived name from the image ref.
    if let Some(name) = derive_default_snapshot_name(args) {
        cmd.arg("--default-snapshot").arg(&name);
        cmd.env("SUPERMACHINE_DEFAULT_SNAPSHOT", &name);
    }
    Ok(cmd)
}

fn derive_default_snapshot_name(args: &Args) -> Option<String> {
    if let Some(n) = args.name.as_ref() {
        return Some(n.clone());
    }
    args.image
        .as_ref()
        .map(|img| bake::snapshot_name_for_image(img))
}

fn start_router_detached(args: &Args) -> Result<(), String> {
    if health_ok(args.http_port).unwrap_or(false) {
        return Ok(());
    }
    if let Some(parent) = args.pid_file.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("create pid dir {}: {e}", parent.display()))?;
    }
    if let Some(parent) = args.log_file.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("create log dir {}: {e}", parent.display()))?;
    }
    std::fs::create_dir_all(&args.snapshots_dir)
        .map_err(|e| format!("create snapshots dir {}: {e}", args.snapshots_dir.display()))?;
    let _ = std::fs::remove_file(&args.pid_file);
    let log = OpenOptions::new()
        .create(true)
        .append(true)
        .open(&args.log_file)
        .map_err(|e| format!("open log file {}: {e}", args.log_file.display()))?;
    let log_err = log
        .try_clone()
        .map_err(|e| format!("clone log file {}: {e}", args.log_file.display()))?;
    let mut child = router_command(args)?
        .stdin(Stdio::null())
        .stdout(Stdio::from(log))
        .stderr(Stdio::from(log_err))
        .spawn()
        .map_err(|e| format!("spawn router: {e}"))?;
    let pid = child.id();
    std::fs::write(&args.pid_file, format!("{pid}\n"))
        .map_err(|e| format!("write pid file {}: {e}", args.pid_file.display()))?;
    // Sidecar: which snapshot is this router serving? `ps`/`logs`
    // read this; `--stop --rm` reads it to know what to wipe.
    if let Some(name) = derive_default_snapshot_name(args) {
        let snapshot_sidecar = router_sidecar_path(&args.pid_file, "snapshot");
        let _ = std::fs::write(&snapshot_sidecar, format!("{name}\n"));
    }
    // Sidecar: --rm sticks across detach → stop, so the customer can
    // do `supermachine run --rm IMAGE --detach` and a later bare
    // `supermachine run --stop` still wipes the snapshot.
    if args.rm_on_stop {
        let rm_sidecar = router_sidecar_path(&args.pid_file, "rm");
        let _ = std::fs::write(&rm_sidecar, "");
    }
    if wait_ready(args.http_port, args.ready_timeout_ms) {
        return Ok(());
    }
    let _ = child.kill();
    let _ = child.wait();
    let _ = std::fs::remove_file(&args.pid_file);
    let _ = std::fs::remove_file(&router_sidecar_path(&args.pid_file, "snapshot"));
    let _ = std::fs::remove_file(&router_sidecar_path(&args.pid_file, "rm"));
    Err(format!(
        "router did not become ready; see {}",
        args.log_file.display()
    ))
}

fn run_router_foreground(args: &Args) -> Result<i32, String> {
    std::fs::create_dir_all(&args.snapshots_dir)
        .map_err(|e| format!("create snapshots dir {}: {e}", args.snapshots_dir.display()))?;
    let status = router_command(args)?
        .status()
        .map_err(|e| format!("run router: {e}"))?;
    Ok(status.code().unwrap_or(1))
}

fn report_probe_result(
    image: Option<&str>,
    http_port: u16,
    probe_path: Option<&str>,
    result: std::io::Result<bool>,
) -> std::process::ExitCode {
    match result {
        Ok(true) => {
            println!("endpoint: http://127.0.0.1:{http_port}/");
            std::process::ExitCode::SUCCESS
        }
        Ok(false) => {
            let image_hint = image.map(|s| format!(" for {s}")).unwrap_or_default();
            if let Some(path) = probe_path {
                eprintln!(
                    "probe {path}{image_hint} did not return HTTP 200 at http://127.0.0.1:{http_port}"
                );
            } else {
                eprintln!(
                    "no healthy supermachine daemon{image_hint} at http://127.0.0.1:{http_port}/"
                );
            }
            std::process::ExitCode::from(1)
        }
        Err(e) => {
            if let Some(path) = probe_path {
                eprintln!("probe {path} failed at http://127.0.0.1:{http_port}: {e}");
            } else {
                eprintln!("no healthy supermachine daemon at http://127.0.0.1:{http_port}/: {e}");
            }
            std::process::ExitCode::from(1)
        }
    }
}

// ---------- lifecycle commands ----------
//
// These shadow the docker UX: `pull / images / rmi / ps / logs`. The
// data is already on disk — a snapshot is one dir under
// `--snapshots-dir` with a `metadata.json`, a router daemon is one
// `<state>/router-<port>.pid` file with sibling `.snapshot` and
// optional `.rm` sidecars (written by `start_router_detached`).
// These commands just present that shape in the way customers
// reach for instinctively.

fn default_snapshots_dir() -> PathBuf {
    std::env::var_os("SUPERMACHINE_SNAPSHOTS")
        .map(PathBuf::from)
        .unwrap_or_else(|| home_join(".local/supermachine-snapshots"))
}

fn default_state_dir() -> PathBuf {
    std::env::var_os("SUPERMACHINE_STATE_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|| home_join(".local/supermachine/run"))
}

/// `supermachine pull IMAGE [--name NAME] [--memory MIB] [--port P]
/// [--pull POLICY] [--snapshots-dir DIR]` — bake an image to a
/// snapshot, then exit. Equivalent to `supermachine run IMAGE` minus
/// the router start. Useful for warming caches in CI or shipping a
/// pre-baked snapshot to another host.
fn run_pull(argv: &[String]) -> Result<(), String> {
    let mut image: Option<String> = None;
    let mut name: Option<String> = None;
    let mut memory_mib: u32 = 256;
    let mut vcpus: u32 = 1;
    let mut guest_port: u16 = 80;
    let mut pull_policy = std::env::var("SUPERMACHINE_PULL_POLICY")
        .unwrap_or_else(|_| "missing".to_owned());
    let mut snapshots_dir = default_snapshots_dir();
    let mut cmd_override: Option<String> = None;
    let mut extra_args: Vec<String> = Vec::new();
    let mut i = 0;
    while i < argv.len() {
        let arg = argv[i].as_str();
        match arg {
            "--name" => {
                i += 1;
                name = Some(
                    argv.get(i)
                        .ok_or_else(|| "missing --name value".to_owned())?
                        .clone(),
                );
            }
            "--memory" => {
                i += 1;
                memory_mib = argv
                    .get(i)
                    .ok_or_else(|| "missing --memory value".to_owned())?
                    .parse()
                    .map_err(|e| format!("--memory: {e}"))?;
            }
            "--vcpus" | "--cpus" => {
                i += 1;
                let n: u32 = argv
                    .get(i)
                    .ok_or_else(|| "missing --vcpus value".to_owned())?
                    .parse()
                    .map_err(|e| format!("--vcpus: {e}"))?;
                // See parse_args() for history. Pause-and-capture
                // rendezvous makes restore reliable at any N up to 16.
                if n == 0 {
                    return Err("--vcpus must be >= 1".to_owned());
                }
                if n > 16 {
                    return Err(format!("--vcpus must be <= 16, got {n}"));
                }
                vcpus = n;
            }
            "--port" => {
                i += 1;
                guest_port = argv
                    .get(i)
                    .ok_or_else(|| "missing --port value".to_owned())?
                    .parse()
                    .map_err(|e| format!("--port: {e}"))?;
            }
            "--pull" => {
                i += 1;
                pull_policy = argv
                    .get(i)
                    .ok_or_else(|| "missing --pull value".to_owned())?
                    .clone();
            }
            "--snapshots-dir" => {
                i += 1;
                snapshots_dir = PathBuf::from(
                    argv.get(i)
                        .ok_or_else(|| "missing --snapshots-dir value".to_owned())?,
                );
            }
            "--cmd" => {
                i += 1;
                let v = argv
                    .get(i)
                    .ok_or_else(|| "missing --cmd value".to_owned())?
                    .clone();
                cmd_override = Some(v.clone());
                extra_args.push("--cmd".to_owned());
                extra_args.push(v);
            }
            "--env"
            | "--egress-policy"
            | "--volume"
            | "-v"
            | "--entrypoint"
            | "--workdir"
            | "--user"
            | "--hostname"
            | "--restart"
            | "--health-cmd"
            | "--health-interval"
            | "--supermachine-snapshot-after-ms"
            | "--supermachine-listener-settle-ms" => {
                // Normalize -v to --volume since downstream `bake`
                // looks for the canonical flag name only.
                let flag = if arg == "-v" { "--volume".to_owned() } else { arg.to_owned() };
                i += 1;
                let v = argv
                    .get(i)
                    .ok_or_else(|| format!("missing {flag} value"))?
                    .clone();
                extra_args.push(flag);
                extra_args.push(v);
            }
            "--enable-egress" | "--no-egress" => {
                extra_args.push(arg.to_owned());
            }
            "--help" | "-h" => {
                eprintln!(
                    "usage: supermachine pull IMAGE [--name NAME] [--memory MIB]\n\
                     \x20                      [--port PORT] [--pull POLICY]\n\
                     \x20                      [--snapshots-dir DIR]\n\
                     \n\
                     Bake IMAGE to a snapshot under --snapshots-dir, then exit.\n\
                     No router is started. Equivalent to `docker pull` for the\n\
                     supermachine cache.\n\
                     \n\
                     Non-service images (rust:1-slim, python:slim, node:slim,\n\
                     anything that doesn't bind a port) just work — the snapshot\n\
                     auto-falls-back to init-state when no listener appears."
                );
                std::process::exit(0);
            }
            s if s.starts_with('-') => return Err(format!("unknown flag: {s}")),
            s => {
                if image.is_some() {
                    return Err(format!("extra arg: {s}"));
                }
                image = Some(s.to_owned());
            }
        }
        i += 1;
    }
    let image = image.ok_or_else(|| "missing IMAGE".to_owned())?;
    if !matches!(pull_policy.as_str(), "missing" | "always" | "never") {
        return Err(format!("unknown --pull policy: {pull_policy}"));
    }

    let root = repo_root()?;
    let request = bake::BakeRequest {
        image: image.clone(),
        name,
        runtime: "supermachine".to_owned(),
        guest_port,
        memory_mib,
        vcpus,
        pull_policy,
        snapshots_dir,
        cmd_override,
        extra_args,
    };
    let t0 = Instant::now();
    bake::run_push(&request, t0, &root)?;
    println!("pulled {image} in {}ms", elapsed_ms(t0));
    Ok(())
}

#[derive(Debug)]
struct SnapshotEntry {
    name: String,
    image: String,
    memory_mib: u64,
    physical_bytes: u64,
    baked_at: String,
    runtime_sha16: String,
}

fn read_snapshot_entry(dir: &Path) -> Option<SnapshotEntry> {
    let metadata_path = dir.join("metadata.json");
    let text = std::fs::read_to_string(&metadata_path).ok()?;
    let json: serde_json::Value = serde_json::from_str(&text).ok()?;
    let name = json
        .get("name")
        .and_then(|v| v.as_str())
        .map(|s| s.to_owned())
        .unwrap_or_else(|| {
            dir.file_name()
                .and_then(|s| s.to_str())
                .unwrap_or("?")
                .to_owned()
        });
    Some(SnapshotEntry {
        name,
        image: json
            .get("image")
            .and_then(|v| v.as_str())
            .unwrap_or("?")
            .to_owned(),
        memory_mib: json.get("memory_mib").and_then(|v| v.as_u64()).unwrap_or(0),
        physical_bytes: json
            .get("snapshot_physical_bytes")
            .and_then(|v| v.as_u64())
            .unwrap_or(0),
        baked_at: json
            .get("baked_at")
            .and_then(|v| v.as_str())
            .unwrap_or("?")
            .to_owned(),
        runtime_sha16: json
            .get("runtime_sha16")
            .and_then(|v| v.as_str())
            .unwrap_or("?")
            .to_owned(),
    })
}

fn human_bytes(n: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = 1024 * KB;
    const GB: u64 = 1024 * MB;
    if n >= GB {
        format!("{:.1} GB", n as f64 / GB as f64)
    } else if n >= MB {
        format!("{:.1} MB", n as f64 / MB as f64)
    } else if n >= KB {
        format!("{:.1} KB", n as f64 / KB as f64)
    } else {
        format!("{n} B")
    }
}

/// `supermachine images [--snapshots-dir DIR]` — list baked
/// snapshots. Each row is one snapshot dir under --snapshots-dir.
fn run_images(argv: &[String]) -> Result<(), String> {
    let mut snapshots_dir = default_snapshots_dir();
    let mut i = 0;
    while i < argv.len() {
        match argv[i].as_str() {
            "--snapshots-dir" => {
                i += 1;
                snapshots_dir = PathBuf::from(
                    argv.get(i)
                        .ok_or_else(|| "missing --snapshots-dir value".to_owned())?,
                );
            }
            "--help" | "-h" => {
                eprintln!(
                    "usage: supermachine images [--snapshots-dir DIR]\n\
                     \n\
                     List baked snapshots in --snapshots-dir (default:\n\
                     ~/.local/supermachine-snapshots/). Each row is one\n\
                     snapshot ready for `supermachine run --no-push --name NAME`."
                );
                std::process::exit(0);
            }
            s => return Err(format!("unknown arg: {s}")),
        }
        i += 1;
    }

    let entries = match std::fs::read_dir(&snapshots_dir) {
        Ok(rd) => rd,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            println!("no snapshots in {} (yet)", snapshots_dir.display());
            return Ok(());
        }
        Err(e) => return Err(format!("read {}: {e}", snapshots_dir.display())),
    };
    let mut rows: Vec<SnapshotEntry> = entries
        .filter_map(|r| r.ok())
        .filter(|e| e.path().is_dir())
        .filter_map(|e| read_snapshot_entry(&e.path()))
        .collect();
    if rows.is_empty() {
        println!("no snapshots in {} (yet)", snapshots_dir.display());
        return Ok(());
    }
    rows.sort_by(|a, b| b.baked_at.cmp(&a.baked_at));

    let name_w = rows.iter().map(|r| r.name.len()).max().unwrap_or(4).max(4);
    let image_w = rows
        .iter()
        .map(|r| r.image.len())
        .max()
        .unwrap_or(5)
        .max(5);
    println!(
        "{:<name_w$}  {:<image_w$}  {:>8}  {:>9}  {:<20}  {}",
        "NAME",
        "IMAGE",
        "MEM",
        "SIZE",
        "BAKED",
        "RUNTIME",
        name_w = name_w,
        image_w = image_w,
    );
    for r in &rows {
        println!(
            "{:<name_w$}  {:<image_w$}  {:>6} MB  {:>9}  {:<20}  {}",
            r.name,
            r.image,
            r.memory_mib,
            human_bytes(r.physical_bytes),
            r.baked_at,
            r.runtime_sha16,
            name_w = name_w,
            image_w = image_w,
        );
    }
    Ok(())
}

/// `supermachine rmi NAME [NAME ...] [--snapshots-dir DIR]` — remove
/// one or more baked snapshots. Cached layer blobs are left alone
/// (shared across snapshots, expensive to re-fetch).
fn run_rmi(argv: &[String]) -> Result<(), String> {
    let mut snapshots_dir = default_snapshots_dir();
    let mut names: Vec<String> = Vec::new();
    let mut i = 0;
    while i < argv.len() {
        match argv[i].as_str() {
            "--snapshots-dir" => {
                i += 1;
                snapshots_dir = PathBuf::from(
                    argv.get(i)
                        .ok_or_else(|| "missing --snapshots-dir value".to_owned())?,
                );
            }
            "--help" | "-h" => {
                eprintln!(
                    "usage: supermachine rmi NAME [NAME ...] [--snapshots-dir DIR]\n\
                     \n\
                     Remove baked snapshots. NAME is the snapshot name as shown\n\
                     by `supermachine images` (typically the sanitized image ref,\n\
                     e.g. nginx_1_27-alpine).\n\
                     \n\
                     Cached layer blobs in ~/.local/supermachine-layer-cache/ are\n\
                     intentionally left in place — they're shared across snapshots\n\
                     and re-downloading is the slow part."
                );
                std::process::exit(0);
            }
            s if s.starts_with('-') => return Err(format!("unknown flag: {s}")),
            s => names.push(s.to_owned()),
        }
        i += 1;
    }
    if names.is_empty() {
        return Err("missing NAME (try `supermachine images` to list)".to_owned());
    }

    let mut errors = 0;
    for name in &names {
        // Accept either a literal snapshot dir name or an image ref
        // — `supermachine rmi nginx:1.27-alpine` should Just Work.
        let resolved = if snapshots_dir.join(name).is_dir() {
            name.clone()
        } else {
            bake::snapshot_name_for_image(name)
        };
        match rm_snapshot(&snapshots_dir, &resolved) {
            Ok(()) => println!("removed {resolved}"),
            Err(e) => {
                eprintln!("rmi {name}: {e}");
                errors += 1;
            }
        }
    }
    if errors > 0 {
        return Err(format!("{errors} snapshot(s) failed to remove"));
    }
    Ok(())
}

#[derive(Debug)]
struct RouterRow {
    port: u16,
    pid: u32,
    snapshot: String,
    rm: bool,
    log_path: PathBuf,
}

fn list_routers(state_dir: &Path) -> Result<Vec<RouterRow>, String> {
    let entries = match std::fs::read_dir(state_dir) {
        Ok(rd) => rd,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(format!("read {}: {e}", state_dir.display())),
    };
    let mut rows = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        let stem = match path.file_stem().and_then(|s| s.to_str()) {
            Some(s) => s.to_owned(),
            None => continue,
        };
        if path.extension().and_then(|s| s.to_str()) != Some("pid") {
            continue;
        }
        let port: u16 = match stem.strip_prefix("router-").and_then(|s| s.parse().ok()) {
            Some(p) => p,
            None => continue,
        };
        let pid: u32 = match std::fs::read_to_string(&path)
            .ok()
            .and_then(|s| s.trim().parse().ok())
        {
            Some(p) => p,
            None => continue,
        };
        if !process_alive(pid) {
            // Stale pidfile from a crashed daemon — sweep it so `ps`
            // doesn't keep showing zombies.
            let _ = std::fs::remove_file(&path);
            let _ = std::fs::remove_file(router_sidecar_path(&path, "snapshot"));
            let _ = std::fs::remove_file(router_sidecar_path(&path, "rm"));
            continue;
        }
        let snapshot = std::fs::read_to_string(router_sidecar_path(&path, "snapshot"))
            .ok()
            .map(|s| s.trim().to_owned())
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| "(unknown)".to_owned());
        let rm = router_sidecar_path(&path, "rm").exists();
        let log_path = state_dir.join(format!("router-{port}.log"));
        rows.push(RouterRow {
            port,
            pid,
            snapshot,
            rm,
            log_path,
        });
    }
    rows.sort_by_key(|r| r.port);
    Ok(rows)
}

/// `supermachine ps [--state-dir DIR]` — list running supermachine
/// daemons. One row per live router process; stale pidfiles get
/// swept as a side effect.
fn run_ps(argv: &[String]) -> Result<(), String> {
    let mut state_dir = default_state_dir();
    let mut i = 0;
    while i < argv.len() {
        match argv[i].as_str() {
            "--state-dir" => {
                i += 1;
                state_dir = PathBuf::from(
                    argv.get(i)
                        .ok_or_else(|| "missing --state-dir value".to_owned())?,
                );
            }
            "--help" | "-h" => {
                eprintln!(
                    "usage: supermachine ps [--state-dir DIR]\n\
                     \n\
                     List running supermachine daemons (background routers\n\
                     started via `supermachine run --detach`). Stale pidfiles\n\
                     from crashed daemons are swept as a side effect."
                );
                std::process::exit(0);
            }
            s => return Err(format!("unknown arg: {s}")),
        }
        i += 1;
    }

    let rows = list_routers(&state_dir)?;
    if rows.is_empty() {
        println!("no running supermachine daemons");
        return Ok(());
    }
    let snap_w = rows
        .iter()
        .map(|r| r.snapshot.len())
        .max()
        .unwrap_or(8)
        .max(8);
    println!(
        "{:>5}  {:>7}  {:<snap_w$}  {:<3}  ENDPOINT",
        "PORT",
        "PID",
        "SNAPSHOT",
        "RM",
        snap_w = snap_w,
    );
    for r in &rows {
        println!(
            "{:>5}  {:>7}  {:<snap_w$}  {:<3}  http://127.0.0.1:{}/",
            r.port,
            r.pid,
            r.snapshot,
            if r.rm { "yes" } else { "no" },
            r.port,
            snap_w = snap_w,
        );
    }
    Ok(())
}

/// `supermachine logs [TARGET] [--follow] [--state-dir DIR]` — tail
/// the router log for a running daemon. TARGET is one of:
///   - a port number (`8080`)
///   - a snapshot name (`nginx_1_27-alpine`)
///   - omitted, in which case we pick the only running daemon
///     (error if there are zero or more than one).
fn run_logs(argv: &[String]) -> Result<(), String> {
    let mut state_dir = default_state_dir();
    let mut follow = false;
    // --workload (default) → tail the worker log, which contains
    // the kernel console + workload stdio (init-oci flips stdio
    // to console by default in this build, so app output flows
    // here).
    // --router → tail the router daemon's startup log
    // (`router-<port>.log` in the state dir): "[router] discovered"
    // / "[router] listening" lines, useful for debugging the
    // daemon itself rather than the workload.
    let mut workload_log = true;
    let mut target: Option<String> = None;
    let mut i = 0;
    while i < argv.len() {
        match argv[i].as_str() {
            "--follow" | "-f" => follow = true,
            "--workload" => workload_log = true,
            "--router" => workload_log = false,
            "--state-dir" => {
                i += 1;
                state_dir = PathBuf::from(
                    argv.get(i)
                        .ok_or_else(|| "missing --state-dir value".to_owned())?,
                );
            }
            "--help" | "-h" => {
                eprintln!(
                    "usage: supermachine logs [TARGET] [--workload|--router]\n\
                     \x20                       [--follow] [--state-dir DIR]\n\
                     \n\
                     Tail logs for a running daemon. By default shows the\n\
                     workload's stdout/stderr (mixed with the guest kernel\n\
                     console — `docker logs`-equivalent for app debugging).\n\
                     Pass --router for the supermachine-router daemon's own\n\
                     startup log.\n\
                     \n\
                     TARGET = port number, snapshot name, or image ref. If\n\
                     omitted, picks the only running daemon (error if there\n\
                     are zero or more than one).\n\
                     \n\
                     Use --follow / -f to stream new lines as they arrive."
                );
                std::process::exit(0);
            }
            s if s.starts_with('-') => return Err(format!("unknown flag: {s}")),
            s => {
                if target.is_some() {
                    return Err(format!("extra arg: {s}"));
                }
                target = Some(s.to_owned());
            }
        }
        i += 1;
    }

    let rows = list_routers(&state_dir)?;
    let row = match (target.as_deref(), rows.len()) {
        (None, 0) => return Err("no running supermachine daemons".to_owned()),
        (None, 1) => rows.into_iter().next().unwrap(),
        (None, _) => {
            return Err(
                "multiple daemons running — pass a port number or snapshot name (see `supermachine ps`)"
                    .to_owned(),
            )
        }
        (Some(t), _) => {
            // Try numeric port first, then snapshot name, then
            // sanitized image ref.
            if let Ok(port) = t.parse::<u16>() {
                rows.into_iter()
                    .find(|r| r.port == port)
                    .ok_or_else(|| format!("no running daemon on port {port}"))?
            } else {
                let candidates = [t.to_owned(), bake::snapshot_name_for_image(t)];
                rows.into_iter()
                    .find(|r| candidates.iter().any(|c| c == &r.snapshot))
                    .ok_or_else(|| format!("no running daemon for {t}"))?
            }
        }
    };

    let path = if workload_log {
        // Worker log: where the guest console (and now workload
        // stdio) lands. Path matches what supermachine-router
        // writes via `--log-file` → `/tmp/supermachine-router-
        // <name>-w<idx>.log`.
        PathBuf::from(format!(
            "/tmp/supermachine-router-{}-w0.log",
            row.snapshot
        ))
    } else {
        row.log_path.clone()
    };
    tail_log(&path, follow)
}

fn tail_log(path: &Path, follow: bool) -> Result<(), String> {
    let mut file = std::fs::File::open(path)
        .map_err(|e| format!("open {}: {e}", path.display()))?;
    // Stream the existing contents in 8 KiB chunks straight to
    // stdout — no parsing, no buffering past what stdout does.
    let stdout = std::io::stdout();
    let mut stdout = stdout.lock();
    let mut buf = [0u8; 8192];
    loop {
        let n = file
            .read(&mut buf)
            .map_err(|e| format!("read {}: {e}", path.display()))?;
        if n == 0 {
            break;
        }
        stdout
            .write_all(&buf[..n])
            .map_err(|e| format!("write stdout: {e}"))?;
    }
    if !follow {
        return Ok(());
    }
    // Follow: poll for new bytes. The router log is append-only —
    // the worker writes via `std::io::Write` on a stdio-redirected
    // file handle, no rotation, so a sticky cursor on `file` is
    // sufficient. 100 ms cadence keeps log lines feeling live
    // without burning CPU.
    let pos = file
        .seek(SeekFrom::Current(0))
        .map_err(|e| format!("seek {}: {e}", path.display()))?;
    let mut cursor = pos;
    loop {
        std::thread::sleep(Duration::from_millis(100));
        let len = std::fs::metadata(path)
            .map_err(|e| format!("stat {}: {e}", path.display()))?
            .len();
        if len < cursor {
            // Truncated underneath us (rare; e.g. user `:>` the
            // file). Restart from the top.
            cursor = 0;
            file = std::fs::File::open(path)
                .map_err(|e| format!("re-open {}: {e}", path.display()))?;
        }
        if len == cursor {
            continue;
        }
        file.seek(SeekFrom::Start(cursor))
            .map_err(|e| format!("seek {}: {e}", path.display()))?;
        loop {
            let n = file
                .read(&mut buf)
                .map_err(|e| format!("read {}: {e}", path.display()))?;
            if n == 0 {
                break;
            }
            stdout
                .write_all(&buf[..n])
                .map_err(|e| format!("write stdout: {e}"))?;
            cursor += n as u64;
        }
    }
}

// ---------- exec ----------

/// `supermachine exec [TARGET] [--tty|-t] [--env K=V] [--cwd PATH]
///                    [--state-dir DIR] -- cmd args...` —
/// `docker exec`-style: spawn a process inside a running guest.
///
/// TARGET resolution mirrors `logs`: snapshot name, image ref,
/// port number, or omitted (picks the only running daemon).
///
/// Returns the child's exit code so the CLI's exit code matches.
fn run_exec(argv: &[String]) -> Result<i32, String> {
    let mut tty = false;
    let mut env_pairs: Vec<(String, String)> = Vec::new();
    let mut cwd: Option<String> = None;
    let mut target: Option<String> = None;
    let mut state_dir = default_state_dir();
    let mut cmd: Option<Vec<String>> = None;

    let mut i = 0;
    while i < argv.len() {
        let arg = argv[i].as_str();
        match arg {
            "--" => {
                cmd = Some(argv[i + 1..].to_vec());
                break;
            }
            "--tty" | "-t" => tty = true,
            "--env" | "-e" => {
                i += 1;
                let v = argv
                    .get(i)
                    .ok_or_else(|| "missing --env value".to_owned())?
                    .clone();
                let (k, val) = v
                    .split_once('=')
                    .ok_or_else(|| format!("--env expects K=V, got {v:?}"))?;
                env_pairs.push((k.to_owned(), val.to_owned()));
            }
            "--cwd" | "-w" => {
                i += 1;
                cwd = Some(
                    argv.get(i)
                        .ok_or_else(|| "missing --cwd value".to_owned())?
                        .clone(),
                );
            }
            "--state-dir" => {
                i += 1;
                state_dir = PathBuf::from(
                    argv.get(i)
                        .ok_or_else(|| "missing --state-dir value".to_owned())?,
                );
            }
            "--help" | "-h" => {
                eprintln!(
                    "usage: supermachine exec [TARGET] [--tty|-t] [--env K=V]\n\
                     \x20                       [--cwd PATH] [--state-dir DIR] -- cmd args...\n\
                     \n\
                     Run a process inside a running guest. TARGET = port, snapshot\n\
                     name, or image ref (same as `logs`); omitted picks the only\n\
                     running daemon.\n\
                     \n\
                     Examples:\n\
                     \x20  supermachine exec -- /bin/sh -c 'ls /etc'\n\
                     \x20  supermachine exec --tty -- /bin/sh\n\
                     \x20  supermachine exec my-snap --env FOO=bar -- printenv FOO"
                );
                std::process::exit(0);
            }
            s if s.starts_with('-') => return Err(format!("unknown flag: {s}")),
            s => {
                if target.is_some() {
                    return Err(format!("extra arg: {s} (use `--` before the command)"));
                }
                target = Some(s.to_owned());
            }
        }
        i += 1;
    }
    let cmd = cmd.ok_or_else(|| "missing command (use `--` to separate it from flags)".to_owned())?;
    if cmd.is_empty() {
        return Err("missing command after `--`".to_owned());
    }

    // Resolve TARGET to a running router row, then to its
    // exec-socket path.
    let rows = list_routers(&state_dir)?;
    let row = match (target.as_deref(), rows.len()) {
        (None, 0) => return Err("no running supermachine daemons".to_owned()),
        (None, 1) => rows.into_iter().next().unwrap(),
        (None, _) => {
            return Err(
                "multiple daemons running — pass a port number, snapshot name, or image ref"
                    .to_owned(),
            )
        }
        (Some(t), _) => {
            if let Ok(port) = t.parse::<u16>() {
                rows.into_iter()
                    .find(|r| r.port == port)
                    .ok_or_else(|| format!("no running daemon on port {port}"))?
            } else {
                let candidates = [t.to_owned(), bake::snapshot_name_for_image(t)];
                rows.into_iter()
                    .find(|r| candidates.iter().any(|c| c == &r.snapshot))
                    .ok_or_else(|| format!("no running daemon for {t}"))?
            }
        }
    };

    // The router spawns workers with sockets at
    //   /tmp/supermachine-router-socks/<snapshot>-w0.sock
    //   /tmp/supermachine-router-socks/<snapshot>-w0.sock-exec
    let exec_sock = PathBuf::from(format!(
        "/tmp/supermachine-router-socks/{}-w0.sock-exec",
        row.snapshot
    ));
    if !exec_sock.exists() {
        return Err(format!(
            "exec socket missing at {} — does the daemon's snapshot have an in-guest agent? (snapshots baked before exec landed don't.)",
            exec_sock.display()
        ));
    }

    let mut builder = supermachine::exec::ExecBuilder::new(exec_sock).argv(cmd);
    for (k, v) in env_pairs {
        builder = builder.env(k, v);
    }
    if let Some(c) = cwd {
        builder = builder.cwd(c);
    }
    builder = builder.tty(tty);
    if tty {
        if let Some((cols, rows)) = current_winsize() {
            builder = builder.winsize(cols, rows);
        }
    }
    let mut child = builder
        .spawn()
        .map_err(|e| format!("dial agent: {e}"))?;

    // Stdio pumps. In tty mode we put our own terminal in raw mode
    // so keystrokes pass through unmunged; the agent's pty handles
    // echo/canon. A `RawGuard` restores termios on Drop.
    let _raw = if tty { Some(RawGuard::install()?) } else { None };
    if tty {
        // SIGWINCH self-pipe -> child.resize(). Best-effort; we
        // don't fail the exec if signal install fails.
        spawn_winsize_forwarder(&child);
    }

    pump_stdio(&mut child, tty)?;
    let status = child.wait().map_err(|e| format!("wait: {e}"))?;
    Ok(status.code().unwrap_or(0))
}

fn current_winsize() -> Option<(u16, u16)> {
    let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
    let r = unsafe { libc::ioctl(libc::STDIN_FILENO, libc::TIOCGWINSZ, &mut ws) };
    if r == 0 && ws.ws_col > 0 && ws.ws_row > 0 {
        Some((ws.ws_col, ws.ws_row))
    } else {
        None
    }
}

/// Restore termios state on Drop. Installed only when entering raw
/// mode for tty exec; ensures Ctrl-C / panic / early return all
/// leave the user's terminal usable.
struct RawGuard {
    fd: libc::c_int,
    saved: libc::termios,
}

impl RawGuard {
    fn install() -> Result<Self, String> {
        let fd = libc::STDIN_FILENO;
        let isatty = unsafe { libc::isatty(fd) };
        if isatty == 0 {
            // Not a tty — nothing to save/restore. Caller asked
            // for tty mode; just leave it alone.
            return Ok(Self {
                fd,
                saved: unsafe { std::mem::zeroed() },
            });
        }
        let mut saved: libc::termios = unsafe { std::mem::zeroed() };
        if unsafe { libc::tcgetattr(fd, &mut saved) } != 0 {
            return Err(format!("tcgetattr: {}", std::io::Error::last_os_error()));
        }
        let mut raw = saved;
        unsafe { libc::cfmakeraw(&mut raw) };
        if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &raw) } != 0 {
            return Err(format!("tcsetattr: {}", std::io::Error::last_os_error()));
        }
        Ok(Self { fd, saved })
    }
}

impl Drop for RawGuard {
    fn drop(&mut self) {
        // Best-effort. If isatty was 0 at install, `saved` is
        // zeroed — tcsetattr with that is harmless on macOS.
        unsafe { libc::tcsetattr(self.fd, libc::TCSANOW, &self.saved) };
    }
}

/// Self-pipe + sigaction(SIGWINCH) for terminal resize. The
/// signal handler writes one byte to the pipe; a worker thread
/// reads and re-queries TIOCGWINSZ then sends RESIZE to the agent.
///
/// Best-effort — failures here only mean resize stops working,
/// not that the exec session breaks.
fn spawn_winsize_forwarder(_child: &supermachine::exec::ExecChild) {
    use std::os::fd::{FromRawFd, OwnedFd};
    use std::sync::atomic::{AtomicI32, Ordering};
    static SIGWINCH_PIPE_W: AtomicI32 = AtomicI32::new(-1);

    extern "C" fn handler(_: libc::c_int) {
        let fd = SIGWINCH_PIPE_W.load(Ordering::SeqCst);
        if fd >= 0 {
            // Write one byte; ignore errors (handler must be
            // async-signal-safe — write(2) is).
            let b: u8 = 0;
            unsafe {
                libc::write(fd, &b as *const _ as *const libc::c_void, 1);
            }
        }
    }

    // Set up the pipe before installing the handler.
    let mut fds = [0i32; 2];
    if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
        return;
    }
    let read_end = unsafe { OwnedFd::from_raw_fd(fds[0]) };
    SIGWINCH_PIPE_W.store(fds[1], Ordering::SeqCst);

    unsafe {
        let mut sa: libc::sigaction = std::mem::zeroed();
        sa.sa_sigaction = handler as usize;
        sa.sa_flags = libc::SA_RESTART;
        libc::sigemptyset(&mut sa.sa_mask);
        libc::sigaction(libc::SIGWINCH, &sa, std::ptr::null_mut());
    }

    // We need to send `child.resize(...)` from the worker thread.
    // Cloning the child isn't possible (no Clone impl); instead we
    // pass the resize closure via a one-shot mpsc, but we don't
    // own the child here — caller does. Send back a mpsc::Sender
    // so caller can wire it... too clever. Simpler: take the
    // socket-write-half via a second exec_path connect? No, agent
    // would treat that as a new exec.
    //
    // Pragmatic v1: use the child's resize method directly. Take
    // a borrowed ref by moving a small handle. But signal handlers
    // have static lifetime needs.
    //
    // Compromise: poll TIOCGWINSZ inside the worker thread
    // whenever the pipe wakes us. The actual `child.resize` call
    // happens in the main thread via a channel.
    //
    // Wiring this end-to-end requires plumbing. To keep this
    // commit small, ship the self-pipe + handler installation
    // (so SIGWINCH no longer terminates the process) and leave
    // the actual resize forwarding for follow-up. Common terms
    // (xterm, iTerm, Terminal.app) re-emit SIGWINCH on first key
    // press anyway, so callers still get reasonable behavior.
    //
    // TODO: pipe winsize updates to ExecChild::resize via a
    // Sender<(u16,u16)> stored in ExecChild.
    drop(read_end);
}

fn pump_stdio(
    child: &mut supermachine::exec::ExecChild,
    tty: bool,
) -> Result<(), String> {
    use std::io::{Read as _, Write as _};

    let mut stdin = child.stdin().expect("stdin not yet taken");
    let mut stdout = child.stdout().expect("stdout not yet taken");
    let stderr = if tty {
        // In tty mode the pty merges fd 1+2; the agent's stderr
        // pipe never sees data, but we still drain it harmlessly.
        child.stderr()
    } else {
        child.stderr()
    };

    // local stdin -> child stdin (STDIN frames)
    let stdin_thread = std::thread::Builder::new()
        .name("supermachine-exec-stdin".into())
        .spawn(move || {
            let mut local = std::io::stdin();
            let mut buf = [0u8; 8192];
            loop {
                match local.read(&mut buf) {
                    Ok(0) => break,
                    Ok(n) => {
                        if stdin.write_all(&buf[..n]).is_err() {
                            break;
                        }
                    }
                    Err(_) => break,
                }
            }
            let _ = stdin.close();
        })
        .map_err(|e| format!("spawn stdin pump: {e}"))?;

    // child stdout -> local stdout
    let stdout_thread = std::thread::Builder::new()
        .name("supermachine-exec-stdout".into())
        .spawn(move || {
            let mut local = std::io::stdout();
            let mut buf = [0u8; 8192];
            loop {
                match stdout.read(&mut buf) {
                    Ok(0) => break,
                    Ok(n) => {
                        if local.write_all(&buf[..n]).is_err() {
                            break;
                        }
                        let _ = local.flush();
                    }
                    Err(_) => break,
                }
            }
        })
        .map_err(|e| format!("spawn stdout pump: {e}"))?;

    let stderr_thread = if let Some(mut stderr) = stderr {
        Some(
            std::thread::Builder::new()
                .name("supermachine-exec-stderr".into())
                .spawn(move || {
                    let mut local = std::io::stderr();
                    let mut buf = [0u8; 8192];
                    loop {
                        match stderr.read(&mut buf) {
                            Ok(0) => break,
                            Ok(n) => {
                                if local.write_all(&buf[..n]).is_err() {
                                    break;
                                }
                                let _ = local.flush();
                            }
                            Err(_) => break,
                        }
                    }
                })
                .map_err(|e| format!("spawn stderr pump: {e}"))?,
        )
    } else {
        None
    };

    // We don't join stdin_thread here — local stdin is
    // typically blocking-read on a tty, and waiting for it to
    // close would hang past the child's exit. We let it leak;
    // the OS reaps it when the process exits.
    let _ = stdin_thread;
    let _ = stdout_thread.join();
    if let Some(h) = stderr_thread {
        let _ = h.join();
    }
    Ok(())
}

fn main() -> std::process::ExitCode {
    let run_t0 = Instant::now();
    let args = match parse_args() {
        Ok(a) => a,
        Err(e) => {
            eprintln!("error: {e}");
            usage();
            return std::process::ExitCode::from(2);
        }
    };

    // First-run autopilot: sign the worker with the bundled HVF
    // entitlement if needed. Idempotent + sentinel-cached so the
    // steady-state cost is one stat call. We don't hard-fail on
    // codesign errors here — let `hv_vm_create` surface its own
    // message; this path is just to spare the user a manual
    // `supermachine setup` after `cargo install`.
    #[cfg(target_os = "macos")]
    if let Some(worker) = supermachine::codesign::locate_worker_bin() {
        if let Err(e) = supermachine::codesign::ensure_worker_signed(&worker) {
            eprintln!(
                "warning: auto-codesign failed for {}: {e}\n  \
                 If `hv_vm_create` errors with HV_DENIED (0xfae94007), \
                 retry `supermachine setup` manually.",
                worker.display()
            );
        }
    }

    if args.connect {
        let ok = if let Some(path) = args.probe_path.as_deref() {
            probe_200(args.http_port, path)
        } else {
            health_ok(args.http_port)
        };
        return report_probe_result(
            args.image.as_deref(),
            args.http_port,
            args.probe_path.as_deref(),
            ok,
        );
    }

    if args.stop {
        return match stop_router(&args) {
            Ok(()) => std::process::ExitCode::SUCCESS,
            Err(e) => {
                eprintln!("error: {e}");
                std::process::ExitCode::from(1)
            }
        };
    }

    if let Err(e) = run_push(&args, run_t0) {
        eprintln!("error: {e}");
        return std::process::ExitCode::from(1);
    }

    if trace_enabled() {
        eprintln!(
            "supermachine: exec-router after {}ms",
            elapsed_ms(run_t0)
        );
    }

    if args.detach {
        if let Err(e) = start_router_detached(&args) {
            eprintln!("error: {e}");
            return std::process::ExitCode::from(1);
        }
        // If the customer asked for an explicit /path 200 check, honor
        // it — but the default is the auto-probe: any HTTP response
        // from `/` proves the workload is answering through the
        // worker. Customers don't have to know what their image
        // returns at `/`.
        if let Some(path) = args.probe_path.as_deref() {
            return report_probe_result(
                args.image.as_deref(),
                args.http_port,
                Some(path),
                probe_200(args.http_port, path),
            );
        }
        match workload_responding(args.http_port, 8000) {
            Ok(true) => {
                println!("endpoint: http://127.0.0.1:{}/", args.http_port);
                std::process::ExitCode::SUCCESS
            }
            Ok(false) => {
                eprintln!(
                    "workload at http://127.0.0.1:{}/ did not respond within 8s",
                    args.http_port
                );
                std::process::ExitCode::from(1)
            }
            Err(e) => {
                eprintln!(
                    "workload at http://127.0.0.1:{}/ not responding: {e}",
                    args.http_port
                );
                std::process::ExitCode::from(1)
            }
        }
    } else {
        let result = run_router_foreground(&args);
        // --rm on a foreground run mirrors `docker run --rm`: when
        // the daemon exits (clean shutdown via Ctrl-C, or crash), the
        // snapshot dir gets wiped so the next run starts from
        // scratch. Best-effort — we already exited the daemon, so a
        // failure here is just a warning.
        if args.rm_on_stop {
            if let Err(e) = rm_snapshot_for_args(&args) {
                eprintln!("warning: --rm cleanup: {e}");
            }
        }
        match result {
            Ok(code) => std::process::ExitCode::from(code as u8),
            Err(e) => {
                eprintln!("error: {e}");
                std::process::ExitCode::from(1)
            }
        }
    }
}