Skip to main content

rpi_cli/
install.rs

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