mise 2026.9.1

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
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use crate::backend::pipx::PIPXBackend;
use crate::cli::args::{BackendArg, ToolArg};
use crate::config::{Config, Settings, config_file};
use crate::errors::split_install_result;
use crate::file::display_path;
use crate::install_before::{
    effective_minimum_release_age_for_tool, resolve_cli_minimum_release_age,
};
use crate::semver::split_version_prefix;
use crate::toolset::is_outdated_version;
use crate::toolset::outdated_info::OutdatedInfo;
use crate::toolset::outdated_info::prefixed_latest_query;
use crate::toolset::{
    ConfigScope, InstallOptions, NeededVersions, ResolveOptions, ToolSource, ToolVersion,
    ToolsetBuilder, get_versions_needed_by_tracked_configs_excluding_locks,
    get_versions_needed_by_tracked_stubs,
};
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::ui::progress_report::SingleReport;
use crate::{config, env, exit, runtime_symlinks, ui};
use console::Term;
use demand::DemandOption;
use eyre::{Context, Result, eyre};
use indexmap::IndexMap;
use jiff::{Span, Timestamp, civil::date};

const MAX_OUT_OF_RANGE_UPDATES: usize = 5;

/// Upgrades outdated tools
///
/// By default, this keeps the range specified in mise.toml. So if you have node@20 set, it will
/// upgrade to the latest 20.x.x version available. See the `--bump` flag to use the latest version
/// and bump the version in mise.toml.
///
/// This will update mise.lock if it is enabled, see https://mise.jdx.dev/configuration/settings.html#lockfile
#[derive(Debug, usage_rs::Args)]
#[usage(visible_alias = "up", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub(crate) struct Upgrade {
    /// Tool(s) to upgrade
    /// e.g.: node@20 python@3.10
    /// If not specified, all current tools will be upgraded
    #[usage(value_name = "INSTALLED_TOOL@VERSION", verbatim_doc_comment)]
    tool: Vec<ToolArg>,

    /// Upgrades to the latest version available, bumping the version in mise.toml
    ///
    /// For example, if you have `node = "20.0.0"` in your mise.toml but 22.1.0 is the latest available,
    /// this will install 22.1.0 and set `node = "22.1.0"` in your config.
    ///
    /// It keeps the same precision as what was there before, so if you instead had `node = "20"`, it
    /// would change your config to `node = "22"`.
    #[usage(long, short = 'b', verbatim_doc_comment)]
    bump: bool,

    /// Display multiselect menu to choose which tools to upgrade
    #[usage(long, short, verbatim_doc_comment, conflicts = "tool")]
    interactive: bool,

    /// Number of jobs to run in parallel
    /// Values below 1 are treated as 1
    /// [default: 4]
    #[usage(long, short, env = "MISE_JOBS", verbatim_doc_comment)]
    jobs: Option<usize>,

    /// Deprecated shorthand for --bump
    #[usage(short = 'l', hide = true)]
    legacy_bump: bool,

    /// Just print what would be done, don't actually do it
    #[usage(long, short = 'n', verbatim_doc_comment)]
    dry_run: bool,

    /// Tool(s) to exclude from upgrading
    /// e.g.: go python
    #[usage(long, short = 'x', value_name = "INSTALLED_TOOL", verbatim_doc_comment)]
    exclude: Vec<ToolArg>,

    /// Like --dry-run but exits with code 1 if there are outdated tools
    ///
    /// This is useful for scripts to check if tools need to be upgraded.
    #[usage(long, verbatim_doc_comment)]
    dry_run_code: bool,

    /// Upgrade all tools, including installed-but-inactive tools not present in the current config
    #[usage(long, verbatim_doc_comment, conflicts = "local")]
    inactive: bool,

    /// Only upgrade tools defined in local config files
    ///
    /// This will only upgrade tools that are defined in project-local mise.toml and
    /// will skip tools defined in the global config (~/.config/mise/config.toml).
    #[usage(long, verbatim_doc_comment)]
    local: bool,

    /// Only upgrade to versions released before this date or older than this duration
    ///
    /// Supports absolute dates like "2024-06-01" and relative durations like "90d" or "1y".
    /// This can be useful for reproducibility or security purposes.
    ///
    /// This only affects fuzzy version matches like "20" or "latest".
    /// Explicitly pinned versions like "22.5.0" are not filtered.
    #[usage(long, alias = "before", verbatim_doc_comment)]
    minimum_release_age: Option<String>,

    /// Placeholder for future monorepo upgrades; `mise upgrade --monorepo` is not implemented yet.
    #[usage(long, verbatim_doc_comment)]
    monorepo: bool,

    /// Do not uninstall the versions that were upgraded away from
    ///
    /// The old version is left in place and is not scheduled for removal. Use this when something
    /// outside mise points at the install directory.
    ///
    /// Set `upgrade.auto_prune = false` to make this the default.
    #[usage(long, verbatim_doc_comment, overrides = "prune")]
    no_prune: bool,

    /// Immediately uninstall the versions that were upgraded away from
    ///
    /// Use this to bypass `upgrade.prune_after`, or to override
    /// `upgrade.auto_prune = false` for a single run.
    #[usage(long, verbatim_doc_comment, overrides = "no_prune")]
    prune: bool,

    /// Connect backend install command stdin/stdout/stderr directly to the terminal
    /// Implies --jobs=1
    #[usage(long, overrides = "jobs")]
    raw: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PruneMode {
    None,
    Immediate,
    Deferred(Duration),
}

impl Upgrade {
    pub(super) fn is_dry_run(&self) -> bool {
        self.dry_run || self.dry_run_code
    }

    /// How versions upgraded away from should be handled. Either flag wins over
    /// the settings, and `overrides_with` makes the later flag win.
    fn prune_mode(&self) -> Result<PruneMode> {
        if self.prune {
            return Ok(PruneMode::Immediate);
        }
        if self.no_prune || !Settings::get().upgrade.auto_prune {
            return Ok(PruneMode::None);
        }
        Ok(PruneMode::Deferred(
            Settings::get().upgrade_prune_after_duration()?,
        ))
    }

    fn scope(&self) -> ConfigScope {
        if self.local {
            ConfigScope::LocalOnly
        } else {
            ConfigScope::All
        }
    }

    pub(crate) async fn run(mut self) -> Result<()> {
        if self.legacy_bump {
            deprecated_at!(
                "2026.8.5",
                "2027.8.5",
                "cli.upgrade.bump-l",
                "`mise upgrade -l` is deprecated. Use `mise upgrade -b` or `mise upgrade --bump` instead. After removal, `-l` will become shorthand for `--local`."
            );
            self.bump = true;
        }
        if self.monorepo {
            unimplemented!("mise upgrade --monorepo is not implemented yet");
        }
        let mut config = Config::get().await?;
        if !self.is_dry_run() {
            crate::lockfile::migrate_monorepo_lockfiles(&config, false)?;
        }
        let ts = ToolsetBuilder::new()
            .with_args(&self.tool)
            .with_scope(self.scope())
            .build(&config)
            .await?;
        // Compute before_date once to ensure consistency when using relative durations
        let before_date = self.get_before_date()?;
        let opts = ResolveOptions {
            use_locked_version: false,
            latest_versions: true,
            resolve_rolling_channels: false,
            prefer_exact_version: false,
            before_date,
            before_date_from_default: false,
            filter_installed_versions_by_release_date: false,
            offline: false,
            refresh_remote_versions: false,
            inactive: self.inactive,
        };
        // Filter tools to check before doing expensive version lookups
        let filter_tools = if !self.interactive && !self.tool.is_empty() {
            Some(self.tool.as_slice())
        } else {
            None
        };
        let exclude_tools = if !self.exclude.is_empty() {
            Some(self.exclude.as_slice())
        } else {
            None
        };
        let mut outdated = ts
            .list_outdated_versions_filtered(&config, self.bump, &opts, filter_tools, exclude_tools)
            .await;
        self.warn_if_newer_versions_hidden_by_minimum_release_age(
            &config,
            &ts,
            &opts,
            filter_tools,
            exclude_tools,
        )
        .await;
        if self.interactive && !outdated.is_empty() {
            outdated = self.get_interactive_tool_set(&outdated)?;
            if outdated.is_empty() {
                return Ok(());
            }
        }
        if outdated.is_empty() {
            let bump_outdated = if self.bump {
                Vec::new()
            } else {
                ts.list_outdated_versions_filtered(
                    &config,
                    true,
                    &opts,
                    filter_tools,
                    exclude_tools,
                )
                .await
                .into_iter()
                .filter(|o| o.bump.is_some())
                .collect::<Vec<_>>()
            };
            if bump_outdated.is_empty() {
                info!("All tools are up to date");
            } else {
                let hidden = bump_outdated.len().saturating_sub(MAX_OUT_OF_RANGE_UPDATES);
                let mut updates = bump_outdated
                    .iter()
                    .take(MAX_OUT_OF_RANGE_UPDATES)
                    .map(|o| {
                        let current = o.current.as_deref().unwrap_or("MISSING");
                        format!("  {} {} → {} ({})", o.name, current, o.latest, o.source)
                    })
                    .collect::<Vec<_>>()
                    .join("\n");
                if hidden > 0 {
                    updates.push_str(&format!("\n  … and {hidden} more"));
                }
                info!(
                    "Newer versions are available but do not match the configured version ranges:\n{updates}\nRun `mise outdated --bump` to view all, or `mise upgrade --bump` to update the configuration and upgrade."
                );
            }
        } else {
            self.upgrade(&mut config, outdated, before_date).await?;
        }

        Ok(())
    }

    async fn upgrade(
        &self,
        config: &mut Arc<Config>,
        outdated: Vec<OutdatedInfo>,
        before_date: Option<Timestamp>,
    ) -> Result<()> {
        let mpr = MultiProgressReport::get();
        let prune_mode = self.prune_mode()?;
        let mut ts = ToolsetBuilder::new()
            .with_args(&self.tool)
            .with_scope(self.scope())
            .build(config)
            .await?;

        let mut parsed_config_files: IndexMap<PathBuf, Arc<dyn config_file::ConfigFile>> =
            IndexMap::new();
        let mut failed_config_files = HashSet::new();
        let mut outdated_with_config_files = vec![];
        for o in outdated.iter() {
            if let (Some(path), Some(_bump)) = (o.source.path(), &o.bump) {
                let cf = if let Some(cf) = parsed_config_files.get(path) {
                    Some(Arc::clone(cf))
                } else if failed_config_files.contains(path) {
                    None
                } else {
                    match config_file::parse(path).await {
                        Ok(cf) => {
                            parsed_config_files.insert(path.to_path_buf(), Arc::clone(&cf));
                            Some(cf)
                        }
                        Err(e) => {
                            warn!("failed to parse {}: {e}", display_path(path));
                            failed_config_files.insert(path.to_path_buf());
                            None
                        }
                    }
                };
                if let Some(cf) = cf {
                    outdated_with_config_files.push((o, cf));
                }
            }
        }
        let config_file_updates = outdated_with_config_files
            .iter()
            .filter_map(|(o, cf)| {
                if let Ok(trs) = cf.to_tool_request_set()
                    && let Some(versions) = trs.tools.get(o.tool_request.ba())
                    && versions.len() != 1
                {
                    warn!("upgrading multiple versions with --bump is not yet supported");
                    return None;
                }
                Some((*o, Arc::clone(cf)))
            })
            .collect::<Vec<_>>();

        // Determine which old versions should be uninstalled after upgrade
        // Skip uninstall when current == latest (channel-based versions that update in-place)
        let to_remove: Vec<_> = if prune_mode == PruneMode::None {
            vec![]
        } else {
            outdated
                .iter()
                .filter_map(|o| {
                    o.current.as_ref().and_then(|current| {
                        // Skip if current and latest version strings are identical
                        // This handles channels like "nightly", "stable", "beta" that update in-place
                        if &o.latest == current {
                            return None;
                        }
                        Some((o, current.clone()))
                    })
                })
                .collect()
        };

        if self.is_dry_run() {
            for (o, current) in &to_remove {
                match prune_mode {
                    PruneMode::Immediate => {
                        miseprintln!("Would uninstall {}@{}", o.name, current);
                    }
                    PruneMode::Deferred(_) => miseprintln!(
                        "Would schedule {}@{} for pruning after {}",
                        o.name,
                        current,
                        Settings::get().upgrade.prune_after
                    ),
                    PruneMode::None => unreachable!(),
                }
            }
            for o in &outdated {
                miseprintln!("Would install {}@{}", o.name, o.latest);
            }
            for (o, cf) in &config_file_updates {
                miseprintln!(
                    "Would bump {}@{} in {}",
                    o.name,
                    o.tool_request.version(),
                    display_path(cf.get_path())
                );
            }
            if !self.bump {
                use crate::toolset::outdated_info::compute_config_bumps;
                let tool_versions: Vec<(String, String)> = self
                    .tool
                    .iter()
                    .filter_map(|t| {
                        t.tvr
                            .as_ref()
                            .map(|tvr| (t.ba.short.clone(), tvr.version()))
                    })
                    .collect();
                let refs: Vec<(&str, &str)> = tool_versions
                    .iter()
                    .map(|(n, v)| (n.as_str(), v.as_str()))
                    .collect();
                let bumps = compute_config_bumps(config, &refs);
                for bump in &bumps {
                    miseprintln!(
                        "Would update {} from {} to {} in {}",
                        bump.tool_name,
                        bump.old_version,
                        bump.new_version,
                        display_path(&bump.config_path)
                    );
                }
            }
            if self.dry_run_code {
                return Err(exit::request(1));
            }
            return Ok(());
        }

        let opts = InstallOptions {
            reason: "upgrade".to_string(),
            force: false,
            jobs: self.jobs,
            raw: self.raw,
            resolve_options: ResolveOptions {
                use_locked_version: false,
                latest_versions: true,
                resolve_rolling_channels: false,
                prefer_exact_version: false,
                before_date,
                before_date_from_default: false,
                filter_installed_versions_by_release_date: false,
                offline: false,
                refresh_remote_versions: false,
                inactive: self.inactive,
            },
            locked: false,
            ..Default::default()
        };

        // Preserve the storage scope of an existing system install while upgrading it.
        // Equal user/system roots classify as local, so they intentionally take the
        // ordinary path and are never scanned or installed twice.
        let (system_outdated, user_outdated): (Vec<_>, Vec<_>) =
            outdated.iter().partition(|outdated| {
                env::install_path_category(&outdated.tool_version.install_path())
                    == env::InstallPathCategory::System
            });
        let user_requests = user_outdated
            .into_iter()
            .map(|outdated| outdated.tool_request.clone())
            .collect::<Vec<_>>();
        let system_requests = system_outdated
            .into_iter()
            .map(|outdated| outdated.tool_request.clone())
            .collect::<Vec<_>>();

        let mut successful_versions = vec![];
        let mut install_errors = vec![];
        if !user_requests.is_empty() {
            let (installed, result) =
                split_install_result(ts.install_all_versions(config, user_requests, &opts).await);
            successful_versions.extend(installed);
            if let Err(err) = result {
                install_errors.push(err);
            }
        }
        if !system_requests.is_empty() {
            let system_opts = InstallOptions {
                install_dir: Some(Settings::get().system_installs_dir().to_path_buf()),
                ..opts.clone()
            };
            let (installed, result) = split_install_result(
                ts.install_all_versions(config, system_requests, &system_opts)
                    .await,
            );
            successful_versions.extend(installed);
            if let Err(err) = result {
                install_errors.push(err);
            }
        }
        let install_error = if install_errors.is_empty() {
            Ok(())
        } else {
            Err(eyre!(
                "{}",
                install_errors
                    .into_iter()
                    .map(|err| format!("{err:#}"))
                    .collect::<Vec<_>>()
                    .join("\n")
            ))
        };

        // Only update config files for tools that were successfully installed
        let mut config_file_updates_by_path = IndexMap::new();
        for (o, cf) in config_file_updates {
            if successful_versions
                .iter()
                .any(|v| v.ba() == o.tool_version.ba())
            {
                config_file_updates_by_path
                    .entry(cf.get_path().to_path_buf())
                    .or_insert_with(|| (cf, vec![]))
                    .1
                    .push(o);
            }
        }
        let mut config_file_errors = vec![];
        for (path, (cf, updates)) in config_file_updates_by_path {
            let mut update_failed = false;
            for o in updates {
                if let Err(e) =
                    cf.replace_versions(o.tool_request.ba(), vec![o.tool_request.clone()])
                {
                    config_file_errors.push(eyre!("Failed to update config for {}: {}", o.name, e));
                    update_failed = true;
                    break;
                }
            }
            if update_failed {
                continue;
            }
            if let Err(e) = cf.save() {
                config_file_errors.push(eyre!(
                    "Failed to save config {}: {}",
                    display_path(&path),
                    e
                ));
            }
        }
        if config_file_errors.len() == 1 {
            return Err(config_file_errors.pop().unwrap());
        }
        if !config_file_errors.is_empty() {
            let errors = config_file_errors
                .into_iter()
                .map(|e| format!("{e:#}"))
                .collect::<Vec<_>>()
                .join("\n");
            return Err(eyre!("Failed to update config files:\n{errors}"));
        }

        // When a specific version is provided via CLI (e.g., `mise upgrade tiny@3.0.1`),
        // update the config file prefix if the new version doesn't match the current specifier.
        // Skip if --bump was used since it already handles config updates.
        if !self.bump {
            use crate::toolset::outdated_info::{apply_config_bumps, compute_config_bumps};
            let tool_versions: Vec<(String, String)> = self
                .tool
                .iter()
                .filter_map(|t| {
                    t.tvr.as_ref().and_then(|tvr| {
                        let name = t.ba.short.clone();
                        // Only process tools that were successfully installed
                        if successful_versions.iter().any(|v| v.ba().short == name) {
                            Some((name, tvr.version()))
                        } else {
                            None
                        }
                    })
                })
                .collect();
            let refs: Vec<(&str, &str)> = tool_versions
                .iter()
                .map(|(n, v)| (n.as_str(), v.as_str()))
                .collect();
            let bumps = compute_config_bumps(config, &refs);
            apply_config_bumps(config, &bumps)?;
        }

        // Reset config after upgrades so tracked configs resolve with new versions
        *config = Config::reset().await?;

        // Rebuild symlinks BEFORE getting versions needed by tracked configs
        // This ensures "latest" symlinks point to the new versions, not the old ones
        let ts = config.get_toolset().await?;
        runtime_symlinks::rebuild_for_toolset(config, ts)
            .await
            .wrap_err("failed to rebuild runtime symlinks")?;

        // Get versions needed by tracked configs AFTER upgrade. Preserve lockfile pins
        // from other projects, but ignore stale pre-upgrade locks for configs we just
        // upgraded so their old versions can still be removed.
        let successful_backends: HashSet<_> = successful_versions
            .iter()
            .flat_map(|v| {
                [
                    v.ba().short.clone(),
                    v.ba().tool_name.clone(),
                    v.ba().full(),
                    v.ba().full_without_opts(),
                ]
            })
            .collect();
        let mut upgraded_config_paths: HashSet<_> = outdated
            .iter()
            .filter(|o| backend_matches(&successful_backends, o.tool_version.ba()))
            .filter_map(|o| o.source.path().map(|path| path.to_path_buf()))
            .collect();
        for tvl in ts.versions.values() {
            if backend_matches(&successful_backends, &tvl.backend)
                && let Some(path) = tvl.source.path()
            {
                upgraded_config_paths.insert(path.to_path_buf());
            }
        }
        for (path, cf) in config.config_files.iter() {
            let Ok(trs) = cf.to_tool_request_set() else {
                continue;
            };
            if trs
                .tools
                .keys()
                .any(|ba| backend_matches(&successful_backends, ba))
            {
                upgraded_config_paths.insert(path.clone());
            }
        }
        // Resolving every tracked config and stub is only worth doing when something is
        // actually up for removal — with --no-prune, or when every upgrade was in-place,
        // the answer would be discarded.
        let versions_needed_by_tracked = if to_remove.is_empty() {
            NeededVersions::new()
        } else {
            let mut needed = get_versions_needed_by_tracked_configs_excluding_locks(
                config,
                true,
                false,
                &upgraded_config_paths,
            )
            .await?;
            needed.extend(get_versions_needed_by_tracked_stubs(config).await?);
            needed
        };

        // Only uninstall old versions of tools that were successfully upgraded
        // and are not needed by any tracked config
        for (o, old_version) in to_remove {
            if successful_versions
                .iter()
                .any(|v| v.ba() == o.tool_version.ba())
            {
                // Build a ToolVersion that targets the actual installed old version
                // (e.g., "1.0.0"), not the resolved latest (e.g., "2.0.0").
                // When minimum_release_age forces a remote lookup for "latest",
                // the toolset resolves to the remote version, and tv_pathname()
                // on the toolset version would give the wrong key.
                let old_tv = ToolVersion::new(o.tool_version.request.clone(), old_version.clone());
                let version_key = (old_tv.ba().short.to_string(), old_tv.tv_pathname());
                if versions_needed_by_tracked.contains_key(&version_key) {
                    debug!(
                        "Keeping {}@{} because it's still needed by a tracked config or tool stub",
                        o.name, old_version
                    );
                    continue;
                }

                match prune_mode {
                    PruneMode::Immediate => {
                        let pr = mpr.add(&format!("uninstall {}@{}", o.name, old_version));
                        if let Err(e) = self
                            .uninstall_old_version(config, &old_tv, pr.as_ref())
                            .await
                        {
                            warn!("Failed to uninstall old version of {}: {}", o.name, e);
                        } else if let Err(err) =
                            crate::tool_purgatory::forget_path(&old_tv.install_path())
                        {
                            warn!("failed to clear tool purgatory entry: {err:#}");
                        }
                    }
                    PruneMode::Deferred(after) => {
                        if let Err(err) = crate::tool_purgatory::schedule(&old_tv, after) {
                            warn!(
                                "failed to schedule {}@{} for pruning: {err:#}",
                                o.name, old_version
                            );
                        } else {
                            info!(
                                "{}@{} will be pruned after {}",
                                o.name,
                                old_version,
                                Settings::get().upgrade.prune_after
                            );
                        }
                    }
                    PruneMode::None => unreachable!(),
                }
            }
        }

        mpr.finish_progress();

        // Fix up sources and requests for lockfile update - CLI args produce
        // ToolSource::Argument but lockfile update only processes ToolSource::MiseToml.
        // Also copy the config's request version (e.g., "latest") so the lockfile update
        // correctly replaces the old entry instead of adding a duplicate.
        for tv in &mut successful_versions {
            if matches!(tv.request.source(), ToolSource::Argument)
                && let Some(tvl) = ts.versions.get(tv.ba())
                && matches!(&tvl.source, ToolSource::MiseToml(_))
            {
                // Use the config's request (preserves version specifier like "latest")
                // but keep the resolved version from the upgrade
                if let Some(config_tv) = tvl.versions.first() {
                    tv.request = config_tv.request.clone();
                } else {
                    tv.request.set_source(tvl.source.clone());
                }
            }
        }

        config::rebuild_shims_and_runtime_symlinks(
            config,
            ts,
            &successful_versions,
            crate::lockfile::LockfileUpdateMode::AllowLocked,
        )
        .await?;

        if successful_versions.iter().any(|v| v.short() == "python") {
            PIPXBackend::reinstall_all(config)
                .await
                .unwrap_or_else(|err| {
                    warn!("failed to reinstall pipx tools: {err}");
                });
        }

        mpr.finish_progress();
        Self::print_summary(&outdated, &successful_versions)?;

        install_error
    }

    async fn uninstall_old_version(
        &self,
        config: &Arc<Config>,
        tv: &ToolVersion,
        pr: &dyn SingleReport,
    ) -> Result<()> {
        tv.backend()?
            .uninstall_version(config, tv, pr, self.dry_run)
            .await
            .wrap_err_with(|| format!("failed to uninstall {tv}"))?;
        pr.finish();
        Ok(())
    }

    fn print_summary(outdated: &[OutdatedInfo], successful_versions: &[ToolVersion]) -> Result<()> {
        let upgraded: Vec<_> = outdated
            .iter()
            .filter(|o| {
                successful_versions
                    .iter()
                    .any(|v| v.ba() == o.tool_version.ba() && v.version == o.latest)
            })
            .collect();
        if !upgraded.is_empty() {
            let s = if upgraded.len() == 1 { "" } else { "s" };
            miseprintln!("\nUpgraded {} tool{}:", upgraded.len(), s);
            for o in &upgraded {
                let from = o.current.as_deref().unwrap_or("(none)");
                miseprintln!("  {} {} → {}", o.name, from, o.latest);
            }
        }
        Ok(())
    }

    fn get_interactive_tool_set(&self, outdated: &Vec<OutdatedInfo>) -> Result<Vec<OutdatedInfo>> {
        ui::ctrlc::show_cursor_after_ctrl_c();
        let theme = crate::ui::theme::get_theme();
        let mut ms = demand::MultiSelect::new("mise upgrade")
            .description("Select tools to upgrade")
            .filterable(true)
            .theme(&theme);
        for out in outdated {
            ms = ms.option(DemandOption::new(out.clone()));
        }
        match ms.run() {
            Ok(selected) => Ok(selected.into_iter().collect()),
            Err(e) => {
                Term::stderr().show_cursor()?;
                Err(eyre!(e))
            }
        }
    }

    /// Get the minimum_release_age cutoff from the CLI --minimum-release-age flag only.
    /// Per-tool and global setting fallbacks are handled in ToolRequest::resolve.
    fn get_before_date(&self) -> Result<Option<Timestamp>> {
        resolve_cli_minimum_release_age(self.minimum_release_age.as_deref())
    }

    async fn warn_if_newer_versions_hidden_by_minimum_release_age(
        &self,
        config: &Arc<Config>,
        ts: &crate::toolset::Toolset,
        opts: &ResolveOptions,
        filter_tools: Option<&[ToolArg]>,
        exclude_tools: Option<&[ToolArg]>,
    ) {
        let list_versions = if opts.inactive {
            match ts.list_all_versions(config).await {
                Ok(v) => v,
                Err(err) => {
                    warn!("Failed to list all versions: {err:#}");
                    vec![]
                }
            }
        } else {
            ts.list_current_versions()
        };
        let mut warned = HashSet::new();
        for (_, tv) in list_versions {
            if let Some(exclude) = exclude_tools
                && exclude.iter().any(|t| t.ba.as_ref() == tv.ba())
            {
                continue;
            }
            if let Some(tools) = filter_tools
                && !tools.iter().any(|t| t.ba.as_ref() == tv.ba())
            {
                continue;
            }
            let warning_key = format!("{}@{}", tv.ba().short, tv.request.version());
            if !warned.insert(warning_key) {
                continue;
            }
            let mut opts_with_effective_before_date = opts.clone();
            if let Err(err) = opts_with_effective_before_date
                .apply_before_date_for_tool(tv.ba(), tv.request.options().minimum_release_age())
            {
                warn!(
                    "Error resolving minimum_release_age for {}: {err:#}",
                    tv.ba()
                );
                continue;
            }
            if opts_with_effective_before_date.before_date.is_none() {
                continue;
            }
            // The raw age value for display: a cutoff already present in
            // `opts` came from the CLI flag; otherwise it resolved from the
            // per-tool option, the global setting, or the built-in default.
            let age = if opts.before_date.is_some() {
                self.minimum_release_age.clone()
            } else {
                effective_minimum_release_age_for_tool(
                    tv.ba(),
                    tv.request.options().minimum_release_age(),
                )
            };
            let eligible_latest = self
                .latest_for_upgrade(config, &tv, &opts_with_effective_before_date)
                .await;
            let eligible_latest = match eligible_latest {
                Ok(latest) => latest,
                Err(err) => {
                    warn!("Error getting latest version for {}: {err:#}", tv.ba());
                    continue;
                }
            };
            let baseline_latest = match self.baseline_latest_for_upgrade(config, &tv, opts).await {
                Ok(latest) => latest,
                Err(err) => {
                    warn!("Error getting latest version for {}: {err:#}", tv.ba());
                    continue;
                }
            };
            match (eligible_latest, baseline_latest) {
                (Some(eligible), Some(baseline)) if is_outdated_version(&eligible, &baseline) => {
                    if current_satisfies_hidden_release(config, &tv, &baseline) {
                        continue;
                    }
                    let suffix = format!("latest eligible release is {eligible}");
                    warn_hidden_release_ignored_by_minimum_release_age(
                        config,
                        &tv,
                        &baseline,
                        age.as_deref(),
                        &suffix,
                    )
                    .await;
                }
                (None, Some(baseline)) => {
                    if current_satisfies_hidden_release(config, &tv, &baseline) {
                        continue;
                    }
                    warn_hidden_release_ignored_by_minimum_release_age(
                        config,
                        &tv,
                        &baseline,
                        age.as_deref(),
                        "no eligible release found",
                    )
                    .await;
                }
                _ => {}
            }
        }
    }

    async fn latest_for_upgrade(
        &self,
        config: &Arc<Config>,
        tv: &ToolVersion,
        opts: &ResolveOptions,
    ) -> Result<Option<String>> {
        let backend = tv.backend()?;
        if self.bump || (opts.inactive && tv.request.source() == &ToolSource::Unknown) {
            let (prefix, prefix_version) = split_version_prefix(&tv.request.version());
            backend
                .latest_version(
                    config,
                    prefixed_latest_query(&prefix, &prefix_version),
                    opts.before_date,
                )
                .await
        } else {
            tv.latest_version_with_opts(config, opts).await.map(Some)
        }
    }

    async fn baseline_latest_for_upgrade(
        &self,
        config: &Arc<Config>,
        tv: &ToolVersion,
        opts: &ResolveOptions,
    ) -> Result<Option<String>> {
        let backend = tv.backend()?;
        let query = if self.bump || (opts.inactive && tv.request.source() == &ToolSource::Unknown) {
            let (prefix, prefix_version) = split_version_prefix(&tv.request.version());
            prefixed_latest_query(&prefix, &prefix_version)
        } else {
            Some(tv.request.version())
        };
        backend.latest_version_unfiltered(config, query).await
    }
}

fn current_satisfies_hidden_release(
    config: &Arc<Config>,
    tv: &ToolVersion,
    hidden_version: &str,
) -> bool {
    OutdatedInfo::new(config, tv.clone(), hidden_version.to_string())
        .ok()
        .and_then(|info| info.current)
        .as_deref()
        .is_some_and(|current| current_version_satisfies_hidden_release(current, hidden_version))
}

fn current_version_satisfies_hidden_release(current: &str, hidden_version: &str) -> bool {
    !is_outdated_version(current, hidden_version)
}

fn backend_matches(backends: &HashSet<String>, ba: &BackendArg) -> bool {
    backends.contains(&ba.short)
        || backends.contains(&ba.tool_name)
        || backends.contains(&ba.full())
        || backends.contains(&ba.full_without_opts())
}

async fn warn_hidden_release_ignored_by_minimum_release_age(
    config: &Arc<Config>,
    tv: &ToolVersion,
    hidden_version: &str,
    age: Option<&str>,
    suffix: &str,
) {
    let (released, age) = hidden_release_details(config, tv, hidden_version, age).await;
    warn!(
        "newer {} release {hidden_version}{released} ignored by minimum_release_age{age}; {suffix}",
        tv.ba().short
    );
}

/// Fragments for the minimum_release_age warning: when the hidden release came
/// out and when it becomes eligible, plus the configured age value. The remote
/// version list is already cached in memory by the resolution that found the
/// hidden release, so this does not trigger another fetch.
async fn hidden_release_details(
    config: &Arc<Config>,
    tv: &ToolVersion,
    hidden_version: &str,
    age: Option<&str>,
) -> (String, String) {
    let created_at = match tv.backend() {
        Ok(backend) => backend
            .list_remote_versions_with_info(config)
            .await
            .ok()
            .and_then(|versions| {
                versions
                    .iter()
                    .find(|v| v.version == hidden_version)
                    .and_then(|v| v.created_at_timestamp())
            }),
        Err(_) => None,
    };
    format_hidden_release_details(created_at, age, jiff::tz::TimeZone::system())
}

fn format_hidden_release_details(
    created_at: Option<Timestamp>,
    age: Option<&str>,
    tz: jiff::tz::TimeZone,
) -> (String, String) {
    let age_fragment = age.map(|age| format!(" ({age})")).unwrap_or_default();
    let released_fragment = match created_at {
        Some(created) => {
            // An age given as an absolute date is a fixed cutoff, so the
            // release never becomes eligible — only show when it will for
            // relative ages.
            let eligible_at = age.and_then(|age| release_eligible_at(created, age));
            let released = created.to_zoned(tz.clone()).strftime("%Y-%m-%d");
            match eligible_at {
                Some(at) => format!(
                    " (released {released}, eligible {})",
                    at.to_zoned(tz).strftime("%Y-%m-%d %H:%M %Z")
                ),
                None => format!(" (released {released})"),
            }
        }
        None => String::new(),
    };
    (released_fragment, age_fragment)
}

fn release_eligible_at(created_at: Timestamp, age: &str) -> Option<Timestamp> {
    const DAY_NANOS: i128 = 86_400 * 1_000_000_000;

    let span = age.parse::<Span>().ok()?;
    let duration = span.to_duration(date(2025, 1, 1)).ok()?;
    if duration.is_negative() {
        return None;
    }
    let mut high = created_at
        .to_zoned(jiff::tz::TimeZone::UTC)
        .checked_add(span)
        .ok()
        .map(|eligible| eligible.timestamp())?;

    for _ in 0..370 {
        if release_is_eligible_at(created_at, high, &span) {
            let mut low_nanos = created_at.as_nanosecond();
            let mut high_nanos = high.as_nanosecond();
            while low_nanos < high_nanos {
                let mid_nanos = low_nanos + (high_nanos - low_nanos) / 2;
                let mid = Timestamp::from_nanosecond(mid_nanos).ok()?;
                if release_is_eligible_at(created_at, mid, &span) {
                    high_nanos = mid_nanos;
                } else {
                    low_nanos = mid_nanos + 1;
                }
            }
            return Timestamp::from_nanosecond(high_nanos).ok();
        }
        high = Timestamp::from_nanosecond(high.as_nanosecond().checked_add(DAY_NANOS)?).ok()?;
    }
    None
}

fn release_is_eligible_at(created_at: Timestamp, now: Timestamp, age: &Span) -> bool {
    now.to_zoned(jiff::tz::TimeZone::UTC)
        .checked_sub(age)
        .is_ok_and(|cutoff| cutoff.timestamp() > created_at)
}

static AFTER_LONG_HELP: &str = color_print::cstr!(
    r#"<bold><underline>Deprecation:</underline></bold>

The `-l` shorthand for `--bump` is deprecated and will be removed in mise 2027.8.5.
After removal, `-l` will become shorthand for `--local`. Use `-b` or `--bump` instead.

<bold><underline>Examples:</underline></bold>

    # Upgrades node to the latest version matching the range in mise.toml
    $ <bold>mise upgrade node</bold>

    # Upgrades node to the latest version and bumps the version in mise.toml
    $ <bold>mise upgrade node --bump</bold>

    # Upgrades all tools to the latest versions
    $ <bold>mise upgrade</bold>

    # Upgrades all tools to the latest versions and bumps the version in mise.toml
    $ <bold>mise upgrade --bump</bold>

    # Just print what would be done, don't actually do it
    $ <bold>mise upgrade --dry-run</bold>

    # Upgrades node and python to the latest versions
    $ <bold>mise upgrade node python</bold>

    # Upgrade all tools except go
    $ <bold>mise upgrade --exclude go</bold>

    # Show a multiselect menu to choose which tools to upgrade
    $ <bold>mise upgrade --interactive</bold>

    # Only upgrade tools defined in local mise.toml, not global ones
    $ <bold>mise upgrade --local</bold>
"#
);

#[cfg(test)]
mod tests {
    use super::{
        current_version_satisfies_hidden_release, format_hidden_release_details,
        release_is_eligible_at,
    };
    use jiff::tz::TimeZone;

    #[test]
    fn test_current_version_satisfies_hidden_release() {
        assert!(!current_version_satisfies_hidden_release("1.0.0", "1.1.0"));
        assert!(current_version_satisfies_hidden_release("1.1.0", "1.1.0"));
        assert!(current_version_satisfies_hidden_release("1.2.0", "1.1.0"));
    }

    #[test]
    fn test_format_hidden_release_details_with_duration_age() {
        let created = "2026-06-26T14:03:00Z".parse().unwrap();
        let (released, age) =
            format_hidden_release_details(Some(created), Some("3d"), TimeZone::UTC);
        assert_eq!(
            released,
            " (released 2026-06-26, eligible 2026-06-29 14:03 UTC)"
        );
        assert_eq!(age, " (3d)");
    }

    #[test]
    fn test_format_hidden_release_details_with_calendar_age() {
        let created = "2023-03-01T14:03:00Z".parse().unwrap();
        let (released, age) =
            format_hidden_release_details(Some(created), Some("1y"), TimeZone::UTC);
        assert_eq!(
            released,
            " (released 2023-03-01, eligible 2024-03-01 14:03 UTC)"
        );
        assert_eq!(age, " (1y)");
    }

    #[test]
    fn test_format_hidden_release_details_with_non_reversible_calendar_age() {
        let created = "2019-01-31T15:30:00Z".parse().unwrap();
        let (released, age) =
            format_hidden_release_details(Some(created), Some("1mo"), TimeZone::UTC);
        assert_eq!(
            released,
            " (released 2019-01-31, eligible 2019-03-01 00:00 UTC)"
        );
        assert_eq!(age, " (1mo)");
    }

    #[test]
    fn test_release_is_eligible_at_uses_strict_cutoff() {
        let created = "2024-01-01T00:00:00Z".parse().unwrap();
        let age = "24h".parse().unwrap();
        let exact_cutoff = "2024-01-02T00:00:00Z".parse().unwrap();
        let after_cutoff = "2024-01-02T00:00:00.000000001Z".parse().unwrap();

        assert!(!release_is_eligible_at(created, exact_cutoff, &age));
        assert!(release_is_eligible_at(created, after_cutoff, &age));
    }

    #[test]
    fn test_format_hidden_release_details_with_absolute_age() {
        // An absolute-date cutoff never becomes eligible, so no eligible time
        let created = "2026-06-26T14:03:00Z".parse().unwrap();
        let (released, age) =
            format_hidden_release_details(Some(created), Some("2026-01-01"), TimeZone::UTC);
        assert_eq!(released, " (released 2026-06-26)");
        assert_eq!(age, " (2026-01-01)");
    }

    #[test]
    fn test_format_hidden_release_details_without_release_date() {
        let (released, age) = format_hidden_release_details(None, Some("24h"), TimeZone::UTC);
        assert_eq!(released, "");
        assert_eq!(age, " (24h)");
    }

    #[test]
    fn test_format_hidden_release_details_without_age() {
        let created = "2026-06-26T14:03:00Z".parse().unwrap();
        let (released, age) = format_hidden_release_details(Some(created), None, TimeZone::UTC);
        assert_eq!(released, " (released 2026-06-26)");
        assert_eq!(age, "");
    }
}