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