zc2 0.0.53

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

use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

use ureq::config::{ConfigBuilder, RedirectAuthHeaders};
use ureq::http::{StatusCode, Uri};
use ureq::typestate::AgentScope;

const REPO_API_LATEST: &str = "https://api.github.com/repos/zakuro-ai/zc/releases/latest";
const REPO_CLONE_HOST: &str = "github.com/zakuro-ai/zc";
/// The `Accept` header that makes a release asset's API `url` answer with the
/// asset's bytes (through a redirect) instead of its JSON description.
const OCTET_STREAM: &str = "application/octet-stream";
/// The most `zc update` reads of a release binary. ureq's default body limit
/// (10 MiB) is smaller than a release binary: v0.0.26's are 14–17 MB.
const MAX_BINARY_BYTES: u64 = 256 * 1024 * 1024;
/// What `zc update` says when the releases API answers 404 and no token was
/// found: GitHub answers 404 for a private repo it won't show you.
const PRIVATE_RELEASES: &str = "zc releases are private. Sign in with `gh auth login` (or set GH_PAT / GITHUB_TOKEN) and run zc update again.";
/// The fallback suggested when the prebuilt release can't be installed.
const FROM_SOURCE_FALLBACK: &str = "Fallback: try building from source instead — `zc update --from-source` (it also needs a GitHub token with access to zakuro-ai/zc).";
/// Release asset name for the host platform. Must match the names uploaded by
/// .github/workflows/release.yml.
fn asset_name() -> &'static str {
    // Windows is x86_64 only (MinGW cross build in auto-release.yml).
    if cfg!(windows) {
        return "zc-windows-x86_64.exe";
    }
    match (cfg!(target_os = "macos"), cfg!(target_arch = "aarch64")) {
        (true, true) => "zc-darwin-arm64",
        (true, false) => "zc-darwin-x86_64",
        (false, true) => "zc-linux-arm64",
        (false, false) => "zc-linux-x86_64",
    }
}

/// Oldest glibc the `-gnu` release builds run on: they are linked against
/// glibc 2.31 by cargo-zigbuild (see auto-release.yml).
const MIN_GNU_GLIBC: (u32, u32) = (2, 31);

/// The Linux release asset to install. The default `zc-linux-*` builds are
/// static musl and cannot `dlopen` libcuda, so a GPU host would be benchmarked
/// as CPU-only (#357). A host with an NVIDIA driver and glibc >= 2.31 gets the
/// `-gnu` build instead; everything else, and any release that predates the
/// `-gnu` assets, keeps musl. Pure so it is unit-testable.
fn choose_linux_asset(
    arm64: bool,
    has_nvidia: bool,
    glibc: Option<(u32, u32)>,
    assets: &[String],
) -> String {
    let musl = if arm64 {
        "zc-linux-arm64"
    } else {
        "zc-linux-x86_64"
    };
    let gnu = format!("{musl}-gnu");
    let glibc_ok = glibc.is_some_and(|v| v >= MIN_GNU_GLIBC);
    if has_nvidia && glibc_ok && assets.contains(&gnu) {
        gnu
    } else {
        musl.to_string()
    }
}

/// Why a GPU host is getting the musl build, if it is. `None` when the host
/// has no GPU or gets the `-gnu` build.
fn gpu_musl_fallback_reason(
    arm64: bool,
    has_nvidia: bool,
    glibc: Option<(u32, u32)>,
    assets: &[String],
) -> Option<&'static str> {
    if !has_nvidia {
        return None;
    }
    if glibc.is_none_or(|v| v < MIN_GNU_GLIBC) {
        return Some("glibc < 2.31 or not detected");
    }
    let gnu = if arm64 {
        "zc-linux-arm64-gnu"
    } else {
        "zc-linux-x86_64-gnu"
    };
    if !assets.iter().any(|a| a == gnu) {
        return Some("no glibc asset in this release");
    }
    None
}

/// Parse the glibc version out of `ldd --version` output. `None` for anything
/// that is not glibc (musl's ldd, empty output).
fn parse_glibc_version(ldd_output: &str) -> Option<(u32, u32)> {
    let first = ldd_output.lines().next()?;
    let lower = first.to_lowercase();
    if !lower.contains("glibc") && !lower.contains("gnu libc") {
        return None;
    }
    let ver = first.split_whitespace().last()?;
    let mut it = ver.split('.');
    let major = it.next()?.parse().ok()?;
    let minor = it.next()?.parse().ok()?;
    Some((major, minor))
}

/// The host's glibc version, read from `ldd --version` (the running binary may
/// itself be musl, so it cannot ask libc directly). musl's ldd prints to
/// stderr, hence both streams.
#[cfg(target_os = "linux")]
fn host_glibc_version() -> Option<(u32, u32)> {
    let out = Command::new("ldd").arg("--version").output().ok()?;
    let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
    text.push_str(&String::from_utf8_lossy(&out.stderr));
    parse_glibc_version(&text)
}

/// Whether the host has an NVIDIA driver: its device node, or a resolvable
/// `libcuda.so.1`.
#[cfg(target_os = "linux")]
fn host_has_nvidia() -> bool {
    if Path::new("/dev/nvidiactl").exists() {
        return true;
    }
    if let Ok(out) = Command::new("ldconfig").arg("-p").output() {
        if String::from_utf8_lossy(&out.stdout).contains("libcuda.so.1") {
            return true;
        }
    }
    [
        "/usr/lib/x86_64-linux-gnu",
        "/usr/lib/aarch64-linux-gnu",
        "/usr/lib64",
        "/usr/lib",
        "/usr/local/nvidia/lib64",
        "/usr/lib/wsl/lib",
    ]
    .iter()
    .any(|d| Path::new(d).join("libcuda.so.1").exists())
}

/// Names of the assets on `release`.
fn asset_names(release: &serde_json::Value) -> Vec<String> {
    release
        .get("assets")
        .and_then(|a| a.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|x| x.get("name").and_then(|n| n.as_str()).map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

/// Release asset name for this host given the release being installed.
fn asset_name_for(release: &serde_json::Value) -> String {
    #[cfg(target_os = "linux")]
    {
        let arm64 = cfg!(target_arch = "aarch64");
        let (nvidia, glibc, assets) = (
            host_has_nvidia(),
            host_glibc_version(),
            asset_names(release),
        );
        if let Some(reason) = gpu_musl_fallback_reason(arm64, nvidia, glibc, &assets) {
            println!(
                "GPU host but using the musl build ({reason}): GPU benchmarking/CUDA unavailable"
            );
        }
        choose_linux_asset(arm64, nvidia, glibc, &assets)
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = release;
        asset_name().to_string()
    }
}

/// Which update strategy to use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    /// Download the latest prebuilt release binary.
    PrebuiltRelease,
    /// Clone the source repo and `cargo build --release`.
    FromSource,
}

/// Parse `zc update [--from-source]` args into a [`Mode`]. Pure/testable —
/// takes plain string slices, no process spawning.
pub fn parse_mode(args: &[String]) -> Mode {
    if args.iter().any(|a| a == "--from-source") {
        Mode::FromSource
    } else {
        Mode::PrebuiltRelease
    }
}

/// Resolve a GitHub auth token, in precedence order:
///   1. `try_gh()` — e.g. `gh auth token` via the GitHub CLI
///   2. `get_env("GH_PAT")`
///   3. `get_env("GITHUB_TOKEN")`
///
/// Both dependencies are injected so this is unit-testable without spawning
/// a real `gh` process or touching real process env vars.
pub fn resolve_token<F1, F2>(try_gh: F1, get_env: F2) -> Option<String>
where
    F1: FnOnce() -> Option<String>,
    F2: Fn(&str) -> Option<String>,
{
    if let Some(t) = try_gh() {
        if !t.trim().is_empty() {
            return Some(t.trim().to_string());
        }
    }
    if let Some(t) = get_env("GH_PAT") {
        if !t.trim().is_empty() {
            return Some(t.trim().to_string());
        }
    }
    if let Some(t) = get_env("GITHUB_TOKEN") {
        if !t.trim().is_empty() {
            return Some(t.trim().to_string());
        }
    }
    None
}

/// Real `gh auth token` lookup — returns `None` if `gh` isn't installed,
/// isn't authenticated, or the call otherwise fails.
fn gh_auth_token() -> Option<String> {
    let out = Command::new("gh").args(["auth", "token"]).output().ok()?;
    if !out.status.success() {
        return None;
    }
    let token = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if token.is_empty() {
        None
    } else {
        Some(token)
    }
}

fn real_env(key: &str) -> Option<String> {
    std::env::var(key).ok()
}

/// Entry point mirroring the other subcommand modules' `run_cli` convention
/// (see `vpn::run_cli`). Returns the process exit code: 0 once the new binary
/// is installed, 1 on any failure.
pub fn run_cli(args: &[String]) -> i32 {
    // `--check` / `--from-crates`: compare with, and build from, crates.io.
    if let Some(m) = crate::update_crates::mode(args) {
        return crate::update_crates::run(m, args);
    }
    match parse_mode(args) {
        Mode::PrebuiltRelease => {
            let p = crate::profile::active();
            match sig_policy_for(args, p.env, p.update_trust_root) {
                Ok(policy) => update_from_release(policy),
                Err(e) => {
                    eprintln!("{e}");
                    2
                }
            }
        }
        Mode::FromSource => update_from_source(),
    }
}

/// What to install after trying the preferred (`-gnu`) build and, if it did
/// not run, the musl fallback.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum InstallChoice {
    Gnu,
    Musl,
    KeepOld,
}

/// Pure decision: `gnu_ok` is `None` when no gnu build was attempted;
/// `musl_ok` is `None` when musl was not tried (it is only fetched after a
/// failed gnu build, or as the primary asset).
fn decide_install(gnu_ok: Option<bool>, musl_ok: Option<bool>) -> InstallChoice {
    if gnu_ok == Some(true) {
        InstallChoice::Gnu
    } else if musl_ok == Some(true) {
        InstallChoice::Musl
    } else {
        InstallChoice::KeepOld
    }
}

/// Run `<bytes> --version` from a scratch file next to `exe_path` with a 10 s
/// timeout; true only on exit 0. Guards against replacing a working binary
/// with one the host cannot exec (e.g. a glibc build on NixOS / gcompat).
pub(crate) fn binary_runs(exe_path: &Path, bytes: &[u8]) -> bool {
    let dir = exe_path.parent().unwrap_or_else(|| Path::new("."));
    let probe: PathBuf = dir.join(format!(".zc-update-verify-{}.tmp", std::process::id()));
    if std::fs::write(&probe, bytes).is_err() {
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if std::fs::set_permissions(&probe, std::fs::Permissions::from_mode(0o755)).is_err() {
            let _ = std::fs::remove_file(&probe);
            return false;
        }
    }
    let ok = match Command::new(&probe)
        .arg("--version")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
    {
        Ok(mut child) => {
            let deadline = std::time::Instant::now() + Duration::from_secs(10);
            loop {
                match child.try_wait() {
                    Ok(Some(status)) => break status.success(),
                    Ok(None) if std::time::Instant::now() < deadline => {
                        std::thread::sleep(Duration::from_millis(50));
                    }
                    _ => {
                        let _ = child.kill();
                        let _ = child.wait();
                        break false;
                    }
                }
            }
        }
        Err(_) => false,
    };
    let _ = std::fs::remove_file(&probe);
    ok
}

/// The version a binary reports: writes `bytes` next to `exe_path`, runs
/// `--version` (10 s timeout) and returns the token after "zc version".
/// `None` if it cannot be run or prints something else.
pub(crate) fn binary_version(exe_path: &Path, bytes: &[u8]) -> Option<String> {
    let dir = exe_path.parent().unwrap_or_else(|| Path::new("."));
    let probe: PathBuf = dir.join(format!(".zc-update-version-{}.tmp", std::process::id()));
    std::fs::write(&probe, bytes).ok()?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if std::fs::set_permissions(&probe, std::fs::Permissions::from_mode(0o755)).is_err() {
            let _ = std::fs::remove_file(&probe);
            return None;
        }
    }
    let child = Command::new(&probe)
        .arg("--version")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn();
    let out = match child {
        Ok(mut c) => {
            let deadline = std::time::Instant::now() + Duration::from_secs(10);
            loop {
                match c.try_wait() {
                    Ok(Some(_)) => break c.wait_with_output().ok(),
                    Ok(None) if std::time::Instant::now() < deadline => {
                        std::thread::sleep(Duration::from_millis(50));
                    }
                    _ => {
                        let _ = c.kill();
                        let _ = c.wait();
                        break None;
                    }
                }
            }
        }
        Err(_) => None,
    };
    let _ = std::fs::remove_file(&probe);
    parse_version_output(&String::from_utf8_lossy(&out?.stdout))
}

/// The version out of `zc version X (hash) built on ...`.
pub(crate) fn parse_version_output(text: &str) -> Option<String> {
    let mut it = text.lines().next()?.split_whitespace();
    (it.next()? == "zc" && it.next()? == "version").then_some(())?;
    it.next().map(str::to_string)
}

/// Atomically replace the file at `exe_path` with `bytes`: write to a temp
/// file alongside it, chmod 0755, then `rename()` over the target. `rename`
/// within the same filesystem works on Linux even while `exe_path` is the
/// currently-running binary. Windows refuses to overwrite a running .exe but
/// lets it be renamed, so the old binary is first moved aside to `zc.old.exe`
/// (removed on the next update).
pub(crate) fn replace_binary_atomic(exe_path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    let dir = exe_path.parent().unwrap_or_else(|| Path::new("."));
    let tmp_path: PathBuf = dir.join(format!(".zc-update-{}.tmp", std::process::id()));
    std::fs::write(&tmp_path, bytes)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o755))?;
    }
    #[cfg(windows)]
    if exe_path.exists() {
        let old = exe_path.with_extension("old.exe");
        let _ = std::fs::remove_file(&old);
        if let Err(e) = std::fs::rename(exe_path, &old) {
            let _ = std::fs::remove_file(&tmp_path);
            return Err(e);
        }
    }
    std::fs::rename(&tmp_path, exe_path)?;
    Ok(())
}

fn current_exe_or_bail() -> Option<PathBuf> {
    match std::env::current_exe() {
        Ok(p) => Some(p),
        Err(e) => {
            eprintln!(
                "Error: could not determine the current executable path: {}",
                e
            );
            None
        }
    }
}

/// Can we create (and remove) a file in `dir`? Used to decide whether we can
/// update the running binary in place, or must fall back to ~/.local/bin.
pub(crate) fn dir_writable(dir: &Path) -> bool {
    let probe = dir.join(format!(".zc-write-probe-{}", std::process::id()));
    match std::fs::File::create(&probe) {
        Ok(_) => {
            let _ = std::fs::remove_file(&probe);
            true
        }
        Err(_) => false,
    }
}

fn local_bin_zc() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
    PathBuf::from(home).join(".local").join("bin").join("zc")
}

/// Choose a user-writable install target. Prefer replacing the running binary in
/// place; if its directory isn't writable (e.g. root-owned /usr/local/bin), fall
/// back to ~/.local/bin/zc so the update never needs sudo. Returns
/// `(path, installed_to_local_bin)`.
fn resolve_install_target() -> (PathBuf, bool) {
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            if dir_writable(dir) {
                return (exe, false);
            }
        }
    }
    (local_bin_zc(), true)
}

/// Append `line` to `path` unless it's already present. Returns Ok(true) if it
/// was added, Ok(false) if it was already there.
fn append_line_once(path: &Path, line: &str) -> std::io::Result<bool> {
    let existing = std::fs::read_to_string(path).unwrap_or_default();
    if existing.lines().any(|l| l.trim() == line.trim()) {
        return Ok(false);
    }
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    let sep = if existing.is_empty() || existing.ends_with('\n') {
        ""
    } else {
        "\n"
    };
    writeln!(
        f,
        "{}# added by `zc update` — put ~/.local/bin on PATH\n{}",
        sep, line
    )?;
    Ok(true)
}

/// The shell rc file to persist a PATH change into, inferred from $SHELL.
fn shell_rc_path() -> Option<PathBuf> {
    let home = std::env::var("HOME").ok()?;
    let shell = std::env::var("SHELL").unwrap_or_default();
    let file = if shell.contains("zsh") {
        ".zshrc"
    } else if shell.contains("bash") {
        ".bashrc"
    } else {
        ".profile"
    };
    Some(PathBuf::from(home).join(file))
}

/// After a ~/.local/bin install, make sure that dir is on PATH: append the
/// export to the shell rc if missing, and tell the user how to pick it up.
fn ensure_local_bin_on_path(installed: &Path) {
    let bin_dir = installed
        .parent()
        .map(|p| p.display().to_string())
        .unwrap_or_default();
    let on_path = std::env::var("PATH")
        .map(|p| p.split(':').any(|d| d == bin_dir))
        .unwrap_or(false);

    if on_path {
        println!("Installed to {}.", installed.display());
        println!("Run `hash -r` (or open a new terminal) so your shell uses the new binary.");
        return;
    }

    let export = "export PATH=\"$HOME/.local/bin:$PATH\"".to_string();
    let appended = shell_rc_path().and_then(|rc| {
        let ok = append_line_once(&rc, &export).unwrap_or(false);
        ok.then_some(rc)
    });

    println!("Installed to {}.", installed.display());
    match appended {
        Some(rc) => {
            println!("Added ~/.local/bin to your PATH in {}.", rc.display());
            println!(
                "Open a new terminal (or `source {}`) and run `zc`.",
                rc.display()
            );
        }
        None => {
            println!("Add ~/.local/bin to your PATH so `zc` is found:");
            println!("    {}", export);
        }
    }
    // An older zc elsewhere on PATH (e.g. /usr/local/bin) is now shadowed by the
    // prepended dir; remove it if you like: `sudo rm /usr/local/bin/zc`.
}

/// Where to download a release asset from, and the `Accept` header to send.
#[derive(Debug, PartialEq, Eq)]
struct AssetSource {
    url: String,
    accept: &'static str,
}

/// The source of the asset called `name` in `release` (a releases API
/// response), or `None` when the release has no such asset.
///
/// The asset's API `url`, fetched with `Accept: application/octet-stream`,
/// redirects to the bytes, and works for a private repo when the token can
/// see it. `browser_download_url` answers 404 for a private repo, token or
/// not, so it is only the fallback for a response without `url`.
fn select_asset(release: &serde_json::Value, name: &str) -> Option<AssetSource> {
    let asset = release
        .get("assets")?
        .as_array()?
        .iter()
        .find(|a| a.get("name").and_then(|n| n.as_str()) == Some(name))?;
    let field = |key: &str| asset.get(key).and_then(|v| v.as_str()).map(str::to_string);
    match field("url") {
        Some(url) => Some(AssetSource {
            url,
            accept: OCTET_STREAM,
        }),
        None => field("browser_download_url").map(|url| AssetSource { url, accept: "*/*" }),
    }
}

/// `token` if a request to `url` may carry it: only an https request whose
/// host is exactly `api.github.com`. The download URL comes from the release
/// JSON, and its `browser_download_url` fallback is on github.com.
fn token_for<'a>(url: &str, token: Option<&'a str>) -> Option<&'a str> {
    let uri: Uri = url.parse().ok()?;
    let github_api = uri.scheme_str() == Some("https")
        && uri
            .host()
            .is_some_and(|h| h.eq_ignore_ascii_case("api.github.com"));
    token.filter(|_| github_api)
}

/// Headers for a request to GitHub: `User-Agent`, `Accept`, and
/// `Authorization` when given a token. Callers pass the token through
/// [`token_for`] first, and the download drops it on the redirect to the
/// storage host (see [`download_config`]).
fn github_headers(accept: &str, token: Option<&str>) -> Vec<(&'static str, String)> {
    let mut headers = vec![
        ("User-Agent", "zc-update".to_string()),
        ("Accept", accept.to_string()),
    ];
    if let Some(t) = token {
        headers.push(("Authorization", format!("Bearer {t}")));
    }
    headers
}

/// The releases API call: a small JSON document, so 30 s. Error statuses come
/// back as responses rather than errors, so a 404 can be explained.
fn api_config() -> ConfigBuilder<AgentScope> {
    ureq::Agent::config_builder()
        .timeout_connect(Some(Duration::from_secs(10)))
        .timeout_global(Some(Duration::from_secs(30)))
        .http_status_as_error(false)
}

/// The asset download: 300 s, since under the API call's 30 s a 14–17 MB
/// release binary would need about 0.5 MB/s. GitHub answers the asset's API
/// `url` with a 302 to a signed storage URL, and the storage host rejects a
/// request that carries both that signature and an `Authorization` header,
/// so redirects are followed without it: `RedirectAuthHeaders::Never`
/// removes `Authorization` from every redirected request. It is also ureq's
/// default; setting it here means nothing depends on that.
fn download_config() -> ConfigBuilder<AgentScope> {
    ureq::Agent::config_builder()
        .timeout_connect(Some(Duration::from_secs(10)))
        .timeout_global(Some(Duration::from_secs(300)))
        .http_status_as_error(false)
        .redirect_auth_headers(RedirectAuthHeaders::Never)
}

/// What to print when the releases API answers `status` instead of 200.
fn api_status_message(status: StatusCode, have_token: bool) -> String {
    if status != StatusCode::NOT_FOUND {
        format!("GitHub releases API returned HTTP {status}\n{FROM_SOURCE_FALLBACK}")
    } else if !have_token {
        PRIVATE_RELEASES.to_string()
    } else {
        format!(
            "GitHub releases API returned HTTP {status}: the GitHub token zc found may not have access to zakuro-ai/zc (the repo is private), or there is no release yet.\n\
             Check its account with `gh auth status`; zc uses gh's token first, then GH_PAT, then GITHUB_TOKEN.\n\
             {FROM_SOURCE_FALLBACK}"
        )
    }
}

/// GET `src` and return the final response's body, following redirects as
/// `agent` is configured to. `token` goes in the first request's
/// `Authorization` header, so callers pass it through [`token_for`] first.
fn download(
    agent: &ureq::Agent,
    src: &AssetSource,
    token: Option<&str>,
) -> Result<Vec<u8>, String> {
    let mut req = agent.get(&src.url);
    for (name, value) in github_headers(src.accept, token) {
        req = req.header(name, value);
    }
    let resp = req
        .call()
        .map_err(|e| format!("Failed to download release asset: {e}"))?;
    if resp.status() != StatusCode::OK {
        return Err(format!("Download failed: HTTP {}", resp.status()));
    }
    resp.into_body()
        .with_config()
        .limit(MAX_BINARY_BYTES)
        .read_to_vec()
        .map_err(|e| format!("Failed to read downloaded binary: {e}"))
}

// ---------------------------------------------------------------------------
// Mirror path (default): https://get.zakuro-ai.com/zc
// ---------------------------------------------------------------------------

/// The canonical, public, token-free source of `zc` binaries: a verified mirror
/// of the zakuro-ai/zc GitHub releases (ZC-0015).
pub(crate) const MIRROR_BASE: &str = "https://get.zakuro-ai.com/zc";

/// Env var overriding the mirror base (e.g. the staging mirror).
pub(crate) const ENV_UPDATE_URL: &str = "ZAKURO_UPDATE_URL";

/// Normalise a mirror base: trim whitespace and trailing `/`, append `/zc`
/// when missing, and require `https://` (plain `http://` only for
/// 127.0.0.1/localhost, for tests). Pure.
pub(crate) fn normalize_mirror_base(raw: &str) -> Result<String, String> {
    let mut b = raw.trim().trim_end_matches('/').to_string();
    let rest = if let Some(r) = b.strip_prefix("https://") {
        r
    } else if let Some(r) = b.strip_prefix("http://") {
        let host = r.split(['/', ':']).next().unwrap_or("");
        if host != "127.0.0.1" && host != "localhost" {
            return Err(format!("{ENV_UPDATE_URL} must be https:// (got {raw:?})"));
        }
        r
    } else {
        return Err(format!(
            "{ENV_UPDATE_URL} must be an https:// URL (got {raw:?})"
        ));
    };
    if rest.is_empty() || rest.starts_with('/') {
        return Err(format!("{ENV_UPDATE_URL} has no host (got {raw:?})"));
    }
    if !(b.ends_with("/zc")) {
        b.push_str("/zc");
    }
    Ok(b)
}

/// The mirror base in effect: `ZAKURO_UPDATE_URL` (normalised) or the
/// `ZAKURO_ENV` profile's (`MIRROR_BASE` for prod and staging). The profile's
/// own base is trusted as compiled in, so the lab's plain-http one is allowed.
pub(crate) fn mirror_base() -> Result<String, String> {
    match crate::profile::resolve().mirror_base {
        (v, crate::profile::Source::Override(_)) => normalize_mirror_base(&v),
        (v, crate::profile::Source::Profile) => Ok(v),
    }
}

/// How `zc update` treats the mirror manifest's signature (GET-0013, zc#505).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SigPolicy<'a> {
    /// Fetch `<manifest>.sig` and refuse unless it verifies against this
    /// minisign public key (base64 key line) and names the platform asked for.
    Require(&'a str),
    /// `--insecure-skip-signature`: accepted under the lab profile only.
    Skip,
}

/// The flag that skips the manifest signature check (lab only).
pub(crate) const INSECURE_SKIP_SIGNATURE: &str = "--insecure-skip-signature";

/// The signature policy for `args` under the active profile, or the error to
/// print. The skip flag is refused outside the lab: the escape hatch exists
/// for lab images built without the release key, never for real nodes.
pub(crate) fn sig_policy_for(
    args: &[String],
    env: crate::profile::Env,
    trust_root: &'static str,
) -> Result<SigPolicy<'static>, String> {
    if args.iter().any(|a| a == INSECURE_SKIP_SIGNATURE) {
        if env == crate::profile::Env::Lab {
            return Ok(SigPolicy::Skip);
        }
        return Err(format!(
            "{INSECURE_SKIP_SIGNATURE} is only allowed under ZAKURO_ENV=lab (profile: {}).",
            env.name()
        ));
    }
    if trust_root.trim().is_empty() {
        return Err(format!(
            "this zc build has no update signing key for the {} profile; refusing to update. Re-run the installer: curl -fsSL https://get.zakuro-ai.com/zc | bash",
            env.name()
        ));
    }
    Ok(SigPolicy::Require(trust_root))
}

/// `Ok` when `sig` is a minisign signature of exactly `body` by `trust_root`
/// and the signed body names `platform`. Every failure is an integrity
/// refusal, never a reason to try another source.
pub(crate) fn verify_manifest_signature(
    trust_root: &str,
    platform: &str,
    body: &[u8],
    sig: &[u8],
) -> Result<(), String> {
    let pk = minisign_verify::PublicKey::from_base64(trust_root.trim())
        .map_err(|e| format!("the compiled-in update key is invalid: {e}"))?;
    let sig = std::str::from_utf8(sig)
        .ok()
        .and_then(|t| minisign_verify::Signature::decode(t).ok())
        .ok_or_else(|| format!("{platform} manifest signature is malformed; refusing to update"))?;
    pk.verify(body, &sig, false).map_err(|_| {
        format!("{platform} manifest signature does not verify against the zc release key; refusing to update")
    })?;
    let signed_for = serde_json::from_slice::<serde_json::Value>(body)
        .ok()
        .and_then(|v| v.get("platform")?.as_str().map(str::to_string));
    if signed_for.as_deref() != Some(platform) {
        return Err(format!(
            "the signed manifest is for {:?}, not {platform}; refusing to update",
            signed_for.unwrap_or_default()
        ));
    }
    Ok(())
}

/// Why a mirror update did not complete.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum MirrorError {
    /// Could not talk to the mirror (DNS, connect, timeout, 5xx).
    Unreachable(String),
    /// The mirror has no build for this platform.
    Unsupported(String),
    /// The download does not match the manifest: never installed, never
    /// retried through another source.
    Integrity(String),
    /// Anything else (bad manifest, install failure, ...).
    Other(String),
}

/// A failed GET: no response at all, or a non-200 status.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum FetchError {
    Transport(String),
    Status(u16),
}

/// HTTP GET, injected so the update flow is testable without a network. It
/// never carries credentials: the mirror is public.
pub(crate) trait Fetcher {
    fn get(&self, url: &str) -> Result<Vec<u8>, FetchError>;
}

pub(crate) struct UreqFetcher(ureq::Agent, String);

impl UreqFetcher {
    pub(crate) fn new() -> Self {
        Self::with_user_agent("zc-update")
    }

    pub(crate) fn with_user_agent(ua: &str) -> Self {
        Self(
            ureq::Agent::new_with_config(download_config().build()),
            ua.to_string(),
        )
    }
}

impl Fetcher for UreqFetcher {
    fn get(&self, url: &str) -> Result<Vec<u8>, FetchError> {
        let resp = self
            .0
            .get(url)
            .header("User-Agent", self.1.as_str())
            .call()
            .map_err(|e| FetchError::Transport(e.to_string()))?;
        if resp.status() != StatusCode::OK {
            return Err(FetchError::Status(resp.status().as_u16()));
        }
        resp.into_body()
            .with_config()
            .limit(MAX_BINARY_BYTES)
            .read_to_vec()
            .map_err(|e| FetchError::Transport(e.to_string()))
    }
}

/// `GET /zc/manifest/{platform}` body.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Manifest {
    pub(crate) version: String,
    sha256: String,
}

pub(crate) fn parse_manifest(body: &[u8]) -> Result<Manifest, String> {
    let v: serde_json::Value =
        serde_json::from_slice(body).map_err(|e| format!("invalid manifest JSON: {e}"))?;
    let field = |k: &str| {
        v.get(k)
            .and_then(|x| x.as_str())
            .map(str::trim)
            .filter(|x| !x.is_empty())
            .map(str::to_string)
            .ok_or_else(|| format!("manifest has no \"{k}\""))
    };
    let version = field("version")?;
    let sha256 = field("sha256")?.to_ascii_lowercase();
    // `version` goes into a query string; keep it to release-version characters.
    if parse_version(&version).is_none()
        || !version
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+' | '_'))
    {
        return Err(format!(
            "manifest version {version:?} is not a release version"
        ));
    }
    if sha256.len() != 64 || !sha256.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err("manifest sha256 is not 64 hex characters".to_string());
    }
    Ok(Manifest { version, sha256 })
}

/// `MAJOR.MINOR.PATCH` of a release version, tolerating a leading `v` and a
/// `-pre`/`+build` suffix (ignored). `None` when it is not three numbers.
fn parse_version(v: &str) -> Option<(u64, u64, u64)> {
    let core = v.trim().trim_start_matches('v');
    let core = core.split(['-', '+']).next()?;
    let mut it = core.split('.');
    let t = (
        it.next()?.parse().ok()?,
        it.next()?.parse().ok()?,
        it.next()?.parse().ok()?,
    );
    it.next().is_none().then_some(t)
}

/// Whether `candidate` is strictly newer than `current`.
fn is_newer(candidate: &str, current: &str) -> Result<bool, String> {
    match (parse_version(candidate), parse_version(current)) {
        (Some(c), Some(cur)) => Ok(c > cur),
        _ => Err(format!(
            "cannot compare versions {candidate:?} and {current:?}"
        )),
    }
}

/// Mirror platform names for this host, in order of preference. A host with
/// an NVIDIA driver and glibc >= 2.31 first asks for the glibc build
/// (`<platform>_gnu`, #357/#364) — the mirror serves only the musl builds
/// today, so a 404 there falls through to plain `<platform>`. `None` when the
/// mirror has no platform for this OS/arch (e.g. macOS x86_64).
fn mirror_platforms(
    macos: bool,
    arm64: bool,
    has_nvidia: bool,
    glibc: Option<(u32, u32)>,
) -> Option<Vec<String>> {
    match (macos, arm64) {
        (true, true) => Some(vec!["darwin_arm64".to_string()]),
        (true, false) => None,
        (false, _) => {
            let base = if arm64 { "linux_arm64" } else { "linux_amd64" };
            let mut v = Vec::new();
            if has_nvidia && glibc.is_some_and(|g| g >= MIN_GNU_GLIBC) {
                v.push(format!("{base}_gnu"));
            }
            v.push(base.to_string());
            Some(v)
        }
    }
}

/// The platform candidates for the running host.
pub(crate) fn host_mirror_platforms() -> Option<Vec<String>> {
    #[cfg(target_os = "linux")]
    let (nvidia, glibc) = (host_has_nvidia(), host_glibc_version());
    #[cfg(not(target_os = "linux"))]
    let (nvidia, glibc) = (false, None);
    mirror_platforms(
        cfg!(target_os = "macos"),
        cfg!(target_arch = "aarch64"),
        nvidia,
        glibc,
    )
}

/// What a finished mirror update did.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum MirrorOutcome {
    UpToDate(String),
    Installed { version: String, platform: String },
}

/// `Err` unless the sha256 of `bytes` equals `expected` (hex, any case).
fn verify_sha256(what: &str, bytes: &[u8], expected: &str) -> Result<(), String> {
    let actual = crate::dataset::sha256_hex(bytes);
    if actual.eq_ignore_ascii_case(expected.trim()) {
        Ok(())
    } else {
        Err(format!(
            "{what}: sha256 mismatch (expected {expected}, got {actual}); refusing to install"
        ))
    }
}

/// The whole mirror update. For each candidate platform: read its manifest,
/// compare versions, download the exact manifest version, verify the sha256,
/// check that the binary runs (`runs`), and only then replace `exe_path`.
/// Nothing is written to `exe_path` before the sha256 matches.
#[cfg(test)]
pub(crate) fn update_via_mirror(
    fetch: &dyn Fetcher,
    base: &str,
    platforms: &[String],
    current: &str,
    exe_path: &Path,
    runs: &dyn Fn(&Path, &[u8]) -> bool,
) -> Result<MirrorOutcome, MirrorError> {
    update_via_mirror_checked(
        fetch,
        base,
        platforms,
        current,
        exe_path,
        runs,
        SigPolicy::Skip,
    )
}

/// [`update_via_mirror`] with the manifest signature check: under
/// [`SigPolicy::Require`] an unsigned or badly signed manifest is an
/// [`MirrorError::Integrity`] refusal, checked before anything is compared or
/// downloaded.
pub(crate) fn update_via_mirror_checked(
    fetch: &dyn Fetcher,
    base: &str,
    platforms: &[String],
    current: &str,
    exe_path: &Path,
    runs: &dyn Fn(&Path, &[u8]) -> bool,
    sig: SigPolicy<'_>,
) -> Result<MirrorOutcome, MirrorError> {
    let mut last = MirrorError::Unsupported(format!("no mirror build for {platforms:?}"));
    for (i, platform) in platforms.iter().enumerate() {
        let is_last = i + 1 == platforms.len();
        let murl = format!("{base}/manifest/{platform}");
        let body = match fetch.get(&murl) {
            Ok(b) => b,
            // The optional glibc platform may not exist on the mirror yet.
            Err(FetchError::Status(400 | 404)) => {
                last = MirrorError::Unsupported(format!(
                    "the mirror has no {platform} build (HTTP 404)"
                ));
                continue;
            }
            Err(FetchError::Status(s)) => {
                return Err(MirrorError::Unreachable(format!("{murl}: HTTP {s}")))
            }
            Err(FetchError::Transport(e)) => {
                return Err(MirrorError::Unreachable(format!("{murl}: {e}")))
            }
        };
        if let SigPolicy::Require(key) = sig {
            let surl = format!("{murl}.sig");
            let sig_body = match fetch.get(&surl) {
                Ok(b) => b,
                Err(FetchError::Status(404)) => {
                    return Err(MirrorError::Integrity(format!(
                    "the {platform} manifest is not signed ({surl}: HTTP 404); refusing to update"
                )))
                }
                Err(FetchError::Status(s)) => {
                    return Err(MirrorError::Unreachable(format!("{surl}: HTTP {s}")))
                }
                Err(FetchError::Transport(e)) => {
                    return Err(MirrorError::Unreachable(format!("{surl}: {e}")))
                }
            };
            verify_manifest_signature(key, platform, &body, &sig_body)
                .map_err(MirrorError::Integrity)?;
        }
        let m = parse_manifest(&body)
            .map_err(|e| MirrorError::Other(format!("{platform} manifest: {e}")))?;
        if !is_newer(&m.version, current).map_err(MirrorError::Other)? {
            return Ok(MirrorOutcome::UpToDate(current.to_string()));
        }
        println!("Downloading zc {} ({platform})...", m.version);
        let durl = format!("{base}/download/{platform}?version={}", m.version);
        let bytes = fetch.get(&durl).map_err(|e| match e {
            FetchError::Transport(e) => MirrorError::Unreachable(format!("{durl}: {e}")),
            FetchError::Status(s) => MirrorError::Unreachable(format!("{durl}: HTTP {s}")),
        })?;
        verify_sha256(&format!("{platform} {}", m.version), &bytes, &m.sha256)
            .map_err(MirrorError::Integrity)?;
        if !runs(exe_path, &bytes) {
            let msg = format!("the {platform} build does not run on this host");
            if !is_last {
                eprintln!("{msg}; trying the next build.");
            }
            last = MirrorError::Other(msg);
            continue;
        }
        println!("Installing to {}...", exe_path.display());
        replace_binary_atomic(exe_path, &bytes)
            .map_err(|e| MirrorError::Other(format!("Failed to install the new binary: {e}")))?;
        return Ok(MirrorOutcome::Installed {
            version: m.version,
            platform: platform.clone(),
        });
    }
    Err(last)
}

/// What `zc update` does after the mirror path failed with `err`.
#[derive(Debug, PartialEq, Eq)]
enum Fallback {
    GitHub,
    Fail(String),
}

/// Fallback policy. GitHub releases are tried only when a token is present
/// AND the mirror could not serve this host (unreachable, or no build for the
/// platform). Never after an integrity failure: that is a refusal, not an
/// outage. Chosen over an explicit flag so an outage does not block a user who
/// already has access, while a user without a token never sees the private
/// repo's 404.
fn fallback_decision(err: &MirrorError, has_token: bool) -> Fallback {
    match err {
        MirrorError::Integrity(m) | MirrorError::Other(m) => Fallback::Fail(m.clone()),
        MirrorError::Unreachable(m) | MirrorError::Unsupported(m) => {
            if has_token {
                Fallback::GitHub
            } else {
                Fallback::Fail(format!(
                    "{m}\nCould not update from get.zakuro-ai.com and no GitHub token was found for the fallback. Try again later, or re-run the installer: curl -fsSL https://get.zakuro-ai.com/zc | bash"
                ))
            }
        }
    }
}

/// The release's own sha256 for `name` (`"sha256:<hex>"` in the releases API's
/// asset `digest` field).
fn asset_digest(release: &serde_json::Value, name: &str) -> Option<String> {
    release
        .get("assets")?
        .as_array()?
        .iter()
        .find(|a| a.get("name").and_then(|n| n.as_str()) == Some(name))?
        .get("digest")?
        .as_str()?
        .strip_prefix("sha256:")
        .map(str::to_string)
}

/// Verify `bytes` against the digest `release` publishes for `name`; refuses
/// when the release publishes none.
fn verify_asset_digest(
    release: &serde_json::Value,
    name: &str,
    bytes: &[u8],
) -> Result<(), String> {
    match asset_digest(release, name) {
        Some(d) => verify_sha256(name, bytes, &d),
        None => Err(format!(
            "{name}: the release publishes no sha256 digest for it; refusing to install an unverified binary"
        )),
    }
}

fn update_from_release(sig: SigPolicy<'static>) -> i32 {
    let base = match mirror_base() {
        Ok(b) => b,
        Err(e) => {
            eprintln!("{e}");
            return 1;
        }
    };
    let host = base
        .trim_start_matches("https://")
        .trim_start_matches("http://")
        .trim_end_matches("/zc");
    println!("Checking latest zc release ({host})...");
    if base != MIRROR_BASE {
        let from = match crate::profile::resolve().mirror_base.1 {
            crate::profile::Source::Override(v) => v.to_string(),
            crate::profile::Source::Profile => {
                format!("{} profile", crate::profile::active().env.name())
            }
        };
        println!("Using mirror {base} ({from})");
    }
    let platforms = host_mirror_platforms();
    let (exe_path, to_local_bin) = resolve_install_target();
    if let Some(parent) = exe_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let result = match &platforms {
        Some(p) => {
            if sig == SigPolicy::Skip {
                eprintln!(
                    "warning: {INSECURE_SKIP_SIGNATURE}: the manifest signature is NOT checked (lab only)."
                );
            }
            update_via_mirror_checked(
                &UreqFetcher::new(),
                &base,
                p,
                env!("CARGO_PKG_VERSION"),
                &exe_path,
                &binary_runs,
                sig,
            )
        }
        None => Err(MirrorError::Unsupported(
            "get.zakuro-ai.com has no build for this OS/architecture".to_string(),
        )),
    };
    match result {
        Ok(MirrorOutcome::UpToDate(v)) => {
            println!("zc {v} is already up to date.");
            0
        }
        Ok(MirrorOutcome::Installed { version, .. }) => {
            if to_local_bin {
                ensure_local_bin_on_path(&exe_path);
            }
            println!("updated to {}", version);
            0
        }
        // The lab is offline by design: falling back to GitHub would leave it.
        Err(e) if !crate::profile::active().github_update_fallback => {
            let (MirrorError::Unreachable(m)
            | MirrorError::Unsupported(m)
            | MirrorError::Integrity(m)
            | MirrorError::Other(m)) = &e;
            eprintln!("{m}");
            eprintln!(
                "No GitHub fallback under the {} profile.",
                crate::profile::active().env.name()
            );
            1
        }
        Err(e) => {
            let token = if matches!(e, MirrorError::Integrity(_) | MirrorError::Other(_)) {
                None
            } else {
                resolve_token(gh_auth_token, real_env)
            };
            match fallback_decision(&e, token.is_some()) {
                Fallback::GitHub => {
                    if let MirrorError::Unreachable(m) | MirrorError::Unsupported(m) = &e {
                        eprintln!("{m}");
                    }
                    eprintln!("Falling back to the GitHub releases (token found).");
                    update_from_github(token)
                }
                Fallback::Fail(m) => {
                    eprintln!("{m}");
                    1
                }
            }
        }
    }
}

/// The GitHub-releases path (fallback, see [`fallback_decision`]).
/// zakuro-ai/zc is private: without a token the releases API answers 404.
fn update_from_github(token: Option<String>) -> i32 {
    println!("Checking latest zc release on GitHub...");

    let api = ureq::Agent::new_with_config(api_config().build());
    let mut req = api.get(REPO_API_LATEST);
    let api_token = token_for(REPO_API_LATEST, token.as_deref());
    for (name, value) in github_headers("application/vnd.github+json", api_token) {
        req = req.header(name, value);
    }

    let resp = match req.call() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("Failed to reach GitHub releases API: {}", e);
            eprintln!("{FROM_SOURCE_FALLBACK}");
            return 1;
        }
    };

    if resp.status() != StatusCode::OK {
        eprintln!("{}", api_status_message(resp.status(), api_token.is_some()));
        return 1;
    }

    let body = match resp.into_body().read_to_string() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("Failed to read releases API response: {}", e);
            return 1;
        }
    };

    let data: serde_json::Value = match serde_json::from_str(&body) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Failed to parse releases API response: {}", e);
            return 1;
        }
    };

    let version = data
        .get("tag_name")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown")
        .to_string();

    let asset = asset_name_for(&data);
    let src = match select_asset(&data, &asset) {
        Some(s) => s,
        None => {
            eprintln!("No {} asset found on release {}.", asset, version);
            eprintln!("{FROM_SOURCE_FALLBACK}");
            return 1;
        }
    };

    println!("Downloading {} ({})...", asset, version);

    let downloader = ureq::Agent::new_with_config(download_config().build());
    let bytes = match download(&downloader, &src, token_for(&src.url, token.as_deref())) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("{e}");
            eprintln!("{FROM_SOURCE_FALLBACK}");
            return 1;
        }
    };

    // Refuse a download that does not match the release's own digest, before
    // it is run or installed.
    if let Err(e) = verify_asset_digest(&data, &asset, &bytes) {
        eprintln!("{e}");
        return 1;
    }

    let (exe_path, to_local_bin) = resolve_install_target();
    if let Some(parent) = exe_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    // Never rename an unverified binary over a working one: a -gnu build the
    // host cannot exec (NixOS, gcompat) would brick `zc`.
    let primary_ok = binary_runs(&exe_path, &bytes);
    let is_gnu = asset.ends_with("-gnu");
    let mut musl_bytes: Option<Vec<u8>> = None;
    let mut musl_ok = None;
    if !primary_ok {
        if is_gnu {
            eprintln!("The {asset} build does not run on this host; falling back to musl.");
            let musl_name = asset.trim_end_matches("-gnu");
            musl_bytes = select_asset(&data, musl_name)
                .and_then(|m| download(&downloader, &m, token_for(&m.url, token.as_deref())).ok())
                .filter(|b| verify_asset_digest(&data, musl_name, b).is_ok());
            musl_ok = Some(
                musl_bytes
                    .as_ref()
                    .is_some_and(|b| binary_runs(&exe_path, b)),
            );
        } else {
            musl_ok = Some(false);
        }
    }
    let (choice, install_bytes) = if is_gnu {
        (decide_install(Some(primary_ok), musl_ok), &bytes)
    } else {
        (decide_install(None, Some(primary_ok)), &bytes)
    };
    let to_install: &[u8] = match choice {
        InstallChoice::Gnu => install_bytes,
        InstallChoice::Musl if is_gnu => musl_bytes.as_deref().unwrap_or_default(),
        InstallChoice::Musl => install_bytes,
        InstallChoice::KeepOld => {
            eprintln!(
                "The downloaded binary does not run on this host; keeping the existing zc ({}).",
                exe_path.display()
            );
            eprintln!("{FROM_SOURCE_FALLBACK}");
            return 1;
        }
    };

    println!("Installing to {}...", exe_path.display());
    if let Err(e) = replace_binary_atomic(&exe_path, to_install) {
        eprintln!("Failed to install the new binary: {}", e);
        return 1;
    }
    if to_local_bin {
        ensure_local_bin_on_path(&exe_path);
    }

    println!("updated to {}", version);
    0
}

fn update_from_source() -> i32 {
    let token = match resolve_token(gh_auth_token, real_env) {
        Some(t) => t,
        None => {
            eprintln!("no GitHub token found; run `gh auth login` or set GH_PAT/GITHUB_TOKEN");
            return 1;
        }
    };

    let (exe_path, to_local_bin) = resolve_install_target();
    if let Some(parent) = exe_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    let tmp_dir = std::env::temp_dir().join(format!("zc-update-src-{}", std::process::id()));
    if let Err(e) = std::fs::create_dir_all(&tmp_dir) {
        eprintln!("Failed to create temp dir {}: {}", tmp_dir.display(), e);
        return 1;
    }

    println!("Cloning zakuro-ai/zc (source build)...");
    let clone_url = format!("https://x-access-token:{}@{}", token, REPO_CLONE_HOST);
    let clone_status = Command::new("git")
        .args(["clone", "--depth", "1", &clone_url, "."])
        .current_dir(&tmp_dir)
        .status();

    match clone_status {
        Ok(s) if s.success() => {}
        Ok(s) => {
            eprintln!("git clone failed (exit {}).", s);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return 1;
        }
        Err(e) => {
            eprintln!("Failed to run git clone: {}", e);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return 1;
        }
    }

    println!("Building (cargo build --release)... this can take a few minutes.");
    let (prog, pre_args) = cargo_invocation();
    let build_output = Command::new(&prog)
        .args(pre_args.iter().map(String::as_str))
        .args(["build", "--release"])
        .current_dir(&tmp_dir)
        .output();

    let build_output = match build_output {
        Ok(o) => o,
        Err(e) => {
            eprintln!("Failed to run cargo build: {}", e);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return 1;
        }
    };

    if !build_output.status.success() {
        let stderr = String::from_utf8_lossy(&build_output.stderr);
        let tail: String = stderr
            .lines()
            .rev()
            .take(30)
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect::<Vec<_>>()
            .join("\n");
        eprintln!("cargo build --release failed. Build output (tail):");
        eprintln!("{}", tail);
        if stderr.contains("lock file version") {
            eprintln!();
            eprintln!(
                "This is a toolchain problem, not a code problem: the cargo that ran is\n\
                 too old to read this repo's Cargo.lock (v4 needs Rust >= 1.78).\n\
                 Install rustup so the pinned `stable` toolchain is used, or run the\n\
                 build yourself with a newer cargo:\n\
                 \n\
                 \trustup run stable cargo build --release"
            );
        }
        let _ = std::fs::remove_dir_all(&tmp_dir);
        return 1;
    }

    let mut built_bin: Option<PathBuf> = None;
    for c in ["zc", "zc2"] {
        let p = tmp_dir.join("target/release").join(c);
        if p.is_file() {
            built_bin = Some(p);
            break;
        }
    }
    let built_bin = match built_bin {
        Some(p) => p,
        None => {
            eprintln!("Build finished but no zc binary found under target/release/.");
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return 1;
        }
    };

    let bytes = match std::fs::read(&built_bin) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("Failed to read built binary: {}", e);
            let _ = std::fs::remove_dir_all(&tmp_dir);
            return 1;
        }
    };

    println!("Installing to {}...", exe_path.display());
    if let Err(e) = replace_binary_atomic(&exe_path, &bytes) {
        eprintln!("Failed to install the new binary: {}", e);
        let _ = std::fs::remove_dir_all(&tmp_dir);
        return 1;
    }
    if to_local_bin {
        ensure_local_bin_on_path(&exe_path);
    }

    // Best-effort version string from the built binary itself.
    let version = Command::new(&exe_path)
        .arg("--version")
        .output()
        .ok()
        .filter(|o| o.status.success())
        // First line only: `--version` also prints the binary's sha256, and
        // "updated to <two lines>" reads as a broken message.
        .and_then(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .next()
                .map(|l| l.trim().to_string())
        })
        .unwrap_or_else(|| "source build".to_string());

    let _ = std::fs::remove_dir_all(&tmp_dir);

    println!("updated to {}", version);
    0
}

/// How to invoke cargo for a source build: `("rustup", ["run","stable","cargo"])`
/// when rustup is available, else plain `("cargo", [])`.
///
/// The repo pins `channel = "stable"` in rust-toolchain.toml, but that pin is
/// only honoured by the rustup *shim*. A distro cargo at /usr/bin/cargo is a
/// real binary that ignores it, and if it predates lockfile v4 the build dies
/// with "lock file version 4 requires `-Znext-lockfile-bump`" before compiling
/// a line -- which is exactly what a user with both installed hits, because
/// /usr/bin usually precedes ~/.cargo/bin on PATH.
///
/// Going through rustup means the toolchain file decides, not PATH order.
fn cargo_invocation() -> (String, Vec<String>) {
    let rustup_ok = Command::new("rustup")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);
    if rustup_ok {
        (
            "rustup".to_string(),
            ["run", "stable", "cargo"]
                .iter()
                .map(|s| s.to_string())
                .collect(),
        )
    } else {
        ("cargo".to_string(), Vec::new())
    }
}

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

    #[test]
    fn append_line_once_is_idempotent() {
        let dir = std::env::temp_dir().join(format!("zc-rc-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let rc = dir.join("rc");
        let line = "export PATH=\"$HOME/.local/bin:$PATH\"";
        assert!(super::append_line_once(&rc, line).unwrap()); // added
        assert!(!super::append_line_once(&rc, line).unwrap()); // already present
        let body = std::fs::read_to_string(&rc).unwrap();
        assert_eq!(body.matches(line).count(), 1);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn parse_mode_default_is_prebuilt_release() {
        let args: Vec<String> = vec![];
        assert_eq!(parse_mode(&args), Mode::PrebuiltRelease);
    }

    #[test]
    fn parse_mode_other_flags_still_prebuilt_release() {
        let args: Vec<String> = vec!["--verbose".to_string()];
        assert_eq!(parse_mode(&args), Mode::PrebuiltRelease);
    }

    #[test]
    fn parse_mode_from_source_flag_selects_source_build() {
        let args: Vec<String> = vec!["--from-source".to_string()];
        assert_eq!(parse_mode(&args), Mode::FromSource);
    }

    #[test]
    fn parse_mode_from_source_among_other_args() {
        let args: Vec<String> = vec!["--verbose".to_string(), "--from-source".to_string()];
        assert_eq!(parse_mode(&args), Mode::FromSource);
    }

    #[test]
    fn resolve_token_prefers_gh() {
        let t = resolve_token(
            || Some("gh-token".to_string()),
            |k| match k {
                "GH_PAT" => Some("pat-token".to_string()),
                "GITHUB_TOKEN" => Some("gh-env-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("gh-token"));
    }

    #[test]
    fn resolve_token_falls_back_to_gh_pat() {
        let t = resolve_token(
            || None,
            |k| match k {
                "GH_PAT" => Some("pat-token".to_string()),
                "GITHUB_TOKEN" => Some("gh-env-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("pat-token"));
    }

    #[test]
    fn resolve_token_falls_back_to_github_token() {
        let t = resolve_token(
            || None,
            |k| match k {
                "GH_PAT" => None,
                "GITHUB_TOKEN" => Some("gh-env-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("gh-env-token"));
    }

    #[test]
    fn resolve_token_none_found() {
        let t = resolve_token(|| None, |_k| None);
        assert_eq!(t, None);
    }

    #[test]
    fn resolve_token_skips_blank_values() {
        // A blank gh token or blank env var should not shadow a real one
        // further down the precedence chain.
        let t = resolve_token(
            || Some("   ".to_string()),
            |k| match k {
                "GH_PAT" => Some("".to_string()),
                "GITHUB_TOKEN" => Some("real-token".to_string()),
                _ => None,
            },
        );
        assert_eq!(t.as_deref(), Some("real-token"));
    }

    fn names(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn linux_gpu_host_with_new_enough_glibc_gets_the_gnu_build() {
        let assets = names(&["zc-linux-x86_64", "zc-linux-x86_64-gnu"]);
        assert_eq!(
            choose_linux_asset(false, true, Some((2, 35)), &assets),
            "zc-linux-x86_64-gnu"
        );
        let assets = names(&["zc-linux-arm64", "zc-linux-arm64-gnu"]);
        assert_eq!(
            choose_linux_asset(true, true, Some((2, 31)), &assets),
            "zc-linux-arm64-gnu"
        );
    }

    #[test]
    fn linux_keeps_musl_without_a_gpu_or_with_old_or_unknown_glibc() {
        let assets = names(&["zc-linux-x86_64", "zc-linux-x86_64-gnu"]);
        assert_eq!(
            choose_linux_asset(false, false, Some((2, 39)), &assets),
            "zc-linux-x86_64"
        );
        assert_eq!(
            choose_linux_asset(false, true, Some((2, 28)), &assets),
            "zc-linux-x86_64"
        );
        assert_eq!(
            choose_linux_asset(false, true, None, &assets),
            "zc-linux-x86_64"
        );
    }

    #[test]
    fn linux_falls_back_to_musl_when_the_release_has_no_gnu_asset() {
        let assets = names(&["zc-linux-x86_64", "zc-linux-arm64"]);
        assert_eq!(
            choose_linux_asset(false, true, Some((2, 39)), &assets),
            "zc-linux-x86_64"
        );
        assert_eq!(
            choose_linux_asset(true, true, Some((2, 39)), &assets),
            "zc-linux-arm64"
        );
    }

    #[test]
    fn install_decision_never_replaces_with_a_binary_that_does_not_run() {
        use InstallChoice::*;
        assert_eq!(decide_install(Some(true), None), Gnu);
        assert_eq!(decide_install(Some(true), Some(true)), Gnu);
        assert_eq!(decide_install(Some(false), Some(true)), Musl);
        assert_eq!(decide_install(Some(false), Some(false)), KeepOld);
        assert_eq!(decide_install(Some(false), None), KeepOld);
        assert_eq!(decide_install(None, Some(true)), Musl);
        assert_eq!(decide_install(None, Some(false)), KeepOld);
    }

    #[test]
    fn gpu_musl_fallback_is_explained_only_for_gpu_hosts() {
        let with = names(&["zc-linux-x86_64", "zc-linux-x86_64-gnu"]);
        let without = names(&["zc-linux-x86_64"]);
        assert_eq!(
            gpu_musl_fallback_reason(false, false, Some((2, 35)), &without),
            None
        );
        assert_eq!(
            gpu_musl_fallback_reason(false, true, Some((2, 35)), &with),
            None
        );
        assert!(
            gpu_musl_fallback_reason(false, true, Some((2, 35)), &without)
                .unwrap()
                .contains("no glibc asset")
        );
        assert!(gpu_musl_fallback_reason(false, true, Some((2, 28)), &with)
            .unwrap()
            .contains("glibc < 2.31"));
        assert!(gpu_musl_fallback_reason(false, true, None, &with).is_some());
    }

    #[test]
    fn glibc_version_is_parsed_from_ldd_output() {
        assert_eq!(
            parse_glibc_version("ldd (Ubuntu GLIBC 2.35-0ubuntu3.8) 2.35\nCopyright"),
            Some((2, 35))
        );
        assert_eq!(parse_glibc_version("ldd (GNU libc) 2.31\n"), Some((2, 31)));
        assert_eq!(
            parse_glibc_version("musl libc (x86_64)\nVersion 1.2.5\n"),
            None
        );
        assert_eq!(parse_glibc_version(""), None);
    }

    const API_ASSET: &str = "https://api.github.com/repos/zakuro-ai/zc/releases/assets/2";
    const BROWSER_ASSET: &str =
        "https://github.com/zakuro-ai/zc/releases/download/v0.0.26/zc-darwin-arm64";

    #[test]
    fn asset_selection_prefers_the_api_url_with_octet_stream() {
        let release = serde_json::json!({ "tag_name": "v0.0.26", "assets": [
            {
                "name": "zc-linux-x86_64",
                "url": "https://api.github.com/repos/zakuro-ai/zc/releases/assets/1",
                "browser_download_url": "https://github.com/zakuro-ai/zc/releases/download/v0.0.26/zc-linux-x86_64",
            },
            { "name": "zc-darwin-arm64", "url": API_ASSET, "browser_download_url": BROWSER_ASSET },
        ]});
        assert_eq!(
            select_asset(&release, "zc-darwin-arm64"),
            Some(AssetSource {
                url: API_ASSET.to_string(),
                accept: "application/octet-stream",
            })
        );
        assert_eq!(select_asset(&release, "zc-linux-arm64"), None);
    }

    #[test]
    fn asset_selection_falls_back_to_the_browser_download_url() {
        let release = serde_json::json!({ "assets": [
            { "name": "zc-darwin-arm64", "browser_download_url": BROWSER_ASSET },
        ]});
        assert_eq!(
            select_asset(&release, "zc-darwin-arm64"),
            Some(AssetSource {
                url: BROWSER_ASSET.to_string(),
                accept: "*/*",
            })
        );
    }

    #[test]
    fn a_token_becomes_an_authorization_header_on_github_requests_only() {
        let with = github_headers(OCTET_STREAM, Some("t0ken"));
        assert!(
            with.contains(&("Authorization", "Bearer t0ken".to_string())),
            "{with:?}"
        );
        assert!(
            with.contains(&("Accept", OCTET_STREAM.to_string())),
            "{with:?}"
        );
        assert!(
            with.contains(&("User-Agent", "zc-update".to_string())),
            "{with:?}"
        );
        let without = github_headers(OCTET_STREAM, None);
        assert!(
            without.iter().all(|(k, _)| *k != "Authorization"),
            "{without:?}"
        );
        // The storage host GitHub redirects the download to never gets it.
        assert_eq!(
            download_config().build().redirect_auth_headers(),
            RedirectAuthHeaders::Never
        );
    }

    #[test]
    fn the_download_gets_300_s_and_the_api_call_30_s() {
        assert_eq!(
            download_config().build().timeouts().global,
            Some(Duration::from_secs(300))
        );
        assert_eq!(
            api_config().build().timeouts().global,
            Some(Duration::from_secs(30))
        );
    }

    #[test]
    fn without_a_token_a_404_says_the_releases_are_private() {
        assert_eq!(
            api_status_message(StatusCode::NOT_FOUND, false),
            "zc releases are private. Sign in with `gh auth login` (or set GH_PAT / GITHUB_TOKEN) and run zc update again."
        );
        // Any other status, token or not, is GitHub's answer and the
        // source-build fallback.
        for have_token in [false, true] {
            let m = api_status_message(StatusCode::FORBIDDEN, have_token);
            assert!(
                m.starts_with("GitHub releases API returned HTTP 403 Forbidden\n"),
                "{m}"
            );
            assert!(m.ends_with(FROM_SOURCE_FALLBACK), "{m}");
        }
    }

    /// A token that can't see the private repo gets a 404 too, as does a repo
    /// with no release: say so, and point at where zc got the token.
    #[test]
    fn with_a_token_a_404_says_it_may_lack_access_or_there_is_no_release() {
        let m = api_status_message(StatusCode::NOT_FOUND, true);
        for part in [
            "HTTP 404 Not Found",
            "may not have access to zakuro-ai/zc (the repo is private)",
            "or there is no release yet",
            "`gh auth status`",
            "GH_PAT",
            "GITHUB_TOKEN",
        ] {
            assert!(m.contains(part), "missing {part:?} in: {m}");
        }
        assert!(m.ends_with(FROM_SOURCE_FALLBACK), "{m}");
    }

    #[test]
    fn the_token_goes_to_api_github_com_only() {
        let sends_token = |url: &str| {
            github_headers(OCTET_STREAM, token_for(url, Some("t0ken")))
                .iter()
                .any(|(k, v)| *k == "Authorization" && v == "Bearer t0ken")
        };
        for url in [
            REPO_API_LATEST,
            API_ASSET,
            "https://API.GitHub.com/repos/zakuro-ai/zc/releases/latest",
        ] {
            assert!(sends_token(url), "{url} gets the token");
        }
        for url in [
            BROWSER_ASSET, // the browser_download_url fallback, on github.com
            "https://objects.githubusercontent.com/github-production-release-asset/1?sig=x",
            "https://api.github.com.evil.example/repos/zakuro-ai/zc", // host only starts with it
            "https://evil.example/api.github.com/repos/zakuro-ai/zc", // only in the path
            "https://api.github.com@evil.example/repos/zakuro-ai/zc", // userinfo; host is evil
            "http://api.github.com/repos/zakuro-ai/zc",               // not https
            "not a url",
        ] {
            assert!(!sends_token(url), "{url} must not get the token");
        }
        assert_eq!(token_for(REPO_API_LATEST, None), None);
    }

    /// A one-shot HTTP server on 127.0.0.1: answers the first request with
    /// `response` and hands back that request's head (request line and
    /// headers).
    fn one_shot_server(response: Vec<u8>) -> (String, std::thread::JoinHandle<String>) {
        use std::io::{Read, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let handle = std::thread::spawn(move || {
            let (mut s, _) = listener.accept().unwrap();
            let mut head = Vec::new();
            let mut b = [0u8; 1024];
            while !head.windows(4).any(|w| w == b"\r\n\r\n") {
                match s.read(&mut b) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => head.extend_from_slice(&b[..n]),
                }
            }
            s.write_all(&response).unwrap();
            String::from_utf8_lossy(&head).into_owned()
        });
        (base, handle)
    }

    /// GitHub's asset API answers with a 302 to a signed storage URL, and the
    /// storage host rejects a request that also carries the token.
    #[test]
    fn the_download_follows_the_redirect_without_the_token() {
        let blob = b"\x7fELF not really a zc binary".to_vec();
        let mut ok = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
            blob.len()
        )
        .into_bytes();
        ok.extend_from_slice(&blob);
        let (storage, storage_req) = one_shot_server(ok);
        let (api, api_req) = one_shot_server(
            format!(
                "HTTP/1.1 302 Found\r\nLocation: {storage}/signed?sig=abc\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
            )
            .into_bytes(),
        );

        // No proxy from the environment: the fake servers are on loopback.
        let agent = ureq::Agent::new_with_config(download_config().proxy(None).build());
        let src = AssetSource {
            url: format!("{api}/repos/zakuro-ai/zc/releases/assets/2"),
            accept: OCTET_STREAM,
        };
        let bytes = download(&agent, &src, Some("t0ken")).expect("download succeeds");
        assert_eq!(bytes, blob);

        let api_req = api_req.join().unwrap().to_ascii_lowercase();
        assert!(
            api_req.contains("\r\nauthorization: bearer t0ken\r\n"),
            "{api_req}"
        );
        assert!(
            api_req.contains("\r\naccept: application/octet-stream\r\n"),
            "{api_req}"
        );
        let storage_req = storage_req.join().unwrap().to_ascii_lowercase();
        assert!(
            storage_req.starts_with("get /signed?sig=abc http/1.1\r\n"),
            "{storage_req}"
        );
        assert!(!storage_req.contains("authorization"), "{storage_req}");
    }

    // ---- mirror path (ZC-0015) ----

    use std::cell::RefCell;
    use std::collections::HashMap;

    /// Canned responses by URL; records every URL asked for.
    struct MockFetcher {
        routes: HashMap<String, Result<Vec<u8>, FetchError>>,
        seen: RefCell<Vec<String>>,
    }
    impl MockFetcher {
        fn new() -> Self {
            Self {
                routes: HashMap::new(),
                seen: RefCell::new(vec![]),
            }
        }
        fn ok(mut self, url: &str, body: &[u8]) -> Self {
            self.routes.insert(url.to_string(), Ok(body.to_vec()));
            self
        }
        fn status(mut self, url: &str, s: u16) -> Self {
            self.routes
                .insert(url.to_string(), Err(FetchError::Status(s)));
            self
        }
    }
    impl Fetcher for MockFetcher {
        fn get(&self, url: &str) -> Result<Vec<u8>, FetchError> {
            self.seen.borrow_mut().push(url.to_string());
            match self.routes.get(url) {
                Some(Ok(b)) => Ok(b.clone()),
                Some(Err(FetchError::Status(s))) => Err(FetchError::Status(*s)),
                Some(Err(FetchError::Transport(m))) => Err(FetchError::Transport(m.clone())),
                None => Err(FetchError::Transport(format!("no route {url}"))),
            }
        }
    }

    const BASE: &str = "https://mirror.test/zc";
    const NEW_BIN: &[u8] = b"new zc binary";

    fn manifest_json(version: &str, bin: &[u8]) -> Vec<u8> {
        serde_json::json!({
            "version": version,
            "sha256": crate::dataset::sha256_hex(bin),
            "bin": "zc",
        })
        .to_string()
        .into_bytes()
    }

    fn temp_exe(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("zc-mirror-test-{tag}-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let exe = dir.join("zc");
        std::fs::write(&exe, b"old zc binary").unwrap();
        exe
    }

    fn plats(p: &[&str]) -> Vec<String> {
        p.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn manifest_parses_with_and_without_sig() {
        let sha = "ab".repeat(32);
        let m = parse_manifest(
            format!(r#"{{"version":"0.0.35","sha256":"{sha}","bin":"zc","sig":"x"}}"#).as_bytes(),
        )
        .unwrap();
        assert_eq!(m.version, "0.0.35");
        assert_eq!(m.sha256, sha);
        assert!(
            parse_manifest(format!(r#"{{"version":"v0.0.35","sha256":"{sha}"}}"#).as_bytes())
                .is_ok()
        );
    }

    #[test]
    fn manifest_rejects_bad_input() {
        let sha = "ab".repeat(32);
        assert!(parse_manifest(b"not json").is_err());
        assert!(parse_manifest(br#"{"version":"0.0.35"}"#).is_err());
        assert!(parse_manifest(format!(r#"{{"sha256":"{sha}"}}"#).as_bytes()).is_err());
        assert!(parse_manifest(br#"{"version":"0.0.35","sha256":"abc"}"#).is_err());
        // The version is interpolated into a URL: nothing but a release version.
        let evil = format!(r#"{{"version":"0.0.35&x=1","sha256":"{sha}"}}"#);
        assert!(parse_manifest(evil.as_bytes()).is_err());
    }

    #[test]
    fn mirror_base_normalisation() {
        let ok = |i: &str| normalize_mirror_base(i).unwrap();
        assert_eq!(
            ok("https://stg.get.zakuro-ai.com"),
            "https://stg.get.zakuro-ai.com/zc"
        );
        assert_eq!(
            ok("https://stg.get.zakuro-ai.com/"),
            "https://stg.get.zakuro-ai.com/zc"
        );
        assert_eq!(
            ok(" https://get.zakuro-ai.com/zc/ "),
            "https://get.zakuro-ai.com/zc"
        );
        assert_eq!(ok("http://127.0.0.1:8080"), "http://127.0.0.1:8080/zc");
        assert_eq!(ok("http://localhost/zc"), "http://localhost/zc");
        assert!(normalize_mirror_base("http://evil.example/zc").is_err());
        assert!(normalize_mirror_base("http://127.0.0.1.evil.com").is_err());
        assert!(normalize_mirror_base("ftp://x").is_err());
        assert!(normalize_mirror_base("get.zakuro-ai.com").is_err());
        assert!(normalize_mirror_base("https://").is_err());
        assert!(normalize_mirror_base("https:///zc").is_err());
    }

    #[test]
    fn version_output_parsing() {
        assert_eq!(
            parse_version_output(
                "zc version 0.0.39 (abc1234) built on 2026-10-08\nbinary sha256 ff"
            ),
            Some("0.0.39".into())
        );
        assert_eq!(parse_version_output("other 1.0"), None);
        assert_eq!(parse_version_output(""), None);
    }

    #[test]
    fn version_compare() {
        assert_eq!(parse_version("v0.0.35"), Some((0, 0, 35)));
        assert_eq!(parse_version("1.2.3-rc1"), Some((1, 2, 3)));
        assert_eq!(parse_version("1.2"), None);
        assert_eq!(parse_version("1.2.3.4"), None);
        assert_eq!(is_newer("0.0.35", "0.0.34"), Ok(true));
        assert_eq!(is_newer("0.0.34", "0.0.34"), Ok(false));
        assert_eq!(is_newer("0.0.33", "0.0.34"), Ok(false));
        assert_eq!(is_newer("0.0.100", "0.0.34"), Ok(true));
        assert_eq!(is_newer("v0.1.0", "0.0.99"), Ok(true));
        assert!(is_newer("latest", "0.0.34").is_err());
    }

    #[test]
    fn platform_mapping() {
        assert_eq!(
            mirror_platforms(true, true, false, None),
            Some(plats(&["darwin_arm64"]))
        );
        assert_eq!(mirror_platforms(true, false, false, None), None);
        assert_eq!(
            mirror_platforms(false, false, false, None),
            Some(plats(&["linux_amd64"]))
        );
        assert_eq!(
            mirror_platforms(false, true, false, None),
            Some(plats(&["linux_arm64"]))
        );
        // NVIDIA + glibc >= 2.31 prefers the glibc build, then musl (#357/#364).
        assert_eq!(
            mirror_platforms(false, false, true, Some((2, 35))),
            Some(plats(&["linux_amd64_gnu", "linux_amd64"]))
        );
        assert_eq!(
            mirror_platforms(false, true, true, Some((2, 31))),
            Some(plats(&["linux_arm64_gnu", "linux_arm64"]))
        );
        // Old or unknown glibc, or no GPU: musl only.
        assert_eq!(
            mirror_platforms(false, false, true, Some((2, 28))),
            Some(plats(&["linux_amd64"]))
        );
        assert_eq!(
            mirror_platforms(false, false, true, None),
            Some(plats(&["linux_amd64"]))
        );
    }

    // Signed-manifest vectors (GET-0013), made with a throwaway minisign key
    // by zak-get's scripts/minisign.py; bodies are zak-get's canonical JSON.
    const T_KEY: &str = "RWRmArgKUT5tk4Svw+2AI9E34hkv6X+lFuiOdubYQuUzYdBbHIhZs9dP";
    const T_BODY: &str = r#"{"bin":"zc","platform":"linux_amd64","sha256":"78f494fa64710849e5ddb6c5590fbc83ff2e3ba420393289e0a20dafe7878d9d","version":"0.0.35"}"#;
    const T_SIG: &str = "untrusted comment: signature from zak-get key 936D3E510AB80266\nRURmArgKUT5tk+YmLyJZEieILb7CHFe1DTm69D+pieUFeRY2ncKhAN0YZUJZKcpq6ImzjNeDs0LNJO5IGuYIjNLxuTLkRQckPQ4=\ntrusted comment: zc-manifest platform:linux_amd64 version:0.0.35\nyaOJ7Xf+1aLm0a5XQyF2jWEsGujjaqCKPbvX6XyCRyKvSNKWA7HKRmsmDSvNl6ZxPpVan+BlpOSfzuhDH9RwBQ==\n";
    const T_BODY_ARM: &str = r#"{"bin":"zc","platform":"linux_arm64","sha256":"78f494fa64710849e5ddb6c5590fbc83ff2e3ba420393289e0a20dafe7878d9d","version":"0.0.35"}"#;
    const T_SIG_ARM: &str = "untrusted comment: signature from zak-get key 936D3E510AB80266\nRURmArgKUT5tk++QXtGBE3lpYQA0uqiY0nHJXpbFPEBCSFFo1/tsc/QYfkZulRAP3Z+XYgVwKkOQdrkur9F1t8byBQ1trnvwdAo=\ntrusted comment: zc-manifest platform:linux_arm64 version:0.0.35\nvOTG/Q4u7UFnqZSX0jt87Xz9rjhdPLSJNhKwlp0qx+mlTnVUS04Si6bwg1jyGTb6wmBNQDWSQj0Xr1hzQ/aDAA==\n";
    const T_SIG_OTHER_KEY: &str = "untrusted comment: signature from zak-get key A90A906D6A50661B\nRUQbZlBqbZAKqXV+rthWFEzSQVtky4BhM36CnIF3qXIX50+l6+MWBqQfiZV4Aewy8dkRRBMhHCkT071y4RN2HUbd0/wdgiuk/Q8=\ntrusted comment: x\nOKp2Kc2uvdCntpkvUsL6e/9FoQPRwWuqARl2rIyir6On0BLhQTrWG2elodi1cpTr/Gs0JLqXi8O1X6Ya/CDDDw==\n";

    fn signed_mirror(body: &str, sig: Option<&str>) -> MockFetcher {
        let f = MockFetcher::new()
            .ok(&format!("{BASE}/manifest/linux_amd64"), body.as_bytes())
            .ok(
                &format!("{BASE}/download/linux_amd64?version=0.0.35"),
                NEW_BIN,
            );
        match sig {
            Some(s) => f.ok(&format!("{BASE}/manifest/linux_amd64.sig"), s.as_bytes()),
            None => f.status(&format!("{BASE}/manifest/linux_amd64.sig"), 404),
        }
    }

    fn run_signed(f: &MockFetcher, exe: &Path) -> Result<MirrorOutcome, MirrorError> {
        update_via_mirror_checked(
            f,
            BASE,
            &plats(&["linux_amd64"]),
            "0.0.34",
            exe,
            &|_, _| true,
            SigPolicy::Require(T_KEY),
        )
    }

    fn assert_refused(out: Result<MirrorOutcome, MirrorError>, exe: &Path, needle: &str) {
        match out {
            Err(MirrorError::Integrity(m)) => assert!(m.contains(needle), "{m}"),
            other => panic!("expected Integrity({needle}), got {other:?}"),
        }
        assert_eq!(std::fs::read(exe).unwrap(), b"old zc binary");
    }

    #[test]
    fn signed_manifest_installs() {
        let exe = temp_exe("signed-ok");
        let out = run_signed(&signed_mirror(T_BODY, Some(T_SIG)), &exe);
        assert!(
            matches!(out, Ok(MirrorOutcome::Installed { .. })),
            "{out:?}"
        );
        assert_eq!(std::fs::read(&exe).unwrap(), NEW_BIN);
    }

    #[test]
    fn unsigned_manifest_is_refused() {
        let exe = temp_exe("signed-none");
        let f = signed_mirror(T_BODY, None);
        assert_refused(run_signed(&f, &exe), &exe, "not signed");
        assert!(
            !f.seen.borrow().iter().any(|u| u.contains("/download/")),
            "nothing is downloaded before the signature verifies"
        );
    }

    #[test]
    fn tampered_manifest_is_refused() {
        let exe = temp_exe("signed-tampered");
        // An attacker swaps the hash for one of their own binary.
        let evil = T_BODY.replace("78f494fa", "00000000");
        assert_refused(
            run_signed(&signed_mirror(&evil, Some(T_SIG)), &exe),
            &exe,
            "does not verify",
        );
    }

    #[test]
    fn manifest_signed_by_another_key_is_refused() {
        let exe = temp_exe("signed-otherkey");
        assert_refused(
            run_signed(&signed_mirror(T_BODY, Some(T_SIG_OTHER_KEY)), &exe),
            &exe,
            "does not verify",
        );
    }

    #[test]
    fn signature_for_another_platform_is_refused() {
        let exe = temp_exe("signed-otherplat");
        // Validly signed, but for linux_arm64: served as the linux_amd64 manifest.
        assert_refused(
            run_signed(&signed_mirror(T_BODY_ARM, Some(T_SIG_ARM)), &exe),
            &exe,
            "not linux_amd64",
        );
    }

    #[test]
    fn garbage_signature_is_refused() {
        let exe = temp_exe("signed-garbage");
        assert_refused(
            run_signed(&signed_mirror(T_BODY, Some("not a signature")), &exe),
            &exe,
            "malformed",
        );
    }

    #[test]
    fn integrity_refusal_never_falls_back_to_github() {
        let e = MirrorError::Integrity("the linux_amd64 manifest is not signed".into());
        assert!(matches!(fallback_decision(&e, true), Fallback::Fail(_)));
    }

    #[test]
    fn skip_signature_flag_is_lab_only() {
        use crate::profile::Env;
        let skip = vec!["update".to_string(), INSECURE_SKIP_SIGNATURE.to_string()];
        let none = vec!["update".to_string()];
        assert_eq!(sig_policy_for(&skip, Env::Lab, "k"), Ok(SigPolicy::Skip));
        for env in [Env::Prod, Env::Staging] {
            let e = sig_policy_for(&skip, env, "k").unwrap_err();
            assert!(e.contains("only allowed under ZAKURO_ENV=lab"), "{e}");
            assert_eq!(sig_policy_for(&none, env, "k"), Ok(SigPolicy::Require("k")));
        }
        assert!(sig_policy_for(&none, Env::Prod, "").is_err());
    }

    #[test]
    fn every_profile_pins_a_valid_update_key() {
        for p in [
            &crate::profile::PROD,
            &crate::profile::STAGING,
            &crate::profile::LAB,
        ] {
            minisign_verify::PublicKey::from_base64(p.update_trust_root)
                .unwrap_or_else(|e| panic!("{:?}: {e}", p.env));
        }
    }

    #[test]
    fn mirror_update_installs_verified_binary() {
        let exe = temp_exe("ok");
        let f = MockFetcher::new()
            .ok(
                &format!("{BASE}/manifest/linux_amd64"),
                &manifest_json("0.0.35", NEW_BIN),
            )
            .ok(
                &format!("{BASE}/download/linux_amd64?version=0.0.35"),
                NEW_BIN,
            );
        let out = update_via_mirror(
            &f,
            BASE,
            &plats(&["linux_amd64"]),
            "0.0.34",
            &exe,
            &|_, _| true,
        );
        assert_eq!(
            out,
            Ok(MirrorOutcome::Installed {
                version: "0.0.35".into(),
                platform: "linux_amd64".into()
            })
        );
        assert_eq!(std::fs::read(&exe).unwrap(), NEW_BIN);
    }

    #[test]
    fn mirror_update_sha256_mismatch_refuses_and_keeps_current_binary() {
        let exe = temp_exe("mismatch");
        // Manifest says NEW_BIN; the download is something else.
        let f = MockFetcher::new()
            .ok(
                &format!("{BASE}/manifest/linux_amd64"),
                &manifest_json("0.0.35", NEW_BIN),
            )
            .ok(
                &format!("{BASE}/download/linux_amd64?version=0.0.35"),
                b"tampered",
            );
        let out = update_via_mirror(
            &f,
            BASE,
            &plats(&["linux_amd64"]),
            "0.0.34",
            &exe,
            &|_, _| true,
        );
        match out {
            Err(MirrorError::Integrity(m)) => assert!(m.contains("sha256 mismatch"), "{m}"),
            other => panic!("expected Integrity, got {other:?}"),
        }
        assert_eq!(std::fs::read(&exe).unwrap(), b"old zc binary");
    }

    #[test]
    fn mirror_update_skips_when_up_to_date_or_newer_installed() {
        for cur in ["0.0.35", "0.0.40"] {
            let exe = temp_exe("uptodate");
            let f = MockFetcher::new().ok(
                &format!("{BASE}/manifest/linux_amd64"),
                &manifest_json("0.0.35", NEW_BIN),
            );
            let out =
                update_via_mirror(&f, BASE, &plats(&["linux_amd64"]), cur, &exe, &|_, _| true);
            assert_eq!(out, Ok(MirrorOutcome::UpToDate(cur.into())));
            assert_eq!(f.seen.borrow().len(), 1, "no download when up to date");
            assert_eq!(std::fs::read(&exe).unwrap(), b"old zc binary");
        }
    }

    #[test]
    fn mirror_update_glibc_build_falls_back_to_musl() {
        // No gnu platform on the mirror: 404 -> musl.
        let exe = temp_exe("gnu404");
        let f = MockFetcher::new()
            .status(&format!("{BASE}/manifest/linux_amd64_gnu"), 404)
            .ok(
                &format!("{BASE}/manifest/linux_amd64"),
                &manifest_json("0.0.35", NEW_BIN),
            )
            .ok(
                &format!("{BASE}/download/linux_amd64?version=0.0.35"),
                NEW_BIN,
            );
        let out = update_via_mirror(
            &f,
            BASE,
            &plats(&["linux_amd64_gnu", "linux_amd64"]),
            "0.0.34",
            &exe,
            &|_, _| true,
        );
        assert!(
            matches!(out, Ok(MirrorOutcome::Installed { ref platform, .. }) if platform == "linux_amd64"),
            "{out:?}"
        );

        // A gnu build that does not run on this host -> musl.
        let exe = temp_exe("gnunorun");
        let gnu = b"gnu build".to_vec();
        let f = MockFetcher::new()
            .ok(
                &format!("{BASE}/manifest/linux_amd64_gnu"),
                &manifest_json("0.0.35", &gnu),
            )
            .ok(
                &format!("{BASE}/download/linux_amd64_gnu?version=0.0.35"),
                &gnu,
            )
            .ok(
                &format!("{BASE}/manifest/linux_amd64"),
                &manifest_json("0.0.35", NEW_BIN),
            )
            .ok(
                &format!("{BASE}/download/linux_amd64?version=0.0.35"),
                NEW_BIN,
            );
        let out = update_via_mirror(
            &f,
            BASE,
            &plats(&["linux_amd64_gnu", "linux_amd64"]),
            "0.0.34",
            &exe,
            &|_, b| b == NEW_BIN,
        );
        assert!(
            matches!(out, Ok(MirrorOutcome::Installed { ref platform, .. }) if platform == "linux_amd64"),
            "{out:?}"
        );
        assert_eq!(std::fs::read(&exe).unwrap(), NEW_BIN);
    }

    #[test]
    fn mirror_unreachable_and_unsupported_are_classified() {
        let exe = temp_exe("down");
        let f = MockFetcher::new(); // every GET is a transport error
        let out = update_via_mirror(
            &f,
            BASE,
            &plats(&["linux_amd64"]),
            "0.0.34",
            &exe,
            &|_, _| true,
        );
        assert!(matches!(out, Err(MirrorError::Unreachable(_))), "{out:?}");
        let f = MockFetcher::new().status(&format!("{BASE}/manifest/linux_amd64"), 503);
        let out = update_via_mirror(
            &f,
            BASE,
            &plats(&["linux_amd64"]),
            "0.0.34",
            &exe,
            &|_, _| true,
        );
        assert!(matches!(out, Err(MirrorError::Unreachable(_))), "{out:?}");
        let f = MockFetcher::new().status(&format!("{BASE}/manifest/linux_amd64"), 404);
        let out = update_via_mirror(
            &f,
            BASE,
            &plats(&["linux_amd64"]),
            "0.0.34",
            &exe,
            &|_, _| true,
        );
        assert!(matches!(out, Err(MirrorError::Unsupported(_))), "{out:?}");
        assert_eq!(std::fs::read(&exe).unwrap(), b"old zc binary");
    }

    #[test]
    fn fallback_selection() {
        let down = MirrorError::Unreachable("x".into());
        let unsupported = MirrorError::Unsupported("x".into());
        // GitHub only with a token AND a mirror that could not serve us.
        assert_eq!(fallback_decision(&down, true), Fallback::GitHub);
        assert_eq!(fallback_decision(&unsupported, true), Fallback::GitHub);
        assert!(matches!(fallback_decision(&down, false), Fallback::Fail(_)));
        assert!(matches!(
            fallback_decision(&unsupported, false),
            Fallback::Fail(_)
        ));
        // A checksum mismatch is a refusal, never routed around.
        let bad = MirrorError::Integrity("sha256 mismatch".into());
        assert!(matches!(fallback_decision(&bad, true), Fallback::Fail(_)));
        assert!(matches!(
            fallback_decision(&MirrorError::Other("x".into()), true),
            Fallback::Fail(_)
        ));
    }

    #[test]
    fn github_asset_digest_is_verified() {
        let good = crate::dataset::sha256_hex(NEW_BIN);
        let release = serde_json::json!({ "assets": [
            { "name": "zc-linux-x86_64", "digest": format!("sha256:{good}") },
            { "name": "zc-linux-arm64" },
        ]});
        assert_eq!(asset_digest(&release, "zc-linux-x86_64"), Some(good));
        assert!(verify_asset_digest(&release, "zc-linux-x86_64", NEW_BIN).is_ok());
        let err = verify_asset_digest(&release, "zc-linux-x86_64", b"tampered").unwrap_err();
        assert!(err.contains("sha256 mismatch"), "{err}");
        // No published digest: refuse rather than install unverified.
        assert!(verify_asset_digest(&release, "zc-linux-arm64", NEW_BIN).is_err());
        assert!(verify_asset_digest(&release, "missing", NEW_BIN).is_err());
    }

    #[test]
    fn ureq_fetcher_maps_status_and_never_sends_credentials() {
        let (base, req) = one_shot_server(
            b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec(),
        );
        let f = UreqFetcher(
            ureq::Agent::new_with_config(download_config().proxy(None).build()),
            "zc-update".to_string(),
        );
        assert_eq!(
            f.get(&format!("{base}/manifest/linux_amd64")),
            Err(FetchError::Status(404))
        );
        let head = req.join().unwrap().to_ascii_lowercase();
        assert!(!head.contains("authorization"), "{head}");
    }
}

#[cfg(test)]
mod cargo_invocation_tests {
    /// The shape matters: `rustup run stable cargo build --release`, so the
    /// repo's rust-toolchain.toml decides the toolchain instead of PATH order.
    /// Without this, a distro cargo at /usr/bin (which precedes ~/.cargo/bin on
    /// a default PATH) silently wins and dies on the v4 lock file.
    #[test]
    fn rustup_invocation_puts_cargo_after_run_stable() {
        let (prog, pre) = super::cargo_invocation();
        if prog == "rustup" {
            assert_eq!(pre, vec!["run", "stable", "cargo"]);
        } else {
            assert_eq!(prog, "cargo");
            assert!(pre.is_empty(), "plain cargo takes no leading args");
        }
    }
}