runner-manager 0.4.8

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
// owner: f1-cli-auth-host-status
//
// f1 owns this module list and `dispatch`, plus `auth`, `host` and `status`;
// f2 owns `policy`; f3 owns `daemon` and `service`.

//! The command tree, the exit-code taxonomy, and the composition root.
//!
//! # The command surface is declared whole, here, once
//!
//! `02-target-architecture.md` lists the binary's commands and says *"This list
//! is exhaustive"*. All of it is declared in this file — including the `repo`,
//! `org`, `daemon` and `service` families that `f2` and `f3` implement — so that
//! those tasks attach handlers to a shape that already exists rather than
//! growing the surface one task at a time. A command that appears only when its
//! implementer arrives is a command nobody can write a script against, and
//! `--help` is the thing an operator reads before deciding whether this tool
//! does what they need.
//!
//! The unimplemented arms return [`Failure::NotImplemented`] and name the task
//! that owns them. That is deliberately a *distinct* exit code: a script that
//! runs `repo add` today must be able to tell "this build cannot do that yet"
//! from "your arguments were wrong".
//!
//! # Exit codes are a scripting contract
//!
//! `f1`, `f2` and `f3` all require *"distinct exit codes per failure class"*, so
//! the taxonomy lives here rather than in each command file. [`Failure`] is the
//! whole of it; `the_exit_codes_are_distinct_and_non_zero` in the tests below is
//! what keeps two classes from quietly collapsing onto one number.
//!
//! # What the composition root actually composes
//!
//! [`Context`] resolves — once, at the top — the four things every command below
//! needs and none of them may resolve for itself:
//!
//! | Thing | Where it comes from | Why it is here |
//! |---|---|---|
//! | [`AppPaths`] | `d1` | Two resolutions in one process must agree |
//! | the SQLite [`Store`] | `b2` | Its path is `config/`, which only `AppPaths` knows |
//! | the [`SecretStore`] | `d2` | Its *scope* follows the host's start mode (D13) |
//! | [`Endpoints`] + [`AppRegistration`] | `c2` | The published App is a product fact, not a per-command one |

pub mod auth;
pub mod daemon;
pub mod host;
pub mod policy;
pub mod service;
pub mod status;
pub mod ui;
pub mod update;
pub mod workspace;
pub mod wsl;

use std::fmt;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::Arc;

use clap::{Args, Parser, Subcommand};
use runner_manager_domain::model::{Clock, Host, StartMode, SystemClock};
use runner_manager_domain::store::{SqliteStore, Store};
use runner_manager_domain::workspace::WorkspaceKind;
use runner_manager_github::{AppRegistration, Endpoints};
use runner_manager_platform::paths::AppPaths;
use runner_manager_platform::secrets::{PlatformSecretStore, SecretScope, SecretStore};

// ---------------------------------------------------------------------------
// The published App
// ---------------------------------------------------------------------------

/// The published GitHub App's OAuth client id.
///
/// Phase 0 of `06-migration-rollout.md` — registering and publishing the App —
/// landed on 2026-08-24. This is the real client id of `runner-manager-scaler`
/// (App id 4707028), which declares exactly the permission set the README's
/// disclosure names, has Device Flow enabled, and holds no webhook URL.
///
/// **It is not a secret.** A device-flow client id is sent to GitHub by every
/// copy of this program and appears in the request an operator can watch; what
/// authenticates a user is the code they type on GitHub's own page. The App's
/// private key is the thing that would matter, and this project never generates
/// one — which is what makes "the project cannot act on your repositories even
/// in principle" true rather than a promise.
///
/// It was empty until Phase 0 landed, because a plausible-looking placeholder
/// would produce a device flow that fails against GitHub with
/// `incorrect_client_credentials` — a message that reads like a GitHub outage
/// rather than like an unfinished rollout. Empty produced
/// [`Failure::AppNotPublished`], which said exactly what was wrong.
pub const PUBLISHED_CLIENT_ID: &str = "Iv23liUGaKmwt8p3ZxRc";

/// The published App's slug, the `<slug>` in
/// `github.com/apps/<slug>/installations/new`.
///
/// Renaming the App changes this, and a released binary keeps sending users to
/// the slug it was built with — so a rename needs a release, not just a setting.
pub const PUBLISHED_APP_SLUG: &str = "runner-manager-scaler";

/// Overrides the client id, for a test that drives a fake GitHub.
pub const CLIENT_ID_VARIABLE: &str = "RUNNER_MANAGER_GITHUB_CLIENT_ID";
/// Overrides the App slug, for a test that drives a fake GitHub.
pub const APP_SLUG_VARIABLE: &str = "RUNNER_MANAGER_GITHUB_APP_SLUG";

/// Points every GitHub endpoint at another origin.
///
/// # This is a test seam and it is restricted to loopback
///
/// The device flow ends with a bearer token being handed to whatever answered
/// the access-token request, so an environment variable that could redirect
/// `github.com` to an arbitrary host would be a credential-harvesting primitive
/// aimed at whoever runs `auth login` next. [`Context::resolve_endpoints`]
/// therefore accepts **only** a loopback origin, and says loudly on stderr that
/// it is not talking to GitHub.
///
/// It exists because there is no other way to exercise `auth login` end to end:
/// `crates/app` has no HTTP mocking dev-dependency and may not acquire one
/// (`a1` owns every manifest), and `DeviceFlow` is a concrete type with no
/// gateway trait. The alternative was to leave the whole authentication path
/// untested against the real client.
pub const GITHUB_BASE_URL_VARIABLE: &str = "RUNNER_MANAGER_GITHUB_BASE_URL";

/// The file the local SQLite database lives in, under `config/`.
///
/// `05-infrastructure.md` puts *"non-secret TOML and SQLite"* in `config/`;
/// this is the SQLite half. Named rather than inlined because `f2`, `f3` and
/// `g1` all reach the same database through [`Context::store`] and a second
/// spelling would be a second database.
pub const DATABASE_FILE: &str = "runner-manager.sqlite3";

/// Where `--data-dir` can also be given.
pub const DATA_DIR_VARIABLE: &str = "RUNNER_MANAGER_DATA_DIR";

/// The default `host_capacity` for a host record this tool creates.
///
/// **One, chosen rather than inferred.** `f1`'s specification is explicit that
/// a capacity value *"comes from an observed workload measurement"* and must
/// never be derived from a runner count, so the only honest default is the most
/// conservative non-zero one: this host will start at most one runner attempt
/// until its operator says otherwise. `03-control-flows.md` step 2 assumes
/// exactly this shape — *"runs `host set-capacity 2` if the host default is not
/// acceptable"*.
pub const DEFAULT_HOST_CAPACITY: u16 = 1;

// ---------------------------------------------------------------------------
// Exit codes
// ---------------------------------------------------------------------------

/// One number per failure class, for a script to branch on.
///
/// `2` is absent because clap owns it: a usage error exits `2` before any of
/// this runs, and re-using it for a runtime failure would make the two
/// indistinguishable to the caller. `1` is [`Failure::Unclassified`] and is the
/// bucket a failure lands in when it has not been classified — a value worth
/// having precisely so that "we forgot to classify this" is visible rather than
/// disguised as one of the named classes.
//
// ----------------------------------------------------------------------------
// THE TAXONOMY IS DECLARED ONCE AND EVERYTHING IS DERIVED FROM THAT DECLARATION.
// ----------------------------------------------------------------------------
// `Failure::ALL` used to be a hand-maintained array typed `[Failure; 19]`,
// parallel to the enum rather than derived from it. That is a real hole and not
// a stylistic one: adding a variant forces an edit to `as_str`'s exhaustive
// match — the compiler sees to that — but nothing forced an edit to `ALL`, so a
// new class was invisible to every test that iterates it.
//
// Worth being exact about which half rustc already covers, because the two are
// easy to conflate. A *duplicate* discriminant is a compile error either way:
// this is a `#[repr(u8)]` enum with an explicit value on every variant, so
// `RateLimited = 4` beside `AuthenticationFailed = 4` is E0081 and never
// reaches a test. What rustc does not catch is a class on a *fresh* value that
// is nonetheless wrong — `RateLimited = 2`, on the code clap already owns for a
// usage error. Under the old shape that compiled, `ALL` stayed at nineteen,
// `the_exit_codes_are_distinct_and_non_zero` never iterated the new class, and
// the whole suite passed: measured, 39 passed / 0 failed. Under this shape the
// same edit fails that test on `assert_ne!(class.code(), 2)`. The Definition of
// Done reads "every command returns a distinct non-zero exit code per failure
// class", and that is the gap it was leaving open.
//
// Rust cannot enumerate an enum's variants without a macro or a derive, and no
// derive crate is available here (`a1` owns every manifest). So the list below
// is the *only* place a class is written down: the enum, `ALL`, and `as_str`
// are all expanded from it. Adding a class to the enum without adding it to
// `ALL` is no longer something a person can do — there is one list, and it
// feeds all three.
//
// `dead_code` is allowed for the same reason the command tree above is declared
// whole: the taxonomy is a scripting contract, and the classes `f2` and `f3`
// will raise (`NotFound`, `Conflict`, `BudgetRefused`) have to hold their
// numbers before those tasks land, or the numbers move under a script that was
// already written against them. This crate is a `[[bin]]`, so an unused `pub`
// item is dead code rather than public API.
macro_rules! failure_taxonomy {
    (
        $(
            $(#[$documentation:meta])*
            $variant:ident = $code:literal => $name:literal,
        )+
    ) => {
        #[allow(dead_code)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        #[repr(u8)]
        pub enum Failure {
            $(
                $(#[$documentation])*
                $variant = $code,
            )+
        }

        impl Failure {
            /// Every class, expanded from the same declaration as the enum, so
            /// it cannot fall behind it.
            #[allow(
                dead_code,
                reason = "read by the distinctness proof in this file's tests"
            )]
            pub const ALL: &'static [Failure] = &[$(Failure::$variant,)+];

            /// The stable name a `--json` document and a log field use.
            #[must_use]
            pub const fn as_str(self) -> &'static str {
                match self {
                    $(Self::$variant => $name,)+
                }
            }
        }
    };
}

failure_taxonomy! {
    /// Something went wrong that this taxonomy does not name yet.
    Unclassified = 1 => "unclassified",
    /// No credential is stored on this host. Remedy: `auth login`.
    NotAuthenticated = 3 => "not_authenticated",
    /// GitHub rejected the stored credential. Remedy: `auth login`.
    AuthenticationFailed = 4 => "authentication_failed",
    /// GitHub's temporary authentication lockout. Remedy: wait.
    AuthenticationLockout = 5 => "authentication_lockout",
    /// The user declined the login on GitHub. **Not** a case to retry: the same
    /// login presented again re-prompts somebody who has already said no.
    AuthenticationDeclined = 6 => "authentication_declined",
    /// GitHub could not be reached at all.
    GithubUnavailable = 7 => "github_unavailable",
    /// GitHub answered, refusing on rate-limit or permission grounds.
    GithubRefused = 8 => "github_refused",
    /// An argument was well-formed for clap and wrong for the domain.
    InvalidArgument = 9 => "invalid_argument",
    /// The thing named does not exist locally.
    NotFound = 10 => "not_found",
    /// A concurrent change, a duplicate, or a held lock.
    Conflict = 11 => "conflict",
    /// The projected REST budget will not admit this configuration.
    BudgetRefused = 12 => "budget_refused",
    /// The machine-scoped secret store could not be reached.
    SecretStore = 13 => "secret_store",
    /// Local configuration or the SQLite journal could not be read or written.
    LocalState = 14 => "local_state",
    /// This host's OS or architecture is outside GitHub's documented matrix.
    UnsupportedHost = 15 => "unsupported_host",
    /// This build carries no published GitHub App registration.
    AppNotPublished = 16 => "app_not_published",
    /// A declared command whose implementing task has not landed.
    NotImplemented = 17 => "not_implemented",
    /// The device code expired, or GitHub stopped recognising it. Unlike
    /// [`Failure::AuthenticationDeclined`], starting a fresh login is the right
    /// response and a script may do it unattended.
    AuthenticationExpired = 18 => "authentication_expired",
    /// GitHub says the published App itself is wrong — device flow not
    /// enabled, or a `client_id` it does not know. No operator action helps;
    /// a maintainer must fix the registration.
    AppMisconfigured = 19 => "app_misconfigured",
    /// GitHub's answer could not be used: it did not decode, it carried a value
    /// this client cannot accept, or — the security case — it pointed the login
    /// at a verification page that is not GitHub's own.
    UnusableResponse = 20 => "unusable_response",
    /// A newer binary was installed at this daemon's own path, every runner it
    /// held has finished, and it stopped so the new one can take over.
    ///
    /// **This is not a failure, and it is in this enum because the operating
    /// system has no other word for it.** All three service managers reinstate
    /// a service only when it exits non-zero — systemd `Restart=on-failure`,
    /// launchd `KeepAlive{SuccessfulExit:false}`, and the Windows failure
    /// actions this product configures. A clean exit is read as "this service
    /// is done" and nothing restarts it, which for an upgrade would leave the
    /// machine with no daemon at all. So the restart is bought with a non-zero
    /// code, and this variant exists to say which one and why.
    UpgradePending = 21 => "upgrade_pending",
    /// `update` will not update this copy, and nothing was attempted. Either
    /// it is not an installation at all -- a build in a checkout, or the
    /// private copy the service runs -- or the package manager that owns it is
    /// not on this PATH.
    ///
    /// Distinct from [`Failure::UpdateFailed`] because the two need opposite
    /// responses: this one says the command was aimed at the wrong file and the
    /// remedy names the right one, and re-running `update` here will refuse
    /// again forever.
    UpdateUnsupported = 22 => "update_unsupported",
    /// `update` was attempted and did not complete: a package manager exited
    /// non-zero, or the replacement could not be carried out.
    ///
    /// The binary in place is the one that was there before -- every path that
    /// raises this either changed nothing or put the previous file back.
    UpdateFailed = 23 => "update_failed",
    /// A managed WSL host operation ran and did not complete: `wsl.exe` or
    /// `schtasks.exe` refused, a Linux step exited non-zero, or the final
    /// read-back found the host only partly provisioned.
    ///
    /// Its own class rather than [`Failure::Unclassified`] because the whole
    /// provisioning transaction is designed to be **rerun**
    /// (`03-security-and-lifecycle.md`, "Provisioning failure model"): a script
    /// that meets this knows the remedy is "fix what the report names, then run
    /// `wsl install` again", which is true of no other class here. The
    /// preflight refusals are deliberately *not* this — they are
    /// [`Failure::UnsupportedHost`] and [`Failure::InvalidArgument`], because
    /// nothing was changed and rerunning without fixing the distribution
    /// changes nothing either.
    WslProvisioning = 24 => "wsl_provisioning",
}

impl Failure {
    /// The process exit code for this class.
    #[must_use]
    pub const fn code(self) -> u8 {
        self as u8
    }
}

impl fmt::Display for Failure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A failure with the two things an operator needs: what happened, and the
/// command that fixes it.
///
/// `f1`: *"Every failure explains itself in one screenful, without exposing
/// credentials, and names the command that fixes it."* The `remedy` field is
/// that last clause made structural — a failure constructed without one is
/// visible in the source rather than only in the rendered output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CliError {
    class: Failure,
    message: String,
    remedy: Option<String>,
}

impl CliError {
    /// A failure whose remedy is not a command this tool offers.
    #[must_use]
    pub fn new(class: Failure, message: impl Into<String>) -> Self {
        Self {
            class,
            message: message.into(),
            remedy: None,
        }
    }

    /// A failure and the command that clears it.
    #[must_use]
    pub fn with_remedy(
        class: Failure,
        message: impl Into<String>,
        remedy: impl Into<String>,
    ) -> Self {
        Self {
            class,
            message: message.into(),
            remedy: Some(remedy.into()),
        }
    }

    #[must_use]
    pub const fn class(&self) -> Failure {
        self.class
    }

    #[must_use]
    #[allow(dead_code, reason = "read by the failure-copy tests in `auth`")]
    pub fn message(&self) -> &str {
        &self.message
    }

    #[must_use]
    #[allow(dead_code, reason = "read by the failure-copy tests in `auth`")]
    pub fn remedy(&self) -> Option<&str> {
        self.remedy.as_deref()
    }

    /// Renders onto stderr in the shape every command uses.
    pub fn render(&self, err: &mut dyn Write) -> io::Result<()> {
        // Styled from stderr's own terminal-ness rather than stdout's: a run
        // whose output is piped to a file still shows its failures to a human,
        // and that human should get the red label. The plain rendering is
        // unchanged — `error: `, then `  try: ` — so every exit-code test and
        // every log that captures stderr reads exactly what it read before.
        ui::Ui::new(Styling::for_stderr()).error(err, &self.message, self.remedy.as_deref())
    }
}

impl fmt::Display for CliError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

/// The phrase a failure uses when nothing the operator can type will help.
///
/// Stated as a constant because it is load-bearing rather than decorative.
/// `every_failure_says_what_to_do_next` treats "carries a remedy" and "says
/// plainly that no remedy exists" as the two allowed answers and checks them as
/// an exact bi-implication, so a phrase is what makes the second answer
/// recognisable. Without one that test degenerated into accepting any message
/// at all — it matched the substring `"Nothing was stored."`, which several
/// arms emit *alongside* a remedy.
///
/// It lives here rather than in [`auth`] because three different mappers owe
/// the same guarantee: `auth`'s two error mappers and
/// [`Context::app_registration`]. The first version of this constant was
/// `auth`-local, and the mapper one function away from it was left carrying
/// neither a remedy nor the phrase.
pub const NO_OPERATOR_REMEDY: &str = "there is no command here that fixes this";

/// The failure every command reaches when its output sink gives way.
///
/// One definition rather than one per command file. `auth`, `host` and `status`
/// each had a byte-identical copy of this, and `f2` and `f3` would have added a
/// fourth and a fifth — every one of them constructing the same
/// [`Failure::Unclassified`] from the same `io::Error`.
///
/// `what` names the thing that was being written, because "cannot write to this
/// terminal" is the same sentence whether a status document or a permission
/// disclosure was cut short, and the two are worth telling apart in a bug
/// report.
///
/// # Bind it once per command, do not spell it at each call site
///
/// The return type is `Fn + Copy` rather than `FnOnce` for one reason: so a
/// command can write `let failed = write_failed("this sign-out");` at the top
/// and pass `failed` to every `map_err` below it. Repeating the string at each
/// call site is how `auth status` and `auth logout` ended up reporting *"cannot
/// write this sign-in"* — a bulk edit gave one string to a file that holds
/// three commands, and nothing in the shape of the code objected. One binding
/// per command makes that particular mistake unwritable, and puts the string
/// next to the function whose name has to agree with it.
pub fn write_failed(what: &str) -> impl Fn(io::Error) -> CliError + Copy + '_ {
    move |source| {
        CliError::new(
            Failure::Unclassified,
            format!("cannot write {what}: {source}"),
        )
    }
}

// ---------------------------------------------------------------------------
// The command tree
// ---------------------------------------------------------------------------

/// Local-first autoscaling manager for ephemeral GitHub Actions runners.
#[derive(Debug, Parser)]
#[command(
    name = "runner-manager",
    version,
    about = "Local-first autoscaling manager for ephemeral GitHub Actions self-hosted runners.",
    long_about = None,
    propagate_version = true,
    disable_help_subcommand = true
)]
pub struct Cli {
    /// Root for this host's config, state, runtime and log directories.
    ///
    /// Also selects a secret store rooted under it. Without this, the
    /// platform-standard locations are used.
    #[arg(long, value_name = "DIR", global = true, env = DATA_DIR_VARIABLE)]
    pub data_dir: Option<PathBuf>,

    /// Which host this command is addressed to: `local`, or `wsl:NAME`.
    ///
    /// `local` is the default and is this machine, exactly as before. With
    /// `wsl:NAME` the command is carried out inside that managed WSL2
    /// distribution instead, by the copy of runner-manager installed there —
    /// so `--host wsl:Ubuntu repo list` lists the Linux host's policies.
    /// `auth login` is the exception: the sign-in happens here, where the
    /// browser is, and the credential it issues is handed straight to the
    /// Linux host without being stored on this one.
    #[arg(
        long,
        value_name = "HOST",
        global = true,
        default_value = LOCAL_HOST_SELECTOR,
        value_parser = HostSelector::parse,
    )]
    pub host: HostSelector,

    #[command(subcommand)]
    pub command: Command,
}

/// The spelling of `--host`'s default.
pub const LOCAL_HOST_SELECTOR: &str = "local";

/// The prefix that addresses a managed WSL distribution.
pub const WSL_HOST_PREFIX: &str = "wsl:";

/// The long option `--host` is spelled with, as it appears in an argument
/// vector.
///
/// Named because the proxy has to *remove* it from the vector it forwards, and
/// a second spelling there would forward a flag the Linux binary does not know.
pub const HOST_OPTION: &str = "--host";

/// Which host a command is addressed to.
///
/// # Why a value and not a `bool`
///
/// `02-target-architecture.md` requires that `--host local` "preserves every
/// existing invocation", and that `wsl` and `--host wsl:…` on a non-Windows
/// build "fail with an actionable unsupported-platform error rather than
/// disappearing from help". Both are properties of a value that always parses
/// and is refused later, by a command that can say *why* — not of a flag that
/// exists on one platform.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HostSelector {
    /// This machine. The default, and what every invocation written before
    /// this feature means.
    Local,
    /// The named WSL2 distribution on this machine.
    Wsl(String),
}

impl HostSelector {
    /// Parses `local` or `wsl:NAME`.
    ///
    /// The distribution name is **not** validated here beyond being non-empty:
    /// `runner_manager_platform::wsl::discovery::validate_distribution_name`
    /// owns that rule, it produces a sentence naming the rule that was broken,
    /// and a clap usage error would replace that sentence with `error: invalid
    /// value`. So this accepts the shape and the command refuses the name.
    ///
    /// # Errors
    /// A message for clap when the value is neither form.
    pub fn parse(raw: &str) -> Result<Self, String> {
        if raw == LOCAL_HOST_SELECTOR {
            return Ok(Self::Local);
        }
        if let Some(name) = raw.strip_prefix(WSL_HOST_PREFIX) {
            if name.is_empty() {
                return Err(format!(
                    "`{WSL_HOST_PREFIX}` needs the distribution's name after it, as \
                     `--host {WSL_HOST_PREFIX}Ubuntu`. `runner-manager wsl list` names the \
                     ones this machine has."
                ));
            }
            return Ok(Self::Wsl(name.to_string()));
        }
        Err(format!(
            "expected `{LOCAL_HOST_SELECTOR}` or `{WSL_HOST_PREFIX}<distribution>`, not \
             {raw:?}. `runner-manager wsl list` names the distributions this machine has."
        ))
    }

    /// The distribution this addresses, when it is not this machine.
    #[must_use]
    pub fn distribution(&self) -> Option<&str> {
        match self {
            Self::Local => None,
            Self::Wsl(name) => Some(name),
        }
    }
}

impl fmt::Display for HostSelector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Local => f.write_str(LOCAL_HOST_SELECTOR),
            Self::Wsl(name) => write!(f, "{WSL_HOST_PREFIX}{name}"),
        }
    }
}

/// The whole command surface of `02-target-architecture.md`.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Sign in to GitHub, inspect the credential, or purge it.
    #[command(subcommand)]
    Auth(AuthCommand),
    /// Read and change this machine's runner ceiling.
    #[command(subcommand)]
    Host(HostCommand),
    /// Repository-scoped scale policies.
    #[command(subcommand)]
    Repo(RepoCommand),
    /// Organization-scoped scale policies.
    #[command(subcommand)]
    Org(OrgCommand),
    /// Run the host agent in the foreground.
    #[command(subcommand)]
    Daemon(DaemonCommand),
    /// Install, remove, or inspect the OS service.
    #[command(subcommand)]
    Service(ServiceCommand),
    /// Open the terminal UI.
    Tui,
    /// One snapshot of this host, for a human or for a script.
    Status(StatusArgs),
    /// Install the newest release over this one, however it was installed.
    Update(UpdateArgs),
    /// Manage a WSL2 distribution as a second runner host (Windows).
    #[command(subcommand)]
    Wsl(WslCommand),
    /// Keep this distribution's service alive. Not for people.
    ///
    /// ------------------------------------------------------------------
    /// HIDDEN, AND THE HIDING IS PART OF THE DESIGN.
    /// ------------------------------------------------------------------
    /// The Windows lifecycle task's action is
    /// `wsl.exe --distribution NAME --user root --exec
    /// /usr/local/bin/runner-manager wsl-host hold`, and this is the other end
    /// of it: a Linux-only process that starts the systemd unit and then stays
    /// alive so WSL does not retire the distribution. An operator has no
    /// reason to type it — `wsl install` registers the task that does — and
    /// `cli_command_surface.rs` transcribes the *published* surface from the
    /// design document, so a command not in that document has to be hidden for
    /// that test to keep meaning what it says.
    #[command(subcommand, hide = true)]
    WslHost(WslHostCommand),
}

// -- the managed WSL host surface --------------------------------------------

#[derive(Debug, Subcommand)]
pub enum WslCommand {
    /// Name the WSL distributions this machine has, and which are managed.
    List,
    /// Make a distribution a second runner host, or bring one up to date.
    Install(WslInstallArgs),
    /// Report a managed distribution's real state, not its record.
    Status(WslStatusArgs),
    /// Remove this machine's lifecycle task and record. Deletes no Linux data.
    Detach(WslDetachArgs),
}

/// The `--distribution NAME` every `wsl` subcommand but `list` takes.
///
/// The rule is spelled out in full here and abbreviated to its first line in
/// [`WslInstallArgs`] and [`WslStatusArgs`], which take the same option: the
/// value is matched **exactly** against `wsl --list --verbose`, and one full
/// description rather than three is one chance to describe it wrongly rather
/// than three.
#[derive(Debug, Args)]
pub struct WslDetachArgs {
    /// The distribution's exact name, as `wsl --list --verbose` spells it.
    ///
    /// Matched exactly, including case and spaces: WSL allows two names that
    /// differ only in case, and guessing between them would be guessing which
    /// host to change.
    #[arg(long, value_name = "NAME")]
    pub distribution: String,
}

#[derive(Debug, Args)]
pub struct WslInstallArgs {
    /// The distribution's exact name, as `wsl --list --verbose` spells it.
    #[arg(long, value_name = "NAME")]
    pub distribution: String,

    /// Concurrent runner attempts the Linux host may hold.
    ///
    /// Left out, the Linux host keeps whatever it already has, and a host that
    /// has never been configured gets the product default. This is never
    /// derived from a runner count or a core count: a capacity comes from an
    /// observed workload measurement, so the only value this command sets is
    /// one you typed.
    #[arg(long, value_name = "N")]
    pub capacity: Option<u16>,
}

#[derive(Debug, Args)]
pub struct WslStatusArgs {
    /// The distribution's exact name, as `wsl --list --verbose` spells it.
    #[arg(long, value_name = "NAME")]
    pub distribution: String,

    /// Emit the versioned, schema-stable JSON document instead of text.
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Subcommand)]
pub enum WslHostCommand {
    /// Start the Linux service, then stay alive until this process is stopped.
    Hold,
}

#[derive(Debug, Subcommand)]
pub enum AuthCommand {
    /// Sign in with GitHub's device flow.
    Login(AuthLoginArgs),
    /// Report the credential's state and what it can reach.
    Status(AuthStatusArgs),
    /// Purge the local credential.
    Logout,
    /// Take a credential document on stdin and store it. Not for people.
    ///
    /// ------------------------------------------------------------------
    /// HIDDEN, AND THE HIDING IS PART OF THE DESIGN.
    /// ------------------------------------------------------------------
    /// `02-target-architecture.md` (managed WSL host) makes this the one
    /// cross-process bridge by which a provider hands a *newly issued*
    /// credential to a host it controls, without that credential ever being
    /// written down on the issuing machine. It is not a command an operator
    /// has any reason to type: `auth login` is how a person authenticates a
    /// host, and this refuses a terminal precisely so that nobody turns it
    /// into a paste workflow.
    ///
    /// `cli_command_surface.rs` transcribes the *published* surface from the
    /// design document and asserts `--help` matches it exactly, so a hidden
    /// command has to be hidden for that test to keep meaning what it says.
    #[command(hide = true)]
    Receive(AuthReceiveArgs),
}

#[derive(Debug, Args)]
pub struct AuthLoginArgs {
    /// Which start mode's credential store to sign in to.
    ///
    /// The credential lives in a store chosen by how the agent will start, and
    /// the two are different places: `boot` is machine-scoped and needs
    /// privilege, `login` is your own. A daemon reads only the one its start
    /// mode names, so signing in to the wrong one leaves a valid credential the
    /// service cannot see. Defaults to the mode this host already records.
    #[arg(long, value_name = "WHEN")]
    pub start_at: Option<StartAt>,

    /// Name every repository the credential reaches, instead of counting them.
    #[arg(long)]
    pub list: bool,
}

#[derive(Debug, Args)]
pub struct AuthReceiveArgs {
    /// Which start mode's credential store to write.
    ///
    /// Required rather than defaulted, and deliberately: the caller is another
    /// process on another machine, and it knows how the daemon it is
    /// provisioning will start. `auth login` may fall back to the mode this
    /// host already recorded because a person is there to read the line that
    /// says which store was chosen; nobody is reading this one.
    #[arg(long, value_name = "WHEN")]
    pub start_at: StartAt,
}

#[derive(Debug, Args)]
pub struct AuthStatusArgs {
    /// Name every repository the credential reaches, instead of counting them.
    ///
    /// An installation on a large account reaches hundreds, and printing them
    /// on every run buries the four lines that answer the question asked. The
    /// count and the over-broad warning are unconditional; the roll call is
    /// what this flag adds.
    #[arg(long)]
    pub list: bool,

    /// Print the permission set the App declares, and what it permits.
    #[arg(long)]
    pub permissions: bool,
}

#[derive(Debug, Subcommand)]
pub enum HostCommand {
    /// Set the ceiling on concurrent runner attempts for this machine.
    SetCapacity(HostSetCapacityArgs),
    /// Place disposable runner workspaces under a directory you choose.
    SetRuntimeRoot(HostSetRuntimeRootArgs),
    /// Return runner placement to this platform's default directory.
    ResetRuntimeRoot,
    /// Show this machine's capacity, store, and projected REST budget.
    Show,
}

#[derive(Debug, Args)]
pub struct HostSetCapacityArgs {
    /// Concurrent runner attempts this machine may hold, across every policy.
    #[arg(value_name = "N")]
    pub capacity: u16,
}

#[derive(Debug, Args)]
pub struct HostSetRuntimeRootArgs {
    /// An absolute local directory for disposable runner attempts.
    ///
    /// Application data does not move with it: config, the SQLite journal, logs
    /// and the package cache stay where `--data-dir` puts them. Nothing under
    /// the previous root is moved or deleted.
    #[arg(long, value_name = "PATH", required = true)]
    pub path: String,
}

#[derive(Debug, Args)]
pub struct StatusArgs {
    /// Emit the versioned, schema-stable JSON document instead of text.
    #[arg(long)]
    pub json: bool,
}

// ----------------------------------------------------------------------------
// `update` HAS NO `--version` FLAG, AND CANNOT HAVE ONE.
// ----------------------------------------------------------------------------
// `propagate_version = true` on the root command gives every subcommand its own
// `-V/--version`, which prints this build's version and exits. A `--version
// 1.2.3` argument on `update` would collide with it, and the collision is a
// clap panic at startup rather than a compile error -- so the flag is not
// merely unavailable, it is unwritable.
//
// Pinning a version is what the installer is for, and it already takes one:
//
//     curl -fsSL <...>/install.sh | sh -s -- --version 1.2.3
//
// so nothing is lost by leaving that where it already works.
#[derive(Debug, Args)]
pub struct UpdateArgs {
    /// Report what an update would do and change nothing.
    ///
    /// Exits zero whether or not a newer release exists; the report says which.
    /// An update being available is not a failure, and giving it a non-zero
    /// exit would put it in a taxonomy whose every other member is one.
    #[arg(long)]
    pub check: bool,
}

// -- f2's surface, declared here so `f2` attaches to a shape that exists ------

#[derive(Debug, Subcommand)]
pub enum RepoCommand {
    /// Create a repository-scoped policy in `pending`. Never enables scaling.
    Add(RepoAddArgs),
    /// List repository-scoped policies.
    List,
    /// Set a policy's `max_capacity`, promoting monitor-only to autoscale.
    SetCapacity(RepoSetCapacityArgs),
    /// Arm or drain a policy.
    SetScale(RepoSetScaleArgs),
    /// Answer one more `runs-on` label than the derived host label.
    AddLabel(RepoLabelArgs),
    /// Stop answering a label. The derived host label cannot be removed.
    RemoveLabel(RepoLabelArgs),
    /// Choose disposable or persistent job workspaces for this repository.
    SetWorkspace(RepoSetWorkspaceArgs),
    /// Remove a policy, optionally with its cache and diagnostics.
    Remove(RepoRemoveArgs),
}

/// `--mode`, mapped onto `a1`'s [`WorkspaceKind`].
///
/// A separate enum rather than a `clap` derive on the domain type: `a1` owns
/// `crates/domain` and its value is a persisted token, while this is a
/// command-line spelling. They are equal today and are allowed to diverge
/// without one of them silently changing the other.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum WorkspaceMode {
    /// The default: the whole attempt directory is removed after every job.
    Ephemeral,
    /// Opt-in: a stable `sN` slot whose `_work` directory survives the job.
    Persistent,
}

impl From<WorkspaceMode> for WorkspaceKind {
    fn from(value: WorkspaceMode) -> Self {
        match value {
            WorkspaceMode::Ephemeral => WorkspaceKind::Ephemeral,
            WorkspaceMode::Persistent => WorkspaceKind::Persistent,
        }
    }
}

// ----------------------------------------------------------------------------
// A DOC COMMENT ON A CLAP FIELD IS OPERATOR-FACING TEXT, NOT A NOTE TO A READER.
// ----------------------------------------------------------------------------
// `clap`'s derive turns the first line of a field's doc comment into its short
// help and the rest into its LONG help, which is what `--help` prints. So the
// rationale for the `--path` rule below is an ordinary `//` comment: an operator
// asking how to configure a workspace should not be shown a paragraph about
// which refusal `clap` can express.
//
// The rule itself: `--mode persistent` requires `--path` and `--mode ephemeral`
// forbids it. clap can say the first (`required_if_eq`) and has no spelling for
// the second, so the first is a usage error — exit 2, clap's own code — and the
// second is `Failure::InvalidArgument`, exit 9, raised by `policy::set_workspace`.
// That is exactly what the class is for: "an argument was well-formed for clap
// and wrong for the domain". Both refuse and both name the command to run
// instead; what neither does is silently ignore a path the operator typed, which
// is the outcome `02-target-architecture.md` rules out.
#[derive(Debug, Args)]
pub struct RepoSetWorkspaceArgs {
    /// The repository whose workspace behaviour is being set.
    #[arg(value_name = "OWNER/REPO")]
    pub repository: String,
    /// `ephemeral` discards the workspace after every job; `persistent` keeps
    /// each slot's `_work` directory for the next job on the same slot.
    #[arg(long, value_name = "MODE")]
    pub mode: WorkspaceMode,
    /// The directory this repository's persistent slots live in.
    ///
    /// Required by `--mode persistent`, and refused by `--mode ephemeral`,
    /// which has no slots to place. Nothing under a previous root is moved or
    /// deleted.
    #[arg(long, value_name = "PATH", required_if_eq("mode", "persistent"))]
    pub path: Option<String>,
}

#[derive(Debug, Args)]
pub struct RepoAddArgs {
    /// `OWNER/REPO`.
    #[arg(value_name = "OWNER/REPO")]
    pub repository: String,
    /// The host identity the routing label is derived from.
    #[arg(long, value_name = "HOST")]
    pub host_label: String,
    /// Omit for a monitor-only policy that never starts a runner (D19).
    #[arg(long, value_name = "N")]
    pub max_capacity: Option<u16>,
    /// An extra `runs-on` label this policy's runners answer, repeatable.
    ///
    /// GitHub adds none implicitly: a runner answers `runs-on: self-hosted`
    /// only if `self-hosted` is among its labels. The derived host label is
    /// always present and is never replaced by these.
    #[arg(long = "label", value_name = "LABEL")]
    pub labels: Vec<String>,
    /// Arm the policy in the same command, instead of a separate `set-scale`.
    ///
    /// Creation stays non-arming by default: without this the policy is
    /// `pending` and starts nothing, which is what makes `repo add` safe to run
    /// before you have decided. This flag is the same explicit act `set-scale`
    /// performs, spelled on the line that created the policy.
    #[arg(long)]
    pub enable: bool,
}

#[derive(Debug, Args)]
pub struct RepoLabelArgs {
    #[arg(value_name = "OWNER/REPO")]
    pub repository: String,
    /// The label to add or remove, repeatable.
    #[arg(long = "label", value_name = "LABEL", required = true)]
    pub labels: Vec<String>,
}

#[derive(Debug, Args)]
pub struct RepoSetCapacityArgs {
    #[arg(value_name = "OWNER/REPO")]
    pub repository: String,
    #[arg(long, value_name = "N")]
    pub max_capacity: u16,
}

#[derive(Debug, Args)]
pub struct RepoSetScaleArgs {
    #[arg(value_name = "OWNER/REPO")]
    pub repository: String,
    #[arg(long, value_name = "BOOL", action = clap::ArgAction::Set)]
    pub enabled: bool,
}

#[derive(Debug, Args)]
pub struct RepoRemoveArgs {
    #[arg(value_name = "OWNER/REPO")]
    pub repository: String,
    /// Also delete the runner package cache and historical diagnostics.
    #[arg(long)]
    pub purge: bool,
}

#[derive(Debug, Subcommand)]
pub enum OrgCommand {
    /// Create an organization-scoped policy in `pending`.
    Add(OrgAddArgs),
    /// List organization-scoped policies.
    List,
    /// Set a policy's `max_capacity`, promoting monitor-only to autoscale.
    SetCapacity(OrgSetCapacityArgs),
    /// Arm or drain a policy.
    SetScale(OrgSetScaleArgs),
    /// Answer one more `runs-on` label than the derived host label.
    AddLabel(OrgLabelArgs),
    /// Stop answering a label. The derived host label cannot be removed.
    RemoveLabel(OrgLabelArgs),
    /// Remove a policy, optionally with its cache and diagnostics.
    Remove(OrgRemoveArgs),
}

#[derive(Debug, Args)]
pub struct OrgAddArgs {
    #[arg(value_name = "ORG")]
    pub organization: String,
    #[arg(long, value_name = "HOST")]
    pub host_label: String,
    #[arg(long, value_name = "N")]
    pub max_capacity: Option<u16>,
    /// An extra `runs-on` label this policy's runners answer, repeatable.
    #[arg(long = "label", value_name = "LABEL")]
    pub labels: Vec<String>,
    /// Arm the policy in the same command, instead of a separate `set-scale`.
    #[arg(long)]
    pub enable: bool,
}

#[derive(Debug, Args)]
pub struct OrgLabelArgs {
    #[arg(value_name = "ORG")]
    pub organization: String,
    /// The label to add or remove, repeatable.
    #[arg(long = "label", value_name = "LABEL", required = true)]
    pub labels: Vec<String>,
}

#[derive(Debug, Args)]
pub struct OrgSetCapacityArgs {
    #[arg(value_name = "ORG")]
    pub organization: String,
    #[arg(long, value_name = "N")]
    pub max_capacity: u16,
}

#[derive(Debug, Args)]
pub struct OrgSetScaleArgs {
    #[arg(value_name = "ORG")]
    pub organization: String,
    #[arg(long, value_name = "BOOL", action = clap::ArgAction::Set)]
    pub enabled: bool,
}

#[derive(Debug, Args)]
pub struct OrgRemoveArgs {
    #[arg(value_name = "ORG")]
    pub organization: String,
    #[arg(long)]
    pub purge: bool,
}

// -- f3's surface ------------------------------------------------------------

#[derive(Debug, Subcommand)]
pub enum DaemonCommand {
    /// Run the reconciliation loop in the foreground.
    Run(DaemonRunArgs),
}

/// Arguments normally supplied by `service install`.
///
/// The four hidden leaves preserve the application-data layout selected by
/// the installing operator when the service manager later starts the daemon
/// under LocalSystem/root. They do not affect secret-store selection: the
/// secret remains in the platform-standard machine/user store for the recorded
/// start mode.
#[derive(Debug, Args, Default)]
pub struct DaemonRunArgs {
    #[arg(long, hide = true, requires_all = ["service_state_dir", "service_runtime_dir", "service_logs_dir"])]
    pub service_config_dir: Option<PathBuf>,
    #[arg(long, hide = true, requires_all = ["service_config_dir", "service_runtime_dir", "service_logs_dir"])]
    pub service_state_dir: Option<PathBuf>,
    #[arg(long, hide = true, requires_all = ["service_config_dir", "service_state_dir", "service_logs_dir"])]
    pub service_runtime_dir: Option<PathBuf>,
    #[arg(long, hide = true, requires_all = ["service_config_dir", "service_state_dir", "service_runtime_dir"])]
    pub service_logs_dir: Option<PathBuf>,
    /// Installed only in Windows boot-service registrations. Login scheduled
    /// tasks carry the same directory arguments but must never enter SCM.
    #[arg(long, hide = true, requires = "service_config_dir")]
    pub windows_service_host: bool,
}

impl DaemonRunArgs {
    fn service_paths(&self) -> Option<AppPaths> {
        Some(AppPaths::from_directories(
            self.service_config_dir.as_ref()?,
            self.service_state_dir.as_ref()?,
            self.service_runtime_dir.as_ref()?,
            self.service_logs_dir.as_ref()?,
        ))
    }
}

#[derive(Debug, Subcommand)]
pub enum ServiceCommand {
    /// Register `daemon run` with the operating system.
    Install(ServiceInstallArgs),
    /// Deregister without deleting configuration, secrets, or cache.
    Uninstall,
    /// Report the start mode, resolved binary path, and last GitHub contact.
    Status,
}

#[derive(Debug, Args)]
pub struct ServiceInstallArgs {
    /// `boot` starts the agent with the machine; `login` waits for a session.
    #[arg(long, value_name = "WHEN", default_value = "boot")]
    pub start_at: StartAt,
}

/// `--start-at boot|login`, mapped onto `b1`'s [`StartMode`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum StartAt {
    Boot,
    Login,
}

impl From<StartAt> for StartMode {
    fn from(value: StartAt) -> Self {
        match value {
            StartAt::Boot => StartMode::Boot,
            StartAt::Login => StartMode::Login,
        }
    }
}

// ---------------------------------------------------------------------------
// The composition root
// ---------------------------------------------------------------------------

/// Everything a command needs, resolved once.
#[derive(Debug)]
pub struct Context {
    paths: AppPaths,
    /// `Some` when `--data-dir` was given: the secret store is rooted there too.
    data_root: Option<PathBuf>,
    endpoints: Endpoints,
    clock: Arc<dyn Clock>,
    /// A stand-in for the platform store, set only by [`Context::with_secret_store`].
    ///
    /// `#[cfg(test)]`, so it is not a field of the shipped type and there is no
    /// way to reach it from a binary: the same reasoning
    /// [`Context::rooted_against`] gives for being a test-only constructor.
    #[cfg(test)]
    secret_store_double: Option<Arc<dyn SecretStore>>,
}

impl Context {
    /// Resolves paths and endpoints, and creates the four directories.
    ///
    /// # Errors
    /// [`Failure::LocalState`] when the platform reports no home directory or
    /// the directories cannot be created, and [`Failure::InvalidArgument`] when
    /// [`GITHUB_BASE_URL_VARIABLE`] holds something this refuses to trust.
    pub fn resolve(data_dir: Option<&Path>, err: &mut dyn Write) -> Result<Self, CliError> {
        let paths = match data_dir {
            Some(root) => AppPaths::rooted_at(root),
            None => AppPaths::discover().map_err(|source| {
                CliError::with_remedy(
                    Failure::LocalState,
                    format!("cannot work out where this host's data directories live: {source}"),
                    "runner-manager --data-dir <DIR> <COMMAND>",
                )
            })?,
        };
        paths.create_all().map_err(|source| {
            CliError::with_remedy(
                Failure::LocalState,
                format!("cannot create this host's data directories: {source}"),
                "runner-manager --data-dir <DIR> <COMMAND>",
            )
        })?;

        warn_about_an_app_override(err);

        Ok(Self {
            paths,
            data_root: data_dir.map(Path::to_path_buf),
            endpoints: Self::resolve_endpoints(err)?,
            clock: Arc::new(SystemClock),
            #[cfg(test)]
            secret_store_double: None,
        })
    }

    /// Resolves a daemon against the exact non-secret directories captured by
    /// `service install`, while leaving the secret store platform-standard.
    fn resolve_service(paths: AppPaths, err: &mut dyn Write) -> Result<Self, CliError> {
        paths.create_all().map_err(|source| {
            CliError::new(
                Failure::LocalState,
                format!("cannot create this service's application-data directories: {source}"),
            )
        })?;
        Ok(Self {
            paths,
            // This is the load-bearing difference from `--data-dir`: a service
            // path handoff must not re-root the machine secret into another
            // file underneath the data tree.
            data_root: None,
            endpoints: Self::resolve_endpoints(err)?,
            clock: Arc::new(SystemClock),
            #[cfg(test)]
            secret_store_double: None,
        })
    }

    /// A context rooted at `root` and pointed at a fixture server.
    ///
    /// # Why a constructor rather than the environment variable
    ///
    /// [`Context::resolve`] takes its endpoints from
    /// [`GITHUB_BASE_URL_VARIABLE`], which is a *process*-wide value. A unit
    /// test that set it would be setting it for every other test running in
    /// the same process at the same time — and in edition 2024
    /// `std::env::set_var` is `unsafe` for exactly that reason. The integration
    /// suites can use the variable because each of them is a separate process
    /// driving the binary; the in-crate tests cannot.
    ///
    /// `#[cfg(test)]`, so this is not compiled into the shipped binary and
    /// there is no way to reach it from one.
    ///
    /// # Errors
    /// [`Failure::LocalState`] when the directories cannot be created.
    #[cfg(test)]
    pub(crate) fn rooted_against(
        paths_root: &Path,
        endpoints: Endpoints,
    ) -> Result<Self, CliError> {
        let paths = AppPaths::rooted_at(paths_root);
        paths.create_all().map_err(|source| {
            CliError::new(
                Failure::LocalState,
                format!("cannot create this test's data directories: {source}"),
            )
        })?;
        Ok(Self {
            paths,
            data_root: Some(paths_root.to_path_buf()),
            endpoints,
            clock: Arc::new(SystemClock),
            secret_store_double: None,
        })
    }

    /// The same context, with `double` standing in for the platform secret
    /// store that [`Context::secret_store`] would otherwise resolve.
    ///
    /// # Why the composition root, and not the call site
    ///
    /// The property `b1` has to assert is that the credential broker never
    /// *reaches* the active host store, and the broker takes a [`Context`] and
    /// nothing else. A double handed straight to the function under test would
    /// therefore prove nothing: the only place a regression could pick the
    /// store up is here, so this is the only place a stand-in catches one.
    ///
    /// `#[cfg(test)]` for the reason [`Context::rooted_against`] gives.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn with_secret_store(mut self, double: Arc<dyn SecretStore>) -> Self {
        self.secret_store_double = Some(double);
        self
    }

    /// Production GitHub, unless a loopback override says otherwise.
    ///
    /// See [`GITHUB_BASE_URL_VARIABLE`] for why the loopback restriction is the
    /// whole of this function's security value.
    ///
    /// The parse goes through [`Endpoints::for_test_server`] rather than
    /// through `url` directly: `url` is not a dependency of this crate and `a1`
    /// owns every manifest, so the URL type is reachable only through the
    /// values `crates/github` hands back. That is a constraint, not a
    /// preference, and it is why the loopback test below reads a host *string*
    /// rather than matching on `url::Host`.
    fn resolve_endpoints(err: &mut dyn Write) -> Result<Endpoints, CliError> {
        let Some(raw) = std::env::var_os(GITHUB_BASE_URL_VARIABLE) else {
            return Ok(Endpoints::production());
        };
        let raw = raw.to_string_lossy().into_owned();
        let endpoints = Endpoints::for_test_server(&raw).map_err(|source| {
            CliError::new(
                Failure::InvalidArgument,
                format!("{GITHUB_BASE_URL_VARIABLE} is not usable as an endpoint base: {source}"),
            )
        })?;
        refuse_unless_every_origin_is_loopback(&endpoints, &raw)?;
        let _ = writeln!(
            err,
            "warning: talking to {raw} instead of GitHub, because \
             {GITHUB_BASE_URL_VARIABLE} is set."
        );
        Ok(endpoints)
    }

    #[must_use]
    pub fn paths(&self) -> &AppPaths {
        &self.paths
    }

    #[must_use]
    pub fn endpoints(&self) -> &Endpoints {
        &self.endpoints
    }

    #[must_use]
    pub fn clock(&self) -> Arc<dyn Clock> {
        Arc::clone(&self.clock)
    }

    /// The published App this binary authenticates as.
    ///
    /// # Errors
    /// [`Failure::AppNotPublished`] while [`PUBLISHED_CLIENT_ID`] is empty and
    /// no override is set. See that constant for why an empty default is the
    /// honest one.
    pub fn app_registration(&self) -> Result<AppRegistration, CliError> {
        // --------------------------------------------------------------------
        // THE OVERRIDE APPLIES TO A FAKE GITHUB, AND ONLY TO A FAKE GITHUB.
        // --------------------------------------------------------------------
        // These two variables exist for a test that drives a fake GitHub, and
        // every such test sets [`GITHUB_BASE_URL_VARIABLE`] alongside them --
        // which is itself restricted to loopback. Against the real github.com
        // they have no legitimate use, and one dangerous one: an override left
        // at machine scope after a spike sends whoever runs `auth login` next to
        // a DIFFERENT App's consent screen, showing a name they have never heard
        // of on the page where they grant `Administration: Read and write`.
        //
        // That is not hypothetical. A `runner-manager-d17-spike` override
        // survived on a workstation and the shipped 0.1.2 asked for
        // authorization as the spike; the operator noticed only because the name
        // on GitHub's page was wrong.
        //
        // So the seam is bound to the thing it is a seam for. Talking to real
        // GitHub, the published registration wins and the override is announced
        // as ignored rather than silently obeyed.
        let against_a_fake_github = std::env::var_os(GITHUB_BASE_URL_VARIABLE).is_some();
        let (client_id, slug) = if against_a_fake_github {
            (
                std::env::var(CLIENT_ID_VARIABLE)
                    .unwrap_or_else(|_| PUBLISHED_CLIENT_ID.to_string()),
                std::env::var(APP_SLUG_VARIABLE).unwrap_or_else(|_| PUBLISHED_APP_SLUG.to_string()),
            )
        } else {
            (
                PUBLISHED_CLIENT_ID.to_string(),
                PUBLISHED_APP_SLUG.to_string(),
            )
        };
        AppRegistration::new(client_id, slug).map_err(|_| {
            CliError::new(
                Failure::AppNotPublished,
                format!(
                    "this build carries no published GitHub App registration, so there is \
                     nothing to sign in to. Registering and publishing the App is Phase 0 of \
                     the rollout and has not happened yet, so {NO_OPERATOR_REMEDY}."
                ),
            )
        })
    }

    /// The local SQLite database, opened under `config/`.
    ///
    /// # Errors
    /// [`Failure::LocalState`], carrying what SQLite said.
    pub fn store(&self) -> Result<SqliteStore, CliError> {
        let path = self.paths.config_dir().join(DATABASE_FILE);
        SqliteStore::open(&path).map_err(|source| {
            CliError::new(
                Failure::LocalState,
                format!(
                    "cannot open the local database at {}: {source}",
                    path.display()
                ),
            )
        })
    }

    /// The secret store this host's start mode obliges (D13).
    ///
    /// The scope is **not** a preference: `SecretScope::for_start_mode` is a
    /// total function of the start mode recorded for this host, because a
    /// service starting at boot has no login session to read a user-scoped
    /// store from. A host that has never been configured has no recorded mode,
    /// and [`StartMode::default`] — `boot` — is what `service install` defaults
    /// to, so the two agree by construction.
    ///
    /// Handed out as the [`SecretStore`] port rather than as the concrete
    /// platform type, because every caller uses it as the port already and
    /// because a test needs to be able to put a stand-in here; see
    /// [`Context::with_secret_store`].
    ///
    /// # Errors
    /// [`Failure::SecretStore`] when the platform cannot say where the store
    /// lives.
    pub fn secret_store(&self, start_mode: StartMode) -> Result<Arc<dyn SecretStore>, CliError> {
        #[cfg(test)]
        if let Some(double) = &self.secret_store_double {
            return Ok(Arc::clone(double));
        }

        let scope = SecretScope::for_start_mode(start_mode);
        let resolved = match &self.data_root {
            Some(root) => PlatformSecretStore::rooted_at(scope, root),
            None => PlatformSecretStore::standard(scope),
        };
        resolved
            .map(|store| Arc::new(store) as Arc<dyn SecretStore>)
            .map_err(|source| {
                CliError::with_remedy(
                    Failure::SecretStore,
                    format!("cannot reach the {scope}-scoped secret store: {source}"),
                    "runner-manager host show",
                )
            })
    }

    /// The start mode recorded for this host, or the default when none is.
    ///
    /// # Errors
    /// [`Failure::LocalState`] when the database cannot be read.
    pub fn recorded_start_mode(&self, store: &dyn Store) -> Result<StartMode, CliError> {
        Ok(host::local_host(store)?.map_or_else(StartMode::default, |h| h.service_start_mode))
    }
}

/// Refuses an override unless **every** origin it produced is loopback.
///
/// # Why both bases, and not the one this check used to read
///
/// [`Endpoints`] carries two: `api_base` for `api.github.com`, and `web_base`
/// for `github.com`. The bearer token is exchanged at
/// `Endpoints::access_token_url`, which joins **`web_base`** — and `web_base` is
/// also what `c2` compares the device-flow `verification_uri` against, so it is
/// the origin behind both of this variable's security properties.
///
/// This check used to read `api_base` alone. That was sound only because
/// `Endpoints::for_test_server` builds both bases from one root, which is an
/// invariant `c2` owns and could reasonably change — a loosening there would
/// silently unhook the one check whose whole purpose is to be unbypassable.
/// Reading both costs a line and removes the cross-crate dependence.
///
/// # Errors
/// [`Failure::InvalidArgument`], naming which base failed.
fn refuse_unless_every_origin_is_loopback(
    endpoints: &Endpoints,
    raw: &str,
) -> Result<(), CliError> {
    let bases = [
        ("the API base", endpoints.api_base()),
        (
            "the web base, which is where the device flow hands over the token",
            endpoints.web_base(),
        ),
    ];
    for (what, base) in bases {
        let host = base.host_str().unwrap_or_default();
        if !is_loopback_host(host) {
            return Err(CliError::new(
                Failure::InvalidArgument,
                format!(
                    "{GITHUB_BASE_URL_VARIABLE} may only point at a loopback address. \
                     {raw:?} put {what} on host {host:?}, which is not one. This variable \
                     redirects the device flow, and the device flow ends by handing a \
                     GitHub credential to whatever answered it."
                ),
            ));
        }
    }
    Ok(())
}

/// Whether a URL host component names this machine.
///
/// Three forms, and no more. A domain other than `localhost` is refused
/// outright rather than resolved: a name that resolves to `127.0.0.1` today can
/// resolve elsewhere on the next lookup, and the whole value of this check is
/// that it cannot be talked out of its answer.
fn is_loopback_host(host: &str) -> bool {
    if host.eq_ignore_ascii_case("localhost") {
        return true;
    }
    if let Ok(address) = host.parse::<std::net::Ipv4Addr>() {
        return address.is_loopback();
    }
    // `Url::host_str` renders an IPv6 literal in its bracketed authority form.
    let unbracketed = host.strip_prefix('[').and_then(|h| h.strip_suffix(']'));
    if let Some(inner) = unbracketed
        && let Ok(address) = inner.parse::<std::net::Ipv6Addr>()
    {
        return address.is_loopback();
    }
    false
}

// ---------------------------------------------------------------------------
// Dispatch
// ---------------------------------------------------------------------------

/// The single entry point `main` calls.
///
/// Two properties of the original skeleton survive, and must keep surviving:
/// it returns an [`ExitCode`] so exit codes stay a CLI concern, and the `tui`
/// command calls [`crate::tui::run`] and nothing else reaches the terminal UI.
#[must_use]
pub fn dispatch() -> ExitCode {
    // The vector is kept, not just parsed. `--host wsl:NAME` forwards *the
    // original arguments* to the Linux binary, and clap's parsed tree cannot
    // reproduce them: it has already normalised `--json`/`-j`, dropped the
    // difference between `--capacity 4` and `--capacity=4`, and expanded
    // defaults nobody typed. Re-rendering from the tree would forward a
    // command line the operator did not write.
    let argv: Vec<std::ffi::OsString> = std::env::args_os().collect();
    let cli = Cli::parse_from(&argv);

    // A Windows service process is not an ordinary console process. SCM
    // requires its main thread to enter StartServiceCtrlDispatcher, and kills
    // a process which merely runs the daemon loop without doing so. The hidden
    // service directories are the unambiguous marker written by our installer;
    // interactive `daemon run` therefore keeps its console signal behavior.
    #[cfg(windows)]
    if matches!(
        &cli.command,
        Command::Daemon(DaemonCommand::Run(args)) if args.windows_service_host
    ) {
        return dispatch_windows_service(cli);
    }

    // ------------------------------------------------------------------------
    // ANOTHER HOST IS DECIDED BEFORE ANYTHING LOCAL IS RESOLVED.
    // ------------------------------------------------------------------------
    // A command addressed to `wsl:NAME` is the Linux host's to answer, and
    // `run` below opens this host's database, its secret store and its log
    // files on the way to routing one. Deciding here means `--host wsl:Ubuntu
    // status` reports the Linux host without having touched a single file of
    // the Windows one -- which is also what makes the proxy's exit code the
    // child's own rather than something this process decided afterwards.
    if let Some(distribution) = cli.host.distribution() {
        return wsl::dispatch_to_selected_host(&cli, distribution, &argv);
    }

    // The terminal UI owns the terminal and owns its own exit code, so it is
    // routed here rather than through `run`: `ExitCode` cannot be inspected, so
    // a TUI that exited non-zero for its own reasons would otherwise be
    // re-reported as whichever class this file guessed. The data root still
    // crosses this seam: the TUI's production event source reads the same local
    // lifecycle journal as `status`, never a second database.
    if matches!(cli.command, Command::Tui) {
        return crate::tui::run(cli.data_dir.as_deref());
    }

    let stdout = io::stdout();
    let stderr = io::stderr();
    let mut out = stdout.lock();
    let mut err = stderr.lock();

    match run(&cli, &mut out, &mut err) {
        Ok(()) => {
            let _ = out.flush();
            ExitCode::SUCCESS
        }
        Err(failure) => {
            let _ = out.flush();
            let _ = failure.render(&mut err);
            let _ = err.flush();
            ExitCode::from(failure.class().code())
        }
    }
}

/// Everything `dispatch` does except owning the process's streams and turning
/// a failure into an exit code.
///
/// Separated so that routing is written against `&mut dyn Write` rather than
/// against `stdout()`, which is what lets every command below be a function of
/// its output sink instead of of the process.
///
/// # Errors
/// Whatever the routed command returns.
pub fn run(cli: &Cli, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> {
    run_with_shutdown(cli, out, err, None)
}

fn run_with_shutdown(
    cli: &Cli,
    out: &mut dyn Write,
    err: &mut dyn Write,
    service_shutdown: Option<runner_manager_platform::service::ServiceShutdown>,
) -> Result<(), CliError> {
    let service_paths = match &cli.command {
        Command::Daemon(DaemonCommand::Run(args)) => args.service_paths(),
        _ => None,
    };
    if service_paths.is_some() && cli.data_dir.is_some() {
        return Err(CliError::new(
            Failure::InvalidArgument,
            "the service supplied its recorded application-data directories, so --data-dir cannot also select a different database",
        ));
    }
    // The service supplying its own directories is also what says this process
    // is the daemon rather than a command an operator typed, and the two write
    // different files: on a boot-mode host they are different accounts sharing
    // one `logs/` directory. See `logging::LogRole`.
    let role = if service_paths.is_some() {
        runner_manager_platform::logging::LogRole::Service
    } else {
        runner_manager_platform::logging::LogRole::Operator
    };
    let context = match service_paths {
        Some(paths) => Context::resolve_service(paths, err)?,
        None => Context::resolve(cli.data_dir.as_deref(), err)?,
    };

    // Diagnostics go to `logs/`, redacted by `d1`'s allowlist sink. A CLI that
    // could not install them is still a CLI that must run, so this is a warning
    // rather than a failure: the alternative is `host show` refusing to print a
    // capacity because a log file could not be opened.
    let _logging = match runner_manager_platform::logging::install(context.paths(), role, "warn") {
        Ok(guard) => Some(guard),
        Err(source) => {
            let _ = writeln!(err, "warning: diagnostics are not being recorded: {source}");
            None
        }
    };

    // ------------------------------------------------------------------------
    // A REPORT IS BUFFERED SO IT CAN BE DECORATED; EVERYTHING ELSE STREAMS.
    // ------------------------------------------------------------------------
    // `ui::Ui::decorate` aligns a whole block on its widest key, so it has to
    // see the block. That is right for a report, which is written all at once
    // and then the command exits — and WRONG for anything the operator waits
    // in front of. `auth login` prints a code and then blocks on GitHub for
    // minutes; `daemon run` never ends. Buffering either would show the
    // operator nothing at all, so they keep the real sink.
    if is_decorated_report(&cli.command) {
        let mut buffered = Vec::new();
        // The command writes PLAIN text into the buffer: decoration is this
        // layer's job, and a writer that styled its own output would hand the
        // decorator escape sequences to parse as report structure.
        let outcome = route(
            &cli.command,
            &context,
            &mut buffered,
            service_shutdown,
            Styling::plain_for_buffer(),
        );
        // Decorated even when the command failed: a report that got halfway
        // before erroring is still the operator's best evidence, and dropping
        // it would leave them with an error and no context.
        let text = String::from_utf8_lossy(&buffered);
        ui::Ui::new(Styling::for_stdout())
            .decorate(out, &text)
            .map_err(write_failed("this report"))?;
        return outcome;
    }

    route(
        &cli.command,
        &context,
        out,
        service_shutdown,
        Styling::for_stdout(),
    )
}

/// Whether this command's output is a report that may be decorated.
///
/// An allow-list, and it has to be. The one output that must never be touched
/// is `status --json`: it is a schema-stable document, and a decorator that
/// drew a rule under its opening brace because the line looked like a heading
/// would corrupt it for every consumer parsing it. Naming the commands that MAY
/// be decorated means a new command is undecorated until somebody says
/// otherwise, rather than decorated until somebody notices.
fn is_decorated_report(command: &Command) -> bool {
    match command {
        Command::Status(args) => !args.json,
        // The same rule for the same reason: `wsl status --json` is a
        // schema-stable document, and `wsl install` streams a device-flow
        // prompt and a download that an operator waits in front of.
        Command::Wsl(WslCommand::Status(args)) => !args.json,
        Command::Wsl(WslCommand::List | WslCommand::Detach(_)) => true,
        Command::Host(_) | Command::Service(_) | Command::Repo(_) | Command::Org(_) => true,
        // `auth status` and `auth logout` are reports; `auth login` is a
        // conversation with a person and streams.
        Command::Auth(AuthCommand::Status(_) | AuthCommand::Logout) => true,
        // `update` opens with a report and then downloads tens of megabytes or
        // hands the terminal to `npm`. Buffering it would show the operator
        // nothing until the work was already done, which is the same reason
        // `auth login` is not decorated.
        _ => false,
    }
}

fn route(
    command: &Command,
    context: &Context,
    out: &mut dyn Write,
    service_shutdown: Option<runner_manager_platform::service::ServiceShutdown>,
    styling: Styling,
) -> Result<(), CliError> {
    match command {
        Command::Auth(command) => auth::dispatch(context, command, styling, out),
        Command::Host(command) => host::dispatch(context, command, styling, out),
        Command::Status(args) => status::dispatch(context, args, out),
        Command::Repo(command) => policy::dispatch_repo(context, command, out),
        Command::Org(command) => policy::dispatch_org(context, command, out),
        Command::Daemon(command) => daemon::dispatch(context, command, out, service_shutdown),
        Command::Service(command) => service::dispatch(context, command, out),
        Command::Update(args) => update::dispatch(context, args, out),
        Command::Wsl(command) => wsl::dispatch(context, command, styling, out),
        Command::WslHost(command) => wsl::dispatch_wsl_host(command, out),
        // `dispatch` returns the terminal UI's own exit code before reaching
        // here, so that `g1` owns what `tui` exits with.
        Command::Tui => Err(not_implemented("g1")),
    }
}

#[cfg(windows)]
fn dispatch_windows_service(cli: Cli) -> ExitCode {
    match runner_manager_platform::service::run_windows_service_host(move |shutdown| {
        let mut out = io::sink();
        let mut err = io::sink();
        match run_with_shutdown(&cli, &mut out, &mut err, Some(shutdown)) {
            Ok(()) => 0,
            Err(failure) => failure.class().code(),
        }
    }) {
        Ok(0) => ExitCode::SUCCESS,
        Ok(code) => ExitCode::from(code),
        Err(failure) => {
            let stderr = io::stderr();
            let mut err = stderr.lock();
            let cli_failure = CliError::new(Failure::LocalState, failure.to_string());
            let _ = cli_failure.render(&mut err);
            let _ = err.flush();
            ExitCode::from(cli_failure.class().code())
        }
    }
}

/// Whether this process may write ANSI styling, and how.
///
/// # Why a value rather than a check at the point of writing
///
/// Every command here writes through a `&mut dyn Write` that is a terminal in
/// production and a `Vec<u8>` under test. A styling decision taken by looking at
/// the process's stdout would therefore depend on how the TEST was run —
/// `cargo test` captures, `cargo test -- --nocapture` does not — and the same
/// assertion would pass or fail on escape codes nobody intended to compare.
/// Passing the decision in keeps it explicit: [`Styling::plain`] in tests,
/// [`Styling::for_stdout`] once, in `dispatch`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Styling {
    enabled: bool,
}

impl Styling {
    /// Styling for the real stdout: on when it is a terminal, off when it is a
    /// pipe, a file, or when `NO_COLOR` is set (<https://no-color.org>).
    ///
    /// The pipe case is the one that matters for correctness rather than taste:
    /// `runner-manager status | grep`, and every integration test that runs this
    /// binary as a subprocess, must see the same bytes a `Vec<u8>` sink sees.
    #[must_use]
    pub fn for_stdout() -> Self {
        Self {
            enabled: std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none(),
        }
    }

    /// Styling for the real stderr, which is where failures and warnings go.
    ///
    /// Asked separately from [`Styling::for_stdout`] because the two streams are
    /// redirected independently: `runner-manager status > report.txt` still
    /// shows its errors to a person, and that person should get the red label.
    #[must_use]
    pub fn for_stderr() -> Self {
        Self {
            enabled: std::io::stderr().is_terminal() && std::env::var_os("NO_COLOR").is_none(),
        }
    }

    /// No styling at all.
    ///
    /// `#[cfg(test)]` because production has exactly one way in —
    /// [`Styling::for_stdout`], which already answers "plain" for every pipe and
    /// every redirect. A second production constructor would be a second way for
    /// a command to decide, and the point of passing the decision around is that
    /// it is taken once.
    #[cfg(test)]
    #[must_use]
    pub const fn plain() -> Self {
        Self { enabled: false }
    }

    fn wrap(self, codes: &str, text: &str) -> String {
        if self.enabled {
            format!("\u{1b}[{codes}m{text}\u{1b}[0m")
        } else {
            text.to_string()
        }
    }

    /// The one string the operator has to type somewhere else. Bright, bold and
    /// reversed, because it is the thing they are hunting for on the screen.
    #[must_use]
    pub fn code(self, text: &str) -> String {
        self.wrap("1;7;36", text)
    }

    /// A URL to open. Underlined, the way a terminal renders a link.
    #[must_use]
    pub fn url(self, text: &str) -> String {
        self.wrap("4;36", text)
    }

    /// A step label, so the actions stand out from the paragraphs around them.
    #[must_use]
    pub fn step(self, text: &str) -> String {
        self.wrap("1;32", text)
    }

    /// No styling, for a command whose output is buffered for decoration.
    ///
    /// Separate from the `#[cfg(test)]` [`Styling::plain`] because this one has
    /// a production caller: `route` hands it to every buffered report, so that
    /// what reaches [`ui::Ui::decorate`] is report structure rather than escape
    /// sequences that happen to look like it.
    #[must_use]
    pub const fn plain_for_buffer() -> Self {
        Self { enabled: false }
    }

    /// Styling that is ON, for a test that asserts what a terminal would see.
    #[cfg(test)]
    #[must_use]
    pub const fn styled() -> Self {
        Self { enabled: true }
    }

    /// Whether anything will actually be emitted.
    #[must_use]
    pub const fn is_enabled(self) -> bool {
        self.enabled
    }

    /// A report's heading.
    #[must_use]
    pub fn heading(self, text: &str) -> String {
        self.wrap("1", text)
    }

    /// The rule drawn under a heading. Dim, because it is furniture.
    #[must_use]
    pub fn rule(self, text: &str) -> String {
        self.wrap("2", text)
    }

    /// The left-hand column of a report.
    #[must_use]
    pub fn key(self, text: &str) -> String {
        self.wrap("2;36", text)
    }

    /// A value that says the thing is working.
    #[must_use]
    pub fn good(self, text: &str) -> String {
        self.wrap("32", text)
    }

    /// A value that says something is absent or pending, and a warning label.
    #[must_use]
    pub fn caution(self, text: &str) -> String {
        self.wrap("33", text)
    }

    /// A value that says something is broken, and an error label.
    #[must_use]
    pub fn failure(self, text: &str) -> String {
        self.wrap("1;31", text)
    }

    /// A command the operator is meant to type.
    #[must_use]
    pub fn command(self, text: &str) -> String {
        self.wrap("1;36", text)
    }
}

/// Opens `url` in the operator's browser, best effort.
///
/// # Best effort is the whole contract
///
/// Returns whether the launcher was started, and nothing more: a browser that
/// opens on another virtual desktop, a headless server with no handler, an SSH
/// session — none of those are failures this command should report, let alone
/// fail on. The URL is printed either way, which is what the caller relies on.
///
/// Skipped entirely when stdout is not a terminal, which keeps it out of pipes,
/// out of CI, and out of the integration tests that drive `auth login` against
/// a fake GitHub — a test suite that spawned a browser per run would be a bug
/// nobody would thank us for.
pub(crate) fn open_in_browser(url: &str, styling: Styling) -> bool {
    if !styling.enabled {
        return false;
    }

    // No `open`/`webbrowser` crate: this is one command per platform, and the
    // workspace's dependency policy is that a manifest change needs a reason
    // bigger than three match arms.
    let mut command = if cfg!(target_os = "windows") {
        // `start` is a shell builtin rather than an executable, hence `cmd /c`.
        // The empty string is `start`'s title argument: without it, a quoted URL
        // is taken AS the title and nothing opens.
        let mut command = std::process::Command::new("cmd");
        command.args(["/c", "start", "", url]);
        command
    } else if cfg!(target_os = "macos") {
        let mut command = std::process::Command::new("open");
        command.arg(url);
        command
    } else {
        let mut command = std::process::Command::new("xdg-open");
        command.arg(url);
        command
    };

    command
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .is_ok()
}

/// Says on stderr when this process is not authenticating as the App this build
/// publishes.
///
/// # An override that does not announce itself is a trap
///
/// [`CLIENT_ID_VARIABLE`] and [`APP_SLUG_VARIABLE`] are a test seam, and a
/// machine-scoped one outlives the development that set it. A released binary
/// then sends the operator to a DIFFERENT App's consent screen — showing a name
/// they have never heard of on the page where they are deciding whether to grant
/// `Administration: Read and write`. That is not hypothetical: a
/// `runner-manager-d17-spike` override survived at machine scope on a
/// workstation, and the shipped 0.1.2 asked for authorization as the spike.
///
/// [`Context::resolve_endpoints`] already says loudly when it is not talking to
/// GitHub. This owes the same warning for the same reason. It warns rather than
/// refuses because driving another App is exactly what the seam is for.
fn warn_about_an_app_override(err: &mut dyn Write) {
    let client_id = std::env::var(CLIENT_ID_VARIABLE).ok();
    let slug = std::env::var(APP_SLUG_VARIABLE).ok();
    let against_a_fake_github = std::env::var_os(GITHUB_BASE_URL_VARIABLE).is_some();
    write_app_override_warning(
        err,
        client_id.as_deref(),
        slug.as_deref(),
        against_a_fake_github,
    );
}

/// The warning itself, as a function of its two inputs.
///
/// Split from the environment read so that it can be driven by a test: setting
/// a process-wide variable would race every other test in this binary, and a
/// warning nothing exercises is a warning that stops being emitted the first
/// time somebody refactors around it.
fn write_app_override_warning(
    err: &mut dyn Write,
    client_id: Option<&str>,
    slug: Option<&str>,
    against_a_fake_github: bool,
) {
    if client_id.is_none() && slug.is_none() {
        return;
    }

    let ui = ui::Ui::new(Styling::for_stderr());
    if against_a_fake_github {
        let named = slug.unwrap_or("<no slug set>");
        let _ = ui.warning(
            err,
            &format!(
                "authenticating as the GitHub App `{named}`, not this build's \
                 `{PUBLISHED_APP_SLUG}`, because {CLIENT_ID_VARIABLE} or {APP_SLUG_VARIABLE} is \
                 set alongside a {GITHUB_BASE_URL_VARIABLE} that is not GitHub."
            ),
        );
        return;
    }

    // The dangerous case, and the one that reads as reassurance rather than as
    // an alarm: the variables are set, they are being IGNORED, and sign-in is
    // going to the published App after all.
    let _ = ui.warning(
        err,
        &format!(
            "ignoring {CLIENT_ID_VARIABLE}/{APP_SLUG_VARIABLE}: they apply only when \
             {GITHUB_BASE_URL_VARIABLE} points at a fake GitHub. Signing in as \
             `{PUBLISHED_APP_SLUG}`. Unset them to silence this."
        ),
    );
}

/// The arm a declared-but-unimplemented command takes.
///
/// It names the task rather than saying "not supported", because the command
/// *is* part of the surface `02-target-architecture.md` fixes — a script that
/// finds it missing is looking at an unfinished build, not at a typo.
fn not_implemented(task: &str) -> CliError {
    CliError::new(
        Failure::NotImplemented,
        format!(
            "this command is declared but not implemented in this build (task {task}). \
             It exits {} so a script can tell it apart from a usage error.",
            Failure::NotImplemented.code()
        ),
    )
}

/// Builds the current-thread Tokio runtime a command needs for GitHub I/O.
///
/// Current-thread rather than multi-thread: every CLI command issues a short
/// sequence of requests and then exits, so a worker pool buys nothing and costs
/// one thread per core on a home host.
///
/// # Errors
/// [`Failure::Unclassified`] when the runtime will not start.
pub fn runtime() -> Result<tokio::runtime::Runtime, CliError> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|source| {
            CliError::new(
                Failure::Unclassified,
                format!("cannot start the async runtime: {source}"),
            )
        })
}

/// The one place a host record is created, for [`host`] and for `f2`.
///
/// # Errors
/// [`Failure::UnsupportedHost`] when this OS/architecture pair is outside
/// GitHub's documented matrix, and [`Failure::LocalState`] on a write failure.
pub fn create_local_host(store: &dyn Store, clock: &dyn Clock) -> Result<Host, CliError> {
    let support = runner_manager_platform::os::detect().map_err(|source| {
        CliError::new(
            Failure::UnsupportedHost,
            format!("this machine cannot run GitHub's runner application: {source}"),
        )
    })?;
    let capacity = std::num::NonZeroU16::new(DEFAULT_HOST_CAPACITY)
        .expect("DEFAULT_HOST_CAPACITY is a non-zero constant");
    let host = Host::new(
        runner_manager_domain::model::HostId::new_random(),
        local_display_name(),
        support.os(),
        support.arch(),
        capacity,
        clock.now(),
    )
    .map_err(|source| {
        CliError::new(
            Failure::LocalState,
            format!("cannot describe this host: {source}"),
        )
    })?;
    store.put_host(&host).map_err(|source| {
        CliError::new(
            Failure::LocalState,
            format!("cannot record this host: {source}"),
        )
    })?;
    Ok(host)
}

/// A human-readable name for this machine.
///
/// `d1` exposes no hostname primitive — it deliberately covers only the
/// platform differences some task's Definition of Done depends on — and this is
/// a display string with no authority behind it: nothing routes, matches, or
/// authorises on it. So it is read from whichever environment variable the
/// platform sets, and falls back to a constant rather than failing a command
/// over a cosmetic field.
fn local_display_name() -> String {
    for variable in ["COMPUTERNAME", "HOSTNAME"] {
        if let Ok(value) = std::env::var(variable) {
            let trimmed = value.trim();
            if !trimmed.is_empty() {
                return trimmed.to_string();
            }
        }
    }
    "this host".to_string()
}

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

    use clap::CommandFactory as _;

    /// The whole point of the taxonomy: two classes must never share a number,
    /// and none may be zero, or a script cannot branch on the answer.
    #[test]
    fn the_exit_codes_are_distinct_and_non_zero() {
        let mut seen = std::collections::BTreeMap::new();
        for class in Failure::ALL.iter().copied() {
            assert_ne!(
                class.code(),
                0,
                "{class} would be indistinguishable from success"
            );
            assert_ne!(
                class.code(),
                2,
                "{class} would be indistinguishable from clap's usage error, which exits 2 \
                 before any of this code runs"
            );
            if let Some(previous) = seen.insert(class.code(), class) {
                panic!("{previous} and {class} both exit {}", class.code());
            }
        }
        assert_eq!(
            seen.len(),
            Failure::ALL.len(),
            "every class must occupy its own code"
        );
    }

    /// The distinctness proof above is only worth its name if `ALL` really is
    /// every class, so this pins the property that makes it so.
    ///
    /// `ALL` is expanded from the `failure_taxonomy!` declaration, alongside the
    /// enum itself and `as_str`, so a class that exists and is missing from
    /// `ALL` is not a thing that can be written. The previous version of this
    /// test asserted `!class.as_str().is_empty()` over an exhaustive match —
    /// which is true by construction, because every arm returns a string
    /// literal, and which left the actual hole open: `ALL` was a separate
    /// hand-maintained array, and a new variant compiled without being added
    /// to it.
    ///
    /// What is checked here is the one thing the macro does *not* guarantee:
    /// that two classes were not given the same name. The names reach
    /// `status --json` and the `tracing` fields, where a duplicate would make
    /// two different failures indistinguishable to a consumer for the same
    /// reason a shared exit code would.
    #[test]
    fn every_class_is_reachable_from_all_and_names_itself_uniquely() {
        assert!(
            Failure::ALL.len() >= 19,
            "the taxonomy has only ever grown; a shorter `ALL` means classes were \
             removed without the scripting contract being revisited"
        );

        let mut names = std::collections::BTreeMap::new();
        for class in Failure::ALL.iter().copied() {
            assert!(
                !class.as_str().is_empty(),
                "{class:?} has no stable name for a `--json` document to carry"
            );
            if let Some(previous) = names.insert(class.as_str(), class) {
                panic!(
                    "{previous:?} and {class:?} are both called {:?}",
                    class.as_str()
                );
            }
        }
        assert_eq!(names.len(), Failure::ALL.len());
    }

    /// A sink that fails on the first byte, so every command's write path can
    /// be driven to its error branch.
    #[derive(Debug)]
    struct BrokenPipe;

    impl Write for BrokenPipe {
        fn write(&mut self, _: &[u8]) -> io::Result<usize> {
            Err(io::Error::new(io::ErrorKind::BrokenPipe, "the pipe closed"))
        }

        fn flush(&mut self) -> io::Result<()> {
            Err(io::Error::new(io::ErrorKind::BrokenPipe, "the pipe closed"))
        }
    }

    /// Every command reports the operation **it** was performing when its
    /// output sink gave way.
    ///
    /// This is the assertion that was missing. `write_failed` takes the noun as
    /// a parameter, and a bulk edit handed one noun to a file holding three
    /// commands: `auth status` and `auth logout` both reported *"cannot write
    /// this sign-in"*. Nothing objected, because a wrong string is still a
    /// string — and error copy that names the wrong operation is the same class
    /// of defect as error copy that names the wrong remedy, which this task's
    /// Definition of Done rules out explicitly.
    ///
    /// The table is checked in both directions: each command's message must
    /// carry its own noun **and** none of the others'. A one-directional check
    /// would have passed the very bug it is here to catch, because "this
    /// sign-in" really was present in the logout message.
    #[test]
    fn every_command_names_the_operation_whose_output_failed() {
        let temporary = tempfile::tempdir().expect("a temporary directory");
        let mut discarded = Vec::new();
        let context = Context::resolve(Some(temporary.path()), &mut discarded)
            .expect("a context rooted at a temporary directory");

        // (what the command is, the noun it must use)
        let expected: [(&str, &str); 6] = [
            ("auth login", "this sign-in"),
            ("auth status", "this credential's status"),
            ("auth logout", "this sign-out"),
            ("host set-capacity", "this host's new capacity"),
            ("host show", "this host's settings"),
            ("status", "this host's status"),
        ];

        let run_one = |command: &str| -> CliError {
            let out: &mut dyn Write = &mut BrokenPipe;
            let outcome = match command {
                "auth login" => auth::login(&context, None, false, Styling::plain(), out),
                "auth status" => auth::status(
                    &context,
                    &AuthStatusArgs {
                        list: false,
                        permissions: false,
                    },
                    Styling::plain(),
                    out,
                ),
                "auth logout" => auth::logout(&context, out),
                "host set-capacity" => {
                    host::set_capacity(&context, &HostSetCapacityArgs { capacity: 1 }, out)
                }
                "host show" => host::show(&context, out),
                "status" => status::dispatch(&context, &StatusArgs { json: false }, out),
                other => panic!("unknown command {other}"),
            };
            outcome.expect_err("a sink that fails on the first byte must fail the command")
        };

        for (command, noun) in expected {
            let error = run_one(command);
            assert_eq!(
                error.class(),
                Failure::Unclassified,
                "`{command}` must report a write failure as a write failure, not as \
                 something about GitHub or the local database: {error}"
            );
            assert!(
                error.message().contains(noun),
                "`{command}` must say it could not write {noun:?}; it said: {error}"
            );
            for (other_command, other_noun) in expected {
                if other_noun == noun {
                    continue;
                }
                assert!(
                    !error.message().contains(other_noun),
                    "`{command}` reported {other_noun:?}, which belongs to \
                     `{other_command}`: {error}"
                );
            }
        }
    }

    /// clap refuses to build a malformed command tree, and it does so at
    /// runtime rather than at compile time. Every other test in this crate that
    /// runs the binary would fail with the same panic and a worse message.
    #[test]
    fn the_command_tree_is_well_formed() {
        Cli::command().debug_assert();
    }

    #[test]
    fn repository_and_organization_set_scale_parse_explicit_true_and_false() {
        for (scope, target) in [("repo", "octo/repo"), ("org", "octo")] {
            for expected in [true, false] {
                let cli = Cli::try_parse_from([
                    "runner-manager",
                    scope,
                    "set-scale",
                    target,
                    "--enabled",
                    if expected { "true" } else { "false" },
                ])
                .unwrap();
                let actual = match cli.command {
                    Command::Repo(RepoCommand::SetScale(args)) => args.enabled,
                    Command::Org(OrgCommand::SetScale(args)) => args.enabled,
                    _ => panic!("wrong command parsed for {scope}"),
                };
                assert_eq!(actual, expected, "{scope} must retain explicit {expected}");
            }
        }
    }

    /// The override is the one environment variable that can send a credential
    /// somewhere other than GitHub, so the loopback rule is asserted from both
    /// sides.
    #[test]
    fn only_a_loopback_origin_may_replace_github() {
        for raw in [
            "http://127.0.0.1:8080/",
            "http://127.0.0.2/",
            "http://[::1]:8080/",
            "http://localhost:8080/",
            "http://LOCALHOST:8080/",
        ] {
            let endpoints = Endpoints::for_test_server(raw).expect("a valid URL");
            refuse_unless_every_origin_is_loopback(&endpoints, raw)
                .unwrap_or_else(|error| panic!("{raw} must be accepted: {error}"));
        }

        for raw in [
            "https://api.github.com/",
            "http://127.0.0.1.evil.example/",
            "http://localhost.evil.example/",
            "http://10.0.0.1/",
            "http://[2001:db8::1]/",
        ] {
            let endpoints = Endpoints::for_test_server(raw).expect("a valid URL");
            assert!(
                refuse_unless_every_origin_is_loopback(&endpoints, raw).is_err(),
                "{raw} must be refused: this variable redirects the device flow, and the \
                 device flow ends by handing a GitHub credential to whatever answered"
            );
        }

        // A URL with no host component at all must not be read as loopback by
        // the `unwrap_or_default()` that turns `None` into `""`.
        assert!(!is_loopback_host(""), "an absent host is not loopback");
    }

    /// The token is exchanged at `web_base`, so a guard that only inspected
    /// `api_base` would pass a pair whose web half is remote.
    ///
    /// `Endpoints::for_test_server` cannot build such a pair — it sets both from
    /// one root — which is precisely why the old single-base check was sound in
    /// practice and unsound in principle: it depended on an invariant owned by
    /// `crates/github`. `Endpoints::new` can build it, so the case is testable
    /// here without touching that crate, and this test fails if the guard is
    /// ever narrowed back to one base.
    #[test]
    fn a_pair_whose_web_base_is_remote_is_refused_even_when_the_api_base_is_loopback() {
        let loopback = Endpoints::for_test_server("http://127.0.0.1:8080/").expect("valid");
        let production = Endpoints::production();

        let split = Endpoints::new(loopback.api_base().clone(), production.web_base().clone());
        assert!(
            is_loopback_host(split.api_base().host_str().unwrap_or_default()),
            "the API half of this pair is loopback, which is what makes it the case the \
             old check would have waved through"
        );
        let refusal = refuse_unless_every_origin_is_loopback(&split, "http://127.0.0.1:8080/")
            .expect_err(
                "a pair whose web base is github.com must be refused: `access_token_url` \
                 joins `web_base`, so that is the origin the bearer token is handed to",
            );
        assert!(
            refusal.message().contains("hands over the token"),
            "the refusal must name which base failed: {refusal}"
        );

        // And the mirror image, so the loop is not simply refusing everything.
        let both_loopback =
            Endpoints::new(loopback.api_base().clone(), loopback.web_base().clone());
        refuse_unless_every_origin_is_loopback(&both_loopback, "http://127.0.0.1:8080/")
            .expect("a pair that is loopback on both bases must be accepted");
    }

    /// The empty default is load-bearing: it is what turns "the App has not
    /// been registered yet" into a named failure instead of a device flow that
    /// dies against GitHub with a message about client credentials.
    #[test]
    fn no_plausible_client_id_is_compiled_in() {
        // Phase 0 of `06-migration-rollout.md` landed on 2026-08-24, which is
        // what this test was told to record when it did. It used to require
        // both constants to be EMPTY, because until an App existed any value
        // here was one somebody invented.
        //
        // What replaces that is the same guarantee from the other side: a
        // device-flow client id GitHub issues is `Iv` followed by 18 more
        // base62 characters, and a slug is the lowercase, hyphenated name in
        // `github.com/apps/<slug>`. An invented value -- `TODO`, `changeme`,
        // a copied example -- fails this, and so does half a rollout that
        // filled in one constant and not the other.
        assert!(
            PUBLISHED_CLIENT_ID.len() == 20
                && PUBLISHED_CLIENT_ID.starts_with("Iv")
                && PUBLISHED_CLIENT_ID
                    .chars()
                    .all(|character| character.is_ascii_alphanumeric()),
            "`{PUBLISHED_CLIENT_ID}` is not shaped like a GitHub device-flow client id"
        );
        assert!(
            !PUBLISHED_APP_SLUG.is_empty()
                && PUBLISHED_APP_SLUG
                    .chars()
                    .all(|character| character.is_ascii_lowercase()
                        || character.is_ascii_digit()
                        || character == '-'),
            "`{PUBLISHED_APP_SLUG}` is not a GitHub App slug, and it is what \
             `github.com/apps/<slug>/installations/new` is built from"
        );
    }

    #[test]
    fn a_failure_renders_its_remedy() {
        let error = CliError::with_remedy(
            Failure::NotAuthenticated,
            "no credential is stored on this host",
            "runner-manager auth login",
        );
        let mut rendered = Vec::new();
        error.render(&mut rendered).expect("writing to a Vec");
        let rendered = String::from_utf8(rendered).expect("ASCII");
        assert!(rendered.contains("error: no credential is stored on this host"));
        assert!(rendered.contains("try: runner-manager auth login"));
    }

    // ------------------------------------------------------------------------
    // Styling
    // ------------------------------------------------------------------------

    #[test]
    fn plain_styling_emits_no_escape_sequences() {
        // The property every piped run and every captured test depends on: a
        // `Vec<u8>` sink must receive the same bytes a human would read without
        // colour. An escape leaking into this path is what breaks
        // `runner-manager status --json | jq` and every exact-match assertion in
        // the suite at once.
        let plain = Styling::plain();
        for rendered in [
            plain.code("WDJB-MJHT"),
            plain.url("https://github.com/login/device"),
            plain.step("Action 2 of 3:"),
        ] {
            assert!(
                !rendered.contains('\u{1b}'),
                "plain styling wrote an escape sequence: {rendered:?}"
            );
        }
        assert_eq!(plain.code("WDJB-MJHT"), "WDJB-MJHT");
    }

    #[test]
    fn styled_output_wraps_the_text_and_resets_afterwards() {
        // And the other half, or the assertion above passes on a `Styling` that
        // styles nothing at all: an enabled palette must actually wrap, and must
        // close what it opens. A missing reset bleeds colour into everything the
        // terminal prints afterwards, including the shell prompt.
        let styled = Styling::styled();
        let rendered = styled.code("WDJB-MJHT");
        assert!(rendered.contains("WDJB-MJHT"));
        assert!(rendered.starts_with('\u{1b}'), "not styled: {rendered:?}");
        assert!(
            rendered.ends_with("\u{1b}[0m"),
            "styling must reset: {rendered:?}"
        );
    }

    #[test]
    fn an_app_override_is_announced_and_names_the_published_slug() {
        // The warning is what makes the seam visible. A machine-scoped override
        // left over from development sent the shipped 0.1.2 to another App's
        // consent screen, and the operator had nothing on screen to tell them.
        //
        // Driven through the formatter rather than the environment: setting a
        // process-wide variable would race every other test in this binary.
        // Against a fake GitHub the override is in force, and the warning says
        // which App is being used.
        let mut in_force = Vec::new();
        write_app_override_warning(
            &mut in_force,
            Some("Iv23li39jMQVdEuupmI2"),
            Some("runner-manager-d17-spike"),
            true,
        );
        let rendered = String::from_utf8(in_force).expect("ASCII");
        assert!(
            rendered.contains("runner-manager-d17-spike") && rendered.contains(PUBLISHED_APP_SLUG),
            "the warning must name BOTH the App being used and the one this build \
             publishes, or it does not tell the operator what is wrong: {rendered}"
        );

        // Against real GitHub the same variables are IGNORED, and saying so is
        // the whole point: this is the case that shipped an operator to another
        // App's consent screen.
        let mut ignored = Vec::new();
        write_app_override_warning(
            &mut ignored,
            Some("Iv23li39jMQVdEuupmI2"),
            Some("runner-manager-d17-spike"),
            false,
        );
        let rendered = String::from_utf8(ignored).expect("ASCII");
        assert!(
            rendered.contains("ignoring") && rendered.contains(PUBLISHED_APP_SLUG),
            "against real GitHub the warning must say the override is ignored and \
             name the App actually used: {rendered}"
        );
        assert!(
            rendered.contains(CLIENT_ID_VARIABLE) || rendered.contains(APP_SLUG_VARIABLE),
            "and it must name the variable to unset: {rendered}"
        );

        // Silence is the other half, and it is the common case: a stock build
        // that printed a warning on every command would train operators to skip
        // the line that matters.
        let mut quiet = Vec::new();
        write_app_override_warning(&mut quiet, None, None, false);
        assert!(
            quiet.is_empty(),
            "a build with no override must say nothing: {:?}",
            String::from_utf8_lossy(&quiet)
        );
    }
}