runner-manager 0.4.42

Local-first autoscaling manager for ephemeral GitHub Actions self-hosted runners, with a CLI and a Ratatui TUI.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
// owner: host-prepare

//! `host doctor`, `host prepare`, `host required-tools`, and the host-fitness
//! preflight the daemon applies before it registers a runner.
//!
//! # Why this exists
//!
//! Every item in [`CHECKS`] is something a real host needed fixing by hand
//! before its runners worked properly: Windows Defender scanning a runner
//! workspace on access (a jsdom test worker took 22 s instead of 2.7 s),
//! `LongPathsEnabled` off and git's own `core.longpaths` unset, a login task
//! whose standard token cannot create symbolic links (`setup-bun` failed with
//! `EPERM`), a Windows PowerShell execution policy of `Restricted` under
//! `SYSTEM`, a macOS LaunchAgent that ran every runner at background priority,
//! a capacity of ten on an 8 GB machine, Spotlight indexing the runner root.
//! The doctor finds them; `host prepare` fixes the ones that can be fixed, and
//! asks for administrator rights only when a fix needs them.
//!
//! # A check is a pure function of facts
//!
//! A check's probe reads [`HostFacts`] and returns an [`Outcome`]; it never
//! reaches the operating system itself. [`SystemFacts`] is the real
//! implementation and the tests use a table. Fixes are the same through
//! [`HostActions`], and every fix returns the [`Change`]s it made, with the
//! value it replaced, so `host prepare --revert <id>` can put it back.
//!
//! # Elevation is asked for once, and only for what needs it
//!
//! A fix that needs administrator rights, in a process that does not have
//! them, is not attempted in-process. The whole batch of such fixes is handed
//! to one elevated copy of this binary — `ShellExecuteExW` `runas` on Windows,
//! `sudo` on a terminal or the system password dialog on macOS — with the plan
//! on its command line and a file to report into. That copy re-probes each
//! check before it changes anything, applies only what is still needed,
//! reports, and exits; it never opens the database or writes the journal, which
//! stays owned by the invoking account. A refused prompt is reported and the
//! rest of the command carries on.
//!
//! # Anything that lowers security needs an explicit yes
//!
//! Excluding a runner root from Defender's real-time scanning and turning on
//! Developer Mode both trade security for function. Neither is applied without
//! a specific flag (`--allow-av-exclusion`, `--allow-developer-mode`) or a
//! question answered on a terminal, and `--yes` alone never implies them.
//!
//! # Required, recommended, informational
//!
//! A **required** check failing means runners on this host cannot work
//! correctly, and the daemon refuses to start any (`host_unfit`). A check whose
//! answer is *unknown* never refuses: a probe that could not run is not
//! evidence that the host is unfit, and refusing on it would stop a working
//! host. **Recommended** checks are reported everywhere and never block.
//! **Informational** ones appear only in `host doctor`.

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::io::{self, BufRead, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Duration;

use runner_manager_domain::model::{Host, StartMode, Timestamp};
use runner_manager_domain::policy::ScalePolicy;
use runner_manager_domain::store::Store as _;
use runner_manager_platform::host_fitness::{self, ElevationOutcome};
use runner_manager_platform::runner_env::{self, Inherited, RunnerEnv, RunnerPlatform};
use runner_manager_platform::service::{
    InstallRecord, LAUNCHD_PROCESS_TYPE, ServiceAccount, ServiceDirectories, ServiceStatus,
    plist_string_value, service_account_name,
};
use runner_manager_platform::unattended_login::{self, Resume, UnattendedLogin};
use serde::{Deserialize, Serialize};

use super::workspace::{self, HostRoot};
use super::{
    CliError, Context, Failure, HostDoctorArgs, HostPrepareArgs, HostRequiredToolsArgs,
    write_failed,
};

/// The version of the `host doctor --json` document.
pub const REPORT_SCHEMA_VERSION: u32 = 1;

/// What `host prepare` changed, per check, under `config/`.
pub const JOURNAL_FILE: &str = "host-prepare.json";
const JOURNAL_SCHEMA_VERSION: u32 = 1;

/// The tools every runner on this host must find on its `PATH`, under
/// `config/`.
pub const REQUIRED_TOOLS_FILE: &str = "required-tools.json";

/// Set on the service binary `status` this module starts to read the
/// credential, so that copy does not run the doctor in turn.
pub const SKIP_DOCTOR_VARIABLE: &str = "RUNNER_MANAGER_SKIP_HOST_DOCTOR";

pub use host_fitness::DAEMON_RECHECK;

const GIB: u64 = 1024 * 1024 * 1024;
/// The memory one concurrent job is assumed to need when a capacity is
/// recommended. A guide, not a measurement of any particular workload.
const MEMORY_PER_RUNNER_GIB: u64 = 3;

/// A GitHub contact this recent proves the service could read its credential.
pub(crate) const RECENT_CONTACT_SECS: u64 = 15 * 60;

const ALLOW_AV_EXCLUSION: &str = "--allow-av-exclusion";
const ALLOW_DEVELOPER_MODE: &str = "--allow-developer-mode";

const WINDOWS_PWSH: &str = r"C:\Program Files\PowerShell\7\pwsh.exe";
/// The `PATH` systemd gives a unit that sets none.
const SYSTEMD_DEFAULT_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";

// ---------------------------------------------------------------------------
// Vocabulary
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
    /// Runners cannot work correctly without it; the daemon refuses to start
    /// any while it fails.
    Required,
    /// Reported everywhere, never blocks.
    Recommended,
    /// Reported by `host doctor` only.
    Info,
}

impl Severity {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Required => "required",
            Self::Recommended => "recommended",
            Self::Info => "info",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
    Pass,
    Fail,
    /// The probe could not answer, for instance without administrator rights.
    Unknown,
    NotApplicable,
}

impl Status {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Pass => "pass",
            Self::Fail => "fail",
            Self::Unknown => "unknown",
            Self::NotApplicable => "n/a",
        }
    }
}

/// Whose view a probe takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Perspective {
    /// A person's command. Facts about the service's account are inferred from
    /// how the service is (or is about to be) registered.
    Operator,
    /// The daemon itself, which *is* the account runners inherit.
    Daemon,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HostOs {
    Windows,
    Macos,
    Linux,
}

impl HostOs {
    #[must_use]
    pub const fn current() -> Self {
        match RunnerPlatform::current() {
            RunnerPlatform::Windows => Self::Windows,
            RunnerPlatform::MacOs => Self::Macos,
            RunnerPlatform::Linux => Self::Linux,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CheckPlatform {
    Windows,
    Macos,
    Any,
}

impl CheckPlatform {
    const fn includes(self, os: HostOs) -> bool {
        matches!(
            (self, os),
            (Self::Any, _) | (Self::Windows, HostOs::Windows) | (Self::Macos, HostOs::Macos)
        )
    }
}

// ---------------------------------------------------------------------------
// What a check is evaluated against
// ---------------------------------------------------------------------------

/// The registered (or about-to-be-registered) service, as far as checks care.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceSetup {
    pub start_mode: StartMode,
    pub binary: PathBuf,
    pub definition_path: Option<PathBuf>,
    /// The launchd label, for the restart command a macOS remedy names.
    pub label: String,
    /// Whether the service manager reports the daemon running. `None` when
    /// not asked: the daemon's own view, and a service about to be installed.
    #[serde(default)]
    pub running: Option<bool>,
    /// The other installation the machine's service belongs to, for a
    /// sentence, when it is not this account's. See
    /// [`runner_manager_platform::service::ForeignService`].
    #[serde(default)]
    pub installed_from: Option<String>,
    /// That installation's directories, where its daemon records what the
    /// checks read: its contact, its refusals, its polling.
    #[serde(default)]
    pub foreign_directories: Option<ServiceDirectories>,
}

/// Everything about this host's configuration a check reads. Serializable
/// because the elevated copy receives it on its command line rather than
/// opening the database itself.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HostSetup {
    pub os: HostOs,
    pub perspective: Perspective,
    pub service: Option<ServiceSetup>,
    /// Where jobs run: the effective host runner root, every persistent
    /// repository root, and the dependency-cache root when no runner root
    /// contains it.
    pub runner_roots: Vec<PathBuf>,
    pub capacity: u16,
    pub required_tools: Vec<String>,
    /// Why the required-tools file could not be read, when it could not: the
    /// check is then unknown rather than "none configured".
    #[serde(default)]
    pub required_tools_error: Option<String>,
    /// The `PATH` a native runner starts with, as well as this process can
    /// tell (exact in the daemon).
    pub runner_path: Option<String>,
    /// A directory this account owns, for the symbolic-link probe.
    pub probe_dir: PathBuf,
    pub data_root: Option<PathBuf>,
    /// How long ago the service last reached GitHub, in seconds, as it
    /// recorded it -- counted only when the contact is newer than the service
    /// binary, see [`current_daemon_contact_age`]. A recent contact by the
    /// binary now installed proves it could read its credential.
    #[serde(default)]
    pub service_contact_age_secs: Option<u64>,
    /// Whether the daemon recorded that it cannot read its stored credential:
    /// its own answer, from the session it runs in.
    #[serde(default)]
    pub service_credential_unreadable: bool,
    /// Whether this process reads the login-mode credential itself, to tell a
    /// credential the service binary cannot read from a keychain this whole
    /// session cannot read. `None` when not asked (not a macOS login service).
    #[serde(default)]
    pub own_keychain_readable: Option<bool>,
    /// Why the daemon starts no runner, from its own record or a stuck WSL
    /// launch fence. See [`runner_manager_platform::launch_health`].
    #[serde(default)]
    pub launches_blocked: Option<runner_manager_platform::launch_health::LaunchesBlocked>,
    /// The account the service runs as, or would run as, on macOS.
    #[serde(default)]
    pub service_account: Option<String>,
    /// That account's home folder, on macOS.
    #[serde(default)]
    pub service_home: Option<PathBuf>,
    /// The required checks the running daemon finds failing, from its own
    /// session, when it refuses to start runners. See [`evaluate`].
    #[serde(default, skip_serializing)]
    pub daemon_unfit: Option<host_fitness::HostUnfitRecord>,
    /// The poll intervals, and the daemon's last measurement of what polling
    /// costs. `None` when the intervals could not be read. Never sent to
    /// the elevated copy: no fix reads it.
    #[serde(default, skip_serializing)]
    pub polling: Option<PollingFacts>,
}

/// What `github.polling` reads.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PollingFacts {
    pub idle_secs: u16,
    pub active_secs: u16,
    /// `state/poll-traffic.toml`, when a daemon has written it.
    pub traffic: Option<runner_manager_platform::polling::PollTraffic>,
    /// Whether `traffic` is older than the daemon would let it get while it
    /// runs: see [`super::polling::STALE_AFTER`].
    #[serde(default)]
    pub stale: bool,
}

impl HostSetup {
    fn start_mode(&self) -> Option<StartMode> {
        self.service.as_ref().map(|service| service.start_mode)
    }
}

// ---------------------------------------------------------------------------
// Facts and actions
// ---------------------------------------------------------------------------

/// The registry values checks read, by meaning. A closed set so that nothing
/// in a plan or a journal can name an arbitrary key for the elevated copy to
/// write.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RegValue {
    LongPathsEnabled,
    DeveloperMode,
    ExecutionPolicy,
    ExecutionPolicyGroupPolicy,
    InstallationType,
    DefenderServiceRunning,
    DefenderPassiveMode,
    DefenderRealtimeOff,
    DefenderRealtimeOffPolicy,
    MachinePath,
}

impl RegValue {
    /// `(subkey under HKLM, value name)`.
    #[must_use]
    pub const fn location(self) -> (&'static str, &'static str) {
        match self {
            Self::LongPathsEnabled => (
                r"SYSTEM\CurrentControlSet\Control\FileSystem",
                "LongPathsEnabled",
            ),
            Self::DeveloperMode => (
                r"SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock",
                "AllowDevelopmentWithoutDevLicense",
            ),
            Self::ExecutionPolicy => (
                r"SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell",
                "ExecutionPolicy",
            ),
            Self::ExecutionPolicyGroupPolicy => (
                r"SOFTWARE\Policies\Microsoft\Windows\PowerShell",
                "ExecutionPolicy",
            ),
            Self::InstallationType => (
                r"SOFTWARE\Microsoft\Windows NT\CurrentVersion",
                "InstallationType",
            ),
            Self::DefenderServiceRunning => {
                (r"SOFTWARE\Microsoft\Windows Defender", "IsServiceRunning")
            }
            Self::DefenderPassiveMode => (r"SOFTWARE\Microsoft\Windows Defender", "PassiveMode"),
            Self::DefenderRealtimeOff => (
                r"SOFTWARE\Microsoft\Windows Defender\Real-Time Protection",
                "DisableRealtimeMonitoring",
            ),
            Self::DefenderRealtimeOffPolicy => (
                r"SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection",
                "DisableRealtimeMonitoring",
            ),
            Self::MachinePath => (
                r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
                "Path",
            ),
        }
    }

    /// Whether `host prepare` (or its revert) may ever write this value.
    const fn writable(self) -> bool {
        matches!(
            self,
            Self::LongPathsEnabled | Self::DeveloperMode | Self::ExecutionPolicy
        )
    }
}

/// What reading the service binary's credential found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CredentialProbe {
    Readable,
    Absent,
    Unreadable(String),
}

/// Read-only facts about this host. Every method is safe without privilege.
pub trait HostFacts {
    fn elevated(&self) -> bool;
    fn dword(&self, value: RegValue) -> Result<Option<u32>, String>;
    fn string(&self, value: RegValue) -> Result<Option<String>, String>;
    /// `Ok(None)` when this token may not read the list.
    fn defender_exclusions(&self) -> Result<Option<Vec<String>>, String>;
    fn git_system_value(&self, git: &Path, name: &str) -> Result<Option<String>, String>;
    fn symlink_allowed(&self, directory: &Path) -> Result<bool, String>;
    fn find_tool(&self, tool: &str, path: Option<&str>) -> Option<PathBuf>;
    fn file_exists(&self, path: &Path) -> bool;
    fn memory_bytes(&self) -> Option<u64>;
    fn cpu_count(&self) -> usize;
    /// `Ok(None)` when Spotlight gave no answer for this volume (a mount point).
    fn spotlight_indexing(&self, volume: &Path) -> Result<Option<bool>, String>;
    fn mount_point(&self, path: &Path) -> Option<PathBuf>;
    /// A bounded `stat` and one-entry listing of `directory`.
    fn directory_responds(&self, directory: &Path) -> host_fitness::Responsiveness;
    fn launchd_process_type(&self, plist: &Path) -> Result<Option<String>, String>;
    fn throttled_runner_processes(&self) -> Result<usize, String>;
    fn service_credential(
        &self,
        binary: &Path,
        data_root: Option<&Path>,
    ) -> Result<CredentialProbe, String>;
    /// macOS's power settings in use now (`pmset -g`), by name. `Ok(None)` on
    /// a platform without them.
    fn power_settings(&self) -> Result<Option<BTreeMap<String, u32>>, String> {
        Ok(None)
    }
    /// Automatic login and FileVault. `None` on a platform without them.
    fn unattended_login(&self) -> Option<UnattendedLogin> {
        None
    }
}

/// The writes fixes and reverts make.
pub trait HostActions {
    fn set_dword(&self, value: RegValue, data: Option<u32>) -> Result<(), String>;
    fn set_string(&self, value: RegValue, data: Option<&str>) -> Result<(), String>;
    fn set_git_system_value(
        &self,
        git: &Path,
        name: &str,
        value: Option<&str>,
    ) -> Result<(), String>;
    fn add_defender_exclusions(&self, paths: &[String]) -> Result<(), String>;
    fn remove_defender_exclusions(&self, paths: &[String]) -> Result<(), String>;
    fn set_spotlight(&self, volume: &Path, enabled: bool) -> Result<(), String>;
    /// `pmset -a NAME VALUE`, for one of [`POWER_SETTINGS`].
    fn set_power_setting(&self, name: &str, _value: u32) -> Result<(), String> {
        Err(format!(
            "cannot set {name}: power settings exist only on macOS"
        ))
    }
}

/// One change a fix made, with what it replaced.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Change {
    RegistryDword {
        value: RegValue,
        previous: Option<u32>,
        applied: u32,
    },
    RegistryString {
        value: RegValue,
        previous: Option<String>,
        applied: String,
    },
    GitSystemConfig {
        git: PathBuf,
        name: String,
        previous: Option<String>,
        applied: String,
    },
    DefenderExclusions {
        added: Vec<String>,
    },
    SpotlightIndexingOff {
        volume: PathBuf,
    },
    PowerSetting {
        name: String,
        previous: Option<u32>,
        applied: u32,
    },
}

/// The power settings a fix may write, with the largest value a revert may
/// restore. A closed set, as with [`RegValue`]: the journal is a plain file.
const POWER_SETTINGS: [(&str, u32); 4] = [
    ("sleep", u16::MAX as u32),
    ("disksleep", u16::MAX as u32),
    ("autorestart", 1),
    ("womp", 1),
];

/// The only execution policies a revert may restore.
const EXECUTION_POLICIES: [&str; 6] = [
    "Restricted",
    "AllSigned",
    "RemoteSigned",
    "Unrestricted",
    "Bypass",
    "Undefined",
];
const GIT_LONG_PATHS: &str = "core.longpaths";

impl Change {
    /// Identifies what was changed, so a second `prepare` of the same check
    /// does not replace the value the first one recorded.
    fn key(&self) -> String {
        match self {
            Self::RegistryDword { value, .. } | Self::RegistryString { value, .. } => {
                format!("registry:{value:?}")
            }
            Self::GitSystemConfig { name, .. } => format!("git:{name}"),
            Self::DefenderExclusions { added } => format!("defender:{}", added.join(";")),
            Self::SpotlightIndexingOff { volume } => format!("spotlight:{}", volume.display()),
            Self::PowerSetting { name, .. } => format!("pmset:{name}"),
        }
    }

    fn describe(&self) -> String {
        match self {
            Self::RegistryDword {
                value,
                previous,
                applied,
            } => format!(
                "{} = {applied} (was {})",
                value.location().1,
                previous.map_or_else(|| "not set".to_owned(), |v| v.to_string())
            ),
            Self::RegistryString {
                value,
                previous,
                applied,
            } => format!(
                "{} = {applied} (was {})",
                value.location().1,
                previous.as_deref().unwrap_or("not set")
            ),
            Self::GitSystemConfig {
                name,
                previous,
                applied,
                ..
            } => format!(
                "git config --system {name} {applied} (was {})",
                previous.as_deref().unwrap_or("not set")
            ),
            Self::DefenderExclusions { added } => {
                format!("Defender exclusion added: {}", added.join(", "))
            }
            Self::SpotlightIndexingOff { volume } => {
                format!("Spotlight indexing off for {}", volume.display())
            }
            Self::PowerSetting {
                name,
                previous,
                applied,
            } => format!(
                "pmset -a {name} {applied} (was {})",
                previous.map_or_else(|| "not set".to_owned(), |v| v.to_string())
            ),
        }
    }

    /// Puts back what this change replaced. Refuses anything outside the
    /// closed set a fix can produce, because a journal is an ordinary file.
    fn revert(&self, actions: &dyn HostActions) -> Result<(), String> {
        match self {
            Self::RegistryDword {
                value, previous, ..
            } if value.writable() => actions.set_dword(*value, *previous),
            Self::RegistryString {
                value, previous, ..
            } if value.writable()
                && previous.as_deref().is_none_or(|text| {
                    EXECUTION_POLICIES
                        .iter()
                        .any(|p| p.eq_ignore_ascii_case(text))
                }) =>
            {
                actions.set_string(*value, previous.as_deref())
            }
            Self::GitSystemConfig {
                git,
                name,
                previous,
                ..
            } if name == GIT_LONG_PATHS => {
                actions.set_git_system_value(git, name, previous.as_deref())
            }
            Self::DefenderExclusions { added } => actions.remove_defender_exclusions(added),
            Self::SpotlightIndexingOff { volume } => actions.set_spotlight(volume, true),
            Self::PowerSetting {
                name,
                previous: Some(previous),
                ..
            } if POWER_SETTINGS
                .iter()
                .any(|(known, most)| known == name && previous <= most) =>
            {
                actions.set_power_setting(name, *previous)
            }
            Self::PowerSetting {
                name,
                previous: None,
                ..
            } => Err(format!(
                "pmset reported no `{name}` before `host prepare` set it, so there is nothing to \
                 put back"
            )),
            _ => Err(format!(
                "the journal records a change `host prepare` never makes ({}); it was not reverted",
                self.key()
            )),
        }
    }
}

// ---------------------------------------------------------------------------
// The registry
// ---------------------------------------------------------------------------

/// What a probe found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Outcome {
    pub status: Status,
    pub detail: String,
    /// The manual action, when there is one worth naming.
    pub remedy: Option<String>,
    /// `false` when the check's automatic fix cannot help in this situation
    /// (a Group Policy setting, a startup volume).
    pub fixable: bool,
}

impl Outcome {
    fn new(status: Status, detail: impl Into<String>) -> Self {
        Self {
            status,
            detail: detail.into(),
            remedy: None,
            fixable: true,
        }
    }

    fn remedy(mut self, remedy: impl Into<String>) -> Self {
        self.remedy = Some(remedy.into());
        self
    }

    fn not_fixable(mut self) -> Self {
        self.fixable = false;
        self
    }
}

fn pass(detail: impl Into<String>) -> Outcome {
    Outcome::new(Status::Pass, detail)
}
fn fail(detail: impl Into<String>) -> Outcome {
    Outcome::new(Status::Fail, detail)
}
fn unknown(detail: impl Into<String>) -> Outcome {
    Outcome::new(Status::Unknown, detail)
}
fn not_applicable(detail: impl Into<String>) -> Outcome {
    Outcome::new(Status::NotApplicable, detail)
}

type Probe = fn(&HostSetup, &dyn HostFacts) -> Outcome;
type Apply = fn(&HostSetup, &dyn HostFacts, &dyn HostActions) -> Result<Vec<Change>, String>;

/// An automatic fix.
pub struct FixSpec {
    pub needs_admin: bool,
    /// The flag that consents to a fix that lowers security; `None` for one
    /// that does not.
    pub consent_flag: Option<&'static str>,
    /// What it will do, in a phrase.
    pub action: &'static str,
    apply: Apply,
}

/// One check.
pub struct CheckSpec {
    pub id: &'static str,
    pub title: &'static str,
    pub platform: CheckPlatform,
    pub severity: Severity,
    probe: Probe,
    pub fix: Option<FixSpec>,
}

/// Every check, in the order they are reported.
pub const CHECKS: &[CheckSpec] = &[
    CheckSpec {
        id: "windows.symlink_privilege",
        title: "Symbolic links for the runner account",
        platform: CheckPlatform::Windows,
        severity: Severity::Required,
        probe: probe_symlink,
        fix: Some(FixSpec {
            needs_admin: true,
            consent_flag: Some(ALLOW_DEVELOPER_MODE),
            action: "turn on Developer Mode (lets every account create symbolic links and sideload apps)",
            apply: |_, facts, actions| set_dword(facts, actions, RegValue::DeveloperMode, 1),
        }),
    },
    CheckSpec {
        id: "windows.long_paths",
        title: "Win32 long paths (LongPathsEnabled)",
        platform: CheckPlatform::Windows,
        severity: Severity::Recommended,
        probe: probe_long_paths,
        fix: Some(FixSpec {
            needs_admin: true,
            consent_flag: None,
            action: "set LongPathsEnabled = 1",
            apply: |_, facts, actions| set_dword(facts, actions, RegValue::LongPathsEnabled, 1),
        }),
    },
    CheckSpec {
        id: "windows.git_long_paths",
        title: "git core.longpaths (system configuration)",
        platform: CheckPlatform::Windows,
        severity: Severity::Recommended,
        probe: probe_git_long_paths,
        fix: Some(FixSpec {
            needs_admin: true,
            consent_flag: None,
            action: "git config --system core.longpaths true",
            apply: apply_git_long_paths,
        }),
    },
    CheckSpec {
        id: "windows.defender_exclusion",
        title: "Runner roots excluded from Defender real-time scanning",
        platform: CheckPlatform::Windows,
        severity: Severity::Recommended,
        probe: probe_defender,
        fix: Some(FixSpec {
            needs_admin: true,
            consent_flag: Some(ALLOW_AV_EXCLUSION),
            action: "Add-MpPreference -ExclusionPath <each runner root> (files there are no longer scanned on access)",
            apply: apply_defender,
        }),
    },
    CheckSpec {
        id: "windows.execution_account",
        title: "Service account can run unattended",
        platform: CheckPlatform::Windows,
        severity: Severity::Recommended,
        probe: probe_execution_account,
        fix: None,
    },
    CheckSpec {
        id: "windows.execution_policy",
        title: "Windows PowerShell execution policy",
        platform: CheckPlatform::Windows,
        severity: Severity::Recommended,
        probe: probe_execution_policy,
        fix: Some(FixSpec {
            needs_admin: true,
            consent_flag: None,
            action: "Set-ExecutionPolicy RemoteSigned -Scope LocalMachine",
            apply: apply_execution_policy,
        }),
    },
    CheckSpec {
        id: "windows.pwsh",
        title: "PowerShell 7 (pwsh) on the runners' PATH",
        platform: CheckPlatform::Windows,
        severity: Severity::Info,
        probe: probe_pwsh,
        fix: None,
    },
    CheckSpec {
        id: "macos.launchd_priority",
        title: "Service and runners at normal priority",
        platform: CheckPlatform::Macos,
        severity: Severity::Recommended,
        probe: probe_launchd_priority,
        fix: None,
    },
    CheckSpec {
        id: "macos.spotlight",
        title: "Spotlight does not index the runner roots",
        platform: CheckPlatform::Macos,
        severity: Severity::Recommended,
        probe: probe_spotlight,
        fix: Some(FixSpec {
            needs_admin: true,
            consent_flag: None,
            action: "mdutil -i off <the volume holding the runner root> (Spotlight stops indexing that whole volume)",
            apply: apply_spotlight,
        }),
    },
    CheckSpec {
        id: "macos.sleep",
        title: "The Mac does not go to sleep",
        platform: CheckPlatform::Macos,
        severity: Severity::Recommended,
        probe: probe_sleep,
        fix: Some(FixSpec {
            needs_admin: true,
            consent_flag: None,
            action: "pmset -a sleep 0 (the Mac stops sleeping when nobody uses it; the display \
                     still turns off)",
            apply: apply_sleep,
        }),
    },
    CheckSpec {
        id: "macos.disk_sleep",
        title: "Disks do not sleep",
        platform: CheckPlatform::Macos,
        severity: Severity::Recommended,
        probe: probe_disk_sleep,
        fix: Some(FixSpec {
            needs_admin: true,
            consent_flag: None,
            action: "pmset -a disksleep 0",
            apply: apply_disk_sleep,
        }),
    },
    CheckSpec {
        id: "macos.autorestart",
        title: "The Mac starts again after a power failure",
        platform: CheckPlatform::Macos,
        severity: Severity::Recommended,
        probe: probe_autorestart,
        fix: Some(FixSpec {
            needs_admin: true,
            consent_flag: None,
            action: "pmset -a autorestart 1",
            apply: apply_autorestart,
        }),
    },
    CheckSpec {
        id: "macos.wake_on_lan",
        title: "The Mac wakes for network access",
        platform: CheckPlatform::Macos,
        severity: Severity::Info,
        probe: probe_wake_on_lan,
        fix: Some(FixSpec {
            needs_admin: true,
            consent_flag: None,
            action: "pmset -a womp 1",
            apply: apply_wake_on_lan,
        }),
    },
    CheckSpec {
        id: "macos.unattended_login",
        title: "The service comes back after an unattended restart",
        platform: CheckPlatform::Macos,
        severity: Severity::Recommended,
        probe: probe_unattended_login,
        // Automatic login and FileVault are security settings: reported with
        // the steps, never changed by `host prepare`.
        fix: None,
    },
    CheckSpec {
        id: "macos.runner_root_location",
        title: "Runner roots have no spaces and are outside the service account's home",
        platform: CheckPlatform::Macos,
        severity: Severity::Recommended,
        probe: probe_runner_root_location,
        fix: None,
    },
    CheckSpec {
        id: "macos.keychain_credential",
        title: "Service binary can read its GitHub credential",
        platform: CheckPlatform::Macos,
        severity: Severity::Required,
        probe: probe_keychain_credential,
        fix: None,
    },
    CheckSpec {
        id: "host.runner_root_responsive",
        title: "Runner roots respond",
        platform: CheckPlatform::Any,
        severity: Severity::Required,
        probe: probe_runner_root_responsive,
        fix: None,
    },
    CheckSpec {
        id: "host.capacity",
        title: "Capacity fits this machine's memory and cores",
        platform: CheckPlatform::Any,
        severity: Severity::Recommended,
        probe: probe_capacity,
        fix: None,
    },
    CheckSpec {
        id: "host.required_tools",
        title: "Required tools on the runners' PATH",
        platform: CheckPlatform::Any,
        severity: Severity::Required,
        probe: probe_required_tools,
        fix: None,
    },
    CheckSpec {
        id: "github.polling",
        title: "GitHub polling runs at its configured pace",
        platform: CheckPlatform::Any,
        severity: Severity::Info,
        probe: probe_polling,
        fix: None,
    },
    // Recommended, not Required: a Required failure makes the daemon refuse
    // every launch, and this check reports exactly that refusal.
    // The daemon's own: its host checks did not finish, so one is blocked. A
    // command's look always finishes, so it passes here; `daemon_view` fails
    // it when the service recorded it.
    CheckSpec {
        id: BLOCKED_CHECKS_ID,
        title: "The service's host checks finish",
        platform: CheckPlatform::Any,
        severity: Severity::Required,
        probe: |_, _| pass("the host checks finish"),
        fix: None,
    },
    CheckSpec {
        id: "host.launches",
        title: "The service can start runners",
        platform: CheckPlatform::Any,
        severity: Severity::Recommended,
        probe: probe_launches,
        fix: None,
    },
];

/// The id the daemon's host-unfit record carries when its host checks did not
/// finish.
pub const BLOCKED_CHECKS_ID: &str = "host.checks";

fn check(id: &str) -> Option<&'static CheckSpec> {
    CHECKS.iter().find(|check| check.id == id)
}

fn fix(id: &str) -> Option<&'static FixSpec> {
    check(id).and_then(|check| check.fix.as_ref())
}

fn fix_needs_admin(id: &str) -> bool {
    fix(id).is_some_and(|fix| fix.needs_admin)
}

/// Whether the fix for `id` lowers security and so needs explicit consent.
#[must_use]
pub fn lowers_security(id: &str) -> bool {
    fix(id).is_some_and(|fix| fix.consent_flag.is_some())
}

fn set_dword(
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
    value: RegValue,
    data: u32,
) -> Result<Vec<Change>, String> {
    let previous = facts.dword(value)?;
    actions.set_dword(value, Some(data))?;
    Ok(vec![Change::RegistryDword {
        value,
        previous,
        applied: data,
    }])
}

// -- windows.symlink_privilege ----------------------------------------------

const SYMLINK_CONSEQUENCE: &str =
    "`npm`, `pnpm` and `setup-bun` then fail in jobs with EPERM when they link a file";

fn probe_symlink(setup: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    let boot_remedy = "or run the service as LocalSystem instead: runner-manager service install \
                       --start-at boot (from an elevated terminal)";
    let measured =
        |facts: &dyn HostFacts, account: &str| match facts.symlink_allowed(&setup.probe_dir) {
            Ok(true) => pass(format!("{account} can create symbolic links")),
            Ok(false) => fail(format!(
                "{account} cannot create symbolic links; {SYMLINK_CONSEQUENCE}"
            ))
            .remedy(boot_remedy),
            Err(error) => unknown(format!("the symbolic-link probe could not run: {error}")),
        };
    if setup.perspective == Perspective::Daemon {
        return measured(facts, "this daemon's account");
    }
    if facts.dword(RegValue::DeveloperMode) == Ok(Some(1)) {
        return pass("Developer Mode is on, so every account can create symbolic links");
    }
    match setup.start_mode() {
        Some(StartMode::Boot) => {
            pass("the boot service runs as LocalSystem, which holds the symbolic-link privilege")
        }
        Some(StartMode::Login) if !facts.elevated() => measured(
            facts,
            "this account (the login service runs as it, unelevated)",
        ),
        Some(StartMode::Login) => fail(format!(
            "the login service runs with this user's standard (unelevated) token, which cannot \
             create symbolic links while Developer Mode is off; {SYMLINK_CONSEQUENCE}"
        ))
        .remedy(boot_remedy),
        None => measured(facts, "this account"),
    }
}

// -- windows.long_paths -------------------------------------------------------

fn probe_long_paths(_: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    match facts.dword(RegValue::LongPathsEnabled) {
        Ok(Some(1)) => pass("LongPathsEnabled is 1"),
        Ok(found) => fail(format!(
            "LongPathsEnabled is {}, so programs that opt in still stop at 260 characters in deep \
             node_modules and build trees",
            found.map_or_else(|| "not set".to_owned(), |value| value.to_string())
        )),
        Err(error) => unknown(format!("LongPathsEnabled could not be read: {error}")),
    }
}

// -- windows.git_long_paths ---------------------------------------------------

fn runner_git(setup: &HostSetup, facts: &dyn HostFacts) -> Option<PathBuf> {
    facts.find_tool("git", setup.runner_path.as_deref())
}

fn probe_git_long_paths(setup: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    let Some(git) = runner_git(setup, facts) else {
        return not_applicable("git is not on the runners' PATH");
    };
    match facts.git_system_value(&git, GIT_LONG_PATHS) {
        Ok(Some(value)) if value.trim().eq_ignore_ascii_case("true") => pass(format!(
            "{} reads core.longpaths = true from its system configuration",
            git.display()
        )),
        Ok(found) => fail(format!(
            "core.longpaths is {} in {}'s system configuration. Git does not honour \
             LongPathsEnabled, so a checkout holding a path over 260 characters fails",
            found.as_deref().unwrap_or("not set"),
            git.display()
        )),
        Err(error) => unknown(format!(
            "git's system configuration could not be read: {error}"
        )),
    }
}

fn apply_git_long_paths(
    setup: &HostSetup,
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
) -> Result<Vec<Change>, String> {
    let git = runner_git(setup, facts).ok_or("git is not on the runners' PATH")?;
    let previous = facts.git_system_value(&git, GIT_LONG_PATHS)?;
    actions.set_git_system_value(&git, GIT_LONG_PATHS, Some("true"))?;
    Ok(vec![Change::GitSystemConfig {
        git,
        name: GIT_LONG_PATHS.to_owned(),
        previous,
        applied: "true".to_owned(),
    }])
}

// -- windows.defender_exclusion -----------------------------------------------

/// Why Defender is not the scanner to worry about, when it is not.
fn defender_inactive(facts: &dyn HostFacts) -> Option<&'static str> {
    if facts.dword(RegValue::DefenderRealtimeOffPolicy) == Ok(Some(1))
        || facts.dword(RegValue::DefenderRealtimeOff) == Ok(Some(1))
    {
        return Some("Defender real-time protection is turned off");
    }
    if facts.dword(RegValue::DefenderPassiveMode) == Ok(Some(1)) {
        return Some("Defender runs in passive mode behind another antivirus product");
    }
    if facts.dword(RegValue::DefenderServiceRunning) == Ok(Some(0)) {
        return Some("the Defender service is not running");
    }
    None
}

/// Expands `%NAME%` references from this process's environment, leaving
/// unknown ones as they are.
fn expand_environment(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(start) = rest.find('%') {
        out.push_str(&rest[..start]);
        let after = &rest[start + 1..];
        match after.find('%') {
            Some(end) if end > 0 => {
                let name = &after[..end];
                match std::env::var(name) {
                    Ok(value) => out.push_str(&value),
                    Err(_) => {
                        out.push('%');
                        out.push_str(name);
                        out.push('%');
                    }
                }
                rest = &after[end + 1..];
            }
            _ => {
                out.push('%');
                rest = after;
            }
        }
    }
    out.push_str(rest);
    out
}

fn normalised_windows_path(text: &str) -> String {
    expand_environment(text)
        .replace('/', "\\")
        .trim_end_matches('\\')
        .to_ascii_lowercase()
}

/// The runner roots no exclusion covers. An exclusion covers its own path and
/// everything under it.
fn uncovered_roots(roots: &[PathBuf], exclusions: &[String]) -> Vec<String> {
    let exclusions: Vec<String> = exclusions
        .iter()
        .map(|e| normalised_windows_path(e))
        .collect();
    roots
        .iter()
        .map(|root| root.display().to_string())
        .filter(|root| {
            let root_key = normalised_windows_path(root);
            !exclusions.iter().any(|exclusion| {
                !exclusion.is_empty()
                    && (root_key == *exclusion
                        || root_key
                            .strip_prefix(exclusion.as_str())
                            .is_some_and(|tail| tail.starts_with('\\')))
            })
        })
        .collect()
}

fn probe_defender(setup: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    if setup.runner_roots.is_empty() {
        return not_applicable("no runner root could be resolved");
    }
    if let Some(reason) = defender_inactive(facts) {
        return not_applicable(reason);
    }
    match facts.defender_exclusions() {
        Ok(Some(exclusions)) => {
            let missing = uncovered_roots(&setup.runner_roots, &exclusions);
            if missing.is_empty() {
                pass("every runner root is excluded from real-time scanning")
            } else {
                fail(format!(
                    "Defender scans every file jobs read and write under {} on access, which \
                     makes installs and test start-up several times slower (measured: 22 s \
                     instead of 2.7 s per jsdom test worker)",
                    missing.join(", ")
                ))
            }
        }
        Ok(None) => unknown(
            "only an administrator can read Defender's exclusion list; run `runner-manager host \
             doctor` from an elevated terminal to see it",
        ),
        Err(error) => unknown(format!(
            "Defender's exclusion list could not be read: {error}"
        )),
    }
}

fn apply_defender(
    setup: &HostSetup,
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
) -> Result<Vec<Change>, String> {
    let exclusions = facts
        .defender_exclusions()?
        .ok_or("Defender's exclusion list cannot be read even with administrator rights")?;
    let missing = uncovered_roots(&setup.runner_roots, &exclusions);
    if missing.is_empty() {
        return Ok(Vec::new());
    }
    actions.add_defender_exclusions(&missing)?;
    Ok(vec![Change::DefenderExclusions { added: missing }])
}

// -- windows.execution_account ------------------------------------------------

fn probe_execution_account(setup: &HostSetup, _: &dyn HostFacts) -> Outcome {
    // Another installation's login registration is moved to boot by that
    // installation, never from here.
    if let Some(installed_from) = setup
        .service
        .as_ref()
        .and_then(|service| service.installed_from.as_ref())
        && setup.start_mode() == Some(StartMode::Login)
    {
        return fail(format!(
            "the login service installed from {installed_from} runs with its account's standard \
             token, so a prompt waits for a person who is not there"
        ))
        .remedy(format!(
            "for an autonomous host, the account whose data root that is moves it to `--start-at \
             boot`; changing it from this account would re-register it against this account's \
             directories ({installed_from})"
        ));
    }
    match setup.start_mode() {
        Some(StartMode::Boot) => pass(
            "the boot service runs as LocalSystem: it needs no signed-in session and nothing it \
             starts waits on a prompt",
        ),
        Some(StartMode::Login) => fail(
            "the login service runs with this user's standard token. Windows Firewall prompts for \
             tools that listen on the network (Node.js from a fresh per-job path) wait for a \
             person who is not there, and anything that needs administrator rights fails",
        )
        .remedy(
            "for an autonomous host: runner-manager service install --start-at boot (from an \
             elevated terminal)",
        ),
        None => not_applicable("no service is installed"),
    }
}

// -- windows.execution_policy -------------------------------------------------

fn probe_execution_policy(_: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    let read = |value| facts.string(value);
    let (policy, source, managed) = match read(RegValue::ExecutionPolicyGroupPolicy) {
        Ok(Some(policy)) => (policy, "Group Policy", true),
        Err(error) => return unknown(format!("the execution policy could not be read: {error}")),
        Ok(None) => match read(RegValue::ExecutionPolicy) {
            Ok(Some(policy)) if !policy.eq_ignore_ascii_case("Undefined") => {
                (policy, "LocalMachine", false)
            }
            Err(error) => {
                return unknown(format!("the execution policy could not be read: {error}"));
            }
            Ok(_) => {
                let server = read(RegValue::InstallationType)
                    .ok()
                    .flatten()
                    .is_some_and(|kind| kind.to_ascii_lowercase().contains("server"));
                let default = if server { "RemoteSigned" } else { "Restricted" };
                (default.to_owned(), "the Windows default", false)
            }
        },
    };
    let blocks = ["Restricted", "AllSigned"]
        .iter()
        .any(|blocking| policy.eq_ignore_ascii_case(blocking));
    if !blocks {
        return pass(format!("{policy} ({source})"));
    }
    let outcome = fail(format!(
        "Windows PowerShell's execution policy is {policy} ({source}), so `shell: powershell` \
         steps that run a .ps1 script under the service account are refused"
    ));
    if managed {
        outcome
            .not_fixable()
            .remedy("Group Policy sets it; change the policy where it is managed")
    } else {
        outcome
    }
}

fn apply_execution_policy(
    _: &HostSetup,
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
) -> Result<Vec<Change>, String> {
    if facts
        .string(RegValue::ExecutionPolicyGroupPolicy)?
        .is_some()
    {
        return Err(
            "Group Policy sets the execution policy; a local change would not apply".into(),
        );
    }
    let previous = facts.string(RegValue::ExecutionPolicy)?;
    actions.set_string(RegValue::ExecutionPolicy, Some("RemoteSigned"))?;
    Ok(vec![Change::RegistryString {
        value: RegValue::ExecutionPolicy,
        previous,
        applied: "RemoteSigned".to_owned(),
    }])
}

// -- windows.pwsh -------------------------------------------------------------

fn probe_pwsh(setup: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    if let Some(found) = facts.find_tool("pwsh", setup.runner_path.as_deref()) {
        return pass(found.display().to_string());
    }
    let install = "winget install --id Microsoft.PowerShell --source winget --scope machine";
    if facts.file_exists(Path::new(WINDOWS_PWSH)) {
        fail(format!(
            "PowerShell 7 is installed at {WINDOWS_PWSH} but is not on the runners' PATH, so \
             `shell: pwsh` steps fail"
        ))
        .remedy("add its directory with `runner-manager host env set PATH=...`")
    } else {
        fail("PowerShell 7 is not installed, so `shell: pwsh` steps fail").remedy(install)
    }
}

// -- github.polling -----------------------------------------------------------

/// The poll intervals, the share of polls GitHub answered `304`, and whether
/// the daemon is slowing down. Information only: being throttled resolves by
/// waiting, and the daemon already does.
fn probe_polling(setup: &HostSetup, _facts: &dyn HostFacts) -> Outcome {
    let Some(polling) = &setup.polling else {
        return unknown(
            "config/polling.toml could not be read, so the service polls at the default idle \
             interval",
        )
        .remedy("runner-manager host set-poll-interval --idle 10s (rewrites the file)");
    };
    let intervals = format!(
        "idle every {}s, active every {}s",
        polling.idle_secs, polling.active_secs
    );
    let Some(traffic) = &polling.traffic else {
        return pass(format!(
            "{intervals}; no service has measured its polling yet"
        ));
    };
    if polling.stale {
        return unknown(format!(
            "{intervals}; the last measurement is from {}, so the service is probably not \
             running",
            traffic.written_at.to_rfc3339()
        ));
    }
    let share = traffic.not_modified_percent().map_or_else(
        || "no responses yet".to_string(),
        |percent| {
            format!(
                "{percent}% of {} responses over {} minute(s) were 304 (free against the hourly \
                 quota)",
                traffic.total(),
                traffic.observed_minutes
            )
        },
    );
    let quota = match (traffic.rate_limit_remaining, traffic.rate_limit_limit) {
        (Some(remaining), Some(limit)) => {
            format!("; the account has {remaining} of {limit} requests left this hour")
        }
        _ => String::new(),
    };
    let detail = format!(
        "{intervals}; {share}; busiest minute {} of {} secondary-limit points{quota}",
        traffic.peak_requests_per_minute,
        runner_manager_github::traffic::SECONDARY_POINTS_PER_MINUTE
    );
    match &traffic.throttled_because {
        None => pass(format!("{detail}; not throttled")),
        Some(reason) => {
            let remedy = match traffic.pace.as_str() {
                "blocked" => {
                    "runner-manager auth status, then sign in again or grant the missing \
                              permission"
                }
                "offline" => "check this machine's network; the service retries on its own",
                _ => {
                    "nothing to do here; the service waits and recovers on its own. If the \
                      quota is low, something else signed in as the same GitHub user may be \
                      spending it"
                }
            };
            fail(format!("{detail}. Throttled: {reason}")).remedy(remedy)
        }
    }
}

// -- macos.launchd_priority ---------------------------------------------------

fn probe_launchd_priority(setup: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    let mut problems = Vec::new();
    let plist = setup
        .service
        .as_ref()
        .and_then(|service| service.definition_path.as_ref());
    if let Some(plist) = plist {
        // The same rule `service status` applies to the plist it rendered.
        match facts.launchd_process_type(plist) {
            Ok(Some(kind)) if kind == LAUNCHD_PROCESS_TYPE => {}
            Ok(kind) => problems.push(format!(
                "{} sets ProcessType = {}, not {LAUNCHD_PROCESS_TYPE}, so launchd runs the daemon \
                 and every runner it starts below normal priority",
                plist.display(),
                kind.as_deref().unwrap_or("nothing (Standard)")
            )),
            Err(error) => {
                return unknown(format!("{} could not be read: {error}", plist.display()));
            }
        }
    }
    match facts.throttled_runner_processes() {
        Ok(0) => {}
        Ok(count) => problems.push(format!(
            "{count} runner process(es) are running at background priority"
        )),
        Err(error) if problems.is_empty() => {
            return unknown(format!("runner priorities could not be read: {error}"));
        }
        Err(_) => {}
    }
    if !problems.is_empty() {
        let restart = match setup.service.as_ref() {
            Some(service) if service.start_mode == StartMode::Boot => {
                format!("sudo launchctl kickstart -k system/{}", service.label)
            }
            Some(service) => format!("launchctl kickstart -k gui/$(id -u)/{}", service.label),
            None => "runner-manager service install".to_owned(),
        };
        return fail(problems.join("; ")).remedy(format!(
            "the daemon (0.4.32 and later; `runner-manager update`) rewrites the plist with \
             ProcessType = Interactive and reloads itself when it starts with no runner; to do \
             it now, restart the service while no job runs: {restart}"
        ));
    }
    if plist.is_none() {
        return not_applicable("no LaunchAgent or LaunchDaemon is installed");
    }
    if setup.service.as_ref().and_then(|service| service.running) == Some(false) {
        return unknown(
            "the plist asks for normal priority, but the service is not running, so the \
             priority it runs at cannot be seen; `runner-manager service status` says why",
        );
    }
    pass("the service runs at normal priority and no runner is throttled")
}

// -- macos.spotlight ----------------------------------------------------------

fn is_noindex(root: &Path) -> bool {
    root.components()
        .any(|part| part.as_os_str().to_string_lossy().ends_with(".noindex"))
}

/// The volumes macOS boots from, where turning Spotlight off would disable
/// search for the whole machine.
fn is_startup_volume(volume: &Path) -> bool {
    volume == Path::new("/") || volume == Path::new("/System/Volumes/Data")
}

/// The indexed runner roots and the volume each lives on.
///
/// Spotlight answers per volume: `mdutil -s` on a folder inside a volume says
/// "unknown indexing state" (measured on the Mac mini), so the question is put
/// to the root's mount point. A volume it gives no answer for is an error, not
/// a pass.
fn indexed_roots(
    setup: &HostSetup,
    facts: &dyn HostFacts,
) -> Result<Vec<(PathBuf, PathBuf)>, String> {
    let mut indexed = Vec::new();
    // Roots usually share a volume; ask Spotlight about each volume once.
    let mut answers: BTreeMap<PathBuf, Option<bool>> = BTreeMap::new();
    for root in setup.runner_roots.iter().filter(|root| !is_noindex(root)) {
        // `df` and `mdutil` on a hung volume would hang this whole check.
        if facts.directory_responds(root) != host_fitness::Responsiveness::Responds {
            return Err(format!("{} does not respond", root.display()));
        }
        let volume = facts
            .mount_point(root)
            .ok_or_else(|| format!("the volume holding {} could not be found", root.display()))?;
        let answer = match answers.get(&volume) {
            Some(answer) => *answer,
            None => {
                let answer = facts.spotlight_indexing(&volume)?;
                answers.insert(volume.clone(), answer);
                answer
            }
        };
        match answer {
            Some(true) => indexed.push((root.clone(), volume)),
            Some(false) => {}
            None => return Err(format!("Spotlight gave no answer for {}", volume.display())),
        }
    }
    Ok(indexed)
}

fn probe_spotlight(setup: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    if setup.runner_roots.is_empty() {
        return not_applicable("no runner root could be resolved");
    }
    let indexed = match indexed_roots(setup, facts) {
        Ok(indexed) => indexed,
        Err(error) => return unknown(format!("Spotlight's status could not be read: {error}")),
    };
    if indexed.is_empty() {
        return pass("Spotlight does not index the volumes holding the runner roots");
    }
    let names = indexed
        .iter()
        .map(|(root, _)| root.display().to_string())
        .collect::<Vec<_>>()
        .join(", ");
    let outcome = fail(format!(
        "Spotlight indexes {names}, re-reading every file jobs write there"
    ));
    // The fix turns indexing off per volume and never on a startup volume, so
    // a root there needs the manual remedy even when another root is fixable.
    let Some((startup_root, _)) = indexed.iter().find(|(_, volume)| is_startup_volume(volume))
    else {
        return outcome;
    };
    let remedy = format!(
        "{} is on the startup volume: move it into a folder whose name ends in `.noindex`, has \
         no spaces and is outside your home folder (runner-manager host set-runtime-root --path \
         {MACOS_RUNNER_ROOT}), or add it to System Settings > Spotlight > Search Privacy",
        startup_root.display(),
    );
    let outcome = outcome.remedy(remedy);
    if indexed.iter().all(|(_, volume)| is_startup_volume(volume)) {
        outcome.not_fixable()
    } else {
        outcome
    }
}

fn apply_spotlight(
    setup: &HostSetup,
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
) -> Result<Vec<Change>, String> {
    let mut changes = Vec::new();
    let mut volumes: Vec<PathBuf> = indexed_roots(setup, facts)?
        .into_iter()
        .map(|(_, volume)| volume)
        .filter(|volume| !is_startup_volume(volume))
        .collect();
    volumes.sort();
    volumes.dedup();
    if volumes.is_empty() {
        return Err("every indexed runner root is on the startup volume; see the remedy".into());
    }
    for volume in volumes {
        actions.set_spotlight(&volume, false)?;
        changes.push(Change::SpotlightIndexingOff { volume });
    }
    Ok(changes)
}

// -- macos.sleep, macos.disk_sleep, macos.autorestart, macos.wake_on_lan --------

/// A runner root a Mac can always use: no spaces, outside every home folder,
/// and named `.noindex` so Spotlight leaves it alone. Jobs that broke under
/// `~/Library/Application Support` pass there, measured on the runner Macs.
const MACOS_RUNNER_ROOT: &str = "/Users/Shared/rman.noindex";

/// Reads `pmset -g`: every setting it lists, by name. A name can contain
/// spaces (`Sleep On Power Button 1`) and a value can carry a note (`sleep 0
/// (sleep prevented by powerd)`), so the value is the first number on the line
/// and the name is everything before it.
fn power_settings_in(output: &str) -> BTreeMap<String, u32> {
    let mut settings = BTreeMap::new();
    for line in output
        .lines()
        .filter(|line| line.starts_with(char::is_whitespace))
    {
        let words: Vec<&str> = line.split_whitespace().collect();
        if let Some(at) = words.iter().position(|word| word.parse::<u32>().is_ok())
            && at > 0
            && let Ok(value) = words[at].parse()
        {
            settings.insert(words[..at].join(" "), value);
        }
    }
    settings
}

/// One power setting against the value a runner host wants.
fn power_probe(
    settings: Result<Option<BTreeMap<String, u32>>, String>,
    name: &str,
    wanted: u32,
    good: &str,
    bad: impl Fn(u32) -> String,
) -> Outcome {
    match settings {
        Err(error) => unknown(format!("`pmset -g` could not be read: {error}")),
        Ok(None) => not_applicable("this platform has no power settings to check"),
        Ok(Some(settings)) => match settings.get(name) {
            None => not_applicable(format!("this Mac has no `{name}` power setting")),
            Some(&value) if value == wanted => pass(good),
            Some(&value) => fail(bad(value)),
        },
    }
}

fn apply_power(
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
    name: &str,
    wanted: u32,
) -> Result<Vec<Change>, String> {
    let previous = facts
        .power_settings()?
        .and_then(|settings| settings.get(name).copied());
    actions.set_power_setting(name, wanted)?;
    Ok(vec![Change::PowerSetting {
        name: name.to_owned(),
        previous,
        applied: wanted,
    }])
}

fn probe_sleep(_: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    let settings = facts.power_settings();
    if let Ok(Some(settings)) = &settings
        && settings.get("SleepDisabled") == Some(&1)
    {
        return pass("sleep is disabled for the whole system");
    }
    power_probe(
        settings,
        "sleep",
        0,
        "the Mac does not sleep on its own",
        |minutes| {
            format!(
                "the Mac sleeps after {minutes} minute(s) nobody uses it, and a sleeping Mac freezes \
             the job it is running; GitHub fails a job whose runner stops answering"
            )
        },
    )
}

fn apply_sleep(
    _: &HostSetup,
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
) -> Result<Vec<Change>, String> {
    apply_power(facts, actions, "sleep", 0)
}

fn probe_disk_sleep(_: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    power_probe(
        facts.power_settings(),
        "disksleep",
        0,
        "disks do not sleep",
        |minutes| {
            format!(
                "disks sleep after {minutes} minute(s) idle, so the first read after a quiet spell \
             waits for a disk to wake"
            )
        },
    )
}

fn apply_disk_sleep(
    _: &HostSetup,
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
) -> Result<Vec<Change>, String> {
    apply_power(facts, actions, "disksleep", 0)
}

fn probe_autorestart(_: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    power_probe(
        facts.power_settings(),
        "autorestart",
        1,
        "the Mac starts again by itself after a power failure",
        |_| {
            "after a power failure the Mac stays off until somebody presses its power button"
                .to_owned()
        },
    )
}

fn apply_autorestart(
    _: &HostSetup,
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
) -> Result<Vec<Change>, String> {
    apply_power(facts, actions, "autorestart", 1)
}

fn probe_wake_on_lan(_: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    power_probe(
        facts.power_settings(),
        "womp",
        1,
        "the Mac wakes when the network asks it to",
        |_| "Wake for network access is off, so the Mac cannot be woken remotely".to_owned(),
    )
}

fn apply_wake_on_lan(
    _: &HostSetup,
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
) -> Result<Vec<Change>, String> {
    apply_power(facts, actions, "womp", 1)
}

// -- macos.unattended_login ---------------------------------------------------

fn probe_unattended_login(setup: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    let Some(service) = &setup.service else {
        return not_applicable("no service is installed");
    };
    let Some(found) = facts.unattended_login() else {
        return not_applicable("automatic login and FileVault could not be probed here");
    };
    let account = setup
        .service_account
        .as_deref()
        .unwrap_or("the service account");
    let verdict = unattended_login::resume(&found, service.start_mode, account);
    let (Some(detail), Some(remedy)) = (verdict.detail(account), verdict.remedy()) else {
        return match verdict {
            Resume::Resumes => pass(match service.start_mode {
                StartMode::Login => format!(
                    "automatic login signs {account} in and FileVault is off, so the service \
                     starts again after a restart"
                ),
                StartMode::Boot => "FileVault is off, so the service starts at boot".to_owned(),
            }),
            _ => unknown(verdict.detail(account).unwrap_or_default()),
        };
    };
    fail(detail).remedy(remedy)
}

// -- macos.runner_root_location -----------------------------------------------

fn probe_runner_root_location(setup: &HostSetup, _: &dyn HostFacts) -> Outcome {
    if setup.runner_roots.is_empty() {
        return not_applicable("no runner root could be resolved");
    }
    let home = setup
        .service_home
        .as_deref()
        .filter(|home| *home != Path::new("/"));
    let mut found = Vec::new();
    for root in &setup.runner_roots {
        if root.to_string_lossy().chars().any(char::is_whitespace) {
            found.push(format!(
                "{} has a space in its path, which breaks job scripts that do not quote paths",
                root.display()
            ));
        }
        if let Some(home) = home
            && root.starts_with(home)
        {
            found.push(format!(
                "{} is inside {}, the home folder of the account the service runs as, and so is \
                 every job's TMPDIR; a test that builds a stand-in home folder under TMPDIR then \
                 nests it inside the real one",
                root.display(),
                home.display()
            ));
        }
    }
    if found.is_empty() {
        pass("no runner root has a space in its path or is inside the service account's home")
    } else {
        fail(found.join("; ")).remedy(format!(
            "move the runner root to a folder with no spaces outside every home folder: \
             runner-manager host set-runtime-root --path {MACOS_RUNNER_ROOT}"
        ))
    }
}

// -- macos.keychain_credential ------------------------------------------------

fn probe_keychain_credential(setup: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    if setup.perspective == Perspective::Daemon {
        return not_applicable("the daemon reads its own credential directly");
    }
    let Some(service) = &setup.service else {
        return not_applicable("no service is installed");
    };
    if service.start_mode == StartMode::Boot {
        return not_applicable(
            "a boot service keeps its credential in the System Keychain, which only root reads",
        );
    }
    // Probing would run another account's binary as this account.
    if let Some(installed_from) = &service.installed_from {
        return not_applicable(format!(
            "the service is installed from {installed_from}; its login keychain is read only in \
             its own account"
        ));
    }
    let sign_in = || {
        format!(
            "{}{} (sign in again with the service binary; never switch to --start-at boot for \
             this)",
            super::update::force::auth_command_line(
                setup.data_root.as_deref(),
                StartMode::Login,
                &service.binary
            ),
            runner_manager_platform::service::MACOS_LOGIN_PLACE
        )
    };
    if setup.service_credential_unreadable {
        return fail(
            "the service recorded that it cannot read its stored GitHub credential, so it starts \
             no runner",
        )
        .remedy(sign_in());
    }
    if let Some(age) = setup
        .service_contact_age_secs
        .filter(|age| *age <= RECENT_CONTACT_SECS)
    {
        return pass(format!(
            "the service binary now installed reached GitHub {} minute(s) ago, so it reads its \
             credential",
            age / 60
        ));
    }
    match facts.service_credential(&service.binary, setup.data_root.as_deref()) {
        Ok(CredentialProbe::Readable) => {
            pass("the service binary reads its GitHub credential from the login keychain")
        }
        Ok(CredentialProbe::Absent) => not_applicable(
            "no GitHub credential is stored yet (`runner-manager auth login --start-at login`)",
        ),
        // If this process cannot read it either, the session is the problem
        // (an SSH session cannot unlock the login keychain), not the service
        // binary's grant.
        Ok(CredentialProbe::Unreadable(_)) if setup.own_keychain_readable != Some(true) => unknown(
            "this session cannot read the login keychain at all (an SSH session cannot unlock \
                 it), so the service binary's own access cannot be told apart; run `runner-manager \
                 host doctor` in a Terminal on this Mac",
        ),
        Ok(CredentialProbe::Unreadable(reason)) => fail(format!(
            "the service binary {} cannot read its GitHub credential ({reason}). The login \
             keychain ties an item to the exact build that wrote it; the daemon hands the \
             credential to the new build when it updates, so this is an item written by a build \
             that did not: the first update to 0.4.34 or later, or a binary replaced by hand",
            service.binary.display()
        ))
        .remedy(sign_in()),
        Err(error) => unknown(format!("the service binary could not be asked: {error}")),
    }
}

// -- host.runner_root_responsive ----------------------------------------------

/// How long a runner root has to answer a `stat` and a one-entry listing.
pub const RUNNER_ROOT_DEADLINE: Duration = Duration::from_secs(5);

/// A hung volume under a runner root -- seen on the Mac mini, whose external
/// `/Volumes/NVME` stopped answering `ls` -- wedges every runner placed there
/// and leaves a slot held by an attempt with no process. Required, so the
/// daemon registers no runner while it lasts.
fn probe_runner_root_responsive(setup: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    if setup.runner_roots.is_empty() {
        return not_applicable("no runner root could be resolved");
    }
    let mut hung = Vec::new();
    let mut asking = Vec::new();
    let mut refused = Vec::new();
    let mut errors = Vec::new();
    for root in &setup.runner_roots {
        let privacy_protected = setup.os == HostOs::Macos && is_privacy_protected_volume(root);
        match facts.directory_responds(root) {
            host_fitness::Responsiveness::Responds => {}
            host_fitness::Responsiveness::ListingBlocked if privacy_protected => {
                asking.push(root.display().to_string());
            }
            host_fitness::Responsiveness::NotPermitted(_) if privacy_protected => {
                refused.push(root.display().to_string());
            }
            host_fitness::Responsiveness::Hung | host_fitness::Responsiveness::ListingBlocked => {
                hung.push(root.display().to_string());
            }
            host_fitness::Responsiveness::NotPermitted(error)
            | host_fitness::Responsiveness::Failed(error) => {
                errors.push(format!("{}: {error}", root.display()));
            }
        }
    }
    if !asking.is_empty() {
        return fail(format!(
            "macOS has not let the service list {}: listing it waits, which is what a pending \
             privacy question looks like (\"would like to access files on a removable volume\", \
             or on a network volume). Nothing starts there until somebody answers it",
            asking.join(", ")
        ))
        .remedy(format!(
            "{PRIVACY_PROMPT_REMEDY}; if no dialog is showing, check the volume"
        ));
    }
    if !refused.is_empty() {
        return fail(format!(
            "macOS refuses to let the service list {} (Operation not permitted): its access to \
             files on that volume was turned down",
            refused.join(", ")
        ))
        .remedy(PRIVACY_REFUSED_REMEDY);
    }
    if !hung.is_empty() {
        return fail(format!(
            "runner root not responding: {} did not answer within {} seconds, so a runner \
             placed there would hang",
            hung.join(", "),
            RUNNER_ROOT_DEADLINE.as_secs()
        ))
        .remedy("check the volume holding it (a stalled external disk or network mount); a reboot or reconnect usually clears it");
    }
    if !errors.is_empty() {
        return unknown(format!(
            "a runner root could not be read: {}",
            errors.join("; ")
        ));
    }
    pass("every runner root answers")
}

/// Folders macOS guards behind a privacy question: every other volume, under
/// `/Volumes`. The startup volume's own folders are not asked about.
fn is_privacy_protected_volume(root: &Path) -> bool {
    root.starts_with("/Volumes")
}

/// What to click when the question is on the desktop.
const PRIVACY_PROMPT_REMEDY: &str = "at this Mac's desktop, click Allow on the dialog asking \
     whether runner-manager may access files on a removable (or network) volume. macOS asks \
     again after every runner-manager update, because it ties the answer to the exact build";

/// What to turn on when the question was answered no.
const PRIVACY_REFUSED_REMEDY: &str = "System Settings > Privacy & Security > Files & Folders > \
     runner-manager: turn on Removable Volumes (or Network Volumes); the service checks again \
     within five minutes";

// -- host.capacity ------------------------------------------------------------

/// About [`MEMORY_PER_RUNNER_GIB`] of memory and one core per concurrent job.
#[must_use]
pub fn recommended_capacity(memory_bytes: u64, cores: usize) -> u16 {
    let by_memory = memory_bytes / GIB / MEMORY_PER_RUNNER_GIB;
    let by_cores = u64::try_from(cores).unwrap_or(u64::MAX);
    u16::try_from(by_memory.min(by_cores).max(1)).unwrap_or(u16::MAX)
}

fn probe_capacity(setup: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    let Some(memory) = facts.memory_bytes() else {
        return unknown("this machine's memory could not be read");
    };
    let cores = facts.cpu_count();
    let recommended = recommended_capacity(memory, cores);
    let machine = format!("{} GiB of memory and {cores} cores", memory / GIB);
    if setup.capacity <= recommended {
        return pass(format!(
            "capacity {} on {machine} (up to {recommended} fits)",
            setup.capacity
        ));
    }
    fail(format!(
        "capacity {} on {machine}; at about {MEMORY_PER_RUNNER_GIB} GiB and one core per \
         concurrent job, {recommended} is what fits without memory pressure (other runners on \
         this machine need room too)",
        setup.capacity
    ))
    .remedy(format!("runner-manager host set-capacity {recommended}"))
}

// -- host.launches ------------------------------------------------------------

fn probe_launches(setup: &HostSetup, _facts: &dyn HostFacts) -> Outcome {
    match &setup.launches_blocked {
        None => pass("no blocked launches recorded"),
        Some(blocked) => fail(format!("the service has started no runner {blocked}"))
            .remedy(blocked.remedy.clone()),
    }
}

// -- host.required_tools ------------------------------------------------------

fn probe_required_tools(setup: &HostSetup, facts: &dyn HostFacts) -> Outcome {
    if let Some(error) = &setup.required_tools_error {
        return unknown(format!("the required tools could not be read: {error}"))
            .remedy("runner-manager host required-tools --set <TOOLS> (rewrites the file)");
    }
    if setup.required_tools.is_empty() {
        return not_applicable(
            "no required tools are configured (runner-manager host required-tools --set git,node)",
        );
    }
    let missing: Vec<&str> = setup
        .required_tools
        .iter()
        .filter(|tool| {
            facts
                .find_tool(tool, setup.runner_path.as_deref())
                .is_none()
        })
        .map(String::as_str)
        .collect();
    if missing.is_empty() {
        return pass(format!(
            "found on the runners' PATH: {}",
            setup.required_tools.join(", ")
        ));
    }
    fail(format!("not on the runners' PATH: {}", missing.join(", ")))
        .remedy("install them, or add their directory with `runner-manager host env set PATH=...`")
}

// ---------------------------------------------------------------------------
// The report
// ---------------------------------------------------------------------------

/// What a fix would do, as the report shows it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FixView {
    pub action: &'static str,
    pub needs_admin: bool,
    /// The flag that consents to it, when it lowers security.
    pub consent_flag: Option<&'static str>,
    pub revert: String,
}

/// One evaluated check.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Finding {
    pub id: &'static str,
    pub title: &'static str,
    pub platform: CheckPlatform,
    pub severity: Severity,
    pub status: Status,
    pub detail: String,
    /// `null` when there is no automatic fix, or it cannot help here.
    pub fix: Option<FixView>,
    pub remedy: Option<String>,
}

impl Finding {
    /// Failing or unknown, with an automatic fix that can help.
    fn wants_fix(&self) -> bool {
        matches!(self.status, Status::Fail | Status::Unknown) && self.fix.is_some()
    }

    /// Failing, and not merely informational.
    #[must_use]
    pub fn needs_attention(&self) -> bool {
        self.status == Status::Fail && self.severity != Severity::Info
    }
}

/// The `host doctor --json` document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Report {
    pub schema_version: u32,
    pub os: HostOs,
    pub perspective: Perspective,
    pub elevated: bool,
    /// The other installation the machine's service belongs to, when it is
    /// not this account's: the service checks judge that registration, while
    /// the runner roots and tools checked are this account's configuration.
    /// Absent when the service is this account's or there is none.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_installed_from: Option<String>,
    pub findings: Vec<Finding>,
}

impl Report {
    /// The ids of the required checks that fail. Unknown never counts.
    #[must_use]
    pub fn required_failing(&self) -> Vec<String> {
        self.with(Severity::Required, Status::Fail)
            .map(|finding| finding.id.to_owned())
            .collect()
    }

    /// The findings of one severity in one status.
    fn with(&self, severity: Severity, status: Status) -> impl Iterator<Item = &Finding> {
        self.findings
            .iter()
            .filter(move |finding| finding.severity == severity && finding.status == status)
    }
}

impl Finding {
    /// `id  status (severity): detail`, the line every report prints.
    fn line(&self, width: usize) -> String {
        format!(
            "{:<width$}  {} ({}): {}",
            self.id,
            self.status.as_str(),
            self.severity.as_str(),
            self.detail
        )
    }
}

/// Evaluates every check that applies to `setup.os`.
#[must_use]
pub fn evaluate(setup: &HostSetup, facts: &dyn HostFacts) -> Report {
    let findings = CHECKS
        .iter()
        .filter(|check| check.platform.includes(setup.os))
        .map(|check| {
            let outcome = daemon_view(setup, check.id, (check.probe)(setup, facts));
            Finding {
                id: check.id,
                title: check.title,
                platform: check.platform,
                severity: check.severity,
                status: outcome.status,
                detail: outcome.detail,
                fix: check
                    .fix
                    .as_ref()
                    .filter(|_| outcome.fixable)
                    .map(|fix| FixView {
                        action: fix.action,
                        needs_admin: fix.needs_admin,
                        consent_flag: fix.consent_flag,
                        revert: format!("runner-manager host prepare --revert {}", check.id),
                    }),
                remedy: outcome.remedy,
            }
        })
        .collect();
    Report {
        schema_version: REPORT_SCHEMA_VERSION,
        os: setup.os,
        perspective: setup.perspective,
        elevated: facts.elevated(),
        service_installed_from: setup
            .service
            .as_ref()
            .and_then(|service| service.installed_from.clone()),
        findings,
    }
}

/// A required check the running daemon finds failing fails here too, whatever
/// this command's own probe says.
///
/// The two can disagree, and the daemon is the one that matters: it is the
/// account and the session runners inherit. Over SSH on a Mac, the daemon in
/// the desktop session was waiting on a privacy question about the runner
/// root's volume and starting no runner, while `host doctor` in the SSH
/// session listed the same root and reported it passing.
fn daemon_view(setup: &HostSetup, id: &str, outcome: Outcome) -> Outcome {
    if setup.perspective != Perspective::Operator || outcome.status == Status::Fail {
        return outcome;
    }
    let Some(unfit) = &setup.daemon_unfit else {
        return outcome;
    };
    if !unfit.checks.iter().any(|failing| failing == id) {
        return outcome;
    }
    let found = unfit.findings.iter().find(|finding| finding.id == id);
    let failed = fail(format!(
        "the service finds this failing from its own session, and starts no runner until it \
         passes{}; this command's own look found: {}",
        found.map_or_else(String::new, |finding| format!(": {}", finding.detail)),
        outcome.detail
    ));
    match found
        .and_then(|finding| finding.remedy.clone())
        .or(outcome.remedy)
    {
        Some(remedy) => failed.remedy(remedy),
        None => failed,
    }
}

/// The plain report `host doctor` prints.
fn write_report(out: &mut dyn Write, report: &Report) -> io::Result<()> {
    let os = match report.os {
        HostOs::Windows => "windows",
        HostOs::Macos => "macos",
        HostOs::Linux => "linux",
    };
    let view = match report.perspective {
        Perspective::Operator => "operator view",
        Perspective::Daemon => "daemon view",
    };
    let elevated = if report.elevated {
        "elevated"
    } else {
        "not elevated"
    };
    writeln!(out, "Host doctor ({os}, {view}, {elevated})")?;
    if let Some(installed_from) = &report.service_installed_from {
        writeln!(
            out,
            "  This machine's service is installed from {installed_from}, another \
             installation's. The service checks below judge that registration; the runner roots \
             and tools are this account's own configuration, which it does not run."
        )?;
    }
    let widest = report
        .findings
        .iter()
        .map(|finding| finding.id.len())
        .max()
        .unwrap_or(0);
    for finding in &report.findings {
        writeln!(out, "  {}", finding.line(widest))?;
        if finding.status == Status::Pass || finding.status == Status::NotApplicable {
            continue;
        }
        if let Some(fix) = &finding.fix {
            let mut conditions = Vec::new();
            if fix.needs_admin {
                conditions.push("administrator rights".to_owned());
            }
            if let Some(flag) = fix.consent_flag {
                conditions.push(format!("lowers security, needs {flag}"));
            }
            let conditions = if conditions.is_empty() {
                String::new()
            } else {
                format!(" [{}]", conditions.join("; "))
            };
            writeln!(out, "      fix: {}{conditions}", fix.action)?;
        }
        if let Some(remedy) = &finding.remedy {
            writeln!(
                out,
                "      {}: {remedy}",
                if finding.fix.is_some() { "or" } else { "do" }
            )?;
        }
    }
    writeln!(out)?;
    writeln!(out, "Summary")?;
    for severity in [Severity::Required, Severity::Recommended] {
        writeln!(
            out,
            "  {:<12}{} failing, {} unknown",
            severity.as_str(),
            report.with(severity, Status::Fail).count(),
            report.with(severity, Status::Unknown).count()
        )?;
    }
    let fixable = report.findings.iter().filter(|f| f.wants_fix()).count();
    let next = if fixable == 0 {
        "nothing `host prepare` can fix".to_owned()
    } else {
        format!(
            "runner-manager host prepare (fixes {fixable}; asks for administrator rights once if needed)"
        )
    };
    writeln!(out, "  {:<12}{next}", "next")
}

// ---------------------------------------------------------------------------
// The setup, from this host's configuration
// ---------------------------------------------------------------------------

#[derive(Debug, Default, Serialize, Deserialize)]
struct RequiredToolsFile {
    schema_version: u32,
    tools: Vec<String>,
}

const REQUIRED_TOOLS_SCHEMA_VERSION: u32 = 1;

fn required_tools_path(context: &Context) -> PathBuf {
    context.paths().config_dir().join(REQUIRED_TOOLS_FILE)
}

/// The configured required tools; empty when none are.
///
/// # Errors
/// [`Failure::LocalState`] when the file exists and cannot be read.
pub fn required_tools(context: &Context) -> Result<Vec<String>, CliError> {
    read_json_or(&required_tools_path(context), RequiredToolsFile::default).map(|file| file.tools)
}

fn validate_tool(tool: &str) -> Result<(), CliError> {
    let valid = !tool.is_empty()
        && tool.len() <= 64
        && tool
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '+'));
    if valid {
        Ok(())
    } else {
        Err(CliError::with_remedy(
            Failure::InvalidArgument,
            format!(
                "{tool:?} is not a tool name: use the bare command name, such as `git` or `pwsh`, \
                 with no path"
            ),
            "runner-manager host required-tools --set git,pwsh,node",
        ))
    }
}

/// `PATH` as a boot service on this platform inherits it, before runner
/// defaults and `runner.env` are applied.
fn service_inherited_path(os: HostOs, mode: Option<StartMode>) -> Option<OsString> {
    match (os, mode) {
        (HostOs::Windows, Some(StartMode::Boot)) => {
            let (subkey, value) = RegValue::MachinePath.location();
            host_fitness::read_registry_string(subkey, value)
                .ok()
                .flatten()
                .map(|path| OsString::from(expand_environment(&path)))
                .or_else(|| std::env::var_os("PATH"))
        }
        (HostOs::Macos, Some(_)) => Some(OsString::from(runner_env::MACOS_SYSTEM_PATH)),
        (HostOs::Linux, Some(_)) => Some(OsString::from(SYSTEMD_DEFAULT_PATH)),
        _ => std::env::var_os("PATH"),
    }
}

/// The `PATH` a native runner starts with: `runner.env`'s, else the platform
/// defaults over what the daemon inherits.
fn runner_path(
    context: &Context,
    perspective: Perspective,
    mode: Option<StartMode>,
) -> Option<String> {
    let file =
        RunnerEnv::load(&runner_env::path_in(context.paths().config_dir())).unwrap_or_default();
    if let Some(path) = file.get("PATH") {
        return Some(path.to_owned());
    }
    let inherited = match perspective {
        Perspective::Daemon => std::env::var_os("PATH"),
        Perspective::Operator => service_inherited_path(HostOs::current(), mode),
    };
    let defaults = runner_env::platform_defaults(
        RunnerPlatform::current(),
        Path::new(""),
        &Inherited {
            path: inherited.clone(),
            has_locale: true,
            ..Inherited::default()
        },
        Path::exists,
    );
    defaults
        .into_iter()
        .find(|(name, _)| *name == "PATH")
        .map(|(_, value)| value)
        .or(inherited)
        .map(|path| path.to_string_lossy().into_owned())
}

/// How long ago the daemon now installed reached GitHub, if it has.
///
/// The contact file is written by whichever daemon ran last. Straight after an
/// upgrade that is the *previous* binary, which kept reaching GitHub through
/// its drain -- so its contact said nothing about whether the new binary can
/// read the credential, and the keychain check passed while every start of the
/// new daemon failed with `-25293` (watched on the 0.4.33 rollout). A contact
/// counts only when it is newer than the moment the service binary was put in
/// place, which the old daemon cannot have reached.
fn current_daemon_contact_age(
    contact: Option<chrono::DateTime<chrono::Utc>>,
    binary_replaced_at: Option<chrono::DateTime<chrono::Utc>>,
    now: chrono::DateTime<chrono::Utc>,
) -> Option<u64> {
    let contact = contact?;
    if binary_replaced_at.is_some_and(|replaced| contact <= replaced) {
        return None;
    }
    u64::try_from((now - contact).num_seconds()).ok()
}

/// How long ago the installed service last reached GitHub, counted only when
/// the binary installed now made that contact. See
/// [`current_daemon_contact_age`].
pub(crate) fn installed_service_contact_age(context: &Context) -> Option<u64> {
    let binary = InstallRecord::read(context.paths()).ok().flatten()?.binary;
    service_contact_age(context.paths(), context.clock().now(), Some(&binary))
}

/// [`current_daemon_contact_age`] for the service binary at `binary`, whose
/// daemon writes its contact under `paths`.
fn service_contact_age(
    paths: &runner_manager_platform::paths::AppPaths,
    now: chrono::DateTime<chrono::Utc>,
    binary: Option<&Path>,
) -> Option<u64> {
    current_daemon_contact_age(
        runner_manager_platform::service::last_github_contact(paths)
            .ok()
            .flatten(),
        binary.and_then(replaced_at),
        now,
    )
}

/// When `binary` was put in place: its status-change time, which a copy or a
/// rename sets and nothing can set back (a copy may keep the source's
/// modification time). The modification time where there is no such field.
fn replaced_at(binary: &Path) -> Option<chrono::DateTime<chrono::Utc>> {
    let metadata = std::fs::metadata(binary).ok()?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt as _;
        let nanos = u32::try_from(metadata.ctime_nsec()).unwrap_or(0);
        chrono::DateTime::from_timestamp(metadata.ctime(), nanos)
    }
    #[cfg(not(unix))]
    {
        metadata.modified().ok().map(chrono::DateTime::from)
    }
}

/// The installed service, as the checks judge it.
///
/// This account's own install record, and from the operator's view whether
/// the service manager reports it running -- unless the machine's service is
/// another installation's, when it is that registration: an earlier login
/// install's record left in this account's directories used to fail
/// `windows.execution_account` with a `service install --start-at boot`
/// remedy on a machine whose boot service was healthy.
fn installed_service(context: &Context, perspective: Perspective) -> Option<ServiceSetup> {
    let label = super::service::identity().launchd_label();
    let status = (perspective == Perspective::Operator)
        .then(|| super::service::operations(context).status().ok())
        .flatten();
    if let Some(status) = &status
        && let Some(foreign) = status.foreign()
    {
        return Some(ServiceSetup {
            start_mode: status.start_mode()?,
            binary: status.service_binary()?,
            definition_path: status
                .record()
                .and_then(|record| record.definition_path.clone()),
            label,
            running: Some(status.is_running()),
            installed_from: Some(foreign.installed_by()),
            foreign_directories: Some(foreign.directories.clone()),
        });
    }
    InstallRecord::read(context.paths())
        .ok()
        .flatten()
        .map(|record| ServiceSetup {
            start_mode: record.start_mode,
            binary: record.binary,
            definition_path: record.definition_path,
            label,
            running: status.as_ref().map(ServiceStatus::is_running),
            installed_from: None,
            foreign_directories: None,
        })
}

/// Builds the setup from values the caller has already read.
///
/// `service` overrides the installed registration; `service install` passes
/// the one it is about to make, because that is the account runners will use.
fn setup_from_parts(
    context: &Context,
    perspective: Perspective,
    host: Option<&Host>,
    policies: &[ScalePolicy],
    runner_root: &HostRoot,
    service: Option<ServiceSetup>,
) -> HostSetup {
    let service = service.or_else(|| installed_service(context, perspective));
    let mut runner_roots: Vec<PathBuf> = runner_root
        .effective
        .iter()
        .map(|root| PathBuf::from(root.as_str()))
        .collect();
    for policy in policies {
        if let Some(root) = policy.workspace_policy().root() {
            let root = PathBuf::from(root.as_str());
            if !runner_roots.contains(&root) {
                runner_roots.push(root);
            }
        }
    }
    // Jobs read and write the dependency-cache root as much as their own
    // workspace, so it gets the same Defender, Spotlight and responsiveness
    // checks, and `host prepare` excludes it with the runner roots. Only when it
    // exists and no runner root already contains it, which the default
    // (`<runner root>/_cache`) always is.
    if let Some(cache_root) = super::cache::active_root(context, host)
        && cache_root.is_dir()
        && !runner_roots.iter().any(|root| cache_root.starts_with(root))
    {
        runner_roots.push(cache_root);
    }
    // What the service recorded is read where it runs: another installation's
    // directories when it is one, as far as this account may read them.
    let service_paths = service
        .as_ref()
        .and_then(|service| service.foreign_directories.as_ref())
        .map_or_else(|| context.paths().clone(), ServiceDirectories::paths);
    let mode = service.as_ref().map(|service| service.start_mode);
    let (service_account, service_home) = service_account_and_home(perspective, mode);
    let (required_tools, required_tools_error) = match required_tools(context) {
        Ok(tools) => (tools, None),
        Err(error) => (Vec::new(), Some(error.to_string())),
    };
    HostSetup {
        os: HostOs::current(),
        perspective,
        runner_roots,
        capacity: host.map_or(super::DEFAULT_HOST_CAPACITY, Host::host_capacity),
        required_tools,
        required_tools_error,
        runner_path: runner_path(context, perspective, mode),
        probe_dir: context.paths().state_dir().to_path_buf(),
        data_root: context.data_root.clone(),
        service_contact_age_secs: service_contact_age(
            &service_paths,
            context.clock().now(),
            service.as_ref().map(|service| service.binary.as_path()),
        ),
        service_credential_unreadable:
            runner_manager_platform::service::credential_unreadable_since(&service_paths)
                .is_ok_and(|since| since.is_some()),
        own_keychain_readable: (HostOs::current() == HostOs::Macos
            && perspective == Perspective::Operator
            && mode == Some(StartMode::Login))
        .then(|| {
            context
                .secret_store(StartMode::Login)
                .is_ok_and(|store| store.load().is_ok())
        }),
        launches_blocked: runner_manager_platform::launch_health::launches_blocked(
            &service_paths,
            context.clock().now(),
        ),
        service_account,
        service_home,
        daemon_unfit: (perspective == Perspective::Operator)
            .then(|| host_fitness::host_unfit_in_force(&service_paths, context.clock().now()))
            .flatten(),
        polling: runner_manager_platform::polling::idle_interval(&service_paths)
            .ok()
            .map(|idle| {
                let traffic = runner_manager_platform::polling::last_traffic(&service_paths)
                    .ok()
                    .flatten();
                let now = context.clock().now();
                PollingFacts {
                    idle_secs: idle.as_secs(),
                    active_secs: host.map_or(
                        runner_manager_domain::model::RefreshInterval::DEFAULT_SECS,
                        |host| host.refresh_interval.as_secs(),
                    ),
                    stale: traffic.as_ref().is_some_and(|traffic| {
                        super::polling::is_stale(&service_paths, traffic.written_at, now)
                    }),
                    traffic,
                }
            }),
        service,
    }
}

/// The account the service runs as on macOS, and its home folder: root's for
/// a boot service seen by an operator, and otherwise this process's own (a
/// login service runs as the account that installed it, and the daemon is the
/// service). `(None, None)` elsewhere, where nothing reads them.
fn service_account_and_home(
    perspective: Perspective,
    mode: Option<StartMode>,
) -> (Option<String>, Option<PathBuf>) {
    if HostOs::current() != HostOs::Macos {
        return (None, None);
    }
    if perspective == Perspective::Operator && mode == Some(StartMode::Boot) {
        return (
            Some(ServiceAccount::Root.as_str().to_owned()),
            Some(PathBuf::from("/var/root")),
        );
    }
    (
        Some(service_account_name(&ServiceAccount::InvokingUser)),
        runner_manager_platform::service::host_home(),
    )
}

/// Builds the setup by reading this host's configuration.
///
/// # Errors
/// [`Failure::LocalState`] when the database cannot be read.
pub fn setup(
    context: &Context,
    perspective: Perspective,
    service: Option<ServiceSetup>,
) -> Result<HostSetup, CliError> {
    let store = context.store()?;
    let host = super::host::local_host(&store)?;
    let policies = store.policies().map_err(|source| {
        CliError::new(
            Failure::LocalState,
            format!("cannot read this host's policies: {source}"),
        )
    })?;
    let root = workspace::host_root(context.paths(), host.as_ref());
    Ok(setup_from_parts(
        context,
        perspective,
        host.as_ref(),
        &policies,
        &root,
        service,
    ))
}

// ---------------------------------------------------------------------------
// The real facts and actions
// ---------------------------------------------------------------------------

/// [`HostFacts`] read from this machine.
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemFacts;

fn run_capture(program: &Path, args: &[&str]) -> Result<std::process::Output, String> {
    std::process::Command::new(program)
        .args(args)
        .stdin(std::process::Stdio::null())
        .output()
        .map_err(|error| format!("{} could not be started: {error}", program.display()))
}

#[cfg(windows)]
fn windows_powershell() -> PathBuf {
    host_fitness::system_directory()
        .map_or_else(|_| PathBuf::from(r"C:\Windows\System32"), PathBuf::from)
        .join(r"WindowsPowerShell\v1.0\powershell.exe")
}

#[cfg(windows)]
fn run_windows_powershell(script: &str) -> Result<(), String> {
    let encoded: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
    let output = std::process::Command::new(windows_powershell())
        .args([
            "-NoProfile",
            "-NonInteractive",
            "-ExecutionPolicy",
            "Bypass",
            "-EncodedCommand",
            &crate::tui::shell::base64(&encoded),
        ])
        .stdin(std::process::Stdio::null())
        .output()
        .map_err(|error| format!("Windows PowerShell could not be started: {error}"))?;
    if output.status.success() {
        Ok(())
    } else {
        Err(format!(
            "Windows PowerShell failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        ))
    }
}

/// A PowerShell array literal of single-quoted strings.
#[cfg(any(windows, test))]
fn powershell_list(paths: &[String]) -> String {
    let quoted: Vec<String> = paths
        .iter()
        .map(|path| format!("'{}'", path.replace('\'', "''")))
        .collect();
    format!("@({})", quoted.join(","))
}

impl HostFacts for SystemFacts {
    fn elevated(&self) -> bool {
        host_fitness::is_elevated()
    }

    fn dword(&self, value: RegValue) -> Result<Option<u32>, String> {
        let (subkey, name) = value.location();
        host_fitness::read_registry_dword(subkey, name).map_err(|error| error.to_string())
    }

    fn string(&self, value: RegValue) -> Result<Option<String>, String> {
        let (subkey, name) = value.location();
        host_fitness::read_registry_string(subkey, name).map_err(|error| error.to_string())
    }

    fn defender_exclusions(&self) -> Result<Option<Vec<String>>, String> {
        match host_fitness::registry_value_names(
            r"SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths",
        ) {
            Ok(names) => Ok(Some(names)),
            Err(host_fitness::RegistryError::AccessDenied) => Ok(None),
            Err(error) => Err(error.to_string()),
        }
    }

    fn git_system_value(&self, git: &Path, name: &str) -> Result<Option<String>, String> {
        let output = run_capture(git, &["config", "--system", "--get", name])?;
        match output.status.code() {
            Some(0) => Ok(Some(
                String::from_utf8_lossy(&output.stdout).trim().to_owned(),
            )),
            // 1: the key is not set.
            Some(1) => Ok(None),
            _ => Err(String::from_utf8_lossy(&output.stderr).trim().to_owned()),
        }
    }

    fn symlink_allowed(&self, directory: &Path) -> Result<bool, String> {
        host_fitness::can_create_symlink(directory).map_err(|error| error.to_string())
    }

    fn find_tool(&self, tool: &str, path: Option<&str>) -> Option<PathBuf> {
        host_fitness::find_on_path(tool, &OsString::from(path?))
    }

    fn file_exists(&self, path: &Path) -> bool {
        path.is_file()
    }

    fn memory_bytes(&self) -> Option<u64> {
        host_fitness::physical_memory_bytes()
    }

    fn cpu_count(&self) -> usize {
        std::thread::available_parallelism().map_or(1, std::num::NonZero::get)
    }

    fn power_settings(&self) -> Result<Option<BTreeMap<String, u32>>, String> {
        if !cfg!(target_os = "macos") {
            return Ok(None);
        }
        let output = run_capture(Path::new("/usr/bin/pmset"), &["-g"])?;
        if !output.status.success() {
            return Err(String::from_utf8_lossy(&output.stderr).trim().to_owned());
        }
        Ok(Some(power_settings_in(&String::from_utf8_lossy(
            &output.stdout,
        ))))
    }

    fn unattended_login(&self) -> Option<UnattendedLogin> {
        unattended_login::probe()
    }

    fn spotlight_indexing(&self, volume: &Path) -> Result<Option<bool>, String> {
        let output = run_capture(
            Path::new("/usr/bin/mdutil"),
            &["-s", &volume.to_string_lossy()],
        )?;
        let text = String::from_utf8_lossy(&output.stdout).to_ascii_lowercase();
        Ok(if text.contains("indexing enabled") {
            Some(true)
        } else if text.contains("indexing disabled")
            || text.contains("indexing and searching disabled")
        {
            Some(false)
        } else {
            None
        })
    }

    fn directory_responds(&self, directory: &Path) -> host_fitness::Responsiveness {
        host_fitness::directory_responds(directory, RUNNER_ROOT_DEADLINE)
    }

    fn mount_point(&self, path: &Path) -> Option<PathBuf> {
        let existing = path.ancestors().find(|ancestor| ancestor.exists())?;
        let output =
            run_capture(Path::new("/bin/df"), &["-P", &existing.to_string_lossy()]).ok()?;
        let text = String::from_utf8_lossy(&output.stdout);
        let line = text.lines().nth(1)?;
        // `df -P`'s sixth column; a mount point may contain spaces, so it is
        // everything after the fifth.
        let mount = line
            .split_whitespace()
            .skip(5)
            .collect::<Vec<_>>()
            .join(" ");
        (!mount.is_empty()).then(|| PathBuf::from(mount))
    }

    fn launchd_process_type(&self, plist: &Path) -> Result<Option<String>, String> {
        let text = std::fs::read_to_string(plist).map_err(|error| error.to_string())?;
        Ok(plist_string_value(&text, "ProcessType"))
    }

    fn throttled_runner_processes(&self) -> Result<usize, String> {
        let output = run_capture(Path::new("/bin/ps"), &["-axo", "pri=,comm="])?;
        Ok(throttled_runners_in(&String::from_utf8_lossy(
            &output.stdout,
        )))
    }

    fn service_credential(
        &self,
        binary: &Path,
        data_root: Option<&Path>,
    ) -> Result<CredentialProbe, String> {
        let mut command = std::process::Command::new(binary);
        if let Some(root) = data_root {
            command.arg("--data-dir").arg(root);
        }
        command
            .args(["status", "--json"])
            .env(SKIP_DOCTOR_VARIABLE, "1")
            .stdin(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .stdout(std::process::Stdio::piped());
        let mut child = command
            .spawn()
            .map_err(|error| format!("{} could not be started: {error}", binary.display()))?;
        // Read on a thread so a large document can never fill the pipe and
        // stall the child, and so the answer is taken the moment it is ready.
        let mut stdout = child.stdout.take().ok_or("the child had no stdout")?;
        let (sender, receiver) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let mut bytes = Vec::new();
            let _ = sender.send(io::Read::read_to_end(&mut stdout, &mut bytes).map(|_| bytes));
        });
        let Ok(read) = receiver.recv_timeout(Duration::from_secs(20)) else {
            let _ = child.kill();
            let _ = child.wait();
            return Err("it did not answer within 20 seconds".into());
        };
        let _ = child.wait();
        let bytes = read.map_err(|error| error.to_string())?;
        let document: serde_json::Value = serde_json::from_slice(&bytes)
            .map_err(|error| format!("its status document did not parse: {error}"))?;
        let credential = &document["credential"];
        Ok(match credential["unreadable"].as_str() {
            Some(reason) => CredentialProbe::Unreadable(reason.to_owned()),
            None if credential["present"].as_bool() == Some(true) => CredentialProbe::Readable,
            None => CredentialProbe::Absent,
        })
    }
}

/// Runner processes in `ps -axo pri=,comm=` output at background priority.
fn throttled_runners_in(listing: &str) -> usize {
    listing
        .lines()
        .filter_map(|line| {
            let line = line.trim_start();
            let (priority, command) = line.split_once(char::is_whitespace)?;
            Some((priority.parse::<i32>().ok()?, command.trim()))
        })
        .filter(|(priority, command)| {
            *priority <= 4
                && (command.ends_with("Runner.Listener") || command.ends_with("Runner.Worker"))
        })
        .count()
}

/// [`HostActions`] carried out on this machine.
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemActions;

impl HostActions for SystemActions {
    fn set_dword(&self, value: RegValue, data: Option<u32>) -> Result<(), String> {
        if !value.writable() {
            return Err(format!("{value:?} is not a value host prepare writes"));
        }
        let (subkey, name) = value.location();
        host_fitness::write_registry_dword(subkey, name, data).map_err(|error| error.to_string())
    }

    fn set_string(&self, value: RegValue, data: Option<&str>) -> Result<(), String> {
        if !value.writable() {
            return Err(format!("{value:?} is not a value host prepare writes"));
        }
        let (subkey, name) = value.location();
        host_fitness::write_registry_string(subkey, name, data).map_err(|error| error.to_string())
    }

    fn set_git_system_value(
        &self,
        git: &Path,
        name: &str,
        value: Option<&str>,
    ) -> Result<(), String> {
        let output = match value {
            Some(value) => run_capture(git, &["config", "--system", name, value])?,
            None => run_capture(git, &["config", "--system", "--unset", name])?,
        };
        // `--unset` of a key that is not set exits 5; that is the goal state.
        if output.status.success() || (value.is_none() && output.status.code() == Some(5)) {
            Ok(())
        } else {
            Err(String::from_utf8_lossy(&output.stderr).trim().to_owned())
        }
    }

    #[cfg(windows)]
    fn add_defender_exclusions(&self, paths: &[String]) -> Result<(), String> {
        run_windows_powershell(&format!(
            "$ErrorActionPreference='Stop'; Add-MpPreference -ExclusionPath {}",
            powershell_list(paths)
        ))
    }

    #[cfg(windows)]
    fn remove_defender_exclusions(&self, paths: &[String]) -> Result<(), String> {
        run_windows_powershell(&format!(
            "$ErrorActionPreference='Stop'; Remove-MpPreference -ExclusionPath {}",
            powershell_list(paths)
        ))
    }

    #[cfg(not(windows))]
    fn add_defender_exclusions(&self, _: &[String]) -> Result<(), String> {
        Err("Defender exists only on Windows".into())
    }

    #[cfg(not(windows))]
    fn remove_defender_exclusions(&self, _: &[String]) -> Result<(), String> {
        Err("Defender exists only on Windows".into())
    }

    fn set_spotlight(&self, volume: &Path, enabled: bool) -> Result<(), String> {
        let flag = if enabled { "on" } else { "off" };
        let output = run_capture(
            Path::new("/usr/bin/mdutil"),
            &["-i", flag, &volume.to_string_lossy()],
        )?;
        if output.status.success() {
            Ok(())
        } else {
            Err(String::from_utf8_lossy(&output.stderr).trim().to_owned())
        }
    }

    fn set_power_setting(&self, name: &str, value: u32) -> Result<(), String> {
        if !POWER_SETTINGS.iter().any(|(known, _)| *known == name) {
            return Err(format!(
                "{name} is not a power setting `host prepare` changes"
            ));
        }
        let output = run_capture(
            Path::new("/usr/bin/pmset"),
            &["-a", name, &value.to_string()],
        )?;
        if output.status.success() {
            Ok(())
        } else {
            Err(String::from_utf8_lossy(&output.stderr).trim().to_owned())
        }
    }
}

// ---------------------------------------------------------------------------
// Applying fixes
// ---------------------------------------------------------------------------

/// How one fix (or revert) went.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub enum FixOutcome {
    Applied {
        changes: Vec<Change>,
    },
    /// The re-probe found nothing left to do.
    AlreadyDone,
    Reverted,
    Failed {
        error: String,
    },
    NotAttempted {
        reason: String,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FixResult {
    pub id: String,
    #[serde(flatten)]
    pub outcome: FixOutcome,
}

/// What the elevated copy is asked to do. Carried on its command line.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ElevatedRequest {
    pub setup: HostSetup,
    pub apply: Vec<String>,
    pub revert: Vec<(String, Vec<Change>)>,
}

/// Why no elevated copy reported back.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ElevationFailure {
    Refused,
    Unavailable(String),
    Failed(String),
}

impl ElevationFailure {
    pub(crate) fn reason(&self) -> String {
        match self {
            Self::Refused => "administrator rights were refused".to_owned(),
            Self::Unavailable(detail) => {
                format!("administrator rights could not be asked for: {detail}")
            }
            Self::Failed(detail) => format!("the elevated step failed: {detail}"),
        }
    }
}

/// Runs a request with administrator rights.
pub trait Elevator {
    fn elevate(&self, request: &ElevatedRequest) -> Result<Vec<FixResult>, ElevationFailure>;
}

/// Relaunches this binary through [`host_fitness::run_elevated`].
#[derive(Debug, Clone, Copy)]
pub struct SystemElevator {
    /// Whether a password may be asked for on this terminal (`sudo`); `false`
    /// uses the system dialog.
    pub terminal: bool,
}

impl Elevator for SystemElevator {
    fn elevate(&self, request: &ElevatedRequest) -> Result<Vec<FixResult>, ElevationFailure> {
        let plan = serde_json::to_string(request)
            .map_err(|error| ElevationFailure::Failed(error.to_string()))?;
        run_elevated_reporting(
            |result| {
                vec![
                    OsString::from("host"),
                    OsString::from("prepare"),
                    OsString::from("--elevated-request"),
                    OsString::from(plan),
                    OsString::from("--elevated-result"),
                    result.as_os_str().to_owned(),
                ]
            },
            self.terminal,
        )
    }
}

/// Runs one elevated copy of this binary with the arguments `args` builds
/// around the file it is to report into, waits for it, and reads that
/// report back. The elevated window is hidden, so the file is its only voice.
///
/// # Errors
/// [`ElevationFailure::Refused`] or [`ElevationFailure::Unavailable`] when no
/// elevated copy ran, and [`ElevationFailure::Failed`] when one ran and left
/// no readable report.
pub(crate) fn run_elevated_reporting<T: serde::de::DeserializeOwned>(
    args: impl FnOnce(&Path) -> Vec<OsString>,
    terminal: bool,
) -> Result<T, ElevationFailure> {
    let failed = |error: String| ElevationFailure::Failed(error);
    let program = std::env::current_exe().map_err(|error| failed(error.to_string()))?;
    let directory = tempfile::tempdir().map_err(|error| failed(error.to_string()))?;
    let result = directory.path().join("result.json");
    match host_fitness::run_elevated(&program, &args(&result), terminal) {
        ElevationOutcome::Refused => Err(ElevationFailure::Refused),
        ElevationOutcome::Unavailable(detail) => Err(ElevationFailure::Unavailable(detail)),
        ElevationOutcome::Exited(code) => {
            let text = std::fs::read_to_string(&result).map_err(|error| {
                failed(format!("it exited {code} and wrote no result ({error})"))
            })?;
            serde_json::from_str(&text).map_err(|error| failed(error.to_string()))
        }
    }
}

fn apply_one(
    id: &str,
    setup: &HostSetup,
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
) -> FixResult {
    let outcome = match check(id) {
        Some(CheckSpec {
            probe,
            fix: Some(fix),
            ..
        }) => {
            let before = probe(setup, facts);
            if matches!(before.status, Status::Pass | Status::NotApplicable) {
                FixOutcome::AlreadyDone
            } else {
                match (fix.apply)(setup, facts, actions) {
                    Ok(changes) if changes.is_empty() => FixOutcome::AlreadyDone,
                    Ok(changes) => FixOutcome::Applied { changes },
                    Err(error) => FixOutcome::Failed { error },
                }
            }
        }
        _ => FixOutcome::NotAttempted {
            reason: "no automatic fix exists for this check".into(),
        },
    };
    FixResult {
        id: id.to_owned(),
        outcome,
    }
}

fn revert_one(id: &str, changes: &[Change], actions: &dyn HostActions) -> FixResult {
    // Newest first, so a check that changed two things unwinds in order.
    let outcome = changes
        .iter()
        .rev()
        .try_for_each(|change| change.revert(actions))
        .map_or_else(
            |error| FixOutcome::Failed { error },
            |()| FixOutcome::Reverted,
        );
    FixResult {
        id: id.to_owned(),
        outcome,
    }
}

/// Carries out `request` in this process.
fn run_request(
    request: &ElevatedRequest,
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
) -> Vec<FixResult> {
    let mut results: Vec<FixResult> = request
        .apply
        .iter()
        .map(|id| apply_one(id, &request.setup, facts, actions))
        .collect();
    results.extend(
        request
            .revert
            .iter()
            .map(|(id, changes)| revert_one(id, changes, actions)),
    );
    results
}

/// Applies (or reverts) in-process what needs no elevation, and hands the rest
/// to one elevated run.
fn execute(
    request: ElevatedRequest,
    facts: &dyn HostFacts,
    actions: &dyn HostActions,
    elevator: &dyn Elevator,
) -> Vec<FixResult> {
    let elevated = facts.elevated();
    let (admin_apply, local_apply): (Vec<String>, Vec<String>) = request
        .apply
        .into_iter()
        .partition(|id| !elevated && fix_needs_admin(id));
    // Every kind of `Change` is a machine-wide setting, so undoing one needs
    // the same rights making it did.
    let (admin_revert, local_revert): (Vec<_>, Vec<_>) =
        request.revert.into_iter().partition(|_| !elevated);
    let mut results = run_request(
        &ElevatedRequest {
            setup: request.setup.clone(),
            apply: local_apply,
            revert: local_revert,
        },
        facts,
        actions,
    );
    if admin_apply.is_empty() && admin_revert.is_empty() {
        return results;
    }
    let ids: Vec<String> = admin_apply
        .iter()
        .cloned()
        .chain(admin_revert.iter().map(|(id, _)| id.clone()))
        .collect();
    let elevated_request = ElevatedRequest {
        setup: request.setup,
        apply: admin_apply,
        revert: admin_revert,
    };
    match elevator.elevate(&elevated_request) {
        Ok(reported) => {
            // Anything the elevated copy did not mention is reported as such
            // rather than silently dropped.
            for id in ids {
                match reported.iter().find(|result| result.id == id) {
                    Some(result) => results.push(result.clone()),
                    None => results.push(FixResult {
                        id,
                        outcome: FixOutcome::NotAttempted {
                            reason: "the elevated step did not report it".into(),
                        },
                    }),
                }
            }
        }
        Err(failure) => results.extend(ids.into_iter().map(|id| FixResult {
            id,
            outcome: FixOutcome::NotAttempted {
                reason: failure.reason(),
            },
        })),
    }
    results
}

// ---------------------------------------------------------------------------
// The journal
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
struct Journal {
    schema_version: u32,
    entries: BTreeMap<String, JournalEntry>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct JournalEntry {
    applied_at: Timestamp,
    by_version: String,
    changes: Vec<Change>,
}

fn journal_path(context: &Context) -> PathBuf {
    context.paths().config_dir().join(JOURNAL_FILE)
}

/// A JSON file under `config/`, or `missing()` when there is none.
fn read_json_or<T: serde::de::DeserializeOwned>(
    path: &Path,
    missing: impl FnOnce() -> T,
) -> Result<T, CliError> {
    match std::fs::read_to_string(path) {
        Ok(text) => serde_json::from_str(&text).map_err(|error| {
            CliError::new(
                Failure::LocalState,
                format!("{} is not valid: {error}", path.display()),
            )
        }),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(missing()),
        Err(error) => Err(CliError::new(
            Failure::LocalState,
            format!("cannot read {}: {error}", path.display()),
        )),
    }
}

fn write_json(path: &Path, value: &impl Serialize) -> Result<(), CliError> {
    serde_json::to_vec_pretty(value)
        .map_err(io::Error::other)
        .and_then(|bytes| host_fitness::write_atomically(path, &bytes))
        .map_err(|error| {
            CliError::new(
                Failure::LocalState,
                format!("cannot write {}: {error}", path.display()),
            )
        })
}

fn read_journal(path: &Path) -> Result<Journal, CliError> {
    read_json_or(path, || Journal {
        schema_version: JOURNAL_SCHEMA_VERSION,
        entries: BTreeMap::new(),
    })
}

/// Records applied changes and forgets reverted checks. A change already
/// recorded for the same thing keeps its original `previous` value, so a
/// revert always returns to the state before the first `prepare`.
fn update_journal(journal: &mut Journal, results: &[FixResult], now: Timestamp) {
    for result in results {
        match &result.outcome {
            FixOutcome::Applied { changes } => {
                let entry =
                    journal
                        .entries
                        .entry(result.id.clone())
                        .or_insert_with(|| JournalEntry {
                            applied_at: now,
                            by_version: env!("CARGO_PKG_VERSION").to_owned(),
                            changes: Vec::new(),
                        });
                for change in changes {
                    if !entry
                        .changes
                        .iter()
                        .any(|known| known.key() == change.key())
                    {
                        entry.changes.push(change.clone());
                    }
                }
            }
            FixOutcome::Reverted => {
                journal.entries.remove(&result.id);
            }
            _ => {}
        }
    }
}

// ---------------------------------------------------------------------------
// Asking the person
// ---------------------------------------------------------------------------

/// A yes/no question to the person running the command, when there is one.
pub trait Prompt {
    /// `None` when nobody can be asked.
    fn confirm(&mut self, question: &str) -> Option<bool>;
}

/// Nobody to ask: the daemon, the TUI's one-key fix, a script.
pub struct NoPrompt;

impl Prompt for NoPrompt {
    fn confirm(&mut self, _: &str) -> Option<bool> {
        None
    }
}

/// A terminal: the question on `err`, the answer from `input`.
pub struct TerminalPrompt<'a> {
    pub input: &'a mut dyn BufRead,
    pub err: &'a mut dyn Write,
}

impl Prompt for TerminalPrompt<'_> {
    fn confirm(&mut self, question: &str) -> Option<bool> {
        let _ = write!(self.err, "{question} [y/N] ");
        let _ = self.err.flush();
        let mut answer = String::new();
        self.input.read_line(&mut answer).ok()?;
        Some(matches!(
            answer.trim().to_ascii_lowercase().as_str(),
            "y" | "yes"
        ))
    }
}

/// What the person allowed.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Consent {
    pub assume_yes: bool,
    pub allow_av_exclusion: bool,
    pub allow_developer_mode: bool,
}

impl Consent {
    fn grants(&self, flag: &str) -> bool {
        match flag {
            ALLOW_AV_EXCLUSION => self.allow_av_exclusion,
            ALLOW_DEVELOPER_MODE => self.allow_developer_mode,
            _ => false,
        }
    }
}

/// Which fixes to apply, and which were held back and why.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Plan {
    pub apply: Vec<&'static str>,
    pub held: Vec<(&'static str, String)>,
}

/// Chooses the fixes to apply from a report.
///
/// A fix that lowers security is included only with its flag or an explicit
/// yes on a terminal; everything else is included and then confirmed as a
/// batch, unless `--yes`.
pub fn plan(report: &Report, only: &[String], consent: &Consent, prompt: &mut dyn Prompt) -> Plan {
    let mut plan = Plan::default();
    for finding in report
        .findings
        .iter()
        .filter(|finding| finding.wants_fix())
        .filter(|finding| only.is_empty() || only.iter().any(|id| id == finding.id))
    {
        let fix = finding.fix.as_ref().expect("wants_fix implies a fix");
        if let Some(flag) = fix.consent_flag
            && !consent.grants(flag)
        {
            let question = format!(
                "{}: {} -- this lowers security. Apply it?",
                finding.id, fix.action
            );
            match prompt.confirm(&question) {
                Some(true) => {}
                Some(false) => {
                    plan.held.push((finding.id, "declined".into()));
                    continue;
                }
                None => {
                    plan.held.push((
                        finding.id,
                        format!("lowers security; pass {flag} to apply it"),
                    ));
                    continue;
                }
            }
        }
        plan.apply.push(finding.id);
    }
    plan
}

// ---------------------------------------------------------------------------
// Commands
// ---------------------------------------------------------------------------

/// `host doctor [--json]`. Exits [`Failure::HostUnfit`] when a required check
/// fails, after printing the whole report.
///
/// # Errors
/// [`Failure::HostUnfit`], or the local-state failures of reading the setup.
pub fn doctor(
    context: &Context,
    args: &HostDoctorArgs,
    out: &mut dyn Write,
) -> Result<(), CliError> {
    let failed = write_failed("this host check");
    let setup = setup(context, Perspective::Operator, None)?;
    let report = evaluate(&setup, &SystemFacts);
    if args.json {
        serde_json::to_writer_pretty(&mut *out, &report)
            .map_err(|error| io::Error::other(error.to_string()))
            .and_then(|()| writeln!(out))
            .map_err(failed)?;
    } else {
        write_report(out, &report).map_err(failed)?;
    }
    unfit_failure(&report)
}

fn unfit_failure(report: &Report) -> Result<(), CliError> {
    let failing = report.required_failing();
    if failing.is_empty() {
        return Ok(());
    }
    Err(CliError::with_remedy(
        Failure::HostUnfit,
        format!(
            "required host check(s) fail: {}; the daemon starts no runner until they pass",
            failing.join(", ")
        ),
        "runner-manager host prepare",
    ))
}

fn known_ids(ids: &[String]) -> Result<(), CliError> {
    if let Some(unknown) = ids.iter().find(|id| check(id).is_none()) {
        let known: Vec<&str> = CHECKS.iter().map(|check| check.id).collect();
        return Err(CliError::with_remedy(
            Failure::InvalidArgument,
            format!(
                "{unknown:?} is not a host check; the checks are {}",
                known.join(", ")
            ),
            "runner-manager host doctor",
        ));
    }
    Ok(())
}

fn describe_result(result: &FixResult) -> String {
    match &result.outcome {
        FixOutcome::Applied { changes } => format!(
            "applied: {}",
            changes
                .iter()
                .map(Change::describe)
                .collect::<Vec<_>>()
                .join("; ")
        ),
        FixOutcome::AlreadyDone => "nothing to change".into(),
        FixOutcome::Reverted => "reverted".into(),
        FixOutcome::Failed { error } => format!("failed: {error}"),
        FixOutcome::NotAttempted { reason } => format!("not attempted: {reason}"),
    }
}

/// Everything `host prepare`, `service install` and the TUI share.
pub struct PrepareRun<'a> {
    pub context: &'a Context,
    pub setup: HostSetup,
    pub facts: &'a dyn HostFacts,
    pub actions: &'a dyn HostActions,
    pub elevator: &'a dyn Elevator,
    pub prompt: &'a mut dyn Prompt,
    pub consent: Consent,
}

/// The outcome of a prepare run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrepareOutcome {
    pub results: Vec<FixResult>,
    pub held: Vec<(&'static str, String)>,
    pub after: Report,
    /// `true` when nothing was applied because the batch was not confirmed.
    pub cancelled: bool,
}

/// Plans, confirms, applies, journals and re-probes.
///
/// # Errors
/// [`Failure::InvalidArgument`] for an unknown id, or a non-interactive run
/// without `--yes`; [`Failure::LocalState`] when the journal cannot be written.
pub fn prepare(
    mut run: PrepareRun<'_>,
    only: &[String],
    out: &mut dyn Write,
) -> Result<PrepareOutcome, CliError> {
    known_ids(only)?;
    // What the service found is reported, not prepared: a fix is planned from
    // this host's own probes, and judged by them afterwards. The service
    // re-checks within five minutes and drops its record then.
    run.setup.daemon_unfit = None;
    let failed = write_failed("this host preparation");
    let before = evaluate(&run.setup, run.facts);
    let plan = plan(&before, only, &run.consent, run.prompt);
    if plan.apply.is_empty() {
        writeln!(out, "Nothing to apply.").map_err(failed)?;
    } else {
        writeln!(out, "Host prepare will apply:").map_err(failed)?;
        for id in &plan.apply {
            let fix = fix(id).expect("planned ids have fixes");
            let admin = if fix.needs_admin && !run.facts.elevated() {
                " (administrator)"
            } else {
                ""
            };
            writeln!(out, "  {id}  {}{admin}", fix.action).map_err(failed)?;
        }
    }
    for (id, reason) in &plan.held {
        writeln!(out, "  held back: {id} ({reason})").map_err(failed)?;
    }
    out.flush().map_err(failed)?;
    if plan.apply.is_empty() {
        return Ok(PrepareOutcome {
            results: Vec::new(),
            held: plan.held,
            after: before,
            cancelled: false,
        });
    }
    if !run.consent.assume_yes {
        let question = format!("Apply {} change(s)?", plan.apply.len());
        match run.prompt.confirm(&question) {
            Some(true) => {}
            Some(false) => {
                writeln!(out, "Nothing was changed.").map_err(failed)?;
                return Ok(PrepareOutcome {
                    results: Vec::new(),
                    held: plan.held,
                    after: before,
                    cancelled: true,
                });
            }
            None => {
                return Err(CliError::with_remedy(
                    Failure::InvalidArgument,
                    "host prepare changes machine settings and there is no terminal to confirm \
                     on; nothing was changed",
                    "runner-manager host prepare --yes",
                ));
            }
        }
    }
    if !run.facts.elevated() && plan.apply.iter().any(|id| fix_needs_admin(id)) {
        writeln!(
            out,
            "Asking for administrator rights once for the changes that need them..."
        )
        .map_err(failed)?;
        out.flush().map_err(failed)?;
    }
    let results = apply_and_report(
        run.context,
        ElevatedRequest {
            setup: run.setup.clone(),
            apply: plan.apply.iter().map(|id| (*id).to_owned()).collect(),
            revert: Vec::new(),
        },
        (run.facts, run.actions, run.elevator),
        out,
    )?;
    let after = evaluate(&run.setup, run.facts);
    Ok(PrepareOutcome {
        results,
        held: plan.held,
        after,
        cancelled: false,
    })
}

/// Carries out `request` (elevating what needs it), journals what changed,
/// and prints one line per check.
fn apply_and_report(
    context: &Context,
    request: ElevatedRequest,
    (facts, actions, elevator): (&dyn HostFacts, &dyn HostActions, &dyn Elevator),
    out: &mut dyn Write,
) -> Result<Vec<FixResult>, CliError> {
    let results = execute(request, facts, actions, elevator);
    if results
        .iter()
        .any(|r| matches!(r.outcome, FixOutcome::Applied { .. } | FixOutcome::Reverted))
    {
        let path = journal_path(context);
        let mut journal = read_journal(&path)?;
        update_journal(&mut journal, &results, context.clock().now());
        write_json(&path, &journal)?;
    }
    for result in &results {
        writeln!(out, "  {}  {}", result.id, describe_result(result))
            .map_err(write_failed("this host preparation"))?;
    }
    Ok(results)
}

/// `host prepare [--yes] [--only ID]... [--allow-…] | --revert ID...`.
///
/// # Errors
/// See [`prepare`]; [`Failure::HostUnfit`] when a required check still fails
/// afterwards; [`Failure::NotFound`] for a revert nothing was recorded for.
pub fn prepare_command(
    context: &Context,
    args: &HostPrepareArgs,
    out: &mut dyn Write,
) -> Result<(), CliError> {
    let failed = write_failed("this host preparation");
    let terminal = io::stdin().is_terminal() && io::stderr().is_terminal();
    let setup = setup(context, Perspective::Operator, None)?;
    let elevator = SystemElevator { terminal };
    if !args.revert.is_empty() {
        return revert_command(context, setup, &args.revert, &elevator, out);
    }
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut stderr = io::stderr();
    let mut terminal_prompt = TerminalPrompt {
        input: &mut input,
        err: &mut stderr,
    };
    let mut no_prompt = NoPrompt;
    let prompt: &mut dyn Prompt = if terminal {
        &mut terminal_prompt
    } else {
        &mut no_prompt
    };
    let outcome = prepare(
        PrepareRun {
            context,
            setup,
            facts: &SystemFacts,
            actions: &SystemActions,
            elevator: &elevator,
            prompt,
            consent: Consent {
                assume_yes: args.yes,
                allow_av_exclusion: args.allow_av_exclusion,
                allow_developer_mode: args.allow_developer_mode,
            },
        },
        &args.only,
        out,
    )?;
    writeln!(out).map_err(failed)?;
    write_report(out, &outcome.after).map_err(failed)?;
    unfit_failure(&outcome.after)
}

fn revert_command(
    context: &Context,
    setup: HostSetup,
    ids: &[String],
    elevator: &dyn Elevator,
    out: &mut dyn Write,
) -> Result<(), CliError> {
    known_ids(ids)?;
    let journal = read_journal(&journal_path(context))?;
    let mut revert = Vec::new();
    for id in ids {
        let Some(entry) = journal.entries.get(id) else {
            return Err(CliError::with_remedy(
                Failure::NotFound,
                format!(
                    "host prepare has recorded no change for {id} on this host, so there is \
                     nothing to revert"
                ),
                "runner-manager host doctor",
            ));
        };
        revert.push((id.clone(), entry.changes.clone()));
    }
    let results = apply_and_report(
        context,
        ElevatedRequest {
            setup,
            apply: Vec::new(),
            revert,
        },
        (&SystemFacts, &SystemActions, elevator),
        out,
    )?;
    if results.iter().all(|r| r.outcome == FixOutcome::Reverted) {
        Ok(())
    } else {
        Err(CliError::new(
            Failure::Unclassified,
            "not every change could be reverted; the journal still records the rest",
        ))
    }
}

/// `host required-tools [--set a,b | --clear]`.
///
/// # Errors
/// [`Failure::InvalidArgument`] for a name that is not a bare command;
/// [`Failure::LocalState`] when the file cannot be read or written.
pub fn required_tools_command(
    context: &Context,
    args: &HostRequiredToolsArgs,
    out: &mut dyn Write,
) -> Result<(), CliError> {
    let failed = write_failed("the required tools");
    let path = required_tools_path(context);
    if args.clear {
        match std::fs::remove_file(&path) {
            Ok(()) => {}
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(error) => {
                return Err(CliError::new(
                    Failure::LocalState,
                    format!("cannot remove {}: {error}", path.display()),
                ));
            }
        }
    } else if let Some(tools) = &args.set {
        let mut list: Vec<String> = Vec::new();
        for tool in tools
            .iter()
            .map(|tool| tool.trim())
            .filter(|tool| !tool.is_empty())
        {
            validate_tool(tool)?;
            if !list.iter().any(|known| known == tool) {
                list.push(tool.to_owned());
            }
        }
        write_json(
            &path,
            &RequiredToolsFile {
                schema_version: REQUIRED_TOOLS_SCHEMA_VERSION,
                tools: list,
            },
        )?;
    }
    let tools = required_tools(context)?;
    writeln!(out, "Required tools").map_err(failed)?;
    writeln!(
        out,
        "  tools     {}",
        if tools.is_empty() {
            "none".to_owned()
        } else {
            tools.join(", ")
        }
    )
    .map_err(failed)?;
    writeln!(out, "  file      {}", path.display()).map_err(failed)?;
    writeln!(
        out,
        "  effect    the daemon starts no runner while one of them is missing from the runners' PATH"
    )
    .map_err(failed)
}

/// The elevated copy: reads the plan from its own command line, carries it
/// out, writes the results, and exits. Opens no database and no log, because
/// as root on macOS either would leave files the invoking account cannot
/// write.
#[must_use]
pub fn run_elevated_child(request: &str, result: &Path) -> ExitCode {
    let request: ElevatedRequest = match serde_json::from_str(request) {
        Ok(request) => request,
        Err(_) => return ExitCode::from(2),
    };
    let results = run_request(&request, &SystemFacts, &SystemActions);
    match serde_json::to_string(&results)
        .map_err(io::Error::other)
        .and_then(|text| std::fs::write(result, text))
    {
        Ok(()) => ExitCode::SUCCESS,
        Err(_) => ExitCode::from(2),
    }
}

// ---------------------------------------------------------------------------
// Where it runs automatically
// ---------------------------------------------------------------------------

/// A failing check, as `status`, `service status` and the TUI show it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FindingSummary {
    pub id: String,
    pub severity: Severity,
    pub title: String,
    pub detail: String,
    pub remedy: Option<String>,
    /// Whether `host prepare` can fix it.
    pub fixable: bool,
    pub needs_admin: bool,
    pub consent_flag: Option<String>,
}

/// The daemon's refusal, as recorded.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HostUnfitSummary {
    pub since: Timestamp,
    pub checks: Vec<String>,
    /// What each check found and what fixes it, as the daemon recorded it.
    pub detail: String,
}

/// The `doctor` block of `status --json`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DoctorSummary {
    /// How many checks were evaluated; `0` when the doctor was skipped.
    pub checked: usize,
    /// Required and recommended checks that fail.
    pub failing: Vec<FindingSummary>,
    /// Checks that could not be answered.
    pub unknown: Vec<String>,
    /// The daemon's recorded refusal to start runners, if any.
    pub daemon_host_unfit: Option<HostUnfitSummary>,
}

impl DoctorSummary {
    fn of(report: Option<&Report>, context: &Context) -> Self {
        let findings = report.map_or(&[][..], |report| report.findings.as_slice());
        Self {
            checked: findings.len(),
            failing: findings
                .iter()
                .filter(|finding| finding.needs_attention())
                .map(|finding| FindingSummary {
                    id: finding.id.to_owned(),
                    severity: finding.severity,
                    title: finding.title.to_owned(),
                    detail: finding.detail.clone(),
                    remedy: finding.remedy.clone(),
                    fixable: finding.fix.is_some(),
                    needs_admin: finding.fix.as_ref().is_some_and(|fix| fix.needs_admin),
                    consent_flag: finding
                        .fix
                        .as_ref()
                        .and_then(|fix| fix.consent_flag)
                        .map(str::to_owned),
                })
                .collect(),
            unknown: findings
                .iter()
                .filter(|finding| {
                    finding.status == Status::Unknown && finding.severity != Severity::Info
                })
                .map(|finding| finding.id.to_owned())
                .collect(),
            // A record a daemon stopped re-stamping is not a refusal in force.
            daemon_host_unfit: host_fitness::host_unfit_in_force(
                context.paths(),
                context.clock().now(),
            )
            .map(|record| HostUnfitSummary {
                since: record.since,
                detail: record.describe(),
                checks: record.checks,
            }),
        }
    }

    /// One line for `status` and `service status`.
    #[must_use]
    pub fn line(&self) -> String {
        if self.checked == 0 {
            return "not checked".to_owned();
        }
        let required = self
            .failing
            .iter()
            .filter(|finding| finding.severity == Severity::Required)
            .count();
        let recommended = self.failing.len() - required;
        if self.failing.is_empty() {
            return format!("ok ({} checks)", self.checked);
        }
        let ids: Vec<&str> = self
            .failing
            .iter()
            .map(|finding| finding.id.as_str())
            .collect();
        format!(
            "{required} required, {recommended} recommended failing ({}); runner-manager host doctor",
            ids.join(", ")
        )
    }
}

/// The doctor summary for `status`, from values `status` already read.
#[must_use]
pub fn status_summary(
    context: &Context,
    host: Option<&Host>,
    policies: &[ScalePolicy],
    runner_root: &HostRoot,
) -> DoctorSummary {
    if std::env::var_os(SKIP_DOCTOR_VARIABLE).is_some() {
        return DoctorSummary::of(None, context);
    }
    let setup = setup_from_parts(
        context,
        Perspective::Operator,
        host,
        policies,
        runner_root,
        None,
    );
    DoctorSummary::of(Some(&evaluate(&setup, &SystemFacts)), context)
}

/// A summary with no checks run yet, still carrying the daemon's recorded
/// refusal.
#[must_use]
pub fn pending_summary(context: &Context) -> DoctorSummary {
    DoctorSummary::of(None, context)
}

/// The doctor summary read fresh from this host's configuration, for a
/// caller that has nothing to hand it: `service status`, and the TUI's own
/// doctor thread. `Err` when the configuration could not be read.
///
/// # Errors
/// The local-state failure of reading the configuration.
pub fn current_summary(context: &Context) -> Result<DoctorSummary, CliError> {
    let setup = setup(context, Perspective::Operator, None)?;
    Ok(DoctorSummary::of(
        Some(&evaluate(&setup, &SystemFacts)),
        context,
    ))
}

/// The doctor summary for `service status`.
#[must_use]
pub fn service_status_line(context: &Context) -> String {
    current_summary(context).map_or_else(
        |error| format!("not checked ({error})"),
        |summary| summary.line(),
    )
}

/// Run by `service install` before it registers anything: reports the
/// checks that matter for the account the service is about to run as, and on
/// a terminal offers to fix them.
///
/// Never fails the install: a host that is not ready yet can still have its
/// service installed, and the daemon refuses runners until it is.
///
/// # Errors
/// Only when `out` cannot be written.
pub fn before_service_install(
    context: &Context,
    start_mode: StartMode,
    out: &mut dyn Write,
) -> Result<(), CliError> {
    let failed = write_failed("this service installation");
    let binary = std::env::current_exe().unwrap_or_default();
    let Ok(setup) = setup(
        context,
        Perspective::Operator,
        Some(ServiceSetup {
            start_mode,
            binary,
            definition_path: None,
            label: super::service::identity().launchd_label(),
            running: None,
            installed_from: None,
            foreign_directories: None,
        }),
    ) else {
        return Ok(());
    };
    let report = evaluate(&setup, &SystemFacts);
    let attention: Vec<&Finding> = report
        .findings
        .iter()
        .filter(|f| f.needs_attention())
        .collect();
    if attention.is_empty() {
        return Ok(());
    }
    writeln!(out, "Host checks for a {start_mode} service").map_err(failed)?;
    for finding in &attention {
        writeln!(out, "  {}", finding.line(0)).map_err(failed)?;
    }
    let interactive = io::stdin().is_terminal() && io::stderr().is_terminal();
    let fixable = report.findings.iter().any(Finding::wants_fix);
    if interactive && fixable {
        // The offer goes to stderr: `out` is buffered for decoration and a
        // question nobody can see is not an offer.
        let stdin = io::stdin();
        let mut input = stdin.lock();
        let mut stderr = io::stderr();
        let mut prompt = TerminalPrompt {
            input: &mut input,
            err: &mut stderr,
        };
        if prompt.confirm("Fix what can be fixed before installing?") == Some(true) {
            let mut err = io::stderr();
            let _ = prepare(
                PrepareRun {
                    context,
                    setup,
                    facts: &SystemFacts,
                    actions: &SystemActions,
                    elevator: &SystemElevator { terminal: true },
                    prompt: &mut prompt,
                    consent: Consent {
                        assume_yes: true,
                        ..Consent::default()
                    },
                },
                &[],
                &mut err,
            );
            return Ok(());
        }
    }
    writeln!(
        out,
        "  next  runner-manager host prepare (asks for administrator rights only if needed)"
    )
    .map_err(failed)?;
    writeln!(out).map_err(failed)
}

/// The TUI's one-key fix: applies the fixes for `checks` -- the ones the
/// dialog named, never another -- that the person consented to, asking for
/// administrator rights through the system's own dialog, and returns one line
/// describing what happened.
#[must_use]
pub fn prepare_from_tui(
    context: &Context,
    checks: &[String],
    allow_security_tradeoffs: bool,
) -> String {
    // An empty `only` means every check to `prepare`; here it means none.
    if checks.is_empty() {
        return "Host prepare: nothing was chosen to fix.".into();
    }
    let setup = match setup(context, Perspective::Operator, None) {
        Ok(setup) => setup,
        Err(error) => return format!("host prepare could not start: {error}"),
    };
    let mut sink = Vec::new();
    match prepare(
        PrepareRun {
            context,
            setup,
            facts: &SystemFacts,
            actions: &SystemActions,
            elevator: &SystemElevator { terminal: false },
            prompt: &mut NoPrompt,
            consent: Consent {
                assume_yes: true,
                allow_av_exclusion: allow_security_tradeoffs,
                allow_developer_mode: allow_security_tradeoffs,
            },
        },
        checks,
        &mut sink,
    ) {
        Ok(outcome) => tui_summary(&outcome),
        Err(error) => format!("host prepare failed: {error}"),
    }
}

fn tui_summary(outcome: &PrepareOutcome) -> String {
    let count = |predicate: fn(&FixOutcome) -> bool| {
        outcome
            .results
            .iter()
            .filter(|r| predicate(&r.outcome))
            .count()
    };
    let applied = count(|o| matches!(o, FixOutcome::Applied { .. } | FixOutcome::AlreadyDone));
    let mut parts = vec![format!("{applied} fixed")];
    let not_done: Vec<String> = outcome
        .results
        .iter()
        .filter_map(|r| match &r.outcome {
            FixOutcome::Failed { error } => Some(format!("{}: {error}", r.id)),
            FixOutcome::NotAttempted { reason } => Some(format!("{}: {reason}", r.id)),
            _ => None,
        })
        .collect();
    if !not_done.is_empty() {
        parts.push(format!("not fixed: {}", not_done.join("; ")));
    }
    if !outcome.held.is_empty() {
        let held: Vec<&str> = outcome.held.iter().map(|(id, _)| *id).collect();
        parts.push(format!("held back: {}", held.join(", ")));
    }
    let remaining = outcome
        .after
        .findings
        .iter()
        .filter(|f| f.needs_attention())
        .count();
    parts.push(format!("{remaining} still need attention"));
    format!("Host prepare: {}.", parts.join("; "))
}

/// What [`daemon_preflight`] answers while an earlier evaluation is still
/// running.
pub const PREFLIGHT_STILL_RUNNING: &str = "the previous host checks are still running";

/// What the daemon's preflight found.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DaemonVerdict {
    /// Failing required checks: while this is non-empty no runner starts.
    pub required: Vec<String>,
    /// Failing recommended checks, for the log.
    pub recommended: Vec<String>,
}

/// The daemon's preflight: evaluates every check from the daemon's own point
/// of view, off the runtime thread, and records or clears the refusal `status`
/// and the TUI read. Never prompts, and never refuses on a check it could not
/// evaluate.
///
/// # Errors
/// A description of why the checks could not run at all; the caller then
/// holds nothing back.
pub async fn daemon_preflight(context: &Context) -> Result<DaemonVerdict, String> {
    use std::sync::atomic::{AtomicBool, Ordering};
    /// Set while an evaluation runs. One that outlived its caller's deadline
    /// still holds a thread, so a recheck does not start a second beside it.
    static EVALUATING: AtomicBool = AtomicBool::new(false);
    struct Done;
    impl Drop for Done {
        fn drop(&mut self) {
            EVALUATING.store(false, Ordering::Release);
        }
    }
    let setup = setup(context, Perspective::Daemon, None).map_err(|error| error.to_string())?;
    if EVALUATING.swap(true, Ordering::AcqRel) {
        return Err(PREFLIGHT_STILL_RUNNING.to_owned());
    }
    let report = tokio::task::spawn_blocking(move || {
        let _done = Done;
        evaluate(&setup, &SystemFacts)
    })
    .await
    .map_err(|error| error.to_string())?;
    let verdict = DaemonVerdict {
        required: report.required_failing(),
        recommended: report
            .with(Severity::Recommended, Status::Fail)
            .map(|f| f.id.to_owned())
            .collect(),
    };
    let recorded = if verdict.required.is_empty() {
        host_fitness::clear_host_unfit(context.paths())
    } else {
        let findings: Vec<host_fitness::UnfitFinding> = report
            .with(Severity::Required, Status::Fail)
            .map(|finding| host_fitness::UnfitFinding {
                id: finding.id.to_owned(),
                detail: finding.detail.clone(),
                remedy: finding.remedy.clone(),
            })
            .collect();
        host_fitness::record_host_unfit(context.paths(), &findings, context.clock().now())
    };
    // The refusal itself does not depend on the record; only what `status`
    // can show does.
    if let Err(error) = recorded {
        tracing::warn!(
            event = "host_unfit_unrecorded",
            "the host-fitness record could not be written: {error}"
        );
    }
    Ok(verdict)
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;
    use std::collections::HashMap;

    use super::*;

    /// A table of facts. Anything not set answers "absent".
    #[derive(Default)]
    struct Facts {
        elevated: bool,
        dwords: HashMap<RegValue, Result<Option<u32>, String>>,
        strings: HashMap<RegValue, Option<String>>,
        exclusions: Option<Vec<String>>,
        git: Option<PathBuf>,
        git_values: RefCell<HashMap<String, String>>,
        symlinks: bool,
        tools: Vec<&'static str>,
        files: Vec<PathBuf>,
        memory: Option<u64>,
        cores: usize,
        /// Volumes Spotlight indexes; any other volume answers "disabled".
        indexed: Vec<PathBuf>,
        /// Volumes Spotlight gives no answer for.
        unanswered: Vec<PathBuf>,
        mounts: HashMap<PathBuf, PathBuf>,
        /// Directories that do not answer.
        hung: Vec<PathBuf>,
        /// Directories that answer something other than "responds" or "hung".
        answers: HashMap<PathBuf, host_fitness::Responsiveness>,
        process_type: Option<String>,
        throttled: usize,
        credential: Option<CredentialProbe>,
        power: Option<BTreeMap<String, u32>>,
        unattended: Option<UnattendedLogin>,
    }

    impl HostFacts for Facts {
        fn elevated(&self) -> bool {
            self.elevated
        }
        fn dword(&self, value: RegValue) -> Result<Option<u32>, String> {
            self.dwords.get(&value).cloned().unwrap_or(Ok(None))
        }
        fn string(&self, value: RegValue) -> Result<Option<String>, String> {
            Ok(self.strings.get(&value).cloned().flatten())
        }
        fn defender_exclusions(&self) -> Result<Option<Vec<String>>, String> {
            Ok(self.exclusions.clone())
        }
        fn git_system_value(&self, _: &Path, name: &str) -> Result<Option<String>, String> {
            Ok(self.git_values.borrow().get(name).cloned())
        }
        fn symlink_allowed(&self, _: &Path) -> Result<bool, String> {
            Ok(self.symlinks)
        }
        fn find_tool(&self, tool: &str, _: Option<&str>) -> Option<PathBuf> {
            if tool == "git" {
                return self.git.clone();
            }
            self.tools
                .contains(&tool)
                .then(|| PathBuf::from(format!("/bin/{tool}")))
        }
        fn file_exists(&self, path: &Path) -> bool {
            self.files.iter().any(|file| file == path)
        }
        fn memory_bytes(&self) -> Option<u64> {
            self.memory
        }
        fn cpu_count(&self) -> usize {
            self.cores
        }
        fn spotlight_indexing(&self, volume: &Path) -> Result<Option<bool>, String> {
            if self.unanswered.iter().any(|v| v == volume) {
                return Ok(None);
            }
            Ok(Some(self.indexed.iter().any(|v| v == volume)))
        }
        fn directory_responds(&self, directory: &Path) -> host_fitness::Responsiveness {
            if let Some(answer) = self.answers.get(directory) {
                return answer.clone();
            }
            if self.hung.iter().any(|hung| hung == directory) {
                host_fitness::Responsiveness::Hung
            } else {
                host_fitness::Responsiveness::Responds
            }
        }
        fn mount_point(&self, path: &Path) -> Option<PathBuf> {
            self.mounts.get(path).cloned()
        }
        fn launchd_process_type(&self, _: &Path) -> Result<Option<String>, String> {
            Ok(self.process_type.clone())
        }
        fn throttled_runner_processes(&self) -> Result<usize, String> {
            Ok(self.throttled)
        }
        fn service_credential(
            &self,
            _: &Path,
            _: Option<&Path>,
        ) -> Result<CredentialProbe, String> {
            self.credential.clone().ok_or_else(|| "no answer".into())
        }
        fn power_settings(&self) -> Result<Option<BTreeMap<String, u32>>, String> {
            Ok(self.power.clone())
        }
        fn unattended_login(&self) -> Option<UnattendedLogin> {
            self.unattended.clone()
        }
    }

    /// Records every write, and applies git writes to the facts.
    #[derive(Default)]
    struct Actions<'a> {
        log: RefCell<Vec<String>>,
        git: Option<&'a Facts>,
    }

    impl HostActions for Actions<'_> {
        fn set_dword(&self, value: RegValue, data: Option<u32>) -> Result<(), String> {
            self.log
                .borrow_mut()
                .push(format!("dword {value:?}={data:?}"));
            Ok(())
        }
        fn set_string(&self, value: RegValue, data: Option<&str>) -> Result<(), String> {
            self.log
                .borrow_mut()
                .push(format!("string {value:?}={data:?}"));
            Ok(())
        }
        fn set_git_system_value(
            &self,
            _: &Path,
            name: &str,
            value: Option<&str>,
        ) -> Result<(), String> {
            self.log.borrow_mut().push(format!("git {name}={value:?}"));
            if let Some(facts) = self.git {
                let mut values = facts.git_values.borrow_mut();
                match value {
                    Some(value) => values.insert(name.to_owned(), value.to_owned()),
                    None => values.remove(name),
                };
            }
            Ok(())
        }
        fn add_defender_exclusions(&self, paths: &[String]) -> Result<(), String> {
            self.log
                .borrow_mut()
                .push(format!("defender add {}", paths.join("|")));
            Ok(())
        }
        fn remove_defender_exclusions(&self, paths: &[String]) -> Result<(), String> {
            self.log
                .borrow_mut()
                .push(format!("defender remove {}", paths.join("|")));
            Ok(())
        }
        fn set_spotlight(&self, volume: &Path, enabled: bool) -> Result<(), String> {
            self.log
                .borrow_mut()
                .push(format!("spotlight {} {enabled}", volume.display()));
            Ok(())
        }
        fn set_power_setting(&self, name: &str, value: u32) -> Result<(), String> {
            self.log.borrow_mut().push(format!("pmset {name} {value}"));
            Ok(())
        }
    }

    fn windows_setup() -> HostSetup {
        HostSetup {
            os: HostOs::Windows,
            perspective: Perspective::Operator,
            service: Some(ServiceSetup {
                start_mode: StartMode::Boot,
                binary: PathBuf::from(r"C:\rm\runner-manager.exe"),
                definition_path: None,
                label: "rm".into(),
                running: None,
                installed_from: None,
                foreign_directories: None,
            }),
            runner_roots: vec![PathBuf::from(r"C:\rman")],
            capacity: 2,
            required_tools: Vec::new(),
            required_tools_error: None,
            runner_path: Some(r"C:\Windows\System32".into()),
            probe_dir: PathBuf::from(r"C:\state"),
            data_root: None,
            service_contact_age_secs: None,
            service_credential_unreadable: false,
            own_keychain_readable: None,
            launches_blocked: None,
            service_account: None,
            service_home: None,
            daemon_unfit: None,
            polling: None,
        }
    }

    fn macos_setup() -> HostSetup {
        HostSetup {
            os: HostOs::Macos,
            service: Some(ServiceSetup {
                start_mode: StartMode::Login,
                binary: PathBuf::from("/Users/me/rm/runner-manager"),
                definition_path: Some(PathBuf::from("/Users/me/Library/LaunchAgents/rm.plist")),
                label: "io.github.IvanMurzak.runner-manager".into(),
                running: None,
                installed_from: None,
                foreign_directories: None,
            }),
            runner_roots: vec![PathBuf::from("/Volumes/NVME/rman")],
            runner_path: Some("/usr/bin".into()),
            probe_dir: PathBuf::from("/tmp/state"),
            service_account: Some("me".into()),
            service_home: Some(PathBuf::from("/Users/me")),
            ..windows_setup()
        }
    }

    fn finding<'a>(report: &'a Report, id: &str) -> &'a Finding {
        report
            .findings
            .iter()
            .find(|f| f.id == id)
            .unwrap_or_else(|| panic!("{id} missing"))
    }

    fn status_of(setup: &HostSetup, facts: &Facts, id: &str) -> Status {
        finding(&evaluate(setup, facts), id).status
    }

    /// `pmset -g` on the runner Mac that was set up with the defaults.
    const SLEEPY_MAC_PMSET: &str = "System-wide power settings:\n\
                                    Currently in use:\n \
                                    standby              0\n \
                                    Sleep On Power Button 1\n \
                                    autorestart          0\n \
                                    powernap             1\n \
                                    disksleep            10\n \
                                    sleep                1 (sleep prevented by powerd)\n \
                                    womp                 1\n";

    #[test]
    fn power_settings_are_read_the_way_pmset_prints_them() {
        let settings = power_settings_in(SLEEPY_MAC_PMSET);
        assert_eq!(settings.get("sleep"), Some(&1));
        assert_eq!(settings.get("disksleep"), Some(&10));
        assert_eq!(settings.get("autorestart"), Some(&0));
        assert_eq!(settings.get("womp"), Some(&1));
        assert_eq!(settings.get("Sleep On Power Button"), Some(&1));
        assert!(!settings.contains_key("Currently in use:"));
    }

    #[test]
    fn a_mac_that_sleeps_or_stays_off_after_a_power_failure_is_fixed_with_pmset() {
        let setup = macos_setup();
        let mut facts = Facts {
            power: Some(power_settings_in(SLEEPY_MAC_PMSET)),
            ..Facts::default()
        };
        let report = evaluate(&setup, &facts);
        for id in ["macos.sleep", "macos.disk_sleep", "macos.autorestart"] {
            let found = finding(&report, id);
            assert_eq!(found.status, Status::Fail, "{id}");
            assert_eq!(found.severity, Severity::Recommended, "{id}");
            let fix = found.fix.as_ref().expect("fixable");
            assert!(fix.needs_admin, "{id}");
            assert!(fix.consent_flag.is_none(), "{id}");
        }
        assert_eq!(finding(&report, "macos.wake_on_lan").status, Status::Pass);

        let actions = Actions::default();
        for (id, expected) in [
            ("macos.sleep", ("sleep", Some(1), 0)),
            ("macos.disk_sleep", ("disksleep", Some(10), 0)),
            ("macos.autorestart", ("autorestart", Some(0), 1)),
        ] {
            let (name, previous, applied) = expected;
            assert_eq!(
                apply_one(id, &setup, &facts, &actions).outcome,
                FixOutcome::Applied {
                    changes: vec![Change::PowerSetting {
                        name: name.into(),
                        previous,
                        applied,
                    }]
                },
                "{id}"
            );
        }
        assert_eq!(
            *actions.log.borrow(),
            ["pmset sleep 0", "pmset disksleep 0", "pmset autorestart 1"]
        );

        // A revert puts back exactly what was there, and nothing outside the
        // closed set a journal could name.
        let reverting = Actions::default();
        Change::PowerSetting {
            name: "disksleep".into(),
            previous: Some(10),
            applied: 0,
        }
        .revert(&reverting)
        .unwrap();
        assert_eq!(*reverting.log.borrow(), ["pmset disksleep 10"]);
        for tampered in [
            Change::PowerSetting {
                name: "hibernatemode".into(),
                previous: Some(0),
                applied: 3,
            },
            Change::PowerSetting {
                name: "autorestart".into(),
                previous: Some(7),
                applied: 1,
            },
        ] {
            assert!(tampered.revert(&reverting).is_err(), "{tampered:?}");
        }

        facts.power = Some(power_settings_in(
            "Currently in use:\n sleep 0\n disksleep 0\n autorestart 1\n womp 0\n",
        ));
        for id in ["macos.sleep", "macos.disk_sleep", "macos.autorestart"] {
            assert_eq!(status_of(&setup, &facts, id), Status::Pass, "{id}");
        }
        let womp = finding(&evaluate(&setup, &facts), "macos.wake_on_lan").clone();
        assert_eq!((womp.status, womp.severity), (Status::Fail, Severity::Info));
        assert!(!womp.needs_attention(), "wake-on-LAN is optional");
        facts.power = None;
        assert_eq!(
            status_of(&setup, &facts, "macos.sleep"),
            Status::NotApplicable
        );
    }

    #[test]
    fn unattended_login_is_reported_with_its_steps_and_never_fixed() {
        use runner_manager_platform::unattended_login::AutoLogin;
        let id = "macos.unattended_login";
        let mut setup = macos_setup();
        let mut facts = Facts {
            unattended: Some(UnattendedLogin {
                auto_login: AutoLogin::As("me".into()),
                filevault_on: Some(false),
            }),
            ..Facts::default()
        };
        assert_eq!(status_of(&setup, &facts, id), Status::Pass);

        facts.unattended = Some(UnattendedLogin {
            auto_login: AutoLogin::Off,
            filevault_on: Some(false),
        });
        let report = evaluate(&setup, &facts);
        let off = finding(&report, id);
        assert_eq!(off.status, Status::Fail);
        assert!(
            off.fix.is_none(),
            "automatic login is never changed for you"
        );
        assert!(
            off.detail.contains("waits for me to sign in"),
            "{}",
            off.detail
        );
        assert!(
            off.remedy
                .as_deref()
                .unwrap()
                .contains("System Settings > Users & Groups"),
            "{off:?}"
        );

        facts.unattended = Some(UnattendedLogin {
            auto_login: AutoLogin::As("me".into()),
            filevault_on: Some(true),
        });
        let report = evaluate(&setup, &facts);
        let locked = finding(&report, id);
        assert_eq!(locked.status, Status::Fail);
        assert!(locked.fix.is_none(), "FileVault is never changed for you");
        assert!(
            locked
                .remedy
                .as_deref()
                .unwrap()
                .contains("Privacy & Security > FileVault"),
            "{locked:?}"
        );

        setup.service = None;
        assert_eq!(status_of(&setup, &facts, id), Status::NotApplicable);
    }

    /// The old Mac after an update: the daemon's listing of a runner root on
    /// an external volume waits on "would like to access files on a removable
    /// volume", and the report has to say which button that is.
    #[test]
    fn a_runner_root_behind_a_privacy_question_names_what_to_click() {
        let id = "host.runner_root_responsive";
        let root = PathBuf::from("/Volumes/NVME/runners");
        let mut setup = macos_setup();
        setup.runner_roots = vec![root.clone()];
        let mut facts = Facts::default();
        facts
            .answers
            .insert(root.clone(), host_fitness::Responsiveness::ListingBlocked);
        let report = evaluate(&setup, &facts);
        let asking = finding(&report, id);
        assert_eq!(asking.status, Status::Fail);
        assert_eq!(asking.severity, Severity::Required);
        assert!(
            asking.detail.contains("removable volume"),
            "{}",
            asking.detail
        );
        assert!(
            asking.remedy.as_deref().unwrap().contains("click Allow"),
            "{asking:?}"
        );

        facts.answers.insert(
            root.clone(),
            host_fitness::Responsiveness::NotPermitted("Operation not permitted".into()),
        );
        let report = evaluate(&setup, &facts);
        let refused = finding(&report, id);
        assert_eq!(refused.status, Status::Fail, "a refusal is not an unknown");
        assert!(
            refused
                .remedy
                .as_deref()
                .unwrap()
                .contains("Files & Folders > runner-manager"),
            "{refused:?}"
        );

        // Off `/Volumes` the startup volume asks nothing: a blocked listing is
        // a stalled disk there, as before.
        let local = PathBuf::from("/Users/Shared/rman.noindex");
        setup.runner_roots = vec![local.clone()];
        facts
            .answers
            .insert(local, host_fitness::Responsiveness::ListingBlocked);
        let report = evaluate(&setup, &facts);
        let stalled = finding(&report, id);
        assert_eq!(stalled.status, Status::Fail);
        assert!(!stalled.detail.contains("removable"), "{}", stalled.detail);
    }

    /// `host doctor` over SSH listed a root the daemon, in the desktop
    /// session, could not, and called it passing. The daemon's own finding
    /// wins.
    #[test]
    fn a_check_the_daemon_finds_failing_fails_here_too() {
        let id = "host.runner_root_responsive";
        let mut setup = macos_setup();
        let facts = Facts::default();
        assert_eq!(status_of(&setup, &facts, id), Status::Pass);

        let record = host_fitness::HostUnfitRecord {
            schema_version: 1,
            since: chrono::Utc::now(),
            checked_at: chrono::Utc::now(),
            checks: vec![id.into()],
            findings: vec![host_fitness::UnfitFinding {
                id: id.into(),
                detail: "macOS has not let the service list /Volumes/NVME/rman".into(),
                remedy: Some("click Allow".into()),
            }],
        };
        setup.daemon_unfit = Some(record);
        let report = evaluate(&setup, &facts);
        let found = finding(&report, id);
        assert_eq!(found.status, Status::Fail);
        assert!(
            found.detail.contains("from its own session"),
            "{}",
            found.detail
        );
        assert!(
            found.detail.contains("/Volumes/NVME/rman"),
            "{}",
            found.detail
        );
        assert_eq!(found.remedy.as_deref(), Some("click Allow"));
        assert!(!report.required_failing().is_empty());
        assert_eq!(
            finding(&report, "macos.spotlight").status,
            status_of(
                &HostSetup {
                    daemon_unfit: None,
                    ..setup.clone()
                },
                &facts,
                "macos.spotlight"
            ),
            "only the checks the daemon names change"
        );

        // The daemon's own preflight is not overridden by its own record.
        setup.perspective = Perspective::Daemon;
        assert_eq!(status_of(&setup, &facts, id), Status::Pass);
    }

    #[test]
    fn a_runner_root_with_a_space_or_inside_the_service_home_is_reported() {
        let id = "macos.runner_root_location";
        let mut setup = macos_setup();
        let facts = Facts::default();
        assert_eq!(status_of(&setup, &facts, id), Status::Pass);

        // The default root on a login-mode Mac: both problems at once.
        setup.runner_roots = vec![PathBuf::from(
            "/Users/me/Library/Application Support/io.github.IvanMurzak.runner-manager/runtime",
        )];
        let report = evaluate(&setup, &facts);
        let found = finding(&report, id);
        assert_eq!(found.status, Status::Fail);
        assert!(found.detail.contains("has a space"), "{}", found.detail);
        assert!(
            found.detail.contains("inside /Users/me"),
            "{}",
            found.detail
        );
        let remedy = found.remedy.as_deref().unwrap();
        assert!(remedy.contains(MACOS_RUNNER_ROOT), "{remedy}");
        assert!(!MACOS_RUNNER_ROOT.contains(' '));

        setup.runner_roots = vec![PathBuf::from("/Users/me/rman.noindex")];
        let found = finding(&evaluate(&setup, &facts), id).clone();
        assert_eq!(found.status, Status::Fail);
        assert!(!found.detail.contains("has a space"), "{}", found.detail);

        setup.runner_roots = vec![PathBuf::from(MACOS_RUNNER_ROOT)];
        assert_eq!(status_of(&setup, &facts, id), Status::Pass);
    }

    #[test]
    fn the_spotlight_remedy_names_a_root_with_no_spaces() {
        let mut setup = macos_setup();
        let root = PathBuf::from(
            "/Users/me/Library/Application Support/io.github.IvanMurzak.runner-manager/runtime",
        );
        setup.runner_roots = vec![root.clone()];
        let mut facts = Facts::default();
        facts
            .mounts
            .insert(root, PathBuf::from("/System/Volumes/Data"));
        facts.indexed = vec![PathBuf::from("/System/Volumes/Data")];
        let report = evaluate(&setup, &facts);
        let remedy = finding(&report, "macos.spotlight").remedy.clone().unwrap();
        assert!(
            remedy.contains(&format!("--path {MACOS_RUNNER_ROOT})")),
            "{remedy}"
        );
        assert!(!remedy.contains("runtime.noindex"), "{remedy}");
    }

    #[test]
    fn check_ids_are_unique_and_every_security_tradeoff_needs_a_flag() {
        let mut ids: Vec<&str> = CHECKS.iter().map(|c| c.id).collect();
        let before = ids.len();
        ids.sort_unstable();
        ids.dedup();
        assert_eq!(ids.len(), before);
        for id in ["windows.defender_exclusion", "windows.symlink_privilege"] {
            assert!(
                check(id)
                    .unwrap()
                    .fix
                    .as_ref()
                    .unwrap()
                    .consent_flag
                    .is_some(),
                "{id}"
            );
        }
    }

    #[test]
    fn only_this_platforms_checks_are_evaluated() {
        let facts = Facts::default();
        let windows = evaluate(&windows_setup(), &facts);
        assert!(
            windows
                .findings
                .iter()
                .all(|f| f.platform != CheckPlatform::Macos)
        );
        assert!(
            windows
                .findings
                .iter()
                .any(|f| f.id == "windows.long_paths")
        );
        let linux = evaluate(
            &HostSetup {
                os: HostOs::Linux,
                ..windows_setup()
            },
            &facts,
        );
        assert!(
            linux
                .findings
                .iter()
                .all(|f| f.platform == CheckPlatform::Any)
        );
    }

    #[test]
    fn long_paths_pass_only_at_one() {
        let setup = windows_setup();
        let mut facts = Facts::default();
        assert_eq!(
            status_of(&setup, &facts, "windows.long_paths"),
            Status::Fail
        );
        facts.dwords.insert(RegValue::LongPathsEnabled, Ok(Some(0)));
        assert_eq!(
            status_of(&setup, &facts, "windows.long_paths"),
            Status::Fail
        );
        facts.dwords.insert(RegValue::LongPathsEnabled, Ok(Some(1)));
        assert_eq!(
            status_of(&setup, &facts, "windows.long_paths"),
            Status::Pass
        );
        facts
            .dwords
            .insert(RegValue::LongPathsEnabled, Err("access denied".into()));
        assert_eq!(
            status_of(&setup, &facts, "windows.long_paths"),
            Status::Unknown
        );
    }

    #[test]
    fn git_long_paths_reads_the_system_scope_of_the_runners_git() {
        let setup = windows_setup();
        let mut facts = Facts::default();
        assert_eq!(
            status_of(&setup, &facts, "windows.git_long_paths"),
            Status::NotApplicable
        );
        facts.git = Some(PathBuf::from(r"C:\Git\cmd\git.exe"));
        assert_eq!(
            status_of(&setup, &facts, "windows.git_long_paths"),
            Status::Fail
        );
        facts
            .git_values
            .borrow_mut()
            .insert(GIT_LONG_PATHS.into(), "true".into());
        assert_eq!(
            status_of(&setup, &facts, "windows.git_long_paths"),
            Status::Pass
        );
    }

    #[test]
    fn a_defender_exclusion_covers_its_own_path_and_everything_below_it() {
        let roots = vec![
            PathBuf::from(r"C:\rman"),
            PathBuf::from(r"C:\ProgramData\rm\runner-workspaces"),
            PathBuf::from(r"D:\rmanx"),
        ];
        let exclusions = vec![
            r"c:\RMAN\".to_owned(),
            r"C:\ProgramData".to_owned(),
            r"D:\rman".to_owned(),
        ];
        assert_eq!(uncovered_roots(&roots, &exclusions), [r"D:\rmanx"]);
        assert_eq!(uncovered_roots(&roots, &[]).len(), 3);
    }

    #[test]
    fn defender_is_unknown_without_admin_and_not_applicable_when_off() {
        let setup = windows_setup();
        let mut facts = Facts::default();
        assert_eq!(
            status_of(&setup, &facts, "windows.defender_exclusion"),
            Status::Unknown
        );
        facts.exclusions = Some(vec![r"C:\rman".into()]);
        assert_eq!(
            status_of(&setup, &facts, "windows.defender_exclusion"),
            Status::Pass
        );
        facts.exclusions = Some(vec![r"C:\other".into()]);
        assert_eq!(
            status_of(&setup, &facts, "windows.defender_exclusion"),
            Status::Fail
        );
        facts
            .dwords
            .insert(RegValue::DefenderPassiveMode, Ok(Some(1)));
        assert_eq!(
            status_of(&setup, &facts, "windows.defender_exclusion"),
            Status::NotApplicable
        );
    }

    #[test]
    fn symlink_privilege_follows_the_execution_account() {
        let mut setup = windows_setup();
        let mut facts = Facts::default();
        assert_eq!(
            status_of(&setup, &facts, "windows.symlink_privilege"),
            Status::Pass,
            "boot"
        );
        setup.service.as_mut().unwrap().start_mode = StartMode::Login;
        facts.elevated = true;
        assert_eq!(
            status_of(&setup, &facts, "windows.symlink_privilege"),
            Status::Fail,
            "login"
        );
        facts.dwords.insert(RegValue::DeveloperMode, Ok(Some(1)));
        assert_eq!(
            status_of(&setup, &facts, "windows.symlink_privilege"),
            Status::Pass,
            "dev mode"
        );
        facts.dwords.remove(&RegValue::DeveloperMode);
        facts.elevated = false;
        facts.symlinks = true;
        assert_eq!(
            status_of(&setup, &facts, "windows.symlink_privilege"),
            Status::Pass,
            "an unelevated login account that measurably can"
        );
        setup.perspective = Perspective::Daemon;
        setup.service.as_mut().unwrap().start_mode = StartMode::Boot;
        facts.symlinks = false;
        assert_eq!(
            status_of(&setup, &facts, "windows.symlink_privilege"),
            Status::Fail,
            "the daemon measures rather than infers"
        );
    }

    #[test]
    fn execution_policy_defaults_to_restricted_on_a_client_and_respects_group_policy() {
        let setup = windows_setup();
        let mut facts = Facts::default();
        let id = "windows.execution_policy";
        assert_eq!(status_of(&setup, &facts, id), Status::Fail);
        facts
            .strings
            .insert(RegValue::InstallationType, Some("Server".into()));
        assert_eq!(status_of(&setup, &facts, id), Status::Pass);
        facts
            .strings
            .insert(RegValue::InstallationType, Some("Client".into()));
        facts
            .strings
            .insert(RegValue::ExecutionPolicy, Some("RemoteSigned".into()));
        assert_eq!(status_of(&setup, &facts, id), Status::Pass);
        facts.strings.insert(
            RegValue::ExecutionPolicyGroupPolicy,
            Some("AllSigned".into()),
        );
        let report = evaluate(&setup, &facts);
        let managed = finding(&report, id);
        assert_eq!(managed.status, Status::Fail);
        assert!(
            managed.fix.is_none(),
            "a Group Policy setting has no local fix"
        );
    }

    #[test]
    fn pwsh_and_execution_account_report_without_fixing() {
        let mut setup = windows_setup();
        let mut facts = Facts::default();
        assert_eq!(status_of(&setup, &facts, "windows.pwsh"), Status::Fail);
        facts.files.push(PathBuf::from(WINDOWS_PWSH));
        let report = evaluate(&setup, &facts);
        assert!(
            finding(&report, "windows.pwsh")
                .detail
                .contains("not on the runners' PATH")
        );
        facts.tools.push("pwsh");
        assert_eq!(status_of(&setup, &facts, "windows.pwsh"), Status::Pass);
        assert_eq!(
            status_of(&setup, &facts, "windows.execution_account"),
            Status::Pass
        );
        setup.service.as_mut().unwrap().start_mode = StartMode::Login;
        let report = evaluate(&setup, &facts);
        let account = finding(&report, "windows.execution_account");
        assert_eq!(account.status, Status::Fail);
        assert!(
            account
                .remedy
                .as_deref()
                .unwrap()
                .contains("--start-at boot")
        );
        setup.service = None;
        assert_eq!(
            status_of(&setup, &facts, "windows.execution_account"),
            Status::NotApplicable
        );
    }

    #[test]
    fn a_background_launch_agent_or_a_throttled_runner_fails_the_priority_check() {
        let setup = macos_setup();
        let mut facts = Facts::default();
        let id = "macos.launchd_priority";
        facts.process_type = Some(LAUNCHD_PROCESS_TYPE.into());
        assert_eq!(status_of(&setup, &facts, id), Status::Pass);
        facts.process_type = None;
        assert_eq!(
            status_of(&setup, &facts, id),
            Status::Fail,
            "no ProcessType is Standard, below normal priority, as `service status` judges it"
        );
        facts.process_type = Some("Background".into());
        let report = evaluate(&setup, &facts);
        assert_eq!(finding(&report, id).status, Status::Fail);
        assert!(
            finding(&report, id).remedy.as_deref().unwrap().ends_with(
                "launchctl kickstart -k gui/$(id -u)/io.github.IvanMurzak.runner-manager"
            ),
            "{:?}",
            finding(&report, id).remedy
        );
        facts.process_type = Some("Interactive".into());
        facts.throttled = 2;
        assert_eq!(status_of(&setup, &facts, id), Status::Fail);
    }

    #[test]
    fn throttled_runners_are_counted_from_ps_output() {
        let listing = "  4 /Users/me/rman/a/bin/Runner.Listener\n 31 /Users/me/rman/b/bin/Runner.Listener\n  4 /usr/libexec/other\n  4 /x/bin/Runner.Worker\n";
        assert_eq!(throttled_runners_in(listing), 2);
    }

    #[test]
    fn spotlight_is_fixable_only_off_the_startup_volume() {
        let mut setup = macos_setup();
        let mut facts = Facts::default();
        let id = "macos.spotlight";
        assert_eq!(
            status_of(&setup, &facts, id),
            Status::Unknown,
            "a root whose volume cannot be found is not a pass"
        );
        facts.mounts.insert(
            PathBuf::from("/Volumes/NVME/rman"),
            PathBuf::from("/Volumes/NVME"),
        );
        facts.unanswered.push(PathBuf::from("/Volumes/NVME"));
        assert_eq!(
            status_of(&setup, &facts, id),
            Status::Unknown,
            "mdutil's `unknown indexing state` is not a pass"
        );
        facts.unanswered.clear();
        assert_eq!(status_of(&setup, &facts, id), Status::Pass);
        facts.indexed.push(PathBuf::from("/Volumes/NVME"));
        let report = evaluate(&setup, &facts);
        assert_eq!(finding(&report, id).status, Status::Fail);
        assert!(finding(&report, id).fix.is_some());
        let actions = Actions::default();
        let result = apply_one(id, &setup, &facts, &actions);
        assert_eq!(
            result.outcome,
            FixOutcome::Applied {
                changes: vec![Change::SpotlightIndexingOff {
                    volume: PathBuf::from("/Volumes/NVME")
                }]
            }
        );
        setup.runner_roots = vec![PathBuf::from("/Users/me/rman")];
        facts.indexed = vec![PathBuf::from("/System/Volumes/Data")];
        facts.mounts.insert(
            PathBuf::from("/Users/me/rman"),
            PathBuf::from("/System/Volumes/Data"),
        );
        let report = evaluate(&setup, &facts);
        assert!(finding(&report, id).fix.is_none());
        assert!(
            finding(&report, id)
                .remedy
                .as_deref()
                .unwrap()
                .contains(".noindex")
        );
        setup.runner_roots = vec![PathBuf::from("/Users/me/rman.noindex/x")];
        assert_eq!(
            status_of(&setup, &facts, id),
            Status::Pass,
            "a `.noindex` folder is skipped even on an indexed volume"
        );
    }

    #[test]
    fn an_unreadable_keychain_credential_names_the_exact_login_command() {
        let mut setup = macos_setup();
        setup.own_keychain_readable = Some(true);
        let mut facts = Facts {
            credential: Some(CredentialProbe::Unreadable(
                "errSecInteractionNotAllowed".into(),
            )),
            ..Facts::default()
        };
        let report = evaluate(&setup, &facts);
        let keychain = finding(&report, "macos.keychain_credential");
        assert_eq!(keychain.status, Status::Fail);
        let remedy = keychain.remedy.as_deref().unwrap();
        assert!(
            remedy.contains("/Users/me/rm/runner-manager")
                && remedy.contains(" auth login --start-at login")
                && !remedy.contains("sudo"),
            "{remedy}"
        );
        assert_eq!(report.required_failing(), ["macos.keychain_credential"]);

        // A session that cannot read the keychain at all (SSH) is not the
        // service binary's fault: measured on the Mac mini, both binaries
        // answered -25293 over SSH while the daemon was serving jobs.
        setup.own_keychain_readable = Some(false);
        assert_eq!(
            status_of(&setup, &facts, "macos.keychain_credential"),
            Status::Unknown
        );
        // And a service that reached GitHub minutes ago read its credential
        // to do it.
        let recent = HostSetup {
            service_contact_age_secs: Some(120),
            ..setup.clone()
        };
        assert_eq!(
            status_of(&recent, &facts, "macos.keychain_credential"),
            Status::Pass
        );
        facts.credential = Some(CredentialProbe::Readable);
        assert_eq!(
            status_of(&setup, &facts, "macos.keychain_credential"),
            Status::Pass
        );
        let daemon = HostSetup {
            perspective: Perspective::Daemon,
            ..setup
        };
        assert_eq!(
            status_of(&daemon, &facts, "macos.keychain_credential"),
            Status::NotApplicable
        );
    }

    /// The 0.4.33 rollout: right after the binary swap every start of the new
    /// daemon failed with `-25293`, and the check passed on the contact the
    /// *old* daemon had made during its drain, "0 minute(s) ago".
    #[test]
    fn a_contact_made_before_the_binary_was_replaced_proves_nothing() {
        let now = chrono::Utc::now();
        let swapped = now - chrono::Duration::seconds(20);
        let old_daemon_contact = Some(swapped - chrono::Duration::seconds(5));
        assert_eq!(
            current_daemon_contact_age(old_daemon_contact, Some(swapped), now),
            None,
            "the previous binary's contact is not the installed binary's"
        );
        let new_daemon_contact = Some(swapped + chrono::Duration::seconds(10));
        assert_eq!(
            current_daemon_contact_age(new_daemon_contact, Some(swapped), now),
            Some(10)
        );
        assert_eq!(
            current_daemon_contact_age(new_daemon_contact, None, now),
            Some(10),
            "a binary whose time cannot be read does not discard a contact"
        );

        // End to end through the check: the stale contact is gone, so the
        // service binary is asked, and it cannot read the item.
        let mut setup = macos_setup();
        setup.own_keychain_readable = Some(true);
        setup.service_contact_age_secs =
            current_daemon_contact_age(old_daemon_contact, Some(swapped), now);
        let facts = Facts {
            credential: Some(CredentialProbe::Unreadable("-25293".into())),
            ..Facts::default()
        };
        assert_eq!(
            status_of(&setup, &facts, "macos.keychain_credential"),
            Status::Fail
        );
    }

    #[test]
    fn the_daemons_own_unreadable_record_fails_the_check_whatever_else_says() {
        let setup = HostSetup {
            service_credential_unreadable: true,
            service_contact_age_secs: Some(0),
            ..macos_setup()
        };
        let facts = Facts {
            credential: Some(CredentialProbe::Readable),
            ..Facts::default()
        };
        let report = evaluate(&setup, &facts);
        let keychain = finding(&report, "macos.keychain_credential");
        assert_eq!(keychain.status, Status::Fail);
        assert!(
            keychain
                .remedy
                .as_deref()
                .unwrap()
                .contains(" auth login --start-at login"),
            "{keychain:?}"
        );
    }

    #[test]
    fn a_stopped_service_is_not_reported_as_running_at_normal_priority() {
        let mut setup = macos_setup();
        let facts = Facts {
            process_type: Some(LAUNCHD_PROCESS_TYPE.to_string()),
            ..Facts::default()
        };
        setup.service.as_mut().unwrap().running = Some(true);
        assert_eq!(
            status_of(&setup, &facts, "macos.launchd_priority"),
            Status::Pass
        );
        setup.service.as_mut().unwrap().running = Some(false);
        assert_eq!(
            status_of(&setup, &facts, "macos.launchd_priority"),
            Status::Unknown
        );
    }

    #[test]
    fn capacity_is_recommended_from_memory_and_cores() {
        assert_eq!(recommended_capacity(8 * GIB, 8), 2);
        assert_eq!(recommended_capacity(64 * GIB, 16), 16);
        assert_eq!(recommended_capacity(GIB, 4), 1);
        let setup = HostSetup {
            capacity: 10,
            ..macos_setup()
        };
        let facts = Facts {
            memory: Some(8 * GIB),
            cores: 8,
            ..Facts::default()
        };
        let report = evaluate(&setup, &facts);
        let capacity = finding(&report, "host.capacity");
        assert_eq!(capacity.status, Status::Fail);
        assert_eq!(
            capacity.remedy.as_deref(),
            Some("runner-manager host set-capacity 2")
        );
        assert!(
            capacity.fix.is_none(),
            "capacity is never changed automatically"
        );
    }

    /// A hung runner volume is a required failure (the daemon refuses
    /// runners), and the Spotlight check does not call `df` or `mdutil` on it.
    #[test]
    fn a_hung_runner_root_is_unfit_and_spotlight_does_not_touch_it() {
        let setup = macos_setup();
        let mut facts = Facts::default();
        facts.mounts.insert(
            PathBuf::from("/Volumes/NVME/rman"),
            PathBuf::from("/Volumes/NVME"),
        );
        let id = "host.runner_root_responsive";
        assert_eq!(status_of(&setup, &facts, id), Status::Pass);
        assert_eq!(status_of(&setup, &facts, "macos.spotlight"), Status::Pass);

        facts.hung.push(PathBuf::from("/Volumes/NVME/rman"));
        let report = evaluate(&setup, &facts);
        let root = finding(&report, id);
        assert_eq!(root.status, Status::Fail);
        assert!(
            root.detail.starts_with("runner root not responding"),
            "{}",
            root.detail
        );
        assert!(report.required_failing().contains(&id.to_owned()));
        assert_eq!(finding(&report, "macos.spotlight").status, Status::Unknown);
    }

    #[test]
    fn required_tools_fail_by_name() {
        let mut setup = windows_setup();
        let facts = Facts {
            tools: vec!["node"],
            ..Facts::default()
        };
        assert_eq!(
            status_of(&setup, &facts, "host.required_tools"),
            Status::NotApplicable
        );
        setup.required_tools = vec!["node".into(), "pwsh".into()];
        let report = evaluate(&setup, &facts);
        assert_eq!(
            finding(&report, "host.required_tools").detail,
            "not on the runners' PATH: pwsh"
        );
        assert_eq!(report.required_failing(), ["host.required_tools"]);

        // A file that cannot be read is not "none configured".
        setup.required_tools = Vec::new();
        setup.required_tools_error = Some("required-tools.json is not valid".into());
        assert_eq!(
            status_of(&setup, &facts, "host.required_tools"),
            Status::Unknown
        );
    }

    /// Blocked launches fail the doctor with the reason and the remedy, and
    /// never as a Required check: that would make the daemon refuse launches
    /// because launches are refused.
    #[test]
    fn blocked_launches_fail_with_their_remedy_but_never_make_the_host_unfit() {
        let mut setup = windows_setup();
        let facts = Facts::default();
        assert_eq!(status_of(&setup, &facts, "host.launches"), Status::Pass);
        setup.launches_blocked = Some(runner_manager_platform::launch_health::LaunchesBlocked {
            since: chrono::DateTime::from_timestamp(1_790_000_000, 0).unwrap(),
            reason: "a runner launch by process 189 has held the WSL launch fence".into(),
            remedy: "restart the service".into(),
        });
        let report = evaluate(&setup, &facts);
        let launches = finding(&report, "host.launches");
        assert_eq!(launches.status, Status::Fail);
        assert!(
            launches.detail.contains("process 189"),
            "{}",
            launches.detail
        );
        assert_eq!(launches.remedy.as_deref(), Some("restart the service"));
        assert!(
            !report
                .required_failing()
                .contains(&"host.launches".to_owned())
        );
    }

    #[test]
    fn unknown_never_counts_as_unfit() {
        let setup = HostSetup {
            perspective: Perspective::Daemon,
            ..windows_setup()
        };
        struct Broken;
        impl HostFacts for Broken {
            fn elevated(&self) -> bool {
                false
            }
            fn dword(&self, _: RegValue) -> Result<Option<u32>, String> {
                Err("x".into())
            }
            fn string(&self, _: RegValue) -> Result<Option<String>, String> {
                Err("x".into())
            }
            fn defender_exclusions(&self) -> Result<Option<Vec<String>>, String> {
                Err("x".into())
            }
            fn git_system_value(&self, _: &Path, _: &str) -> Result<Option<String>, String> {
                Err("x".into())
            }
            fn symlink_allowed(&self, _: &Path) -> Result<bool, String> {
                Err("x".into())
            }
            fn find_tool(&self, _: &str, _: Option<&str>) -> Option<PathBuf> {
                None
            }
            fn file_exists(&self, _: &Path) -> bool {
                false
            }
            fn memory_bytes(&self) -> Option<u64> {
                None
            }
            fn cpu_count(&self) -> usize {
                1
            }
            fn spotlight_indexing(&self, _: &Path) -> Result<Option<bool>, String> {
                Err("x".into())
            }
            fn directory_responds(&self, _: &Path) -> host_fitness::Responsiveness {
                host_fitness::Responsiveness::Failed("x".into())
            }
            fn mount_point(&self, _: &Path) -> Option<PathBuf> {
                None
            }
            fn launchd_process_type(&self, _: &Path) -> Result<Option<String>, String> {
                Err("x".into())
            }
            fn throttled_runner_processes(&self) -> Result<usize, String> {
                Err("x".into())
            }
            fn service_credential(
                &self,
                _: &Path,
                _: Option<&Path>,
            ) -> Result<CredentialProbe, String> {
                Err("x".into())
            }
        }
        let report = evaluate(&setup, &Broken);
        assert_eq!(
            finding(&report, "windows.symlink_privilege").status,
            Status::Unknown
        );
        assert!(report.required_failing().is_empty());
    }

    struct Scripted {
        answers: Vec<bool>,
        asked: Vec<String>,
    }

    impl Prompt for Scripted {
        fn confirm(&mut self, question: &str) -> Option<bool> {
            self.asked.push(question.to_owned());
            Some(self.answers.remove(0))
        }
    }

    fn report_needing_everything() -> Report {
        let mut setup = windows_setup();
        setup.service.as_mut().unwrap().start_mode = StartMode::Login;
        let facts = Facts {
            elevated: true,
            exclusions: Some(Vec::new()),
            git: Some(PathBuf::from(r"C:\Git\cmd\git.exe")),
            ..Facts::default()
        };
        evaluate(&setup, &facts)
    }

    #[test]
    fn a_security_tradeoff_is_never_planned_without_its_flag_or_a_yes() {
        let report = report_needing_everything();
        let plan_without = plan(
            &report,
            &[],
            &Consent {
                assume_yes: true,
                ..Consent::default()
            },
            &mut NoPrompt,
        );
        assert!(!plan_without.apply.contains(&"windows.defender_exclusion"));
        assert!(!plan_without.apply.contains(&"windows.symlink_privilege"));
        assert!(plan_without.apply.contains(&"windows.long_paths"));
        assert!(
            plan_without
                .held
                .iter()
                .any(|(id, reason)| *id == "windows.defender_exclusion"
                    && reason.contains(ALLOW_AV_EXCLUSION))
        );

        let flagged = plan(
            &report,
            &[],
            &Consent {
                allow_av_exclusion: true,
                ..Consent::default()
            },
            &mut NoPrompt,
        );
        assert!(flagged.apply.contains(&"windows.defender_exclusion"));
        assert!(!flagged.apply.contains(&"windows.symlink_privilege"));

        let mut prompt = Scripted {
            answers: vec![false, true],
            asked: Vec::new(),
        };
        let asked = plan(&report, &[], &Consent::default(), &mut prompt);
        assert_eq!(prompt.asked.len(), 2);
        assert!(asked.apply.contains(&"windows.defender_exclusion"));
        assert!(
            asked
                .held
                .iter()
                .any(|(id, _)| *id == "windows.symlink_privilege")
        );
    }

    #[test]
    fn only_restricts_the_plan() {
        let report = report_needing_everything();
        let plan = plan(
            &report,
            &["windows.long_paths".into()],
            &Consent::default(),
            &mut NoPrompt,
        );
        assert_eq!(plan.apply, ["windows.long_paths"]);
    }

    struct FakeElevator<'a> {
        facts: &'a Facts,
        actions: &'a Actions<'a>,
        refuse: bool,
        requests: RefCell<Vec<ElevatedRequest>>,
    }

    impl Elevator for FakeElevator<'_> {
        fn elevate(&self, request: &ElevatedRequest) -> Result<Vec<FixResult>, ElevationFailure> {
            self.requests.borrow_mut().push(request.clone());
            if self.refuse {
                return Err(ElevationFailure::Refused);
            }
            Ok(run_request(request, self.facts, self.actions))
        }
    }

    #[test]
    fn admin_fixes_go_to_one_elevated_run_and_a_refusal_is_reported_per_check() {
        let setup = windows_setup();
        let facts = Facts::default();
        let actions = Actions::default();
        let elevator = FakeElevator {
            facts: &facts,
            actions: &actions,
            refuse: false,
            requests: RefCell::default(),
        };
        let request = ElevatedRequest {
            setup: setup.clone(),
            apply: vec![
                "windows.long_paths".into(),
                "windows.execution_policy".into(),
            ],
            revert: Vec::new(),
        };
        let results = execute(request.clone(), &facts, &actions, &elevator);
        assert_eq!(
            elevator.requests.borrow().len(),
            1,
            "one prompt for the batch"
        );
        assert_eq!(elevator.requests.borrow()[0].apply.len(), 2);
        assert!(
            results
                .iter()
                .all(|r| matches!(r.outcome, FixOutcome::Applied { .. }))
        );
        assert_eq!(
            *actions.log.borrow(),
            [
                "dword LongPathsEnabled=Some(1)",
                "string ExecutionPolicy=Some(\"RemoteSigned\")"
            ]
        );

        let refusing = FakeElevator {
            refuse: true,
            ..elevator
        };
        let results = execute(request, &facts, &actions, &refusing);
        assert!(results.iter().all(|r| matches!(
            &r.outcome,
            FixOutcome::NotAttempted { reason } if reason.contains("refused")
        )));
    }

    #[test]
    fn an_elevated_process_applies_in_process_and_never_relaunches() {
        let setup = windows_setup();
        let facts = Facts {
            elevated: true,
            ..Facts::default()
        };
        let actions = Actions::default();
        let elevator = FakeElevator {
            facts: &facts,
            actions: &actions,
            refuse: true,
            requests: RefCell::default(),
        };
        let results = execute(
            ElevatedRequest {
                setup,
                apply: vec!["windows.long_paths".into()],
                revert: Vec::new(),
            },
            &facts,
            &actions,
            &elevator,
        );
        assert!(elevator.requests.borrow().is_empty());
        assert!(matches!(results[0].outcome, FixOutcome::Applied { .. }));
    }

    #[test]
    fn a_fix_re_probes_first_and_changes_nothing_that_already_passes() {
        let setup = windows_setup();
        let mut facts = Facts::default();
        facts.dwords.insert(RegValue::LongPathsEnabled, Ok(Some(1)));
        let actions = Actions::default();
        assert_eq!(
            apply_one("windows.long_paths", &setup, &facts, &actions).outcome,
            FixOutcome::AlreadyDone
        );
        assert!(actions.log.borrow().is_empty());
    }

    #[test]
    fn a_revert_restores_exactly_what_the_fix_replaced() {
        let setup = windows_setup();
        let mut facts = Facts {
            git: Some(PathBuf::from(r"C:\Git\cmd\git.exe")),
            ..Facts::default()
        };
        facts
            .git_values
            .borrow_mut()
            .insert(GIT_LONG_PATHS.into(), "false".into());
        facts.dwords.insert(RegValue::LongPathsEnabled, Ok(Some(0)));
        let actions = Actions {
            git: Some(&facts),
            ..Actions::default()
        };
        let fixed = run_request(
            &ElevatedRequest {
                setup: setup.clone(),
                apply: vec!["windows.long_paths".into(), "windows.git_long_paths".into()],
                revert: Vec::new(),
            },
            &facts,
            &actions,
        );
        let mut journal = Journal::default();
        update_journal(&mut journal, &fixed, chrono::Utc::now());
        assert_eq!(journal.entries.len(), 2);
        let revert: Vec<(String, Vec<Change>)> = journal
            .entries
            .iter()
            .map(|(id, entry)| (id.clone(), entry.changes.clone()))
            .collect();
        actions.log.borrow_mut().clear();
        let reverted = run_request(
            &ElevatedRequest {
                setup,
                apply: Vec::new(),
                revert,
            },
            &facts,
            &actions,
        );
        assert!(reverted.iter().all(|r| r.outcome == FixOutcome::Reverted));
        assert_eq!(
            *actions.log.borrow(),
            [
                "git core.longpaths=Some(\"false\")",
                "dword LongPathsEnabled=Some(0)"
            ]
        );
        update_journal(&mut journal, &reverted, chrono::Utc::now());
        assert!(journal.entries.is_empty());
    }

    #[test]
    fn a_second_prepare_keeps_the_first_previous_value() {
        let now = chrono::Utc::now();
        let first = FixResult {
            id: "windows.long_paths".into(),
            outcome: FixOutcome::Applied {
                changes: vec![Change::RegistryDword {
                    value: RegValue::LongPathsEnabled,
                    previous: Some(0),
                    applied: 1,
                }],
            },
        };
        let second = FixResult {
            id: "windows.long_paths".into(),
            outcome: FixOutcome::Applied {
                changes: vec![Change::RegistryDword {
                    value: RegValue::LongPathsEnabled,
                    previous: Some(1),
                    applied: 1,
                }],
            },
        };
        let mut journal = Journal::default();
        update_journal(&mut journal, &[first, second], now);
        assert_eq!(
            journal.entries["windows.long_paths"].changes,
            [Change::RegistryDword {
                value: RegValue::LongPathsEnabled,
                previous: Some(0),
                applied: 1
            }]
        );
    }

    #[test]
    fn a_tampered_journal_cannot_make_a_revert_write_an_arbitrary_value() {
        let actions = Actions::default();
        for change in [
            Change::RegistryDword {
                value: RegValue::MachinePath,
                previous: Some(0),
                applied: 1,
            },
            Change::RegistryString {
                value: RegValue::ExecutionPolicy,
                previous: Some("Anything; Evil".into()),
                applied: "RemoteSigned".into(),
            },
            Change::GitSystemConfig {
                git: PathBuf::from("git"),
                name: "core.sshCommand".into(),
                previous: Some("evil".into()),
                applied: "x".into(),
            },
        ] {
            assert!(change.revert(&actions).is_err(), "{change:?}");
        }
        assert!(actions.log.borrow().is_empty());
    }

    #[test]
    fn the_elevated_request_round_trips_through_its_command_line() {
        let request = ElevatedRequest {
            setup: macos_setup(),
            apply: vec!["macos.spotlight".into()],
            revert: vec![(
                "windows.defender_exclusion".into(),
                vec![Change::DefenderExclusions {
                    added: vec![r"C:\r m\'x".into()],
                }],
            )],
        };
        let text = serde_json::to_string(&request).unwrap();
        assert_eq!(
            serde_json::from_str::<ElevatedRequest>(&text).unwrap(),
            request
        );
    }

    #[test]
    fn environment_references_expand_and_unknown_ones_survive() {
        // SAFETY-free: reads a variable every process has on its platform.
        let path = std::env::var("PATH").unwrap();
        assert_eq!(expand_environment("%PATH%;x"), format!("{path};x"));
        assert_eq!(
            expand_environment("%NO_SUCH_RM_VAR%\\a"),
            "%NO_SUCH_RM_VAR%\\a"
        );
        assert_eq!(expand_environment("100%"), "100%");
    }

    #[test]
    fn powershell_lists_escape_single_quotes() {
        assert_eq!(
            powershell_list(&[r"C:\a".into(), "it's".into()]),
            r"@('C:\a','it''s')"
        );
    }

    fn rooted_context(root: &Path) -> Context {
        let endpoints =
            runner_manager_github::Endpoints::for_test_server("http://127.0.0.1:9").unwrap();
        Context::rooted_against(root, endpoints).unwrap()
    }

    /// The whole prepare path against fakes: nothing is applied without a yes
    /// and with nobody to ask, and with one the batch goes to one elevated
    /// run and every change lands in the journal with what it replaced.
    fn unfit_record(id: &str) -> host_fitness::HostUnfitRecord {
        host_fitness::HostUnfitRecord {
            schema_version: 1,
            since: chrono::Utc::now(),
            checked_at: chrono::Utc::now(),
            checks: vec![id.into()],
            findings: vec![host_fitness::UnfitFinding {
                id: id.into(),
                detail: "it fails for the service".into(),
                remedy: None,
            }],
        }
    }

    /// What the service found is reported, never prepared: a run plans from
    /// this host's own probes and judges them afterwards, and the elevated
    /// copy is not handed the record.
    #[test]
    fn prepare_neither_plans_nor_judges_by_the_services_record() {
        let root = tempfile::tempdir().unwrap();
        let context = rooted_context(root.path());
        let mut setup = windows_setup();
        setup.daemon_unfit = Some(unfit_record("windows.long_paths"));
        let facts = Facts {
            dwords: [(RegValue::LongPathsEnabled, Ok(Some(1)))].into(),
            exclusions: Some(Vec::new()),
            ..Facts::default()
        };
        assert_eq!(
            status_of(&setup, &facts, "windows.long_paths"),
            Status::Fail,
            "host doctor reports the service's finding"
        );
        let actions = Actions::default();
        let elevator = FakeElevator {
            facts: &facts,
            actions: &actions,
            refuse: false,
            requests: RefCell::default(),
        };
        let outcome = prepare(
            PrepareRun {
                context: &context,
                setup: setup.clone(),
                facts: &facts,
                actions: &actions,
                elevator: &elevator,
                prompt: &mut NoPrompt,
                consent: Consent {
                    assume_yes: true,
                    ..Consent::default()
                },
            },
            &["windows.long_paths".to_owned()],
            &mut Vec::new(),
        )
        .unwrap();
        assert!(outcome.results.is_empty(), "{outcome:?}");
        assert_eq!(
            finding(&outcome.after, "windows.long_paths").status,
            Status::Pass
        );
        let encoded = serde_json::to_string(&setup).unwrap();
        assert!(!encoded.contains("daemon_unfit"), "{encoded}");
    }

    /// The service's own "my checks never finished" is a check `host doctor`
    /// shows, not a refusal only `status` knows about.
    #[test]
    fn host_checks_the_service_could_not_finish_fail_in_host_doctor() {
        let mut setup = macos_setup();
        let facts = Facts::default();
        assert_eq!(status_of(&setup, &facts, BLOCKED_CHECKS_ID), Status::Pass);
        setup.daemon_unfit = Some(unfit_record(BLOCKED_CHECKS_ID));
        let report = evaluate(&setup, &facts);
        assert_eq!(finding(&report, BLOCKED_CHECKS_ID).status, Status::Fail);
        assert!(
            report
                .required_failing()
                .iter()
                .any(|id| id == BLOCKED_CHECKS_ID)
        );
    }

    #[test]
    fn prepare_needs_a_yes_then_elevates_once_and_journals_what_it_changed() {
        let root = tempfile::tempdir().unwrap();
        let context = rooted_context(root.path());
        let setup = windows_setup();
        let facts = Facts {
            exclusions: Some(Vec::new()),
            ..Facts::default()
        };
        let actions = Actions::default();
        let elevator = FakeElevator {
            facts: &facts,
            actions: &actions,
            refuse: false,
            requests: RefCell::default(),
        };
        let run = |consent: Consent, out: &mut Vec<u8>| {
            prepare(
                PrepareRun {
                    context: &context,
                    setup: setup.clone(),
                    facts: &facts,
                    actions: &actions,
                    elevator: &elevator,
                    prompt: &mut NoPrompt,
                    consent,
                },
                &[],
                out,
            )
        };

        let refused = run(Consent::default(), &mut Vec::new()).unwrap_err();
        assert_eq!(refused.class(), Failure::InvalidArgument);
        assert!(
            actions.log.borrow().is_empty(),
            "nothing may change without a yes"
        );
        assert!(elevator.requests.borrow().is_empty());
        assert!(!journal_path(&context).exists());

        let mut out = Vec::new();
        let outcome = run(
            Consent {
                assume_yes: true,
                ..Consent::default()
            },
            &mut out,
        )
        .unwrap();
        let text = String::from_utf8(out).unwrap();
        assert_eq!(elevator.requests.borrow().len(), 1, "{text}");
        assert!(
            outcome
                .held
                .iter()
                .any(|(id, _)| *id == "windows.defender_exclusion"),
            "--yes alone never applies a security trade-off: {text}"
        );
        assert!(
            !actions
                .log
                .borrow()
                .iter()
                .any(|line| line.starts_with("defender"))
        );
        let journal = read_journal(&journal_path(&context)).unwrap();
        assert_eq!(
            journal.entries["windows.long_paths"].changes,
            [Change::RegistryDword {
                value: RegValue::LongPathsEnabled,
                previous: None,
                applied: 1
            }]
        );
    }

    #[test]
    fn the_summary_line_counts_by_severity() {
        let failing = |id: &str, severity| FindingSummary {
            id: id.into(),
            severity,
            title: String::new(),
            detail: String::new(),
            remedy: None,
            fixable: true,
            needs_admin: true,
            consent_flag: None,
        };
        let summary = DoctorSummary {
            checked: 9,
            failing: vec![
                failing("a", Severity::Required),
                failing("b", Severity::Recommended),
            ],
            unknown: Vec::new(),
            daemon_host_unfit: None,
        };
        assert_eq!(
            summary.line(),
            "1 required, 1 recommended failing (a, b); runner-manager host doctor"
        );
        let clean = DoctorSummary {
            failing: Vec::new(),
            ..summary
        };
        assert_eq!(clean.line(), "ok (9 checks)");
    }

    fn polling_setup(
        traffic: Option<runner_manager_platform::polling::PollTraffic>,
        stale: bool,
    ) -> HostSetup {
        HostSetup {
            polling: Some(PollingFacts {
                idle_secs: 10,
                active_secs: 60,
                traffic,
                stale,
            }),
            ..windows_setup()
        }
    }

    fn measured(throttled_because: Option<&str>) -> runner_manager_platform::polling::PollTraffic {
        let mut traffic = runner_manager_platform::polling::PollTraffic::new(chrono::Utc::now());
        traffic.observed_minutes = 60;
        traffic.full = 40;
        traffic.not_modified = 680;
        traffic.peak_requests_per_minute = 14;
        traffic.rate_limit_limit = Some(5_000);
        traffic.rate_limit_remaining = Some(4_200);
        traffic.throttled_because = throttled_because.map(str::to_string);
        traffic
    }

    #[test]
    fn the_polling_check_reports_the_intervals_the_304_share_and_throttling() {
        let facts = Facts::default();
        let healthy = evaluate(&polling_setup(Some(measured(None)), false), &facts);
        let found = finding(&healthy, "github.polling");
        assert_eq!(
            (found.status, found.severity),
            (Status::Pass, Severity::Info)
        );
        for part in [
            "idle every 10s",
            "active every 60s",
            "94% of 720",
            "4200 of 5000",
            "not throttled",
        ] {
            assert!(found.detail.contains(part), "{part}: {}", found.detail);
        }

        let throttled = evaluate(
            &polling_setup(Some(measured(Some("the quota is low"))), false),
            &facts,
        );
        let found = finding(&throttled, "github.polling");
        assert_eq!(found.status, Status::Fail);
        assert!(
            found.detail.contains("Throttled: the quota is low"),
            "{}",
            found.detail
        );
        assert!(
            !found.needs_attention(),
            "information only: a throttled host recovers by waiting"
        );

        let stale = evaluate(&polling_setup(Some(measured(None)), true), &facts);
        assert_eq!(finding(&stale, "github.polling").status, Status::Unknown);

        // Every wording, read in full: a lost line continuation pads a
        // sentence with a run of spaces that no substring check notices.
        for report in [&healthy, &throttled, &stale] {
            let found = finding(report, "github.polling");
            for text in [Some(&found.detail), found.remedy.as_ref()]
                .into_iter()
                .flatten()
            {
                assert!(!text.contains("  "), "a run of spaces: {text}");
            }
        }

        let never = evaluate(&polling_setup(None, false), &facts);
        assert_eq!(finding(&never, "github.polling").status, Status::Pass);
        let unreadable = evaluate(&windows_setup(), &facts);
        assert_eq!(
            finding(&unreadable, "github.polling").status,
            Status::Unknown
        );
    }
}