rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
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
#[cfg(not(windows))]
use std::process::Stdio;
use std::{
    path::{Path, PathBuf},
    sync::OnceLock,
    time::Duration,
};

use crate::app::daemon_install::{self, Installed};
use crate::installation::{
    self, cargo_install_root_contains_crate, cargo_update_root_for_exe, InstallHint,
    ManagedInstallation, Probe, ScoopInstallScope, ThisProcess,
};
use anyhow::Context;
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, USER_AGENT};
#[cfg(not(windows))]
use rho_protocol::ClientEnvironment;
use serde::{Deserialize, Serialize};
#[cfg(not(windows))]
use tokio::process::Command;

#[path = "update_check.rs"]
mod check;
#[path = "update_in_place.rs"]
mod in_place;
#[path = "update_unattended.rs"]
mod unattended;
pub(crate) use check::{run_check, CheckFormat};
#[cfg(windows)]
pub(crate) use in_place::remove_update_leftovers;
pub(crate) use unattended::{update_unattended, Lands, Unattended};

const RELEASES_URL: &str = "https://api.github.com/repos/matthewyjiang/rho/releases";
// GitHub documents 100 as the maximum releases page size. Use it so old drafts
// or releases for sibling workspace crates cannot hide the latest app release.
const RELEASES_PER_PAGE: u64 = 100;
const CRATE_NAME: &str = "rho-coding-agent";
const RELEASE_TAG_PREFIX: &str = "rho-coding-agent-v";
const PACMAN_PACKAGE_TARGET: &str = "mjiang-extras/rho-coding-agent";
const DNF_PACKAGE: &str = "rho-coding-agent";
const SCOOP_PACKAGE: &str = "rho";
/// Shell command that fetches and runs `install.sh` from `git_ref`. Pinned to
/// the release tag being installed so an update runs reviewed, released code
/// rather than whatever `main` holds at that moment.
#[cfg(not(windows))]
fn script_install_sh_command(git_ref: &str) -> String {
    format!(
        "tmp=$(mktemp) || exit; curl --proto '=https' --tlsv1.2 -LsSf \
         https://raw.githubusercontent.com/matthewyjiang/rho/{git_ref}/scripts/install.sh \
         -o \"$tmp\"; status=$?; if [ $status -eq 0 ]; then sh \"$tmp\"; status=$?; fi; \
         rm -f \"$tmp\"; exit $status"
    )
}

/// PowerShell equivalent of [`script_install_sh_command`], pinned to `git_ref`.
#[cfg(windows)]
fn script_install_ps1_command(git_ref: &str) -> String {
    format!(
        "irm https://raw.githubusercontent.com/matthewyjiang/rho/{git_ref}/scripts/install.ps1 | iex"
    )
}

/// Accepts a release tag for interpolation into the installer shell command only
/// when it is a plain git ref. An unexpected tag (metacharacters, spaces) would
/// otherwise inject into `sh -c`, so fall back to `main` rather than run it.
fn install_script_ref(tag: String) -> String {
    let is_plain_ref = !tag.is_empty()
        && tag
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'/'));
    if is_plain_ref {
        tag
    } else {
        "main".to_string()
    }
}

/// The newest published rho release, next to the running version.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UpdateInfo {
    pub latest_tag: String,
    pub latest_version: String,
    pub current_version: String,
}

impl UpdateInfo {
    /// Whether the latest release is newer than the running rho.
    pub fn is_available(&self) -> bool {
        version_is_newer(&self.latest_version, &self.current_version)
    }
}

/// How rho was installed, which decides how `rho update` updates it. The
/// serialized names are the ones `rho update --check --json` reports.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum InstallMethod {
    Cargo,
    Mise,
    Pacman,
    Dnf,
    Scoop,
    ScoopGlobal,
    Script,
}

impl InstallMethod {
    pub fn label(self) -> &'static str {
        match self {
            Self::Cargo => "Cargo",
            Self::Mise => "mise",
            Self::Pacman => "pacman",
            Self::Dnf => "dnf",
            Self::Scoop => "Scoop",
            Self::ScoopGlobal => "Scoop (global)",
            Self::Script => "install script",
        }
    }

    /// How `rho update` installs a release for this method on this
    /// platform.
    fn updater(self) -> Updater {
        if !cfg!(windows) {
            return Updater::Command;
        }
        match self {
            Self::Script => Updater::InPlace,
            Self::Cargo
            | Self::Mise
            | Self::Pacman
            | Self::Dnf
            | Self::Scoop
            | Self::ScoopGlobal => Updater::PrintsCommand,
        }
    }

    /// Where this method's update puts the new rho, which decides whether
    /// a running daemon can re-execute it in place.
    fn installs(self) -> Installed {
        match self.updater() {
            Updater::InPlace => return Installed::MovingTheRunningAside,
            Updater::Command | Updater::PrintsCommand => {}
        }
        match self {
            Self::Cargo | Self::Pacman | Self::Dnf | Self::Script => Installed::OverTheExecutable,
            Self::Mise | Self::Scoop | Self::ScoopGlobal => Installed::AtAnotherPath,
        }
    }

    /// Whether `rho update` needs a person at a terminal to finish: pacman
    /// and dnf ask for sudo's password, and where rho only prints the
    /// command, a person runs it.
    fn needs_terminal(self) -> bool {
        match self.updater() {
            Updater::PrintsCommand => true,
            Updater::InPlace => false,
            Updater::Command => match self {
                Self::Pacman | Self::Dnf => true,
                Self::Cargo | Self::Mise | Self::Scoop | Self::ScoopGlobal | Self::Script => false,
            },
        }
    }

    /// The command shown to the user. Fails when a mise install's tool cannot
    /// be resolved, rather than showing a command that would not work.
    pub fn update_command(self, git_ref: &str) -> anyhow::Result<String> {
        self.update_command_in(git_ref, &Lookups::OfThisProcess)
    }

    /// [`Self::update_command`], naming what `lookups` found.
    fn update_command_in(self, git_ref: &str, lookups: &Lookups) -> anyhow::Result<String> {
        Ok(match self {
            Self::Cargo => cargo_update_command_display(lookups.cargo_root()),
            Self::Mise => mise_update_command_display(lookups.mise_tool()?),
            Self::Pacman => pacman_update_command_display(),
            Self::Dnf => dnf_update_command_display(),
            Self::Scoop => scoop_update_command_display(ScoopInstallScope::User),
            Self::ScoopGlobal => scoop_update_command_display(ScoopInstallScope::Global),
            Self::Script => script_update_command_display(git_ref),
        })
    }
}

/// How `rho update` installs a release.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Updater {
    /// Runs the install method's update command.
    Command,
    /// Downloads the release and replaces its own executable
    /// (`update_in_place.rs`): the install script's rho on Windows, where
    /// running the script meant a hidden PowerShell (rho#106).
    InPlace,
    /// Prints the install method's command for a person to run: package
    /// managers on Windows.
    PrintsCommand,
}

#[derive(Deserialize)]
struct Release {
    tag_name: String,
    draft: bool,
    prerelease: bool,
}

fn latest_app_release_tag(releases: &[Release]) -> Option<&str> {
    releases
        .iter()
        .find(|release| {
            !release.draft
                && !release.prerelease
                && release_tag_to_version(&release.tag_name).is_some()
        })
        .map(|release| release.tag_name.as_str())
}

/// Looks up the newest published release. `rho update`, `rho update --check`,
/// and the TUI's update notice all ask this.
pub async fn latest_release(current_version: &str) -> anyhow::Result<UpdateInfo> {
    let latest_tag = latest_release_tag().await?;
    let Some(latest_version) = release_tag_to_version(&latest_tag) else {
        anyhow::bail!("latest release tag '{latest_tag}' does not contain a version");
    };
    Ok(UpdateInfo {
        latest_tag,
        latest_version,
        current_version: current_version.to_string(),
    })
}

pub async fn update_notice(current_version: &str) -> Option<String> {
    match tokio::time::timeout(Duration::from_millis(900), latest_release(current_version)).await {
        Ok(Ok(update)) if update.is_available() => {
            let method = detect_install_method();
            Some(format!(
                "update available: v{} (current v{}). run `rho update` to {} via {}.",
                update.latest_version,
                update.current_version,
                update_action_label(method),
                method.label()
            ))
        }
        Ok(Ok(_)) | Ok(Err(_)) | Err(_) => None,
    }
}

/// Where an update says what it does, a line at a time: `rho update`
/// prints to its terminal ([`Terminal`]), and the daemon's update streams
/// to the client that asked (`app::daemon_host::machine_update`). Neither
/// may block: an update never waits on its report.
pub(crate) trait Report {
    /// A line `rho update` prints to stdout.
    fn say(&mut self, line: &str);
    /// A warning, which `rho update` prints to stderr.
    fn warn(&mut self, line: &str);
}

/// `rho update`'s report: its terminal.
struct Terminal;

impl Report for Terminal {
    fn say(&mut self, line: &str) {
        println!("{line}");
    }

    fn warn(&mut self, line: &str) {
        eprintln!("{line}");
    }
}

/// What an update command names besides how rho was installed: the Cargo
/// root that holds rho, for a Cargo install, and the mise tool that
/// installed it, for a mise one.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Lookups {
    /// Looked up in this process's environment as the command needs them,
    /// as `rho update` does.
    OfThisProcess,
    /// Looked up already, as the daemon's update does in the user's login
    /// environment (`unattended::install_method`).
    Found {
        cargo_root: Option<PathBuf>,
        mise_tool: Option<String>,
    },
}

impl Lookups {
    /// The Cargo root to pass `cargo install --root`, unless rho is in
    /// Cargo's default one.
    fn cargo_root(&self) -> Option<PathBuf> {
        match self {
            Self::OfThisProcess => current_cargo_update_root(),
            Self::Found { cargo_root, .. } => cargo_root.clone(),
        }
    }

    /// The mise tool that installed rho.
    fn mise_tool(&self) -> anyhow::Result<&str> {
        match self {
            Self::OfThisProcess => current_mise_tool(),
            Self::Found { mise_tool, .. } => mise_tool
                .as_deref()
                .context("could not find the mise tool that installed rho"),
        }
    }
}

/// What `rho update` does, once it looked up the latest release.
#[derive(Debug, PartialEq, Eq)]
enum Plan {
    /// Runs the install method's command, pinned to `git_ref`.
    Run { git_ref: String },
    /// Prints the install method's command, pinned to `git_ref`.
    Print { git_ref: String },
    /// Replaces the running rho with the release.
    InPlace(UpdateInfo),
}

impl Plan {
    /// `latest` is the release when one is newer, or why it could not be
    /// looked up. Only the in-place update fails without it: a command
    /// goes on, pinned to `main`, which `report` hears.
    fn new(
        method: InstallMethod,
        latest: anyhow::Result<UpdateInfo>,
        report: &mut impl Report,
    ) -> anyhow::Result<Self> {
        let mut git_ref = |latest: anyhow::Result<UpdateInfo>| match latest {
            Ok(update) => install_script_ref(update.latest_tag),
            Err(err) => {
                report.warn(&format!("warning: could not check latest release: {err}"));
                report.say(&format!(
                    "continuing with {} update command.",
                    method.label()
                ));
                "main".to_string()
            }
        };
        Ok(match method.updater() {
            Updater::Command => Self::Run {
                git_ref: git_ref(latest),
            },
            Updater::PrintsCommand => Self::Print {
                git_ref: git_ref(latest),
            },
            Updater::InPlace => {
                Self::InPlace(latest.context("could not check the latest rho release")?)
            }
        })
    }
}

/// Looks up the latest release for `method`, saying so to `report` as `rho
/// update` does; `None` once rho is up to date. Both `rho update` and the
/// daemon's update ([`update_unattended`]) start here.
async fn prepare(
    method: InstallMethod,
    current_version: &str,
    report: &mut impl Report,
) -> anyhow::Result<Option<Plan>> {
    report.say(&format!("detected install method: {}", method.label()));

    let latest = match latest_release(current_version).await {
        Ok(update) if update.is_available() => {
            report.say(&format!(
                "rho v{} is available (current v{}).",
                update.latest_version, update.current_version
            ));
            Ok(update)
        }
        Ok(_) => {
            report.say(&format!("rho is up to date (v{current_version})."));
            return Ok(None);
        }
        Err(err) => Err(err),
    };
    Plan::new(method, latest, report).map(Some)
}

/// Says what `plan` runs, naming what `lookups` found, and what `method`
/// may ask of a person, as `rho update` does before it installs.
fn announce(
    method: InstallMethod,
    plan: &Plan,
    lookups: &Lookups,
    report: &mut impl Report,
) -> anyhow::Result<()> {
    match plan {
        Plan::Run { git_ref } | Plan::Print { git_ref } => {
            report.say(&format!(
                "update command: {}",
                method.update_command_in(git_ref, lookups)?
            ));
        }
        Plan::InPlace(_) => {}
    }
    match method {
        InstallMethod::Pacman => report.say("pacman may prompt for your sudo password."),
        InstallMethod::Dnf => report.say("dnf may prompt for your sudo password."),
        InstallMethod::Mise => report.say(
            "mise upgrades within your configured version request; a pinned version stays pinned.",
        ),
        InstallMethod::Cargo
        | InstallMethod::Scoop
        | InstallMethod::ScoopGlobal
        | InstallMethod::Script => {}
    }
    Ok(())
}

pub async fn run_update(current_version: &str) -> anyhow::Result<()> {
    let method = detect_install_method();
    let mut terminal = Terminal;
    let Some(plan) = prepare(method, current_version, &mut terminal).await? else {
        return Ok(());
    };
    announce(method, &plan, &Lookups::OfThisProcess, &mut terminal)?;

    let mut output = std::io::stdout();
    // The daemon is a courtesy to the update, never a reason to fail it: one
    // that could not be asked is reported and the update goes on.
    let watched = daemon_install::before_update(method.installs(), &mut output)
        .await
        .inspect_err(|error| {
            eprintln!(
                "warning: could not check the running rho daemon: {error:#}; run `rho daemon stop` if the installer cannot replace rho"
            );
        })
        .ok();
    match plan {
        Plan::Run { git_ref } => run_update_command(method, &git_ref).await?,
        Plan::Print { git_ref } => {
            println!(
                "automatic updates are disabled on Windows to avoid launching background shells that can trigger security software."
            );
            println!("copy and run this command yourself to update:");
            println!("{}", method.update_command(&git_ref)?);
        }
        Plan::InPlace(update) => update_in_place(method, &update, &mut terminal).await?,
    }
    if let Some(watched) = watched {
        if let Err(error) = watched.follow(&mut output).await {
            eprintln!(
                "warning: could not follow the running rho daemon: {error:#}; `rho daemon restart` moves it to the updated rho"
            );
        }
    }
    Ok(())
}

/// Replaces the running rho, installed by `method`, with `update`'s
/// release, saying so to `report`.
async fn update_in_place(
    method: InstallMethod,
    update: &UpdateInfo,
    report: &mut impl Report,
) -> anyhow::Result<()> {
    let installed = current_exe().context("could not find the rho executable")?;
    let aside = in_place::update(update, &installed, report).await.with_context(|| {
        // The daemon still runs the installed rho, which the install script
        // cannot write over.
        format!(
            "could not update rho in place; to update by hand, run `rho daemon stop` once its work is done, then: {}",
            method
                .update_command(&install_script_ref(update.latest_tag.clone()))
                .unwrap_or_default()
        )
    })?;
    report.say(&format!(
        "installed rho v{} at {}; rho removes the previous one, now {}, once nothing runs it",
        update.latest_version,
        installed.display(),
        aside.display()
    ));
    Ok(())
}

#[cfg(windows)]
async fn run_update_command(method: InstallMethod, _git_ref: &str) -> anyhow::Result<()> {
    // Unreachable: `InstallMethod::updater` never chooses `Updater::Command`
    // on Windows, which spawns no update command.
    anyhow::bail!("rho runs no {} update command on Windows", method.label())
}

#[cfg(not(windows))]
async fn run_update_command(method: InstallMethod, git_ref: &str) -> anyhow::Result<()> {
    let status = update_command(method, git_ref, &Lookups::OfThisProcess, None)?
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
        .await
        .with_context(|| format!("failed to run {} update command", method.label()))?;

    if !status.success() {
        anyhow::bail!("{} update command exited with {status}", method.label());
    }
    Ok(())
}

/// What `rho update` does for `method`, as the update notice says it.
fn update_action_label(method: InstallMethod) -> &'static str {
    match method.updater() {
        Updater::Command | Updater::InPlace => "update",
        Updater::PrintsCommand => "show the update command",
    }
}

/// The command that updates rho installed by `method`, pinned to `git_ref`,
/// naming what `lookups` found. It runs with `environment` alone when
/// given, as the daemon's update runs it in the user's login environment,
/// and with this process's otherwise.
#[cfg(not(windows))]
fn update_command(
    method: InstallMethod,
    git_ref: &str,
    lookups: &Lookups,
    environment: Option<&ClientEnvironment>,
) -> anyhow::Result<Command> {
    let program = |name: &str| {
        let mut command = Command::new(name);
        if let Some(environment) = environment {
            command.env_clear().envs(environment.iter());
        }
        command
    };
    Ok(match method {
        InstallMethod::Cargo => {
            let mut command = program("cargo");
            command.args(["install", CRATE_NAME, "--locked"]);
            if let Some(root) = lookups.cargo_root() {
                command.arg("--root").arg(root);
            }
            command
        }
        InstallMethod::Mise => {
            // Never a bare `mise upgrade`, which would upgrade every tool.
            let tool = lookups.mise_tool()?;
            let mut command = program("mise");
            command.args(["upgrade", "--global", tool]);
            command
        }
        InstallMethod::Pacman => {
            let mut command = program("sudo");
            command.args(["pacman", "-Sy", PACMAN_PACKAGE_TARGET]);
            command
        }
        InstallMethod::Dnf => {
            let mut command = program("sudo");
            command.args(["dnf", "upgrade", "--refresh", DNF_PACKAGE]);
            command
        }
        InstallMethod::Scoop | InstallMethod::ScoopGlobal => {
            let mut command = program("sh");
            command.args(["-c", &method.update_command_in(git_ref, lookups)?]);
            command
        }
        InstallMethod::Script => script_update_command(git_ref, program("sh")),
    })
}

fn cargo_update_command_display(root: Option<PathBuf>) -> String {
    let mut command = format!("cargo install {CRATE_NAME} --locked");
    if let Some(root) = root {
        command.push_str(" --root ");
        command.push_str(&shell_quote_path(&root));
    }
    command
}

// `mise upgrade` keeps the tool's configured version request, so a pinned
// version stays pinned and `latest` moves to the newest release. `--global`
// (mise 2026.10.7+) upgrades the global request rather than one a project
// config in the current directory sets for the same tool.
fn mise_update_command_display(tool: &str) -> String {
    format!("mise upgrade --global {}", shell_quote(tool))
}

fn pacman_update_command_display() -> String {
    format!("sudo pacman -Sy {PACMAN_PACKAGE_TARGET}")
}

// `--refresh` expires cached metadata first, so a release published within
// the repo's `metadata_expire` window is visible.
fn dnf_update_command_display() -> String {
    format!("sudo dnf upgrade --refresh {DNF_PACKAGE}")
}

fn scoop_update_command_display(scope: ScoopInstallScope) -> String {
    // Refresh Scoop/buckets first so a just-published release is visible even when
    // Scoop's own outdated check would still skip a bucket sync.
    match scope {
        ScoopInstallScope::User => format!("scoop update; scoop update {SCOOP_PACKAGE}"),
        ScoopInstallScope::Global => {
            format!("scoop update; scoop update -g {SCOOP_PACKAGE}")
        }
    }
}

#[cfg(windows)]
fn script_update_command_display(git_ref: &str) -> String {
    let ps1 = script_install_ps1_command(git_ref);
    let Some(install_dir) = current_exe_parent() else {
        return format!(
            "powershell -NoProfile -ExecutionPolicy Bypass -Command {}",
            powershell_quote(&ps1)
        );
    };
    format!(
        "powershell -NoProfile -ExecutionPolicy Bypass -Command {command}",
        command = powershell_quote(&format!(
            "$env:RHO_INSTALL_DIR={}; {ps1}",
            powershell_quote_path(&install_dir)
        ))
    )
}

#[cfg(not(windows))]
fn script_update_command_display(git_ref: &str) -> String {
    let command = format!("sh -c {}", shell_quote(&script_install_sh_command(git_ref)));
    let Some(install_dir) = current_exe_parent() else {
        return command;
    };
    format!(
        "RHO_INSTALL_DIR={} {command}",
        shell_quote_path(&install_dir)
    )
}

/// `sh`, as `command`, running the install script pinned to `git_ref`.
#[cfg(not(windows))]
fn script_update_command(git_ref: &str, mut command: Command) -> Command {
    command.args(["-c", &script_install_sh_command(git_ref)]);
    if let Some(install_dir) = current_exe_parent() {
        command.env("RHO_INSTALL_DIR", install_dir);
    }
    command
}

pub fn detect_install_method() -> InstallMethod {
    detect_install_method_in(&ThisProcess)
}

/// [`detect_install_method`], asking `probe` what detection asks. The
/// `RHO_INSTALL_METHOD` override is this process's own all the same: a
/// daemon's is what its service, or its test, set.
fn detect_install_method_in(probe: &impl Probe) -> InstallMethod {
    if let Ok(method) = std::env::var("RHO_INSTALL_METHOD") {
        match installation::install_hint(&method) {
            InstallHint::Cargo => return InstallMethod::Cargo,
            InstallHint::Pacman => return InstallMethod::Pacman,
            InstallHint::Dnf => return InstallMethod::Dnf,
            InstallHint::Scoop(ScoopInstallScope::User) => return InstallMethod::Scoop,
            InstallHint::Scoop(ScoopInstallScope::Global) => return InstallMethod::ScoopGlobal,
            InstallHint::Script => return InstallMethod::Script,
            InstallHint::Unknown => {}
        }
    }

    match current_exe()
        .ok()
        .as_deref()
        .and_then(|path| installation::detect_in(path, probe).managed)
    {
        Some(ManagedInstallation::Cargo { .. }) => InstallMethod::Cargo,
        Some(ManagedInstallation::Mise { .. }) => InstallMethod::Mise,
        Some(ManagedInstallation::Pacman) => InstallMethod::Pacman,
        Some(ManagedInstallation::Dnf) => InstallMethod::Dnf,
        Some(ManagedInstallation::Scoop(ScoopInstallScope::User)) => InstallMethod::Scoop,
        Some(ManagedInstallation::Scoop(ScoopInstallScope::Global)) => InstallMethod::ScoopGlobal,
        None => InstallMethod::Script,
    }
}

/// This process's executable, which `rho update` updates and finds how it
/// was installed from. On Linux the OS names it `<path> (deleted)` once an
/// installer replaced the file, as a daemon that updated finds it while it
/// waits to restart; the installed path is `<path>` all the same.
fn current_exe() -> std::io::Result<PathBuf> {
    let path = std::env::current_exe()?;
    let installed = path
        .to_str()
        .and_then(|path| path.strip_suffix(" (deleted)"));
    Ok(match installed {
        Some(installed) if cfg!(target_os = "linux") => PathBuf::from(installed),
        _ => path,
    })
}

fn current_exe_parent() -> Option<PathBuf> {
    current_exe()
        .ok()
        .and_then(|path| path.parent().map(Path::to_path_buf))
}

/// The mise tool that installed the running executable. Looked up once, since
/// `rho update` both prints and runs the command.
fn current_mise_tool() -> anyhow::Result<&'static str> {
    static TOOL: OnceLock<Result<String, String>> = OnceLock::new();
    TOOL.get_or_init(|| mise_tool_in(&ThisProcess).map_err(|err| format!("{err:#}")))
        .as_deref()
        .map_err(|err| anyhow::anyhow!("could not find the mise tool that installed rho: {err}"))
}

/// The mise tool that installed the running executable, as `probe` finds
/// it, looked up each time.
fn mise_tool_in(probe: &impl Probe) -> anyhow::Result<String> {
    let current_exe = current_exe()?;
    let Some(ManagedInstallation::Mise { install_path }) =
        installation::detect_in(&current_exe, probe).managed
    else {
        anyhow::bail!("{current_exe:?} is not in a mise installs directory");
    };
    installation::mise_tool(&install_path, probe)
}

fn current_cargo_update_root() -> Option<PathBuf> {
    cargo_update_root_in(&ThisProcess)
}

/// The Cargo root holding the running executable that `cargo install
/// --root` needs, as `probe` finds it: none for Cargo's default one.
fn cargo_update_root_in(probe: &impl Probe) -> Option<PathBuf> {
    let current_exe = current_exe().ok()?;
    cargo_update_root_for_exe(&current_exe, |root| {
        cargo_install_root_contains_crate(root, probe)
    })
}

fn shell_quote_path(path: &Path) -> String {
    shell_quote(&path.to_string_lossy())
}

fn shell_quote(value: &str) -> String {
    if value.is_empty() {
        return "''".to_string();
    }
    if value
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'.' | b'_' | b'-'))
    {
        return value.to_string();
    }
    format!("'{}'", value.replace('\'', "'\"'\"'"))
}

#[cfg(windows)]
fn powershell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "''"))
}

#[cfg(windows)]
fn powershell_quote_path(path: &Path) -> String {
    powershell_quote(&path.to_string_lossy())
}

pub(crate) async fn latest_release_tag() -> anyhow::Result<String> {
    let mut headers = HeaderMap::new();
    headers.insert(USER_AGENT, HeaderValue::from_static("rho-coding-agent"));
    headers.insert(
        ACCEPT,
        HeaderValue::from_static("application/vnd.github+json"),
    );
    let client = crate::reqwest_client_builder()
        .default_headers(headers)
        .timeout(Duration::from_secs(10))
        .build()?;
    let mut page = 1_u64;
    loop {
        let releases = client
            .get(RELEASES_URL)
            .query(&[("per_page", RELEASES_PER_PAGE), ("page", page)])
            .send()
            .await?
            .error_for_status()?
            .json::<Vec<Release>>()
            .await?;
        if let Some(tag) = latest_app_release_tag(&releases) {
            return Ok(tag.to_string());
        }
        if releases.len() < RELEASES_PER_PAGE as usize {
            anyhow::bail!("GitHub releases did not include a published {CRATE_NAME} release");
        }
        page += 1;
    }
}

pub(crate) fn release_tag_to_version(tag: &str) -> Option<String> {
    let version = tag.strip_prefix(RELEASE_TAG_PREFIX)?.trim();
    parse_version(version)
        .is_some()
        .then(|| version.to_string())
}

/// Whether `candidate` is a later version than `current`, by semantic
/// version precedence: a pre-release such as `3.0.0-alpha.dev` is older
/// than `3.0.0-beta.1` and `3.0.0`, and newer than every `2.x`. Build metadata is ignored, and a
/// version that does not parse is never newer or older.
pub(crate) fn version_is_newer(candidate: &str, current: &str) -> bool {
    let Some(candidate) = parse_version(candidate) else {
        return false;
    };
    let Some(current) = parse_version(current) else {
        return false;
    };
    candidate > current
}

/// Whether `version` carries a pre-release tag, such as `3.0.0-alpha.dev`.
pub(crate) fn is_prerelease(version: &str) -> bool {
    parse_version(version).is_some_and(|version| matches!(version.stage, Stage::PreRelease(_)))
}

/// A parsed version. The derived order is semantic version precedence: the
/// numeric core first, then the stage.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Version {
    core: Vec<u64>,
    stage: Stage,
}

/// Variant order is precedence: every pre-release of a core precedes its
/// release.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Stage {
    PreRelease(Vec<PreReleaseIdentifier>),
    Release,
}

/// One dot-separated part of a pre-release tag. Variant order is precedence:
/// numeric identifiers compare as numbers and precede text ones.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum PreReleaseIdentifier {
    Numeric(u64),
    Text(String),
}

fn parse_version(version: &str) -> Option<Version> {
    let version = version.trim().trim_start_matches('v');
    let version = version
        .split_once('+')
        .map_or(version, |(version, _)| version);
    let (core, pre_release) = match version.split_once('-') {
        Some((core, pre_release)) => (core, Some(pre_release)),
        None => (version, None),
    };
    let core = core
        .split('.')
        .map(str::parse::<u64>)
        .collect::<Result<Vec<_>, _>>()
        .ok()?;
    let stage = match pre_release {
        Some(pre_release) => Stage::PreRelease(
            pre_release
                .split('.')
                .map(|identifier| match identifier.parse() {
                    Ok(number) => PreReleaseIdentifier::Numeric(number),
                    Err(_) => PreReleaseIdentifier::Text(identifier.to_owned()),
                })
                .collect(),
        ),
        None => Stage::Release,
    };
    Some(Version { core, stage })
}

#[cfg(test)]
#[path = "update_tests.rs"]
mod tests;