Skip to main content

tuff_core/
bundle.rs

1//! Harness bundle formats (RFC-110 D9).
2//!
3//! A bundle format is a harness's own layout for a set of capabilities
4//! installed as one unit, such as a Claude Code plugin. An adapter crate
5//! declares the format; this module holds what every format shares: the
6//! contract a reader implements, the pack a reader produces, and the writer
7//! that turns that pack into an ordinary standalone source pack on disk.
8//! After an import, nothing in Tuff depends on where a pack came from.
9
10use std::collections::BTreeSet;
11use std::fs;
12use std::path::{Component, Path, PathBuf};
13
14use crate::error::{Result, TuffError};
15use crate::manifest::CapabilityType;
16use crate::pack::{self, PackManifest, PackMember, PackUnsupported};
17
18/// One file of a bundle, by its path relative to the bundle's root.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct BundleFile {
21    pub path: String,
22    pub bytes: Vec<u8>,
23}
24
25/// One capability read from a bundle.
26#[derive(Debug, Clone)]
27pub struct ImportedMember {
28    pub id: String,
29    pub capability_type: CapabilityType,
30    /// The member's `tuff.toml`.
31    pub manifest: toml::Table,
32    /// The member's own files, relative to its folder.
33    pub files: Vec<BundleFile>,
34}
35
36/// A bundle read as a pack.
37#[derive(Debug, Clone)]
38pub struct ImportedPack {
39    /// The pack manifest. Its `capabilities` are filled in by the writer.
40    pub manifest: PackManifest,
41    pub members: Vec<ImportedMember>,
42    /// Files the pack does not carry as members, kept under `extra/` so a
43    /// later Tuff or a host can use them.
44    pub extra: Vec<BundleFile>,
45    /// Facts worth telling the person importing, such as a version Tuff had
46    /// to choose.
47    pub notes: Vec<String>,
48}
49
50impl ImportedPack {
51    /// What the source had that the pack does not carry.
52    pub fn unsupported(&self) -> &[PackUnsupported] {
53        self.manifest
54            .import
55            .as_ref()
56            .map(|import| import.unsupported.as_slice())
57            .unwrap_or_default()
58    }
59}
60
61/// Where a bundle's files are: in the folder that was read, or in another
62/// repository that a listing (such as a marketplace) points to.
63#[derive(Debug, Clone)]
64pub enum BundleLocation {
65    Local(LocalBundle),
66    Remote(RemoteBundle),
67}
68
69/// A bundle whose files are in a local folder.
70#[derive(Debug, Clone)]
71pub struct LocalBundle {
72    pub root: PathBuf,
73    /// The bundle's name in the listing that selected it, if one did.
74    pub name: Option<String>,
75    /// The listing's entry, for formats where it can declare components.
76    pub entry: Option<serde_json::Value>,
77}
78
79/// A bundle a listing places in another git repository.
80#[derive(Debug, Clone)]
81pub struct RemoteBundle {
82    pub name: String,
83    pub url: String,
84    /// The folder inside that repository.
85    pub path: Option<String>,
86    /// A tag or branch the listing names.
87    pub git_ref: Option<String>,
88    /// A commit the listing names.
89    pub commit: Option<String>,
90    pub entry: serde_json::Value,
91}
92
93/// What an adapter crate implements to read its harness's bundle format.
94pub trait BundleReader {
95    /// The format id, such as `claude-plugin`.
96    fn id(&self) -> &'static str;
97    /// Whether `root` holds a bundle or a listing of bundles in this format.
98    fn detect(&self, root: &Path) -> bool;
99    /// Find the bundle at `root`, or the one named `entry` in a listing.
100    ///
101    /// # Errors
102    ///
103    /// Returns an error when no bundle is found, or a listing holds several
104    /// and none is named.
105    fn locate(&self, root: &Path, entry: Option<&str>) -> Result<BundleLocation>;
106    /// Read a local bundle as a pack. `version_hint` is the version a release
107    /// tag named, for a bundle that declares none.
108    ///
109    /// # Errors
110    ///
111    /// Returns an error for a malformed bundle. Parts Tuff cannot carry are
112    /// recorded as unsupported, not refused.
113    fn read(&self, bundle: &LocalBundle, version_hint: Option<&str>) -> Result<ImportedPack>;
114}
115
116/// What a bundle writer produced for a pack.
117#[derive(Debug, Clone, Default)]
118pub struct BundleOutput {
119    /// Every file of the bundle, relative to the bundle's root.
120    pub files: Vec<BundleFile>,
121    /// Where each member the bundle holds lives in it.
122    pub members: Vec<BundleMemberOutput>,
123    /// Members the format cannot hold, with why.
124    pub skipped: Vec<PackUnsupported>,
125    /// Things the author should know, such as a hook that will not find its
126    /// files inside the bundle.
127    pub warnings: Vec<String>,
128}
129
130/// One member's place in a written bundle.
131#[derive(Debug, Clone)]
132pub struct BundleMemberOutput {
133    pub id: String,
134    /// The member's folder, or the shared file holding it, in the bundle.
135    pub path: String,
136    /// The files that belong to this member alone, relative to the bundle.
137    pub files: Vec<String>,
138    /// The member's content as the bundle holds it, for its hash: its own
139    /// files, or its entry in a shared file.
140    pub content: Vec<u8>,
141}
142
143/// What an adapter crate implements to write its harness's bundle format.
144pub trait BundleWriter {
145    /// The format id, used as a build target, such as `claude-plugin`.
146    fn id(&self) -> &'static str;
147    /// Write `members` of the pack described by `manifest` as one bundle.
148    ///
149    /// # Errors
150    ///
151    /// Returns an error when the pack cannot be a bundle at all, such as a
152    /// name the format does not allow. A member the format cannot hold is
153    /// returned in `skipped`.
154    fn write(
155        &self,
156        manifest: &PackManifest,
157        members: &[crate::adapter::ResolvedCapability],
158    ) -> Result<BundleOutput>;
159}
160
161/// Every regular file under `relative` in `root`, with paths relative to
162/// `root`. Symbolic links are never followed; each one is returned in the
163/// second list so the caller can report it. `.git` folders are skipped.
164///
165/// # Errors
166///
167/// Returns an error when a directory cannot be read.
168pub fn read_tree(root: &Path, relative: &Path) -> Result<(Vec<BundleFile>, Vec<String>)> {
169    let mut files = Vec::new();
170    let mut links = Vec::new();
171    walk(root, &root.join(relative), &mut files, &mut links)?;
172    files.sort_by(|a, b| a.path.cmp(&b.path));
173    links.sort();
174    Ok((files, links))
175}
176
177fn walk(
178    root: &Path,
179    current: &Path,
180    files: &mut Vec<BundleFile>,
181    links: &mut Vec<String>,
182) -> Result<()> {
183    let mut entries = fs::read_dir(current)?.collect::<std::io::Result<Vec<_>>>()?;
184    entries.sort_by_key(fs::DirEntry::file_name);
185    for entry in entries {
186        let path = entry.path();
187        if entry.file_name() == ".git" {
188            continue;
189        }
190        let relative = relative_name(root, &path)?;
191        let metadata = fs::symlink_metadata(&path)?;
192        if metadata.file_type().is_symlink() {
193            links.push(relative);
194        } else if metadata.is_dir() {
195            walk(root, &path, files, links)?;
196        } else if metadata.is_file() {
197            files.push(BundleFile {
198                path: relative,
199                bytes: fs::read(&path)?,
200            });
201        }
202    }
203    Ok(())
204}
205
206fn relative_name(root: &Path, path: &Path) -> Result<String> {
207    let relative = path
208        .strip_prefix(root)
209        .map_err(|_| TuffError::refused("bundle file escaped its root"))?;
210    Ok(relative.to_string_lossy().replace('\\', "/"))
211}
212
213/// Read a path a bundle manifest declares, such as `./skills/review`, as a
214/// clean path inside the bundle. `.` is the bundle's root.
215///
216/// # Errors
217///
218/// Returns a refusal for an absolute path or one that climbs out.
219pub fn bundle_path(declared: &str) -> Result<PathBuf> {
220    let trimmed = declared.trim_start_matches("./");
221    if trimmed.is_empty() || trimmed == "." {
222        return Ok(PathBuf::new());
223    }
224    let path = Path::new(trimmed);
225    if path.is_absolute()
226        || path
227            .components()
228            .any(|component| !matches!(component, Component::Normal(_)))
229    {
230        return Err(TuffError::refused(format!(
231            "bundle path '{declared}' leaves the bundle"
232        )));
233    }
234    Ok(path.to_path_buf())
235}
236
237/// Write an imported pack as a standalone source pack in `output`, which
238/// must be missing or empty: `tuff-pack.toml`, `capabilities/<id>/` for
239/// each member, and `extra/` for everything else. The folder is assembled
240/// in a temporary directory beside `output` and renamed into place.
241///
242/// # Errors
243///
244/// Returns an error for a non-empty output, an unsafe or duplicate path, or
245/// a failed write.
246pub fn write_source_pack(output: &Path, imported: &ImportedPack) -> Result<()> {
247    if output.exists() && (!output.is_dir() || fs::read_dir(output)?.next().is_some()) {
248        return Err(TuffError::refused(format!(
249            "import output must be missing or empty: {}",
250            output.display()
251        )));
252    }
253    let parent = output
254        .parent()
255        .filter(|parent| !parent.as_os_str().is_empty())
256        .unwrap_or_else(|| Path::new("."));
257    fs::create_dir_all(parent)?;
258    let staging = tempfile::Builder::new()
259        .prefix("tuff-import-")
260        .tempdir_in(parent)?;
261
262    let mut manifest = imported.manifest.clone();
263    manifest.capabilities.clear();
264    let mut ids = BTreeSet::new();
265    for member in &imported.members {
266        crate::manifest::validate_capability_id(&member.id)?;
267        if !ids.insert(member.id.clone()) {
268            return Err(TuffError::usage(format!(
269                "two imported members are both named '{}'",
270                member.id
271            )));
272        }
273        let folder = PathBuf::from("capabilities").join(&member.id);
274        write_file(
275            staging.path(),
276            &folder.join("tuff.toml"),
277            toml::to_string_pretty(&member.manifest)?.as_bytes(),
278        )?;
279        for file in &member.files {
280            if file.path == "tuff.toml" {
281                return Err(TuffError::refused(format!(
282                    "imported member '{}' has its own tuff.toml, which Tuff writes",
283                    member.id
284                )));
285            }
286            write_file(
287                staging.path(),
288                &folder.join(pack::validate_relative_path(Path::new(&file.path))?),
289                &file.bytes,
290            )?;
291        }
292        manifest.capabilities.push(PackMember {
293            path: format!("capabilities/{}", member.id),
294        });
295    }
296    for file in &imported.extra {
297        write_file(
298            staging.path(),
299            &Path::new("extra").join(pack::validate_relative_path(Path::new(&file.path))?),
300            &file.bytes,
301        )?;
302    }
303    pack::write_manifest(&staging.path().join(pack::PACK_MANIFEST_FILE), &manifest)?;
304    // Loading the written folder is the check that it is a valid source pack.
305    pack::load_pack(staging.path())?;
306
307    if output.exists() {
308        fs::remove_dir(output)?;
309    }
310    fs::rename(staging.keep(), output)?;
311    Ok(())
312}
313
314fn write_file(root: &Path, relative: &Path, bytes: &[u8]) -> Result<()> {
315    let destination = root.join(relative);
316    if destination.exists() {
317        return Err(TuffError::usage(format!(
318            "imported pack writes {} twice",
319            relative.display()
320        )));
321    }
322    if let Some(parent) = destination.parent() {
323        fs::create_dir_all(parent)?;
324    }
325    fs::write(destination, bytes)?;
326    Ok(())
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    #[test]
334    fn a_declared_path_stays_inside_the_bundle() {
335        assert_eq!(
336            bundle_path("./skills/review").unwrap(),
337            PathBuf::from("skills/review")
338        );
339        assert_eq!(bundle_path(".").unwrap(), PathBuf::new());
340        assert_eq!(bundle_path("./").unwrap(), PathBuf::new());
341        for escape in ["../outside", "./a/../../b", "/etc"] {
342            assert!(bundle_path(escape).is_err(), "{escape}");
343        }
344    }
345
346    #[cfg(unix)]
347    #[test]
348    fn read_tree_reports_links_without_following_them() {
349        let temp = tempfile::tempdir().unwrap();
350        fs::create_dir_all(temp.path().join("skills/a")).unwrap();
351        fs::write(temp.path().join("skills/a/SKILL.md"), "# A\n").unwrap();
352        std::os::unix::fs::symlink("/etc/hosts", temp.path().join("skills/a/hosts")).unwrap();
353        fs::create_dir_all(temp.path().join(".git")).unwrap();
354        fs::write(temp.path().join(".git/HEAD"), "ref").unwrap();
355        let (files, links) = read_tree(temp.path(), Path::new("")).unwrap();
356        assert_eq!(
357            files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
358            ["skills/a/SKILL.md"]
359        );
360        assert_eq!(links, ["skills/a/hosts"]);
361    }
362}