runner-manager 0.4.7

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
// owner: a3-distribution-and-readme
//
// ----------------------------------------------------------------------------
// a3's DEFINITION OF DONE IS WRITTEN AS THINGS A CLEAN MACHINE WOULD OBSERVE.
// ----------------------------------------------------------------------------
// "on a clean Windows, a clean macOS and a clean Linux host that has never
// built the product, each channel installs a working binary"; "each install
// script aborts, with a clear message and a non-zero exit, when pointed at a
// deliberately corrupted asset"; "running it twice leaves one working binary";
// "`--version X.Y.Z` installs that exact version".
//
// Every one of those needs a PUBLISHED RELEASE to install from, and this
// project's release workflow publishes under the project's name (D10, and
// `07-security.md` operational requirement 7). A gate whose only test is "cut a
// release and try it" is a gate first exercised by the release that needed it.
//
// So `common::build_release` builds a synthetic release -- five archives laid
// out exactly as the real ones are, plus a `SHA256SUMS` generated by
// `release.sh sha256`, the same code the real release calls -- and BOTH INSTALL
// SCRIPTS ARE RUN AGAINST IT, END TO END, on every pull request, on all three
// operating systems. Nothing is published and no credential is needed.
//
// This is possible because each script accepts a local directory as its asset
// base. That is not a test hook bolted on: it is what an air-gapped or mirrored
// install looks like, and it is documented in both scripts' headers.
//
// ----------------------------------------------------------------------------
// WHAT THIS FILE CANNOT REACH, RECORDED RATHER THAN PAPERED OVER.
// ----------------------------------------------------------------------------
//   * The real https://github.com/.../releases/latest/download address. What is
//     driven here is the resolution and verification logic; the network hop is
//     `curl`'s and `Invoke-WebRequest`'s.
//   * "No Gatekeeper block and no SmartScreen warning." Those are properties of
//     a quarantine flag that only a browser sets, on OS versions no CI matrix
//     here runs. `the_readme_advertises_no_download_that_is_not_a_terminal_command`
//     in `readme_disclosure.rs` guards the thing that would BREAK it -- a
//     download button reappearing -- which is the half that is checkable.
//   * A real cross-architecture binary. The stand-in is a `/bin/sh` script that
//     echoes its version, so "the installed file still runs" is a real
//     assertion; "the aarch64 build runs on aarch64" is not.

mod common;

use common::{
    FixtureRelease, TARGETS, bash_program, build_release, install_script, posix, repository_root,
    run_bash, substitute_payload,
};

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Mutex, MutexGuard};

use tempfile::TempDir;

// ----------------------------------------------------------------------------
// Driving install.sh.
// ----------------------------------------------------------------------------

/// A platform the installer is being asked to believe it is on.
struct Host {
    uname_s: &'static str,
    uname_m: &'static str,
}

const LINUX_X64: Host = Host {
    uname_s: "Linux",
    uname_m: "x86_64",
};

fn run_install_sh(
    host: &Host,
    base: &Path,
    install_dir: &Path,
    arguments: &[&str],
) -> (bool, String) {
    run_bash(
        &install_script("install.sh"),
        arguments,
        &[
            ("RUNNER_MANAGER_INSTALL_UNAME_S", host.uname_s),
            ("RUNNER_MANAGER_INSTALL_UNAME_M", host.uname_m),
            ("RUNNER_MANAGER_INSTALL_BASE_URL", &posix(base)),
            ("RUNNER_MANAGER_INSTALL_DIR", &posix(install_dir)),
        ],
    )
}

/// One `key=value` line out of `--print-plan`.
fn plan_value(output: &str, key: &str) -> String {
    let prefix = format!("{key}=");
    output
        .lines()
        .find_map(|line| line.trim().strip_prefix(&prefix))
        .unwrap_or_else(|| panic!("--print-plan printed no `{key}=` line:\n{output}"))
        .to_string()
}

/// Runs the installed stand-in binary and returns what it printed.
///
/// Through bash, so that the one assertion that matters -- the file that landed
/// is intact and still executes -- holds on Windows too, where the fixture's
/// `#!/bin/sh` payload cannot be started by the OS directly.
fn run_installed(binary: &Path) -> String {
    let output = Command::new(bash_program())
        .arg(posix(binary))
        .output()
        .unwrap_or_else(|err| panic!("cannot run the installed binary: {err}"));
    assert!(
        output.status.success(),
        "the installed binary did not run: {}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8_lossy(&output.stdout).trim().to_string()
}

fn installed_entries(directory: &Path) -> Vec<String> {
    let mut names: Vec<String> = std::fs::read_dir(directory)
        .unwrap_or_else(|err| panic!("cannot list {}: {err}", directory.display()))
        .map(|entry| {
            entry
                .expect("a directory entry")
                .file_name()
                .to_string_lossy()
                .into_owned()
        })
        .collect();
    names.sort();
    names
}

// ----------------------------------------------------------------------------
// install.sh -- choosing an artifact.
// ----------------------------------------------------------------------------

#[test]
fn install_sh_selects_the_right_artifact_for_every_supported_platform() {
    // `uname -m` does not report one spelling per architecture, and the two
    // spellings do not come from the same operating systems: macOS says
    // `arm64`, Linux says `aarch64`, and a handful of Linux userlands say
    // `amd64` where the kernel says `x86_64`. A mapping that knows one of each
    // pair installs nothing on half the hosts it was written for.
    let temporary = TempDir::new().expect("a temporary directory");
    let base = temporary.path();

    for (uname_s, uname_m, expected) in [
        ("Linux", "x86_64", "x86_64-unknown-linux-gnu"),
        ("Linux", "amd64", "x86_64-unknown-linux-gnu"),
        ("Linux", "aarch64", "aarch64-unknown-linux-gnu"),
        ("Linux", "arm64", "aarch64-unknown-linux-gnu"),
        ("Darwin", "arm64", "aarch64-apple-darwin"),
        ("Darwin", "aarch64", "aarch64-apple-darwin"),
        ("Darwin", "x86_64", "x86_64-apple-darwin"),
    ] {
        let host = Host { uname_s, uname_m };
        let (ok, output) = run_install_sh(&host, base, base, &["--print-plan"]);
        assert!(ok, "install.sh refused {uname_s}/{uname_m}:\n{output}");
        assert_eq!(
            plan_value(&output, "target"),
            expected,
            "install.sh maps {uname_s}/{uname_m} to the wrong artifact:\n{output}"
        );
    }
}

#[test]
fn install_sh_refuses_a_platform_it_does_not_recognise() {
    // An unrecognised platform must be a refusal and not a guess. "Probably the
    // x86_64 one" produces a binary that fails to exec with a message about the
    // dynamic loader, which is a far worse thing to hand a user than a sentence
    // naming what was seen.
    let temporary = TempDir::new().expect("a temporary directory");
    let base = temporary.path();

    for (uname_s, uname_m, must_mention, why) in [
        (
            "SunOS",
            "x86_64",
            "SunOS",
            "the rejection has to name the value it saw, or an operator cannot \
             tell a wrong override from an unsupported host",
        ),
        (
            "Linux",
            "riscv64",
            "cargo install",
            "an unsupported architecture still has a way in -- building from \
             source -- and the refusal is where to say so",
        ),
        (
            "MINGW64_NT-10.0-26100",
            "x86_64",
            "install.ps1",
            "a Windows user piping this into Git Bash is the likeliest way to \
             reach install.sh by mistake, and it must point at the right script \
             rather than install a Linux binary that cannot run",
        ),
    ] {
        let host = Host { uname_s, uname_m };
        let (ok, output) = run_install_sh(&host, base, base, &["--print-plan"]);
        assert!(
            !ok,
            "install.sh accepted {uname_s}/{uname_m}, which it publishes no \
             artifact for:\n{output}"
        );
        assert!(
            output.contains(must_mention),
            "the refusal for {uname_s}/{uname_m} does not mention \
             `{must_mention}`: {why}\n{output}"
        );
    }
}

#[test]
fn install_sh_defaults_to_the_documented_directory() {
    // Load-bearing rather than tidiness: `service install` records the
    // ABSOLUTE path of the binary (`05-infrastructure.md`, service behaviour
    // 6), so an install location that moves breaks unattended start. This is
    // the assertion that notices the default being "improved" to
    // /usr/local/bin (needs root) or to a toolchain prefix (moves).
    let temporary = TempDir::new().expect("a temporary directory");
    // A distinctive name, because the assertion below matches on the tail of
    // the path rather than on all of it: Git Bash rewrites `HOME` on the way
    // into the script, mapping the Windows temp directory onto `/tmp`, so the
    // string the script prints is not the string this test passed in.
    let home = temporary.path().join("fixture-home");
    std::fs::create_dir_all(&home).expect("a fake home");

    let (ok, output) = run_bash(
        &install_script("install.sh"),
        &["--print-plan"],
        &[
            ("RUNNER_MANAGER_INSTALL_UNAME_S", "Linux"),
            ("RUNNER_MANAGER_INSTALL_UNAME_M", "x86_64"),
            ("RUNNER_MANAGER_INSTALL_BASE_URL", &posix(temporary.path())),
            ("HOME", &posix(&home)),
            // Deliberately unset, so the default is what is measured.
            ("RUNNER_MANAGER_INSTALL_DIR", ""),
        ],
    );
    assert!(ok, "install.sh --print-plan failed:\n{output}");

    let directory = plan_value(&output, "install_dir");
    assert!(
        directory.ends_with("/fixture-home/.local/bin"),
        "install.sh must default to `$HOME/.local/bin`, and it must be the HOME \
         it was given rather than a hardcoded path. `~/.local/bin` is chosen \
         because it belongs to the user rather than to a toolchain, so it does \
         not move when the operator switches Node or Rust versions -- which an \
         installed service's recorded absolute path cannot survive. \
         Got `{directory}`.\n{output}"
    );
    assert_eq!(
        plan_value(&output, "binary"),
        format!("{directory}/runner-manager"),
        "the plan's binary path must be the install directory plus the binary \
         name; that path is what `service install` records\n{output}"
    );
}

#[test]
fn install_sh_rejects_a_version_that_is_not_x_y_z() {
    let temporary = TempDir::new().expect("a temporary directory");
    let base = temporary.path();

    for (argument, why) in [
        ("1.2", "a Cargo version has exactly three components"),
        ("v1.2.3", "the `v` belongs to the tag, not to the version"),
        ("abc", "not a version at all"),
        ("1.2.3-rc1", "pre-releases are not a v1 channel (D12)"),
    ] {
        let (ok, output) = run_install_sh(&LINUX_X64, base, base, &["--version", argument]);
        assert!(
            !ok,
            "install.sh accepted --version {argument}: {why}\n{output}"
        );
        assert!(
            output.contains("is not X.Y.Z") || output.contains("belongs to the tag"),
            "the refusal of --version {argument} must say what is wrong with \
             it, not fail later as a download error:\n{output}"
        );
    }
}

// ----------------------------------------------------------------------------
// install.sh -- installing.
// ----------------------------------------------------------------------------

struct Installed {
    _temporary: TempDir,
    release: FixtureRelease,
    directory: PathBuf,
}

impl Installed {
    fn binary(&self) -> PathBuf {
        self.directory.join("runner-manager")
    }
}

fn prepare(version: &str) -> Installed {
    let temporary = TempDir::new().expect("a temporary directory");
    let release = build_release(temporary.path(), version);
    let directory = temporary.path().join("bin");
    Installed {
        _temporary: temporary,
        release,
        directory,
    }
}

#[test]
fn install_sh_verifies_the_published_digest_and_installs_a_working_binary() {
    let fixture = prepare("1.2.3");
    let (ok, output) = run_install_sh(&LINUX_X64, &fixture.release.assets, &fixture.directory, &[]);
    assert!(ok, "install.sh failed on a good release:\n{output}");

    // The digest is not merely computed, it is REPORTED. A user who never sees
    // this line has no way to tell a verified install from an unverified one.
    assert!(
        output.contains("SHA-256 OK"),
        "install.sh installed without reporting that it verified the archive:\n{output}"
    );

    let binary = fixture.binary();
    assert!(
        binary.is_file(),
        "install.sh reported success and installed nothing to {}",
        fixture.directory.display()
    );
    assert_eq!(
        run_installed(&binary),
        fixture.release.expected_output("x86_64-unknown-linux-gnu"),
        "the installed file is not the binary from the archive"
    );

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(&binary)
            .expect("metadata")
            .permissions()
            .mode();
        assert!(
            mode & 0o111 != 0,
            "the installed binary is not executable (mode {mode:o}). A file \
             that has to be chmod'ed by hand is not an install."
        );
    }

    // The version is discovered from SHA256SUMS rather than hardcoded, which is
    // why the script never needs editing at release time.
    assert!(
        output.contains("Release 1.2.3"),
        "install.sh must report the version it resolved from SHA256SUMS:\n{output}"
    );
}

#[test]
fn install_sh_aborts_on_a_corrupted_archive_and_leaves_the_previous_install_alone() {
    // ------------------------------------------------------------------------
    // THE ARCHIVE IS SUBSTITUTED, NOT DAMAGED. See `common::substitute_payload`:
    // a damaged one is refused by `tar` before the digest is ever consulted, so
    // a script with no checksum check would pass this test too.
    //
    // THE SECOND HALF IS THE ONE THAT IS EASY TO GET WRONG.
    // ------------------------------------------------------------------------
    // "Aborts on a corrupted asset" is satisfied by a script that deletes the
    // old binary, downloads, discovers the mismatch and exits -- and that is a
    // worse outcome than not running it at all: a failed UPGRADE would take out
    // a working install and the host's boot-start service with it. So this
    // installs a good version first and asserts it still runs afterwards.
    let fixture = prepare("1.2.3");
    let (ok, output) = run_install_sh(&LINUX_X64, &fixture.release.assets, &fixture.directory, &[]);
    assert!(ok, "the first install must succeed:\n{output}");
    let before = run_installed(&fixture.binary());

    substitute_payload(&fixture.release, "x86_64-unknown-linux-gnu");

    let (ok, output) = run_install_sh(&LINUX_X64, &fixture.release.assets, &fixture.directory, &[]);
    assert!(
        !ok,
        "install.sh installed an archive whose digest does not match the \
         published one. `07-security.md` lists artifact tampering in transit as \
         a threat whose only control is this check.\n{output}"
    );
    assert!(
        output.contains("CHECKSUM MISMATCH"),
        "the abort must say plainly what went wrong; a user seeing only a \
         non-zero exit will assume a network problem and retry forever:\n{output}"
    );
    assert!(
        output.contains("nothing has been\ninstalled") || output.contains("nothing has been"),
        "the abort must tell the user that nothing was installed:\n{output}"
    );

    assert_eq!(
        run_installed(&fixture.binary()),
        before,
        "a failed install replaced or damaged the binary that was already \
         working. A failed upgrade must be a no-op."
    );
    assert_eq!(
        installed_entries(&fixture.directory),
        vec!["runner-manager".to_string()],
        "the aborted install left a staging file behind in the install \
         directory"
    );
}

#[test]
fn install_sh_is_idempotent() {
    let fixture = prepare("1.2.3");
    for attempt in 1..=2 {
        let (ok, output) =
            run_install_sh(&LINUX_X64, &fixture.release.assets, &fixture.directory, &[]);
        assert!(ok, "install.sh failed on attempt {attempt}:\n{output}");
    }

    assert_eq!(
        installed_entries(&fixture.directory),
        vec!["runner-manager".to_string()],
        "running install.sh twice must leave exactly one working binary and no \
         staging or backup files"
    );
    assert_eq!(
        run_installed(&fixture.binary()),
        fixture.release.expected_output("x86_64-unknown-linux-gnu"),
        "the binary left by the second run does not work"
    );
}

#[test]
fn install_sh_installs_the_exact_version_asked_for_or_nothing() {
    let fixture = prepare("1.2.3");

    // The version that IS published installs.
    let (ok, output) = run_install_sh(
        &LINUX_X64,
        &fixture.release.assets,
        &fixture.directory,
        &["--version", "1.2.3"],
    );
    assert!(ok, "--version 1.2.3 must install release 1.2.3:\n{output}");
    assert!(
        fixture.binary().is_file(),
        "nothing was installed:\n{output}"
    );

    // One that is not must be a refusal, and it must name both versions. This
    // is the case a remote 404 would normally catch and a local or mirrored
    // asset directory would not -- so the check is on the resolved asset name,
    // not on the transport.
    let (ok, output) = run_install_sh(
        &LINUX_X64,
        &fixture.release.assets,
        &fixture.directory,
        &["--version", "9.9.9"],
    );
    assert!(
        !ok,
        "install.sh installed 1.2.3 when it was asked for 9.9.9:\n{output}"
    );
    assert!(
        output.contains("9.9.9") && output.contains("1.2.3"),
        "the refusal must name what was asked for and what is available:\n{output}"
    );
}

#[test]
fn install_sh_refuses_a_release_that_publishes_nothing_for_this_platform() {
    // The install script derives the asset name from SHA256SUMS instead of
    // constructing it, so "this release has no build for you" is a state it can
    // actually observe. It must be a refusal: constructing the name anyway
    // produces a 404 that reads like an outage.
    let fixture = prepare("1.2.3");
    let sums = std::fs::read_to_string(fixture.release.sums()).expect("the fixture SHA256SUMS");
    let thinned: String = sums
        .lines()
        .filter(|line| !line.contains("x86_64-unknown-linux-gnu"))
        .map(|line| format!("{line}\n"))
        .collect();
    assert!(
        thinned.lines().count() == TARGETS.len() - 1,
        "the fixture SHA256SUMS did not lose exactly one line; the assertion \
         below would not be testing what it says"
    );
    std::fs::write(fixture.release.sums(), thinned).expect("rewriting SHA256SUMS");

    let (ok, output) = run_install_sh(&LINUX_X64, &fixture.release.assets, &fixture.directory, &[]);
    assert!(!ok, "install.sh installed something anyway:\n{output}");
    assert!(
        output.contains("lists no archive for x86_64-unknown-linux-gnu"),
        "the refusal must name the platform the release is missing:\n{output}"
    );
}

// ----------------------------------------------------------------------------
// Both scripts -- properties that are shapes in the source.
// ----------------------------------------------------------------------------

/// A script with its comments removed.
///
/// ----------------------------------------------------------------------------
/// SCANNED OVER EXECUTABLE TEXT, NOT OVER THE FILE -- a2's LESSON, AGAIN.
/// ----------------------------------------------------------------------------
/// `release_workflow.rs` learned this the hard way: the release workflow is
/// REQUIRED to document `git tag -d` as operator recovery, so a whole-file
/// search for it forced the workflow to choose between documenting the recovery
/// and passing its own test. The same trap is here. Both install scripts are
/// required to explain why there is no `--skip-verify` and why a bashism would
/// break `sh` -- which means both files necessarily contain the exact strings
/// the scans below look for, in comments, as prose for a human.
///
/// What matters is not whether the string appears but whether it is EXECUTED.
fn executable_text(name: &str) -> String {
    let source = std::fs::read_to_string(install_script(name))
        .unwrap_or_else(|err| panic!("cannot read {name}: {err}"));

    // PowerShell's block comment first: `<# ... #>` spans lines and holds each
    // script's whole header.
    let mut without_blocks = String::new();
    let mut rest = source.as_str();
    while let Some(open) = rest.find("<#") {
        without_blocks.push_str(&rest[..open]);
        match rest[open..].find("#>") {
            Some(close) => rest = &rest[open + close + 2..],
            None => {
                rest = "";
                break;
            }
        }
    }
    without_blocks.push_str(rest);

    without_blocks
        .lines()
        .filter(|line| !line.trim_start().starts_with('#'))
        .collect::<Vec<_>>()
        .join("\n")
}

#[test]
fn neither_installer_offers_a_way_to_skip_the_checksum() {
    // ------------------------------------------------------------------------
    // THERE IS NO FLAG FOR THIS, AND THERE MUST NEVER BE ONE.
    // ------------------------------------------------------------------------
    // A verification that can be turned off is a verification an attacker can
    // ask to have turned off -- in a forum post, in a stale blog, in an
    // "if the checksum fails, try --no-verify" answer. Such a flag is always
    // added for a good reason (a mirror that is briefly stale, a corporate
    // proxy rewriting bodies) and it is the reason the control stops existing.
    for name in ["install.sh", "install.ps1"] {
        let source = executable_text(name).to_lowercase();
        assert!(
            source.contains("sha256sums"),
            "{name}'s executable text never reads SHA256SUMS, so the absences \
             below would be vacuous -- a script that verifies nothing trivially \
             has no flag to switch verification off"
        );
        for forbidden in [
            "--skip-verify",
            "--no-verify",
            "--insecure",
            "-skipverify",
            "-noverify",
            "-insecure",
        ] {
            assert!(
                !source.contains(forbidden),
                "{name} accepts `{forbidden}`. The SHA-256 check is the only \
                 control `07-security.md` lists against a tampered release \
                 artifact; it does not get an off switch."
            );
        }
    }
}

#[test]
fn install_sh_stays_runnable_by_a_posix_shell() {
    // The documented command is `curl ... | sh`. On Debian and Ubuntu that is
    // `dash`; on Alpine it is BusyBox ash. Neither has `[[`, arrays, or
    // `${var,,}`, and a bashism here fails on exactly the hosts the script
    // exists to serve -- halfway through, after the download.
    //
    // The test suite runs this script under bash, which would accept every one
    // of these happily, so a static scan is the only thing that notices.
    let raw = std::fs::read_to_string(install_script("install.sh")).expect("install.sh");
    assert!(
        raw.starts_with("#!/bin/sh\n"),
        "install.sh must declare `#!/bin/sh`: the README documents piping it \
         into `sh`, and the shebang is what a reader checks it against"
    );

    // Scanned over executable text: the script's own header explains why a
    // bashism would break `sh`, and naming them there must not fail this.
    let source = executable_text("install.sh");
    // Positive guard: a file this scan could not read would satisfy every
    // absence below.
    assert!(
        source.contains("case \"$uname_s\" in"),
        "install.sh no longer looks like the script this scan was written \
         against; the bashism assertions below would be checking nothing"
    );

    for (bashism, why) in [
        ("<<<", "here-strings are bash-only"),
        (
            "declare ",
            "`declare` is bash-only; POSIX has no equivalent",
        ),
        ("${!", "indirect expansion is bash-only"),
        (
            ",,}",
            "case conversion in a parameter expansion is bash-only",
        ),
        (
            "^^}",
            "case conversion in a parameter expansion is bash-only",
        ),
        (
            "function ",
            "`function name()` is bash syntax; POSIX is `name()`",
        ),
        ("+=(", "arrays are bash-only"),
        (
            "local -",
            "`local -a`/`local -n` are bash-only; plain `local` is fine",
        ),
        // --------------------------------------------------------------------
        // THE ONE MOST LIKELY TO ARRIVE BY COPY-PASTE -- AND THE ONE THE dash
        // RUN BELOW WOULD NOT CATCH.
        // --------------------------------------------------------------------
        // BOTH sibling scripts open with `set -euo pipefail` (release.sh:36,
        // channels.sh:36) because both are `#!/usr/bin/env bash`. Anyone
        // hardening this file reaches for the line they can see two directories
        // away.
        //
        // And this is the entry that shows why the static scan is not made
        // redundant by `install_sh_installs_end_to_end_under_a_real_posix_shell`.
        // MEASURED, both ways: dash 0.5.12 and later ACCEPT `set -o pipefail`
        // -- it was added upstream in 2022 -- so the dash leg runs green with
        // this line in place. BusyBox ash, which is Alpine's `/bin/sh`, and any
        // dash older than 0.5.12 reject it and stop on line 1, before anything
        // else runs. So the shell that would actually break is the one no CI
        // leg here has, and a substring is the only thing that notices.
        (
            "set -o pipefail",
            "`pipefail` is a bash/ksh option that only recent dash grew. \
             BusyBox ash -- Alpine's `/bin/sh` -- and dash before 0.5.12 reject \
             the whole `set` on line 1. Both sibling scripts here use it, which \
             is exactly why it is the likeliest thing to be pasted in",
        ),
        (
            "&>",
            "`&>file` is bash's combined redirect; POSIX is `>file 2>&1`",
        ),
        (
            "echo -e",
            "`echo -e` is bash; dash's `echo` interprets escapes with no flag \
             and prints a literal `-e`. `printf` is the portable spelling, and \
             it is what this script already uses",
        ),
    ] {
        assert!(
            !source.contains(bashism),
            "install.sh uses `{bashism}`: {why}. It runs under `sh`, which on \
             Debian and Ubuntu is dash and on Alpine is BusyBox ash."
        );
    }

    // ------------------------------------------------------------------------
    // SOME PATTERNS NEED MORE THAN A SUBSTRING, AND THE REASON IS THE SAME ONE
    // EVERY TIME: THE LEGAL SPELLING CONTAINS THE ILLEGAL ONE.
    // ------------------------------------------------------------------------
    // `[[` is a bash keyword AND the opening of a POSIX character class. `==`
    // is a bashism in `[ ... ]` AND ordinary awk, and install.sh embeds an awk
    // program to read SHA256SUMS. `((` is a bash arithmetic command AND the
    // tail of POSIX `$((`. `$'` is bash's ANSI-C quoting AND a `$` anchor
    // sitting at the end of a single-quoted regex, which line 157 has. And
    // `source ` is a bashism as a COMMAND but ordinary English inside the two
    // messages that say "build from source".
    //
    // Every one of those, searched as a bare substring, reports correct code as
    // a bug -- and the fix somebody reaches for at that point is to delete the
    // check rather than to sharpen it. So each is narrowed here instead.
    for (number, line) in source.lines().enumerate() {
        let number = number + 1;
        assert!(
            !line.replace("[[:", "").contains("[["),
            "install.sh line {number} uses bash's `[[`; POSIX test is `[`:\n  {line}"
        );
        // A shell test with `==` is written `[ x == y ]`, so the line carries a
        // bracket followed by a space. `field[1] == 2` inside awk does not.
        assert!(
            !(line.contains(" == ") && line.contains("[ ")),
            "install.sh line {number} compares with `==` inside `[ ]`; POSIX \
             test compares with `=`:\n  {line}"
        );
        // `((expr))` is bash's arithmetic COMMAND. `$((expr))` is POSIX
        // arithmetic expansion and perfectly fine, so it is removed first --
        // the same exception as `[[:` above, for the same reason.
        assert!(
            !line.replace("$((", "").contains("(("),
            "install.sh line {number} uses bash's `((...))` arithmetic command; \
             POSIX has `$((...))` expansion, or `expr`:\n  {line}"
        );
        assert!(
            !has_substring_expansion(line),
            "install.sh line {number} uses bash's `${{var:offset:length}}` \
             substring expansion; POSIX parameter expansion has no offsets. \
             `${{var:-default}}` and `${{var:+alt}}` are POSIX and are not what \
             this flags:\n  {line}"
        );
        assert!(
            !has_ansi_c_quoting(line),
            "install.sh line {number} uses bash's `$'...'` ANSI-C quoting; dash \
             reads that as a `$` followed by a quoted string:\n  {line}"
        );
        assert!(
            !sources_a_file(line),
            "install.sh line {number} runs `source`; POSIX spells it `.`:\n  {line}"
        );
    }
}

/// `${name:0:8}` -- bash substring expansion.
///
/// Told apart from `${name:-default}` and `${name:+alt}`, which are POSIX and
/// begin identically, by the character after the colon: an offset is a digit.
fn has_substring_expansion(line: &str) -> bool {
    let bytes = line.as_bytes();
    let mut index = 0;
    while let Some(offset) = line[index..].find("${") {
        let mut cursor = index + offset + 2;
        while cursor < bytes.len()
            && (bytes[cursor].is_ascii_alphanumeric() || bytes[cursor] == b'_')
        {
            cursor += 1;
        }
        if cursor + 1 < bytes.len() && bytes[cursor] == b':' && bytes[cursor + 1].is_ascii_digit() {
            return true;
        }
        index = index + offset + 2;
    }
    false
}

/// `$'...'` -- bash's ANSI-C quoting -- as opposed to a `$` that happens to end
/// a single-quoted string.
///
/// install.sh line 157 carries `...[0-9]*)$'`: a regex anchor immediately
/// before the closing quote. ANSI-C quoting OPENS a word, so the character in
/// front of it decides.
fn has_ansi_c_quoting(line: &str) -> bool {
    let bytes = line.as_bytes();
    let mut index = 0;
    while let Some(offset) = line[index..].find("$'") {
        let at = index + offset;
        let opens_a_word = match at.checked_sub(1).map(|previous| bytes[previous]) {
            None => true,
            Some(byte) => byte.is_ascii_whitespace() || matches!(byte, b'=' | b'(' | b'{' | b','),
        };
        if opens_a_word {
            return true;
        }
        index = at + 2;
    }
    false
}

/// `source file` as a COMMAND, not the word "source" inside a message.
///
/// Both architecture refusals in install.sh say "Build from source with
/// `cargo install`", and both are executable lines.
fn sources_a_file(line: &str) -> bool {
    let trimmed = line.trim_start();
    trimmed.starts_with("source ")
        || ["; source ", "&& source ", "|| source ", "( source "]
            .iter()
            .any(|opener| line.contains(opener))
}

// ----------------------------------------------------------------------------
// install.ps1.
// ----------------------------------------------------------------------------

/// One PowerShell runtime at a time inside this integration-test process.
///
/// Rust runs tests concurrently by default. That made this file start six or
/// more `pwsh` processes at once on the two Unix CI hosts. The hosted macOS
/// runtime has then failed while parsing a truncated
/// `System.Collections.Concurrent` assembly name, and the hosted Linux runtime
/// has exited with a stack overflow. Both are failures before install.ps1 gets
/// control, and reruns on the same commit have passed.
///
/// Serialising the child runtimes fixes the actual contention without weakening
/// the suite: the Rust tests still run concurrently, every installer scenario
/// still executes, and each scenario still makes its checksum, corruption,
/// rollback, idempotency, architecture and destination assertions. Holding the
/// lock only through `Command::output` also keeps unrelated fixture construction
/// and install.sh coverage parallel.
static POWERSHELL_PROCESS: Mutex<()> = Mutex::new(());

fn powershell_process() -> MutexGuard<'static, ()> {
    POWERSHELL_PROCESS
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// EVERY PowerShell host on this machine that install.ps1 has to work under.
///
/// ----------------------------------------------------------------------------
/// THE FIRST HOST FOUND IS NOT ENOUGH, AND THAT WAS THE BUG.
/// ----------------------------------------------------------------------------
/// This used to return the FIRST of `pwsh`, `pwsh.exe`, `powershell.exe`.
/// GitHub's `windows-latest` image ships PowerShell 7 on PATH and so does a
/// normal developer machine, so every `install_ps1_*` test ran on pwsh 7 alone
/// -- and Windows PowerShell 5.1, which the script's own header calls a
/// supported host rather than a fallback, was never executed by anything.
///
/// That matters because 5.1 is not a subset of 7 by accident: it has no `??`,
/// no ternary, no `-Parallel`, and `Invoke-WebRequest` there needs
/// `-UseBasicParsing`. The script forbids all of them in prose. Nothing
/// enforced it, so any of them would have shipped green -- onto exactly the
/// clean Windows host with no PowerShell 7 and no Node that the Definition of
/// Done names as the case `irm ... | iex` exists to serve.
///
/// Covering it costs a loop, not a dependency: 5.1 is part of the operating
/// system and always lives at
/// `%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe`.
fn powershell_hosts() -> Vec<PathBuf> {
    let mut hosts: Vec<PathBuf> = Vec::new();

    for name in ["pwsh", "pwsh.exe"] {
        if let Some(found) = find_program(name)
            && !hosts.contains(&found)
        {
            hosts.push(found);
        }
    }

    if cfg!(windows) {
        // Resolved through PATH and by absolute path. Its directory is on PATH
        // by default, but "by default" is not something the only assertion
        // covering 5.1 should rest on. First hit wins, so the two spellings of
        // the same file do not become two runs of the same host.
        let mut candidates: Vec<PathBuf> = Vec::new();
        if let Some(found) = find_program("powershell.exe") {
            candidates.push(found);
        }
        let system_root = std::env::var_os("SystemRoot")
            .unwrap_or_else(|| std::ffi::OsString::from(r"C:\Windows"));
        candidates.push(
            PathBuf::from(system_root)
                .join("System32")
                .join("WindowsPowerShell")
                .join("v1.0")
                .join("powershell.exe"),
        );
        for candidate in candidates {
            if candidate.is_file() {
                hosts.push(candidate);
                break;
            }
        }
    }

    hosts
}

fn find_program(program: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    std::env::split_paths(&path)
        .map(|directory| directory.join(program))
        .find(|candidate| candidate.is_file())
}

/// Resolves every PowerShell host, or explains why the caller may stop.
///
/// PowerShell 7 is preinstalled on all three GitHub-hosted runner images and
/// Windows always has 5.1, so an empty list is a developer-machine condition
/// and not a CI one. Skipping quietly wherever it is missing would make this an
/// assertion that could vanish from CI unnoticed, so `CI` being set turns the
/// skip back into a failure.
fn powershell_hosts_or_skip() -> Vec<PathBuf> {
    let hosts = powershell_hosts();

    // Written as a branch rather than `assert!(!cfg!(windows), ...)`, which
    // clippy reads -- correctly -- as an assertion on a constant.
    if cfg!(windows) {
        assert!(
            !hosts.is_empty(),
            "no PowerShell found on a Windows host. Windows PowerShell 5.1 is \
             part of the operating system, so this is a broken PATH rather than \
             a missing dependency."
        );
        assert!(
            hosts.iter().any(|host| host
                .file_name()
                .is_some_and(|name| name.eq_ignore_ascii_case("powershell.exe"))),
            "Windows PowerShell 5.1 is not among the hosts these tests will \
             run ({hosts:?}). It is part of the operating system, and it is the \
             host install.ps1 is deliberately written for -- a clean Windows \
             machine has 5.1 and no PowerShell 7. Exercising only pwsh 7 is \
             what previously let a 5.1-only breakage ship green."
        );
        return hosts;
    }

    if !hosts.is_empty() {
        return hosts;
    }
    assert!(
        std::env::var_os("CI").is_none(),
        "no `pwsh` on PATH in CI. PowerShell 7 is preinstalled on GitHub's \
         ubuntu and macOS runner images; if that stops being true, install it \
         in the workflow rather than letting install.ps1 go untested."
    );
    eprintln!(
        "SKIPPED: no PowerShell on PATH. install.ps1 is exercised on Windows \
         and in CI; install `pwsh` to run it here."
    );
    hosts
}

/// True where `shell` is Windows PowerShell 5.1 rather than PowerShell 7.
fn is_windows_powershell(shell: &Path) -> bool {
    shell
        .file_name()
        .is_some_and(|name| name.eq_ignore_ascii_case("powershell.exe"))
}

/// The `PSModulePath` a CLEAN Windows host gives Windows PowerShell 5.1.
///
/// ----------------------------------------------------------------------------
/// WITHOUT THIS, THE 5.1 LEG MEASURES A MACHINE NOBODY MEANT TO TEST.
/// ----------------------------------------------------------------------------
/// `PSModulePath` is inherited, and every parent in the chain that reaches these
/// tests -- a developer's pwsh 7 prompt, GitHub's `run:` step, which is pwsh by
/// default on the windows image -- puts PowerShell 7's module directories in
/// FRONT of 5.1's. 5.1 started that way then resolves
/// `Microsoft.PowerShell.Utility` to PowerShell 7's copy and loses
/// `Get-FileHash` outright. Measured; and it is that one cmdlet, not a general
/// collapse.
///
/// That machine is worth testing, but it is a DIFFERENT machine from the one the
/// Definition of Done names -- "a clean Windows host with no Node installed",
/// which has 5.1 and no PowerShell 7 at all. So the two are separated: every
/// test through `run_install_ps1` gets the clean host, and
/// `install_ps1_verifies_the_digest_where_get_filehash_is_shadowed` constructs
/// the other one deliberately.
fn clean_windows_powershell_module_path() -> String {
    let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_string());
    format!(r"{system_root}\System32\WindowsPowerShell\v1.0\Modules")
}

/// install.ps1 is a Windows installer, and the Linux and macOS legs run it under
/// PowerShell 7 so its logic is covered on all three. Two of the variables a
/// real Windows host always sets do not exist there. Tests that need
/// `%LOCALAPPDATA%` already fake it for themselves; nothing faked
/// `%PROCESSOR_ARCHITECTURE%`, which is the one the script reads to choose an
/// artifact -- so every ps1 test that relies on detection failed off Windows
/// with "could not determine the processor architecture", while
/// `install_ps1_selects_the_windows_artifact_for_both_architectures` kept
/// passing precisely because it is the one test that passes `-Arch` explicitly.
///
/// Supplying it is fixture setup of the same kind as the faked `%LOCALAPPDATA%`,
/// not a bypass of the code under test: the script's own
/// `if (-not $Arch) { $Arch = $env:PROCESSOR_ARCHITECTURE }` is still the line
/// being exercised, which passing `-Arch` would skip.
///
/// On Windows the real variable is left alone, so that leg still tests what the
/// host actually reports.
fn supply_windows_host_environment(command: &mut Command) {
    if !cfg!(windows) {
        command.env("PROCESSOR_ARCHITECTURE", "AMD64");
    }
}
fn run_install_ps1(
    shell: &Path,
    base: &Path,
    install_dir: &Path,
    arguments: &[&str],
) -> (bool, String) {
    let script = install_script("install.ps1");
    let mut command = Command::new(shell);
    supply_windows_host_environment(&mut command);
    command.arg("-NoProfile").arg("-NonInteractive");
    if is_windows_powershell(shell) {
        command.env("PSModulePath", clean_windows_powershell_module_path());
    }
    if cfg!(windows) {
        // `-ExecutionPolicy` applies to Windows only; pwsh on Linux rejects it.
        //
        // This bypass is a HARNESS convenience -- `-File` is the only way to
        // pass `-BaseUrl`, `-Dir` and `-PrintPlan` -- and it is precisely what
        // hid the fact that the README's documented two-step form was refused
        // on a `Restricted` host. That form is exercised without any bypass by
        // `the_documented_windows_two_step_form_installs_under_a_restricted_policy`
        // below; do not let this line stand in for it.
        command.arg("-ExecutionPolicy").arg("Bypass");
    }
    command.arg("-File").arg(&script);
    command.arg("-BaseUrl").arg(base);
    command.arg("-Dir").arg(install_dir);
    command.args(arguments);
    command.current_dir(repository_root());

    let _runtime = powershell_process();
    let output = command
        .output()
        .unwrap_or_else(|err| panic!("cannot run install.ps1: {err}"));
    (
        output.status.success(),
        format!(
            "{}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        ),
    )
}

#[test]
fn install_ps1_selects_the_windows_artifact_for_both_architectures() {
    for shell in powershell_hosts_or_skip() {
        let host = shell.display();
        let temporary = TempDir::new().expect("a temporary directory");
        let base = temporary.path();

        // Only one Windows target is published, and Windows-on-ARM is served by
        // it through the x64 emulation layer. npm cannot do that -- it will not
        // install a `"cpu": ["x64"]` package onto an arm64 host -- so this is
        // the one platform where the install script reaches a user npm cannot.
        for architecture in ["AMD64", "ARM64"] {
            let (ok, output) =
                run_install_ps1(&shell, base, base, &["-PrintPlan", "-Arch", architecture]);
            assert!(
                ok,
                "install.ps1 refused {architecture} under {host}:\n{output}"
            );
            assert_eq!(
                plan_value(&output, "target"),
                "x86_64-pc-windows-msvc",
                "install.ps1 maps {architecture} to the wrong artifact under \
                 {host}:\n{output}"
            );
        }

        // 32-bit x86 publishes nothing, so it must be a refusal rather than a
        // silent x64 install that fails to load.
        let (ok, output) = run_install_ps1(&shell, base, base, &["-PrintPlan", "-Arch", "x86"]);
        assert!(
            !ok,
            "install.ps1 accepted a 32-bit x86 host, which publishes no \
             artifact, under {host}:\n{output}"
        );
        assert!(
            output.contains("cargo install"),
            "the refusal must point at the way in that still exists ({host}):\n{output}"
        );
    }
}

#[test]
fn install_ps1_defaults_to_the_documented_directory() {
    for shell in powershell_hosts_or_skip() {
        let host = shell.display();
        let temporary = TempDir::new().expect("a temporary directory");
        let local_app_data = temporary.path().join("LocalAppData");
        std::fs::create_dir_all(&local_app_data).expect("a fake LOCALAPPDATA");

        let script = install_script("install.ps1");
        let mut command = Command::new(&shell);
        supply_windows_host_environment(&mut command);
        command.arg("-NoProfile").arg("-NonInteractive");
        if cfg!(windows) {
            command.arg("-ExecutionPolicy").arg("Bypass");
        }
        command.arg("-File").arg(&script);
        command.arg("-BaseUrl").arg(temporary.path());
        command.arg("-PrintPlan");
        command.env("LOCALAPPDATA", &local_app_data);
        command.env("RUNNER_MANAGER_INSTALL_DIR", "");
        command.current_dir(repository_root());

        let _runtime = powershell_process();
        let output = command.output().expect("cannot run install.ps1");
        let text = format!(
            "{}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            output.status.success(),
            "install.ps1 --print-plan failed under {host}:\n{text}"
        );

        let directory = plan_value(&text, "install_dir");
        // Asserted on the shape rather than on an exact string: `Join-Path`
        // uses the host's separator, and this test also runs on Linux and
        // macOS.
        assert!(
            directory.starts_with(&local_app_data.to_string_lossy().to_string()),
            "install.ps1 must default under %LOCALAPPDATA%, got {directory} \
             under {host}"
        );
        assert!(
            directory.contains("Programs") && directory.ends_with("runner-manager"),
            "install.ps1 must default to %LOCALAPPDATA%\\Programs\\runner-manager. \
             It is per-user, needs no elevation, and does not move when a \
             toolchain moves -- which an installed service's recorded absolute \
             path cannot survive. Got {directory} under {host}"
        );
    }
}

#[test]
fn install_ps1_verifies_the_published_digest_and_installs() {
    for shell in powershell_hosts_or_skip() {
        let host = shell.display();
        let fixture = prepare("1.2.3");
        let (ok, output) =
            run_install_ps1(&shell, &fixture.release.assets, &fixture.directory, &[]);
        assert!(
            ok,
            "install.ps1 failed on a good release under {host}:\n{output}"
        );
        assert!(
            output.contains("SHA-256 OK"),
            "install.ps1 installed without reporting that it verified the \
             archive ({host}):\n{output}"
        );

        let binary = fixture.directory.join("runner-manager.exe");
        assert!(
            binary.is_file(),
            "install.ps1 reported success and installed nothing to {} under {host}",
            fixture.directory.display()
        );
        assert_eq!(
            std::fs::read(&binary).expect("the installed binary"),
            std::fs::read(
                fixture
                    .release
                    .staged("x86_64-pc-windows-msvc")
                    .join("runner-manager.exe")
            )
            .expect("the staged binary"),
            "the installed file is not byte-identical to the one in the archive \
             ({host})"
        );
        assert!(
            output.contains("Release 1.2.3"),
            "install.ps1 must report the version it resolved from SHA256SUMS \
             ({host}):\n{output}"
        );
    }
}

#[test]
fn install_ps1_aborts_on_a_corrupted_archive_and_leaves_the_previous_install_alone() {
    for shell in powershell_hosts_or_skip() {
        let host = shell.display();
        let fixture = prepare("1.2.3");
        let (ok, output) =
            run_install_ps1(&shell, &fixture.release.assets, &fixture.directory, &[]);
        assert!(ok, "the first install must succeed under {host}:\n{output}");

        let binary = fixture.directory.join("runner-manager.exe");
        let before = std::fs::read(&binary).expect("the installed binary");

        substitute_payload(&fixture.release, "x86_64-pc-windows-msvc");

        let (ok, output) =
            run_install_ps1(&shell, &fixture.release.assets, &fixture.directory, &[]);
        assert!(
            !ok,
            "install.ps1 installed an archive whose digest does not match the \
             published one, under {host}:\n{output}"
        );
        assert!(
            output.contains("CHECKSUM MISMATCH"),
            "the abort must say plainly what went wrong ({host}):\n{output}"
        );
        assert_eq!(
            std::fs::read(&binary).expect("the installed binary"),
            before,
            "a failed install replaced or damaged a binary that was already \
             working, under {host}. A failed upgrade must be a no-op."
        );
        assert_eq!(
            installed_entries(&fixture.directory),
            vec!["runner-manager.exe".to_string()],
            "the aborted install left a staging file behind ({host})"
        );
    }
}

#[test]
fn install_ps1_is_idempotent_and_pins_the_version_asked_for() {
    for shell in powershell_hosts_or_skip() {
        let host = shell.display();
        let fixture = prepare("1.2.3");

        for attempt in 1..=2 {
            let (ok, output) =
                run_install_ps1(&shell, &fixture.release.assets, &fixture.directory, &[]);
            assert!(
                ok,
                "install.ps1 failed on attempt {attempt} under {host}:\n{output}"
            );
        }
        assert_eq!(
            installed_entries(&fixture.directory),
            vec!["runner-manager.exe".to_string()],
            "running install.ps1 twice must leave exactly one binary and no \
             staging files ({host})"
        );

        let (ok, output) = run_install_ps1(
            &shell,
            &fixture.release.assets,
            &fixture.directory,
            &["-Version", "9.9.9"],
        );
        assert!(
            !ok,
            "install.ps1 installed 1.2.3 when it was asked for 9.9.9, under \
             {host}:\n{output}"
        );
        assert!(
            output.contains("9.9.9") && output.contains("1.2.3"),
            "the refusal must name what was asked for and what is available \
             ({host}):\n{output}"
        );

        let (ok, output) = run_install_ps1(
            &shell,
            &fixture.release.assets,
            &fixture.directory,
            &["-Version", "v1.2.3"],
        );
        assert!(
            !ok,
            "install.ps1 accepted -Version v1.2.3 under {host}:\n{output}"
        );
        assert!(
            output.contains("belongs to the tag"),
            "the refusal must explain that the `v` is the tag's, not the \
             version's ({host}):\n{output}"
        );
    }
}

// ----------------------------------------------------------------------------
// The README's Windows two-step form, run the way the README writes it.
// ----------------------------------------------------------------------------

/// The RUN step of the README's Windows two-step block.
///
/// Read OUT OF THE README rather than written here, so this test drives the
/// command the documentation actually hands people. Rewrite that block and this
/// executes the rewrite -- which is the only way a documented invocation stays
/// tested rather than merely asserted about.
fn documented_windows_two_step_run_command() -> String {
    let source = std::fs::read_to_string(repository_root().join("README.md"))
        .expect("README.md must be readable")
        .replace("\r\n", "\n");

    let mut blocks: Vec<Vec<String>> = Vec::new();
    let mut current: Option<Vec<String>> = None;
    for line in source.lines() {
        if let Some(rest) = line.trim_end().strip_prefix("```") {
            match current.take() {
                Some(body) => blocks.push(body),
                None => {
                    if rest.trim() == "powershell" {
                        current = Some(Vec::new());
                    }
                }
            }
            continue;
        }
        if let Some(body) = current.as_mut() {
            body.push(line.trim_end().to_string());
        }
    }

    let block = blocks
        .iter()
        .find(|body| {
            body.iter()
                .any(|line| line.contains("-OutFile install.ps1"))
        })
        .unwrap_or_else(|| {
            panic!(
                "README.md has no ```powershell block that downloads install.ps1 \
                 with `-OutFile`. That block is the two-step download-read-run \
                 form `09-release-distribution.md` requires for operators who \
                 will not pipe a remote script into a shell, and this test runs \
                 its last line verbatim."
            )
        });

    block
        .iter()
        .rev()
        .find(|line| !line.trim().is_empty())
        .expect("the two-step block must end with the step that runs the script")
        .trim()
        .to_string()
}

/// PowerShell wraps the text of an ERROR RECORD to the host's console width,
/// breaking on whitespace wherever that width happens to fall -- which moves
/// with the width itself and with the length of the paths inside the message.
/// `running scripts is disabled` therefore arrives with a newline somewhere
/// inside it often enough to matter, so a plain `contains` against the raw text
/// is a coin flip that lands differently in a developer's terminal, in a CI log,
/// and between two temporary directories of different name lengths.
///
/// Collapsing every whitespace run to a single space matches the phrase the
/// message actually carries rather than the shape the console gave it.
fn collapse_whitespace(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Runs `command` in a PowerShell whose PROCESS-scope execution policy is
/// `Restricted` -- which is what a clean Windows client has by default.
///
/// Process scope is per-process and outranks every scope but a Group Policy, so
/// the condition is constructed without touching the machine. Where a Group
/// Policy IS in force the process prints `POLICY-NOT-RESTRICTED` and runs
/// nothing, because a check that quietly ran under a permissive policy would
/// assert nothing at all. The marker carries the `MachinePolicy` and
/// `UserPolicy` scopes with it, so a caller can tell a host where the condition
/// is genuinely unconstructable from one where the lowering failed for some
/// other reason -- which would mean this helper had stopped working.
fn run_under_restricted_policy(
    shell: &Path,
    working_directory: &Path,
    command: &str,
    envs: &[(&str, &str)],
) -> (bool, String) {
    let script = format!(
        "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Restricted -Force; \
         if ((Get-ExecutionPolicy) -ne 'Restricted') {{ \
         Write-Output \"POLICY-NOT-RESTRICTED \
         MachinePolicy=$(Get-ExecutionPolicy -Scope MachinePolicy) \
         UserPolicy=$(Get-ExecutionPolicy -Scope UserPolicy) \
         Effective=$(Get-ExecutionPolicy)\"; exit 0 }}; {command}"
    );

    let mut process = Command::new(shell);
    process
        .arg("-NoProfile")
        .arg("-NonInteractive")
        .arg("-Command")
        .arg(&script);
    if is_windows_powershell(shell) {
        // `Set-ExecutionPolicy` lives in `Microsoft.PowerShell.Security` and is
        // lost to the same shadowing that takes `Get-FileHash`, so this test
        // could not even construct its own condition without a clean path.
        process.env("PSModulePath", clean_windows_powershell_module_path());
    }
    process.current_dir(working_directory);
    for (key, value) in envs {
        process.env(key, value);
    }

    let _runtime = powershell_process();
    let output = process
        .output()
        .unwrap_or_else(|err| panic!("cannot run {}: {err}", shell.display()));
    (
        output.status.success(),
        format!(
            "{}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        ),
    )
}

#[test]
fn the_documented_windows_two_step_form_installs_under_a_restricted_policy() {
    // ------------------------------------------------------------------------
    // THE POLICY IS THE WHOLE POINT, AND THE HARNESS USED TO BYPASS IT.
    // ------------------------------------------------------------------------
    // Two facts collide. `09-release-distribution.md` requires a two-step
    // download-read-run form for operators who will not pipe a remote script
    // into a shell. A Windows CLIENT's default `LocalMachine` execution policy
    // is `Restricted`. So `.\install.ps1` on such a host fails with "cannot be
    // loaded because running scripts is disabled on this system" -- and it
    // fails at the LAST step, after the operator has already downloaded and
    // read the script, which is the worst possible moment to be refused.
    //
    // Every other install.ps1 test here passes `-ExecutionPolicy Bypass`,
    // because `-File` is the only way to hand the script parameters. The suite
    // therefore could not see this, and did not. This test uses no bypass, and
    // it runs the command it READS OUT OF THE README rather than one written
    // here -- so documenting a form that does not work is a red test.
    //
    // Execution policy is a Windows-only concept and `Set-ExecutionPolicy` is
    // not supported by pwsh on Linux or macOS, so there is nothing to build
    // there.
    if !cfg!(windows) {
        eprintln!(
            "SKIPPED: execution policy is a Windows concept. The documented \
             two-step form is exercised on the windows leg."
        );
        return;
    }

    let run_step = documented_windows_two_step_run_command();

    for shell in powershell_hosts_or_skip() {
        let host = shell.display().to_string();
        let fixture = prepare("1.2.3");

        // What the README's first two lines leave behind: the script,
        // downloaded into the operator's working directory, and read.
        let download = fixture.release.root.join("download");
        std::fs::create_dir_all(&download).expect("a download directory");
        std::fs::copy(install_script("install.ps1"), download.join("install.ps1"))
            .expect("copying install.ps1 the way the documented download would");

        // ---- the negative control ------------------------------------------
        // Without it, a machine whose policy could not actually be lowered
        // would satisfy the positive assertion below for entirely the wrong
        // reason, and this test would go green on a host it never constrained.
        let (ran, refusal) =
            run_under_restricted_policy(&shell, &download, "& '.\\install.ps1' -PrintPlan", &[]);
        if refusal.contains("POLICY-NOT-RESTRICTED") {
            // Process scope outranks every scope but a Group Policy, so a host
            // that refuses the lowering is either policy-managed -- in which
            // case NOBODY can construct this condition on it, CI included --
            // or something else is overriding the policy and this negative
            // control has stopped being sound. Only the second is a defect,
            // and the marker names the scopes so the two can be told apart.
            //
            // Keying that distinction on `CI`, as this did, asserted something
            // else entirely: that no CI image is ever policy-managed. Where
            // that is false the assertion fires on every run, and reports the
            // image as a failure of whatever change is under test.
            let pinned_by_group_policy = !refusal.contains("MachinePolicy=Undefined")
                || !refusal.contains("UserPolicy=Undefined");
            assert!(
                pinned_by_group_policy,
                "the execution policy could not be lowered to Restricted \
                 ({host}), and no Group Policy explains it. Process scope \
                 outranks every other scope, so something else is overriding \
                 it and this test's negative control is no longer measuring \
                 what it claims:\n{refusal}"
            );
            eprintln!(
                "SKIPPED: a Group Policy pins the execution policy on this \
                 machine ({host}), so `Restricted` cannot be constructed. \
                 Reported scopes: {}",
                refusal.trim()
            );
            continue;
        }
        assert!(
            !ran,
            "running `.\\install.ps1` as a FILE succeeded under a Restricted \
             execution policy on {host}. That is not what Windows does, so \
             either the policy was not applied or this test is measuring \
             nothing:\n{refusal}"
        );
        assert!(
            collapse_whitespace(&refusal).contains("running scripts is disabled"),
            "the file form was refused under {host}, but not by the execution \
             policy -- so the policy is not what this test is holding \
             constant:\n{refusal}"
        );

        // ---- the form the README actually documents ------------------------
        let assets = posix(&fixture.release.assets);
        let directory = posix(&fixture.directory);
        let environment = [
            ("RUNNER_MANAGER_INSTALL_BASE_URL", assets.as_str()),
            ("RUNNER_MANAGER_INSTALL_DIR", directory.as_str()),
        ];

        let (ok, output) = run_under_restricted_policy(&shell, &download, &run_step, &environment);
        assert!(
            ok,
            "the README documents `{run_step}` as the last step of the two-step \
             install, and it does not work on a Windows host with the default \
             `Restricted` execution policy ({host}). An operator who declines to \
             pipe a remote script into a shell is refused at the last step, \
             after reading the script:\n{output}"
        );
        assert!(
            output.contains("SHA-256 OK"),
            "the documented form installed without reporting that it verified \
             the archive ({host}):\n{output}"
        );

        let binary = fixture.directory.join("runner-manager.exe");
        assert!(
            binary.is_file(),
            "the documented form reported success and installed nothing to {} \
             under {host}:\n{output}",
            fixture.directory.display()
        );
        let before = std::fs::read(&binary).expect("the installed binary");

        // --------------------------------------------------------------------
        // BYTE-IDENTICAL, BECAUSE THIS IS THE ONLY TEST THAT REACHES THE
        // `ZipFile` FALLBACK.
        // --------------------------------------------------------------------
        // Under `Restricted` the `Microsoft.PowerShell.Archive` module cannot
        // load, so this run -- and no other in this file -- unpacks through
        // `[IO.Compression.ZipFile]::ExtractToDirectory`. `is_file()` alone
        // asked only whether a file of the right NAME appeared, which every
        // wrong extraction this fallback could perform would also satisfy. The
        // `Expand-Archive` path is held to byte-identity a few tests up; the
        // path that is harder to reach must not be held to less.
        assert_eq!(
            before,
            std::fs::read(
                fixture
                    .release
                    .staged("x86_64-pc-windows-msvc")
                    .join("runner-manager.exe")
            )
            .expect("the staged binary"),
            "the .NET zip reader installed something that is not byte-for-byte \
             the archive's payload under {host}. The fixture archive carries a \
             directory entry, the binary and a LICENSE, so an extractor that \
             takes the first entry and stops, or that writes a truncated file, \
             reaches here rather than passing on a name:\n{output}"
        );

        // ---- and the abort path under the same form ------------------------
        // This is where `exit` would have been fatal. Under `iex` there is no
        // script of our own to exit FROM, so `exit` terminates the SESSION that
        // ran it: Windows Terminal closes the tab and takes the CHECKSUM
        // MISMATCH message with it. Note the asymmetry -- the success path
        // never calls `exit`, so only a FAILURE killed the session, which is
        // the one case where the message most needed to survive. install.ps1
        // throws instead when `$MyInvocation.MyCommand.Path` is empty.
        substitute_payload(&fixture.release, "x86_64-pc-windows-msvc");
        let (ok, output) = run_under_restricted_policy(&shell, &download, &run_step, &environment);
        assert!(
            !ok,
            "the documented form installed an archive whose digest does not \
             match the published one, under {host}:\n{output}"
        );
        assert!(
            output.contains("CHECKSUM MISMATCH"),
            "the abort message did not survive the documented invocation on \
             {host}. A user who sees only a non-zero exit -- or a closed \
             terminal -- assumes a network problem and retries forever:\n{output}"
        );
        assert_eq!(
            std::fs::read(&binary).expect("the installed binary"),
            before,
            "a failed install through the documented form replaced or damaged a \
             binary that was already working ({host}). A failed upgrade must be \
             a no-op."
        );
    }
}

#[test]
fn install_sh_removes_its_staging_file_when_the_install_step_fails() {
    // ------------------------------------------------------------------------
    // THE ONE TEMPORARY FILE THAT IS NOT IN THE TEMPORARY DIRECTORY.
    // ------------------------------------------------------------------------
    // The staged copy cannot live under `$work`, and that is not an oversight:
    // a rename is only atomic within a filesystem, so the staging file has to
    // be written beside the destination. `$work` is a temp directory that may
    // well be on another mount.
    //
    // Which means the EXIT trap removing only `$work` left
    // `.runner-manager.install-tmp` sitting in the user's install directory
    // whenever `chmod` or `mv` failed -- a full disk, a mount option, a
    // destination that is a running executable. install.ps1 has always removed
    // its own in the `catch` that wraps the same two steps.
    //
    // Reaching that branch needs a filesystem that misbehaves, so `mv` is
    // shadowed with a command that always fails. That is portable, and it is
    // the only thing here that executes the trap's second line.
    let fixture = prepare("1.2.3");
    let (ok, output) = run_install_sh(&LINUX_X64, &fixture.release.assets, &fixture.directory, &[]);
    assert!(ok, "the first install must succeed:\n{output}");

    let shim = fixture.release.root.join("shim");
    std::fs::create_dir_all(&shim).expect("a shim directory");
    let failing_mv = shim.join("mv");
    std::fs::write(&failing_mv, "#!/bin/sh\nexit 1\n").expect("a failing mv");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&failing_mv, std::fs::Permissions::from_mode(0o755))
            .expect("the shim must be executable");
    }

    // PATH is prepended INSIDE the shell rather than handed to the process.
    // Git for Windows' `bash.exe` front-loads its own `/mingw64/bin:/usr/bin`
    // ahead of whatever PATH it inherits, so an inherited entry can never win
    // there -- measured. Doing it after the shell has started also sidesteps
    // spelling the directory in the shell's own path form: `$PWD` already is.
    let wrapper = format!(
        "cd '{}' && PATH=\"$PWD:$PATH\" && export PATH && exec '{}'",
        posix(&shim),
        posix(&install_script("install.sh"))
    );

    let mut command = Command::new(bash_program());
    command.arg("-c").arg(&wrapper);
    command.env("RUNNER_MANAGER_INSTALL_UNAME_S", LINUX_X64.uname_s);
    command.env("RUNNER_MANAGER_INSTALL_UNAME_M", LINUX_X64.uname_m);
    command.env(
        "RUNNER_MANAGER_INSTALL_BASE_URL",
        posix(&fixture.release.assets),
    );
    command.env("RUNNER_MANAGER_INSTALL_DIR", posix(&fixture.directory));
    let finished = command.output().expect("cannot run install.sh");
    let ok = finished.status.success();
    let output = format!(
        "{}{}",
        String::from_utf8_lossy(&finished.stdout),
        String::from_utf8_lossy(&finished.stderr)
    );

    // The positive guard: if the shim were not reached, the install would
    // SUCCEED and the assertion below would be checking a clean directory that
    // no failure ever touched.
    assert!(
        !ok,
        "`mv` was shadowed with a command that always fails and install.sh \
         still reported success, so the branch this test exists for was never \
         entered:\n{output}"
    );
    assert!(
        output.contains("could not install into"),
        "the failure must name the step that failed:\n{output}"
    );

    assert_eq!(
        installed_entries(&fixture.directory),
        vec!["runner-manager".to_string()],
        "install.sh left its staging file in the install directory after a \
         failed install. The EXIT trap has to remove the staged path as well as \
         `$work`: the staged path is the one temporary file that is NOT under \
         `$work`, and nothing else will ever clean it up."
    );
    assert_eq!(
        run_installed(&fixture.binary()),
        fixture.release.expected_output("x86_64-unknown-linux-gnu"),
        "the binary that was already working must survive a failed upgrade"
    );
}

// ----------------------------------------------------------------------------
// The destination that is a DIRECTORY, in both installers.
// ----------------------------------------------------------------------------
// A FALSE SUCCESS, and the same class as a checksum that is never compared:
// both scripts finish, both print "Installed runner-manager 1.2.3 to <path>",
// and nothing is installed. `07-security.md`'s reasoning about a mismatch
// applies unchanged -- a failure sends the user looking and a false success does
// not -- which is why this is a guard with a test rather than a one-line fix.
//
// Measured on both platforms before either guard was written:
//
//     Move-Item SUCCEEDED
//     C:\tmp\mvprobe2\bin\runner-manager.exe\.staged
//
// `mv -f src dst` and `Move-Item -Force` do not replace a directory and do not
// fail: they move the source INSIDE it. So the `|| fail` on one side and the
// `catch` on the other never run, and the staging cleanup no-ops as well,
// because the staged path is no longer where the cleanup looks for it.
//
// How the directory gets there is not exotic: an interrupted extraction, a
// `mkdir -p` of the wrong path, a packaging tool that made a folder. What makes
// it worth a test is that the user's next action is `runner-manager --version`
// -- which the script itself tells them to run -- and it is still not found.

#[test]
fn install_sh_refuses_a_destination_that_is_a_directory() {
    let fixture = prepare("1.2.3");
    let destination = fixture.directory.join("runner-manager");
    std::fs::create_dir_all(&destination).expect("a directory where the binary belongs");

    let (ok, output) = run_install_sh(&LINUX_X64, &fixture.release.assets, &fixture.directory, &[]);

    assert!(
        !ok,
        "install.sh reported SUCCESS with a directory where the binary belongs. \
         `mv -f` moved the staged file inside it and exited 0, so the `|| fail` \
         never ran:\n{output}"
    );
    assert!(
        output.contains("is a directory, not a file"),
        "the refusal must name the cause. `could not install into ...` sends \
         the reader to permissions, which is not what is wrong:\n{output}"
    );
    assert!(
        !output.contains("Installed runner-manager"),
        "install.sh announced an install it did not perform:\n{output}"
    );

    // The move must not have happened AT ALL -- not into the directory, and not
    // beside it. This is the assertion that separates a real guard from a
    // message printed after the damage.
    assert_eq!(
        installed_entries(&destination),
        Vec::<String>::new(),
        "install.sh moved the staged binary INSIDE the directory that was \
         standing where the binary belongs. That is the false success this \
         guard exists to prevent, now with a non-zero exit in front of it."
    );

    // And the staging file is gone. It lives beside the destination rather than
    // under `$work`, so only the EXIT trap removes it -- and the trap could only
    // no-op before, because the staged path had been moved away.
    assert_eq!(
        installed_entries(&fixture.directory),
        vec!["runner-manager".to_string()],
        "install.sh left its staging file in the install directory after \
         refusing. The EXIT trap removes the staged path, and this is the case \
         where it must still be there to remove."
    );
}

#[test]
fn install_ps1_refuses_a_destination_that_is_a_directory() {
    for shell in powershell_hosts_or_skip() {
        let host = shell.display().to_string();
        let fixture = prepare("1.2.3");
        let destination = fixture.directory.join("runner-manager.exe");
        std::fs::create_dir_all(&destination).expect("a directory where the binary belongs");

        let (ok, output) =
            run_install_ps1(&shell, &fixture.release.assets, &fixture.directory, &[]);

        assert!(
            !ok,
            "install.ps1 reported SUCCESS with a directory where the binary \
             belongs ({host}). `Move-Item -Force` moved the staged file inside \
             it and did not throw, so the `catch` never ran:\n{output}"
        );
        assert!(
            output.contains("is a directory, not a file"),
            "the refusal must name the cause ({host}). `could not replace ...` \
             sends the reader to the running-agent advice, which is not what is \
             wrong here:\n{output}"
        );
        assert!(
            !output.contains("Installed runner-manager"),
            "install.ps1 announced an install it did not perform \
             ({host}):\n{output}"
        );
        assert_eq!(
            installed_entries(&destination),
            Vec::<String>::new(),
            "install.ps1 moved the staged binary INSIDE the directory standing \
             where the binary belongs ({host})"
        );
        assert_eq!(
            installed_entries(&fixture.directory),
            vec!["runner-manager.exe".to_string()],
            "install.ps1 left its staging file in the install directory after \
             refusing ({host}). The guard removes the staged copy before it \
             fails, the way the `catch` beside it already did."
        );
    }
}

// ----------------------------------------------------------------------------
// Windows PowerShell 5.1 on a machine that ALSO has PowerShell 7.
// ----------------------------------------------------------------------------

/// PowerShell 7's module directory, where this machine has PowerShell 7.
fn powershell_seven_modules() -> Option<PathBuf> {
    for shell in powershell_hosts() {
        if is_windows_powershell(&shell) {
            continue;
        }
        if let Some(modules) = shell.parent().map(|directory| directory.join("Modules"))
            && modules.is_dir()
        {
            return Some(modules);
        }
    }
    None
}

#[test]
fn install_ps1_verifies_the_digest_where_get_filehash_is_shadowed() {
    // ------------------------------------------------------------------------
    // THE FIRST THING RUNNING 5.1 FOUND WAS A 5.1-ONLY DEFECT.
    // ------------------------------------------------------------------------
    // Type `powershell.exe` at a pwsh 7 prompt -- an ordinary thing to do -- and
    // the 5.1 you get inherits a `PSModulePath` whose first entries are
    // PowerShell 7's. 5.1 resolves `Microsoft.PowerShell.Utility` to 7's copy,
    // cannot load it, and `Get-FileHash` becomes "not recognized as the name of
    // a cmdlet". Measured on 5.1.26100; and it is narrow -- every other cmdlet
    // install.ps1 uses still resolves, including `Invoke-WebRequest`, which is
    // in the same module.
    //
    // What made it worth fixing rather than noting is WHERE it lands: after the
    // download, at the digest comparison, so the user is told about a missing
    // cmdlet instead of about the archive. It fails closed, which is the right
    // direction and not the same thing as working.
    //
    // install.ps1 now falls through to `System.Security.Cryptography.SHA256`,
    // which is part of the framework rather than of a module. This test is what
    // keeps that branch honest: it is the only thing that executes it.
    if !cfg!(windows) {
        eprintln!("SKIPPED: Windows PowerShell 5.1 exists only on Windows.");
        return;
    }

    let Some(shell) = powershell_hosts_or_skip()
        .into_iter()
        .find(|host| is_windows_powershell(host))
    else {
        return;
    };

    let Some(seven) = powershell_seven_modules() else {
        assert!(
            std::env::var_os("CI").is_none(),
            "PowerShell 7 is preinstalled on GitHub's windows runner image, so \
             its module directory not being found in CI means this test cannot \
             construct the condition it exists for -- and the .NET digest \
             fallback in install.ps1 would then be executed by nothing."
        );
        eprintln!(
            "SKIPPED: no PowerShell 7 on this machine, so 5.1's module path \
             cannot be shadowed the way a dual-install shadows it."
        );
        return;
    };

    let shadowed = format!(
        "{};{}",
        seven.display(),
        clean_windows_powershell_module_path()
    );

    // The positive guard. If PowerShell 7 ever stops shadowing 5.1's
    // `Get-FileHash`, this test would still install perfectly -- through the
    // cmdlet, never touching the fallback -- and would report success while
    // covering nothing.
    let mut probe = Command::new(&shell);
    probe
        .arg("-NoProfile")
        .arg("-NonInteractive")
        .arg("-Command")
        .arg("if (Get-Command Get-FileHash -ErrorAction SilentlyContinue) { 'PRESENT' } else { 'ABSENT' }")
        .env("PSModulePath", &shadowed);
    let _runtime = powershell_process();
    let probed = probe.output().expect("cannot run Windows PowerShell");
    drop(_runtime);
    let probed = String::from_utf8_lossy(&probed.stdout).trim().to_string();
    if probed != "ABSENT" {
        eprintln!(
            "SKIPPED: `Get-FileHash` still resolves under a PowerShell 7 module \
             path on this machine (probe said {probed:?}), so the shadowing this \
             test reproduces no longer happens here."
        );
        return;
    }

    let fixture = prepare("1.2.3");
    let script = install_script("install.ps1");
    let run = |arguments: &[&str]| -> (bool, String) {
        let mut command = Command::new(&shell);
        command
            .arg("-NoProfile")
            .arg("-NonInteractive")
            .arg("-ExecutionPolicy")
            .arg("Bypass")
            .arg("-File")
            .arg(&script)
            .arg("-BaseUrl")
            .arg(&fixture.release.assets)
            .arg("-Dir")
            .arg(&fixture.directory)
            .args(arguments)
            .env("PSModulePath", &shadowed)
            .current_dir(repository_root());
        let _runtime = powershell_process();
        let output = command.output().expect("cannot run install.ps1");
        (
            output.status.success(),
            format!(
                "{}{}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            ),
        )
    };

    let (ok, output) = run(&[]);
    assert!(
        ok,
        "install.ps1 could not install under a Windows PowerShell 5.1 whose \
         `Get-FileHash` is shadowed by a PowerShell 7 install. That is a real \
         machine, and the failure lands after the download at the verification \
         step:\n{output}"
    );
    assert!(
        output.contains("SHA-256 OK"),
        "the fallback digest path installed without reporting that it verified \
         the archive:\n{output}"
    );

    let binary = fixture.directory.join("runner-manager.exe");
    let before = std::fs::read(&binary).expect("the installed binary");

    // The fallback must be a real SHA-256 and not a check that passes. This is
    // the assertion that would catch a "fallback" that returned an empty string
    // and compared equal to nothing.
    substitute_payload(&fixture.release, "x86_64-pc-windows-msvc");
    let (ok, output) = run(&[]);
    assert!(
        !ok,
        "the fallback digest path accepted an archive whose digest does not \
         match the published one. A fallback that cannot refuse is worse than \
         no fallback: it turns a loud missing-cmdlet error into a silent \
         unverified install:\n{output}"
    );
    assert!(
        output.contains("CHECKSUM MISMATCH"),
        "the fallback path aborted without saying why:\n{output}"
    );
    assert_eq!(
        std::fs::read(&binary).expect("the installed binary"),
        before,
        "a failed install through the fallback path damaged a working binary"
    );
}

// ----------------------------------------------------------------------------
// SHA256SUMS is a parsed interface, and it has two forms in circulation.
// ----------------------------------------------------------------------------

/// Rewrites the fixture's `SHA256SUMS` into the binary-mode form.
///
/// `<hash> *<name>` -- one space and a marker -- is what `sha256sum -b` writes
/// everywhere and what GNU sha256sum writes on Windows by default. `sha256sum
/// -c` verifies it, and the README tells readers to check a release with
/// exactly that command.
fn rewrite_sums_as_binary_mode(release: &FixtureRelease) {
    let text = std::fs::read_to_string(release.sums()).expect("the fixture SHA256SUMS");
    let rewritten: String = text
        .lines()
        .map(|line| match line.split_once("  ") {
            Some((hash, name)) => format!("{hash} *{name}\n"),
            None => format!("{line}\n"),
        })
        .collect();
    // A rewrite that changed nothing would leave every assertion below testing
    // the same format as every other test in this file.
    assert!(
        rewritten.contains(" *runner-manager-"),
        "the fixture rewrite produced no binary-mode line:\n{rewritten}"
    );
    std::fs::write(release.sums(), rewritten).expect("rewriting SHA256SUMS");
}

#[test]
fn both_installers_read_the_binary_mode_form_of_sha256sums() {
    // ------------------------------------------------------------------------
    // A PARSER STRICTER THAN `sha256sum -c` REFUSES FILES THE README ENDORSES.
    // ------------------------------------------------------------------------
    // Deriving the asset name from SHA256SUMS is what lets these scripts
    // survive a version bump untouched -- and it makes the file an INTERFACE
    // rather than a blob. `sha256sum -c` accepts both `<hash>  <name>` and
    // `<hash> *<name>`, and "Verifying a release yourself" in the README tells
    // people to use `sha256sum -c`. A script that accepts only the first form
    // refuses a file that command verifies -- and, before this, refused it by
    // announcing "This release does not publish that platform", which sends the
    // reader looking for a missing build that is sitting right there.
    let fixture = prepare("1.2.3");
    rewrite_sums_as_binary_mode(&fixture.release);
    let (ok, output) = run_install_sh(&LINUX_X64, &fixture.release.assets, &fixture.directory, &[]);
    assert!(
        ok,
        "install.sh refused a SHA256SUMS in the binary-mode form that \
         `sha256sum -b` writes and `sha256sum -c` verifies:\n{output}"
    );
    assert_eq!(
        run_installed(&fixture.binary()),
        fixture.release.expected_output("x86_64-unknown-linux-gnu"),
        "install.sh parsed the binary-mode form but installed the wrong thing"
    );

    for shell in powershell_hosts_or_skip() {
        let host = shell.display();
        let fixture = prepare("1.2.3");
        rewrite_sums_as_binary_mode(&fixture.release);
        let (ok, output) =
            run_install_ps1(&shell, &fixture.release.assets, &fixture.directory, &[]);
        assert!(
            ok,
            "install.ps1 refused a SHA256SUMS in the binary-mode form under \
             {host}:\n{output}"
        );
        assert!(
            fixture.directory.join("runner-manager.exe").is_file(),
            "install.ps1 reported success and installed nothing ({host}):\n{output}"
        );
    }
}

#[test]
fn install_sh_tells_an_unreadable_checksum_file_from_a_missing_platform() {
    // ------------------------------------------------------------------------
    // TWO FAILURES THAT NEED TWO SENTENCES.
    // ------------------------------------------------------------------------
    // "SHA256SUMS parsed to nothing" is a truncated download, a proxy's error
    // page, or a file that is not a checksum file at all. "SHA256SUMS parsed,
    // and none of it is for you" is a release that genuinely skipped a
    // platform. They have different causes and different fixes, and reporting
    // the first as the second is how an operator comes away believing their
    // platform was dropped from a release that is perfectly intact.
    let fixture = prepare("1.2.3");
    std::fs::write(
        fixture.release.sums(),
        "<html><head><title>404 Not Found</title></head></html>\n",
    )
    .expect("overwriting SHA256SUMS");

    let (ok, output) = run_install_sh(&LINUX_X64, &fixture.release.assets, &fixture.directory, &[]);
    assert!(
        !ok,
        "install.sh installed something from a SHA256SUMS it could not \
         parse:\n{output}"
    );
    assert!(
        output.contains("no line this script can read"),
        "the refusal must say the file could not be read at all:\n{output}"
    );
    assert!(
        !output.contains("does not publish that platform"),
        "install.sh reported an unparseable SHA256SUMS as a release that \
         skipped this platform. The user then goes looking for a missing build \
         instead of a corrupted download:\n{output}"
    );
}

// ----------------------------------------------------------------------------
// The whole-name guard, in the two places it is implemented and was not tested.
// ----------------------------------------------------------------------------

/// Appends the decoy classes a release carries the moment anything is published
/// beside an archive -- one line of each shape, per target.
///
/// ----------------------------------------------------------------------------
/// FOUR SHAPES, BECAUSE THE FIRST TWO DO NOT CONSTRAIN THE `^` AT ALL.
/// ----------------------------------------------------------------------------
/// The first two are NAME decoys: a name the archive's is a SUFFIX of
/// (`vendored-...`) and one it is a PREFIX of (`...zip.sig`). Those were the
/// whole set, and measured against install.ps1's regex they pin the `$` and
/// nothing else -- because in
///
///     ^([0-9a-f]{64})\s+\*?(runner-manager-...\.zip)$
///
/// the `^` anchors the HASH, not the name. `vendored-` is rejected by `\s+\*?`
/// abutting `runner-manager-` with the anchor or without it, and `.sig` is
/// rejected by `$` either way. So deleting the `^` from that regex passed this
/// test, and the comment in install.ps1 that claimed `vendored-` "needs `^`"
/// was simply wrong.
///
/// The last two are the shapes that DO constrain `^` -- a line carrying
/// something before the digest, and a line whose hex run is too long:
///
///     junk <64 hex>  runner-manager-...           unanchored, this matches
///     <70 hex>  runner-manager-...                unanchored, this matches
///
/// and the over-long one is why this is a line of fixture rather than a note in
/// a comment. Unanchored the engine starts six characters in and takes the LAST
/// 64 of the 70, so install.ps1 does not refuse: it pins a SHIFTED digest and
/// then reports CHECKSUM MISMATCH against an archive that is perfectly good.
///
/// install.sh's awk is unaffected by the last two -- it splits on whitespace
/// and drops any record that is not exactly two fields whose first matches
/// `^[0-9a-f]{64}$` -- so they are inert there and constrain only the regex.
/// That asymmetry is the point: the property is implemented twice and each
/// implementation needs its own decoy.
///
/// Every digest here is deliberately not the archive's, so picking any of these
/// lines is not merely detectable as a count -- it is fatal to the install.
fn add_decoy_lines(release: &FixtureRelease) {
    let mut text = std::fs::read_to_string(release.sums()).expect("the fixture SHA256SUMS");
    for (target, extension, _) in TARGETS {
        text.push_str(&format!(
            "{}  vendored-runner-manager-{}-{target}.{extension}\n",
            "b".repeat(64),
            release.version
        ));
        text.push_str(&format!(
            "{}  runner-manager-{}-{target}.{extension}.sig\n",
            "c".repeat(64),
            release.version
        ));
        text.push_str(&format!(
            "junk {}  runner-manager-{}-{target}.{extension}\n",
            "d".repeat(64),
            release.version
        ));
        text.push_str(&format!(
            "{}  runner-manager-{}-{target}.{extension}\n",
            "e".repeat(70),
            release.version
        ));
    }
    std::fs::write(release.sums(), &text).expect("rewriting SHA256SUMS");

    // A positive control on the fixture itself. Every assertion in the test
    // below is an ABSENCE of misbehaviour, and a decoy that never reached the
    // file makes all of them vacuous -- which is precisely how the `^` shipped
    // unconstrained in the first place.
    let written = std::fs::read_to_string(release.sums()).expect("the rewritten SHA256SUMS");
    for (target, extension, _) in TARGETS {
        for shape in [
            format!(
                "{}  vendored-runner-manager-{}-{target}.{extension}",
                "b".repeat(64),
                release.version
            ),
            format!(
                "{}  runner-manager-{}-{target}.{extension}.sig",
                "c".repeat(64),
                release.version
            ),
            format!(
                "junk {}  runner-manager-{}-{target}.{extension}",
                "d".repeat(64),
                release.version
            ),
            format!(
                "{}  runner-manager-{}-{target}.{extension}",
                "e".repeat(70),
                release.version
            ),
        ] {
            assert!(
                written.lines().any(|line| line == shape),
                "the decoy `{shape}` is not in the SHA256SUMS the scripts will \
                 read. Without it the anchor it constrains is untested and \
                 every assertion below passes for the wrong reason."
            );
        }
    }
}

#[test]
fn both_installers_match_the_whole_asset_name_when_neighbours_are_published() {
    // ------------------------------------------------------------------------
    // THE PROPERTY WAS ASSERTED ONCE AND IMPLEMENTED THREE TIMES.
    // ------------------------------------------------------------------------
    // `the_checksum_lookup_matches_the_whole_asset_name` in
    // `release_channels.rs` covers channels.sh with both decoy classes. The
    // SAME property is implemented separately in install.sh's awk and in
    // install.ps1's regex, and the fixture those two run against has never
    // carried a decoy -- so dropping the `^` or the `$` from either anchor
    // shipped green.
    //
    // Today's release publishes one file per target and both anchors are
    // unobservable. They stop being unobservable the first time anything is
    // published beside an archive -- a `.sig`, a `.intoto.jsonl`, a vendored
    // rebuild -- which is precisely the change nobody would connect to an
    // installer that suddenly refuses to guess, or worse, guesses.
    //
    // ------------------------------------------------------------------------
    // AND THE FIRST VERSION OF THIS TEST STILL DID NOT CONSTRAIN THE `^`.
    // ------------------------------------------------------------------------
    // Measured, per anchor, per shape. install.sh's awk is fully covered by the
    // two NAME decoys: both of its anchors sit on the name, and each decoy
    // flips its match count. install.ps1's regex is not, because its `^`
    // anchors the HASH -- so with only the name decoys present, deleting `^`
    // changed no match count anywhere and shipped green. `add_decoy_lines`
    // therefore also publishes two malformed digest fields; see its comment for
    // which anchor each shape pins.
    let fixture = prepare("1.2.3");
    add_decoy_lines(&fixture.release);

    let (ok, output) = run_install_sh(&LINUX_X64, &fixture.release.assets, &fixture.directory, &[]);
    assert!(
        ok,
        "install.sh could not resolve an archive in a release that also \
         publishes a `.sig`, a vendored rebuild, and two malformed digest \
         fields beside it. Anchored at both ends there is exactly one match; \
         unanchored there are more:\n{output}"
    );
    assert!(
        output.lines().any(|line| line.trim()
            == "Release 1.2.3, asset runner-manager-1.2.3-x86_64-unknown-linux-gnu.tar.gz"),
        "install.sh resolved the wrong asset out of a release with decoys \
         beside the archive:\n{output}"
    );
    assert_eq!(
        run_installed(&fixture.binary()),
        fixture.release.expected_output("x86_64-unknown-linux-gnu"),
        "install.sh installed something other than the archive SHA256SUMS names"
    );

    for shell in powershell_hosts_or_skip() {
        let host = shell.display();
        let fixture = prepare("1.2.3");
        add_decoy_lines(&fixture.release);

        let (ok, output) =
            run_install_ps1(&shell, &fixture.release.assets, &fixture.directory, &[]);
        assert!(
            ok,
            "install.ps1 could not resolve an archive in a release that also \
             publishes a `.sig`, a vendored rebuild, and two malformed digest \
             fields beside it ({host}):\n{output}"
        );
        assert!(
            output.lines().any(|line| line.trim()
                == "Release 1.2.3, asset runner-manager-1.2.3-x86_64-pc-windows-msvc.zip"),
            "install.ps1 resolved the wrong asset out of a release with decoys \
             beside the archive ({host}):\n{output}"
        );
        assert_eq!(
            std::fs::read(fixture.directory.join("runner-manager.exe"))
                .expect("the installed binary"),
            std::fs::read(
                fixture
                    .release
                    .staged("x86_64-pc-windows-msvc")
                    .join("runner-manager.exe")
            )
            .expect("the staged binary"),
            "install.ps1 installed something other than the archive SHA256SUMS \
             names ({host})"
        );
    }
}

// ----------------------------------------------------------------------------
// install.sh under a shell that is not bash.
// ----------------------------------------------------------------------------

/// A real POSIX `sh` -- dash -- if this machine has one.
///
/// ----------------------------------------------------------------------------
/// THE STATIC SCAN IS A BACKSTOP; THIS IS WHAT ACTUALLY NOTICES.
/// ----------------------------------------------------------------------------
/// Every other install.sh test here runs the script under BASH, which accepts
/// every bashism happily, so `install_sh_stays_runnable_by_a_posix_shell` -- a
/// list of forbidden substrings -- was the only thing standing between this
/// file and a script that fails on Debian, Ubuntu and Alpine. A list catches
/// only what somebody thought to write down.
///
/// Ubuntu's `/bin/sh` IS dash and Git for Windows ships `usr/bin/dash.exe`, so
/// two of the three CI legs run the real thing for the cost of resolving a
/// path. macOS ships no dash and is the one leg that skips.
///
/// ----------------------------------------------------------------------------
/// IT DOES NOT REPLACE THE SCAN, AND THE SCAN DOES NOT REPLACE IT.
/// ----------------------------------------------------------------------------
/// Measured against this machine's dash, which is 0.5.12-era: `${var:0:3}` is a
/// `Bad substitution` here and the scan catches it too, but `set -o pipefail` is
/// ACCEPTED -- upstream dash added it in 2022 -- while BusyBox ash still rejects
/// it. So each of the two finds things the other misses, and neither is the
/// redundant one.
fn dash_program() -> Option<PathBuf> {
    if let Some(explicit) = std::env::var_os("RUNNER_MANAGER_DASH") {
        let path = PathBuf::from(explicit);
        if path.is_file() {
            return Some(path);
        }
    }
    for name in ["dash", "dash.exe"] {
        if let Some(found) = find_program(name) {
            return Some(found);
        }
    }
    if !cfg!(windows) {
        let standard = PathBuf::from("/bin/dash");
        if standard.is_file() {
            return Some(standard);
        }
    }
    // Git for Windows, resolved through `git` the way `common::bash_program`
    // resolves bash -- anyone who cloned this repository has Git.
    if let Some(git) = find_program("git.exe")
        && let Some(root) = git.parent().and_then(Path::parent)
    {
        let candidate = root.join("usr").join("bin").join("dash.exe");
        if candidate.is_file() {
            return Some(candidate);
        }
    }
    let standard = PathBuf::from(r"C:\Program Files\Git\usr\bin\dash.exe");
    if standard.is_file() {
        return Some(standard);
    }
    None
}

fn dash_or_skip() -> Option<PathBuf> {
    if let Some(found) = dash_program() {
        return Some(found);
    }
    assert!(
        std::env::var_os("CI").is_none() || cfg!(target_os = "macos"),
        "no `dash` found in CI. Ubuntu's /bin/sh IS dash and Git for Windows \
         ships usr/bin/dash.exe, so on those two legs this is a broken \
         environment rather than a missing dependency -- and this is the only \
         test that runs install.sh under a shell that is not bash. macOS ships \
         no dash and is the leg allowed to skip."
    );
    eprintln!(
        "SKIPPED: no dash on this machine. install.sh's POSIX compliance is \
         then covered only by the static scan, which catches only what somebody \
         thought to list."
    );
    None
}

/// `run_bash`, but with the shell chosen by the caller.
///
/// Git Bash normally prepends its own `usr/bin` before starting a script. A
/// direct `dash.exe script` invocation does not: on a stock Git-for-Windows
/// install it inherits the runner's Windows PATH and cannot find the adjacent
/// `mktemp.exe` (or the other POSIX tools install.sh deliberately uses). Put the
/// selected shell's tool directory first so this measures install.sh under dash
/// rather than an environment no Git shell creates.
fn supply_shell_tool_path(command: &mut Command, shell: &Path) {
    let Some(directory) = shell.parent() else {
        return;
    };
    let inherited = std::env::var_os("PATH").unwrap_or_default();
    let paths = std::iter::once(directory.to_path_buf()).chain(std::env::split_paths(&inherited));
    let joined = std::env::join_paths(paths).unwrap_or_else(|err| {
        panic!(
            "cannot put {} on PATH for {}: {err}",
            directory.display(),
            shell.display()
        )
    });
    command.env("PATH", joined);
}

fn run_with_shell(
    shell: &Path,
    script: &Path,
    arguments: &[&str],
    envs: &[(&str, &str)],
) -> (bool, String) {
    let mut command = Command::new(shell);
    supply_shell_tool_path(&mut command, shell);
    command.arg(posix(script));
    command.args(arguments);
    command.current_dir(repository_root());
    for (key, value) in envs {
        command.env(key, value);
    }
    let output = command.output().unwrap_or_else(|err| {
        panic!(
            "cannot run {} under {}: {err}",
            posix(script),
            shell.display()
        )
    });
    (
        output.status.success(),
        format!(
            "{}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        ),
    )
}

#[test]
fn install_sh_installs_end_to_end_under_a_real_posix_shell() {
    let Some(dash) = dash_or_skip() else {
        return;
    };

    // Anti-vacuity for the process environment above. The installer would also
    // fail when one of these is absent, but only after fixture construction and
    // with a symptom such as `mktemp: not found`. This proves up front that the
    // direct dash process has the same baseline tools as the documented `sh`
    // invocation and names the harness fault if that ever changes.
    let mut probe = Command::new(&dash);
    supply_shell_tool_path(&mut probe, &dash);
    let probe = probe
        .arg("-c")
        .arg("for tool in awk sed grep cut tr mktemp tar; do command -v \"$tool\" || exit 1; done")
        .output()
        .unwrap_or_else(|err| panic!("cannot probe dash at {}: {err}", dash.display()));
    assert!(
        probe.status.success(),
        "dash at {} cannot see every POSIX tool install.sh requires. The test \
         would then measure a broken direct-shell PATH instead of the \
         installer:\n{}{}",
        dash.display(),
        String::from_utf8_lossy(&probe.stdout),
        String::from_utf8_lossy(&probe.stderr)
    );

    let fixture = prepare("1.2.3");
    let assets = posix(&fixture.release.assets);
    let directory = posix(&fixture.directory);
    let environment = [
        ("RUNNER_MANAGER_INSTALL_UNAME_S", "Linux"),
        ("RUNNER_MANAGER_INSTALL_UNAME_M", "x86_64"),
        ("RUNNER_MANAGER_INSTALL_BASE_URL", assets.as_str()),
        ("RUNNER_MANAGER_INSTALL_DIR", directory.as_str()),
    ];

    let script = install_script("install.sh");
    let (ok, output) = run_with_shell(&dash, &script, &[], &environment);
    assert!(
        ok,
        "install.sh failed under dash ({}). The documented command is \
         `curl ... | sh`, and on Debian and Ubuntu that shell IS this \
         one:\n{output}",
        dash.display()
    );
    assert!(
        output.contains("SHA-256 OK"),
        "install.sh installed under dash without reporting that it verified \
         the archive:\n{output}"
    );
    assert_eq!(
        run_installed(&fixture.binary()),
        fixture.release.expected_output("x86_64-unknown-linux-gnu"),
        "the file install.sh installed under dash is not the binary from the \
         archive"
    );

    // The abort path too. A bashism in an error branch is the one a smoke test
    // never reaches and a user reaches on their worst day.
    substitute_payload(&fixture.release, "x86_64-unknown-linux-gnu");
    let (ok, output) = run_with_shell(&dash, &script, &[], &environment);
    assert!(
        !ok,
        "install.sh under dash installed an archive whose digest does not \
         match the published one:\n{output}"
    );
    assert!(
        output.contains("CHECKSUM MISMATCH"),
        "the abort must say plainly what went wrong under dash too:\n{output}"
    );
    assert_eq!(
        installed_entries(&fixture.directory),
        vec!["runner-manager".to_string()],
        "the aborted install under dash left a staging file behind"
    );
}