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