mise 2026.9.4

Dev tools, env vars, and tasks in one CLI
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
use crate::backend::backend_type::BackendType;
use crate::backend::options::VersionOrder;
use crate::cli::args::BackendArg;
use crate::config::Settings;
use crate::http::HTTP;
use crate::toolset::{RawBackendOptions, ToolVersionOptions};
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::{dirs, file};
use eyre::{Context, Result, bail, ensure};
use heck::ToShoutySnakeCase;
use indexmap::IndexMap;
use serde::Serialize as _;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::env;
use std::env::consts::OS;
use std::fmt::Display;
use std::fs::File;
use std::io::Read;
use std::iter::Iterator;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock as Lazy, Mutex};
use std::time::Duration;
use strum::IntoEnumIterator;
use url::Url;

// the registry is generated from registry/ in the project root
static BAKED_REGISTRY: Registry = include!(concat!(env!("OUT_DIR"), "/registry.rs"));

#[cfg(any(test, debug_assertions))]
pub(crate) fn baked_registry() -> &'static Registry {
    &BAKED_REGISTRY
}

pub(crate) static REGISTRY: Lazy<&'static Registry> = Lazy::new(|| {
    if !Settings::get().registry_floating {
        return &BAKED_REGISTRY;
    }

    if !registry_cache_path().exists() {
        return &BAKED_REGISTRY;
    }

    match load_cached_floating_registry() {
        Ok(registry) if !registry.missing_version_order => Box::leak(Box::new(registry)),
        Ok(_) => {
            warn!(
                "cached floating mise registry predates version-order metadata, using baked-in registry"
            );
            &BAKED_REGISTRY
        }
        Err(err) => {
            warn!("failed to load floating mise registry, using baked-in registry: {err:#}");
            &BAKED_REGISTRY
        }
    }
});

const MISE_REGISTRY_ARCHIVE_URL: &str = "https://mise.jdx.dev/registry/latest.tar.zst";
const MAX_REGISTRY_ARCHIVE_ENTRIES: usize = 4096;
const MAX_REGISTRY_ARCHIVE_ENTRY_SIZE: u64 = 1024 * 1024;
const MAX_REGISTRY_ARCHIVE_SIZE: u64 = 16 * 1024 * 1024;

pub(crate) struct Registry {
    entries: &'static [(&'static str, RegistryTool)],
    lookup: RegistryLookup,
    missing_version_order: bool,
}

enum RegistryLookup {
    Static(phf::Map<&'static str, usize>),
    Dynamic(HashMap<&'static str, usize>),
}

impl Registry {
    pub(crate) fn get(&self, name: &str) -> Option<&'static RegistryTool> {
        self.lookup.get(name).map(|index| &self.entries[*index].1)
    }

    pub(crate) fn contains_key(&self, name: &str) -> bool {
        self.lookup.get(name).is_some()
    }

    pub(crate) fn iter(&self) -> impl Iterator<Item = (&'static str, &'static RegistryTool)> {
        self.entries.iter().map(|(name, tool)| (*name, tool))
    }

    pub(crate) fn keys(&self) -> impl Iterator<Item = &'static str> {
        self.entries.iter().map(|(name, _)| *name)
    }

    pub(crate) fn values(&self) -> impl Iterator<Item = &'static RegistryTool> {
        self.entries.iter().map(|(_, tool)| tool)
    }

    fn dynamic(entries: BTreeMap<String, RegistryTool>, missing_version_order: bool) -> Self {
        let entries = entries
            .into_iter()
            .map(|(name, tool)| (leak_string(name), tool))
            .collect::<Vec<_>>();
        let entries = leak_vec(entries);
        let lookup = entries
            .iter()
            .enumerate()
            .map(|(index, (name, _))| (*name, index))
            .collect();
        Self {
            entries,
            lookup: RegistryLookup::Dynamic(lookup),
            missing_version_order,
        }
    }
}

impl RegistryLookup {
    fn get(&self, name: &str) -> Option<&usize> {
        match self {
            Self::Static(lookup) => lookup.get(name),
            Self::Dynamic(lookup) => lookup.get(name),
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct RegistryTool {
    pub short: &'static str,
    pub description: Option<&'static str>,
    pub(crate) version_order: VersionOrder,
    pub backends: &'static [RegistryBackend],
    pub bins: &'static [&'static str],
    #[allow(unused)]
    pub aliases: &'static [&'static str],
    pub overrides: &'static [&'static str],
    pub test: &'static Option<RegistryToolTest>,
    pub os: &'static [&'static str],
    pub idiomatic_files: &'static [RegistryIdiomaticFile],
    pub detect: &'static [&'static str],
}

#[derive(Debug, Clone)]
pub(crate) struct RegistryIdiomaticFile {
    pub path: &'static str,
    pub version_regex: Option<&'static str>,
    pub version_json_path: Option<&'static str>,
    pub version_expr: Option<&'static str>,
    /// Set when this file should no longer be read. The value is the reason, shown in
    /// the deprecation warning emitted when the file still resolves a version. Used for
    /// files that only declare a minimum compatible version rather than the version the
    /// project is built with.
    pub deprecated: Option<&'static str>,
}

impl RegistryIdiomaticFile {
    pub(crate) fn has_parser(&self) -> bool {
        self.version_regex.is_some()
            || self.version_json_path.is_some()
            || self.version_expr.is_some()
    }
}

#[derive(Debug, Clone)]
pub(crate) struct RegistryToolTest {
    pub cmd: &'static str,
    pub expected: &'static str,
    pub tools: &'static [&'static str],
}

#[derive(Debug, Clone)]
pub(crate) struct RegistryBackend {
    pub full: &'static str,
    pub platforms: &'static [&'static str],
    pub min_version: Option<&'static str>,
    pub options: &'static [(&'static str, &'static str)],
}

impl RegistryBackend {
    fn supports_version(&self, request: &str) -> bool {
        let Some(minimum) = self.min_version else {
            return true;
        };
        // Validated when loading both bundled and floating registries. This
        // boundary is explicitly restricted to semver tools; it never orders
        // backend version lists or interprets opaque lockfile versions.
        let minimum = semver::Version::parse(minimum).expect("validated registry min_version");
        let request = request.strip_prefix("prefix:").unwrap_or(request);
        let request = request.trim_start_matches(['v', 'V']);
        if let Ok(version) = semver::Version::parse(request) {
            return !version.cmp_precedence(&minimum).is_lt();
        }
        // A numeric prefix is excluded only when the entire prefix is below
        // the boundary. Let the backend resolve prefixes that overlap it.
        let parts = request.split('.').collect::<Vec<_>>();
        if !(1..=2).contains(&parts.len()) {
            return true;
        }
        let Some(parts) = parts
            .into_iter()
            .map(|part| {
                if part.is_empty()
                    || !part.bytes().all(|c| c.is_ascii_digit())
                    || (part.len() > 1 && part.starts_with('0'))
                {
                    return None;
                }
                part.parse::<u64>().ok()
            })
            .collect::<Option<Vec<_>>>()
        else {
            return true;
        };
        let minimum_parts = [minimum.major, minimum.minor];
        for (part, minimum) in parts.into_iter().zip(minimum_parts) {
            match part.cmp(&minimum) {
                std::cmp::Ordering::Less => return false,
                std::cmp::Ordering::Greater => return true,
                std::cmp::Ordering::Equal => {}
            }
        }
        true
    }
}

fn registry_cache_path() -> PathBuf {
    dirs::CACHE.join("mise-registry").join("registry.tar.zst")
}

fn load_cached_floating_registry() -> Result<Registry> {
    parse_registry_archive(&registry_cache_path())
        .wrap_err("failed to load cached floating mise registry")
}

fn cache_is_fresh(path: &Path, ttl: Duration) -> bool {
    path.metadata()
        .and_then(|metadata| metadata.modified())
        .and_then(|modified| modified.elapsed().map_err(std::io::Error::other))
        .is_ok_and(|age| age < ttl)
}

/// Refresh the floating mise registry before anything initializes [`REGISTRY`].
/// Fast and offline commands use the cached archive (or the baked registry) without networking.
pub(crate) async fn refresh() {
    let settings = Settings::get();
    if !settings.registry_floating || settings.prefer_offline() {
        return;
    }

    let cache_path = registry_cache_path();
    if cache_is_fresh(&cache_path, settings.registry_cache_ttl()) {
        match parse_registry_archive(&cache_path) {
            Ok(registry) if !registry.missing_version_order => return,
            Ok(_) => warn!(
                "cached floating mise registry predates version-order metadata; refreshing it"
            ),
            Err(_) => warn!("cached floating mise registry is invalid; refreshing it"),
        }
    }

    if let Err(err) = download_registry_archive(&cache_path).await {
        warn!("failed to refresh floating mise registry: {err:#}");
    }
}

async fn download_registry_archive(cache_path: &Path) -> Result<()> {
    let download_path = cache_path.with_extension(format!("download-{}", std::process::id()));
    let pr = MultiProgressReport::get().add_pre_backend("mise registry");
    if let Err(err) = HTTP
        .download_file(MISE_REGISTRY_ARCHIVE_URL, &download_path, Some(pr.as_ref()))
        .await
    {
        let _ = file::remove_file(&download_path);
        pr.abandon();
        return Err(err);
    }

    let result = (|| {
        parse_registry_archive(&download_path)
            .wrap_err("downloaded mise registry archive is invalid")?;
        replace_registry_cache(&download_path, cache_path)?;
        Ok(())
    })();
    match result {
        Ok(()) => {
            pr.finish();
            Ok(())
        }
        Err(err) => {
            let _ = file::remove_file(&download_path);
            pr.abandon();
            Err(err)
        }
    }
}

#[cfg(not(windows))]
fn replace_registry_cache(download_path: &Path, cache_path: &Path) -> Result<()> {
    file::rename(download_path, cache_path)
}

#[cfg(windows)]
fn replace_registry_cache(download_path: &Path, cache_path: &Path) -> Result<()> {
    let backup_path = cache_path.with_extension(format!("backup-{}", std::process::id()));
    let had_cache = cache_path.exists();
    if backup_path.exists() {
        file::remove_file(&backup_path)?;
    }
    if had_cache {
        file::rename(cache_path, &backup_path)?;
    }
    if let Err(install_err) = file::rename(download_path, cache_path) {
        if had_cache && let Err(restore_err) = file::rename(&backup_path, cache_path) {
            return Err(install_err).wrap_err(format!(
                "failed to install downloaded registry and restore cached registry: {restore_err:#}"
            ));
        }
        return Err(install_err).wrap_err("failed to install downloaded registry");
    }
    if had_cache {
        file::remove_file(&backup_path)?;
    }
    Ok(())
}

fn parse_registry_archive(path: &Path) -> Result<Registry> {
    let file = File::open(path)?;
    let decoder = zstd::Decoder::new(file)?;
    let mut archive = jdx_tar::Archive::new(decoder);
    let mut sources = BTreeMap::new();
    let mut archive_size = 0_u64;

    for (index, entry) in archive.entries()?.enumerate() {
        let mut entry = entry?;
        track_registry_archive_entry(index, entry.size(), &mut archive_size)?;
        if entry.entry_type() != jdx_tar::EntryType::File {
            continue;
        }
        let path = entry.path()?;
        let components = path
            .components()
            .map(|component| component.as_os_str())
            .collect::<Vec<_>>();
        if components.len() != 2 || components[0] != "registry" {
            continue;
        }
        let file_path = PathBuf::from(components[1]);
        if file_path
            .extension()
            .is_none_or(|extension| extension != "toml")
        {
            continue;
        }
        let short = file_path
            .file_stem()
            .and_then(|stem| stem.to_str())
            .ok_or_else(|| eyre::eyre!("invalid registry filename: {}", path.display()))?
            .to_string();
        let mut source = String::new();
        entry.read_to_string(&mut source)?;
        sources.insert(short, source);
    }

    ensure!(
        !sources.is_empty(),
        "archive does not contain registry entries"
    );
    registry_from_sources(sources)
}

fn track_registry_archive_entry(
    index: usize,
    entry_size: u64,
    archive_size: &mut u64,
) -> Result<()> {
    ensure!(
        index < MAX_REGISTRY_ARCHIVE_ENTRIES,
        "registry archive contains too many entries"
    );
    ensure!(
        entry_size <= MAX_REGISTRY_ARCHIVE_ENTRY_SIZE,
        "registry archive entry is too large"
    );
    *archive_size = archive_size
        .checked_add(entry_size)
        .ok_or_else(|| eyre::eyre!("registry archive size overflow"))?;
    ensure!(
        *archive_size <= MAX_REGISTRY_ARCHIVE_SIZE,
        "registry archive is too large"
    );
    Ok(())
}

fn registry_from_sources(sources: BTreeMap<String, String>) -> Result<Registry> {
    let mut entries = BTreeMap::new();
    let mut missing_version_order = false;
    for (short, source) in sources {
        let value: toml::Value = toml::from_str(&source)
            .wrap_err_with(|| format!("failed to parse registry/{short}.toml"))?;
        let (tool, tool_missing_version_order) = parse_registry_tool(&short, &value)
            .wrap_err_with(|| format!("invalid registry/{short}.toml"))?;
        missing_version_order |= tool_missing_version_order;
        entries.insert(short, tool.clone());
        for alias in tool.aliases {
            entries.insert((*alias).to_string(), tool.clone());
        }
    }
    Ok(Registry::dynamic(entries, missing_version_order))
}

fn parse_registry_tool(short: &str, value: &toml::Value) -> Result<(RegistryTool, bool)> {
    let table = value
        .as_table()
        .ok_or_else(|| eyre::eyre!("registry tool must be a TOML table"))?;
    let backends = table
        .get("backends")
        .and_then(toml::Value::as_array)
        .ok_or_else(|| eyre::eyre!("backends must be an array"))?
        .iter()
        .map(parse_registry_backend)
        .collect::<Result<Vec<_>>>()?;
    ensure!(!backends.is_empty(), "backends must not be empty");

    let missing_version_order = !table.contains_key("version_order");
    let version_order = match table.get("version_order").and_then(toml::Value::as_str) {
        Some("source") => VersionOrder::Source,
        Some("semver") => VersionOrder::Semver,
        Some(_) => bail!("version_order must be \"source\" or \"semver\""),
        None => VersionOrder::Source,
    };

    ensure!(
        version_order == VersionOrder::Semver || backends.iter().all(|b| b.min_version.is_none()),
        "backend min_version requires version_order = \"semver\""
    );
    let aliases = string_array(table.get("aliases"), "aliases")?;
    let bins = if table.contains_key("bins") {
        string_array(table.get("bins"), "bins")?
    } else {
        BAKED_REGISTRY
            .get(short)
            .map(|tool| tool.bins.to_vec())
            .unwrap_or_default()
    };
    let overrides = string_array(table.get("overrides"), "overrides")?;
    let os = string_array(table.get("os"), "os")?;
    let idiomatic_files = parse_registry_idiomatic_files(table.get("idiomatic_files"))?;
    let detect = string_array(table.get("detect"), "detect")?;
    let description = table
        .get("description")
        .map(|value| {
            value
                .as_str()
                .map(|value| leak_string(value.to_string()))
                .ok_or_else(|| eyre::eyre!("description must be a string"))
        })
        .transpose()?;
    let test = table.get("test").map(parse_registry_test).transpose()?;

    let tool = RegistryTool {
        short: leak_string(short.to_string()),
        description,
        version_order,
        backends: leak_vec(backends),
        bins: leak_vec(bins),
        aliases: leak_vec(aliases),
        overrides: leak_vec(overrides),
        test: Box::leak(Box::new(test)),
        os: leak_vec(os),
        idiomatic_files: leak_vec(idiomatic_files),
        detect: leak_vec(detect),
    };
    Ok((tool, missing_version_order))
}

fn parse_registry_idiomatic_files(
    value: Option<&toml::Value>,
) -> Result<Vec<RegistryIdiomaticFile>> {
    value
        .map(|value| {
            value
                .as_array()
                .ok_or_else(|| eyre::eyre!("idiomatic_files must be an array"))?
                .iter()
                .map(parse_registry_idiomatic_file)
                .collect()
        })
        .transpose()
        .map(Option::unwrap_or_default)
}

fn parse_registry_idiomatic_file(value: &toml::Value) -> Result<RegistryIdiomaticFile> {
    match value {
        toml::Value::String(path) => Ok(RegistryIdiomaticFile {
            path: leak_string(path.clone()),
            version_regex: None,
            version_json_path: None,
            version_expr: None,
            deprecated: None,
        }),
        toml::Value::Table(table) => {
            for key in table.keys() {
                ensure!(
                    matches!(
                        key.as_str(),
                        "path"
                            | "version_regex"
                            | "version_json_path"
                            | "version_expr"
                            | "deprecated"
                    ),
                    "unknown idiomatic file field: {key}"
                );
            }
            let string = |key: &str| -> Result<Option<&'static str>> {
                table
                    .get(key)
                    .map(|value| {
                        value
                            .as_str()
                            .map(|value| leak_string(value.to_string()))
                            .ok_or_else(|| eyre::eyre!("idiomatic_files.{key} must be a string"))
                    })
                    .transpose()
            };
            let path = string("path")?
                .ok_or_else(|| eyre::eyre!("idiomatic_files.path must be a string"))?;
            Ok(RegistryIdiomaticFile {
                path,
                version_regex: string("version_regex")?,
                version_json_path: string("version_json_path")?,
                version_expr: string("version_expr")?,
                deprecated: string("deprecated")?,
            })
        }
        _ => Err(eyre::eyre!(
            "idiomatic_files entries must be strings or tables"
        )),
    }
}

fn parse_registry_backend(value: &toml::Value) -> Result<RegistryBackend> {
    match value {
        toml::Value::String(full) => Ok(RegistryBackend {
            full: leak_string(full.clone()),
            platforms: &[],
            min_version: None,
            options: &[],
        }),
        toml::Value::Table(table) => {
            let full = table
                .get("full")
                .and_then(toml::Value::as_str)
                .ok_or_else(|| eyre::eyre!("backend full must be a string"))?;
            let platforms = string_array(table.get("platforms"), "backend platforms")?;
            let min_version = table
                .get("min_version")
                .map(|value| {
                    let value = value
                        .as_str()
                        .ok_or_else(|| eyre::eyre!("backend min_version must be a string"))?;
                    semver::Version::parse(value)
                        .wrap_err("backend min_version must be a semantic version")?;
                    Ok::<_, eyre::Report>(leak_string(value.to_string()))
                })
                .transpose()?;
            let options = table
                .get("options")
                .and_then(toml::Value::as_table)
                .map(|options| {
                    options
                        .iter()
                        .map(|(key, value)| {
                            let mut serialized = String::new();
                            value.serialize(toml::ser::ValueSerializer::new(&mut serialized))?;
                            Ok((leak_string(key.clone()), leak_string(serialized)))
                        })
                        .collect::<Result<Vec<_>>>()
                })
                .transpose()?
                .unwrap_or_default();
            Ok(RegistryBackend {
                full: leak_string(full.to_string()),
                platforms: leak_vec(platforms),
                min_version,
                options: leak_vec(options),
            })
        }
        _ => bail!("backend must be a string or table"),
    }
}

fn parse_registry_test(value: &toml::Value) -> Result<RegistryToolTest> {
    let table = value
        .as_table()
        .ok_or_else(|| eyre::eyre!("test must be a table"))?;
    let cmd = table
        .get("cmd")
        .and_then(toml::Value::as_str)
        .ok_or_else(|| eyre::eyre!("test.cmd must be a string"))?;
    let expected = table
        .get("expected")
        .and_then(toml::Value::as_str)
        .ok_or_else(|| eyre::eyre!("test.expected must be a string"))?;
    let tools = string_array(table.get("tools"), "test.tools")?;
    Ok(RegistryToolTest {
        cmd: leak_string(cmd.to_string()),
        expected: leak_string(expected.to_string()),
        tools: leak_vec(tools),
    })
}

fn string_array(value: Option<&toml::Value>, name: &str) -> Result<Vec<&'static str>> {
    value
        .map(|value| {
            value
                .as_array()
                .ok_or_else(|| eyre::eyre!("{name} must be an array"))?
                .iter()
                .map(|value| {
                    value
                        .as_str()
                        .map(|value| leak_string(value.to_string()))
                        .ok_or_else(|| eyre::eyre!("{name} must contain only strings"))
                })
                .collect()
        })
        .transpose()
        .map(Option::unwrap_or_default)
}

fn leak_string(value: String) -> &'static str {
    Box::leak(value.into_boxed_str())
}

fn leak_vec<T>(value: Vec<T>) -> &'static [T] {
    Box::leak(value.into_boxed_slice())
}

// Cache for environment variable overrides
static ENV_BACKENDS: Lazy<Mutex<HashMap<String, &'static str>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

impl RegistryTool {
    pub(crate) fn provides_bin(&self, bin_name: &str) -> bool {
        let exe_suffix = std::env::consts::EXE_SUFFIX;
        let bin_name = if exe_suffix.is_empty() {
            bin_name
        } else {
            let suffix_start = bin_name.len().saturating_sub(exe_suffix.len());
            match (bin_name.get(..suffix_start), bin_name.get(suffix_start..)) {
                (Some(name), Some(suffix)) if suffix.eq_ignore_ascii_case(exe_suffix) => name,
                _ => bin_name,
            }
        };
        self.bins.iter().any(|bin| {
            if cfg!(windows) {
                bin.eq_ignore_ascii_case(bin_name)
            } else {
                *bin == bin_name
            }
        })
    }

    pub(crate) fn backends(&self) -> Vec<&'static str> {
        // Check for environment variable override first
        // e.g., MISE_BACKENDS_GRAPHITE='github:withgraphite/homebrew-tap[exe=gt]'
        let env_key = format!("MISE_BACKENDS_{}", self.short.to_shouty_snake_case());

        // Check cache first
        {
            let cache = ENV_BACKENDS.lock().unwrap();
            if let Some(&backend) = cache.get(&env_key) {
                return vec![backend];
            }
        }

        // Check environment variable
        if let Ok(env_value) = env::var(&env_key) {
            // Store in cache with 'static lifetime
            let leaked = Box::leak(env_value.into_boxed_str());
            let mut cache = ENV_BACKENDS.lock().unwrap();
            cache.insert(env_key.clone(), leaked);
            return vec![leaked];
        }

        static BACKEND_TYPES: Lazy<HashSet<String>> = Lazy::new(|| {
            let mut backend_types = BackendType::iter()
                .map(|b| b.to_string())
                .collect::<HashSet<_>>();
            time!("disable_backends");
            for backend in &Settings::get().disable_backends {
                backend_types.remove(backend);
            }
            time!("disable_backends");
            if cfg!(windows) {
                backend_types.remove("asdf");
            }
            backend_types
        });
        let settings = Settings::get();
        let experimental = settings.experimental;
        self.backends
            .iter()
            .filter(|rb| backend_matches_platform(rb.platforms, &settings))
            .map(|rb| rb.full)
            .filter(|full| {
                full.split(':')
                    .next()
                    .is_some_and(|b| BACKEND_TYPES.contains(b))
            })
            // Filter out experimental backends if experimental mode is disabled
            .filter(|full| {
                if experimental {
                    return true;
                }
                let backend_type = BackendType::guess(full);
                !backend_type.is_experimental()
            })
            .collect()
    }

    /// Filter only requests known to be older than a backend's introduction.
    /// Channels and unresolved aliases retain the ordinary backend priority.
    pub(crate) fn backends_for_version(&self, version: Option<&str>) -> Vec<&'static str> {
        self.backends()
            .into_iter()
            .filter(|full| version.is_none_or(|v| self.backend_supports_version(full, v)))
            .collect()
    }

    pub(crate) fn backend_supports_version(&self, full: &str, version: &str) -> bool {
        self.get_backend(full)
            .is_none_or(|backend| backend.supports_version(version))
    }

    pub(crate) fn is_supported_os(&self) -> bool {
        self.os.is_empty() || self.os.contains(&OS)
    }

    pub(crate) fn ba(&self) -> Option<BackendArg> {
        self.backends()
            .first()
            .map(|f| BackendArg::new(self.short.to_string(), Some(f.to_string())))
    }

    /// Get RegistryBackend for a specific full backend string
    pub(crate) fn get_backend(&self, full: &str) -> Option<&RegistryBackend> {
        self.backends.iter().find(|rb| rb.full == full)
    }

    /// Get options for a specific backend
    pub(crate) fn backend_options(&self, full: &str) -> ToolVersionOptions {
        let mut opts = IndexMap::new();

        if let Some(backend) = self.get_backend(full) {
            for (k, v) in backend.options {
                let value = v.parse::<toml::Value>().unwrap_or_else(|e| {
                    panic!("failed to parse registry option {k} as a TOML value: {e}")
                });
                opts.insert(k.to_string(), value);
            }
        }

        ToolVersionOptions {
            opts: RawBackendOptions::from(opts),
            ..Default::default()
        }
    }

    pub(crate) fn version_order(&self, full: &str) -> Option<VersionOrder> {
        matches!(
            BackendType::guess(full),
            BackendType::Aqua
                | BackendType::Forgejo
                | BackendType::Github
                | BackendType::Gitlab
                | BackendType::Http
        )
        .then_some(self.version_order)
    }
}

/// Matches registry backend selectors using the schema's normalized platform names.
///
/// Unlike `backends.options.platforms.*` lookup, this is deliberately not
/// alias-tolerant: registry selectors use canonical names such as `macos-x64`,
/// while option lookup accepts release asset aliases such as `darwin-amd64`.
///
/// Windows on arm64 additionally matches the x64 selectors. That is not alias
/// tolerance creeping in — `windows-x64` still names a different platform than
/// `windows-arm64` — it is the same capability rule the aqua backend already
/// applies in `is_platform_supported`: Windows arm64 runs amd64 binaries under
/// emulation. Without it the registry drops a backend here, before aqua is ever
/// asked whether it supports the platform, and aqua would have said yes.
fn backend_matches_platform(platforms: &[&str], settings: &Settings) -> bool {
    let os = settings.os();
    let arch = settings.arch();
    let platform = format!("{os}-{arch}");

    platforms.is_empty()
        || platforms.contains(&os)
        || platforms.contains(&arch)
        || platforms.contains(&platform.as_str())
        || (os == "windows"
            && arch == "arm64"
            && (platforms.contains(&"x64") || platforms.contains(&"windows-x64")))
}

pub(crate) fn shorts_for_full(full: &str) -> &'static Vec<&'static str> {
    static EMPTY: Vec<&'static str> = vec![];
    static FULL_TO_SHORT: Lazy<HashMap<&'static str, Vec<&'static str>>> = Lazy::new(|| {
        let mut map: HashMap<&'static str, Vec<&'static str>> = HashMap::new();
        for (short, rt) in REGISTRY.iter() {
            for full in rt.backends() {
                map.entry(full).or_default().push(short);
            }
        }
        map
    });
    FULL_TO_SHORT.get(full).unwrap_or(&EMPTY)
}

pub(crate) fn is_trusted_plugin(name: &str, remote: &str) -> bool {
    let Ok(normalized_url) = normalize_remote(remote) else {
        return false;
    };
    if normalized_url.starts_with("github.com/mise-plugins/") {
        return true;
    }

    let official_registry_plugin_remotes = || {
        static REMOTES: Lazy<HashSet<String>> = Lazy::new(|| {
            REGISTRY
                .values()
                .flat_map(|tool| tool.backends.iter().map(|backend| backend.full))
                .filter(|full| full.starts_with("asdf:") || full.starts_with("vfox:"))
                .filter_map(|full| normalize_remote(&full_to_url(full)).ok())
                .collect()
        });
        &*REMOTES
    };

    let name_matches_official_remote = REGISTRY.get(name).is_some_and(|tool| {
        tool.backends
            .iter()
            .map(|backend| backend.full)
            .filter(|full| full.starts_with("asdf:") || full.starts_with("vfox:"))
            .filter_map(|full| normalize_remote(&full_to_url(full)).ok())
            .any(|official_remote| official_remote == normalized_url)
    });

    name_matches_official_remote || official_registry_plugin_remotes().contains(&normalized_url)
}

pub(crate) fn normalize_remote(remote: &str) -> eyre::Result<String> {
    let url = Url::parse(remote)?;
    let host = url
        .host_str()
        .ok_or_else(|| eyre::eyre!("URL has no host: {remote}"))?;
    let path = url.path().trim_end_matches(".git");
    Ok(format!("{host}{path}"))
}

pub(crate) fn full_to_url(full: &str) -> String {
    if let Some(source) = full.strip_prefix("vfox:packslip:") {
        return format!("packslip:{source}");
    }
    if full.starts_with("packslip:") {
        return full.to_string();
    }
    if url_like(full) {
        return full.to_string();
    }
    let (_backend, url) = full.split_once(':').unwrap_or(("", full));
    if url_like(url) {
        url.to_string()
    } else {
        format!("https://github.com/{url}.git")
    }
}

pub(crate) fn url_like(s: &str) -> bool {
    s.starts_with("https://")
        || s.starts_with("http://")
        || s.starts_with("git@")
        || s.starts_with("ssh://")
        || s.starts_with("git://")
}

impl Display for RegistryTool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.short)
    }
}

/// Returns true when `name` passes the configured tool filter.
///
/// `None` means no allowlist is configured, so `disable_tools` excludes
/// individual tools. `Some(empty)` is an explicit empty allowlist and disables
/// every tool. When an allowlist is configured, it is authoritative and
/// `disable_tools` is not applied.
pub(crate) fn tool_enabled<T: Ord>(
    enable_tools: Option<&BTreeSet<T>>,
    disable_tools: &BTreeSet<T>,
    name: &T,
) -> bool {
    match enable_tools {
        Some(enable_tools) => enable_tools.contains(name),
        None => !disable_tools.contains(name),
    }
}

#[cfg(test)]
mod tests {
    use super::{BTreeMap, baked_registry, registry_from_sources};
    use crate::config::Config;

    #[test]
    fn registry_min_version_boundaries() {
        let backend = super::RegistryBackend {
            full: "packslip:github.com/example/tool",
            platforms: &[],
            min_version: Some("1.58.1"),
            options: &[],
        };
        for request in [
            "0",
            "1.5",
            "1.57",
            "prefix:1.57",
            "1.58.0",
            "v1.58.0",
            "V1.58.0",
            "prefix:V1.57",
            "1.58.1-rc.1",
        ] {
            assert!(!backend.supports_version(request), "{request}");
        }
        for request in [
            "1",
            "1.58",
            "prefix:1.58",
            "1.58.1",
            "V1.58.1",
            "1.58.1+build.2",
            "2.0.0",
            "latest",
            "nightly",
            "ref:main",
            "lts/iron",
            "0.nightly",
            "1.58.0.2",
            "01.57",
            "",
        ] {
            assert!(backend.supports_version(request), "{request}");
        }
    }

    #[test]
    fn registry_min_version_parsing_and_validation() {
        use super::*;
        let parse = |order: &str, minimum: &str| {
            let source = format!(
                r#"
version_order = "{order}"
backends = [
  {{ full = "packslip:github.com/example/tool", min_version = {minimum} }},
  "aqua:example/tool",
]
"#
            );
            parse_registry_tool("example", &toml::from_str::<toml::Value>(&source).unwrap())
        };
        let (tool, _) = parse("semver", r#""1.58.1""#).unwrap();
        assert_eq!(tool.backends[0].min_version, Some("1.58.1"));
        assert_eq!(tool.backends[1].min_version, None);
        assert_eq!(
            tool.backends_for_version(Some("1.57")),
            ["aqua:example/tool"]
        );
        assert_eq!(
            tool.backends_for_version(Some("latest")),
            ["packslip:github.com/example/tool", "aqua:example/tool"]
        );
        for minimum in [
            r#""latest""#,
            r#""1.58""#,
            r#""01.58.1""#,
            r#""1.0.0-01""#,
            r#""1.0.0-a..b""#,
            r#""1.0.0+a..b""#,
            "true",
            "12",
        ] {
            assert!(parse("semver", minimum).is_err(), "{minimum}");
        }
        assert!(parse("source", r#""1.58.1""#).is_err());
    }

    #[test]
    fn registry_min_version_schema_matches_semver_identifiers() {
        let schema: serde_json::Value =
            serde_json::from_str(include_str!("../schema/mise-registry-tool.json")).unwrap();
        let pattern = schema["properties"]["backends"]["items"]["oneOf"][1]
            ["properties"]["min_version"]["pattern"].as_str().unwrap();
        let pattern = regex::Regex::new(pattern).unwrap();
        for (version, valid) in [
            ("1.58.1", true),
            ("0.0.0", true),
            ("1.0.0-0", true),
            ("1.0.0-0alpha.1+build.01", true),
            ("1.0.0+01", true),
            ("1.0.0-a..b", false),
            ("1.0.0-01", false),
            ("1.0.0-alpha.01", false),
            ("1.0.0+a..b", false),
            ("1.0.0+", false),
            ("1.0.0-", false),
            ("01.0.0", false),
        ] {
            assert_eq!(pattern.is_match(version), valid, "{version}");
            assert_eq!(semver::Version::parse(version).is_ok(), valid, "{version}");
        }
    }

    #[test]
    fn baked_registry_infers_bins_from_preferred_aqua_backend() {
        let tool = baked_registry().get("jq").unwrap();
        assert_eq!(tool.bins, &["jq"]);
    }

    #[test]
    fn floating_registry_reuses_baked_inferred_bins() {
        let registry = registry_from_sources(BTreeMap::from([(
            "jq".to_string(),
            r#"
backends = ["aqua:jqlang/jq"]
version_order = "source"
"#
            .to_string(),
        )]))
        .unwrap();

        assert_eq!(registry.get("jq").unwrap().bins, &["jq"]);
    }

    fn registry_archive(entries: &[(&str, &str)]) -> tempfile::NamedTempFile {
        use std::io::Cursor;

        let file = tempfile::NamedTempFile::new().unwrap();
        let encoder = zstd::Encoder::new(file.reopen().unwrap(), 0).unwrap();
        let mut archive = jdx_tar::Builder::new(encoder);
        for (path, contents) in entries {
            let mut header = jdx_tar::Header::new_gnu(jdx_tar::EntryType::File);
            header.set_size(contents.len() as u64);
            header.set_mode(0o644);
            archive
                .append_data(&mut header, path, Cursor::new(contents.as_bytes()))
                .unwrap();
        }
        archive.into_inner().unwrap().finish().unwrap();
        file
    }

    #[test]
    fn test_dynamic_registry_parses_tools_aliases_and_options() {
        use super::*;

        let registry = registry_from_sources(BTreeMap::from([(
            "example".to_string(),
            r#"
aliases = ["example-alias"]
description = "Example tool"
version_order = "semver"
bins = ["example", "example-helper"]
backends = [
  "aqua:example/tool",
  { full = "github:example/tool", platforms = ["linux-x64"], options = { bin = "example" } },
]
idiomatic_files = [
  ".example-version",
  { path = "example.json", version_json_path = ".tool.version" },
  { path = "example.txt", version_regex = 'version=(\S+)', version_expr = "versions[0]" },
  { path = "example.conf", version_regex = 'minimum=(\S+)', deprecated = "it declares a minimum." },
]
test = { cmd = "example --version", expected = "{{version}}", tools = ["node"] }
"#
            .to_string(),
        )]))
        .unwrap();

        let tool = registry.get("example-alias").unwrap();
        assert_eq!(tool.short, "example");
        assert_eq!(tool.description, Some("Example tool"));
        assert_eq!(tool.bins, &["example", "example-helper"]);
        assert!(tool.provides_bin("example"));
        assert!(!tool.provides_bin("other"));
        if cfg!(windows) {
            assert!(tool.provides_bin("EXAMPLE.EXE"));
        }
        assert_eq!(tool.backends[0].full, "aqua:example/tool");
        assert_eq!(tool.backends[1].platforms, &["linux-x64"]);
        assert_eq!(
            tool.backend_options("github:example/tool").get("bin"),
            Some("example")
        );
        assert_eq!(
            tool.version_order("aqua:example/tool"),
            Some(VersionOrder::Semver)
        );
        assert_eq!(tool.idiomatic_files[0].path, ".example-version");
        assert!(!tool.idiomatic_files[0].has_parser());
        assert_eq!(tool.idiomatic_files[1].path, "example.json");
        assert_eq!(
            tool.idiomatic_files[1].version_json_path,
            Some(".tool.version")
        );
        assert_eq!(
            tool.idiomatic_files[2].version_regex,
            Some(r"version=(\S+)")
        );
        assert_eq!(tool.idiomatic_files[2].version_expr, Some("versions[0]"));
        assert_eq!(tool.idiomatic_files[2].deprecated, None);
        assert_eq!(tool.idiomatic_files[3].path, "example.conf");
        assert_eq!(
            tool.idiomatic_files[3].deprecated,
            Some("it declares a minimum.")
        );
        assert_eq!(tool.test.as_ref().unwrap().tools, &["node"]);
        assert!(!registry.missing_version_order);
    }

    #[test]
    fn test_dynamic_registry_defaults_missing_version_order_to_source() {
        use super::*;

        let registry = registry_from_sources(BTreeMap::from([(
            "example".to_string(),
            "backends = [\"aqua:example/tool\"]".to_string(),
        )]))
        .unwrap();

        assert_eq!(
            registry
                .get("example")
                .unwrap()
                .version_order("aqua:example/tool"),
            Some(VersionOrder::Source)
        );
        assert!(registry.missing_version_order);
    }

    #[test]
    fn test_dynamic_registry_rejects_unknown_idiomatic_file_fields() {
        use super::*;

        let err = registry_from_sources(BTreeMap::from([(
            "example".to_string(),
            r#"
backends = ["aqua:example/tool"]
version_order = "source"
idiomatic_files = [{ path = ".example-version", parser = "shell" }]
"#
            .to_string(),
        )]))
        .err()
        .unwrap();

        assert!(
            format!("{err:#}").contains("unknown idiomatic file field: parser"),
            "{err:#}"
        );
    }

    #[test]
    fn test_registry_archive_only_reads_top_level_registry_directory() {
        use super::*;

        let archive = registry_archive(&[
            (
                "registry/example.toml",
                "backends = [\"aqua:good/tool\"]\nversion_order = \"source\"",
            ),
            (
                "e2e/registry/example.toml",
                "backends = [\"aqua:wrong/tool\"]",
            ),
        ]);
        let registry = parse_registry_archive(archive.path()).unwrap();

        assert_eq!(
            registry.get("example").unwrap().backends[0].full,
            "aqua:good/tool"
        );
    }

    #[test]
    fn test_registry_archive_rejects_nested_registry_directory() {
        use super::*;

        let archive = registry_archive(&[(
            "e2e/registry/example.toml",
            "backends = [\"aqua:wrong/tool\"]",
        )]);

        assert!(parse_registry_archive(archive.path()).is_err());
    }

    #[test]
    fn test_registry_archive_limits() {
        use super::*;

        let mut size = 0;
        assert!(
            track_registry_archive_entry(MAX_REGISTRY_ARCHIVE_ENTRIES, 0, &mut size)
                .unwrap_err()
                .to_string()
                .contains("too many entries")
        );
        assert!(
            track_registry_archive_entry(0, MAX_REGISTRY_ARCHIVE_ENTRY_SIZE + 1, &mut size)
                .unwrap_err()
                .to_string()
                .contains("entry is too large")
        );
        size = MAX_REGISTRY_ARCHIVE_SIZE;
        assert!(
            track_registry_archive_entry(0, 1, &mut size)
                .unwrap_err()
                .to_string()
                .contains("archive is too large")
        );
    }

    #[test]
    fn test_tool_disabled() {
        use super::*;
        let name = "cargo";

        assert!(tool_enabled(None, &BTreeSet::new(), &name));
        assert!(!tool_enabled(
            Some(&BTreeSet::new()),
            &BTreeSet::new(),
            &name
        ));
        assert!(tool_enabled(
            Some(&BTreeSet::from(["cargo"])),
            &BTreeSet::new(),
            &name
        ));
        assert!(!tool_enabled(None, &BTreeSet::from(["cargo"]), &name));
        assert!(tool_enabled(
            Some(&BTreeSet::from(["cargo"])),
            &BTreeSet::from(["cargo"]),
            &name
        ));
    }

    #[test]
    fn test_registry_iteration_is_sorted() {
        use super::*;

        // The interactive tool selector and --all test-tool path consume registry
        // iteration order directly, so keep PHF lookup separate from sorted output.
        let keys = REGISTRY.keys().collect::<Vec<_>>();
        let mut sorted = keys.clone();
        sorted.sort_unstable();

        assert!(!keys.is_empty());
        assert_eq!(keys, sorted);
    }

    #[test]
    fn test_backend_platform_matching_normalizes_settings() {
        use super::*;

        for (raw_os, raw_arch, selector) in [
            ("windows", "x86_64", "windows-x64"),
            ("windows", "amd64", "x64"),
            ("linux", "aarch64", "linux-arm64"),
            ("darwin", "x86_64", "macos-x64"),
        ] {
            let settings = Settings {
                os: Some(raw_os.to_string()),
                arch: Some(raw_arch.to_string()),
                ..Default::default()
            };

            assert!(
                backend_matches_platform(&[selector], &settings),
                "{raw_os}-{raw_arch} should match normalized selector {selector}"
            );
        }
    }

    // A tool's `os` list drops it from the tool request set before any backend is consulted, so a
    // list that no longer matches what the backend can do makes mise refuse a tool that works.
    //
    // All 52 entries whose `os` line left out `windows` were put through `mise install` on Windows
    // and then had whatever landed on disk executed. Five of them produced a working Windows
    // executable -- `entire.exe version` reports `OS/Arch: windows/amd64`, `gitsign.exe --version`
    // reports `gitsign version v0.17.1` -- while their `os` line still said linux and macos only.
    // `acli`, `mimirtool` and `specstory` joined them later, measured the same way, once the
    // vendored aqua snapshot stopped restricting them.
    //
    // Installing is not evidence on its own: eight more installed successfully and unpacked no
    // Windows executable at all (`libsql-server` extracts a source tarball), so they keep their
    // restriction. So do the few the sweep could not settle for reasons that have nothing to do
    // with Windows -- `cocoapods` needs a ruby that is not there, `swift` overflowed the capture.
    // Unsettled is not the same as wrong, and only measured entries were changed.
    //
    // Read from `BAKED_REGISTRY` rather than `REGISTRY`: the claim under test is about the
    // `registry/*.toml` files in this commit, and `REGISTRY` hands back a cached floating registry
    // instead whenever `registry_floating` is on and the cache exists. That would let the test pass
    // against data this commit does not contain.
    //
    // Windows-only on purpose: off Windows every name here is allowed either way, so the assertion
    // would hold without the change and prove nothing.
    #[cfg(windows)]
    #[test]
    fn tools_that_run_on_windows_are_not_restricted_away_from_it() {
        use super::*;

        for short in [
            "entireio-cli",
            "gitsign",
            "go-swagger",
            "grpc-health-probe",
            "httpie-go",
            "acli",
            "mimirtool",
            "specstory",
        ] {
            let rt = BAKED_REGISTRY.get(short).unwrap();
            assert!(rt.is_supported_os(), "{short}: os = {:?}", rt.os);
        }

        // The controls, and they are the point: this is not "remove every os list". Each was
        // checked the same way and each stays. `kpt` ships no Windows asset at all.
        //
        // `docker-slim` is a control twice over: it is also the fixture in
        // `e2e-win/exec_os_unsupported_tool.Tests.ps1`, which asserts the exact message mise prints
        // for a tool this platform is not listed for. Dropping its `os` line would leave that test
        // with nothing to observe, so it fails here first, by name.
        for short in ["docker-slim", "kpt"] {
            let rt = BAKED_REGISTRY.get(short).unwrap();
            assert!(!rt.is_supported_os(), "{short}: os = {:?}", rt.os);
        }
    }

    // `mod tests` imports nothing at this level -- each test brings its own `use super::*` -- so
    // this one names the path.
    fn settings_for(os: &str, arch: &str) -> crate::config::Settings {
        crate::config::Settings {
            os: Some(os.to_string()),
            arch: Some(arch.to_string()),
            ..Default::default()
        }
    }

    // Windows arm64 runs amd64 binaries under emulation. The aqua backend already assumes this in
    // `is_platform_supported`, so a registry selector of `windows-x64` was dropping backends that
    // aqua itself would have accepted -- measured with `MISE_OS`/`MISE_ARCH`, where
    // `mise registry imagemagick` returned only `conda:imagemagick` on windows/arm64 while
    // windows/x64 got `aqua:ImageMagick/ImageMagick` first.
    #[test]
    fn windows_arm64_matches_x64_selectors_the_way_aqua_does() {
        use super::*;

        let settings = settings_for("windows", "arm64");
        for selector in ["windows-x64", "x64"] {
            assert!(
                backend_matches_platform(&[selector], &settings),
                "windows-arm64 should reach the {selector} backend under emulation"
            );
        }
    }

    // The controls. Each one fails if the rule above was written more broadly than intended, and
    // together they are what distinguishes "Windows emulates amd64" from "any arm64 takes x64".
    #[test]
    fn the_x64_fallback_is_confined_to_windows_arm64() {
        use super::*;

        for (os, arch, selector) in [
            // Linux on arm64 cannot execute an x86_64 build, so no backend is the right answer.
            ("linux", "arm64", "linux-x64"),
            // macOS has Rosetta, but aqua declares no rule for it and this change invents none.
            ("macos", "arm64", "macos-x64"),
            // Right platform, wrong OS in the selector.
            ("windows", "arm64", "linux-x64"),
            // Still not alias-tolerant, which the doc comment on the function promises: these name
            // the same machine as `windows-x64` but are not the canonical spelling.
            ("windows", "arm64", "windows-amd64"),
            ("windows", "arm64", "amd64"),
            // And the emulation direction is one-way -- x64 does not get to run arm64 builds.
            ("windows", "x64", "windows-arm64"),
        ] {
            let settings = settings_for(os, arch);
            assert!(
                !backend_matches_platform(&[selector], &settings),
                "{os}-{arch} should not match {selector}"
            );
        }
    }

    // Passing the backend filter is only half of it: the http backend then looks up
    // `platforms.<key>.url`, and `platform_aliases()` has no emulation rule of its own, so
    // windows/arm64 would resolve a backend and fail to find a URL. `android-cli` declares the
    // block explicitly rather than relying on a lookup fallback, and it has to stay pointed at the
    // x64 download -- Google publishes no arm64 build at all.
    #[test]
    fn android_cli_serves_windows_arm64_the_x64_download() {
        use super::*;

        let rt = BAKED_REGISTRY.get("android-cli").unwrap();
        let opts = rt.backend_options("http:android-cli");
        for key in ["url", "checksum_url", "bin"] {
            let arm64 = opts.get_nested_string(&format!("platforms.windows-arm64.{key}"));
            let x64 = opts.get_nested_string(&format!("platforms.windows-x64.{key}"));
            assert!(arm64.is_some(), "platforms.windows-arm64.{key} is missing");
            assert_eq!(arm64, x64, "windows-arm64 {key} should be the x64 one");
        }
    }

    // `pre-commit` ships a `.pyz` zipapp rather than a native binary, so aqua marks the package
    // `supported_envs: [darwin, linux]` and always will -- Windows has nothing to run a shebang
    // with. A short name resolves to `backends().first()` and there is no install-time fallback,
    // so without the `platforms` annotation Windows lands on that backend and stops, with the
    // registered `pipx:` one never reached. Split by platform rather than written as one test
    // because the pair is its own control: the same expression has to answer differently by
    // platform, which is the whole claim.
    //
    // Both first assert that `MISE_BACKENDS_PRE_COMMIT` is unset: `backends()` returns that
    // override ahead of every filter, so a process carrying one would make these pass or fail
    // without touching the registry at all. Asserted rather than cleared, because removing it
    // would mutate process-wide state other tests share.
    //
    // Read from `BAKED_REGISTRY` for the same reason the `os` test above does: the claim is about
    // `registry/pre-commit.toml` in this commit, and `REGISTRY` substitutes a cached floating
    // registry whenever `registry_floating` is on and the cache exists.
    #[cfg(windows)]
    #[test]
    fn pre_commit_falls_through_to_pipx_on_windows() {
        use super::*;

        assert!(env::var("MISE_BACKENDS_PRE_COMMIT").is_err());
        let backends = BAKED_REGISTRY.get("pre-commit").unwrap().backends();
        assert_eq!(
            backends.first().copied(),
            Some("pipx:pre-commit"),
            "{backends:?}"
        );
    }

    // Not `not(windows)`: mise runs on Android too, where `backend_matches_platform` sees `android`
    // and drops the aqua backend along with Windows, so this expectation would be wrong there.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn pre_commit_keeps_the_aqua_backend_off_windows() {
        use super::*;

        assert!(env::var("MISE_BACKENDS_PRE_COMMIT").is_err());
        let backends = BAKED_REGISTRY.get("pre-commit").unwrap().backends();
        assert_eq!(
            backends.first().copied(),
            Some("aqua:pre-commit/pre-commit"),
            "{backends:?}"
        );
    }

    #[test]
    fn test_backend_platform_matching_preserves_os_only_and_order() {
        use super::*;

        let settings = Settings {
            os: Some("darwin".to_string()),
            arch: Some("amd64".to_string()),
            ..Default::default()
        };
        let backends = [
            RegistryBackend {
                full: "aqua:first/tool",
                platforms: &["macos"],
                min_version: None,
                options: &[],
            },
            RegistryBackend {
                full: "github:second/tool",
                platforms: &["macos-x64"],
                min_version: None,
                options: &[],
            },
            RegistryBackend {
                full: "cargo:third-tool",
                platforms: &[],
                min_version: None,
                options: &[],
            },
            RegistryBackend {
                full: "npm:excluded-tool",
                platforms: &["linux"],
                min_version: None,
                options: &[],
            },
        ];

        let matching = backends
            .iter()
            .filter(|backend| backend_matches_platform(backend.platforms, &settings))
            .map(|backend| backend.full)
            .collect::<Vec<_>>();

        assert_eq!(
            matching,
            ["aqua:first/tool", "github:second/tool", "cargo:third-tool"]
        );

        let alias_selector = RegistryBackend {
            full: "github:owner/repo",
            platforms: &["darwin-amd64"],
            min_version: None,
            options: &[],
        };
        assert!(!backend_matches_platform(
            alias_selector.platforms,
            &settings
        ));
    }

    #[test]
    fn test_backend_options_parse_toml_values() {
        use super::*;

        static OPTIONS: &[(&str, &str)] = &[
            ("bin", r#""rg""#),
            ("prerelease", "true"),
            ("strip_components", "1"),
            (
                "targets",
                r#"["x86_64-unknown-linux-gnu", "aarch64-apple-darwin"]"#,
            ),
            (
                "platforms",
                r#"{ linux-x64 = { asset_pattern = "tool-linux.tar.gz" } }"#,
            ),
        ];
        static BACKENDS: &[RegistryBackend] = &[RegistryBackend {
            full: "github:owner/repo",
            platforms: &[],
            min_version: None,
            options: OPTIONS,
        }];
        let tool = RegistryTool {
            short: "test",
            description: None,
            version_order: VersionOrder::Source,
            backends: BACKENDS,
            bins: &[],
            aliases: &[],
            overrides: &[],
            test: &None,
            os: &[],
            idiomatic_files: &[],
            detect: &[],
        };

        let opts = tool.backend_options("github:owner/repo");

        assert_eq!(opts.get("bin"), Some("rg"));
        assert_eq!(
            opts.opts.get("prerelease"),
            Some(&toml::Value::Boolean(true))
        );
        assert_eq!(
            opts.opts.get("strip_components"),
            Some(&toml::Value::Integer(1))
        );
        assert!(opts.opts.get("targets").is_some_and(toml::Value::is_array));
        assert_eq!(
            opts.get_nested_string("platforms.linux-x64.asset_pattern"),
            Some("tool-linux.tar.gz".to_string())
        );
    }

    #[test]
    fn test_semver_registry_order_only_applies_to_supported_backends() {
        use super::*;

        static BACKENDS: &[RegistryBackend] = &[
            RegistryBackend {
                full: "aqua:owner/repo",
                platforms: &[],
                min_version: None,
                options: &[],
            },
            RegistryBackend {
                full: "npm:package",
                platforms: &[],
                min_version: None,
                options: &[],
            },
        ];
        let tool = RegistryTool {
            short: "test",
            description: None,
            version_order: VersionOrder::Semver,
            backends: BACKENDS,
            bins: &[],
            aliases: &[],
            overrides: &[],
            test: &None,
            os: &[],
            idiomatic_files: &[],
            detect: &[],
        };

        assert_eq!(
            tool.version_order("aqua:owner/repo"),
            Some(VersionOrder::Semver)
        );
        assert_eq!(tool.version_order("npm:package"), None);
    }

    #[tokio::test]
    async fn test_backend_env_override() {
        let _config = Config::get().await.unwrap();
        use super::*;

        // Clear the cache first
        ENV_BACKENDS.lock().unwrap().clear();

        // Test with a known tool from the registry
        if let Some(tool) = REGISTRY.get("node") {
            // First test without env var - should return default backends
            let default_backends = tool.backends();
            assert!(!default_backends.is_empty());

            // Test with env var override
            // SAFETY: This is safe in a test environment
            unsafe {
                env::set_var("MISE_BACKENDS_NODE", "test:backend");
            }
            let overridden_backends = tool.backends();
            assert_eq!(overridden_backends.len(), 1);
            assert_eq!(overridden_backends[0], "test:backend");

            // Clean up
            // SAFETY: This is safe in a test environment
            unsafe {
                env::remove_var("MISE_BACKENDS_NODE");
            }
            ENV_BACKENDS.lock().unwrap().clear();
        }
    }

    #[test]
    fn test_normalize_remote() {
        use super::*;

        // Standard HTTPS URLs should work
        let result = normalize_remote("https://github.com/mise-plugins/vfox-node.git");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "github.com/mise-plugins/vfox-node");

        // file:// URLs should return an error (no host)
        let result = normalize_remote("file:///path/to/repo");
        assert!(result.is_err());

        // Invalid URLs should return an error
        let result = normalize_remote("not-a-url");
        assert!(result.is_err());
    }

    #[test]
    fn test_is_trusted_plugin_rejects_non_normalizable_remote() {
        use super::*;

        assert!(!is_trusted_plugin("cmake", "not-a-url"));
    }

    #[test]
    fn test_is_trusted_plugin_rejects_non_registry_plugin_url() {
        use super::*;

        assert!(!is_trusted_plugin(
            "vfox-attacker-evil",
            "https://github.com/attacker/evil.git"
        ));
    }

    #[test]
    fn test_is_trusted_plugin_accepts_official_registry_plugin_url() {
        use super::*;

        assert!(is_trusted_plugin(
            "cmake",
            "https://github.com/mise-plugins/vfox-cmake.git"
        ));
        assert!(is_trusted_plugin(
            "vfox-jdx-vfox-mongod",
            "https://github.com/jdx/vfox-mongod.git"
        ));
    }

    #[test]
    fn test_is_trusted_plugin_rejects_shorthand_mismatch() {
        use super::*;

        assert!(!is_trusted_plugin(
            "cmake",
            "https://github.com/attacker/vfox-cmake.git"
        ));
    }
}