seshat-cli 0.3.0

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

use crate::CliError;
use crate::version_cache::VersionCache;
use flate2::read::GzDecoder;
use indicatif::{ProgressBar, ProgressStyle};
use sha2::Digest;
use tar::Archive;

use sha2::Sha256;

const GITHUB_RELEASES_API: &str = "https://api.github.com/repos/KSDaemon/seshat/releases/latest";
const USER_AGENT: &str = "seshat";
const TIMEOUT_SECS: u64 = 15;

#[derive(Debug, PartialEq, Clone, Copy)]
enum InstallMethod {
    Homebrew,
    Direct,
}

struct RateLimitInfo {
    retry_after_minutes: u64,
}

pub fn run_update(check: bool) -> Result<(), CliError> {
    if check {
        run_check()
    } else {
        run_self_update()
    }
}

pub fn check_and_print_update_notice() {
    check_and_print_update_notice_inner(&VersionCache::cache_path());
}

fn check_and_print_update_notice_inner(cache_path: &Option<PathBuf>) {
    let current = env!("CARGO_PKG_VERSION");

    if let Some(path) = cache_path {
        if let Some(cache) = VersionCache::read_from_path(path) {
            if cache.is_fresh() {
                if cache.has_assets == Some(false) {
                    return;
                }
                if is_newer(&cache.latest_version, current) {
                    eprintln!(
                        "Seshat v{} is available (current: v{current}). Run seshat update to upgrade.",
                        cache.latest_version
                    );
                }
                return;
            }
        }
    }

    let (version, has_assets) = match fetch_latest_release() {
        Ok(result) => result,
        Err(_) => return,
    };

    if let Some(path) = cache_path {
        let cache = if has_assets {
            VersionCache::with_assets(version.clone(), true)
        } else {
            VersionCache::with_assets(current.to_owned(), false)
        };
        let _ = cache.write_to_path(path);
    }

    if !has_assets {
        return;
    }

    if is_newer(&version, current) {
        eprintln!(
            "Seshat v{version} is available (current: v{current}). Run seshat update to upgrade."
        );
    }
}

fn run_self_update() -> Result<(), CliError> {
    let install_method = detect_install_method()?;
    if install_method == InstallMethod::Homebrew {
        eprintln!("Seshat was installed via Homebrew. Run brew upgrade seshat to update.");
        return Err(CliError::CommandFailed {
            command: "update".to_owned(),
            reason: "installed via Homebrew".to_owned(),
        });
    }

    let current = env!("CARGO_PKG_VERSION");

    let release_assets = fetch_release_assets()?;
    let (version, asset_url, checksums_url) = match release_assets {
        Some(assets) => assets,
        None => {
            println!("Seshat is up to date (v{current}).");
            return Ok(());
        }
    };

    if !is_newer(&version, current) {
        println!("Seshat is already up to date (v{current}).");
        return Ok(());
    }

    let expected_sha256 = fetch_checksum_for_asset(&checksums_url, &version)?;

    let temp_dir = tempfile::TempDir::new().map_err(|e| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("failed to create temp directory: {e}"),
    })?;

    let download_path = temp_dir
        .path()
        .join(format!("seshat.{}", archive_extension(current_target())));
    download_with_progress(&asset_url, &download_path)?;

    verify_sha256(&download_path, &expected_sha256).inspect_err(|_| {
        let _ = fs::remove_dir_all(temp_dir.path());
    })?;

    let binary_path =
        extract_binary(&download_path, temp_dir.path(), &version).inspect_err(|_| {
            let _ = fs::remove_dir_all(temp_dir.path());
        })?;

    preflight_check(&binary_path, temp_dir.path())?;

    let target_exe = resolve_target_exe()?;

    replace_binary(&binary_path, &target_exe, temp_dir.path())?;

    if is_cargo_install() {
        println!(
            "Note: seshat was installed via cargo. You may want to run 'cargo install seshat' to keep ~/.cargo/.crates2.json in sync."
        );
    }

    println!("Seshat updated to v{version}.");
    Ok(())
}

fn detect_install_method() -> Result<InstallMethod, CliError> {
    if cfg!(target_os = "windows") {
        return Ok(InstallMethod::Direct);
    }

    let exe_path = std::env::current_exe().map_err(|e| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("cannot determine current executable: {e}"),
    })?;

    if exe_path.to_string_lossy().contains("/Cellar/") {
        return Ok(InstallMethod::Homebrew);
    }

    if let Ok(canonical) = exe_path.canonicalize() {
        if canonical.to_string_lossy().contains("/Cellar/") {
            return Ok(InstallMethod::Homebrew);
        }
    }

    Ok(InstallMethod::Direct)
}

fn fetch_release_assets() -> Result<Option<(String, String, String)>, CliError> {
    let agent = build_agent();

    let response = agent
        .get(GITHUB_RELEASES_API)
        .header("User-Agent", USER_AGENT)
        .call()
        .map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to fetch release info: {e}"),
        })?;

    let status = response.status().into();
    let headers = response.headers().clone();
    check_response_status(status, &headers)?;

    let body = response
        .into_body()
        .read_to_string()
        .map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to read release info: {e}"),
        })?;

    let json: serde_json::Value =
        serde_json::from_str(&body).map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to parse release info: {e}"),
        })?;

    let tag_name = json["tag_name"].as_str().unwrap_or("v0.0.0");
    let version = tag_name.strip_prefix('v').unwrap_or(tag_name).to_owned();

    let target = current_target();
    if target == "unsupported" {
        return Err(CliError::CommandFailed {
            command: "update".to_owned(),
            reason: "unsupported platform for self-update".to_owned(),
        });
    }

    let assets = json["assets"]
        .as_array()
        .ok_or_else(|| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: "no assets found in release".to_owned(),
        })?;

    let checksums_url = find_checksums_url(assets, &version)?;

    let binary_asset = find_binary_asset(assets, target, &version);
    match binary_asset {
        Some((_, asset_url)) => Ok(Some((version, asset_url, checksums_url))),
        None => Ok(None),
    }
}

fn find_checksums_url(assets: &[serde_json::Value], version: &str) -> Result<String, CliError> {
    let mut best: Option<String> = None;

    for asset in assets {
        let name = asset["name"].as_str().unwrap_or("");
        if name == "sha256sums.txt" || name.contains("sha256sums") {
            let url = asset["browser_download_url"]
                .as_str()
                .map(|u| u.to_owned())
                .ok_or_else(|| CliError::CommandFailed {
                    command: "update".to_owned(),
                    reason: "no download URL for checksums file".to_owned(),
                })?;

            if name.contains(version) {
                return Ok(url);
            }
            if best.is_none() {
                best = Some(url);
            }
        }
    }

    best.ok_or_else(|| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: "checksums file not found in release assets".to_owned(),
    })
}

fn find_binary_asset(
    assets: &[serde_json::Value],
    target: &str,
    version: &str,
) -> Option<(String, String)> {
    // Match the exact canonical archive name produced by `release.yml`:
    // `seshat-{target}-v{version}.{ext}`. The previous matcher was a loose
    // `name.contains(target) && extension_match`, which allowed sibling
    // artefacts (`...-pdb.zip` debug-symbol bundles, `...-debug.tar.gz`,
    // ordering-dependent shadowing) to pre-empt the real binary on the
    // first-match-wins iteration. A strict equality match means the only
    // way to ship a binary is to upload it under its canonical name.
    let expected = format!(
        "seshat-{target}-v{version}.{ext}",
        ext = archive_extension(target),
    );
    let expected_lower = expected.to_ascii_lowercase();

    assets.iter().find_map(|asset| {
        let name = asset["name"].as_str().unwrap_or("");
        if name.to_ascii_lowercase() == expected_lower {
            let url = asset["browser_download_url"].as_str()?;
            Some((name.to_owned(), url.to_owned()))
        } else {
            None
        }
    })
}

fn fetch_checksum_for_asset(checksums_url: &str, version: &str) -> Result<String, CliError> {
    let agent = build_agent();

    let response = agent
        .get(checksums_url)
        .header("User-Agent", USER_AGENT)
        .call()
        .map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to download checksums: {e}"),
        })?;

    let status = response.status().into();
    let headers = response.headers().clone();
    check_response_status(status, &headers)?;

    let body = response
        .into_body()
        .read_to_string()
        .map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to read checksums: {e}"),
        })?;

    let target = current_target();
    let extension = archive_extension(target);
    let expected_archive = format!("seshat-{target}-v{version}.{extension}");

    for line in body.lines() {
        let mut trimmed = line.trim();
        if let Some(stripped) = trimmed.strip_prefix('*') {
            trimmed = stripped;
        }
        if let Some((hex, filename)) = trimmed.split_once([' ', '\t']) {
            let filename = filename.trim();
            if filename == expected_archive || filename.ends_with(&expected_archive) {
                return Ok(hex.to_owned());
            }
        }
    }

    Err(CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("checksum not found for {expected_archive}"),
    })
}

fn download_with_progress(url: &str, dest: &Path) -> Result<(), CliError> {
    let agent = build_agent();

    let response = agent
        .get(url)
        .header("User-Agent", USER_AGENT)
        .call()
        .map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to download binary: {e}"),
        })?;

    let status = response.status().into();
    let headers = response.headers().clone();
    check_response_status(status, &headers)?;

    let total_size = response
        .headers()
        .get("Content-Length")
        .and_then(|v| v.to_str().ok().and_then(|s| s.parse().ok()))
        .unwrap_or(0u64);

    let style = if total_size > 0 {
        ProgressBar::new(total_size)
    } else {
        ProgressBar::new_spinner()
    };
    let pb = style;
    if total_size > 0 {
        pb.set_style(
            ProgressStyle::with_template(
                "{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})",
            )
            .unwrap()
            .progress_chars("#>-"),
        );
    } else {
        pb.set_style(
            ProgressStyle::with_template("{spinner:.green} [{elapsed_precise}] {bytes} (? eta)")
                .unwrap(),
        );
    }

    let mut file = fs::File::create(dest).map_err(|e| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("failed to create download file: {e}"),
    })?;

    let mut reader = response.into_body().into_reader();
    let mut downloaded = 0u64;

    loop {
        let mut buf = [0u8; 8192];
        let read = reader.read(&mut buf).map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("download interrupted: {e}"),
        })?;
        if read == 0 {
            break;
        }
        file.write_all(&buf[..read])
            .map_err(|e| CliError::CommandFailed {
                command: "update".to_owned(),
                reason: format!("failed to write download: {e}"),
            })?;
        downloaded += read as u64;
        if total_size > 0 {
            pb.set_position(downloaded);
        } else {
            pb.set_message(format!("Downloaded {downloaded} bytes"));
        }
    }

    if downloaded == 0 {
        let _ = fs::remove_file(dest);
        return Err(CliError::CommandFailed {
            command: "update".to_owned(),
            reason: "downloaded file is empty (0 bytes)".to_owned(),
        });
    }

    pb.finish_with_message("Download complete");
    Ok(())
}

fn verify_sha256(file_path: &Path, expected: &str) -> Result<(), CliError> {
    let mut file = fs::File::open(file_path).map_err(|e| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("cannot open file for verification: {e}"),
    })?;

    let mut hasher = Sha256::new();
    let mut buf = [0u8; 8192];
    loop {
        let n = file.read(&mut buf).map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to read file for hashing: {e}"),
        })?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }

    let hash = hasher.finalize();
    let mut computed = String::with_capacity(hash.len() * 2);
    for byte in hash {
        use std::fmt::Write;
        let _ = write!(computed, "{byte:02x}");
    }

    if computed.eq_ignore_ascii_case(expected) {
        Ok(())
    } else {
        Err(CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("SHA256 mismatch: expected {expected}, computed {computed}"),
        })
    }
}

fn extract_binary(
    archive_path: &Path,
    dest_dir: &Path,
    version: &str,
) -> Result<PathBuf, CliError> {
    let archive_file = fs::File::open(archive_path).map_err(|e| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("failed to open archive for extraction: {e}"),
    })?;

    let name = archive_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("");
    if name.ends_with(".zip") {
        extract_zip(archive_file, dest_dir)?;
    } else {
        extract_tar_gz(archive_file, dest_dir)?;
    }

    let target = current_target();
    let expected_dir = format!("seshat-{target}-v{version}");
    let binary_path = dest_dir
        .join(&expected_dir)
        .join(format!("seshat{}", std::env::consts::EXE_SUFFIX));

    if !binary_path.is_file() {
        return Err(CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!(
                "extracted binary not found at expected path: {}",
                binary_path.display()
            ),
        });
    }

    set_executable(&binary_path)?;

    Ok(binary_path)
}

fn extract_tar_gz(archive_file: fs::File, dest_dir: &Path) -> Result<(), CliError> {
    let decoder = GzDecoder::new(archive_file);
    let mut archive = Archive::new(decoder);

    for entry in archive.entries().map_err(|e| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("failed to read archive entries: {e}"),
    })? {
        let mut entry = entry.map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to read archive entry: {e}"),
        })?;

        let path = entry.path().map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to resolve archive entry path: {e}"),
        })?;

        if path.as_os_str().is_empty() {
            continue;
        }

        if path
            .components()
            .any(|c| matches!(c, std::path::Component::ParentDir))
        {
            continue;
        }

        let abs_path = dest_dir.join(&path);
        let Ok(canonical) = abs_path.canonicalize() else {
            entry
                .unpack_in(dest_dir)
                .map_err(|e| CliError::CommandFailed {
                    command: "update".to_owned(),
                    reason: format!("failed to extract entry: {e}"),
                })?;
            continue;
        };

        if !canonical.starts_with(dest_dir) {
            continue;
        }

        entry
            .unpack_in(dest_dir)
            .map_err(|e| CliError::CommandFailed {
                command: "update".to_owned(),
                reason: format!("failed to extract entry: {e}"),
            })?;
    }

    Ok(())
}

/// Verify that `abs_path` resolves inside `canonical_dest_dir`, even when the
/// leaf or some ancestors do not yet exist on disk.
///
/// The previous guard called `abs_path.canonicalize()` directly, which returns
/// `Err` for paths whose final component is missing — and the surrounding
/// `if let Ok(_) = ...` silently skipped the check. That left two real attack
/// shapes uncovered:
///
/// 1. **Symlink-via-zip**: a previous entry creates `dest_dir/link -> /etc`,
///    and a later entry `link/file` resolves through the symlink.
/// 2. **Brand-new escape paths**: an entry whose parent directory does not yet
///    exist sails past the existence-gated check entirely.
///
/// This helper walks the ancestor chain bottom-up to find the deepest
/// component that *does* exist, canonicalises that ancestor (which follows
/// symlinks), and rejects the entry unless the canonical form still lives
/// under `canonical_dest_dir`. `dest_dir` always exists, so the loop is
/// bounded.
fn path_stays_inside_dest(abs_path: &Path, canonical_dest_dir: &Path) -> bool {
    let mut probe: &Path = abs_path;
    loop {
        if probe.exists() {
            return match probe.canonicalize() {
                Ok(canonical) => canonical.starts_with(canonical_dest_dir),
                Err(_) => false,
            };
        }
        match probe.parent() {
            Some(parent) if !parent.as_os_str().is_empty() => probe = parent,
            _ => return false,
        }
    }
}

/// Hard cap on per-entry decompressed size for zip extraction. Defends
/// against zip-bomb release artefacts: a small archive with gigabytes of
/// decompressed payload would otherwise exhaust disk before SHA256
/// verification mattered. The Windows release `.zip` ships a single
/// `seshat.exe` measured in tens of MB; 256 MiB leaves generous headroom
/// for a debug binary or future bundled assets.
const MAX_ZIP_ENTRY_SIZE: u64 = 256 * 1024 * 1024;

fn extract_zip(archive_file: fs::File, dest_dir: &Path) -> Result<(), CliError> {
    extract_zip_with_limit(archive_file, dest_dir, MAX_ZIP_ENTRY_SIZE)
}

fn extract_zip_with_limit(
    archive_file: fs::File,
    dest_dir: &Path,
    max_entry_size: u64,
) -> Result<(), CliError> {
    let mut archive = zip::ZipArchive::new(archive_file).map_err(|e| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("failed to read zip archive: {e}"),
    })?;

    let canonical_dest_dir = dest_dir
        .canonicalize()
        .map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to canonicalise extraction directory: {e}"),
        })?;

    for i in 0..archive.len() {
        let mut entry = archive.by_index(i).map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to read zip entry: {e}"),
        })?;

        let raw_name = entry.name().to_owned();
        if raw_name.is_empty() {
            continue;
        }

        let entry_path = match entry.enclosed_name() {
            Some(p) => p,
            None => continue,
        };

        if entry_path.as_os_str().is_empty() {
            continue;
        }

        if entry_path
            .components()
            .any(|c| matches!(c, std::path::Component::ParentDir))
        {
            continue;
        }

        let abs_path = dest_dir.join(&entry_path);
        if !path_stays_inside_dest(&abs_path, &canonical_dest_dir) {
            continue;
        }

        // Skip symlink entries unconditionally. The release pipeline never
        // emits symlinks; honouring them would either materialise an actual
        // symlink (a fresh escape vector for the next entry to traverse
        // through) or, as the previous code did, write the link target as
        // regular file content and apply symlink mode bits to a normal file
        // — both incorrect.
        if entry.is_symlink() {
            continue;
        }

        if entry.is_dir() {
            fs::create_dir_all(&abs_path).map_err(|e| CliError::CommandFailed {
                command: "update".to_owned(),
                reason: format!("failed to create directory: {e}"),
            })?;
            continue;
        }

        if let Some(parent) = abs_path.parent() {
            fs::create_dir_all(parent).map_err(|e| CliError::CommandFailed {
                command: "update".to_owned(),
                reason: format!("failed to create directory: {e}"),
            })?;
        }

        // Cheap pre-check on the declared size. Most legitimate archives
        // report `entry.size()` accurately; a malicious archive that
        // under-reports is still caught by the post-copy bounded check
        // below (we copy at most max_entry_size + 1 bytes and abort if the
        // overflow byte was consumed).
        if entry.size() > max_entry_size {
            return Err(CliError::CommandFailed {
                command: "update".to_owned(),
                reason: format!(
                    "zip entry exceeds maximum decompressed size of {max_entry_size} bytes \
                     (entry declares {} bytes)",
                    entry.size()
                ),
            });
        }

        let mut out = fs::File::create(&abs_path).map_err(|e| CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to create extracted file: {e}"),
        })?;
        let written = {
            // Scope the `Take` adapter so the `&mut entry` borrow ends before
            // we reach `entry.unix_mode()` below.
            let mut limited = (&mut entry).take(max_entry_size + 1);
            std::io::copy(&mut limited, &mut out).map_err(|e| CliError::CommandFailed {
                command: "update".to_owned(),
                reason: format!("failed to extract zip entry: {e}"),
            })?
        };
        if written > max_entry_size {
            // Drop the partially-written file before reporting; otherwise a
            // later fsync or the caller's cleanup could touch a half-written
            // attacker-controlled blob.
            drop(out);
            let _ = fs::remove_file(&abs_path);
            return Err(CliError::CommandFailed {
                command: "update".to_owned(),
                reason: format!(
                    "zip entry exceeds maximum decompressed size of {max_entry_size} bytes"
                ),
            });
        }

        #[cfg(unix)]
        if let Some(mode) = entry.unix_mode() {
            use std::os::unix::fs::PermissionsExt;
            let _ = fs::set_permissions(&abs_path, fs::Permissions::from_mode(mode));
        }
    }

    Ok(())
}

#[cfg(unix)]
fn set_executable(path: &Path) -> Result<(), CliError> {
    use std::os::unix::fs::PermissionsExt;
    let metadata = fs::metadata(path).map_err(|e| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("failed to read binary metadata: {e}"),
    })?;
    let mut perms = metadata.permissions();
    perms.set_mode(0o755);
    fs::set_permissions(path, perms).map_err(|e| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("failed to set executable permission: {e}"),
    })?;
    Ok(())
}

#[cfg(not(unix))]
fn set_executable(_path: &Path) -> Result<(), CliError> {
    Ok(())
}

fn preflight_check(binary_path: &Path, temp_dir: &Path) -> Result<(), CliError> {
    let output = ProcessCommand::new(binary_path)
        .arg("--version")
        .output()
        .map_err(|e| {
            let _ = fs::remove_dir_all(temp_dir);
            CliError::CommandFailed {
                command: "update".to_owned(),
                reason: format!("failed to run extracted binary: {e}"),
            }
        })?;

    if output.status.success() {
        return Ok(());
    }

    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        match output.status.signal() {
            Some(9) => {
                let _ = fs::remove_dir_all(temp_dir);
                eprintln!(
                    "macOS Gatekeeper blocked the update binary. Remove quarantine with:\n  xattr -d com.apple.quarantine {}",
                    binary_path.display()
                );
                return Err(CliError::CommandFailed {
                    command: "update".to_owned(),
                    reason: "macOS Gatekeeper killed the binary (signal 9)".to_owned(),
                });
            }
            Some(sig) => {
                let _ = fs::remove_dir_all(temp_dir);
                return Err(CliError::CommandFailed {
                    command: "update".to_owned(),
                    reason: format!("extracted binary terminated by signal {sig}"),
                });
            }
            None => {}
        }
    }

    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    if version_output_contains_seshat(&stdout) || version_output_contains_seshat(&stderr) {
        return Ok(());
    }

    let _ = fs::remove_dir_all(temp_dir);
    Err(CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!(
            "extracted binary failed preflight: exit code {:?}",
            output.status.code()
        ),
    })
}

fn version_output_contains_seshat(output: &str) -> bool {
    let lower = output.to_lowercase();
    if let Some(idx) = lower.find("seshat") {
        let after = &lower[idx + "seshat".len()..];
        return after
            .trim_start()
            .starts_with(|c: char| c.is_ascii_digit() || c == 'v');
    }
    false
}

fn resolve_target_exe() -> Result<PathBuf, CliError> {
    let exe = std::env::current_exe().map_err(|e| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("cannot determine current executable: {e}"),
    })?;

    exe.canonicalize().map_err(|e| CliError::CommandFailed {
        command: "update".to_owned(),
        reason: format!("cannot resolve current executable path: {e}"),
    })
}

fn replace_binary(new_binary: &Path, target_exe: &Path, temp_dir: &Path) -> Result<(), CliError> {
    match self_replace::self_replace(new_binary) {
        Ok(()) => Ok(()),
        Err(e) => {
            let _ = fs::remove_dir_all(temp_dir);
            Err(map_replace_error(e, target_exe))
        }
    }
}

fn map_replace_error(e: std::io::Error, target_exe: &Path) -> CliError {
    if e.kind() == std::io::ErrorKind::PermissionDenied {
        #[cfg(windows)]
        let hint = "Try running as Administrator.";
        #[cfg(not(windows))]
        let hint = "Try: sudo seshat update";
        eprintln!(
            "Permission denied updating {}. {hint}",
            target_exe.display()
        );
        #[cfg(windows)]
        let reason = "permission denied; try running as Administrator".to_owned();
        #[cfg(not(windows))]
        let reason = "permission denied; try sudo seshat update".to_owned();
        CliError::CommandFailed {
            command: "update".to_owned(),
            reason,
        }
    } else {
        CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!("failed to replace binary: {e}"),
        }
    }
}

/// Best-effort cleanup of a leftover `<current_exe>.old` from a prior
/// Windows self-update.
///
/// On Windows, manual or recovery scenarios may leave a `seshat.exe.old`
/// next to the running `seshat.exe` (the happy-path `self_replace::self_replace`
/// flow already schedules its own relocated-binary deletion via the crate's
/// `.__selfdelete__.exe` helper, so this is purely defensive). Errors are
/// silently dropped — cleanup must never fail the user's command.
///
/// On Unix this is a no-op: atomic `rename(2)` semantics in `replace_binary`
/// never leave a `.old` file behind, so there is nothing to probe for.
pub fn cleanup_stale_old_binary() {
    #[cfg(windows)]
    if let Ok(current) = std::env::current_exe() {
        cleanup_stale_old_binary_at(&current);
    }
}

#[cfg(windows)]
fn cleanup_stale_old_binary_at(current_exe: &Path) {
    let mut stale: std::ffi::OsString = current_exe.as_os_str().to_owned();
    stale.push(".old");
    let _ = fs::remove_file(PathBuf::from(stale));
}

fn is_cargo_install() -> bool {
    let cargo_dir = if let Ok(cargo_home) = std::env::var("CARGO_HOME") {
        PathBuf::from(cargo_home)
    } else if let Some(home) = dirs::home_dir() {
        home.join(".cargo")
    } else {
        return false;
    };

    let crates2 = cargo_dir.join(".crates2.json");
    if crates2.exists() {
        if let Ok(content) = fs::read_to_string(&crates2) {
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) {
                if cargo_json_contains_seshat(&json) {
                    return true;
                }
            }
        }
    }

    let crates_toml = cargo_dir.join(".crates.toml");
    if crates_toml.exists() {
        if let Ok(content) = fs::read_to_string(&crates_toml) {
            if cargo_toml_contains_seshat(&content) {
                return true;
            }
        }
    }

    false
}

fn cargo_json_contains_seshat(json: &serde_json::Value) -> bool {
    if let Some(installs) = json.get("installs").and_then(|v| v.as_object()) {
        return installs.keys().any(|k| k.starts_with("seshat "));
    }
    false
}

fn cargo_toml_contains_seshat(content: &str) -> bool {
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('[') {
            continue;
        }
        if let Some((key, _)) = trimmed.split_once('=').or_else(|| trimmed.split_once(" =")) {
            let key = key.trim().trim_matches('"');
            if key.starts_with("seshat ") {
                return true;
            }
        }
    }
    false
}

fn build_agent() -> ureq::Agent {
    let config = ureq::Agent::config_builder()
        .timeout_global(Some(Duration::from_secs(TIMEOUT_SECS)))
        .build();
    let agent: ureq::Agent = config.into();

    if let Ok(token) = std::env::var("GITHUB_TOKEN") {
        if !token.is_empty() {
            return agent;
        }
    }

    agent
}

fn check_response_status(status: u16, headers: &ureq::http::HeaderMap) -> Result<(), CliError> {
    if status < 400 {
        return Ok(());
    }

    if let Some(info) = parse_rate_limit(status, headers) {
        return Err(CliError::CommandFailed {
            command: "update".to_owned(),
            reason: format!(
                "rate limited by GitHub. Try again in {} minutes.",
                info.retry_after_minutes
            ),
        });
    }

    let reason = if status == 404 {
        "release not found (404)".to_owned()
    } else if status >= 500 {
        format!("GitHub server error (HTTP {status})")
    } else {
        format!("HTTP {status}")
    };

    Err(CliError::CommandFailed {
        command: "update".to_owned(),
        reason,
    })
}

fn parse_rate_limit(status: u16, headers: &ureq::http::HeaderMap) -> Option<RateLimitInfo> {
    if status != 403 && status != 429 {
        return None;
    }

    let reset = headers
        .get("x-ratelimit-reset")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.parse::<u64>().ok())?;

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .ok()?
        .as_secs();

    let retry_after_minutes = if reset > now {
        ((reset - now) / 60).max(1)
    } else {
        1
    };

    Some(RateLimitInfo {
        retry_after_minutes,
    })
}

fn run_check() -> Result<(), CliError> {
    run_check_inner(&VersionCache::cache_path())
}

fn run_check_inner(cache_path: &Option<PathBuf>) -> Result<(), CliError> {
    if let Some(path) = cache_path {
        if let Some(cache) = VersionCache::read_from_path(path) {
            if cache.is_fresh() && cache.has_assets != Some(false) {
                return print_update_status(&cache.latest_version);
            }
        }
    }

    match fetch_latest_release() {
        Ok((version, has_assets)) => {
            if let Some(path) = cache_path {
                let cache = if has_assets {
                    VersionCache::with_assets(version.clone(), true)
                } else {
                    VersionCache::with_assets(env!("CARGO_PKG_VERSION").to_owned(), false)
                };
                let _ = cache.write_to_path(path);
            }

            if has_assets {
                print_update_status(&version)
            } else {
                println!("Seshat is up to date (v{}).", env!("CARGO_PKG_VERSION"));
                Ok(())
            }
        }
        Err(e) => {
            eprintln!("Could not check for updates: {e}");
            Err(CliError::CommandFailed {
                command: "update".to_owned(),
                reason: e,
            })
        }
    }
}

fn print_update_status(latest_version: &str) -> Result<(), CliError> {
    let current = env!("CARGO_PKG_VERSION");

    if is_newer(latest_version, current) {
        if detect_homebrew() {
            println!(
                "Seshat v{latest_version} is available. You installed via Homebrew. Run brew upgrade seshat."
            );
        } else {
            println!(
                "Seshat v{latest_version} is available (current: v{current}). Run seshat update to upgrade."
            );
        }
    } else {
        println!("Seshat is up to date (v{current}).");
    }

    Ok(())
}

fn fetch_latest_release() -> Result<(String, bool), String> {
    let agent = build_agent();

    let response = agent
        .get(GITHUB_RELEASES_API)
        .header("User-Agent", USER_AGENT)
        .call()
        .map_err(|e| format!("network error: {e}"))?;

    let status = response.status().into();
    let headers = response.headers().clone();

    if status >= 400 {
        if let Some(info) = parse_rate_limit(status, &headers) {
            return Err(format!(
                "rate limited by GitHub. Try again in {} minutes.",
                info.retry_after_minutes
            ));
        }
        if status == 404 {
            return Err("release not found (404)".to_owned());
        }
        return Err(format!("HTTP {status}"));
    }

    let body = response
        .into_body()
        .read_to_string()
        .map_err(|e| format!("failed to read response: {e}"))?;

    let json: serde_json::Value =
        serde_json::from_str(&body).map_err(|e| format!("failed to parse response: {e}"))?;

    // Check for GitHub error payload
    if let Some(msg) = json.get("message").and_then(|v| v.as_str()) {
        return Err(format!("GitHub API error: {msg}"));
    }

    let tag_name = json["tag_name"].as_str().unwrap_or("v0.0.0");
    let version = tag_name.strip_prefix('v').unwrap_or(tag_name);

    let has_assets = has_binary_asset_for_current_target(&json);

    Ok((version.to_owned(), has_assets))
}

fn is_newer(latest: &str, current: &str) -> bool {
    let parse =
        |v: &str| -> Vec<u32> { v.split('.').filter_map(|p| p.parse::<u32>().ok()).collect() };

    let latest_parts = parse(latest);
    let current_parts = parse(current);

    if latest_parts.is_empty() || current_parts.is_empty() {
        return false;
    }

    for (l, c) in latest_parts.iter().zip(current_parts.iter()) {
        if l > c {
            return true;
        }
        if l < c {
            return false;
        }
    }

    latest_parts.len() > current_parts.len()
}

fn current_target() -> &'static str {
    let arch = std::env::consts::ARCH;
    let os = std::env::consts::OS;
    match (arch, os) {
        ("aarch64", "macos") => "aarch64-apple-darwin",
        ("x86_64", "macos") => "x86_64-apple-darwin",
        ("x86_64", "linux") => {
            if is_musl() {
                "x86_64-unknown-linux-musl"
            } else {
                "x86_64-unknown-linux-gnu"
            }
        }
        ("aarch64", "linux") => {
            if is_musl() {
                "aarch64-unknown-linux-musl"
            } else {
                "aarch64-unknown-linux-gnu"
            }
        }
        ("x86_64", "windows") => "x86_64-pc-windows-msvc",
        _ => "unsupported",
    }
}

/// Archive extension for the release artifact of `target`.
///
/// Centralises the "is this a zip target?" predicate so the download path,
/// checksum lookup, and asset matcher cannot drift out of sync. Returns
/// `"zip"` for Windows MSVC targets (which are packaged via `7z` in
/// `release.yml`), and `"tar.gz"` for all Unix targets.
fn archive_extension(target: &str) -> &'static str {
    if target.ends_with("windows-msvc") {
        "zip"
    } else {
        "tar.gz"
    }
}

fn is_musl() -> bool {
    #[cfg(target_os = "linux")]
    {
        std::fs::read_dir("/lib")
            .ok()
            .and_then(|entries| {
                for entry in entries.flatten() {
                    let name = entry.file_name();
                    if let Some(name_str) = name.to_str() {
                        if name_str.contains("ld-musl") {
                            return Some(true);
                        }
                    }
                }
                None
            })
            .unwrap_or(false)
    }
    #[cfg(not(target_os = "linux"))]
    {
        false
    }
}

fn has_binary_asset_for_current_target(json: &serde_json::Value) -> bool {
    let target = current_target();
    if target == "unsupported" {
        return false;
    }

    if let Some(assets) = json["assets"].as_array() {
        assets.iter().any(|asset| {
            asset["name"]
                .as_str()
                .is_some_and(|name| name.contains(target))
        })
    } else {
        false
    }
}

fn detect_homebrew() -> bool {
    match std::env::current_exe() {
        Ok(path) => {
            if path.to_string_lossy().contains("/Cellar/") {
                return true;
            }
            if let Ok(canonical) = path.canonicalize() {
                canonical.to_string_lossy().contains("/Cellar/")
            } else {
                false
            }
        }
        Err(_) => false,
    }
}

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

    #[test]
    fn newer_major_version() {
        assert!(is_newer("2.0.0", "1.0.0"));
    }

    #[test]
    fn older_major_version() {
        assert!(!is_newer("1.0.0", "2.0.0"));
    }

    #[test]
    fn same_version() {
        assert!(!is_newer("1.0.0", "1.0.0"));
    }

    #[test]
    fn newer_minor_version() {
        assert!(is_newer("1.1.0", "1.0.0"));
    }

    #[test]
    fn newer_patch_version() {
        assert!(is_newer("1.0.1", "1.0.0"));
    }

    #[test]
    fn newer_with_extra_component() {
        assert!(is_newer("1.0.0.1", "1.0.0"));
    }

    #[test]
    fn older_with_fewer_components() {
        assert!(!is_newer("1.0", "1.0.0"));
    }

    #[test]
    fn invalid_versions_compare_equal() {
        assert!(!is_newer("abc", "1.0.0"));
        assert!(!is_newer("1.0.0", "abc"));
    }

    #[test]
    fn current_target_is_known_on_main_platforms() {
        let target = current_target();
        #[cfg(any(
            target_os = "macos",
            target_os = "linux",
            all(target_os = "windows", target_arch = "x86_64"),
        ))]
        assert_ne!(target, "unsupported");
        #[cfg(all(target_os = "windows", target_arch = "x86_64"))]
        assert_eq!(target, "x86_64-pc-windows-msvc");
    }

    #[test]
    fn archive_extension_matches_target_platform() {
        assert_eq!(archive_extension("x86_64-pc-windows-msvc"), "zip");
        assert_eq!(archive_extension("aarch64-pc-windows-msvc"), "zip");
        assert_eq!(archive_extension("x86_64-unknown-linux-gnu"), "tar.gz");
        assert_eq!(archive_extension("x86_64-unknown-linux-musl"), "tar.gz");
        assert_eq!(archive_extension("aarch64-apple-darwin"), "tar.gz");
        assert_eq!(archive_extension("x86_64-apple-darwin"), "tar.gz");
    }

    /// Regression test for the hardcoded `seshat.tar.gz` download filename
    /// bug: `extract_binary` dispatches on the file extension, so the
    /// download path must use `.zip` on Windows-MSVC and `.tar.gz` elsewhere.
    /// If this invariant breaks, `extract_binary` will feed zip bytes to
    /// `GzDecoder` (or vice versa) and the user-facing update flow fails
    /// even though every fixture-based test still passes.
    #[test]
    fn download_filename_extension_matches_extract_dispatch() {
        for target in [
            "x86_64-pc-windows-msvc",
            "x86_64-unknown-linux-gnu",
            "x86_64-unknown-linux-musl",
            "aarch64-apple-darwin",
            "x86_64-apple-darwin",
        ] {
            let filename = format!("seshat.{}", archive_extension(target));
            if archive_extension(target) == "zip" {
                assert!(
                    filename.ends_with(".zip"),
                    "download filename for {target} must end with .zip"
                );
            } else {
                assert!(
                    filename.ends_with(".tar.gz"),
                    "download filename for {target} must end with .tar.gz"
                );
            }
        }
    }

    #[test]
    fn has_binary_asset_returns_true_when_matching() {
        let target = current_target();
        if target == "unsupported" {
            return;
        }
        let json = serde_json::json!({
            "tag_name": "v1.0.0",
            "assets": [
                {"name": format!("seshat-{target}-v1.0.0.tar.gz")},
            ]
        });
        assert!(has_binary_asset_for_current_target(&json));
    }

    #[test]
    fn has_binary_asset_returns_false_when_no_match() {
        let json = serde_json::json!({
            "tag_name": "v1.0.0",
            "assets": [
                {"name": "seshat-wasm32-unknown-unknown-v1.0.0.tar.gz"},
            ]
        });
        assert!(!has_binary_asset_for_current_target(&json));
    }

    #[test]
    fn has_binary_asset_empty_assets() {
        let json = serde_json::json!({
            "tag_name": "v1.0.0",
            "assets": []
        });
        assert!(!has_binary_asset_for_current_target(&json));
    }

    #[test]
    fn has_binary_asset_unsupported_target() {
        let json = serde_json::json!({
            "tag_name": "v1.0.0",
            "assets": [
                {"name": "seshat-some-target-v1.0.0.tar.gz"},
            ]
        });
        let _ = has_binary_asset_for_current_target(&json);
    }

    #[test]
    fn detect_homebrew_is_bool() {
        let _ = detect_homebrew();
    }

    #[test]
    fn fresh_cache_no_network() {
        let dir = tempfile::TempDir::new().unwrap();
        let cache_path = dir.path().join("version-check.json");
        let cache = VersionCache::new("99.99.99".to_owned());
        cache.write_to_path(&cache_path).unwrap();

        let result = run_check_inner(&Some(cache_path));
        assert!(result.is_ok());
    }

    #[test]
    fn detect_install_method_on_current_platform() {
        let method = detect_install_method();
        assert!(method.is_ok());
        assert_eq!(method.unwrap(), InstallMethod::Direct);
    }

    #[test]
    fn install_method_enum_equality() {
        assert_eq!(InstallMethod::Homebrew, InstallMethod::Homebrew);
        assert_eq!(InstallMethod::Direct, InstallMethod::Direct);
        assert_ne!(InstallMethod::Homebrew, InstallMethod::Direct);
    }

    #[test]
    fn sha256_verify_matching() {
        let dir = tempfile::TempDir::new().unwrap();
        let file_path = dir.path().join("test.bin");
        fs::write(&file_path, b"hello world").unwrap();

        let mut hasher = Sha256::new();
        hasher.update(b"hello world");
        let hash = hasher.finalize();
        let mut hex = String::new();
        for byte in hash {
            use std::fmt::Write;
            let _ = write!(hex, "{byte:02x}");
        }

        assert!(verify_sha256(&file_path, &hex).is_ok());
    }

    #[test]
    fn sha256_verify_mismatch() {
        let dir = tempfile::TempDir::new().unwrap();
        let file_path = dir.path().join("test.bin");
        fs::write(&file_path, b"hello world").unwrap();

        let result = verify_sha256(
            &file_path,
            "0000000000000000000000000000000000000000000000000000000000000000",
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("SHA256 mismatch"));
    }

    // Unix-only: `extract_binary` exists to support the `seshat update`
    // self-update flow, whose `current_target()` only enumerates Unix
    // triples (Windows resolves to "unsupported"). The fixture archive
    // also encodes a `0o755` mode bit which tar's Windows backend cannot
    // round-trip cleanly. Coverage on Windows for this code path would
    // be misleading.
    #[cfg(unix)]
    #[test]
    fn extract_binary_from_valid_tar_gz() {
        let dir = tempfile::TempDir::new().unwrap();
        let archive_path = dir.path().join("test.tar.gz");

        let file = fs::File::create(&archive_path).unwrap();
        let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default());
        let mut builder = tar::Builder::new(encoder);

        let expected_dir = format!("seshat-{}-v1.0.0", current_target());
        let binary_dir = format!("{expected_dir}/seshat");

        let mut header = tar::Header::new_gnu();
        header.set_entry_type(tar::EntryType::Directory);
        header.set_size(0);
        builder
            .append_data(&mut header, &expected_dir, &[][..])
            .unwrap();

        let mut header = tar::Header::new_gnu();
        header.set_size(4);
        header.set_mode(0o755);
        builder
            .append_data(&mut header, &binary_dir, &b"fake"[..])
            .unwrap();

        let archive_data = builder.into_inner().unwrap().finish().unwrap();
        drop(archive_data);

        let result = extract_binary(&archive_path, dir.path(), "1.0.0");
        assert!(result.is_ok());
        let binary_path = result.unwrap();
        assert!(binary_path.is_file());
        assert!(binary_path.ends_with(format!("{expected_dir}/seshat")));
    }

    #[test]
    fn extract_binary_corrupted_archive_errors() {
        let dir = tempfile::TempDir::new().unwrap();
        let archive_path = dir.path().join("corrupt.tar.gz");
        fs::write(&archive_path, b"not a valid gzip file").unwrap();

        let result = extract_binary(&archive_path, dir.path(), "1.0.0");
        assert!(result.is_err());
    }

    fn build_zip_archive(entries: &[(&str, &[u8])]) -> Vec<u8> {
        use std::io::Cursor;
        use zip::write::SimpleFileOptions;

        let mut buf = Vec::new();
        {
            let cursor = Cursor::new(&mut buf);
            let mut writer = zip::ZipWriter::new(cursor);
            let opts =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
            for (name, data) in entries {
                if name.ends_with('/') {
                    writer.add_directory(*name, opts).unwrap();
                } else {
                    writer.start_file(*name, opts).unwrap();
                    writer.write_all(data).unwrap();
                }
            }
            writer.finish().unwrap();
        }
        buf
    }

    #[test]
    fn extract_binary_from_valid_zip() {
        let dir = tempfile::TempDir::new().unwrap();
        let archive_path = dir.path().join("test.zip");

        let expected_dir = format!("seshat-{}-v1.0.0", current_target());
        let binary_in_zip = format!("{expected_dir}/seshat{}", std::env::consts::EXE_SUFFIX);
        let dir_entry = format!("{expected_dir}/");

        let bytes = build_zip_archive(&[(&dir_entry, &[]), (&binary_in_zip, b"fake")]);
        fs::write(&archive_path, &bytes).unwrap();

        let result = extract_binary(&archive_path, dir.path(), "1.0.0");
        assert!(result.is_ok(), "extract_binary failed: {result:?}");
        let binary_path = result.unwrap();
        assert!(binary_path.is_file());
        assert!(binary_path.ends_with(format!(
            "{expected_dir}/seshat{}",
            std::env::consts::EXE_SUFFIX
        )));
    }

    #[test]
    fn extract_binary_corrupted_zip_errors() {
        let dir = tempfile::TempDir::new().unwrap();
        let archive_path = dir.path().join("corrupt.zip");
        fs::write(&archive_path, b"definitely not a zip file").unwrap();

        let result = extract_binary(&archive_path, dir.path(), "1.0.0");
        assert!(result.is_err());
    }

    #[test]
    fn extract_binary_zip_skips_path_traversal() {
        let dir = tempfile::TempDir::new().unwrap();
        let archive_path = dir.path().join("traversal.zip");

        let traversal_name = format!("../escape/seshat{}", std::env::consts::EXE_SUFFIX);
        let bytes = build_zip_archive(&[(&traversal_name, b"evil")]);
        fs::write(&archive_path, &bytes).unwrap();

        let result = extract_binary(&archive_path, dir.path(), "1.0.0");
        assert!(
            result.is_err(),
            "expected missing-binary error, got {result:?}"
        );
        let escape_path = dir
            .path()
            .parent()
            .unwrap()
            .join("escape")
            .join(format!("seshat{}", std::env::consts::EXE_SUFFIX));
        assert!(
            !escape_path.exists(),
            "traversal entry was extracted to {}",
            escape_path.display()
        );
    }

    #[test]
    fn path_stays_inside_dest_accepts_normal_relative_paths() {
        let dir = tempfile::TempDir::new().unwrap();
        let canonical = dir.path().canonicalize().unwrap();
        let leaf = dir.path().join("subdir").join("file.txt");
        assert!(path_stays_inside_dest(&leaf, &canonical));
    }

    #[test]
    fn path_stays_inside_dest_rejects_path_outside_dest() {
        let dir = tempfile::TempDir::new().unwrap();
        let canonical = dir.path().canonicalize().unwrap();
        let outside = std::env::temp_dir().join("definitely-not-in-dest");
        assert!(!path_stays_inside_dest(&outside, &canonical));
    }

    #[cfg(unix)]
    #[test]
    fn path_stays_inside_dest_rejects_path_resolving_through_symlink() {
        let dir = tempfile::TempDir::new().unwrap();
        let outside = tempfile::TempDir::new().unwrap();
        let canonical = dir.path().canonicalize().unwrap();

        std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();

        // The leaf doesn't exist yet; the ancestor `link` does and resolves
        // outside `canonical_dest_dir`. The previous canonicalize-only guard
        // returned `Err` here and silently allowed the entry.
        let leaf = dir.path().join("link").join("payload.txt");
        assert!(!path_stays_inside_dest(&leaf, &canonical));
    }

    /// Walk every regular file under `dir` and return their relative paths
    /// (sorted). Test helper for "no escape happened" assertions: the
    /// previous `extract_binary_zip_skips_path_traversal` only checked one
    /// specific escape destination, so a traversal that landed elsewhere
    /// would silently pass.
    fn collect_regular_files(dir: &Path) -> Vec<PathBuf> {
        fn walk(d: &Path, out: &mut Vec<PathBuf>, root: &Path) {
            let entries = match fs::read_dir(d) {
                Ok(e) => e,
                Err(_) => return,
            };
            for entry in entries.flatten() {
                let path = entry.path();
                let metadata = match fs::symlink_metadata(&path) {
                    Ok(m) => m,
                    Err(_) => continue,
                };
                if metadata.file_type().is_dir() {
                    walk(&path, out, root);
                } else if metadata.file_type().is_file() {
                    if let Ok(rel) = path.strip_prefix(root) {
                        out.push(rel.to_path_buf());
                    }
                }
            }
        }
        let mut out = Vec::new();
        walk(dir, &mut out, dir);
        out.sort();
        out
    }

    /// Stronger version of the original traversal test: assert via a full
    /// filesystem walk that the zip's malicious `../escape/...` entry left
    /// nothing inside `dest_dir` and that no file appeared anywhere on the
    /// containing temp parent. The original test only probed a single hard-
    /// coded escape destination.
    #[test]
    fn extract_zip_path_traversal_leaves_no_files_anywhere() {
        let dir = tempfile::TempDir::new().unwrap();
        let bytes = build_zip_archive(&[("../escape/seshat.bin", b"evil")]);
        let archive_path = dir.path().join("traversal.zip");
        fs::write(&archive_path, &bytes).unwrap();

        let archive_file = fs::File::open(&archive_path).unwrap();
        extract_zip(archive_file, dir.path()).unwrap();

        // Inside dest_dir: only the archive file we just wrote.
        let inside = collect_regular_files(dir.path());
        assert_eq!(
            inside,
            vec![PathBuf::from("traversal.zip")],
            "unexpected files inside dest_dir after traversal attempt: {inside:?}"
        );

        // Outside dest_dir but still under the temp parent: nothing under
        // any sibling `escape` directory the malicious entry might have
        // created.
        if let Some(parent) = dir.path().parent() {
            let escape_root = parent.join("escape");
            assert!(
                !escape_root.exists(),
                "traversal entry materialised under {}",
                escape_root.display()
            );
        }
    }

    /// `..` components in the middle of an entry path get normalised by the
    /// zip writer at archive-creation time (`good/../bad/file` -> `bad/file`).
    /// The extractor sees only the normalised path, which lands safely
    /// inside `dest_dir`. This test locks that behaviour: nothing escapes,
    /// and the file appears at its post-normalisation location.
    #[test]
    fn extract_zip_handles_normalised_parent_dir_in_middle() {
        let dir = tempfile::TempDir::new().unwrap();
        let bytes = build_zip_archive(&[("good/../bad/seshat.bin", b"ok")]);
        let archive_path = dir.path().join("midtraversal.zip");
        fs::write(&archive_path, &bytes).unwrap();

        let archive_file = fs::File::open(&archive_path).unwrap();
        extract_zip(archive_file, dir.path()).unwrap();

        // Only files that resolve inside `dest_dir`. `bad/seshat.bin` is the
        // post-normalisation location; nothing must appear at `good/...` or
        // outside `dest_dir`.
        let inside = collect_regular_files(dir.path());
        assert!(inside.contains(&PathBuf::from("bad/seshat.bin")));
        assert!(!inside.iter().any(|p| p.starts_with("good")));
    }

    /// macOS `/tmp` is a symlink to `/private/tmp`. `path_stays_inside_dest`
    /// canonicalises both `dest_dir` and the probe ancestor, so the
    /// comparison must succeed for legitimate entries even when the caller
    /// passed a non-canonical `dest_dir`. This test would catch a regression
    /// where the canonicalisation drift made every Linux/macOS extraction
    /// fail.
    #[test]
    fn extract_zip_succeeds_when_dest_dir_path_is_non_canonical() {
        let dir = tempfile::TempDir::new().unwrap();
        // Write a deeply-nested entry whose ancestors don't exist yet.
        let bytes = build_zip_archive(&[
            ("nested/", b""),
            ("nested/sub/", b""),
            ("nested/sub/seshat.bin", b"ok"),
        ]);
        let archive_path = dir.path().join("nested.zip");
        fs::write(&archive_path, &bytes).unwrap();

        let archive_file = fs::File::open(&archive_path).unwrap();
        extract_zip(archive_file, dir.path()).unwrap();

        assert!(
            dir.path()
                .join("nested")
                .join("sub")
                .join("seshat.bin")
                .is_file()
        );
    }

    /// Build a zip archive containing a single symlink entry. Used to verify
    /// `extract_zip` skips symlink entries instead of materialising them.
    fn build_zip_with_symlink(name: &str, target: &str) -> Vec<u8> {
        use std::io::Cursor;
        use zip::write::SimpleFileOptions;

        let mut buf = Vec::new();
        {
            let cursor = Cursor::new(&mut buf);
            let mut writer = zip::ZipWriter::new(cursor);
            let opts = SimpleFileOptions::default();
            writer.add_symlink(name, target, opts).unwrap();
            writer.finish().unwrap();
        }
        buf
    }

    /// Reject entries whose declared decompressed size exceeds the cap.
    /// This is the cheap, fast path that catches well-formed but oversized
    /// entries without spending IO bandwidth.
    #[test]
    fn extract_zip_rejects_oversized_entry_by_declared_size() {
        let dir = tempfile::TempDir::new().unwrap();
        // 2 KiB payload, cap at 1 KiB.
        let payload = vec![0xAB_u8; 2048];
        let bytes = build_zip_archive(&[("payload.bin", &payload)]);
        let archive_path = dir.path().join("oversized.zip");
        fs::write(&archive_path, &bytes).unwrap();

        let archive_file = fs::File::open(&archive_path).unwrap();
        let result = extract_zip_with_limit(archive_file, dir.path(), 1024);
        assert!(
            result.is_err(),
            "oversized entry was extracted instead of rejected"
        );
        assert!(
            !dir.path().join("payload.bin").exists()
                || fs::metadata(dir.path().join("payload.bin")).unwrap().len() <= 1024,
            "oversized entry left a >cap-sized file on disk"
        );
    }

    /// The post-copy bounded read also catches archives that under-report
    /// `entry.size()` - i.e. malicious archives that lie about decompressed
    /// size to slip past the pre-check.
    #[test]
    fn extract_zip_rejects_oversized_entry_via_bounded_copy() {
        // The pre-check is sized off `entry.size()`, which the zip writer
        // sets honestly. To exercise the post-copy bound independently, we
        // run with a cap smaller than the pre-check would have caught at
        // production-default, then assert the streaming check fired and the
        // partial file was cleaned up.
        let dir = tempfile::TempDir::new().unwrap();
        let payload = vec![0xCD_u8; 4096];
        let bytes = build_zip_archive(&[("payload.bin", &payload)]);
        let archive_path = dir.path().join("oversized2.zip");
        fs::write(&archive_path, &bytes).unwrap();

        let archive_file = fs::File::open(&archive_path).unwrap();
        // Cap below payload size; pre-check fires first here, but verify
        // we didn't leave a partial extraction either way.
        let result = extract_zip_with_limit(archive_file, dir.path(), 256);
        assert!(result.is_err());
        assert!(!dir.path().join("payload.bin").exists());
    }

    /// `extract_zip` must drop symlink entries on the floor. Honouring them
    /// would either create a fresh symlink (a new escape vector for later
    /// entries to resolve through) or write the link target string as
    /// regular file content with symlink mode bits — both wrong.
    #[test]
    fn extract_zip_skips_symlink_entries() {
        let dir = tempfile::TempDir::new().unwrap();
        let bytes = build_zip_with_symlink("payload", "/etc/passwd");
        let archive_path = dir.path().join("symlink.zip");
        fs::write(&archive_path, &bytes).unwrap();

        let archive_file = fs::File::open(&archive_path).unwrap();
        extract_zip(archive_file, dir.path()).unwrap();

        let materialised = dir.path().join("payload");
        assert!(
            !materialised.exists() && fs::symlink_metadata(&materialised).is_err(),
            "symlink entry was materialised at {}",
            materialised.display()
        );
    }

    /// Regression test for the canonicalize-bypass bug. A pre-placed symlink
    /// inside `dest_dir` points outside; a zip entry uses the symlink as a
    /// path component. `extract_zip` must not write through the symlink.
    #[cfg(unix)]
    #[test]
    fn extract_zip_rejects_entry_escaping_through_existing_symlink() {
        let dir = tempfile::TempDir::new().unwrap();
        let outside = tempfile::TempDir::new().unwrap();

        std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();

        let bytes = build_zip_archive(&[("link/payload.txt", b"escaped")]);
        let archive_path = dir.path().join("malicious.zip");
        fs::write(&archive_path, &bytes).unwrap();

        let archive_file = fs::File::open(&archive_path).unwrap();
        // Extraction should not error; the malicious entry is skipped.
        extract_zip(archive_file, dir.path()).unwrap();

        assert!(
            !outside.path().join("payload.txt").exists(),
            "entry escaped extraction directory through symlink"
        );
    }

    #[test]
    fn extract_binary_dispatches_on_extension() {
        let dir = tempfile::TempDir::new().unwrap();
        let expected_dir = format!("seshat-{}-v1.0.0", current_target());
        let binary_in_zip = format!("{expected_dir}/seshat{}", std::env::consts::EXE_SUFFIX);
        let dir_entry = format!("{expected_dir}/");
        let zip_bytes = build_zip_archive(&[(&dir_entry, &[]), (&binary_in_zip, b"fake")]);

        let zip_named = dir.path().join("ok.zip");
        fs::write(&zip_named, &zip_bytes).unwrap();
        let ok = extract_binary(&zip_named, dir.path(), "1.0.0");
        assert!(ok.is_ok(), "zip dispatch failed: {ok:?}");

        let dir2 = tempfile::TempDir::new().unwrap();
        let mismatched = dir2.path().join("ok.tar.gz");
        fs::write(&mismatched, &zip_bytes).unwrap();
        let err = extract_binary(&mismatched, dir2.path(), "1.0.0");
        assert!(
            err.is_err(),
            "expected error when zip bytes are read as tar.gz, got {err:?}"
        );
    }

    #[test]
    fn find_binary_asset_matches_target() {
        let assets = vec![
            serde_json::json!({
                "name": "seshat-aarch64-apple-darwin-v1.0.0.tar.gz",
                "browser_download_url": "https://example.com/asset1.tar.gz"
            }),
            serde_json::json!({
                "name": "seshat-x86_64-apple-darwin-v1.0.0.tar.gz",
                "browser_download_url": "https://example.com/asset2.tar.gz"
            }),
        ];

        let target = "aarch64-apple-darwin";
        let result = find_binary_asset(&assets, target, "1.0.0");
        assert!(result.is_some());
        let (name, url) = result.unwrap();
        assert!(name.contains("aarch64-apple-darwin"));
        assert_eq!(url, "https://example.com/asset1.tar.gz");
    }

    #[test]
    fn find_binary_asset_no_match() {
        let assets = vec![serde_json::json!({
            "name": "seshat-wasm32-unknown-unknown-v1.0.0.tar.gz",
            "browser_download_url": "https://example.com/asset1.tar.gz"
        })];

        let result = find_binary_asset(&assets, "aarch64-apple-darwin", "1.0.0");
        assert!(result.is_none());
    }

    #[test]
    fn find_binary_asset_skips_non_tar() {
        let assets = vec![serde_json::json!({
            "name": "seshat-aarch64-apple-darwin-v1.0.0.msi",
            "browser_download_url": "https://example.com/asset1.msi"
        })];

        let result = find_binary_asset(&assets, "aarch64-apple-darwin", "1.0.0");
        assert!(result.is_none());
    }

    #[test]
    fn find_binary_asset_matches_windows_target() {
        let assets = vec![serde_json::json!({
            "name": "seshat-x86_64-pc-windows-msvc-v1.0.0.zip",
            "browser_download_url": "https://example.com/asset.zip"
        })];

        let result = find_binary_asset(&assets, "x86_64-pc-windows-msvc", "1.0.0");
        assert!(result.is_some());
        let (name, url) = result.unwrap();
        assert!(name.ends_with(".zip"));
        assert_eq!(url, "https://example.com/asset.zip");
    }

    #[test]
    fn find_binary_asset_matches_uppercase_zip_extension() {
        let assets = vec![serde_json::json!({
            "name": "seshat-x86_64-pc-windows-msvc-v1.0.0.ZIP",
            "browser_download_url": "https://example.com/asset.ZIP"
        })];

        let result = find_binary_asset(&assets, "x86_64-pc-windows-msvc", "1.0.0");
        assert!(
            result.is_some(),
            "uppercase .ZIP extension should match on windows-msvc target"
        );
    }

    #[test]
    fn find_binary_asset_matches_mixed_case_tar_gz_extension() {
        let assets = vec![serde_json::json!({
            "name": "seshat-x86_64-unknown-linux-gnu-v1.0.0.Tar.Gz",
            "browser_download_url": "https://example.com/asset.tar.gz"
        })];

        let result = find_binary_asset(&assets, "x86_64-unknown-linux-gnu", "1.0.0");
        assert!(
            result.is_some(),
            "mixed-case .Tar.Gz extension should match on linux target"
        );
    }

    #[test]
    fn find_binary_asset_skips_zip_on_unix_target() {
        let assets = vec![serde_json::json!({
            "name": "seshat-x86_64-unknown-linux-gnu-v1.0.0.zip",
            "browser_download_url": "https://example.com/asset.zip"
        })];

        let result = find_binary_asset(&assets, "x86_64-unknown-linux-gnu", "1.0.0");
        assert!(result.is_none());
    }

    /// Sibling artefacts whose names contain the target triple (debug
    /// symbols, source bundles, archive variants) must NOT be returned in
    /// place of the canonical binary archive. Pre-fix, the matcher used
    /// `name.contains(target) && extension_match` which was first-match-wins.
    #[test]
    fn find_binary_asset_rejects_shadowing_sibling_artifacts() {
        let assets = vec![
            serde_json::json!({
                "name": "seshat-x86_64-pc-windows-msvc-v1.0.0-pdb.zip",
                "browser_download_url": "https://example.com/pdb.zip"
            }),
            serde_json::json!({
                "name": "seshat-x86_64-pc-windows-msvc-v1.0.0-debug.zip",
                "browser_download_url": "https://example.com/debug.zip"
            }),
            serde_json::json!({
                "name": "seshat-x86_64-pc-windows-msvc-v1.0.0.zip",
                "browser_download_url": "https://example.com/canonical.zip"
            }),
        ];

        let result = find_binary_asset(&assets, "x86_64-pc-windows-msvc", "1.0.0");
        assert!(result.is_some());
        let (name, url) = result.unwrap();
        assert_eq!(name, "seshat-x86_64-pc-windows-msvc-v1.0.0.zip");
        assert_eq!(url, "https://example.com/canonical.zip");
    }

    /// A release whose tag version doesn't match the requested version
    /// must produce no match. Previously the `contains(target)` check
    /// would have accepted any version's archive.
    #[test]
    fn find_binary_asset_requires_version_match() {
        let assets = vec![serde_json::json!({
            "name": "seshat-x86_64-pc-windows-msvc-v0.9.0.zip",
            "browser_download_url": "https://example.com/old.zip"
        })];

        let result = find_binary_asset(&assets, "x86_64-pc-windows-msvc", "1.0.0");
        assert!(
            result.is_none(),
            "asset for v0.9.0 must not match a request for v1.0.0"
        );
    }

    #[test]
    fn find_checksums_url_prefers_version_match() {
        let assets = vec![
            serde_json::json!({
                "name": "sha256sums-v0.5.0.txt",
                "browser_download_url": "https://example.com/sha256sums-old.txt"
            }),
            serde_json::json!({
                "name": "sha256sums-v1.0.0.txt",
                "browser_download_url": "https://example.com/sha256sums-v1.0.0.txt"
            }),
        ];

        let result = find_checksums_url(&assets, "1.0.0");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "https://example.com/sha256sums-v1.0.0.txt");
    }

    #[test]
    fn find_checksums_url_fallback_first_match() {
        let assets = vec![
            serde_json::json!({
                "name": "seshat-aarch64-apple-darwin-v1.0.0.tar.gz",
                "browser_download_url": "https://example.com/asset1.tar.gz"
            }),
            serde_json::json!({
                "name": "sha256sums.txt",
                "browser_download_url": "https://example.com/sha256sums.txt"
            }),
        ];

        let result = find_checksums_url(&assets, "1.0.0");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "https://example.com/sha256sums.txt");
    }

    #[test]
    fn find_checksums_url_not_found() {
        let assets = vec![serde_json::json!({
            "name": "seshat-aarch64-apple-darwin-v1.0.0.tar.gz",
            "browser_download_url": "https://example.com/asset1.tar.gz"
        })];

        let result = find_checksums_url(&assets, "1.0.0");
        assert!(result.is_err());
    }

    #[test]
    fn is_cargo_install_returns_bool() {
        let _ = is_cargo_install();
    }

    #[test]
    fn cargo_json_contains_seshat_true() {
        let json = serde_json::json!({
            "installs": {
                "seshat 1.2.3 (registry+https://github.com/rust-lang/crates.io-index)": {
                    "version_req": "^1",
                    "bins": ["seshat"],
                    "features": [],
                    "all_features": false,
                    "no_default_features": false,
                    "profile": "release",
                    "target": "aarch64-apple-darwin",
                    "rustc": "1.75.0"
                }
            }
        });
        assert!(cargo_json_contains_seshat(&json));
    }

    #[test]
    fn cargo_json_contains_seshat_false() {
        let json = serde_json::json!({
            "installs": {
                "ripgrep 13.0.0 (registry+https://github.com/rust-lang/crates.io-index)": {}
            }
        });
        assert!(!cargo_json_contains_seshat(&json));
    }

    #[test]
    fn cargo_json_no_installs_key() {
        let json = serde_json::json!({ "other": "data" });
        assert!(!cargo_json_contains_seshat(&json));
    }

    #[test]
    fn cargo_json_empty_installs() {
        let json = serde_json::json!({ "installs": {} });
        assert!(!cargo_json_contains_seshat(&json));
    }

    #[test]
    fn cargo_toml_contains_seshat_true() {
        let content = r#"[v1]
"seshat 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = ["seshat"]
"#;
        assert!(cargo_toml_contains_seshat(content));
    }

    #[test]
    fn cargo_toml_contains_seshat_false() {
        let content = r#"[v1]
"ripgrep 13.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = ["rg"]
"#;
        assert!(!cargo_toml_contains_seshat(content));
    }

    #[test]
    fn cargo_toml_substring_no_false_positive() {
        let content = r#"[v1]
"seshat-something 1.0.0" = ["not-seshat"]
"#;
        assert!(!cargo_toml_contains_seshat(content));
    }

    #[test]
    fn cargo_toml_empty() {
        assert!(!cargo_toml_contains_seshat(""));
        assert!(!cargo_toml_contains_seshat("[v1]\n"));
    }

    #[test]
    fn is_cargo_install_with_fake_crates2_json() {
        let dir = tempfile::TempDir::new().unwrap();
        let cargo_dir = dir.path();

        let crates2 = cargo_dir.join(".crates2.json");
        let json = serde_json::json!({
            "installs": {
                "seshat 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)": {
                    "bins": ["seshat"]
                }
            }
        });
        fs::write(&crates2, serde_json::to_string(&json).unwrap()).unwrap();

        let content = fs::read_to_string(&crates2).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert!(cargo_json_contains_seshat(&parsed));
    }

    #[test]
    fn is_cargo_install_with_corrupted_crates2_json() {
        let dir = tempfile::TempDir::new().unwrap();
        let crates2 = dir.path().join(".crates2.json");
        fs::write(&crates2, b"not valid json").unwrap();

        let content = fs::read_to_string(&crates2).unwrap();
        let result = serde_json::from_str::<serde_json::Value>(&content);
        assert!(result.is_err());
    }

    #[test]
    fn resolve_target_exe_returns_path() {
        let result = resolve_target_exe();
        assert!(result.is_ok());
        let path = result.unwrap();
        assert!(path.is_absolute());
    }

    #[test]
    fn map_replace_error_translates_permission_denied() {
        let dir = tempfile::TempDir::new().unwrap();
        let target = dir.path().join("seshat");
        let e = std::io::Error::from(std::io::ErrorKind::PermissionDenied);

        let cli_err = map_replace_error(e, &target);
        match cli_err {
            CliError::CommandFailed { command, reason } => {
                assert_eq!(command, "update");
                #[cfg(windows)]
                assert!(
                    reason.contains("Administrator"),
                    "Windows reason should mention Administrator hint, got: {reason}"
                );
                #[cfg(not(windows))]
                assert!(
                    reason.contains("sudo seshat update"),
                    "Unix reason should mention sudo hint, got: {reason}"
                );
            }
            other => panic!("expected CommandFailed, got: {other:?}"),
        }
    }

    #[test]
    fn map_replace_error_passes_through_other_errors() {
        let dir = tempfile::TempDir::new().unwrap();
        let target = dir.path().join("seshat");
        let e = std::io::Error::other("boom");

        let cli_err = map_replace_error(e, &target);
        match cli_err {
            CliError::CommandFailed { reason, .. } => {
                assert!(
                    reason.starts_with("failed to replace binary: "),
                    "non-permission errors should map to the generic 'failed to replace binary' reason, got: {reason}"
                );
                assert!(reason.contains("boom"));
            }
            other => panic!("expected CommandFailed, got: {other:?}"),
        }
    }

    #[cfg(windows)]
    #[test]
    fn replace_binary_translates_permission_denied_to_admin_hint_on_windows() {
        let dir = tempfile::TempDir::new().unwrap();
        let target = dir.path().join("seshat.exe");
        let e = std::io::Error::from(std::io::ErrorKind::PermissionDenied);

        let cli_err = map_replace_error(e, &target);
        match cli_err {
            CliError::CommandFailed { reason, .. } => {
                assert!(
                    reason.contains("Administrator"),
                    "Windows admin hint should appear in the CliError reason, got: {reason}"
                );
                assert!(!reason.contains("sudo"));
            }
            other => panic!("expected CommandFailed, got: {other:?}"),
        }
    }

    #[cfg(windows)]
    #[test]
    fn is_cargo_install_with_fake_crates2_json_on_windows() {
        let dir = tempfile::TempDir::new().unwrap();
        let cargo_dir = dir.path();

        let crates2 = cargo_dir.join(".crates2.json");
        let json = serde_json::json!({
            "installs": {
                "seshat 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)": {
                    "bins": ["seshat.exe"]
                }
            }
        });
        fs::write(&crates2, serde_json::to_string(&json).unwrap()).unwrap();

        let content = fs::read_to_string(&crates2).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert!(cargo_json_contains_seshat(&parsed));
    }

    #[test]
    fn preflight_check_with_valid_binary() {
        let dir = tempfile::TempDir::new().unwrap();

        let echo_path = std::path::Path::new("/bin/echo");
        if !echo_path.exists() {
            return;
        }

        let script = dir.path().join("fake_seshat");
        fs::write(&script, b"#!/bin/sh\necho 'seshat 1.0.0'\n").unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&script).unwrap().permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&script, perms).unwrap();
        }

        let result = preflight_check(&script, dir.path());
        assert!(result.is_ok());
    }

    #[cfg(unix)]
    #[test]
    fn preflight_check_detects_nonzero_exit() {
        let dir = tempfile::TempDir::new().unwrap();
        let script = dir.path().join("failing_binary");
        fs::write(&script, b"#!/bin/sh\nexit 1\n").unwrap();

        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&script).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script, perms).unwrap();

        let result = preflight_check(&script, dir.path());
        assert!(result.is_err());
    }

    #[test]
    fn version_output_contains_seshat_with_version() {
        assert!(version_output_contains_seshat("seshat 1.2.3"));
        assert!(version_output_contains_seshat("seshat v0.2.0"));
        assert!(version_output_contains_seshat("foo seshat 1.0.0"));
    }

    #[test]
    fn version_output_does_not_contain_seshat() {
        assert!(!version_output_contains_seshat(""));
        assert!(!version_output_contains_seshat("something else"));
        assert!(!version_output_contains_seshat("seshat not a version"));
        assert!(!version_output_contains_seshat("seshat-error happened"));
    }

    #[test]
    fn notice_skips_when_cache_fresh_and_up_to_date() {
        let dir = tempfile::TempDir::new().unwrap();
        let cache_path = dir.path().join("version-check.json");

        let current = env!("CARGO_PKG_VERSION");
        let cache = VersionCache::new(current.to_owned());
        cache.write_to_path(&cache_path).unwrap();

        check_and_print_update_notice_inner(&Some(cache_path));
    }

    #[test]
    fn notice_skips_when_cache_fresh_and_old_version() {
        let dir = tempfile::TempDir::new().unwrap();
        let cache_path = dir.path().join("version-check.json");

        let cache = VersionCache::new("0.0.1".to_owned());
        cache.write_to_path(&cache_path).unwrap();

        check_and_print_update_notice_inner(&Some(cache_path));
    }

    #[test]
    fn notice_skips_when_cache_no_assets() {
        let dir = tempfile::TempDir::new().unwrap();
        let cache_path = dir.path().join("version-check.json");

        let cache = VersionCache::with_assets("9999.0.0".to_owned(), false);
        cache.write_to_path(&cache_path).unwrap();

        check_and_print_update_notice_inner(&Some(cache_path));
    }

    #[test]
    fn notice_with_fresh_cache_newer_version() {
        let dir = tempfile::TempDir::new().unwrap();
        let cache_path = dir.path().join("version-check.json");

        let cache = VersionCache::new("9999.0.0".to_owned());
        cache.write_to_path(&cache_path).unwrap();

        check_and_print_update_notice_inner(&Some(cache_path));
    }

    #[test]
    fn notice_skips_when_no_cache_path() {
        check_and_print_update_notice_inner(&None);
    }

    #[test]
    fn notice_skips_when_cache_missing() {
        let dir = tempfile::TempDir::new().unwrap();
        let nonexistent = dir.path().join("no-such-file.json");
        check_and_print_update_notice_inner(&Some(nonexistent));
    }

    // ── parse_rate_limit / check_response_status ─────────────────────

    fn future_reset_headers(seconds_from_now: u64) -> ureq::http::HeaderMap {
        let mut h = ureq::http::HeaderMap::new();
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let reset = now + seconds_from_now;
        h.insert("x-ratelimit-reset", reset.to_string().parse().unwrap());
        h
    }

    #[test]
    fn parse_rate_limit_ignores_non_throttling_status() {
        let h = future_reset_headers(600);
        assert!(parse_rate_limit(200, &h).is_none());
        assert!(parse_rate_limit(404, &h).is_none());
        assert!(parse_rate_limit(500, &h).is_none());
    }

    #[test]
    fn parse_rate_limit_handles_403_with_reset_header() {
        let h = future_reset_headers(1800); // 30 minutes from now
        let info = parse_rate_limit(403, &h).expect("should parse");
        // Rounding to whole minutes can drop us to 29 right at the boundary;
        // anything in 25..=30 is fine for an integration-ish unit test.
        assert!(
            (25..=30).contains(&info.retry_after_minutes),
            "unexpected retry_after_minutes: {}",
            info.retry_after_minutes
        );
    }

    #[test]
    fn parse_rate_limit_handles_429_with_reset_header() {
        let h = future_reset_headers(120);
        let info = parse_rate_limit(429, &h).expect("should parse");
        assert!(info.retry_after_minutes >= 1);
    }

    #[test]
    fn parse_rate_limit_clamps_past_reset_to_one_minute() {
        let mut h = ureq::http::HeaderMap::new();
        h.insert("x-ratelimit-reset", "1".parse().unwrap()); // far in the past
        let info = parse_rate_limit(403, &h).expect("should parse");
        assert_eq!(info.retry_after_minutes, 1);
    }

    #[test]
    fn parse_rate_limit_returns_none_when_header_missing() {
        let h = ureq::http::HeaderMap::new();
        assert!(parse_rate_limit(403, &h).is_none());
        assert!(parse_rate_limit(429, &h).is_none());
    }

    #[test]
    fn parse_rate_limit_returns_none_when_header_unparseable() {
        let mut h = ureq::http::HeaderMap::new();
        h.insert("x-ratelimit-reset", "not-a-number".parse().unwrap());
        assert!(parse_rate_limit(403, &h).is_none());
    }

    #[test]
    fn parse_rate_limit_floor_to_one_minute_when_reset_under_60s() {
        // ~30 seconds ahead → integer division (30/60) == 0, then clamped via .max(1)
        let h = future_reset_headers(30);
        let info = parse_rate_limit(429, &h).expect("should parse");
        assert_eq!(info.retry_after_minutes, 1);
    }

    #[test]
    fn check_response_status_ok_for_2xx_and_3xx() {
        let h = ureq::http::HeaderMap::new();
        assert!(check_response_status(200, &h).is_ok());
        assert!(check_response_status(204, &h).is_ok());
        assert!(check_response_status(301, &h).is_ok());
        assert!(check_response_status(399, &h).is_ok());
    }

    #[test]
    fn check_response_status_404_message() {
        let h = ureq::http::HeaderMap::new();
        let err = check_response_status(404, &h).unwrap_err();
        assert!(err.to_string().contains("release not found"));
    }

    #[test]
    fn check_response_status_5xx_message() {
        let h = ureq::http::HeaderMap::new();
        let err = check_response_status(503, &h).unwrap_err();
        assert!(err.to_string().contains("server error"));
        assert!(err.to_string().contains("503"));
    }

    #[test]
    fn check_response_status_other_4xx_includes_status() {
        let h = ureq::http::HeaderMap::new();
        let err = check_response_status(418, &h).unwrap_err();
        assert!(err.to_string().contains("418"));
    }

    #[test]
    fn check_response_status_403_with_reset_returns_rate_limit_message() {
        let h = future_reset_headers(600);
        let err = check_response_status(403, &h).unwrap_err();
        assert!(err.to_string().contains("rate limited"));
    }

    #[test]
    fn check_response_status_403_without_reset_falls_through_to_generic_4xx() {
        let h = ureq::http::HeaderMap::new();
        let err = check_response_status(403, &h).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("403"));
        // The "rate limited" branch must NOT activate when the header is missing.
        assert!(!msg.contains("rate limited"), "got: {msg}");
    }

    #[cfg(unix)]
    #[test]
    fn cleanup_after_update_is_noop_on_unix() {
        // Unix has atomic rename(2), so `replace_binary` never leaves a `.old`
        // behind. The helper compiles to a no-op here — the contract under
        // test is "calling this from `lib.rs::run()` on Unix has no effect".
        // We do NOT call the upstream `self_replace::self_delete_outside_path`,
        // which would unconditionally `fs::remove_file(current_exe())` on Unix
        // and brick the cargo-test binary.
        cleanup_stale_old_binary();
    }

    #[cfg(windows)]
    #[test]
    fn cleanup_stale_old_binary_removes_existing_old_file() {
        let dir = tempfile::TempDir::new().unwrap();
        let exe = dir.path().join("seshat.exe");
        let stale = dir.path().join("seshat.exe.old");
        fs::write(&exe, b"new").unwrap();
        fs::write(&stale, b"old").unwrap();
        cleanup_stale_old_binary_at(&exe);
        assert!(!stale.exists(), "stale .old file must be removed");
        assert!(exe.exists(), "live binary must be preserved");
    }

    #[cfg(windows)]
    #[test]
    fn cleanup_stale_old_binary_is_noop_when_old_file_missing() {
        let dir = tempfile::TempDir::new().unwrap();
        let exe = dir.path().join("seshat.exe");
        fs::write(&exe, b"new").unwrap();
        cleanup_stale_old_binary_at(&exe);
        assert!(exe.exists());
    }

    // ── US-007: integration-style tests for the Windows update flow ──
    //
    // PRD AC for US-007 asks for tests against a "mocked HTTP server" and
    // claims "existing mock-server helpers" exist. Neither is true:
    //   (a) `update.rs` hardcodes `GITHUB_RELEASES_API` as a `const &str`, so
    //       there is no URL injection point; standing up a real mock server
    //       would require non-trivial dependency injection in run_self_update.
    //   (b) `replace_binary` calls `self_replace::self_replace(new_binary)`,
    //       which derives the *target* from `std::env::current_exe()` and
    //       therefore would overwrite the cargo-test binary mid-run if
    //       exercised end-to-end (this constraint is documented in US-005).
    //   (c) No mock-server helper code exists anywhere in the workspace.
    //
    // The user-story intent is regression coverage of the windows-msvc code
    // paths — extension-based asset matching, zip extraction, sha256 verify,
    // preflight, and update-notice. We satisfy that intent by composing the
    // real helper functions against fixture data inside cfg(windows) tests,
    // stopping short of `replace_binary` (deferred to manual + Windows CI
    // integration via US-008). Each test below maps 1:1 to a PRD AC:

    /// US-007 happy path. Builds a hand-crafted .zip with a fake `seshat.exe`
    /// inside the expected `seshat-{target}-v{version}/` layout, computes its
    /// SHA-256, then walks `verify_sha256` → `extract_binary` (which dispatches
    /// to the windows zip path) and asserts the staged .exe lands at the
    /// expected path with the correct content. This is the in-process
    /// equivalent of "asserts target_exe content matches new binary" — minus
    /// the actual `replace_binary` step (see module-level note).
    #[cfg(windows)]
    #[test]
    fn run_self_update_windows_happy_path() {
        let dir = tempfile::TempDir::new().unwrap();
        let archive_path = dir.path().join("seshat-windows-v1.0.0.zip");

        let target = current_target();
        let expected_dir = format!("seshat-{target}-v1.0.0");
        let binary_in_zip = format!("{expected_dir}/seshat.exe");
        let dir_entry = format!("{expected_dir}/");
        let new_binary_bytes = b"new-windows-binary-v1.0.0";

        let zip_bytes = build_zip_archive(&[(&dir_entry, &[]), (&binary_in_zip, new_binary_bytes)]);
        fs::write(&archive_path, &zip_bytes).unwrap();

        let mut hasher = Sha256::new();
        hasher.update(&zip_bytes);
        let hash = hasher.finalize();
        let mut expected_hex = String::with_capacity(hash.len() * 2);
        for byte in hash {
            use std::fmt::Write;
            let _ = write!(expected_hex, "{byte:02x}");
        }

        verify_sha256(&archive_path, &expected_hex).expect("hash matches");

        let staged = extract_binary(&archive_path, dir.path(), "1.0.0").expect("extract ok");
        assert!(staged.is_file(), "staged binary should exist on disk");
        assert!(
            staged.ends_with(format!("{expected_dir}/seshat.exe")),
            "staged binary path should match the windows layout, got: {}",
            staged.display()
        );
        let staged_bytes = fs::read(&staged).unwrap();
        assert_eq!(
            staged_bytes, new_binary_bytes,
            "staged binary content must match the bytes embedded in the zip"
        );
    }

    /// US-007 sha mismatch. Same .zip fixture as happy-path, but verify with
    /// a deliberately-wrong hash → `verify_sha256` returns CommandFailed.
    /// Asserts the existing binary stays unchanged by virtue of the early
    /// error: no extraction or replace ever runs (the real `run_self_update`
    /// short-circuits on the `verify_sha256.inspect_err(...)` branch at
    /// update.rs:123).
    #[cfg(windows)]
    #[test]
    fn run_self_update_windows_sha_mismatch() {
        let dir = tempfile::TempDir::new().unwrap();
        let archive_path = dir.path().join("seshat-windows-v1.0.0.zip");

        let target = current_target();
        let expected_dir = format!("seshat-{target}-v1.0.0");
        let binary_in_zip = format!("{expected_dir}/seshat.exe");
        let dir_entry = format!("{expected_dir}/");
        let zip_bytes = build_zip_archive(&[(&dir_entry, &[]), (&binary_in_zip, b"any-bytes")]);
        fs::write(&archive_path, &zip_bytes).unwrap();

        let wrong_hash = "0".repeat(64);
        let result = verify_sha256(&archive_path, &wrong_hash);
        match result {
            Err(CliError::CommandFailed { reason, .. }) => {
                assert!(
                    reason.contains("SHA256 mismatch"),
                    "sha mismatch path must surface CliError::CommandFailed with a 'SHA256 mismatch' reason, got: {reason}"
                );
            }
            other => panic!("expected SHA256 mismatch CommandFailed, got: {other:?}"),
        }

        let unstaged = dir.path().join(&expected_dir).join("seshat.exe");
        assert!(
            !unstaged.exists(),
            "no extraction must happen on sha mismatch"
        );
    }

    /// US-007 no-zip-asset path. A release whose only artefacts are `.tar.gz`
    /// (Unix triples) with the windows-msvc target → `find_binary_asset`
    /// returns None, which `fetch_release_assets` translates to `Ok(None)` and
    /// `run_self_update` prints "Seshat is up to date" and returns Ok(()).
    /// We don't need to drive `run_self_update` for this — the matcher is the
    /// only branch point.
    #[cfg(windows)]
    #[test]
    fn run_self_update_windows_no_zip_asset_for_target() {
        let assets = vec![
            serde_json::json!({
                "name": "seshat-x86_64-unknown-linux-gnu-v1.0.0.tar.gz",
                "browser_download_url": "https://example.com/linux.tar.gz"
            }),
            serde_json::json!({
                "name": "seshat-aarch64-apple-darwin-v1.0.0.tar.gz",
                "browser_download_url": "https://example.com/darwin.tar.gz"
            }),
        ];

        let result = find_binary_asset(&assets, "x86_64-pc-windows-msvc", "1.0.0");
        assert!(
            result.is_none(),
            "windows-msvc target must NOT match any .tar.gz asset, got: {result:?}"
        );

        let json = serde_json::json!({
            "tag_name": "v1.0.0",
            "assets": assets,
        });
        assert!(
            !has_binary_asset_for_current_target(&json),
            "no windows-msvc .zip in this release → background-notice must skip"
        );
    }

    /// US-007 preflight failure. A "binary" that fails to spawn (non-PE bytes
    /// at a `.exe` path) makes `Command::output()` Err on Windows, which
    /// `preflight_check` maps to CommandFailed and triggers temp-dir cleanup.
    /// Asserts: `preflight_check` errs, the temp dir is wiped, and the
    /// existing binary on disk (which we never produced — the fixture stops
    /// before `replace_binary`) is intact.
    #[cfg(windows)]
    #[test]
    fn run_self_update_windows_preflight_fail() {
        let dir = tempfile::TempDir::new().unwrap();
        let temp_dir = dir.path().join("staging");
        fs::create_dir_all(&temp_dir).unwrap();
        let bogus_binary = temp_dir.join("seshat.exe");
        fs::write(&bogus_binary, b"not a PE file").unwrap();

        let result = preflight_check(&bogus_binary, &temp_dir);
        assert!(
            result.is_err(),
            "preflight_check must error on non-executable bytes"
        );
        match result {
            Err(CliError::CommandFailed { command, reason }) => {
                assert_eq!(command, "update");
                assert!(
                    !reason.is_empty(),
                    "CommandFailed should carry a non-empty reason"
                );
            }
            other => panic!("expected CommandFailed, got: {other:?}"),
        }
        assert!(
            !temp_dir.exists(),
            "preflight_check must clean up the staging temp dir on failure"
        );
    }

    /// US-007 background-notice on Windows. Pre-populated cache with a newer
    /// version + has_assets=true is the fast path that
    /// `check_and_print_update_notice_inner` follows; the function emits the
    /// expected eprintln. We can't capture stderr from a unit test without
    /// dup2'ing FD 2, so we lock the contract at the cache layer: after the
    /// call the cache file is unchanged (no network was touched), and the
    /// helper did not panic.
    #[cfg(windows)]
    #[test]
    fn background_notice_prints_on_windows() {
        let dir = tempfile::TempDir::new().unwrap();
        let cache_path = dir.path().join("version-check.json");

        let cache = VersionCache::with_assets("9999.0.0".to_owned(), true);
        cache.write_to_path(&cache_path).unwrap();
        let before = fs::read_to_string(&cache_path).unwrap();

        check_and_print_update_notice_inner(&Some(cache_path.clone()));

        let after = fs::read_to_string(&cache_path).unwrap();
        assert_eq!(
            before, after,
            "fresh cache fast path must not rewrite the cache file"
        );
    }
}