tokensave 7.12.1

Code intelligence tool that builds a semantic knowledge graph from Rust, Go, Java, Scala, TypeScript, Python, C, C++, Kotlin, C#, Swift, and many more codebases
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
//! Self-update for the tokensave binary.
//!
//! Downloads the latest release asset directly from GitHub, extracts the
//! binary, and replaces the running executable using `self_replace`.
//! Beta and stable are separate channels — a beta build only sees beta
//! releases and vice versa.

use std::collections::HashSet;
use std::path::Path;

use crate::cloud::{self, InstallMethod};
use crate::errors::{Result, TokenSaveError};
use crate::user_config::UserConfig;

const GITHUB_REPO: &str = "aovestdipaperino/tokensave";

// Asset-naming and platform helpers live in `crate::cloud` so the version-
// detection path can use the same naming convention to filter out releases
// whose CI hasn't finished uploading the current platform's binary yet.
use crate::cloud::asset_name;
#[cfg(test)]
use crate::cloud::current_platform;

/// The GitHub release tag for a given version.
fn release_tag(version: &str) -> String {
    format!("v{version}")
}

fn io_err(msg: &str) -> impl Fn(std::io::Error) -> TokenSaveError + '_ {
    move |e| TokenSaveError::Config {
        message: format!("{msg}: {e}"),
    }
}

/// The name of the release asset listing each other asset's SHA256.
///
/// Published by both release workflows in `sha256sum` format, one line per
/// asset.
const SUMS_ASSET: &str = "SHA256SUMS";

/// One asset attached to a GitHub release.
#[derive(serde::Deserialize)]
struct Asset {
    name: String,
    browser_download_url: String,
}

/// A located release asset, together with the SHA256 the release publishes
/// for it.
struct VerifiedAsset {
    url: String,
    sha256: String,
}

/// Fetches every asset attached to a release.
///
/// One request serves both the binary lookup and the `SHA256SUMS` lookup —
/// they come from the same release, so asking twice would only add a way for
/// the two to disagree.
fn fetch_release_assets(tag: &str) -> Result<Vec<Asset>> {
    #[derive(serde::Deserialize)]
    struct Release {
        assets: Vec<Asset>,
    }

    let url = format!("https://api.github.com/repos/{GITHUB_REPO}/releases/tags/{tag}");
    let agent = cloud::agent_with_timeout(std::time::Duration::from_secs(30));

    let release: Release = agent
        .get(&url)
        .header("User-Agent", "tokensave")
        .call()
        .map_err(|e| TokenSaveError::Config {
            message: format!("failed to reach GitHub: {e}"),
        })?
        .body_mut()
        .read_json()
        .map_err(|e| TokenSaveError::Config {
            message: format!("failed to parse release info: {e}"),
        })?;

    Ok(release.assets)
}

/// Downloads a small text asset (the sums file) in full.
fn fetch_text_asset(url: &str) -> Result<String> {
    let agent = cloud::agent_with_timeout(std::time::Duration::from_secs(30));
    agent
        .get(url)
        .header("User-Agent", "tokensave")
        .call()
        .map_err(|e| TokenSaveError::Config {
            message: format!("failed to download {SUMS_ASSET}: {e}"),
        })?
        .body_mut()
        .read_to_string()
        .map_err(|e| TokenSaveError::Config {
            message: format!("failed to read {SUMS_ASSET}: {e}"),
        })
}

/// Pulls one asset's hash out of a `sha256sum`-format listing.
///
/// Accepts both the text (`hash  name`) and binary (`hash *name`) markers
/// `sha256sum` emits, and ignores blank lines so a trailing newline is not an
/// error. Returns `None` when the file is well-formed but does not mention
/// `asset`, which the caller reports separately from a malformed file.
fn sha256_for_asset(listing: &str, asset: &str) -> Option<String> {
    listing.lines().find_map(|line| {
        let (hash, name) = line.split_once(char::is_whitespace)?;
        let name = name.trim_start_matches(['*', ' ']).trim();
        (name == asset && hash.len() == 64 && hash.chars().all(|c| c.is_ascii_hexdigit()))
            .then(|| hash.to_ascii_lowercase())
    })
}

/// Locates the platform's release asset and the SHA256 published for it.
///
/// Fails closed (#525). A release whose `SHA256SUMS` is missing, unreadable,
/// or silent about this asset aborts the upgrade rather than installing an
/// unverified binary: `upgrade` only ever moves forward to a channel's latest,
/// so every release a verifying binary can reach is one published after the
/// sums file started shipping. Treating "no sums" as "skip verification" would
/// hand anyone who can suppress the file a silent downgrade to no integrity
/// check at all, which is the property being bought here.
fn locate_verified_asset(tag: &str, expected_asset: &str) -> Result<VerifiedAsset> {
    let assets = fetch_release_assets(tag)?;

    let url = assets
        .iter()
        .find(|a| a.name == expected_asset)
        .map(|a| a.browser_download_url.clone())
        .ok_or_else(|| TokenSaveError::Config {
            message: format!(
                "release {tag} exists but asset '{expected_asset}' is not yet available.\n  \
                 CI build may still be in progress — try again in a few minutes.\n  \
                 https://github.com/{GITHUB_REPO}/releases/tag/{tag}",
            ),
        })?;

    let sums_url = assets
        .iter()
        .find(|a| a.name == SUMS_ASSET)
        .map(|a| a.browser_download_url.clone())
        .ok_or_else(|| TokenSaveError::Update {
            message: format!(
                "release {tag} publishes no {SUMS_ASSET}, so the download cannot be \
                 verified — refusing to install.\n  \
                 If CI is still finishing, try again in a few minutes:\n  \
                 https://github.com/{GITHUB_REPO}/releases/tag/{tag}",
            ),
        })?;

    let listing = fetch_text_asset(&sums_url)?;
    let sha256 =
        sha256_for_asset(&listing, expected_asset).ok_or_else(|| TokenSaveError::Update {
            message: format!(
                "release {tag} publishes {SUMS_ASSET} but it lists no hash for \
                 '{expected_asset}' — refusing to install.\n  \
                 https://github.com/{GITHUB_REPO}/releases/tag/{tag}",
            ),
        })?;

    Ok(VerifiedAsset { url, sha256 })
}

/// Hex-encodes the SHA256 of `data`.
fn sha256_hex(data: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(data);
    hasher
        .finalize()
        .iter()
        .fold(String::with_capacity(64), |mut acc, byte| {
            use std::fmt::Write;
            let _ = write!(acc, "{byte:02x}");
            acc
        })
}

/// A downloaded binary staged for installation, and the private directory
/// holding it.
///
/// The directory is owned by this value so it is removed when the staged
/// binary goes out of scope, whether the replacement succeeded or not.
struct StagedBinary {
    /// Held for its `Drop`, which removes the directory and anything left in
    /// it. Never read directly — [`Self::path`] is the accessor.
    _dir: tempfile::TempDir,
    path: std::path::PathBuf,
}

impl StagedBinary {
    fn path(&self) -> &Path {
        &self.path
    }
}

/// Creates the private directory the downloaded binary is extracted into.
///
/// The destination used to be `std::env::temp_dir().join("tokensave_upgrade_<pid>")`
/// — a name another local user can predict and pre-create. Both extraction
/// paths open it with `create`-like semantics that follow symlinks, so on a
/// host with a shared world-writable `/tmp` a symlink planted at that path
/// would be followed and the target written with this process's privileges
/// (#525). `TempDir` picks a random name and creates it exclusively, failing
/// rather than adopting a path that already exists, which is what defeats the
/// planted symlink; the extraction code is then unchanged and simply writes
/// somewhere nobody else can name. The mode is narrowed to `0700` afterwards
/// because `tempdir()` creates with `0777 & !umask` — commonly `0755`, which
/// would leave the staged binary readable by every other local user between
/// extraction and install.
fn new_staging_dir() -> Result<tempfile::TempDir> {
    let dir = tempfile::Builder::new()
        .prefix("tokensave_upgrade_")
        .tempdir()
        .map_err(io_err("create temp dir failed"))?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700))
            .map_err(io_err("secure temp dir failed"))?;
    }

    Ok(dir)
}

/// Downloads the archive from `url` into memory, then extracts `bin_name`
/// into a freshly created private directory. Returns the staged binary.
fn download_and_extract(url: &str, bin_name: &str, expected_sha256: &str) -> Result<StagedBinary> {
    let tmp_dir = new_staging_dir()?;
    let tmp_path = tmp_dir.path().join(format!(
        "tokensave{}",
        if cfg!(windows) { ".exe" } else { "" }
    ));

    let agent = cloud::agent_with_timeout(std::time::Duration::from_mins(5));

    eprint!("  Downloading...");

    // Buffer the entire archive so the reader type is concrete (Cursor<Vec<u8>>),
    // which makes type inference for tar::Entry and zip::ZipArchive unambiguous.
    let raw: Vec<u8> = {
        use std::io::Read;
        let mut buf = Vec::new();
        agent
            .get(url)
            .header("User-Agent", "tokensave")
            .call()
            .map_err(|e| TokenSaveError::Config {
                message: format!("download failed: {e}"),
            })?
            .body_mut()
            .as_reader()
            .read_to_end(&mut buf)
            .map_err(io_err("download read failed"))?;
        buf
    };

    eprintln!(" ({:.1} MiB)", raw.len() as f64 / 1_048_576.0);

    // Verified before extraction, not after (#525): extraction writes the
    // archive's contents to disk, so a mismatched archive must never reach it.
    eprint!("  Verifying...");
    let actual = sha256_hex(&raw);
    if actual != expected_sha256 {
        eprintln!(" \x1b[31mFAILED\x1b[0m");
        return Err(TokenSaveError::Update {
            message: format!(
                "downloaded archive does not match the SHA256 published for it — \
                 refusing to install.\n  \
                 expected: {expected_sha256}\n  \
                 actual:   {actual}\n  \
                 This means the download was corrupted or tampered with. \
                 Nothing has been installed."
            ),
        });
    }
    eprintln!(" OK");

    eprint!("  Extracting...");

    #[cfg(not(windows))]
    extract_targz(&raw, bin_name, &tmp_path)?;

    #[cfg(windows)]
    extract_zip(&raw, bin_name, &tmp_path)?;

    eprintln!(" Done");
    Ok(StagedBinary {
        _dir: tmp_dir,
        path: tmp_path,
    })
}

/// Extracts `bin_name` from a `.tar.gz` archive (Unix).
#[cfg(not(windows))]
fn extract_targz(data: &[u8], bin_name: &str, dest: &Path) -> Result<()> {
    use flate2::read::GzDecoder;
    use std::io::Cursor;
    use tar::Archive;

    let gz = GzDecoder::new(Cursor::new(data));
    let mut archive = Archive::new(gz);

    for entry in archive.entries().map_err(io_err("archive open failed"))? {
        let mut entry = entry.map_err(io_err("archive read failed"))?;
        let path = entry
            .path()
            .map_err(io_err("archive path error"))?
            .to_path_buf();

        if path.file_name().and_then(|n| n.to_str()) == Some(bin_name) {
            entry.unpack(dest).map_err(io_err("extract failed"))?;

            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mut perms = std::fs::metadata(dest)
                    .map_err(io_err("stat failed"))?
                    .permissions();
                perms.set_mode(0o755);
                std::fs::set_permissions(dest, perms).map_err(io_err("chmod failed"))?;
            }

            return Ok(());
        }
    }

    Err(TokenSaveError::Config {
        message: format!("binary '{bin_name}' not found in archive"),
    })
}

/// Extracts `bin_name` from a `.zip` archive (Windows).
#[cfg(windows)]
fn extract_zip(data: &[u8], bin_name: &str, dest: &Path) -> Result<()> {
    use std::io::Cursor;

    let mut archive =
        zip::ZipArchive::new(Cursor::new(data)).map_err(|e| TokenSaveError::Config {
            message: format!("zip open failed: {e}"),
        })?;

    for i in 0..archive.len() {
        let mut file = archive.by_index(i).map_err(|e| TokenSaveError::Config {
            message: format!("zip entry error: {e}"),
        })?;

        if Path::new(file.name()).file_name().and_then(|n| n.to_str()) == Some(bin_name) {
            let mut out = std::fs::File::create(dest).map_err(io_err("create temp file failed"))?;
            std::io::copy(&mut file, &mut out).map_err(io_err("extract failed"))?;
            return Ok(());
        }
    }

    Err(TokenSaveError::Config {
        message: format!("binary '{bin_name}' not found in zip"),
    })
}

/// Replaces the running binary with `new_exe`, dispatching to the
/// appropriate strategy for the detected install method. Cleans up the
/// temp file afterwards regardless of outcome.
fn replace_binary(new_exe: &Path, method: &InstallMethod, new_version: &str) -> Result<()> {
    let result = match method {
        InstallMethod::Brew => replace_for_brew(new_exe, new_version),
        InstallMethod::Scoop => replace_for_scoop(new_exe, new_version),
        _ => replace_default(new_exe),
    };
    let _ = std::fs::remove_file(new_exe);
    result
}

/// Default replacement using `self_replace`. Falls back to a direct copy
/// when the running binary is behind a symlink (avoids ENOENT caused by
/// `self_replace` resolving relative symlink targets from CWD).
fn replace_default(new_exe: &Path) -> Result<()> {
    #[cfg(unix)]
    {
        let exe = std::env::current_exe().ok();
        let canonical = exe.as_ref().and_then(|e| e.canonicalize().ok());
        if let (Some(exe), Some(ref canonical)) = (&exe, canonical) {
            if exe.as_path() != canonical.as_path() {
                return install_binary(new_exe, canonical);
            }
        }
    }

    self_replace::self_replace(new_exe).map_err(|e| TokenSaveError::Config {
        message: format!(
            "binary replacement failed: {e}\n  \
             The old version is still in place.\n  \
             To upgrade manually: https://github.com/{GITHUB_REPO}/releases/latest"
        ),
    })
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UpgradeStatus<'a> {
    AlreadyCurrent,
    UpgradeAvailable(&'a str),
}

fn classify_upgrade<'a>(current: &str, latest: &'a str) -> UpgradeStatus<'a> {
    if cloud::is_newer_version(current, latest) {
        UpgradeStatus::UpgradeAvailable(latest)
    } else {
        UpgradeStatus::AlreadyCurrent
    }
}

/// Atomically replace a binary at `target` by copying `src` to a temp file
/// in the same directory, setting permissions, then renaming over `target`.
/// Avoids `ETXTBSY` on Linux (rename swaps directory entries rather than
/// writing into the running executable).
#[cfg(unix)]
fn install_binary(src: &Path, target: &Path) -> Result<()> {
    let dir = target.parent().ok_or_else(|| TokenSaveError::Config {
        message: "cannot determine target directory".into(),
    })?;
    let temp = dir.join(format!(".tokensave_upgrade_{}", std::process::id()));

    std::fs::copy(src, &temp).map_err(io_err("cannot copy new binary"))?;

    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&temp, std::fs::Permissions::from_mode(0o755))
            .map_err(io_err("cannot set permissions"))?;
    }

    if let Err(e) = std::fs::rename(&temp, target) {
        let _ = std::fs::remove_file(&temp);
        return Err(io_err("cannot replace binary")(e));
    }

    Ok(())
}

// ── Homebrew ────────────────────────────────────────────────────────────

/// Replace the binary inside the Homebrew Cellar, then rename the version
/// directory and update the symlink so that `brew` reports the new version.
#[cfg(unix)]
fn replace_for_brew(new_exe: &Path, new_version: &str) -> Result<()> {
    let exe = std::env::current_exe().map_err(io_err("cannot determine current exe"))?;
    let canonical = exe
        .canonicalize()
        .map_err(io_err("cannot resolve binary path"))?;

    // Validate Cellar layout: <prefix>/Cellar/<formula>/<version>/bin/<binary>
    let bin_dir = match canonical.parent() {
        Some(p) if p.file_name().and_then(|n| n.to_str()) == Some("bin") => p,
        _ => return replace_default(new_exe),
    };
    let Some(version_dir) = bin_dir.parent() else {
        return replace_default(new_exe);
    };
    let Some(formula_dir) = version_dir.parent() else {
        return replace_default(new_exe);
    };
    let cellar_dir = match formula_dir.parent() {
        Some(p) if p.file_name().and_then(|n| n.to_str()) == Some("Cellar") => p,
        _ => return replace_default(new_exe),
    };
    let Some(prefix) = cellar_dir.parent() else {
        return replace_default(new_exe);
    };

    let Some(bin_name) = canonical.file_name() else {
        return replace_default(new_exe);
    };
    let Some(old_version_os) = version_dir.file_name() else {
        return replace_default(new_exe);
    };
    let old_version = old_version_os.to_string_lossy().to_string();

    // Step 1 (critical): replace the binary atomically.
    install_binary(new_exe, &canonical)?;

    // Steps 2-4 update Cellar metadata so `brew` sees the correct version.
    // These are best-effort — if they fail the binary itself is fine.
    if old_version != new_version {
        let new_version_dir = formula_dir.join(new_version);

        // Step 2: rename the version directory (e.g. 4.0.3 → 4.0.4).
        match std::fs::rename(version_dir, &new_version_dir) {
            Ok(()) => {
                // Step 3: update the symlink at <prefix>/bin/<binary>.
                let symlink_path = prefix.join("bin").join(bin_name);
                if let Ok(meta) = std::fs::symlink_metadata(&symlink_path) {
                    if meta.file_type().is_symlink() {
                        if let Ok(old_target) = std::fs::read_link(&symlink_path) {
                            let new_target = std::path::PathBuf::from(
                                old_target
                                    .to_string_lossy()
                                    .replacen(&old_version, new_version, 1),
                            );
                            let _ = std::fs::remove_file(&symlink_path);
                            let _ = std::os::unix::fs::symlink(&new_target, &symlink_path);
                        }
                    }
                }

                // Step 4: patch INSTALL_RECEIPT.json so `brew info` is accurate.
                let receipt = new_version_dir.join("INSTALL_RECEIPT.json");
                if receipt.exists() {
                    if let Ok(text) = std::fs::read_to_string(&receipt) {
                        let _ = std::fs::write(&receipt, text.replace(&old_version, new_version));
                    }
                }
            }
            Err(e) => {
                eprintln!(
                    "\n  \x1b[33mwarning:\x1b[0m could not rename Cellar directory: {e}\n    \
                     brew may still report the old version"
                );
            }
        }
    }

    Ok(())
}

#[cfg(not(unix))]
fn replace_for_brew(new_exe: &Path, _new_version: &str) -> Result<()> {
    replace_default(new_exe)
}

// ── Scoop ───────────────────────────────────────────────────────────────

/// Replace the binary via `self_replace` (handles Windows exe locking),
/// then update Scoop's version directory and junction so that
/// `scoop status` reports the new version.
#[cfg(windows)]
fn replace_for_scoop(new_exe: &Path, new_version: &str) -> Result<()> {
    self_replace::self_replace(new_exe).map_err(|e| TokenSaveError::Config {
        message: format!(
            "binary replacement failed: {e}\n  \
             The old version is still in place.\n  \
             To upgrade manually: https://github.com/{GITHUB_REPO}/releases/latest"
        ),
    })?;

    // Best-effort: update Scoop metadata for `scoop status` compatibility.
    update_scoop_metadata(new_version);

    Ok(())
}

#[cfg(windows)]
fn update_scoop_metadata(new_version: &str) {
    let Ok(exe) = std::env::current_exe() else {
        return;
    };
    let canonical = exe.canonicalize().unwrap_or(exe);

    let Some(version_dir) = find_scoop_version_dir(&canonical) else {
        return;
    };
    let Some(app_dir) = version_dir.parent() else {
        return;
    };
    let old_version = version_dir
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default();

    if old_version == new_version || old_version == "current" {
        return;
    }

    let new_version_dir = app_dir.join(new_version);
    if std::fs::create_dir_all(&new_version_dir).is_err() {
        return;
    }

    // Copy files from old version directory to new.
    if let Ok(entries) = std::fs::read_dir(&version_dir) {
        for entry in entries.flatten() {
            if !entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
                continue;
            }
            let name = entry.file_name();
            if name.to_string_lossy().contains("__self_delete__") {
                continue;
            }
            let _ = std::fs::copy(entry.path(), new_version_dir.join(&name));
        }
    }

    // Patch manifest.json version.
    let manifest = new_version_dir.join("manifest.json");
    if manifest.exists() {
        if let Ok(text) = std::fs::read_to_string(&manifest) {
            let _ = std::fs::write(&manifest, text.replace(&old_version, new_version));
        }
    }

    // Update the `current` directory junction.
    let current = app_dir.join("current");
    let _ = std::fs::remove_dir(&current);
    use std::os::windows::process::CommandExt;
    let _ = std::process::Command::new("cmd")
        .args([
            "/c",
            "mklink",
            "/J",
            &current.to_string_lossy(),
            &new_version_dir.to_string_lossy(),
        ])
        .creation_flags(0x08000000) // CREATE_NO_WINDOW
        .status();
}

/// Walk the canonical path to find the Scoop version directory.
/// Layout: `<scoop>/apps/<app>/<version>/…`
#[cfg(windows)]
fn find_scoop_version_dir(path: &Path) -> Option<std::path::PathBuf> {
    let mut found_apps = false;
    let mut depth_after_apps = 0u8;
    let mut result = std::path::PathBuf::new();

    for comp in path.components() {
        result.push(comp);
        if found_apps {
            depth_after_apps += 1;
            if depth_after_apps == 2 {
                return Some(result);
            }
        } else if let std::path::Component::Normal(name) = comp {
            if name.to_string_lossy().eq_ignore_ascii_case("apps") {
                found_apps = true;
            }
        }
    }
    None
}

#[cfg(not(windows))]
fn replace_for_scoop(new_exe: &Path, _new_version: &str) -> Result<()> {
    replace_default(new_exe)
}

// ────────────────────────────────────────────────────────────────────────

/// Downloads, extracts, and installs the binary for `version`/`is_beta`.
/// Verifies the release asset exists on GitHub and returns the download URL.
/// Call this early so we fail fast when CI hasn't finished building the
/// release yet.
fn preflight_asset_check(version: &str, is_beta: bool) -> Result<VerifiedAsset> {
    let tag = release_tag(version);
    let expected = asset_name(version, is_beta);
    eprintln!("  Asset: {expected}");
    // Resolving the hash here rather than mid-download keeps the fail-fast
    // property the asset check already had: a release missing its sums fails
    // before the archive is fetched, not after ~150 MiB of it.
    locate_verified_asset(&tag, &expected)
}

/// Record the *currently running* binary's version in user config just before
/// the binary is replaced. The new binary reads this on startup as
/// `previous_version` and decides whether reinstall is required for the
/// transition (e.g. minor/major bumps re-register agents to pick up new MCP
/// tools or hook changes; patch bumps just update the field).
fn record_previous_version() {
    let current = env!("CARGO_PKG_VERSION");
    let mut cfg = UserConfig::load();
    if cfg.previous_version == current {
        return;
    }
    cfg.previous_version = current.to_string();
    if !cfg.save() {
        eprintln!(
            "  \x1b[33mwarning:\x1b[0m could not record previous version; \
             run `tokensave reinstall` manually if new tools aren't registered"
        );
    }
}

fn perform_upgrade(version: &str, asset: &VerifiedAsset, method: &InstallMethod) -> Result<()> {
    let bin_name = if cfg!(windows) {
        "tokensave.exe"
    } else {
        "tokensave"
    };

    let staged = download_and_extract(&asset.url, bin_name, &asset.sha256)?;

    let label = match method {
        InstallMethod::Brew => " (Homebrew Cellar)",
        InstallMethod::Scoop => " (Scoop)",
        _ => "",
    };
    eprint!("  Replacing binary{label}...");
    replace_binary(staged.path(), method, version)?;
    eprintln!(" Done");

    Ok(())
}

fn brew_upgrade_command() -> (&'static str, [&'static str; 2]) {
    ("brew", ["upgrade", "tokensave"])
}

fn run_brew_upgrade(current: &str) -> Result<String> {
    eprintln!("Updating Homebrew formula cache...");
    let update_ok = std::process::Command::new("brew")
        .args(["update", "--quiet"])
        .status()
        .is_ok_and(|s| s.success());
    if !update_ok {
        eprintln!("  warning: `brew update` failed — continuing with existing cache");
    }

    let (program, args) = brew_upgrade_command();
    eprintln!(
        "Delegating upgrade to Homebrew: {program} {}",
        args.join(" ")
    );

    let status = std::process::Command::new(program)
        .args(args)
        .status()
        .map_err(io_err("failed to run Homebrew upgrade"))?;

    if status.success() {
        record_previous_version();
        Ok(current.to_string())
    } else {
        Err(TokenSaveError::Config {
            message: format!("Homebrew upgrade failed with status: {status}"),
        })
    }
}

/// A running tokensave process other than this one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunningProcess {
    pub pid: u32,
    /// Command line (or process name when the command line is unavailable).
    pub description: String,
}

/// Strip a case-insensitive `.exe` suffix from a Windows process name,
/// without panicking when the last 4 bytes of `name` don't fall on a UTF-8
/// character boundary.
///
/// Compiled for `test` too (not just `windows`) so the boundary-safety
/// regression test can exercise this logic on any host platform.
#[cfg(any(windows, test))]
fn strip_windows_exe_suffix(name: &str) -> &str {
    let len = name.len();
    if len < 4 || !name.is_char_boundary(len - 4) {
        return name;
    }
    let (stem, suffix) = name.split_at(len - 4);
    if suffix.eq_ignore_ascii_case(".exe") {
        stem
    } else {
        name
    }
}

/// Is `stem` (a basename with any `.exe` suffix already stripped) the
/// tokensave binary, using Windows matching semantics?
///
/// Windows treats file and process names as case-insensitive, so basenames
/// like `TokenSave` or `TOKENSAVE` refer to the same binary as `tokensave`.
///
/// Compiled for `test` too (not just `windows`) so the regression test can
/// exercise Windows matching semantics on any host platform.
#[cfg(any(windows, test))]
fn is_tokensave_stem_windows(stem: &str) -> bool {
    stem.eq_ignore_ascii_case("tokensave")
}

/// Is `name` the tokensave binary (platform-dependent extension included)?
fn is_tokensave_process_name(name: &str) -> bool {
    #[cfg(windows)]
    {
        let stem = strip_windows_exe_suffix(name);
        is_tokensave_stem_windows(stem)
    }
    #[cfg(not(windows))]
    {
        let stem = name.strip_suffix(".exe").unwrap_or(name);
        stem == "tokensave"
    }
}

/// A reduced, pure row used for kill-candidate selection: just enough of a
/// process snapshot (pid, parent pid, name, description) to reason about
/// ancestry without touching sysinfo directly. Keeping this separate from
/// `RunningProcess` lets the selection logic be unit-tested with a
/// hand-built table instead of the real process tree.
#[derive(Debug, Clone, PartialEq, Eq)]
struct ProcessEntry {
    pid: u32,
    parent: Option<u32>,
    name: String,
    description: String,
}

/// PIDs to exclude from kill candidates: this process plus every reachable
/// ancestor found by walking `parent` links in `table`.
///
/// The walk stops as soon as it can no longer make progress safely: the
/// current pid has no entry in `table`, its parent is absent or `0`, or the
/// parent has already been visited (a cycle or self-parent). This guards a
/// Scoop shim (or any other launcher) named `tokensave`/`tokensave.exe` from
/// being offered as a killable "unrelated" process, even when it launched us
/// through an intermediate non-tokensave process (e.g. a shell).
fn self_and_ancestor_pids(table: &[ProcessEntry], self_pid: u32) -> HashSet<u32> {
    let mut excluded = HashSet::new();
    let mut current = Some(self_pid);

    while let Some(pid) = current {
        if pid == 0 || !excluded.insert(pid) {
            break;
        }
        current = table.iter().find(|e| e.pid == pid).and_then(|e| e.parent);
    }

    excluded
}

/// Reduce a process table to the tokensave processes safe to offer as kill
/// candidates: exclude this process and every reachable ancestor, keep the
/// rest that look like tokensave, and preserve pid ordering.
fn kill_candidates(table: &[ProcessEntry], self_pid: u32) -> Vec<RunningProcess> {
    let excluded = self_and_ancestor_pids(table, self_pid);

    let mut found: Vec<RunningProcess> = table
        .iter()
        .filter(|e| !excluded.contains(&e.pid) && is_tokensave_process_name(&e.name))
        .map(|e| RunningProcess {
            pid: e.pid,
            description: e.description.clone(),
        })
        .collect();
    found.sort_by_key(|p| p.pid);
    found
}

/// List running tokensave processes, excluding this one and its ancestors.
///
/// These are mostly MCP servers spawned by editors/agents. They hold the old
/// binary's DB handles open, so upgrading under them can leave a server
/// running code that no longer matches the on-disk index format.
fn find_running_processes() -> Vec<RunningProcess> {
    use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System};

    let self_pid = std::process::id();
    let mut sys = System::new();
    sys.refresh_processes_specifics(
        ProcessesToUpdate::All,
        true,
        ProcessRefreshKind::new().with_cmd(sysinfo::UpdateKind::Always),
    );

    let table: Vec<ProcessEntry> = sys
        .processes()
        .values()
        .map(|p| {
            let cmd: Vec<String> = p
                .cmd()
                .iter()
                .map(|a| a.to_string_lossy().into_owned())
                .collect();
            let name = p.name().to_string_lossy().into_owned();
            let description = if cmd.is_empty() {
                name.clone()
            } else {
                cmd.join(" ")
            };
            ProcessEntry {
                pid: p.pid().as_u32(),
                parent: p.parent().map(sysinfo::Pid::as_u32),
                name,
                description,
            }
        })
        .collect();

    kill_candidates(&table, self_pid)
}

/// Terminate `procs`; returns the number successfully signalled.
fn kill_processes(procs: &[RunningProcess]) -> usize {
    use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};

    let pids: Vec<Pid> = procs.iter().map(|p| Pid::from_u32(p.pid)).collect();
    let mut sys = System::new();
    sys.refresh_processes_specifics(
        ProcessesToUpdate::Some(&pids),
        true,
        ProcessRefreshKind::new(),
    );

    let mut killed = 0;
    for proc in procs {
        let pid = Pid::from_u32(proc.pid);
        match sys.process(pid) {
            Some(p) if p.kill() => {
                eprintln!("  \x1b[32m✔\x1b[0m killed pid {}", proc.pid);
                killed += 1;
            }
            Some(_) => eprintln!("  \x1b[33m!\x1b[0m failed to kill pid {}", proc.pid),
            // Already gone between listing and killing — treat as success.
            None => killed += 1,
        }
    }
    killed
}

/// Decide whether the upgrade may proceed after attempting to stop blocking
/// tokensave processes.
///
/// v7.8.0 defines "stopped" as *successfully signalled*: this does not wait
/// for the OS to finish tearing a process down, and it does not rescan for
/// respawned processes. If fewer processes were signalled than requested,
/// the upgrade is aborted rather than proceeding while an old binary may
/// still be running.
fn post_kill_outcome(requested: usize, killed: usize) -> Result<()> {
    if killed >= requested {
        return Ok(());
    }
    Err(TokenSaveError::Config {
        message: format!(
            "upgrade stopped: only {killed}/{requested} running tokensave process(es) could be stopped.\n  \
             Stop the remaining process(es) manually, then retry the upgrade.",
        ),
    })
}

/// Handle tokensave processes that are still running before an upgrade.
///
/// With `kill` set, terminate them without asking. Otherwise ask, but only
/// when there is something to kill and stdin is a TTY; a non-interactive run
/// just warns and continues. If a kill was requested (via `--kill` or an
/// interactive `y`) and not every process could be stopped, the upgrade is
/// aborted rather than proceeding under a still-running old binary.
fn handle_running_processes(kill: bool) -> Result<()> {
    use std::io::{IsTerminal, Write};

    let procs = find_running_processes();
    if procs.is_empty() {
        return Ok(());
    }

    eprintln!("{} other tokensave process(es) running:", procs.len());
    for p in &procs {
        eprintln!("  • pid {}{}", p.pid, p.description);
    }

    if !kill {
        if !std::io::stdin().is_terminal() {
            eprintln!(
                "  \x1b[33m!\x1b[0m Continuing without killing them (non-interactive; use --kill)."
            );
            return Ok(());
        }
        eprint!("  Kill them before upgrading? [y/N] ");
        std::io::stderr().flush().ok();
        let mut answer = String::new();
        if std::io::stdin().read_line(&mut answer).is_err() {
            return Ok(());
        }
        if !answer.trim().eq_ignore_ascii_case("y") {
            eprintln!("  Leaving them running.");
            return Ok(());
        }
    }

    let requested = procs.len();
    let killed = kill_processes(&procs);
    eprintln!("Killed {killed}/{requested} process(es).");
    post_kill_outcome(requested, killed)
}

/// Check for a newer version and perform the upgrade if one is available.
///
/// With `kill` set, any other running tokensave processes are terminated
/// without prompting.
///
/// Returns the new version string on success.
pub fn run_upgrade(kill: bool) -> Result<String> {
    let current = env!("CARGO_PKG_VERSION");
    let is_beta = cloud::is_beta();
    let channel = if is_beta { "beta" } else { "stable" };
    let method = cloud::detect_install_method();

    let method_suffix = match &method {
        InstallMethod::Brew => " · Homebrew",
        InstallMethod::Scoop => " · Scoop",
        InstallMethod::Cargo => " · cargo",
        InstallMethod::Unknown => "",
    };
    eprintln!("Current version: v{current} ({channel} channel{method_suffix})");

    if matches!(method, InstallMethod::Brew) {
        // Homebrew decides for itself whether there is anything to do, so the
        // running-process check has to happen before delegating.
        handle_running_processes(kill)?;
        return run_brew_upgrade(current);
    }

    eprintln!("Checking for updates...");

    // Name the condition that actually holds. A release with no asset for this
    // platform used to be reported as an unreachable network, sending people to
    // debug a working connection (#513).
    let latest = cloud::try_fetch_latest_version().map_err(|e| TokenSaveError::Update {
        message: match e {
            cloud::VersionCheckError::Unreachable { .. } => {
                format!("failed to check for updates — {e}")
            }
            _ => format!("{e}. Staying on v{current}"),
        },
    })?;

    let latest = match classify_upgrade(current, &latest) {
        UpgradeStatus::AlreadyCurrent => {
            eprintln!("\x1b[32m✔\x1b[0m Already up to date (v{current}).");
            return Ok(current.to_string());
        }
        UpgradeStatus::UpgradeAvailable(latest) => latest,
    };

    eprintln!("Upgrading v{current} → v{latest}...");

    handle_running_processes(kill)?;

    let asset = preflight_asset_check(latest, is_beta)?;

    perform_upgrade(latest, &asset, &method)?;
    record_previous_version();
    eprintln!("\x1b[32m✔\x1b[0m Successfully upgraded to v{latest}!");
    Ok(latest.to_string())
}

/// Print the current channel.
pub fn show_channel() {
    let current = env!("CARGO_PKG_VERSION");
    let channel = if cloud::is_beta() { "beta" } else { "stable" };
    eprintln!("v{current} ({channel})");
}

/// Switch to a different channel by downloading the latest release from it.
pub fn switch_channel(target_channel: &str) -> Result<String> {
    let current = env!("CARGO_PKG_VERSION");
    let current_is_beta = cloud::is_beta();
    let current_channel = if current_is_beta { "beta" } else { "stable" };
    let method = cloud::detect_install_method();

    let target_is_beta = match target_channel {
        "beta" => true,
        "stable" => false,
        other => {
            return Err(TokenSaveError::Config {
                message: format!("unknown channel '{other}'. Valid channels: stable, beta"),
            });
        }
    };

    if target_is_beta == current_is_beta {
        eprintln!("Already on the {current_channel} channel (v{current}).");
        eprintln!("Run `tokensave upgrade` to check for updates within this channel.");
        return Ok(current.to_string());
    }

    eprintln!("Switching from {current_channel} to {target_channel}...");

    let latest = if target_is_beta {
        cloud::try_fetch_latest_beta_version()
    } else {
        cloud::try_fetch_latest_stable_version()
    }
    .map_err(|e| TokenSaveError::Update {
        message: format!("cannot switch to the {target_channel} channel — {e}"),
    })?;

    eprintln!("  Target: v{latest}");

    let asset = preflight_asset_check(&latest, target_is_beta)?;

    perform_upgrade(&latest, &asset, &method)?;
    record_previous_version();
    eprintln!("\x1b[32m✔\x1b[0m Switched to {target_channel} channel: v{latest}");
    Ok(latest)
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::case_sensitive_file_extension_comparisons,
    clippy::doc_markdown,
    clippy::redundant_closure_for_method_calls
)]
mod tests {
    use super::*;

    /// The staging directory must not be at a name another local user can
    /// predict. The old path was `temp_dir()/tokensave_upgrade_<pid>`, and a
    /// pid is both guessable and observable, so a symlink planted there ahead
    /// of the download would have been followed on extraction (#525).
    #[test]
    fn the_staging_directory_is_not_a_predictable_path() {
        let a = new_staging_dir().expect("staging dir");
        let b = new_staging_dir().expect("staging dir");

        assert_ne!(
            a.path(),
            b.path(),
            "two staging directories in the same process must not collide"
        );

        let legacy = std::env::temp_dir().join(format!("tokensave_upgrade_{}", std::process::id()));
        assert_ne!(a.path(), legacy, "must not reuse the old pid-derived name");
    }

    /// `TempDir` must create the directory rather than adopt one that is
    /// already there — adopting is what makes a planted path dangerous.
    #[test]
    fn the_staging_directory_is_freshly_created() {
        let dir = new_staging_dir().expect("staging dir");
        assert!(dir.path().is_dir(), "the directory must exist");
        assert!(
            std::fs::read_dir(dir.path())
                .expect("read staging dir")
                .next()
                .is_none(),
            "a freshly created staging directory must be empty"
        );
    }

    /// On Unix the directory must not be readable or writable by other users,
    /// so nothing can race the extracted binary between write and install.
    /// `tempdir()` alone creates with `0777 & !umask` — commonly `0755`, which
    /// leaves the staged binary readable by every other local user while it
    /// sits there. The narrowing is therefore explicit, and asserted.
    #[cfg(unix)]
    #[test]
    fn the_staging_directory_is_private_to_this_user() {
        use std::os::unix::fs::PermissionsExt;

        let dir = new_staging_dir().expect("staging dir");
        let mode = std::fs::metadata(dir.path())
            .expect("stat staging dir")
            .permissions()
            .mode()
            & 0o777;

        assert_eq!(
            mode, 0o700,
            "staging directory should be user-only, got {mode:o}"
        );
    }

    /// The staged binary sits inside that directory, so its full path inherits
    /// the directory's unpredictability even though the file name is fixed.
    #[test]
    fn the_staged_binary_lives_inside_the_private_directory() {
        let dir = new_staging_dir().expect("staging dir");
        let staged = dir.path().join(format!(
            "tokensave{}",
            if cfg!(windows) { ".exe" } else { "" }
        ));

        assert!(
            staged.starts_with(dir.path()),
            "the staged binary must be contained by the private directory"
        );
    }

    // ── SHA256 verification (#525) ───────────────────────────────────────

    #[test]
    fn sha256_hex_matches_a_known_vector() {
        // The empty-input digest, so this pins the encoding rather than
        // restating whatever the implementation happens to produce.
        assert_eq!(
            sha256_hex(b""),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
        assert_eq!(
            sha256_hex(b"abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }

    #[test]
    fn a_sums_listing_yields_the_hash_for_the_named_asset() {
        let listing = "\
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855  tokensave-v1.2.3-x86_64-linux.tar.gz
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad  tokensave-v1.2.3-aarch64-macos.tar.gz
";
        assert_eq!(
            sha256_for_asset(listing, "tokensave-v1.2.3-aarch64-macos.tar.gz").as_deref(),
            Some("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
        );
    }

    #[test]
    fn a_sums_listing_accepts_the_binary_mode_marker() {
        // `sha256sum -b` and the Windows leg emit `hash *name`.
        let listing =
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 *tokensave-v1.2.3-x86_64-windows.zip\n";
        assert_eq!(
            sha256_for_asset(listing, "tokensave-v1.2.3-x86_64-windows.zip").as_deref(),
            Some("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
        );
    }

    #[test]
    fn an_asset_absent_from_the_listing_has_no_hash() {
        // The caller turns this into a refusal, not a skipped check — a
        // release that does not name our asset must not install (#525).
        let listing =
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855  some-other-asset.tar.gz\n";
        assert!(sha256_for_asset(listing, "tokensave-v1.2.3-x86_64-linux.tar.gz").is_none());
    }

    #[test]
    fn a_malformed_or_truncated_hash_is_not_accepted() {
        // A short, over-long, or non-hex field must not be treated as a hash:
        // it would compare unequal to every real digest and turn a verifiable
        // release into an unexplained mismatch.
        for bad in [
            "deadbeef  tokensave-v1.2.3-x86_64-linux.tar.gz",
            "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz  tokensave-v1.2.3-x86_64-linux.tar.gz",
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855aa  tokensave-v1.2.3-x86_64-linux.tar.gz",
        ] {
            assert!(
                sha256_for_asset(bad, "tokensave-v1.2.3-x86_64-linux.tar.gz").is_none(),
                "{bad} should not parse as a hash"
            );
        }
    }

    #[test]
    fn an_empty_or_blank_listing_has_no_hash() {
        for listing in ["", "\n", "   \n\n"] {
            assert!(sha256_for_asset(listing, "tokensave-v1.2.3-x86_64-linux.tar.gz").is_none());
        }
    }

    #[test]
    fn a_hash_is_compared_case_insensitively() {
        // Some tools emit uppercase hex; normalising on parse keeps that from
        // reading as tampering.
        let listing =
            "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855  tokensave-v1.2.3-x86_64-linux.tar.gz\n";
        assert_eq!(
            sha256_for_asset(listing, "tokensave-v1.2.3-x86_64-linux.tar.gz").as_deref(),
            Some(sha256_hex(b"").as_str())
        );
    }

    #[test]
    fn test_asset_name_stable() {
        let name = asset_name("3.3.3", false);
        assert!(name.starts_with("tokensave-v3.3.3-"));
        assert!(!name.contains("beta"));
        if cfg!(windows) {
            assert!(name.ends_with(".zip"));
        } else {
            assert!(name.ends_with(".tar.gz"));
        }
    }

    #[test]
    fn test_asset_name_beta() {
        let name = asset_name("4.0.2-beta.1", true);
        assert!(name.starts_with("tokensave-beta-v4.0.2-beta.1-"));
        if cfg!(windows) {
            assert!(name.ends_with(".zip"));
        } else {
            assert!(name.ends_with(".tar.gz"));
        }
    }

    #[test]
    fn tokensave_process_names_are_recognized() {
        assert!(is_tokensave_process_name("tokensave"));
        assert!(is_tokensave_process_name("tokensave.exe"));
        assert!(!is_tokensave_process_name("tokensave-helper"));
        assert!(!is_tokensave_process_name("cargo"));
        assert!(!is_tokensave_process_name(""));
    }

    #[test]
    fn strip_windows_exe_suffix_does_not_panic_on_unicode_boundary() {
        // Each '€' is a 3-byte UTF-8 sequence, so this 6-byte, 2-char name
        // has `len - 4 == 2`, a byte offset that falls *inside* the first
        // '€' rather than on a char boundary. The naive `name[len - 4..]`
        // slice used to panic here even though the name has nothing to do
        // with tokensave or `.exe`.
        let name = "€€";
        assert_eq!(strip_windows_exe_suffix(name), name);
    }

    #[test]
    fn is_tokensave_process_name_ignores_unrelated_unicode_names() {
        assert!(!is_tokensave_process_name("€€"));
    }

    #[test]
    fn is_tokensave_stem_windows_is_ascii_case_insensitive() {
        // Windows file/process names are case-insensitive: mixed-case
        // basenames like `TokenSave.EXE` or `TOKENSAVE.exe` (after the
        // `.exe` suffix has already been stripped) must still be recognized
        // as the tokensave binary under Windows matching semantics, even
        // though the Unix comparison stays exact/case-sensitive.
        assert!(is_tokensave_stem_windows(strip_windows_exe_suffix(
            "TokenSave.EXE"
        )));
        assert!(is_tokensave_stem_windows(strip_windows_exe_suffix(
            "TOKENSAVE.exe"
        )));
        assert!(is_tokensave_stem_windows("tokensave"));
        assert!(!is_tokensave_stem_windows("tokensave-helper"));
    }

    #[test]
    fn find_running_processes_excludes_self() {
        let self_pid = std::process::id();
        assert!(find_running_processes().iter().all(|p| p.pid != self_pid));
    }

    fn entry(pid: u32, parent: Option<u32>, name: &str, description: &str) -> ProcessEntry {
        ProcessEntry {
            pid,
            parent,
            name: name.to_string(),
            description: description.to_string(),
        }
    }

    #[test]
    fn kill_candidates_excludes_scoop_shim_parent_launching_self() {
        // A Scoop shim named tokensave.exe launched us directly.
        let table = [
            entry(50, None, "tokensave.exe", r"C:\shims\tokensave.exe upgrade"),
            entry(100, Some(50), "tokensave.exe", "tokensave.exe upgrade"),
        ];
        assert!(kill_candidates(&table, 100).is_empty());
    }

    #[test]
    fn kill_candidates_excludes_tokensave_grandparent_behind_shell() {
        // self -> bash -> tokensave (e.g. a launcher script invoked via a shell).
        let table = [
            entry(40, None, "tokensave", "tokensave"),
            entry(60, Some(40), "bash", "bash"),
            entry(100, Some(60), "tokensave", "tokensave upgrade"),
        ];
        assert!(kill_candidates(&table, 100).is_empty());
    }

    #[test]
    fn kill_candidates_keeps_unrelated_server_excludes_launcher_ancestor() {
        let table = [
            entry(50, None, "tokensave.exe", r"C:\shims\tokensave.exe upgrade"),
            entry(100, Some(50), "tokensave", "tokensave upgrade --kill"),
            entry(200, None, "tokensave", "tokensave serve"),
        ];
        let candidates = kill_candidates(&table, 100);
        assert_eq!(
            candidates,
            vec![RunningProcess {
                pid: 200,
                description: "tokensave serve".to_string(),
            }]
        );
    }

    #[test]
    fn self_and_ancestor_pids_terminates_on_self_parent_cycle() {
        let table = [entry(100, Some(100), "tokensave", "tokensave")];
        let excluded = self_and_ancestor_pids(&table, 100);
        assert_eq!(excluded, HashSet::from([100]));
    }

    #[test]
    fn self_and_ancestor_pids_terminates_on_two_cycle() {
        let table = [
            entry(100, Some(200), "tokensave", "tokensave"),
            entry(200, Some(100), "tokensave", "tokensave"),
        ];
        let excluded = self_and_ancestor_pids(&table, 100);
        assert_eq!(excluded, HashSet::from([100, 200]));
    }

    #[test]
    fn kill_candidates_excludes_lookalikes_and_preserves_pid_order() {
        let table = [
            entry(400, None, "tokensave", "tokensave serve two"),
            entry(300, None, "tokensave-helper", "tokensave-helper"),
            entry(250, None, "tokensave", "tokensave serve"),
        ];
        let candidates = kill_candidates(&table, 100);
        assert_eq!(
            candidates,
            vec![
                RunningProcess {
                    pid: 250,
                    description: "tokensave serve".to_string(),
                },
                RunningProcess {
                    pid: 400,
                    description: "tokensave serve two".to_string(),
                },
            ]
        );
    }

    #[test]
    fn self_and_ancestor_pids_stops_on_missing_parent_entry() {
        // self's parent pid (999) has no entry in the table. The walk records
        // it (harmless — it can never match a real table row) and then halts
        // because there is nothing further to look up.
        let table = [entry(100, Some(999), "bash", "bash")];
        let excluded = self_and_ancestor_pids(&table, 100);
        assert_eq!(excluded, HashSet::from([100, 999]));
    }

    #[test]
    fn self_and_ancestor_pids_stops_on_zero_parent() {
        let table = [entry(100, Some(0), "bash", "bash")];
        let excluded = self_and_ancestor_pids(&table, 100);
        assert_eq!(excluded, HashSet::from([100]));
    }

    #[test]
    fn self_and_ancestor_pids_stops_when_self_has_no_entry() {
        // self_pid has no corresponding row in the table at all.
        let table = [entry(1, None, "bash", "bash")];
        let excluded = self_and_ancestor_pids(&table, 100);
        assert_eq!(excluded, HashSet::from([100]));
    }

    #[test]
    fn self_and_ancestor_pids_walks_a_deep_chain() {
        let table = [
            entry(1, None, "init", "init"),
            entry(10, Some(1), "bash", "bash"),
            entry(20, Some(10), "bash", "bash"),
            entry(30, Some(20), "tokensave", "tokensave"),
            entry(100, Some(30), "tokensave", "tokensave upgrade"),
        ];
        let excluded = self_and_ancestor_pids(&table, 100);
        assert_eq!(excluded, HashSet::from([100, 30, 20, 10, 1]));
    }

    #[test]
    #[cfg(unix)]
    fn live_snapshot_includes_self_and_real_parent_pid() {
        extern "C" {
            fn getppid() -> i32;
        }

        use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System};
        let self_pid = std::process::id();
        let real_ppid = unsafe { getppid() } as u32;

        let mut sys = System::new();
        sys.refresh_processes_specifics(
            ProcessesToUpdate::All,
            true,
            ProcessRefreshKind::new().with_cmd(sysinfo::UpdateKind::Always),
        );

        let self_proc = sys
            .process(sysinfo::Pid::from_u32(self_pid))
            .expect("current process must be present in its own snapshot");
        assert_eq!(
            self_proc.parent().map(|p| p.as_u32()),
            Some(real_ppid),
            "sysinfo's reported parent must match the real OS parent pid"
        );
    }

    #[test]
    fn post_kill_outcome_succeeds_when_all_requested_were_killed() {
        assert!(post_kill_outcome(3, 3).is_ok());
    }

    #[test]
    fn post_kill_outcome_succeeds_when_nothing_was_requested() {
        assert!(post_kill_outcome(0, 0).is_ok());
    }

    #[test]
    fn post_kill_outcome_fails_on_partial_kill() {
        let err = post_kill_outcome(3, 2).unwrap_err();
        let message = err.to_string();
        assert!(
            message.contains('2'),
            "message should include killed count: {message}"
        );
        assert!(
            message.contains('3'),
            "message should include requested count: {message}"
        );
        assert!(
            message.to_lowercase().contains("upgrade") && message.to_lowercase().contains("stop"),
            "message should explain the upgrade stopped: {message}"
        );
        assert!(
            message.to_lowercase().contains("manually") && message.to_lowercase().contains("retry"),
            "message should tell the user to stop them manually and retry: {message}"
        );
    }

    #[test]
    fn post_kill_outcome_fails_on_total_kill_failure() {
        let err = post_kill_outcome(3, 0).unwrap_err();
        let message = err.to_string();
        assert!(message.contains('0'));
        assert!(message.contains('3'));
    }

    #[test]
    #[cfg(unix)]
    fn kill_processes_tolerates_dead_pids() {
        // A process that has already exited counts as killed, not as a failure.
        let mut child = std::process::Command::new("sleep")
            .arg("30")
            .spawn()
            .unwrap();
        let pid = child.id();
        child.kill().unwrap();
        child.wait().unwrap();

        let killed = kill_processes(&[RunningProcess {
            pid,
            description: "sleep 30".to_string(),
        }]);
        assert_eq!(killed, 1);
    }

    #[test]
    #[cfg(unix)]
    fn kill_processes_kills_a_live_child() {
        let mut child = std::process::Command::new("sleep")
            .arg("30")
            .spawn()
            .unwrap();
        let killed = kill_processes(&[RunningProcess {
            pid: child.id(),
            description: "sleep 30".to_string(),
        }]);
        assert_eq!(killed, 1);
        // Reap so the test leaves no zombie behind.
        child.wait().ok();
    }

    #[test]
    fn test_release_tag() {
        assert_eq!(release_tag("3.3.3"), "v3.3.3");
        assert_eq!(release_tag("4.0.2-beta.1"), "v4.0.2-beta.1");
    }

    #[test]
    fn test_current_platform_not_unknown() {
        assert_ne!(current_platform(), "unknown");
    }

    #[test]
    fn brew_upgrade_command_delegates_to_homebrew() {
        let (program, args) = brew_upgrade_command();

        assert_eq!(program, "brew");
        assert_eq!(args, ["upgrade", "tokensave"]);
    }

    #[test]
    fn test_asset_name_matches_ci_convention() {
        let stable = asset_name("3.3.3", false);
        let platform = current_platform();
        if cfg!(windows) {
            assert_eq!(stable, format!("tokensave-v3.3.3-{platform}.zip"));
        } else {
            assert_eq!(stable, format!("tokensave-v3.3.3-{platform}.tar.gz"));
        }

        let beta = asset_name("4.0.2-beta.1", true);
        if cfg!(windows) {
            assert_eq!(beta, format!("tokensave-beta-v4.0.2-beta.1-{platform}.zip"));
        } else {
            assert_eq!(
                beta,
                format!("tokensave-beta-v4.0.2-beta.1-{platform}.tar.gz")
            );
        }
    }

    #[test]
    fn classify_upgrade_marks_equal_version_as_already_current() {
        assert_eq!(
            classify_upgrade("4.0.3", "4.0.3"),
            UpgradeStatus::AlreadyCurrent
        );
    }

    #[test]
    fn classify_upgrade_marks_newer_version_as_upgrade_available() {
        assert_eq!(
            classify_upgrade("4.0.2", "4.0.3"),
            UpgradeStatus::UpgradeAvailable("4.0.3")
        );
    }

    #[test]
    fn switch_channel_same_channel_is_a_successful_noop() {
        let current = env!("CARGO_PKG_VERSION").to_string();
        let current_channel = if cloud::is_beta() { "beta" } else { "stable" };

        let result = switch_channel(current_channel);

        assert_eq!(result.unwrap(), current);
    }

    // ── Regression tests for symlink upgrade bug ────────────────────────
    //
    // The self-replace crate resolves symlinks via `fs::read_link`, which
    // returns the raw target (often relative for Homebrew). Subsequent
    // operations resolve that relative path from CWD instead of the
    // symlink's parent, causing ENOENT.
    //
    // Our fix: canonicalize the exe path before passing it to self_update.
    // These tests verify the canonicalization works correctly for every
    // symlink layout we've seen in the wild.

    #[cfg(unix)]
    mod symlink_upgrade_regression {
        use std::fs;
        use std::os::unix::fs::symlink;
        use std::path::PathBuf;

        /// Helper: create a fake binary file in a Homebrew-style Cellar layout.
        /// Returns (cellar_binary_path, symlink_path, tmp_guard).
        fn homebrew_layout() -> (PathBuf, PathBuf, tempfile::TempDir) {
            let tmp = tempfile::tempdir().unwrap();
            // Cellar/tokensave/4.1.1-beta.1/bin/tokensave
            let cellar_bin_dir = tmp.path().join("Cellar/tokensave/4.1.1-beta.1/bin");
            fs::create_dir_all(&cellar_bin_dir).unwrap();
            let real_binary = cellar_bin_dir.join("tokensave");
            fs::write(&real_binary, b"fake-binary").unwrap();

            // bin/tokensave -> ../Cellar/tokensave/4.1.1-beta.1/bin/tokensave
            let bin_dir = tmp.path().join("bin");
            fs::create_dir_all(&bin_dir).unwrap();
            let link_path = bin_dir.join("tokensave");
            symlink("../Cellar/tokensave/4.1.1-beta.1/bin/tokensave", &link_path).unwrap();

            (real_binary, link_path, tmp)
        }

        #[test]
        fn read_link_returns_relative_path_for_homebrew_symlink() {
            let (_real, link, _tmp) = homebrew_layout();
            let target = fs::read_link(&link).unwrap();
            assert!(
                target.is_relative(),
                "Homebrew symlink target should be relative, got: {target:?}"
            );
            assert_eq!(
                target,
                PathBuf::from("../Cellar/tokensave/4.1.1-beta.1/bin/tokensave")
            );
        }

        #[test]
        fn relative_read_link_fails_from_wrong_cwd() {
            // This is the exact bug: read_link returns a relative path, and
            // metadata() resolves it from CWD rather than the symlink's parent.
            let (_real, link, _tmp) = homebrew_layout();
            let target = fs::read_link(&link).unwrap();

            // From a different directory (e.g. the user's home), the relative
            // path doesn't resolve to anything valid.
            let other_dir = tempfile::tempdir().unwrap();
            let wrong_path = other_dir.path().join(&target);
            assert!(
                wrong_path.metadata().is_err(),
                "relative symlink target should NOT resolve from an unrelated directory"
            );
        }

        #[test]
        fn canonicalize_resolves_relative_symlink_to_absolute() {
            let (real, link, _tmp) = homebrew_layout();
            let canonical = link.canonicalize().unwrap();
            let real_canonical = real.canonicalize().unwrap();
            assert_eq!(
                canonical, real_canonical,
                "canonicalize should resolve symlink to the real Cellar path"
            );
            assert!(canonical.is_absolute());
        }

        #[test]
        fn canonical_path_differs_from_symlink_path() {
            // This is the key property our fix relies on: after canonicalization,
            // the path differs from the symlink path, which makes self_update
            // choose the Move code path instead of the buggy self_replace path.
            let (_real, link, _tmp) = homebrew_layout();
            let canonical = link.canonicalize().unwrap();
            assert_ne!(
                canonical, link,
                "canonical path and symlink path must differ so self_update uses Move"
            );
        }

        #[test]
        fn canonical_path_parent_exists() {
            // Move::to_dest needs the parent directory to exist for rename().
            let (_real, link, _tmp) = homebrew_layout();
            let canonical = link.canonicalize().unwrap();
            assert!(
                canonical.parent().unwrap().is_dir(),
                "parent of canonical path must be a real directory"
            );
        }

        #[test]
        fn canonicalize_is_identity_for_non_symlink() {
            // For direct installs (cargo install, manual copy), canonicalize
            // returns the same path, so self_replace is still used — no
            // behavior change for non-symlink installs.
            let tmp = tempfile::tempdir().unwrap();
            let binary = tmp.path().join("tokensave");
            fs::write(&binary, b"fake-binary").unwrap();

            let canonical = binary.canonicalize().unwrap();
            let original_canonical = binary.canonicalize().unwrap();
            assert_eq!(canonical, original_canonical);
        }

        #[test]
        fn canonicalize_resolves_absolute_symlink() {
            // Some package managers use absolute symlinks.
            let tmp = tempfile::tempdir().unwrap();
            let real_dir = tmp.path().join("lib");
            fs::create_dir_all(&real_dir).unwrap();
            let real_binary = real_dir.join("tokensave");
            fs::write(&real_binary, b"fake-binary").unwrap();

            let bin_dir = tmp.path().join("bin");
            fs::create_dir_all(&bin_dir).unwrap();
            let link = bin_dir.join("tokensave");
            symlink(&real_binary, &link).unwrap();

            let canonical = link.canonicalize().unwrap();
            assert_eq!(canonical, real_binary.canonicalize().unwrap());
            assert_ne!(canonical, link);
        }

        #[test]
        fn canonicalize_resolves_chained_symlinks() {
            // A -> B -> C: canonicalize must reach C.
            let tmp = tempfile::tempdir().unwrap();
            let real = tmp.path().join("real_binary");
            fs::write(&real, b"fake-binary").unwrap();

            let link_b = tmp.path().join("link_b");
            symlink(&real, &link_b).unwrap();

            let link_a = tmp.path().join("link_a");
            symlink(&link_b, &link_a).unwrap();

            let canonical = link_a.canonicalize().unwrap();
            assert_eq!(canonical, real.canonicalize().unwrap());
        }

        #[test]
        fn canonicalize_resolves_symlink_with_dotdot_in_real_path() {
            // Real path contains ".." components — canonicalize normalizes them.
            let tmp = tempfile::tempdir().unwrap();
            let deep = tmp.path().join("a/b/c");
            fs::create_dir_all(&deep).unwrap();
            let real = deep.join("tokensave");
            fs::write(&real, b"fake-binary").unwrap();

            // Construct a path with ".." that still reaches the same file
            let dotdot_path = tmp.path().join("a/b/c/../c/tokensave");
            let canonical = dotdot_path.canonicalize().unwrap();
            assert_eq!(canonical, real.canonicalize().unwrap());
            assert!(
                !canonical.to_string_lossy().contains(".."),
                "canonical path should have no '..' components"
            );
        }

        #[test]
        fn rename_works_for_canonical_cellar_path() {
            // Simulate what Move::to_dest does: rename a new binary over the
            // canonical (Cellar) path. The symlink continues to work.
            let (real, link, _tmp) = homebrew_layout();

            // "New binary" in a temp location (same filesystem)
            let new_binary = real.parent().unwrap().join(".tokensave.__temp__");
            fs::write(&new_binary, b"upgraded-binary").unwrap();

            // Rename new binary over the real path (what Move does)
            let canonical = link.canonicalize().unwrap();
            fs::rename(&new_binary, &canonical).unwrap();

            // Verify: reading through the symlink yields the new content
            let content = fs::read(&link).unwrap();
            assert_eq!(content, b"upgraded-binary");

            // Verify: the canonical path also has new content
            let content = fs::read(&canonical).unwrap();
            assert_eq!(content, b"upgraded-binary");
        }

        #[test]
        fn symlink_survives_rename_replacement() {
            // After the upgrade replaces the Cellar binary, the Homebrew
            // symlink must still point to a valid file.
            let (_real, link, _tmp) = homebrew_layout();
            let canonical = link.canonicalize().unwrap();

            // Replace the binary at the canonical path
            fs::write(&canonical, b"new-version").unwrap();

            // Symlink still works
            assert!(
                link.exists(),
                "symlink must still resolve after replacement"
            );
            assert!(
                fs::symlink_metadata(&link)
                    .unwrap()
                    .file_type()
                    .is_symlink(),
                "must still be a symlink"
            );
            assert_eq!(fs::read(&link).unwrap(), b"new-version");
        }

        #[test]
        fn canonicalize_fails_for_dangling_symlink() {
            // If the Cellar dir was removed (brew cleanup), canonicalize
            // should fail and we gracefully fall back to the default.
            let tmp = tempfile::tempdir().unwrap();
            let bin_dir = tmp.path().join("bin");
            fs::create_dir_all(&bin_dir).unwrap();
            let link = bin_dir.join("tokensave");
            symlink("../Cellar/tokensave/old/bin/tokensave", &link).unwrap();
            // Target doesn't exist — dangling symlink
            assert!(
                link.canonicalize().is_err(),
                "canonicalize should fail for dangling symlinks"
            );
        }

        #[test]
        fn our_fix_pattern_handles_all_cases() {
            // Simulate the exact pattern used in run_upgrade/switch_channel:
            //   if let Ok(canonical) = path.canonicalize() { ... }
            // Verify it does the right thing for each scenario.

            // Case 1: relative symlink (Homebrew) — canonical differs
            let (_, link, _tmp) = homebrew_layout();
            let canonical = link.canonicalize();
            assert!(canonical.is_ok());
            assert_ne!(canonical.unwrap(), link);

            // Case 2: direct file — canonical matches
            let tmp2 = tempfile::tempdir().unwrap();
            let direct = tmp2.path().join("tokensave");
            fs::write(&direct, b"binary").unwrap();
            let canonical = direct.canonicalize().unwrap();
            // After canonicalization of the tmpdir itself, they match
            assert_eq!(canonical, direct.canonicalize().unwrap());

            // Case 3: dangling symlink — canonical fails, we skip setting
            // bin_install_path and let self_update use its default
            let tmp3 = tempfile::tempdir().unwrap();
            let dangling = tmp3.path().join("tokensave");
            symlink("/nonexistent/path/tokensave", &dangling).unwrap();
            assert!(dangling.canonicalize().is_err());
        }

        // ── install_binary tests ───────────────────────────────────────

        #[test]
        fn install_binary_replaces_target_atomically() {
            let tmp = tempfile::tempdir().unwrap();
            let target = tmp.path().join("tokensave");
            fs::write(&target, b"old-binary").unwrap();

            let src = tmp.path().join("new-binary");
            fs::write(&src, b"new-binary-content").unwrap();

            super::super::install_binary(&src, &target).unwrap();

            assert_eq!(fs::read(&target).unwrap(), b"new-binary-content");
            // Temp file should be cleaned up
            assert!(!tmp
                .path()
                .join(format!(".tokensave_upgrade_{}", std::process::id()))
                .exists());
        }

        #[test]
        fn install_binary_sets_executable_permission() {
            use std::os::unix::fs::PermissionsExt;

            let tmp = tempfile::tempdir().unwrap();
            let target = tmp.path().join("tokensave");
            fs::write(&target, b"old").unwrap();

            let src = tmp.path().join("new");
            fs::write(&src, b"new").unwrap();

            super::super::install_binary(&src, &target).unwrap();

            let mode = fs::metadata(&target).unwrap().permissions().mode();
            assert_eq!(mode & 0o755, 0o755, "binary should be executable");
        }

        // ── Brew upgrade flow ──────────────────────────────────────────

        #[test]
        fn brew_upgrade_renames_version_dir_and_updates_symlink() {
            let (_real, link, _tmp) = homebrew_layout();

            // Write an "upgraded" binary via the Cellar path
            let canonical = link.canonicalize().unwrap();
            fs::write(&canonical, b"v5.0.0-binary").unwrap();

            // Simulate the Cellar directory rename (4.1.1-beta.1 → 5.0.0)
            let bin_dir = canonical.parent().unwrap();
            let version_dir = bin_dir.parent().unwrap();
            let formula_dir = version_dir.parent().unwrap();
            let cellar_dir = formula_dir.parent().unwrap();
            let _prefix = cellar_dir.parent().unwrap();

            let new_version_dir = formula_dir.join("5.0.0");
            fs::rename(version_dir, &new_version_dir).unwrap();

            // Update the symlink
            let old_target = fs::read_link(&link).unwrap();
            let new_target = PathBuf::from(old_target.to_string_lossy().replacen(
                "4.1.1-beta.1",
                "5.0.0",
                1,
            ));
            fs::remove_file(&link).unwrap();
            symlink(&new_target, &link).unwrap();

            // Verify: symlink resolves and has the new content
            assert!(link.exists(), "symlink must resolve after dir rename");
            assert_eq!(fs::read(&link).unwrap(), b"v5.0.0-binary");

            // Verify: new version directory exists, old one doesn't
            assert!(new_version_dir.exists());
            assert!(!version_dir.exists());

            // Verify: brew would see "5.0.0" as the installed version
            // (brew reads directory names under Cellar/<formula>/)
            let versions: Vec<_> = fs::read_dir(formula_dir)
                .unwrap()
                .filter_map(|e| e.ok())
                .map(|e| e.file_name().to_string_lossy().to_string())
                .collect();
            assert_eq!(versions, vec!["5.0.0"]);
        }

        #[test]
        fn brew_upgrade_updates_install_receipt() {
            let tmp = tempfile::tempdir().unwrap();
            let cellar = tmp.path().join("Cellar/tokensave/4.0.3");
            fs::create_dir_all(cellar.join("bin")).unwrap();
            fs::write(cellar.join("bin/tokensave"), b"binary").unwrap();

            let receipt_content = r#"{
  "source": {
    "versions": { "stable": "4.0.3" }
  },
  "tabfile": "/opt/homebrew/Cellar/tokensave/4.0.3/INSTALL_RECEIPT.json"
}"#;
            fs::write(cellar.join("INSTALL_RECEIPT.json"), receipt_content).unwrap();

            // Simulate rename + receipt update
            let new_dir = tmp.path().join("Cellar/tokensave/4.0.4");
            fs::rename(&cellar, &new_dir).unwrap();

            let text = fs::read_to_string(new_dir.join("INSTALL_RECEIPT.json")).unwrap();
            let updated = text.replace("4.0.3", "4.0.4");
            fs::write(new_dir.join("INSTALL_RECEIPT.json"), &updated).unwrap();

            assert!(updated.contains("\"stable\": \"4.0.4\""));
            assert!(updated.contains("/4.0.4/INSTALL_RECEIPT.json"));
            assert!(!updated.contains("4.0.3"));
        }
    }
}