windows-headless 0.3.2-alpha

Headless Windows 11 VMs from a Microsoft ISO: downloads portable QEMU binaries (no Docker, no host install) and hands you SSH.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
//! Command implementations behind the thin CLI in `main.rs`.
//!
//! Each `cmd_*` takes plain params (no clap types) so the logic is callable
//! from tests and other frontends. Cache-dir and arch defaults live here.
//!
//! Stream rule: stdout carries primary data only (`gen` XML, `report`
//! table, `guest exec` output). All status, progress, prompts, warnings,
//! and ready lines go to stderr — the CLI stays pipe-safe.
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::ipc::{MON_SOCK_NAME, QMP_SOCK_NAME, SERIAL_LOG_NAME, vm_endpoint};
use crate::qemu::{
    Display, HeadlessVmBuilder, PROVEN_SSH_HOST, PROVEN_SSH_PORT, PROVEN_VNC_PASSWORD,
    WindowsVersion, qmp_alive, vnc_url,
};
use crate::storage::DiskManager;
use crate::timeouts;
use crate::unattend::{Architecture, VmConfig, auto_detect_platform};
use crate::vision::{
    SampleOutcome, SamplingProfile, ScreenSampler, ScreenState, describe, fmt_bytes, fmt_secs,
    is_error_state, take_screenshot,
};

/// Disk partitioning script laid onto the installer USB (`setup/part.txt`).
const PART_TXT: &str = include_str!("../setup/part.txt");

/// Guest arch: explicit `--arch` wins, else the host arch (HVF/KVM require
/// host == guest, so the default is almost always right).
pub fn resolve_arch(a: Option<Architecture>) -> Architecture {
    a.unwrap_or_else(|| auto_detect_platform().0)
}

/// Scratch dir that deletes itself on drop (all exit paths except SIGKILL).
/// `create` purges any stale contents first (previous kill's leftovers).
pub struct ScratchDir(PathBuf);

impl ScratchDir {
    pub fn create(dir: &Path) -> Result<Self> {
        if dir.exists() {
            eprintln!("purging stale scratch {}", dir.display());
            std::fs::remove_dir_all(dir)?;
        }
        std::fs::create_dir_all(dir)?;
        Ok(Self(dir.to_path_buf()))
    }
}

impl Drop for ScratchDir {
    fn drop(&mut self) {
        if let Err(e) = std::fs::remove_dir_all(&self.0) {
            eprintln!(
                "warning: scratch cleanup failed ({}): {e:#}",
                self.0.display()
            );
        }
    }
}

/// Default VM dir: project cache `vms/win11` (created, never evicted —
/// disk images are tens of GB), or `./win11-vm` without the downloader
/// feature (no cache-manager available).
#[cfg(feature = "downloader")]
pub fn default_vm_dir() -> Result<PathBuf> {
    let root = crate::cache::resolve_cache_root(None, "WINDOWS_HEADLESS_VM_DIR")?;
    Ok(root.ensure_group(crate::paths::VM_GROUP)?)
}

#[cfg(not(feature = "downloader"))]
pub fn default_vm_dir() -> Result<PathBuf> {
    Ok(PathBuf::from(crate::paths::FALLBACK_VM_DIR))
}

/// Default USB installer image: project cache `media/winusb.dmg`
/// (created, never evicted — 10 GB, slow to rebuild), or `./winusb.dmg`
/// without the downloader feature. `$WINDOWS_HEADLESS_MEDIA_DIR` overrides
/// the cache base, mirroring the ISO cache.
#[cfg(feature = "downloader")]
pub fn default_media_image() -> Result<PathBuf> {
    let root = crate::cache::resolve_cache_root(None, "WINDOWS_HEADLESS_MEDIA_DIR")?;
    Ok(root
        .ensure_group(crate::paths::MEDIA_GROUP)?
        .join(crate::paths::WINUSB_IMAGE))
}

#[cfg(not(feature = "downloader"))]
pub fn default_media_image() -> Result<PathBuf> {
    Ok(PathBuf::from(crate::paths::FALLBACK_WINUSB_IMAGE))
}

/// Expand a leading `~` (shells don't expand it inside quotes, so
/// `'~/Downloads/x.iso'` arrives literally — observed live as a bare
/// ENOENT with no filename). `~` and `~/...` only; other users untouched.
fn expand_tilde(p: PathBuf) -> PathBuf {
    let s = p.to_string_lossy();
    if let Some(rest) = s.strip_prefix("~/").or_else(|| (s == "~").then_some(""))
        && let Ok(home) = std::env::var("HOME")
    {
        return PathBuf::from(home).join(rest);
    }
    p
}

/// Fail fast when the Windows ISO is absent, naming the path we actually
/// resolved instead of guessing at a cause. The `~` hint is emitted only
/// when a literal `~` survived [`expand_tilde`] — i.e. `HOME` was unset (or
/// the path is `~otheruser/...`), which is the only way a `~` reaches here
/// from either an unquoted or a quoted argument.
fn require_win_iso(path: &Path) -> Result<()> {
    if path.is_file() {
        return Ok(());
    }
    let shown = path.display();
    let raw = path.to_string_lossy();
    if raw == "~" || raw.starts_with("~/") {
        anyhow::bail!("Windows ISO not found: {shown} (`~` not expanded — is $HOME set?)");
    }
    if raw.starts_with('~') {
        anyhow::bail!("Windows ISO not found: {shown} (`~otheruser` paths are not expanded)");
    }
    anyhow::bail!("Windows ISO not found: {shown}");
}

fn stage_local_dir(base: &Path, prefix: &str, out: &mut Vec<(String, Vec<u8>)>) -> Result<()> {
    fn walk(base: &Path, rel: &str, prefix: &str, out: &mut Vec<(String, Vec<u8>)>) -> Result<()> {
        let dir = if rel.is_empty() {
            base.to_path_buf()
        } else {
            base.join(rel)
        };
        for e in std::fs::read_dir(&dir)? {
            let e = e?;
            let name = e.file_name().to_string_lossy().into_owned();
            let rp = if rel.is_empty() {
                name.clone()
            } else {
                format!("{rel}/{name}")
            };
            if e.file_type()?.is_dir() {
                walk(base, &rp, prefix, out)?;
            } else {
                out.push((format!("{prefix}/{rp}"), std::fs::read(e.path())?));
            }
        }
        Ok(())
    }
    walk(base, "", prefix, out)
}

// ---------------------------------------------------------------------------
// gen
// ---------------------------------------------------------------------------

pub struct GenArgs {
    pub username: String,
    pub password: String,
    pub locale: String,
    pub autologon: bool,
    pub unattend_dir: Option<PathBuf>,
    pub arch: Option<Architecture>,
}

pub fn cmd_gen(a: GenArgs) -> Result<()> {
    let cfg = VmConfig {
        username: a.username,
        password: a.password,
        locale: a.locale,
        auto_logon: a.autologon,
        arch: resolve_arch(a.arch),
        ..VmConfig::default()
    };
    let xml = cfg.generate_unattend_xml();
    if let Some(dir) = a.unattend_dir {
        let f = DiskManager::ensure_unattend_dir(&dir, &xml)?;
        eprintln!("wrote {}", f.display());
    } else {
        println!("{xml}");
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// build-media
// ---------------------------------------------------------------------------

pub struct BuildMediaArgs {
    pub win_iso: PathBuf,
    pub arch: Option<Architecture>,
    pub virtio_iso: Option<PathBuf>,
    pub drivers_dir: Option<PathBuf>,
    pub openssh_zip: Option<PathBuf>,
    pub out: Option<PathBuf>,
    pub wimlib_bin: Option<PathBuf>,
    pub username: String,
    pub password: String,
    pub locale: String,
    /// Rebuild even when the output image + sidecar already exist.
    pub force: bool,
}

/// The `build` pipeline: `setup` (fetch deps) + `build-media` (USB image).
/// One command, one artifact. Requires the downloader feature (fetching is
/// the whole point); the hidden `build-media` stays for no-fetch flows.
#[cfg(feature = "downloader")]
pub struct BuildArgs {
    pub win_iso: PathBuf,
    pub arch: Option<Architecture>,
    pub username: String,
    pub password: String,
    pub locale: String,
    pub out: Option<PathBuf>,
    pub force: bool,
}

#[cfg(feature = "downloader")]
pub async fn cmd_build(a: BuildArgs) -> Result<PathBuf> {
    // The ISO is the one input `setup` cannot fetch, so check it BEFORE the
    // downloads: a bad path must fail in milliseconds, not after gigabytes.
    require_win_iso(&expand_tilde(a.win_iso.clone()))?;
    cmd_setup(None, a.arch).await?;
    // Resolve the media path here (same rule as build-media) so callers
    // chaining into `install` know which image came out.
    let out = a.out.map(expand_tilde).unwrap_or(default_media_image()?);
    cmd_build_media(BuildMediaArgs {
        win_iso: a.win_iso,
        arch: a.arch,
        virtio_iso: None,
        drivers_dir: None,
        openssh_zip: None,
        out: Some(out.clone()),
        wimlib_bin: None,
        username: a.username,
        password: a.password,
        locale: a.locale,
        force: a.force,
    })
    .await?;
    Ok(out)
}

pub async fn cmd_build_media(a: BuildMediaArgs) -> Result<()> {
    use crate::media::{
        MediaSpec, build_installer_media, extract_iso_file_to_disk, extract_virtio_netkvm,
        list_iso_tree, split_wim,
    };
    let arch = resolve_arch(a.arch);
    let out = a.out.map(expand_tilde).unwrap_or(default_media_image()?);
    let win_iso = expand_tilde(a.win_iso);
    // Freshness skip: output + sidecar both present means a completed
    // build (sidecar is written last). `--force` rebuilds regardless.
    // Stale inputs with a fresh output are the user's explicit choice.
    if !a.force && out.is_file() && crate::provenance::Provenance::sidecar_path(&out).is_file() {
        eprintln!(
            "already built: {} (sidecar present; --force to rebuild)",
            out.display()
        );
        return Ok(());
    }

    // ISO first, honest error, before any state changes: a missing input
    // must not invalidate a good sidecar or stage the driver archives.
    require_win_iso(&win_iso)?;

    // Invalidate first: a crashed/failed build must never leave a previous
    // sidecar next to a partial image, or the next run skips as "fresh"
    // over garbage (observed live: unusable image reported fresh).
    crate::provenance::Provenance::invalidate(&out);

    // Vendored wimlib: explicit --wimlib-bin wins, else the pinned tree
    // from `fetch-wimlib` (same pattern as `run`). Keep the tag alongside
    // for the provenance sidecar.
    let (wimlib_tag, wimlib_bin) = match a.wimlib_bin {
        Some(b) => ("explicit --wimlib-bin".to_string(), b),
        None => {
            #[cfg(feature = "downloader")]
            {
                let w = crate::qemu_portable::pinned_cached_wimlib()?;
                eprintln!("using pinned portable wimlib {}", w.version);
                (w.version.clone(), w.wimlib_bin())
            }
            #[cfg(not(feature = "downloader"))]
            {
                ("PATH".to_string(), PathBuf::from("wimlib-imagex"))
            }
        }
    };
    eprintln!("building installer media from {} ...", win_iso.display());
    // Driver inputs default to the ISO cache (`setup` fetches them):
    // explicit flags win, else `<iso-cache>/virtio-win.iso` and the
    // per-arch OpenSSH zip. Missing files bail with the fix
    // (`setup`), not a bare NotFound.
    #[cfg(feature = "downloader")]
    let iso_cache = crate::downloader::iso_cache_dir()?;
    let openssh_zip = match a.openssh_zip.map(expand_tilde) {
        Some(p) => p,
        None => {
            #[cfg(feature = "downloader")]
            {
                let p = iso_cache.join(arch.openssh_zip_name());
                if !p.exists() {
                    anyhow::bail!(
                        "{} missing (run `setup` first, or pass --openssh-zip)",
                        p.display()
                    );
                }
                eprintln!("using cached {}", p.display());
                p
            }
            #[cfg(not(feature = "downloader"))]
            {
                anyhow::bail!("pass --openssh-zip <zip>");
            }
        }
    };
    let xml = VmConfig {
        username: a.username.clone(),
        password: a.password.clone(),
        locale: a.locale.clone(),
        arch,
        ..VmConfig::default()
    }
    .generate_unattend_xml();
    // Drivers: explicit tree wins; else extract NetKVM from the
    // virtio ISO in-crate (pure Rust, no host tools). Remember which
    // ISO was used for the provenance sidecar (`None` = --drivers-dir).
    let mut virtio_used: Option<PathBuf> = None;
    let mut staged = vec![
        (crate::paths::UNATTEND_XML.to_string(), xml.into_bytes()),
        (
            crate::paths::PART_TXT_PATH.to_string(),
            PART_TXT.as_bytes().to_vec(),
        ),
        (
            format!("{}/{}", crate::paths::TOOLS_DIR, arch.openssh_zip_name()),
            std::fs::read(&openssh_zip)?,
        ),
    ];
    match (
        a.drivers_dir.map(expand_tilde),
        a.virtio_iso.map(expand_tilde),
    ) {
        (Some(dir), _) => stage_local_dir(&dir, crate::paths::DRIVERS_STAGE_DIR, &mut staged)?,
        (None, Some(iso)) => {
            staged.extend(extract_virtio_netkvm(&iso, arch)?);
            virtio_used = Some(iso);
        }
        (None, None) => {
            #[cfg(feature = "downloader")]
            {
                let p = iso_cache.join(crate::paths::VIRTIO_ISO);
                if !p.exists() {
                    anyhow::bail!(
                        "{} missing (run `setup` first, or pass --virtio-iso/--drivers-dir)",
                        p.display()
                    );
                }
                eprintln!("using cached {}", p.display());
                staged.extend(extract_virtio_netkvm(&p, arch)?);
                virtio_used = Some(p);
            }
            #[cfg(not(feature = "downloader"))]
            {
                anyhow::bail!("pass --virtio-iso <iso> or --drivers-dir <tree>");
            }
        }
    }
    // install.wim must reach wimlib as a file: stream it straight to
    // scratch on disk (7 GB). The old `read_iso_tree` + `fs::write` path
    // held the whole WIM in RAM first; the streaming extractor also
    // tolerates the UDF variants hadris-udf rejects with
    // `invalid Information Control Block` (isomage first, hadris fallback).
    eprintln!("extracting install.wim (several minutes) ...");
    // Deterministic scratch under the project cache (not $TMPDIR):
    // a previous killed/failed run leaves it behind, so purge-then-
    // reuse. The Drop guard removes it on every exit path — success,
    // `?` early-return, panic unwind — so only SIGKILL can orphan it
    // (and the next run's purge collects that too). Peak ~14 GB
    // (install.wim + SWM parts); $TMPDIR orphans used to accumulate
    // one full set per aborted run.
    #[cfg(feature = "downloader")]
    let scratch_root = crate::downloader::iso_cache_dir()?
        .parent()
        .map(|p| p.join("scratch"))
        .unwrap_or_else(std::env::temp_dir);
    #[cfg(not(feature = "downloader"))]
    let scratch_root: PathBuf = std::env::temp_dir();
    let scratch = scratch_root.join("build-media");
    let _scratch_guard = ScratchDir::create(&scratch)?;
    let wim_path = scratch.join("install.wim");
    extract_iso_file_to_disk(&win_iso, "sources/install.wim", &wim_path).map_err(|e| {
        let size = std::fs::metadata(&win_iso).map(|m| m.len()).unwrap_or(0);
        anyhow::anyhow!(
            "extract sources/install.wim from {} (ISO {} bytes): {e:#}\n\
             hint: verify the ISO is a complete, untruncated download \
             (compare its size/hash against your Microsoft download source, \
             then re-download or re-copy it if it differs)",
            win_iso.display(),
            size
        )
    })?;
    let wim_len = std::fs::metadata(&wim_path).map(|m| m.len()).unwrap_or(0);
    eprintln!("media: install.wim extracted ({} bytes)", wim_len);
    eprintln!("splitting install.wim with {} ...", wimlib_bin.display());
    let swm_prefix = scratch.join("install.swm");
    let swm_parts = split_wim(&wimlib_bin, &wim_path, &swm_prefix)?;
    // Provenance while install.wim still exists (wimlib info query),
    // sidecar written after the image build succeeds below.
    #[cfg(feature = "downloader")]
    let qemu_tag = crate::qemu_portable::pinned_cached()
        .map(|q| q.version)
        .unwrap_or_else(|_| "none cached".to_string());
    #[cfg(not(feature = "downloader"))]
    let qemu_tag = "unknown (no downloader feature)".to_string();
    let provenance = crate::provenance::Provenance::gather(
        &win_iso,
        &wimlib_bin,
        &wim_path,
        arch,
        &qemu_tag,
        &wimlib_tag,
        virtio_used.as_deref(),
        &a.username,
        &a.locale,
    )?;
    std::fs::remove_file(&wim_path)?;
    // List ISO tree paths without reading content — files are streamed
    // one at a time during image build (peak ~600 MB vs ~6 GB).
    let subtree_skip: (String, Vec<String>) = ("sources".into(), ["install.wim".into()].into());
    let iso_paths = list_iso_tree(
        &win_iso,
        &["efi".into(), "boot".into()],
        &[],
        Some(&subtree_skip),
    )?;
    let spec = MediaSpec {
        iso: win_iso.clone(),
        out: out.clone(),
        size_bytes: 10 * 1024 * 1024 * 1024,
        label: "WINSETUP".to_string(),
        iso_paths,
        staged,
        swm_parts,
    };
    build_installer_media(&spec)?;
    eprintln!("wrote {}", out.display());
    provenance.write_sidecar(&out)?;
    Ok(())
}

// ---------------------------------------------------------------------------
// run
// ---------------------------------------------------------------------------

pub struct RunArgs {
    pub disk: Option<String>,
    pub ssh_port: u16,
    pub display: crate::qemu::Display,
    /// Guest RAM in MB (parsed from Docker syntax by clap `value_parser`).
    pub memory: u32,
    /// Guest vCPUs (`--cpus`; `--smp` is an alias).
    pub cpus: u32,
    /// New-disk size in GB (install path only; parsed from Docker syntax).
    pub disk_size: u32,
    pub vm_dir: Option<PathBuf>,
    pub qemu_dir: Option<PathBuf>,
    pub username: String,
    pub password: String,
    pub shell: bool,
    /// Opt into the experimental live snapshot resume (`savevm` state):
    /// instant boot when it works. Default off — golden rewind always works.
    pub live: bool,
    /// Windows ISO: when the disk is missing, run the install chain
    /// (setup + build-media + install) instead of bailing.
    pub win_iso: Option<PathBuf>,
    /// Budget for that install's SSH wait, in seconds (`run` passes it
    /// straight through; only reached when `--win-iso` installs).
    pub install_timeout_secs: u64,
    /// Screendump cadence during the boot wait in seconds (0 = disabled);
    /// frames land in `<vm-dir>/screenshots/`.
    pub screenshots_every_secs: u64,
    /// In-memory screen-classification cadence in seconds: `Some(0)` =
    /// disabled, `None` = profile default from the accelerator (10s
    /// hardware, 30s TCG). Screendump + nearest-exemplar match with no
    /// disk write.
    pub classify_every_secs: Option<u64>,
}

/// Install params for the `run --win-iso` chain (missing disk): everything
/// the user sized carries through, nothing silently resets to defaults.
/// Split out so a test pins the passthrough (the screenshot cadence was
/// once hardcoded to 60 here while `run` advertised the flag).
fn run_chain_install_params(a: &RunArgs, iso: PathBuf) -> InstallParams {
    InstallParams {
        usb_image: None,
        win_iso: Some(iso),
        screenshots_every_secs: a.screenshots_every_secs,
        classify_every_secs: a.classify_every_secs,
        username: a.username.clone(),
        password: a.password.clone(),
        recovery: false,
        auto_updates: false,
        install_timeout_secs: a.install_timeout_secs,
        memory_mb: a.memory,
        cpus: a.cpus,
        disk_size_gb: a.disk_size,
        display: a.display.clone(),
    }
}

pub async fn cmd_run(a: RunArgs) -> Result<()> {
    let vm_dir = match a.vm_dir.clone() {
        Some(d) => d,
        None => default_vm_dir()?,
    };
    // Already running? Attach instead of booting: the qcow2 write lock
    // would reject a second QEMU with a cryptic error. A live SSH banner
    // is the ground truth (pidfile alone may be stale).
    if banner_once(a.ssh_port).await.is_some() {
        eprintln!(
            "already running — ssh -p {} <username>@{PROVEN_SSH_HOST}",
            a.ssh_port
        );
        if a.shell {
            crate::ssh::interactive_shell(PROVEN_SSH_HOST, a.ssh_port, &a.username, &a.password)
                .await?;
        }
        return Ok(());
    }
    let _ = std::fs::remove_file(vm_dir.join(crate::paths::QEMU_PIDFILE));
    let disk = a.disk.clone().unwrap_or_else(|| {
        vm_dir
            .join(crate::paths::DISK_IMAGE)
            .to_string_lossy()
            .into_owned()
    });
    // A fresh `qemu-img create` shell is ~200 KB; anything under 1 GB holds
    // no OS (a real install is tens of GB). Treat shells as missing so an
    // interrupted install re-installs instead of booting into UEFI Shell
    // forever (observed live: "guest: Shell>", zero SSH, eternal poll).
    const MIN_VIABLE_DISK: u64 = 1024 * 1024 * 1024;
    let disk_viable = std::fs::metadata(&disk)
        .map(|m| m.len() >= MIN_VIABLE_DISK)
        .unwrap_or(false);
    if !disk_viable {
        match a.win_iso.clone().map(expand_tilde) {
            // Chain: install the disk, then fall through to boot it below.
            // Uses the core only — no shell, no Ctrl-C wait mid-chain. The
            // installer VM is torn down immediately so this command blocks
            // exactly once (in the shared tail after boot), then drops into
            // the guest shell. Explicit `--win-iso` only — never silent.
            Some(iso) => {
                eprintln!(
                    "disk {disk} missing — installing from {} (new {}G disk, {} MB RAM, {} vCPUs) ...",
                    iso.display(),
                    a.disk_size,
                    a.memory,
                    a.cpus,
                );
                let mut session = install_to_ready(run_chain_install_params(&a, iso)).await?;
                finish_install_capture(&mut session).await;
                prove_landed_shell(PROVEN_SSH_PORT, &a.username, &a.password).await?;
                let target = session.vm_dir.join(crate::paths::DISK_IMAGE);
                let target_s = target.to_string_lossy().into_owned();
                shutdown_guest_clean(PROVEN_SSH_HOST, PROVEN_SSH_PORT, &a.username, &a.password)
                    .await?;
                session.child.kill().await?;
                snapshot_golden(&session.img_bin, &target_s).await?;
            }
            None => anyhow::bail!(
                "disk {disk} does not exist (run `install` first, pass --disk <image>, or pass --win-iso to install it now)"
            ),
        }
    }
    // Stale serial from a previous session: drop it before the spawn.
    // QEMU's chardev truncates on open, but the baseline below must be 0
    // *without racing OVMF's first line* (reading after spawn often found
    // the first `BdsDxe: starting` already written and swallowed the
    // "guest booted" narration); an old file would also skew a pre-spawn
    // read.
    let _ = std::fs::remove_file(crate::ipc::vm_endpoint(
        &vm_dir,
        crate::ipc::SERIAL_LOG_NAME,
    ));
    let mut b = HeadlessVmBuilder::new(WindowsVersion::Win11)
        .ssh_port(a.ssh_port)
        .display(a.display.clone())
        .memory_mb(a.memory)
        .smp_cores(a.cpus)
        .workdir(vm_dir);
    match a.qemu_dir {
        Some(d) => b = b.qemu_dir(d),
        None => {
            #[cfg(feature = "downloader")]
            {
                let q = crate::qemu_portable::pinned_cached()?;
                eprintln!("using pinned portable QEMU {}", q.version);
                b = b.qemu_dir(q.root);
            }
        }
    }
    // Golden rewind: a verified landed state rolls the disk past any
    // dirty stop — Recovery can never appear on a rewound base. Applied
    // (`snapshot -a`) rather than `-loadvm`: loadvm restores device state
    // too, and QEMU refuses it with a writable pflash drive attached.
    // Runs after qemu_dir resolution so the same portable qemu-img that
    // wrote the snapshot applies it. Skipped under --live with a live
    // snapshot present: the live state carries the disk, so rewinding
    // first is pure waste (and costs a multi-GB copy for nothing).
    let live_armed = a.live && live_sidecar(&disk).is_file();
    if live_armed {
        // Live resume prep, all pre-boot: the state file, VARS backup, and
        // sidecar must all exist (a partial save resumes nothing); VARS is
        // restored over the live file (raw pflash is outside every
        // snapshot); the save-time overlay is consumed (its post-save
        // writes are superseded by the rewind-to-save-point semantics).
        let vm_dir_pb = b.workdir.clone();
        let (state, vars_backup, overlay) = live_paths(&vm_dir_pb);
        for p in [&state, &vars_backup] {
            if !p.is_file() {
                anyhow::bail!(
                    "live sidecar present but {} is missing (partial save?) — delete {} and re-take with `snapshot --live`",
                    p.display(),
                    live_sidecar(&disk).display()
                );
            }
        }
        std::fs::copy(&vars_backup, vm_dir_pb.join(crate::paths::VARS_FILE))?;
        if overlay.is_file() {
            let _ = std::fs::remove_file(&overlay);
            eprintln!("consuming save-time overlay (post-save writes superseded) ...");
        }
        eprintln!("resuming live state (RAM streams in over -incoming, no boot) ...");
        b = b.incoming(migrate_read_uri(&state));
    } else {
        // Orphaned overlay without a live resume: its writes are
        // unreachable once the base boots alone — drop it out loud rather
        // than hoarding a dead file.
        let workdir = b.workdir.clone();
        let (_, _, overlay) = live_paths(&workdir);
        if overlay.is_file() {
            let _ = std::fs::remove_file(&overlay);
            eprintln!(
                "dropping orphaned live overlay {} (plain boot cannot reach it) ...",
                overlay.file_name().unwrap_or_default().to_string_lossy()
            );
        }
        if golden_sidecar(&disk).is_file() {
            let img_bin = img_bin_for(&b.qemu_dir);
            eprintln!("rewinding to golden snapshot (landed state) ...");
            let st = tokio::process::Command::new(&img_bin)
                .args(["snapshot", "-a", crate::timeouts::GOLDEN_TAG, &disk])
                .status()
                .await?;
            if !st.success() {
                anyhow::bail!(
                    "golden sidecar present but snapshot apply failed — disk left untouched, refusing to boot a half-state (delete {} to boot normally)",
                    golden_sidecar(&disk).display()
                );
            }
        }
    }
    eprintln!(
        "booting {disk} ({} MB RAM, {} vCPUs, display {})",
        a.memory,
        a.cpus,
        a.display.as_arg()
    );
    eprintln!(
        "waiting for SSH on {PROVEN_SSH_HOST}:{} (up to {} min) ...",
        a.ssh_port,
        timeouts::BOOT_SSH_DEADLINE.as_secs() / 60
    );
    // Stale serial from a previous session was dropped pre-spawn so the
    // baseline below is 0 (never a post-spawn read racing OVMF's line).
    let mut vm = b.boot_existing(&disk).await?;
    // One monitor session for the whole boot: VNC handshake plus the stall
    // watchdog below share it (single-client transports forbid overlap).
    // Same retrying handshake as install (live-but-slow QEMU refuses early
    // connects).
    let mon = crate::ipc::Monitor::connect_retry(
        &vm.builder.monitor_socket,
        timeouts::MONITOR_CONNECT_SECS,
        || vm.child.try_wait().map(|o| o.is_none()).unwrap_or(false),
    )
    .await?;
    if a.display.is_vnc() {
        mon.command(&vnc_password_command()).await?;
        let url = vnc_url(&a.display.as_arg()).unwrap_or_else(|| a.display.as_arg());
        eprintln!("VNC {url} (password {PROVEN_VNC_PASSWORD})");
    }
    // Opt-in live resume is fully pre-boot now (state streams in over
    // `-incoming`, VARS + disk restored above): by the time the monitor is
    // up the guest is already continuing, so SSH should answer in seconds.
    if a.live {
        let phase_start = std::time::Instant::now();
        eprintln!("live state streaming in (2-3 GB over -incoming; watch it land) ...");
        let deadline =
            std::time::Instant::now() + Duration::from_secs(timeouts::MIGRATION_BUDGET_SECS);
        loop {
            let mut qmp = vm.qmp().await?;
            match qmp.query_migrate_status().await?.as_str() {
                "completed" => break,
                "failed" | "cancelled" | "cancelling" => {
                    anyhow::bail!(
                        "incoming migration failed — state file may be truncated; re-take with `snapshot --live`"
                    );
                }
                status => {
                    if std::time::Instant::now() > deadline {
                        anyhow::bail!(
                            "incoming migration still '{status}' after {} s — state file unreadable or stream stalled; plain `run` (golden rewind) stays the default that works",
                            timeouts::MIGRATION_BUDGET_SECS
                        );
                    }
                    eprintln!("... incoming migration '{status}' ...");
                    tokio::time::sleep(Duration::from_secs(timeouts::MIGRATION_POLL_SECS)).await;
                }
            }
        }
        eprintln!(
            "live state loaded in {} s — guest resuming ...",
            phase_start.elapsed().as_secs()
        );
        // Mirror of the save-side guard: a completed incoming stream can
        // still leave the destination paused (login screen up, nothing
        // executing — SSH can never answer). Verify running, resume if not.
        // Then a stop/cont round-trip regardless: HVF may not re-arm
        // halted-vCPU timers on the incoming path (frozen lock-screen
        // clock, static frames), and the cycle re-arms them.
        {
            let mut qmp = vm.qmp().await?;
            match qmp.query_vm_status().await?.as_str() {
                "running" => eprintln!("guest executing after restore."),
                stalled => {
                    eprintln!("guest {stalled} after restore — resuming ...");
                    qmp.resume_vm().await?;
                }
            }
            eprintln!("re-arming guest timers (stop/cont cycle) ...");
            qmp.pause_vm().await?;
            tokio::time::sleep(Duration::from_secs(2)).await;
            qmp.resume_vm().await?;
            eprintln!(
                "restore overhead total: {} s (stream + re-arm) — SSH settle next ...",
                phase_start.elapsed().as_secs()
            );
        }
        // The restored virtio-net rings point at the OLD slirp backend
        // (gone with the saving QEMU): packets blackhole while Windows
        // believes nothing changed — healthy desktop, dead SSH (observed).
        // A link flap forces DHCP + NLA + the listener to re-run against
        // the fresh backend. The NIC's device name comes from `info
        // network` (auto-assigned, never guessed); best-effort throughout.
        let nic = mon
            .command("info network")
            .await
            .ok()
            .and_then(|info| find_nic_name(&info).map(str::to_string))
            .unwrap_or_else(|| "n1".to_string());
        for (state, cmd) in [
            ("down", format!("set_link {nic} off")),
            ("up", format!("set_link {nic} on")),
        ] {
            if let Err(e) = mon.command(&cmd).await {
                eprintln!("warning: link flap {state} failed ({e:#}); continuing without it ...");
                break;
            }
            if state == "down" {
                tokio::time::sleep(Duration::from_secs(3)).await;
            }
        }
        // Classify the wire before the blind wait: refused means the guest
        // stack is alive with nothing listening (sshd died in restore);
        // timeout means packets blackhole (NIC/backend mismatch). The fix
        // differs completely, so say which.
        match classify_port(a.ssh_port).await {
            PortState::Open => eprintln!(
                "port {} accepts TCP — waiting for the SSH banner ...",
                a.ssh_port
            ),
            PortState::Refused => eprintln!(
                "port {} REFUSED (guest stack alive, sshd not listening — service did not survive restore)",
                a.ssh_port
            ),
            PortState::Timeout => eprintln!(
                "port {} connect timeout (packets blackholed — NIC/backend mismatch despite flap)",
                a.ssh_port
            ),
        }
        eprintln!("link flapped — waiting for SSH to re-bind ...");
    }
    if !a.live {
        eprintln!("QEMU launched; guest is booting ...");
    }
    let pidfile = vm.builder.pidfile();
    let start = std::time::Instant::now();
    // One shots dir for the whole wait: periodic boot frames land here and
    // every failure path captures its final frame into it too.
    let shots_dir = screenshots_dir(&vm.builder.workdir);
    let disk = vm.builder.workdir.join(crate::paths::DISK_IMAGE);
    // Cadence policy resolves after accelerator detection: an explicit
    // flag wins, else TCG earns 3x spacing on classification.
    let profile = SamplingProfile::resolve(
        a.screenshots_every_secs,
        a.classify_every_secs,
        auto_detect_platform().1,
    );
    if !profile.save_every.is_zero() {
        eprintln!(
            "Saving a boot screenshot every {}s → {}",
            profile.save_every.as_secs(),
            shots_dir.display()
        );
    }
    if !profile.classify_every.is_zero() {
        eprintln!(
            "Classifying the boot screen every {}s (in memory, no file)",
            profile.classify_every.as_secs()
        );
    }
    // VNC coordinates for failure reports (None for gtk/cocoa/none — the
    // frame + serial line still say what happened).
    let vnc = a
        .display
        .is_vnc()
        .then(|| vnc_url(&a.display.as_arg()).unwrap_or_else(|| a.display.as_arg()));
    // Single tick authority: the profile's interval drives; save,
    // classify, and narration each gate on their own due-check inside.
    // All-zero cadences still need the SSH wait + stall watchdog, so fall
    // back to the SSH poll interval (sampling simply never fires).
    let tick_interval = profile.tick().unwrap_or(timeouts::SSH_POLL_INTERVAL);
    let mut ticker = tokio::time::interval(tick_interval);
    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    // Skip the immediate first tick so the first status line comes
    // after a full interval of actual waiting, not at launch.
    ticker.tick().await;
    // Stall sensor + screen state, reunited per tick: serial-silent deaths
    // would otherwise poll SSH blindly.
    let mon = std::sync::Arc::new(mon);
    let mut activity = ActivityMonitor::new();
    let mut sampler = ScreenSampler::new(std::sync::Arc::clone(&mon), shots_dir.clone());
    // Reboot awareness below the screenshot layer: OVMF's per-boot handoff
    // line in the serial file, so "the guest bounced" is announced even
    // while the screen looks like nothing happened. Baseline 0 (the stale
    // file was removed pre-spawn) — never a post-spawn read, which races
    // OVMF's first line.
    let mut boots_seen = 0u64;
    // Narration due-check state: the "... still waiting" pulse on the
    // profile's rhythm, never a second ticker.
    let mut last_narrate = start;
    tokio::select! {
        r = vm.wait_for_ssh(timeouts::BOOT_SSH_DEADLINE) => {
            // Time's up: the serial is silent through a Windows boot, so
            // the screen + serial tail are the only evidence of *where*
            // boot died (black handoff vs a parked Windows prompt —
            // neither is guessable from the timeout alone). Attach both
            // instead of dropping the frame on the floor.
            if let Err(e) = r {
                let report =
                    boot_failure_report(&mon, &vm.builder.serial_log, &shots_dir, &vnc).await;
                anyhow::bail!("{e:#}\n{report}");
            }
        }
        cause = async {
            loop {
                ticker.tick().await;
                // Dead-screen watchdog: a fatal serial signature means the
                // boot already failed — return it as the cause instead of
                // polling on.
                check_boot_failure(&vm.builder.serial_log)?;
                // Reboot narration (first boot or a bounce): serial truth,
                // independent of what the screenshots look like.
                let boots = boot_count(&vm.builder.serial_log);
                if let Some(note) = boot_note(boots_seen, boots) {
                    eprintln!("{note}");
                }
                boots_seen = boots;
                // Sample first: the stall check below needs fresh counters.
                activity.sample(&mon, Some(disk.as_path())).await;
                // One sampler tick, then the reporter line. Save and
                // classify gate inside; narration gates below.
                sampler.poll(&profile).await;
                // Stall watchdog, conditioned on screen state: frozen disk
                // I/O during valid progress (Setup applying, OOBE) is a
                // slow host, never a stuck guest — progress states answer
                // only to the outer SSH deadline. Bail propagates out of
                // the select arm below.
                activity.check_stall(sampler.state(), true)?;
                report_sample("boot", &sampler, &activity);
                // Narrate the boot on the profile pulse only: last serial
                // line says what the guest is doing (recovery, Boot Manager,
                // Setup pass...). The ticker may run faster for
                // classification; this line must not turn into spam.
                if last_narrate.elapsed() < profile.narrate_every {
                    continue;
                }
                last_narrate = std::time::Instant::now();
                let doing = last_serial_line(&vm.builder.serial_log);
                if doing.is_empty() {
                    eprintln!(
                        "... still waiting for SSH ({}s elapsed)",
                        start.elapsed().as_secs()
                    );
                } else {
                    eprintln!(
                        "... still waiting for SSH ({}s elapsed) — guest: {doing}",
                        start.elapsed().as_secs()
                    );
                }
            }
            #[allow(unreachable_code)]
            Ok::<(), anyhow::Error>(())
        } => {
            // The loop only ever ends by erroring (its Ok arm is
            // unreachable): carry the cause, then the evidence block —
            // final frame with path + screen classification, last serial
            // line, VNC coordinates — so the failure reads without VNC.
            let cause =
                cause.map_or_else(|e| format!("{e:#}"), |_| "guest failed to boot".to_string());
            let report =
                boot_failure_report(&mon, &vm.builder.serial_log, &shots_dir, &vnc).await;
            eprintln!("stopping dead guest...");
            vm.kill().await?;
            let _ = std::fs::remove_file(pidfile);
            anyhow::bail!("{cause}\n{report}");
        }
        _ = shutdown_signal() => {
            eprintln!("interrupted during boot; stopping guest...");
            if let Err(e) = vm.kill().await {
                eprintln!("warning: kill failed: {e:#}");
            }
            let _ = std::fs::remove_file(pidfile);
            return Ok(());
        }
    }
    eprintln!(
        "ready — ssh -p {} <user>@{PROVEN_SSH_HOST} (you will be prompted for credentials)",
        a.ssh_port,
    );
    // Cooked mode, SIGINT/SIGTERM via shutdown_signal — the term-wm way.
    // Raw mode was tried here (Ctrl-C as byte 0x03): under a multiplexer
    // the byte path proved unreliable while kernel signals always land.
    // Echo-trash during the wait is cosmetic; a non-exiting shutdown is
    // functional. Never trade the latter for the former again.
    // Ctrl-C means kill, immediately. No ACPI grace period by explicit
    // user decision: a forgotten snapshot is the user's fault, and a
    // 90-second wait that reads as a hang is worse than a dirty bit that
    // chkdsk replays. The overlay/golden design absorbs the risk.
    // A second branch watches the child: `snapshot` from another terminal
    // quits this QEMU out from under us — exit with the news instead of
    // parking at the Ctrl-C prompt on a dead VM.
    tokio::select! {
        r = shell_then_wait(
            a.shell,
            PROVEN_SSH_HOST,
            a.ssh_port,
            &a.username,
            &a.password,
            "press Ctrl-C to stop the VM (immediate kill, no graceful wait)...",
        ) => {
            r?;
            eprintln!("killing guest...");
            if let Err(e) = vm.kill().await {
                eprintln!("warning: kill failed: {e:#}");
            }
        }
        s = vm.child.wait() => {
            match s {
                Ok(status) => eprintln!("VM exited underneath us (status {status}) — e.g. `snapshot` from another terminal. Exiting ..."),
                Err(e) => eprintln!("VM wait failed ({e:#}) — exiting ..."),
            }
        }
    }
    let _ = std::fs::remove_file(pidfile);
    eprintln!("stopped");
    Ok(())
}

// ---------------------------------------------------------------------------
// install
// ---------------------------------------------------------------------------

/// Sidecar next to the disk proving a golden snapshot lives inside it.
/// Written only after a verified landing; removed when an install starts,
/// so a stale sidecar can never bless a half-written disk.
pub fn golden_sidecar(disk: &str) -> PathBuf {
    PathBuf::from(format!("{disk}.golden"))
}

/// Sidecar for the experimental live snapshot (`--live`): migrated RAM +
/// device state plus VARS backup, kept strictly separate from golden so a
/// failed live experiment can never confuse the rewind path.
pub fn live_sidecar(disk: &str) -> PathBuf {
    PathBuf::from(format!("{disk}.golden-live"))
}

/// NIC device name from HMP `info network` (first `type=nic` entry):
/// auto-assigned by QEMU, never guessed — the flap must name the device,
/// not the netdev.
fn find_nic_name(info: &str) -> Option<&str> {
    info.lines().find_map(|l| {
        let l = l.trim();
        let (name, rest) = l.split_once(':')?;
        if rest.contains("type=nic") {
            Some(name.trim())
        } else {
            None
        }
    })
}

/// One-shot TCP classification for the SSH port: does the restored guest
/// accept, refuse, or swallow SYNs? Decides between "sshd died" and
/// "packets blackholed" without a VNC session.
enum PortState {
    Open,
    Refused,
    Timeout,
}

async fn classify_port(port: u16) -> PortState {
    match tokio::time::timeout(
        Duration::from_secs(5),
        tokio::net::TcpStream::connect((PROVEN_SSH_HOST, port)),
    )
    .await
    {
        Ok(Ok(_)) => PortState::Open,
        Ok(Err(_)) => PortState::Refused,
        Err(_) => PortState::Timeout,
    }
}
/// Shell-quote a path for QEMU `exec:` migration URIs (single-quote with
/// embedded quotes escaped — cache paths routinely contain spaces).
fn shell_quote(path: &Path) -> String {
    format!("'{}'", path.to_string_lossy().replace('\'', "'\\''"))
}

/// Migration-write URI for `snapshot --live` (`migrate` streams the guest
/// out through `cat` into the state file).
pub fn migrate_write_uri(state: &Path) -> String {
    format!("exec:cat > {}", shell_quote(state))
}

/// Migration-read URI for `run --live` (`-incoming` streams the state file
/// back into a fresh QEMU).
pub fn migrate_read_uri(state: &Path) -> String {
    format!("exec:cat {}", shell_quote(state))
}

/// Live-snapshot companions inside the VM dir.
fn live_paths(vm_dir: &Path) -> (PathBuf, PathBuf, PathBuf) {
    (
        vm_dir.join(crate::paths::LIVE_STATE_FILE),
        vm_dir.join(crate::paths::LIVE_VARS_BACKUP),
        vm_dir.join(crate::paths::LIVE_OVERLAY),
    )
}

/// Remove all live-snapshot remnants (announced): a new install or rewind
/// voids them — resuming post-save writes against a rewound base would
/// boot a half-state.
fn clear_live_state(vm_dir: &Path) {
    let disk = vm_dir
        .join(crate::paths::DISK_IMAGE)
        .to_string_lossy()
        .into_owned();
    let (state, vars, overlay) = live_paths(vm_dir);
    for p in [live_sidecar(&disk), state, vars, overlay] {
        if p.is_file() {
            let _ = std::fs::remove_file(&p);
            eprintln!(
                "dropping stale live snapshot file {} ...",
                p.file_name().unwrap_or_default().to_string_lossy()
            );
        }
    }
}

/// Portable `qemu-img` for `qemu_dir` (resolved tree) or PATH fallback.
fn img_bin_for(qemu_dir: &Option<PathBuf>) -> PathBuf {
    match qemu_dir {
        Some(d) => d
            .join(crate::paths::PORTABLE_BIN_DIR)
            .join(crate::paths::QEMU_IMG_NAME),
        None => PathBuf::from(crate::paths::QEMU_IMG_NAME),
    }
}

/// Prove the landed shell, deterministically: banner up, readiness probe
/// passing, and a real exec returning the right user. No clocks, no
/// windows — each check is present-tense evidence, and the snapshot below
/// is voided the moment the banner drops, so no prediction is needed.
async fn prove_landed_shell(port: u16, user: &str, password: &str) -> Result<()> {
    if banner_once(port).await.is_none() {
        anyhow::bail!("no SSH banner at snapshot time");
    }
    if !crate::ssh::probe_setup_done(PROVEN_SSH_HOST, port, user, password)
        .await
        .is_ok_and(|g| g.is_ready())
    {
        anyhow::bail!("guest not READY at snapshot time");
    }
    // LITERAL shell landing: a pty shell answering back, the exact path
    // a user login takes — not a banner read, not an exec probe.
    crate::ssh::prove_interactive_shell(PROVEN_SSH_HOST, port, user, password).await?;
    eprintln!("shell proven (prompt answered), saving golden ...");
    Ok(())
}

/// Watch the golden snapshot's premise: any banner loss after snapshotting
/// means the guest bounced (the extra reboot the first banner never shows),
/// so the sidecar is deleted on the spot. Returns when voided. Safe
/// direction only: losing golden just means the next boot is normal.
async fn watch_golden_void(port: u16, disk: String) {
    loop {
        tokio::time::sleep(Duration::from_secs(15)).await;
        if banner_once(port).await.is_none() {
            let _ = std::fs::remove_file(golden_sidecar(&disk));
            eprintln!("guest bounced after golden — snapshot voided, next boot is normal ...");
            return;
        }
    }
}

/// Clean guest shutdown ahead of a golden snapshot: `Stop-Computer` over
/// SSH, then wait for the banner to die (halted). Golden must capture a
/// clean bit — a QMP-quit power cut here would bake the dirty flag into
/// every future rewind. Loud failure instead of a dirty snapshot: the
/// caller reports, nothing is captured.
async fn shutdown_guest_clean(host: &str, port: u16, user: &str, pass: &str) -> Result<()> {
    eprintln!(
        "shutting guest down cleanly for snapshot (up to {} s) ...",
        timeouts::GUEST_SHUTDOWN_SECS
    );
    // Best-effort issue: if the guest is already dying, the banner wait
    // below still does the real gating.
    let _ = crate::ssh::ssh_exec(
        host,
        port,
        user,
        pass,
        "powershell -NoProfile -Command \"Stop-Computer -Force\"",
    )
    .await;
    let deadline = std::time::Instant::now() + Duration::from_secs(timeouts::GUEST_SHUTDOWN_SECS);
    // Two consecutive misses: a single loopback blip must not pass for a
    // halt with the guest still running (snapshotting that disk would
    // bless torn writes).
    let mut misses = 0u32;
    loop {
        if banner_once(port).await.is_none() {
            misses += 1;
            if misses >= 2 {
                eprintln!("guest halted.");
                return Ok(());
            }
        } else {
            misses = 0;
        }
        if std::time::Instant::now() > deadline {
            anyhow::bail!(
                "guest did not halt within {} s — refusing a dirty snapshot (stop it and retry)",
                timeouts::GUEST_SHUTDOWN_SECS
            );
        }
        tokio::time::sleep(Duration::from_secs(5)).await;
    }
}

/// Disk-only golden snapshot of the landed state + sidecar. QEMU must
/// already be stopped (this runs post-kill): offline `qemu-img snapshot`
/// sidesteps live device state entirely — boots rewind with `snapshot -a`
/// and enumerate devices fresh, so pflash never blocks anything.
async fn snapshot_golden(img_bin: &Path, disk: &str) -> Result<()> {
    // Best-effort delete first: re-snapshotting over an existing tag must
    // not fail. Stderr nulled: deleting a nonexistent tag is the normal
    // first-snapshot case, not an error worth printing.
    use std::process::Stdio;
    let _ = tokio::process::Command::new(img_bin)
        .args(["snapshot", "-d", timeouts::GOLDEN_TAG, disk])
        .stderr(Stdio::null())
        .status()
        .await;
    let st = tokio::process::Command::new(img_bin)
        .args(["snapshot", "-c", timeouts::GOLDEN_TAG, disk])
        .status()
        .await?;
    if !st.success() {
        anyhow::bail!("qemu-img snapshot failed");
    }
    std::fs::write(
        golden_sidecar(disk),
        format!("{}\n", crate::provenance::now_epoch()),
    )?;
    eprintln!("golden snapshot saved — next boots resume in seconds.");
    Ok(())
}

/// Live installer session: QEMU still running after the OS reports ready.
/// The caller owns the tail (capture a final frame, optionally offer a
/// shell, wait for Ctrl-C, kill) via the shared helpers below — `cmd_install`
/// supervises it, `cmd_run --win-iso` tears it down immediately and boots
/// the disk instead. One core, no pasted tails.
pub struct InstallSession {
    pub child: tokio::process::Child,
    pub mon: std::sync::Arc<crate::ipc::Monitor>,
    pub vm_dir: PathBuf,
    pub screenshots: Option<tokio::task::JoinHandle<()>>,
    /// `qemu-img` binary used for this install (for the post-kill golden
    /// snapshot — the session outlives the paths that found it).
    pub img_bin: PathBuf,
}

/// Shared middle of the run/install tails (defined once, called twice):
/// optional guest shell, then block for Ctrl-C/SIGTERM. Killing stays with
/// the caller (run owns a `HeadlessVm` + pidfile, install owns a raw
/// `Child`), so this helper only covers the identical part.
async fn shell_then_wait(
    shell: bool,
    host: &str,
    port: u16,
    username: &str,
    password: &str,
    prompt: &str,
) -> Result<()> {
    if shell {
        crate::ssh::interactive_shell(host, port, username, password).await?;
        // The guest prompt never terminates its line — without this, the
        // wait prompt below lands mid-prompt (`C:\...>press Ctrl-C ...`).
        eprintln!();
    }
    eprintln!("{prompt}");
    shutdown_signal().await;
    Ok(())
}

/// Shared installer capture step (defined once): stop the time-lapse, keep
/// one final desktop frame as evidence. Called by both the standalone
/// `install` tail and the `run --win-iso` chain teardown.
async fn finish_install_capture(session: &mut InstallSession) {
    if let Some(h) = session.screenshots.take() {
        h.abort();
    }
    // Final frame after victory: the desktop as proven, not mid-install.
    if let Some((p, s, m)) = take_screenshot(&session.mon, &screenshots_dir(&session.vm_dir)).await
    {
        eprintln!(
            "final frame: {} ({})",
            p.file_name().unwrap_or_default().to_string_lossy(),
            describe(s, m)
        );
    }
}

/// Inputs for the install-time QEMU argv (pure constructor below): every
/// runtime-resolved path plus the user sizing, so tests can assert the
/// flags reach QEMU without spawning anything.
pub(crate) struct InstallQemuArgv<'a> {
    pub machine: &'a str,
    pub accel: &'a str,
    pub cpu: &'a str,
    pub memory_mb: u32,
    pub cpus: u32,
    pub display: Display,
    pub code_tpl: &'a Path,
    pub vars_fd: &'a Path,
    pub serial_log: &'a str,
    pub mon_sock: &'a str,
    pub qmp_sock: &'a str,
    pub usb_image: &'a Path,
    pub target: &'a str,
    pub arch: Architecture,
}

/// `qemu-img create` args (binary excluded): carries the user disk size.
/// `-q` silences the `Formatting ...` line (our own banner says it).
pub(crate) fn qemu_img_create_args(target: &str, disk_size_gb: u32) -> Vec<String> {
    vec![
        "create".into(),
        "-q".into(),
        "-f".into(),
        "qcow2".into(),
        target.into(),
        format!("{disk_size_gb}G"),
    ]
}

/// Installer QEMU argv (binary excluded): `-m`/`-smp` carry the user sizing.
pub(crate) fn install_qemu_argv(s: &InstallQemuArgv) -> Vec<String> {
    let mut argv = vec![
        "-M".into(),
        s.machine.to_string(),
        "-accel".into(),
        s.accel.to_string(),
        "-cpu".into(),
        s.cpu.to_string(),
        "-m".into(),
        s.memory_mb.to_string(),
        "-smp".into(),
        s.cpus.to_string(),
        "-drive".into(),
        format!(
            "if=pflash,format=raw,file={},readonly=on",
            s.code_tpl.display()
        ),
        "-drive".into(),
        format!("if=pflash,format=raw,file={}", s.vars_fd.display()),
        "-display".into(),
        s.display.to_string(),
        "-serial".into(),
        format!("file:{}", s.serial_log),
        "-drive".into(),
        format!(
            "file={},format=raw,if=none,id=usbstick",
            s.usb_image.display()
        ),
        "-netdev".into(),
        format!("user,id=n1,hostfwd=tcp::{}-:22", PROVEN_SSH_PORT),
        "-device".into(),
        "virtio-net-pci,netdev=n1".into(),
        "-monitor".into(),
        crate::ipc::qemu_arg(s.mon_sock),
        "-qmp".into(),
        crate::ipc::qemu_arg(s.qmp_sock),
    ];
    // xHCI first: neither q35 nor virt ships a USB bus, so usb-storage and
    // the ARM64 input devices below would be bus-less without it.
    argv.push("-device".into());
    argv.push("qemu-xhci,id=xhci".into());
    // ARM64 virt ships with NO input/display devices of its own:
    // USB keyboard (send-key needs it) + USB tablet (VNC
    // pointer needs it), and ramfb as the one framebuffer (single
    // console: VNC and screendump keep working after Windows takes
    // over, unlike virtio-gpu). x86/pc has PS/2 + VGA by default.
    if s.arch == Architecture::Arm64 {
        argv.push("-device".into());
        argv.push("usb-kbd".into());
        argv.push("-device".into());
        argv.push("usb-tablet".into());
        argv.push("-device".into());
        argv.push("ramfb".into());
    }
    // Removable USB media (never ide-hd). Two separate things decide
    // whether Setup finds its media and where it installs — they were
    // conflated here before, and both were verified live:
    //   * partition type (media.rs): WinPE letters a Microsoft Basic Data
    //     FAT32 volume, but mounts an ESP — or any GUID it won't letter —
    //     Hidden with no drive letter, so Setup never sees
    //     sources/install.swm and parks at "Install driver to show hardware";
    //   * enumeration order: USB storage lands behind the NVMe (Disk 0 =
    //     the target), while ide-hd came first (Disk 0 = the 10 GB media),
    //     and the unattend installs to Disk 0.
    argv.push("-device".into());
    argv.push("usb-storage,drive=usbstick,removable=true,bootindex=1".into());
    argv.push("-drive".into());
    argv.push(format!("file={},format=qcow2,if=none,id=tgt", s.target));
    argv.push("-device".into());
    argv.push("nvme,drive=tgt,serial=nvme1,bootindex=0".into());
    argv
}

/// One orchestrator for all install stages: grouping the params in a
/// struct beats counting them in a lint attribute.
pub struct InstallParams {
    pub usb_image: Option<PathBuf>,
    pub win_iso: Option<PathBuf>,
    pub screenshots_every_secs: u64,
    pub classify_every_secs: Option<u64>,
    pub username: String,
    pub password: String,
    pub recovery: bool,
    pub auto_updates: bool,
    pub install_timeout_secs: u64,
    pub memory_mb: u32,
    pub cpus: u32,
    pub disk_size_gb: u32,
    pub display: crate::qemu::Display,
}

/// Proven NVMe+USB unattended install: installer USB + NVMe target,
/// answer file, probe-gated SSH wait. Both platforms present the media
/// as removable USB storage (bootindex 1) behind xHCI and the target as
/// NVMe (bootindex 0): that is the topology the macOS run proved, and
/// Linux now shares it (its old IDE-HD branch enumerated the 10 GB media
/// first, as Disk 0, while the unattend installs to Disk 0).
///
/// Core only: leaves the installer QEMU running and returns it. No shell,
/// no Ctrl-C wait, no kill — the caller picks the tail via
/// `shell_then_wait` + `finish_install_capture`.
///
/// Run from the repo root (USB media must already exist).
async fn install_to_ready(p: InstallParams) -> Result<InstallSession> {
    // Sockets, serial log, SSH port and VNC settings match what `run`
    // boots: every endpoint is scoped to this VM dir (never /tmp —
    // world-writable-sticky, symlink squatting, cross-VM collisions).
    let (arch, _) = auto_detect_platform();

    let vm_dir = default_vm_dir()?;
    let mon_sock = vm_endpoint(&vm_dir, MON_SOCK_NAME);
    let qmp_sock = vm_endpoint(&vm_dir, QMP_SOCK_NAME);
    let serial_log = vm_endpoint(&vm_dir, SERIAL_LOG_NAME);
    // Install into the same disk `run` boots by default, so plain `run`
    // starts what this installed (no --disk needed).
    let target = vm_dir.join(crate::paths::DISK_IMAGE);
    let target_s = target.to_string_lossy().into_owned();
    // One NVRAM file shared with `run`. The install refreshes it from the
    // template (a reused VARS carries stale boot entries that shadow the
    // installer's ISO — BlInitializeLibrary 0xc00000bb), then keeps it
    // across Setup's own reboots; `run` never refreshes it, so the guest's
    // firmware state survives its boots.
    let vars_fd = vm_dir.join(crate::paths::VARS_FILE);
    let run_log = vm_dir.join(crate::paths::INSTALL_LOG);
    let usb_image = p.usb_image.unwrap_or(default_media_image()?);
    if !usb_image.is_file() {
        match p.win_iso {
            // Chain: fetch deps + build the USB image, then install from it.
            // Explicit `--win-iso` only — never silent (setup downloads).
            #[cfg(feature = "downloader")]
            Some(iso) => {
                // The ISO is the one input `setup` cannot fetch: check it
                // BEFORE the downloads, so a bad path fails in milliseconds
                // instead of after gigabytes of tools.
                require_win_iso(&expand_tilde(iso.clone()))?;
                eprintln!(
                    "USB installer media missing — building it from {} (one-time; downloads tools, then builds a ~7 GB image) ...",
                    iso.display()
                );
                cmd_setup(None, None).await?;
                cmd_build_media(BuildMediaArgs {
                    win_iso: iso,
                    arch: None,
                    virtio_iso: None,
                    drivers_dir: None,
                    openssh_zip: None,
                    out: Some(usb_image.clone()),
                    wimlib_bin: None,
                    username: p.username.clone(),
                    password: p.password.clone(),
                    locale: "en-US".to_string(),
                    // Chain runs only when the image is absent — nothing to force.
                    force: false,
                })
                .await?;
            }
            #[cfg(not(feature = "downloader"))]
            Some(_) => anyhow::bail!("--win-iso chaining needs the downloader feature"),
            None => anyhow::bail!(
                "USB installer image {} missing — build it with `build-media --win-iso <iso>`, pass --usb-image <image>, or pass --win-iso to build it now",
                usb_image.display()
            ),
        }
    }

    // Portable QEMU tree: the pinned release under the downloader
    // feature, else the pinned version dir under `./.cache/qemu-portable`.
    #[cfg(feature = "downloader")]
    let qdir = crate::qemu_portable::pinned_cached()?.root;
    #[cfg(not(feature = "downloader"))]
    let qdir = {
        // pins + paths (not qemu_portable): that module is downloader-gated.
        // The tag is the cache dir name, verbatim — no mangling.
        use crate::paths::{FALLBACK_QEMU_CACHE, PORTABLE_BIN_DIR, QEMU_IMG_NAME, QEMU_INNER};
        use crate::pins::QEMU_PORTABLE_TAG;
        let dir = std::env::current_dir()?
            .join(FALLBACK_QEMU_CACHE)
            .join(QEMU_PORTABLE_TAG)
            .join(QEMU_INNER);
        anyhow::ensure!(
            dir.join(PORTABLE_BIN_DIR).join(QEMU_IMG_NAME).is_file(),
            "pinned portable QEMU {QEMU_PORTABLE_TAG} not cached in {} (no downloader feature to fetch it)",
            dir.display()
        );
        dir
    };
    let sys_bin = qdir.join(format!("bin/{}", arch.qemu_binary()));
    let img_bin = qdir
        .join(crate::paths::PORTABLE_BIN_DIR)
        .join(crate::paths::QEMU_IMG_NAME);
    let share = qdir.join("share/qemu");
    let (code_names, vars_names) = arch.firmware_names();
    let code_tpl = code_names
        .iter()
        .map(|n| share.join(n))
        .find(|p| p.is_file());
    let vars_tpl = vars_names
        .iter()
        .map(|n| share.join(n))
        .find(|p| p.is_file());
    let (code_tpl, vars_tpl) = match (code_tpl, vars_tpl) {
        (Some(c), Some(v)) => (c, v),
        _ => anyhow::bail!("no UEFI firmware for {arch:?} in {}", share.display()),
    };
    for p in [&sys_bin, &img_bin] {
        if !p.exists() {
            anyhow::bail!("missing required file: {}", p.display());
        }
    }
    // CODE runs straight from the portable tree (readonly, same bytes —
    // no scratch copy). VARS is refreshed per install from the template:
    // a zeroed NVRAM file breaks OVMF initialisation (BlInitializeLibrary
    // 0xc00000bb) because the firmware needs the template's runtime
    // services data to present correct UEFI protocols to the Boot Manager.
    let _ = std::fs::remove_file(&vars_fd);
    std::fs::copy(&vars_tpl, &vars_fd).with_context(|| {
        format!(
            "copy VARS template {} -> {}",
            vars_tpl.display(),
            vars_fd.display()
        )
    })?;
    let _ = std::fs::remove_file(&target);
    // A new install voids any golden snapshot (sidecar dies with the
    // disk it blessed — a stale sidecar must never bless new bytes).
    let _ = std::fs::remove_file(golden_sidecar(&target_s));
    // ...and any live snapshot (its base, RAM, and VARS all predate this
    // disk — resuming them would boot a half-state).
    if let Some(parent) = std::path::Path::new(&target_s).parent() {
        clear_live_state(parent);
    }
    eprintln!(
        "installing Windows to {target_s} (new {}G disk, {} MB RAM, {} vCPUs) ...",
        p.disk_size_gb, p.memory_mb, p.cpus
    );
    let st = tokio::process::Command::new(&img_bin)
        .args(qemu_img_create_args(&target_s, p.disk_size_gb))
        .status()
        .await?;
    if !st.success() {
        anyhow::bail!("qemu-img create failed");
    }
    for s in [&mon_sock, &qmp_sock] {
        crate::ipc::stale_remove(s);
    }
    let out = std::fs::File::create(&run_log)?;
    eprintln!("QEMU output log: {}", run_log.display());
    // Same probe as `run`/boot argv (unattend::resolve_accel): Linux
    // without usable /dev/kvm (OrbStack, containers) falls back to tcg
    // instead of dying on `-accel kvm`. CPU follows the accel: `host`
    // passthrough on hardware accel, `max` under TCG (the `virt` default
    // is too old for Windows 11 ARM64).
    let (_, accel) = auto_detect_platform();
    let cpu = if accel == "tcg" { "max" } else { "host" };
    // (No extra warning here: resolve_accel already warned via tracing.)
    let machine = crate::qemu::machine_for(arch);
    let mut child = tokio::process::Command::new(&sys_bin);
    child.args(install_qemu_argv(&InstallQemuArgv {
        machine,
        accel,
        cpu,
        memory_mb: p.memory_mb,
        cpus: p.cpus,
        display: p.display.clone(),
        code_tpl: &code_tpl,
        vars_fd: &vars_fd,
        serial_log: &serial_log,
        mon_sock: &mon_sock,
        qmp_sock: &qmp_sock,
        usb_image: &usb_image,
        target: &target_s,
        arch,
    }));
    child
        .stdin(std::process::Stdio::null())
        .stdout(out.try_clone()?)
        .stderr(out)
        .kill_on_drop(true);
    // Own process group (Unix): same tty-SIGINT rationale as qemu.rs spawn —
    // the installer's Ctrl-C must reach only the CLI, never QEMU directly.
    // Windows: CREATE_NEW_PROCESS_GROUP, same rationale (see qemu.rs).
    #[cfg(unix)]
    {
        child.process_group(0);
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        /// Win32 `CREATE_NEW_PROCESS_GROUP` (no winapi dep for one flag).
        const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
        child.as_std_mut().creation_flags(CREATE_NEW_PROCESS_GROUP);
    }
    let mut child = child.spawn()?;
    let child_pid = child.id();
    eprintln!(
        "QEMU started (pid {child_pid:?}); waiting for the monitor (up to {}s) ...",
        timeouts::MONITOR_CONNECT_SECS
    );
    // Retry the REAL handshake, never a probe connect: QEMU's listen
    // backlog is a single slot and a probe occupies it, refusing the real
    // handshake with ECONNREFUSED on a live QEMU (observed). Retry while
    // the child lives, bail on death — never on a live child, or
    // kill_on_drop destroys the evidence (the old 3 s bail did exactly
    // that to slow hvf starters).
    let mon =
        match crate::ipc::Monitor::connect_retry(&mon_sock, timeouts::MONITOR_CONNECT_SECS, || {
            child.try_wait().map(|o| o.is_none()).unwrap_or(false)
        })
        .await
        {
            Ok(m) => m,
            Err(e) => {
                let status = child
                    .try_wait()
                    .map(|o| {
                        o.map(|s| s.to_string())
                            .unwrap_or_else(|| "still alive".into())
                    })
                    .unwrap_or_else(|e| format!("status unknown ({e:#})"));
                let _ = child.kill().await;
                anyhow::bail!(
                    "QEMU (pid {child_pid:?}, status {status}): {e:#}; check {}",
                    run_log.display()
                );
            }
        };
    // VNC-only step (same guard as the boot path): cocoa/gtk/sdl have
    // no VNC server to password-protect.
    if p.display.is_vnc() {
        mon.command(&vnc_password_command()).await?;
    }
    let mon = std::sync::Arc::new(mon);
    let url = vnc_url(&p.display.as_arg()).unwrap_or_else(|| p.display.as_arg());
    if p.display.is_vnc() {
        eprintln!(
            "Windows installer is running — watch it at {url} (VNC password: {PROVEN_VNC_PASSWORD})."
        );
    } else {
        eprintln!("Windows installer is running on the {url} display.");
    }

    if accel == "tcg" {
        eprintln!(
            "This takes a while (much longer under TCG emulation); SSH answers when Setup finishes."
        );
    } else {
        eprintln!("This takes a while; SSH answers when Setup finishes.");
    }
    // Cadence policy resolves after accel detection (same `accel` the
    // install argv above used — post any KVM→TCG fallback): an explicit
    // flag wins, else TCG earns 3x spacing on classification.
    let profile = SamplingProfile::resolve(p.screenshots_every_secs, p.classify_every_secs, accel);
    let screenshots = if !profile.save_every.is_zero() || !profile.classify_every.is_zero() {
        let dir = screenshots_dir(&vm_dir);
        if !profile.save_every.is_zero() {
            eprintln!(
                "Saving an installer screenshot every {}s until then → {}",
                profile.save_every.as_secs(),
                dir.display()
            );
        }
        if !profile.classify_every.is_zero() {
            eprintln!(
                "Classifying the installer screen every {}s (in memory, no file)",
                profile.classify_every.as_secs()
            );
        }
        spawn_sampler(
            std::sync::Arc::clone(&mon),
            dir,
            vm_dir.join(crate::paths::DISK_IMAGE),
            profile,
            "installer",
        )
    } else {
        None
    };
    let shots_dir = screenshots_dir(&vm_dir);
    let scope = GuestScope {
        mon: std::sync::Arc::clone(&mon),
        shots_dir,
        serial_log: serial_log.clone(),
        vnc: p.display.is_vnc().then(|| url.clone()),
    };
    tokio::select! {
        r = wait_install_ready(
            PROVEN_SSH_PORT,
            // A progressing install, not a parked one: the wait's own
            // no-I/O watchdog (`timeouts::IDLE_BAIL_SECS`) already fails
            // fast on a guest that stops moving, so this only bounds how
            // long a *slow* host may keep applying the image (hours on a
            // ~1 MB/s machine).
            Duration::from_secs(p.install_timeout_secs),
            &p.username,
            &p.password,
            p.recovery,
            p.auto_updates,
            &scope,
        ) => {
            let banner = match r {
                Ok(b) => b,
                Err(e) => {
                    // Same evidence block as `run`'s failure arms: final
                    // frame + serial tail + VNC, attached to the cause
                    // (banner timeout, fatal signature, stall watchdog).
                    let report = boot_failure_report(
                        &scope.mon,
                        &scope.serial_log,
                        &scope.shots_dir,
                        &scope.vnc,
                    )
                    .await;
                    anyhow::bail!("{e:#}\n{report}");
                }
            };
            // Committed proof: one tested-isos.jsonl line from the image's
            // sidecar, plus a README table refresh when the markers exist.
            // Best-effort throughout — images built before sidecars existed
            // still install fine, they just leave no record. (The probe
            // already authenticated as `p.username`, so the CLI value is
            // authoritative for the ready line.)
            match crate::provenance::TestRecord::load_sidecar(&usb_image) {
                Ok(prov) => {
                    match crate::provenance::TestRecord::append(prov, &banner) {
                        Ok(_) => {
                            use crate::provenance::TestRecord;
                            let readme = PathBuf::from(README_FILE);
                            if readme.is_file() {
                                let log = PathBuf::from(TestRecord::LOG);
                                if let Err(e) = cmd_report(ReportArgs { log, readme: Some(readme) }) {
                                    eprintln!("warning: README table refresh failed: {e:#}");
                                }
                            }
                        }
                        Err(e) => eprintln!("warning: test record append failed: {e:#}"),
                    }
                }
                Err(e) => eprintln!("warning: no sidecar, skipping test record: {e:#}"),
            }
            eprintln!(
                "ready — ssh -p {} <user>@{PROVEN_SSH_HOST} (credentials not shown)",
                PROVEN_SSH_PORT
            );
        }
        _ = shutdown_signal() => {
            eprintln!("interrupted; stopping guest...");
            if let Some(h) = &screenshots {
                h.abort();
            }
            child.kill().await?;
            // Interrupt is NOT success: bail so callers (`run --win-iso`)
            // stop the chain instead of booting a half-installed disk.
            anyhow::bail!("interrupted during install; disk left half-written (rerun to start over)");
        }
    }
    Ok(InstallSession {
        child,
        mon,
        vm_dir,
        screenshots,
        img_bin,
    })
}

/// Snapshot the running guest's disk as the new golden state (`docker
/// commit`): proves the shell, stops QEMU, snapshots offline, and writes
/// the sidecar. The guest must be up (boot it with `run` first); QEMU is
/// left stopped afterward, so boot again to resume the new golden.
/// With `live`: QMP `savevm` on the running guest instead (no shutdown —
/// instant-boot state, experimental; the writable pflash drive may veto
/// it, in which case nothing is written and the guest keeps running).
pub async fn cmd_snapshot(
    vm_dir: Option<PathBuf>,
    qemu_dir: Option<PathBuf>,
    username: String,
    password: String,
    ssh_port: u16,
    live: bool,
) -> Result<()> {
    let vm_dir = match vm_dir {
        Some(d) => d,
        None => default_vm_dir()?,
    };
    let disk = vm_dir
        .join(crate::paths::DISK_IMAGE)
        .to_string_lossy()
        .into_owned();
    if !std::path::Path::new(&disk).is_file() {
        anyhow::bail!("no disk at {disk} (install first)");
    }
    // The guest must be running: a snapshot of a stopped disk proves
    // nothing about the shell.
    if banner_once(ssh_port).await.is_none() {
        anyhow::bail!(
            "no SSH banner on {PROVEN_SSH_HOST}:{ssh_port} (boot the guest with `run` first)"
        );
    }
    prove_landed_shell(ssh_port, &username, &password).await?;
    if live {
        // Live path: pivot an overlay (atomic — the base freezes at this
        // instant, post-save writes land in the overlay), then migrate
        // RAM + devices to the state file (migration transfers pflash
        // content, so the savevm veto does not apply), then back up VARS
        // (raw pflash lives outside every snapshot). Guest keeps running
        // throughout; crash-consistent like a power cut at the pivot.
        let (state, vars_backup, overlay) = live_paths(&vm_dir);
        // Fresh pivot each save: a leftover overlay would fail the pivot
        // and poison the consistency story.
        for p in [&state, &vars_backup, &overlay] {
            let _ = std::fs::remove_file(p);
        }
        let qmp_sock = crate::ipc::vm_endpoint(&vm_dir, crate::ipc::QMP_SOCK_NAME);
        let mut qmp = crate::qmp::QmpClient::connect(&qmp_sock).await?;
        eprintln!("pivoting live overlay (freezing base) ...");
        qmp.live_overlay("tgt", &overlay.to_string_lossy())
            .await
            .map_err(|e| anyhow::anyhow!("live overlay pivot refused ({e:#}) — guest untouched"))?;
        eprintln!("migrating guest state to file (brief stun) ...");
        qmp.migrate_to_file(&state).await.map_err(|e| {
            anyhow::anyhow!(
                "live migration refused ({e:#}) — guest still running on the overlay; delete {} to unwind",
                overlay.display()
            )
        })?;
        let deadline =
            std::time::Instant::now() + Duration::from_secs(timeouts::MIGRATION_BUDGET_SECS);
        loop {
            let status = qmp.query_migrate_status().await?;
            if status == "completed" {
                break;
            }
            if status == "failed" || status == "cancelled" {
                anyhow::bail!(
                    "live migration {status} — guest still running on the overlay; delete {} to unwind",
                    overlay.display()
                );
            }
            if std::time::Instant::now() > deadline {
                anyhow::bail!(
                    "live migration still '{status}' after {} s — guest still running on the overlay; delete {} to unwind",
                    timeouts::MIGRATION_BUDGET_SECS,
                    overlay.display()
                );
            }
            tokio::time::sleep(Duration::from_secs(timeouts::MIGRATION_POLL_SECS)).await;
        }
        std::fs::copy(vm_dir.join(crate::paths::VARS_FILE), &vars_backup)?;
        // Post-migration liveness: a completed job can still leave the VM
        // paused (observed: guest "locked up" after a clean save). Verify
        // running, resume if paused — never hand back a frozen guest.
        match qmp.query_vm_status().await?.as_str() {
            "running" => {}
            stalled => {
                eprintln!("guest {stalled} after migration — resuming ...");
                qmp.resume_vm().await?;
            }
        }
        std::fs::write(
            live_sidecar(&disk),
            format!("{}\n", crate::provenance::now_epoch()),
        )?;
        eprintln!("live snapshot saved — `run --live` resumes it instantly; guest still running.");
        return Ok(());
    }
    let img_bin = match qemu_dir {
        Some(d) => d
            .join(crate::paths::PORTABLE_BIN_DIR)
            .join(crate::paths::QEMU_IMG_NAME),
        None => {
            #[cfg(feature = "downloader")]
            {
                let q = crate::qemu_portable::pinned_cached()?;
                q.root
                    .join(crate::paths::PORTABLE_BIN_DIR)
                    .join(crate::paths::QEMU_IMG_NAME)
            }
            #[cfg(not(feature = "downloader"))]
            {
                PathBuf::from(crate::paths::QEMU_IMG_NAME)
            }
        }
    };
    // Clean halt first (guest-initiated, so the bit is clean), then QMP
    // quit reaps a halted QEMU, then the offline snapshot. A power-cut
    // snapshot would bake the dirty flag into every future rewind.
    shutdown_guest_clean(PROVEN_SSH_HOST, ssh_port, &username, &password).await?;
    cmd_stop(Some(vm_dir), None).await?;
    snapshot_golden(&img_bin, &disk).await?;
    eprintln!("golden refreshed — `run` resumes this state from now on.");
    Ok(())
}

/// Standalone `install`: full install, then supervise the VM for a human
/// via the shared tail (final frame + optional shell + Ctrl-C wait + kill).
/// `shell` only affects this tail, never the install itself.
pub async fn cmd_install(p: InstallParams, shell: bool) -> Result<()> {
    let username = p.username.clone();
    let password = p.password.clone();
    let mut session = install_to_ready(p).await?;
    finish_install_capture(&mut session).await;
    // Golden before shell/kill: prove the shell now, snapshot now. A bounce
    // afterward voids the sidecar (watcher below) instead of having been
    // predicted by a timer.
    prove_landed_shell(PROVEN_SSH_PORT, &username, &password).await?;
    let target = session.vm_dir.join(crate::paths::DISK_IMAGE);
    let target_s = target.to_string_lossy().into_owned();
    if shell {
        let disk = target_s.clone();
        tokio::select! {
            _ = shell_then_wait(
                true,
                PROVEN_SSH_HOST,
                PROVEN_SSH_PORT,
                &username,
                &password,
                "press Ctrl-C to shut the VM down cleanly",
            ) => {},
            // Bounce voids golden but the install stands: keep waiting for
            // Ctrl-C afterward instead of exiting early.
            _ = watch_golden_void(PROVEN_SSH_PORT, disk) => {
                shell_then_wait(
                    true,
                    PROVEN_SSH_HOST,
                    PROVEN_SSH_PORT,
                    &username,
                    &password,
                    "press Ctrl-C to shut the VM down cleanly",
                )
                .await?;
            }
        }
    } else {
        eprintln!("install complete (non-interactive — shutting down guest)...");
    }
    // Clean halt before the snapshot (same reason as `snapshot`): golden
    // must capture a clean bit. Ctrl-C still kills instantly everywhere
    // else — only snapshot paths pay for clean.
    shutdown_guest_clean(PROVEN_SSH_HOST, PROVEN_SSH_PORT, &username, &password).await?;
    session.child.kill().await?;
    snapshot_golden(&session.img_bin, &target_s).await?;
    Ok(())
}

// ---------------------------------------------------------------------------
// report
// ---------------------------------------------------------------------------

pub struct ReportArgs {
    pub log: PathBuf,
    /// README to splice the table into (between TESTED markers). If absent,
    /// the table prints to stdout for manual pasting.
    pub readme: Option<PathBuf>,
}

/// README filename refreshed automatically by `install` (repo root,
/// current dir at runtime). Marker-gated: absent markers mean warn, never
/// blind rewrite.
pub const README_FILE: &str = "README.md";

const REPORT_BEGIN: &str = "<!-- TESTED-BEGIN -->";
const REPORT_END: &str = "<!-- TESTED-END -->";

fn epoch_to_date(epoch: u64) -> String {
    // No chrono dep: days since epoch → approximate YYYY-MM-DD via a tiny
    // civil-date conversion (Howard Hinnant's algorithm).
    let days = (epoch / 86_400) as i64;
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    format!("{:04}-{:02}-{:02}", if m <= 2 { y + 1 } else { y }, m, d)
}

/// Release page URL for a tag in our portable repo (used to link generated
/// report cells to the exact artifacts consumed).
fn release_tag_url(tag: &str) -> String {
    format!(
        "https://github.com/{}/releases/tag/{tag}",
        crate::pins::RELEASE_REPO
    )
}

/// Render `tested-isos.jsonl` as a markdown table: the human-readable face
/// of the machine-readable log. Short commit + `*` when the build was dirty
/// (hash alone doesn't reproduce it); virtio as short SHA of the consumed
/// ISO (name when `--drivers-dir` bypassed the ISO). Newest first: the log
/// is append-only, so rows are collected then reversed for display.
/// QEMU/wimlib/virtio cells link to their exact release pages.
pub fn render_report(log: &Path) -> Result<String> {
    let text = std::fs::read_to_string(log).with_context(|| format!("read {}", log.display()))?;
    let mut rows = vec![
        "| Date | ISO | Arch | Accel | Host | QEMU | wimlib | virtio | Commit | Result |"
            .to_string(),
        "|---|---|---|---|---|---|---|---|---|---|".to_string(),
    ];
    let mut entries = Vec::new();
    for (n, line) in text.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let r: crate::provenance::TestRecord = serde_json::from_str(line)
            .with_context(|| format!("{} line {}", log.display(), n + 1))?;
        let p = &r.provenance;
        let commit_short = p.build_commit.chars().take(7).collect::<String>();
        // Clean-tree hashes exist upstream — link them. Dirty-tree hashes
        // (`*`) don't, so they stay plain text (a link would 404).
        let commit = if p.build_dirty {
            format!("{commit_short}*")
        } else {
            format!(
                "[{commit_short}]({}/commit/{})",
                env!("CARGO_PKG_REPOSITORY"),
                p.build_commit
            )
        };
        let virtio = match &p.deps.virtio_sha256 {
            Some(sha) => format!(
                "[{}]({})",
                sha.chars().take(7).collect::<String>(),
                release_tag_url(crate::pins::DRIVERS_RELEASE_TAG)
            ),
            None => p.deps.virtio_iso_name.clone(),
        };
        entries.push(format!(
            "| {} | {} | {} | {} | {} {} | [{}]({}) | [{}]({}) | {} | {} | {} |",
            epoch_to_date(r.tested_at_epoch),
            p.source_iso.file_name,
            p.guest.arch,
            p.guest.accel,
            p.host.os,
            p.host.os_version,
            p.deps.qemu_tag,
            release_tag_url(&p.deps.qemu_tag),
            p.deps.wimlib_tag,
            release_tag_url(&p.deps.wimlib_tag),
            virtio,
            commit,
            r.outcome,
        ));
    }
    entries.reverse();
    rows.extend(entries);
    Ok(rows.join("\n") + "\n")
}

/// Score one PNG through the k-NN classifier ([`crate::screen_knn`]:
/// blurred unit-norm luminance + cosine vs the baked cluster centers).
/// OOD triage in one shot — no fixture dir, no snapshot, nothing
/// blessed. The verdict names the matched exemplar, so a miss is a
/// viewable cause. User-supplied path, so loading is fallible
/// (`try_load_rgb_8bit`) — bad input exits nonzero via `anyhow`, never a
/// panic out of the fixture loader.
pub fn cmd_classify(png: &std::path::Path) -> Result<()> {
    use crate::screen_knn::{KNN_TOP_K, KNN_UNCERTAIN_GAP, KnnIndex, bundled_index};
    let path = png
        .to_str()
        .with_context(|| format!("non-UTF8 image path: {}", png.display()))?;
    let (rgb, w, h) = crate::screen_knn::try_load_rgb_8bit(path)
        .map_err(|e| anyhow::anyhow!("load {path}: {e}"))?;
    if rgb.is_empty() || w == 0 {
        println!("top-1: Dark gap 1.000 (empty input — nothing captured)");
        println!("verdict: COMMITTED (margin holds — narration states the label)");
        return Ok(());
    }
    let index = bundled_index();
    let q = KnnIndex::embed_frame(&rgb, w, h);
    let (top, gap, matched) = index
        .predict(&q, None)
        .with_context(|| "empty bundled k-NN index — rebuild artifacts/knn_index.bin")?;
    println!("top-1: {top:?} gap {gap:.4} via {matched}");
    for (label, cos, name) in index.query(&q, None, KNN_TOP_K) {
        let class = crate::screen_knn::BY_INDEX
            .iter()
            .find(|c| **c as usize == label)
            .copied()
            .unwrap_or(crate::screen_knn::ScreenClass::Dark);
        println!("  {class:?}: {cos:.4} {name}");
    }
    if gap < KNN_UNCERTAIN_GAP {
        println!(
            "verdict: UNCERTAIN (gap below {KNN_UNCERTAIN_GAP:.2} — narration hedges, nothing gates)"
        );
    } else {
        println!("verdict: COMMITTED (margin holds — narration states the label)");
    }
    Ok(())
}

pub fn cmd_report(a: ReportArgs) -> Result<()> {
    let table = render_report(&a.log)?;
    match a.readme {
        None => print!("{table}"),
        Some(readme) => {
            let text = std::fs::read_to_string(&readme)?;
            let (head, rest) = text
                .split_once(REPORT_BEGIN)
                .with_context(|| format!("{} has no {REPORT_BEGIN} marker", readme.display()))?;
            let (_, tail) = rest
                .split_once(REPORT_END)
                .with_context(|| format!("{} has no {REPORT_END} marker", readme.display()))?;
            let updated = format!("{head}{REPORT_BEGIN}\n{table}{REPORT_END}{tail}");
            std::fs::write(&readme, updated)?;
            eprintln!("updated {}", readme.display());
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// guest
// ---------------------------------------------------------------------------

/// Guest verbs (work on any booted machine via SSH). Same verbs the
/// install flow uses internally — exposed here for live machines.
#[derive(clap::Subcommand)]
pub enum GuestOp {
    /// Execute one command, print stdout.
    Exec {
        /// Command line (joined with spaces).
        #[arg(last = true)]
        cmd: Vec<String>,
    },
    /// Rotate the guest password (verified by fresh login).
    SetPassword {
        /// New password (never logged).
        new_password: String,
    },
    /// Set Automatic Repair on/off.
    SetRecovery {
        /// `true` keeps it, `false` disables it.
        #[arg(action = clap::ArgAction::Set, value_parser = clap::value_parser!(bool))]
        enabled: bool,
    },
    /// Set automatic Windows updates on/off.
    SetUpdates {
        /// `true` enables wuauserv, `false` disables it.
        #[arg(action = clap::ArgAction::Set, value_parser = clap::value_parser!(bool))]
        enabled: bool,
    },
    /// Ask the guest whether Setup is finished (READY/BUSY verdict).
    Probe,
}

pub struct GuestArgs {
    pub op: GuestOp,
    pub ssh_port: u16,
    pub username: String,
    pub password: String,
}

pub async fn cmd_guest(a: GuestArgs) -> Result<()> {
    use crate::qemu::PROVEN_SSH_HOST;
    let host = PROVEN_SSH_HOST;
    match a.op {
        GuestOp::Exec { cmd } => {
            let out =
                crate::ssh::ssh_exec(host, a.ssh_port, &a.username, &a.password, &cmd.join(" "))
                    .await?;
            print!("{out}");
        }
        GuestOp::SetPassword { new_password } => {
            crate::ssh::change_guest_password(
                host,
                a.ssh_port,
                &a.username,
                &a.password,
                &new_password,
            )
            .await?;
            eprintln!("password rotated (verified by fresh login)");
        }
        GuestOp::SetRecovery { enabled } => {
            crate::ssh::set_recovery_enabled(host, a.ssh_port, &a.username, &a.password, enabled)
                .await?;
        }
        GuestOp::SetUpdates { enabled } => {
            crate::ssh::set_auto_updates(host, a.ssh_port, &a.username, &a.password, enabled)
                .await?;
        }
        GuestOp::Probe => {
            let progress =
                crate::ssh::probe_setup_done(host, a.ssh_port, &a.username, &a.password).await?;
            eprintln!("{}", if progress.is_ready() { "READY" } else { "BUSY" });
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// overlay / stop
// ---------------------------------------------------------------------------

pub async fn cmd_overlay(
    base: Option<PathBuf>,
    overlay: PathBuf,
    qemu_dir: Option<PathBuf>,
) -> Result<()> {
    // Base defaults to the disk `run` boots — overlays are deltas over it.
    let base = match base {
        Some(b) => b,
        None => default_vm_dir()?.join(crate::paths::DISK_IMAGE),
    };
    if !base.is_file() {
        anyhow::bail!("base {} missing (run `install` first)", base.display());
    }
    let img = qemu_dir
        .map(|d| {
            d.join(crate::paths::PORTABLE_BIN_DIR)
                .join(crate::paths::QEMU_IMG_NAME)
        })
        .unwrap_or_else(|| PathBuf::from(crate::paths::QEMU_IMG_NAME));
    DiskManager::create_overlay(&img, &base, &overlay).await?;
    eprintln!("overlay {} over {}", overlay.display(), base.display());
    Ok(())
}

pub async fn cmd_stop(vm_dir: Option<PathBuf>, qmp_sock: Option<String>) -> Result<()> {
    use crate::qmp::QmpClient;
    let vm_dir = match vm_dir {
        Some(d) => d,
        None => default_vm_dir()?,
    };
    // Default QMP endpoint lives next to the disk (never /tmp); explicit
    // --qmp-sock overrides (URLs/paths as given).
    let qmp_sock = qmp_sock.unwrap_or_else(|| vm_endpoint(&vm_dir, QMP_SOCK_NAME));
    // Best-effort pid lookup for messaging (kill fallback below).
    let pid = std::fs::read_to_string(vm_dir.join(crate::paths::QEMU_PIDFILE))
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty());
    if !qmp_alive(&qmp_sock).await {
        // Not reachable: drop a stale pidfile if present, then report.
        let pidfile = vm_dir.join(crate::paths::QEMU_PIDFILE);
        if pidfile.exists() {
            let _ = std::fs::remove_file(&pidfile);
        }
        match pid {
            Some(p) => println!(
                "no QMP on {qmp_sock}: VM is unreachable (wedged or already gone). If `ps -p {p}` is alive, `kill {p}` to clean up."
            ),
            None => println!("no running VM on {qmp_sock}"),
        }
        return Ok(());
    }
    let mut qmp = QmpClient::connect(&qmp_sock).await?;
    qmp.quit().await?;
    // Drop the session before probing: single-client transports refuse a
    // probe while our own session is open (false "dead").
    drop(qmp);
    for _ in 0..timeouts::QMP_QUIT_POLL_COUNT {
        if !qmp_alive(&qmp_sock).await {
            break;
        }
        tokio::time::sleep(timeouts::QMP_QUIT_POLL_INTERVAL).await;
    }
    let pidfile = vm_dir.join(crate::paths::QEMU_PIDFILE);
    let _ = std::fs::remove_file(&pidfile);
    if qmp_alive(&qmp_sock).await {
        anyhow::bail!(
            "VM ignored QMP quit; kill it manually (see {} before cleanup)",
            crate::paths::QEMU_PIDFILE
        );
    }
    eprintln!("stopped");
    Ok(())
}

// ---------------------------------------------------------------------------
// downloader-backed commands
// ---------------------------------------------------------------------------

/// Download one file into place (skip when cached and valid). Shared by
/// `fetch` and `setup` so both print the same `cached|downloaded` lines.
/// `force` re-downloads even a valid cache entry (for URL-rotated
/// artifacts like the Windows ISO); `setup` always passes false.
#[cfg(feature = "downloader")]
pub async fn fetch_one(
    url: &str,
    dest: &std::path::Path,
    hash: Option<&str>,
    force: bool,
) -> Result<()> {
    use crate::downloader;
    let name = dest
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| dest.display().to_string());
    let is_iso = name.ends_with(".iso");
    // A previously cached file may be a bot-check HTML stub
    // (HTTP 200 with no ISO magic) — drop it so it re-downloads
    // instead of poisoning this run and hanging EDK2 at boot.
    if is_iso && dest.exists() && downloader::validate_iso_image(dest).is_err() {
        eprintln!(
            "cached {} is not an ISO image; re-downloading",
            dest.display()
        );
        std::fs::remove_file(dest)?;
    }
    match downloader::download_if_missing(url, dest, hash, force).await? {
        downloader::DownloadStatus::Cached { path } => {
            if is_iso {
                downloader::validate_iso_image(&path)?;
            }
            eprintln!("cached {}", path.display())
        }
        downloader::DownloadStatus::Downloaded { path, sha256 } => {
            if is_iso && let Err(e) = downloader::validate_iso_image(&path) {
                let _ = std::fs::remove_file(&path);
                return Err(e)
                    .with_context(|| format!("downloaded {} failed validation", path.display()));
            }
            eprintln!("downloaded {} (sha256 {sha256})", path.display())
        }
    }
    Ok(())
}

#[cfg(feature = "downloader")]
pub async fn cmd_fetch_qemu(
    qemu_tag: Option<String>,
    dir: Option<PathBuf>,
    allow_unverified: bool,
) -> Result<()> {
    let q = crate::qemu_portable::ensure(dir, qemu_tag, allow_unverified).await?;
    eprintln!("portable QEMU {} at {}", q.version, q.root.display());
    for bin in q.system_binaries() {
        eprintln!("  system: {}", bin.display());
    }
    eprintln!("  img:    {}", q.qemu_img().display());
    Ok(())
}

#[cfg(feature = "downloader")]
pub struct FetchArgs {
    pub win_iso_url: Option<String>,
    pub win_iso_sha256: Option<String>,
    pub virtio_iso_url: Option<String>,
    pub dir: Option<PathBuf>,
    pub virtio_sha256: Option<String>,
    pub openssh: bool,
    pub arch: Option<Architecture>,
    /// Re-download even valid cache entries (for URL-rotated artifacts
    /// like the Windows ISO, whose slot name can't see upstream changes).
    pub force: bool,
}

#[cfg(feature = "downloader")]
pub async fn cmd_fetch(a: FetchArgs) -> Result<()> {
    use crate::downloader;
    let dir = match a.dir {
        Some(d) => d,
        None => downloader::iso_cache_dir()?,
    };
    // Explicit flag wins; else a pre-fetched time-limited link via env.
    // No page scraper: Microsoft links require the interactive form.
    // Absent entirely: skip the Windows ISO (e.g. you already have one
    // on disk and only need virtio-win.iso).
    let mut items: Vec<(String, &str, Option<String>)> = Vec::new();
    match downloader::resolve_win_iso_url(a.win_iso_url) {
        Ok(u) => {
            // Explicit flag wins, else $WIN11_ISO_SHA256; absent = TLS only.
            let win_hash = a
                .win_iso_sha256
                .or_else(|| std::env::var("WIN11_ISO_SHA256").ok());
            items.push((u, crate::paths::WIN11_ISO_NAME, win_hash))
        }
        Err(e) => eprintln!("skipping Windows ISO: {e:#}"),
    }
    // virtio-win.iso: explicit URL wins, else our vendored release
    // asset (hash from the release sidecar). No fallback: a failed
    // lookup means the pin is wrong or GitHub is unreachable, and
    // silently substituting unpinned upstream bytes would hide either.
    let (virtio_url, virtio_hash) = match a.virtio_iso_url {
        Some(u) => {
            if a.virtio_sha256.is_none() {
                tracing::warn!(
                    "custom --virtio-iso-url without --virtio-sha256: virtio-win.iso will be TLS-only (no hash verification)"
                );
            }
            (u, a.virtio_sha256)
        }
        None => {
            let (u, h) = downloader::virtio_release_info().await.with_context(|| {
                format!(
                    "virtio release lookup failed for {} (check the pin and GitHub API rate limits)",
                    downloader::VIRTIO_RELEASE_TAG
                )
            })?;
            (u, a.virtio_sha256.or(Some(h)))
        }
    };
    items.push((virtio_url, crate::paths::VIRTIO_ISO, virtio_hash));
    if a.openssh {
        let arch = resolve_arch(a.arch);
        items.push((
            downloader::openssh_zip_url(arch),
            arch.openssh_zip_name(),
            Some(arch.openssh_sha256().to_string()),
        ));
    }
    for (url, name, hash) in items {
        fetch_one(&url, &dir.join(name), hash.as_deref(), a.force).await?;
    }
    Ok(())
}

#[cfg(feature = "downloader")]
pub async fn cmd_setup(virtio_iso_url: Option<String>, arch: Option<Architecture>) -> Result<()> {
    use crate::downloader;
    let arch = resolve_arch(arch);
    let q = crate::qemu_portable::ensure(None, None, false).await?;
    eprintln!("portable QEMU {} at {}", q.version, q.root.display());
    let w = crate::qemu_portable::ensure_wimlib(None, None, false).await?;
    eprintln!("portable wimlib {} at {}", w.version, w.root.display());
    let dir = downloader::iso_cache_dir()?;
    let (virtio_url, virtio_hash) = match virtio_iso_url {
        Some(u) => {
            tracing::warn!(
                "custom virtio ISO URL without --virtio-sha256: virtio-win.iso will be TLS-only (no hash verification)"
            );
            (u, None)
        }
        None => {
            let (u, h) = downloader::virtio_release_info().await?;
            (u, Some(h))
        }
    };
    fetch_one(
        &virtio_url,
        &dir.join(crate::paths::VIRTIO_ISO),
        virtio_hash.as_deref(),
        false,
    )
    .await?;
    fetch_one(
        &downloader::openssh_zip_url(arch),
        &dir.join(arch.openssh_zip_name()),
        Some(arch.openssh_sha256()),
        false,
    )
    .await?;
    eprintln!("setup complete (Windows ISO still yours: pass --win-iso to build-media)");
    Ok(())
}

#[cfg(feature = "downloader")]
pub async fn cmd_fetch_wimlib(
    wimlib_tag: Option<String>,
    dir: Option<PathBuf>,
    allow_unverified: bool,
) -> Result<()> {
    let w = crate::qemu_portable::ensure_wimlib(dir, wimlib_tag, allow_unverified).await?;
    eprintln!("portable wimlib {} at {}", w.version, w.root.display());
    eprintln!("  bin: {}", w.wimlib_bin().display());
    Ok(())
}

/// Verify every pinned external artifact WITHOUT downloading archives or
/// installing anything (CI-friendly: KBs of metadata, plus two ~5 MB OpenSSH
/// zips). Checks, per artifact:
/// 1. the release asset exists (availability for that environment), and
/// 2. its hash matches the code-pinned expectation.
///
/// Hash-only sources are preferred wherever they exist (`SHA256SUMS.txt`,
/// virtio `.sha256` sidecar); only OpenSSH (no upstream sums) downloads the
/// payload itself. Prints one line per check; returns an error summarizing
/// all failures so a single CI run reports everything at once.
#[cfg(feature = "downloader")]
pub async fn cmd_verify_pins() -> Result<()> {
    use crate::downloader;
    use crate::qemu_portable::{parse_sums, release_by_tag};
    let mut failures: Vec<String> = Vec::new();
    let ok = |label: &str| eprintln!("pin ok: {label}");

    // Portable QEMU + wimlib: all three platform markers, sums hash vs pin.
    for (product, tag, prefix, is_wimlib) in [
        (
            "qemu",
            crate::pins::QEMU_PORTABLE_TAG,
            crate::paths::QEMU_ASSET_PREFIX,
            false,
        ),
        (
            "wimlib",
            crate::pins::WIMLIB_PORTABLE_TAG,
            crate::paths::WIMLIB_ASSET_PREFIX,
            true,
        ),
    ] {
        let assets = match release_by_tag(tag).await {
            Ok(a) => a,
            Err(e) => {
                failures.push(format!("{product} {tag}: release lookup failed: {e:#}"));
                continue;
            }
        };
        let sums_url = match assets
            .iter()
            .find(|(n, _)| n == crate::paths::SHA256SUMS_FILE)
            .map(|(_, u)| u.clone())
        {
            Some(u) => u,
            None => {
                failures.push(format!(
                    "{product} {tag}: no {}",
                    crate::paths::SHA256SUMS_FILE
                ));
                continue;
            }
        };
        let sums_body = match downloader::fetch_text(&sums_url).await {
            Ok(b) => b,
            Err(e) => {
                failures.push(format!("{product} {tag}: sums fetch failed: {e:#}"));
                continue;
            }
        };
        for marker in [
            crate::paths::MARKER_MACOS_ARM64,
            crate::paths::MARKER_LINUX_X86_64,
            crate::paths::MARKER_LINUX_AARCH64,
        ] {
            let label = format!("{product} {tag} [{marker}]");
            let Some(asset) = assets
                .iter()
                .find(|(n, _)| n.contains(marker) && n.starts_with(prefix))
                .map(|(n, _)| n.clone())
            else {
                failures.push(format!("{label}: no release asset"));
                continue;
            };
            let Some(expected) = (if is_wimlib {
                crate::qemu_portable::pinned_wimlib_sha256(marker)
            } else {
                crate::qemu_portable::pinned_qemu_sha256(marker)
            }) else {
                failures.push(format!("{label}: no pinned hash for marker"));
                continue;
            };
            match parse_sums(&sums_body, &asset) {
                Some(h) if h.eq_ignore_ascii_case(expected) => ok(&label),
                Some(h) => failures.push(format!(
                    "{label}: sums hash {h} != pinned {expected} (stale pin? asset rotated?)"
                )),
                None => failures.push(format!(
                    "{label}: {asset} missing from {}",
                    crate::paths::SHA256SUMS_FILE
                )),
            }
        }
    }

    // virtio-win.iso: sidecar must be a valid 64-hex digest AND match the
    // code pin (closes the TOFU gap: a forged sidecar+ISO pair fails here).
    match downloader::virtio_release_info().await {
        Ok((url, sha)) => {
            ok(&format!("virtio-win.iso [{sha}] ({url})"));
        }
        Err(e) => failures.push(format!("virtio-win.iso: release lookup failed: {e:#}")),
    }
    // OpenSSH: no upstream sums — download both zips (~5 MB) to a tempdir
    // and hash against the arch-strict pins.
    let tmp = tempfile::tempdir().context("verify-pins tempdir")?;
    for arch in [crate::Architecture::Amd64, crate::Architecture::Arm64] {
        let label = format!("{} ({})", arch.openssh_zip_name(), arch.as_xml_str());
        let dest = tmp.path().join(arch.openssh_zip_name());
        match downloader::download(&downloader::openssh_zip_url(arch), &dest).await {
            Ok(actual) => {
                let _ = std::fs::remove_file(&dest);
                if actual.eq_ignore_ascii_case(arch.openssh_sha256()) {
                    ok(&label);
                } else {
                    failures.push(format!(
                        "{label}: downloaded hash {actual} != pinned {}",
                        arch.openssh_sha256()
                    ));
                }
            }
            Err(e) => failures.push(format!("{label}: download failed: {e:#}")),
        }
    }

    if failures.is_empty() {
        eprintln!("verify-pins: all pinned artifacts available and hash-matched");
        Ok(())
    } else {
        for f in &failures {
            eprintln!("pin FAIL: {f}");
        }
        anyhow::bail!("verify-pins: {} check(s) failed", failures.len())
    }
}

// ---------------------------------------------------------------------------
// VM helpers (shared by run / install)
// ---------------------------------------------------------------------------

/// Last meaningful line of the guest serial log (EDK2/Windows boot chatter).
/// Shown in the boot-wait ticker so a slow boot narrates itself instead of
/// printing bare elapsed seconds (observed live: 450 s of silence during a
/// recovery boot). Empty when the log has nothing yet.
///
/// Filters EDK2 memory-map/TPM noise (`ConvertPages`, `Tcg2`) that repeats
/// for minutes and says nothing — without this the ticker quotes firmware
/// trivia as status (observed live).
fn last_serial_line(serial_log: &str) -> String {
    /// Substrings marking firmware noise, never boot progress.
    const NOISE: &[&str] = &[
        "ConvertPages: failed to find range",
        "Tpm2SubmitCommand",
        "Tcg2",
        "Tpm2GetCapability",
    ];
    let text = std::fs::read_to_string(serial_log).unwrap_or_default();
    // Serial carries ANSI escapes and \r; take the last line with text
    // (reverse scan stops at the first hit instead of walking the log).
    fn stripped(line: &str, noise: &[&str]) -> Option<String> {
        // Strip common ANSI CSI sequences (best-effort, no regex dep).
        let mut s = String::with_capacity(line.len());
        let mut chars = line.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '\x1b' && chars.peek() == Some(&'[') {
                for c2 in chars.by_ref() {
                    if c2.is_ascii_alphabetic() {
                        break;
                    }
                }
            } else {
                s.push(c);
            }
        }
        let s = s.trim().to_string();
        (!s.is_empty() && !noise.iter().any(|n| s.contains(n))).then_some(s)
    }
    let line = text
        .replace('\r', "\n")
        .lines()
        .rev()
        .filter_map(|l| stripped(l, NOISE))
        .next()
        .unwrap_or_default();
    // Cap length: some lines are progress bars several KB wide.
    if line.len() > 100 {
        format!("{}...", &line[..100])
    } else {
        line
    }
}
/// Fatal boot-failure patterns in the guest serial log (EDK2/Windows).
/// Patterns live in `templates/boot-fatal-patterns.txt` (one substring per
/// line), not in code — new dead screens are learned by editing a text
/// file, not shipping a release. Conservative by design: only signatures
/// that never appear in a healthy boot. A hit means VNC would show a dead
/// screen — fail fast with the evidence instead of polling SSH.
fn fatal_boot_patterns() -> Vec<String> {
    const TPL: &str = include_str!("../templates/boot-fatal-patterns.txt");
    TPL.lines()
        .map(str::trim)
        .filter(|l| !l.is_empty() && !l.starts_with('#'))
        .map(str::to_string)
        .collect()
}

/// Firmware boot handoffs in the serial log: OVMF prints one
/// `BdsDxe: starting <entry>` line per boot attempt it launches (failed
/// candidates log `failed to load` instead), so the count rises on every
/// guest reboot — the below-screenshot "did it bounce?" signal. QEMU's
/// file chardev truncates at VM start, so it counts this session only.
/// Caveat: a boot entry whose `Start()` returns without loading can add a
/// line without a full reboot — the trend (flat vs rising) is the signal.
fn boot_count(serial_log: &str) -> u64 {
    std::fs::read_to_string(serial_log)
        .unwrap_or_default()
        .matches("BdsDxe: starting")
        .count() as u64
}

/// One-shot narration for a rising [`boot_count`]: `None` while flat, a
/// line for the first boot, a reboot line after it. Count regressions
/// (a truncated log) stay silent — never claim a reboot that didn't show.
fn boot_note(old: u64, new: u64) -> Option<String> {
    (new > old).then(|| {
        if new == 1 {
            "guest booted (first firmware boot)".to_string()
        } else {
            format!("guest rebooted (firmware boot #{new} seen on serial)")
        }
    })
}

/// Fatal serial signature check (see [`fatal_boot_patterns`]): returns the
/// cause only — `cmd_run`'s failure arms append the evidence block (frame
/// path + serial tail + VNC) via [`boot_failure_report`].
fn check_boot_failure(serial_log: &str) -> Result<()> {
    let fatal = fatal_boot_patterns();
    let text = std::fs::read_to_string(serial_log).unwrap_or_default();
    // Only the tail matters (log persists across runs); keep the last 8 KB.
    let tail = if text.len() > 8192 {
        &text[text.len() - 8192..]
    } else {
        &text
    };
    for pat in &fatal {
        if tail.contains(pat) {
            anyhow::bail!("guest failed to boot (serial shows {pat:?})");
        }
    }
    Ok(())
}

/// Guest-activity ledger: the sole consumer of `info blockstats` plus
/// host-side disk-size samples. Answers "is the guest doing anything" so
/// the warning policy can tell a slow install (moving) from a parked one
/// (flat). Sample on every tick; judge on horizons — qcow2 grows stepwise,
/// so per-second diffs false-report static.
struct ActivityMonitor {
    last_total: u64,
    last_change: std::time::Instant,
    warned: bool,
    disk_start: Option<u64>,
    disk_last: u64,
    disk_last_change: std::time::Instant,
    last_sample: Option<std::time::Instant>,
    /// I/O bytes/s, exponential average over [`Self::EMA_WINDOW_SECS`].
    pub(crate) io_ema_bps: f64,
    /// Disk-growth bytes/s, same window.
    pub(crate) growth_ema_bps: f64,
}

impl ActivityMonitor {
    /// EMA window in seconds: bursts read as rates, not spikes.
    const EMA_WINDOW_SECS: f64 = 300.0;

    fn new() -> Self {
        let now = std::time::Instant::now();
        Self {
            last_total: 0,
            last_change: now,
            warned: false,
            disk_start: None,
            disk_last: 0,
            disk_last_change: now,
            last_sample: None,
            io_ema_bps: 0.0,
            growth_ema_bps: 0.0,
        }
    }

    /// Sum all `rd_bytes`/`wr_bytes` in HMP `info blockstats` output.
    /// Best-effort parse (unparseable → None, never fail the wait on it).
    fn parse_total(text: &str) -> Option<u64> {
        let mut total = 0u64;
        let mut found = false;
        for key in ["rd_bytes=", "wr_bytes="] {
            for part in text.split(key).skip(1) {
                let digits: String = part.chars().take_while(|c| c.is_ascii_digit()).collect();
                if let Ok(n) = digits.parse::<u64>() {
                    total = total.saturating_add(n);
                    found = true;
                }
            }
        }
        found.then_some(total)
    }

    /// One EMA step, pure: `prev` toward `inst` over `dt_secs` in a
    /// `window_secs` horizon. Unit-testable without clocks.
    fn ema_step(prev: f64, inst: f64, dt_secs: f64, window_secs: f64) -> f64 {
        if dt_secs <= 0.0 {
            return prev;
        }
        let alpha = (dt_secs / window_secs).min(1.0);
        prev + alpha * (inst - prev)
    }

    /// Feed one tick: monitor counters plus host-side disk size. Every
    /// part best-effort — an unreachable monitor or stat failure skips
    /// that signal, never the wait. `None` disk skips growth tracking
    /// (blockstats still feed the stall watchdog).
    async fn sample(&mut self, mon: &crate::ipc::Monitor, disk: Option<&Path>) {
        let now = std::time::Instant::now();
        let dt = self
            .last_sample
            .map(|t| now.duration_since(t).as_secs_f64())
            .unwrap_or(0.0);
        self.last_sample = Some(now);
        let text = mon.command("info blockstats").await.unwrap_or_default();
        if let Some(total) = Self::parse_total(&text) {
            // Unconditional on movement: a flat interval feeds inst 0.0 so
            // the average decays toward zero instead of freezing at its
            // last active rate for hours on an idle guest.
            if dt > 0.0 {
                let inst = total.saturating_sub(self.last_total) as f64 / dt;
                self.io_ema_bps = Self::ema_step(self.io_ema_bps, inst, dt, Self::EMA_WINDOW_SECS);
            }
            if total != self.last_total {
                self.last_total = total;
                self.last_change = now;
                self.warned = false;
            }
        }
        if let Some(disk) = disk
            && let Ok(size) = std::fs::metadata(disk).map(|m| m.len())
        {
            if self.disk_start.is_none() {
                // First sample arms the baseline without tripping motion:
                // a pre-existing disk is not growth.
                self.disk_start = Some(size);
                self.disk_last = size;
                self.disk_last_change = now;
            } else if dt > 0.0 {
                let inst = size.saturating_sub(self.disk_last) as f64 / dt;
                self.growth_ema_bps =
                    Self::ema_step(self.growth_ema_bps, inst, dt, Self::EMA_WINDOW_SECS);
                // Growth timer advances only on real growth; the average
                // still decays through the zero inst above.
                if size != self.disk_last {
                    self.disk_last_change = now;
                }
                self.disk_last = size;
            }
        }
    }

    /// Seconds since block I/O last moved.
    fn idle_secs(&self) -> u64 {
        self.last_change.elapsed().as_secs()
    }

    /// Seconds since the disk image last grew.
    fn disk_idle_secs(&self) -> u64 {
        self.disk_last_change.elapsed().as_secs()
    }

    /// Bytes the disk image grew since the first sample (saturating).
    fn growth_since_start(&self) -> u64 {
        self.disk_start
            .map(|s| self.disk_last.saturating_sub(s))
            .unwrap_or(0)
    }

    /// Moving right now: any I/O inside the warn horizon.
    fn is_moving(&self) -> bool {
        self.idle_secs() < timeouts::IDLE_WARN_SECS
    }

    /// Stall watchdog, conditioned on screen state: frozen disk I/O during
    /// valid progress (Setup applying, OOBE, boot art, idle desktop) is a
    /// slow host, never a stuck guest — progress answers only to the
    /// operator. The bail fires solely on the conjunction: a non-progress
    /// screen (error states, Dark, FlatField) AND ceased block I/O AND a
    /// disk that stopped growing. `None` state (no frame yet) takes the
    /// strict path: nothing rendered is itself evidence of stuck.
    /// `fatal` decides the teeth: the run boot wait bails (a dead boot
    /// has its own SSH deadline anyway), the install path only ever warns
    /// — nothing but the operator halts an install. `Err` on bail so
    /// fatal callers `?` straight out.
    fn check_stall(&mut self, state: Option<ScreenState>, fatal: bool) -> Result<()> {
        let progress = matches!(
            state,
            Some(
                ScreenState::InstallerStep
                    | ScreenState::OobeStep
                    | ScreenState::FirmwareBoot
                    | ScreenState::Lockscreen
            )
        );
        if progress {
            // Slow host, not stuck guest: reset the warn latch so a later
            // genuine stall still warns, and return without judging.
            self.warned = false;
            return Ok(());
        }
        let idle = self.idle_secs();
        let disk_idle = self.disk_idle_secs();
        if idle >= timeouts::IDLE_BAIL_SECS && disk_idle >= timeouts::IDLE_BAIL_SECS {
            if !fatal {
                // Install path: say so loudly, keep waiting. Only the
                // operator halts an install. Warn every time past bail
                // (not warn-once): a stall that persists for hours should
                // stay visible, and nothing else will say it.
                eprintln!(
                    "warning: no disk I/O for {idle}s, disk static for {disk_idle}s and no SSH — guest may be parked at an input screen (Ctrl-C stops the install, nothing else does)"
                );
                return Ok(());
            }
            // Cause only; failure arms append frame + serial + VNC.
            anyhow::bail!(
                "guest appears stuck: no disk I/O for {idle}s, disk static for {disk_idle}s and no SSH — likely parked at an input screen (recovery, EULA)"
            );
        }
        if idle >= timeouts::IDLE_WARN_SECS && !self.warned {
            self.warned = true;
            // Never name an input screen without seeing one: the SSH-probe
            // loop calls with no frame (None), while the sampler task may
            // concurrently report progress. A blind loop claiming a parked
            // input screen next to an installer-progress line is the exact
            // contradiction that erodes trust in every other warning.
            if state.is_none() {
                eprintln!("warning: no disk I/O for {idle}s and no SSH banner yet — still waiting");
            } else {
                eprintln!(
                    "warning: no disk I/O for {idle}s and no SSH yet — guest may be stuck at an input screen"
                );
            }
        }
        Ok(())
    }
}

/// Time-lapse dir name under the VM dir, and frame filename prefix.
/// Single source: screenshots_dir() builds the path, take_screenshot names files.
pub const SCREENSHOTS_DIR: &str = "screenshots";

fn screenshots_dir(vm_dir: &Path) -> PathBuf {
    vm_dir.join(SCREENSHOTS_DIR)
}

/// Monitor command setting the VNC password. Single source so the run
/// and install paths cannot drift (or typo) apart again.
fn vnc_password_command() -> String {
    format!("change vnc password {PROVEN_VNC_PASSWORD}")
}

/// Evidence block for a failed boot wait: final frame (path + screen
/// classification), last serial line, activity evidence, VNC coordinates.
/// Pure formatter so the layout is unit-testable; [`boot_failure_report`]
/// gathers the parts.
fn format_failure_report(
    frame: Option<(PathBuf, ScreenState)>,
    serial: &str,
    boots: u64,
    activity: Option<(u64, u64)>,
    vnc: &Option<String>,
) -> String {
    let mut out = match frame {
        Some((p, s)) => format!("boot diagnosis: {s} — {}", p.display()),
        None => "boot diagnosis: no screenshot could be captured".to_string(),
    };
    if !serial.is_empty() {
        out.push_str(&format!("\n  last serial: {serial}"));
    }
    out.push_str(&format!("\n  guest boots seen: {boots}"));
    if let Some((idle_secs, growth)) = activity {
        out.push_str(&format!(
            "\n  guest activity: no I/O for {idle_secs}s, disk +{}",
            fmt_bytes(growth)
        ));
    }
    if let Some(u) = vnc {
        out.push_str(&format!("\n  vnc: {u} (password {PROVEN_VNC_PASSWORD})"));
    }
    out
}

/// Gather the evidence for [`format_failure_report`]: one final frame off
/// the live monitor (the serial is silent through a Windows boot, so the
/// screen is the primary witness), the last meaningful serial line, one
/// activity sample, and the caller's VNC coordinates. Every part is
/// best-effort — a missing piece is stated, never invented.
async fn boot_failure_report(
    mon: &crate::ipc::Monitor,
    serial_log: &str,
    shots_dir: &Path,
    vnc: &Option<String>,
) -> String {
    let frame = take_screenshot(mon, shots_dir)
        .await
        .map(|(p, s, _)| (p, s));
    let serial = last_serial_line(serial_log);
    let mut activity_mon = ActivityMonitor::new();
    let disk = shots_dir.parent().map(|d| d.join(crate::paths::DISK_IMAGE));
    activity_mon.sample(mon, disk.as_deref()).await;
    let activity = Some((activity_mon.idle_secs(), activity_mon.growth_since_start()));
    format_failure_report(frame, &serial, boot_count(serial_log), activity, vnc)
}

/// Background time-lapse: ticks on the profile until aborted. Returns the
/// join handle (`None` when every cadence is off); callers `.abort()` it
/// when the wait ends.
fn spawn_sampler(
    mon: std::sync::Arc<crate::ipc::Monitor>,
    screenshots_dir: PathBuf,
    disk: PathBuf,
    profile: SamplingProfile,
    label: &'static str,
) -> Option<tokio::task::JoinHandle<()>> {
    let tick = profile.tick()?;
    Some(tokio::spawn(async move {
        // First frame immediately (proves the display is alive early),
        // then on cadence. Numbered, basename-only (the dir was announced
        // once above), so the log reads as progress toward the SSH answer.
        let mut sampler = ScreenSampler::new(mon, screenshots_dir);
        let mut activity = ActivityMonitor::new();
        sampler.poll(&profile).await;
        report_sample(label, &sampler, &activity);
        let mut ticker = tokio::time::interval(tick);
        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        ticker.tick().await; // skip the immediate tick
        loop {
            ticker.tick().await;
            activity.sample(&sampler.mon, Some(disk.as_path())).await;
            sampler.poll(&profile).await;
            // Stall check after the fresh classification: frozen I/O
            // during valid progress is a slow host, never a stuck guest.
            // Warn-only by construction (fatal=false never errs): no
            // screen, state, or activity reading exits this loop early.
            // The task ends solely on abort (victory) or cancellation.
            activity.check_stall(sampler.state(), false).ok();
            report_sample(label, &sampler, &activity);
        }
    }))
}

/// One scrollback-safe status line per tick: the whole instrument panel.
/// Nothing prints for [`SampleOutcome::Skipped`].
fn report_sample(label: &str, sampler: &ScreenSampler, activity: &ActivityMonitor) {
    let (noun, n, state, margin, file) = match &sampler.last_outcome {
        SampleOutcome::Saved(p, s, m) => (
            "screenshot",
            sampler.shot_n,
            *s,
            *m,
            p.file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned(),
        ),
        // Status lines carry wall-clock runtime, not a counter: on a
        // 3-hour install "status 412" says nothing, "2h41m" says where.
        SampleOutcome::Classified(s, m) => (
            "status",
            sampler.started.elapsed().as_secs(),
            *s,
            *m,
            String::new(),
        ),
        SampleOutcome::Skipped => return,
    };
    // Error reads warn only under the activity conjunction (flat guest);
    // a moving guest with an error read is a transient misread or live
    // recovery, and logs as observation, never alarm.
    let warn = if is_error_state(state) && !activity.is_moving() {
        "WARNING: "
    } else {
        ""
    };
    let file_part = if file.is_empty() {
        String::new()
    } else {
        format!("{file} ")
    };
    // Disk growth reads with its own age: a disk that stopped growing
    // long ago while I/O still trickles is a different shape than both
    // moving together.
    let disk_part = if activity.disk_idle_secs() >= timeouts::IDLE_WARN_SECS {
        format!(
            "disk +{} (static {})",
            fmt_bytes(activity.growth_since_start()),
            fmt_secs(activity.disk_idle_secs())
        )
    } else {
        format!("disk +{}", fmt_bytes(activity.growth_since_start()))
    };
    eprintln!(
        "{warn}{label} {noun} {}: {file_part}{} (phase {}, static {}, io {}/s avg, {disk_part}, io-idle {})",
        if noun == "status" {
            fmt_secs(n)
        } else {
            n.to_string()
        },
        describe(state, margin),
        fmt_secs(sampler.phase_secs()),
        fmt_secs(sampler.static_secs()),
        fmt_bytes(activity.io_ema_bps as u64),
        fmt_secs(activity.idle_secs()),
    );
}

/// Tri-state banner probe: distinguishes a closed port (nothing
/// listening — sshd not started) from an open-but-silent one (TCP
/// accepted, no SSH banner — sshd starting, or something else holding
/// the port). The wait loops log transitions; a long silence that moves
/// Closed→Silent is progress, not a stall.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BannerProbe {
    Banner,
    /// Accepted, no bytes (timeout or clean EOF): listener present,
    /// banner not out yet.
    OpenSilent,
    /// Accepted, but the bytes are not SSH: wrong daemon, port squat,
    /// or corrupt transmission — never "sshd starting".
    Unexpected,
    Closed,
}

async fn probe_banner(port: u16) -> (BannerProbe, Option<String>) {
    use tokio::io::AsyncReadExt;
    let stream = match tokio::time::timeout(
        timeouts::SSH_BANNER_CONNECT_BUDGET,
        tokio::net::TcpStream::connect((PROVEN_SSH_HOST, port)),
    )
    .await
    {
        Ok(Ok(s)) => s,
        _ => return (BannerProbe::Closed, None),
    };
    let mut buf = [0u8; 256];
    let mut stream = stream;
    match tokio::time::timeout(timeouts::SSH_BANNER_READ_BUDGET, stream.read(&mut buf)).await {
        Ok(Ok(n)) if n > 0 => {
            let b = String::from_utf8_lossy(&buf[..n]);
            if b.starts_with("SSH-") {
                (BannerProbe::Banner, Some(b.trim().to_string()))
            } else {
                (BannerProbe::Unexpected, None)
            }
        }
        // Accepted but silent: starting, not absent.
        _ => (BannerProbe::OpenSilent, None),
    }
}

/// One banner read ([`timeouts::SSH_BANNER_CONNECT_BUDGET`] +
/// [`timeouts::SSH_BANNER_READ_BUDGET`]). `None` = no sshd right now.
async fn banner_once(port: u16) -> Option<String> {
    probe_banner(port).await.1
}

/// Guest readiness: banner phases for display, registry probe for truth.
/// The FIRST banner only means Setup reached a boot with SSH up — Windows
/// then typically reboots into further passes. Victory is declared when
/// the guest itself reports Setup done (no OOBE in progress, no reboot
/// pending), not after any fixed time window. Returns the banner (for the
/// `tested-isos.jsonl` record).
///
/// Always probes with the default password (the media is always built with
/// it — Setup rejects weak ones mid-install). A custom `password` is
/// rotated in after READY, before the ready line, via
/// `change_guest_password` (which verifies the new login). The custom
/// password never touches the answer file.
/// Shared observability for the install/boot waits: the one monitor
/// session plus the paths it watches. Bundled so the wait fns don't
/// sprawl argument lists (clippy limit is 7). `vnc` is the report
/// coordinate (None for gtk/cocoa/none displays).
#[derive(Clone)]
struct GuestScope {
    mon: std::sync::Arc<crate::ipc::Monitor>,
    shots_dir: PathBuf,
    serial_log: String,
    vnc: Option<String>,
}

async fn wait_install_ready(
    port: u16,
    deadline: Duration,
    user: &str,
    password: &str,
    recovery: bool,
    auto_updates: bool,
    scope: &GuestScope,
) -> Result<String> {
    use crate::ssh::{GuestProgress, probe_setup_done};
    use crate::unattend::DEFAULT_PASSWORD;
    let start = std::time::Instant::now();
    // Phase 1: first banner.
    let mut activity = ActivityMonitor::new();
    // Disk beside the screenshots dir feeds growth tracking (`shots_dir`
    // is `<vm>/screenshots`, so its parent is the VM dir).
    let disk = scope
        .shots_dir
        .parent()
        .map(|d| d.join(crate::paths::DISK_IMAGE));
    // Reboot awareness while Setup applies (no SSH yet — serial is the
    // only below-screenshot voice): count OVMF firmware handoffs.
    let mut boots_seen = boot_count(&scope.serial_log);
    // The install never times out on its own: only the operator stops it
    // (Ctrl-C). Past the deadline the loop says so loudly and keeps
    // waiting — a slow host is not a failed install.
    let mut deadline_warned = false;
    // Miss-reason tracking: a silence that moves closed→silent is sshd
    // stirring (progress); log transitions, never pollute per tick. None
    // until the first probe, so tick 1 always announces the baseline.
    let mut probe_state: Option<BannerProbe> = None;
    let banner = loop {
        if start.elapsed() > deadline && !deadline_warned {
            deadline_warned = true;
            eprintln!(
                "still no SSH banner on {PROVEN_SSH_HOST}:{port} after {} s — still waiting (Ctrl-C stops the install, nothing else does)",
                deadline.as_secs()
            );
        }
        match probe_banner(port).await {
            (BannerProbe::Banner, Some(b)) => {
                eprintln!(
                    "guest SSH is up (first contact) — Setup is still installing Windows, not ready yet ({b})"
                );
                break b;
            }
            (state, _) => {
                if Some(state) != probe_state {
                    probe_state = Some(state);
                    match state {
                        BannerProbe::Closed => eprintln!(
                            "ssh port {port} closed (sshd not started yet) — still waiting"
                        ),
                        BannerProbe::OpenSilent => eprintln!(
                            "ssh port {port} open but silent (sshd starting?) — still waiting"
                        ),
                        BannerProbe::Unexpected => eprintln!(
                            "ssh port {port} answered but not with SSH (wrong daemon or port squat?) — still waiting"
                        ),
                        BannerProbe::Banner => {}
                    }
                }
            }
        }
        // Dead-screen watchdog (same as run): fail fast with evidence.
        check_boot_failure(&scope.serial_log)?;
        // Reboot narration: Setup reboots between passes; announce each
        // firmware bounce instead of leaving the long wait mute.
        let boots = boot_count(&scope.serial_log);
        if let Some(note) = boot_note(boots_seen, boots) {
            eprintln!("{note}");
        }
        boots_seen = boots;
        // Stall watchdog: frozen disk I/O + no banner = parked. No screen
        // state down here (SSH probing, not frame watching), so take the
        // strict path — same as a boot that never rendered. Warn-only:
        // nothing but the operator halts an install.
        activity.sample(&scope.mon, disk.as_deref()).await;
        activity.check_stall(None, false)?;
        tokio::time::sleep(timeouts::SSH_POLL_INTERVAL).await;
    };
    // Phase 2: ask the guest until it reports done. Banner loss between
    // probes means a reboot (reported); probe errors mean sshd is
    // mid-restart (retried, not fatal). Each probe gets a hard budget: a
    // stalled handshake mid-reboot must surface, never hang the loop.
    // Separate counter for the overloaded state: banner stable but every
    // exec timing out means the guest is too saturated to cold-start
    // PowerShell (Setup still applying), not rebooting. Hammering it with
    // a probe every 10 s only stacks more powershell.exe on the pile, so
    // the cadence backs off while stalled.
    //
    // Narration policy: transient states print once per *change* (reboot,
    // new pending phase) plus a slow heartbeat — never one line per probe.
    // Default output is progress; words like "failed"/"ERROR" are reserved
    // for things that are actually wrong (raw errors: RUST_LOG=debug).
    let mut reboots = 0u32;
    let mut was_up = true;
    let mut exec_stalls = 0u32;
    // Last pending-state line printed, and when the heartbeat last fired.
    let mut phase: Option<String> = None;
    let mut last_beat = start;
    // Same operator-only rule as phase 1: the install never times out on
    // its own. Past the deadline the loop says so loudly and keeps
    // probing — a slow host is not a failed install.
    let mut deadline_warned = false;
    loop {
        if start.elapsed() > deadline && !deadline_warned {
            deadline_warned = true;
            eprintln!(
                "still waiting for guest readiness on {PROVEN_SSH_HOST}:{port} after {} s — still probing (Ctrl-C stops the install, nothing else does)",
                deadline.as_secs()
            );
        }
        // The probe itself gets a hard budget: a stalled handshake
        // mid-reboot would otherwise hang the loop silently (observed as
        // "long polling, never noticing SSH is up"). Timeout = not yet.
        match tokio::time::timeout(
            timeouts::READINESS_PROBE_BUDGET,
            probe_setup_done(PROVEN_SSH_HOST, port, user, DEFAULT_PASSWORD),
        )
        .await
        {
            Ok(Ok(GuestProgress::Ready)) => {
                if password != DEFAULT_PASSWORD {
                    eprintln!("rotating guest password ...");
                    crate::ssh::change_guest_password(
                        PROVEN_SSH_HOST,
                        port,
                        user,
                        DEFAULT_PASSWORD,
                        password,
                    )
                    .await?;
                }
                // Recovery policy (default off, docker-like): a damaged disk
                // fails fast instead of parking at "Diagnosing your PC".
                // Specialize already set the off state on the first OS boot
                // (an early Ctrl-C is covered there); this step applies the
                // flag's end state as the credential (post-rotation) —
                // `--recovery` re-arms both switches.
                if let Err(e) = crate::ssh::set_recovery_enabled(
                    PROVEN_SSH_HOST,
                    port,
                    user,
                    password,
                    recovery,
                )
                .await
                {
                    eprintln!("warning: bcdedit failed ({e:#}); recovery state unchanged");
                }
                // Update policy (default off, docker-like): wuauserv runs as
                // SYSTEM and would otherwise reboot the box on Microsoft's
                // schedule with no logon. Disabled = deterministic; manual
                // updates over SSH still work anytime.
                if !auto_updates
                    && let Err(e) =
                        crate::ssh::set_auto_updates(PROVEN_SSH_HOST, port, user, password, false)
                            .await
                {
                    eprintln!("warning: wuauserv disable failed ({e:#})");
                }
                // Headless diet (was specialize orders; moved post-READY so
                // four PowerShell cold starts stop serializing into Setup):
                // NLA Private + service trim in one invocation, best-effort.
                if let Err(e) =
                    crate::ssh::apply_headless_diet(PROVEN_SSH_HOST, port, user, password).await
                {
                    eprintln!("warning: headless diet failed ({e:#})");
                }
                eprintln!(
                    "guest reports Setup complete across {reboots} reboot(s) — install complete"
                );
                return Ok(banner);
            }
            Ok(Ok(GuestProgress::Busy(what))) => {
                exec_stalls = 0;
                if phase.as_deref() == Some(what.as_str()) {
                    // Unchanged since the last probe: stay quiet unless the
                    // heartbeat is due (proof of life on a long install).
                    if last_beat.elapsed() >= timeouts::PROGRESS_HEARTBEAT {
                        last_beat = std::time::Instant::now();
                        eprintln!(
                            "still installing: {what} — {}s elapsed, {reboots} reboot(s) so far",
                            start.elapsed().as_secs()
                        );
                    }
                } else {
                    eprintln!("still installing: {what}");
                    phase = Some(what);
                    last_beat = std::time::Instant::now();
                }
            }
            Ok(Err(e)) => {
                exec_stalls += 1;
                if e.downcast_ref::<crate::ssh::ProbeOutputBroken>().is_some() {
                    // OUR probe broke, not the guest: never narrate that as a
                    // reboot. Rare but real, so it stays at the default level.
                    if exec_stalls == 1 || exec_stalls == 5 {
                        eprintln!(
                            "warning: readiness probe could not read the guest's reply ({e:#}) — probe/output problem, not a reboot; retrying ..."
                        );
                    }
                } else if exec_stalls == 1 {
                    // Expected while Setup reboots: sshd restarts with the
                    // guest. One calm line per stall run; the raw transport
                    // error goes to RUST_LOG=debug instead of reading as a
                    // failure.
                    eprintln!(
                        "waiting: SSH dropped — Windows is rebooting as part of Setup, retrying ..."
                    );
                    tracing::debug!("probe error: {e:#}");
                } else if exec_stalls == 5 {
                    // Five straight exec failures with the banner up is not a
                    // reboot (the banner would drop) — it is saturation.
                    eprintln!(
                        "exec stalled 5x with SSH stable — guest is overloaded (Setup still applying), not rebooting; backing off probes ..."
                    );
                }
            }
            Err(_) => {
                exec_stalls += 1;
                if exec_stalls == 1 {
                    eprintln!(
                        "waiting: probe timed out — guest is busy (Setup still applying), retrying ..."
                    );
                } else if exec_stalls == 5 {
                    eprintln!(
                        "probe timed out 5x with SSH stable — guest is overloaded, backing off probes ..."
                    );
                }
            }
        }
        let up = banner_once(port).await.is_some();
        match (was_up, up) {
            (true, false) => {
                eprintln!(
                    "Windows is rebooting (#{}) — SSH dropped, waiting for it to return ...",
                    reboots + 1
                );
            }
            (false, true) => {
                reboots += 1;
                exec_stalls = 0;
                eprintln!("SSH back (reboot #{reboots} finished) — resuming probes ...");
            }
            _ => {}
        }
        was_up = up;
        // Back off while stalled (10 s → up to 60 s): each probe spawns a
        // PowerShell cold start, and hammering a saturated guest buries it.
        let backoff = 1 + (exec_stalls / 5).min(5);
        tokio::time::sleep(timeouts::READINESS_PROBE_INTERVAL * backoff).await;
    }
}

/// Ctrl-C and SIGTERM both mean "stop the VM". Signals don't unwind, so
/// without this a SIGTERM'd CLI would orphan QEMU despite `kill_on_drop`.
#[cfg(unix)]
async fn shutdown_signal() {
    use tokio::signal::unix::{SignalKind, signal};
    let mut term = signal(SignalKind::terminate()).expect("SIGTERM handler");
    tokio::select! {
        _ = tokio::signal::ctrl_c() => {},
        _ = term.recv() => {},
    }
}

#[cfg(not(unix))]
async fn shutdown_signal() {
    let _ = tokio::signal::ctrl_c().await;
}

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

    fn install_fixture(memory_mb: u32, cpus: u32) -> (Vec<String>, Vec<String>) {
        let dir = std::env::temp_dir();
        let code = dir.join("code.fd");
        let vars = dir.join("vars.fd");
        let usb = dir.join("usb.dmg");
        let spec = InstallQemuArgv {
            machine: "virt",
            accel: "tcg",
            cpu: "max",
            memory_mb,
            cpus,
            display: Display::Vnc("vnc=127.0.0.1:10,password=on".to_string()),
            code_tpl: &code,
            vars_fd: &vars,
            serial_log: "serial.log",
            mon_sock: "mon.sock",
            qmp_sock: "qmp.sock",
            usb_image: &usb,
            target: "disk.qcow2",
            arch: Architecture::Arm64,
        };
        (
            install_qemu_argv(&spec),
            qemu_img_create_args("disk.qcow2", 128),
        )
    }

    #[test]
    fn install_sizing_reaches_qemu_argv() {
        // The flags a user passes must be the bytes QEMU gets: no QEMU
        // needed, just the pure argv constructors.
        // Golden sidecar lives next to the disk it blesses.
        assert_eq!(
            golden_sidecar("disk.qcow2"),
            std::path::PathBuf::from("disk.qcow2.golden")
        );
        let (argv, img) = install_fixture(8192, 8);
        let at = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
        assert_eq!(at("-m"), "8192");
        assert_eq!(at("-smp"), "8");
        assert_eq!(img.last().unwrap(), "128G");
        // Defaults stay proven-shaped.
        let (argv, img) = install_fixture(4096, 4);
        let at = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
        assert_eq!(at("-m"), "4096");
        assert_eq!(at("-smp"), "4");
        assert_eq!(at("-display"), "vnc=127.0.0.1:10,password=on");
        let img64 = qemu_img_create_args("disk.qcow2", 64);
        assert_eq!(img64.last().unwrap(), "64G");
        assert_eq!(img[..5], img64[..5]);
    }

    #[test]
    fn live_migration_uris_quote_paths() {
        // NIC name comes from `info network`, never guessed: first
        // type=nic entry wins, netdev/user lines are skipped.
        let info = "virtio-net-pci.0: index=0,type=nic,model=virtio-net-pci,macaddr=52:54:00:12:34:56\n \\ n1: index=0,type=user,net=10.0.2.0/24,hostfwd=tcp::2232-:22\n";
        assert_eq!(find_nic_name(info), Some("virtio-net-pci.0"));
        assert_eq!(find_nic_name("n1: index=0,type=user\n"), None);
        assert_eq!(find_nic_name("garbage\n"), None);
        // Migration URIs quote paths (cache dirs contain spaces) and the
        // live companions live next to the disk they belong to.
        let spaced = std::path::Path::new("/Volumes/2TB Storage Vault/vm/golden-live.state");
        assert_eq!(
            migrate_write_uri(spaced),
            "exec:cat > '/Volumes/2TB Storage Vault/vm/golden-live.state'"
        );
        assert_eq!(
            migrate_read_uri(spaced),
            "exec:cat '/Volumes/2TB Storage Vault/vm/golden-live.state'"
        );
        let quoted = std::path::Path::new("/tmp/o'brien/state");
        assert_eq!(
            migrate_write_uri(quoted),
            "exec:cat > '/tmp/o'\\''brien/state'"
        );
        let dir = std::path::Path::new("/tmp/vm");
        let (state, vars, overlay) = live_paths(dir);
        assert_eq!(state, dir.join(crate::paths::LIVE_STATE_FILE));
        assert_eq!(vars, dir.join(crate::paths::LIVE_VARS_BACKUP));
        assert_eq!(overlay, dir.join(crate::paths::LIVE_OVERLAY));
    }

    #[test]
    fn install_cocoa_display_passes_through() {
        // Non-VNC displays reach QEMU verbatim (the VNC password step is
        // guarded separately); cocoa installs show a window instead.
        let dir = std::env::temp_dir();
        let code = dir.join("code.fd");
        let vars = dir.join("vars.fd");
        let usb = dir.join("usb.dmg");
        let spec = InstallQemuArgv {
            machine: "virt",
            accel: "tcg",
            cpu: "max",
            memory_mb: 4096,
            cpus: 4,
            display: Display::Cocoa,
            code_tpl: &code,
            vars_fd: &vars,
            serial_log: "serial.log",
            mon_sock: "mon.sock",
            qmp_sock: "qmp.sock",
            usb_image: &usb,
            target: "disk.qcow2",
            arch: Architecture::Arm64,
        };
        let argv = install_qemu_argv(&spec);
        let at = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
        assert_eq!(at("-display"), "cocoa");
    }

    #[test]
    fn blockstats_parse_totals() {
        let sample = "drive-tgt: rd_bytes=1048576 wr_bytes=524288 rd_operations=12\n\
                      drive-usb: rd_bytes=100 wr_bytes=0\n";
        assert_eq!(
            ActivityMonitor::parse_total(sample),
            Some(1048576 + 524288 + 100)
        );
        assert_eq!(ActivityMonitor::parse_total(""), None);
    }

    #[test]
    fn activity_math_without_qemu() {
        // Pure derivations on hand-built state: no monitor, no sleeps.
        let now = std::time::Instant::now();
        let mut m = ActivityMonitor {
            last_total: 1000,
            last_change: now - Duration::from_secs(61),
            warned: false,
            disk_start: Some(100),
            disk_last: 150,
            disk_last_change: now - Duration::from_secs(61),
            last_sample: Some(now),
            io_ema_bps: 0.0,
            growth_ema_bps: 0.0,
        };
        assert_eq!(m.idle_secs(), 61);
        assert_eq!(m.disk_idle_secs(), 61);
        assert_eq!(m.growth_since_start(), 50);
        assert!(!m.is_moving());
        // EMA: half-window step moves halfway to the instant rate.
        assert_eq!(ActivityMonitor::ema_step(0.0, 100.0, 150.0, 300.0), 50.0);
        assert_eq!(ActivityMonitor::ema_step(50.0, 100.0, 0.0, 300.0), 50.0);
        // Fresh activity resets the idle clock.
        m.last_change = std::time::Instant::now();
        assert!(m.is_moving());
    }

    #[test]
    fn stall_watchdog_needs_non_progress_and_flat_guest() {
        // Progress states never bail, however long I/O has been flat: a
        // slow host applying the image answers only to the operator, not
        // the stall watchdog (live 2026-10-07: 120s of CPU-bound setup
        // with InstallerStep on screen aborted a valid install).
        let mut m = ActivityMonitor {
            last_total: 1000,
            last_change: std::time::Instant::now() - Duration::from_secs(10_000),
            warned: false,
            disk_start: Some(100),
            disk_last: 100,
            disk_last_change: std::time::Instant::now() - Duration::from_secs(10_000),
            last_sample: None,
            io_ema_bps: 0.0,
            growth_ema_bps: 0.0,
        };
        for state in [
            ScreenState::InstallerStep,
            ScreenState::OobeStep,
            ScreenState::FirmwareBoot,
            ScreenState::Lockscreen,
        ] {
            assert!(m.check_stall(Some(state), true).is_ok(), "{state:?}");
        }
        // Non-progress + flat on both signals bails when fatal.
        assert!(m.check_stall(Some(ScreenState::ErrorScreen), true).is_err());
        assert!(m.check_stall(Some(ScreenState::Dark), true).is_err());
        // No frame yet: strict path, bails like a boot that never rendered.
        assert!(m.check_stall(None, true).is_err());
        // Flat I/O but a growing disk is not parked: bail needs both.
        m.disk_last_change = std::time::Instant::now();
        m.disk_last = 200;
        assert!(m.check_stall(Some(ScreenState::ErrorScreen), true).is_ok());
        // Install path is warn-only: the same flat guest that bails above
        // only warns when fatal is false — nothing but the operator halts
        // an install.
        m.disk_last_change = std::time::Instant::now() - Duration::from_secs(10_000);
        m.disk_last = 100;
        assert!(m.check_stall(Some(ScreenState::ErrorScreen), false).is_ok());
        assert!(m.check_stall(None, false).is_ok());
    }

    #[test]
    fn tilde_expands_to_home() {
        let home = std::env::var("HOME").unwrap();
        assert_eq!(
            expand_tilde("~/x.iso".into()),
            PathBuf::from(home.clone()).join("x.iso")
        );
        assert_eq!(expand_tilde("~".into()), PathBuf::from(home));
        // Untouched: relative, absolute, other users.
        assert_eq!(expand_tilde("rel/x.iso".into()), PathBuf::from("rel/x.iso"));
        assert_eq!(
            expand_tilde("/abs/x.iso".into()),
            PathBuf::from("/abs/x.iso")
        );
        assert_eq!(
            expand_tilde("~other/x.iso".into()),
            PathBuf::from("~other/x.iso")
        );
    }

    #[test]
    fn missing_iso_error_names_the_path_it_tried() {
        let tmp = tempfile::tempdir().unwrap();
        let present = tmp.path().join("present.iso");
        std::fs::write(&present, b"x").unwrap();
        assert!(require_win_iso(&present).is_ok());
        // A directory is not an ISO.
        assert!(require_win_iso(tmp.path()).is_err());

        let missing = tmp.path().join("Win11.iso");
        let err = require_win_iso(&missing).unwrap_err().to_string();
        assert!(err.contains(&missing.display().to_string()), "{err}");
        assert!(!err.contains("quote-shielded"), "{err}");
        assert!(!err.contains("unquoted"), "{err}");

        // A literal `~` survives expand_tilde only when $HOME is unset (or
        // the path is ~otheruser) — the hint must say that, not "quote it".
        let err = require_win_iso(Path::new("~/Win11.iso"))
            .unwrap_err()
            .to_string();
        assert!(err.contains("$HOME"), "{err}");
        let err = require_win_iso(Path::new("~other/x.iso"))
            .unwrap_err()
            .to_string();
        assert!(err.contains("~otheruser"), "{err}");
    }

    #[test]
    fn report_renders_table() {
        use crate::provenance::{DependencyPins, GuestParams, HostSpecs, IsoIdentity, Provenance};
        let record = crate::provenance::TestRecord {
            tested_at_epoch: 1_758_600_000,
            outcome: "ssh-banner".to_string(),
            ssh_banner: Some("SSH-2.0-test".to_string()),
            provenance: Provenance {
                builder_version: "0.1.0".to_string(),
                build_commit: "abcdef1234567".to_string(),
                build_dirty: true,
                built_at_epoch: 1_758_600_000,
                source_iso: IsoIdentity {
                    file_name: "Win11.iso".to_string(),
                    size_bytes: 1,
                    sha256: "x".to_string(),
                    pvd_creation: None,
                    wim_images: vec![],
                },
                host: HostSpecs {
                    os: "macos".to_string(),
                    os_version: "26.0".to_string(),
                    arch: "aarch64".to_string(),
                },
                deps: DependencyPins {
                    qemu_tag: "qemu-v11.1.1".to_string(),
                    wimlib_tag: "wimlib-v1.14.5-27".to_string(),
                    virtio_iso_name: "virtio-win.iso".to_string(),
                    virtio_sha256: None,
                    openssh_zip_name: "OpenSSH-ARM64.zip".to_string(),
                    openssh_release_tag: "t".to_string(),
                },
                guest: GuestParams {
                    arch: "arm64".to_string(),
                    username: "u".to_string(),
                    locale: "en-US".to_string(),
                    accel: "tcg".to_string(),
                },
            },
        };
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("tested-isos.jsonl");
        std::fs::write(&log, serde_json::to_string(&record).unwrap() + "\n").unwrap();
        let table = render_report(&log).unwrap();
        assert!(table.contains("| Date | ISO |"), "{table}");
        assert!(table.contains("Win11.iso"), "{table}");
        assert!(table.contains("abcdef1*"), "{table}");
        // No virtio hash in the fixture → falls back to the ISO name.
        assert!(table.contains("virtio-win.iso"), "{table}");
        assert_eq!(epoch_to_date(1_758_600_000), "2025-09-23");
    }

    // --- boot failure screen classification -------------------------------

    #[test]
    fn boot_count_and_note_from_serial() {
        let path = std::env::temp_dir().join(format!("wh-boot-count-{}.log", std::process::id()));
        std::fs::write(
            &path,
            "BdsDxe: loading Boot0001 \"USB\"\n\
             BdsDxe: starting Boot0001 \"USB\"\n\
             BdsDxe: failed to load Boot0002 \"NVMe\": Not Found\n\
             BdsDxe: starting Boot0003 \"Windows Boot Manager\"\n",
        )
        .unwrap();
        assert_eq!(boot_count(path.to_str().unwrap()), 2);
        let _ = std::fs::remove_file(&path);
        assert_eq!(boot_count("/nonexistent/wh-no-serial.log"), 0);
        // Narration: first boot, reboots, flat, and regressions.
        assert_eq!(boot_note(0, 0), None);
        assert_eq!(
            boot_note(0, 1).as_deref(),
            Some("guest booted (first firmware boot)")
        );
        assert_eq!(
            boot_note(1, 3).as_deref(),
            Some("guest rebooted (firmware boot #3 seen on serial)")
        );
        assert_eq!(boot_note(3, 3), None);
        assert_eq!(boot_note(3, 2), None);
    }

    #[test]
    fn screen_state_real_frames_classify_by_directory() {
        // Integration over real screendumps through the k-NN classifier.
        // The class directory IS the label: drop a capture in, rebuild
        // the index, and both this test and the runtime pick it up with
        // no filename list anywhere.
        // Layout: tests/fixtures/<windows-version>/<class-dir>/*.png.
        //
        // Verdicts are snapshotted, not asserted at 100%: the corpus
        // holds known-unlearnable twin pairs, so exact-fit is demanded
        // nowhere. A changed verdict fails with a diff; bless it with
        // `cargo insta review` (or `INSTA_UPDATE=always` as the
        // auto-accept escape hatch).
        // Single dir→label map: a new class dir touches one arm, never two.
        let target_for_class = |class: &str| match class {
            "dark" => ScreenState::Dark,
            "flat-field" => ScreenState::FlatField,
            "error-shell" => ScreenState::ErrorShell,
            "error-recovery" => ScreenState::ErrorRecovery,
            "error-bluescreen" | "error-modal" => ScreenState::ErrorScreen,
            "oobe-step" => ScreenState::OobeStep,
            "installer-step" => ScreenState::InstallerStep,
            "firmware-boot" => ScreenState::FirmwareBoot,
            "lockscreen" => ScreenState::Lockscreen,
            // Unknown future class dirs: fail loudly here instead of
            // silently absorbing into the snapshot.
            _ => panic!("test map missing class dir: {class}"),
        };
        let root = format!("{}/tests/fixtures", env!("CARGO_MANIFEST_DIR"));
        // The shipped path, not a test-only twin: the baked artifact
        // scores here exactly as the live tick scores in production.
        let index = crate::screen_knn::bundled_index();
        let mut checked = 0;
        let mut lines = Vec::new();
        let mut misses = Vec::new();
        let mut ok_gap_sum = 0.0f64;
        let mut versions: Vec<_> = std::fs::read_dir(&root)
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        versions.sort();
        for version in versions {
            // Skip Finder noise (.DS_Store) and anything else that is
            // not a version directory.
            if !std::path::Path::new(&format!("{root}/{version}")).is_dir() {
                continue;
            }
            let mut classes: Vec<_> = std::fs::read_dir(format!("{root}/{version}"))
                .unwrap()
                .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
                .collect();
            classes.sort();
            for class in classes {
                let dir = format!("{root}/{version}/{class}");
                if !std::path::Path::new(&dir).is_dir() {
                    continue;
                }
                let mut names: Vec<_> = std::fs::read_dir(&dir)
                    .unwrap()
                    .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
                    .filter(|n| n.ends_with(".png"))
                    .collect();
                names.sort();
                for name in names {
                    let key = format!("{version}/{class}/{name}");
                    // Unknown class dirs fail loudly via the map (never
                    // silently absorbed); misses group at the bottom under
                    // their own header, so no horizontal hunt/peck. Gaps
                    // print to stdout (not the snapshot: float formatting
                    // must stay bit-exact everywhere, and the gap is a
                    // tuning signal, not a verdict). Run with
                    // `-- --nocapture` to score an index rebuild: wider
                    // gaps bless new centers, narrower ones don't.
                    let want = target_for_class(&class);
                    let (got, gap, matched) = classify_fixture(&index, &key);
                    println!("gap {gap:.4} {key} via {matched}");
                    if got == want {
                        ok_gap_sum += f64::from(gap);
                        lines.push(format!("ok   {key} => {got:?}"));
                    } else {
                        misses.push(format!(
                            "MISS {key} => got {got:?}, want {want:?} via {matched}"
                        ));
                    }
                    checked += 1;
                }
            }
        }
        assert!(checked > 0, "no fixtures found under tests/fixtures");
        let ok_count = checked - misses.len();
        let mean_ok = ok_gap_sum / f64::from(ok_count.max(1) as u32);
        println!("mean ok-gap {mean_ok:.4} over {ok_count}/{checked}");
        lines.push(format!("--- misses {}/{checked} ---", misses.len()));
        lines.extend(misses);
        insta::assert_snapshot!("screen_state_by_directory", lines.join("\n"));
    }

    /// Test-only fixture classification through the real live path:
    /// [`crate::vision::classify_screen`] on the decoded frame. Returns
    /// the state plus the matched exemplar name, so misses carry their
    /// cause into the snapshot itself.
    fn classify_fixture(
        index: &crate::screen_knn::KnnIndex,
        name: &str,
    ) -> (ScreenState, f32, String) {
        let path = format!("{}/tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR"));
        let (rgb, w, h) = crate::screen_knn::load_rgb_8bit(&path);
        let q = crate::screen_knn::KnnIndex::embed_frame(&rgb, w, h);
        let (got_class, gap, matched) = index.predict(&q, None).unwrap();
        let got = match got_class {
            crate::screen_knn::ScreenClass::Dark => ScreenState::Dark,
            crate::screen_knn::ScreenClass::FlatField => ScreenState::FlatField,
            crate::screen_knn::ScreenClass::ErrorShell => ScreenState::ErrorShell,
            crate::screen_knn::ScreenClass::InstallerStep => ScreenState::InstallerStep,
            crate::screen_knn::ScreenClass::Lockscreen => ScreenState::Lockscreen,
            crate::screen_knn::ScreenClass::FirmwareBoot => ScreenState::FirmwareBoot,
            crate::screen_knn::ScreenClass::OobeStep => ScreenState::OobeStep,
            crate::screen_knn::ScreenClass::ErrorRecovery => ScreenState::ErrorRecovery,
            crate::screen_knn::ScreenClass::ErrorScreen => ScreenState::ErrorScreen,
        };
        (got, gap, matched)
    }

    #[test]
    fn vnc_password_command_is_exact() {
        // Regression: the install path once sent "change vnc p.password",
        // which QEMU ignores — VNC auth then failed with no error anywhere.
        assert_eq!(
            vnc_password_command(),
            format!("change vnc password {PROVEN_VNC_PASSWORD}")
        );
    }

    #[test]
    fn run_chain_install_params_passes_cadence_through() {
        // Regression: `run --win-iso --screenshots-every-secs 10` installed
        // at 60s cadence because the chain hardcoded the default.
        let args = RunArgs {
            disk: None,
            ssh_port: crate::qemu::PROVEN_SSH_PORT,
            display: crate::qemu::Display::parse("vnc=127.0.0.1:10").unwrap(),
            memory: 4096,
            cpus: 4,
            disk_size: 64,
            vm_dir: None,
            qemu_dir: None,
            username: "u".into(),
            password: "p".into(),
            shell: false,
            live: false,
            win_iso: None,
            install_timeout_secs: 60,
            screenshots_every_secs: 10,
            classify_every_secs: Some(5),
        };
        let p = run_chain_install_params(&args, PathBuf::from("w.iso"));
        assert_eq!(p.screenshots_every_secs, 10);
        assert_eq!(p.classify_every_secs, Some(5));
        assert_eq!(p.install_timeout_secs, 60);
        assert_eq!(p.memory_mb, 4096);
        assert_eq!(p.cpus, 4);
        assert_eq!(p.disk_size_gb, 64);
    }

    #[test]
    fn failure_report_carries_frame_serial_vnc() {
        let report = format_failure_report(
            Some((
                PathBuf::from("/vm/screenshots/screenshot-1.png"),
                ScreenState::FlatField,
            )),
            "BdsDxe: starting Boot0003",
            3,
            Some((95, 12_582_912)),
            &Some("vnc://127.0.0.1:5910".to_string()),
        );
        assert!(report.contains("solid color field"), "{report}");
        assert!(report.contains("guest boots seen: 3"), "{report}");
        assert!(
            report.contains("/vm/screenshots/screenshot-1.png"),
            "{report}"
        );
        assert!(
            report.contains("last serial: BdsDxe: starting Boot0003"),
            "{report}"
        );
        assert!(report.contains("vnc: vnc://127.0.0.1:5910"), "{report}");
        assert!(report.contains("no I/O for 95s"), "{report}");
    }

    #[test]
    fn failure_report_states_missing_parts() {
        let report = format_failure_report(None, "", 0, None, &None);
        assert!(
            report.contains("no screenshot could be captured"),
            "{report}"
        );
        assert!(!report.contains("last serial"), "{report}");
        assert!(!report.contains("vnc:"), "{report}");
    }
}