Skip to main content

rpi_cli/
updates.rs

1//! Lightweight update discovery and update commands.
2//!
3//! Startup checks are deliberately best-effort: callers decide when to run
4//! them, each registry request uses a short timeout, and cached values are
5//! retained only as a fallback for temporary registry failures.
6
7use std::collections::{BTreeMap, BTreeSet};
8use std::future::Future;
9use std::path::{Path, PathBuf};
10#[cfg(windows)]
11use std::process::Stdio;
12use std::time::{SystemTime, UNIX_EPOCH};
13
14use futures::{stream, StreamExt};
15use serde::{Deserialize, Serialize};
16
17const CACHE_FILE: &str = "update-check.json";
18const CACHE_FALLBACK_MAX_AGE_MS: i64 = 6 * 60 * 60 * 1000;
19const REQUEST_TIMEOUT_MS: u64 = 1800;
20const UPDATE_CHECK_CONCURRENCY: usize = 4;
21const GITHUB_RELEASES_API: &str =
22    "https://api.github.com/repos/bigfish1913/pi-rust/releases?per_page=100";
23/// The single-release endpoint for the newest non-draft, non-prerelease tag.
24/// Authoritative version source for the stable CLI channel.
25const GITHUB_RELEASES_LATEST_API: &str =
26    "https://api.github.com/repos/bigfish1913/pi-rust/releases/latest";
27const STAGED_RPI_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
28const MAX_STAGED_RPI_OUTPUT_BYTES: usize = 4 * 1024;
29const MAX_SELF_UPDATE_STATUS_BYTES: u64 = 64 * 1024;
30const MAX_SELF_UPDATE_STATUS_MESSAGE_CHARS: usize = 2 * 1024;
31/// How long a running self-update may stay in a non-terminal state before a
32/// later process treats it as debris and prunes it. A `cargo install` compiles
33/// from source, so the window is generous; a helper that outlives it is stuck,
34/// not slow.
35const STALE_SELF_UPDATE_STATUS_TTL_MS: i64 = 60 * 60 * 1000;
36/// How long a completed update keeps its status record. `rpi update` prints
37/// that path, so the file has to outlive the command that named it by long
38/// enough to actually be read; after that it is just clutter.
39const COMPLETED_SELF_UPDATE_STATUS_TTL_MS: i64 = 24 * 60 * 60 * 1000;
40static UPDATE_CACHE_WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
41static SELF_UPDATE_STATUS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct UpdateNotice {
45    pub name: String,
46    pub current: String,
47    pub latest: String,
48    pub command: String,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct UpdateWarning {
53    pub message: String,
54    pub command: String,
55}
56
57#[derive(Debug, Clone, Default, PartialEq, Eq)]
58pub struct UpdateReport {
59    pub notices: Vec<UpdateNotice>,
60    pub warnings: Vec<UpdateWarning>,
61}
62
63impl UpdateReport {
64    pub fn is_empty(&self) -> bool {
65        self.notices.is_empty() && self.warnings.is_empty()
66    }
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize, Default)]
70#[serde(rename_all = "camelCase")]
71struct UpdateCache {
72    /// Legacy aggregate timestamp retained for backward-compatible cache reads.
73    checked_at: i64,
74    rpi_latest: Option<String>,
75    #[serde(default)]
76    native_packages: BTreeMap<String, String>,
77    #[serde(default)]
78    freshness: UpdateCacheFreshness,
79}
80
81#[derive(Debug, Clone, Serialize, Deserialize, Default)]
82#[serde(rename_all = "camelCase")]
83struct UpdateCacheFreshness {
84    rpi: i64,
85    #[serde(default)]
86    native_packages: BTreeMap<String, i64>,
87}
88
89type RegistryCacheUpdate = (BTreeMap<String, String>, BTreeMap<String, i64>);
90
91#[derive(Debug, Deserialize)]
92struct CratesResponse {
93    #[serde(rename = "crate")]
94    crate_info: CrateInfo,
95}
96
97#[derive(Debug, Deserialize)]
98struct CrateInfo {
99    max_version: String,
100}
101
102#[derive(Debug, Deserialize)]
103struct GithubRelease {
104    tag_name: String,
105    #[serde(default)]
106    draft: bool,
107    #[serde(default)]
108    prerelease: bool,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112enum UpdateChannel {
113    Stable,
114    Preview,
115}
116
117const HOMEBREW_UPGRADE_COMMAND: &str = "brew upgrade rpi";
118
119fn current_homebrew_keg() -> Option<PathBuf> {
120    homebrew_keg_for_exe(&std::env::current_exe().ok()?)
121}
122
123/// Resolve Homebrew's `bin/rpi` symlink to `Cellar/rpi/<version>/bin/rpi`.
124/// The receipt distinguishes a Homebrew keg from a similarly named directory.
125fn homebrew_keg_for_exe(exe: &Path) -> Option<PathBuf> {
126    let exe = exe.canonicalize().ok()?;
127    let bin = exe.parent()?;
128    let keg = bin.parent()?;
129    let formula = keg.parent()?;
130    if exe.file_name()? == crate::APP_NAME
131        && bin.file_name()? == "bin"
132        && formula.file_name()? == crate::APP_NAME
133        && formula.parent()?.file_name()? == "Cellar"
134        && keg.join("INSTALL_RECEIPT.json").is_file()
135    {
136        return Some(keg.to_path_buf());
137    }
138    None
139}
140
141#[derive(Debug, Deserialize)]
142#[serde(rename_all = "camelCase")]
143struct SelfUpdateStatus {
144    state: String,
145    #[serde(default)]
146    message: String,
147    /// The staging directory this update was installed into. Written by the
148    /// Windows helper; the older `preparing` records lack it, which is why an
149    /// unmapped staging directory is aged out instead of matched by name.
150    #[serde(default)]
151    staging: Option<PathBuf>,
152    #[serde(default)]
153    updated_at_ms: i64,
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
157enum RegistryLookup {
158    Found(String),
159    Missing,
160    TransientFailure,
161}
162
163/// Best-effort startup check for the rpi release and installed Rust extensions.
164pub async fn check_startup(cwd: &Path) -> UpdateReport {
165    let _ = cwd;
166    check_rpi_startup().await
167}
168
169/// Check the rpi release and every installed Rust cdylib extension.
170///
171/// Native-only: the npm/Git package halves of the old scope went away with the
172/// Pi compatibility layer, so this never shells out to a package manager.
173pub async fn check_rpi_startup() -> UpdateReport {
174    if update_checks_disabled() {
175        return report_without_remote_checks();
176    }
177    check_startup_with_client(startup_http_client()).await
178}
179
180fn update_checks_disabled() -> bool {
181    crate::args::offline_env_enabled() || std::env::var_os("RPI_DISABLE_UPDATE_CHECK").is_some()
182}
183
184/// Report the outcome of a self-update that ran in a previous process.
185fn report_without_remote_checks() -> UpdateReport {
186    let warnings = crate::config::agent_dir()
187        .ok()
188        .map(|agent_dir| consume_self_update_statuses(&agent_dir))
189        .unwrap_or_default();
190    UpdateReport {
191        notices: Vec::new(),
192        warnings,
193    }
194}
195
196fn startup_http_client() -> Option<reqwest::Client> {
197    let mut builder = reqwest::Client::builder()
198        .timeout(std::time::Duration::from_millis(REQUEST_TIMEOUT_MS))
199        .user_agent(format!("rpi/{}", crate::VERSION));
200    // The saved Web proxy is a fallback for this client. Keep explicit
201    // environment settings and leave the process environment alone.
202    if let Some(saved) = crate::settings::load_settings()
203        .ok()
204        .and_then(|settings| settings.http_proxy)
205    {
206        let proxy_url = |upper, lower| {
207            [upper, lower, "ALL_PROXY", "all_proxy"]
208                .into_iter()
209                .find_map(|key| std::env::var(key).ok().filter(|value| !value.is_empty()))
210                .unwrap_or_else(|| saved.clone())
211        };
212        let no_proxy = reqwest::NoProxy::from_env();
213        let http = reqwest::Proxy::http(proxy_url("HTTP_PROXY", "http_proxy")).ok()?;
214        let https = reqwest::Proxy::https(proxy_url("HTTPS_PROXY", "https_proxy")).ok()?;
215        builder = builder
216            .proxy(http.no_proxy(no_proxy.clone()))
217            .proxy(https.no_proxy(no_proxy));
218    }
219    builder.build().ok()
220}
221
222async fn check_startup_with_client(client: Option<reqwest::Client>) -> UpdateReport {
223    let agent_dir = match crate::config::agent_dir() {
224        Ok(dir) => dir,
225        Err(_) => return UpdateReport::default(),
226    };
227    let warnings = consume_self_update_statuses(&agent_dir);
228    let cache = refresh_update_cache(&agent_dir, client).await;
229    let mut report = report_from_cache(&cache);
230    report.warnings = warnings;
231    report
232}
233
234async fn refresh_update_cache(agent_dir: &Path, client: Option<reqwest::Client>) -> UpdateCache {
235    let cache_path = agent_dir.join(CACHE_FILE);
236    let previous_cache = read_cache(&cache_path);
237
238    // Installed Rust extensions come from `rpi install`'s registry, so this
239    // path stays independent of any Pi package resource discovery.
240    let native_checks = crate::install::installed_native_packages()
241        .into_iter()
242        .filter(|package| package.supports_registry_update())
243        .map(|package| {
244            let client = client.clone();
245            async move {
246                let latest = match client.as_ref() {
247                    Some(client) if package.prebuilt.is_some() => {
248                        match crate::prebuilt_extensions::latest_compatible_version(
249                            client, &package,
250                        )
251                        .await
252                        {
253                            Ok(Some(version)) => RegistryLookup::Found(version),
254                            Ok(None) => RegistryLookup::Missing,
255                            Err(_) => RegistryLookup::TransientFailure,
256                        }
257                    }
258                    Some(client) => fetch_crates_latest(client, &package.name).await,
259                    None => RegistryLookup::TransientFailure,
260                };
261                (native_cache_key(&package), latest)
262            }
263        });
264    let rpi_check = async {
265        Some(match client.as_ref() {
266            Some(client) => fetch_rpi_latest(client).await,
267            None => RegistryLookup::TransientFailure,
268        })
269    };
270    let (rpi_result, native_results) = tokio::join!(rpi_check, collect_bounded(native_checks));
271
272    let checked_at = now_ms();
273    let mut rpi_update = None;
274    if let Some(rpi_result) = rpi_result {
275        let cached_at = previous_cache
276            .as_ref()
277            .map(rpi_cache_checked_at)
278            .unwrap_or_default();
279        let fallback_allowed = timestamp_is_fresh(cached_at, checked_at);
280        let (latest, used_fallback) = lookup_with_cache_fallback(
281            rpi_result,
282            previous_cache
283                .as_ref()
284                .and_then(|cache| cache.rpi_latest.as_deref()),
285            fallback_allowed,
286        );
287        let value_checked_at =
288            resolved_checked_at(latest.as_deref(), used_fallback, cached_at, checked_at);
289        rpi_update = Some((latest, value_checked_at));
290    }
291
292    let legacy_checked_at = previous_cache
293        .as_ref()
294        .map(|cache| cache.checked_at)
295        .unwrap_or_default();
296    let native_packages = results_with_individual_cache_fallback(
297        native_results,
298        previous_cache.as_ref().map(|cache| &cache.native_packages),
299        previous_cache
300            .as_ref()
301            .map(|cache| &cache.freshness.native_packages),
302        legacy_checked_at,
303        checked_at,
304    );
305
306    merge_and_write_cache(&cache_path, checked_at, rpi_update, native_packages)
307}
308
309async fn collect_bounded<I, F, T>(checks: I) -> Vec<T>
310where
311    I: IntoIterator<Item = F>,
312    F: Future<Output = T>,
313{
314    stream::iter(checks)
315        .buffer_unordered(UPDATE_CHECK_CONCURRENCY)
316        .collect()
317        .await
318}
319
320fn rpi_cache_checked_at(cache: &UpdateCache) -> i64 {
321    if cache.freshness.rpi > 0 {
322        cache.freshness.rpi
323    } else {
324        cache.checked_at
325    }
326}
327
328fn entry_cache_checked_at(
329    freshness: Option<&BTreeMap<String, i64>>,
330    key: &str,
331    legacy_checked_at: i64,
332) -> i64 {
333    freshness
334        .and_then(|values| values.get(key).copied())
335        .filter(|checked_at| *checked_at > 0)
336        .unwrap_or(legacy_checked_at)
337}
338
339fn timestamp_is_fresh(checked_at: i64, now: i64) -> bool {
340    let age = now.saturating_sub(checked_at);
341    checked_at > 0 && (0..=CACHE_FALLBACK_MAX_AGE_MS).contains(&age)
342}
343
344fn resolved_checked_at(
345    value: Option<&str>,
346    used_fallback: bool,
347    cached_at: i64,
348    checked_at: i64,
349) -> i64 {
350    if value.is_none() {
351        0
352    } else if used_fallback {
353        cached_at
354    } else {
355        checked_at
356    }
357}
358
359fn results_with_individual_cache_fallback(
360    results: Vec<(String, RegistryLookup)>,
361    cached: Option<&BTreeMap<String, String>>,
362    freshness: Option<&BTreeMap<String, i64>>,
363    legacy_checked_at: i64,
364    checked_at: i64,
365) -> RegistryCacheUpdate {
366    let mut values = BTreeMap::new();
367    let mut checked_at_values = BTreeMap::new();
368    for (name, result) in results {
369        let cached_value = cached.and_then(|cached| cached.get(&name).map(String::as_str));
370        let cached_at = entry_cache_checked_at(freshness, &name, legacy_checked_at);
371        let (latest, used_fallback) = lookup_with_cache_fallback(
372            result,
373            cached_value,
374            timestamp_is_fresh(cached_at, checked_at),
375        );
376        if let Some(latest) = latest {
377            checked_at_values.insert(
378                name.clone(),
379                resolved_checked_at(Some(&latest), used_fallback, cached_at, checked_at),
380            );
381            values.insert(name, latest);
382        }
383    }
384    (values, checked_at_values)
385}
386
387fn merge_and_write_cache(
388    path: &Path,
389    checked_at: i64,
390    rpi_update: Option<(Option<String>, i64)>,
391    native_packages: RegistryCacheUpdate,
392) -> UpdateCache {
393    let _guard = UPDATE_CACHE_WRITE_LOCK
394        .lock()
395        .unwrap_or_else(std::sync::PoisonError::into_inner);
396    let mut cache = read_cache(path).unwrap_or_default();
397    if cache.checked_at <= 0 {
398        cache.checked_at = checked_at;
399    }
400    if let Some((latest, latest_checked_at)) = rpi_update {
401        cache.rpi_latest = latest;
402        cache.freshness.rpi = latest_checked_at;
403    }
404    cache.native_packages = native_packages.0;
405    cache.freshness.native_packages = native_packages.1;
406    let _ = write_cache(path, &cache);
407    cache
408}
409
410fn lookup_with_cache_fallback(
411    result: RegistryLookup,
412    cached: Option<&str>,
413    fallback_allowed: bool,
414) -> (Option<String>, bool) {
415    match result {
416        RegistryLookup::Found(version) => (Some(version), false),
417        RegistryLookup::Missing => (None, false),
418        RegistryLookup::TransientFailure if fallback_allowed => {
419            (cached.map(str::to_owned), cached.is_some())
420        }
421        RegistryLookup::TransientFailure => (None, false),
422    }
423}
424fn native_cache_key(package: &crate::install::InstalledNativePackage) -> String {
425    match &package.prebuilt {
426        Some(source) => format!(
427            "prebuilt:{}:{}#{}:{}",
428            if source.custom_repository {
429                "github"
430            } else {
431                "crates"
432            },
433            source.repository,
434            package.name,
435            source.target
436        ),
437        None => package.name.clone(),
438    }
439}
440
441fn report_from_cache(cache: &UpdateCache) -> UpdateReport {
442    let mut notices = Vec::new();
443    if let Some(latest) = cache.rpi_latest.as_deref() {
444        if is_newer(crate::VERSION, latest) {
445            notices.push(UpdateNotice {
446                name: "rpi".into(),
447                current: crate::VERSION.into(),
448                latest: latest.into(),
449                command: if current_homebrew_keg().is_some() {
450                    HOMEBREW_UPGRADE_COMMAND.into()
451                } else {
452                    "rpi update".into()
453                },
454            });
455        }
456    }
457    for package in crate::install::installed_native_packages() {
458        if !package.supports_registry_update() {
459            continue;
460        }
461        let Some(latest) = cache.native_packages.get(&native_cache_key(&package)) else {
462            continue;
463        };
464        if is_newer(&package.version, latest) {
465            notices.push(UpdateNotice {
466                name: package.name.clone(),
467                current: package.version,
468                latest: latest.clone(),
469                command: format!("rpi extension update {}", package.name),
470            });
471        }
472    }
473    UpdateReport {
474        notices,
475        warnings: Vec::new(),
476    }
477}
478
479fn normalize_windows_path(path: PathBuf) -> PathBuf {
480    if cfg!(windows) {
481        let text = path.to_string_lossy();
482        if let Some(unc) = text.strip_prefix(r"\\?\UNC\") {
483            return PathBuf::from(format!(r"\\{unc}"));
484        }
485        if let Some(local) = text.strip_prefix(r"\\?\") {
486            return PathBuf::from(local);
487        }
488    }
489    path
490}
491
492fn windows_paths_equal(left: &Path, right: &Path) -> bool {
493    let left = normalize_windows_path(left.to_path_buf());
494    let right = normalize_windows_path(right.to_path_buf());
495    if cfg!(windows) {
496        left.to_string_lossy()
497            .replace('/', "\\")
498            .eq_ignore_ascii_case(&right.to_string_lossy().replace('/', "\\"))
499    } else {
500        left == right
501    }
502}
503
504async fn fetch_rpi_latest(client: &reqwest::Client) -> RegistryLookup {
505    fetch_stable_from_github(client, GITHUB_RELEASES_LATEST_API).await
506}
507
508/// The stable version a `/releases/latest` body names, or `None` when the body
509/// is not a usable stable release.
510///
511/// `/releases/latest` already excludes drafts and prereleases, but the flags are
512/// re-checked here so a GitHub API behaviour change cannot silently hand the
513/// stable channel a prerelease. This is deliberately separate from
514/// `latest_preview_version`, which selects prereleases from the full list.
515fn stable_version_from_release(release: &GithubRelease) -> Option<String> {
516    if release.prerelease || release.draft {
517        return None;
518    }
519    let version = release.tag_name.strip_prefix('v')?;
520    let parsed = semver::Version::parse(version).ok()?;
521    parsed.pre.is_empty().then(|| version.to_string())
522}
523
524async fn fetch_stable_from_github(client: &reqwest::Client, url: &str) -> RegistryLookup {
525    let response = match client
526        .get(url)
527        .header(reqwest::header::ACCEPT, "application/vnd.github+json")
528        .send()
529        .await
530    {
531        Ok(response) => response,
532        Err(_) => return RegistryLookup::TransientFailure,
533    };
534    // Missing, unavailable or malformed release metadata must not invalidate
535    // a fresh cached answer. A release may be temporarily unavailable while
536    // publishing; offline/cache age policy stays with the caller.
537    if !response.status().is_success() {
538        return RegistryLookup::TransientFailure;
539    }
540    let release = match response.json::<GithubRelease>().await {
541        Ok(release) => release,
542        Err(_) => return RegistryLookup::TransientFailure,
543    };
544    // A body that is not a usable stable release is an unanswered lookup too,
545    // for the same reason: keep a fresh cache able to serve the request.
546    match stable_version_from_release(&release) {
547        Some(version) => RegistryLookup::Found(version),
548        None => RegistryLookup::TransientFailure,
549    }
550}
551
552fn latest_preview_version(releases: impl IntoIterator<Item = GithubRelease>) -> RegistryLookup {
553    releases
554        .into_iter()
555        .filter(|release| release.prerelease && !release.draft)
556        .filter_map(|release| {
557            let version = release.tag_name.strip_prefix('v')?.to_string();
558            let parsed = semver::Version::parse(&version).ok()?;
559            (!parsed.pre.is_empty()).then_some((parsed, version))
560        })
561        .max_by(|left, right| left.0.cmp(&right.0))
562        .map(|(_, version)| RegistryLookup::Found(version))
563        .unwrap_or(RegistryLookup::Missing)
564}
565
566async fn fetch_rpi_preview_latest(client: &reqwest::Client) -> RegistryLookup {
567    let response = match client
568        .get(GITHUB_RELEASES_API)
569        .header(reqwest::header::ACCEPT, "application/vnd.github+json")
570        .send()
571        .await
572    {
573        Ok(response) => response,
574        Err(_) => return RegistryLookup::TransientFailure,
575    };
576    if response.status() == reqwest::StatusCode::NOT_FOUND {
577        return RegistryLookup::Missing;
578    }
579    if !response.status().is_success() {
580        return RegistryLookup::TransientFailure;
581    }
582    let releases = match response.json::<Vec<GithubRelease>>().await {
583        Ok(releases) => releases,
584        Err(_) => return RegistryLookup::TransientFailure,
585    };
586    latest_preview_version(releases)
587}
588
589async fn fetch_crates_latest(client: &reqwest::Client, name: &str) -> RegistryLookup {
590    fetch_crates_url(client, &format!("https://crates.io/api/v1/crates/{name}")).await
591}
592
593async fn fetch_crates_url(client: &reqwest::Client, url: &str) -> RegistryLookup {
594    let response = match client.get(url).send().await {
595        Ok(response) => response,
596        Err(_) => return RegistryLookup::TransientFailure,
597    };
598    if matches!(
599        response.status(),
600        reqwest::StatusCode::NOT_FOUND | reqwest::StatusCode::GONE
601    ) {
602        return RegistryLookup::Missing;
603    }
604    if !response.status().is_success() {
605        return RegistryLookup::TransientFailure;
606    }
607    match response.json::<CratesResponse>().await {
608        Ok(response) => RegistryLookup::Found(response.crate_info.max_version),
609        Err(_) => RegistryLookup::TransientFailure,
610    }
611}
612
613/// Compare complete semantic versions, including prerelease precedence.
614pub fn is_newer(current: &str, latest: &str) -> bool {
615    let parse = |value: &str| semver::Version::parse(value.trim().trim_start_matches('v')).ok();
616    match (parse(current), parse(latest)) {
617        (Some(current), Some(latest)) => latest.cmp_precedence(&current).is_gt(),
618        _ => false,
619    }
620}
621
622fn read_cache(path: &Path) -> Option<UpdateCache> {
623    serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
624}
625
626fn write_cache(path: &Path, cache: &UpdateCache) -> Result<(), String> {
627    if let Some(parent) = path.parent() {
628        std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
629    }
630    let data = serde_json::to_vec_pretty(cache).map_err(|error| error.to_string())?;
631    crate::config::atomic_write(path, &data).map_err(|error| error.to_string())
632}
633
634fn now_ms() -> i64 {
635    SystemTime::now()
636        .duration_since(UNIX_EPOCH)
637        .map(|duration| duration.as_millis() as i64)
638        .unwrap_or(0)
639}
640
641pub fn print_startup_notices(report: &UpdateReport) {
642    for warning in &report.warnings {
643        eprintln!("warning: {} Run `{}`.", warning.message, warning.command);
644    }
645    for notice in &report.notices {
646        eprintln!(
647            "Update available: {} {} -> {}. Run `{}`.",
648            notice.name, notice.current, notice.latest, notice.command
649        );
650    }
651}
652
653#[derive(Debug, Clone, PartialEq, Eq)]
654enum SelfUpdateArgs {
655    Help,
656    Run {
657        force: bool,
658        build: bool,
659        channel: UpdateChannel,
660        cdn_base: Option<reqwest::Url>,
661    },
662    Usage,
663}
664
665/// Parse `rpi update`'s own arguments after the global `--offline` flag has been
666/// stripped.
667fn parse_self_update_args(args: &[String]) -> SelfUpdateArgs {
668    let mut force = false;
669    let mut build = false;
670    let mut channel = UpdateChannel::Stable;
671    let mut cdn = None;
672    let mut i = 0;
673    while i < args.len() {
674        match args[i].as_str() {
675            "--help" | "-h" => return SelfUpdateArgs::Help,
676            "--force" | "-f" => force = true,
677            "--build" => build = true,
678            "--cdn" => {
679                i += 1;
680                let Some(value) = args.get(i).filter(|value| !value.starts_with('-')) else {
681                    return SelfUpdateArgs::Usage;
682                };
683                cdn = Some(value.as_str());
684            }
685            "preview" if channel == UpdateChannel::Stable => channel = UpdateChannel::Preview,
686            _ => return SelfUpdateArgs::Usage,
687        }
688        i += 1;
689    }
690    let cdn_base = match crate::cdn::resolve_base(cdn) {
691        Ok(base) => base,
692        Err(_) => return SelfUpdateArgs::Usage,
693    };
694    SelfUpdateArgs::Run {
695        force,
696        build,
697        channel,
698        cdn_base,
699    }
700}
701
702fn print_self_update_help() {
703    println!(
704        "Usage: rpi update [preview] [--force] [--offline] [--build] [--cdn <URL>]\n\n\
705         Update the rpi CLI using verified GitHub prebuilt releases.\n\
706         The optional `preview` channel installs the latest GitHub prerelease;\n\
707         it is never selected by the normal update check.\n\n\
708         Options:\n  \
709         preview    use the GitHub prerelease channel instead of stable releases\n  \
710         --build    explicitly compile with Cargo instead of downloading a prebuilt binary\n  \
711         --force    reinstall even when this rpi is already the latest release\n  \
712         --offline  do not touch the network; report the last known answer only\n\n\
713         A Homebrew install is upgraded with `brew upgrade rpi`; `rpi update`\n\
714         refuses to overwrite the binary Homebrew owns."
715    );
716}
717
718/// The latest release this process already knows about.
719///
720/// `registry_lookup: true` means a live request just answered *in this process*
721/// from the official GitHub release channel, so using it to short-circuit
722/// cannot hide a newer release. A value read from the
723/// 6-hour cache is only trusted for the offline report, where there is no
724/// alternative and the output says so.
725fn known_latest_rpi(registry_lookup: Option<&str>, cached: Option<&str>) -> Option<(String, bool)> {
726    registry_lookup
727        .map(|latest| (latest.to_string(), false))
728        .or_else(|| cached.map(|latest| (latest.to_string(), true)))
729}
730
731async fn lookup_latest_rpi() -> Option<(String, bool)> {
732    lookup_latest_rpi_from(GITHUB_RELEASES_LATEST_API).await
733}
734
735/// Resolve the latest stable version and report whether it came from a live
736/// answer.
737///
738/// The endpoint is a parameter so the whole decision — including `verified`
739/// and the cache fallback — can be exercised offline.
740async fn lookup_latest_rpi_from(github_latest_url: &str) -> Option<(String, bool)> {
741    let cache_path = crate::config::agent_dir()
742        .ok()
743        .map(|dir| dir.join(CACHE_FILE));
744    let cached = cache_path.as_deref().and_then(read_cache);
745    let result = match reqwest::Client::builder()
746        .timeout(std::time::Duration::from_secs(15))
747        .user_agent(format!("rpi/{}", crate::VERSION))
748        .build()
749    {
750        Ok(client) => fetch_stable_from_github(&client, github_latest_url).await,
751        Err(_) => RegistryLookup::TransientFailure,
752    };
753    // Only a live answer from an authoritative source counts as verified; a
754    // value that came back from the cache means every request failed and the
755    // version is up to six hours old. Only GitHub supplies live CLI versions.
756    let verified = matches!(result, RegistryLookup::Found(_));
757    let previous = cached
758        .as_ref()
759        .filter(|cache| timestamp_is_fresh(rpi_cache_checked_at(cache), now_ms()))
760        .and_then(|cache| cache.rpi_latest.as_deref());
761    let (latest, _) = lookup_with_cache_fallback(result, previous, true);
762    latest.map(|latest| (latest, verified))
763}
764
765/// `rpi update` is synchronous, so its registry lookup runs on its own thread and
766/// current-thread runtime. That also keeps it safe to call from inside a Tokio
767/// runtime, which is where the CLI enters it.
768fn lookup_latest_rpi_blocking() -> Option<(String, bool)> {
769    std::thread::Builder::new()
770        .name("rpi-update-latest-lookup".to_string())
771        .spawn(|| {
772            let runtime = tokio::runtime::Builder::new_current_thread()
773                .enable_all()
774                .build()
775                .ok()?;
776            runtime.block_on(lookup_latest_rpi())
777        })
778        .ok()?
779        .join()
780        .ok()?
781}
782
783async fn lookup_latest_preview() -> Option<(String, bool)> {
784    let result = match reqwest::Client::builder()
785        .timeout(std::time::Duration::from_secs(15))
786        .user_agent(format!("rpi/{}", crate::VERSION))
787        .build()
788    {
789        Ok(client) => fetch_rpi_preview_latest(&client).await,
790        Err(_) => RegistryLookup::TransientFailure,
791    };
792    let verified = matches!(result, RegistryLookup::Found(_));
793    match result {
794        RegistryLookup::Found(version) => Some((version, verified)),
795        _ => None,
796    }
797}
798
799fn lookup_latest_preview_blocking() -> Option<(String, bool)> {
800    std::thread::Builder::new()
801        .name("rpi-update-preview-lookup".to_string())
802        .spawn(|| {
803            let runtime = tokio::runtime::Builder::new_current_thread()
804                .enable_all()
805                .build()
806                .ok()?;
807            runtime.block_on(lookup_latest_preview())
808        })
809        .ok()?
810        .join()
811        .ok()?
812}
813
814/// The newest version already staged in a `pending-*` directory.
815///
816/// A staged update is a fully validated binary waiting for the running process
817/// to exit. Re-running `rpi update` while one is queued must not start a second
818/// compile, so the staged version joins the up-to-date comparison.
819fn staged_pending_version(update_root: &Path, channel: UpdateChannel) -> Option<semver::Version> {
820    let entries = std::fs::read_dir(update_root).ok()?;
821    let mut newest: Option<semver::Version> = None;
822    for entry in entries.flatten() {
823        let name = entry.file_name();
824        let Some(name) = name.to_str() else {
825            continue;
826        };
827        let Some(suffix) = name.strip_prefix("pending-") else {
828            continue;
829        };
830        // `tempfile` builds the name from `[A-Za-z0-9]`; anything else is not
831        // ours, so it is left alone rather than probed.
832        if suffix.is_empty() || !suffix.bytes().all(|byte| byte.is_ascii_alphanumeric()) {
833            continue;
834        }
835        let staging = update_root.join(name);
836        if validated_real_directory(&staging, "self-update staging directory").is_err() {
837            continue;
838        }
839        let Ok(version) = validate_rpi_executable_version(
840            &staging.join("bin").join(staged_rpi_file_name()),
841            update_root,
842            crate::VERSION,
843            "staged rpi",
844        ) else {
845            continue;
846        };
847        if (channel == UpdateChannel::Stable && !version.pre.is_empty())
848            || (channel == UpdateChannel::Preview && version.pre.is_empty())
849        {
850            continue;
851        }
852        if newest.as_ref().is_none_or(|newest| version > *newest) {
853            newest = Some(version);
854        }
855    }
856    newest
857}
858
859fn staged_rpi_file_name() -> &'static str {
860    if cfg!(windows) {
861        "rpi.exe"
862    } else {
863        crate::APP_NAME
864    }
865}
866
867/// Reclaim debris and surface a previous run's failure, without a network
868/// round trip.
869///
870/// `rpi update` is the command that creates `self-update` records and staging
871/// directories, so it is also the right place to clean them up: leaving it to
872/// the startup check means a machine that only ever runs `rpi chat` keeps the
873/// debris from every interrupted update until the next start.
874fn reclaim_self_update_artifacts() {
875    let Ok(agent_dir) = crate::config::agent_dir() else {
876        return;
877    };
878    for warning in consume_self_update_statuses(&agent_dir) {
879        eprintln!("warning: {} Run `{}`.", warning.message, warning.command);
880    }
881}
882
883/// Download a verified CLI release by default; --build explicitly selects Cargo.
884/// Both paths use the same staging validation and transactional replacement.
885pub fn run_self_update(args: &[String]) -> i32 {
886    let offline = crate::args::normalize_offline_mode(args);
887    let args = crate::args::without_offline_flag(args);
888    let (force, build, channel, cdn_base) = match parse_self_update_args(&args) {
889        SelfUpdateArgs::Help => {
890            print_self_update_help();
891            return 0;
892        }
893        SelfUpdateArgs::Run {
894            force,
895            build,
896            channel,
897            cdn_base,
898        } => (force, build, channel, cdn_base),
899        SelfUpdateArgs::Usage => {
900            eprintln!(
901                "error: `rpi update` accepts only `preview`, `--force`, `--offline`, `--build` and `--cdn <URL>`"
902            );
903            return 2;
904        }
905    };
906
907    if let Some(keg) = current_homebrew_keg() {
908        eprintln!(
909            "error: Homebrew manages this rpi installation ({}).\n\
910             Run `{HOMEBREW_UPGRADE_COMMAND}` to update it.",
911            keg.display()
912        );
913        return 1;
914    }
915
916    if offline {
917        reclaim_self_update_artifacts();
918        if channel == UpdateChannel::Preview {
919            println!(
920                "rpi preview update skipped: offline mode is enabled;\n\
921                 run `rpi update preview` without --offline to query GitHub."
922            );
923            return 0;
924        }
925        // The cache is the only source available without a network round trip,
926        // so it may be stale — say so rather than assert a version.
927        match known_latest_rpi(None, cached_latest_rpi().as_deref()) {
928            Some((latest, true)) if is_newer(crate::VERSION, &latest) => println!(
929                "rpi {} -> {} is available (offline: last known, not verified)\n\
930                 Run `rpi update` without --offline to install it.",
931                crate::VERSION,
932                latest
933            ),
934            Some(_) => println!(
935                "rpi is up to date with the last known release ({})\n\
936                 Offline mode is enabled; the registry was not contacted.",
937                crate::VERSION
938            ),
939            None => println!(
940                "rpi update skipped: offline mode is enabled and no cached release is known"
941            ),
942        }
943        return 0;
944    }
945
946    // Without this gate `rpi update` at the newest release still runs a full
947    // `cargo install` and schedules a binary replacement for the version that
948    // is already installed — which is exactly what makes a working update look
949    // broken. `--force` keeps an explicit reinstall available.
950    let release = if !build || !force {
951        match channel {
952            UpdateChannel::Stable => lookup_latest_rpi_blocking(),
953            UpdateChannel::Preview => lookup_latest_preview_blocking(),
954        }
955    } else {
956        None
957    };
958    if !force {
959        reclaim_self_update_artifacts();
960        let staged = pending_staged_version(channel);
961        let (latest, verified) = match release.clone() {
962            Some(found) => found,
963            None if staged.is_some() => {
964                println!(
965                    "could not reach the latest {} release; using the already staged update",
966                    if channel == UpdateChannel::Preview {
967                        "preview"
968                    } else {
969                        "stable"
970                    }
971                );
972                (crate::VERSION.to_string(), false)
973            }
974            None => {
975                println!(
976                    "could not reach the latest {} release\n\
977                     Retry later, or use `rpi update --build --force` for an explicit Cargo build.",
978                    if channel == UpdateChannel::Preview {
979                        "preview"
980                    } else {
981                        "stable"
982                    }
983                );
984                return 1;
985            }
986        };
987        // A staged update counts as "already going to happen": it is a fully
988        // validated binary waiting only for this process to exit, so compiling
989        // a second one buys nothing. It only counts when it is at least as new
990        // as the release the registry just reported.
991        let staged_wins = staged
992            .as_ref()
993            .filter(|staged| !is_newer(&staged.to_string(), &latest))
994            .map(std::string::ToString::to_string);
995        let target = staged_wins.clone().unwrap_or_else(|| latest.clone());
996        let needs_update = match channel {
997            UpdateChannel::Stable => is_newer(crate::VERSION, &target),
998            // Explicitly selecting preview is allowed from a stable install;
999            // a preview channel is intentionally independent of the stable channel's
1000            // stable precedence ordering.
1001            UpdateChannel::Preview => {
1002                let current = semver::Version::parse(crate::VERSION).ok();
1003                current.is_some_and(|current| current.pre.is_empty())
1004                    || is_newer(crate::VERSION, &target)
1005            }
1006        };
1007        if !needs_update {
1008            if staged_wins.is_some() {
1009                println!(
1010                    "rpi {target} is already staged; quit this rpi and it will be applied\n\
1011                     Run `rpi update --force` to stage it again."
1012                );
1013            } else if verified {
1014                println!(
1015                    "rpi is up to date ({} is the latest release)\n\
1016                     Run `rpi update --force` to reinstall anyway.",
1017                    crate::VERSION
1018                );
1019            } else {
1020                println!(
1021                    "rpi is up to date ({}; last known release {latest}, unverified)\n\
1022                     Run `rpi update --force` to reinstall anyway.",
1023                    crate::VERSION
1024                );
1025            }
1026            return 0;
1027        }
1028    }
1029
1030    if !build && release.is_none() {
1031        eprintln!(
1032            "error: could not resolve the {} release version; retry later or select --build explicitly",
1033            if channel == UpdateChannel::Preview {
1034                "preview"
1035            } else {
1036                "stable"
1037            }
1038        );
1039        return 1;
1040    }
1041    let version = release.as_ref().map(|(version, _)| version.as_str());
1042    let code = {
1043        #[cfg(windows)]
1044        {
1045            run_windows_self_update(build, version, cdn_base.as_ref())
1046        }
1047        #[cfg(not(windows))]
1048        {
1049            run_direct_self_update(build, version, cdn_base.as_ref())
1050        }
1051    };
1052    if code == 0 {
1053        clear_cached_latest_rpi();
1054    }
1055    code
1056}
1057
1058fn pending_staged_version(channel: UpdateChannel) -> Option<semver::Version> {
1059    let agent_dir = crate::config::agent_dir().ok()?;
1060    let update_root = agent_dir.join("self-update");
1061    staged_pending_version(&update_root, channel)
1062}
1063
1064fn cached_latest_rpi() -> Option<String> {
1065    let agent_dir = crate::config::agent_dir().ok()?;
1066    let cache = read_cache(&agent_dir.join(CACHE_FILE))?;
1067    cache.rpi_latest
1068}
1069
1070/// A self-update just changed the binary on disk, so the cached release is the
1071/// version being replaced. Dropping it stops the next startup (and the next
1072/// `rpi update`) from announcing an update that is already installed; the
1073/// following registry check refills it.
1074fn clear_cached_latest_rpi() {
1075    let Ok(agent_dir) = crate::config::agent_dir() else {
1076        return;
1077    };
1078    let path = agent_dir.join(CACHE_FILE);
1079    let _guard = UPDATE_CACHE_WRITE_LOCK
1080        .lock()
1081        .unwrap_or_else(std::sync::PoisonError::into_inner);
1082    let Some(mut cache) = read_cache(&path) else {
1083        return;
1084    };
1085    cache.rpi_latest = None;
1086    cache.freshness.rpi = 0;
1087    let _ = write_cache(&path, &cache);
1088}
1089
1090fn cargo_install_command(
1091    staging_root: Option<&Path>,
1092    isolated_cwd: &Path,
1093) -> Result<std::process::Command, String> {
1094    let isolated_cwd = validated_self_update_command_dir(isolated_cwd)?;
1095    let mut command = std::process::Command::new("cargo");
1096    command.arg("install").current_dir(isolated_cwd);
1097    for variable in [
1098        "RUSTC_WRAPPER",
1099        "RUSTC_WORKSPACE_WRAPPER",
1100        "CARGO_BUILD_RUSTC_WRAPPER",
1101        "CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER",
1102    ] {
1103        command.env_remove(variable);
1104    }
1105    if let Some(staging_root) = staging_root {
1106        command.arg("--root").arg(staging_root);
1107    }
1108    // `--quiet` suppresses cargo's trailing advice to add the install root to
1109    // PATH. Here that advice is actively wrong: the staging root is a temp
1110    // directory that the atomic replace consumes, so a user who follows it
1111    // adds a path that will not exist a second later. Errors still print.
1112    command.args(["rpi-cli", "--locked", "--force", "--quiet"]);
1113    Ok(command)
1114}
1115
1116/// Both distribution paths feed the same validated staging/atomic replacement.
1117/// Cargo is only reached when the user explicitly selects --build.
1118fn prepare_self_update(
1119    staging: &Path,
1120    build: bool,
1121    version: Option<&str>,
1122    cdn_base: Option<&reqwest::Url>,
1123) -> Result<(), String> {
1124    if build {
1125        let command_dir = create_self_update_command_dir()?;
1126        let status = cargo_install_command(Some(staging), command_dir.path())?
1127            .status()
1128            .map_err(|e| format!("could not run Cargo: {e}"))?;
1129        return if status.success() {
1130            Ok(())
1131        } else {
1132            Err(format!("cargo install exited with {status}"))
1133        };
1134    }
1135    let version = version
1136        .ok_or("no verified release version is available")?
1137        .to_string();
1138    let staging = staging.to_path_buf();
1139    let cdn_base = cdn_base.cloned();
1140    std::thread::Builder::new()
1141        .name("rpi-prebuilt-update".into())
1142        .spawn(move || {
1143            let runtime = tokio::runtime::Builder::new_current_thread()
1144                .enable_all()
1145                .build()
1146                .map_err(|e| e.to_string())?;
1147            runtime.block_on(crate::prebuilt_release::download_to(
1148                &version,
1149                &staging,
1150                cdn_base.as_ref(),
1151            ))
1152        })
1153        .map_err(|e| e.to_string())?
1154        .join()
1155        .map_err(|_| "prebuilt update worker failed".to_string())?
1156}
1157
1158pub(crate) fn validate_downloaded_rpi(
1159    path: &Path,
1160    staging: &Path,
1161    expected: &str,
1162) -> Result<(), String> {
1163    let found = validate_rpi_executable_version(path, staging, crate::VERSION, "downloaded rpi")?;
1164    if found.to_string() != expected {
1165        return Err(format!(
1166            "downloaded rpi version {found} does not match manifest {expected}"
1167        ));
1168    }
1169    Ok(())
1170}
1171
1172/// Cargo discovers `.cargo/config.toml` from its working directory upward.
1173/// Put update commands directly below the user's home directory so neither an
1174/// untrusted project, a project-local `CARGO_HOME`, nor a world-writable system
1175/// temp directory can join that discovery chain. Cargo still reads its
1176/// explicitly configured user-level home through its normal environment.
1177fn create_self_update_command_dir() -> Result<tempfile::TempDir, String> {
1178    let configured_root =
1179        dirs::home_dir().ok_or_else(|| "could not resolve the user home directory".to_string())?;
1180    if !configured_root.is_absolute() {
1181        return Err("user home must be absolute for self-update".to_string());
1182    }
1183    let canonical_root = std::fs::canonicalize(&configured_root)
1184        .map(normalize_windows_path)
1185        .map_err(|error| format!("could not canonicalize user home: {error}"))?;
1186    let metadata = std::fs::symlink_metadata(&canonical_root)
1187        .map_err(|error| format!("could not inspect user home: {error}"))?;
1188    if !metadata.is_dir() || metadata.file_type().is_symlink() {
1189        return Err("user home does not resolve to a real directory".to_string());
1190    }
1191    let current = std::env::current_dir()
1192        .and_then(std::fs::canonicalize)
1193        .map(normalize_windows_path)
1194        .map_err(|error| format!("could not validate the caller directory: {error}"))?;
1195    let project_root = current
1196        .ancestors()
1197        .find(|ancestor| std::fs::symlink_metadata(ancestor.join(".git")).is_ok())
1198        .map(Path::to_path_buf);
1199    validate_configured_cargo_home(project_root.as_deref())?;
1200    if project_root.as_deref().is_some_and(|root| {
1201        !windows_paths_equal(&canonical_root, root) && path_is_within(&canonical_root, root)
1202    }) {
1203        return Err(
1204            "refusing to create a self-update command directory inside the caller project"
1205                .to_string(),
1206        );
1207    }
1208    let directory = tempfile::Builder::new()
1209        .prefix("rpi-self-update-command-")
1210        .tempdir_in(&canonical_root)
1211        .map_err(|error| format!("could not allocate Cargo command directory: {error}"))?;
1212    validated_self_update_command_dir(directory.path())?;
1213    #[cfg(unix)]
1214    {
1215        use std::os::unix::fs::{MetadataExt, PermissionsExt};
1216
1217        let directory_metadata = std::fs::symlink_metadata(directory.path())
1218            .map_err(|error| format!("could not inspect Cargo command directory: {error}"))?;
1219        if metadata.uid() != directory_metadata.uid() || metadata.permissions().mode() & 0o022 != 0
1220        {
1221            return Err("user home is not private to the current account".to_string());
1222        }
1223    }
1224    Ok(directory)
1225}
1226
1227fn path_is_within(candidate: &Path, ancestor: &Path) -> bool {
1228    candidate
1229        .ancestors()
1230        .any(|component| windows_paths_equal(component, ancestor))
1231}
1232
1233fn validate_configured_cargo_home(project_root: Option<&Path>) -> Result<(), String> {
1234    let Some(configured) = std::env::var_os("CARGO_HOME") else {
1235        return Ok(());
1236    };
1237    let configured = PathBuf::from(configured);
1238    if !configured.is_absolute() {
1239        return Err("CARGO_HOME must be absolute for self-update".to_string());
1240    }
1241    let project_local = match project_root {
1242        Some(root) => cargo_home_is_project_local(&configured, root)?,
1243        None => {
1244            canonicalize_allow_missing(&configured, "CARGO_HOME")?;
1245            false
1246        }
1247    };
1248    if project_local {
1249        return Err("refusing project-local CARGO_HOME during self-update".to_string());
1250    }
1251    Ok(())
1252}
1253
1254fn cargo_home_is_project_local(configured: &Path, project_root: &Path) -> Result<bool, String> {
1255    if !configured.is_absolute() {
1256        return Err("CARGO_HOME must be absolute for self-update".to_string());
1257    }
1258    let configured = canonicalize_allow_missing(configured, "CARGO_HOME")?;
1259    Ok(path_is_within(&configured, project_root))
1260}
1261
1262fn canonicalize_allow_missing(path: &Path, label: &str) -> Result<PathBuf, String> {
1263    if path.components().any(|component| {
1264        matches!(
1265            component,
1266            std::path::Component::CurDir | std::path::Component::ParentDir
1267        )
1268    }) {
1269        return Err(format!("{label} contains relative path components"));
1270    }
1271    let mut existing = path;
1272    let mut missing = Vec::new();
1273    loop {
1274        match std::fs::symlink_metadata(existing) {
1275            Ok(_) => break,
1276            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1277                let name = existing
1278                    .file_name()
1279                    .ok_or_else(|| format!("could not resolve {label}"))?;
1280                missing.push(name.to_os_string());
1281                existing = existing
1282                    .parent()
1283                    .ok_or_else(|| format!("could not resolve {label}"))?;
1284            }
1285            Err(error) => return Err(format!("could not inspect {label}: {error}")),
1286        }
1287    }
1288    let mut canonical = std::fs::canonicalize(existing)
1289        .map(normalize_windows_path)
1290        .map_err(|error| format!("could not canonicalize {label}: {error}"))?;
1291    for component in missing.into_iter().rev() {
1292        canonical.push(component);
1293    }
1294    Ok(canonical)
1295}
1296
1297fn canonical_display(path: &Path) -> String {
1298    std::fs::canonicalize(path)
1299        .map(normalize_windows_path)
1300        .map(|path| path.display().to_string())
1301        .unwrap_or_else(|_| "<unresolvable>".to_string())
1302}
1303
1304fn validated_self_update_command_dir(path: &Path) -> Result<PathBuf, String> {
1305    if !path.is_absolute() {
1306        return Err("self-update command directory must be absolute".to_string());
1307    }
1308    let metadata = std::fs::symlink_metadata(path)
1309        .map_err(|error| format!("could not inspect self-update command directory: {error}"))?;
1310    if !metadata.is_dir() || metadata.file_type().is_symlink() {
1311        return Err("self-update command directory is not a real directory".to_string());
1312    }
1313    let canonical = std::fs::canonicalize(path)
1314        .map(normalize_windows_path)
1315        .map_err(|error| {
1316            format!("could not canonicalize self-update command directory: {error}")
1317        })?;
1318    Ok(canonical)
1319}
1320
1321#[cfg(not(windows))]
1322#[derive(Debug, Clone)]
1323struct DirectUpdatePlan {
1324    staging_dir: PathBuf,
1325    staged_exe: PathBuf,
1326    target_exe: PathBuf,
1327    replacement_temp: PathBuf,
1328    backup_file: PathBuf,
1329}
1330
1331#[cfg(not(windows))]
1332fn run_direct_self_update(
1333    build: bool,
1334    version: Option<&str>,
1335    cdn_base: Option<&reqwest::Url>,
1336) -> i32 {
1337    let staging = match create_self_update_staging_directory() {
1338        Ok(directory) => directory,
1339        Err(error) => {
1340            eprintln!("error: could not create self-update staging directory: {error}");
1341            return 1;
1342        }
1343    };
1344    if let Err(error) = prepare_self_update(staging.path(), build, version, cdn_base) {
1345        eprintln!("error: {error}");
1346        return 1;
1347    }
1348
1349    let current_exe = match std::env::current_exe() {
1350        Ok(path) => path,
1351        Err(error) => {
1352            eprintln!("error: could not resolve the current rpi executable: {error}");
1353            return 1;
1354        }
1355    };
1356    let plan = match build_direct_update_plan(staging.path(), &current_exe) {
1357        Ok(plan) => plan,
1358        Err(error) => {
1359            eprintln!("error: {error}");
1360            return 1;
1361        }
1362    };
1363    match activate_direct_update(&plan) {
1364        Ok(version) => {
1365            println!("rpi updated successfully to {version}");
1366            0
1367        }
1368        Err(error) => {
1369            eprintln!("error: {error}");
1370            1
1371        }
1372    }
1373}
1374
1375fn create_self_update_staging_directory() -> Result<tempfile::TempDir, String> {
1376    let agent = crate::config::agent_dir().map_err(|error| error.to_string())?;
1377    if !agent.is_absolute() {
1378        return Err("agent directory must be absolute".to_string());
1379    }
1380    std::fs::create_dir_all(&agent)
1381        .map_err(|error| format!("could not create {}: {error}", agent.display()))?;
1382    let agent = validated_real_directory(&agent, "agent directory")?;
1383    let update_root = agent.join("self-update");
1384    std::fs::create_dir_all(&update_root)
1385        .map_err(|error| format!("could not create {}: {error}", update_root.display()))?;
1386    let update_root = validated_real_directory(&update_root, "self-update root")?;
1387    let staging = tempfile::Builder::new()
1388        .prefix("pending-")
1389        .tempdir_in(&update_root)
1390        .map_err(|error| format!("could not allocate staging directory: {error}"))?;
1391    validated_real_directory(staging.path(), "self-update staging directory")?;
1392    Ok(staging)
1393}
1394
1395#[cfg(not(windows))]
1396fn build_direct_update_plan(
1397    staging_dir: &Path,
1398    target_exe: &Path,
1399) -> Result<DirectUpdatePlan, String> {
1400    let staging_dir = validated_real_directory(staging_dir, "self-update staging directory")?;
1401    let staged_exe = validated_regular_file(
1402        &staging_dir.join("bin").join(crate::APP_NAME),
1403        "staged rpi executable",
1404    )?;
1405    let target_exe = validated_regular_file(target_exe, "current rpi executable")?;
1406    let target_dir = validated_real_directory(
1407        target_exe
1408            .parent()
1409            .ok_or_else(|| "current executable has no parent directory".to_string())?,
1410        "current executable directory",
1411    )?;
1412    if target_exe.parent() != Some(target_dir.as_path()) {
1413        return Err("current executable is not a direct child of its validated directory".into());
1414    }
1415    let token = uuid::Uuid::new_v4().simple().to_string();
1416    let replacement_temp = target_dir.join(format!(".rpi-update-{token}.new"));
1417    let backup_file = target_dir.join(format!(".rpi-update-{token}.old"));
1418    if replacement_temp.exists() || backup_file.exists() {
1419        return Err("self-update replacement path collision".to_string());
1420    }
1421    Ok(DirectUpdatePlan {
1422        staging_dir,
1423        staged_exe,
1424        target_exe,
1425        replacement_temp,
1426        backup_file,
1427    })
1428}
1429
1430#[cfg(not(windows))]
1431fn activate_direct_update(plan: &DirectUpdatePlan) -> Result<semver::Version, String> {
1432    let staged_version = validate_rpi_executable_version(
1433        &plan.staged_exe,
1434        &plan.staging_dir,
1435        crate::VERSION,
1436        "staged rpi",
1437    )?;
1438    preflight_direct_replacement(plan)?;
1439
1440    let result = (|| {
1441        std::fs::copy(&plan.staged_exe, &plan.replacement_temp).map_err(|error| {
1442            format!("could not copy staged rpi beside the current executable: {error}")
1443        })?;
1444        validated_regular_file(&plan.replacement_temp, "replacement rpi executable")?;
1445        let copied_version = validate_rpi_executable_version(
1446            &plan.replacement_temp,
1447            plan.target_exe
1448                .parent()
1449                .ok_or_else(|| "current executable has no parent directory".to_string())?,
1450            crate::VERSION,
1451            "replacement rpi",
1452        )?;
1453        if copied_version != staged_version
1454            || !files_are_identical(&plan.staged_exe, &plan.replacement_temp)?
1455        {
1456            return Err(
1457                "replacement rpi does not match the validated staged executable".to_string(),
1458            );
1459        }
1460
1461        std::fs::hard_link(&plan.target_exe, &plan.backup_file)
1462            .map_err(|error| format!("could not preserve the current rpi executable: {error}"))?;
1463        let installed_version = validate_rpi_executable_version(
1464            &plan.backup_file,
1465            plan.target_exe
1466                .parent()
1467                .ok_or_else(|| "current executable has no parent directory".to_string())?,
1468            crate::VERSION,
1469            "current rpi",
1470        )?;
1471        if staged_version < installed_version {
1472            return Err(format!(
1473                "refusing to replace rpi {installed_version} with older version {staged_version}"
1474            ));
1475        }
1476        if !files_are_identical(&plan.target_exe, &plan.backup_file)? {
1477            return Err("current rpi executable changed while preparing the update".to_string());
1478        }
1479
1480        std::fs::rename(&plan.replacement_temp, &plan.target_exe).map_err(|error| {
1481            format!("could not atomically replace the current rpi executable: {error}")
1482        })?;
1483        Ok(())
1484    })();
1485
1486    if let Err(error) = result {
1487        let _ = remove_file_if_exists(&plan.replacement_temp);
1488        let _ = remove_file_if_exists(&plan.backup_file);
1489        return Err(error);
1490    }
1491
1492    let validation = (|| {
1493        if !files_are_identical(&plan.staged_exe, &plan.target_exe)? {
1494            return Err("updated rpi executable does not match the staged executable".to_string());
1495        }
1496        let updated_version = validate_rpi_executable_version(
1497            &plan.target_exe,
1498            plan.target_exe
1499                .parent()
1500                .ok_or_else(|| "current executable has no parent directory".to_string())?,
1501            crate::VERSION,
1502            "updated rpi",
1503        )?;
1504        if updated_version != staged_version {
1505            return Err(format!(
1506                "updated rpi reported version {updated_version}, expected {staged_version}"
1507            ));
1508        }
1509        Ok(())
1510    })();
1511
1512    if let Err(error) = validation {
1513        return Err(rollback_direct_update(plan, &error));
1514    }
1515    let _ = remove_file_if_exists(&plan.backup_file);
1516    Ok(staged_version)
1517}
1518
1519#[cfg(not(windows))]
1520fn preflight_direct_replacement(plan: &DirectUpdatePlan) -> Result<(), String> {
1521    for path in [&plan.replacement_temp, &plan.backup_file] {
1522        if path.exists() {
1523            return Err(format!(
1524                "self-update path already exists: {}",
1525                path.display()
1526            ));
1527        }
1528        let file = std::fs::OpenOptions::new()
1529            .write(true)
1530            .create_new(true)
1531            .open(path)
1532            .map_err(|error| format!("cannot write beside the current executable: {error}"))?;
1533        drop(file);
1534        std::fs::remove_file(path)
1535            .map_err(|error| format!("could not remove self-update probe: {error}"))?;
1536    }
1537    Ok(())
1538}
1539
1540#[cfg(not(windows))]
1541fn rollback_direct_update(plan: &DirectUpdatePlan, failure: &str) -> String {
1542    let _ = remove_file_if_exists(&plan.replacement_temp);
1543    match std::fs::rename(&plan.backup_file, &plan.target_exe) {
1544        Ok(()) => format!("{failure}; restored the previous rpi executable"),
1545        Err(rollback) => format!(
1546            "{failure}; automatic rollback failed ({rollback}); the previous executable remains at {}",
1547            plan.backup_file.display()
1548        ),
1549    }
1550}
1551
1552fn remove_file_if_exists(path: &Path) -> Result<(), String> {
1553    match std::fs::remove_file(path) {
1554        Ok(()) => Ok(()),
1555        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
1556        Err(error) => Err(error.to_string()),
1557    }
1558}
1559
1560#[cfg(windows)]
1561#[derive(Debug, Clone)]
1562struct WindowsUpdatePlan {
1563    staging_dir: PathBuf,
1564    staged_exe: PathBuf,
1565    target_exe: PathBuf,
1566    helper_script: PathBuf,
1567    status_file: PathBuf,
1568    replacement_temp: PathBuf,
1569    backup_file: PathBuf,
1570    rollback_displaced_file: PathBuf,
1571}
1572
1573#[cfg(windows)]
1574struct WindowsUpdateStaging {
1575    directory: tempfile::TempDir,
1576    status_file: PathBuf,
1577}
1578
1579#[cfg(windows)]
1580const WINDOWS_UPDATE_HELPER: &str = r#"param(
1581    [Parameter(Mandatory = $true)][long] $ParentPid,
1582    [Parameter(Mandatory = $true)][string] $StagingPath,
1583    [Parameter(Mandatory = $true)][string] $StagedPath,
1584    [Parameter(Mandatory = $true)][string] $StagedVersion,
1585    [Parameter(Mandatory = $true)][string] $TargetPath,
1586    [Parameter(Mandatory = $true)][string] $TempPath,
1587    [Parameter(Mandatory = $true)][string] $BackupPath,
1588    [Parameter(Mandatory = $true)][string] $RollbackDisplacedPath,
1589    [Parameter(Mandatory = $true)][string] $StatusPath
1590)
1591
1592Set-StrictMode -Version Latest
1593$ErrorActionPreference = 'Stop'
1594
1595function Write-UpdateStatus {
1596    param([string] $State, [string] $Message)
1597    $record = [ordered]@{
1598        state = $State
1599        message = $Message
1600        parentPid = $ParentPid
1601        staging = $StagingPath
1602        target = $TargetPath
1603        staged = $StagedPath
1604        stagedVersion = $StagedVersion
1605        backup = $BackupPath
1606        rollbackDisplaced = $RollbackDisplacedPath
1607        updatedAt = [DateTime]::UtcNow.ToString('o')
1608    }
1609    $json = $record | ConvertTo-Json -Compress
1610    $statusTemp = $StatusPath + '.tmp'
1611    [IO.File]::WriteAllText($statusTemp, $json, [Text.UTF8Encoding]::new($false))
1612    Move-Item -LiteralPath $statusTemp -Destination $StatusPath -Force
1613}
1614
1615function Assert-RegularFile {
1616    param([string] $Path, [string] $Label)
1617    $item = Get-Item -LiteralPath $Path -Force
1618    if ($item.PSIsContainer -or $item.Length -le 0 -or
1619        (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0)) {
1620        throw "$Label is not a non-empty regular file"
1621    }
1622}
1623
1624function Assert-WindowsExecutable {
1625    param([string] $Path, [string] $Label)
1626    Assert-RegularFile -Path $Path -Label $Label
1627    $stream = [IO.File]::OpenRead($Path)
1628    try {
1629        if ($stream.ReadByte() -ne 77 -or $stream.ReadByte() -ne 90) {
1630            throw "$Label is not a Windows executable"
1631        }
1632    } finally {
1633        $stream.Dispose()
1634    }
1635}
1636
1637function Assert-RealDirectory {
1638    param([string] $Path, [string] $Label)
1639    $item = Get-Item -LiteralPath $Path -Force
1640    if (-not $item.PSIsContainer -or
1641        (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0)) {
1642        throw "$Label is not a real directory"
1643    }
1644}
1645
1646function Get-FileSha256 {
1647    param([string] $Path)
1648    $stream = [IO.File]::OpenRead($Path)
1649    try {
1650        $sha256 = [Security.Cryptography.SHA256]::Create()
1651        try {
1652            return ([BitConverter]::ToString($sha256.ComputeHash($stream))).Replace('-', '')
1653        } finally {
1654            $sha256.Dispose()
1655        }
1656    } finally {
1657        $stream.Dispose()
1658    }
1659}
1660
1661function Remove-StagingPayload {
1662    try {
1663        $root = [IO.Path]::GetFullPath($StagingPath)
1664        Assert-RealDirectory -Path $root -Label 'self-update staging directory'
1665        $bin = [IO.Path]::Combine($root, 'bin')
1666        $helper = [IO.Path]::Combine($root, 'apply-update.ps1')
1667        foreach ($file in @(
1668            $StagedPath,
1669            [IO.Path]::Combine($root, '.crates.toml'),
1670            [IO.Path]::Combine($root, '.crates2.json'),
1671            $helper
1672        )) {
1673            if ([IO.File]::Exists($file)) {
1674                [IO.File]::Delete($file)
1675            }
1676        }
1677        if ([IO.Directory]::Exists($bin) -and
1678            [IO.Directory]::GetFileSystemEntries($bin).Length -eq 0) {
1679            [IO.Directory]::Delete($bin, $false)
1680        }
1681        if ([IO.Directory]::Exists($root) -and
1682            [IO.Directory]::GetFileSystemEntries($root).Length -eq 0) {
1683            [IO.Directory]::Delete($root, $false)
1684        }
1685    } catch {
1686        # Cleanup is best-effort; update status and recovery files stay intact.
1687    }
1688}
1689
1690$replaced = $false
1691try {
1692    $stagingFull = [IO.Path]::GetFullPath($StagingPath)
1693    $stagedFull = [IO.Path]::GetFullPath($StagedPath)
1694    $targetFull = [IO.Path]::GetFullPath($TargetPath)
1695    $tempFull = [IO.Path]::GetFullPath($TempPath)
1696    $backupFull = [IO.Path]::GetFullPath($BackupPath)
1697    $rollbackDisplacedFull = [IO.Path]::GetFullPath($RollbackDisplacedPath)
1698    $helperFull = [IO.Path]::Combine($stagingFull, 'apply-update.ps1')
1699    $statusFull = [IO.Path]::GetFullPath($StatusPath)
1700    $targetDirectory = [IO.Path]::GetDirectoryName($targetFull)
1701    if (-not [StringComparer]::OrdinalIgnoreCase.Equals(
1702            [IO.Path]::GetDirectoryName([IO.Path]::GetDirectoryName($stagedFull)), $stagingFull) -or
1703        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1704            [IO.Path]::GetDirectoryName($helperFull), $stagingFull) -or
1705        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1706            [IO.Path]::GetFullPath($PSScriptRoot), $stagingFull) -or
1707        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1708            [IO.Path]::GetDirectoryName($statusFull), [IO.Path]::GetDirectoryName($stagingFull)) -or
1709        [string]::IsNullOrWhiteSpace($targetDirectory) -or
1710        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1711            [IO.Path]::GetDirectoryName($tempFull), $targetDirectory) -or
1712        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1713            [IO.Path]::GetDirectoryName($backupFull), $targetDirectory) -or
1714        -not [StringComparer]::OrdinalIgnoreCase.Equals(
1715            [IO.Path]::GetDirectoryName($rollbackDisplacedFull), $targetDirectory)) {
1716        throw 'self-update paths are outside their validated staging or target directories'
1717    }
1718
1719    Assert-RealDirectory -Path $stagingFull -Label 'self-update staging directory'
1720    Assert-RealDirectory -Path $targetDirectory -Label 'target directory'
1721    Assert-WindowsExecutable -Path $stagedFull -Label 'staged executable'
1722    Assert-WindowsExecutable -Path $targetFull -Label 'current executable'
1723    $expectedHash = Get-FileSha256 -Path $stagedFull
1724    $originalTargetHash = Get-FileSha256 -Path $targetFull
1725    if ([IO.File]::Exists($tempFull) -or [IO.File]::Exists($backupFull) -or
1726        [IO.File]::Exists($rollbackDisplacedFull)) {
1727        throw 'replacement, backup, or rollback path already exists'
1728    }
1729
1730    Write-UpdateStatus -State 'waiting' -Message 'waiting for the current rpi process to exit'
1731    if ($ParentPid -lt 1 -or $ParentPid -gt [int]::MaxValue) {
1732        throw 'parent process id is outside the supported Windows range'
1733    }
1734    $parentProcess = $null
1735    try {
1736        $candidate = [Diagnostics.Process]::GetProcessById([int]$ParentPid)
1737        try {
1738            $candidatePath = [IO.Path]::GetFullPath($candidate.MainModule.FileName)
1739            if ([StringComparer]::OrdinalIgnoreCase.Equals($candidatePath, $targetFull)) {
1740                $parentProcess = $candidate
1741            } else {
1742                $candidate.Dispose()
1743            }
1744        } catch {
1745            if ($candidate.HasExited) {
1746                $candidate.Dispose()
1747            } else {
1748                throw
1749            }
1750        }
1751    } catch [ArgumentException] {
1752        # The invoking process exited before the helper acquired its handle.
1753    }
1754    if ($null -ne $parentProcess) {
1755        try {
1756            if (-not $parentProcess.WaitForExit(600000)) {
1757                throw 'timed out waiting for the current rpi process to exit'
1758            }
1759        } finally {
1760            $parentProcess.Dispose()
1761        }
1762    }
1763
1764    Assert-RealDirectory -Path $targetDirectory -Label 'target directory'
1765    Assert-WindowsExecutable -Path $stagedFull -Label 'staged executable'
1766    Assert-WindowsExecutable -Path $targetFull -Label 'current executable'
1767    if ((Get-FileSha256 -Path $stagedFull) -ne $expectedHash) {
1768        throw 'staged executable changed while waiting for rpi to exit'
1769    }
1770    if ((Get-FileSha256 -Path $targetFull) -ne $originalTargetHash) {
1771        throw 'current executable changed while waiting for rpi to exit'
1772    }
1773    if ([IO.File]::Exists($tempFull) -or [IO.File]::Exists($backupFull) -or
1774        [IO.File]::Exists($rollbackDisplacedFull)) {
1775        throw 'replacement, backup, or rollback path appeared while waiting for rpi to exit'
1776    }
1777
1778    [IO.File]::Copy($stagedFull, $tempFull, $false)
1779    Assert-WindowsExecutable -Path $tempFull -Label 'replacement executable'
1780    if ((Get-FileSha256 -Path $tempFull) -ne $expectedHash) {
1781        throw 'replacement executable hash mismatch'
1782    }
1783
1784    [IO.File]::Replace($tempFull, $targetFull, $backupFull, $true)
1785    $replaced = $true
1786    Assert-WindowsExecutable -Path $targetFull -Label 'updated executable'
1787    if ((Get-FileSha256 -Path $targetFull) -ne $expectedHash) {
1788        throw 'updated executable hash mismatch'
1789    }
1790} catch {
1791    $failureMessage = $_.Exception.Message
1792    $recoveryMessage = ''
1793    if ($replaced -and [IO.File]::Exists($BackupPath)) {
1794        try {
1795            [IO.File]::Copy($BackupPath, $TempPath, $false)
1796            Assert-WindowsExecutable -Path $TempPath -Label 'rollback executable'
1797            if ((Get-FileSha256 -Path $TempPath) -ne $originalTargetHash) {
1798                throw 'rollback executable hash mismatch'
1799            }
1800            [IO.File]::Replace($TempPath, $TargetPath, $RollbackDisplacedPath, $true)
1801            Assert-WindowsExecutable -Path $TargetPath -Label 'restored executable'
1802            if ((Get-FileSha256 -Path $TargetPath) -ne $originalTargetHash) {
1803                throw 'restored executable hash mismatch'
1804            }
1805            $replaced = $false
1806            try { [IO.File]::Delete($BackupPath) } catch {}
1807            try { [IO.File]::Delete($RollbackDisplacedPath) } catch {}
1808        } catch {
1809            $rollbackFailure = $_.Exception.Message
1810            if ([IO.File]::Exists($BackupPath)) {
1811                $recoveryMessage = "; automatic rollback failed ($rollbackFailure); the original executable remains at $BackupPath"
1812            } else {
1813                $recoveryMessage = "; automatic rollback failed ($rollbackFailure) and no verified recovery backup remains"
1814            }
1815        }
1816    }
1817    if ([IO.File]::Exists($TempPath)) {
1818        try { Remove-Item -LiteralPath $TempPath -Force } catch {}
1819    }
1820    try { Write-UpdateStatus -State 'failed' -Message ($failureMessage + $recoveryMessage) } catch {}
1821    Remove-StagingPayload
1822    exit 1
1823}
1824
1825try { Write-UpdateStatus -State 'succeeded' -Message 'rpi executable replaced successfully' } catch {}
1826if ([IO.File]::Exists($BackupPath)) {
1827    try { Remove-Item -LiteralPath $BackupPath -Force } catch {}
1828}
1829Remove-StagingPayload
1830exit 0
1831"#;
1832
1833#[cfg(windows)]
1834fn run_windows_self_update(
1835    build: bool,
1836    version: Option<&str>,
1837    cdn_base: Option<&reqwest::Url>,
1838) -> i32 {
1839    let staging = match create_windows_update_staging() {
1840        Ok(staging) => staging,
1841        Err(error) => {
1842            eprintln!("error: could not create self-update staging directory: {error}");
1843            return 1;
1844        }
1845    };
1846    let staging_dir = staging.directory.path().to_path_buf();
1847    let status_file = staging.status_file.clone();
1848    let _ = write_windows_update_status(
1849        &status_file,
1850        "preparing",
1851        "installing the update into staging",
1852    );
1853
1854    let current_exe = match std::env::current_exe() {
1855        Ok(path) => path,
1856        Err(error) => {
1857            let message = format!("could not resolve the current rpi executable: {error}");
1858            let _ = write_windows_update_status(&status_file, "failed", &message);
1859            eprintln!("error: {message}");
1860            return 1;
1861        }
1862    };
1863    let powershell = match system_powershell_path() {
1864        Ok(path) => path,
1865        Err(error) => {
1866            let _ = write_windows_update_status(&status_file, "failed", &error);
1867            eprintln!("error: {error}");
1868            return 1;
1869        }
1870    };
1871
1872    if let Err(error) = prepare_self_update(&staging_dir, build, version, cdn_base) {
1873        let _ = write_windows_update_status(&status_file, "failed", &error);
1874        eprintln!("error: {error}");
1875        return 1;
1876    }
1877
1878    let plan = match build_windows_update_plan(&staging_dir, &current_exe, &status_file) {
1879        Ok(plan) => plan,
1880        Err(error) => {
1881            let _ = write_windows_update_status(&status_file, "failed", &error);
1882            eprintln!("error: {error}");
1883            return 1;
1884        }
1885    };
1886    let staged_version = match validate_staged_rpi(&plan) {
1887        Ok(version) => version,
1888        Err(error) => {
1889            let _ = write_windows_update_status(&plan.status_file, "failed", &error);
1890            eprintln!("error: {error}");
1891            return 1;
1892        }
1893    };
1894    if let Err(error) = preflight_windows_replacement(&plan) {
1895        let _ = write_windows_update_status(&plan.status_file, "failed", &error);
1896        eprintln!("error: {error}");
1897        return 1;
1898    }
1899    if let Err(error) = std::fs::write(&plan.helper_script, WINDOWS_UPDATE_HELPER.as_bytes()) {
1900        let message = format!("could not write the self-update helper: {error}");
1901        let _ = write_windows_update_status(&plan.status_file, "failed", &message);
1902        eprintln!("error: {message}");
1903        return 1;
1904    }
1905    if validated_regular_file(&plan.helper_script, "self-update helper").is_err() {
1906        let message = "self-update helper did not pass regular-file validation";
1907        let _ = write_windows_update_status(&plan.status_file, "failed", message);
1908        eprintln!("error: {message}");
1909        return 1;
1910    }
1911    let _ = write_windows_update_status(
1912        &plan.status_file,
1913        "scheduled",
1914        &format!("validated rpi {staged_version}; waiting to replace rpi after this process exits"),
1915    );
1916    let mut command = windows_update_helper_command(
1917        &powershell,
1918        &plan,
1919        std::process::id(),
1920        &staged_version.to_string(),
1921    );
1922    use std::os::windows::process::CommandExt;
1923    command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
1924    match command.spawn() {
1925        Ok(_) => {
1926            let persisted_staging = staging.directory.keep();
1927            println!(
1928                "rpi {staged_version} staged; quit this rpi and it will be applied.\n\
1929                 Status: {}",
1930                plan.status_file.display()
1931            );
1932            debug_assert!(windows_paths_equal(&persisted_staging, &plan.staging_dir));
1933            0
1934        }
1935        Err(error) => {
1936            let message = format!("could not start the self-update helper: {error}");
1937            let _ = write_windows_update_status(&plan.status_file, "failed", &message);
1938            eprintln!("error: {message}");
1939            1
1940        }
1941    }
1942}
1943
1944#[cfg(windows)]
1945fn create_windows_update_staging() -> Result<WindowsUpdateStaging, String> {
1946    let staging = create_self_update_staging_directory()?;
1947    let update_root = staging
1948        .path()
1949        .parent()
1950        .ok_or_else(|| "self-update staging directory has no parent".to_string())?;
1951    let status_file = update_root.join(format!("status-{}.json", uuid::Uuid::new_v4().simple()));
1952    if status_file.exists() {
1953        return Err("self-update status path collision".to_string());
1954    }
1955    Ok(WindowsUpdateStaging {
1956        directory: staging,
1957        status_file,
1958    })
1959}
1960
1961#[cfg(windows)]
1962fn build_windows_update_plan(
1963    staging_dir: &Path,
1964    target_exe: &Path,
1965    status_file: &Path,
1966) -> Result<WindowsUpdatePlan, String> {
1967    let staging_dir = validated_real_directory(staging_dir, "self-update staging directory")?;
1968    if !status_file.is_absolute() {
1969        return Err("self-update status path must be absolute".to_string());
1970    }
1971    let status_parent = validated_real_directory(
1972        status_file
1973            .parent()
1974            .ok_or_else(|| "self-update status path has no parent".to_string())?,
1975        "self-update status directory",
1976    )?;
1977    if staging_dir.parent() != Some(status_parent.as_path()) {
1978        return Err("self-update status file is outside the staging parent".to_string());
1979    }
1980    let status_name = status_file
1981        .file_name()
1982        .ok_or_else(|| "self-update status file has no name".to_string())?;
1983    if !is_self_update_status_name(status_name) {
1984        return Err("self-update status file has an invalid name".to_string());
1985    }
1986    if status_file.exists() {
1987        validated_regular_file(status_file, "self-update status file")?;
1988    }
1989    let staged_exe = validated_windows_executable(
1990        &staging_dir.join("bin").join("rpi.exe"),
1991        "staged rpi executable",
1992    )?;
1993    let target_exe = validated_windows_executable(target_exe, "current rpi executable")?;
1994    let target_dir = validated_real_directory(
1995        target_exe
1996            .parent()
1997            .ok_or_else(|| "current executable has no parent directory".to_string())?,
1998        "current executable directory",
1999    )?;
2000    if target_exe.parent() != Some(target_dir.as_path()) {
2001        return Err("current executable is not a direct child of its validated directory".into());
2002    }
2003    let token = uuid::Uuid::new_v4().simple().to_string();
2004    let replacement_temp = target_dir.join(format!(".rpi-update-{token}.new.exe"));
2005    let backup_file = target_dir.join(format!(".rpi-update-{token}.old.exe"));
2006    let rollback_displaced_file = target_dir.join(format!(".rpi-update-{token}.rollback-new.exe"));
2007    if replacement_temp.exists() || backup_file.exists() || rollback_displaced_file.exists() {
2008        return Err("self-update replacement path collision".to_string());
2009    }
2010
2011    Ok(WindowsUpdatePlan {
2012        staging_dir: staging_dir.clone(),
2013        staged_exe,
2014        target_exe,
2015        helper_script: staging_dir.join("apply-update.ps1"),
2016        status_file: status_file.to_path_buf(),
2017        replacement_temp,
2018        backup_file,
2019        rollback_displaced_file,
2020    })
2021}
2022
2023#[cfg(windows)]
2024fn preflight_windows_replacement(plan: &WindowsUpdatePlan) -> Result<(), String> {
2025    for path in [
2026        &plan.replacement_temp,
2027        &plan.backup_file,
2028        &plan.rollback_displaced_file,
2029    ] {
2030        if path.exists() {
2031            return Err(format!(
2032                "self-update path already exists: {}",
2033                path.display()
2034            ));
2035        }
2036        let file = std::fs::OpenOptions::new()
2037            .write(true)
2038            .create_new(true)
2039            .open(path)
2040            .map_err(|error| format!("cannot write beside the current executable: {error}"))?;
2041        drop(file);
2042        std::fs::remove_file(path)
2043            .map_err(|error| format!("could not remove self-update probe: {error}"))?;
2044    }
2045    Ok(())
2046}
2047
2048#[cfg(windows)]
2049fn validate_staged_rpi(plan: &WindowsUpdatePlan) -> Result<semver::Version, String> {
2050    let cwd = plan
2051        .helper_script
2052        .parent()
2053        .ok_or_else(|| "self-update staging directory is missing".to_string())?;
2054    validate_rpi_executable_version(&plan.staged_exe, cwd, crate::VERSION, "staged rpi")
2055}
2056
2057/// Captured output of a bounded self-update probe.
2058struct BoundedProcessOutput {
2059    status: std::process::ExitStatus,
2060    stdout: Vec<u8>,
2061    stderr: Vec<u8>,
2062}
2063
2064/// Run a short-lived probe under both a wall-clock and an output cap.
2065///
2066/// The child runs on its own thread and current-thread runtime so this stays
2067/// safe when `rpi update` is entered from inside a Tokio runtime. The old
2068/// implementation reused the npm bridge's process runner, which went away with
2069/// the Pi compatibility layer.
2070fn run_bounded_process_blocking(
2071    program: &str,
2072    args: &[String],
2073    cwd: &Path,
2074    timeout: std::time::Duration,
2075    max_output_bytes: usize,
2076) -> Result<BoundedProcessOutput, String> {
2077    let program = program.to_string();
2078    let args = args.to_vec();
2079    let cwd = cwd.to_path_buf();
2080    std::thread::Builder::new()
2081        .name("rpi-bounded-version-probe".to_string())
2082        .spawn(move || {
2083            let runtime = tokio::runtime::Builder::new_current_thread()
2084                .enable_all()
2085                .build()
2086                .map_err(|error| format!("probe runtime failed: {error}"))?;
2087            runtime.block_on(async move {
2088                let child = tokio::process::Command::new(&program)
2089                    .args(&args)
2090                    .current_dir(&cwd)
2091                    .stdin(std::process::Stdio::null())
2092                    .stdout(std::process::Stdio::piped())
2093                    .stderr(std::process::Stdio::piped())
2094                    .kill_on_drop(true)
2095                    .spawn()
2096                    .map_err(|error| format!("spawn failed: {error}"))?;
2097                let output = match tokio::time::timeout(timeout, child.wait_with_output()).await {
2098                    Ok(result) => result.map_err(|error| format!("wait failed: {error}"))?,
2099                    // Dropping the future drops the child, which `kill_on_drop`
2100                    // turns into a kill.
2101                    Err(_) => return Err(format!("timed out after {timeout:?}")),
2102                };
2103                Ok(BoundedProcessOutput {
2104                    status: output.status,
2105                    stdout: cap_bytes(output.stdout, max_output_bytes),
2106                    stderr: cap_bytes(output.stderr, max_output_bytes),
2107                })
2108            })
2109        })
2110        .map_err(|error| format!("probe thread failed: {error}"))?
2111        .join()
2112        .map_err(|_| "probe worker panicked".to_string())?
2113}
2114
2115fn cap_bytes(bytes: Vec<u8>, limit: usize) -> Vec<u8> {
2116    if bytes.len() <= limit {
2117        bytes
2118    } else {
2119        bytes[..limit].to_vec()
2120    }
2121}
2122
2123/// Byte-for-byte comparison, used to prove a copied or replaced rpi binary is
2124/// the one that was validated.
2125#[cfg(not(windows))]
2126fn files_are_identical(left: &Path, right: &Path) -> Result<bool, String> {
2127    use std::io::{BufReader, Read};
2128
2129    let left_file = std::fs::File::open(left)
2130        .map_err(|error| format!("could not open {}: {error}", left.display()))?;
2131    let right_file = std::fs::File::open(right)
2132        .map_err(|error| format!("could not open {}: {error}", right.display()))?;
2133    if left_file
2134        .metadata()
2135        .map_err(|error| error.to_string())?
2136        .len()
2137        != right_file
2138            .metadata()
2139            .map_err(|error| error.to_string())?
2140            .len()
2141    {
2142        return Ok(false);
2143    }
2144    let mut left = BufReader::new(left_file);
2145    let mut right = BufReader::new(right_file);
2146    let mut left_buffer = [0u8; 64 * 1024];
2147    let mut right_buffer = [0u8; 64 * 1024];
2148    loop {
2149        let left_read = left
2150            .read(&mut left_buffer)
2151            .map_err(|error| error.to_string())?;
2152        let right_read = right
2153            .read(&mut right_buffer)
2154            .map_err(|error| error.to_string())?;
2155        if left_read != right_read || left_buffer[..left_read] != right_buffer[..right_read] {
2156            return Ok(false);
2157        }
2158        if left_read == 0 {
2159            return Ok(true);
2160        }
2161    }
2162}
2163
2164fn validate_rpi_executable_version(
2165    executable: &Path,
2166    cwd: &Path,
2167    current: &str,
2168    label: &str,
2169) -> Result<semver::Version, String> {
2170    let program = executable
2171        .to_str()
2172        .ok_or_else(|| format!("{label} path cannot be represented as Unicode"))?;
2173    let args = vec!["--version".to_string()];
2174    let output = run_bounded_process_blocking(
2175        program,
2176        &args,
2177        cwd,
2178        STAGED_RPI_CHECK_TIMEOUT,
2179        MAX_STAGED_RPI_OUTPUT_BYTES,
2180    )
2181    .map_err(|error| format!("{label} version check failed: {error}"))?;
2182    if !output.status.success() {
2183        return Err(format!("{label} --version exited with {}", output.status));
2184    }
2185    validate_staged_rpi_version_output(&output.stdout, &output.stderr, current)
2186}
2187
2188fn validate_staged_rpi_version_output(
2189    stdout: &[u8],
2190    stderr: &[u8],
2191    current: &str,
2192) -> Result<semver::Version, String> {
2193    if !stderr.is_empty() {
2194        return Err("staged rpi --version wrote unexpected stderr output".to_string());
2195    }
2196    let staged = parse_rpi_version_output(stdout)
2197        .ok_or_else(|| "staged rpi returned an invalid --version response".to_string())?;
2198    let current = semver::Version::parse(current)
2199        .map_err(|_| "the running rpi version is not valid semantic versioning".to_string())?;
2200    if staged < current {
2201        return Err(format!(
2202            "refusing to replace rpi {current} with older version {staged}"
2203        ));
2204    }
2205    Ok(staged)
2206}
2207
2208fn parse_rpi_version_output(output: &[u8]) -> Option<semver::Version> {
2209    let output = std::str::from_utf8(output).ok()?;
2210    let line = output
2211        .strip_suffix("\r\n")
2212        .or_else(|| output.strip_suffix('\n'))
2213        .unwrap_or(output);
2214    if line.contains(['\r', '\n']) {
2215        return None;
2216    }
2217    let version = line.strip_prefix(crate::APP_NAME)?.strip_prefix(' ')?;
2218    if version.is_empty() || version.chars().any(char::is_whitespace) {
2219        return None;
2220    }
2221    semver::Version::parse(version).ok()
2222}
2223
2224/// A real directory *by its own entry*: the leaf is not a link, so the update
2225/// is free to write into it. Links further up are resolved rather than
2226/// refused — a launch path such as `C:\tools\current\rpi.exe` where `current`
2227/// is a junction names the real install directory, which is exactly what an
2228/// update should rewrite.
2229fn validated_real_directory(path: &Path, label: &str) -> Result<PathBuf, String> {
2230    if !path.is_absolute() {
2231        return Err(format!("{label} must be absolute"));
2232    }
2233    let metadata = std::fs::symlink_metadata(path)
2234        .map_err(|error| format!("could not inspect {label}: {error}"))?;
2235    if metadata.file_type().is_symlink() {
2236        return Err(format!(
2237            "{label} is a link or junction, not a real directory ({} -> {})",
2238            path.display(),
2239            canonical_display(path),
2240        ));
2241    }
2242    if !metadata.is_dir() {
2243        return Err(format!("{label} is not a real directory"));
2244    }
2245    std::fs::canonicalize(path)
2246        .map(normalize_windows_path)
2247        .map_err(|error| format!("could not canonicalize {label}: {error}"))
2248}
2249
2250/// A non-empty regular file *by its own entry*: a link to a file is refused
2251/// with both paths named, because replacing the link would leave the real
2252/// target stale. Ancestor links are resolved, as in
2253/// [`validated_real_directory`].
2254fn validated_regular_file(path: &Path, label: &str) -> Result<PathBuf, String> {
2255    if !path.is_absolute() {
2256        return Err(format!("{label} must be absolute"));
2257    }
2258    let metadata = std::fs::symlink_metadata(path)
2259        .map_err(|error| format!("could not inspect {label}: {error}"))?;
2260    if metadata.file_type().is_symlink() {
2261        return Err(format!(
2262            "{label} is a link or junction, not a non-empty regular file ({} -> {})",
2263            path.display(),
2264            canonical_display(path),
2265        ));
2266    }
2267    if !metadata.is_file() || metadata.len() == 0 {
2268        return Err(format!("{label} is not a non-empty regular file"));
2269    }
2270    std::fs::canonicalize(path)
2271        .map(normalize_windows_path)
2272        .map_err(|error| format!("could not canonicalize {label}: {error}"))
2273}
2274
2275fn is_self_update_status_name(name: &std::ffi::OsStr) -> bool {
2276    let Some(name) = name.to_str() else {
2277        return false;
2278    };
2279    let Some(token) = name
2280        .strip_prefix("status-")
2281        .and_then(|name| name.strip_suffix(".json"))
2282    else {
2283        return false;
2284    };
2285    token.len() == 32 && token.bytes().all(|byte| byte.is_ascii_hexdigit())
2286}
2287
2288/// `tempfile::Builder::new().prefix("pending-")` mints the rest of the name
2289/// from `[A-Za-z0-9]`. Requiring that shape keeps the pruning from ever
2290/// pointing `remove_dir_all` at a directory this tool did not create.
2291fn is_self_update_staging_name(name: &str) -> bool {
2292    let Some(suffix) = name.strip_prefix("pending-") else {
2293        return false;
2294    };
2295    !suffix.is_empty() && suffix.bytes().all(|byte| byte.is_ascii_alphanumeric())
2296}
2297
2298fn validated_self_update_status_file(update_root: &Path, path: &Path) -> Result<PathBuf, String> {
2299    if !path.is_absolute() || path.parent() != Some(update_root) {
2300        return Err("self-update status file is outside the update root".to_string());
2301    }
2302    if !path.file_name().is_some_and(is_self_update_status_name) {
2303        return Err("self-update status file has an invalid name".to_string());
2304    }
2305    let path = validated_regular_file(path, "self-update status file")?;
2306    let length = std::fs::metadata(&path)
2307        .map_err(|error| format!("could not inspect self-update status file: {error}"))?
2308        .len();
2309    if length > MAX_SELF_UPDATE_STATUS_BYTES {
2310        return Err("self-update status file is too large".to_string());
2311    }
2312    Ok(path)
2313}
2314
2315fn read_self_update_status(path: &Path) -> Option<SelfUpdateStatus> {
2316    use std::io::Read;
2317
2318    let file = std::fs::File::open(path).ok()?;
2319    let mut data = Vec::with_capacity(
2320        usize::try_from(MAX_SELF_UPDATE_STATUS_BYTES)
2321            .unwrap_or_default()
2322            .min(8 * 1024),
2323    );
2324    file.take(MAX_SELF_UPDATE_STATUS_BYTES.saturating_add(1))
2325        .read_to_end(&mut data)
2326        .ok()?;
2327    if data.len() as u64 > MAX_SELF_UPDATE_STATUS_BYTES {
2328        return None;
2329    }
2330    serde_json::from_slice(&data).ok()
2331}
2332
2333fn sanitized_self_update_status_message(message: &str) -> String {
2334    let mut sanitized = String::new();
2335    let mut pending_space = false;
2336    let mut truncated = false;
2337    for character in message.trim().chars() {
2338        if character.is_control() || character.is_whitespace() {
2339            pending_space = !sanitized.is_empty();
2340            continue;
2341        }
2342        if sanitized.chars().count() >= MAX_SELF_UPDATE_STATUS_MESSAGE_CHARS {
2343            truncated = true;
2344            break;
2345        }
2346        if pending_space {
2347            sanitized.push(' ');
2348            pending_space = false;
2349        }
2350        sanitized.push(character);
2351    }
2352    if sanitized.is_empty() {
2353        return "no diagnostic message was recorded".to_string();
2354    }
2355    if truncated {
2356        sanitized.push_str("...");
2357    }
2358    sanitized
2359}
2360
2361fn consume_self_update_statuses(agent_dir: &Path) -> Vec<UpdateWarning> {
2362    let _guard = SELF_UPDATE_STATUS_LOCK
2363        .lock()
2364        .unwrap_or_else(std::sync::PoisonError::into_inner);
2365    let agent_dir = match validated_real_directory(agent_dir, "agent directory") {
2366        Ok(path) => path,
2367        Err(_) => return Vec::new(),
2368    };
2369    let update_root = match validated_real_directory(
2370        &agent_dir.join("self-update"),
2371        "self-update status directory",
2372    ) {
2373        Ok(path) if path.parent() == Some(agent_dir.as_path()) => path,
2374        _ => return Vec::new(),
2375    };
2376    let entries = match std::fs::read_dir(&update_root) {
2377        Ok(entries) => entries,
2378        Err(_) => return Vec::new(),
2379    };
2380
2381    let now = now_ms();
2382    let mut warnings = Vec::new();
2383    // Every staging directory a live status file still claims.
2384    let mut claimed = BTreeSet::new();
2385    // Staging directories a status file proved to be debris: the helper that
2386    // would have installed from them is gone, so their on-disk age — which can
2387    // look recent when a run died early — does not have to vouch for them.
2388    let mut obsolete = BTreeSet::new();
2389    // Non-terminal records young enough that the writer is probably still
2390    // alive. Reconciled after the scan, once a terminal record could have
2391    // claimed the same directory.
2392    let mut undecided = Vec::new();
2393    for entry in entries.flatten() {
2394        if !is_self_update_status_name(&entry.file_name()) {
2395            continue;
2396        }
2397        let path = match validated_self_update_status_file(&update_root, &entry.path()) {
2398            Ok(path) => path,
2399            Err(_) => continue,
2400        };
2401        let Some(status) = read_self_update_status(&path) else {
2402            continue;
2403        };
2404        if !matches!(status.state.as_str(), "failed" | "succeeded") {
2405            // A record with no usable timestamp has an unknown age. Leaving it
2406            // alone is the safe reading: the alternative deletes a status file
2407            // that a live helper may still be writing.
2408            let stale = status.updated_at_ms > 0
2409                && now.saturating_sub(status.updated_at_ms) > STALE_SELF_UPDATE_STATUS_TTL_MS;
2410            if stale {
2411                if let Some(staging) = status.staging.as_deref() {
2412                    obsolete.insert(staging.to_path_buf());
2413                }
2414                let _ = remove_file_if_exists(&path);
2415            } else {
2416                undecided.push((path, status));
2417            }
2418            continue;
2419        }
2420        if let Some(staging) = status.staging.as_deref() {
2421            claimed.insert(staging.to_path_buf());
2422        }
2423
2424        if status.state == "succeeded" {
2425            // Kept as the durable record of what was installed. The path is
2426            // printed by `rpi update`, so deleting the file on the next start
2427            // made a finished update look like it had never run. It ages out
2428            // with the rest of the record set instead.
2429            let old = status.updated_at_ms > 0
2430                && now.saturating_sub(status.updated_at_ms) > COMPLETED_SELF_UPDATE_STATUS_TTL_MS;
2431            if old {
2432                if let Some(staging) = status.staging.as_deref() {
2433                    claimed.remove(staging);
2434                    obsolete.insert(staging.to_path_buf());
2435                }
2436                let _ = remove_file_if_exists(&path);
2437            }
2438            continue;
2439        }
2440
2441        match std::fs::remove_file(&path) {
2442            Ok(()) => {}
2443            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
2444            // A failure is still actionable even when cleanup is denied. Keep
2445            // the file so a later startup can retry consumption.
2446            Err(_) => {}
2447        }
2448        warnings.push(UpdateWarning {
2449            message: format!(
2450                "The previously scheduled rpi update failed: {}",
2451                sanitized_self_update_status_message(&status.message)
2452            ),
2453            command: "rpi update".to_string(),
2454        });
2455    }
2456
2457    // A non-terminal record whose staging directory a terminal record already
2458    // owns is a leftover of a completed run, not a live one.
2459    for (path, status) in undecided {
2460        let staging = status.staging.clone();
2461        if staging
2462            .as_deref()
2463            .is_some_and(|staging| claimed.contains(staging))
2464        {
2465            let _ = remove_file_if_exists(&path);
2466            continue;
2467        }
2468        if let Some(staging) = staging {
2469            claimed.insert(staging);
2470        }
2471    }
2472
2473    prune_self_update_staging(&update_root, &claimed, &obsolete, now);
2474    warnings
2475}
2476
2477/// Delete staging directories no live status file references.
2478///
2479/// A Windows update persists its staging directory (`TempDir::keep`) so the
2480/// helper can install from it after the parent exits. When the helper dies
2481/// first — a reboot at the wrong moment, a machine-wide `taskkill` — the
2482/// directory stays behind forever: nothing else in the update path removes it,
2483/// and because its status file was still `preparing` the next start never
2484/// looked at it either. Those are the directories that pile up in
2485/// `~/.rpi/agent/self-update`.
2486///
2487/// A directory a status file already proved dead (`obsolete`) goes as soon as
2488/// its name validates. Otherwise the evidence has to come from the directory
2489/// itself: empty debris goes unconditionally, because no update can be
2490/// mid-install in a directory with nothing in it, while a populated one waits
2491/// for the TTL. That keeps a staging directory whose record was just consumed —
2492/// and which a helper may still be reading — from being deleted underneath it.
2493fn prune_self_update_staging(
2494    update_root: &Path,
2495    claimed: &BTreeSet<PathBuf>,
2496    obsolete: &BTreeSet<PathBuf>,
2497    now: i64,
2498) {
2499    let Ok(entries) = std::fs::read_dir(update_root) else {
2500        return;
2501    };
2502    for entry in entries.flatten() {
2503        let name = entry.file_name();
2504        let Some(name) = name.to_str() else {
2505            continue;
2506        };
2507        if !is_self_update_staging_name(name) {
2508            continue;
2509        }
2510        let path = update_root.join(name);
2511        if claimed.contains(&path) {
2512            continue;
2513        }
2514        if validated_real_directory(&path, "self-update staging directory").is_err() {
2515            continue;
2516        }
2517        let aged_out = directory_age_ms(
2518            entry.metadata().ok().and_then(|meta| meta.modified().ok()),
2519            now,
2520        )
2521        .is_some_and(|age| age >= STALE_SELF_UPDATE_STATUS_TTL_MS);
2522        if obsolete.contains(&path) || !staging_holds_payload(&path) || aged_out {
2523            let _ = std::fs::remove_dir_all(&path);
2524        }
2525    }
2526}
2527
2528/// Whether a staging directory still holds something an install could use.
2529///
2530/// `cargo install --root <dir>` leaves zero-byte `.crates.toml` / `.crates2.json`
2531/// bookkeeping files behind even when it produced no binary, and the helper's
2532/// own cleanup deletes the payload first. So the presence of *a* file proves
2533/// nothing — a directory whose only contents are empty files is debris that can
2534/// never be installed from, and waiting out the TTL for it just keeps garbage
2535/// around. Only a non-empty file does, and the payload lives one level down in
2536/// `bin/`.
2537fn staging_holds_payload(path: &Path) -> bool {
2538    let Ok(entries) = std::fs::read_dir(path) else {
2539        return false;
2540    };
2541    for entry in entries.flatten() {
2542        let Ok(metadata) = entry.metadata() else {
2543            continue;
2544        };
2545        if metadata.is_file() {
2546            if metadata.len() > 0 {
2547                return true;
2548            }
2549            continue;
2550        }
2551        if metadata.is_dir()
2552            && std::fs::read_dir(entry.path()).is_ok_and(|nested| {
2553                nested.flatten().any(|nested| {
2554                    nested
2555                        .metadata()
2556                        .is_ok_and(|metadata| metadata.is_file() && metadata.len() > 0)
2557                })
2558            })
2559        {
2560            return true;
2561        }
2562    }
2563    false
2564}
2565
2566fn directory_age_ms(modified: Option<SystemTime>, now: i64) -> Option<i64> {
2567    let modified = modified?;
2568    let millis = modified.duration_since(UNIX_EPOCH).ok()?.as_millis();
2569    i64::try_from(millis).ok().map(|at| now.saturating_sub(at))
2570}
2571
2572#[cfg(windows)]
2573fn validated_windows_executable(path: &Path, label: &str) -> Result<PathBuf, String> {
2574    use std::io::Read;
2575
2576    let path = validated_regular_file(path, label)?;
2577    let mut file =
2578        std::fs::File::open(&path).map_err(|error| format!("could not open {label}: {error}"))?;
2579    let mut magic = [0u8; 2];
2580    file.read_exact(&mut magic)
2581        .map_err(|error| format!("could not read {label}: {error}"))?;
2582    if magic != *b"MZ" {
2583        return Err(format!("{label} is not a Windows executable"));
2584    }
2585    Ok(path)
2586}
2587
2588#[cfg(windows)]
2589fn system_powershell_path() -> Result<PathBuf, String> {
2590    use std::ffi::OsString;
2591    use std::os::windows::ffi::OsStringExt;
2592    use windows_sys::Win32::System::SystemInformation::GetWindowsDirectoryW;
2593
2594    let mut buffer = vec![0u16; 260];
2595    let system_root = loop {
2596        let length = unsafe {
2597            GetWindowsDirectoryW(
2598                buffer.as_mut_ptr(),
2599                u32::try_from(buffer.len()).unwrap_or(u32::MAX),
2600            )
2601        };
2602        if length == 0 {
2603            return Err(format!(
2604                "could not locate the Windows system directory: {}",
2605                std::io::Error::last_os_error()
2606            ));
2607        }
2608        let length = usize::try_from(length)
2609            .map_err(|error| format!("invalid Windows system directory length: {error}"))?;
2610        if length < buffer.len() {
2611            buffer.truncate(length);
2612            break PathBuf::from(OsString::from_wide(&buffer));
2613        }
2614        buffer.resize(length.saturating_add(1), 0);
2615    };
2616    let system_root = validated_real_directory(&system_root, "Windows system root")?;
2617    let powershell = validated_windows_executable(
2618        &system_root.join("System32/WindowsPowerShell/v1.0/powershell.exe"),
2619        "Windows PowerShell",
2620    )?;
2621    powershell
2622        .strip_prefix(&system_root)
2623        .map_err(|_| "Windows PowerShell is outside SystemRoot".to_string())?;
2624    Ok(powershell)
2625}
2626
2627#[cfg(windows)]
2628fn windows_update_helper_command(
2629    powershell: &Path,
2630    plan: &WindowsUpdatePlan,
2631    parent_pid: u32,
2632    staged_version: &str,
2633) -> std::process::Command {
2634    let mut command = std::process::Command::new(powershell);
2635    let powershell_modules = powershell
2636        .parent()
2637        .expect("validated PowerShell path has a parent")
2638        .join("Modules");
2639    command
2640        .args([
2641            "-NoLogo",
2642            "-NoProfile",
2643            "-NonInteractive",
2644            "-ExecutionPolicy",
2645            "Bypass",
2646            "-File",
2647        ])
2648        .arg(&plan.helper_script)
2649        .arg("-ParentPid")
2650        .arg(parent_pid.to_string())
2651        .arg("-StagingPath")
2652        .arg(&plan.staging_dir)
2653        .arg("-StagedPath")
2654        .arg(&plan.staged_exe)
2655        .arg("-StagedVersion")
2656        .arg(staged_version)
2657        .arg("-TargetPath")
2658        .arg(&plan.target_exe)
2659        .arg("-TempPath")
2660        .arg(&plan.replacement_temp)
2661        .arg("-BackupPath")
2662        .arg(&plan.backup_file)
2663        .arg("-RollbackDisplacedPath")
2664        .arg(&plan.rollback_displaced_file)
2665        .arg("-StatusPath")
2666        .arg(&plan.status_file)
2667        .current_dir(
2668            plan.status_file
2669                .parent()
2670                .expect("validated status path has an update-root parent"),
2671        )
2672        .env("PSModulePath", powershell_modules)
2673        .stdin(Stdio::null())
2674        .stdout(Stdio::null())
2675        .stderr(Stdio::null());
2676    command
2677}
2678
2679#[cfg(windows)]
2680fn write_windows_update_status(path: &Path, state: &str, message: &str) -> Result<(), String> {
2681    let data = serde_json::to_vec_pretty(&serde_json::json!({
2682        "state": state,
2683        "message": message,
2684        "parentPid": std::process::id(),
2685        "currentVersion": crate::VERSION,
2686        "updatedAtMs": now_ms(),
2687    }))
2688    .map_err(|error| error.to_string())?;
2689    std::fs::write(path, data)
2690        .map_err(|error| format!("could not write update status {}: {error}", path.display()))
2691}
2692
2693/// Machine-readable update inventory for the web UI.
2694///
2695/// The web UI needs the same answer as the startup notice without parsing
2696/// human-readable CLI output: installed versions, latest versions, and
2697/// whether each target can be updated from this install.
2698#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2699#[serde(rename_all = "camelCase")]
2700pub struct UpdateInventory {
2701    pub current_version: String,
2702    pub last_checked_at: i64,
2703    pub host: UpdateInventoryEntry,
2704    pub extensions: Vec<UpdateInventoryEntry>,
2705}
2706
2707#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2708#[serde(rename_all = "camelCase")]
2709pub struct UpdateInventoryEntry {
2710    pub name: String,
2711    pub current: String,
2712    #[serde(skip_serializing_if = "Option::is_none")]
2713    pub latest: Option<String>,
2714    pub updatable: bool,
2715    #[serde(skip_serializing_if = "Option::is_none")]
2716    pub reason: Option<String>,
2717}
2718
2719/// `rpi updates check --json`. Currently JSON is the only supported format so
2720/// callers get a stable contract; the command rejects other arguments rather
2721/// than silently inventing output.
2722pub async fn run_updates(args: &[String]) -> i32 {
2723    let refresh = match args {
2724        [command, flag] if command == "check" && flag == "--json" => false,
2725        [command, flag] if command == "refresh" && flag == "--json" => true,
2726        _ => {
2727            eprintln!("error: `rpi updates` accepts `check --json` or `refresh --json`");
2728            return 2;
2729        }
2730    };
2731    if refresh && !update_checks_disabled() {
2732        if let Ok(agent_dir) = crate::config::agent_dir() {
2733            refresh_update_cache(&agent_dir, startup_http_client()).await;
2734        }
2735    }
2736    let inventory = build_inventory_from_cache();
2737    match serde_json::to_string_pretty(&inventory) {
2738        Ok(json) => {
2739            println!("{json}");
2740            0
2741        }
2742        Err(error) => {
2743            eprintln!("error: could not serialize update inventory: {error}");
2744            1
2745        }
2746    }
2747}
2748
2749fn build_inventory_from_cache() -> UpdateInventory {
2750    let cache = crate::config::agent_dir()
2751        .ok()
2752        .and_then(|dir| read_cache(&dir.join(CACHE_FILE)))
2753        .unwrap_or_default();
2754    let host_latest = cache
2755        .rpi_latest
2756        .as_ref()
2757        .filter(|latest| is_newer(crate::VERSION, latest))
2758        .cloned();
2759    UpdateInventory {
2760        current_version: crate::VERSION.to_owned(),
2761        last_checked_at: cache.checked_at,
2762        host: UpdateInventoryEntry {
2763            name: "rpi".into(),
2764            current: crate::VERSION.into(),
2765            updatable: host_latest.is_some(),
2766            latest: host_latest,
2767            reason: None,
2768        },
2769        extensions: installed_extension_inventory(
2770            &cache,
2771            crate::install::installed_native_packages(),
2772        ),
2773    }
2774}
2775
2776fn installed_extension_inventory(
2777    cache: &UpdateCache,
2778    packages: impl IntoIterator<Item = crate::install::InstalledNativePackage>,
2779) -> Vec<UpdateInventoryEntry> {
2780    packages
2781        .into_iter()
2782        .map(|package| {
2783            let supports_update = package.supports_registry_update();
2784            let latest = cache
2785                .native_packages
2786                .get(&native_cache_key(&package))
2787                .filter(|latest| supports_update && is_newer(&package.version, latest))
2788                .cloned();
2789            UpdateInventoryEntry {
2790                name: package.name.clone(),
2791                current: package.version,
2792                updatable: latest.is_some(),
2793                latest,
2794                reason: (!supports_update).then(|| "local-install".into()),
2795            }
2796        })
2797        .collect()
2798}
2799
2800#[cfg(test)]
2801mod tests {
2802    #[test]
2803    fn update_inventory_reports_registry_updates_and_skips_local_installs() {
2804        let registry = crate::install::InstalledNativePackage {
2805            name: "registry-ext".into(),
2806            version: "1.0.0".into(),
2807            source: None,
2808            prebuilt: None,
2809            artifacts: Vec::new(),
2810        };
2811        let local = crate::install::InstalledNativePackage {
2812            name: "local-ext".into(),
2813            version: "1.0.0".into(),
2814            source: Some("local:preview".into()),
2815            prebuilt: None,
2816            artifacts: Vec::new(),
2817        };
2818        let cache = super::UpdateCache {
2819            native_packages: std::collections::BTreeMap::from([
2820                ("registry-ext".into(), "1.2.0".into()),
2821                ("local-ext".into(), "2.0.0".into()),
2822            ]),
2823            ..super::UpdateCache::default()
2824        };
2825        let entries = super::installed_extension_inventory(&cache, vec![registry, local]);
2826        assert_eq!(entries.len(), 2);
2827        assert_eq!(entries[0].name, "registry-ext");
2828        assert_eq!(entries[0].latest.as_deref(), Some("1.2.0"));
2829        assert!(entries[0].updatable);
2830        assert_eq!(entries[0].reason, None);
2831        assert_eq!(entries[1].name, "local-ext");
2832        assert_eq!(entries[1].reason.as_deref(), Some("local-install"));
2833        assert!(!entries[1].updatable);
2834    }
2835
2836    #[test]
2837    fn extension_update_notices_unify_commands_and_separate_source_caches() {
2838        let _guard = crate::config::test_support::env_lock()
2839            .lock()
2840            .unwrap_or_else(|p| p.into_inner());
2841        let agent = tempfile::tempdir().unwrap();
2842        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
2843        std::env::set_var(crate::config::CONFIG_DIR_ENV, agent.path());
2844        let record: crate::install::InstalledNativePackage = serde_json::from_value(serde_json::json!({
2845            "name":"demo", "version":"1.0.0", "source":"prebuilt:https://github.com/owner/repo", "artifacts":["custom.dll"],
2846            "prebuilt":{"repository":"https://github.com/owner/repo","target":"x86_64-pc-windows-msvc",
2847                "manifest_sha256":"a".repeat(64),"source_commit":"b".repeat(40),"sdk_version":"0.3.23","plugin_abi":4,
2848                "archive_sha256":"c".repeat(64),"library_sha256":"d".repeat(64),"custom_repository":true}
2849        })).unwrap();
2850        std::fs::write(
2851            agent.path().join("native-packages.json"),
2852            serde_json::to_vec(&[record.clone()]).unwrap(),
2853        )
2854        .unwrap();
2855        let mut cache = super::UpdateCache::default();
2856        cache.native_packages.insert("demo".into(), "99.0.0".into()); // old Cargo source cannot supply a prebuilt update
2857        assert!(super::report_from_cache(&cache).notices.is_empty());
2858        cache
2859            .native_packages
2860            .insert(super::native_cache_key(&record), "2.0.0".into());
2861        let report = super::report_from_cache(&cache);
2862        assert_eq!(report.notices.len(), 1);
2863        assert_eq!(report.notices[0].latest, "2.0.0");
2864        assert_eq!(report.notices[0].command, "rpi extension update demo");
2865        let mut other = record.clone();
2866        other.prebuilt.as_mut().unwrap().repository = "https://github.com/another/repo".into();
2867        assert_ne!(
2868            super::native_cache_key(&record),
2869            super::native_cache_key(&other)
2870        );
2871
2872        // A successful install updates the registry. A cached remote version
2873        // must no longer advertise an update after that version is installed.
2874        let mut updated = record.clone();
2875        updated.version = "2.0.0".into();
2876        std::fs::write(
2877            agent.path().join("native-packages.json"),
2878            serde_json::to_vec(&[updated]).unwrap(),
2879        )
2880        .unwrap();
2881        assert!(super::report_from_cache(&cache).notices.is_empty());
2882        other = record.clone();
2883        other.prebuilt.as_mut().unwrap().custom_repository = false;
2884        assert_ne!(
2885            super::native_cache_key(&record),
2886            super::native_cache_key(&other)
2887        );
2888        let mut cargo = record.clone();
2889        cargo.source = None;
2890        cargo.prebuilt = None;
2891        for (package, command) in [
2892            (other, "rpi extension update demo"),
2893            (cargo, "rpi extension update demo"),
2894        ] {
2895            cache
2896                .native_packages
2897                .insert(super::native_cache_key(&package), "2.0.0".into());
2898            std::fs::write(
2899                agent.path().join("native-packages.json"),
2900                serde_json::to_vec(&[package]).unwrap(),
2901            )
2902            .unwrap();
2903            let report = super::report_from_cache(&cache);
2904            assert_eq!(report.notices.len(), 1);
2905            assert_eq!(report.notices[0].command, command);
2906        }
2907    }
2908
2909    /// Fixtures may live under an ambient TEMP that is itself a junction
2910    /// (e.g. `D:\Temp` on some Windows hosts). Ancestor links are resolved by
2911    /// the path validation rather than refused, so a plain `tempdir()` is a
2912    /// valid fixture — and using one keeps these tests honest about that.
2913    fn real_tempdir() -> tempfile::TempDir {
2914        tempfile::Builder::new()
2915            .prefix("rpi-update-test-")
2916            .tempdir()
2917            .unwrap()
2918    }
2919
2920    /// The path a fixture resolves to once production validation has seen it.
2921    ///
2922    /// Every validated call site canonicalizes and normalizes a path before it
2923    /// stores or compares it, so a test asserting against a production-derived
2924    /// path has to resolve its own fixture the same way. `real_tempdir()` stays
2925    /// unresolved on purpose — that is what keeps these tests honest about an
2926    /// ambient temp root that is itself a link — but on macOS `/var` is a link
2927    /// to `/private/var`, so the raw fixture path and the resolved production
2928    /// path are different strings for the same directory. Comparing them
2929    /// directly fails for a reason that has nothing to do with the code under
2930    /// test, and does so only on hosts whose temp root is reached through a
2931    /// link, which is why a Linux-only CI never saw it.
2932    fn as_production_resolves(path: &Path) -> std::path::PathBuf {
2933        super::normalize_windows_path(std::fs::canonicalize(path).unwrap())
2934    }
2935
2936    use std::collections::BTreeMap;
2937    use std::ffi::OsString;
2938    use std::path::Path;
2939    use std::sync::atomic::{AtomicUsize, Ordering};
2940    use std::sync::Arc;
2941
2942    #[cfg(unix)]
2943    use super::{activate_direct_update, build_direct_update_plan};
2944    #[cfg(windows)]
2945    use super::{
2946        build_windows_update_plan, preflight_windows_replacement, system_powershell_path,
2947        windows_update_helper_command, write_windows_update_status, WINDOWS_UPDATE_HELPER,
2948    };
2949    use super::{
2950        cargo_home_is_project_local, cargo_install_command, collect_bounded,
2951        create_self_update_command_dir, fetch_crates_url, is_newer, parse_rpi_version_output,
2952        path_is_within, results_with_individual_cache_fallback, validate_staged_rpi_version_output,
2953        RegistryLookup, CACHE_FALLBACK_MAX_AGE_MS, UPDATE_CHECK_CONCURRENCY,
2954    };
2955
2956    struct RestoreConfigDir(Option<OsString>);
2957
2958    impl Drop for RestoreConfigDir {
2959        fn drop(&mut self) {
2960            match self.0.take() {
2961                Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
2962                None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
2963            }
2964        }
2965    }
2966
2967    struct RestoreEnv {
2968        name: &'static str,
2969        value: Option<OsString>,
2970    }
2971
2972    impl RestoreEnv {
2973        fn capture(name: &'static str) -> Self {
2974            Self {
2975                name,
2976                value: std::env::var_os(name),
2977            }
2978        }
2979    }
2980
2981    impl Drop for RestoreEnv {
2982        fn drop(&mut self) {
2983            match self.value.take() {
2984                Some(value) => std::env::set_var(self.name, value),
2985                None => std::env::remove_var(self.name),
2986            }
2987        }
2988    }
2989
2990    #[cfg(windows)]
2991    fn fake_windows_executable(path: &Path, marker: &[u8]) {
2992        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
2993        let mut bytes = b"MZ".to_vec();
2994        bytes.extend_from_slice(marker);
2995        std::fs::write(path, bytes).unwrap();
2996    }
2997
2998    #[cfg(unix)]
2999    fn fake_unix_rpi(path: &Path, version: &str, fail_after_rename_to: Option<&str>) {
3000        use std::os::unix::fs::PermissionsExt;
3001
3002        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
3003        let failure = fail_after_rename_to.map_or_else(String::new, |name| {
3004            format!(
3005                "case \"$0\" in\n  */{name}) echo 'post-replace failure' >&2; exit 1 ;;\nesac\n"
3006            )
3007        });
3008        std::fs::write(
3009            path,
3010            format!("#!/bin/sh\n{failure}printf 'rpi {version}\\n'\n"),
3011        )
3012        .unwrap();
3013        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
3014    }
3015
3016    fn write_test_update_status_at(path: &Path, state: &str, message: &str, updated_at_ms: i64) {
3017        let mut status = serde_json::json!({
3018            "state": state,
3019            "message": message,
3020        });
3021        if updated_at_ms > 0 {
3022            status["updatedAtMs"] = serde_json::json!(updated_at_ms);
3023        }
3024        std::fs::write(path, serde_json::to_vec(&status).unwrap()).unwrap();
3025    }
3026
3027    fn write_test_update_status(path: &Path, state: &str, message: &str) {
3028        std::fs::write(
3029            path,
3030            serde_json::to_vec(&serde_json::json!({
3031                "state": state,
3032                "message": message,
3033            }))
3034            .unwrap(),
3035        )
3036        .unwrap();
3037    }
3038
3039    #[test]
3040    fn path_validation_resolves_ancestor_links_but_refuses_a_link_leaf() {
3041        let temp = real_tempdir();
3042        // Real targets, plus a link directory that points at one of them.
3043        let real_dir = temp.path().join("real-dir");
3044        let real_file = temp.path().join("real-file.exe");
3045        std::fs::create_dir_all(&real_dir).unwrap();
3046        std::fs::write(&real_file, b"payload").unwrap();
3047
3048        let link_dir = temp.path().join("link-dir");
3049        let link_file = temp.path().join("link-file.exe");
3050        #[cfg(unix)]
3051        let linked = {
3052            std::os::unix::fs::symlink(&real_dir, &link_dir).unwrap();
3053            std::os::unix::fs::symlink(&real_file, &link_file).unwrap();
3054            true
3055        };
3056        #[cfg(windows)]
3057        let linked = {
3058            // Junctions need no elevation; file symlinks do, so skip the file
3059            // half when this process cannot create one.
3060            let dir_ok = std::process::Command::new("cmd")
3061                .args(["/c", "mklink", "/J"])
3062                .arg(&link_dir)
3063                .arg(&real_dir)
3064                .output()
3065                .map(|out| out.status.success())
3066                .unwrap_or(false);
3067            if dir_ok {
3068                let file_ok = std::os::windows::fs::symlink_file(&real_file, &link_file).is_ok();
3069                if !file_ok {
3070                    eprintln!("skipping the file-link half: no symlink privilege");
3071                }
3072            }
3073            dir_ok
3074        };
3075        if !linked {
3076            eprintln!("skipping: this platform could not create the link fixture");
3077            return;
3078        }
3079
3080        // A file *below* a linked directory resolves: the link is an ancestor,
3081        // not the thing being written.
3082        let through_link = link_dir.join("nested").join("leaf.exe");
3083        std::fs::create_dir_all(through_link.parent().unwrap()).unwrap();
3084        std::fs::write(&through_link, b"payload").unwrap();
3085        super::validated_regular_file(&through_link, "file below a linked directory").unwrap();
3086        assert_eq!(
3087            std::fs::canonicalize(&link_dir).unwrap(),
3088            std::fs::canonicalize(&real_dir).unwrap(),
3089        );
3090
3091        // A link *leaf* is still refused, and the error names both paths.
3092        let error = super::validated_real_directory(&link_dir, "linked directory").unwrap_err();
3093        assert!(error.contains("link or junction"), "{error}");
3094        assert!(error.contains(&link_dir.display().to_string()), "{error}");
3095
3096        if link_file.exists() {
3097            let error = super::validated_regular_file(&link_file, "linked file").unwrap_err();
3098            assert!(error.contains("link or junction"), "{error}");
3099            assert!(error.contains(&link_file.display().to_string()), "{error}");
3100            assert!(error.contains(&real_file.display().to_string()), "{error}");
3101        }
3102
3103        // The link leaf check must not be a blanket refusal: the real targets
3104        // still validate.
3105        super::validated_real_directory(&real_dir, "real directory").unwrap();
3106        super::validated_regular_file(&real_file, "real file").unwrap();
3107    }
3108
3109    #[test]
3110    fn cargo_self_update_staging_is_passed_as_a_structured_argument() {
3111        let temp = real_tempdir();
3112        let staging = temp.path().join("staging");
3113        let command_dir = temp.path().join("command");
3114        std::fs::create_dir_all(&staging).unwrap();
3115        std::fs::create_dir_all(&command_dir).unwrap();
3116        let command = cargo_install_command(Some(&staging), &command_dir).unwrap();
3117        let args = command.get_args().map(OsString::from).collect::<Vec<_>>();
3118
3119        assert_eq!(command.get_program(), "cargo");
3120        assert_eq!(args.len(), 7);
3121        assert_eq!(args[0], "install");
3122        assert_eq!(args[1], "--root");
3123        assert_eq!(args[2], staging.as_os_str());
3124        assert_eq!(args[3], "rpi-cli");
3125        assert_eq!(args[4], "--locked");
3126        assert_eq!(args[5], "--force");
3127        // Suppresses cargo's "add this to your PATH" advice, which names the
3128        // staging root that the atomic replace is about to consume.
3129        assert_eq!(args[6], "--quiet");
3130        // The command runs in the resolved directory, not the unresolved
3131        // fixture path: `cargo_install_command` validates it first.
3132        assert_eq!(
3133            command.get_current_dir(),
3134            Some(as_production_resolves(&command_dir).as_path())
3135        );
3136    }
3137
3138    #[cfg(unix)]
3139    #[test]
3140    fn direct_update_replaces_the_selected_target_and_rejects_downgrades() {
3141        let temp = real_tempdir();
3142        let staging = temp.path().join("staging");
3143        let staged = staging.join("bin/rpi");
3144        let target = temp.path().join("target/rpi-current");
3145        fake_unix_rpi(&staged, "9.9.9", None);
3146        fake_unix_rpi(&target, crate::VERSION, None);
3147        let expected = std::fs::read(&staged).unwrap();
3148
3149        let plan = build_direct_update_plan(&staging, &target).unwrap();
3150        assert_eq!(activate_direct_update(&plan).unwrap().to_string(), "9.9.9");
3151        assert_eq!(std::fs::read(&target).unwrap(), expected);
3152        assert!(!plan.replacement_temp.exists());
3153        assert!(!plan.backup_file.exists());
3154
3155        fake_unix_rpi(&staged, "0.0.1", None);
3156        let plan = build_direct_update_plan(&staging, &target).unwrap();
3157        let error = activate_direct_update(&plan).unwrap_err();
3158        assert!(error.contains("older version"), "{error}");
3159        assert_eq!(std::fs::read(&target).unwrap(), expected);
3160    }
3161
3162    #[cfg(unix)]
3163    #[test]
3164    fn direct_update_rolls_back_when_post_replace_validation_fails() {
3165        let temp = real_tempdir();
3166        let staging = temp.path().join("staging");
3167        let staged = staging.join("bin/rpi");
3168        let target = temp.path().join("target/rpi-current");
3169        fake_unix_rpi(&staged, "9.9.9", Some("rpi-current"));
3170        fake_unix_rpi(&target, crate::VERSION, None);
3171        let original = std::fs::read(&target).unwrap();
3172
3173        let plan = build_direct_update_plan(&staging, &target).unwrap();
3174        let error = activate_direct_update(&plan).unwrap_err();
3175
3176        assert!(error.contains("restored the previous"), "{error}");
3177        assert_eq!(std::fs::read(&target).unwrap(), original);
3178        assert!(!plan.replacement_temp.exists());
3179        assert!(!plan.backup_file.exists());
3180    }
3181
3182    #[test]
3183    fn self_update_arguments_are_parsed_explicitly() {
3184        let args = |list: &[&str]| list.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();
3185        assert_eq!(
3186            super::parse_self_update_args(&args(&["--build", "--force"])),
3187            super::SelfUpdateArgs::Run {
3188                force: true,
3189                build: true,
3190                channel: super::UpdateChannel::Stable,
3191                cdn_base: None,
3192            }
3193        );
3194        assert_eq!(
3195            super::parse_self_update_args(&args(&[])),
3196            super::SelfUpdateArgs::Run {
3197                force: false,
3198                build: false,
3199                channel: super::UpdateChannel::Stable,
3200                cdn_base: None,
3201            }
3202        );
3203        for flag in ["--force", "-f"] {
3204            assert_eq!(
3205                super::parse_self_update_args(&args(&[flag])),
3206                super::SelfUpdateArgs::Run {
3207                    force: true,
3208                    build: false,
3209                    channel: super::UpdateChannel::Stable,
3210                    cdn_base: None,
3211                }
3212            );
3213        }
3214        assert_eq!(
3215            super::parse_self_update_args(&args(&["preview"])),
3216            super::SelfUpdateArgs::Run {
3217                force: false,
3218                build: false,
3219                channel: super::UpdateChannel::Preview,
3220                cdn_base: None,
3221            }
3222        );
3223        for flag in ["--help", "-h"] {
3224            assert_eq!(
3225                super::parse_self_update_args(&args(&[flag])),
3226                super::SelfUpdateArgs::Help
3227            );
3228        }
3229        // `--help` wins wherever it appears, and unknown flags are a usage
3230        // error rather than being silently ignored.
3231        assert_eq!(
3232            super::parse_self_update_args(&args(&["--force", "--help"])),
3233            super::SelfUpdateArgs::Help
3234        );
3235        assert_eq!(
3236            super::parse_self_update_args(&args(&["--nope"])),
3237            super::SelfUpdateArgs::Usage
3238        );
3239    }
3240
3241    #[test]
3242    fn default_self_update_requires_a_release_and_never_falls_back_to_cargo() {
3243        let staging = tempfile::tempdir().unwrap();
3244        let error = super::prepare_self_update(staging.path(), false, None, None).unwrap_err();
3245        assert!(error.contains("no verified release version"));
3246        assert_eq!(std::fs::read_dir(staging.path()).unwrap().count(), 0);
3247    }
3248
3249    #[test]
3250    fn self_update_honors_env_and_early_dispatched_offline_flag() {
3251        let _guard = crate::config::test_support::env_lock().lock().unwrap();
3252        let _restore = RestoreEnv::capture(crate::args::RPI_OFFLINE_ENV);
3253
3254        std::env::set_var(crate::args::RPI_OFFLINE_ENV, "tRuE");
3255        assert_eq!(super::run_self_update(&[]), 0);
3256
3257        std::env::set_var(crate::args::RPI_OFFLINE_ENV, "0");
3258        assert_eq!(super::run_self_update(&["--offline".into()]), 0);
3259        assert_eq!(
3260            std::env::var(crate::args::RPI_OFFLINE_ENV).as_deref(),
3261            Ok("1")
3262        );
3263    }
3264
3265    #[tokio::test]
3266    async fn offline_skips_rpi_startup_checks_before_cache_io() {
3267        let _guard = crate::config::test_support::env_lock().lock().unwrap();
3268        let _restore_config = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
3269        let _restore_offline = RestoreEnv::capture(crate::args::RPI_OFFLINE_ENV);
3270        let _restore_disabled = RestoreEnv::capture("RPI_DISABLE_UPDATE_CHECK");
3271        let temp = real_tempdir();
3272        let agent = temp.path().join("offline-agent");
3273        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
3274        std::env::set_var(crate::args::RPI_OFFLINE_ENV, "YES");
3275        std::env::remove_var("RPI_DISABLE_UPDATE_CHECK");
3276
3277        let report = super::check_rpi_startup().await;
3278
3279        assert_eq!(report, super::UpdateReport::default());
3280        assert!(
3281            !agent.exists(),
3282            "offline checks must not create the update cache directory"
3283        );
3284    }
3285
3286    #[tokio::test]
3287    async fn inventory_refresh_preserves_self_update_failure_for_startup() {
3288        let _guard = crate::config::test_support::env_lock().lock().unwrap();
3289        let _restore_config = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
3290        let _restore_offline = RestoreEnv::capture(crate::args::RPI_OFFLINE_ENV);
3291        let temp = real_tempdir();
3292        let agent = temp.path().join("agent");
3293        let update_root = agent.join("self-update");
3294        std::fs::create_dir_all(&update_root).unwrap();
3295        let failed = update_root.join("status-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json");
3296        write_test_update_status(&failed, "failed", "permission denied");
3297        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
3298        std::env::set_var(crate::args::RPI_OFFLINE_ENV, "1");
3299
3300        assert_eq!(
3301            super::run_updates(&["refresh".into(), "--json".into()]).await,
3302            0
3303        );
3304        super::refresh_update_cache(&agent, None).await;
3305        assert!(failed.exists());
3306
3307        let report = super::check_rpi_startup().await;
3308        assert_eq!(report.warnings.len(), 1);
3309        assert!(report.warnings[0].message.contains("permission denied"));
3310        assert!(!failed.exists());
3311    }
3312
3313    #[test]
3314    fn completed_self_update_statuses_are_consumed_once() {
3315        let temp = real_tempdir();
3316        let agent = temp.path().join("agent");
3317        let update_root = agent.join("self-update");
3318        std::fs::create_dir_all(&update_root).unwrap();
3319        let failed = update_root.join("status-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json");
3320        let succeeded = update_root.join("status-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.json");
3321        let waiting = update_root.join("status-cccccccccccccccccccccccccccccccc.json");
3322        let temporary = update_root.join("status-dddddddddddddddddddddddddddddddd.json.tmp");
3323        let malformed = update_root.join("status-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee.json");
3324        let invalid_name = update_root.join("status-not-a-uuid.json");
3325        write_test_update_status(&failed, "failed", "permission\u{1b}[31m\r\n denied\u{7}");
3326        write_test_update_status(&succeeded, "succeeded", "done");
3327        write_test_update_status(&waiting, "waiting", "still running");
3328        write_test_update_status(&temporary, "failed", "not published");
3329        std::fs::write(&malformed, b"{not-json").unwrap();
3330        write_test_update_status(&invalid_name, "failed", "invalid name");
3331
3332        let warnings = super::consume_self_update_statuses(&agent);
3333
3334        assert_eq!(warnings.len(), 1);
3335        assert!(warnings[0]
3336            .message
3337            .contains("rpi update failed: permission [31m denied"));
3338        assert!(!warnings[0].message.chars().any(char::is_control));
3339        assert_eq!(warnings[0].command, "rpi update");
3340        assert!(!failed.exists());
3341        // A `succeeded` record is the receipt for the version now installed —
3342        // `rpi update` prints its path — so it survives consumption instead of
3343        // being deleted the moment the next start looks at it.
3344        assert!(succeeded.exists());
3345        assert!(waiting.exists());
3346        assert!(temporary.exists());
3347        assert!(malformed.exists());
3348        assert!(invalid_name.exists());
3349        // The failure is reported once: the record is gone, the kept one is not
3350        // a failure, and the young `waiting` record says nothing.
3351        assert!(super::consume_self_update_statuses(&agent).is_empty());
3352        assert!(succeeded.exists());
3353    }
3354
3355    #[test]
3356    fn stale_and_orphaned_self_update_records_are_pruned() {
3357        let temp = real_tempdir();
3358        let agent = temp.path().join("agent");
3359        std::fs::create_dir_all(&agent).unwrap();
3360        // `consume_self_update_statuses` resolves the agent directory before it
3361        // derives any staging path from it, so the fixture starts from the same
3362        // resolved path. Otherwise a staging directory this test records in a
3363        // status file would never compare equal to the one pruning computes,
3364        // and the pruning under test would silently not run.
3365        let agent = as_production_resolves(&agent);
3366        let update_root = agent.join("self-update");
3367        std::fs::create_dir_all(&update_root).unwrap();
3368        let name =
3369            |token: char| update_root.join(format!("status-{}.json", token.to_string().repeat(32)));
3370        let now = super::now_ms();
3371        let stale_ms = now - super::STALE_SELF_UPDATE_STATUS_TTL_MS - 60_000;
3372
3373        // Live run: recent `waiting` record that owns its staging directory.
3374        let live_status = name('1');
3375        let live_staging = update_root.join("pending-Live001");
3376        std::fs::create_dir_all(live_staging.join("bin")).unwrap();
3377        std::fs::write(live_staging.join("bin").join("rpi.exe"), b"payload").unwrap();
3378        std::fs::write(
3379            &live_status,
3380            serde_json::to_vec(&serde_json::json!({
3381                "state": "waiting",
3382                "staging": live_staging,
3383                "updatedAtMs": now - 1000,
3384            }))
3385            .unwrap(),
3386        )
3387        .unwrap();
3388
3389        // Abandoned run: the helper died, so the record aged out and the
3390        // payload it claims is debris.
3391        let dead_status = name('2');
3392        let dead_staging = update_root.join("pending-Dead002");
3393        std::fs::create_dir_all(dead_staging.join("bin")).unwrap();
3394        std::fs::write(dead_staging.join("bin").join("rpi.exe"), b"payload").unwrap();
3395        write_test_update_status_at(&dead_status, "preparing", "installing", stale_ms);
3396        // Name the staging directory in the stale record, the way the Windows
3397        // helper does: that is the evidence its payload is debris even though
3398        // the directory's own timestamp looks recent.
3399        let mut dead =
3400            serde_json::from_slice::<serde_json::Value>(&std::fs::read(&dead_status).unwrap())
3401                .unwrap();
3402        dead["staging"] = serde_json::json!(dead_staging);
3403        std::fs::write(&dead_status, serde_json::to_vec(&dead).unwrap()).unwrap();
3404
3405        // Orphan: no status file ever named it, and it was created long ago.
3406        let orphan = update_root.join("pending-Orphan3");
3407        std::fs::create_dir_all(orphan.join("bin")).unwrap();
3408        std::fs::write(orphan.join("bin").join("rpi.exe"), b"payload").unwrap();
3409
3410        // Debris that can never be serving an update: an empty staging
3411        // directory, even while it is brand new.
3412        let empty = update_root.join("pending-Empty04");
3413        std::fs::create_dir(&empty).unwrap();
3414
3415        // Not ours to touch: the name is not a tempfile label.
3416        let foreign = update_root.join("pending-not-ours");
3417        std::fs::create_dir_all(&foreign).unwrap();
3418        std::fs::write(foreign.join("keep"), b"keep").unwrap();
3419
3420        let warnings = super::consume_self_update_statuses(&agent);
3421
3422        assert!(warnings.is_empty());
3423        assert!(live_status.exists(), "a live run's record must survive");
3424        assert!(live_staging.exists(), "a live run's staging must survive");
3425        assert!(!dead_status.exists());
3426        assert!(!dead_staging.exists());
3427        // Pruning only deletes a populated directory it can prove is old; an
3428        // untimestamped orphan is left for a later pass rather than guessed at.
3429        assert!(orphan.exists());
3430        // An empty directory cannot be serving an update, whatever its age.
3431        assert!(!empty.exists());
3432        assert!(foreign.exists());
3433    }
3434
3435    #[test]
3436    fn completed_records_survive_and_supersede_leftovers() {
3437        let temp = real_tempdir();
3438        let agent = temp.path().join("agent");
3439        let update_root = agent.join("self-update");
3440        std::fs::create_dir_all(&update_root).unwrap();
3441        let now = super::now_ms();
3442        let staging = update_root.join("pending-Done001");
3443        std::fs::create_dir_all(staging.join("bin")).unwrap();
3444        std::fs::write(staging.join("bin").join("rpi.exe"), b"payload").unwrap();
3445
3446        // A `waiting` leftover naming the same directory as a completed run.
3447        let leftover = update_root.join(format!("status-{}.json", "3".repeat(32)));
3448        std::fs::write(
3449            &leftover,
3450            serde_json::to_vec(&serde_json::json!({
3451                "state": "waiting",
3452                "staging": staging,
3453                "updatedAtMs": now,
3454            }))
3455            .unwrap(),
3456        )
3457        .unwrap();
3458
3459        let recent = update_root.join(format!("status-{}.json", "4".repeat(32)));
3460        std::fs::write(
3461            &recent,
3462            serde_json::to_vec(&serde_json::json!({
3463                "state": "succeeded",
3464                "message": "rpi executable replaced successfully",
3465                "staging": staging,
3466                "updatedAtMs": now,
3467            }))
3468            .unwrap(),
3469        )
3470        .unwrap();
3471
3472        let aged = update_root.join(format!("status-{}.json", "5".repeat(32)));
3473        std::fs::write(
3474            &aged,
3475            serde_json::to_vec(&serde_json::json!({
3476                "state": "succeeded",
3477                "message": "rpi executable replaced successfully",
3478                "updatedAtMs": now - super::COMPLETED_SELF_UPDATE_STATUS_TTL_MS - 60_000,
3479            }))
3480            .unwrap(),
3481        )
3482        .unwrap();
3483
3484        assert!(super::consume_self_update_statuses(&agent).is_empty());
3485
3486        // The receipt for the installed version is kept until it ages out.
3487        assert!(recent.exists());
3488        assert!(!aged.exists());
3489        // The completed record owns the staging directory, so the leftover
3490        // `waiting` record that names it is debris; the directory itself is
3491        // still referenced, so it stays.
3492        assert!(!leftover.exists());
3493        assert!(staging.exists());
3494    }
3495
3496    #[test]
3497    fn self_update_status_validation_rejects_escape_and_links() {
3498        let temp = real_tempdir();
3499        let agent = temp.path().join("agent");
3500        let update_root = agent.join("self-update");
3501        let outside_root = temp.path().join("outside");
3502        std::fs::create_dir_all(&update_root).unwrap();
3503        std::fs::create_dir_all(&outside_root).unwrap();
3504        let name = "status-ffffffffffffffffffffffffffffffff.json";
3505        let outside = outside_root.join(name);
3506        write_test_update_status(&outside, "failed", "outside");
3507
3508        assert!(super::validated_self_update_status_file(&update_root, &outside).is_err());
3509
3510        let linked = update_root.join(name);
3511        #[cfg(unix)]
3512        std::os::unix::fs::symlink(&outside, &linked).unwrap();
3513        #[cfg(windows)]
3514        let link_created = std::os::windows::fs::symlink_file(&outside, &linked).is_ok();
3515        #[cfg(unix)]
3516        let link_created = true;
3517        if link_created {
3518            assert!(super::validated_self_update_status_file(&update_root, &linked).is_err());
3519            assert!(super::consume_self_update_statuses(&agent).is_empty());
3520            assert!(outside.exists());
3521        }
3522    }
3523
3524    #[test]
3525    fn cargo_self_update_without_staging_never_inherits_the_callers_cwd() {
3526        let temp = real_tempdir();
3527        let command_dir = temp.path().join("isolated");
3528        std::fs::create_dir_all(&command_dir).unwrap();
3529
3530        let command = cargo_install_command(None, &command_dir).unwrap();
3531        let args = command.get_args().map(OsString::from).collect::<Vec<_>>();
3532
3533        assert_eq!(
3534            args,
3535            ["install", "rpi-cli", "--locked", "--force", "--quiet"]
3536                .into_iter()
3537                .map(OsString::from)
3538                .collect::<Vec<_>>()
3539        );
3540        assert_eq!(
3541            command.get_current_dir(),
3542            Some(as_production_resolves(&command_dir).as_path())
3543        );
3544        assert_ne!(
3545            command.get_current_dir(),
3546            std::env::current_dir().ok().as_deref()
3547        );
3548        for variable in [
3549            "RUSTC_WRAPPER",
3550            "RUSTC_WORKSPACE_WRAPPER",
3551            "CARGO_BUILD_RUSTC_WRAPPER",
3552            "CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER",
3553        ] {
3554            assert!(command
3555                .get_envs()
3556                .any(|(name, value)| name == variable && value.is_none()));
3557        }
3558        assert!(cargo_install_command(None, Path::new("relative-command-dir")).is_err());
3559
3560        let generated = create_self_update_command_dir().unwrap();
3561        let caller = std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap();
3562        assert!(generated.path().is_absolute());
3563        assert!(!path_is_within(generated.path(), &caller));
3564    }
3565
3566    #[test]
3567    fn project_local_cargo_home_is_rejected_even_when_its_leaf_is_missing() {
3568        let temp = real_tempdir();
3569        let project = temp.path().join("project");
3570        let global = temp.path().join("global-cargo");
3571        std::fs::create_dir_all(&project).unwrap();
3572        std::fs::create_dir_all(&global).unwrap();
3573        let project = std::fs::canonicalize(project).unwrap();
3574
3575        assert!(cargo_home_is_project_local(&project.join(".cargo-home"), &project).unwrap());
3576        assert!(cargo_home_is_project_local(&project, &project).unwrap());
3577        assert!(!cargo_home_is_project_local(&global, &project).unwrap());
3578        assert!(cargo_home_is_project_local(Path::new("relative"), &project).is_err());
3579    }
3580
3581    #[cfg(windows)]
3582    #[test]
3583    fn windows_update_helper_atomically_replaces_a_valid_target() {
3584        let temp = real_tempdir();
3585        let staging = temp.path().join("staging 'semi;& with spaces");
3586        let staged = staging.join("bin/rpi.exe");
3587        let target = temp.path().join("target 'semi;& with spaces/rpi-copy.exe");
3588        fake_windows_executable(&staged, b"new-version");
3589        fake_windows_executable(&target, b"old-version");
3590        let expected = std::fs::read(&staged).unwrap();
3591        let plan = build_windows_update_plan(
3592            &staging,
3593            &target,
3594            &temp
3595                .path()
3596                .join("status-00000000000000000000000000000000.json"),
3597        )
3598        .unwrap();
3599        preflight_windows_replacement(&plan).unwrap();
3600        std::fs::write(&plan.helper_script, WINDOWS_UPDATE_HELPER).unwrap();
3601        write_windows_update_status(&plan.status_file, "scheduled", "test").unwrap();
3602
3603        let powershell = system_powershell_path().unwrap();
3604        let mut command =
3605            windows_update_helper_command(&powershell, &plan, i32::MAX as u32, "9.9.9");
3606        let args = command.get_args().map(OsString::from).collect::<Vec<_>>();
3607        for (flag, expected) in [
3608            ("-StagingPath", &plan.staging_dir),
3609            ("-StagedPath", &plan.staged_exe),
3610            ("-TargetPath", &plan.target_exe),
3611            ("-TempPath", &plan.replacement_temp),
3612            ("-BackupPath", &plan.backup_file),
3613            ("-RollbackDisplacedPath", &plan.rollback_displaced_file),
3614            ("-StatusPath", &plan.status_file),
3615        ] {
3616            let index = args.iter().position(|arg| arg == flag).unwrap();
3617            assert_eq!(args[index + 1], expected.as_os_str());
3618        }
3619        let version_index = args.iter().position(|arg| arg == "-StagedVersion").unwrap();
3620        assert_eq!(args[version_index + 1], "9.9.9");
3621        assert_eq!(command.get_current_dir(), plan.status_file.parent());
3622        assert!(command.get_envs().any(|(name, value)| {
3623            name == "PSModulePath"
3624                && value == Some(powershell.parent().unwrap().join("Modules").as_os_str())
3625        }));
3626        let status = command.status().unwrap();
3627
3628        let status_text = std::fs::read_to_string(&plan.status_file).unwrap();
3629        assert!(
3630            status.success(),
3631            "helper exited with {status}: {status_text}"
3632        );
3633        assert_eq!(std::fs::read(&target).unwrap(), expected);
3634        assert!(!staging.exists());
3635        assert!(!plan.replacement_temp.exists());
3636        assert!(!plan.backup_file.exists());
3637        assert!(!plan.rollback_displaced_file.exists());
3638        let status: serde_json::Value = serde_json::from_str(&status_text).unwrap();
3639        assert_eq!(status["state"], "succeeded");
3640        assert_eq!(status["stagedVersion"], "9.9.9");
3641    }
3642
3643    #[cfg(windows)]
3644    #[test]
3645    fn windows_update_helper_failure_preserves_the_old_executable() {
3646        let temp = real_tempdir();
3647        let staging = temp.path().join("staging with spaces");
3648        let staged = staging.join("bin/rpi.exe");
3649        let target = temp.path().join("target with spaces/rpi-copy.exe");
3650        fake_windows_executable(&staged, b"new-version");
3651        fake_windows_executable(&target, b"old-version");
3652        let expected = std::fs::read(&target).unwrap();
3653        let plan = build_windows_update_plan(
3654            &staging,
3655            &target,
3656            &temp
3657                .path()
3658                .join("status-00000000000000000000000000000000.json"),
3659        )
3660        .unwrap();
3661        preflight_windows_replacement(&plan).unwrap();
3662        std::fs::write(&plan.helper_script, WINDOWS_UPDATE_HELPER).unwrap();
3663        write_windows_update_status(&plan.status_file, "scheduled", "test").unwrap();
3664        std::fs::remove_file(&plan.staged_exe).unwrap();
3665
3666        let status = windows_update_helper_command(
3667            &system_powershell_path().unwrap(),
3668            &plan,
3669            i32::MAX as u32,
3670            "9.9.9",
3671        )
3672        .status()
3673        .unwrap();
3674
3675        let status_text = std::fs::read_to_string(&plan.status_file).unwrap();
3676        assert!(!status.success());
3677        assert_eq!(
3678            std::fs::read(&target).unwrap(),
3679            expected,
3680            "status={status_text}; backup_exists={}",
3681            plan.backup_file.exists()
3682        );
3683        assert!(!staging.exists());
3684        assert!(!plan.replacement_temp.exists());
3685        assert!(!plan.backup_file.exists());
3686        assert!(!plan.rollback_displaced_file.exists());
3687        let status: serde_json::Value = serde_json::from_str(&status_text).unwrap();
3688        assert_eq!(status["state"], "failed");
3689    }
3690
3691    #[cfg(windows)]
3692    #[test]
3693    fn windows_update_helper_rolls_back_after_post_replace_validation_failure() {
3694        let temp = real_tempdir();
3695        let staging = temp.path().join("staging");
3696        let staged = staging.join("bin/rpi.exe");
3697        let target = temp.path().join("target/rpi-copy.exe");
3698        fake_windows_executable(&staged, b"new-version");
3699        fake_windows_executable(&target, b"old-version");
3700        let expected = std::fs::read(&target).unwrap();
3701        let plan = build_windows_update_plan(
3702            &staging,
3703            &target,
3704            &temp
3705                .path()
3706                .join("status-00000000000000000000000000000000.json"),
3707        )
3708        .unwrap();
3709        preflight_windows_replacement(&plan).unwrap();
3710        let forced_failure = WINDOWS_UPDATE_HELPER.replace(
3711            "(Get-FileSha256 -Path $targetFull) -ne $expectedHash",
3712            "$true",
3713        );
3714        assert_ne!(forced_failure, WINDOWS_UPDATE_HELPER);
3715        std::fs::write(&plan.helper_script, forced_failure).unwrap();
3716        write_windows_update_status(&plan.status_file, "scheduled", "test").unwrap();
3717
3718        let status = windows_update_helper_command(
3719            &system_powershell_path().unwrap(),
3720            &plan,
3721            i32::MAX as u32,
3722            "9.9.9",
3723        )
3724        .status()
3725        .unwrap();
3726
3727        let status_text = std::fs::read_to_string(&plan.status_file).unwrap();
3728        assert!(!status.success());
3729        assert_eq!(
3730            std::fs::read(&target).unwrap(),
3731            expected,
3732            "status={status_text}; backup_exists={}",
3733            plan.backup_file.exists()
3734        );
3735        assert!(!staging.exists());
3736        assert!(!plan.replacement_temp.exists());
3737        assert!(!plan.backup_file.exists());
3738        assert!(!plan.rollback_displaced_file.exists());
3739        let status: serde_json::Value = serde_json::from_str(&status_text).unwrap();
3740        assert_eq!(status["state"], "failed");
3741        assert!(status["message"]
3742            .as_str()
3743            .unwrap()
3744            .contains("updated executable hash mismatch"));
3745    }
3746
3747    #[cfg(windows)]
3748    #[test]
3749    fn windows_update_plan_rejects_a_non_executable_staged_file() {
3750        let temp = real_tempdir();
3751        let staging = temp.path().join("staging");
3752        let staged = staging.join("bin/rpi.exe");
3753        let target = temp.path().join("target/rpi.exe");
3754        std::fs::create_dir_all(staged.parent().unwrap()).unwrap();
3755        std::fs::write(&staged, b"not-a-pe").unwrap();
3756        fake_windows_executable(&target, b"old-version");
3757        let expected = std::fs::read(&target).unwrap();
3758
3759        let error = build_windows_update_plan(
3760            &staging,
3761            &target,
3762            &temp
3763                .path()
3764                .join("status-00000000000000000000000000000000.json"),
3765        )
3766        .unwrap_err();
3767
3768        assert!(error.contains("not a Windows executable"));
3769        assert_eq!(std::fs::read(&target).unwrap(), expected);
3770    }
3771
3772    #[test]
3773    fn staged_rpi_version_output_is_exact_and_cannot_downgrade() {
3774        assert_eq!(
3775            parse_rpi_version_output(b"rpi 1.2.3\r\n").unwrap(),
3776            semver::Version::new(1, 2, 3)
3777        );
3778        assert_eq!(
3779            validate_staged_rpi_version_output(b"rpi 1.2.3\n", b"", "1.2.3").unwrap(),
3780            semver::Version::new(1, 2, 3)
3781        );
3782        assert!(
3783            validate_staged_rpi_version_output(b"rpi 1.2.2\n", b"", "1.2.3")
3784                .unwrap_err()
3785                .contains("older version")
3786        );
3787
3788        for output in [
3789            &b"pi 1.2.3\n"[..],
3790            &b"rpi v1.2.3\n"[..],
3791            &b"rpi 1.2.3 extra\n"[..],
3792            &b"rpi 1.2.3\nsecond line\n"[..],
3793            &b" rpi 1.2.3\n"[..],
3794        ] {
3795            assert!(
3796                parse_rpi_version_output(output).is_none(),
3797                "output={output:?}"
3798            );
3799        }
3800        assert!(
3801            validate_staged_rpi_version_output(b"rpi 1.2.3\n", b"warning", "1.2.3")
3802                .unwrap_err()
3803                .contains("stderr")
3804        );
3805    }
3806
3807    #[test]
3808    fn preview_release_selection_ignores_stable_and_draft_releases() {
3809        let releases = vec![
3810            super::GithubRelease {
3811                tag_name: "v0.9.4-preview.1".into(),
3812                draft: false,
3813                prerelease: true,
3814            },
3815            super::GithubRelease {
3816                tag_name: "v0.9.4-preview.3".into(),
3817                draft: false,
3818                prerelease: true,
3819            },
3820            super::GithubRelease {
3821                tag_name: "v0.9.4-preview.99".into(),
3822                draft: true,
3823                prerelease: true,
3824            },
3825            super::GithubRelease {
3826                tag_name: "v0.9.4".into(),
3827                draft: false,
3828                prerelease: false,
3829            },
3830        ];
3831        assert_eq!(
3832            super::latest_preview_version(releases),
3833            super::RegistryLookup::Found("0.9.4-preview.3".into())
3834        );
3835    }
3836
3837    #[test]
3838    fn compares_release_versions_conservatively() {
3839        assert!(is_newer("0.1.9", "0.1.10"));
3840        assert!(is_newer("v1.2.3", "1.3.0"));
3841        assert!(is_newer("1.2.3-beta.1", "1.2.3-beta.2"));
3842        assert!(is_newer("1.2.3-beta.2", "1.2.3"));
3843        assert!(!is_newer("1.2.3", "1.2.3"));
3844        assert!(!is_newer("1.2.3", "1.2.3+build.1"));
3845        assert!(!is_newer("1.2.3+build.1", "1.2.3+build.2"));
3846        assert!(!is_newer("nightly", "1.0.0"));
3847    }
3848
3849    #[test]
3850    fn failed_item_checks_keep_only_corresponding_cached_values() {
3851        let cached = BTreeMap::from([
3852            ("fresh".to_string(), "1.0.0".to_string()),
3853            ("failed".to_string(), "2.0.0".to_string()),
3854            ("removed".to_string(), "3.0.0".to_string()),
3855        ]);
3856        let results = vec![
3857            (
3858                "fresh".to_string(),
3859                RegistryLookup::Found("1.1.0".to_string()),
3860            ),
3861            ("failed".to_string(), RegistryLookup::TransientFailure),
3862            ("uncached".to_string(), RegistryLookup::TransientFailure),
3863            ("missing".to_string(), RegistryLookup::Missing),
3864        ];
3865
3866        let (merged, checked_at_values) =
3867            results_with_individual_cache_fallback(results, Some(&cached), None, 100, 100);
3868        assert_eq!(merged.get("fresh").map(String::as_str), Some("1.1.0"));
3869        assert_eq!(merged.get("failed").map(String::as_str), Some("2.0.0"));
3870        assert!(!merged.contains_key("removed"));
3871        assert!(!merged.contains_key("uncached"));
3872        assert!(!merged.contains_key("missing"));
3873        // A live lookup is stamped with the current check; a fallback keeps the
3874        // timestamp it was cached at, so the fallback window cannot be extended
3875        // indefinitely by repeated offline starts.
3876        assert_eq!(checked_at_values.get("fresh").copied(), Some(100));
3877        assert_eq!(checked_at_values.get("failed").copied(), Some(100));
3878        assert!(!checked_at_values.contains_key("uncached"));
3879        assert!(!checked_at_values.contains_key("missing"));
3880    }
3881
3882    #[tokio::test]
3883    async fn package_update_checks_have_a_shared_concurrency_limit() {
3884        let in_flight = Arc::new(AtomicUsize::new(0));
3885        let maximum = Arc::new(AtomicUsize::new(0));
3886        let checks = (0..(UPDATE_CHECK_CONCURRENCY * 3)).map(|index| {
3887            let in_flight = Arc::clone(&in_flight);
3888            let maximum = Arc::clone(&maximum);
3889            async move {
3890                let active = in_flight.fetch_add(1, Ordering::SeqCst) + 1;
3891                maximum.fetch_max(active, Ordering::SeqCst);
3892                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
3893                in_flight.fetch_sub(1, Ordering::SeqCst);
3894                index
3895            }
3896        });
3897
3898        let mut results = collect_bounded(checks).await;
3899        results.sort_unstable();
3900
3901        assert_eq!(
3902            results,
3903            (0..(UPDATE_CHECK_CONCURRENCY * 3)).collect::<Vec<_>>()
3904        );
3905        assert_eq!(maximum.load(Ordering::SeqCst), UPDATE_CHECK_CONCURRENCY);
3906        assert_eq!(in_flight.load(Ordering::SeqCst), 0);
3907    }
3908
3909    #[tokio::test]
3910    async fn bounded_checks_do_not_head_of_line_block_new_work() {
3911        let release_first = Arc::new(tokio::sync::Notify::new());
3912        let checks = (0..(UPDATE_CHECK_CONCURRENCY + 1)).map(|index| {
3913            let release_first = Arc::clone(&release_first);
3914            async move {
3915                if index == 0 {
3916                    release_first.notified().await;
3917                } else if index == UPDATE_CHECK_CONCURRENCY {
3918                    release_first.notify_one();
3919                }
3920                index
3921            }
3922        });
3923
3924        let mut results =
3925            tokio::time::timeout(std::time::Duration::from_secs(1), collect_bounded(checks))
3926                .await
3927                .expect("a completed later check must free a concurrency slot");
3928        results.sort_unstable();
3929        assert_eq!(results, (0..=UPDATE_CHECK_CONCURRENCY).collect::<Vec<_>>());
3930    }
3931
3932    #[test]
3933    fn fresh_results_keep_individual_timestamps_when_a_peer_uses_fallback() {
3934        let now = 10 * CACHE_FALLBACK_MAX_AGE_MS;
3935        let nearly_stale = now - CACHE_FALLBACK_MAX_AGE_MS + 60_000;
3936        let cached = BTreeMap::from([
3937            ("fresh".to_string(), "1.0.0".to_string()),
3938            ("failed".to_string(), "2.0.0".to_string()),
3939        ]);
3940        let freshness = BTreeMap::from([
3941            ("fresh".to_string(), nearly_stale),
3942            ("failed".to_string(), nearly_stale),
3943        ]);
3944        let (values, timestamps) = results_with_individual_cache_fallback(
3945            vec![
3946                (
3947                    "fresh".to_string(),
3948                    RegistryLookup::Found("1.1.0".to_string()),
3949                ),
3950                ("failed".to_string(), RegistryLookup::TransientFailure),
3951            ],
3952            Some(&cached),
3953            Some(&freshness),
3954            nearly_stale,
3955            now,
3956        );
3957
3958        assert_eq!(timestamps.get("fresh"), Some(&now));
3959        assert_eq!(timestamps.get("failed"), Some(&nearly_stale));
3960        let after_old_entry_expires = now + 120_000;
3961        let (fallback, _) = results_with_individual_cache_fallback(
3962            vec![
3963                ("fresh".to_string(), RegistryLookup::TransientFailure),
3964                ("failed".to_string(), RegistryLookup::TransientFailure),
3965            ],
3966            Some(&values),
3967            Some(&timestamps),
3968            nearly_stale,
3969            after_old_entry_expires,
3970        );
3971        assert_eq!(fallback.get("fresh").map(String::as_str), Some("1.1.0"));
3972        assert!(!fallback.contains_key("failed"));
3973    }
3974
3975    #[tokio::test]
3976    async fn crates_rate_limits_and_request_timeouts_are_transient() {
3977        async fn lookup(status: &str, body: &str) -> RegistryLookup {
3978            use std::io::{BufRead, BufReader, Write};
3979
3980            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3981            let address = listener.local_addr().unwrap();
3982            let status = status.to_string();
3983            let body = body.to_string();
3984            let server = std::thread::spawn(move || {
3985                let (mut stream, _) = listener.accept().unwrap();
3986                {
3987                    let mut reader = BufReader::new(&mut stream);
3988                    let mut line = String::new();
3989                    loop {
3990                        line.clear();
3991                        if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
3992                            break;
3993                        }
3994                    }
3995                }
3996                write!(
3997                    stream,
3998                    "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
3999                    body.len()
4000                )
4001                .unwrap();
4002            });
4003            let client = reqwest::Client::builder().build().unwrap();
4004            let result = fetch_crates_url(&client, &format!("http://{address}/crate")).await;
4005            server.join().unwrap();
4006            result
4007        }
4008
4009        assert_eq!(
4010            lookup("408 Request Timeout", "").await,
4011            RegistryLookup::TransientFailure
4012        );
4013        assert_eq!(
4014            lookup("429 Too Many Requests", "").await,
4015            RegistryLookup::TransientFailure
4016        );
4017        let malformed = lookup("200 OK", "{malformed-json").await;
4018        assert_eq!(malformed, RegistryLookup::TransientFailure);
4019        assert_eq!(
4020            super::lookup_with_cache_fallback(malformed, Some("9.9.9"), true),
4021            (Some("9.9.9".to_string()), true)
4022        );
4023        assert_eq!(lookup("404 Not Found", "").await, RegistryLookup::Missing);
4024    }
4025
4026    /// One-shot HTTP server: answers the first request with `status`/`body`.
4027    ///
4028    /// Returns the URL, a stop flag, and the thread handle. The no-crates.io
4029    /// regression leaves one server unused, so accept must be nonblocking.
4030    fn serve_once(
4031        status: String,
4032        body: String,
4033    ) -> (
4034        String,
4035        std::sync::Arc<std::sync::atomic::AtomicBool>,
4036        std::thread::JoinHandle<usize>,
4037    ) {
4038        use std::io::{BufRead, BufReader, Write};
4039        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
4040        use std::sync::Arc;
4041
4042        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4043        let address = listener.local_addr().unwrap();
4044        // The no-crates.io regression leaves one of two servers unused, so the
4045        // accept must be able to time out on its own: a blocking accept that no
4046        // client ever reaches would hang the test, and a self-connect cannot
4047        // unblock `accept` on this platform.
4048        listener.set_nonblocking(true).unwrap();
4049        let hits = Arc::new(AtomicUsize::new(0));
4050        let thread_hits = hits.clone();
4051        let stop = Arc::new(AtomicBool::new(false));
4052        let thread_stop = stop.clone();
4053        let handle = std::thread::spawn(move || {
4054            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
4055            let stream = loop {
4056                match listener.accept() {
4057                    Ok((stream, _)) => break Some(stream),
4058                    Err(ref error) if error.kind() == std::io::ErrorKind::WouldBlock => {
4059                        if thread_stop.load(Ordering::SeqCst)
4060                            || std::time::Instant::now() > deadline
4061                        {
4062                            break None;
4063                        }
4064                        std::thread::sleep(std::time::Duration::from_millis(2));
4065                    }
4066                    Err(_) => break None,
4067                }
4068            };
4069            let Some(mut stream) = stream else {
4070                return thread_hits.load(Ordering::SeqCst);
4071            };
4072            // `accept` inherited non-blocking from the listener; the request read
4073            // below must block, so put the stream back into blocking mode.
4074            stream.set_nonblocking(false).unwrap();
4075            thread_hits.fetch_add(1, Ordering::SeqCst);
4076            {
4077                let mut reader = BufReader::new(&mut stream);
4078                let mut line = String::new();
4079                loop {
4080                    line.clear();
4081                    if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
4082                        break;
4083                    }
4084                }
4085            }
4086            write!(
4087                stream,
4088                "HTTP/1.1 {status}
4089Content-Length: {}
4090Connection: close
4091
4092{body}",
4093                body.len()
4094            )
4095            .unwrap();
4096            thread_hits.load(Ordering::SeqCst)
4097        });
4098        (format!("http://{address}/release"), stop, handle)
4099    }
4100
4101    fn stop_and_join(
4102        stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
4103        handle: std::thread::JoinHandle<usize>,
4104        url: &str,
4105    ) -> usize {
4106        use std::sync::atomic::Ordering;
4107        stop.store(true, Ordering::SeqCst);
4108        let _ = url;
4109        handle.join().unwrap()
4110    }
4111
4112    fn stable_release(tag: &str) -> String {
4113        serde_json::json!({"tag_name": tag, "draft": false, "prerelease": false}).to_string()
4114    }
4115
4116    #[tokio::test]
4117    async fn cli_stable_queries_github_without_contacting_crates_io() {
4118        let (crates_url, crates_stop, crates_server) = serve_once(
4119            "200 OK".into(),
4120            r#"{"crate":{"max_version":"99.0.0"}}"#.into(),
4121        );
4122        let (github_url, github_stop, github_server) =
4123            serve_once("200 OK".into(), stable_release("v0.11.0"));
4124        let client = reqwest::Client::new();
4125        let result = super::fetch_stable_from_github(&client, &github_url).await;
4126        assert_eq!(stop_and_join(crates_stop, crates_server, &crates_url), 0);
4127        assert_eq!(stop_and_join(github_stop, github_server, &github_url), 1);
4128        assert_eq!(result, RegistryLookup::Found("0.11.0".into()));
4129    }
4130
4131    #[tokio::test]
4132    async fn github_stable_rejects_prereleases_drafts_and_invalid_versions() {
4133        for body in [
4134            serde_json::json!({"tag_name":"v1.0.0-preview.1","draft":false,"prerelease":true}),
4135            serde_json::json!({"tag_name":"v1.0.0","draft":true,"prerelease":false}),
4136            serde_json::json!({"tag_name":"v1.0.0-rc.1","draft":false,"prerelease":false}),
4137            serde_json::json!({"tag_name":"1.0.0","draft":false,"prerelease":false}),
4138            serde_json::json!({"tag_name":"vnot-semver","draft":false,"prerelease":false}),
4139        ] {
4140            let (url, stop, server) = serve_once("200 OK".into(), body.to_string());
4141            let result = super::fetch_stable_from_github(&reqwest::Client::new(), &url).await;
4142            stop_and_join(stop, server, &url);
4143            assert_eq!(result, RegistryLookup::TransientFailure, "{body}");
4144        }
4145    }
4146
4147    #[tokio::test]
4148    async fn github_errors_preserve_fresh_cache_and_reject_expired_cache() {
4149        let _guard = crate::config::test_support::env_lock()
4150            .lock()
4151            .unwrap_or_else(|p| p.into_inner());
4152        let agent = tempfile::tempdir().unwrap();
4153        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
4154        std::env::set_var(crate::config::CONFIG_DIR_ENV, agent.path());
4155        for (status, body) in [
4156            ("404 Not Found", ""),
4157            ("403 Forbidden", "rate limited"),
4158            ("500 Internal Server Error", ""),
4159            ("200 OK", "{not-json"),
4160        ] {
4161            for fresh in [true, false] {
4162                let stamp = super::now_ms() - if fresh { 1000 } else { 48 * 60 * 60 * 1000 };
4163                let cached = super::UpdateCache {
4164                    checked_at: stamp,
4165                    rpi_latest: Some("0.10.0".into()),
4166                    freshness: super::UpdateCacheFreshness {
4167                        rpi: stamp,
4168                        native_packages: Default::default(),
4169                    },
4170                    ..Default::default()
4171                };
4172                std::fs::write(
4173                    agent.path().join(super::CACHE_FILE),
4174                    serde_json::to_vec(&cached).unwrap(),
4175                )
4176                .unwrap();
4177                let (url, stop, server) = serve_once(status.into(), body.into());
4178                let result = super::lookup_latest_rpi_from(&url).await;
4179                stop_and_join(stop, server, &url);
4180                assert_eq!(
4181                    result,
4182                    fresh.then(|| ("0.10.0".into(), false)),
4183                    "{status}, fresh={fresh}"
4184                );
4185            }
4186        }
4187    }
4188
4189    #[tokio::test]
4190    async fn github_live_answer_is_verified_even_with_an_expired_cache() {
4191        let _guard = crate::config::test_support::env_lock()
4192            .lock()
4193            .unwrap_or_else(|p| p.into_inner());
4194        let agent = tempfile::tempdir().unwrap();
4195        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
4196        std::env::set_var(crate::config::CONFIG_DIR_ENV, agent.path());
4197        let stamp = super::now_ms() - 48 * 60 * 60 * 1000;
4198        let cached = super::UpdateCache {
4199            checked_at: stamp,
4200            rpi_latest: Some("0.10.0".into()),
4201            freshness: super::UpdateCacheFreshness {
4202                rpi: stamp,
4203                native_packages: Default::default(),
4204            },
4205            ..Default::default()
4206        };
4207        std::fs::write(
4208            agent.path().join(super::CACHE_FILE),
4209            serde_json::to_vec(&cached).unwrap(),
4210        )
4211        .unwrap();
4212        let (url, stop, server) = serve_once("200 OK".into(), stable_release("v0.11.0"));
4213        let result = super::lookup_latest_rpi_from(&url).await;
4214        assert_eq!(stop_and_join(stop, server, &url), 1);
4215        assert_eq!(result, Some(("0.11.0".into(), true)));
4216    }
4217
4218    #[test]
4219    fn legacy_prebuilt_records_still_receive_update_notices() {
4220        let _guard = crate::config::test_support::env_lock()
4221            .lock()
4222            .unwrap_or_else(|p| p.into_inner());
4223        let agent = tempfile::tempdir().unwrap();
4224        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
4225        std::env::set_var(crate::config::CONFIG_DIR_ENV, agent.path());
4226        // Records written before exact prebuilt provenance carry only the
4227        // publisher marker; a repository move must not stop their notices.
4228        let record: crate::install::InstalledNativePackage =
4229            serde_json::from_value(serde_json::json!({
4230                "name":"demo", "version":"1.0.0",
4231                "source":"prebuilt:https://github.com/pi-rust/rpi-package",
4232                "artifacts":["custom.so"]
4233            }))
4234            .unwrap();
4235        std::fs::write(
4236            agent.path().join("native-packages.json"),
4237            serde_json::to_vec(&[record.clone()]).unwrap(),
4238        )
4239        .unwrap();
4240        assert_eq!(super::native_cache_key(&record), "demo");
4241        let mut cache = super::UpdateCache::default();
4242        cache
4243            .native_packages
4244            .insert(super::native_cache_key(&record), "2.0.0".into());
4245        let report = super::report_from_cache(&cache);
4246        assert_eq!(report.notices.len(), 1);
4247        assert_eq!(report.notices[0].command, "rpi extension update demo");
4248
4249        // A local development build must never be advertised as updatable.
4250        let local: crate::install::InstalledNativePackage = serde_json::from_value(
4251            serde_json::json!({"name":"local","version":"1.0.0","source":"../local-ext"}),
4252        )
4253        .unwrap();
4254        std::fs::write(
4255            agent.path().join("native-packages.json"),
4256            serde_json::to_vec(&[local]).unwrap(),
4257        )
4258        .unwrap();
4259        let mut cache = super::UpdateCache::default();
4260        cache.native_packages.insert("local".into(), "9.9.9".into());
4261        assert!(super::report_from_cache(&cache).notices.is_empty());
4262    }
4263}