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    version: Option<String>,
535    target: PathBuf,
536    inventory: Inventory,
537}
538#[derive(Default, Serialize, Deserialize)]
539#[serde(deny_unknown_fields)]
540struct Receipts {
541    #[serde(default)]
542    resources: Vec<Receipt>,
543}
544fn receipts(root: &Path) -> Result<Receipts> {
545    let r: Receipts = read_json(&root.join(RECEIPTS))?;
546    let mut keys = BTreeSet::new();
547    if r.resources.len() > 128 {
548        return Err("resource receipts exceed 128 resources per scope".into());
549    }
550    for item in &r.resources {
551        identifier(&item.name)?;
552        if item.version.as_ref().is_some_and(|v| {
553            v.trim().is_empty() || v.len() > 128 || v.chars().any(char::is_control)
554        }) {
555            return Err("invalid resource receipt version".into());
556        }
557        if item.target != item.kind.target(&item.name)
558            || !item.source.is_absolute()
559            || !keys.insert(item.target.to_string_lossy().to_ascii_lowercase())
560        {
561            return Err("unsafe/duplicate resource receipt".into());
562        }
563        checked_path(&root.join(&item.target))?;
564        if item.inventory.files.len() + item.inventory.directories.len() > MAX_FILES {
565            return Err("oversized receipt inventory".into());
566        }
567        for file in &item.inventory.files {
568            if file.path != Path::new(".") {
569                relative(&file.path)?;
570            }
571        }
572        for dir in &item.inventory.directories {
573            relative(dir)?;
574        }
575    }
576    Ok(r)
577}
578#[derive(Default, Serialize, Deserialize)]
579#[serde(deny_unknown_fields)]
580struct Packages {
581    #[serde(default)]
582    packages: Vec<crate::packages::ProjectPackage>,
583}
584fn packages(root: &Path) -> Result<Packages> {
585    let p: Packages = read_json(&root.join("packages.json"))?;
586    let mut names = BTreeSet::new();
587    for item in &p.packages {
588        legacy_package_identity(&item.name)?;
589        if !names.insert(item.name.to_ascii_lowercase()) {
590            return Err("duplicate native package identity".into());
591        }
592        let mut artifacts = BTreeSet::new();
593        for a in &item.artifacts {
594            relative(Path::new(a))?;
595            reserved_identity(a)?;
596            if Path::new(a).components().count() != 1 || !artifacts.insert(a.to_ascii_lowercase()) {
597                return Err("unsafe/duplicate native artifact".into());
598            }
599        }
600    }
601    Ok(p)
602}
603pub(crate) fn legacy_unowned(root: &Path, kind: &str, name: &str) -> Result<()> {
604    let kind = Kind::parse(kind)?;
605    if receipts(root)?
606        .resources
607        .iter()
608        .any(|r| r.kind == kind && r.name.eq_ignore_ascii_case(name))
609    {
610        return Err("resource is managed by rpi resource; use its update/remove commands".into());
611    }
612    if kind == Kind::Package {
613        legacy_package_identity(name)?;
614        let package = root.join(kind.target(name));
615        legacy_unowned_targets(root, &[package.clone(), package.join("extensions")])?;
616    }
617    Ok(())
618}
619fn path_identity(path: &Path) -> Result<PathBuf> {
620    let path = if path.is_absolute() {
621        path.to_path_buf()
622    } else {
623        std::env::current_dir().map_err(err)?.join(path)
624    };
625    checked_path(&path)?;
626    // Existing components are canonicalized; absent leaves still compare by
627    // their absolute addressed path. Reparse paths are rejected, not followed.
628    let mut ancestor = path.as_path();
629    let mut tail = Vec::new();
630    while !ancestor.try_exists().map_err(err)? {
631        tail.push(
632            ancestor
633                .file_name()
634                .ok_or("no path ancestor")?
635                .to_os_string(),
636        );
637        ancestor = ancestor.parent().ok_or("no path ancestor")?;
638    }
639    let mut identity = fs::canonicalize(ancestor).map_err(err)?;
640    for component in tail.into_iter().rev() {
641        identity.push(component);
642    }
643    if cfg!(windows) {
644        Ok(PathBuf::from(identity.to_string_lossy().to_lowercase()))
645    } else {
646        Ok(identity)
647    }
648}
649pub(crate) fn resource_owned_names(root: &Path, kind: &str) -> Result<BTreeSet<String>> {
650    let kind = Kind::parse(kind)?;
651    Ok(receipts(root)?
652        .resources
653        .into_iter()
654        .filter(|r| r.kind == kind)
655        .map(|r| r.name)
656        .collect())
657}
658pub(crate) fn legacy_unowned_targets(root: &Path, targets: &[PathBuf]) -> Result<()> {
659    let targets = targets
660        .iter()
661        .map(|t| path_identity(t))
662        .collect::<Result<Vec<_>>>()?;
663    for r in receipts(root)?.resources {
664        let owned = path_identity(&root.join(&r.target))?;
665        if targets.iter().any(|t| t == &owned || t.starts_with(&owned)) {
666            return Err("target owned by rpi resource; refusing legacy replacement/removal".into());
667        }
668    }
669    Ok(())
670}
671
672#[derive(Serialize, Deserialize)]
673#[serde(deny_unknown_fields)]
674struct Change {
675    target: PathBuf,
676    old: Option<Inventory>,
677    new: Option<Inventory>,
678}
679#[derive(Serialize, Deserialize)]
680#[serde(deny_unknown_fields)]
681struct Journal {
682    directory: String,
683    changes: Vec<Change>,
684}
685fn transaction_target(p: &Path) -> Result<()> {
686    relative(p)?;
687    if p == Path::new(RECEIPTS) || p == Path::new("packages.json") {
688        return Ok(());
689    }
690    let parts = p
691        .iter()
692        .map(|p| p.to_str().ok_or("non-UTF8 target"))
693        .collect::<std::result::Result<Vec<_>, _>>()?;
694    if parts.len() != 2 || !matches!(parts[0], "packages" | "skills" | "extensions") {
695        return Err("unsafe transaction target".into());
696    }
697    identifier(parts[1])
698}
699fn remove_path(path: &Path) -> Result<()> {
700    checked_path(path)?;
701    let m = fs::symlink_metadata(path).map_err(err)?;
702    if m.is_dir() {
703        fs::remove_dir_all(path).map_err(err)
704    } else if m.is_file() {
705        fs::remove_file(path).map_err(err)
706    } else {
707        Err("unsafe removal".into())
708    }
709}
710fn rollback(root: &Path, j: &Journal) -> Result<()> {
711    let dir = root.join(&j.directory);
712    checked_path(&dir)?;
713    // Validate the complete recovery plan before changing any file.
714    for (i, c) in j.changes.iter().enumerate() {
715        transaction_target(&c.target)?;
716        let target = root.join(&c.target);
717        let backup = dir.join(format!("old-{i}"));
718        if backup.try_exists().map_err(err)? {
719            if Some(inventory(&backup)?) != c.old {
720                return Err("transaction backup changed; manual recovery required".into());
721            }
722            if target.try_exists().map_err(err)? && Some(inventory(&target)?) != c.new {
723                return Err("transaction target changed; refusing recovery deletion".into());
724            }
725        } else if target.try_exists().map_err(err)? {
726            let observed = inventory(&target)?;
727            if c.old.as_ref() != Some(&observed) && c.new.as_ref() != Some(&observed) {
728                return Err("transaction target differs from old/new inventory".into());
729            }
730            if c.old.is_some() && c.old.as_ref() != Some(&observed) {
731                return Err("missing rollback backup; manual recovery required".into());
732            }
733        } else if c.old.is_some() {
734            return Err("missing original/backup; manual recovery required".into());
735        }
736    }
737    for (i, c) in j.changes.iter().enumerate().rev() {
738        let target = root.join(&c.target);
739        let backup = dir.join(format!("old-{i}"));
740        if backup.try_exists().map_err(err)? {
741            if target.try_exists().map_err(err)? {
742                remove_path(&target)?;
743            }
744            fs::rename(&backup, &target).map_err(err)?;
745        } else if c.old.is_none() && target.try_exists().map_err(err)? {
746            remove_path(&target)?;
747        }
748    }
749    // Journal last: a failed rollback stays diagnosable and retryable.
750    fs::remove_file(root.join(JOURNAL)).map_err(err)?;
751    fs::remove_dir_all(dir).map_err(err)
752}
753fn recover(root: &Path) -> Result<bool> {
754    let Some(bytes) = read_bytes(&root.join(JOURNAL), MAX_META)? else {
755        return Ok(false);
756    };
757    let j: Journal = serde_json::from_slice(&bytes).map_err(err)?;
758    let suffix = j
759        .directory
760        .strip_prefix(".resource-txn-")
761        .ok_or("invalid transaction directory")?;
762    uuid::Uuid::parse_str(suffix).map_err(err)?;
763    if j.changes.len() > 3 {
764        return Err("oversized transaction plan".into());
765    }
766    let mut seen = BTreeSet::new();
767    for c in &j.changes {
768        transaction_target(&c.target)?;
769        if !seen.insert(&c.target) {
770            return Err("duplicate transaction target".into());
771        }
772    }
773    rollback(root, &j)?;
774    Ok(true)
775}
776fn write_new(path: &Path, bytes: &[u8]) -> Result<()> {
777    let mut f = OpenOptions::new()
778        .write(true)
779        .create_new(true)
780        .open(path)
781        .map_err(err)?;
782    f.write_all(bytes).and_then(|_| f.sync_all()).map_err(err)
783}
784/// Copy a resource snapshot into `target` and return the inventory of the copy.
785///
786/// The returned inventory can differ from `observed` on macOS: native artifacts
787/// are re-signed after copying (see `resign_snapshot_native`), which rewrites
788/// their bytes. Callers must record the **returned** inventory, not the source
789/// one, or every later ownership check fails.
790fn copy_snapshot(
791    kind: Kind,
792    source: &Path,
793    target: &Path,
794    observed: &Inventory,
795) -> Result<Inventory> {
796    fn copy_file(source: &Path, target: &Path, expected: u64) -> Result<()> {
797        checked_path(source)?;
798        let input = File::open(source).map_err(err)?;
799        #[cfg(unix)]
800        let mode = {
801            use std::os::unix::fs::PermissionsExt;
802            // Only ordinary rwx permissions; never copy setuid/setgid/sticky.
803            input.metadata().map_err(err)?.permissions().mode() & 0o777
804        };
805        let mut output = OpenOptions::new()
806            .write(true)
807            .create_new(true)
808            .open(target)
809            .map_err(err)?;
810        let copied = std::io::copy(&mut input.take(expected + 1), &mut output).map_err(err)?;
811        if copied != expected {
812            return Err("resource changed during bounded copy".into());
813        }
814        #[cfg(unix)]
815        {
816            use std::os::unix::fs::PermissionsExt;
817            output
818                .set_permissions(fs::Permissions::from_mode(mode))
819                .map_err(err)?;
820        }
821        output.sync_all().map_err(err)
822    }
823    if source.is_file() {
824        copy_file(
825            source,
826            target,
827            observed
828                .files
829                .first()
830                .ok_or("missing file inventory")?
831                .bytes,
832        )?;
833    } else {
834        fs::create_dir(target).map_err(err)?;
835        for d in &observed.directories {
836            fs::create_dir_all(target.join(d)).map_err(err)?;
837        }
838        for f in &observed.files {
839            let to = target.join(&f.path);
840            if let Some(p) = to.parent() {
841                fs::create_dir_all(p).map_err(err)?;
842            }
843            copy_file(&source.join(&f.path), &to, f.bytes)?;
844        }
845    }
846    if inventory(source)? != *observed {
847        return Err("resource source changed during snapshot copy".into());
848    }
849    // Which copied files are loadable native artifacts is decided by the resource
850    // KIND, because only the kind's validator reserves a place for one:
851    //   - Extension: the single-file source is the artifact, even though its
852    //     inventory path is `.` with no extension
853    //   - Package: only direct children of `extensions/` (see `validate_source`),
854    //     so a `.dylib` under `skills/`, `prompts/` or `themes/` is data
855    //   - Skill: nothing. A skill only has to contain SKILL.md, so a same-suffix
856    //     asset means nothing and must never be handed to `codesign`
857    let native: std::collections::BTreeSet<PathBuf> = match kind {
858        Kind::Extension => observed.files.iter().map(|f| f.path.clone()).collect(),
859        Kind::Package => observed
860            .files
861            .iter()
862            .map(|f| f.path.clone())
863            .filter(|p| is_package_artifact(p))
864            .collect(),
865        Kind::Skill => std::collections::BTreeSet::new(),
866    };
867    let artifacts: Vec<PathBuf> = native.iter().map(|p| target.join(p)).collect();
868    resign_snapshot_native(&artifacts)?;
869    let copied = inventory(target)?;
870    // Every byte outside the re-signed artifacts must still match the source.
871    let comparable = |inv: &Inventory| Inventory {
872        files: inv
873            .files
874            .iter()
875            .filter(|f| !native.contains(&f.path))
876            .cloned()
877            .collect(),
878        directories: inv.directories.clone(),
879        sha256: String::new(),
880    };
881    if comparable(&copied) != comparable(observed) {
882        return Err("resource snapshot copy does not match the source".into());
883    }
884    Ok(copied)
885}
886
887/// Whether a Package file is a native artifact: a direct child of `extensions/`
888/// with the platform library extension. This mirrors what `validate_source`
889/// accepts, so data files that merely use the same suffix elsewhere in the tree
890/// are never handed to `codesign`.
891fn is_package_artifact(path: &Path) -> bool {
892    is_native_artifact(path) && path.components().count() == 2 && path.starts_with("extensions")
893}
894
895/// Whether a path uses this platform's native library extension.
896fn is_native_artifact(path: &Path) -> bool {
897    path.extension().and_then(|s| s.to_str()) == Some(std::env::consts::DLL_EXTENSION)
898}
899/// macOS only: re-sign copied native artifacts so the kernel will map them.
900///
901/// A signed Mach-O carries a code directory whose hashes must match the bytes
902/// the kernel maps. Copying is byte-exact, so a well-formed copy stays valid —
903/// but a plain `io::copy` of a freshly linked cargo `cdylib` can also carry a
904/// linker signature the kernel refuses. When it refuses, it does not return an
905/// error: it kills the host that touched the page.
906///
907/// ```text
908/// CODE SIGNING: process 20087[rpi]: rejecting invalid page at address 0x…
909///   in file "~/.pidd/rpi-agent/extensions/librpi_superagent.dylib"
910///   (cs_mtime:1794052202.55 != mtime:1794056571.77)
911/// CODE SIGNING: cs_invalid_page(0x…): denying page sending SIGKILL
912/// ```
913///
914/// No stderr reaches the caller and the only exit status is 137, so the symptom
915/// reads as "rpi cannot start at all". `codesign -v` also reports these copies
916/// as valid, so verifying first is not a substitute for signing.
917///
918/// Only native artifacts are re-signed; text resources are left untouched.
919fn resign_snapshot_native(artifacts: &[PathBuf]) -> Result<()> {
920    if !cfg!(target_os = "macos") {
921        return Ok(());
922    }
923    for path in artifacts {
924        // Pin the ad-hoc identifier: `codesign --sign -` otherwise derives it from
925        // the file NAME, so the same bytes staged under two different names sign
926        // to different bytes. That would make an unchanged install look changed.
927        let output = std::process::Command::new("/usr/bin/codesign")
928            .args(["--force", "--sign", "-", "--identifier", "com.rpi.native"])
929            .arg(path)
930            .output()
931            .map_err(|e| format!("could not run codesign on {}: {e}", path.display()))?;
932        if !output.status.success() {
933            return Err(format!(
934                "could not re-sign {} (the kernel will refuse to load it): {}",
935                path.display(),
936                String::from_utf8_lossy(&output.stderr).trim()
937            ));
938        }
939    }
940    Ok(())
941}
942
943/// Small same-filesystem transaction; injection is unit-test-only, never an env backdoor.
944fn publish(
945    root: &Path,
946    changes: Vec<(PathBuf, Option<PathBuf>)>,
947    stage: tempfile::TempDir,
948    mut before: impl FnMut(usize) -> Result<()>,
949) -> Result<Vec<String>> {
950    let directory = stage
951        .path()
952        .file_name()
953        .and_then(|s| s.to_str())
954        .ok_or("invalid staging directory")?
955        .to_owned();
956    let mut j = Journal {
957        directory,
958        changes: Vec::new(),
959    };
960    for (target, new) in &changes {
961        transaction_target(target)?;
962        let path = root.join(target);
963        checked_path(&path)?;
964        j.changes.push(Change {
965            target: target.clone(),
966            old: if path.try_exists().map_err(err)? {
967                Some(inventory(&path)?)
968            } else {
969                None
970            },
971            new: new.as_ref().map(|p| inventory(p)).transpose()?,
972        });
973    }
974    let journal_stage = stage.path().join("journal");
975    write_new(&journal_stage, &json_bytes(&j)?)?;
976    fs::rename(&journal_stage, root.join(JOURNAL)).map_err(err)?;
977    // Do not auto-delete backup evidence if interrupted or rollback itself fails.
978    let _owned = stage.keep();
979    let result = (|| {
980        for (i, (target, new)) in changes.iter().enumerate() {
981            before(i * 2)?;
982            let path = root.join(target);
983            if j.changes[i].old.is_some() {
984                fs::rename(&path, root.join(&j.directory).join(format!("old-{i}"))).map_err(err)?;
985            }
986            before(i * 2 + 1)?;
987            if let Some(new) = new {
988                fs::rename(new, &path).map_err(err)?;
989            }
990        }
991        before(changes.len() * 2)?;
992        Ok(())
993    })();
994    if let Err(error) = result {
995        return match rollback(root, &j) {
996            Ok(()) => Err(error),
997            Err(r) => Err(format!(
998                "{error}; rollback incomplete: {r}; run resource recover"
999            )),
1000        };
1001    }
1002    // Commit point: removing the journal makes installed bytes authoritative.
1003    // Orphan staging after this point contains only old bytes, never active data.
1004    if let Err(error) = fs::remove_file(root.join(JOURNAL)) {
1005        return match rollback(root,&j) {
1006            Ok(())=>Err(format!("commit marker removal failed: {error}; rolled back")),
1007            Err(rollback)=>Err(format!("commit marker removal failed: {error}; rollback incomplete: {rollback}; run resource recover")),
1008        };
1009    }
1010    if let Err(e) = fs::remove_dir_all(root.join(&j.directory)) {
1011        return Ok(vec![format!(
1012            "committed; backup cleanup pending (OS error {:?}, {:?})",
1013            e.raw_os_error(),
1014            e.kind()
1015        )]);
1016    }
1017    Ok(Vec::new())
1018}
1019fn stage_dir(root: &Path) -> Result<tempfile::TempDir> {
1020    tempfile::Builder::new()
1021        .prefix(&format!(".resource-txn-{}", uuid::Uuid::new_v4().simple()))
1022        .rand_bytes(0)
1023        .tempdir_in(root)
1024        .map_err(err)
1025}
1026
1027#[derive(Default)]
1028struct Options {
1029    op: String,
1030    kind: Option<Kind>,
1031    name: Option<String>,
1032    scope: Option<Scope>,
1033    source: Option<PathBuf>,
1034    version: Option<String>,
1035}
1036fn parse(args: &[String]) -> Result<Options> {
1037    let mut o = Options {
1038        op: args.first().ok_or("missing resource operation")?.clone(),
1039        ..Default::default()
1040    };
1041    let mut pos = Vec::new();
1042    let mut i = 1;
1043    while i < args.len() {
1044        let a = &args[i];
1045        if matches!(a.as_str(), "--scope" | "--path" | "--version") {
1046            i += 1;
1047            let v = args.get(i).ok_or("missing option value")?;
1048            if v.starts_with('-') {
1049                return Err("missing option value".into());
1050            }
1051            match a.as_str() {
1052                "--scope" => {
1053                    if o.scope.is_some() {
1054                        return Err("duplicate scope".into());
1055                    }
1056                    o.scope = Some(match v.as_str() {
1057                        "project" => Scope::Project,
1058                        "global" => Scope::Global,
1059                        _ => return Err("scope must be project or global".into()),
1060                    });
1061                }
1062                "--path" => {
1063                    if o.source.replace(v.into()).is_some() {
1064                        return Err("duplicate path".into());
1065                    }
1066                }
1067                _ => {
1068                    if v.trim().is_empty()
1069                        || v.len() > 128
1070                        || v.chars().any(char::is_control)
1071                        || o.version.replace(v.clone()).is_some()
1072                    {
1073                        return Err("invalid/duplicate version".into());
1074                    }
1075                }
1076            }
1077        } else if a.starts_with('-') {
1078            return Err(format!(
1079                "unknown resource option {a}; builds require explicit native package link/install"
1080            ));
1081        } else {
1082            pos.push(a.clone());
1083        }
1084        i += 1;
1085    }
1086    if o.scope.is_none() {
1087        return Err("explicit --scope project|global is required".into());
1088    }
1089    if matches!(o.op.as_str(), "list" | "recover") {
1090        if !pos.is_empty() || o.source.is_some() || o.version.is_some() {
1091            return Err("unexpected list/recover arguments".into());
1092        }
1093    } else if matches!(
1094        o.op.as_str(),
1095        "inspect" | "install" | "update" | "reinstall" | "remove"
1096    ) {
1097        if pos.len() != 2 {
1098            return Err("expected KIND NAME".into());
1099        }
1100        o.kind = Some(Kind::parse(&pos[0])?);
1101        if o.op == "inspect" && o.kind == Some(Kind::Package) {
1102            legacy_package_identity(&pos[1])?;
1103        } else {
1104            identifier(&pos[1])?;
1105        }
1106        o.name = Some(pos[1].clone());
1107        let mutation = matches!(o.op.as_str(), "install" | "update" | "reinstall");
1108        if mutation != o.source.is_some() || (!mutation && o.version.is_some()) {
1109            return Err("install/update/reinstall require --path; inspect/remove reject it".into());
1110        }
1111    } else {
1112        return Err("unknown resource operation".into());
1113    }
1114    Ok(o)
1115}
1116fn validate_source(kind: Kind, source: &Path, inv: &Inventory) -> Result<()> {
1117    match kind {
1118        Kind::Skill => {
1119            if !source.is_dir() || !source.join("SKILL.md").is_file() {
1120                return Err("standalone Skill requires a directory containing SKILL.md".into());
1121            }
1122            let text =
1123                read_bytes(&source.join("SKILL.md"), 64 * 1024)?.ok_or("missing SKILL.md")?;
1124            std::str::from_utf8(&text).map_err(err)?;
1125        }
1126        Kind::Extension => {
1127            if !source.is_file()
1128                || source.extension().and_then(|s| s.to_str())
1129                    != Some(std::env::consts::DLL_EXTENSION)
1130            {
1131                return Err("extension source must be a platform native library file".into());
1132            }
1133        }
1134        Kind::Package => {
1135            if !source.is_dir() {
1136                return Err("package source must be a directory".into());
1137            }
1138            if !["extensions", "skills", "prompts", "themes"]
1139                .iter()
1140                .any(|s| source.join(s).is_dir())
1141                && inv.files.is_empty()
1142            {
1143                return Err("empty package".into());
1144            }
1145            for f in &inv.files {
1146                if f.path.starts_with("extensions")
1147                    && (f.path.components().count() != 2
1148                        || f.path.extension().and_then(|s| s.to_str())
1149                            != Some(std::env::consts::DLL_EXTENSION))
1150                {
1151                    return Err(
1152                        "Package extensions must be direct platform native artifacts".into(),
1153                    );
1154                }
1155            }
1156        }
1157    }
1158    Ok(())
1159}
1160fn explicit_source(path: &Path) -> Result<PathBuf> {
1161    let addressed = std::env::current_dir().map_err(err)?.join(path);
1162    let mut normalized = PathBuf::new();
1163    for component in addressed.components() {
1164        match component {
1165            Component::CurDir => {}
1166            Component::ParentDir => {
1167                checked_path(&normalized)?;
1168                if !normalized.pop() {
1169                    return Err("source escapes filesystem root".into());
1170                }
1171            }
1172            other => {
1173                normalized.push(other);
1174                // A Windows drive prefix (`C:` / `\\\\?\\C:`) becomes
1175                // absolute only after its RootDir component is appended.
1176                if !matches!(other, Component::Prefix(_)) && normalized.is_absolute() {
1177                    checked_path(&normalized)?;
1178                }
1179            }
1180        }
1181    }
1182    fs::canonicalize(normalized).map_err(err)
1183}
1184fn mutate(root: &Path, o: &Options) -> Result<Value> {
1185    let _lease = mutation_lease(root)?;
1186    let mut r = receipts(root)?;
1187    let mut p = packages(root)?;
1188    let native: Vec<crate::install::InstalledNativePackage> =
1189        read_json(&root.join("native-packages.json"))?;
1190    let kind = o.kind.ok_or("missing kind")?;
1191    let name = o.name.as_deref().ok_or("missing name")?;
1192    let target = kind.target(name);
1193    let path = root.join(&target);
1194    checked_path(&path)?;
1195    let previous = r
1196        .resources
1197        .iter()
1198        .find(|r| r.kind == kind && r.name.eq_ignore_ascii_case(name))
1199        .cloned();
1200    for owned in r.resources.iter().filter(|r| r.kind == Kind::Package) {
1201        if p.packages.iter().find(|p| p.name == owned.name) != Some(&package_record(owned)) {
1202            return Err(
1203                "owned package receipt disagrees with native packages.json; refusing mutation"
1204                    .into(),
1205            );
1206        }
1207    }
1208    if kind == Kind::Extension
1209        && native.iter().any(|p| {
1210            p.name.eq_ignore_ascii_case(name)
1211                || p.artifacts.iter().any(|a| {
1212                    target
1213                        .file_name()
1214                        .is_some_and(|f| f.to_string_lossy().eq_ignore_ascii_case(a))
1215                })
1216        })
1217    {
1218        return Err(
1219            "extension identity/artifact owned by legacy native registry (even if missing)".into(),
1220        );
1221    }
1222    if let Some(old) = &previous {
1223        if old.name != name {
1224            return Err("identity case collision".into());
1225        }
1226        if inventory(&path)? != old.inventory {
1227            return Err("owned resource content changed; refusing overwrite/removal".into());
1228        }
1229    }
1230    if o.op == "remove" && previous.is_none() {
1231        if path.try_exists().map_err(err)? {
1232            return Err("unmanaged destination: refusing removal".into());
1233        }
1234        return Ok(json!({"outcome":"absent","kind":kind,"name":name}));
1235    }
1236    if previous.is_none() && path.try_exists().map_err(err)? {
1237        return Err("unmanaged destination conflict".into());
1238    }
1239    if kind == Kind::Package
1240        && previous.is_none()
1241        && p.packages.iter().any(|p| p.name.eq_ignore_ascii_case(name))
1242    {
1243        return Err("package identity owned by native package link".into());
1244    }
1245    if matches!(o.op.as_str(), "update" | "reinstall") && previous.is_none() {
1246        return Err("resource is not owned/installed; use install".into());
1247    }
1248    let source = o
1249        .source
1250        .as_ref()
1251        .map(|path| explicit_source(path))
1252        .transpose()?;
1253    if let Some(source) = &source {
1254        let source_identity = path_identity(source)?;
1255        let root_identity = path_identity(root)?;
1256        if source_identity.starts_with(&root_identity)
1257            || root_identity.starts_with(&source_identity)
1258        {
1259            return Err("source/destination resource trees overlap".into());
1260        }
1261    }
1262    let stage = stage_dir(root)?;
1263    let mut next = None;
1264    if let Some(source) = source {
1265        // No Cargo metadata/build or native loader is called here.
1266        let inv = inventory(&source)?;
1267        validate_source(kind, &source, &inv)?;
1268        let version = o
1269            .version
1270            .clone()
1271            .or_else(|| previous.as_ref().and_then(|r| r.version.clone()));
1272        // Copy before building the receipt: on macOS the staged native artifacts
1273        // are re-signed, so the copy's inventory (which is what gets installed and
1274        // later re-verified against) differs from the source's.
1275        let staged = stage.path().join("snapshot");
1276        let copied = copy_snapshot(kind, &source, &staged, &inv)?;
1277        let receipt = Receipt {
1278            kind,
1279            name: name.into(),
1280            source,
1281            version,
1282            target: target.clone(),
1283            inventory: copied,
1284        };
1285        if o.op == "install" {
1286            if let Some(old) = &previous {
1287                if old.source == receipt.source
1288                    && old.version == receipt.version
1289                    && old.inventory == receipt.inventory
1290                {
1291                    return Ok(
1292                        json!({"outcome":"unchanged","resource":observe(root,o.scope.unwrap(),old,false)?}),
1293                    );
1294                }
1295                return Err("already installed; use update or reinstall with --path".into());
1296            }
1297        }
1298        next = Some((receipt, staged));
1299    }
1300    r.resources.retain(|r| !(r.kind == kind && r.name == name));
1301    if kind == Kind::Package {
1302        p.packages.retain(|p| p.name != name);
1303        if let Some((new, _)) = &next {
1304            p.packages.push(package_record(new));
1305        }
1306    }
1307    if let Some((receipt, _)) = &next {
1308        r.resources.push(receipt.clone());
1309    }
1310    if r.resources.len() > 128 {
1311        return Err("resource receipts exceed 128 resources per scope".into());
1312    }
1313    r.resources.sort_by_key(|r| r.target.clone());
1314    p.packages.sort_by(|a, b| a.name.cmp(&b.name));
1315    let receipt_stage = stage.path().join("receipts");
1316    write_new(&receipt_stage, &json_bytes(&r)?)?;
1317    let mut changes = vec![
1318        (target, next.as_ref().map(|(_, p)| p.clone())),
1319        (PathBuf::from(RECEIPTS), Some(receipt_stage)),
1320    ];
1321    if kind == Kind::Package {
1322        let staged = stage.path().join("packages");
1323        write_new(&staged, &json_bytes(&p)?)?;
1324        changes.push((PathBuf::from("packages.json"), Some(staged)));
1325    }
1326    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()?});
1327    // Bound the exact public envelope before publication. Reserve space for a
1328    // bounded post-commit backup-cleanup diagnostic (not a false operation error).
1329    if json_bytes(&success(o, data.clone()))
1330        .map_err(|error| format!("resource success result rejected before publication: {error}"))?
1331        .len()
1332        > MAX_META - 4096
1333    {
1334        return Err("resource success result exceeds bounded publication budget".into());
1335    }
1336    let parent = path.parent().ok_or("no resource parent")?;
1337    checked_path(parent)?;
1338    fs::create_dir_all(parent).map_err(err)?;
1339    let diagnostics = publish(root, changes, stage, |_| Ok(()))?;
1340    data["diagnostics"] = json!(diagnostics);
1341    Ok(data)
1342}
1343fn package_record(r: &Receipt) -> crate::packages::ProjectPackage {
1344    crate::packages::ProjectPackage {
1345        name: r.name.clone(),
1346        version: r.version.clone().unwrap_or_default(),
1347        source: r.source.to_string_lossy().into_owned(),
1348        cargo_package: String::new(),
1349        artifacts: r
1350            .inventory
1351            .files
1352            .iter()
1353            .filter(|f| f.path.starts_with("extensions"))
1354            .filter_map(|f| {
1355                f.path
1356                    .file_name()
1357                    .and_then(|s| s.to_str())
1358                    .map(str::to_owned)
1359            })
1360            .collect(),
1361    }
1362}
1363fn observe(root: &Path, scope: Scope, r: &Receipt, busy: bool) -> Result<Value> {
1364    observe_bounded(root, scope, r, busy, &mut InventoryBudget::default())
1365}
1366fn observe_bounded(
1367    root: &Path,
1368    scope: Scope,
1369    r: &Receipt,
1370    busy: bool,
1371    budget: &mut InventoryBudget,
1372) -> Result<Value> {
1373    let observed = inventory_bounded(&root.join(&r.target), budget);
1374    observe_inventory(root, scope, r, busy, observed)
1375}
1376fn observe_inventory(
1377    root: &Path,
1378    scope: Scope,
1379    r: &Receipt,
1380    busy: bool,
1381    observed: Result<Inventory>,
1382) -> Result<Value> {
1383    let mut diagnostics =
1384        vec!["native ABI compatibility is unverified; inspection never loads code".to_string()];
1385    if observed.as_ref().ok() != Some(&r.inventory) {
1386        diagnostics.push("installed content is missing or differs from ownership receipt".into());
1387    }
1388    if let Err(e) = &observed {
1389        diagnostics.push(e.clone());
1390    }
1391    Ok(
1392        json!({"kind":r.kind,"scope":scope,"identity":format!("{}:{}:{}",if scope==Scope::Project{"project"}else{"global"},r.kind.dir(),r.name),"name":r.name,"source":r.source,"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}),
1393    )
1394}
1395fn selectable(root: &Path, scope: Scope, r: &Receipt) -> Value {
1396    match r.kind {
1397        Kind::Package => json!({"main_package":{"name":r.name,"scope":scope,"instructions":[]}}),
1398        Kind::Skill => json!({"skills":[root.join(&r.target)]}),
1399        Kind::Extension => json!({"extensions":[root.join(&r.target)]}),
1400    }
1401}
1402fn catalog(root: &Path, o: &Options) -> Result<Value> {
1403    checked_path(root)?;
1404    let (_observation_lease, busy) = observation_lease(root)?;
1405    let r = receipts(root)?;
1406    let p = packages(root)?;
1407    let native: Vec<crate::install::InstalledNativePackage> =
1408        read_json(&root.join("native-packages.json"))?;
1409    let scope = o.scope.unwrap();
1410    let mut items = Vec::new();
1411    let mut owned = BTreeSet::new();
1412    let mut budget = InventoryBudget::default();
1413    for receipt in &r.resources {
1414        owned.insert(receipt.target.clone());
1415        items.push(observe_bounded(root, scope, receipt, busy, &mut budget)?);
1416    }
1417    for kind in [Kind::Package, Kind::Skill, Kind::Extension] {
1418        let directory = root.join(kind.dir());
1419        checked_path(&directory)?;
1420        let entries = match fs::read_dir(directory) {
1421            Ok(e) => e,
1422            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
1423            Err(e) => return Err(err(e)),
1424        };
1425        for entry in entries {
1426            let entry = entry.map_err(err)?;
1427            let target = Path::new(kind.dir()).join(entry.file_name());
1428            if owned.contains(&target) {
1429                continue;
1430            }
1431            if items.len() >= MAX_FILES {
1432                return Err("catalog exceeds entry limit".into());
1433            }
1434            let name = if kind == Kind::Extension {
1435                entry
1436                    .path()
1437                    .file_stem()
1438                    .and_then(|s| s.to_str())
1439                    .unwrap_or("")
1440                    .to_string()
1441            } else {
1442                entry
1443                    .file_name()
1444                    .to_str()
1445                    .ok_or("non UTF8 candidate")?
1446                    .to_string()
1447            };
1448            let pkg = p
1449                .packages
1450                .iter()
1451                .find(|p| kind == Kind::Package && p.name == name);
1452            let ext = native.iter().find(|p| {
1453                kind == Kind::Extension
1454                    && p.artifacts
1455                        .iter()
1456                        .any(|a| entry.file_name() == std::ffi::OsStr::new(a))
1457            });
1458            let inv = inventory_bounded(&entry.path(), &mut budget);
1459            let diagnostics = match &inv {
1460                Ok(_) => vec!["unverified candidate; no code executed".to_string()],
1461                Err(e) => vec![e.clone()],
1462            };
1463            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}));
1464        }
1465    }
1466    if o.op == "inspect" {
1467        items.retain(|item| item["name"] == json!(o.name) && item["kind"] == json!(o.kind));
1468        if items.is_empty() {
1469            return Err("resource not found".into());
1470        }
1471    }
1472    items.sort_by_key(|i| i["identity"].as_str().unwrap_or("").to_string());
1473    // When no persistent lock existed initially, first publication could have
1474    // started during traversal. Its lock inode is never unlinked: reject and
1475    // retry rather than returning any potentially mixed observation.
1476    if _observation_lease.is_none() && root.join(LEASE).try_exists().map_err(err)? {
1477        return Err("resource ownership initialized during observation; retry catalog".into());
1478    }
1479    Ok(
1480        json!({"outcome":"observed","resources":items,"diagnostics":if root.join(JOURNAL).try_exists().map_err(err)?{vec!["incomplete transaction; run resource recover"]}else{vec![]}}),
1481    )
1482}
1483fn success(o: &Options, data: Value) -> Value {
1484    json!({"version":1,"success":true,"operation":o.op,"scope":o.scope,"kind":o.kind,"name":o.name,"data":data})
1485}
1486pub fn run(args: &[String]) -> i32 {
1487    if args.is_empty() || args.iter().any(|a| matches!(a.as_str(), "--help" | "-h")) {
1488        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.");
1489        return 0;
1490    }
1491    let result: Result<Value> = (|| {
1492        let o = parse(args)?;
1493        let cwd = std::env::current_dir().map_err(err)?;
1494        let root = o
1495            .scope
1496            .unwrap()
1497            .root(&crate::config::AgentHome::process(), &cwd)?;
1498        let data = if matches!(o.op.as_str(), "list" | "inspect") {
1499            catalog(&root, &o)?
1500        } else if o.op == "recover" {
1501            let _lease = Lease::acquire(&root, true, true)?;
1502            json!({"outcome":if recover(&root)?{"recovered"}else{"unchanged"}})
1503        } else {
1504            mutate(&root, &o)?
1505        };
1506        Ok(success(&o, data))
1507    })();
1508    match result.and_then(|v| json_bytes(&v)) {
1509        Ok(bytes) => {
1510            println!("{}", String::from_utf8_lossy(&bytes));
1511            0
1512        }
1513        Err(e) => {
1514            let bounded = e.chars().take(2048).collect::<String>();
1515            let context = parse(args).ok();
1516            println!(
1517                "{}",
1518                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})
1519            );
1520            1
1521        }
1522    }
1523}
1524
1525#[cfg(test)]
1526mod regressions;
1527#[cfg(test)]
1528mod tests;