Skip to main content

rpi_cli/
resource_management.rs

1//! Native local snapshot management. No compilation, dlopen, provider or network.
2use serde::{Deserialize, Serialize};
3use serde_json::{json, Value};
4use sha2::{Digest, Sha256};
5use std::{
6    collections::BTreeSet,
7    fs::{self, File, OpenOptions},
8    io::{Read, Write},
9    path::{Component, Path, PathBuf},
10    sync::Arc,
11};
12
13const RECEIPTS: &str = "resource-receipts.json";
14const JOURNAL: &str = "resource-transaction.json";
15const LEASE: &str = ".resource-lease";
16const MAX_META: usize = 256 * 1024;
17const MAX_FILES: usize = 2048;
18const MAX_FILE: u64 = 64 * 1024 * 1024;
19const MAX_BYTES: u64 = 256 * 1024 * 1024;
20/// Static protocol description only: never resolves a root or opens metadata.
21pub(crate) fn capabilities() -> Value {
22    json!({"version":1,"command":"resource","commands":{"package":"package","skill":"skill","extension":"extension"},
23        "recoveryCommand":["package","recover"],"kinds":["package","skill","extension"],
24        "scopes":["project","global"],"explicitScopeRequired":true,
25        "operations":["list","inspect","install","update","reinstall","remove","recover"],
26        "localSnapshotsOnly":true,"build":false,"network":false,"hotApply":false,
27        "bounds":{"maxMetadataBytes":MAX_META,"maxResultBytes":MAX_META,"maxResourcesPerScope":128,
28            "maxInventoryEntries":MAX_FILES,"maxDepth":32,"maxFileBytes":MAX_FILE,"maxTotalBytes":MAX_BYTES}})
29}
30
31type Result<T> = std::result::Result<T, String>;
32fn err(e: impl std::fmt::Display) -> String {
33    e.to_string()
34}
35
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "lowercase")]
38pub enum Scope {
39    #[default]
40    Project,
41    Global,
42}
43impl Scope {
44    pub fn is_project(&self) -> bool {
45        *self == Self::Project
46    }
47    pub fn root(self, home: &crate::config::AgentHome, cwd: &Path) -> Result<PathBuf> {
48        let logical = match self {
49            Self::Project => cwd.join(".rpi"),
50            Self::Global => home.root().map_err(err)?,
51        };
52        resolve_scope_root(&logical)
53    }
54}
55
56/// Resolve only the external prefix of an owned scope root.
57///
58/// The root itself is deliberately appended after canonicalization so a link
59/// at `.rpi`/`agent` remains visible to `checked_path`. Missing parents are
60/// represented by a tail appended to the nearest existing parent; this is
61/// path resolution only and never creates directories or reads metadata files.
62fn resolve_scope_root(root: &Path) -> Result<PathBuf> {
63    if !root.is_absolute() {
64        return Err("resource root must be absolute".into());
65    }
66    if root.components().any(|c| matches!(c, Component::ParentDir)) {
67        return Err("resource path traversal".into());
68    }
69    let Some(name) = root.file_name() else {
70        // A filesystem root has no external prefix to resolve.
71        checked_path(root)?;
72        return Ok(root.to_path_buf());
73    };
74    #[cfg(windows)]
75    checked_scope_tail_component(name)?;
76    let mut parent = root.parent().ok_or("resource root has no parent")?;
77    let mut missing = Vec::new();
78    loop {
79        match fs::symlink_metadata(parent) {
80            Ok(_) => break,
81            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
82                missing.push(
83                    parent
84                        .file_name()
85                        .ok_or("resource root has no existing parent")?
86                        .to_os_string(),
87                );
88                parent = parent
89                    .parent()
90                    .ok_or("resource root has no existing parent")?;
91            }
92            Err(e) => {
93                return Err(format!(
94                    "checking resource root parent {}: {e}",
95                    parent.display()
96                ))
97            }
98        }
99    }
100    let mut resolved = fs::canonicalize(parent).map_err(err)?;
101    for component in missing.into_iter().rev() {
102        #[cfg(windows)]
103        checked_scope_tail_component(&component)?;
104        resolved.push(component);
105    }
106    resolved.push(name);
107    checked_path(&resolved)?;
108    Ok(resolved)
109}
110
111#[cfg(windows)]
112fn checked_scope_tail_component(component: &std::ffi::OsStr) -> Result<()> {
113    let name = component
114        .to_str()
115        .ok_or("non-UTF-8 resource scope component")?;
116    // canonicalize returns an extended-length path. Appending a DOS name
117    // with trailing dots/spaces, a device name, or an ADS suffix could then
118    // address a different directory than loaders using the original path.
119    if name.ends_with(['.', ' ']) || name.contains(':') {
120        return Err("ambiguous Windows resource scope component".into());
121    }
122    reserved_identity(name)
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
126#[serde(rename_all = "lowercase")]
127pub(crate) enum Kind {
128    Package,
129    Skill,
130    Extension,
131}
132impl Kind {
133    fn parse(s: &str) -> Result<Self> {
134        match s {
135            "package" => Ok(Self::Package),
136            "skill" => Ok(Self::Skill),
137            "extension" => Ok(Self::Extension),
138            _ => Err("kind must be package, skill or extension".into()),
139        }
140    }
141    fn command(self) -> &'static str {
142        match self {
143            Self::Package => "package",
144            Self::Skill => "skill",
145            Self::Extension => "extension",
146        }
147    }
148    fn dir(self) -> &'static str {
149        match self {
150            Self::Package => "packages",
151            Self::Skill => "skills",
152            Self::Extension => "extensions",
153        }
154    }
155    fn target(self, name: &str) -> PathBuf {
156        Path::new(self.dir()).join(if self == Self::Extension {
157            format!("{name}.{}", std::env::consts::DLL_EXTENSION)
158        } else {
159            name.into()
160        })
161    }
162}
163fn identifier(s: &str) -> Result<()> {
164    if s.is_empty()
165        || s.len() > 96
166        || !s.as_bytes()[0].is_ascii_alphanumeric()
167        || !s
168            .bytes()
169            .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.'))
170        || s.ends_with('.')
171    {
172        return Err("invalid resource identity (portable ASCII name required)".into());
173    }
174    reserved_identity(s)
175}
176
177// Existing native link records allow leading '_' and '.', unlike new managed
178// identities. Accept that grammar only for safe on-disk package components.
179fn legacy_package_identity(s: &str) -> Result<()> {
180    if !crate::packages::valid_name(s) {
181        return Err("invalid native package identity".into());
182    }
183    relative(Path::new(s))?;
184    reserved_identity(s)
185}
186
187fn reserved_identity(s: &str) -> Result<()> {
188    let stem = s.split('.').next().unwrap().to_ascii_uppercase();
189    if matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
190        || (stem.len() == 4
191            && (stem.starts_with("COM") || stem.starts_with("LPT"))
192            && stem.as_bytes()[3].is_ascii_digit())
193    {
194        return Err("reserved resource identity".into());
195    }
196    Ok(())
197}
198fn relative(path: &Path) -> Result<()> {
199    if path.as_os_str().is_empty()
200        || path
201            .components()
202            .any(|c| !matches!(c, Component::Normal(_)))
203    {
204        return Err("unsafe relative resource path".into());
205    }
206    for part in path {
207        let s = part.to_str().ok_or("non-UTF-8 resource path")?;
208        if s.len() > 128 || s.contains([':', '\\']) || s.ends_with(['.', ' ']) {
209            return Err("unsafe resource filename".into());
210        }
211    }
212    Ok(())
213}
214fn is_link(meta: &fs::Metadata) -> bool {
215    #[cfg(windows)]
216    {
217        use std::os::windows::fs::MetadataExt;
218        meta.file_type().is_symlink() || meta.file_attributes() & 0x400 != 0
219    }
220    #[cfg(not(windows))]
221    {
222        meta.file_type().is_symlink()
223    }
224}
225/// Validate every existing ancestor too, including Windows junctions.
226pub(crate) fn checked_path(path: &Path) -> Result<()> {
227    if !path.is_absolute() {
228        return Err("resource path must be absolute".into());
229    }
230    let mut current = PathBuf::new();
231    for c in path.components() {
232        if matches!(c, Component::ParentDir) {
233            return Err("resource path traversal".into());
234        }
235        current.push(c);
236        // Prefix alone is not an addressable ancestor (notably `\\\\?\\C:`).
237        // Inspect the filesystem root once RootDir has made it absolute.
238        if matches!(c, Component::Prefix(_)) || !current.is_absolute() {
239            continue;
240        }
241        match fs::symlink_metadata(&current) {
242            Ok(m) if is_link(&m) => {
243                return Err(format!(
244                    "links/reparse points are not owned resource paths: {}",
245                    current.display()
246                ))
247            }
248            Ok(_) => {}
249            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
250            Err(e) => {
251                return Err(format!(
252                    "checking resource ancestor {}: {e}",
253                    current.display()
254                ))
255            }
256        }
257    }
258    Ok(())
259}
260fn read_bytes(path: &Path, limit: usize) -> Result<Option<Vec<u8>>> {
261    checked_path(path)?;
262    let mut file = match File::open(path) {
263        Ok(f) => f,
264        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
265        Err(e) => return Err(err(e)),
266    };
267    if !file.metadata().map_err(err)?.is_file() {
268        return Err("resource metadata is not a regular file".into());
269    }
270    let mut bytes = Vec::new();
271    Read::by_ref(&mut file)
272        .take(limit as u64 + 1)
273        .read_to_end(&mut bytes)
274        .map_err(err)?;
275    if bytes.len() > limit {
276        return Err(format!("resource metadata exceeds {limit} bytes"));
277    }
278    Ok(Some(bytes))
279}
280fn read_json<T: for<'a> Deserialize<'a> + Default>(path: &Path) -> Result<T> {
281    match read_bytes(path, MAX_META)? {
282        None => Ok(T::default()),
283        Some(b) => {
284            serde_json::from_slice(&b).map_err(|e| format!("invalid {}: {e}", path.display()))
285        }
286    }
287}
288fn json_bytes(value: &impl Serialize) -> Result<Vec<u8>> {
289    let b = serde_json::to_vec_pretty(value).map_err(err)?;
290    if b.len() > MAX_META {
291        Err("resource metadata/output exceeds 256 KiB".into())
292    } else {
293        Ok(b)
294    }
295}
296
297/// Stable lock inode: never removed, no PID heuristics, no blocking wait.
298#[derive(Debug)]
299pub struct Lease {
300    _file: File,
301}
302#[derive(Debug)]
303enum LeaseError {
304    Contended,
305    Other(String),
306}
307impl From<String> for LeaseError {
308    fn from(error: String) -> Self {
309        Self::Other(error)
310    }
311}
312impl From<LeaseError> for String {
313    fn from(error: LeaseError) -> Self {
314        match error {
315            LeaseError::Contended => {
316                "resource scope is in use (host or mutation lease); retry after owners exit".into()
317            }
318            LeaseError::Other(e) => format!("resource lease error: {e}"),
319        }
320    }
321}
322fn lock_error(error: std::io::Error) -> LeaseError {
323    let busy = fs2::lock_contended_error();
324    if error.raw_os_error().is_some() && error.raw_os_error() == busy.raw_os_error() {
325        LeaseError::Contended
326    } else {
327        LeaseError::Other(error.to_string())
328    }
329}
330impl Lease {
331    fn acquire(
332        root: &Path,
333        exclusive: bool,
334        create: bool,
335    ) -> std::result::Result<Option<Self>, LeaseError> {
336        checked_path(root)?;
337        if create {
338            fs::create_dir_all(root).map_err(err)?;
339        }
340        let path = root.join(LEASE);
341        checked_path(&path)?;
342        let file = match OpenOptions::new()
343            .read(true)
344            .write(true)
345            .create(create)
346            .open(path)
347        {
348            Ok(f) => f,
349            Err(e) if !create && e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
350            Err(e) => return Err(LeaseError::Other(err(e))),
351        };
352        let result = if exclusive {
353            fs2::FileExt::try_lock_exclusive(&file)
354        } else {
355            fs2::FileExt::try_lock_shared(&file)
356        };
357        result.map_err(lock_error)?;
358        Ok(Some(Self { _file: file }))
359    }
360}
361impl Drop for Lease {
362    fn drop(&mut self) {
363        let _ = fs2::FileExt::unlock(&self._file);
364    }
365}
366pub(crate) fn mutation_lease(root: &Path) -> Result<Lease> {
367    let lease = Lease::acquire(root, true, true)?.ok_or("missing resource lease")?;
368    ensure_complete(root)?;
369    Ok(lease)
370}
371
372/// Hold a shared resource lease while updating native package metadata. Native
373/// package installation is append/version based and therefore safe alongside
374/// live hosts, but it must still exclude resource mutations that could race
375/// with the registry/receipt ownership checks.
376pub(crate) fn shared_lease(root: &Path) -> Result<Lease> {
377    let lease = Lease::acquire(root, false, true)?.ok_or("missing resource lease")?;
378    ensure_complete(root)?;
379    Ok(lease)
380}
381
382fn ensure_complete(root: &Path) -> Result<()> {
383    if read_bytes(&root.join(JOURNAL), MAX_META)?.is_some() {
384        return Err(
385            "incomplete resource transaction; run rpi package recover with this scope".into(),
386        );
387    }
388    Ok(())
389}
390pub(crate) fn host_leases(cwd: &Path) -> Result<Arc<Vec<Lease>>> {
391    host_leases_for(&crate::config::AgentHome::process(), cwd)
392}
393
394pub(crate) fn host_leases_for(
395    home: &crate::config::AgentHome,
396    cwd: &Path,
397) -> Result<Arc<Vec<Lease>>> {
398    let mut roots = vec![
399        Scope::Project.root(home, cwd)?,
400        Scope::Global.root(home, cwd)?,
401    ];
402    roots.sort();
403    roots.dedup();
404    let mut leases = Vec::new();
405    for root in roots {
406        leases.push(shared_lease(&root)?);
407    }
408    Ok(Arc::new(leases))
409}
410fn observation_lease(root: &Path) -> Result<(Option<Lease>, bool)> {
411    // Retain the idle exclusive probe, or a shared lease alongside hosts.
412    // A mutator's exclusive lease refuses both; no unguarded half-state read.
413    match Lease::acquire(root, true, false) {
414        Ok(lease) => Ok((lease, false)),
415        Err(LeaseError::Contended) => Ok((Lease::acquire(root, false, false)?, true)),
416        Err(e) => Err(e.into()),
417    }
418}
419
420#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
421#[serde(deny_unknown_fields)]
422struct ResourceFile {
423    path: PathBuf,
424    bytes: u64,
425    sha256: String,
426}
427#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
428#[serde(deny_unknown_fields)]
429struct Inventory {
430    files: Vec<ResourceFile>,
431    directories: Vec<PathBuf>,
432    sha256: String,
433}
434#[derive(Default)]
435struct InventoryBudget {
436    entries: usize,
437    bytes: u64,
438}
439fn inventory(path: &Path) -> Result<Inventory> {
440    inventory_bounded(path, &mut InventoryBudget::default())
441}
442fn inventory_bounded(path: &Path, budget: &mut InventoryBudget) -> Result<Inventory> {
443    checked_path(path)?;
444    let mut files = Vec::new();
445    let mut directories = Vec::new();
446    fn walk(
447        root: &Path,
448        path: &Path,
449        files: &mut Vec<ResourceFile>,
450        dirs: &mut Vec<PathBuf>,
451        budget: &mut InventoryBudget,
452        depth: usize,
453    ) -> Result<()> {
454        if depth > 32 {
455            return Err("resource recursion depth exceeds 32".into());
456        }
457        if budget.entries >= MAX_FILES {
458            return Err("resource inventory exceeds 2048 entries".into());
459        }
460        budget.entries += 1;
461        let meta = fs::symlink_metadata(path).map_err(err)?;
462        if is_link(&meta) {
463            return Err(format!(
464                "resource link/reparse point rejected: {}",
465                path.display()
466            ));
467        }
468        let rel = path.strip_prefix(root).map_err(err)?;
469        if !rel.as_os_str().is_empty() {
470            relative(rel)?;
471        }
472        if meta.is_dir() {
473            if !rel.as_os_str().is_empty() {
474                dirs.push(rel.to_path_buf());
475            }
476            let remaining = MAX_FILES - budget.entries;
477            let mut entries = Vec::new();
478            for entry in fs::read_dir(path).map_err(err)?.take(remaining + 1) {
479                if entries.len() == remaining {
480                    return Err("resource directory exceeds remaining entry budget".into());
481                }
482                entries.push(entry.map_err(err)?);
483            }
484            entries.sort_by_key(|e| e.file_name());
485            for e in entries {
486                walk(root, &e.path(), files, dirs, budget, depth + 1)?;
487            }
488        } else if meta.is_file() {
489            if meta.len() > MAX_FILE || budget.bytes + meta.len() > MAX_BYTES {
490                return Err("resource files exceed byte limit (64 MiB/file, 256 MiB total)".into());
491            }
492            let mut input = File::open(path).map_err(err)?;
493            let mut hash = Sha256::new();
494            let mut size = 0;
495            let mut buf = [0; 16384];
496            loop {
497                let n = input.read(&mut buf).map_err(err)?;
498                if n == 0 {
499                    break;
500                }
501                size += n as u64;
502                budget.bytes += n as u64;
503                if size > MAX_FILE || budget.bytes > MAX_BYTES {
504                    return Err("resource changed/exceeded byte limit".into());
505                }
506                hash.update(&buf[..n]);
507            }
508            if size != meta.len() {
509                return Err("resource changed while reading".into());
510            }
511            files.push(ResourceFile {
512                path: if rel.as_os_str().is_empty() {
513                    PathBuf::from(".")
514                } else {
515                    rel.into()
516                },
517                bytes: size,
518                sha256: format!("{:x}", hash.finalize()),
519            });
520        } else {
521            return Err("special resource file rejected".into());
522        }
523        Ok(())
524    }
525    walk(path, path, &mut files, &mut directories, budget, 0)?;
526    let sha256 = format!(
527        "{:x}",
528        Sha256::digest(serde_json::to_vec(&(&files, &directories)).map_err(err)?)
529    );
530    Ok(Inventory {
531        files,
532        directories,
533        sha256,
534    })
535}
536#[derive(Debug, Clone, Serialize, Deserialize)]
537#[serde(deny_unknown_fields)]
538struct Receipt {
539    kind: Kind,
540    name: String,
541    source: PathBuf,
542    #[serde(default, skip_serializing_if = "Option::is_none")]
543    release: Option<String>,
544    version: Option<String>,
545    target: PathBuf,
546    inventory: Inventory,
547}
548#[derive(Default, Serialize, Deserialize)]
549#[serde(deny_unknown_fields)]
550struct Receipts {
551    #[serde(default)]
552    resources: Vec<Receipt>,
553}
554fn receipts(root: &Path) -> Result<Receipts> {
555    let r: Receipts = read_json(&root.join(RECEIPTS))?;
556    let mut keys = BTreeSet::new();
557    if r.resources.len() > 128 {
558        return Err("resource receipts exceed 128 resources per scope".into());
559    }
560    for item in &r.resources {
561        identifier(&item.name)?;
562        if item.version.as_ref().is_some_and(|v| {
563            v.trim().is_empty() || v.len() > 128 || v.chars().any(char::is_control)
564        }) {
565            return Err("invalid resource receipt version".into());
566        }
567        if item.target != item.kind.target(&item.name)
568            || !item.source.is_absolute()
569            || !keys.insert(item.target.to_string_lossy().to_ascii_lowercase())
570        {
571            return Err("unsafe/duplicate resource receipt".into());
572        }
573        checked_path(&root.join(&item.target))?;
574        if item.inventory.files.len() + item.inventory.directories.len() > MAX_FILES {
575            return Err("oversized receipt inventory".into());
576        }
577        for file in &item.inventory.files {
578            if file.path != Path::new(".") {
579                relative(&file.path)?;
580            }
581        }
582        for dir in &item.inventory.directories {
583            relative(dir)?;
584        }
585    }
586    Ok(r)
587}
588#[derive(Default, Serialize, Deserialize)]
589#[serde(deny_unknown_fields)]
590struct Packages {
591    #[serde(default)]
592    packages: Vec<crate::packages::ProjectPackage>,
593}
594fn packages(root: &Path) -> Result<Packages> {
595    let p: Packages = read_json(&root.join("packages.json"))?;
596    let mut names = BTreeSet::new();
597    for item in &p.packages {
598        legacy_package_identity(&item.name)?;
599        if !names.insert(item.name.to_ascii_lowercase()) {
600            return Err("duplicate native package identity".into());
601        }
602        let mut artifacts = BTreeSet::new();
603        for a in &item.artifacts {
604            relative(Path::new(a))?;
605            reserved_identity(a)?;
606            if Path::new(a).components().count() != 1 || !artifacts.insert(a.to_ascii_lowercase()) {
607                return Err("unsafe/duplicate native artifact".into());
608            }
609        }
610    }
611    Ok(p)
612}
613pub(crate) fn legacy_unowned(root: &Path, kind: &str, name: &str) -> Result<()> {
614    let kind = Kind::parse(kind)?;
615    if receipts(root)?
616        .resources
617        .iter()
618        .any(|r| r.kind == kind && r.name.eq_ignore_ascii_case(name))
619    {
620        return Err(format!(
621            "resource is a managed snapshot; use rpi {} update/remove with --scope",
622            kind.command()
623        ));
624    }
625    if kind == Kind::Package {
626        legacy_package_identity(name)?;
627        let package = root.join(kind.target(name));
628        legacy_unowned_targets(root, &[package.clone(), package.join("extensions")])?;
629    }
630    Ok(())
631}
632fn path_identity(path: &Path) -> Result<PathBuf> {
633    let path = if path.is_absolute() {
634        path.to_path_buf()
635    } else {
636        std::env::current_dir().map_err(err)?.join(path)
637    };
638    checked_path(&path)?;
639    // Existing components are canonicalized; absent leaves still compare by
640    // their absolute addressed path. Reparse paths are rejected, not followed.
641    let mut ancestor = path.as_path();
642    let mut tail = Vec::new();
643    while !ancestor.try_exists().map_err(err)? {
644        tail.push(
645            ancestor
646                .file_name()
647                .ok_or("no path ancestor")?
648                .to_os_string(),
649        );
650        ancestor = ancestor.parent().ok_or("no path ancestor")?;
651    }
652    let mut identity = fs::canonicalize(ancestor).map_err(err)?;
653    for component in tail.into_iter().rev() {
654        identity.push(component);
655    }
656    if cfg!(windows) {
657        Ok(PathBuf::from(identity.to_string_lossy().to_lowercase()))
658    } else {
659        Ok(identity)
660    }
661}
662pub(crate) fn resource_owned_names(root: &Path, kind: &str) -> Result<BTreeSet<String>> {
663    let kind = Kind::parse(kind)?;
664    Ok(receipts(root)?
665        .resources
666        .into_iter()
667        .filter(|r| r.kind == kind)
668        .map(|r| r.name)
669        .collect())
670}
671pub(crate) fn legacy_unowned_targets(root: &Path, targets: &[PathBuf]) -> Result<()> {
672    let targets = targets
673        .iter()
674        .map(|t| path_identity(t))
675        .collect::<Result<Vec<_>>>()?;
676    for r in receipts(root)?.resources {
677        let owned = path_identity(&root.join(&r.target))?;
678        if targets.iter().any(|t| t == &owned || t.starts_with(&owned)) {
679            return Err(
680                "target belongs to a managed snapshot; refusing legacy replacement/removal".into(),
681            );
682        }
683    }
684    Ok(())
685}
686
687#[derive(Serialize, Deserialize)]
688#[serde(deny_unknown_fields)]
689struct Change {
690    target: PathBuf,
691    old: Option<Inventory>,
692    new: Option<Inventory>,
693}
694#[derive(Serialize, Deserialize)]
695#[serde(deny_unknown_fields)]
696struct Journal {
697    directory: String,
698    changes: Vec<Change>,
699}
700fn transaction_target(p: &Path) -> Result<()> {
701    relative(p)?;
702    if p == Path::new(RECEIPTS) || p == Path::new("packages.json") {
703        return Ok(());
704    }
705    let parts = p
706        .iter()
707        .map(|p| p.to_str().ok_or("non-UTF8 target"))
708        .collect::<std::result::Result<Vec<_>, _>>()?;
709    if parts.len() != 2 || !matches!(parts[0], "packages" | "skills" | "extensions") {
710        return Err("unsafe transaction target".into());
711    }
712    identifier(parts[1])
713}
714fn remove_path(path: &Path) -> Result<()> {
715    checked_path(path)?;
716    let m = fs::symlink_metadata(path).map_err(err)?;
717    if m.is_dir() {
718        fs::remove_dir_all(path).map_err(err)
719    } else if m.is_file() {
720        fs::remove_file(path).map_err(err)
721    } else {
722        Err("unsafe removal".into())
723    }
724}
725fn rollback(root: &Path, j: &Journal) -> Result<()> {
726    let dir = root.join(&j.directory);
727    checked_path(&dir)?;
728    // Validate the complete recovery plan before changing any file.
729    for (i, c) in j.changes.iter().enumerate() {
730        transaction_target(&c.target)?;
731        let target = root.join(&c.target);
732        let backup = dir.join(format!("old-{i}"));
733        if backup.try_exists().map_err(err)? {
734            if Some(inventory(&backup)?) != c.old {
735                return Err("transaction backup changed; manual recovery required".into());
736            }
737            if target.try_exists().map_err(err)? && Some(inventory(&target)?) != c.new {
738                return Err("transaction target changed; refusing recovery deletion".into());
739            }
740        } else if target.try_exists().map_err(err)? {
741            let observed = inventory(&target)?;
742            if c.old.as_ref() != Some(&observed) && c.new.as_ref() != Some(&observed) {
743                return Err("transaction target differs from old/new inventory".into());
744            }
745            if c.old.is_some() && c.old.as_ref() != Some(&observed) {
746                return Err("missing rollback backup; manual recovery required".into());
747            }
748        } else if c.old.is_some() {
749            return Err("missing original/backup; manual recovery required".into());
750        }
751    }
752    for (i, c) in j.changes.iter().enumerate().rev() {
753        let target = root.join(&c.target);
754        let backup = dir.join(format!("old-{i}"));
755        if backup.try_exists().map_err(err)? {
756            if target.try_exists().map_err(err)? {
757                remove_path(&target)?;
758            }
759            fs::rename(&backup, &target).map_err(err)?;
760        } else if c.old.is_none() && target.try_exists().map_err(err)? {
761            remove_path(&target)?;
762        }
763    }
764    // Journal last: a failed rollback stays diagnosable and retryable.
765    fs::remove_file(root.join(JOURNAL)).map_err(err)?;
766    fs::remove_dir_all(dir).map_err(err)
767}
768fn recover(root: &Path) -> Result<bool> {
769    let Some(bytes) = read_bytes(&root.join(JOURNAL), MAX_META)? else {
770        return Ok(false);
771    };
772    let j: Journal = serde_json::from_slice(&bytes).map_err(err)?;
773    let suffix = j
774        .directory
775        .strip_prefix(".resource-txn-")
776        .ok_or("invalid transaction directory")?;
777    uuid::Uuid::parse_str(suffix).map_err(err)?;
778    if j.changes.len() > 3 {
779        return Err("oversized transaction plan".into());
780    }
781    let mut seen = BTreeSet::new();
782    for c in &j.changes {
783        transaction_target(&c.target)?;
784        if !seen.insert(&c.target) {
785            return Err("duplicate transaction target".into());
786        }
787    }
788    rollback(root, &j)?;
789    Ok(true)
790}
791fn write_new(path: &Path, bytes: &[u8]) -> Result<()> {
792    let mut f = OpenOptions::new()
793        .write(true)
794        .create_new(true)
795        .open(path)
796        .map_err(err)?;
797    f.write_all(bytes).and_then(|_| f.sync_all()).map_err(err)
798}
799/// Copy a resource snapshot into `target` and return the inventory of the copy.
800///
801/// The returned inventory can differ from `observed` on macOS: native artifacts
802/// are re-signed after copying (see `resign_snapshot_native`), which rewrites
803/// their bytes. Callers must record the **returned** inventory, not the source
804/// one, or every later ownership check fails.
805fn copy_snapshot(
806    kind: Kind,
807    source: &Path,
808    target: &Path,
809    observed: &Inventory,
810) -> Result<Inventory> {
811    fn copy_file(source: &Path, target: &Path, expected: u64) -> Result<()> {
812        checked_path(source)?;
813        let input = File::open(source).map_err(err)?;
814        #[cfg(unix)]
815        let mode = {
816            use std::os::unix::fs::PermissionsExt;
817            // Only ordinary rwx permissions; never copy setuid/setgid/sticky.
818            input.metadata().map_err(err)?.permissions().mode() & 0o777
819        };
820        let mut output = OpenOptions::new()
821            .write(true)
822            .create_new(true)
823            .open(target)
824            .map_err(err)?;
825        let copied = std::io::copy(&mut input.take(expected + 1), &mut output).map_err(err)?;
826        if copied != expected {
827            return Err("resource changed during bounded copy".into());
828        }
829        #[cfg(unix)]
830        {
831            use std::os::unix::fs::PermissionsExt;
832            output
833                .set_permissions(fs::Permissions::from_mode(mode))
834                .map_err(err)?;
835        }
836        output.sync_all().map_err(err)
837    }
838    if source.is_file() {
839        copy_file(
840            source,
841            target,
842            observed
843                .files
844                .first()
845                .ok_or("missing file inventory")?
846                .bytes,
847        )?;
848    } else {
849        fs::create_dir(target).map_err(err)?;
850        for d in &observed.directories {
851            fs::create_dir_all(target.join(d)).map_err(err)?;
852        }
853        for f in &observed.files {
854            let to = target.join(&f.path);
855            if let Some(p) = to.parent() {
856                fs::create_dir_all(p).map_err(err)?;
857            }
858            copy_file(&source.join(&f.path), &to, f.bytes)?;
859        }
860    }
861    if inventory(source)? != *observed {
862        return Err("resource source changed during snapshot copy".into());
863    }
864    // Which copied files are loadable native artifacts is decided by the resource
865    // KIND, because only the kind's validator reserves a place for one:
866    //   - Extension: the single-file source is the artifact, even though its
867    //     inventory path is `.` with no extension
868    //   - Package: only direct children of `extensions/` (see `validate_source`),
869    //     so a `.dylib` under `skills/`, `prompts/` or `themes/` is data
870    //   - Skill: nothing. A skill only has to contain SKILL.md, so a same-suffix
871    //     asset means nothing and must never be handed to `codesign`
872    let native: std::collections::BTreeSet<PathBuf> = match kind {
873        Kind::Extension => observed.files.iter().map(|f| f.path.clone()).collect(),
874        Kind::Package => observed
875            .files
876            .iter()
877            .map(|f| f.path.clone())
878            .filter(|p| is_package_artifact(p))
879            .collect(),
880        Kind::Skill => std::collections::BTreeSet::new(),
881    };
882    let artifacts: Vec<PathBuf> = native.iter().map(|p| target.join(p)).collect();
883    resign_snapshot_native(&artifacts)?;
884    let copied = inventory(target)?;
885    // Every byte outside the re-signed artifacts must still match the source.
886    let comparable = |inv: &Inventory| Inventory {
887        files: inv
888            .files
889            .iter()
890            .filter(|f| !native.contains(&f.path))
891            .cloned()
892            .collect(),
893        directories: inv.directories.clone(),
894        sha256: String::new(),
895    };
896    if comparable(&copied) != comparable(observed) {
897        return Err("resource snapshot copy does not match the source".into());
898    }
899    Ok(copied)
900}
901
902/// Whether a Package file is a native artifact: a direct child of `extensions/`
903/// with the platform library extension. This mirrors what `validate_source`
904/// accepts, so data files that merely use the same suffix elsewhere in the tree
905/// are never handed to `codesign`.
906fn is_package_artifact(path: &Path) -> bool {
907    is_native_artifact(path) && path.components().count() == 2 && path.starts_with("extensions")
908}
909
910/// Whether a path uses this platform's native library extension.
911fn is_native_artifact(path: &Path) -> bool {
912    path.extension().and_then(|s| s.to_str()) == Some(std::env::consts::DLL_EXTENSION)
913}
914/// macOS only: re-sign copied native artifacts so the kernel will map them.
915///
916/// A signed Mach-O carries a code directory whose hashes must match the bytes
917/// the kernel maps. Copying is byte-exact, so a well-formed copy stays valid —
918/// but a plain `io::copy` of a freshly linked cargo `cdylib` can also carry a
919/// linker signature the kernel refuses. When it refuses, it does not return an
920/// error: it kills the host that touched the page.
921///
922/// ```text
923/// CODE SIGNING: process 20087[rpi]: rejecting invalid page at address 0x…
924///   in file "~/.pidd/rpi-agent/extensions/librpi_superagent.dylib"
925///   (cs_mtime:1794052202.55 != mtime:1794056571.77)
926/// CODE SIGNING: cs_invalid_page(0x…): denying page sending SIGKILL
927/// ```
928///
929/// No stderr reaches the caller and the only exit status is 137, so the symptom
930/// reads as "rpi cannot start at all". `codesign -v` also reports these copies
931/// as valid, so verifying first is not a substitute for signing.
932///
933/// Only native artifacts are re-signed; text resources are left untouched.
934fn resign_snapshot_native(artifacts: &[PathBuf]) -> Result<()> {
935    if !cfg!(target_os = "macos") {
936        return Ok(());
937    }
938    for path in artifacts {
939        // Pin the ad-hoc identifier: `codesign --sign -` otherwise derives it from
940        // the file NAME, so the same bytes staged under two different names sign
941        // to different bytes. That would make an unchanged install look changed.
942        let output = std::process::Command::new("/usr/bin/codesign")
943            .args(["--force", "--sign", "-", "--identifier", "com.rpi.native"])
944            .arg(path)
945            .output()
946            .map_err(|e| format!("could not run codesign on {}: {e}", path.display()))?;
947        if !output.status.success() {
948            return Err(format!(
949                "could not re-sign {} (the kernel will refuse to load it): {}",
950                path.display(),
951                String::from_utf8_lossy(&output.stderr).trim()
952            ));
953        }
954    }
955    Ok(())
956}
957
958/// Small same-filesystem transaction; injection is unit-test-only, never an env backdoor.
959fn publish(
960    root: &Path,
961    changes: Vec<(PathBuf, Option<PathBuf>)>,
962    stage: tempfile::TempDir,
963    mut before: impl FnMut(usize) -> Result<()>,
964) -> Result<Vec<String>> {
965    let directory = stage
966        .path()
967        .file_name()
968        .and_then(|s| s.to_str())
969        .ok_or("invalid staging directory")?
970        .to_owned();
971    let mut j = Journal {
972        directory,
973        changes: Vec::new(),
974    };
975    for (target, new) in &changes {
976        transaction_target(target)?;
977        let path = root.join(target);
978        checked_path(&path)?;
979        j.changes.push(Change {
980            target: target.clone(),
981            old: if path.try_exists().map_err(err)? {
982                Some(inventory(&path)?)
983            } else {
984                None
985            },
986            new: new.as_ref().map(|p| inventory(p)).transpose()?,
987        });
988    }
989    let journal_stage = stage.path().join("journal");
990    write_new(&journal_stage, &json_bytes(&j)?)?;
991    fs::rename(&journal_stage, root.join(JOURNAL)).map_err(err)?;
992    // Do not auto-delete backup evidence if interrupted or rollback itself fails.
993    let _owned = stage.keep();
994    let result = (|| {
995        for (i, (target, new)) in changes.iter().enumerate() {
996            before(i * 2)?;
997            let path = root.join(target);
998            if j.changes[i].old.is_some() {
999                fs::rename(&path, root.join(&j.directory).join(format!("old-{i}"))).map_err(err)?;
1000            }
1001            before(i * 2 + 1)?;
1002            if let Some(new) = new {
1003                fs::rename(new, &path).map_err(err)?;
1004            }
1005        }
1006        before(changes.len() * 2)?;
1007        Ok(())
1008    })();
1009    if let Err(error) = result {
1010        return match rollback(root, &j) {
1011            Ok(()) => Err(error),
1012            Err(r) => Err(format!(
1013                "{error}; rollback incomplete: {r}; run rpi package recover with this scope"
1014            )),
1015        };
1016    }
1017    // Commit point: removing the journal makes installed bytes authoritative.
1018    // Orphan staging after this point contains only old bytes, never active data.
1019    if let Err(error) = fs::remove_file(root.join(JOURNAL)) {
1020        return match rollback(root,&j) {
1021            Ok(())=>Err(format!("commit marker removal failed: {error}; rolled back")),
1022            Err(rollback)=>Err(format!("commit marker removal failed: {error}; rollback incomplete: {rollback}; run rpi package recover with this scope")),
1023        };
1024    }
1025    if let Err(e) = fs::remove_dir_all(root.join(&j.directory)) {
1026        return Ok(vec![format!(
1027            "committed; backup cleanup pending (OS error {:?}, {:?})",
1028            e.raw_os_error(),
1029            e.kind()
1030        )]);
1031    }
1032    Ok(Vec::new())
1033}
1034fn stage_dir(root: &Path) -> Result<tempfile::TempDir> {
1035    tempfile::Builder::new()
1036        .prefix(&format!(".resource-txn-{}", uuid::Uuid::new_v4().simple()))
1037        .rand_bytes(0)
1038        .tempdir_in(root)
1039        .map_err(err)
1040}
1041
1042#[derive(Default)]
1043struct Options {
1044    op: String,
1045    kind: Option<Kind>,
1046    name: Option<String>,
1047    scope: Option<Scope>,
1048    source: Option<PathBuf>,
1049    version: Option<String>,
1050}
1051fn parse(kind: Option<Kind>, args: &[String]) -> Result<Options> {
1052    let op = args.first().ok_or("missing resource operation")?;
1053    let mut o = Options {
1054        op: match (kind, op.as_str()) {
1055            (Some(Kind::Package), "uninstall") => "remove".into(),
1056            _ => op.clone(),
1057        },
1058        kind,
1059        ..Default::default()
1060    };
1061    let mut pos = Vec::new();
1062    let mut i = 1;
1063    while i < args.len() {
1064        let a = &args[i];
1065        if matches!(a.as_str(), "--scope" | "--path" | "--version") {
1066            i += 1;
1067            let v = args.get(i).ok_or("missing option value")?;
1068            if v.starts_with('-') {
1069                return Err("missing option value".into());
1070            }
1071            match a.as_str() {
1072                "--scope" => {
1073                    if o.scope.is_some() {
1074                        return Err("duplicate scope".into());
1075                    }
1076                    o.scope = Some(match v.as_str() {
1077                        "project" => Scope::Project,
1078                        "global" => Scope::Global,
1079                        _ => return Err("scope must be project or global".into()),
1080                    });
1081                }
1082                "--path" => {
1083                    if o.source.replace(v.into()).is_some() {
1084                        return Err("duplicate path".into());
1085                    }
1086                }
1087                _ => {
1088                    if v.trim().is_empty()
1089                        || v.len() > 128
1090                        || v.chars().any(char::is_control)
1091                        || o.version.replace(v.clone()).is_some()
1092                    {
1093                        return Err("invalid/duplicate version".into());
1094                    }
1095                }
1096            }
1097        } else if a.starts_with('-') {
1098            return Err(format!("unknown snapshot option {a}"));
1099        } else {
1100            pos.push(a.clone());
1101        }
1102        i += 1;
1103    }
1104    if o.scope.is_none() {
1105        return Err("explicit --scope project|global is required".into());
1106    }
1107    if matches!(o.op.as_str(), "list" | "recover") {
1108        if !pos.is_empty() || o.source.is_some() || o.version.is_some() {
1109            return Err("unexpected list/recover arguments".into());
1110        }
1111        if o.op == "recover" {
1112            if kind.is_some_and(|kind| kind != Kind::Package) {
1113                return Err("use rpi package recover with this scope".into());
1114            }
1115            o.kind = None;
1116        }
1117    } else if matches!(
1118        o.op.as_str(),
1119        "inspect" | "install" | "update" | "reinstall" | "remove"
1120    ) {
1121        let (kind, name) = match (kind, pos.as_slice()) {
1122            (Some(kind), [name]) => (kind, name),
1123            (None, [kind, name]) => (Kind::parse(kind)?, name),
1124            (Some(_), _) => return Err("expected NAME".into()),
1125            (None, _) => return Err("expected KIND NAME".into()),
1126        };
1127        if o.op == "inspect" && kind == Kind::Package {
1128            legacy_package_identity(name)?;
1129        } else {
1130            identifier(name)?;
1131        }
1132        o.kind = Some(kind);
1133        o.name = pos.pop();
1134        let mutation = matches!(o.op.as_str(), "install" | "update" | "reinstall");
1135        if mutation != o.source.is_some() || (!mutation && o.version.is_some()) {
1136            return Err("install/update/reinstall require --path; inspect/remove reject it".into());
1137        }
1138    } else {
1139        return Err("unknown resource operation".into());
1140    }
1141    Ok(o)
1142}
1143fn validate_source(kind: Kind, source: &Path, inv: &Inventory) -> Result<()> {
1144    match kind {
1145        Kind::Skill => {
1146            if !source.is_dir() || !source.join("SKILL.md").is_file() {
1147                return Err("standalone Skill requires a directory containing SKILL.md".into());
1148            }
1149            let text =
1150                read_bytes(&source.join("SKILL.md"), 64 * 1024)?.ok_or("missing SKILL.md")?;
1151            std::str::from_utf8(&text).map_err(err)?;
1152        }
1153        Kind::Extension => {
1154            if !source.is_file()
1155                || source.extension().and_then(|s| s.to_str())
1156                    != Some(std::env::consts::DLL_EXTENSION)
1157            {
1158                return Err("extension source must be a platform native library file".into());
1159            }
1160        }
1161        Kind::Package => {
1162            if !source.is_dir() {
1163                return Err("package source must be a directory".into());
1164            }
1165            if !["extensions", "skills", "prompts", "themes"]
1166                .iter()
1167                .any(|s| source.join(s).is_dir())
1168                && inv.files.is_empty()
1169            {
1170                return Err("empty package".into());
1171            }
1172            for f in &inv.files {
1173                if f.path.starts_with("extensions")
1174                    && (f.path.components().count() != 2
1175                        || f.path.extension().and_then(|s| s.to_str())
1176                            != Some(std::env::consts::DLL_EXTENSION))
1177                {
1178                    return Err(
1179                        "Package extensions must be direct platform native artifacts".into(),
1180                    );
1181                }
1182            }
1183        }
1184    }
1185    Ok(())
1186}
1187fn explicit_source(path: &Path) -> Result<PathBuf> {
1188    let addressed = std::env::current_dir().map_err(err)?.join(path);
1189    let mut normalized = PathBuf::new();
1190    for component in addressed.components() {
1191        match component {
1192            Component::CurDir => {}
1193            Component::ParentDir => {
1194                checked_path(&normalized)?;
1195                if !normalized.pop() {
1196                    return Err("source escapes filesystem root".into());
1197                }
1198            }
1199            other => {
1200                normalized.push(other);
1201                // A Windows drive prefix (`C:` / `\\\\?\\C:`) becomes
1202                // absolute only after its RootDir component is appended.
1203                if !matches!(other, Component::Prefix(_)) && normalized.is_absolute() {
1204                    checked_path(&normalized)?;
1205                }
1206            }
1207        }
1208    }
1209    fs::canonicalize(normalized).map_err(err)
1210}
1211pub(crate) fn preflight_published_update(name: &str) -> Result<()> {
1212    let cwd = std::env::current_dir().map_err(err)?;
1213    let root = Scope::Global.root(&crate::config::AgentHome::process(), &cwd)?;
1214    let (_lease, _) = observation_lease(&root)?;
1215    ensure_complete(&root)?;
1216    let inventory = receipts(&root)?;
1217    let previous = inventory
1218        .resources
1219        .iter()
1220        .find(|receipt| receipt.kind == Kind::Package && receipt.name.eq_ignore_ascii_case(name));
1221    require_published_release(previous, name)?;
1222    Ok(())
1223}
1224
1225fn require_published_release<'a>(previous: Option<&'a Receipt>, name: &str) -> Result<&'a Receipt> {
1226    let receipt = previous.ok_or("resource is not owned/installed; use install")?;
1227    if receipt.name != name {
1228        return Err("identity case collision".into());
1229    }
1230    if receipt.release.is_none() {
1231        return Err("package was installed from a local path; use rpi package update NAME --scope global --path PATH".into());
1232    }
1233    Ok(receipt)
1234}
1235
1236fn mutate(root: &Path, o: &Options, release: Option<&str>) -> Result<Value> {
1237    let _lease = mutation_lease(root)?;
1238    let mut r = receipts(root)?;
1239    let mut p = packages(root)?;
1240    let native: Vec<crate::install::InstalledNativePackage> =
1241        read_json(&root.join("native-packages.json"))?;
1242    let kind = o.kind.ok_or("missing kind")?;
1243    let name = o.name.as_deref().ok_or("missing name")?;
1244    let target = kind.target(name);
1245    let path = root.join(&target);
1246    checked_path(&path)?;
1247    let previous = r
1248        .resources
1249        .iter()
1250        .find(|r| r.kind == kind && r.name.eq_ignore_ascii_case(name))
1251        .cloned();
1252    for owned in r.resources.iter().filter(|r| r.kind == Kind::Package) {
1253        if p.packages.iter().find(|p| p.name == owned.name) != Some(&package_record(owned)) {
1254            return Err(
1255                "owned package receipt disagrees with native packages.json; refusing mutation"
1256                    .into(),
1257            );
1258        }
1259    }
1260    if kind == Kind::Extension
1261        && native.iter().any(|p| {
1262            p.name.eq_ignore_ascii_case(name)
1263                || p.artifacts.iter().any(|a| {
1264                    target
1265                        .file_name()
1266                        .is_some_and(|f| f.to_string_lossy().eq_ignore_ascii_case(a))
1267                })
1268        })
1269    {
1270        return Err(
1271            "extension identity/artifact owned by legacy native registry (even if missing)".into(),
1272        );
1273    }
1274    if let Some(old) = &previous {
1275        if old.name != name {
1276            return Err("identity case collision".into());
1277        }
1278        if inventory(&path)? != old.inventory {
1279            return Err("owned resource content changed; refusing overwrite/removal".into());
1280        }
1281    }
1282    if o.op == "remove" && previous.is_none() {
1283        if path.try_exists().map_err(err)? {
1284            return Err("unmanaged destination: refusing removal".into());
1285        }
1286        return Ok(json!({"outcome":"absent","kind":kind,"name":name}));
1287    }
1288    if previous.is_none() && path.try_exists().map_err(err)? {
1289        return Err("unmanaged destination conflict".into());
1290    }
1291    if kind == Kind::Package
1292        && previous.is_none()
1293        && p.packages.iter().any(|p| p.name.eq_ignore_ascii_case(name))
1294    {
1295        return Err("package identity owned by native package link".into());
1296    }
1297    if matches!(o.op.as_str(), "update" | "reinstall") && previous.is_none() {
1298        return Err("resource is not owned/installed; use install".into());
1299    }
1300    let same_release_version = if kind == Kind::Package && o.op == "update" && release.is_some() {
1301        // The preflight releases its observation lease before network I/O.
1302        // Revalidate against the current receipt under the mutation lease.
1303        let old = require_published_release(previous.as_ref(), name)?;
1304        let installed = old
1305            .version
1306            .as_deref()
1307            .and_then(|version| semver::Version::parse(version).ok())
1308            .ok_or("invalid installed package version")?;
1309        let requested = o
1310            .version
1311            .as_deref()
1312            .and_then(|version| semver::Version::parse(version).ok())
1313            .ok_or("invalid requested package version")?;
1314        match requested.cmp_precedence(&installed) {
1315            std::cmp::Ordering::Less => {
1316                return Err(format!(
1317                    "cannot downgrade package from {installed} to {requested}"
1318                ));
1319            }
1320            std::cmp::Ordering::Equal => true,
1321            std::cmp::Ordering::Greater => false,
1322        }
1323    } else {
1324        false
1325    };
1326    let source = o
1327        .source
1328        .as_ref()
1329        .map(|path| explicit_source(path))
1330        .transpose()?;
1331    if let Some(source) = &source {
1332        let source_identity = path_identity(source)?;
1333        let root_identity = path_identity(root)?;
1334        if source_identity.starts_with(&root_identity)
1335            || root_identity.starts_with(&source_identity)
1336        {
1337            return Err("source/destination resource trees overlap".into());
1338        }
1339    }
1340    let stage = stage_dir(root)?;
1341    let mut next = None;
1342    if let Some(source) = source {
1343        // No Cargo metadata/build or native loader is called here.
1344        let inv = inventory(&source)?;
1345        validate_source(kind, &source, &inv)?;
1346        let version = o
1347            .version
1348            .clone()
1349            .or_else(|| previous.as_ref().and_then(|r| r.version.clone()));
1350        // Copy before building the receipt: on macOS the staged native artifacts
1351        // are re-signed, so the copy's inventory (which is what gets installed and
1352        // later re-verified against) differs from the source's.
1353        let staged = stage.path().join("snapshot");
1354        let copied = copy_snapshot(kind, &source, &staged, &inv)?;
1355        let receipt = Receipt {
1356            kind,
1357            name: name.into(),
1358            source,
1359            release: release.map(str::to_owned),
1360            version,
1361            target: target.clone(),
1362            inventory: copied,
1363        };
1364        if o.op == "install" || same_release_version {
1365            if let Some(old) = &previous {
1366                let same_source = match (&old.release, &receipt.release) {
1367                    (None, None) => old.source == receipt.source,
1368                    (old, received) => old == received,
1369                };
1370                if same_source
1371                    && old.version == receipt.version
1372                    && old.inventory == receipt.inventory
1373                {
1374                    return Ok(
1375                        json!({"outcome":"unchanged","resource":observe(root,o.scope.unwrap(),old,false)?}),
1376                    );
1377                }
1378                let error = if same_release_version {
1379                    "package version is already installed with different release provenance or content"
1380                } else if release.is_some() {
1381                    "already installed; use rpi package update NAME --scope global"
1382                } else {
1383                    "already installed; use update or reinstall with --path"
1384                };
1385                return Err(error.into());
1386            }
1387        }
1388        next = Some((receipt, staged));
1389    }
1390    r.resources.retain(|r| !(r.kind == kind && r.name == name));
1391    if kind == Kind::Package {
1392        p.packages.retain(|p| p.name != name);
1393        if let Some((new, _)) = &next {
1394            p.packages.push(package_record(new));
1395        }
1396    }
1397    if let Some((receipt, _)) = &next {
1398        r.resources.push(receipt.clone());
1399    }
1400    if r.resources.len() > 128 {
1401        return Err("resource receipts exceed 128 resources per scope".into());
1402    }
1403    r.resources.sort_by_key(|r| r.target.clone());
1404    p.packages.sort_by(|a, b| a.name.cmp(&b.name));
1405    let receipt_stage = stage.path().join("receipts");
1406    write_new(&receipt_stage, &json_bytes(&r)?)?;
1407    let mut changes = vec![
1408        (target, next.as_ref().map(|(_, p)| p.clone())),
1409        (PathBuf::from(RECEIPTS), Some(receipt_stage)),
1410    ];
1411    if kind == Kind::Package {
1412        let staged = stage.path().join("packages");
1413        write_new(&staged, &json_bytes(&p)?)?;
1414        changes.push((PathBuf::from("packages.json"), Some(staged)));
1415    }
1416    let mut data = json!({"outcome":if o.op=="remove"{"removed"}else if previous.is_some(){"replaced"}else{"installed"},"kind":kind,"name":name,"diagnostics":[],"resource":next.as_ref().map(|(r,_)|observe_inventory(root,o.scope.unwrap(),r,false,Ok(r.inventory.clone()))).transpose()?});
1417    // Bound the exact public envelope before publication. Reserve space for a
1418    // bounded post-commit backup-cleanup diagnostic (not a false operation error).
1419    if json_bytes(&success(o, data.clone()))
1420        .map_err(|error| format!("resource success result rejected before publication: {error}"))?
1421        .len()
1422        > MAX_META - 4096
1423    {
1424        return Err("resource success result exceeds bounded publication budget".into());
1425    }
1426    let parent = path.parent().ok_or("no resource parent")?;
1427    checked_path(parent)?;
1428    fs::create_dir_all(parent).map_err(err)?;
1429    let diagnostics = publish(root, changes, stage, |_| Ok(()))?;
1430    data["diagnostics"] = json!(diagnostics);
1431    Ok(data)
1432}
1433fn receipt_source(r: &Receipt) -> String {
1434    r.release
1435        .clone()
1436        .unwrap_or_else(|| r.source.to_string_lossy().into_owned())
1437}
1438fn package_record(r: &Receipt) -> crate::packages::ProjectPackage {
1439    crate::packages::ProjectPackage {
1440        name: r.name.clone(),
1441        version: r.version.clone().unwrap_or_default(),
1442        source: receipt_source(r),
1443        cargo_package: String::new(),
1444        artifacts: r
1445            .inventory
1446            .files
1447            .iter()
1448            .filter(|f| f.path.starts_with("extensions"))
1449            .filter_map(|f| {
1450                f.path
1451                    .file_name()
1452                    .and_then(|s| s.to_str())
1453                    .map(str::to_owned)
1454            })
1455            .collect(),
1456    }
1457}
1458fn observe(root: &Path, scope: Scope, r: &Receipt, busy: bool) -> Result<Value> {
1459    observe_bounded(root, scope, r, busy, &mut InventoryBudget::default())
1460}
1461fn observe_bounded(
1462    root: &Path,
1463    scope: Scope,
1464    r: &Receipt,
1465    busy: bool,
1466    budget: &mut InventoryBudget,
1467) -> Result<Value> {
1468    let observed = inventory_bounded(&root.join(&r.target), budget);
1469    observe_inventory(root, scope, r, busy, observed)
1470}
1471fn observe_inventory(
1472    root: &Path,
1473    scope: Scope,
1474    r: &Receipt,
1475    busy: bool,
1476    observed: Result<Inventory>,
1477) -> Result<Value> {
1478    let mut diagnostics =
1479        vec!["native ABI compatibility is unverified; inspection never loads code".to_string()];
1480    if observed.as_ref().ok() != Some(&r.inventory) {
1481        diagnostics.push("installed content is missing or differs from ownership receipt".into());
1482    }
1483    if let Err(e) = &observed {
1484        diagnostics.push(e.clone());
1485    }
1486    Ok(
1487        json!({"kind":r.kind,"scope":scope,"identity":format!("{}:{}:{}",if scope==Scope::Project{"project"}else{"global"},r.kind.dir(),r.name),"name":r.name,"source":receipt_source(r),"version":r.version,"ownership":"resource","installed":true,"inUse":busy,"loaded":null,"applied":null,"path":root.join(&r.target),"selectable":selectable(root,scope,r),"recordedDigest":r.inventory.sha256,"observed":observed.ok(),"diagnostics":diagnostics}),
1488    )
1489}
1490fn selectable(root: &Path, scope: Scope, r: &Receipt) -> Value {
1491    match r.kind {
1492        Kind::Package => json!({"main_package":{"name":r.name,"scope":scope,"instructions":[]}}),
1493        Kind::Skill => json!({"skills":[root.join(&r.target)]}),
1494        Kind::Extension => json!({"extensions":[root.join(&r.target)]}),
1495    }
1496}
1497fn catalog(root: &Path, o: &Options) -> Result<Value> {
1498    checked_path(root)?;
1499    let (_observation_lease, busy) = observation_lease(root)?;
1500    let r = receipts(root)?;
1501    let p = if o.kind.is_none_or(|kind| kind == Kind::Package) {
1502        packages(root)?
1503    } else {
1504        Packages::default()
1505    };
1506    let native: Vec<crate::install::InstalledNativePackage> =
1507        if o.kind.is_none_or(|kind| kind == Kind::Extension) {
1508            read_json(&root.join("native-packages.json"))?
1509        } else {
1510            Vec::new()
1511        };
1512    let scope = o.scope.unwrap();
1513    let requested_name = (o.op == "inspect").then_some(o.name.as_deref()).flatten();
1514    let mut items = Vec::new();
1515    let mut owned = BTreeSet::new();
1516    let mut budget = InventoryBudget::default();
1517    for receipt in r
1518        .resources
1519        .iter()
1520        .filter(|r| o.kind.is_none_or(|kind| r.kind == kind))
1521    {
1522        owned.insert(receipt.target.clone());
1523        if requested_name.is_some_and(|name| receipt.name != name) {
1524            continue;
1525        }
1526        items.push(observe_bounded(root, scope, receipt, busy, &mut budget)?);
1527    }
1528    for kind in [Kind::Package, Kind::Skill, Kind::Extension]
1529        .into_iter()
1530        .filter(|&kind| o.kind.is_none_or(|selected| kind == selected))
1531    {
1532        let directory = root.join(kind.dir());
1533        checked_path(&directory)?;
1534        let entries = match fs::read_dir(directory) {
1535            Ok(e) => e,
1536            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
1537            Err(e) => return Err(err(e)),
1538        };
1539        for entry in entries {
1540            let entry = entry.map_err(err)?;
1541            let file_name = entry.file_name();
1542            let target = Path::new(kind.dir()).join(&file_name);
1543            if owned.contains(&target) {
1544                continue;
1545            }
1546            let name = if kind == Kind::Extension {
1547                target.file_stem().unwrap_or_default()
1548            } else {
1549                &file_name
1550            };
1551            if requested_name.is_some_and(|requested| name != std::ffi::OsStr::new(requested)) {
1552                continue;
1553            }
1554            if items.len() >= MAX_FILES {
1555                return Err("catalog exceeds entry limit".into());
1556            }
1557            let name = if kind == Kind::Extension {
1558                name.to_str().unwrap_or("")
1559            } else {
1560                name.to_str().ok_or("non UTF8 candidate")?
1561            };
1562            let pkg = p
1563                .packages
1564                .iter()
1565                .find(|p| kind == Kind::Package && p.name == name);
1566            let ext = native.iter().find(|p| {
1567                kind == Kind::Extension
1568                    && p.artifacts
1569                        .iter()
1570                        .any(|a| file_name == std::ffi::OsStr::new(a))
1571            });
1572            let inv = inventory_bounded(&entry.path(), &mut budget);
1573            let diagnostics = match &inv {
1574                Ok(_) => vec!["unverified candidate; no code executed".to_string()],
1575                Err(e) => vec![e.clone()],
1576            };
1577            items.push(json!({"kind":kind,"scope":scope,"identity":format!("{}:{}:{}",if scope==Scope::Project{"project"}else{"global"},kind.dir(),name),"name":name,"source":pkg.map(|p|p.source.clone()).or_else(||ext.and_then(|p|p.source.clone())),"version":pkg.and_then(|p|if p.version.is_empty(){None}else{Some(&p.version)}).or_else(||ext.filter(|p|!p.version.trim().is_empty()).map(|p|&p.version)),"ownership":if pkg.is_some()||ext.is_some(){"legacy-native"}else{"unmanaged"},"installed":pkg.is_some()||ext.is_some(),"inUse":busy,"loaded":null,"applied":null,"path":entry.path(),"observed":inv.ok(),"diagnostics":diagnostics}));
1578        }
1579    }
1580    if o.op == "inspect" && items.is_empty() {
1581        return Err("resource not found".into());
1582    }
1583    items.sort_by_key(|i| i["identity"].as_str().unwrap_or("").to_string());
1584    // When no persistent lock existed initially, first publication could have
1585    // started during traversal. Its lock inode is never unlinked: reject and
1586    // retry rather than returning any potentially mixed observation.
1587    if _observation_lease.is_none() && root.join(LEASE).try_exists().map_err(err)? {
1588        return Err("resource ownership initialized during observation; retry catalog".into());
1589    }
1590    Ok(
1591        json!({"outcome":"observed","resources":items,"diagnostics":if root.join(JOURNAL).try_exists().map_err(err)?{vec!["incomplete transaction; run rpi package recover with this scope"]}else{vec![]}}),
1592    )
1593}
1594fn success(o: &Options, data: Value) -> Value {
1595    json!({"version":1,"success":true,"operation":o.op,"scope":o.scope,"kind":o.kind,"name":o.name,"data":data})
1596}
1597pub(crate) fn print_snapshot_help(kind: Kind) {
1598    println!(
1599        "Local {} snapshots (JSON v1):\n  list --scope project|global\n  inspect|remove NAME --scope project|global\n  install|update|reinstall NAME --path PATH --scope project|global [--version TEXT]",
1600        kind.command()
1601    );
1602    if kind == Kind::Package {
1603        println!("  uninstall NAME --scope project|global  Alias for remove");
1604    }
1605}
1606
1607pub(crate) fn run(kind: Kind, args: &[String]) -> i32 {
1608    if args.is_empty() || args.iter().any(|a| matches!(a.as_str(), "--help" | "-h")) {
1609        println!("Usage: rpi {} <command>\n", kind.command());
1610        print_snapshot_help(kind);
1611        return 0;
1612    }
1613    run_with_release(Some(kind), args, None)
1614}
1615
1616pub(crate) fn run_legacy(args: &[String]) -> i32 {
1617    if args.is_empty() || args.iter().any(|a| matches!(a.as_str(), "--help" | "-h")) {
1618        println!("rpi resource list|inspect|install|update|reinstall|remove|recover --scope project|global\nMutations: KIND NAME --path PATH [--version TEXT]; remove/inspect: KIND NAME.\nLocal snapshots only; no builds or native registration. JSON v1, 256 KiB bound.");
1619        return 0;
1620    }
1621    run_with_release(None, args, None)
1622}
1623
1624pub(crate) fn publish_release(args: &[String], url: &str) -> i32 {
1625    run_with_release(Some(Kind::Package), args, Some(url))
1626}
1627
1628fn run_with_release(kind: Option<Kind>, args: &[String], release: Option<&str>) -> i32 {
1629    let result: Result<Value> = (|| {
1630        let o = parse(kind, args)?;
1631        let cwd = std::env::current_dir().map_err(err)?;
1632        let root = o
1633            .scope
1634            .unwrap()
1635            .root(&crate::config::AgentHome::process(), &cwd)?;
1636        let data = if matches!(o.op.as_str(), "list" | "inspect") {
1637            catalog(&root, &o)?
1638        } else if o.op == "recover" {
1639            let _lease = Lease::acquire(&root, true, true)?;
1640            json!({"outcome":if recover(&root)?{"recovered"}else{"unchanged"}})
1641        } else {
1642            mutate(&root, &o, release)?
1643        };
1644        Ok(success(&o, data))
1645    })();
1646    match result.and_then(|v| json_bytes(&v)) {
1647        Ok(bytes) => {
1648            println!("{}", String::from_utf8_lossy(&bytes));
1649            0
1650        }
1651        Err(error) => report_failure(parse(kind, args).ok().as_ref(), &error),
1652    }
1653}
1654
1655pub(crate) fn report_published_update_error(name: &str, error: &str) -> i32 {
1656    let context = Options {
1657        op: "update".into(),
1658        kind: Some(Kind::Package),
1659        scope: Some(Scope::Global),
1660        name: Some(name.into()),
1661        ..Default::default()
1662    };
1663    report_failure(Some(&context), error)
1664}
1665
1666fn report_failure(context: Option<&Options>, error: &str) -> i32 {
1667    let bounded = error.chars().take(2048).collect::<String>();
1668    println!(
1669        "{}",
1670        json!({"version":1,"success":false,"operation":context.map(|o|&o.op),"scope":context.and_then(|o|o.scope),"kind":context.and_then(|o|o.kind),"name":context.and_then(|o|o.name.as_ref()),"error":bounded})
1671    );
1672    1
1673}
1674
1675#[cfg(test)]
1676mod regressions;
1677#[cfg(test)]
1678mod tests;