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