capsule_library/lifecycle/unanchored.rs
1//! Sidecars that no provenance chain anchors.
2//!
3//! [`Workspace::open`] restores an asset from its `.provenance.cbor`; a `{uuid}.cbor` under
4//! `media/` with no chain beside it is invisible to every signed operation — it cannot be
5//! verified, exported, or uploaded. Such a file is debris: the signed sidecar of a write that
6//! died after the sidecar rename and before the chain rename (the chain lands last, so a
7//! crash leaves this rather than a torn chain), a torn or foreign file, or a retired unsigned
8//! pre-signed-path record. None of them is restorable without discarding or inventing signed
9//! state, so each is reported — by `open`, and keylessly by [`unanchored_sidecars`] — and
10//! never touched.
11
12use std::fs;
13use std::path::{Path, PathBuf};
14
15use capsule_core::sidecar::shape::{self, SidecarShape};
16use uuid::Uuid;
17use walkdir::WalkDir;
18
19use super::Workspace;
20
21/// The shape of a `{uuid}.cbor` under `media/` that no `.provenance.cbor` anchors.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum UnanchoredShape {
24 /// A signed sidecar whose chain is missing — a write interrupted before its chain landed
25 /// — with the `sidecar_schema` it carries.
26 SignedWithoutChain {
27 /// The value at the sidecar's integer key `0`.
28 schema: u16,
29 },
30 /// Not a signed sidecar: not CBOR, not a map, a torn write, or a retired unsigned
31 /// pre-signed-path record. Reported so it is never silently skipped, and never touched.
32 Unknown,
33}
34
35/// One sidecar file under `media/` that no provenance chain anchors — an asset the workspace
36/// cannot see.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct UnanchoredSidecar {
39 /// The `{uuid}.cbor` file.
40 pub path: PathBuf,
41 /// The asset id its stem names, when the stem parses as one.
42 pub asset_id: Option<Uuid>,
43 /// Which shape the bytes have.
44 pub shape: UnanchoredShape,
45}
46
47/// Every `{uuid}.cbor` under `root/media` — the sidecars, never the sibling
48/// `.provenance.cbor` / `.receipts.cbor` / `.attestations.cbor` logs or the
49/// `.derivatives.cbor` bundle. The same filter `rebuild_index` and the add-id sweep apply.
50fn sidecar_files(root: &Path) -> Vec<PathBuf> {
51 let media = root.join("media");
52 if !media.exists() {
53 return Vec::new();
54 }
55 let mut out: Vec<PathBuf> = WalkDir::new(&media)
56 .into_iter()
57 .filter_map(std::result::Result::ok)
58 .filter(|e| e.path().is_file())
59 .filter(|e| crate::library::paths::is_sidecar_file_name(&e.file_name().to_string_lossy()))
60 .map(|e| e.path().to_path_buf())
61 .collect();
62 // Deterministic order regardless of directory-walk order.
63 out.sort();
64 out
65}
66
67/// The sidecars under `root/media` with no `.provenance.cbor` sibling, each probed for its
68/// shape, in path order. Used by [`Workspace::open`] to report them.
69pub(super) fn find_unanchored(root: &Path) -> Vec<UnanchoredSidecar> {
70 let mut out = Vec::new();
71 for path in sidecar_files(root) {
72 let Some(stem) = path
73 .file_name()
74 .and_then(|n| n.to_str())
75 .and_then(|n| n.strip_suffix(".cbor"))
76 else {
77 continue;
78 };
79 let dir = path.parent().unwrap_or(root);
80 if dir.join(format!("{stem}.provenance.cbor")).exists() {
81 continue;
82 }
83 let asset_id = Uuid::parse_str(stem).ok();
84 let shape = match fs::read(&path) {
85 Ok(bytes) => match shape::probe(&bytes) {
86 SidecarShape::Signed { schema } => UnanchoredShape::SignedWithoutChain { schema },
87 SidecarShape::Unknown => UnanchoredShape::Unknown,
88 },
89 Err(e) => {
90 tracing::warn!(sidecar = %path.display(), error = %e, "unreadable sidecar file");
91 UnanchoredShape::Unknown
92 }
93 };
94 out.push(UnanchoredSidecar {
95 path,
96 asset_id,
97 shape,
98 });
99 }
100 out
101}
102
103/// The sidecars under the library at `root` that no provenance chain anchors — the set
104/// [`Workspace::open`] reports through [`Workspace::unanchored_sidecars`], found without a
105/// passphrase or any key material.
106///
107/// The scan only walks `root/media` and probes each unanchored file's shape, so a keyless
108/// caller (`capsule library info`, which opens the library without unlocking it) can report
109/// it. A missing `media/` directory is an empty library, not an error; an unreadable sidecar
110/// is reported as [`UnanchoredShape::Unknown`], never skipped.
111#[must_use]
112pub fn unanchored_sidecars(root: &Path) -> Vec<UnanchoredSidecar> {
113 let found = find_unanchored(root);
114 tracing::debug!(
115 library = %root.display(),
116 count = found.len(),
117 "keyless unanchored-sidecar scan"
118 );
119 found
120}
121
122impl Workspace {
123 /// The sidecar files [`open`](Self::open) found under `media/` that no provenance chain
124 /// anchors — assets this workspace cannot see, verify, export, or upload. Empty for a
125 /// library with no debris.
126 pub fn unanchored_sidecars(&self) -> &[UnanchoredSidecar] {
127 &self.unanchored
128 }
129}
130
131#[cfg(test)]
132mod tests;