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