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