Skip to main content

rpi_cli/
install.rs

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