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