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/// Best-effort cleanup for retired native artifacts. The exclusive resource
1245/// lease is the proof that no host is currently holding the old libraries; a
1246/// live host therefore only causes cleanup to be deferred until a later
1247/// install or explicit maintenance command.
1248fn gc_retired_native_artifacts(agent_dir: &Path) {
1249    let metadata_path = agent_dir.join(NATIVE_PACKAGES_FILE);
1250    let lease = match crate::resource_management::mutation_lease(agent_dir) {
1251        Ok(lease) => lease,
1252        Err(_) => return,
1253    };
1254    let _lock = match NativePackageMutationLock::acquire_with_lease(&metadata_path, lease) {
1255        Ok(lock) => lock,
1256        Err(_) => return,
1257    };
1258    let records = match read_native_package_registry_at(&metadata_path) {
1259        Ok(registry) => registry.into_records(),
1260        Err(_) => return,
1261    };
1262    let active = records
1263        .iter()
1264        .flat_map(|record| record.artifacts.iter())
1265        .map(|artifact| native_artifact_identity(artifact))
1266        .collect::<HashSet<_>>();
1267    let destination = agent_dir.join("extensions");
1268    let Ok(entries) = std::fs::read_dir(&destination) else {
1269        return;
1270    };
1271    for entry in entries.flatten() {
1272        let path = entry.path();
1273        let Some(name) = path.file_name().and_then(|value| value.to_str()) else {
1274            continue;
1275        };
1276        if !is_dynamic_library(&path)
1277            || !is_versioned_artifact_name(name)
1278            || active.contains(&native_artifact_identity(name))
1279        {
1280            continue;
1281        }
1282        if crate::resource_management::legacy_unowned_targets(
1283            agent_dir,
1284            std::slice::from_ref(&path),
1285        )
1286        .is_err()
1287        {
1288            continue;
1289        }
1290        let Ok(metadata) = std::fs::symlink_metadata(&path) else {
1291            continue;
1292        };
1293        if metadata.file_type().is_file() {
1294            let _ = std::fs::remove_file(path);
1295        }
1296    }
1297}
1298
1299pub(crate) fn versioned_artifact_name(
1300    original: &str,
1301    version: &str,
1302    destination: &Path,
1303) -> Result<String, String> {
1304    let path = Path::new(original);
1305    let stem = path
1306        .file_stem()
1307        .and_then(|value| value.to_str())
1308        .ok_or_else(|| format!("artifact has no UTF-8 file stem: {original}"))?;
1309    let extension = path
1310        .extension()
1311        .and_then(|value| value.to_str())
1312        .ok_or_else(|| format!("artifact has no dynamic-library extension: {original}"))?;
1313    let version = version
1314        .chars()
1315        .map(|value| {
1316            if value.is_ascii_alphanumeric() || matches!(value, '.' | '-' | '_') {
1317                value
1318            } else {
1319                '_'
1320            }
1321        })
1322        .collect::<String>();
1323    let version = if version.is_empty() {
1324        "unknown"
1325    } else {
1326        &version
1327    };
1328    for _ in 0..8 {
1329        let name = format!(
1330            "{stem}-v{version}-{}.{}",
1331            uuid::Uuid::new_v4().simple(),
1332            extension
1333        );
1334        let target = destination.join(&name);
1335        if matches!(std::fs::symlink_metadata(&target), Err(error) if error.kind() == std::io::ErrorKind::NotFound)
1336        {
1337            return Ok(name);
1338        }
1339    }
1340    Err(format!(
1341        "could not allocate a unique versioned artifact for {original}"
1342    ))
1343}
1344
1345fn artifact_file_name(path: &Path) -> Result<String, String> {
1346    let name = path
1347        .file_name()
1348        .and_then(|name| name.to_str())
1349        .ok_or_else(|| format!("artifact has no UTF-8 file name: {}", path.display()))?;
1350    checked_registered_artifact_path(Path::new("."), name)?;
1351    Ok(name.to_string())
1352}
1353
1354fn checked_registered_artifact_path(destination: &Path, name: &str) -> Result<PathBuf, String> {
1355    let relative = Path::new(name);
1356    let is_single_component = relative.components().count() == 1
1357        && relative.file_name().and_then(|value| value.to_str()) == Some(name);
1358    if !is_single_component || !is_dynamic_library(relative) {
1359        return Err(format!("unsafe native package artifact name `{name}`"));
1360    }
1361    Ok(destination.join(relative))
1362}
1363
1364fn native_artifact_identity(name: &str) -> String {
1365    if cfg!(windows) {
1366        name.to_ascii_lowercase()
1367    } else {
1368        name.to_string()
1369    }
1370}
1371
1372/// Whether two paths name the same existing file (one inode). Windows already folds case
1373/// in `native_artifact_identity`, so only Unix needs the inode check.
1374#[cfg(unix)]
1375fn same_file(left: &Path, right: &Path) -> bool {
1376    use std::os::unix::fs::MetadataExt;
1377    match (
1378        std::fs::symlink_metadata(left),
1379        std::fs::symlink_metadata(right),
1380    ) {
1381        (Ok(left), Ok(right)) => left.dev() == right.dev() && left.ino() == right.ino(),
1382        _ => false,
1383    }
1384}
1385
1386#[cfg(not(unix))]
1387fn same_file(_: &Path, _: &Path) -> bool {
1388    false
1389}
1390
1391fn transaction_path_identity(path: &Path) -> String {
1392    let value = path.to_string_lossy().into_owned();
1393    if cfg!(windows) {
1394        value.to_ascii_lowercase()
1395    } else {
1396        value
1397    }
1398}
1399
1400fn adjacent_transaction_path(target: &Path, kind: &str) -> Result<PathBuf, String> {
1401    let parent = target
1402        .parent()
1403        .ok_or_else(|| format!("transaction target has no parent: {}", target.display()))?;
1404    let leaf = target
1405        .file_name()
1406        .and_then(|name| name.to_str())
1407        .unwrap_or("artifact");
1408    for _ in 0..8 {
1409        let candidate = parent.join(format!(
1410            ".{leaf}.rpi-{kind}-{}",
1411            uuid::Uuid::new_v4().simple()
1412        ));
1413        match std::fs::symlink_metadata(&candidate) {
1414            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(candidate),
1415            Ok(_) => {}
1416            Err(error) => {
1417                return Err(format!(
1418                    "could not inspect transaction path {}: {error}",
1419                    candidate.display()
1420                ))
1421            }
1422        }
1423    }
1424    Err(format!(
1425        "could not allocate a transaction path beside {}",
1426        target.display()
1427    ))
1428}
1429
1430/// macOS only: give a freshly copied native artifact an ad-hoc signature.
1431///
1432/// Why this is mandatory and not cosmetic (2026-11-07, 35 SIGKILLs in one
1433/// afternoon): cargo linker-signs a cdylib and that signature records the
1434/// file's mtime (`cs_mtime`). Any copy — `io::copy`, `fs::copy`, `rename` of a
1435/// rewritten file — gives the copy a **new** mtime, and when the kernel maps a
1436/// code page it compares `cs_mtime` against it. On mismatch it refuses the page
1437/// and **kills the whole host process**:
1438///
1439/// ```text
1440/// CODE SIGNING: process 20087[rpi]: rejecting invalid page at address 0x…
1441///   in file "~/.pidd/rpi-agent/extensions/librpi_superagent.dylib"
1442///   (cs_mtime:1794052202.55 != mtime:1794056571.77)
1443/// ```
1444///
1445/// Nothing is printed and no exit code reaches the terminal except 137, so the
1446/// symptom reads as "rpi will not start any session any more". `codesign -v`
1447/// still reports the copy as valid on disk, so verification is useless here —
1448/// only re-signing realigns `cs_mtime` with the file mtime.
1449pub(crate) fn resign_staged_native(path: &Path) -> Result<(), String> {
1450    if !cfg!(target_os = "macos") {
1451        return Ok(());
1452    }
1453    let out = std::process::Command::new("/usr/bin/codesign")
1454        // Pin the identifier: `--sign -` otherwise derives it from the file NAME,
1455        // so the same bytes staged under different names sign to different bytes.
1456        .args(["--force", "--sign", "-", "--identifier", "com.rpi.native"])
1457        .arg(path)
1458        .output()
1459        .map_err(|error| format!("could not run codesign on {}: {error}", path.display()))?;
1460    if !out.status.success() {
1461        return Err(format!(
1462            "re-signing {} failed (the kernel will refuse to load it): {}",
1463            path.display(),
1464            String::from_utf8_lossy(&out.stderr).trim()
1465        ));
1466    }
1467    Ok(())
1468}
1469
1470fn stage_native_artifact(source: &Path, target: &Path) -> Result<StagedNativeFile, String> {
1471    let stage = adjacent_transaction_path(target, "stage")?;
1472    let result = (|| {
1473        let source_metadata = std::fs::symlink_metadata(source).map_err(|error| {
1474            format!(
1475                "could not inspect built artifact {}: {error}",
1476                source.display()
1477            )
1478        })?;
1479        let mut input = std::fs::File::open(source).map_err(|error| {
1480            format!(
1481                "could not open built artifact {}: {error}",
1482                source.display()
1483            )
1484        })?;
1485        let mut output = std::fs::OpenOptions::new()
1486            .write(true)
1487            .create_new(true)
1488            .open(&stage)
1489            .map_err(|error| {
1490                format!(
1491                    "could not create staged artifact {}: {error}",
1492                    stage.display()
1493                )
1494            })?;
1495        std::io::copy(&mut input, &mut output)
1496            .and_then(|_| output.sync_all())
1497            .map_err(|error| {
1498                format!(
1499                    "could not write staged artifact {} beside {}: {error}",
1500                    stage.display(),
1501                    target.display()
1502                )
1503            })?;
1504        drop(output);
1505        std::fs::set_permissions(&stage, source_metadata.permissions()).map_err(|error| {
1506            format!(
1507                "could not preserve permissions on staged artifact {}: {error}",
1508                stage.display()
1509            )
1510        })?;
1511        resign_staged_native(&stage)
1512    })();
1513    if let Err(error) = result {
1514        let _ = std::fs::remove_file(&stage);
1515        return Err(error);
1516    }
1517    Ok(StagedNativeFile { path: stage })
1518}
1519fn stage_native_bytes(bytes: &[u8], target: &Path) -> Result<StagedNativeFile, String> {
1520    let stage = adjacent_transaction_path(target, "stage")?;
1521    let result = (|| {
1522        let mut file = std::fs::OpenOptions::new()
1523            .write(true)
1524            .create_new(true)
1525            .open(&stage)
1526            .map_err(|error| {
1527                format!(
1528                    "could not create staged registry {}: {error}",
1529                    stage.display()
1530                )
1531            })?;
1532        file.write_all(bytes)
1533            .and_then(|()| file.sync_all())
1534            .map_err(|error| {
1535                format!(
1536                    "could not flush staged registry {}: {error}",
1537                    stage.display()
1538                )
1539            })
1540    })();
1541    if let Err(error) = result {
1542        let _ = std::fs::remove_file(&stage);
1543        return Err(error);
1544    }
1545    Ok(StagedNativeFile { path: stage })
1546}
1547
1548fn activate_native_transaction(
1549    replacements: &[NativeReplacement],
1550    removals: &[PathBuf],
1551    before_activate: &mut impl FnMut(usize, &Path) -> Result<(), String>,
1552) -> Result<(), String> {
1553    let mut affected = Vec::new();
1554    let mut seen = HashSet::new();
1555    for target in replacements
1556        .iter()
1557        .map(|replacement| &replacement.target)
1558        .chain(removals.iter())
1559    {
1560        if seen.insert(transaction_path_identity(target)) {
1561            affected.push(target.clone());
1562        }
1563    }
1564
1565    for target in &affected {
1566        match std::fs::symlink_metadata(target) {
1567            Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => {}
1568            Ok(_) => {
1569                return Err(format!(
1570                    "refusing to replace non-regular native package file {}",
1571                    target.display()
1572                ))
1573            }
1574            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1575            Err(error) => {
1576                return Err(format!(
1577                    "could not inspect native package file {}: {error}",
1578                    target.display()
1579                ))
1580            }
1581        }
1582    }
1583
1584    let mut backups = Vec::new();
1585    for target in &affected {
1586        if !target.exists() {
1587            continue;
1588        }
1589        let backup = match adjacent_transaction_path(target, "backup") {
1590            Ok(backup) => backup,
1591            Err(error) => {
1592                let rollback = rollback_native_transaction(&[], &backups);
1593                return Err(transaction_error(error, rollback));
1594            }
1595        };
1596        if let Err(error) = std::fs::rename(target, &backup) {
1597            let rollback = rollback_native_transaction(&[], &backups);
1598            return Err(transaction_error(
1599                format!("could not back up {}: {error}", target.display()),
1600                rollback,
1601            ));
1602        }
1603        backups.push(NativeBackup {
1604            target: target.clone(),
1605            backup,
1606        });
1607    }
1608
1609    let mut activated = Vec::new();
1610    for (index, replacement) in replacements.iter().enumerate() {
1611        let activation = before_activate(index, &replacement.target).and_then(|()| {
1612            std::fs::rename(&replacement.staged.path, &replacement.target).map_err(|error| {
1613                format!(
1614                    "could not activate replacement {}: {error}",
1615                    replacement.target.display()
1616                )
1617            })
1618        });
1619        if let Err(error) = activation {
1620            let rollback = rollback_native_transaction(&activated, &backups);
1621            return Err(transaction_error(error, rollback));
1622        }
1623        activated.push(replacement.target.clone());
1624    }
1625
1626    for backup in backups {
1627        if let Err(error) = std::fs::remove_file(&backup.backup) {
1628            eprintln!(
1629                "warning: native package updated but backup {} could not be removed: {error}",
1630                backup.backup.display()
1631            );
1632        }
1633    }
1634    Ok(())
1635}
1636
1637fn rollback_native_transaction(
1638    activated: &[PathBuf],
1639    backups: &[NativeBackup],
1640) -> Result<(), String> {
1641    let mut errors = Vec::new();
1642    for target in activated.iter().rev() {
1643        match std::fs::remove_file(target) {
1644            Ok(()) => {}
1645            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1646            Err(error) => errors.push(format!("could not remove {}: {error}", target.display())),
1647        }
1648    }
1649    for backup in backups.iter().rev() {
1650        if let Err(error) = std::fs::rename(&backup.backup, &backup.target) {
1651            errors.push(format!(
1652                "could not restore {} from {}: {error}",
1653                backup.target.display(),
1654                backup.backup.display()
1655            ));
1656        }
1657    }
1658    if errors.is_empty() {
1659        Ok(())
1660    } else {
1661        Err(errors.join("; "))
1662    }
1663}
1664
1665fn transaction_error(error: String, rollback: Result<(), String>) -> String {
1666    match rollback {
1667        Ok(()) => error,
1668        Err(rollback) => format!("{error}; rollback also failed: {rollback}"),
1669    }
1670}
1671
1672fn parse_args(args: &[String]) -> Result<InstallOptions, String> {
1673    let mut package = None;
1674    let mut version = None;
1675    let mut path = None;
1676    let mut locked = false;
1677    let mut force = false;
1678    let mut build = false;
1679    let mut repository = None;
1680    let mut cdn = None;
1681    let mut i = 0;
1682    while i < args.len() {
1683        match args[i].as_str() {
1684            "--help" | "-h" => return Err(help_requested().to_string()),
1685            "--offline" => {} // app normalizes this flag before dispatch
1686            "--locked" => locked = true,
1687            "--force" | "-f" => force = true,
1688            "--build" => build = true,
1689            "--github" => {
1690                i += 1;
1691                repository = Some(value(args, i, "--github")?);
1692            }
1693            "--cdn" => {
1694                i += 1;
1695                cdn = Some(value(args, i, "--cdn")?);
1696            }
1697            "--version" | "-V" => {
1698                i += 1;
1699                version = Some(value(args, i, "--version")?);
1700            }
1701            "--path" => {
1702                i += 1;
1703                path = Some(PathBuf::from(value(args, i, "--path")?));
1704            }
1705            value if value.starts_with('-') => {
1706                return Err(format!("unknown install option `{value}`"));
1707            }
1708            value => {
1709                if package.replace(value.to_string()).is_some() {
1710                    return Err("install accepts exactly one crate name".to_string());
1711                }
1712            }
1713        }
1714        i += 1;
1715    }
1716    if path.is_some() && version.is_some() {
1717        return Err("--path and --version cannot be used together".to_string());
1718    }
1719    if repository.is_some() && (build || path.is_some()) {
1720        return Err("--github cannot be combined with --build or --path".into());
1721    }
1722    if locked && !build && path.is_none() {
1723        return Err("--locked requires --build or --path".into());
1724    }
1725    let package = match package {
1726        Some(package) => package,
1727        None => {
1728            let path = path
1729                .as_deref()
1730                .ok_or_else(|| "missing crate name (or use --path <directory>)".to_string())?;
1731            package_name_from_manifest(path)?
1732        }
1733    };
1734    if !valid_package_name(&package) {
1735        return Err(format!("invalid Cargo package name `{package}`"));
1736    }
1737    let cdn_base = if build || path.is_some() {
1738        None
1739    } else {
1740        crate::cdn::resolve_base(cdn.as_deref())?
1741    };
1742    Ok(InstallOptions {
1743        package,
1744        version,
1745        path,
1746        locked,
1747        force,
1748        build,
1749        repository,
1750        cdn_base,
1751    })
1752}
1753
1754fn value(args: &[String], index: usize, flag: &str) -> Result<String, String> {
1755    args.get(index)
1756        .filter(|value| !value.starts_with('-'))
1757        .cloned()
1758        .ok_or_else(|| format!("{flag} requires a value"))
1759}
1760
1761fn package_name_from_manifest(path: &Path) -> Result<String, String> {
1762    let manifest = if path.is_dir() {
1763        path.join("Cargo.toml")
1764    } else {
1765        path.to_path_buf()
1766    };
1767    let output = Command::new("cargo")
1768        .args([
1769            "metadata",
1770            "--no-deps",
1771            "--format-version",
1772            "1",
1773            "--manifest-path",
1774        ])
1775        .arg(&manifest)
1776        .output()
1777        .map_err(|error| format!("could not run cargo metadata: {error}"))?;
1778    if !output.status.success() {
1779        return Err(format!(
1780            "could not inspect {}: {}",
1781            manifest.display(),
1782            String::from_utf8_lossy(&output.stderr).trim()
1783        ));
1784    }
1785    let metadata: serde_json::Value = serde_json::from_slice(&output.stdout)
1786        .map_err(|error| format!("cargo metadata returned invalid JSON: {error}"))?;
1787    let manifest = std::fs::canonicalize(&manifest)
1788        .map_err(|error| format!("could not resolve {}: {error}", manifest.display()))?;
1789    metadata
1790        .get("packages")
1791        .and_then(serde_json::Value::as_array)
1792        .and_then(|packages| {
1793            packages.iter().find_map(|package| {
1794                let package_manifest = package.get("manifest_path")?.as_str()?;
1795                let package_manifest = std::fs::canonicalize(package_manifest).ok()?;
1796                (package_manifest == manifest)
1797                    .then(|| package.get("name")?.as_str().map(str::to_owned))
1798                    .flatten()
1799            })
1800        })
1801        .filter(|name| valid_package_name(name))
1802        .ok_or_else(|| format!("{} has no valid [package].name", manifest.display()))
1803}
1804
1805fn valid_package_name(name: &str) -> bool {
1806    !name.is_empty()
1807        && name
1808            .bytes()
1809            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
1810}
1811
1812fn help_requested() -> &'static str {
1813    "use `rpi install --help` for usage"
1814}
1815
1816pub fn print_help() {
1817    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.");
1818}
1819
1820fn print_uninstall_help() {
1821    println!(
1822        "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"
1823    );
1824}
1825
1826fn write_manifest(path: &Path, options: &InstallOptions) -> Result<(), String> {
1827    let source_dir = path
1828        .parent()
1829        .ok_or_else(|| "temporary workspace has no parent directory".to_string())?
1830        .join("src");
1831    std::fs::create_dir_all(&source_dir).map_err(|error| error.to_string())?;
1832    // Cargo requires the temporary root package to have a target even though
1833    // rpi never builds it; the requested extension is built as a dependency.
1834    std::fs::write(source_dir.join("lib.rs"), "pub fn installer_marker() {}\n")
1835        .map_err(|error| error.to_string())?;
1836    let dependency = if let Some(local_path) = &options.path {
1837        let absolute = if local_path.is_absolute() {
1838            local_path.clone()
1839        } else {
1840            std::env::current_dir()
1841                .map_err(|error| error.to_string())?
1842                .join(local_path)
1843        };
1844        format!(
1845            "rpi_extension_dep = {{ package = {:?}, path = {:?} }}",
1846            options.package,
1847            absolute.display().to_string()
1848        )
1849    } else {
1850        let version = options.version.as_deref().unwrap_or("*");
1851        format!(
1852            "rpi_extension_dep = {{ package = {:?}, version = {:?} }}",
1853            options.package, version
1854        )
1855    };
1856    let contents = format!(
1857        "[package]\nname = \"{INSTALLER_MANIFEST}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\n[workspace]\n\n[dependencies]\n{dependency}\n"
1858    );
1859    std::fs::write(path, contents).map_err(|error| error.to_string())
1860}
1861
1862/// Run the Cargo commands whose output only needs to reach the terminal
1863/// (`fetch`). The `build` step has its own runner so it can capture the JSON
1864/// machine messages that report artifact paths.
1865fn cargo_command(
1866    subcommand: &str,
1867    manifest: &Path,
1868    options: &InstallOptions,
1869) -> Result<(), String> {
1870    let mut command = Command::new("cargo");
1871    command.arg(subcommand).arg("--manifest-path").arg(manifest);
1872    if options.locked {
1873        command.arg("--locked");
1874    }
1875    if crate::args::offline_env_enabled() {
1876        command.arg("--offline");
1877    }
1878    let status = command
1879        .stdin(Stdio::inherit())
1880        .stdout(Stdio::inherit())
1881        .stderr(Stdio::inherit())
1882        .status()
1883        .map_err(|error| format!("could not execute cargo: {error}"))?;
1884    if status.success() {
1885        Ok(())
1886    } else {
1887        Err(format!("cargo {subcommand} exited with {status}"))
1888    }
1889}
1890
1891/// Result of `cargo build --message-format=json-render-diagnostics` for the
1892/// temporary installer workspace.
1893///
1894/// Cargo's build-dir layout is explicitly internal and changed in 1.100.0
1895/// (#15010), which dropped `<profile>/deps` in favour of
1896/// `<profile>/build/<pkg>/<meta>/out`. The JSON machine messages are the
1897/// supported way to learn where a cdylib actually landed, so the artifact paths
1898/// are collected here and the directory scan is only a legacy fallback.
1899struct CargoBuild {
1900    artifacts: Vec<PathBuf>,
1901}
1902
1903impl CargoBuild {
1904    /// Resolve exactly one cdylib per requested target, in target order.
1905    ///
1906    /// Paths reported by Cargo win; only targets Cargo did not name fall back
1907    /// to scanning the build directory.
1908    fn into_artifacts(
1909        self,
1910        release_dir: &Path,
1911        targets: &[&CargoTarget],
1912    ) -> Result<Vec<PathBuf>, String> {
1913        let mut artifacts = Vec::with_capacity(targets.len());
1914        let mut unresolved = Vec::new();
1915        for target in targets {
1916            match self
1917                .artifacts
1918                .iter()
1919                .find(|path| artifact_matches_name(path, &target.name))
1920            {
1921                Some(path) => artifacts.push(path.clone()),
1922                None => unresolved.push(*target),
1923            }
1924        }
1925        if !unresolved.is_empty() {
1926            // `find_artifacts` reports a single missing target per call, so ask
1927            // it for the remaining ones together and preserve their order.
1928            let fallback = find_artifacts(release_dir, &unresolved)?;
1929            artifacts.extend(fallback);
1930        }
1931        Ok(artifacts)
1932    }
1933}
1934
1935/// Match a built dynamic library against a cdylib target name, tolerating the
1936/// platform `lib` prefix and a Cargo metadata hash suffix.
1937fn artifact_matches_name(path: &Path, target: &str) -> bool {
1938    if !is_dynamic_library(path) {
1939        return false;
1940    }
1941    let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
1942        return false;
1943    };
1944    let stem = normalize_name(stem.trim_start_matches("lib"));
1945    let wanted = normalize_name(target);
1946    stem == wanted || stem.starts_with(&format!("{wanted}."))
1947}
1948
1949fn cargo_build(
1950    manifest: &Path,
1951    options: &InstallOptions,
1952    targets: &[&CargoTarget],
1953) -> Result<CargoBuild, String> {
1954    let mut command = Command::new("cargo");
1955    command
1956        .arg("build")
1957        .arg("--manifest-path")
1958        .arg(manifest)
1959        .arg("--package")
1960        .arg(&options.package)
1961        .arg("--release")
1962        .arg("--target-dir")
1963        .arg(manifest.parent().unwrap().join("target"))
1964        .arg("--message-format=json-render-diagnostics");
1965    if options.locked {
1966        command.arg("--locked");
1967    }
1968    if crate::args::offline_env_enabled() {
1969        command.arg("--offline");
1970    }
1971    // Keep Cargo's diagnostics on the terminal while the machine messages on
1972    // stdout are parsed for artifact locations.
1973    command.stdin(Stdio::inherit()).stderr(Stdio::inherit());
1974    let output = command
1975        .output()
1976        .map_err(|error| format!("could not execute cargo: {error}"))?;
1977    if !output.status.success() {
1978        return Err(format!("cargo build exited with {}", output.status));
1979    }
1980    let wanted: Vec<String> = targets
1981        .iter()
1982        .map(|target| normalize_name(&target.name))
1983        .collect();
1984    let mut artifacts = Vec::new();
1985    let mut diagnostics = String::new();
1986    for line in String::from_utf8_lossy(&output.stdout).lines() {
1987        let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
1988            continue;
1989        };
1990        if let Some(rendered) = value
1991            .get("message")
1992            .and_then(|message| message.get("rendered"))
1993            .and_then(|rendered| rendered.as_str())
1994        {
1995            // `json-render-diagnostics` moves diagnostics onto stdout, so the
1996            // rendered text has to be replayed for the user.
1997            diagnostics.push_str(rendered);
1998            continue;
1999        }
2000        if value.get("reason").and_then(|reason| reason.as_str()) != Some("compiler-artifact") {
2001            continue;
2002        }
2003        let Some(name) = value
2004            .get("target")
2005            .and_then(|target| target.get("name"))
2006            .and_then(|name| name.as_str())
2007        else {
2008            continue;
2009        };
2010        if !wanted.contains(&normalize_name(name)) {
2011            continue;
2012        }
2013        artifacts.extend(
2014            value
2015                .get("filenames")
2016                .and_then(|filenames| filenames.as_array())
2017                .into_iter()
2018                .flatten()
2019                .filter_map(|filename| filename.as_str())
2020                .map(PathBuf::from)
2021                .filter(|path| is_dynamic_library(path) && path.is_file()),
2022        );
2023    }
2024    if !diagnostics.is_empty() {
2025        eprint!("{diagnostics}");
2026    }
2027    Ok(CargoBuild { artifacts })
2028}
2029
2030fn cargo_metadata(manifest: &Path, options: &InstallOptions) -> Result<CargoMetadata, String> {
2031    let mut command = Command::new("cargo");
2032    command
2033        .arg("metadata")
2034        .arg("--format-version")
2035        .arg("1")
2036        .arg("--manifest-path")
2037        .arg(manifest);
2038    if options.locked {
2039        command.arg("--locked");
2040    }
2041    if crate::args::offline_env_enabled() {
2042        command.arg("--offline");
2043    }
2044    let output = command
2045        .output()
2046        .map_err(|error| format!("could not execute cargo: {error}"))?;
2047    if !output.status.success() {
2048        return Err(String::from_utf8_lossy(&output.stderr).trim().to_string());
2049    }
2050    serde_json::from_slice(&output.stdout)
2051        .map_err(|error| format!("invalid cargo metadata: {error}"))
2052}
2053
2054fn find_artifacts(release_dir: &Path, targets: &[&CargoTarget]) -> Result<Vec<PathBuf>, String> {
2055    let mut artifacts = Vec::new();
2056    // Legacy layout (<profile>/ and <profile>/deps) plus the 1.100.0 build-dir
2057    // layout (<profile>/build/<pkg>/<meta>/out). Only used as a fallback when
2058    // Cargo's JSON messages did not name the artifact.
2059    let mut dirs = vec![release_dir.to_path_buf(), release_dir.join("deps")];
2060    dirs.extend(build_dir_outputs(release_dir));
2061    for target in targets {
2062        let wanted = normalize_name(&target.name);
2063        let mut matches = Vec::new();
2064        for dir in &dirs {
2065            let entries = match std::fs::read_dir(dir) {
2066                Ok(entries) => entries,
2067                // Cargo omits `deps/` under the 1.100.0 layout; a missing
2068                // candidate directory just contributes no matches.
2069                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
2070                Err(error) => {
2071                    return Err(format!(
2072                        "could not inspect build output {}: {error}",
2073                        dir.display()
2074                    ));
2075                }
2076            };
2077            for entry in entries.flatten() {
2078                let path = entry.path();
2079                if !is_dynamic_library(&path) {
2080                    continue;
2081                }
2082                let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
2083                    continue;
2084                };
2085                let normalized = normalize_name(stem.trim_start_matches("lib"));
2086                if normalized == wanted {
2087                    matches.push(path);
2088                }
2089            }
2090        }
2091        matches.sort_by_key(|path| path.components().count());
2092        let artifact = matches.into_iter().next().ok_or_else(|| {
2093            format!(
2094                "Cargo built `{}` but no cdylib artifact was found in {}",
2095                target.name,
2096                release_dir.display()
2097            )
2098        })?;
2099        artifacts.push(artifact);
2100    }
2101    Ok(artifacts)
2102}
2103
2104fn normalize_name(name: &str) -> String {
2105    name.replace('-', "_").to_ascii_lowercase()
2106}
2107
2108/// Collect `<profile>/build/<pkg>/<meta>/out` directories created by the
2109/// Cargo 1.100.0 build-dir layout. Absent directories simply yield no
2110/// candidates so older Cargo versions keep working unchanged.
2111fn build_dir_outputs(release_dir: &Path) -> Vec<PathBuf> {
2112    let mut outputs = Vec::new();
2113    let Ok(packages) = std::fs::read_dir(release_dir.join("build")) else {
2114        return outputs;
2115    };
2116    for package in packages.flatten() {
2117        let Ok(units) = std::fs::read_dir(package.path()) else {
2118            continue;
2119        };
2120        for unit in units.flatten() {
2121            let out = unit.path().join("out");
2122            if out.is_dir() {
2123                outputs.push(out);
2124            }
2125        }
2126    }
2127    outputs
2128}
2129
2130pub(crate) fn is_dynamic_library(path: &Path) -> bool {
2131    matches!(
2132        path.extension()
2133            .and_then(|extension| extension.to_str())
2134            .map(|extension| extension.to_ascii_lowercase())
2135            .as_deref(),
2136        Some("dll" | "so" | "dylib" | "pyd")
2137    )
2138}
2139
2140#[cfg(test)]
2141mod tests {
2142    use super::*;
2143
2144    /// A staged native artifact must not keep the build-time signature.
2145    ///
2146    /// The copy's mtime no longer matches the `cs_mtime` inside the linker
2147    /// signature, and the kernel answers that mismatch by SIGKILLing the host
2148    /// that maps the page (2026-11-07: 35 silent deaths of `rpi`).
2149    #[cfg(target_os = "macos")]
2150    #[test]
2151    fn staged_native_artifact_is_resigned_before_activation() {
2152        let dir = std::env::temp_dir().join(format!("rpi-resign-{}", std::process::id()));
2153        let _ = std::fs::remove_dir_all(&dir);
2154        std::fs::create_dir_all(&dir).unwrap();
2155        let stage = dir.join("libstaged.dylib");
2156        // Any real Mach-O: the copy gets a fresh mtime and a stale signature.
2157        std::fs::copy("/bin/cp", &stage).unwrap();
2158        resign_staged_native(&stage).unwrap();
2159        let out = std::process::Command::new("/usr/bin/codesign")
2160            .args(["-d", "--verbose=4"])
2161            .arg(&stage)
2162            .output()
2163            .unwrap();
2164        let text = String::from_utf8_lossy(&out.stderr);
2165        assert!(
2166            !text.contains("linker-signed"),
2167            "the staged artifact stayed linker-signed: {text}"
2168        );
2169        let _ = std::fs::remove_dir_all(&dir);
2170    }
2171
2172    fn args(values: &[&str]) -> Vec<String> {
2173        values.iter().map(|value| value.to_string()).collect()
2174    }
2175
2176    fn native_record(name: &str) -> InstalledNativePackage {
2177        InstalledNativePackage {
2178            name: name.to_string(),
2179            version: "1.2.3".to_string(),
2180            source: None,
2181            prebuilt: None,
2182            artifacts: vec![format!("{name}.dll")],
2183        }
2184    }
2185
2186    #[test]
2187    fn install_version_policy_allows_upgrades_and_requires_force_for_downgrades() {
2188        assert!(should_install_version("demo", None, "1.0.0", false).unwrap());
2189        for (current, requested) in [
2190            ("0.1.11", "0.1.12"),
2191            ("1.0.0-beta.1", "1.0.0"),
2192            ("1.0.0-beta.1", "1.0.0-beta.2"),
2193        ] {
2194            assert!(should_install_version("demo", Some(current), requested, false).unwrap());
2195            let error =
2196                should_install_version("demo", Some(requested), current, false).unwrap_err();
2197            assert!(error.contains("--force to downgrade"), "{error}");
2198            assert!(should_install_version("demo", Some(requested), current, true).unwrap());
2199        }
2200        for requested in ["1.2.3", "1.2.3+new-build"] {
2201            assert!(!should_install_version("demo", Some("1.2.3"), requested, false).unwrap());
2202            assert!(should_install_version("demo", Some("1.2.3"), requested, true).unwrap());
2203        }
2204        assert!(should_install_version("demo", Some("unknown"), "1.0.0", false).is_err());
2205        assert!(should_install_version("demo", Some("unknown"), "1.0.0", true).unwrap());
2206    }
2207
2208    #[test]
2209    fn native_install_same_version_is_unchanged_and_force_reinstalls_or_downgrades() {
2210        let temp = tempfile::tempdir().unwrap();
2211        let destination = temp.path().join("extensions");
2212        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
2213        let build = temp.path().join("demo.dll");
2214        std::fs::create_dir_all(&destination).unwrap();
2215        std::fs::write(destination.join("demo.dll"), b"installed").unwrap();
2216        let record = native_record("demo");
2217        write_native_packages_at(&metadata, &[record.clone()]).unwrap();
2218        let original_registry = std::fs::read(&metadata).unwrap();
2219        std::fs::write(&build, b"rebuilt").unwrap();
2220
2221        assert!(install_native_package_at(
2222            &destination,
2223            &metadata,
2224            record.clone(),
2225            &[build.clone()],
2226            false,
2227        )
2228        .unwrap()
2229        .is_empty());
2230        assert_eq!(
2231            std::fs::read(destination.join("demo.dll")).unwrap(),
2232            b"installed"
2233        );
2234        assert_eq!(std::fs::read(&metadata).unwrap(), original_registry);
2235        let mut older = record.clone();
2236        older.version = "1.0.0".into();
2237        let error = install_native_package_at(
2238            &destination,
2239            &metadata,
2240            older.clone(),
2241            &[build.clone()],
2242            false,
2243        )
2244        .unwrap_err();
2245        assert!(error.contains("--force to downgrade"));
2246        assert_eq!(
2247            std::fs::read(destination.join("demo.dll")).unwrap(),
2248            b"installed"
2249        );
2250        assert_eq!(std::fs::read(&metadata).unwrap(), original_registry);
2251
2252        for forced in [record, older] {
2253            install_native_package_at(
2254                &destination,
2255                &metadata,
2256                forced.clone(),
2257                &[build.clone()],
2258                true,
2259            )
2260            .unwrap();
2261            let records = read_native_package_registry_at(&metadata)
2262                .unwrap()
2263                .into_records();
2264            assert_eq!(records[0].version, forced.version);
2265            let active = destination.join(&records[0].artifacts[0]);
2266            assert_eq!(std::fs::read(active).unwrap(), b"rebuilt");
2267            assert_eq!(
2268                std::fs::read(destination.join("demo.dll")).unwrap(),
2269                b"installed"
2270            );
2271        }
2272        assert_no_native_transaction_files(&destination);
2273    }
2274
2275    #[test]
2276    fn native_upgrade_does_not_overwrite_unowned_artifacts() {
2277        let temp = tempfile::tempdir().unwrap();
2278        let destination = temp.path().join("extensions");
2279        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
2280        std::fs::create_dir_all(&destination).unwrap();
2281        std::fs::write(destination.join("demo.dll"), b"installed").unwrap();
2282        std::fs::write(destination.join("unowned.dll"), b"unowned").unwrap();
2283        write_native_packages_at(&metadata, &[native_record("demo")]).unwrap();
2284        let original_registry = std::fs::read(&metadata).unwrap();
2285        let artifact = temp.path().join("build-unowned.dll");
2286        std::fs::write(&artifact, b"new").unwrap();
2287        let mut upgraded = native_record("demo");
2288        upgraded.version = "2.0.0".into();
2289        let installed =
2290            install_native_package_at(&destination, &metadata, upgraded, &[artifact], false)
2291                .unwrap();
2292        assert_eq!(installed.len(), 1);
2293        assert_eq!(
2294            std::fs::read(destination.join("demo.dll")).unwrap(),
2295            b"installed"
2296        );
2297        assert_eq!(
2298            std::fs::read(destination.join("unowned.dll")).unwrap(),
2299            b"unowned"
2300        );
2301        assert_ne!(std::fs::read(&metadata).unwrap(), original_registry);
2302        assert_no_native_transaction_files(&destination);
2303    }
2304
2305    struct TempAgent {
2306        _guard: std::sync::MutexGuard<'static, ()>,
2307        temp: tempfile::TempDir,
2308        previous: Option<std::ffi::OsString>,
2309    }
2310
2311    impl TempAgent {
2312        fn new() -> Self {
2313            let guard = crate::config::test_support::env_lock()
2314                .lock()
2315                .unwrap_or_else(|poisoned| poisoned.into_inner());
2316            let previous = std::env::var_os(crate::config::CONFIG_DIR_ENV);
2317            let temp = tempfile::tempdir().unwrap();
2318            std::env::set_var(crate::config::CONFIG_DIR_ENV, temp.path());
2319            Self {
2320                _guard: guard,
2321                temp,
2322                previous,
2323            }
2324        }
2325
2326        fn metadata_path(&self) -> PathBuf {
2327            self.temp.path().join(NATIVE_PACKAGES_FILE)
2328        }
2329    }
2330
2331    impl Drop for TempAgent {
2332        fn drop(&mut self) {
2333            match self.previous.take() {
2334                Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
2335                None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
2336            }
2337        }
2338    }
2339
2340    #[test]
2341    fn parses_registry_package_and_options() {
2342        let parsed = parse_args(&args(&["my-extension", "--version", "1.2.3", "--force"])).unwrap();
2343        assert_eq!(parsed.package, "my-extension");
2344        assert_eq!(parsed.version.as_deref(), Some("1.2.3"));
2345        assert!(parsed.force);
2346    }
2347
2348    #[test]
2349    fn github_override_and_source_build_are_explicit_options() {
2350        let custom = parse_args(&args(&[
2351            "my-extension",
2352            "--github",
2353            "publisher/monorepo",
2354            "--version",
2355            "1.2.3",
2356        ]))
2357        .unwrap();
2358        assert_eq!(custom.repository.as_deref(), Some("publisher/monorepo"));
2359        assert_eq!(custom.version.as_deref(), Some("1.2.3"));
2360        assert!(!custom.build);
2361        let custom_url = parse_args(&args(&[
2362            "my-extension",
2363            "--github",
2364            "https://github.com/publisher/monorepo",
2365        ]))
2366        .unwrap();
2367        assert!(custom_url.repository.is_some());
2368        assert!(
2369            parse_args(&args(&["my-extension", "--build", "--locked"]))
2370                .unwrap()
2371                .build
2372        );
2373        assert!(parse_args(&args(&["my-extension", "--offline"])).is_ok());
2374        assert!(parse_args(&args(&[
2375            "my-extension",
2376            "--github",
2377            "owner/repo",
2378            "--build"
2379        ]))
2380        .is_err());
2381        assert!(parse_args(&args(&[
2382            "my-extension",
2383            "--github",
2384            "owner/repo",
2385            "--path",
2386            "."
2387        ]))
2388        .is_err());
2389        assert!(parse_args(&args(&["my-extension", "--locked"])).is_err());
2390    }
2391
2392    #[test]
2393    fn synchronous_source_backend_cannot_silently_compile_a_prebuilt_request() {
2394        let _agent = TempAgent::new();
2395        assert_eq!(run(&args(&["demo"])), 2);
2396        assert_eq!(
2397            run(&args(&[
2398                "demo",
2399                "--github",
2400                "publisher/repo",
2401                "--version",
2402                "1.2.3"
2403            ])),
2404            2
2405        );
2406    }
2407
2408    #[test]
2409    fn uninstall_prebuilt_package_uses_its_recorded_library_name() {
2410        let agent = TempAgent::new();
2411        let directory = agent.temp.path().join("extensions");
2412        std::fs::create_dir_all(&directory).unwrap();
2413        std::fs::write(directory.join("different_library.dll"), b"prebuilt library").unwrap();
2414        let record: InstalledNativePackage = serde_json::from_value(serde_json::json!({
2415            "name":"demo", "version":"1.2.3", "source":"prebuilt:https://github.com/owner/repo",
2416            "artifacts":["different_library.dll"],
2417            "prebuilt":{"repository":"https://github.com/owner/repo", "target":"x86_64-pc-windows-msvc",
2418                "manifest_sha256":"a".repeat(64),"source_commit":"b".repeat(40),"sdk_version":"0.3.23","plugin_abi":4,
2419                "archive_sha256":"c".repeat(64),"library_sha256":"d".repeat(64),"custom_repository":true}
2420        })).unwrap();
2421        write_native_packages_at(&agent.metadata_path(), &[record]).unwrap();
2422        assert_eq!(uninstall(&args(&["demo"])), 0);
2423        assert!(!directory.join("different_library.dll").exists());
2424        assert!(installed_native_packages_strict().unwrap().is_empty());
2425    }
2426
2427    #[test]
2428    fn parses_local_package() {
2429        let parsed = parse_args(&args(&["--path", "../extension", "my-extension"])).unwrap();
2430        assert_eq!(parsed.path, Some(PathBuf::from("../extension")));
2431    }
2432
2433    #[test]
2434    fn local_path_can_infer_package_name() {
2435        let parsed = parse_args(&args(&["--path", ".", "--force"])).unwrap();
2436        assert!(!parsed.package.is_empty());
2437        assert!(valid_package_name(&parsed.package));
2438        assert!(parsed.force);
2439    }
2440
2441    #[test]
2442    fn rejects_non_extension_options_and_invalid_names() {
2443        assert!(parse_args(&args(&["my.extension"])).is_err());
2444        assert!(parse_args(&args(&["my-extension", "--unknown"])).is_err());
2445        assert!(parse_args(&args(&["my-extension", "--path", ".", "--version", "1"])).is_err());
2446    }
2447
2448    #[test]
2449    fn cdylib_hint_recommends_unified_and_documents_legacy_compatibility() {
2450        assert!(CDYLIB_EXTENSION_HINT.contains("rpi_plugin_register"));
2451        assert!(CDYLIB_EXTENSION_HINT.contains("rpi_plugin_register_v2"));
2452        assert!(CDYLIB_EXTENSION_HINT.contains("rpi_plugin_register_v3"));
2453    }
2454
2455    #[test]
2456    fn registry_read_distinguishes_missing_and_valid_files() {
2457        let temp = tempfile::tempdir().unwrap();
2458        let path = temp.path().join(NATIVE_PACKAGES_FILE);
2459
2460        assert_eq!(
2461            read_native_package_registry_at(&path).unwrap(),
2462            NativePackageRegistry::Missing
2463        );
2464
2465        std::fs::write(
2466            &path,
2467            br#"[{"name":"demo","version":"1.2.3","source":null}]"#,
2468        )
2469        .unwrap();
2470        assert_eq!(
2471            read_native_package_registry_at(&path).unwrap(),
2472            NativePackageRegistry::Valid(vec![InstalledNativePackage {
2473                name: "demo".to_string(),
2474                version: "1.2.3".to_string(),
2475                source: None,
2476                prebuilt: None,
2477                artifacts: Vec::new(),
2478            }])
2479        );
2480    }
2481
2482    #[test]
2483    fn active_global_artifacts_exclude_retired_versioned_files() {
2484        let agent = tempfile::tempdir().unwrap();
2485        let extensions = agent.path().join("extensions");
2486        std::fs::create_dir_all(&extensions).unwrap();
2487        let active = "libdemo-v2.0.0-0123456789abcdef0123456789abcdef.dll";
2488        let retired = "libdemo-v1.0.0-abcdef0123456789abcdef0123456789.dll";
2489        std::fs::write(extensions.join(active), b"active").unwrap();
2490        std::fs::write(extensions.join(retired), b"retired").unwrap();
2491        std::fs::write(extensions.join("legacy.dll"), b"legacy").unwrap();
2492        write_native_packages_at(
2493            &agent.path().join(NATIVE_PACKAGES_FILE),
2494            &[InstalledNativePackage {
2495                name: "demo".into(),
2496                version: "2.0.0".into(),
2497                source: None,
2498                prebuilt: None,
2499                artifacts: vec![active.into()],
2500            }],
2501        )
2502        .unwrap();
2503
2504        assert_eq!(
2505            active_global_native_package_artifacts_at(agent.path()).unwrap(),
2506            vec![extensions.join(active)]
2507        );
2508        assert_eq!(
2509            unregistered_global_native_package_artifacts_at(agent.path()).unwrap(),
2510            vec![extensions.join("legacy.dll")]
2511        );
2512    }
2513
2514    #[test]
2515    fn registry_read_rejects_corrupt_json() {
2516        let temp = tempfile::tempdir().unwrap();
2517        let path = temp.path().join(NATIVE_PACKAGES_FILE);
2518        std::fs::write(&path, b"[{").unwrap();
2519
2520        let error = read_native_package_registry_at(&path).unwrap_err();
2521        assert!(error.contains("invalid JSON or schema"));
2522    }
2523
2524    #[test]
2525    fn registry_read_rejects_wrong_schema() {
2526        let temp = tempfile::tempdir().unwrap();
2527        let path = temp.path().join(NATIVE_PACKAGES_FILE);
2528        std::fs::write(&path, br#"{"name":"demo","version":"1.2.3"}"#).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 record_does_not_replace_a_corrupt_registry() {
2536        let temp = tempfile::tempdir().unwrap();
2537        let path = temp.path().join(NATIVE_PACKAGES_FILE);
2538        let original = b"[{broken metadata";
2539        std::fs::write(&path, original).unwrap();
2540
2541        assert!(record_native_package_at(&path, &native_record("demo")).is_err());
2542        assert_eq!(std::fs::read(&path).unwrap(), original);
2543    }
2544
2545    #[test]
2546    fn native_install_transaction_preserves_loaded_artifacts_and_publishes_new_ones() {
2547        let temp = tempfile::tempdir().unwrap();
2548        let destination = temp.path().join("extensions");
2549        let metadata_path = temp.path().join(NATIVE_PACKAGES_FILE);
2550        let build = temp.path().join("build");
2551        std::fs::create_dir_all(&destination).unwrap();
2552        std::fs::create_dir_all(&build).unwrap();
2553        std::fs::write(destination.join("old.dll"), b"old-only").unwrap();
2554        std::fs::write(destination.join("same.dll"), b"old-shared").unwrap();
2555        let old = InstalledNativePackage {
2556            name: "demo".into(),
2557            version: "1.0.0".into(),
2558            source: None,
2559            prebuilt: None,
2560            artifacts: vec!["old.dll".into(), "same.dll".into()],
2561        };
2562        write_native_packages_at(&metadata_path, &[old]).unwrap();
2563        std::fs::write(build.join("new.dll"), b"new-only").unwrap();
2564        std::fs::write(build.join("same.dll"), b"new-shared").unwrap();
2565
2566        let installed = install_native_package_at(
2567            &destination,
2568            &metadata_path,
2569            InstalledNativePackage {
2570                name: "demo".into(),
2571                version: "2.0.0".into(),
2572                source: None,
2573                prebuilt: None,
2574                artifacts: Vec::new(),
2575            },
2576            &[build.join("new.dll"), build.join("same.dll")],
2577            false,
2578        )
2579        .unwrap();
2580
2581        assert_eq!(installed.len(), 2);
2582        assert!(installed.iter().all(|path| path.exists()));
2583        assert_eq!(
2584            std::fs::read(destination.join("old.dll")).unwrap(),
2585            b"old-only"
2586        );
2587        assert_eq!(
2588            std::fs::read(destination.join("same.dll")).unwrap(),
2589            b"old-shared"
2590        );
2591        assert!(installed
2592            .iter()
2593            .any(|path| { std::fs::read(path).ok().as_deref() == Some(b"new-only".as_slice()) }));
2594        assert!(installed
2595            .iter()
2596            .any(|path| { std::fs::read(path).ok().as_deref() == Some(b"new-shared".as_slice()) }));
2597        let records = read_native_package_registry_at(&metadata_path)
2598            .unwrap()
2599            .into_records();
2600        assert_eq!(records.len(), 1);
2601        assert_eq!(records[0].version, "2.0.0");
2602        let active_names = installed
2603            .iter()
2604            .map(|path| path.file_name().unwrap().to_string_lossy().into_owned())
2605            .collect::<Vec<_>>();
2606        assert_eq!(records[0].artifacts, active_names);
2607        assert_no_native_transaction_files(temp.path());
2608        assert_no_native_transaction_files(&destination);
2609    }
2610
2611    #[test]
2612    fn native_install_transaction_rolls_back_artifacts_and_registry() {
2613        let temp = tempfile::tempdir().unwrap();
2614        let destination = temp.path().join("extensions");
2615        let metadata_path = temp.path().join(NATIVE_PACKAGES_FILE);
2616        let build = temp.path().join("build");
2617        std::fs::create_dir_all(&destination).unwrap();
2618        std::fs::create_dir_all(&build).unwrap();
2619        std::fs::write(destination.join("old.dll"), b"old-only").unwrap();
2620        std::fs::write(destination.join("same.dll"), b"old-shared").unwrap();
2621        let old = InstalledNativePackage {
2622            name: "demo".into(),
2623            version: "1.0.0".into(),
2624            source: None,
2625            prebuilt: None,
2626            artifacts: vec!["old.dll".into(), "same.dll".into()],
2627        };
2628        write_native_packages_at(&metadata_path, &[old]).unwrap();
2629        let original_registry = std::fs::read(&metadata_path).unwrap();
2630        std::fs::write(build.join("new.dll"), b"new-only").unwrap();
2631        std::fs::write(build.join("same.dll"), b"new-shared").unwrap();
2632
2633        let error = install_native_package_at_with_hook(
2634            &destination,
2635            &metadata_path,
2636            InstalledNativePackage {
2637                name: "demo".into(),
2638                version: "2.0.0".into(),
2639                source: None,
2640                prebuilt: None,
2641                artifacts: Vec::new(),
2642            },
2643            &[build.join("new.dll"), build.join("same.dll")],
2644            &[],
2645            false,
2646            |_, target| {
2647                if target == metadata_path {
2648                    Err("injected registry activation failure".into())
2649                } else {
2650                    Ok(())
2651                }
2652            },
2653        )
2654        .unwrap_err();
2655
2656        assert!(error.contains("injected registry activation failure"));
2657        assert_eq!(std::fs::read(&metadata_path).unwrap(), original_registry);
2658        assert_eq!(
2659            std::fs::read(destination.join("old.dll")).unwrap(),
2660            b"old-only"
2661        );
2662        assert_eq!(
2663            std::fs::read(destination.join("same.dll")).unwrap(),
2664            b"old-shared"
2665        );
2666        assert!(!destination.join("new.dll").exists());
2667        assert_no_native_transaction_files(temp.path());
2668        assert_no_native_transaction_files(&destination);
2669    }
2670
2671    fn assert_no_native_transaction_files(directory: &Path) {
2672        for entry in std::fs::read_dir(directory).unwrap() {
2673            let name = entry.unwrap().file_name().to_string_lossy().into_owned();
2674            assert!(!name.contains(".rpi-stage-"), "left staged file: {name}");
2675            assert!(!name.contains(".rpi-backup-"), "left backup file: {name}");
2676            assert!(
2677                !name.contains(".rpi-assets-stage-"),
2678                "left asset stage: {name}"
2679            );
2680        }
2681    }
2682
2683    #[test]
2684    fn best_effort_registry_read_omits_corrupt_metadata() {
2685        let agent = TempAgent::new();
2686        std::fs::write(agent.metadata_path(), b"[{broken metadata").unwrap();
2687
2688        assert!(installed_native_packages().is_empty());
2689    }
2690
2691    #[test]
2692    fn install_fails_closed_before_work_when_registry_is_corrupt() {
2693        let agent = TempAgent::new();
2694        let path = agent.metadata_path();
2695        let original = b"[{broken metadata";
2696        std::fs::write(&path, original).unwrap();
2697
2698        assert_eq!(run(&args(&["demo"])), 1);
2699        assert_eq!(std::fs::read(&path).unwrap(), original);
2700        assert!(!agent.temp.path().join("extensions").exists());
2701    }
2702
2703    #[test]
2704    fn uninstall_fails_closed_without_removing_artifacts() {
2705        let agent = TempAgent::new();
2706        let path = agent.metadata_path();
2707        let original = b"[{broken metadata";
2708        std::fs::write(&path, original).unwrap();
2709        let extension_dir = agent.temp.path().join("extensions");
2710        std::fs::create_dir_all(&extension_dir).unwrap();
2711        let artifact = extension_dir.join("demo.dll");
2712        std::fs::write(&artifact, b"extension").unwrap();
2713
2714        assert_eq!(uninstall(&args(&["demo"])), 1);
2715        assert_eq!(std::fs::read(&path).unwrap(), original);
2716        assert_eq!(std::fs::read(artifact).unwrap(), b"extension");
2717    }
2718
2719    #[test]
2720    fn uninstall_commits_artifact_and_registry_changes_together() {
2721        let agent = TempAgent::new();
2722        let extension_dir = agent.temp.path().join("extensions");
2723        std::fs::create_dir_all(&extension_dir).unwrap();
2724        std::fs::write(extension_dir.join("demo.dll"), b"demo").unwrap();
2725        std::fs::write(extension_dir.join("other.dll"), b"other").unwrap();
2726        write_native_packages_at(
2727            &agent.metadata_path(),
2728            &[native_record("demo"), native_record("other")],
2729        )
2730        .unwrap();
2731
2732        assert_eq!(uninstall(&args(&["demo"])), 0);
2733        assert!(!extension_dir.join("demo.dll").exists());
2734        assert_eq!(
2735            std::fs::read(extension_dir.join("other.dll")).unwrap(),
2736            b"other"
2737        );
2738        assert_eq!(
2739            read_native_package_registry_at(&agent.metadata_path())
2740                .unwrap()
2741                .into_records(),
2742            vec![native_record("other")]
2743        );
2744        assert_no_native_transaction_files(agent.temp.path());
2745        assert_no_native_transaction_files(&extension_dir);
2746    }
2747
2748    #[test]
2749    fn uninstall_uses_recorded_artifacts_without_name_fallback() {
2750        let agent = TempAgent::new();
2751        let extension_dir = agent.temp.path().join("extensions");
2752        std::fs::create_dir_all(&extension_dir).unwrap();
2753        std::fs::write(extension_dir.join("recorded.dll"), b"managed").unwrap();
2754        std::fs::write(extension_dir.join("demo.dll"), b"unmanaged").unwrap();
2755        write_native_packages_at(
2756            &agent.metadata_path(),
2757            &[InstalledNativePackage {
2758                name: "demo".into(),
2759                version: "1.2.3".into(),
2760                source: None,
2761                prebuilt: None,
2762                artifacts: vec!["recorded.dll".into()],
2763            }],
2764        )
2765        .unwrap();
2766
2767        assert_eq!(uninstall(&args(&["demo"])), 0);
2768        assert!(!extension_dir.join("recorded.dll").exists());
2769        assert_eq!(
2770            std::fs::read(extension_dir.join("demo.dll")).unwrap(),
2771            b"unmanaged"
2772        );
2773        assert!(!agent.metadata_path().exists());
2774        assert_no_native_transaction_files(agent.temp.path());
2775        assert_no_native_transaction_files(&extension_dir);
2776    }
2777
2778    /// A prebuilt record whose ledger names `assets`, as the archive installer writes it.
2779    fn prebuilt_record(
2780        name: &str,
2781        version: &str,
2782        assets: &[(&str, &[u8])],
2783    ) -> InstalledNativePackage {
2784        InstalledNativePackage {
2785            name: name.into(),
2786            version: version.into(),
2787            source: Some(format!("prebuilt:https://github.com/owner/{name}")),
2788            prebuilt: Some(crate::prebuilt_extensions::PrebuiltRecord {
2789                repository: format!("https://github.com/owner/{name}"),
2790                target: "x86_64-unknown-linux-gnu".into(),
2791                manifest_sha256: "a".repeat(64),
2792                source_commit: "b".repeat(40),
2793                sdk_version: "0.3.23".into(),
2794                plugin_abi: 4,
2795                archive_sha256: "c".repeat(64),
2796                library_sha256: "d".repeat(64),
2797                custom_repository: false,
2798                assets: assets
2799                    .iter()
2800                    .map(|(path, bytes)| crate::prebuilt_extensions::PrebuiltAsset {
2801                        path: (*path).into(),
2802                        sha256: crate::prebuilt_extensions::hash(bytes),
2803                    })
2804                    .collect(),
2805            }),
2806            artifacts: Vec::new(),
2807        }
2808    }
2809
2810    fn sidecars(assets: &[(&str, &[u8])]) -> Vec<NativeAssetFile> {
2811        assets
2812            .iter()
2813            .map(|(path, bytes)| NativeAssetFile {
2814                path: (*path).into(),
2815                bytes: bytes.to_vec(),
2816            })
2817            .collect()
2818    }
2819
2820    #[test]
2821    fn native_asset_upgrade_replaces_sidecars_and_prunes_stale_ones() {
2822        let temp = tempfile::tempdir().unwrap();
2823        let destination = temp.path().join("extensions");
2824        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
2825        let library = temp.path().join("libdemo.so");
2826        std::fs::write(&library, b"library v1").unwrap();
2827        let v1 = [
2828            ("runtime/main.mjs", &b"v1"[..]),
2829            ("runtime/old.mjs", &b"old"[..]),
2830        ];
2831        install_native_package_with_assets_at(
2832            &destination,
2833            &metadata,
2834            prebuilt_record("demo", "1.0.0", &v1),
2835            std::slice::from_ref(&library),
2836            &sidecars(&v1),
2837            false,
2838        )
2839        .unwrap();
2840        assert_eq!(
2841            std::fs::read(destination.join("runtime/old.mjs")).unwrap(),
2842            b"old"
2843        );
2844
2845        std::fs::write(&library, b"library v2").unwrap();
2846        let v2 = [
2847            ("runtime/main.mjs", &b"v2"[..]),
2848            ("runtime/deep/lib.mjs", &b"deep"[..]),
2849        ];
2850        let installed = install_native_package_with_assets_at(
2851            &destination,
2852            &metadata,
2853            prebuilt_record("demo", "2.0.0", &v2),
2854            std::slice::from_ref(&library),
2855            &sidecars(&v2),
2856            false,
2857        )
2858        .unwrap();
2859        assert_eq!(installed.len(), 3);
2860        let active_library = installed
2861            .iter()
2862            .find(|path| is_dynamic_library(path))
2863            .expect("installed library");
2864        assert_ne!(active_library, &destination.join("libdemo.so"));
2865        assert_eq!(std::fs::read(active_library).unwrap(), b"library v2");
2866        assert_eq!(
2867            std::fs::read(destination.join("libdemo.so")).unwrap(),
2868            b"library v1"
2869        );
2870        assert_eq!(
2871            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
2872            b"v2"
2873        );
2874        assert_eq!(
2875            std::fs::read(destination.join("runtime/deep/lib.mjs")).unwrap(),
2876            b"deep"
2877        );
2878        assert!(!destination.join("runtime/old.mjs").exists());
2879        let records = read_native_package_registry_at(&metadata)
2880            .unwrap()
2881            .into_records();
2882        assert_eq!(records[0].version, "2.0.0");
2883        let ledger: Vec<&str> = recorded_asset_paths(&records[0]);
2884        assert_eq!(ledger, vec!["runtime/main.mjs", "runtime/deep/lib.mjs"]);
2885        // Dropping every sidecar removes the files and the directories they emptied.
2886        install_native_package_with_assets_at(
2887            &destination,
2888            &metadata,
2889            prebuilt_record("demo", "3.0.0", &[]),
2890            std::slice::from_ref(&library),
2891            &[],
2892            false,
2893        )
2894        .unwrap();
2895        assert!(!destination.join("runtime").exists());
2896        let records = read_native_package_registry_at(&metadata)
2897            .unwrap()
2898            .into_records();
2899        let active_library = destination.join(&records[0].artifacts[0]);
2900        assert_eq!(std::fs::read(active_library).unwrap(), b"library v2");
2901        assert_eq!(
2902            std::fs::read(destination.join("libdemo.so")).unwrap(),
2903            b"library v1"
2904        );
2905        assert_no_native_transaction_files(temp.path());
2906        assert_no_native_transaction_files(&destination);
2907    }
2908
2909    #[test]
2910    fn native_asset_failure_during_activation_restores_the_previous_install() {
2911        let temp = tempfile::tempdir().unwrap();
2912        let destination = temp.path().join("extensions");
2913        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
2914        let library = temp.path().join("libdemo.so");
2915        std::fs::write(&library, b"old library").unwrap();
2916        let v1 = [("runtime/main.mjs", &b"v1"[..])];
2917        install_native_package_with_assets_at(
2918            &destination,
2919            &metadata,
2920            prebuilt_record("demo", "1.0.0", &v1),
2921            std::slice::from_ref(&library),
2922            &sidecars(&v1),
2923            false,
2924        )
2925        .unwrap();
2926        let original_registry = std::fs::read(&metadata).unwrap();
2927
2928        std::fs::write(&library, b"new library").unwrap();
2929        let v2 = [
2930            ("runtime/main.mjs", &b"v2"[..]),
2931            ("runtime/extra.mjs", &b"extra"[..]),
2932        ];
2933        // Replacements activate in order: library, main.mjs, extra.mjs, registry.
2934        let error = install_native_package_at_with_hook(
2935            &destination,
2936            &metadata,
2937            prebuilt_record("demo", "2.0.0", &v2),
2938            std::slice::from_ref(&library),
2939            &sidecars(&v2),
2940            false,
2941            |index, _| {
2942                if index == 2 {
2943                    Err("injected sidecar activation failure".into())
2944                } else {
2945                    Ok(())
2946                }
2947            },
2948        )
2949        .unwrap_err();
2950
2951        assert!(
2952            error.contains("injected sidecar activation failure"),
2953            "{error}"
2954        );
2955        assert_eq!(
2956            std::fs::read(destination.join("libdemo.so")).unwrap(),
2957            b"old library"
2958        );
2959        assert_eq!(
2960            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
2961            b"v1"
2962        );
2963        assert!(!destination.join("runtime/extra.mjs").exists());
2964        assert_eq!(std::fs::read(&metadata).unwrap(), original_registry);
2965        assert_no_native_transaction_files(temp.path());
2966        assert_no_native_transaction_files(&destination);
2967        assert_no_native_transaction_files(&destination.join("runtime"));
2968
2969        // The same upgrade succeeds once the failure is gone.
2970        install_native_package_with_assets_at(
2971            &destination,
2972            &metadata,
2973            prebuilt_record("demo", "2.0.0", &v2),
2974            std::slice::from_ref(&library),
2975            &sidecars(&v2),
2976            false,
2977        )
2978        .unwrap();
2979        assert_eq!(
2980            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
2981            b"v2"
2982        );
2983        assert_eq!(
2984            std::fs::read(destination.join("runtime/extra.mjs")).unwrap(),
2985            b"extra"
2986        );
2987    }
2988
2989    #[test]
2990    fn native_asset_conflicts_and_overlaps_fail_before_any_write() {
2991        let temp = tempfile::tempdir().unwrap();
2992        let destination = temp.path().join("extensions");
2993        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
2994        let library = temp.path().join("libdemo.so");
2995        std::fs::write(&library, b"demo library").unwrap();
2996        let other = temp.path().join("libother.so");
2997        std::fs::write(&other, b"other library").unwrap();
2998        let shared = [("runtime/shared.mjs", &b"other"[..])];
2999        install_native_package_with_assets_at(
3000            &destination,
3001            &metadata,
3002            prebuilt_record("other", "1.0.0", &shared),
3003            std::slice::from_ref(&other),
3004            &sidecars(&shared),
3005            false,
3006        )
3007        .unwrap();
3008        let original_registry = std::fs::read(&metadata).unwrap();
3009
3010        let attempts: [&[(&str, &[u8])]; 3] = [
3011            &[("runtime/shared.mjs", &b"demo"[..])],
3012            &[("Runtime/Shared.mjs", &b"demo"[..])],
3013            &[("runtime", &b"file"[..]), ("runtime/own.mjs", &b"own"[..])],
3014        ];
3015        for assets in attempts {
3016            let error = install_native_package_with_assets_at(
3017                &destination,
3018                &metadata,
3019                prebuilt_record("demo", "1.0.0", assets),
3020                std::slice::from_ref(&library),
3021                &sidecars(assets),
3022                false,
3023            )
3024            .unwrap_err();
3025            assert!(
3026                error.contains("conflicts with asset")
3027                    || error.contains("duplicate or overlapping"),
3028                "{error}"
3029            );
3030            assert!(!destination.join("libdemo.so").exists());
3031            assert_eq!(
3032                std::fs::read(destination.join("runtime/shared.mjs")).unwrap(),
3033                b"other"
3034            );
3035            assert_eq!(std::fs::read(&metadata).unwrap(), original_registry);
3036            assert_eq!(
3037                std::fs::read_dir(destination.join("runtime"))
3038                    .unwrap()
3039                    .count(),
3040                1
3041            );
3042            assert_no_native_transaction_files(&destination);
3043        }
3044    }
3045
3046    #[test]
3047    fn native_asset_replacing_an_unowned_file_requires_force() {
3048        let temp = tempfile::tempdir().unwrap();
3049        let destination = temp.path().join("extensions");
3050        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3051        let library = temp.path().join("libdemo.so");
3052        std::fs::write(&library, b"demo library").unwrap();
3053        std::fs::create_dir_all(destination.join("runtime")).unwrap();
3054        std::fs::write(destination.join("runtime/main.mjs"), b"user file").unwrap();
3055        let assets = [("runtime/main.mjs", &b"demo"[..])];
3056
3057        let error = install_native_package_with_assets_at(
3058            &destination,
3059            &metadata,
3060            prebuilt_record("demo", "1.0.0", &assets),
3061            std::slice::from_ref(&library),
3062            &sidecars(&assets),
3063            false,
3064        )
3065        .unwrap_err();
3066        assert!(error.contains("use --force to replace it"), "{error}");
3067        assert_eq!(
3068            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3069            b"user file"
3070        );
3071        assert!(!metadata.exists());
3072
3073        install_native_package_with_assets_at(
3074            &destination,
3075            &metadata,
3076            prebuilt_record("demo", "1.0.0", &assets),
3077            std::slice::from_ref(&library),
3078            &sidecars(&assets),
3079            true,
3080        )
3081        .unwrap();
3082        assert_eq!(
3083            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3084            b"demo"
3085        );
3086    }
3087
3088    #[test]
3089    fn uninstall_removes_recorded_sidecars_and_only_the_directories_they_empty() {
3090        let agent = TempAgent::new();
3091        let extension_dir = agent.temp.path().join("extensions");
3092        std::fs::create_dir_all(extension_dir.join("runtime/deep")).unwrap();
3093        std::fs::write(extension_dir.join("libdemo.so"), b"library").unwrap();
3094        std::fs::write(extension_dir.join("runtime/main.mjs"), b"main").unwrap();
3095        std::fs::write(extension_dir.join("runtime/deep/lib.mjs"), b"deep").unwrap();
3096        std::fs::write(extension_dir.join("runtime/user.mjs"), b"user").unwrap();
3097        let mut record = prebuilt_record(
3098            "demo",
3099            "1.0.0",
3100            &[
3101                ("runtime/main.mjs", &b"main"[..]),
3102                ("runtime/deep/lib.mjs", &b"deep"[..]),
3103            ],
3104        );
3105        record.artifacts = vec!["libdemo.so".into()];
3106        write_native_packages_at(&agent.metadata_path(), &[record]).unwrap();
3107
3108        assert_eq!(uninstall(&args(&["demo"])), 0);
3109        assert!(!extension_dir.join("libdemo.so").exists());
3110        assert!(!extension_dir.join("runtime/main.mjs").exists());
3111        assert!(!extension_dir.join("runtime/deep").exists());
3112        assert_eq!(
3113            std::fs::read(extension_dir.join("runtime/user.mjs")).unwrap(),
3114            b"user"
3115        );
3116        assert!(!agent.metadata_path().exists());
3117        assert_no_native_transaction_files(agent.temp.path());
3118        assert_no_native_transaction_files(&extension_dir);
3119    }
3120
3121    #[test]
3122    fn native_asset_case_only_rename_prunes_the_old_sidecar() {
3123        let temp = tempfile::tempdir().unwrap();
3124        let destination = temp.path().join("extensions");
3125        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3126        let library = temp.path().join("libdemo.so");
3127        std::fs::write(&library, b"library v1").unwrap();
3128        let first = [("Runtime/main.mjs", &b"worker v1"[..])];
3129        install_native_package_with_assets_at(
3130            &destination,
3131            &metadata,
3132            prebuilt_record("demo", "1.0.0", &first),
3133            std::slice::from_ref(&library),
3134            &sidecars(&first),
3135            false,
3136        )
3137        .unwrap();
3138        let second = [("runtime/main.mjs", &b"worker v2"[..])];
3139        install_native_package_with_assets_at(
3140            &destination,
3141            &metadata,
3142            prebuilt_record("demo", "1.1.0", &second),
3143            std::slice::from_ref(&library),
3144            &sidecars(&second),
3145            false,
3146        )
3147        .unwrap();
3148
3149        assert_eq!(
3150            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3151            b"worker v2"
3152        );
3153        // The old name is no longer recorded, so it must not survive beside the new one.
3154        fn store_files(dir: &Path) -> usize {
3155            std::fs::read_dir(dir)
3156                .unwrap()
3157                .map(|entry| {
3158                    let path = entry.unwrap().path();
3159                    if path.is_dir() {
3160                        store_files(&path)
3161                    } else {
3162                        1
3163                    }
3164                })
3165                .sum()
3166        }
3167        assert_eq!(store_files(&destination), 3);
3168    }
3169
3170    #[test]
3171    fn native_asset_case_variant_of_an_owned_sidecar_is_not_owned() {
3172        let temp = tempfile::tempdir().unwrap();
3173        let destination = temp.path().join("extensions");
3174        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3175        let library = temp.path().join("libdemo.so");
3176        std::fs::write(&library, b"library").unwrap();
3177        let first = [("Runtime/main.mjs", &b"worker v1"[..])];
3178        install_native_package_with_assets_at(
3179            &destination,
3180            &metadata,
3181            prebuilt_record("demo", "1.0.0", &first),
3182            std::slice::from_ref(&library),
3183            &sidecars(&first),
3184            false,
3185        )
3186        .unwrap();
3187        std::fs::create_dir_all(destination.join("runtime")).unwrap();
3188        std::fs::write(destination.join("runtime/main.mjs"), b"user file").unwrap();
3189        if std::fs::read(destination.join("Runtime/main.mjs")).unwrap() == b"user file" {
3190            return; // case-insensitive store: the two names are one file, nothing to test
3191        }
3192
3193        let second = [("runtime/main.mjs", &b"worker v2"[..])];
3194        let error = install_native_package_with_assets_at(
3195            &destination,
3196            &metadata,
3197            prebuilt_record("demo", "1.1.0", &second),
3198            std::slice::from_ref(&library),
3199            &sidecars(&second),
3200            false,
3201        )
3202        .unwrap_err();
3203        assert!(error.contains("--force"), "{error}");
3204        assert_eq!(
3205            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3206            b"user file"
3207        );
3208        assert_eq!(
3209            std::fs::read(destination.join("Runtime/main.mjs")).unwrap(),
3210            b"worker v1"
3211        );
3212
3213        install_native_package_with_assets_at(
3214            &destination,
3215            &metadata,
3216            prebuilt_record("demo", "1.1.0", &second),
3217            std::slice::from_ref(&library),
3218            &sidecars(&second),
3219            true,
3220        )
3221        .unwrap();
3222        assert_eq!(
3223            std::fs::read(destination.join("runtime/main.mjs")).unwrap(),
3224            b"worker v2"
3225        );
3226        assert!(!destination.join("Runtime").exists());
3227    }
3228
3229    #[test]
3230    fn native_asset_failed_first_install_removes_the_directories_it_created() {
3231        let temp = tempfile::tempdir().unwrap();
3232        let destination = temp.path().join("extensions");
3233        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3234        let library = temp.path().join("libdemo.so");
3235        std::fs::write(&library, b"library").unwrap();
3236        std::fs::create_dir_all(destination.join("keep")).unwrap();
3237        let assets = [("runtime/deep/x.mjs", &b"x"[..]), ("keep/y.mjs", &b"y"[..])];
3238        // Replacements activate in order: library, x.mjs, y.mjs, registry.
3239        let error = install_native_package_at_with_hook(
3240            &destination,
3241            &metadata,
3242            prebuilt_record("demo", "1.0.0", &assets),
3243            std::slice::from_ref(&library),
3244            &sidecars(&assets),
3245            false,
3246            |index, _| {
3247                if index == 2 {
3248                    Err("injected sidecar activation failure".into())
3249                } else {
3250                    Ok(())
3251                }
3252            },
3253        )
3254        .unwrap_err();
3255
3256        assert!(error.contains("injected"), "{error}");
3257        assert!(!destination.join("runtime").exists());
3258        // A directory that existed before the install is left alone, even though it is empty.
3259        assert!(destination.join("keep").is_dir());
3260        assert!(!destination.join("libdemo.so").exists());
3261        assert!(!metadata.exists());
3262        assert_no_native_transaction_files(temp.path());
3263        assert_no_native_transaction_files(&destination);
3264    }
3265
3266    #[test]
3267    fn native_asset_overlap_within_one_package_is_rejected_before_any_write() {
3268        // No other package is installed, so only the intra-package check can reject this.
3269        let temp = tempfile::tempdir().unwrap();
3270        let destination = temp.path().join("extensions");
3271        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3272        let library = temp.path().join("libdemo.so");
3273        std::fs::write(&library, b"demo library").unwrap();
3274        let assets = [("runtime", &b"file"[..]), ("runtime/own.mjs", &b"own"[..])];
3275
3276        let error = install_native_package_with_assets_at(
3277            &destination,
3278            &metadata,
3279            prebuilt_record("demo", "1.0.0", &assets),
3280            std::slice::from_ref(&library),
3281            &sidecars(&assets),
3282            false,
3283        )
3284        .unwrap_err();
3285        assert!(error.contains("duplicate or overlapping"), "{error}");
3286        assert_eq!(std::fs::read_dir(&destination).unwrap().count(), 0);
3287        assert!(!metadata.exists());
3288    }
3289
3290    #[cfg(unix)]
3291    #[test]
3292    fn native_asset_parent_links_are_refused_without_writing_through_them() {
3293        let temp = tempfile::tempdir().unwrap();
3294        let destination = temp.path().join("extensions");
3295        let outside = temp.path().join("outside");
3296        let metadata = temp.path().join(NATIVE_PACKAGES_FILE);
3297        let library = temp.path().join("libdemo.so");
3298        std::fs::write(&library, b"demo library").unwrap();
3299        std::fs::create_dir_all(&destination).unwrap();
3300        std::fs::create_dir_all(&outside).unwrap();
3301        std::os::unix::fs::symlink(&outside, destination.join("runtime")).unwrap();
3302        let assets = [("runtime/main.mjs", &b"demo"[..])];
3303
3304        let error = install_native_package_with_assets_at(
3305            &destination,
3306            &metadata,
3307            prebuilt_record("demo", "1.0.0", &assets),
3308            std::slice::from_ref(&library),
3309            &sidecars(&assets),
3310            false,
3311        )
3312        .unwrap_err();
3313        assert!(error.contains("is not a plain directory"), "{error}");
3314        assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
3315        assert!(!destination.join("libdemo.so").exists());
3316    }
3317
3318    fn cdylib_target(name: &'static str) -> CargoTarget {
3319        CargoTarget {
3320            name: name.to_string(),
3321            crate_types: vec!["cdylib".to_string()],
3322        }
3323    }
3324
3325    #[test]
3326    fn find_artifacts_locates_cargo_1_100_build_dir_layout() {
3327        // Cargo 1.100.0 moved intermediate artifacts to
3328        // `<profile>/build/<pkg>/<meta>/out` and stopped creating `deps`.
3329        let temp = tempfile::tempdir().unwrap();
3330        let release_dir = temp.path().join("target").join("release");
3331        let out = release_dir
3332            .join("build")
3333            .join("rpi-web")
3334            .join("0123456789abcdef")
3335            .join("out");
3336        std::fs::create_dir_all(&out).unwrap();
3337        let library = out.join(format!(
3338            "{}rpi_web_extension{}",
3339            std::env::consts::DLL_PREFIX,
3340            std::env::consts::DLL_SUFFIX
3341        ));
3342        std::fs::write(&library, b"cdylib").unwrap();
3343
3344        let target = cdylib_target("rpi_web_extension");
3345        let found = find_artifacts(&release_dir, &[&target]).unwrap();
3346        assert_eq!(found, vec![library]);
3347    }
3348
3349    #[test]
3350    fn find_artifacts_skips_missing_build_directories() {
3351        // With no `deps/` and no `build/`, the scan must report the missing
3352        // artifact instead of failing on the absent directory itself.
3353        let temp = tempfile::tempdir().unwrap();
3354        let release_dir = temp.path().join("target").join("release");
3355        let target = cdylib_target("rpi_web_extension");
3356
3357        let error = find_artifacts(&release_dir, &[&target]).unwrap_err();
3358        assert!(error.contains("no cdylib artifact was found"), "{error}");
3359        assert!(!error.contains("could not inspect build output"), "{error}");
3360    }
3361
3362    #[test]
3363    fn reported_artifacts_win_over_directory_scans() {
3364        // Paths from Cargo's JSON messages are authoritative even when the
3365        // legacy layout also contains a matching library.
3366        let temp = tempfile::tempdir().unwrap();
3367        let release_dir = temp.path().join("target").join("release");
3368        std::fs::create_dir_all(release_dir.join("deps")).unwrap();
3369        let stale = release_dir.join("deps").join(format!(
3370            "{}rpi_web_extension{}",
3371            std::env::consts::DLL_PREFIX,
3372            std::env::consts::DLL_SUFFIX
3373        ));
3374        std::fs::write(&stale, b"stale").unwrap();
3375        let reported = temp.path().join(format!(
3376            "{}rpi_web_extension.abc123{}",
3377            std::env::consts::DLL_PREFIX,
3378            std::env::consts::DLL_SUFFIX
3379        ));
3380        std::fs::write(&reported, b"reported").unwrap();
3381
3382        let target = cdylib_target("rpi_web_extension");
3383        let found = CargoBuild {
3384            artifacts: vec![reported.clone()],
3385        }
3386        .into_artifacts(&release_dir, &[&target])
3387        .unwrap();
3388        assert_eq!(found, vec![reported]);
3389    }
3390}