mise 2026.4.11

The front-end to your dev env
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
use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;

use crate::backend::platform_target::PlatformTarget;
use crate::backend::static_helpers::get_filename_from_url;
use crate::cli::args::BackendArg;
use crate::cli::version::{ARCH, OS};
use crate::config::Settings;
use crate::file::{TarFormat, TarOptions};
use crate::http::HTTP;
use crate::install_context::InstallContext;
use crate::lockfile::{PlatformInfo, ProvenanceType};
use crate::path::{Path, PathBuf, PathExt};
use crate::plugins::VERSION_REGEX;
use crate::registry::REGISTRY;
use crate::toolset::ToolVersion;
use crate::ui::progress_report::SingleReport;
use crate::{
    aqua::aqua_registry_wrapper::{
        AQUA_REGISTRY, AquaChecksum, AquaChecksumType, AquaMinisignType, AquaPackage,
        AquaPackageType,
    },
    cache::{CacheManager, CacheManagerBuilder},
};
use crate::{backend::Backend, config::Config};
use crate::{env, file, github, minisign};
use async_trait::async_trait;
use eyre::{ContextCompat, Result, bail, eyre};
use indexmap::IndexSet;
use itertools::Itertools;
use regex::Regex;
use std::borrow::Cow;
use std::fmt::Debug;
use std::{collections::HashSet, sync::Arc};

#[derive(Debug)]
pub struct AquaBackend {
    ba: Arc<BackendArg>,
    id: String,
    version_tags_cache: CacheManager<Vec<(String, String)>>,
}

#[async_trait]
impl Backend for AquaBackend {
    fn get_type(&self) -> BackendType {
        BackendType::Aqua
    }

    async fn description(&self) -> Option<String> {
        AQUA_REGISTRY
            .package(&self.ba.tool_name)
            .await
            .ok()
            .and_then(|p| p.description.clone())
    }

    async fn install_operation_count(&self, tv: &ToolVersion, _ctx: &InstallContext) -> usize {
        let pkg = match AQUA_REGISTRY
            .package_with_version(&self.id, &[&tv.version])
            .await
        {
            Ok(pkg) => pkg,
            Err(_) => return 3, // fallback to default
        };
        let format = pkg.format(&tv.version, os(), arch()).unwrap_or_default();

        let mut count = 1; // download
        // Count checksum operation if explicitly configured OR if this is a GitHub release
        // (GitHub API may provide a digest even without explicit checksum config)
        if pkg.checksum.as_ref().is_some_and(|c| c.enabled())
            || pkg.r#type == AquaPackageType::GithubRelease
        {
            count += 1;
        }
        if needs_extraction(format, &pkg.r#type) {
            count += 1;
        }
        count
    }

    async fn security_info(&self) -> Vec<crate::backend::SecurityFeature> {
        use crate::backend::SecurityFeature;

        let pkg = match AQUA_REGISTRY.package(&self.ba.tool_name).await {
            Ok(pkg) => pkg,
            Err(_) => return vec![],
        };

        let mut features = vec![];

        // Check base package and all version overrides for security features
        // This gives a complete picture of available security features across all versions
        let all_pkgs: Vec<&AquaPackage> = std::iter::once(&pkg)
            .chain(pkg.version_overrides.iter())
            .collect();

        // Fetch release assets to detect actual security features
        let release_assets = if !pkg.repo_owner.is_empty() && !pkg.repo_name.is_empty() {
            let repo = format!("{}/{}", pkg.repo_owner, pkg.repo_name);
            github::list_releases(&repo)
                .await
                .ok()
                .and_then(|releases| releases.first().cloned())
                .map(|r| r.assets)
                .unwrap_or_default()
        } else {
            vec![]
        };

        // Checksum - check registry config OR actual release assets
        let has_checksum_config = all_pkgs.iter().any(|p| {
            p.checksum
                .as_ref()
                .is_some_and(|checksum| checksum.enabled())
        });
        let has_checksum_assets = release_assets.iter().any(|a| {
            let name = a.name.to_lowercase();
            name.contains("sha256")
                || name.contains("checksum")
                || name.ends_with(".sha256")
                || name.ends_with(".sha512")
        });
        if has_checksum_config || has_checksum_assets {
            let algorithm = all_pkgs
                .iter()
                .filter_map(|p| p.checksum.as_ref())
                .find_map(|c| c.algorithm.as_ref().map(|a| a.to_string()))
                .or_else(|| {
                    if has_checksum_assets {
                        Some("sha256".to_string())
                    } else {
                        None
                    }
                });
            features.push(SecurityFeature::Checksum { algorithm });
        }

        // GitHub Artifact Attestations - check registry config OR actual release assets
        let has_attestations_config = all_pkgs.iter().any(|p| {
            p.github_artifact_attestations
                .as_ref()
                .is_some_and(|a| a.enabled.unwrap_or(true))
        });
        let has_attestations_assets = release_assets.iter().any(|a| {
            let name = a.name.to_lowercase();
            name.ends_with(".sigstore.json") || name.ends_with(".sigstore")
        });
        if has_attestations_config || has_attestations_assets {
            let signer_workflow = all_pkgs
                .iter()
                .filter_map(|p| p.github_artifact_attestations.as_ref())
                .find_map(|a| a.signer_workflow.clone());
            features.push(SecurityFeature::GithubAttestations { signer_workflow });
        }

        // SLSA - check registry config OR actual release assets
        let has_slsa_config = all_pkgs.iter().any(|p| {
            p.slsa_provenance
                .as_ref()
                .is_some_and(|s| s.enabled.unwrap_or(true))
        });
        let has_slsa_assets = release_assets.iter().any(|a| {
            let name = a.name.to_lowercase();
            name.contains(".intoto.jsonl")
                || name.contains("provenance")
                || name.ends_with(".attestation")
        });
        if has_slsa_config || has_slsa_assets {
            features.push(SecurityFeature::Slsa { level: None });
        }

        // Cosign (nested in checksum) - check registry config OR actual release assets
        let has_cosign_config = all_pkgs.iter().any(|p| {
            p.checksum
                .as_ref()
                .and_then(|c| c.cosign.as_ref())
                .is_some_and(|cosign| cosign.enabled.unwrap_or(true))
        });
        let has_cosign_assets = release_assets.iter().any(|a| {
            let name = a.name.to_lowercase();
            name.ends_with(".sig") || name.contains("cosign")
        });
        if has_cosign_config || has_cosign_assets {
            features.push(SecurityFeature::Cosign);
        }

        // Minisign - check registry config OR actual release assets
        let has_minisign_config = all_pkgs.iter().any(|p| {
            p.minisign
                .as_ref()
                .is_some_and(|m| m.enabled.unwrap_or(true))
        });
        let has_minisign_assets = release_assets.iter().any(|a| {
            let name = a.name.to_lowercase();
            name.ends_with(".minisig")
        });
        if has_minisign_config || has_minisign_assets {
            let public_key = all_pkgs
                .iter()
                .filter_map(|p| p.minisign.as_ref())
                .find_map(|m| m.public_key.clone());
            features.push(SecurityFeature::Minisign { public_key });
        }

        features
    }

    fn ba(&self) -> &Arc<BackendArg> {
        &self.ba
    }

    async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
        let pkg = match AQUA_REGISTRY.package(&self.id).await {
            Ok(pkg) => pkg,
            Err(e) => {
                warn!("Remote versions cannot be fetched: {}", e);
                return Ok(vec![]);
            }
        };

        if pkg.repo_owner.is_empty() || pkg.repo_name.is_empty() {
            warn!(
                "aqua package {} does not have repo_owner and/or repo_name.",
                self.id
            );
            return Ok(vec![]);
        }

        let tags_with_timestamps = match get_tags_with_created_at(&pkg).await {
            Ok(tags) => tags,
            Err(e) => {
                warn!("Remote versions cannot be fetched: {}", e);
                return Ok(vec![]);
            }
        };

        let mut versions = Vec::new();
        for (tag, created_at) in tags_with_timestamps.into_iter().rev() {
            let mut version = tag.as_str();
            match pkg.version_filter_ok(version) {
                Ok(true) => {}
                Ok(false) => continue,
                Err(e) => {
                    warn!("[{}] aqua version filter error: {e}", self.ba());
                    continue;
                }
            }
            let versioned_pkg = pkg.clone().with_version(&[version], os(), arch());
            if let Some(prefix) = &versioned_pkg.version_prefix {
                if let Some(_v) = version.strip_prefix(prefix) {
                    version = _v;
                } else {
                    continue;
                }
            }
            version = version.strip_prefix('v').unwrap_or(version);

            // Validate the package has assets
            let check_pkg = AQUA_REGISTRY
                .package_with_version(&self.id, &[&tag])
                .await
                .unwrap_or_default();
            if !check_pkg.no_asset && check_pkg.error_message.is_none() {
                let release_url = format!(
                    "https://github.com/{}/{}/releases/tag/{}",
                    pkg.repo_owner, pkg.repo_name, tag
                );
                versions.push(VersionInfo {
                    version: version.to_string(),
                    created_at,
                    release_url: Some(release_url),
                    ..Default::default()
                });
            }
        }
        Ok(versions)
    }

    async fn install_version_(
        &self,
        ctx: &InstallContext,
        mut tv: ToolVersion,
    ) -> Result<ToolVersion> {
        // Check if URL already exists in lockfile platforms first
        // This allows us to skip API calls when lockfile has the URL
        let platform_key = self.get_platform_key();
        let existing_platform = tv
            .lock_platforms
            .get(&platform_key)
            .and_then(|asset| asset.url.clone());

        // Skip get_version_tags() API call if we have lockfile URL
        let tag = if existing_platform.is_some() {
            None // We'll determine version from URL instead
        } else {
            match self.get_version_tags().await {
                Ok(tags) => tags
                    .iter()
                    .find(|(version, _)| version == &tv.version)
                    .map(|(_, tag)| tag.clone()),
                Err(e) => {
                    warn!(
                        "[{}] failed to fetch version tags, URL may be incorrect: {e}",
                        self.id
                    );
                    None
                }
            }
        };
        if tag.is_none() && existing_platform.is_none() && !tv.version.starts_with('v') {
            debug!(
                "[{}] no tag found for version {}, will try with 'v' prefix",
                self.id, tv.version
            );
        }
        let mut v = tag.clone().unwrap_or_else(|| tv.version.clone());
        let mut v_prefixed =
            (tag.is_none() && !tv.version.starts_with('v')).then(|| format!("v{v}"));
        let versions = match &v_prefixed {
            Some(v_prefixed) => vec![v.as_str(), v_prefixed.as_str()],
            None => vec![v.as_str()],
        };
        let pkg = AQUA_REGISTRY
            .package_with_version(&self.id, &versions)
            .await?;
        if let Some(prefix) = &pkg.version_prefix
            && !v.starts_with(prefix)
        {
            v = format!("{prefix}{v}");
            // Don't add prefix to v_prefixed if it already starts with the prefix
            v_prefixed = v_prefixed.map(|vp| {
                if vp.starts_with(prefix) {
                    vp
                } else {
                    format!("{prefix}{vp}")
                }
            });
        }
        validate(&pkg)?;

        // Validate lockfile URL matches expected asset pattern from registry
        // This handles cases where the registry format changed (e.g., raw binary -> tar.gz)
        // Only validate for GithubRelease packages - other types use fixed URL formats
        // In locked mode, trust the lockfile URL without validation to avoid API calls
        let validated_url = if let Some(ref url) = existing_platform {
            if ctx.locked || pkg.r#type != AquaPackageType::GithubRelease {
                existing_platform // Trust lockfile URL in locked mode or for non-release types
            } else {
                let cached_filename = get_filename_from_url(url);
                let cached_filename_lower = cached_filename.to_lowercase();
                // Check assets for both version variants (with and without v prefix)
                let version_variants: Vec<&str> = match &v_prefixed {
                    Some(vp) => vec![v.as_str(), vp.as_str()],
                    None => vec![v.as_str()],
                };
                let matches = version_variants.iter().any(|ver| {
                    pkg.asset_strs(ver, os(), arch())
                        .unwrap_or_default()
                        .iter()
                        .any(|expected| {
                            // Case-insensitive match to align with github_release_asset behavior
                            cached_filename == *expected
                                || cached_filename_lower == expected.to_lowercase()
                        })
                });
                if matches {
                    existing_platform
                } else {
                    warn!(
                        "lockfile asset '{}' doesn't match registry, refreshing",
                        cached_filename
                    );
                    None
                }
            }
        } else {
            None
        };

        let (url, v, filename, api_digest) = if let Some(validated_url) = validated_url.clone() {
            let url = validated_url;
            let filename = get_filename_from_url(&url);
            // Determine which version variant was used based on the URL or filename
            // Check for version_prefix (e.g., "jq-" for jq), "v" prefix, or raw version
            let v = if let Some(prefix) = &pkg.version_prefix {
                let prefixed_version = format!("{prefix}{}", tv.version);
                if url.contains(&prefixed_version) || filename.contains(&prefixed_version) {
                    prefixed_version
                } else if url.contains(&format!("v{}", tv.version))
                    || filename.contains(&format!("v{}", tv.version))
                {
                    format!("v{}", tv.version)
                } else {
                    tv.version.clone()
                }
            } else if url.contains(&format!("v{}", tv.version))
                || filename.contains(&format!("v{}", tv.version))
            {
                format!("v{}", tv.version)
            } else {
                tv.version.clone()
            };
            (url, v, filename, None)
        } else if ctx.locked {
            bail!(
                "No lockfile URL found for {} on platform {} (--locked mode requires pre-resolved URLs)",
                self.id,
                platform_key
            );
        } else {
            let (url, v, digest) = if let Some(v_prefixed) = v_prefixed {
                // Try v-prefixed version first because most aqua packages use v-prefixed versions
                match self.get_url(&pkg, v_prefixed.as_ref()).await {
                    // If the url is already checked, use it
                    Ok((url, true, digest)) => (url, v_prefixed, digest),
                    Ok((url_prefixed, false, digest_prefixed)) => {
                        let (url, _, digest) = self.get_url(&pkg, &v).await?;
                        // If the v-prefixed URL is the same as the non-prefixed URL, use it
                        if url == url_prefixed {
                            (url_prefixed, v_prefixed, digest_prefixed)
                        } else {
                            // If they are different, check existence
                            match HTTP.head(&url_prefixed).await {
                                Ok(_) => (url_prefixed, v_prefixed, digest_prefixed),
                                Err(_) => (url, v, digest),
                            }
                        }
                    }
                    Err(err) => {
                        let (url, _, digest) =
                            self.get_url(&pkg, &v).await.map_err(|e| err.wrap_err(e))?;
                        (url, v, digest)
                    }
                }
            } else {
                let (url, _, digest) = self.get_url(&pkg, &v).await?;
                (url, v, digest)
            };
            let filename = get_filename_from_url(&url);

            (url, v.to_string(), filename, digest)
        };

        let format = pkg.format(&v, os(), arch()).unwrap_or_default();

        self.download(ctx, &tv, &url, &filename).await?;

        if validated_url.is_none() {
            // Store the asset URL and digest (if available) in the tool version
            let platform_info = tv.lock_platforms.entry(platform_key).or_default();
            platform_info.url = Some(url.clone());
            if let Some(digest) = api_digest.clone() {
                debug!("using GitHub API digest for checksum verification");
                platform_info.checksum = Some(digest);
            }
        }

        // Advance to checksum operation if applicable
        if pkg.checksum.as_ref().is_some_and(|c| c.enabled()) || api_digest.is_some() {
            ctx.pr.next_operation();
        }
        self.verify(ctx, &mut tv, &pkg, &v, &filename).await?;

        // Advance to extraction operation if applicable
        if needs_extraction(format, &pkg.r#type) {
            ctx.pr.next_operation();
        }
        self.install(ctx, &tv, &pkg, &v, &filename)?;

        Ok(tv)
    }

    async fn list_bin_paths(
        &self,
        _config: &Arc<Config>,
        tv: &ToolVersion,
    ) -> Result<Vec<PathBuf>> {
        let mise_bins_dir = tv.install_path().join(".mise-bins");
        if self.symlink_bins(tv) || mise_bins_dir.is_dir() {
            return Ok(vec![mise_bins_dir]);
        }

        let install_path = tv.install_path();

        // For linked versions (external symlinks created via `mise link`),
        // skip aqua registry lookup — the linked install has its own layout.
        if let Ok(Some(target)) = file::resolve_symlink(&install_path)
            && target.is_absolute()
        {
            let bin = install_path.join("bin");
            return Ok(if bin.is_dir() {
                vec![bin]
            } else {
                vec![install_path]
            });
        }

        let cache: CacheManager<Vec<PathBuf>> =
            CacheManagerBuilder::new(tv.cache_path().join("bin_paths.msgpack.z"))
                .with_fresh_file(install_path.clone())
                .with_fresh_duration(Settings::get().fetch_remote_versions_cache())
                .build();

        let paths = cache
            .get_or_try_init_async(async || {
                let pkg = AQUA_REGISTRY
                    .package_with_version(&self.id, &[&tv.version])
                    .await?;

                let srcs = self.srcs(&pkg, tv)?;
                let paths = if srcs.is_empty() {
                    vec![install_path.clone()]
                } else {
                    srcs.iter()
                        .map(|(_, dst)| dst.parent().unwrap().to_path_buf())
                        .collect()
                };
                Ok(paths
                    .into_iter()
                    .unique()
                    .filter(|p| p.exists())
                    .filter_map(|p| p.strip_prefix(&install_path).ok().map(|p| p.to_path_buf()))
                    .collect())
            })
            .await?
            .iter()
            .map(|p| p.mount(&install_path))
            .collect();
        Ok(paths)
    }

    fn fuzzy_match_filter(&self, versions: Vec<String>, query: &str) -> Vec<String> {
        let escaped_query = regex::escape(query);
        let query = if query == "latest" {
            "\\D*[0-9].*"
        } else {
            &escaped_query
        };
        let query_regex = Regex::new(&format!("^{query}([-.].+)?$")).unwrap();
        versions
            .into_iter()
            .filter(|v| {
                if query == v {
                    return true;
                }
                if VERSION_REGEX.is_match(v) {
                    return false;
                }
                query_regex.is_match(v)
            })
            .collect()
    }

    /// Resolve platform-specific lock information for any target platform.
    /// This enables cross-platform lockfile generation without installation.
    async fn resolve_lock_info(
        &self,
        tv: &ToolVersion,
        target: &PlatformTarget,
    ) -> Result<PlatformInfo> {
        // Map Platform to Aqua's os/arch conventions
        let target_os = match target.os_name() {
            "macos" => "darwin",
            other => other,
        };
        let target_arch = match target.arch_name() {
            "x64" => "amd64",
            other => other,
        };

        // Get version tag
        let tag = match self.get_version_tags().await {
            Ok(tags) => tags
                .iter()
                .find(|(version, _)| version == &tv.version)
                .map(|(_, tag)| tag.clone()),
            Err(e) => {
                warn!(
                    "[{}] failed to fetch version tags for lockfile, URL may be incorrect: {e}",
                    self.id
                );
                None
            }
        };
        let tag_is_none = tag.is_none();
        if tag_is_none && !tv.version.starts_with('v') {
            debug!(
                "[{}] no tag found for version {} during lock, will try with 'v' prefix",
                self.id, tv.version
            );
        }
        let mut v = tag.unwrap_or_else(|| tv.version.clone());
        let v_prefixed = (tag_is_none && !tv.version.starts_with('v')).then(|| format!("v{v}"));
        let versions = match &v_prefixed {
            Some(v_prefixed) => vec![v.as_str(), v_prefixed.as_str()],
            None => vec![v.as_str()],
        };

        // Get package and apply version/overrides directly for the target platform.
        // Using package_with_version() here would apply overrides for the current host
        // platform first, which can leak host-specific overrides into cross-platform lock.
        let pkg = AQUA_REGISTRY.package(&self.id).await?;
        let pkg = pkg.with_version(&versions, target_os, target_arch);

        // Apply version prefix if present
        if let Some(prefix) = &pkg.version_prefix
            && !v.starts_with(prefix)
        {
            v = format!("{prefix}{v}");
        }

        // Check if this platform is supported
        if !is_platform_supported(&pkg.supported_envs, target_os, target_arch) {
            debug!(
                "aqua package {} does not support {}: supported_envs={:?}",
                self.id,
                target.to_key(),
                pkg.supported_envs
            );
            return Ok(PlatformInfo::default());
        }

        // Get URL and checksum for the target platform
        let (url, checksum) = match pkg.r#type {
            AquaPackageType::GithubRelease => {
                // For GitHub releases, we need to find the asset for the target platform
                let asset_strs = pkg.asset_strs(&v, target_os, target_arch)?;
                match self.github_release_asset(&pkg, &v, asset_strs).await {
                    Ok((url, digest)) => (Some(url), digest),
                    Err(e) => {
                        debug!(
                            "Failed to get GitHub release asset for {} on {}: {}",
                            self.id,
                            target.to_key(),
                            e
                        );
                        (None, None)
                    }
                }
            }
            AquaPackageType::GithubArchive | AquaPackageType::GithubContent => {
                (Some(self.github_archive_url(&pkg, &v)), None)
            }
            AquaPackageType::Http => (pkg.url(&v, target_os, target_arch).ok(), None),
            _ => (None, None),
        };

        let name = url.as_ref().map(|u| get_filename_from_url(u));

        // Try to get checksum from checksum file if not available from GitHub API
        let checksum = match checksum {
            Some(c) => Some(c),
            None => self
                .fetch_checksum_from_file(&pkg, &v, target_os, target_arch, name.as_deref())
                .await
                .ok()
                .flatten(),
        };

        // Detect provenance from aqua registry config
        let mut provenance = self.detect_provenance_type(&pkg);

        // Resolve SLSA provenance URL for all platforms (not just current).
        // This ensures deterministic lockfile output regardless of host platform.
        if matches!(provenance, Some(ProvenanceType::Slsa { url: None })) {
            match self
                .resolve_slsa_url(&pkg, &v, target_os, target_arch)
                .await
            {
                Ok(resolved_url) => {
                    provenance = Some(ProvenanceType::Slsa {
                        url: Some(resolved_url),
                    });
                }
                Err(e) => {
                    warn!(
                        "failed to resolve SLSA provenance URL for {} ({}-{}), \
                         lockfile entry will use short form: {e}",
                        self.id, target_os, target_arch
                    );
                }
            }
        }

        // For the current platform, verify provenance cryptographically at lock time.
        // This ensures the lockfile's provenance entry is backed by actual verification,
        // not just registry metadata. Cross-platform entries remain detection-only.
        if provenance.is_some()
            && target.is_current()
            && let Some(ref artifact_url) = url
        {
            match self
                .verify_provenance_at_lock_time(
                    &pkg,
                    &v,
                    artifact_url,
                    provenance.as_ref().unwrap(),
                )
                .await
            {
                Ok(verified) => provenance = Some(verified),
                Err(e) => {
                    // Clear provenance so install-time verification will run.
                    // If we kept the unverified provenance, has_lockfile_integrity
                    // would be true and verify_provenance() would be skipped.
                    warn!(
                        "lock-time provenance verification failed for {}, \
                         will be verified at install time: {e}",
                        self.id
                    );
                    provenance = None;
                }
            }
        }

        Ok(PlatformInfo {
            url,
            checksum,
            provenance,
            ..Default::default()
        })
    }
}

impl AquaBackend {
    /// Detect provenance type from aqua registry package config.
    ///
    /// Returns the highest-priority provenance type that is configured and
    /// enabled for the package, based on the `ProvenanceType` priority order:
    /// GithubAttestations (3) > Slsa (2) > Cosign (1) > Minisign (0).
    ///
    /// This detection is based on registry metadata only — no cryptographic
    /// verification happens here. Actual verification occurs at install time
    /// (and is always performed when `locked_verify_provenance` or `paranoid`
    /// is enabled).
    fn detect_provenance_type(&self, pkg: &AquaPackage) -> Option<ProvenanceType> {
        let settings = Settings::get();

        // Check for GitHub artifact attestations (highest priority)
        // The registry metadata (enabled flag, signer_workflow) is sufficient for
        // detection at lock-time. Actual cryptographic verification happens at
        // install time (always when locked_verify_provenance/paranoid is enabled,
        // or on first install when the lockfile doesn't yet have provenance).
        if settings.github_attestations
            && settings.aqua.github_attestations
            && let Some(att) = &pkg.github_artifact_attestations
            && att.enabled != Some(false)
        {
            return Some(ProvenanceType::GithubAttestations);
        }

        // Check for SLSA provenance
        if settings.slsa
            && settings.aqua.slsa
            && let Some(slsa) = &pkg.slsa_provenance
            && slsa.enabled != Some(false)
        {
            return Some(ProvenanceType::Slsa { url: None });
        }

        // Check for cosign (nested under checksum config, requires checksum enabled)
        // Only record cosign provenance if we can actually verify it natively
        // (key-based or bundle-based). Tools that only use opts require the external
        // cosign CLI which we don't shell out to.
        if settings.aqua.cosign
            && let Some(checksum) = &pkg.checksum
            && checksum.enabled()
            && let Some(cosign) = checksum.cosign.as_ref()
            && cosign.enabled != Some(false)
            && (cosign.key.is_some() || cosign.bundle.is_some())
        {
            return Some(ProvenanceType::Cosign);
        }

        // Check for minisign
        if settings.aqua.minisign
            && let Some(minisign) = &pkg.minisign
            && minisign.enabled != Some(false)
        {
            return Some(ProvenanceType::Minisign);
        }

        None
    }

    /// Verify provenance at lock time by downloading the artifact to a temp directory
    /// and running the appropriate cryptographic verification. Only called for the
    /// current platform during `mise lock`.
    async fn verify_provenance_at_lock_time(
        &self,
        pkg: &AquaPackage,
        v: &str,
        artifact_url: &str,
        detected: &ProvenanceType,
    ) -> Result<ProvenanceType> {
        let tmp_dir = tempfile::tempdir()?;
        let filename = get_filename_from_url(artifact_url);
        let artifact_path = tmp_dir.path().join(&filename);

        info!(
            "downloading artifact for lock-time provenance verification: {}",
            filename
        );
        HTTP.download_file(artifact_url, &artifact_path, None)
            .await?;

        match detected {
            ProvenanceType::GithubAttestations => {
                self.run_github_attestation_check(&artifact_path, pkg)
                    .await?;
                Ok(ProvenanceType::GithubAttestations)
            }
            ProvenanceType::Slsa { .. } => {
                let provenance_url = self
                    .run_slsa_check(&artifact_path, pkg, v, tmp_dir.path(), None)
                    .await?;
                Ok(ProvenanceType::Slsa {
                    url: Some(provenance_url),
                })
            }
            ProvenanceType::Minisign => {
                self.run_minisign_check(&artifact_path, &filename, pkg, v, tmp_dir.path(), None)
                    .await?;
                Ok(ProvenanceType::Minisign)
            }
            ProvenanceType::Cosign => {
                let checksum_config = pkg
                    .checksum
                    .as_ref()
                    .wrap_err("cosign provenance detected but no checksum config found")?;
                let checksum_path = self
                    .download_checksum_file(checksum_config, pkg, v, tmp_dir.path(), None)
                    .await?;
                self.run_cosign_check(&checksum_path, pkg, v, tmp_dir.path(), None)
                    .await?;
                Ok(ProvenanceType::Cosign)
            }
        }
    }

    // --- Shared verification helpers used by both lock-time and install-time ---

    /// Run GitHub artifact attestation verification against an already-downloaded artifact.
    async fn run_github_attestation_check(
        &self,
        artifact_path: &Path,
        pkg: &AquaPackage,
    ) -> Result<()> {
        let signer_workflow = pkg
            .github_artifact_attestations
            .as_ref()
            .and_then(|att| att.signer_workflow.clone());

        match sigstore_verification::verify_github_attestation(
            artifact_path,
            &pkg.repo_owner,
            &pkg.repo_name,
            env::GITHUB_TOKEN.as_deref(),
            signer_workflow.as_deref(),
        )
        .await
        {
            Ok(true) => {
                debug!(
                    "GitHub attestations verified for {}/{}",
                    pkg.repo_owner, pkg.repo_name
                );
                Ok(())
            }
            Ok(false) => Err(eyre!(
                "GitHub artifact attestations verification returned false"
            )),
            Err(e) => Err(eyre!(
                "GitHub artifact attestations verification failed: {e}"
            )),
        }
    }

    /// Resolve the SLSA provenance URL for a target platform without downloading.
    /// Uses cached GitHub release data or template-based URL construction.
    async fn resolve_slsa_url(
        &self,
        pkg: &AquaPackage,
        v: &str,
        target_os: &str,
        target_arch: &str,
    ) -> Result<String> {
        let slsa = pkg
            .slsa_provenance
            .as_ref()
            .wrap_err("SLSA provenance detected but no config found")?;

        let mut slsa_pkg = pkg.clone();
        (slsa_pkg.repo_owner, slsa_pkg.repo_name) =
            resolve_repo_info(slsa.repo_owner.as_ref(), slsa.repo_name.as_ref(), pkg);

        match slsa.r#type.as_deref().unwrap_or_default() {
            "github_release" => {
                let asset_strs = slsa.asset_strs(&slsa_pkg, v, target_os, target_arch)?;
                let (url, _) = self.github_release_asset(&slsa_pkg, v, asset_strs).await?;
                Ok(url)
            }
            "http" => slsa.url(&slsa_pkg, v, target_os, target_arch),
            t => Err(eyre!("unsupported slsa type: {t}")),
        }
    }

    /// Download SLSA provenance file and verify against an already-downloaded artifact.
    /// Returns the provenance download URL on success.
    async fn run_slsa_check(
        &self,
        artifact_path: &Path,
        pkg: &AquaPackage,
        v: &str,
        download_dir: &Path,
        pr: Option<&dyn SingleReport>,
    ) -> Result<String> {
        let provenance_url = self.resolve_slsa_url(pkg, v, os(), arch()).await?;
        let provenance_path = download_dir.join(get_filename_from_url(&provenance_url));
        HTTP.download_file(&provenance_url, &provenance_path, pr)
            .await?;

        match sigstore_verification::verify_slsa_provenance(artifact_path, &provenance_path, 1u8)
            .await
        {
            Ok(true) => {
                debug!("SLSA provenance verified");
                Ok(provenance_url)
            }
            Ok(false) => Err(eyre!("SLSA provenance verification failed")),
            Err(e) => Err(e.into()),
        }
    }

    /// Download minisign signature and verify against an already-downloaded artifact.
    async fn run_minisign_check(
        &self,
        artifact_path: &Path,
        artifact_filename: &str,
        pkg: &AquaPackage,
        v: &str,
        download_dir: &Path,
        pr: Option<&dyn SingleReport>,
    ) -> Result<()> {
        let minisign_config = pkg
            .minisign
            .as_ref()
            .wrap_err("minisign provenance detected but no config found")?;

        let sig_path = match minisign_config._type() {
            AquaMinisignType::GithubRelease => {
                let asset = minisign_config.asset(pkg, v, os(), arch())?;
                let (repo_owner, repo_name) = resolve_repo_info(
                    minisign_config.repo_owner.as_ref(),
                    minisign_config.repo_name.as_ref(),
                    pkg,
                );
                let url = github::get_release(&format!("{repo_owner}/{repo_name}"), v)
                    .await?
                    .assets
                    .into_iter()
                    .find(|a| a.name == asset)
                    .map(|a| a.browser_download_url)
                    .wrap_err_with(|| format!("no asset found for minisign: {asset}"))?;
                let path = download_dir.join(&asset);
                HTTP.download_file(&url, &path, pr).await?;
                path
            }
            AquaMinisignType::Http => {
                let url = minisign_config.url(pkg, v, os(), arch())?;
                let path = download_dir.join(format!("{artifact_filename}.minisig"));
                HTTP.download_file(&url, &path, pr).await?;
                path
            }
        };
        let data = file::read(artifact_path)?;
        let sig = file::read_to_string(&sig_path)?;
        minisign::verify(
            &minisign_config.public_key(pkg, v, os(), arch())?,
            &data,
            &sig,
        )?;
        debug!("minisign verified");
        Ok(())
    }

    /// Download cosign key/signature/bundle and verify checksums file.
    /// The checksum file must already be downloaded at `checksum_path`.
    async fn run_cosign_check(
        &self,
        checksum_path: &Path,
        pkg: &AquaPackage,
        v: &str,
        download_dir: &Path,
        pr: Option<&dyn SingleReport>,
    ) -> Result<()> {
        let cosign = pkg
            .checksum
            .as_ref()
            .and_then(|c| c.cosign.as_ref())
            .wrap_err("cosign provenance detected but no config found")?;

        if let Some(key) = &cosign.key {
            let mut key_pkg = pkg.clone();
            (key_pkg.repo_owner, key_pkg.repo_name) =
                resolve_repo_info(key.repo_owner.as_ref(), key.repo_name.as_ref(), pkg);
            let key_url = match key.r#type.as_deref().unwrap_or_default() {
                "github_release" => {
                    let asset_strs = key.asset_strs(pkg, v, os(), arch())?;
                    self.github_release_asset(&key_pkg, v, asset_strs).await?.0
                }
                "http" => key.url(pkg, v, os(), arch())?,
                t => return Err(eyre!("unsupported cosign key type: {t}")),
            };
            let key_path = download_dir.join(get_filename_from_url(&key_url));
            HTTP.download_file(&key_url, &key_path, pr).await?;

            let sig_path = if let Some(signature) = &cosign.signature {
                let mut sig_pkg = pkg.clone();
                (sig_pkg.repo_owner, sig_pkg.repo_name) = resolve_repo_info(
                    signature.repo_owner.as_ref(),
                    signature.repo_name.as_ref(),
                    pkg,
                );
                let sig_url = match signature.r#type.as_deref().unwrap_or_default() {
                    "github_release" => {
                        let asset_strs = signature.asset_strs(pkg, v, os(), arch())?;
                        self.github_release_asset(&sig_pkg, v, asset_strs).await?.0
                    }
                    "http" => signature.url(pkg, v, os(), arch())?,
                    t => return Err(eyre!("unsupported cosign signature type: {t}")),
                };
                let path = download_dir.join(get_filename_from_url(&sig_url));
                HTTP.download_file(&sig_url, &path, pr).await?;
                path
            } else {
                checksum_path.with_extension("sig")
            };

            match sigstore_verification::verify_cosign_signature_with_key(
                checksum_path,
                &sig_path,
                &key_path,
            )
            .await
            {
                Ok(true) => {
                    debug!("cosign (key) verified");
                    Ok(())
                }
                Ok(false) => Err(eyre!("cosign key-based verification returned false")),
                Err(e) => Err(eyre!("cosign key-based verification failed: {e}")),
            }
        } else if let Some(bundle) = &cosign.bundle {
            let mut bundle_pkg = pkg.clone();
            (bundle_pkg.repo_owner, bundle_pkg.repo_name) =
                resolve_repo_info(bundle.repo_owner.as_ref(), bundle.repo_name.as_ref(), pkg);
            let bundle_url = match bundle.r#type.as_deref().unwrap_or_default() {
                "github_release" => {
                    let asset_strs = bundle.asset_strs(pkg, v, os(), arch())?;
                    self.github_release_asset(&bundle_pkg, v, asset_strs)
                        .await?
                        .0
                }
                "http" => bundle.url(pkg, v, os(), arch())?,
                t => return Err(eyre!("unsupported cosign bundle type: {t}")),
            };
            let bundle_path = download_dir.join(get_filename_from_url(&bundle_url));
            HTTP.download_file(&bundle_url, &bundle_path, pr).await?;

            match sigstore_verification::verify_cosign_signature(checksum_path, &bundle_path).await
            {
                Ok(true) => {
                    debug!("cosign (bundle) verified");
                    Ok(())
                }
                Ok(false) => Err(eyre!("cosign bundle-based verification returned false")),
                Err(e) => Err(eyre!("cosign bundle-based verification failed: {e}")),
            }
        } else {
            Err(eyre!("cosign detected but no key or bundle configured"))
        }
    }

    /// Download checksum file to the given directory.
    async fn download_checksum_file(
        &self,
        checksum: &AquaChecksum,
        pkg: &AquaPackage,
        v: &str,
        download_dir: &Path,
        pr: Option<&dyn SingleReport>,
    ) -> Result<PathBuf> {
        let url = match checksum._type() {
            AquaChecksumType::GithubRelease => {
                let asset_strs = checksum.asset_strs(pkg, v, os(), arch())?;
                self.github_release_asset(pkg, v, asset_strs).await?.0
            }
            AquaChecksumType::Http => checksum.url(pkg, v, os(), arch())?,
        };
        let path = download_dir.join(get_filename_from_url(&url));
        HTTP.download_file(&url, &path, pr).await?;
        Ok(path)
    }

    pub fn from_arg(ba: BackendArg) -> Self {
        let full = ba.full_without_opts();
        let mut id = full.split_once(":").unwrap_or(("", &full)).1;
        if !id.contains("/") {
            id = REGISTRY
                .get(id)
                .and_then(|t| t.backends.iter().find_map(|s| s.full.strip_prefix("aqua:")))
                .unwrap_or_else(|| {
                    warn!("invalid aqua tool: {}", id);
                    id
                });
        }
        let cache_path = ba.cache_path.clone();
        Self {
            id: id.to_string(),
            ba: Arc::new(ba),
            version_tags_cache: CacheManagerBuilder::new(cache_path.join("version_tags.msgpack.z"))
                .with_fresh_duration(Settings::get().fetch_remote_versions_cache())
                .build(),
        }
    }

    async fn get_version_tags(&self) -> Result<&Vec<(String, String)>> {
        self.version_tags_cache
            .get_or_try_init_async(|| async {
                let pkg = AQUA_REGISTRY.package(&self.id).await?;
                let mut versions = Vec::new();
                if !pkg.repo_owner.is_empty() && !pkg.repo_name.is_empty() {
                    let tags = get_tags(&pkg).await?;
                    for tag in tags.into_iter().rev() {
                        let mut version = tag.as_str();
                        match pkg.version_filter_ok(version) {
                            Ok(true) => {}
                            Ok(false) => continue,
                            Err(e) => {
                                warn!("[{}] aqua version filter error: {e}", self.ba());
                                continue;
                            }
                        }
                        let pkg = pkg.clone().with_version(&[version], os(), arch());
                        if let Some(prefix) = &pkg.version_prefix {
                            if let Some(_v) = version.strip_prefix(prefix) {
                                version = _v;
                            } else {
                                continue;
                            }
                        }
                        version = version.strip_prefix('v').unwrap_or(version);
                        versions.push((version.to_string(), tag));
                    }
                } else {
                    bail!(
                        "aqua package {} does not have repo_owner and/or repo_name.",
                        self.id
                    );
                }
                Ok(versions)
            })
            .await
    }

    async fn get_url(&self, pkg: &AquaPackage, v: &str) -> Result<(String, bool, Option<String>)> {
        match pkg.r#type {
            AquaPackageType::GithubRelease => self
                .github_release_url(pkg, v)
                .await
                .map(|(url, digest)| (url, true, digest)),
            AquaPackageType::GithubContent => {
                if pkg.path.is_some() {
                    Ok((self.github_content_url(pkg, v), false, None))
                } else {
                    bail!("github_content package requires `path`")
                }
            }
            AquaPackageType::GithubArchive => Ok((self.github_archive_url(pkg, v), false, None)),
            AquaPackageType::Http => pkg.url(v, os(), arch()).map(|url| (url, false, None)),
            ref t => bail!("unsupported aqua package type: {t}"),
        }
    }

    async fn github_release_url(
        &self,
        pkg: &AquaPackage,
        v: &str,
    ) -> Result<(String, Option<String>)> {
        let asset_strs = pkg.asset_strs(v, os(), arch())?;
        self.github_release_asset(pkg, v, asset_strs).await
    }

    async fn github_release_asset(
        &self,
        pkg: &AquaPackage,
        v: &str,
        asset_strs: IndexSet<String>,
    ) -> Result<(String, Option<String>)> {
        let gh_id = format!("{}/{}", pkg.repo_owner, pkg.repo_name);
        let gh_release = github::get_release(&gh_id, v).await?;

        // Prioritize order of asset_strs
        let asset = asset_strs
            .iter()
            .find_map(|expected| {
                gh_release.assets.iter().find(|a| {
                    a.name == *expected || a.name.to_lowercase() == expected.to_lowercase()
                })
            })
            .wrap_err_with(|| {
                format!(
                    "no asset found: {}\nAvailable assets:\n{}",
                    asset_strs.iter().join(", "),
                    gh_release.assets.iter().map(|a| &a.name).join("\n")
                )
            })?;

        Ok((asset.browser_download_url.to_string(), asset.digest.clone()))
    }

    fn github_archive_url(&self, pkg: &AquaPackage, v: &str) -> String {
        let gh_id = format!("{}/{}", pkg.repo_owner, pkg.repo_name);
        format!("https://github.com/{gh_id}/archive/refs/tags/{v}.tar.gz")
    }

    fn github_content_url(&self, pkg: &AquaPackage, v: &str) -> String {
        let gh_id = format!("{}/{}", pkg.repo_owner, pkg.repo_name);
        let path = pkg.path.as_deref().unwrap();
        format!("https://raw.githubusercontent.com/{gh_id}/{v}/{path}")
    }

    /// Fetch checksum from a checksum file without downloading the actual tarball.
    /// This is used for cross-platform lockfile generation.
    async fn fetch_checksum_from_file(
        &self,
        pkg: &AquaPackage,
        v: &str,
        target_os: &str,
        target_arch: &str,
        filename: Option<&str>,
    ) -> Result<Option<String>> {
        let Some(checksum_config) = &pkg.checksum else {
            return Ok(None);
        };
        if !checksum_config.enabled() {
            return Ok(None);
        }
        let Some(filename) = filename else {
            return Ok(None);
        };

        // Get the checksum file URL
        let url = match checksum_config._type() {
            AquaChecksumType::GithubRelease => {
                let asset_strs = checksum_config.asset_strs(pkg, v, target_os, target_arch)?;
                match self.github_release_asset(pkg, v, asset_strs).await {
                    Ok((url, _)) => url,
                    Err(e) => {
                        debug!("Failed to get checksum file asset: {}", e);
                        return Ok(None);
                    }
                }
            }
            AquaChecksumType::Http => checksum_config.url(pkg, v, target_os, target_arch)?,
        };

        // Download checksum file content
        let checksum_content = match HTTP.get_text(&url).await {
            Ok(content) => content,
            Err(e) => {
                debug!("Failed to download checksum file {}: {}", url, e);
                return Ok(None);
            }
        };

        // Parse checksum from file content
        let checksum_str =
            self.parse_checksum_from_content(&checksum_content, checksum_config, filename)?;

        Ok(Some(format!(
            "{}:{}",
            checksum_config.algorithm(),
            checksum_str
        )))
    }

    /// Parse a checksum from checksum file content for a specific filename.
    fn parse_checksum_from_content(
        &self,
        content: &str,
        checksum_config: &AquaChecksum,
        filename: &str,
    ) -> Result<String> {
        let mut checksum_file = content.to_string();

        if checksum_config.file_format() == "regexp" {
            let pattern = checksum_config.pattern();
            if let Some(file_pattern) = &pattern.file {
                let re = regex::Regex::new(file_pattern.as_str())?;
                if let Some(line) = checksum_file
                    .lines()
                    .find(|l| re.captures(l).is_some_and(|c| c[1].to_string() == filename))
                {
                    checksum_file = line.to_string();
                } else {
                    debug!(
                        "no line found matching {} in checksum file for {}",
                        file_pattern, filename
                    );
                }
            }
            let re = regex::Regex::new(pattern.checksum.as_str())?;
            if let Some(caps) = re.captures(checksum_file.as_str()) {
                checksum_file = caps[1].to_string();
            } else {
                debug!(
                    "no checksum found matching {} in checksum file",
                    pattern.checksum
                );
            }
        }

        // Standard format: "<hash>  <filename>" or "<hash> *<filename>"
        let checksum_str = checksum_file
            .lines()
            .filter_map(|l| {
                let split = l.split_whitespace().collect_vec();
                if split.len() == 2 {
                    Some((
                        split[0].to_string(),
                        split[1]
                            .rsplit_once('/')
                            .map(|(_, f)| f)
                            .unwrap_or(split[1])
                            .trim_matches('*')
                            .to_string(),
                    ))
                } else {
                    None
                }
            })
            .find(|(_, f)| f == filename)
            .map(|(c, _)| c)
            .unwrap_or(checksum_file);

        let checksum_str = checksum_str
            .split_whitespace()
            .next()
            .unwrap_or(&checksum_str);
        Ok(checksum_str.to_string())
    }

    async fn download(
        &self,
        ctx: &InstallContext,
        tv: &ToolVersion,
        url: &str,
        filename: &str,
    ) -> Result<()> {
        let tarball_path = tv.download_path().join(filename);
        if tarball_path.exists() {
            return Ok(());
        }
        ctx.pr.set_message(format!("download {filename}"));
        HTTP.download_file(url, &tarball_path, Some(ctx.pr.as_ref()))
            .await?;
        Ok(())
    }

    async fn verify(
        &self,
        ctx: &InstallContext,
        tv: &mut ToolVersion,
        pkg: &AquaPackage,
        v: &str,
        filename: &str,
    ) -> Result<()> {
        // Skip provenance verification if the lockfile already has both a checksum and
        // provenance entry for this platform — the artifact integrity is already guaranteed
        // by the checksum, so re-verifying attestations would just be redundant API calls.
        // However, still check that the recorded provenance type's setting is enabled —
        // disabling a verification setting with a provenance-bearing lockfile is a downgrade.
        //
        // When locked_verify_provenance is enabled (or paranoid mode is on), always
        // re-verify provenance at install time regardless of what the lockfile contains.
        // This closes the gap where lock-time detection records provenance from registry
        // metadata without cryptographic verification.
        let settings = Settings::get();
        let force_verify = settings.force_provenance_verify();
        let platform_key = self.get_platform_key();
        let has_lockfile_integrity = tv
            .lock_platforms
            .get(&platform_key)
            .is_some_and(|pi| pi.checksum.is_some() && pi.provenance.is_some());
        if has_lockfile_integrity && !force_verify {
            self.ensure_provenance_setting_enabled(tv, &platform_key)?;
        } else {
            self.verify_provenance(ctx, tv, pkg, v, filename).await?;
        }

        let tarball_path = tv.download_path().join(filename);
        self.verify_checksum(ctx, tv, &tarball_path)?;
        Ok(())
    }

    async fn verify_provenance(
        &self,
        ctx: &InstallContext,
        tv: &mut ToolVersion,
        pkg: &AquaPackage,
        v: &str,
        filename: &str,
    ) -> Result<()> {
        // Check if the lockfile expects provenance for this platform, then clear it
        // so we can detect whether verification actually re-set it
        let platform_key = self.get_platform_key();
        let locked_provenance = tv
            .lock_platforms
            .get_mut(&platform_key)
            .and_then(|pi| pi.provenance.take());

        // When the lockfile specifies a provenance type, only run that specific mechanism.
        // This prevents false-positive downgrade errors when a tool supports multiple mechanisms
        // (e.g., both minisign and cosign) that would otherwise compete for the provenance slot.
        let skip_attestations = locked_provenance
            .as_ref()
            .is_some_and(|l| !l.is_github_attestations());
        let skip_slsa = locked_provenance.as_ref().is_some_and(|l| !l.is_slsa());
        let skip_minisign = locked_provenance.as_ref().is_some_and(|l| !l.is_minisign());
        let skip_cosign = locked_provenance.as_ref().is_some_and(|l| !l.is_cosign());

        if !skip_attestations {
            self.verify_github_artifact_attestations(ctx, tv, pkg, v, filename)
                .await?;
        }
        if !skip_slsa {
            // Short-circuit: if a higher-priority mechanism already recorded provenance, skip SLSA
            let already_verified = tv
                .lock_platforms
                .get(&platform_key)
                .and_then(|pi| pi.provenance.as_ref())
                .is_some_and(|p| *p > ProvenanceType::Slsa { url: None });
            if !already_verified {
                self.verify_slsa(ctx, tv, pkg, v, filename).await?;
            }
        }
        if !skip_minisign {
            // Short-circuit: if SLSA or GithubAttestations already recorded provenance, skip minisign.
            // Cosign runs later in the checksum block, so it cannot be set at this point.
            let already_verified = tv
                .lock_platforms
                .get(&platform_key)
                .and_then(|pi| pi.provenance.as_ref())
                .is_some_and(|p| p.is_slsa() || p.is_github_attestations());
            if !already_verified {
                self.verify_minisign(ctx, tv, pkg, v, filename).await?;
            }
        }

        let download_path = tv.download_path();
        if let Some(checksum) = &pkg.checksum
            && checksum.enabled()
        {
            let checksum_path = download_path.join(format!("{filename}.checksum"));
            let platform_key = self.get_platform_key();
            let needs_checksum = tv
                .lock_platforms
                .get(&platform_key)
                .is_none_or(|pi| pi.checksum.is_none());

            let needs_cosign = !skip_cosign
                && Settings::get().aqua.cosign
                && checksum
                    .cosign
                    .as_ref()
                    .is_some_and(|c| c.enabled != Some(false));
            // Short-circuit cosign if a higher-priority mechanism already recorded provenance.
            // Safe to cache: provenance is only modified by the single-threaded verification
            // methods above (attestations, slsa, minisign), all of which have completed by now.
            let cosign_already_verified = needs_cosign
                && tv
                    .lock_platforms
                    .get(&platform_key)
                    .and_then(|pi| pi.provenance.as_ref())
                    .is_some_and(|p| *p > ProvenanceType::Cosign);
            // Re-download only if the checksum file doesn't exist yet. An existing file
            // from a prior attempt is trusted because the download directory is version-specific
            // and the final artifact is independently verified by verify_checksum at the end.
            if (needs_checksum || (needs_cosign && !cosign_already_verified))
                && !checksum_path.exists()
            {
                let url = match checksum._type() {
                    AquaChecksumType::GithubRelease => {
                        let asset_strs = checksum.asset_strs(pkg, v, os(), arch())?;
                        self.github_release_asset(pkg, v, asset_strs).await?.0
                    }
                    AquaChecksumType::Http => checksum.url(pkg, v, os(), arch())?,
                };
                HTTP.download_file(&url, &checksum_path, Some(ctx.pr.as_ref()))
                    .await?;
            }

            if needs_cosign && !cosign_already_verified && checksum_path.exists() {
                self.cosign_checksums(ctx, pkg, v, tv, &checksum_path, &download_path)
                    .await?;
            }

            if needs_checksum && checksum_path.exists() {
                let checksum_content = file::read_to_string(&checksum_path)?;
                let checksum_str =
                    self.parse_checksum_from_content(&checksum_content, checksum, filename)?;
                let checksum_val = format!("{}:{}", checksum.algorithm(), checksum_str);
                let platform_key = self.get_platform_key();
                let platform_info = tv.lock_platforms.entry(platform_key).or_default();
                platform_info.checksum = Some(checksum_val);
            }
        }
        // If lockfile recorded provenance, verify that the type matches
        // (checked after all verification methods including cosign have had a chance to record)
        if let Some(ref expected) = locked_provenance {
            let platform_key = self.get_platform_key();
            let got = tv
                .lock_platforms
                .get(&platform_key)
                .and_then(|pi| pi.provenance.as_ref());
            if !got.is_some_and(|g| std::mem::discriminant(g) == std::mem::discriminant(expected)) {
                let got_str = got
                    .map(|g| g.to_string())
                    .unwrap_or_else(|| "no verification".to_string());
                return Err(eyre!(
                    "Lockfile requires {expected} provenance for {tv} but {got_str} was used. \
                     This may indicate a downgrade attack. Enable the corresponding verification setting \
                     or update the lockfile."
                ));
            }
        }

        Ok(())
    }

    /// When skipping full provenance re-verification (lockfile has checksum+provenance),
    /// check that the setting for the recorded provenance type is still enabled.
    /// Disabling a verification setting while the lockfile expects it is a downgrade.
    fn ensure_provenance_setting_enabled(
        &self,
        tv: &ToolVersion,
        platform_key: &str,
    ) -> Result<()> {
        super::ensure_provenance_setting_enabled(tv, platform_key, |provenance| {
            let settings = Settings::get();
            Ok(match provenance {
                ProvenanceType::GithubAttestations => {
                    !settings.github_attestations || !settings.aqua.github_attestations
                }
                ProvenanceType::Slsa { .. } => !settings.slsa || !settings.aqua.slsa,
                ProvenanceType::Cosign => !settings.aqua.cosign,
                ProvenanceType::Minisign => !settings.aqua.minisign,
            })
        })
    }

    async fn verify_minisign(
        &self,
        ctx: &InstallContext,
        tv: &mut ToolVersion,
        pkg: &AquaPackage,
        v: &str,
        filename: &str,
    ) -> Result<()> {
        if !Settings::get().aqua.minisign {
            return Ok(());
        }
        if let Some(minisign) = &pkg.minisign {
            if minisign.enabled == Some(false) {
                debug!("minisign is disabled for {tv}");
                return Ok(());
            }
            ctx.pr.set_message("verify minisign".to_string());
            debug!("minisign: {:?}", minisign);
            let artifact_path = tv.download_path().join(filename);
            self.run_minisign_check(
                &artifact_path,
                filename,
                pkg,
                v,
                &tv.download_path(),
                Some(ctx.pr.as_ref()),
            )
            .await?;

            // Record minisign provenance if no higher-priority verification already recorded
            let platform_key = self.get_platform_key();
            let pi = tv.lock_platforms.entry(platform_key).or_default();
            if pi.provenance.is_none() {
                pi.provenance = Some(ProvenanceType::Minisign);
            }
        }
        Ok(())
    }

    async fn verify_slsa(
        &self,
        ctx: &InstallContext,
        tv: &mut ToolVersion,
        pkg: &AquaPackage,
        v: &str,
        filename: &str,
    ) -> Result<()> {
        let settings = Settings::get();
        if !settings.slsa || !settings.aqua.slsa {
            return Ok(());
        }
        if let Some(slsa) = &pkg.slsa_provenance {
            if slsa.enabled == Some(false) {
                debug!("slsa is disabled for {tv}");
                return Ok(());
            }

            ctx.pr.set_message("verify slsa".to_string());
            let artifact_path = tv.download_path().join(filename);
            let provenance_url = self
                .run_slsa_check(
                    &artifact_path,
                    pkg,
                    v,
                    &tv.download_path(),
                    Some(ctx.pr.as_ref()),
                )
                .await?;

            ctx.pr.set_message("✓ SLSA provenance verified".to_string());
            // Record provenance in lockfile only if not already set by a
            // higher-priority verification (github-attestations runs first)
            let platform_key = self.get_platform_key();
            let pi = tv.lock_platforms.entry(platform_key).or_default();
            if pi.provenance.is_none() {
                pi.provenance = Some(ProvenanceType::Slsa {
                    url: Some(provenance_url),
                });
            }
        }
        Ok(())
    }

    async fn verify_github_artifact_attestations(
        &self,
        ctx: &InstallContext,
        tv: &mut ToolVersion,
        pkg: &AquaPackage,
        _v: &str,
        filename: &str,
    ) -> Result<()> {
        // Check if attestations are enabled via global and aqua-specific settings
        let settings = Settings::get();
        if !settings.github_attestations || !settings.aqua.github_attestations {
            debug!("GitHub artifact attestations verification disabled");
            return Ok(());
        }

        if let Some(github_attestations) = &pkg.github_artifact_attestations {
            if github_attestations.enabled == Some(false) {
                debug!("GitHub artifact attestations verification is disabled for {tv}");
                return Ok(());
            }

            ctx.pr
                .set_message("verify GitHub artifact attestations".to_string());
            let artifact_path = tv.download_path().join(filename);
            self.run_github_attestation_check(&artifact_path, pkg)
                .await?;

            ctx.pr
                .set_message("✓ GitHub artifact attestations verified".to_string());
            let platform_key = self.get_platform_key();
            let pi = tv.lock_platforms.entry(platform_key).or_default();
            if pi.provenance.is_none() {
                pi.provenance = Some(ProvenanceType::GithubAttestations);
            }
        }

        Ok(())
    }

    async fn cosign_checksums(
        &self,
        ctx: &InstallContext,
        pkg: &AquaPackage,
        v: &str,
        tv: &mut ToolVersion,
        checksum_path: &Path,
        download_path: &Path,
    ) -> Result<()> {
        if !Settings::get().aqua.cosign {
            return Ok(());
        }
        if let Some(cosign) = pkg.checksum.as_ref().and_then(|c| c.cosign.as_ref()) {
            if cosign.enabled == Some(false) {
                debug!("cosign is disabled for {tv}");
                return Ok(());
            }

            // Opts-only config (no key or bundle) — nothing to verify natively
            if cosign.key.is_none() && cosign.bundle.is_none() {
                debug!("cosign for {tv} uses opts-only config, skipping native verification");
                return Ok(());
            }

            ctx.pr
                .set_message("verify checksums with cosign".to_string());
            self.run_cosign_check(checksum_path, pkg, v, download_path, Some(ctx.pr.as_ref()))
                .await?;

            ctx.pr.set_message("✓ Cosign verified".to_string());
            let platform_key = self.get_platform_key();
            let pi = tv.lock_platforms.entry(platform_key).or_default();
            if pi
                .provenance
                .as_ref()
                .is_none_or(|p| *p < ProvenanceType::Cosign)
            {
                pi.provenance = Some(ProvenanceType::Cosign);
            }
        }
        Ok(())
    }

    fn install(
        &self,
        ctx: &InstallContext,
        tv: &ToolVersion,
        pkg: &AquaPackage,
        v: &str,
        filename: &str,
    ) -> Result<()> {
        let tarball_path = tv.download_path().join(filename);
        ctx.pr.set_message(format!("extract {filename}"));
        let install_path = tv.install_path();
        file::remove_all(&install_path)?;
        let format = pkg.format(v, os(), arch())?;
        let mut bin_names: Vec<Cow<'_, str>> = pkg
            .files
            .iter()
            .filter_map(|file| match file.src(pkg, v, os(), arch()) {
                Ok(Some(s)) => Some(Cow::Owned(s)),
                Ok(None) => Some(Cow::Borrowed(file.name.as_str())),
                Err(_) => None,
            })
            .collect();
        if bin_names.is_empty() {
            let fallback_name = pkg
                .name
                .as_deref()
                .and_then(|n| n.split('/').next_back())
                .unwrap_or(&pkg.repo_name);
            bin_names = vec![Cow::Borrowed(fallback_name)];
        }
        let bin_paths: Vec<_> = bin_names
            .iter()
            .map(|name| {
                let name_str: &str = name.as_ref();
                install_path.join(name_str)
            })
            .map(|path| {
                if cfg!(windows) && pkg.complete_windows_ext {
                    path.with_extension("exe")
                } else {
                    path
                }
            })
            .collect();
        let first_bin_path = bin_paths
            .first()
            .expect("at least one bin path should exist");
        let tar_opts = TarOptions {
            pr: Some(ctx.pr.as_ref()),
            ..TarOptions::new(TarFormat::from_ext(format))
        };
        let mut make_executable = false;
        if let AquaPackageType::GithubArchive = pkg.r#type {
            file::untar(&tarball_path, &install_path, &tar_opts)?;
        } else if let AquaPackageType::GithubContent = pkg.r#type {
            file::create_dir_all(&install_path)?;
            file::copy(&tarball_path, first_bin_path)?;
            make_executable = true;
        } else if format == "raw" {
            file::create_dir_all(&install_path)?;
            file::copy(&tarball_path, first_bin_path)?;
            make_executable = true;
        } else if format.starts_with("tar") {
            file::untar(&tarball_path, &install_path, &tar_opts)?;
            make_executable = true;
        } else if format == "zip" {
            file::unzip(&tarball_path, &install_path, &Default::default())?;
            make_executable = true;
        } else if format == "gz" {
            file::create_dir_all(&install_path)?;
            file::un_gz(&tarball_path, first_bin_path)?;
            make_executable = true;
        } else if format == "xz" {
            file::create_dir_all(&install_path)?;
            file::un_xz(&tarball_path, first_bin_path)?;
            make_executable = true;
        } else if format == "zst" {
            file::create_dir_all(&install_path)?;
            file::un_zst(&tarball_path, first_bin_path)?;
            make_executable = true;
        } else if format == "bz2" {
            file::create_dir_all(&install_path)?;
            file::un_bz2(&tarball_path, first_bin_path)?;
            make_executable = true;
        } else if format == "dmg" {
            file::un_dmg(&tarball_path, &install_path)?;
        } else if format == "pkg" {
            file::un_pkg(&tarball_path, &install_path)?;
        } else {
            bail!("unsupported format: {}", format);
        }

        if make_executable {
            for bin_path in &bin_paths {
                // bin_path should exist, but doesn't when the registry is outdated
                if bin_path.exists() {
                    file::make_executable(bin_path)?;
                } else {
                    warn!("bin path does not exist: {}", bin_path.display());
                }
            }
        }

        let srcs = self.srcs(pkg, tv)?;
        for (src, dst) in &srcs {
            if src != dst && src.exists() && !dst.exists() {
                if cfg!(windows) {
                    file::copy(src, dst)?;
                } else {
                    let src = PathBuf::from(".").join(src.file_name().unwrap().to_str().unwrap());
                    file::make_symlink(&src, dst)?;
                }
            }
        }

        if self.symlink_bins(tv) {
            self.create_symlink_bin_dir(tv, &srcs)?;
        }

        Ok(())
    }

    /// Creates a `.mise-bins` directory with symlinks only to the binaries defined in the aqua registry.
    /// This prevents bundled dependencies (like Python in aws-cli) from being exposed on PATH.
    fn create_symlink_bin_dir(&self, tv: &ToolVersion, srcs: &[(PathBuf, PathBuf)]) -> Result<()> {
        let symlink_dir = tv.install_path().join(".mise-bins");
        file::create_dir_all(&symlink_dir)?;

        for (_, dst) in srcs {
            if let Some(bin_name) = dst.file_name() {
                let symlink_path = symlink_dir.join(bin_name);
                if dst.exists() && !symlink_path.exists() {
                    file::make_symlink_or_copy(dst, &symlink_path)?;
                }
            }
        }
        Ok(())
    }

    fn symlink_bins(&self, tv: &ToolVersion) -> bool {
        tv.request
            .options()
            .get("symlink_bins")
            .is_some_and(|v| v == "true" || v == "1")
    }

    fn srcs(&self, pkg: &AquaPackage, tv: &ToolVersion) -> Result<Vec<(PathBuf, PathBuf)>> {
        if pkg.files.is_empty() {
            let fallback_name = pkg
                .name
                .as_deref()
                .and_then(|n| n.split('/').next_back())
                .unwrap_or(&pkg.repo_name);

            let mut path = tv.install_path().join(fallback_name);
            if cfg!(windows) && pkg.complete_windows_ext {
                path = path.with_extension("exe");
            }

            return Ok(vec![(path.clone(), path)]);
        }

        let files: Vec<(PathBuf, PathBuf)> = pkg
            .files
            .iter()
            .map(|f| {
                let srcs = if let Some(prefix) = &pkg.version_prefix {
                    vec![f.src(pkg, &format!("{}{}", prefix, tv.version), os(), arch())?]
                } else {
                    vec![
                        f.src(pkg, &tv.version, os(), arch())?,
                        f.src(pkg, &format!("v{}", tv.version), os(), arch())?,
                    ]
                };
                Ok(srcs
                    .into_iter()
                    .flatten()
                    .map(|src| tv.install_path().join(src))
                    .map(|mut src| {
                        let mut dst = src.parent().unwrap().join(f.name.as_str());
                        if cfg!(windows) && pkg.complete_windows_ext {
                            src = src.with_extension("exe");
                            dst = dst.with_extension("exe");
                        }
                        (src, dst)
                    }))
            })
            .flatten_ok()
            .collect::<Result<Vec<_>>>()?
            .into_iter()
            .unique_by(|(src, _)| src.to_path_buf())
            .collect();
        Ok(files)
    }
}

async fn get_tags(pkg: &AquaPackage) -> Result<Vec<String>> {
    Ok(get_tags_with_created_at(pkg)
        .await?
        .into_iter()
        .map(|(tag, _)| tag)
        .collect())
}

/// Get tags with optional created_at timestamps.
/// Returns (tag_name, Option<created_at>) pairs.
async fn get_tags_with_created_at(pkg: &AquaPackage) -> Result<Vec<(String, Option<String>)>> {
    if let Some("github_tag") = pkg.version_source.as_deref() {
        // Tags don't have created_at timestamps
        let versions = github::list_tags(&format!("{}/{}", pkg.repo_owner, pkg.repo_name)).await?;
        return Ok(versions.into_iter().map(|v| (v, None)).collect());
    }
    let releases = github::list_releases(&format!("{}/{}", pkg.repo_owner, pkg.repo_name)).await?;
    if releases.is_empty() {
        // Fall back to tags (no timestamps)
        let versions = github::list_tags(&format!("{}/{}", pkg.repo_owner, pkg.repo_name)).await?;
        return Ok(versions.into_iter().map(|v| (v, None)).collect());
    }
    Ok(releases
        .into_iter()
        .map(|r| (r.tag_name, Some(r.created_at)))
        .collect())
}

fn validate(pkg: &AquaPackage) -> Result<()> {
    if pkg.no_asset {
        bail!("no asset released");
    }
    if let Some(message) = &pkg.error_message {
        bail!("{}", message);
    }
    if !is_platform_supported(&pkg.supported_envs, os(), arch()) {
        bail!(
            "unsupported env: {}/{} (supported: {:?})",
            os(),
            arch(),
            pkg.supported_envs
        );
    }
    match pkg.r#type {
        AquaPackageType::Cargo => {
            bail!(
                "package type `cargo` is not supported in the aqua backend. Use the cargo backend instead{}.",
                pkg.name
                    .as_ref()
                    .and_then(|s| s.strip_prefix("crates.io/"))
                    .map(|name| format!(": cargo:{name}"))
                    .unwrap_or_default()
            )
        }
        AquaPackageType::GoInstall => {
            bail!(
                "package type `go_install` is not supported in the aqua backend. Use the go backend instead{}.",
                pkg.path
                    .as_ref()
                    .map(|path| format!(": go:{path}"))
                    .unwrap_or_else(|| {
                        format!(": go:github.com/{}/{}", pkg.repo_owner, pkg.repo_name)
                    })
            )
        }
        _ => {}
    }
    Ok(())
}

/// Resolve repo owner and name from an override config, falling back to pkg defaults.
fn resolve_repo_info(
    override_owner: Option<&String>,
    override_name: Option<&String>,
    pkg: &AquaPackage,
) -> (String, String) {
    let owner = override_owner
        .cloned()
        .unwrap_or_else(|| pkg.repo_owner.clone());
    let name = override_name
        .cloned()
        .unwrap_or_else(|| pkg.repo_name.clone());
    (owner, name)
}

/// Check if extraction is needed based on format and package type.
fn needs_extraction(format: &str, pkg_type: &AquaPackageType) -> bool {
    (!format.is_empty() && format != "raw")
        || matches!(
            pkg_type,
            AquaPackageType::GithubArchive | AquaPackageType::GithubContent
        )
}

/// Check if a platform is supported by the package's supported_envs.
/// Returns true if supported, false if not.
fn is_platform_supported(supported_envs: &[String], os: &str, arch: &str) -> bool {
    if supported_envs.is_empty() {
        return true;
    }
    let envs: HashSet<&str> = supported_envs.iter().map(|s| s.as_str()).collect();
    let os_arch = format!("{os}/{arch}");
    let mut myself: HashSet<&str> = ["all", os, arch, os_arch.as_str()].into();
    // Windows ARM64 can typically run AMD64 binaries via emulation
    if os == "windows" && arch == "arm64" {
        myself.insert("windows/amd64");
        myself.insert("amd64");
    }
    !envs.is_disjoint(&myself)
}

pub fn os() -> &'static str {
    if cfg!(target_os = "macos") {
        "darwin"
    } else {
        &OS
    }
}

pub fn arch() -> &'static str {
    if cfg!(target_arch = "x86_64") {
        "amd64"
    } else if cfg!(target_arch = "arm") {
        "armv6l"
    } else if cfg!(target_arch = "aarch64") {
        "arm64"
    } else {
        &ARCH
    }
}