Skip to main content

rpi_cli/
install.rs

1//! `rpi install` — install a prebuilt or explicitly built Rust `cdylib` extension.
2//!
3//! Cargo's `cargo install` command is intended for binaries and does not copy
4//! dynamic-library targets. rpi extensions are cdylibs loaded by
5//! `rpi-extensions`. The default async path uses the prebuilt distribution
6//! protocol; the explicit source backend creates a tiny temporary Cargo workspace,
7//! resolves the requested crate through Cargo, builds the dependency in
8//! release mode, and copies its cdylib into the same global directory scanned
9//! during normal startup.
10
11use std::collections::HashSet;
12use std::io::Write;
13use std::path::{Path, PathBuf};
14use std::process::{Command, Stdio};
15
16use serde::{Deserialize, Serialize};
17
18use crate::prebuilt_extensions::{asset_paths_conflict, validate_asset_path};
19
20const INSTALLER_MANIFEST: &str = "rpi-extension-installer";
21const NATIVE_PACKAGES_FILE: &str = "native-packages.json";
22const NATIVE_PACKAGES_LOCK_FILE: &str = "native-packages.lock";
23const CDYLIB_EXTENSION_HINT: &str = "hint: the crate must declare `crate-type = [\"cdylib\"]` and export `rpi_plugin_register` (the unified ABI; legacy `rpi_plugin_register_v2` and `rpi_plugin_register_v3` remain supported for migration)";
24
25/// A Rust-native extension installed through `rpi install`.
26///
27/// `source` is absent for Cargo registry builds, contains the local source
28/// path for `--path`, or marks prebuilt packages so older hosts do not rebuild
29/// them. `prebuilt` stores distribution provenance. Local development crates
30/// are intentionally not eligible for automatic registry updates.
31#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
32pub struct InstalledNativePackage {
33    pub name: String,
34    pub version: String,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub source: Option<String>,
37    /// Exact prebuilt distribution provenance. Missing in older Cargo/local records.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub prebuilt: Option<crate::prebuilt_extensions::PrebuiltRecord>,
40    /// Dynamic-library file names copied into the extension store. Older
41    /// metadata files omit this field; uninstall falls back to crate-name
42    /// matching for those records.
43    #[serde(default, skip_serializing_if = "Vec::is_empty")]
44    pub artifacts: Vec<String>,
45}
46
47impl InstalledNativePackage {
48    /// Prebuilt provenance also uses `source`; only local development builds
49    /// should be excluded from registry update discovery and commands.
50    ///
51    /// Hosts that predate exact prebuilt provenance recorded only the
52    /// `prebuilt:<repository>` source marker. Those installs are still
53    /// registry-updatable, otherwise they would silently never see an update
54    /// again — including the ones published before a repository move.
55    pub(crate) fn supports_registry_update(&self) -> bool {
56        self.source.is_none()
57            || self.prebuilt.is_some()
58            || self.legacy_prebuilt_repository().is_some()
59    }
60
61    /// Repository from the `prebuilt:<repository>` marker written by hosts
62    /// without exact prebuilt provenance, when it is a usable GitHub URL.
63    pub(crate) fn legacy_prebuilt_repository(&self) -> Option<&str> {
64        if self.prebuilt.is_some() {
65            return None;
66        }
67        self.source
68            .as_deref()?
69            .strip_prefix("prebuilt:")
70            .filter(|repository| repository.starts_with("https://github.com/"))
71    }
72}
73
74/// Decide before downloads/builds, then recheck under the package mutation lock.
75/// `false` means the requested version is already installed; only --force
76/// reinstalls it. Build metadata does not change semantic-version precedence.
77pub(crate) fn should_install_version(
78    name: &str,
79    current: Option<&str>,
80    requested: &str,
81    force: bool,
82) -> Result<bool, String> {
83    let Some(current) = current.filter(|_| !force) else {
84        return Ok(true);
85    };
86    let parse = |version: &str| {
87        semver::Version::parse(version).map_err(|_| {
88            format!("cannot compare version `{version}` for `{name}`; use --force to replace it")
89        })
90    };
91    match parse(requested)?.cmp_precedence(&parse(current)?) {
92        std::cmp::Ordering::Greater => Ok(true),
93        std::cmp::Ordering::Equal => Ok(false),
94        std::cmp::Ordering::Less => Err(format!(
95            "{name} {current} is installed; use --force to downgrade to {requested}"
96        )),
97    }
98}
99
100pub(crate) fn print_already_installed(name: &str, version: &str) {
101    println!("{name} {version} is already installed; use --force to reinstall it");
102}
103
104/// The on-disk state of the Rust-native extension registry.
105///
106/// A malformed or unreadable registry is returned as an error, rather than
107/// being conflated with a missing file. Mutation paths use this distinction to
108/// avoid replacing damaged metadata with a newly generated registry.
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub enum NativePackageRegistry {
111    /// No registry has been created yet.
112    Missing,
113    /// A registry was present and passed JSON/schema validation.
114    Valid(Vec<InstalledNativePackage>),
115}
116
117impl NativePackageRegistry {
118    fn into_records(self) -> Vec<InstalledNativePackage> {
119        match self {
120            Self::Missing => Vec::new(),
121            Self::Valid(records) => records,
122        }
123    }
124}
125
126struct NativePackageMutationLock {
127    file: Option<std::fs::File>,
128    _resource_lease: crate::resource_management::Lease,
129}
130
131impl NativePackageMutationLock {
132    fn acquire(metadata_path: &Path) -> Result<Self, String> {
133        let parent = metadata_path
134            .parent()
135            .ok_or_else(|| "native package metadata has no parent".to_string())?;
136        let resource_lease = crate::resource_management::shared_lease(parent)?;
137        Self::acquire_with_lease(metadata_path, resource_lease)
138    }
139
140    fn acquire_exclusive(metadata_path: &Path) -> Result<Self, String> {
141        let parent = metadata_path
142            .parent()
143            .ok_or_else(|| "native package metadata has no parent".to_string())?;
144        let resource_lease = crate::resource_management::mutation_lease(parent)?;
145        Self::acquire_with_lease(metadata_path, resource_lease)
146    }
147
148    fn acquire_with_lease(
149        metadata_path: &Path,
150        resource_lease: crate::resource_management::Lease,
151    ) -> Result<Self, String> {
152        let parent = metadata_path
153            .parent()
154            .ok_or_else(|| "native package metadata has no parent".to_string())?;
155        std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
156        let lock_path = parent.join(NATIVE_PACKAGES_LOCK_FILE);
157        let file = std::fs::OpenOptions::new()
158            .create(true)
159            .truncate(false)
160            .read(true)
161            .write(true)
162            .open(&lock_path)
163            .map_err(|error| {
164                format!(
165                    "could not open native package lock {}: {error}",
166                    lock_path.display()
167                )
168            })?;
169        fs2::FileExt::try_lock_exclusive(&file).map_err(|error| {
170            format!("could not lock native package state (another install may be running): {error}")
171        })?;
172        Ok(Self {
173            file: Some(file),
174            _resource_lease: resource_lease,
175        })
176    }
177}
178
179impl Drop for NativePackageMutationLock {
180    fn drop(&mut self) {
181        if let Some(file) = self.file.take() {
182            let _ = fs2::FileExt::unlock(&file);
183        }
184    }
185}
186
187#[derive(Debug, Clone)]
188struct InstallOptions {
189    package: String,
190    version: Option<String>,
191    path: Option<PathBuf>,
192    locked: bool,
193    force: bool,
194    build: bool,
195    repository: Option<String>,
196    cdn_base: Option<reqwest::Url>,
197}
198
199/// Default to the versioned prebuilt distribution protocol. Cargo builds are
200/// explicit (--build or --path) and run off the async worker.
201pub async fn run_async(args: &[String]) -> i32 {
202    if args.len() == 1 && matches!(args[0].as_str(), "--help" | "-h") {
203        print_help();
204        return 0;
205    }
206    let options = match parse_args(args) {
207        Ok(options) => options,
208        Err(error) => {
209            eprintln!("error: {error}");
210            print_help();
211            return 2;
212        }
213    };
214    if let Err(error) = installed_native_packages_strict() {
215        eprintln!("error: cannot safely install while native package metadata is invalid: {error}");
216        return 1;
217    }
218    if options.build || options.path.is_some() {
219        let args = args.to_vec();
220        return match tokio::task::spawn_blocking(move || run(&args)).await {
221            Ok(code) => code,
222            Err(error) => {
223                eprintln!("error: extension build failed: {error}");
224                1
225            }
226        };
227    }
228    if crate::args::offline_env_enabled() {
229        eprintln!("error: prebuilt installation requires network access; use --build for an explicit Cargo build");
230        return 1;
231    }
232    match crate::prebuilt_extensions::install(
233        &options.package,
234        options.version.as_deref(),
235        options.repository.as_deref(),
236        options.force,
237        options.cdn_base.as_ref(),
238    )
239    .await
240    {
241        Ok(()) => 0,
242        Err(error) => {
243            eprintln!("error: {error}");
244            1
245        }
246    }
247}
248
249#[derive(Debug, Deserialize)]
250struct CargoMetadata {
251    packages: Vec<CargoPackage>,
252}
253
254#[derive(Debug, Deserialize)]
255struct CargoPackage {
256    name: String,
257    version: String,
258    targets: Vec<CargoTarget>,
259}
260
261#[derive(Debug, Deserialize)]
262struct CargoTarget {
263    name: String,
264    crate_types: Vec<String>,
265}
266
267/// Run `rpi install ...`. This is intentionally synchronous: it is a short
268/// lived package operation and keeping Cargo's build output attached to the
269/// user's terminal makes failures actionable.
270pub fn run(args: &[String]) -> i32 {
271    if args.len() == 1 && matches!(args[0].as_str(), "--help" | "-h") {
272        print_help();
273        return 0;
274    }
275    let options = match parse_args(args) {
276        Ok(options) => options,
277        Err(message) => {
278            eprintln!("error: {message}");
279            print_help();
280            return 2;
281        }
282    };
283
284    // Validate before Cargo work or extension-store mutations. A damaged file
285    // may contain the only record of installed artifacts, so treating it as
286    // an empty registry would make a later write destructive.
287    let records = match installed_native_packages_strict() {
288        Ok(records) => records,
289        Err(error) => {
290            eprintln!(
291                "error: cannot safely install while native package metadata is invalid: {error}"
292            );
293            return 1;
294        }
295    };
296    if !options.build && options.path.is_none() {
297        eprintln!(
298            "error: prebuilt installs use the async dispatcher; Cargo compilation requires --build"
299        );
300        return 2;
301    }
302
303    let temp = match tempfile::tempdir() {
304        Ok(temp) => temp,
305        Err(error) => {
306            eprintln!("error: could not create a temporary Cargo workspace: {error}");
307            return 1;
308        }
309    };
310    let manifest = temp.path().join("Cargo.toml");
311    if let Err(error) = write_manifest(&manifest, &options) {
312        eprintln!("error: could not prepare Cargo workspace: {error}");
313        return 1;
314    }
315
316    if let Err(error) = cargo_command("fetch", &manifest, &options) {
317        eprintln!("error: could not resolve `{}`: {error}", options.package);
318        return 1;
319    }
320
321    let metadata = match cargo_metadata(&manifest, &options) {
322        Ok(metadata) => metadata,
323        Err(error) => {
324            eprintln!("error: could not inspect `{}`: {error}", options.package);
325            return 1;
326        }
327    };
328    let package = match metadata
329        .packages
330        .iter()
331        .find(|package| package.name == options.package)
332    {
333        Some(package) => package,
334        None => {
335            eprintln!(
336                "error: Cargo did not resolve a package named `{}`",
337                options.package
338            );
339            return 1;
340        }
341    };
342    match should_install_version(
343        &package.name,
344        records
345            .iter()
346            .find(|p| p.name == package.name)
347            .map(|p| p.version.as_str()),
348        &package.version,
349        options.force,
350    ) {
351        Ok(true) => {}
352        Ok(false) => {
353            print_already_installed(&package.name, &package.version);
354            return 0;
355        }
356        Err(error) => {
357            eprintln!("error: {error}");
358            return 1;
359        }
360    }
361    let cdylib_targets: Vec<&CargoTarget> = package
362        .targets
363        .iter()
364        .filter(|target| target.crate_types.iter().any(|kind| kind == "cdylib"))
365        .collect();
366    if cdylib_targets.is_empty() {
367        eprintln!(
368            "error: `{}` is not an rpi extension crate; it has no `cdylib` target",
369            options.package
370        );
371        eprintln!("{CDYLIB_EXTENSION_HINT}");
372        return 1;
373    }
374
375    let built = match cargo_build(&manifest, &options, &cdylib_targets) {
376        Ok(built) => built,
377        Err(error) => {
378            eprintln!("error: failed to build `{}`: {error}", options.package);
379            return 1;
380        }
381    };
382
383    let artifact_dir = temp.path().join("target").join("release");
384    let artifacts = match built.into_artifacts(&artifact_dir, &cdylib_targets) {
385        Ok(artifacts) => artifacts,
386        Err(error) => {
387            eprintln!("error: {error}");
388            return 1;
389        }
390    };
391
392    let agent_dir = match crate::config::agent_dir() {
393        Ok(dir) => dir,
394        Err(error) => {
395            eprintln!("error: could not resolve the rpi config directory: {error}");
396            return 1;
397        }
398    };
399    let destination = agent_dir.join("extensions");
400    if let Err(error) = std::fs::create_dir_all(&destination) {
401        eprintln!(
402            "error: could not create extension directory {}: {error}",
403            destination.display()
404        );
405        return 1;
406    }
407
408    let version = metadata
409        .packages
410        .iter()
411        .find(|candidate| candidate.name == options.package)
412        .map(|candidate| candidate.version.clone())
413        .unwrap_or_else(|| "0.0.0".to_string());
414    let record = InstalledNativePackage {
415        name: options.package.clone(),
416        version,
417        source: options
418            .path
419            .as_ref()
420            .map(|path| path.to_string_lossy().into_owned()),
421        prebuilt: None,
422        artifacts: Vec::new(),
423    };
424    let installed = match install_native_package_at(
425        &destination,
426        &agent_dir.join(NATIVE_PACKAGES_FILE),
427        record,
428        &artifacts,
429        options.force,
430    ) {
431        Ok(installed) => installed,
432        Err(error) => {
433            eprintln!("error: could not install `{}`: {error}", options.package);
434            return 1;
435        }
436    };
437    for target in installed {
438        println!("installed {}", target.display());
439    }
440    gc_retired_native_artifacts(&agent_dir);
441    println!("rpi will load this extension on the next start.");
442    0
443}
444
445/// Remove a Rust-native extension installed by `rpi install`.
446///
447/// The install registry is authoritative for new installs. For metadata from
448/// older rpi versions, dynamic libraries whose normalized file stem matches
449/// the crate name are removed as a compatibility fallback.
450pub fn uninstall(args: &[String]) -> i32 {
451    if args.len() == 1 && matches!(args[0].as_str(), "--help" | "-h") {
452        print_uninstall_help();
453        return 0;
454    }
455    let name = match parse_uninstall_name(args) {
456        Ok(name) => name,
457        Err(error) => {
458            eprintln!("error: {error}");
459            print_uninstall_help();
460            return 2;
461        }
462    };
463    let agent = match crate::config::agent_dir() {
464        Ok(path) => path,
465        Err(error) => {
466            eprintln!("error: could not resolve the rpi config directory: {error}");
467            return 1;
468        }
469    };
470    let extension_dir = agent.join("extensions");
471    let metadata_path = agent.join(NATIVE_PACKAGES_FILE);
472    let _lock = match NativePackageMutationLock::acquire_exclusive(&metadata_path) {
473        Ok(lock) => lock,
474        Err(error) => {
475            eprintln!("error: cannot safely uninstall: {error}");
476            return 1;
477        }
478    };
479    let records = match read_native_package_registry_at(&metadata_path) {
480        Ok(registry) => registry.into_records(),
481        Err(error) => {
482            eprintln!(
483                "error: cannot safely uninstall while native package metadata is invalid: {error}"
484            );
485            return 1;
486        }
487    };
488    let mut asset_targets = Vec::new();
489    for record in records.iter().filter(|record| record.name == name) {
490        for asset in recorded_asset_paths(record) {
491            match checked_asset_target(&extension_dir, asset) {
492                Ok(path) => asset_targets.push(path),
493                Err(error) => {
494                    eprintln!("error: cannot safely uninstall: {error}");
495                    return 1;
496                }
497            }
498        }
499    }
500    let had_record = records.iter().any(|record| record.name == name);
501    let wanted = normalize_name(&name);
502    let artifact_names: std::collections::HashSet<String> = records
503        .iter()
504        .filter(|record| record.name == name)
505        .flat_map(|record| record.artifacts.iter().cloned())
506        .collect();
507    let use_legacy_name_fallback = artifact_names.is_empty();
508    let mut artifact_targets = Vec::new();
509    if let Ok(entries) = std::fs::read_dir(&extension_dir) {
510        for entry in entries.flatten() {
511            let path = entry.path();
512            let file_name = path
513                .file_name()
514                .map(|name| name.to_string_lossy().into_owned())
515                .unwrap_or_default();
516            let is_artifact = artifact_names.contains(&file_name)
517                || is_versioned_artifact_for_package(&file_name, &wanted)
518                || (use_legacy_name_fallback
519                    && path
520                        .file_stem()
521                        .and_then(|stem| stem.to_str())
522                        .map(|stem| normalize_name(stem.trim_start_matches("lib")) == wanted)
523                        .unwrap_or(false));
524            if is_artifact && is_dynamic_library(&path) {
525                artifact_targets.push(path);
526            }
527        }
528    }
529    if let Err(error) =
530        crate::resource_management::legacy_unowned_targets(&agent, &artifact_targets)
531    {
532        eprintln!("error: {error}");
533        return 1;
534    }
535    let mut remaining: Vec<_> = records
536        .into_iter()
537        .filter(|record| record.name != name)
538        .collect();
539    if had_record {
540        remaining.sort_by(|left, right| left.name.cmp(&right.name));
541    }
542    let mut replacements = Vec::new();
543    let mut removals = artifact_targets.clone();
544    removals.extend(asset_targets.iter().cloned());
545    if had_record {
546        if remaining.is_empty() {
547            removals.push(metadata_path.clone());
548        } else {
549            let registry = match serde_json::to_vec_pretty(&remaining) {
550                Ok(registry) => registry,
551                Err(error) => {
552                    eprintln!("error: could not serialize native package metadata: {error}");
553                    return 1;
554                }
555            };
556            let staged = match stage_native_bytes(&registry, &metadata_path) {
557                Ok(staged) => staged,
558                Err(error) => {
559                    eprintln!("error: could not stage native package metadata: {error}");
560                    return 1;
561                }
562            };
563            replacements.push(NativeReplacement {
564                staged,
565                target: metadata_path.clone(),
566            });
567        }
568    }
569    if let Err(error) = activate_native_transaction(&replacements, &removals, &mut |_, _| Ok(())) {
570        eprintln!("error: could not uninstall Rust extension {name}: {error}");
571        return 1;
572    }
573    prune_empty_dirs(&extension_dir, &asset_targets);
574    for path in artifact_targets.iter().chain(&asset_targets) {
575        println!("removed {}", path.display());
576    }
577    let removed = artifact_targets.len() + asset_targets.len();
578    if removed == 0 && !had_record {
579        println!("Rust extension is not installed: {name}");
580        return 0;
581    }
582    println!("uninstalled Rust extension {name}");
583    0
584}
585
586fn parse_uninstall_name(args: &[String]) -> Result<String, String> {
587    let mut name = None;
588    for arg in args {
589        match arg.as_str() {
590            "--help" | "-h" => return Err("use `rpi uninstall --help` for usage".into()),
591            value if value.starts_with('-') => {
592                return Err(format!("unknown uninstall option `{value}`"))
593            }
594            value => {
595                if name.replace(value.to_string()).is_some() {
596                    return Err("uninstall accepts exactly one crate name".into());
597                }
598            }
599        }
600    }
601    let name = name.ok_or_else(|| "missing crate name".to_string())?;
602    if !valid_package_name(&name) {
603        return Err(format!("invalid Cargo package name `{name}`"));
604    }
605    Ok(name)
606}
607
608#[cfg(test)]
609fn write_native_packages_at(path: &Path, records: &[InstalledNativePackage]) -> Result<(), String> {
610    if records.is_empty() {
611        match std::fs::remove_file(path) {
612            Ok(()) => return Ok(()),
613            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
614            Err(error) => return Err(error.to_string()),
615        }
616    }
617    let parent = path
618        .parent()
619        .ok_or_else(|| "native package metadata has no parent".to_string())?;
620    std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
621    let data = serde_json::to_vec_pretty(records).map_err(|error| error.to_string())?;
622    std::fs::write(path, data).map_err(|error| error.to_string())
623}
624
625/// Read and validate the Rust-native extension registry without hiding errors.
626pub fn read_native_package_registry() -> Result<NativePackageRegistry, String> {
627    let path = crate::config::agent_dir()
628        .map_err(|error| error.to_string())?
629        .join(NATIVE_PACKAGES_FILE);
630    read_native_package_registry_at(&path)
631}
632
633fn read_native_package_registry_at(path: &Path) -> Result<NativePackageRegistry, String> {
634    let data = match std::fs::read(path) {
635        Ok(data) => data,
636        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
637            return Ok(NativePackageRegistry::Missing)
638        }
639        Err(error) => {
640            return Err(format!("could not read {}: {error}", path.display()));
641        }
642    };
643    serde_json::from_slice(&data)
644        .map(NativePackageRegistry::Valid)
645        .map_err(|error| format!("invalid JSON or schema in {}: {error}", path.display()))
646}
647
648/// Read the registry for best-effort discovery and startup update notices.
649///
650/// Missing, unreadable, and malformed registries all produce an empty list so
651/// startup remains safe. Install and uninstall operations instead use
652/// [`read_native_package_registry`] and fail closed on an invalid file.
653pub fn installed_native_packages() -> Vec<InstalledNativePackage> {
654    installed_native_packages_strict().unwrap_or_default()
655}
656
657/// Read the installed package list for a command that may mutate package
658/// state. Unlike startup discovery, callers must surface registry errors and
659/// abort before touching any package store.
660pub(crate) fn installed_native_packages_strict() -> Result<Vec<InstalledNativePackage>, String> {
661    read_native_package_registry().map(NativePackageRegistry::into_records)
662}
663
664/// Resolve the active global native package libraries without scanning the
665/// extension directory. New records name the active files explicitly; older
666/// records had no artifact ledger, so they retain the historical crate-name
667/// scan as a compatibility fallback.
668pub fn active_global_native_package_artifacts() -> Vec<PathBuf> {
669    let Ok(agent_dir) = crate::config::agent_dir() else {
670        return Vec::new();
671    };
672    active_global_native_package_artifacts_at(&agent_dir).unwrap_or_default()
673}
674
675/// Resolve unmanaged legacy libraries from the global extension directory.
676/// Managed versioned artifacts are deliberately omitted: only the active
677/// artifact list above may be loaded for an installed native package.
678pub fn unregistered_global_native_package_artifacts() -> Vec<PathBuf> {
679    let Ok(agent_dir) = crate::config::agent_dir() else {
680        return Vec::new();
681    };
682    unregistered_global_native_package_artifacts_at(&agent_dir).unwrap_or_default()
683}
684
685pub(crate) fn active_global_native_package_artifacts_at(
686    agent_dir: &Path,
687) -> Result<Vec<PathBuf>, String> {
688    let destination = agent_dir.join("extensions");
689    let records =
690        read_native_package_registry_at(&agent_dir.join(NATIVE_PACKAGES_FILE))?.into_records();
691    let mut paths = Vec::new();
692    let mut seen = HashSet::new();
693    for record in records {
694        if record.artifacts.is_empty() {
695            let wanted = normalize_name(&record.name);
696            let Ok(entries) = std::fs::read_dir(&destination) else {
697                continue;
698            };
699            for entry in entries {
700                let entry = entry.map_err(|error| {
701                    format!("could not inspect native extension directory: {error}")
702                })?;
703                let path = entry.path();
704                let matches = path
705                    .file_stem()
706                    .and_then(|stem| stem.to_str())
707                    .map(|stem| normalize_name(stem.trim_start_matches("lib")) == wanted)
708                    .unwrap_or(false);
709                if matches && is_dynamic_library(&path) {
710                    let identity = transaction_path_identity(&path);
711                    if seen.insert(identity) {
712                        paths.push(path);
713                    }
714                }
715            }
716        } else {
717            for artifact in record.artifacts {
718                let path = checked_registered_artifact_path(&destination, &artifact)?;
719                if seen.insert(transaction_path_identity(&path)) {
720                    paths.push(path);
721                }
722            }
723        }
724    }
725    paths.sort();
726    Ok(paths)
727}
728
729pub(crate) fn unregistered_global_native_package_artifacts_at(
730    agent_dir: &Path,
731) -> Result<Vec<PathBuf>, String> {
732    let destination = agent_dir.join("extensions");
733    let records =
734        read_native_package_registry_at(&agent_dir.join(NATIVE_PACKAGES_FILE))?.into_records();
735    let managed = records
736        .iter()
737        .flat_map(|record| record.artifacts.iter())
738        .map(|artifact| native_artifact_identity(artifact))
739        .collect::<HashSet<_>>();
740    let legacy_names = records
741        .iter()
742        .filter(|record| record.artifacts.is_empty())
743        .map(|record| normalize_name(&record.name))
744        .collect::<HashSet<_>>();
745    let mut paths = Vec::new();
746    let Ok(entries) = std::fs::read_dir(&destination) else {
747        return Ok(paths);
748    };
749    for entry in entries {
750        let path = entry
751            .map_err(|error| format!("could not inspect native extension directory: {error}"))?
752            .path();
753        let Some(name) = path.file_name().and_then(|value| value.to_str()) else {
754            continue;
755        };
756        let legacy_managed = path
757            .file_stem()
758            .and_then(|stem| stem.to_str())
759            .map(|stem| legacy_names.contains(&normalize_name(stem.trim_start_matches("lib"))))
760            .unwrap_or(false);
761        if !is_dynamic_library(&path)
762            || managed.contains(&native_artifact_identity(name))
763            || is_versioned_artifact_name(name)
764            || legacy_managed
765        {
766            continue;
767        }
768        paths.push(path);
769    }
770    paths.sort();
771    Ok(paths)
772}
773
774#[cfg(test)]
775fn record_native_package_at(path: &Path, record: &InstalledNativePackage) -> Result<(), String> {
776    let mut records = read_native_package_registry_at(path)?.into_records();
777    if let Some(existing) = records.iter_mut().find(|item| item.name == record.name) {
778        *existing = record.clone();
779    } else {
780        records.push(record.clone());
781    }
782    records.sort_by(|left, right| left.name.cmp(&right.name));
783    write_native_packages_at(path, &records)
784}
785
786struct StagedNativeFile {
787    path: PathBuf,
788}
789
790impl Drop for StagedNativeFile {
791    fn drop(&mut self) {
792        let _ = std::fs::remove_file(&self.path);
793    }
794}
795
796struct NativeReplacement {
797    staged: StagedNativeFile,
798    target: PathBuf,
799}
800
801struct NativeBackup {
802    target: PathBuf,
803    backup: PathBuf,
804}
805
806/// A sidecar file of a prebuilt package, already verified against its archive
807/// index. `path` is the relative store path, such as `runtime/main.mjs`.
808pub(crate) struct NativeAssetFile {
809    pub path: String,
810    pub bytes: Vec<u8>,
811}
812
813pub(crate) fn install_native_package_at(
814    destination: &Path,
815    metadata_path: &Path,
816    record: InstalledNativePackage,
817    artifacts: &[PathBuf],
818    force: bool,
819) -> Result<Vec<PathBuf>, String> {
820    install_native_package_with_assets_at(destination, metadata_path, record, artifacts, &[], force)
821}
822
823/// Install a library and its sidecar assets as one transaction. The returned paths
824/// are the library followed by every asset that was activated.
825pub(crate) fn install_native_package_with_assets_at(
826    destination: &Path,
827    metadata_path: &Path,
828    record: InstalledNativePackage,
829    artifacts: &[PathBuf],
830    assets: &[NativeAssetFile],
831    force: bool,
832) -> Result<Vec<PathBuf>, String> {
833    install_native_package_at_with_hook(
834        destination,
835        metadata_path,
836        record,
837        artifacts,
838        assets,
839        force,
840        |_, _| Ok(()),
841    )
842}
843
844fn install_native_package_at_with_hook(
845    destination: &Path,
846    metadata_path: &Path,
847    mut record: InstalledNativePackage,
848    artifacts: &[PathBuf],
849    assets: &[NativeAssetFile],
850    force: bool,
851    mut before_activate: impl FnMut(usize, &Path) -> Result<(), String>,
852) -> Result<Vec<PathBuf>, String> {
853    std::fs::create_dir_all(destination).map_err(|error| {
854        format!(
855            "could not create extension directory {}: {error}",
856            destination.display()
857        )
858    })?;
859    let metadata_parent = metadata_path
860        .parent()
861        .ok_or_else(|| "native package metadata has no parent".to_string())?;
862    std::fs::create_dir_all(metadata_parent).map_err(|error| error.to_string())?;
863    let _lock = NativePackageMutationLock::acquire(metadata_path)?;
864    let mut records = read_native_package_registry_at(metadata_path)?.into_records();
865    let previous = records
866        .iter()
867        .find(|candidate| candidate.name == record.name)
868        .cloned();
869
870    if !should_install_version(
871        &record.name,
872        previous.as_ref().map(|p| p.version.as_str()),
873        &record.version,
874        force,
875    )? {
876        print_already_installed(&record.name, &record.version);
877        return Ok(Vec::new());
878    }
879
880    let mut source_artifacts = Vec::with_capacity(artifacts.len());
881    let mut source_keys = HashSet::new();
882    for artifact in artifacts {
883        let metadata = std::fs::symlink_metadata(artifact).map_err(|error| {
884            format!(
885                "could not inspect built artifact {}: {error}",
886                artifact.display()
887            )
888        })?;
889        if !metadata.is_file() || metadata.file_type().is_symlink() {
890            return Err(format!(
891                "built artifact is not a regular file: {}",
892                artifact.display()
893            ));
894        }
895        let name = artifact_file_name(artifact)?;
896        if !source_keys.insert(native_artifact_identity(&name)) {
897            return Err(format!("duplicate built artifact name `{name}`"));
898        }
899        source_artifacts.push((name, artifact.clone()));
900    }
901    if source_artifacts.is_empty() {
902        return Err("Cargo produced no installable cdylib artifacts".to_string());
903    }
904
905    // Upgrades get a fresh, version-bearing filename, so an already loaded
906    // DLL/SO/DYLIB is never replaced or unlinked. First installs retain the
907    // historical stable name for compatibility; later upgrades switch to the
908    // immutable versioned name.
909    let mut new_artifacts = Vec::with_capacity(source_artifacts.len());
910    let mut new_keys = HashSet::new();
911    for (name, source) in source_artifacts {
912        let target_name = if previous.is_some() || (force && destination.join(&name).exists()) {
913            versioned_artifact_name(&name, &record.version, destination)?
914        } else {
915            name
916        };
917        if !new_keys.insert(native_artifact_identity(&target_name)) {
918            return Err(format!("duplicate versioned artifact name `{target_name}`"));
919        }
920        new_artifacts.push((target_name, source));
921    }
922
923    for other in records
924        .iter()
925        .filter(|candidate| candidate.name != record.name)
926    {
927        for owned in &other.artifacts {
928            checked_registered_artifact_path(destination, owned)?;
929            if new_keys.contains(&native_artifact_identity(owned)) {
930                return Err(format!(
931                    "artifact `{owned}` is already owned by installed package `{}`",
932                    other.name
933                ));
934            }
935        }
936    }
937
938    // Sidecars share the store namespace with every package's artifacts and assets.
939    validate_new_assets(&record, assets, &new_artifacts)?;
940    for other in records
941        .iter()
942        .filter(|candidate| candidate.name != record.name)
943    {
944        for owned in recorded_asset_paths(other) {
945            let clash = new_artifacts
946                .iter()
947                .map(|(name, _)| name.as_str())
948                .chain(assets.iter().map(|asset| asset.path.as_str()))
949                .find(|new| asset_paths_conflict(new, owned));
950            if let Some(new) = clash {
951                return Err(format!(
952                    "`{new}` conflicts with asset `{owned}` owned by installed package `{}`",
953                    other.name
954                ));
955            }
956        }
957    }
958
959    let installed_targets = new_artifacts
960        .iter()
961        .map(|(name, _)| destination.join(name))
962        .collect::<Vec<_>>();
963    crate::resource_management::legacy_unowned_targets(metadata_parent, &installed_targets)?;
964    for target in &installed_targets {
965        match std::fs::symlink_metadata(target) {
966            Ok(_) => {
967                return Err(format!(
968                    "versioned extension target {} already exists",
969                    target.display()
970                ))
971            }
972            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
973            Err(error) => {
974                return Err(format!(
975                    "could not inspect extension target {}: {error}",
976                    target.display()
977                ))
978            }
979        }
980    }
981
982    let previous_assets: Vec<String> = previous
983        .as_ref()
984        .map(|package| {
985            recorded_asset_paths(package)
986                .into_iter()
987                .map(str::to_owned)
988                .collect()
989        })
990        .unwrap_or_default();
991    let mut asset_targets = Vec::with_capacity(assets.len());
992    for asset in assets {
993        let target = checked_asset_target(destination, &asset.path)?;
994        // Same identity rule as the transaction and the stale check. A case-folded name is
995        // owned only when it is the recorded file itself (a case-insensitive store), never a
996        // different file that merely differs in case.
997        let owned = previous_assets.iter().any(|old| {
998            native_artifact_identity(old) == native_artifact_identity(&asset.path)
999                || (old.eq_ignore_ascii_case(&asset.path)
1000                    && same_file(&destination.join(old), &target))
1001        });
1002        if !force && !owned {
1003            match std::fs::symlink_metadata(&target) {
1004                Ok(_) => {
1005                    return Err(format!(
1006                        "extension {} already exists; use --force to replace it",
1007                        target.display()
1008                    ))
1009                }
1010                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1011                Err(error) => {
1012                    return Err(format!(
1013                        "could not inspect extension target {}: {error}",
1014                        target.display()
1015                    ))
1016                }
1017            }
1018        }
1019        asset_targets.push(target);
1020    }
1021    let mut stale_asset_targets = Vec::new();
1022    for old in &previous_assets {
1023        // On a case-sensitive store a case-only rename is a different file, and leaving
1024        // the old one would orphan it. Windows folds identities, as the transaction does.
1025        if !assets
1026            .iter()
1027            .any(|asset| native_artifact_identity(&asset.path) == native_artifact_identity(old))
1028        {
1029            stale_asset_targets.push(checked_asset_target(destination, old)?);
1030        }
1031    }
1032
1033    record.artifacts = new_artifacts.iter().map(|(name, _)| name.clone()).collect();
1034    if let Some(existing) = records
1035        .iter_mut()
1036        .find(|candidate| candidate.name == record.name)
1037    {
1038        *existing = record;
1039    } else {
1040        records.push(record);
1041    }
1042    records.sort_by(|left, right| left.name.cmp(&right.name));
1043
1044    let mut replacements = Vec::with_capacity(new_artifacts.len() + assets.len() + 1);
1045    for ((_, source), target) in new_artifacts.iter().zip(&installed_targets) {
1046        replacements.push(NativeReplacement {
1047            staged: stage_native_artifact(source, target)?,
1048            target: target.clone(),
1049        });
1050    }
1051    // Sidecars are written into a private directory on the store's filesystem, so
1052    // the transaction can rename each one into place. Nothing reaches the store
1053    // until every replacement has been staged.
1054    let stage = if assets.is_empty() {
1055        None
1056    } else {
1057        Some(StagedDirectory::create(destination)?)
1058    };
1059    if let Some(stage) = &stage {
1060        for (asset, target) in assets.iter().zip(&asset_targets) {
1061            let staged = stage.path.join(&asset.path);
1062            if let Some(parent) = staged.parent() {
1063                std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
1064            }
1065            write_staged_asset(&asset.bytes, &staged)?;
1066            replacements.push(NativeReplacement {
1067                staged: StagedNativeFile { path: staged },
1068                target: target.clone(),
1069            });
1070        }
1071    }
1072    let registry = serde_json::to_vec_pretty(&records).map_err(|error| error.to_string())?;
1073    replacements.push(NativeReplacement {
1074        staged: stage_native_bytes(&registry, metadata_path)?,
1075        target: metadata_path.to_path_buf(),
1076    });
1077    // Directories this transaction creates, so a failed install can remove them again.
1078    let mut created_dirs = Vec::new();
1079    for target in &asset_targets {
1080        if let Some(parent) = target.parent() {
1081            created_dirs.extend(
1082                parent
1083                    .ancestors()
1084                    .take_while(|dir| *dir != destination && !dir.exists())
1085                    .map(Path::to_path_buf),
1086            );
1087            if let Err(error) = std::fs::create_dir_all(parent) {
1088                remove_created_dirs(&mut created_dirs);
1089                return Err(format!(
1090                    "could not create extension directory {}: {error}",
1091                    parent.display()
1092                ));
1093            }
1094        }
1095    }
1096
1097    // Dynamic-library artifacts are intentionally retained across upgrades.
1098    // Only replaceable sidecar files follow the old cleanup behavior.
1099    let mut removals = Vec::new();
1100    removals.extend(stale_asset_targets.iter().cloned());
1101    if let Err(error) = activate_native_transaction(&replacements, &removals, &mut before_activate)
1102    {
1103        remove_created_dirs(&mut created_dirs);
1104        return Err(error);
1105    }
1106    prune_empty_dirs(destination, &stale_asset_targets);
1107    Ok(installed_targets.into_iter().chain(asset_targets).collect())
1108}
1109
1110/// Assets must match the registry ledger exactly, and each must be a valid,
1111/// non-overlapping store path that no library artifact of this package occupies.
1112fn validate_new_assets(
1113    record: &InstalledNativePackage,
1114    assets: &[NativeAssetFile],
1115    artifacts: &[(String, PathBuf)],
1116) -> Result<(), String> {
1117    let declared: Vec<&str> = assets.iter().map(|asset| asset.path.as_str()).collect();
1118    if recorded_asset_paths(record) != declared {
1119        return Err("internal error: sidecar ledger does not match the staged assets".into());
1120    }
1121    for (index, asset) in assets.iter().enumerate() {
1122        validate_asset_path(&asset.path)?;
1123        if assets[..index]
1124            .iter()
1125            .any(|other| asset_paths_conflict(&other.path, &asset.path))
1126        {
1127            return Err(format!(
1128                "duplicate or overlapping asset path `{}`",
1129                asset.path
1130            ));
1131        }
1132        if artifacts
1133            .iter()
1134            .any(|(name, _)| asset_paths_conflict(name, &asset.path))
1135        {
1136            return Err(format!(
1137                "asset `{}` collides with a library artifact",
1138                asset.path
1139            ));
1140        }
1141    }
1142    Ok(())
1143}
1144
1145fn recorded_asset_paths(package: &InstalledNativePackage) -> Vec<&str> {
1146    package
1147        .prebuilt
1148        .iter()
1149        .flat_map(|prebuilt| prebuilt.assets.iter().map(|asset| asset.path.as_str()))
1150        .collect()
1151}
1152
1153/// Resolve a declared sidecar under the store without following links. Existing
1154/// ancestors must be real directories; missing ones are created by the transaction.
1155fn checked_asset_target(destination: &Path, relative: &str) -> Result<PathBuf, String> {
1156    validate_asset_path(relative)?;
1157    let parts: Vec<&str> = relative.split('/').collect();
1158    let mut current = destination.to_path_buf();
1159    for part in &parts[..parts.len() - 1] {
1160        current.push(part);
1161        match std::fs::symlink_metadata(&current) {
1162            Ok(metadata) if metadata.is_dir() => {}
1163            Ok(_) => {
1164                return Err(format!(
1165                    "asset parent {} is not a plain directory",
1166                    current.display()
1167                ))
1168            }
1169            Err(error) if error.kind() == std::io::ErrorKind::NotFound => break,
1170            Err(error) => {
1171                return Err(format!(
1172                    "could not inspect asset parent {}: {error}",
1173                    current.display()
1174                ))
1175            }
1176        }
1177    }
1178    Ok(destination.join(relative))
1179}
1180
1181/// A private staging directory, removed on every exit path.
1182struct StagedDirectory {
1183    path: PathBuf,
1184}
1185
1186impl StagedDirectory {
1187    fn create(destination: &Path) -> Result<Self, String> {
1188        let path = destination.join(format!(
1189            ".rpi-assets-stage-{}",
1190            uuid::Uuid::new_v4().simple()
1191        ));
1192        std::fs::create_dir(&path).map_err(|error| {
1193            format!(
1194                "could not create asset staging directory {}: {error}",
1195                path.display()
1196            )
1197        })?;
1198        Ok(Self { path })
1199    }
1200}
1201
1202impl Drop for StagedDirectory {
1203    fn drop(&mut self) {
1204        let _ = std::fs::remove_dir_all(&self.path);
1205    }
1206}
1207
1208fn write_staged_asset(bytes: &[u8], path: &Path) -> Result<(), String> {
1209    let mut file = std::fs::OpenOptions::new()
1210        .write(true)
1211        .create_new(true)
1212        .open(path)
1213        .map_err(|error| format!("could not create staged asset {}: {error}", path.display()))?;
1214    file.write_all(bytes)
1215        .and_then(|()| file.sync_all())
1216        .map_err(|error| format!("could not write staged asset {}: {error}", path.display()))
1217}
1218
1219/// Remove directories a failed transaction created, deepest first. A directory that is
1220/// not empty (for example after a failed rollback) is kept.
1221fn remove_created_dirs(dirs: &mut [PathBuf]) {
1222    dirs.sort_by_key(|dir| std::cmp::Reverse(dir.components().count()));
1223    for dir in dirs.iter() {
1224        let _ = std::fs::remove_dir(dir);
1225    }
1226}
1227
1228/// Remove directories left empty by removed sidecars. The store itself is kept.
1229fn prune_empty_dirs(root: &Path, removed: &[PathBuf]) {
1230    for path in removed {
1231        let mut current = path.parent();
1232        while let Some(dir) = current {
1233            if dir == root || !dir.starts_with(root) || std::fs::remove_dir(dir).is_err() {
1234                break;
1235            }
1236            current = dir.parent();
1237        }
1238    }
1239}
1240
1241fn is_versioned_artifact_name(name: &str) -> bool {
1242    let Some(stem) = Path::new(name).file_stem().and_then(|value| value.to_str()) else {
1243        return false;
1244    };
1245    let Some((prefix, token)) = stem.rsplit_once('-') else {
1246        return false;
1247    };
1248    prefix.rsplit_once("-v").is_some()
1249        && token.len() == 32
1250        && token.bytes().all(|value| value.is_ascii_hexdigit())
1251}
1252
1253fn is_versioned_artifact_for_package(name: &str, normalized_package: &str) -> bool {
1254    let Some(stem) = Path::new(name).file_stem().and_then(|value| value.to_str()) else {
1255        return false;
1256    };
1257    let Some((prefix, _)) = stem.rsplit_once("-v") else {
1258        return false;
1259    };
1260    is_versioned_artifact_name(name)
1261        && normalize_name(prefix.trim_start_matches("lib")) == normalized_package
1262}
1263
1264/// Outcome of a best-effort retired-native-artifact cleanup.
1265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1266pub(crate) enum RetiredGcOutcome {
1267    /// Cleanup ran; surviving stale artifacts are not loadable via the registry-aware discovery.
1268    Completed,
1269    /// A live host or mutation held the lease, so on-disk cleanup was skipped.
1270    Deferred,
1271}
1272
1273/// Best-effort cleanup for retired native artifacts. The exclusive resource
1274/// lease is the proof that no host is currently holding the old libraries; a
1275/// live host therefore only causes cleanup to be deferred until a later
1276/// install or explicit maintenance command.
1277pub(crate) fn gc_retired_native_artifacts(agent_dir: &Path) -> RetiredGcOutcome {
1278    let metadata_path = agent_dir.join(NATIVE_PACKAGES_FILE);
1279    let lease = match crate::resource_management::mutation_lease(agent_dir) {
1280        Ok(lease) => lease,
1281        Err(_) => return RetiredGcOutcome::Deferred,
1282    };
1283    let _lock = match NativePackageMutationLock::acquire_with_lease(&metadata_path, lease) {
1284        Ok(lock) => lock,
1285        Err(_) => return RetiredGcOutcome::Deferred,
1286    };
1287    let records = match read_native_package_registry_at(&metadata_path) {
1288        Ok(registry) => registry.into_records(),
1289        Err(_) => return RetiredGcOutcome::Deferred,
1290    };
1291    let active = records
1292        .iter()
1293        .flat_map(|record| record.artifacts.iter())
1294        .map(|artifact| native_artifact_identity(artifact))
1295        .collect::<HashSet<_>>();
1296    let destination = agent_dir.join("extensions");
1297    let Ok(entries) = std::fs::read_dir(&destination) else {
1298        return RetiredGcOutcome::Completed;
1299    };
1300    for entry in entries.flatten() {
1301        let path = entry.path();
1302        let Some(name) = path.file_name().and_then(|value| value.to_str()) else {
1303            continue;
1304        };
1305        if !is_dynamic_library(&path)
1306            || !is_versioned_artifact_name(name)
1307            || active.contains(&native_artifact_identity(name))
1308        {
1309            continue;
1310        }
1311        if crate::resource_management::legacy_unowned_targets(
1312            agent_dir,
1313            std::slice::from_ref(&path),
1314        )
1315        .is_err()
1316        {
1317            continue;
1318        }
1319        let Ok(metadata) = std::fs::symlink_metadata(&path) else {
1320            continue;
1321        };
1322        if metadata.file_type().is_file() {
1323            let _ = std::fs::remove_file(path);
1324        }
1325    }
1326    RetiredGcOutcome::Completed
1327}
1328
1329pub(crate) fn versioned_artifact_name(
1330    original: &str,
1331    version: &str,
1332    destination: &Path,
1333) -> Result<String, String> {
1334    let path = Path::new(original);
1335    let stem = path
1336        .file_stem()
1337        .and_then(|value| value.to_str())
1338        .ok_or_else(|| format!("artifact has no UTF-8 file stem: {original}"))?;
1339    let extension = path
1340        .extension()
1341        .and_then(|value| value.to_str())
1342        .ok_or_else(|| format!("artifact has no dynamic-library extension: {original}"))?;
1343    let version = version
1344        .chars()
1345        .map(|value| {
1346            if value.is_ascii_alphanumeric() || matches!(value, '.' | '-' | '_') {
1347                value
1348            } else {
1349                '_'
1350            }
1351        })
1352        .collect::<String>();
1353    let version = if version.is_empty() {
1354        "unknown"
1355    } else {
1356        &version
1357    };
1358    for _ in 0..8 {
1359        let name = format!(
1360            "{stem}-v{version}-{}.{}",
1361            uuid::Uuid::new_v4().simple(),
1362            extension
1363        );
1364        let target = destination.join(&name);
1365        if matches!(std::fs::symlink_metadata(&target), Err(error) if error.kind() == std::io::ErrorKind::NotFound)
1366        {
1367            return Ok(name);
1368        }
1369    }
1370    Err(format!(
1371        "could not allocate a unique versioned artifact for {original}"
1372    ))
1373}
1374
1375fn artifact_file_name(path: &Path) -> Result<String, String> {
1376    let name = path
1377        .file_name()
1378        .and_then(|name| name.to_str())
1379        .ok_or_else(|| format!("artifact has no UTF-8 file name: {}", path.display()))?;
1380    checked_registered_artifact_path(Path::new("."), name)?;
1381    Ok(name.to_string())
1382}
1383
1384fn checked_registered_artifact_path(destination: &Path, name: &str) -> Result<PathBuf, String> {
1385    let relative = Path::new(name);
1386    let is_single_component = relative.components().count() == 1
1387        && relative.file_name().and_then(|value| value.to_str()) == Some(name);
1388    if !is_single_component || !is_dynamic_library(relative) {
1389        return Err(format!("unsafe native package artifact name `{name}`"));
1390    }
1391    Ok(destination.join(relative))
1392}
1393
1394fn native_artifact_identity(name: &str) -> String {
1395    if cfg!(windows) {
1396        name.to_ascii_lowercase()
1397    } else {
1398        name.to_string()
1399    }
1400}
1401
1402/// Whether two paths name the same existing file (one inode). Windows already folds case
1403/// in `native_artifact_identity`, so only Unix needs the inode check.
1404#[cfg(unix)]
1405fn same_file(left: &Path, right: &Path) -> bool {
1406    use std::os::unix::fs::MetadataExt;
1407    match (
1408        std::fs::symlink_metadata(left),
1409        std::fs::symlink_metadata(right),
1410    ) {
1411        (Ok(left), Ok(right)) => left.dev() == right.dev() && left.ino() == right.ino(),
1412        _ => false,
1413    }
1414}
1415
1416#[cfg(not(unix))]
1417fn same_file(_: &Path, _: &Path) -> bool {
1418    false
1419}
1420
1421fn transaction_path_identity(path: &Path) -> String {
1422    let value = path.to_string_lossy().into_owned();
1423    if cfg!(windows) {
1424        value.to_ascii_lowercase()
1425    } else {
1426        value
1427    }
1428}
1429
1430fn adjacent_transaction_path(target: &Path, kind: &str) -> Result<PathBuf, String> {
1431    let parent = target
1432        .parent()
1433        .ok_or_else(|| format!("transaction target has no parent: {}", target.display()))?;
1434    let leaf = target
1435        .file_name()
1436        .and_then(|name| name.to_str())
1437        .unwrap_or("artifact");
1438    for _ in 0..8 {
1439        let candidate = parent.join(format!(
1440            ".{leaf}.rpi-{kind}-{}",
1441            uuid::Uuid::new_v4().simple()
1442        ));
1443        match std::fs::symlink_metadata(&candidate) {
1444            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(candidate),
1445            Ok(_) => {}
1446            Err(error) => {
1447                return Err(format!(
1448                    "could not inspect transaction path {}: {error}",
1449                    candidate.display()
1450                ))
1451            }
1452        }
1453    }
1454    Err(format!(
1455        "could not allocate a transaction path beside {}",
1456        target.display()
1457    ))
1458}
1459
1460/// macOS only: give a freshly copied native artifact an ad-hoc signature.
1461///
1462/// Why this is mandatory and not cosmetic (2026-11-07, 35 SIGKILLs in one
1463/// afternoon): cargo linker-signs a cdylib and that signature records the
1464/// file's mtime (`cs_mtime`). Any copy — `io::copy`, `fs::copy`, `rename` of a
1465/// rewritten file — gives the copy a **new** mtime, and when the kernel maps a
1466/// code page it compares `cs_mtime` against it. On mismatch it refuses the page
1467/// and **kills the whole host process**:
1468///
1469/// ```text
1470/// CODE SIGNING: process 20087[rpi]: rejecting invalid page at address 0x…
1471///   in file "~/.pidd/rpi-agent/extensions/librpi_superagent.dylib"
1472///   (cs_mtime:1794052202.55 != mtime:1794056571.77)
1473/// ```
1474///
1475/// Nothing is printed and no exit code reaches the terminal except 137, so the
1476/// symptom reads as "rpi will not start any session any more". `codesign -v`
1477/// still reports the copy as valid on disk, so verification is useless here —
1478/// only re-signing realigns `cs_mtime` with the file mtime.
1479pub(crate) fn resign_staged_native(path: &Path) -> Result<(), String> {
1480    if !cfg!(target_os = "macos") {
1481        return Ok(());
1482    }
1483    let out = std::process::Command::new("/usr/bin/codesign")
1484        // Pin the identifier: `--sign -` otherwise derives it from the file NAME,
1485        // so the same bytes staged under different names sign to different bytes.
1486        .args(["--force", "--sign", "-", "--identifier", "com.rpi.native"])
1487        .arg(path)
1488        .output()
1489        .map_err(|error| format!("could not run codesign on {}: {error}", path.display()))?;
1490    if !out.status.success() {
1491        return Err(format!(
1492            "re-signing {} failed (the kernel will refuse to load it): {}",
1493            path.display(),
1494            String::from_utf8_lossy(&out.stderr).trim()
1495        ));
1496    }
1497    Ok(())
1498}
1499
1500fn stage_native_artifact(source: &Path, target: &Path) -> Result<StagedNativeFile, String> {
1501    let stage = adjacent_transaction_path(target, "stage")?;
1502    let result = (|| {
1503        let source_metadata = std::fs::symlink_metadata(source).map_err(|error| {
1504            format!(
1505                "could not inspect built artifact {}: {error}",
1506                source.display()
1507            )
1508        })?;
1509        let mut input = std::fs::File::open(source).map_err(|error| {
1510            format!(
1511                "could not open built artifact {}: {error}",
1512                source.display()
1513            )
1514        })?;
1515        let mut output = std::fs::OpenOptions::new()
1516            .write(true)
1517            .create_new(true)
1518            .open(&stage)
1519            .map_err(|error| {
1520                format!(
1521                    "could not create staged artifact {}: {error}",
1522                    stage.display()
1523                )
1524            })?;
1525        std::io::copy(&mut input, &mut output)
1526            .and_then(|_| output.sync_all())
1527            .map_err(|error| {
1528                format!(
1529                    "could not write staged artifact {} beside {}: {error}",
1530                    stage.display(),
1531                    target.display()
1532                )
1533            })?;
1534        drop(output);
1535        std::fs::set_permissions(&stage, source_metadata.permissions()).map_err(|error| {
1536            format!(
1537                "could not preserve permissions on staged artifact {}: {error}",
1538                stage.display()
1539            )
1540        })?;
1541        resign_staged_native(&stage)
1542    })();
1543    if let Err(error) = result {
1544        let _ = std::fs::remove_file(&stage);
1545        return Err(error);
1546    }
1547    Ok(StagedNativeFile { path: stage })
1548}
1549fn stage_native_bytes(bytes: &[u8], target: &Path) -> Result<StagedNativeFile, String> {
1550    let stage = adjacent_transaction_path(target, "stage")?;
1551    let result = (|| {
1552        let mut file = std::fs::OpenOptions::new()
1553            .write(true)
1554            .create_new(true)
1555            .open(&stage)
1556            .map_err(|error| {
1557                format!(
1558                    "could not create staged registry {}: {error}",
1559                    stage.display()
1560                )
1561            })?;
1562        file.write_all(bytes)
1563            .and_then(|()| file.sync_all())
1564            .map_err(|error| {
1565                format!(
1566                    "could not flush staged registry {}: {error}",
1567                    stage.display()
1568                )
1569            })
1570    })();
1571    if let Err(error) = result {
1572        let _ = std::fs::remove_file(&stage);
1573        return Err(error);
1574    }
1575    Ok(StagedNativeFile { path: stage })
1576}
1577
1578fn activate_native_transaction(
1579    replacements: &[NativeReplacement],
1580    removals: &[PathBuf],
1581    before_activate: &mut impl FnMut(usize, &Path) -> Result<(), String>,
1582) -> Result<(), String> {
1583    let mut affected = Vec::new();
1584    let mut seen = HashSet::new();
1585    for target in replacements
1586        .iter()
1587        .map(|replacement| &replacement.target)
1588        .chain(removals.iter())
1589    {
1590        if seen.insert(transaction_path_identity(target)) {
1591            affected.push(target.clone());
1592        }
1593    }
1594
1595    for target in &affected {
1596        match std::fs::symlink_metadata(target) {
1597            Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => {}
1598            Ok(_) => {
1599                return Err(format!(
1600                    "refusing to replace non-regular native package file {}",
1601                    target.display()
1602                ))
1603            }
1604            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1605            Err(error) => {
1606                return Err(format!(
1607                    "could not inspect native package file {}: {error}",
1608                    target.display()
1609                ))
1610            }
1611        }
1612    }
1613
1614    let mut backups = Vec::new();
1615    for target in &affected {
1616        if !target.exists() {
1617            continue;
1618        }
1619        let backup = match adjacent_transaction_path(target, "backup") {
1620            Ok(backup) => backup,
1621            Err(error) => {
1622                let rollback = rollback_native_transaction(&[], &backups);
1623                return Err(transaction_error(error, rollback));
1624            }
1625        };
1626        if let Err(error) = std::fs::rename(target, &backup) {
1627            let rollback = rollback_native_transaction(&[], &backups);
1628            return Err(transaction_error(
1629                format!("could not back up {}: {error}", target.display()),
1630                rollback,
1631            ));
1632        }
1633        backups.push(NativeBackup {
1634            target: target.clone(),
1635            backup,
1636        });
1637    }
1638
1639    let mut activated = Vec::new();
1640    for (index, replacement) in replacements.iter().enumerate() {
1641        let activation = before_activate(index, &replacement.target).and_then(|()| {
1642            std::fs::rename(&replacement.staged.path, &replacement.target).map_err(|error| {
1643                format!(
1644                    "could not activate replacement {}: {error}",
1645                    replacement.target.display()
1646                )
1647            })
1648        });
1649        if let Err(error) = activation {
1650            let rollback = rollback_native_transaction(&activated, &backups);
1651            return Err(transaction_error(error, rollback));
1652        }
1653        activated.push(replacement.target.clone());
1654    }
1655
1656    for backup in backups {
1657        if let Err(error) = std::fs::remove_file(&backup.backup) {
1658            eprintln!(
1659                "warning: native package updated but backup {} could not be removed: {error}",
1660                backup.backup.display()
1661            );
1662        }
1663    }
1664    Ok(())
1665}
1666
1667fn rollback_native_transaction(
1668    activated: &[PathBuf],
1669    backups: &[NativeBackup],
1670) -> Result<(), String> {
1671    let mut errors = Vec::new();
1672    for target in activated.iter().rev() {
1673        match std::fs::remove_file(target) {
1674            Ok(()) => {}
1675            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1676            Err(error) => errors.push(format!("could not remove {}: {error}", target.display())),
1677        }
1678    }
1679    for backup in backups.iter().rev() {
1680        if let Err(error) = std::fs::rename(&backup.backup, &backup.target) {
1681            errors.push(format!(
1682                "could not restore {} from {}: {error}",
1683                backup.target.display(),
1684                backup.backup.display()
1685            ));
1686        }
1687    }
1688    if errors.is_empty() {
1689        Ok(())
1690    } else {
1691        Err(errors.join("; "))
1692    }
1693}
1694
1695fn transaction_error(error: String, rollback: Result<(), String>) -> String {
1696    match rollback {
1697        Ok(()) => error,
1698        Err(rollback) => format!("{error}; rollback also failed: {rollback}"),
1699    }
1700}
1701
1702fn parse_args(args: &[String]) -> Result<InstallOptions, String> {
1703    let mut package = None;
1704    let mut version = None;
1705    let mut path = None;
1706    let mut locked = false;
1707    let mut force = false;
1708    let mut build = false;
1709    let mut repository = None;
1710    let mut cdn = None;
1711    let mut i = 0;
1712    while i < args.len() {
1713        match args[i].as_str() {
1714            "--help" | "-h" => return Err(help_requested().to_string()),
1715            "--offline" => {} // app normalizes this flag before dispatch
1716            "--locked" => locked = true,
1717            "--force" | "-f" => force = true,
1718            "--build" => build = true,
1719            "--github" => {
1720                i += 1;
1721                repository = Some(value(args, i, "--github")?);
1722            }
1723            "--cdn" => {
1724                i += 1;
1725                cdn = Some(value(args, i, "--cdn")?);
1726            }
1727            "--version" | "-V" => {
1728                i += 1;
1729                version = Some(value(args, i, "--version")?);
1730            }
1731            "--path" => {
1732                i += 1;
1733                path = Some(PathBuf::from(value(args, i, "--path")?));
1734            }
1735            value if value.starts_with('-') => {
1736                return Err(format!("unknown install option `{value}`"));
1737            }
1738            value => {
1739                if package.replace(value.to_string()).is_some() {
1740                    return Err("install accepts exactly one crate name".to_string());
1741                }
1742            }
1743        }
1744        i += 1;
1745    }
1746    if path.is_some() && version.is_some() {
1747        return Err("--path and --version cannot be used together".to_string());
1748    }
1749    if repository.is_some() && (build || path.is_some()) {
1750        return Err("--github cannot be combined with --build or --path".into());
1751    }
1752    if locked && !build && path.is_none() {
1753        return Err("--locked requires --build or --path".into());
1754    }
1755    let package = match package {
1756        Some(package) => package,
1757        None => {
1758            let path = path
1759                .as_deref()
1760                .ok_or_else(|| "missing crate name (or use --path <directory>)".to_string())?;
1761            package_name_from_manifest(path)?
1762        }
1763    };
1764    if !valid_package_name(&package) {
1765        return Err(format!("invalid Cargo package name `{package}`"));
1766    }
1767    let cdn_base = if build || path.is_some() {
1768        None
1769    } else {
1770        crate::cdn::resolve_base(cdn.as_deref())?
1771    };
1772    Ok(InstallOptions {
1773        package,
1774        version,
1775        path,
1776        locked,
1777        force,
1778        build,
1779        repository,
1780        cdn_base,
1781    })
1782}
1783
1784fn value(args: &[String], index: usize, flag: &str) -> Result<String, String> {
1785    args.get(index)
1786        .filter(|value| !value.starts_with('-'))
1787        .cloned()
1788        .ok_or_else(|| format!("{flag} requires a value"))
1789}
1790
1791fn package_name_from_manifest(path: &Path) -> Result<String, String> {
1792    let manifest = if path.is_dir() {
1793        path.join("Cargo.toml")
1794    } else {
1795        path.to_path_buf()
1796    };
1797    let output = Command::new("cargo")
1798        .args([
1799            "metadata",
1800            "--no-deps",
1801            "--format-version",
1802            "1",
1803            "--manifest-path",
1804        ])
1805        .arg(&manifest)
1806        .output()
1807        .map_err(|error| format!("could not run cargo metadata: {error}"))?;
1808    if !output.status.success() {
1809        return Err(format!(
1810            "could not inspect {}: {}",
1811            manifest.display(),
1812            String::from_utf8_lossy(&output.stderr).trim()
1813        ));
1814    }
1815    let metadata: serde_json::Value = serde_json::from_slice(&output.stdout)
1816        .map_err(|error| format!("cargo metadata returned invalid JSON: {error}"))?;
1817    let manifest = std::fs::canonicalize(&manifest)
1818        .map_err(|error| format!("could not resolve {}: {error}", manifest.display()))?;
1819    metadata
1820        .get("packages")
1821        .and_then(serde_json::Value::as_array)
1822        .and_then(|packages| {
1823            packages.iter().find_map(|package| {
1824                let package_manifest = package.get("manifest_path")?.as_str()?;
1825                let package_manifest = std::fs::canonicalize(package_manifest).ok()?;
1826                (package_manifest == manifest)
1827                    .then(|| package.get("name")?.as_str().map(str::to_owned))
1828                    .flatten()
1829            })
1830        })
1831        .filter(|name| valid_package_name(name))
1832        .ok_or_else(|| format!("{} has no valid [package].name", manifest.display()))
1833}
1834
1835fn valid_package_name(name: &str) -> bool {
1836    !name.is_empty()
1837        && name
1838            .bytes()
1839            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
1840}
1841
1842fn help_requested() -> &'static str {
1843    "use `rpi install --help` for usage"
1844}
1845
1846pub fn print_help() {
1847    println!("Usage: rpi install [<crate>] [options]\n\nInstall or upgrade a prebuilt Rust extension using the versioned rpi-extension.json protocol.\nRepository and latest stable version are resolved from crates.io metadata, and a repository move is followed for version discovery while previously published releases stay installable.\nNewer versions upgrade automatically; an already installed version is skipped.\n\nOptions:\n  --version <version>  Install an exact package version\n  --github <owner/repo> Use this GitHub repository; default version comes from package-specific tags\n  --cdn <URL>           Download release archives from this HTTPS CDN; manifests remain on GitHub\n  --build              Explicitly compile the extension with Cargo\n  --path <directory>   Build a local extension crate; crate name may be omitted\n  --locked             Require Cargo.lock to remain unchanged (with --build/--path)\n  --force, -f          Reinstall the same version or allow a downgrade/replacement\n  --help, -h           Show this help\n\nExamples:\n  rpi install rpi-todo\n  rpi install rpi-todo --version 0.2.0\n  rpi install my-extension --github owner/repo --version 1.2.3\n  rpi install rpi-todo --build\n  rpi install --path . --force\n\nA missing or incompatible prebuilt release is an error; Cargo compilation requires --build.");
1848}
1849
1850fn print_uninstall_help() {
1851    println!(
1852        "Usage: rpi uninstall <crate>\n\nRemove a Rust cdylib extension installed by `rpi install`.\n\nOptions:\n  --help, -h           Show this help\n\nExample:\n  rpi uninstall rpi-extension-example"
1853    );
1854}
1855
1856fn write_manifest(path: &Path, options: &InstallOptions) -> Result<(), String> {
1857    let source_dir = path
1858        .parent()
1859        .ok_or_else(|| "temporary workspace has no parent directory".to_string())?
1860        .join("src");
1861    std::fs::create_dir_all(&source_dir).map_err(|error| error.to_string())?;
1862    // Cargo requires the temporary root package to have a target even though
1863    // rpi never builds it; the requested extension is built as a dependency.
1864    std::fs::write(source_dir.join("lib.rs"), "pub fn installer_marker() {}\n")
1865        .map_err(|error| error.to_string())?;
1866    let dependency = if let Some(local_path) = &options.path {
1867        let absolute = if local_path.is_absolute() {
1868            local_path.clone()
1869        } else {
1870            std::env::current_dir()
1871                .map_err(|error| error.to_string())?
1872                .join(local_path)
1873        };
1874        format!(
1875            "rpi_extension_dep = {{ package = {:?}, path = {:?} }}",
1876            options.package,
1877            absolute.display().to_string()
1878        )
1879    } else {
1880        let version = options.version.as_deref().unwrap_or("*");
1881        format!(
1882            "rpi_extension_dep = {{ package = {:?}, version = {:?} }}",
1883            options.package, version
1884        )
1885    };
1886    let contents = format!(
1887        "[package]\nname = \"{INSTALLER_MANIFEST}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\n[workspace]\n\n[dependencies]\n{dependency}\n"
1888    );
1889    std::fs::write(path, contents).map_err(|error| error.to_string())
1890}
1891
1892/// Run the Cargo commands whose output only needs to reach the terminal
1893/// (`fetch`). The `build` step has its own runner so it can capture the JSON
1894/// machine messages that report artifact paths.
1895fn cargo_command(
1896    subcommand: &str,
1897    manifest: &Path,
1898    options: &InstallOptions,
1899) -> Result<(), String> {
1900    let mut command = Command::new("cargo");
1901    command.arg(subcommand).arg("--manifest-path").arg(manifest);
1902    if options.locked {
1903        command.arg("--locked");
1904    }
1905    if crate::args::offline_env_enabled() {
1906        command.arg("--offline");
1907    }
1908    let status = command
1909        .stdin(Stdio::inherit())
1910        .stdout(Stdio::inherit())
1911        .stderr(Stdio::inherit())
1912        .status()
1913        .map_err(|error| format!("could not execute cargo: {error}"))?;
1914    if status.success() {
1915        Ok(())
1916    } else {
1917        Err(format!("cargo {subcommand} exited with {status}"))
1918    }
1919}
1920
1921/// Result of `cargo build --message-format=json-render-diagnostics` for the
1922/// temporary installer workspace.
1923///
1924/// Cargo's build-dir layout is explicitly internal and changed in 1.100.0
1925/// (#15010), which dropped `<profile>/deps` in favour of
1926/// `<profile>/build/<pkg>/<meta>/out`. The JSON machine messages are the
1927/// supported way to learn where a cdylib actually landed, so the artifact paths
1928/// are collected here and the directory scan is only a legacy fallback.
1929struct CargoBuild {
1930    artifacts: Vec<PathBuf>,
1931}
1932
1933impl CargoBuild {
1934    /// Resolve exactly one cdylib per requested target, in target order.
1935    ///
1936    /// Paths reported by Cargo win; only targets Cargo did not name fall back
1937    /// to scanning the build directory.
1938    fn into_artifacts(
1939        self,
1940        release_dir: &Path,
1941        targets: &[&CargoTarget],
1942    ) -> Result<Vec<PathBuf>, String> {
1943        let mut artifacts = Vec::with_capacity(targets.len());
1944        let mut unresolved = Vec::new();
1945        for target in targets {
1946            match self
1947                .artifacts
1948                .iter()
1949                .find(|path| artifact_matches_name(path, &target.name))
1950            {
1951                Some(path) => artifacts.push(path.clone()),
1952                None => unresolved.push(*target),
1953            }
1954        }
1955        if !unresolved.is_empty() {
1956            // `find_artifacts` reports a single missing target per call, so ask
1957            // it for the remaining ones together and preserve their order.
1958            let fallback = find_artifacts(release_dir, &unresolved)?;
1959            artifacts.extend(fallback);
1960        }
1961        Ok(artifacts)
1962    }
1963}
1964
1965/// Match a built dynamic library against a cdylib target name, tolerating the
1966/// platform `lib` prefix and a Cargo metadata hash suffix.
1967fn artifact_matches_name(path: &Path, target: &str) -> bool {
1968    if !is_dynamic_library(path) {
1969        return false;
1970    }
1971    let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
1972        return false;
1973    };
1974    let stem = normalize_name(stem.trim_start_matches("lib"));
1975    let wanted = normalize_name(target);
1976    stem == wanted || stem.starts_with(&format!("{wanted}."))
1977}
1978
1979fn cargo_build(
1980    manifest: &Path,
1981    options: &InstallOptions,
1982    targets: &[&CargoTarget],
1983) -> Result<CargoBuild, String> {
1984    let mut command = Command::new("cargo");
1985    command
1986        .arg("build")
1987        .arg("--manifest-path")
1988        .arg(manifest)
1989        .arg("--package")
1990        .arg(&options.package)
1991        .arg("--release")
1992        .arg("--target-dir")
1993        .arg(manifest.parent().unwrap().join("target"))
1994        .arg("--message-format=json-render-diagnostics");
1995    if options.locked {
1996        command.arg("--locked");
1997    }
1998    if crate::args::offline_env_enabled() {
1999        command.arg("--offline");
2000    }
2001    // Keep Cargo's diagnostics on the terminal while the machine messages on
2002    // stdout are parsed for artifact locations.
2003    command.stdin(Stdio::inherit()).stderr(Stdio::inherit());
2004    let output = command
2005        .output()
2006        .map_err(|error| format!("could not execute cargo: {error}"))?;
2007    if !output.status.success() {
2008        return Err(format!("cargo build exited with {}", output.status));
2009    }
2010    let wanted: Vec<String> = targets
2011        .iter()
2012        .map(|target| normalize_name(&target.name))
2013        .collect();
2014    let mut artifacts = Vec::new();
2015    let mut diagnostics = String::new();
2016    for line in String::from_utf8_lossy(&output.stdout).lines() {
2017        let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
2018            continue;
2019        };
2020        if let Some(rendered) = value
2021            .get("message")
2022            .and_then(|message| message.get("rendered"))
2023            .and_then(|rendered| rendered.as_str())
2024        {
2025            // `json-render-diagnostics` moves diagnostics onto stdout, so the
2026            // rendered text has to be replayed for the user.
2027            diagnostics.push_str(rendered);
2028            continue;
2029        }
2030        if value.get("reason").and_then(|reason| reason.as_str()) != Some("compiler-artifact") {
2031            continue;
2032        }
2033        let Some(name) = value
2034            .get("target")
2035            .and_then(|target| target.get("name"))
2036            .and_then(|name| name.as_str())
2037        else {
2038            continue;
2039        };
2040        if !wanted.contains(&normalize_name(name)) {
2041            continue;
2042        }
2043        artifacts.extend(
2044            value
2045                .get("filenames")
2046                .and_then(|filenames| filenames.as_array())
2047                .into_iter()
2048                .flatten()
2049                .filter_map(|filename| filename.as_str())
2050                .map(PathBuf::from)
2051                .filter(|path| is_dynamic_library(path) && path.is_file()),
2052        );
2053    }
2054    if !diagnostics.is_empty() {
2055        eprint!("{diagnostics}");
2056    }
2057    Ok(CargoBuild { artifacts })
2058}
2059
2060fn cargo_metadata(manifest: &Path, options: &InstallOptions) -> Result<CargoMetadata, String> {
2061    let mut command = Command::new("cargo");
2062    command
2063        .arg("metadata")
2064        .arg("--format-version")
2065        .arg("1")
2066        .arg("--manifest-path")
2067        .arg(manifest);
2068    if options.locked {
2069        command.arg("--locked");
2070    }
2071    if crate::args::offline_env_enabled() {
2072        command.arg("--offline");
2073    }
2074    let output = command
2075        .output()
2076        .map_err(|error| format!("could not execute cargo: {error}"))?;
2077    if !output.status.success() {
2078        return Err(String::from_utf8_lossy(&output.stderr).trim().to_string());
2079    }
2080    serde_json::from_slice(&output.stdout)
2081        .map_err(|error| format!("invalid cargo metadata: {error}"))
2082}
2083
2084fn find_artifacts(release_dir: &Path, targets: &[&CargoTarget]) -> Result<Vec<PathBuf>, String> {
2085    let mut artifacts = Vec::new();
2086    // Legacy layout (<profile>/ and <profile>/deps) plus the 1.100.0 build-dir
2087    // layout (<profile>/build/<pkg>/<meta>/out). Only used as a fallback when
2088    // Cargo's JSON messages did not name the artifact.
2089    let mut dirs = vec![release_dir.to_path_buf(), release_dir.join("deps")];
2090    dirs.extend(build_dir_outputs(release_dir));
2091    for target in targets {
2092        let wanted = normalize_name(&target.name);
2093        let mut matches = Vec::new();
2094        for dir in &dirs {
2095            let entries = match std::fs::read_dir(dir) {
2096                Ok(entries) => entries,
2097                // Cargo omits `deps/` under the 1.100.0 layout; a missing
2098                // candidate directory just contributes no matches.
2099                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
2100                Err(error) => {
2101                    return Err(format!(
2102                        "could not inspect build output {}: {error}",
2103                        dir.display()
2104                    ));
2105                }
2106            };
2107            for entry in entries.flatten() {
2108                let path = entry.path();
2109                if !is_dynamic_library(&path) {
2110                    continue;
2111                }
2112                let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
2113                    continue;
2114                };
2115                let normalized = normalize_name(stem.trim_start_matches("lib"));
2116                if normalized == wanted {
2117                    matches.push(path);
2118                }
2119            }
2120        }
2121        matches.sort_by_key(|path| path.components().count());
2122        let artifact = matches.into_iter().next().ok_or_else(|| {
2123            format!(
2124                "Cargo built `{}` but no cdylib artifact was found in {}",
2125                target.name,
2126                release_dir.display()
2127            )
2128        })?;
2129        artifacts.push(artifact);
2130    }
2131    Ok(artifacts)
2132}
2133
2134fn normalize_name(name: &str) -> String {
2135    name.replace('-', "_").to_ascii_lowercase()
2136}
2137
2138/// Collect `<profile>/build/<pkg>/<meta>/out` directories created by the
2139/// Cargo 1.100.0 build-dir layout. Absent directories simply yield no
2140/// candidates so older Cargo versions keep working unchanged.
2141fn build_dir_outputs(release_dir: &Path) -> Vec<PathBuf> {
2142    let mut outputs = Vec::new();
2143    let Ok(packages) = std::fs::read_dir(release_dir.join("build")) else {
2144        return outputs;
2145    };
2146    for package in packages.flatten() {
2147        let Ok(units) = std::fs::read_dir(package.path()) else {
2148            continue;
2149        };
2150        for unit in units.flatten() {
2151            let out = unit.path().join("out");
2152            if out.is_dir() {
2153                outputs.push(out);
2154            }
2155        }
2156    }
2157    outputs
2158}
2159
2160pub(crate) fn is_dynamic_library(path: &Path) -> bool {
2161    matches!(
2162        path.extension()
2163            .and_then(|extension| extension.to_str())
2164            .map(|extension| extension.to_ascii_lowercase())
2165            .as_deref(),
2166        Some("dll" | "so" | "dylib" | "pyd")
2167    )
2168}
2169
2170#[cfg(test)]
2171mod tests {
2172    use super::*;
2173
2174    /// A staged native artifact must not keep the build-time signature.
2175    ///
2176    /// The copy's mtime no longer matches the `cs_mtime` inside the linker
2177    /// signature, and the kernel answers that mismatch by SIGKILLing the host
2178    /// that maps the page (2026-11-07: 35 silent deaths of `rpi`).
2179    #[cfg(target_os = "macos")]
2180    #[test]
2181    fn staged_native_artifact_is_resigned_before_activation() {
2182        let dir = std::env::temp_dir().join(format!("rpi-resign-{}", std::process::id()));
2183        let _ = std::fs::remove_dir_all(&dir);
2184        std::fs::create_dir_all(&dir).unwrap();
2185        let stage = dir.join("libstaged.dylib");
2186        // Any real Mach-O: the copy gets a fresh mtime and a stale signature.
2187        std::fs::copy("/bin/cp", &stage).unwrap();
2188        resign_staged_native(&stage).unwrap();
2189        let out = std::process::Command::new("/usr/bin/codesign")
2190            .args(["-d", "--verbose=4"])
2191            .arg(&stage)
2192            .output()
2193            .unwrap();
2194        let text = String::from_utf8_lossy(&out.stderr);
2195        assert!(
2196            !text.contains("linker-signed"),
2197            "the staged artifact stayed linker-signed: {text}"
2198        );
2199        let _ = std::fs::remove_dir_all(&dir);
2200    }
2201
2202    fn args(values: &[&str]) -> Vec<String> {
2203        values.iter().map(|value| value.to_string()).collect()
2204    }
2205
2206    fn native_record(name: &str) -> InstalledNativePackage {
2207        InstalledNativePackage {
2208            name: name.to_string(),
2209            version: "1.2.3".to_string(),
2210            source: None,
2211            prebuilt: None,
2212            artifacts: vec![format!("{name}.dll")],
2213        }
2214    }
2215
2216    #[test]
2217    fn install_version_policy_allows_upgrades_and_requires_force_for_downgrades() {
2218        assert!(should_install_version("demo", None, "1.0.0", false).unwrap());
2219        for (current, requested) in [
2220            ("0.1.11", "0.1.12"),
2221            ("1.0.0-beta.1", "1.0.0"),
2222            ("1.0.0-beta.1", "1.0.0-beta.2"),
2223        ] {
2224            assert!(should_install_version("demo", Some(current), requested, false).unwrap());
2225            let error =
2226                should_install_version("demo", Some(requested), current, false).unwrap_err();
2227            assert!(error.contains("--force to downgrade"), "{error}");
2228            assert!(should_install_version("demo", Some(requested), current, true).unwrap());
2229        }
2230        for requested in ["1.2.3", "1.2.3+new-build"] {
2231            assert!(!should_install_version("demo", Some("1.2.3"), requested, false).unwrap());
2232            assert!(should_install_version("demo", Some("1.2.3"), requested, true).unwrap());
2233        }
2234        assert!(should_install_version("demo", Some("unknown"), "1.0.0", false).is_err());
2235        assert!(should_install_version("demo", Some("unknown"), "1.0.0", true).unwrap());
2236    }
2237
2238    #[test]
2239    fn native_install_same_version_is_unchanged_and_force_reinstalls_or_downgrades() {
2240        let temp = tempfile::tempdir().unwrap();
2241        let destination = temp.path().join("extensions");
2242        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
2243        let build = temp.path().join("demo.dll");
2244        std::fs::create_dir_all(&destination).unwrap();
2245        std::fs::write(destination.join("demo.dll"), b"installed").unwrap();
2246        let record = native_record("demo");
2247        write_native_packages_at(&metadata, &[record.clone()]).unwrap();
2248        let original_registry = std::fs::read(&metadata).unwrap();
2249        std::fs::write(&build, b"rebuilt").unwrap();
2250
2251        assert!(install_native_package_at(
2252            &destination,
2253            &metadata,
2254            record.clone(),
2255            &[build.clone()],
2256            false,
2257        )
2258        .unwrap()
2259        .is_empty());
2260        assert_eq!(
2261            std::fs::read(destination.join("demo.dll")).unwrap(),
2262            b"installed"
2263        );
2264        assert_eq!(std::fs::read(&metadata).unwrap(), original_registry);
2265        let mut older = record.clone();
2266        older.version = "1.0.0".into();
2267        let error = install_native_package_at(
2268            &destination,
2269            &metadata,
2270            older.clone(),
2271            &[build.clone()],
2272            false,
2273        )
2274        .unwrap_err();
2275        assert!(error.contains("--force to downgrade"));
2276        assert_eq!(
2277            std::fs::read(destination.join("demo.dll")).unwrap(),
2278            b"installed"
2279        );
2280        assert_eq!(std::fs::read(&metadata).unwrap(), original_registry);
2281
2282        for forced in [record, older] {
2283            install_native_package_at(
2284                &destination,
2285                &metadata,
2286                forced.clone(),
2287                &[build.clone()],
2288                true,
2289            )
2290            .unwrap();
2291            let records = read_native_package_registry_at(&metadata)
2292                .unwrap()
2293                .into_records();
2294            assert_eq!(records[0].version, forced.version);
2295            let active = destination.join(&records[0].artifacts[0]);
2296            assert_eq!(std::fs::read(active).unwrap(), b"rebuilt");
2297            assert_eq!(
2298                std::fs::read(destination.join("demo.dll")).unwrap(),
2299                b"installed"
2300            );
2301        }
2302        assert_no_native_transaction_files(&destination);
2303    }
2304
2305    #[test]
2306    fn native_upgrade_does_not_overwrite_unowned_artifacts() {
2307        let temp = tempfile::tempdir().unwrap();
2308        let destination = temp.path().join("extensions");
2309        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
2310        std::fs::create_dir_all(&destination).unwrap();
2311        std::fs::write(destination.join("demo.dll"), b"installed").unwrap();
2312        std::fs::write(destination.join("unowned.dll"), b"unowned").unwrap();
2313        write_native_packages_at(&metadata, &[native_record("demo")]).unwrap();
2314        let original_registry = std::fs::read(&metadata).unwrap();
2315        let artifact = temp.path().join("build-unowned.dll");
2316        std::fs::write(&artifact, b"new").unwrap();
2317        let mut upgraded = native_record("demo");
2318        upgraded.version = "2.0.0".into();
2319        let installed =
2320            install_native_package_at(&destination, &metadata, upgraded, &[artifact], false)
2321                .unwrap();
2322        assert_eq!(installed.len(), 1);
2323        assert_eq!(
2324            std::fs::read(destination.join("demo.dll")).unwrap(),
2325            b"installed"
2326        );
2327        assert_eq!(
2328            std::fs::read(destination.join("unowned.dll")).unwrap(),
2329            b"unowned"
2330        );
2331        assert_ne!(std::fs::read(&metadata).unwrap(), original_registry);
2332        assert_no_native_transaction_files(&destination);
2333    }
2334
2335    struct TempAgent {
2336        _guard: std::sync::MutexGuard<'static, ()>,
2337        temp: tempfile::TempDir,
2338        previous: Option<std::ffi::OsString>,
2339    }
2340
2341    impl TempAgent {
2342        fn new() -> Self {
2343            let guard = crate::config::test_support::env_lock()
2344                .lock()
2345                .unwrap_or_else(|poisoned| poisoned.into_inner());
2346            let previous = std::env::var_os(crate::config::CONFIG_DIR_ENV);
2347            let temp = tempfile::tempdir().unwrap();
2348            std::env::set_var(crate::config::CONFIG_DIR_ENV, temp.path());
2349            Self {
2350                _guard: guard,
2351                temp,
2352                previous,
2353            }
2354        }
2355
2356        fn metadata_path(&self) -> PathBuf {
2357            self.temp.path().join(NATIVE_PACKAGES_FILE)
2358        }
2359    }
2360
2361    impl Drop for TempAgent {
2362        fn drop(&mut self) {
2363            match self.previous.take() {
2364                Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
2365                None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
2366            }
2367        }
2368    }
2369
2370    #[test]
2371    fn parses_registry_package_and_options() {
2372        let parsed = parse_args(&args(&["my-extension", "--version", "1.2.3", "--force"])).unwrap();
2373        assert_eq!(parsed.package, "my-extension");
2374        assert_eq!(parsed.version.as_deref(), Some("1.2.3"));
2375        assert!(parsed.force);
2376    }
2377
2378    #[test]
2379    fn github_override_and_source_build_are_explicit_options() {
2380        let custom = parse_args(&args(&[
2381            "my-extension",
2382            "--github",
2383            "publisher/monorepo",
2384            "--version",
2385            "1.2.3",
2386        ]))
2387        .unwrap();
2388        assert_eq!(custom.repository.as_deref(), Some("publisher/monorepo"));
2389        assert_eq!(custom.version.as_deref(), Some("1.2.3"));
2390        assert!(!custom.build);
2391        let custom_url = parse_args(&args(&[
2392            "my-extension",
2393            "--github",
2394            "https://github.com/publisher/monorepo",
2395        ]))
2396        .unwrap();
2397        assert!(custom_url.repository.is_some());
2398        assert!(
2399            parse_args(&args(&["my-extension", "--build", "--locked"]))
2400                .unwrap()
2401                .build
2402        );
2403        assert!(parse_args(&args(&["my-extension", "--offline"])).is_ok());
2404        assert!(parse_args(&args(&[
2405            "my-extension",
2406            "--github",
2407            "owner/repo",
2408            "--build"
2409        ]))
2410        .is_err());
2411        assert!(parse_args(&args(&[
2412            "my-extension",
2413            "--github",
2414            "owner/repo",
2415            "--path",
2416            "."
2417        ]))
2418        .is_err());
2419        assert!(parse_args(&args(&["my-extension", "--locked"])).is_err());
2420    }
2421
2422    #[test]
2423    fn synchronous_source_backend_cannot_silently_compile_a_prebuilt_request() {
2424        let _agent = TempAgent::new();
2425        assert_eq!(run(&args(&["demo"])), 2);
2426        assert_eq!(
2427            run(&args(&[
2428                "demo",
2429                "--github",
2430                "publisher/repo",
2431                "--version",
2432                "1.2.3"
2433            ])),
2434            2
2435        );
2436    }
2437
2438    #[test]
2439    fn legacy_prebuilt_markers_remain_registry_updatable() {
2440        let record: InstalledNativePackage = serde_json::from_value(serde_json::json!({
2441            "name":"demo", "version":"1.2.3",
2442            "source":"prebuilt:https://github.com/pi-rust/rpi-package",
2443            "artifacts":["custom.so"]
2444        }))
2445        .unwrap();
2446        assert!(record.supports_registry_update());
2447        assert_eq!(
2448            record.legacy_prebuilt_repository(),
2449            Some("https://github.com/pi-rust/rpi-package")
2450        );
2451        // Exact provenance wins; local development builds stay excluded.
2452        let mut exact = record.clone();
2453        exact.prebuilt = Some(crate::prebuilt_extensions::PrebuiltRecord {
2454            repository: "https://github.com/pi-rust/rpi-package".into(),
2455            target: "x86_64-apple-darwin".into(),
2456            manifest_sha256: "a".repeat(64),
2457            source_commit: "b".repeat(40),
2458            sdk_version: "0.4.0".into(),
2459            plugin_abi: 4,
2460            archive_sha256: "c".repeat(64),
2461            library_sha256: "d".repeat(64),
2462            custom_repository: true,
2463            assets: Vec::new(),
2464        });
2465        assert!(exact.supports_registry_update());
2466        assert_eq!(exact.legacy_prebuilt_repository(), None);
2467        let mut local = record;
2468        local.source = Some("../local-ext".into());
2469        assert!(!local.supports_registry_update());
2470        assert_eq!(local.legacy_prebuilt_repository(), None);
2471    }
2472
2473    #[test]
2474    fn uninstall_prebuilt_package_uses_its_recorded_library_name() {
2475        let agent = TempAgent::new();
2476        let directory = agent.temp.path().join("extensions");
2477        std::fs::create_dir_all(&directory).unwrap();
2478        std::fs::write(directory.join("different_library.dll"), b"prebuilt library").unwrap();
2479        let record: InstalledNativePackage = serde_json::from_value(serde_json::json!({
2480            "name":"demo", "version":"1.2.3", "source":"prebuilt:https://github.com/owner/repo",
2481            "artifacts":["different_library.dll"],
2482            "prebuilt":{"repository":"https://github.com/owner/repo", "target":"x86_64-pc-windows-msvc",
2483                "manifest_sha256":"a".repeat(64),"source_commit":"b".repeat(40),"sdk_version":"0.3.23","plugin_abi":4,
2484                "archive_sha256":"c".repeat(64),"library_sha256":"d".repeat(64),"custom_repository":true}
2485        })).unwrap();
2486        write_native_packages_at(&agent.metadata_path(), &[record]).unwrap();
2487        assert_eq!(uninstall(&args(&["demo"])), 0);
2488        assert!(!directory.join("different_library.dll").exists());
2489        assert!(installed_native_packages_strict().unwrap().is_empty());
2490    }
2491
2492    #[test]
2493    fn parses_local_package() {
2494        let parsed = parse_args(&args(&["--path", "../extension", "my-extension"])).unwrap();
2495        assert_eq!(parsed.path, Some(PathBuf::from("../extension")));
2496    }
2497
2498    #[test]
2499    fn local_path_can_infer_package_name() {
2500        let parsed = parse_args(&args(&["--path", ".", "--force"])).unwrap();
2501        assert!(!parsed.package.is_empty());
2502        assert!(valid_package_name(&parsed.package));
2503        assert!(parsed.force);
2504    }
2505
2506    #[test]
2507    fn rejects_non_extension_options_and_invalid_names() {
2508        assert!(parse_args(&args(&["my.extension"])).is_err());
2509        assert!(parse_args(&args(&["my-extension", "--unknown"])).is_err());
2510        assert!(parse_args(&args(&["my-extension", "--path", ".", "--version", "1"])).is_err());
2511    }
2512
2513    #[test]
2514    fn cdylib_hint_recommends_unified_and_documents_legacy_compatibility() {
2515        assert!(CDYLIB_EXTENSION_HINT.contains("rpi_plugin_register"));
2516        assert!(CDYLIB_EXTENSION_HINT.contains("rpi_plugin_register_v2"));
2517        assert!(CDYLIB_EXTENSION_HINT.contains("rpi_plugin_register_v3"));
2518    }
2519
2520    #[test]
2521    fn registry_read_distinguishes_missing_and_valid_files() {
2522        let temp = tempfile::tempdir().unwrap();
2523        let path = temp.path().join(NATIVE_PACKAGES_FILE);
2524
2525        assert_eq!(
2526            read_native_package_registry_at(&path).unwrap(),
2527            NativePackageRegistry::Missing
2528        );
2529
2530        std::fs::write(
2531            &path,
2532            br#"[{"name":"demo","version":"1.2.3","source":null}]"#,
2533        )
2534        .unwrap();
2535        assert_eq!(
2536            read_native_package_registry_at(&path).unwrap(),
2537            NativePackageRegistry::Valid(vec![InstalledNativePackage {
2538                name: "demo".to_string(),
2539                version: "1.2.3".to_string(),
2540                source: None,
2541                prebuilt: None,
2542                artifacts: Vec::new(),
2543            }])
2544        );
2545    }
2546
2547    #[test]
2548    fn active_global_artifacts_exclude_retired_versioned_files() {
2549        let agent = tempfile::tempdir().unwrap();
2550        let extensions = agent.path().join("extensions");
2551        std::fs::create_dir_all(&extensions).unwrap();
2552        let active = "libdemo-v2.0.0-0123456789abcdef0123456789abcdef.dll";
2553        let retired = "libdemo-v1.0.0-abcdef0123456789abcdef0123456789.dll";
2554        std::fs::write(extensions.join(active), b"active").unwrap();
2555        std::fs::write(extensions.join(retired), b"retired").unwrap();
2556        std::fs::write(extensions.join("legacy.dll"), b"legacy").unwrap();
2557        write_native_packages_at(
2558            &agent.path().join(NATIVE_PACKAGES_FILE),
2559            &[InstalledNativePackage {
2560                name: "demo".into(),
2561                version: "2.0.0".into(),
2562                source: None,
2563                prebuilt: None,
2564                artifacts: vec![active.into()],
2565            }],
2566        )
2567        .unwrap();
2568
2569        assert_eq!(
2570            active_global_native_package_artifacts_at(agent.path()).unwrap(),
2571            vec![extensions.join(active)]
2572        );
2573        assert_eq!(
2574            unregistered_global_native_package_artifacts_at(agent.path()).unwrap(),
2575            vec![extensions.join("legacy.dll")]
2576        );
2577    }
2578
2579    #[test]
2580    fn registry_read_rejects_corrupt_json() {
2581        let temp = tempfile::tempdir().unwrap();
2582        let path = temp.path().join(NATIVE_PACKAGES_FILE);
2583        std::fs::write(&path, b"[{").unwrap();
2584
2585        let error = read_native_package_registry_at(&path).unwrap_err();
2586        assert!(error.contains("invalid JSON or schema"));
2587    }
2588
2589    #[test]
2590    fn registry_read_rejects_wrong_schema() {
2591        let temp = tempfile::tempdir().unwrap();
2592        let path = temp.path().join(NATIVE_PACKAGES_FILE);
2593        std::fs::write(&path, br#"{"name":"demo","version":"1.2.3"}"#).unwrap();
2594
2595        let error = read_native_package_registry_at(&path).unwrap_err();
2596        assert!(error.contains("invalid JSON or schema"));
2597    }
2598
2599    #[test]
2600    fn record_does_not_replace_a_corrupt_registry() {
2601        let temp = tempfile::tempdir().unwrap();
2602        let path = temp.path().join(NATIVE_PACKAGES_FILE);
2603        let original = b"[{broken metadata";
2604        std::fs::write(&path, original).unwrap();
2605
2606        assert!(record_native_package_at(&path, &native_record("demo")).is_err());
2607        assert_eq!(std::fs::read(&path).unwrap(), original);
2608    }
2609
2610    #[test]
2611    fn native_install_transaction_preserves_loaded_artifacts_and_publishes_new_ones() {
2612        let temp = tempfile::tempdir().unwrap();
2613        let destination = temp.path().join("extensions");
2614        let metadata_path = temp.path().join(NATIVE_PACKAGES_FILE);
2615        let build = temp.path().join("build");
2616        std::fs::create_dir_all(&destination).unwrap();
2617        std::fs::create_dir_all(&build).unwrap();
2618        std::fs::write(destination.join("old.dll"), b"old-only").unwrap();
2619        std::fs::write(destination.join("same.dll"), b"old-shared").unwrap();
2620        let old = InstalledNativePackage {
2621            name: "demo".into(),
2622            version: "1.0.0".into(),
2623            source: None,
2624            prebuilt: None,
2625            artifacts: vec!["old.dll".into(), "same.dll".into()],
2626        };
2627        write_native_packages_at(&metadata_path, &[old]).unwrap();
2628        std::fs::write(build.join("new.dll"), b"new-only").unwrap();
2629        std::fs::write(build.join("same.dll"), b"new-shared").unwrap();
2630
2631        let installed = install_native_package_at(
2632            &destination,
2633            &metadata_path,
2634            InstalledNativePackage {
2635                name: "demo".into(),
2636                version: "2.0.0".into(),
2637                source: None,
2638                prebuilt: None,
2639                artifacts: Vec::new(),
2640            },
2641            &[build.join("new.dll"), build.join("same.dll")],
2642            false,
2643        )
2644        .unwrap();
2645
2646        assert_eq!(installed.len(), 2);
2647        assert!(installed.iter().all(|path| path.exists()));
2648        assert_eq!(
2649            std::fs::read(destination.join("old.dll")).unwrap(),
2650            b"old-only"
2651        );
2652        assert_eq!(
2653            std::fs::read(destination.join("same.dll")).unwrap(),
2654            b"old-shared"
2655        );
2656        assert!(installed
2657            .iter()
2658            .any(|path| { std::fs::read(path).ok().as_deref() == Some(b"new-only".as_slice()) }));
2659        assert!(installed
2660            .iter()
2661            .any(|path| { std::fs::read(path).ok().as_deref() == Some(b"new-shared".as_slice()) }));
2662        let records = read_native_package_registry_at(&metadata_path)
2663            .unwrap()
2664            .into_records();
2665        assert_eq!(records.len(), 1);
2666        assert_eq!(records[0].version, "2.0.0");
2667        let active_names = installed
2668            .iter()
2669            .map(|path| path.file_name().unwrap().to_string_lossy().into_owned())
2670            .collect::<Vec<_>>();
2671        assert_eq!(records[0].artifacts, active_names);
2672        assert_no_native_transaction_files(temp.path());
2673        assert_no_native_transaction_files(&destination);
2674    }
2675
2676    #[test]
2677    fn native_install_transaction_rolls_back_artifacts_and_registry() {
2678        let temp = tempfile::tempdir().unwrap();
2679        let destination = temp.path().join("extensions");
2680        let metadata_path = temp.path().join(NATIVE_PACKAGES_FILE);
2681        let build = temp.path().join("build");
2682        std::fs::create_dir_all(&destination).unwrap();
2683        std::fs::create_dir_all(&build).unwrap();
2684        std::fs::write(destination.join("old.dll"), b"old-only").unwrap();
2685        std::fs::write(destination.join("same.dll"), b"old-shared").unwrap();
2686        let old = InstalledNativePackage {
2687            name: "demo".into(),
2688            version: "1.0.0".into(),
2689            source: None,
2690            prebuilt: None,
2691            artifacts: vec!["old.dll".into(), "same.dll".into()],
2692        };
2693        write_native_packages_at(&metadata_path, &[old]).unwrap();
2694        let original_registry = std::fs::read(&metadata_path).unwrap();
2695        std::fs::write(build.join("new.dll"), b"new-only").unwrap();
2696        std::fs::write(build.join("same.dll"), b"new-shared").unwrap();
2697
2698        let error = install_native_package_at_with_hook(
2699            &destination,
2700            &metadata_path,
2701            InstalledNativePackage {
2702                name: "demo".into(),
2703                version: "2.0.0".into(),
2704                source: None,
2705                prebuilt: None,
2706                artifacts: Vec::new(),
2707            },
2708            &[build.join("new.dll"), build.join("same.dll")],
2709            &[],
2710            false,
2711            |_, target| {
2712                if target == metadata_path {
2713                    Err("injected registry activation failure".into())
2714                } else {
2715                    Ok(())
2716                }
2717            },
2718        )
2719        .unwrap_err();
2720
2721        assert!(error.contains("injected registry activation failure"));
2722        assert_eq!(std::fs::read(&metadata_path).unwrap(), original_registry);
2723        assert_eq!(
2724            std::fs::read(destination.join("old.dll")).unwrap(),
2725            b"old-only"
2726        );
2727        assert_eq!(
2728            std::fs::read(destination.join("same.dll")).unwrap(),
2729            b"old-shared"
2730        );
2731        assert!(!destination.join("new.dll").exists());
2732        assert_no_native_transaction_files(temp.path());
2733        assert_no_native_transaction_files(&destination);
2734    }
2735
2736    #[test]
2737    fn registry_aware_gc_removes_stale_versioned_cdylibs_but_keeps_active_and_legacy() {
2738        let agent = TempAgent::new();
2739        let extensions = agent.temp.path().join("extensions");
2740        std::fs::create_dir_all(&extensions).unwrap();
2741        let active = "librpi_web_extension-v0.1.64-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.so";
2742        let stale = "librpi_web_extension-v0.1.64-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.so";
2743        let stale_old = "librpi_web_extension-v0.1.63-cccccccccccccccccccccccccccccccc.so";
2744        let legacy = "legacy_custom.so";
2745        for name in [active, stale, stale_old, legacy] {
2746            std::fs::write(extensions.join(name), b"cdylib").unwrap();
2747        }
2748        write_native_packages_at(
2749            &agent.metadata_path(),
2750            &[InstalledNativePackage {
2751                name: "rpi-web".into(),
2752                version: "0.1.64".into(),
2753                source: None,
2754                prebuilt: None,
2755                artifacts: vec![active.into()],
2756            }],
2757        )
2758        .unwrap();
2759
2760        // `tempfile` hands back `/var/folders/...` on macOS, and the resource
2761        // lease rejects a root reached through a symlink (`/var` -> `/private/var`),
2762        // so canonicalize before asking for the lease.
2763        let agent_dir = std::fs::canonicalize(agent.temp.path()).unwrap();
2764        assert_eq!(
2765            gc_retired_native_artifacts(&agent_dir),
2766            RetiredGcOutcome::Completed
2767        );
2768        assert!(extensions.join(active).exists());
2769        assert!(extensions.join(legacy).exists());
2770        assert!(!extensions.join(stale).exists());
2771        assert!(!extensions.join(stale_old).exists());
2772    }
2773
2774    #[test]
2775    fn registry_aware_gc_is_deferred_while_a_host_holds_the_lease() {
2776        let agent = TempAgent::new();
2777        let extensions = agent.temp.path().join("extensions");
2778        let cwd = agent.temp.path().join("project");
2779        std::fs::create_dir_all(&extensions).unwrap();
2780        std::fs::create_dir_all(&cwd).unwrap();
2781        let stale = "librpi_web_extension-v0.1.64-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.so";
2782        std::fs::write(extensions.join(stale), b"cdylib").unwrap();
2783        let _leases = crate::resource_management::host_leases(&cwd).unwrap();
2784
2785        let agent_dir = std::fs::canonicalize(agent.temp.path()).unwrap();
2786        assert_eq!(
2787            gc_retired_native_artifacts(&agent_dir),
2788            RetiredGcOutcome::Deferred
2789        );
2790        assert!(extensions.join(stale).exists());
2791    }
2792
2793    fn assert_no_native_transaction_files(directory: &Path) {
2794        for entry in std::fs::read_dir(directory).unwrap() {
2795            let name = entry.unwrap().file_name().to_string_lossy().into_owned();
2796            assert!(!name.contains(".rpi-stage-"), "left staged file: {name}");
2797            assert!(!name.contains(".rpi-backup-"), "left backup file: {name}");
2798            assert!(
2799                !name.contains(".rpi-assets-stage-"),
2800                "left asset stage: {name}"
2801            );
2802        }
2803    }
2804
2805    #[test]
2806    fn best_effort_registry_read_omits_corrupt_metadata() {
2807        let agent = TempAgent::new();
2808        std::fs::write(agent.metadata_path(), b"[{broken metadata").unwrap();
2809
2810        assert!(installed_native_packages().is_empty());
2811    }
2812
2813    #[test]
2814    fn install_fails_closed_before_work_when_registry_is_corrupt() {
2815        let agent = TempAgent::new();
2816        let path = agent.metadata_path();
2817        let original = b"[{broken metadata";
2818        std::fs::write(&path, original).unwrap();
2819
2820        assert_eq!(run(&args(&["demo"])), 1);
2821        assert_eq!(std::fs::read(&path).unwrap(), original);
2822        assert!(!agent.temp.path().join("extensions").exists());
2823    }
2824
2825    #[test]
2826    fn uninstall_fails_closed_without_removing_artifacts() {
2827        let agent = TempAgent::new();
2828        let path = agent.metadata_path();
2829        let original = b"[{broken metadata";
2830        std::fs::write(&path, original).unwrap();
2831        let extension_dir = agent.temp.path().join("extensions");
2832        std::fs::create_dir_all(&extension_dir).unwrap();
2833        let artifact = extension_dir.join("demo.dll");
2834        std::fs::write(&artifact, b"extension").unwrap();
2835
2836        assert_eq!(uninstall(&args(&["demo"])), 1);
2837        assert_eq!(std::fs::read(&path).unwrap(), original);
2838        assert_eq!(std::fs::read(artifact).unwrap(), b"extension");
2839    }
2840
2841    #[test]
2842    fn uninstall_commits_artifact_and_registry_changes_together() {
2843        let agent = TempAgent::new();
2844        let extension_dir = agent.temp.path().join("extensions");
2845        std::fs::create_dir_all(&extension_dir).unwrap();
2846        std::fs::write(extension_dir.join("demo.dll"), b"demo").unwrap();
2847        std::fs::write(extension_dir.join("other.dll"), b"other").unwrap();
2848        write_native_packages_at(
2849            &agent.metadata_path(),
2850            &[native_record("demo"), native_record("other")],
2851        )
2852        .unwrap();
2853
2854        assert_eq!(uninstall(&args(&["demo"])), 0);
2855        assert!(!extension_dir.join("demo.dll").exists());
2856        assert_eq!(
2857            std::fs::read(extension_dir.join("other.dll")).unwrap(),
2858            b"other"
2859        );
2860        assert_eq!(
2861            read_native_package_registry_at(&agent.metadata_path())
2862                .unwrap()
2863                .into_records(),
2864            vec![native_record("other")]
2865        );
2866        assert_no_native_transaction_files(agent.temp.path());
2867        assert_no_native_transaction_files(&extension_dir);
2868    }
2869
2870    #[test]
2871    fn uninstall_uses_recorded_artifacts_without_name_fallback() {
2872        let agent = TempAgent::new();
2873        let extension_dir = agent.temp.path().join("extensions");
2874        std::fs::create_dir_all(&extension_dir).unwrap();
2875        std::fs::write(extension_dir.join("recorded.dll"), b"managed").unwrap();
2876        std::fs::write(extension_dir.join("demo.dll"), b"unmanaged").unwrap();
2877        write_native_packages_at(
2878            &agent.metadata_path(),
2879            &[InstalledNativePackage {
2880                name: "demo".into(),
2881                version: "1.2.3".into(),
2882                source: None,
2883                prebuilt: None,
2884                artifacts: vec!["recorded.dll".into()],
2885            }],
2886        )
2887        .unwrap();
2888
2889        assert_eq!(uninstall(&args(&["demo"])), 0);
2890        assert!(!extension_dir.join("recorded.dll").exists());
2891        assert_eq!(
2892            std::fs::read(extension_dir.join("demo.dll")).unwrap(),
2893            b"unmanaged"
2894        );
2895        assert!(!agent.metadata_path().exists());
2896        assert_no_native_transaction_files(agent.temp.path());
2897        assert_no_native_transaction_files(&extension_dir);
2898    }
2899
2900    /// A prebuilt record whose ledger names `assets`, as the archive installer writes it.
2901    fn prebuilt_record(
2902        name: &str,
2903        version: &str,
2904        assets: &[(&str, &[u8])],
2905    ) -> InstalledNativePackage {
2906        InstalledNativePackage {
2907            name: name.into(),
2908            version: version.into(),
2909            source: Some(format!("prebuilt:https://github.com/owner/{name}")),
2910            prebuilt: Some(crate::prebuilt_extensions::PrebuiltRecord {
2911                repository: format!("https://github.com/owner/{name}"),
2912                target: "x86_64-unknown-linux-gnu".into(),
2913                manifest_sha256: "a".repeat(64),
2914                source_commit: "b".repeat(40),
2915                sdk_version: "0.3.23".into(),
2916                plugin_abi: 4,
2917                archive_sha256: "c".repeat(64),
2918                library_sha256: "d".repeat(64),
2919                custom_repository: false,
2920                assets: assets
2921                    .iter()
2922                    .map(|(path, bytes)| crate::prebuilt_extensions::PrebuiltAsset {
2923                        path: (*path).into(),
2924                        sha256: crate::prebuilt_extensions::hash(bytes),
2925                    })
2926                    .collect(),
2927            }),
2928            artifacts: Vec::new(),
2929        }
2930    }
2931
2932    fn sidecars(assets: &[(&str, &[u8])]) -> Vec<NativeAssetFile> {
2933        assets
2934            .iter()
2935            .map(|(path, bytes)| NativeAssetFile {
2936                path: (*path).into(),
2937                bytes: bytes.to_vec(),
2938            })
2939            .collect()
2940    }
2941
2942    #[test]
2943    fn native_asset_upgrade_replaces_sidecars_and_prunes_stale_ones() {
2944        let temp = tempfile::tempdir().unwrap();
2945        let destination = temp.path().join("extensions");
2946        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
2947        let library = temp.path().join("libdemo.so");
2948        std::fs::write(&library, b"library v1").unwrap();
2949        let v1 = [
2950            ("runtime/main.mjs", &b"v1"[..]),
2951            ("runtime/old.mjs", &b"old"[..]),
2952        ];
2953        install_native_package_with_assets_at(
2954            &destination,
2955            &metadata,
2956            prebuilt_record("demo", "1.0.0", &v1),
2957            std::slice::from_ref(&library),
2958            &sidecars(&v1),
2959            false,
2960        )
2961        .unwrap();
2962        assert_eq!(
2963            std::fs::read(destination.join("runtime/old.mjs")).unwrap(),
2964            b"old"
2965        );
2966
2967        std::fs::write(&library, b"library v2").unwrap();
2968        let v2 = [
2969            ("runtime/main.mjs", &b"v2"[..]),
2970            ("runtime/deep/lib.mjs", &b"deep"[..]),
2971        ];
2972        let installed = install_native_package_with_assets_at(
2973            &destination,
2974            &metadata,
2975            prebuilt_record("demo", "2.0.0", &v2),
2976            std::slice::from_ref(&library),
2977            &sidecars(&v2),
2978            false,
2979        )
2980        .unwrap();
2981        assert_eq!(installed.len(), 3);
2982        let active_library = installed
2983            .iter()
2984            .find(|path| is_dynamic_library(path))
2985            .expect("installed library");
2986        assert_ne!(active_library, &destination.join("libdemo.so"));
2987        assert_eq!(std::fs::read(active_library).unwrap(), b"library v2");
2988        assert_eq!(
2989            std::fs::read(destination.join("libdemo.so")).unwrap(),
2990            b"library v1"
2991        );
2992        assert_eq!(
2993            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
2994            b"v2"
2995        );
2996        assert_eq!(
2997            std::fs::read(destination.join("runtime/deep/lib.mjs")).unwrap(),
2998            b"deep"
2999        );
3000        assert!(!destination.join("runtime/old.mjs").exists());
3001        let records = read_native_package_registry_at(&metadata)
3002            .unwrap()
3003            .into_records();
3004        assert_eq!(records[0].version, "2.0.0");
3005        let ledger: Vec<&str> = recorded_asset_paths(&records[0]);
3006        assert_eq!(ledger, vec!["runtime/main.mjs", "runtime/deep/lib.mjs"]);
3007        // Dropping every sidecar removes the files and the directories they emptied.
3008        install_native_package_with_assets_at(
3009            &destination,
3010            &metadata,
3011            prebuilt_record("demo", "3.0.0", &[]),
3012            std::slice::from_ref(&library),
3013            &[],
3014            false,
3015        )
3016        .unwrap();
3017        assert!(!destination.join("runtime").exists());
3018        let records = read_native_package_registry_at(&metadata)
3019            .unwrap()
3020            .into_records();
3021        let active_library = destination.join(&records[0].artifacts[0]);
3022        assert_eq!(std::fs::read(active_library).unwrap(), b"library v2");
3023        assert_eq!(
3024            std::fs::read(destination.join("libdemo.so")).unwrap(),
3025            b"library v1"
3026        );
3027        assert_no_native_transaction_files(temp.path());
3028        assert_no_native_transaction_files(&destination);
3029    }
3030
3031    #[test]
3032    fn native_asset_failure_during_activation_restores_the_previous_install() {
3033        let temp = tempfile::tempdir().unwrap();
3034        let destination = temp.path().join("extensions");
3035        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3036        let library = temp.path().join("libdemo.so");
3037        std::fs::write(&library, b"old library").unwrap();
3038        let v1 = [("runtime/main.mjs", &b"v1"[..])];
3039        install_native_package_with_assets_at(
3040            &destination,
3041            &metadata,
3042            prebuilt_record("demo", "1.0.0", &v1),
3043            std::slice::from_ref(&library),
3044            &sidecars(&v1),
3045            false,
3046        )
3047        .unwrap();
3048        let original_registry = std::fs::read(&metadata).unwrap();
3049
3050        std::fs::write(&library, b"new library").unwrap();
3051        let v2 = [
3052            ("runtime/main.mjs", &b"v2"[..]),
3053            ("runtime/extra.mjs", &b"extra"[..]),
3054        ];
3055        // Replacements activate in order: library, main.mjs, extra.mjs, registry.
3056        let error = install_native_package_at_with_hook(
3057            &destination,
3058            &metadata,
3059            prebuilt_record("demo", "2.0.0", &v2),
3060            std::slice::from_ref(&library),
3061            &sidecars(&v2),
3062            false,
3063            |index, _| {
3064                if index == 2 {
3065                    Err("injected sidecar activation failure".into())
3066                } else {
3067                    Ok(())
3068                }
3069            },
3070        )
3071        .unwrap_err();
3072
3073        assert!(
3074            error.contains("injected sidecar activation failure"),
3075            "{error}"
3076        );
3077        assert_eq!(
3078            std::fs::read(destination.join("libdemo.so")).unwrap(),
3079            b"old library"
3080        );
3081        assert_eq!(
3082            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3083            b"v1"
3084        );
3085        assert!(!destination.join("runtime/extra.mjs").exists());
3086        assert_eq!(std::fs::read(&metadata).unwrap(), original_registry);
3087        assert_no_native_transaction_files(temp.path());
3088        assert_no_native_transaction_files(&destination);
3089        assert_no_native_transaction_files(&destination.join("runtime"));
3090
3091        // The same upgrade succeeds once the failure is gone.
3092        install_native_package_with_assets_at(
3093            &destination,
3094            &metadata,
3095            prebuilt_record("demo", "2.0.0", &v2),
3096            std::slice::from_ref(&library),
3097            &sidecars(&v2),
3098            false,
3099        )
3100        .unwrap();
3101        assert_eq!(
3102            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3103            b"v2"
3104        );
3105        assert_eq!(
3106            std::fs::read(destination.join("runtime/extra.mjs")).unwrap(),
3107            b"extra"
3108        );
3109    }
3110
3111    #[test]
3112    fn native_asset_conflicts_and_overlaps_fail_before_any_write() {
3113        let temp = tempfile::tempdir().unwrap();
3114        let destination = temp.path().join("extensions");
3115        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3116        let library = temp.path().join("libdemo.so");
3117        std::fs::write(&library, b"demo library").unwrap();
3118        let other = temp.path().join("libother.so");
3119        std::fs::write(&other, b"other library").unwrap();
3120        let shared = [("runtime/shared.mjs", &b"other"[..])];
3121        install_native_package_with_assets_at(
3122            &destination,
3123            &metadata,
3124            prebuilt_record("other", "1.0.0", &shared),
3125            std::slice::from_ref(&other),
3126            &sidecars(&shared),
3127            false,
3128        )
3129        .unwrap();
3130        let original_registry = std::fs::read(&metadata).unwrap();
3131
3132        let attempts: [&[(&str, &[u8])]; 3] = [
3133            &[("runtime/shared.mjs", &b"demo"[..])],
3134            &[("Runtime/Shared.mjs", &b"demo"[..])],
3135            &[("runtime", &b"file"[..]), ("runtime/own.mjs", &b"own"[..])],
3136        ];
3137        for assets in attempts {
3138            let error = install_native_package_with_assets_at(
3139                &destination,
3140                &metadata,
3141                prebuilt_record("demo", "1.0.0", assets),
3142                std::slice::from_ref(&library),
3143                &sidecars(assets),
3144                false,
3145            )
3146            .unwrap_err();
3147            assert!(
3148                error.contains("conflicts with asset")
3149                    || error.contains("duplicate or overlapping"),
3150                "{error}"
3151            );
3152            assert!(!destination.join("libdemo.so").exists());
3153            assert_eq!(
3154                std::fs::read(destination.join("runtime/shared.mjs")).unwrap(),
3155                b"other"
3156            );
3157            assert_eq!(std::fs::read(&metadata).unwrap(), original_registry);
3158            assert_eq!(
3159                std::fs::read_dir(destination.join("runtime"))
3160                    .unwrap()
3161                    .count(),
3162                1
3163            );
3164            assert_no_native_transaction_files(&destination);
3165        }
3166    }
3167
3168    #[test]
3169    fn native_asset_replacing_an_unowned_file_requires_force() {
3170        let temp = tempfile::tempdir().unwrap();
3171        let destination = temp.path().join("extensions");
3172        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3173        let library = temp.path().join("libdemo.so");
3174        std::fs::write(&library, b"demo library").unwrap();
3175        std::fs::create_dir_all(destination.join("runtime")).unwrap();
3176        std::fs::write(destination.join("runtime/main.mjs"), b"user file").unwrap();
3177        let assets = [("runtime/main.mjs", &b"demo"[..])];
3178
3179        let error = install_native_package_with_assets_at(
3180            &destination,
3181            &metadata,
3182            prebuilt_record("demo", "1.0.0", &assets),
3183            std::slice::from_ref(&library),
3184            &sidecars(&assets),
3185            false,
3186        )
3187        .unwrap_err();
3188        assert!(error.contains("use --force to replace it"), "{error}");
3189        assert_eq!(
3190            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3191            b"user file"
3192        );
3193        assert!(!metadata.exists());
3194
3195        install_native_package_with_assets_at(
3196            &destination,
3197            &metadata,
3198            prebuilt_record("demo", "1.0.0", &assets),
3199            std::slice::from_ref(&library),
3200            &sidecars(&assets),
3201            true,
3202        )
3203        .unwrap();
3204        assert_eq!(
3205            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3206            b"demo"
3207        );
3208    }
3209
3210    #[test]
3211    fn uninstall_removes_recorded_sidecars_and_only_the_directories_they_empty() {
3212        let agent = TempAgent::new();
3213        let extension_dir = agent.temp.path().join("extensions");
3214        std::fs::create_dir_all(extension_dir.join("runtime/deep")).unwrap();
3215        std::fs::write(extension_dir.join("libdemo.so"), b"library").unwrap();
3216        std::fs::write(extension_dir.join("runtime/main.mjs"), b"main").unwrap();
3217        std::fs::write(extension_dir.join("runtime/deep/lib.mjs"), b"deep").unwrap();
3218        std::fs::write(extension_dir.join("runtime/user.mjs"), b"user").unwrap();
3219        let mut record = prebuilt_record(
3220            "demo",
3221            "1.0.0",
3222            &[
3223                ("runtime/main.mjs", &b"main"[..]),
3224                ("runtime/deep/lib.mjs", &b"deep"[..]),
3225            ],
3226        );
3227        record.artifacts = vec!["libdemo.so".into()];
3228        write_native_packages_at(&agent.metadata_path(), &[record]).unwrap();
3229
3230        assert_eq!(uninstall(&args(&["demo"])), 0);
3231        assert!(!extension_dir.join("libdemo.so").exists());
3232        assert!(!extension_dir.join("runtime/main.mjs").exists());
3233        assert!(!extension_dir.join("runtime/deep").exists());
3234        assert_eq!(
3235            std::fs::read(extension_dir.join("runtime/user.mjs")).unwrap(),
3236            b"user"
3237        );
3238        assert!(!agent.metadata_path().exists());
3239        assert_no_native_transaction_files(agent.temp.path());
3240        assert_no_native_transaction_files(&extension_dir);
3241    }
3242
3243    #[test]
3244    fn native_asset_case_only_rename_prunes_the_old_sidecar() {
3245        let temp = tempfile::tempdir().unwrap();
3246        let destination = temp.path().join("extensions");
3247        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3248        let library = temp.path().join("libdemo.so");
3249        std::fs::write(&library, b"library v1").unwrap();
3250        let first = [("Runtime/main.mjs", &b"worker v1"[..])];
3251        install_native_package_with_assets_at(
3252            &destination,
3253            &metadata,
3254            prebuilt_record("demo", "1.0.0", &first),
3255            std::slice::from_ref(&library),
3256            &sidecars(&first),
3257            false,
3258        )
3259        .unwrap();
3260        let second = [("runtime/main.mjs", &b"worker v2"[..])];
3261        install_native_package_with_assets_at(
3262            &destination,
3263            &metadata,
3264            prebuilt_record("demo", "1.1.0", &second),
3265            std::slice::from_ref(&library),
3266            &sidecars(&second),
3267            false,
3268        )
3269        .unwrap();
3270
3271        assert_eq!(
3272            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3273            b"worker v2"
3274        );
3275        // The old name is no longer recorded, so it must not survive beside the new one.
3276        fn store_files(dir: &Path) -> usize {
3277            std::fs::read_dir(dir)
3278                .unwrap()
3279                .map(|entry| {
3280                    let path = entry.unwrap().path();
3281                    if path.is_dir() {
3282                        store_files(&path)
3283                    } else {
3284                        1
3285                    }
3286                })
3287                .sum()
3288        }
3289        assert_eq!(store_files(&destination), 3);
3290    }
3291
3292    #[test]
3293    fn native_asset_case_variant_of_an_owned_sidecar_is_not_owned() {
3294        let temp = tempfile::tempdir().unwrap();
3295        let destination = temp.path().join("extensions");
3296        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3297        let library = temp.path().join("libdemo.so");
3298        std::fs::write(&library, b"library").unwrap();
3299        let first = [("Runtime/main.mjs", &b"worker v1"[..])];
3300        install_native_package_with_assets_at(
3301            &destination,
3302            &metadata,
3303            prebuilt_record("demo", "1.0.0", &first),
3304            std::slice::from_ref(&library),
3305            &sidecars(&first),
3306            false,
3307        )
3308        .unwrap();
3309        std::fs::create_dir_all(destination.join("runtime")).unwrap();
3310        std::fs::write(destination.join("runtime/main.mjs"), b"user file").unwrap();
3311        if std::fs::read(destination.join("Runtime/main.mjs")).unwrap() == b"user file" {
3312            return; // case-insensitive store: the two names are one file, nothing to test
3313        }
3314
3315        let second = [("runtime/main.mjs", &b"worker v2"[..])];
3316        let error = install_native_package_with_assets_at(
3317            &destination,
3318            &metadata,
3319            prebuilt_record("demo", "1.1.0", &second),
3320            std::slice::from_ref(&library),
3321            &sidecars(&second),
3322            false,
3323        )
3324        .unwrap_err();
3325        assert!(error.contains("--force"), "{error}");
3326        assert_eq!(
3327            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3328            b"user file"
3329        );
3330        assert_eq!(
3331            std::fs::read(destination.join("Runtime/main.mjs")).unwrap(),
3332            b"worker v1"
3333        );
3334
3335        install_native_package_with_assets_at(
3336            &destination,
3337            &metadata,
3338            prebuilt_record("demo", "1.1.0", &second),
3339            std::slice::from_ref(&library),
3340            &sidecars(&second),
3341            true,
3342        )
3343        .unwrap();
3344        assert_eq!(
3345            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3346            b"worker v2"
3347        );
3348        assert!(!destination.join("Runtime").exists());
3349    }
3350
3351    #[test]
3352    fn native_asset_failed_first_install_removes_the_directories_it_created() {
3353        let temp = tempfile::tempdir().unwrap();
3354        let destination = temp.path().join("extensions");
3355        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3356        let library = temp.path().join("libdemo.so");
3357        std::fs::write(&library, b"library").unwrap();
3358        std::fs::create_dir_all(destination.join("keep")).unwrap();
3359        let assets = [("runtime/deep/x.mjs", &b"x"[..]), ("keep/y.mjs", &b"y"[..])];
3360        // Replacements activate in order: library, x.mjs, y.mjs, registry.
3361        let error = install_native_package_at_with_hook(
3362            &destination,
3363            &metadata,
3364            prebuilt_record("demo", "1.0.0", &assets),
3365            std::slice::from_ref(&library),
3366            &sidecars(&assets),
3367            false,
3368            |index, _| {
3369                if index == 2 {
3370                    Err("injected sidecar activation failure".into())
3371                } else {
3372                    Ok(())
3373                }
3374            },
3375        )
3376        .unwrap_err();
3377
3378        assert!(error.contains("injected"), "{error}");
3379        assert!(!destination.join("runtime").exists());
3380        // A directory that existed before the install is left alone, even though it is empty.
3381        assert!(destination.join("keep").is_dir());
3382        assert!(!destination.join("libdemo.so").exists());
3383        assert!(!metadata.exists());
3384        assert_no_native_transaction_files(temp.path());
3385        assert_no_native_transaction_files(&destination);
3386    }
3387
3388    #[test]
3389    fn native_asset_overlap_within_one_package_is_rejected_before_any_write() {
3390        // No other package is installed, so only the intra-package check can reject this.
3391        let temp = tempfile::tempdir().unwrap();
3392        let destination = temp.path().join("extensions");
3393        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3394        let library = temp.path().join("libdemo.so");
3395        std::fs::write(&library, b"demo library").unwrap();
3396        let assets = [("runtime", &b"file"[..]), ("runtime/own.mjs", &b"own"[..])];
3397
3398        let error = install_native_package_with_assets_at(
3399            &destination,
3400            &metadata,
3401            prebuilt_record("demo", "1.0.0", &assets),
3402            std::slice::from_ref(&library),
3403            &sidecars(&assets),
3404            false,
3405        )
3406        .unwrap_err();
3407        assert!(error.contains("duplicate or overlapping"), "{error}");
3408        assert_eq!(std::fs::read_dir(&destination).unwrap().count(), 0);
3409        assert!(!metadata.exists());
3410    }
3411
3412    #[cfg(unix)]
3413    #[test]
3414    fn native_asset_parent_links_are_refused_without_writing_through_them() {
3415        let temp = tempfile::tempdir().unwrap();
3416        let destination = temp.path().join("extensions");
3417        let outside = temp.path().join("outside");
3418        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3419        let library = temp.path().join("libdemo.so");
3420        std::fs::write(&library, b"demo library").unwrap();
3421        std::fs::create_dir_all(&destination).unwrap();
3422        std::fs::create_dir_all(&outside).unwrap();
3423        std::os::unix::fs::symlink(&outside, destination.join("runtime")).unwrap();
3424        let assets = [("runtime/main.mjs", &b"demo"[..])];
3425
3426        let error = install_native_package_with_assets_at(
3427            &destination,
3428            &metadata,
3429            prebuilt_record("demo", "1.0.0", &assets),
3430            std::slice::from_ref(&library),
3431            &sidecars(&assets),
3432            false,
3433        )
3434        .unwrap_err();
3435        assert!(error.contains("is not a plain directory"), "{error}");
3436        assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
3437        assert!(!destination.join("libdemo.so").exists());
3438    }
3439
3440    fn cdylib_target(name: &'static str) -> CargoTarget {
3441        CargoTarget {
3442            name: name.to_string(),
3443            crate_types: vec!["cdylib".to_string()],
3444        }
3445    }
3446
3447    #[test]
3448    fn find_artifacts_locates_cargo_1_100_build_dir_layout() {
3449        // Cargo 1.100.0 moved intermediate artifacts to
3450        // `<profile>/build/<pkg>/<meta>/out` and stopped creating `deps`.
3451        let temp = tempfile::tempdir().unwrap();
3452        let release_dir = temp.path().join("target").join("release");
3453        let out = release_dir
3454            .join("build")
3455            .join("rpi-web")
3456            .join("0123456789abcdef")
3457            .join("out");
3458        std::fs::create_dir_all(&out).unwrap();
3459        let library = out.join(format!(
3460            "{}rpi_web_extension{}",
3461            std::env::consts::DLL_PREFIX,
3462            std::env::consts::DLL_SUFFIX
3463        ));
3464        std::fs::write(&library, b"cdylib").unwrap();
3465
3466        let target = cdylib_target("rpi_web_extension");
3467        let found = find_artifacts(&release_dir, &[&target]).unwrap();
3468        assert_eq!(found, vec![library]);
3469    }
3470
3471    #[test]
3472    fn find_artifacts_skips_missing_build_directories() {
3473        // With no `deps/` and no `build/`, the scan must report the missing
3474        // artifact instead of failing on the absent directory itself.
3475        let temp = tempfile::tempdir().unwrap();
3476        let release_dir = temp.path().join("target").join("release");
3477        let target = cdylib_target("rpi_web_extension");
3478
3479        let error = find_artifacts(&release_dir, &[&target]).unwrap_err();
3480        assert!(error.contains("no cdylib artifact was found"), "{error}");
3481        assert!(!error.contains("could not inspect build output"), "{error}");
3482    }
3483
3484    #[test]
3485    fn reported_artifacts_win_over_directory_scans() {
3486        // Paths from Cargo's JSON messages are authoritative even when the
3487        // legacy layout also contains a matching library.
3488        let temp = tempfile::tempdir().unwrap();
3489        let release_dir = temp.path().join("target").join("release");
3490        std::fs::create_dir_all(release_dir.join("deps")).unwrap();
3491        let stale = release_dir.join("deps").join(format!(
3492            "{}rpi_web_extension{}",
3493            std::env::consts::DLL_PREFIX,
3494            std::env::consts::DLL_SUFFIX
3495        ));
3496        std::fs::write(&stale, b"stale").unwrap();
3497        let reported = temp.path().join(format!(
3498            "{}rpi_web_extension.abc123{}",
3499            std::env::consts::DLL_PREFIX,
3500            std::env::consts::DLL_SUFFIX
3501        ));
3502        std::fs::write(&reported, b"reported").unwrap();
3503
3504        let target = cdylib_target("rpi_web_extension");
3505        let found = CargoBuild {
3506            artifacts: vec![reported.clone()],
3507        }
3508        .into_artifacts(&release_dir, &[&target])
3509        .unwrap();
3510        assert_eq!(found, vec![reported]);
3511    }
3512}