mise 2026.9.3

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
use color_eyre::Result;
use color_eyre::eyre::bail;
use console::style;
#[cfg(windows)]
use indoc::formatdoc;
use self_update::backends::github::Update;
use self_update::{VersionStatus, cargo_crate_version};

use crate::cli::version::{ARCH, OS, SelfUpdateSource};
use crate::config::Settings;
use crate::env;
#[cfg(windows)]
use crate::file::MAX_PATH;
use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::fs;
#[cfg(target_os = "macos")]
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::time::Duration;

const AUTO_UPDATE_REEXEC_ENV: &str = "__MISE_AUTO_UPDATE_REEXEC";
#[derive(Debug, Default, serde::Deserialize)]
struct InstructionsToml {
    message: Option<String>,
    #[serde(flatten)]
    commands: BTreeMap<String, String>,
}

fn read_instructions_file(path: &PathBuf) -> Option<String> {
    let body = fs::read_to_string(path).ok()?;
    let parsed: InstructionsToml = toml::from_str(&body).ok()?;
    if let Some(msg) = parsed.message {
        return Some(msg);
    }
    if let Some((_k, v)) = parsed.commands.into_iter().next() {
        return Some(v);
    }
    None
}

pub(crate) fn upgrade_instructions_text() -> Option<String> {
    if let Some(path) = &*env::MISE_SELF_UPDATE_INSTRUCTIONS
        && let Some(msg) = read_instructions_file(path)
    {
        return Some(msg);
    }
    None
}

/// Shown when mise cannot update itself and the packager shipped no instructions
/// file. Without it, telling the user their mise is out of date is a dead end on
/// every install that disables self-update: a marker file (Homebrew, the AUR
/// `mise-bin` package), a build without the `self_update` feature (Arch), or
/// `MISE_SELF_UPDATE_AVAILABLE=false`. The wording stays neutral about which of
/// those applies — being unable to self-update is not by itself proof that a
/// package manager owns the install.
pub(crate) const SELF_UPDATE_DISABLED_HINT: &str =
    "self-update is disabled for this install, update mise the same way you installed it";

/// How to update mise when `mise self-update` is not available: the packager's
/// instructions when they shipped some, otherwise the generic hint.
pub(crate) fn upgrade_instructions_or_hint() -> String {
    upgrade_instructions_text().unwrap_or_else(|| SELF_UPDATE_DISABLED_HINT.to_string())
}

/// Appends self-update guidance and packaging instructions (if any) to a message.
pub(crate) fn append_self_update_instructions(mut message: String) -> String {
    if SelfUpdate::is_available() {
        message.push_str("\nRun `mise self-update` to update mise");
    }
    if let Some(instructions) = upgrade_instructions_text() {
        message.push('\n');
        message.push_str(&instructions);
    } else if !SelfUpdate::is_available() {
        message.push('\n');
        message.push_str(SELF_UPDATE_DISABLED_HINT);
    }
    message
}

/// Checks for and installs an update before an eligible interactive command.
/// Failures are deliberately non-fatal so the requested command still runs.
pub(crate) async fn maybe_auto_update(
    args: &[String],
    original_cwd: Option<&std::path::Path>,
    command_eligible: bool,
) -> Result<()> {
    let Ok(settings) = Settings::try_get() else {
        return Ok(());
    };
    if !auto_update_eligible(AutoUpdateContext {
        enabled: settings.auto_update,
        offline: settings.offline(),
        prefer_offline: settings.prefer_offline(),
        ci: settings.ci || ci_info::is_ci(),
        attended: console::user_attended_stderr(),
        already_reexecuted: env::var_os(AUTO_UPDATE_REEXEC_ENV).is_some(),
        self_update_available: SelfUpdate::is_available(),
        command_eligible,
    }) {
        return Ok(());
    }

    let lock_path = crate::dirs::CACHE.join("auto-update");
    let update_lock = match crate::lock_file::LockFile::new(&lock_path).try_lock() {
        Ok(Some(lock)) => lock,
        Ok(None) => {
            debug!("skipping auto-update because another mise process is updating");
            return Ok(());
        }
        Err(err) => {
            debug!("automatic mise update could not acquire its lock: {err:#}");
            return Ok(());
        }
    };
    let last_check_path = crate::dirs::CACHE.join("auto-update-last-check");
    let check_duration = match settings.auto_update_check_duration() {
        Ok(duration) => duration,
        Err(err) => {
            debug!("automatic mise update has an invalid check duration: {err:#}");
            return Ok(());
        }
    };
    if !auto_update_check_due(&last_check_path, check_duration) {
        return Ok(());
    }
    if let Err(err) = crate::file::write(&last_check_path, "") {
        debug!("automatic mise update could not record its check: {err:#}");
        return Ok(());
    }
    // The marker above is the auto-update throttle. Bypass the separate shared
    // version cache so a shorter-lived `mise version` lookup cannot make this
    // due check accept stale data and advance the marker for another interval.
    let Some(version) = crate::cli::version::check_for_new_version(Duration::ZERO).await else {
        return Ok(());
    };

    let update = SelfUpdate {
        version: Some(version),
        force: false,
        yes: true,
        no_plugins: true,
    };
    if let Err(err) = update.run().await {
        debug!("automatic mise update failed: {err:#}");
        return Ok(());
    }
    drop(update_lock);
    reexec(args, original_cwd)
}

/// Returns whether the automatic-update attempt marker has expired.
fn auto_update_check_due(path: &std::path::Path, duration: Duration) -> bool {
    crate::file::modified_duration(path).map_or(true, |age| age >= duration)
}

/// Runtime conditions that gate automatic updates.
#[derive(Clone, Copy)]
struct AutoUpdateContext {
    enabled: bool,
    offline: bool,
    prefer_offline: bool,
    ci: bool,
    attended: bool,
    already_reexecuted: bool,
    self_update_available: bool,
    command_eligible: bool,
}

/// Applies the automatic-update safety policy without side effects.
fn auto_update_eligible(context: AutoUpdateContext) -> bool {
    context.enabled
        && !context.offline
        && !context.prefer_offline
        && !context.ci
        && context.attended
        && !context.already_reexecuted
        && context.self_update_available
        && context.command_eligible
}

/// Builds the replacement process with the original arguments, directory, and
/// a recursion guard shared by every platform-specific re-exec path.
fn build_reexec_command<I, S>(args: I, original_cwd: Option<&std::path::Path>) -> Command
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let mut command = Command::new(&*env::MISE_BIN);
    command.args(args).env(AUTO_UPDATE_REEXEC_ENV, "1");
    if let Some(cwd) = original_cwd {
        command.current_dir(cwd);
    }
    command
}

#[cfg(unix)]
fn reexec(_args: &[String], original_cwd: Option<&std::path::Path>) -> Result<()> {
    use std::os::unix::process::CommandExt;

    let mut command = build_reexec_command(std::env::args_os().skip(1), original_cwd);
    let err = command.exec();
    warn!("mise was updated but could not re-execute the command: {err}");
    Ok(())
}

#[cfg(windows)]
fn reexec(_args: &[String], original_cwd: Option<&std::path::Path>) -> Result<()> {
    let mut command = build_reexec_command(std::env::args_os().skip(1), original_cwd);
    let status = command.status()?;
    Err(crate::request_exit(status.code().unwrap_or(1)))
}

#[cfg(not(any(unix, windows)))]
fn reexec(args: &[String], original_cwd: Option<&std::path::Path>) -> Result<()> {
    let mut command = build_reexec_command(&args[1..], original_cwd);
    let status = command.status()?;
    Err(crate::request_exit(status.code().unwrap_or(1)))
}

/// Update mise itself
///
/// Uses the GitHub Releases API to find the latest release and binary.
/// By default, this will also update any installed plugins.
/// Uses mise's GitHub token resolution chain for authenticated requests.
///
/// Packagers can disable this command so that mise is updated through the
/// package manager instead. See
/// https://mise.jdx.dev/contributing.html#packaging-and-self-update-instructions
#[derive(Debug, Default, usage_rs::Args)]
#[usage(verbatim_doc_comment)]
pub(crate) struct SelfUpdate {
    /// Update to a specific version
    version: Option<String>,

    /// Update even if already up to date
    #[usage(long, short)]
    force: bool,

    /// Skip confirmation prompt
    #[usage(long, short)]
    yes: bool,

    /// Disable auto-updating plugins
    #[usage(long)]
    no_plugins: bool,
}

/// Whether replacing the running binary would destroy the install with `TEMP` set to `tmp`.
///
/// `self-replace` renames the running mise.exe out of its install directory *first*, then
/// launches a copy of it from `TEMP` to finish the swap. When that copy's path exceeds
/// `MAX_PATH` the launch fails — `CreateProcess` has no `\\?\` escape hatch the way the file
/// APIs do — and nothing puts mise back: the install directory is left empty and the binary is
/// stranded in `TEMP` under a generated name. The crate declares executable paths that long out
/// of scope (self-replace-1.5.0/src/windows.rs, in `self_delete_on_init`), so the only place to
/// stop this is before it starts.
#[cfg(windows)]
fn temp_dir_breaks_self_replace(tmp: &std::path::Path, exe_stem: Option<&str>) -> bool {
    helper_path_len(tmp, exe_stem) >= MAX_PATH
}

/// Length in UTF-16 code units of the helper's full path. MAX_PATH counts UTF-16 code units
/// and includes the terminating NUL, so a total of exactly MAX_PATH is already one too many.
/// `OsStr::len()` would be the wrong unit: it counts WTF-8 bytes.
#[cfg(windows)]
fn helper_path_len(tmp: &std::path::Path, exe_stem: Option<&str>) -> usize {
    use std::os::windows::ffi::OsStrExt;

    // `Path::join` only inserts a separator when there is not one already, and Windows'
    // `temp_dir()` always comes back with a trailing backslash.
    let separator = usize::from(!ends_with_separator(tmp));
    tmp.as_os_str().encode_wide().count() + separator + helper_name_len(exe_stem)
}

/// Length in UTF-16 code units of the name `self-replace` generates for the helper:
/// `.` + the running executable's file stem + `.` + 32 random characters +
/// `.__selfdelete__.exe`, with the stem included only when it is valid UTF-8. Mirrors
/// `get_temp_executable_name` in self-replace-1.5.0/src/windows.rs. This is 57 for
/// `mise.exe` and longer whenever the binary has been renamed, so it cannot be a constant.
#[cfg(windows)]
fn helper_name_len(exe_stem: Option<&str>) -> usize {
    let suffix_len = env::SELF_REPLACE_SUFFIXES[0].len();

    // The stem is followed by a second `.`, and dropped entirely when it is not UTF-8.
    let stem = exe_stem.map_or(0, |s| s.encode_utf16().count() + 1);
    1 + stem + env::SELF_REPLACE_RANDOM_LEN + suffix_len
}

/// Delete the copies of mise that earlier updates left in `TEMP`.
///
/// `self-replace` moves the running binary aside and spawns a copy of it to delete the leftovers.
/// When that copy does not delete itself the deletion never happens and a **full copy of mise.exe**
/// stays in `TEMP` for good. Nothing else collects them: they are not under the cache, so
/// `mise cache clear` does not reach them, and their names mean nothing to anyone else.
///
/// A long `TEMP` is not the only trigger, though it was the one this was first written for
/// (measured at 199 and 201 characters, just under the length #12062 refuses outright). Measured
/// again on a `TEMP` of 31: a successful update leaves **both** copies — the `__relocated__`
/// original and the `__selfdelete__` helper — and neither is locked afterwards, so any later mise
/// can remove them. That is what this exists to do.
///
/// Best effort by design. A copy another mise is still using cannot be deleted on Windows, which is
/// the outcome we want, so failures are ignored rather than warned about.
#[cfg(windows)]
fn sweep_helper_orphans() {
    for (path, _) in helper_orphans() {
        match std::fs::remove_file(&path) {
            Ok(()) => debug!("removed stale self-update copy: {}", path.display()),
            Err(e) => trace!("could not remove {}: {e}", path.display()),
        }
    }
}

/// The copies an earlier update left in `TEMP`, with their sizes.
///
/// Shared with `mise doctor` so that "what counts as a leftover" has one definition rather than two
/// that can drift: the predicate stays [`env::is_self_replace_helper`], and this is only the walk.
/// A file whose size cannot be read is still reported, at 0 — it exists, which is the part that
/// matters, and the size is decoration.
#[cfg(windows)]
pub(crate) fn helper_orphans() -> Vec<(std::path::PathBuf, u64)> {
    let Some(stem) = current_exe_stem() else {
        return Vec::new();
    };
    helper_orphans_in(&std::env::temp_dir(), &stem)
}

#[cfg(windows)]
fn helper_orphans_in(dir: &std::path::Path, stem: &str) -> Vec<(std::path::PathBuf, u64)> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    entries
        .flatten()
        .filter(|entry| {
            entry
                .file_name()
                .to_str()
                .is_some_and(|name| env::is_self_replace_helper(name, stem))
        })
        .map(|entry| {
            let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
            (entry.path(), size)
        })
        .collect()
}

#[cfg(windows)]
fn ends_with_separator(path: &std::path::Path) -> bool {
    use std::os::windows::ffi::OsStrExt;

    path.as_os_str()
        .encode_wide()
        .last()
        .is_some_and(|c| c == u16::from(b'\\') || c == u16::from(b'/'))
}

/// The file stem `self-replace` would put in the helper's name: the running executable's.
#[cfg(windows)]
fn current_exe_stem() -> Option<String> {
    let exe = std::env::current_exe().ok()?;
    exe.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
}

/// Refresh the installed plugins, best effort.
///
/// This runs after the binary has already been replaced, so a failure here says nothing about
/// whether the update worked. Propagating it made a successful update print `Updated mise to X`
/// and then exit non-zero, which reads as "the update failed" — on Windows that is a bad enough
/// misreading to send someone looking for a mise that is not broken. Warned about instead, the way
/// the two housekeeping steps above it already are.
///
/// The message names the step because the error often cannot. `duct` attaches the command only
/// when the child exits non-zero; a child that never starts comes back as the bare OS error, so an
/// `ACCESS_DENIED` from spawning the freshly written binary arrives as nothing but
/// "Access is denied. (os error 5)".
///
/// Takes the binary to run rather than reading [`env::MISE_BIN`] itself, so a test can drive the
/// failure without a real update.
fn update_plugins(bin: &std::path::Path) {
    if let Err(err) = cmd!(bin, "plugins", "update").run() {
        warn!("Failed to update plugins: {err}");
    }
}

impl SelfUpdate {
    pub(crate) async fn run(self) -> Result<()> {
        if !Self::is_available() && !self.force {
            if let Some(instructions) = upgrade_instructions_text() {
                warn!("{}", instructions);
            }
            bail!("mise is installed via a package manager, cannot update");
        }
        // Before the update, not after: this run is about to create a copy of its own, and that one
        // is in use rather than stale. Before the length check too, and that ordering is the whole
        // point: a `TEMP` long enough to refuse the update is the case the leftovers come from, so
        // running the sweep afterwards means the only machines that accumulate them are the only
        // machines that never reach the code that collects them.
        #[cfg(windows)]
        sweep_helper_orphans();
        #[cfg(windows)]
        Self::ensure_temp_dir_can_replace_binary()?;
        let status = self.do_update()?;

        if status.is_updated() {
            let version = status.version().to_string();
            let styled_version = style(&version).bright().yellow();
            miseprintln!("Updated mise to {styled_version}");
            // On Windows, "exe"/"hardlink" shims are copies of mise-shim.exe and
            // go stale after an update. Refresh mise-shim.exe, and ONLY if that
            // succeeds rebuild the shim copies from it. Reshimming on failure
            // would re-copy the OLD mise-shim.exe yet still stamp the new version
            // in the `.version` marker, masking the staleness from future
            // (non-forced) reshims. Best-effort. See discussion #10022.
            #[cfg(windows)]
            match Self::update_mise_shim(&SelfUpdateSource::current(), &version).await {
                Ok(()) => {
                    if let Err(e) = Self::reshim_after_update().await {
                        warn!("Failed to reshim after self-update: {e}");
                    }
                }
                Err(e) => warn!("Failed to update mise-shim.exe: {e}"),
            }
        } else {
            miseprintln!("mise is already up to date");
        }
        crate::cli::version::show_auto_update_hint();
        if !self.no_plugins {
            update_plugins(&env::MISE_BIN);
        }

        Ok(())
    }

    /// Stop before anything is downloaded or moved when `TEMP` is long enough that
    /// replacing the binary would leave no mise installed at all.
    #[cfg(windows)]
    fn ensure_temp_dir_can_replace_binary() -> Result<()> {
        use std::os::windows::ffi::OsStrExt;

        let tmp = std::env::temp_dir();
        let stem = current_exe_stem();
        if !temp_dir_breaks_self_replace(&tmp, stem.as_deref()) {
            return Ok(());
        }
        let msg = formatdoc! {r#"
            TEMP is too long to replace mise.exe safely ({len} UTF-16 code units)

              TEMP = {tmp}

            Updating moves the running mise.exe aside and then launches a helper from TEMP to
            put the new one in place. That helper's path would be {helper} UTF-16 code units,
            and Windows cannot launch an executable whose path reaches {max}. The move happens
            first, so going ahead would leave no mise installed at all.

            Point TEMP and TMP at a shorter directory and run mise self-update again:

              $env:TEMP = 'C:\Temp'; $env:TMP = 'C:\Temp'"#,
            len = tmp.as_os_str().encode_wide().count(),
            tmp = tmp.display(),
            helper = helper_path_len(&tmp, stem.as_deref()),
            max = MAX_PATH,
        };
        bail!("{msg}");
    }

    fn do_update(&self) -> Result<VersionStatus> {
        // Use block_in_place to allow self_update's blocking HTTP calls
        // to work within mise's async runtime
        tokio::task::block_in_place(|| self.do_update_blocking())
    }

    fn do_update_blocking(&self) -> Result<VersionStatus> {
        let settings = Settings::try_get();
        let source = settings
            .as_ref()
            .map(|settings| SelfUpdateSource::from_settings(settings))
            .unwrap_or_default();
        source.validate()?;
        let (repo_owner, repo_name) = source.repository_parts()?;
        let mut update = Update::configure();
        update.reqwest_client(Self::http_client()?);
        if let Some(token) = crate::github::resolve_token_for_api_url(&source.api_url) {
            update.auth_token(&token);
        }
        #[cfg(windows)]
        let bin_path_in_archive = "mise/bin/mise.exe";
        #[cfg(not(windows))]
        let bin_path_in_archive = "mise/bin/mise";
        update
            .repo_owner(repo_owner)
            .repo_name(repo_name)
            .api_base_url(&source.api_url)
            .bin_name("mise")
            .current_version(cargo_crate_version!())
            .bin_path_in_archive(bin_path_in_archive);

        let v = self
            .version
            .clone()
            .map_or_else(
                || -> Result<String> {
                    Ok(update
                        .build()?
                        .get_latest_release()?
                        .latest()
                        .ok_or_else(|| {
                            eyre::eyre!("no GitHub releases found for {}", source.repository)
                        })?
                        .version()
                        .to_string())
                },
                Ok,
            )
            .map(|v| format!("v{v}"))?;

        // Check if already up to date (unless --force is specified)
        let current_version = format!("v{}", cargo_crate_version!());
        if !self.force && v == current_version {
            return Ok(VersionStatus::UpToDate(current_version));
        }

        let target = format!("{}-{}", *OS, *ARCH);
        #[cfg(target_env = "musl")]
        let target = format!("{target}-musl");
        // Always set release_tag to ensure we download the correct release
        // (fixes semver mismatch across year boundaries, e.g. 2025.x -> 2026.x)
        update.release_tag(&v);
        #[cfg(windows)]
        let target = format!("mise-{v}-{target}.zip");
        #[cfg(not(windows))]
        let target = format!("mise-{v}-{target}.tar.gz");
        let status = update
            .verifying_keys([*include_bytes!("../../zipsign.pub")])
            .show_download_progress(true)
            .target(&target)
            .no_confirm(settings.is_ok_and(|s| s.yes) || self.yes)
            .build()?
            .update()?;

        // Verify macOS binary signature after update
        #[cfg(target_os = "macos")]
        if status.is_updated() {
            Self::verify_macos_signature(&env::MISE_BIN)?;
        }

        Ok(status)
    }

    fn http_client() -> Result<self_update::reqwest::blocking::Client> {
        Ok(self_update::reqwest::blocking::Client::builder()
            .https_only(true)
            .redirect(Self::redirect_policy())
            .build()?)
    }

    fn redirect_policy() -> reqwest::redirect::Policy {
        use reqwest::redirect::Policy;

        Policy::custom(|attempt| {
            if crate::http::is_https_downgrade(attempt.previous(), attempt.url()) {
                attempt.error(std::io::Error::other(
                    "refusing to redirect a self-update request from HTTPS to an insecure URL",
                ))
            } else {
                Policy::default().redirect(attempt)
            }
        })
    }

    // Rebuild the Windows shim copies in-process instead of shelling out to
    // `mise reshim --force`. Mirrors `cli::reshim::Reshim::run`.
    #[cfg(windows)]
    async fn reshim_after_update() -> Result<()> {
        use crate::config::Config;
        use crate::toolset::ToolsetBuilder;

        let config = Config::get().await?;
        let ts = ToolsetBuilder::new().build(&config).await?;
        crate::shims::reshim_for(&config, &ts, true, crate::shims::ShimScope::User).await?;
        let user_shims = crate::dirs::shims();
        let system_shims = crate::dirs::system_shims();
        if system_shims.is_dir() && !crate::file::storage_paths_eq(&user_shims, &system_shims) {
            crate::shims::reshim_for(&config, &ts, true, crate::shims::ShimScope::System).await?;
        }
        Ok(())
    }

    #[cfg(windows)]
    async fn update_mise_shim(source: &SelfUpdateSource, version: &str) -> Result<()> {
        use std::io::Read;

        source.validate()?;
        let version = version.strip_prefix('v').unwrap_or(version);
        let archive_name = format!("mise-v{version}-{}-{}.zip", *OS, *ARCH);
        let release = crate::github::get_release_for_url_with_versions_host(
            &source.api_url,
            &source.repository,
            &format!("v{version}"),
            false,
        )
        .await?;
        let asset = release
            .assets
            .iter()
            .find(|asset| asset.name == archive_name)
            .ok_or_else(|| {
                color_eyre::eyre::eyre!(
                    "release v{version} for {} has no asset named {archive_name}",
                    source.repository
                )
            })?;
        // Use the API asset endpoint directly so every redirect is governed by
        // the downgrade-rejecting client below. This also supports private releases.
        let url = asset.url.clone();
        debug!("Downloading mise-shim.exe from {url}");

        let temp_dir = tempfile::tempdir()?;
        // Use the real archive name so zipsign context matches the release signature
        let zip_path = temp_dir.path().join(&archive_name);
        let headers = crate::github::get_headers(&url)?;
        let settings = Settings::get();
        let request_timeout = settings.http_timeout();
        let archive = reqwest::Client::builder()
            .user_agent(format!("mise/{}", cargo_crate_version!()))
            .https_only(true)
            .redirect(Self::redirect_policy())
            .connect_timeout(request_timeout)
            .read_timeout(request_timeout)
            .timeout(settings.http_download_timeout())
            .build()?
            .get(&url)
            .headers(headers)
            .send()
            .await?
            .error_for_status()?
            .bytes()
            .await?;
        fs::write(&zip_path, archive)?;

        // Verify the archive signature using the same key as the main update
        Self::verify_zip_signature(&zip_path)?;

        let file = fs::File::open(&zip_path)?;
        let mut archive = zip::ZipArchive::new(file)?;

        let mut shim_entry = match archive.by_name("mise/bin/mise-shim.exe") {
            Ok(entry) => entry,
            Err(_) => {
                warn!("mise-shim.exe not found in release archive, skipping");
                return Ok(());
            }
        };

        let dest = env::MISE_BIN
            .parent()
            .expect("MISE_BIN should have a parent directory")
            .join("mise-shim.exe");

        // Write to a temp file first, then rename for atomic replacement
        let mut buf = Vec::new();
        shim_entry.read_to_end(&mut buf)?;
        let temp_shim = temp_dir.path().join("mise-shim.exe");
        fs::write(&temp_shim, &buf)?;
        if fs::rename(&temp_shim, &dest).is_err() {
            // Fallback for cross-filesystem moves
            fs::copy(&temp_shim, &dest)?;
        }

        debug!("Updated mise-shim.exe at {}", dest.display());
        Ok(())
    }

    #[cfg(windows)]
    fn verify_zip_signature(path: &std::path::Path) -> Result<()> {
        let context = path
            .file_name()
            .and_then(|s| s.to_str())
            .map(|s| s.as_bytes())
            .ok_or_else(|| color_eyre::eyre::eyre!("non-UTF8 archive path"))?;

        let keys = zipsign_api::verify::collect_keys(
            [*include_bytes!("../../zipsign.pub")].into_iter().map(Ok),
        )
        .map_err(|e| color_eyre::eyre::eyre!("failed to load verification keys: {e}"))?;

        let mut file = fs::File::open(path)?;
        zipsign_api::verify::verify_zip(&mut file, &keys, Some(context))
            .map_err(|e| color_eyre::eyre::eyre!("zip signature verification failed: {e}"))?;

        debug!("Verified zip signature for {}", path.display());
        Ok(())
    }

    pub(crate) fn is_available() -> bool {
        if let Some(b) = *env::MISE_SELF_UPDATE_AVAILABLE {
            return b;
        }
        let has_disable = env::MISE_SELF_UPDATE_DISABLED_PATH.is_some();
        let has_instructions = env::MISE_SELF_UPDATE_INSTRUCTIONS.is_some();
        !(has_disable || has_instructions)
    }

    #[cfg(target_os = "macos")]
    fn verify_macos_signature(binary_path: &Path) -> Result<()> {
        use std::process::Command;

        debug!(
            "Verifying macOS code signature for: {}",
            binary_path.display()
        );

        // Check if codesign is available
        let codesign_check = Command::new("which").arg("codesign").output();

        if codesign_check.is_err() || !codesign_check.unwrap().status.success() {
            warn!("codesign command not found in PATH, skipping binary signature verification");
            warn!("This is unusual on macOS - consider verifying your system installation");
            return Ok(());
        }

        // Verify signature and identifier in one step using --test-requirement
        let output = Command::new("codesign")
            .args([
                "--verify",
                "--deep",
                "--strict",
                "-R=identifier \"dev.jdx.mise\"",
            ])
            .arg(binary_path)
            .output()?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            bail!(
                "macOS binary signature verification failed (invalid signature or incorrect identifier): {}",
                stderr.trim()
            );
        }

        debug!("macOS binary signature verified successfully");
        Ok(())
    }
}

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

    fn eligible_context() -> AutoUpdateContext {
        AutoUpdateContext {
            enabled: true,
            offline: false,
            prefer_offline: false,
            ci: false,
            attended: true,
            already_reexecuted: false,
            self_update_available: true,
            command_eligible: true,
        }
    }

    #[test]
    fn eligible_interactive_command_updates() {
        assert!(auto_update_eligible(eligible_context()));
    }

    #[test]
    fn safety_conditions_disable_auto_update() {
        let context = eligible_context();
        for ineligible in [
            AutoUpdateContext {
                enabled: false,
                ..context
            },
            AutoUpdateContext {
                offline: true,
                ..context
            },
            AutoUpdateContext {
                prefer_offline: true,
                ..context
            },
            AutoUpdateContext {
                ci: true,
                ..context
            },
            AutoUpdateContext {
                attended: false,
                ..context
            },
            AutoUpdateContext {
                already_reexecuted: true,
                ..context
            },
            AutoUpdateContext {
                self_update_available: false,
                ..context
            },
        ] {
            assert!(!auto_update_eligible(ineligible));
        }
    }

    #[test]
    fn ineligible_commands_do_not_update() {
        assert!(!auto_update_eligible(AutoUpdateContext {
            command_eligible: false,
            ..eligible_context()
        }));
    }

    #[test]
    fn reexec_preserves_arguments_directory_and_guard() {
        use std::ffi::OsString;

        let cwd = std::path::Path::new("a directory");
        let args = [OsString::from("install"), OsString::from("node@22 beta")];
        let command = build_reexec_command(&args, Some(cwd));

        assert_eq!(command.get_args().collect::<Vec<_>>(), args);
        assert_eq!(command.get_current_dir(), Some(cwd));
        assert!(command.get_envs().any(|(key, value)| {
            key == AUTO_UPDATE_REEXEC_ENV && value == Some(OsStr::new("1"))
        }));
    }

    #[test]
    fn automatic_update_attempts_are_throttled() {
        let temp = tempfile::tempdir().unwrap();
        let marker = temp.path().join("last-check");
        assert!(auto_update_check_due(&marker, Duration::from_secs(60)));
        std::fs::write(&marker, "").unwrap();
        assert!(!auto_update_check_due(&marker, Duration::from_secs(60)));
        assert!(auto_update_check_due(&marker, Duration::ZERO));
    }
}

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

    /// By the time plugins are refreshed the new binary is already in place, so a failure there
    /// must not turn a successful update into a failed command. Driving a real spawn failure
    /// rather than a stub: a binary that cannot be started is what Windows produces while an AV
    /// scanner still holds the file mise just wrote, and what discussion #8827 produces over SSH.
    #[test]
    fn a_plugins_update_that_cannot_run_is_not_fatal() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("mise-that-is-not-there");

        // Control: without this the test would pass just as well on a spawn that quietly
        // succeeded, and prove nothing. `run()` has to actually fail for the line below to mean
        // anything.
        assert!(cmd!(&missing, "plugins", "update").run().is_err());

        // And the step swallows it. There is no error here to propagate — which is exactly what
        // the `?` this replaces used to do.
        update_plugins(&missing);
    }
}

#[cfg(all(test, windows))]
mod tests {
    use super::*;
    use std::path::{Path, PathBuf};

    /// What `env::temp_dir()` hands back on Windows: a directory path of exactly `len`
    /// UTF-16 code units, trailing backslash included.
    fn temp_dir_of_len(len: usize) -> PathBuf {
        let mut s = String::from("C:\\");
        while s.len() < len - 1 {
            s.push('t');
        }
        s.push('\\');
        assert_eq!(s.len(), len, "test helper built the wrong length");
        PathBuf::from(s)
    }

    fn breaks(len: usize) -> bool {
        temp_dir_breaks_self_replace(&temp_dir_of_len(len), Some("mise"))
    }

    #[test]
    fn an_ordinary_temp_dir_is_left_alone() {
        let tmp = Path::new("C:\\Users\\u\\AppData\\Local\\Temp\\");
        assert!(!temp_dir_breaks_self_replace(tmp, Some("mise")));
    }

    #[test]
    fn the_boundary_matches_what_windows_actually_does() {
        // Measured on Windows 11 26200 with LongPathsEnabled=0, running self-update against
        // a copy of mise.exe: with TEMP at 201 it succeeds and the binary survives, at 202 it
        // fails with `os error 3` and the install directory is left empty. `temp_dir()`
        // appends a backslash to both, which is why these are 202 and 203 here.
        assert!(!breaks(202));
        assert!(breaks(203));
    }

    #[test]
    fn temp_dirs_measured_as_destructive_are_rejected() {
        assert!(breaks(206)); // TEMP=205
        assert!(breaks(244)); // TEMP=243
    }

    #[test]
    fn a_long_temp_dir_that_still_works_is_not_rejected() {
        // Control: length alone is not the trigger. TEMP=190 was measured as succeeding, so a
        // guard that fired here would block updates that work.
        assert!(!breaks(191));
    }

    #[test]
    fn a_trailing_separator_is_not_counted_twice() {
        // `env::temp_dir()` always ends in a separator on Windows and `Path::join` does not
        // add a second one, so both spellings of the same directory have to agree.
        assert_eq!(
            helper_path_len(Path::new("C:\\Temp\\"), Some("mise")),
            helper_path_len(Path::new("C:\\Temp"), Some("mise"))
        );
    }

    #[test]
    fn the_helper_name_follows_the_running_executable() {
        // `.` + stem + `.` + 32 random characters + `.__selfdelete__.exe`
        assert_eq!(helper_name_len(Some("mise")), 57);
        assert_eq!(helper_name_len(Some("mise-dev")), 61);
        // self-replace leaves the stem out when it is not valid UTF-8
        assert_eq!(helper_name_len(None), 52);
    }

    #[test]
    fn a_renamed_binary_lowers_the_ceiling() {
        // A TEMP that is safe for `mise.exe` is not safe once the binary has been renamed to
        // something longer, so the guard cannot assume the stem.
        let tmp = temp_dir_of_len(202);
        assert!(!temp_dir_breaks_self_replace(&tmp, Some("mise")));
        assert!(temp_dir_breaks_self_replace(&tmp, Some("mise-dev")));
    }

    /// The walk, not the predicate — `env::is_self_replace_helper` has its own tests. What matters
    /// here is that `doctor` and the sweep see the same set, and that a directory full of unrelated
    /// files does not turn into a warning about mise.
    #[test]
    fn only_the_generated_copies_are_collected() {
        let dir = tempfile::tempdir().unwrap();
        let rand = "a".repeat(env::SELF_REPLACE_RANDOM_LEN);
        let collected = [
            format!(".mise.{rand}.__selfdelete__.exe"),
            format!(".mise.{rand}.__relocated__.exe"),
        ];
        let ignored = [
            "mise.exe".to_string(),
            // a different binary's leftovers are not ours to delete
            format!(".other.{rand}.__selfdelete__.exe"),
            // near-misses on the random segment: too short, and not lowercase
            format!(".mise.{}.__selfdelete__.exe", "a".repeat(31)),
            format!(".mise.{}A.__selfdelete__.exe", "a".repeat(31)),
            "setup-x64.exe".to_string(),
        ];
        for name in collected.iter().chain(ignored.iter()) {
            std::fs::write(dir.path().join(name), b"xyz").unwrap();
        }

        let found = helper_orphans_in(dir.path(), "mise");
        let mut names = found
            .iter()
            .map(|(p, _)| p.file_name().unwrap().to_str().unwrap().to_string())
            .collect::<Vec<_>>();
        names.sort();
        let mut want = collected.to_vec();
        want.sort();
        assert_eq!(names, want);
        // the size is what `doctor` adds up, so it has to come from the files rather than a count
        assert_eq!(found.iter().map(|(_, size)| size).sum::<u64>(), 6);
    }

    #[test]
    fn a_missing_directory_is_not_an_error() {
        // `TEMP` pointing at something unreadable must not take `self-update` or `doctor` down.
        assert!(helper_orphans_in(Path::new("C:\\nope\\nope\\nope"), "mise").is_empty());
    }

    #[test]
    fn the_length_is_counted_in_utf16_code_units() {
        // Control against the `OsStr::len()` trap: this path is 202 UTF-16 code units, the
        // longest that works, but 598 WTF-8 bytes. Counting bytes would reject it.
        let mut s = String::from("C:\\");
        while s.chars().count() < 201 {
            s.push('');
        }
        s.push('\\');
        let tmp = PathBuf::from(s);
        assert_eq!(tmp.as_os_str().len(), 598);
        assert!(!temp_dir_breaks_self_replace(&tmp, Some("mise")));
    }
}