1use std::path::{Path, PathBuf};
2
3use serde::{Deserialize, Serialize};
4
5use crate::error::{Result, TuffError};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
8#[serde(rename_all = "lowercase")]
9pub enum CapabilityType {
10 Skill,
11 Tool,
12 Hook,
13 Policy,
14 #[serde(rename = "mcp-server")]
18 McpServer,
19}
20
21impl CapabilityType {
22 pub fn plural_dir(&self) -> &'static str {
23 match self {
24 Self::Skill => "skills",
25 Self::Tool => "tools",
26 Self::Hook => "hooks",
27 Self::Policy => "policies",
28 Self::McpServer => "mcp-servers",
29 }
30 }
31
32 pub fn as_str(&self) -> &'static str {
33 match self {
34 Self::Skill => "skill",
35 Self::Tool => "tool",
36 Self::Hook => "hook",
37 Self::Policy => "policy",
38 Self::McpServer => "mcp-server",
39 }
40 }
41
42 pub fn parse(s: &str) -> Option<Self> {
43 match s {
44 "skill" => Some(Self::Skill),
45 "tool" => Some(Self::Tool),
46 "hook" => Some(Self::Hook),
47 "policy" => Some(Self::Policy),
48 "mcp-server" | "mcp" => Some(Self::McpServer),
49 _ => None,
50 }
51 }
52}
53
54impl std::fmt::Display for CapabilityType {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 f.write_str(self.as_str())
57 }
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct CapabilityManifest {
62 pub id: String,
63 pub version: String,
64 #[serde(rename = "type")]
65 pub capability_type: CapabilityType,
66 pub description: String,
67 #[serde(default)]
68 pub files: Vec<String>,
69 #[serde(default)]
70 pub parameters: Option<serde_json::Value>,
71 #[serde(default)]
72 pub implementation: Option<ImplementationConfig>,
73 #[serde(default)]
74 pub hook: Option<HookConfig>,
75 #[serde(default)]
76 pub server: Option<McpServerConfig>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub policy: Option<crate::policy::PolicyConfig>,
80 #[serde(default)]
81 #[allow(dead_code)]
82 pub targets: Vec<String>,
83 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
85 pub x: crate::host::HostTables,
86
87 #[serde(skip)]
88 pub root: PathBuf,
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct McpServerConfig {
102 #[serde(default)]
103 pub transport: McpTransport,
104 #[serde(default, skip_serializing_if = "Option::is_none")]
105 pub command: Option<String>,
106 #[serde(default)]
107 pub args: Vec<String>,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
109 pub url: Option<String>,
110 #[serde(default)]
111 pub env: std::collections::BTreeMap<String, EnvRef>,
112 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
116 pub headers: std::collections::BTreeMap<String, HeaderRef>,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub metadata: Option<McpServerMetadata>,
119}
120
121#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(rename_all = "lowercase")]
123pub enum McpTransport {
124 #[default]
125 Stdio,
126 Http,
127}
128
129impl McpTransport {
130 pub fn as_str(&self) -> &'static str {
131 match self {
132 Self::Stdio => "stdio",
133 Self::Http => "http",
134 }
135 }
136}
137
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(deny_unknown_fields)]
143pub struct EnvRef {
144 pub from_env: String,
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(deny_unknown_fields)]
156pub struct HeaderRef {
157 pub from_env: String,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
159 pub format: Option<String>,
160}
161
162impl HeaderRef {
163 pub fn render(&self, value_reference: &str) -> String {
167 match &self.format {
168 Some(format) => format.replacen(FORMAT_PLACEHOLDER, value_reference, 1),
169 None => value_reference.to_string(),
170 }
171 }
172}
173
174pub const FORMAT_PLACEHOLDER: &str = "{}";
176
177#[derive(Debug, Clone, Default, Serialize, Deserialize)]
178pub struct McpServerMetadata {
179 #[serde(default, skip_serializing_if = "Option::is_none")]
180 pub tools_summary: Option<String>,
181}
182
183#[derive(Debug, Clone, Serialize, Deserialize)]
184pub struct ImplementationConfig {
185 pub language: String,
186 pub entrypoint: String,
187 #[serde(default)]
188 pub mcp: bool,
189 #[serde(default)]
190 pub runtime_deps: Vec<String>,
191}
192
193#[derive(Debug, Clone, Serialize, Deserialize)]
194pub struct HookConfig {
195 pub event: String,
196 pub command: String,
197 #[serde(default = "default_cwd")]
198 pub working_directory: String,
199}
200
201fn default_cwd() -> String {
202 ".".to_string()
203}
204
205impl CapabilityManifest {
206 pub fn source_files(&self) -> Result<Vec<PathBuf>> {
218 let mut paths = Vec::new();
219
220 for f in &self.files {
221 let path = contained_source_file(&self.root, f)?;
222 paths.push(path);
223 }
224
225 if self.capability_type == CapabilityType::Tool
226 && let Some(ref imp) = self.implementation
227 {
228 let ep_path = self.root.join(imp.entrypoint.trim_start_matches("./"));
229 if !paths.contains(&ep_path) && ep_path.exists() {
230 paths.push(contained_source_file(&self.root, &imp.entrypoint)?);
231 }
232 }
233
234 Ok(paths)
235 }
236
237 pub fn read_source_contents_with_names(&self) -> Result<Vec<(String, Vec<u8>)>> {
245 let mut installed: Vec<(String, PathBuf, Vec<u8>)> = Vec::new();
246 for p in self.source_files()? {
247 let rel = p
248 .strip_prefix(&self.root)
249 .unwrap_or(&p)
250 .to_string_lossy()
251 .replace('\\', "/");
252 let rel = rel.strip_prefix("src/").unwrap_or(&rel).to_string();
253 if let Some((_, first, _)) = installed.iter().find(|(name, _, _)| *name == rel) {
254 if *first == p {
255 continue;
256 }
257 return Err(TuffError::refused(format!(
258 "capability '{}' lists two files that would install as '{rel}': {} and {}",
259 self.id,
260 first.display(),
261 p.display()
262 ))
263 .with_hint("rename one of them, or list only one"));
264 }
265 let content = std::fs::read(&p)?;
266 installed.push((rel, p, content));
267 }
268 Ok(installed
269 .into_iter()
270 .map(|(rel, _, content)| (rel, content))
271 .collect())
272 }
273}
274
275fn contained_source_file(root: &Path, entry: &str) -> Result<PathBuf> {
282 let trimmed = entry.trim_start_matches("./");
283 let relative = crate::pack::validate_relative_path(Path::new(trimmed)).map_err(|_| {
284 TuffError::refused(format!(
285 "capability source path must stay inside the capability directory: '{entry}'"
286 ))
287 .with_hint("list files by their path relative to tuff.toml, without '..' or a leading '/'")
288 })?;
289 let mut current = root.to_path_buf();
290 for component in relative.components() {
291 current.push(component);
292 match std::fs::symlink_metadata(¤t) {
293 Ok(metadata) if metadata.file_type().is_symlink() => {
294 return Err(TuffError::refused(format!(
295 "symbolic links are not allowed in capability sources: {}",
296 current.display()
297 )));
298 }
299 Ok(_) => {}
300 Err(_) => {
301 return Err(TuffError::not_found(format!(
302 "capability source file not found: {}",
303 root.join(&relative).display()
304 )));
305 }
306 }
307 }
308 if !current.is_file() {
309 return Err(TuffError::usage(format!(
310 "capability source must be a file, not a directory: {}",
311 current.display()
312 )));
313 }
314 Ok(current)
315}
316
317pub fn validate_capability_id(id: &str) -> Result<()> {
332 let plain = !id.is_empty()
333 && id.trim() == id
334 && !id.contains(['\\', '\0'])
335 && id
336 .split('/')
337 .all(|segment| !segment.is_empty() && segment != "." && segment != "..");
338 if plain {
339 return Ok(());
340 }
341 Err(TuffError::refused(format!(
342 "capability id must be a relative path of plain names: '{}'",
343 id.escape_debug()
344 ))
345 .with_hint(
346 "use a name such as 'release-checklist' or 'security/review', without '..', '.', a leading '/', or '\\'",
347 ))
348}
349
350fn validate_non_empty(field: &str, value: &str) -> Result<()> {
351 if value.is_empty() {
352 return Err(TuffError::usage(format!(
353 "capability manifest field '{field}' must be a non-empty string"
354 )));
355 }
356 Ok(())
357}
358
359pub fn load_manifest(capability_dir: &Path) -> Result<CapabilityManifest> {
360 let manifest_path = capability_dir.join("tuff.toml");
361 if !manifest_path.exists() {
362 return Err(TuffError::not_found(format!(
363 "capability manifest not found: {}",
364 manifest_path.display()
365 )));
366 }
367
368 let raw = std::fs::read_to_string(&manifest_path)?;
369 let mut manifest = parse_manifest(&raw, &manifest_path)?;
370 manifest.root = capability_dir.to_path_buf();
371
372 validate_non_empty("id", &manifest.id)?;
373 validate_capability_id(&manifest.id)?;
374 validate_non_empty("version", &manifest.version)?;
375 validate_non_empty("type", &manifest.capability_type.to_string())?;
376 validate_non_empty("description", &manifest.description)?;
377 crate::host::validate(&manifest.x, &manifest_path.display().to_string())?;
378
379 match manifest.capability_type {
380 CapabilityType::Skill => {
381 if manifest.files.is_empty() {
382 return Err(TuffError::usage(
383 "skill capability 'files' must not be empty",
384 ));
385 }
386 manifest.source_files()?;
387 }
388 CapabilityType::Tool => {
389 if manifest.parameters.is_none() {
390 return Err(TuffError::usage(
391 "tool capability requires a [parameters] section with JSON Schema",
392 ));
393 }
394 if manifest.implementation.is_none() {
395 return Err(TuffError::usage(
396 "tool capability requires an [implementation] section",
397 ));
398 }
399
400 let params = manifest.parameters.as_ref().unwrap();
401 crate::tool::validate_json_schema(params)?;
402
403 let impl_cfg = manifest.implementation.as_ref().unwrap();
404 crate::tool::validate_entrypoint(&manifest.root, &impl_cfg.entrypoint)?;
405
406 if !impl_cfg.runtime_deps.is_empty() {
407 eprintln!(
408 "note: this tool requires runtime dependencies: {}",
409 impl_cfg.runtime_deps.join(", ")
410 );
411 }
412
413 if !manifest.files.is_empty() {
414 manifest.source_files()?;
415 }
416 }
417 CapabilityType::Hook => {
418 let hook_cfg = manifest
419 .hook
420 .as_ref()
421 .ok_or_else(|| TuffError::usage("hook capability requires a [hook] section"))?;
422
423 if hook_cfg.event.trim().is_empty() {
424 return Err(TuffError::usage("hook 'event' must be a non-empty string"));
425 }
426 if hook_cfg.command.trim().is_empty() {
427 return Err(TuffError::usage(
428 "hook 'command' must be a non-empty string",
429 ));
430 }
431
432 crate::tool::check_path_traversal(&hook_cfg.working_directory)?;
433
434 eprintln!(
435 "note: this hook runs '{}' on event '{}' — it will not be executed during install",
436 hook_cfg.command, hook_cfg.event
437 );
438
439 if !manifest.files.is_empty() {
440 manifest.source_files()?;
441 }
442 }
443 CapabilityType::Policy => {
444 let policy = manifest.policy.as_ref().ok_or_else(|| {
445 TuffError::usage(
446 "policy capability requires a [policy] section with at least one [[policy.rules]] entry",
447 )
448 })?;
449 crate::policy::validate_policy(policy)?;
450 if !manifest.files.is_empty() {
451 return Err(TuffError::usage(
452 "a policy capability installs no files; remove `files` from its tuff.toml",
453 ));
454 }
455 }
456 CapabilityType::McpServer => {
457 let server = manifest.server.as_ref().ok_or_else(|| {
458 TuffError::usage("mcp-server capability requires a [server] section")
459 })?;
460 validate_mcp_server(server)?;
461
462 if !manifest.files.is_empty() {
463 manifest.source_files()?;
464 }
465 }
466 }
467
468 Ok(manifest)
469}
470
471pub fn validate_mcp_server(server: &McpServerConfig) -> Result<()> {
472 match server.transport {
473 McpTransport::Stdio => {
474 if server
475 .command
476 .as_deref()
477 .is_none_or(|c| c.trim().is_empty())
478 {
479 return Err(TuffError::usage(
480 "mcp-server with transport = \"stdio\" requires a non-empty 'command'",
481 ));
482 }
483 }
484 McpTransport::Http => {
485 if server.url.as_deref().is_none_or(|u| u.trim().is_empty()) {
486 return Err(TuffError::usage(
487 "mcp-server with transport = \"http\" requires a non-empty 'url'",
488 ));
489 }
490 }
491 }
492 for (name, reference) in &server.env {
493 if name.trim().is_empty() {
494 return Err(TuffError::usage("[server.env] keys must be non-empty"));
495 }
496 if reference.from_env.trim().is_empty() {
497 return Err(TuffError::usage(format!(
498 "[server.env] {name} must reference a variable: {name} = {{ from_env = \"VAR\" }}"
499 )));
500 }
501 }
502 validate_mcp_headers(server)?;
503 Ok(())
504}
505
506fn validate_mcp_headers(server: &McpServerConfig) -> Result<()> {
510 if !server.headers.is_empty() && server.transport != McpTransport::Http {
511 return Err(TuffError::usage(
512 "[server.headers] applies to transport = \"http\"; a stdio server passes \
513 secrets through [server.env]",
514 ));
515 }
516 for (name, reference) in &server.headers {
517 if name.trim().is_empty() {
518 return Err(TuffError::usage("[server.headers] keys must be non-empty"));
519 }
520 if reference.from_env.trim().is_empty() {
521 return Err(TuffError::usage(format!(
522 "[server.headers] {name} must reference a variable: \
523 {name} = {{ from_env = \"VAR\" }}"
524 )));
525 }
526 if let Some(format) = &reference.format {
527 let placeholders = format.matches(FORMAT_PLACEHOLDER).count();
528 if placeholders != 1 {
529 let problem = if placeholders == 0 {
530 "would discard the value"
531 } else {
532 "would repeat the value"
533 };
534 return Err(TuffError::usage(format!(
535 "[server.headers] {name}: format \"{format}\" {problem}"
536 ))
537 .with_hint("format must contain exactly one {} placeholder, as in \"Bearer {}\""));
538 }
539 }
540 }
541 Ok(())
542}
543
544fn parse_manifest(raw: &str, manifest_path: &Path) -> Result<CapabilityManifest> {
548 toml::from_str(raw).map_err(|error: toml::de::Error| {
549 let message = error.to_string();
550 let looks_literal =
551 message.contains("invalid type: string") || message.contains("expected a table");
552 let literal_table = looks_literal
553 .then(|| {
554 ["[server.env]", "[server.headers]"]
555 .into_iter()
556 .find(|table| raw.contains(table))
557 })
558 .flatten();
559 if let Some(table) = literal_table {
560 let example = if table == "[server.headers]" {
561 "Authorization = { from_env = \"TOKEN\", format = \"Bearer {}\" }"
562 } else {
563 "NAME = { from_env = \"NAME\" }"
564 };
565 TuffError::usage(format!(
566 "invalid manifest at {}: {} values must be references, never \
567 literals — write {} ({})",
568 manifest_path.display(),
569 table,
570 example,
571 message.trim()
572 ))
573 } else if message.contains("unknown variant `workflow`") {
574 TuffError::usage(format!(
575 "invalid manifest at {}: Tuff no longer has workflow capabilities",
576 manifest_path.display()
577 ))
578 .with_hint("install the skills, tools, and hooks the workflow listed on their own, or group them in a pack")
579 } else {
580 TuffError::from(error)
581 }
582 })
583}
584
585pub fn write_manifest(path: &Path, manifest: &CapabilityManifest) -> Result<()> {
591 std::fs::write(path, toml::to_string_pretty(manifest)?)?;
592 Ok(())
593}
594
595pub fn declared_version(dir: &Path) -> Option<String> {
601 if dir.join("tuff.toml").is_file() {
602 return load_manifest(dir).ok().map(|manifest| manifest.version);
603 }
604 let skill = std::fs::read_to_string(dir.join("SKILL.md")).ok()?;
605 frontmatter_version(&skill)
606}
607
608pub fn frontmatter_version(skill: &str) -> Option<String> {
613 let mut lines = skill.lines().map(|line| line.trim_end_matches('\r'));
614 if lines.next()?.trim() != "---" {
615 return None;
616 }
617 let mut in_metadata = false;
618 let mut nested = None;
619 for line in lines {
620 if line.trim() == "---" {
621 break;
622 }
623 let indented = line.starts_with([' ', '\t']);
624 if !indented {
625 in_metadata = line.trim_end() == "metadata:";
626 if let Some(value) = line.strip_prefix("version:") {
627 return frontmatter_scalar(value);
628 }
629 continue;
630 }
631 if in_metadata
632 && nested.is_none()
633 && let Some(value) = line.trim_start().strip_prefix("version:")
634 {
635 nested = frontmatter_scalar(value);
636 }
637 }
638 nested
639}
640
641pub fn declared_description(dir: &Path) -> Option<String> {
648 if dir.join("tuff.toml").is_file() {
649 return load_manifest(dir).ok().map(|manifest| manifest.description);
650 }
651 let skill = std::fs::read_to_string(dir.join("SKILL.md")).ok()?;
652 frontmatter_description(&skill)
653}
654
655pub fn frontmatter_description(skill: &str) -> Option<String> {
661 let mut lines = skill.lines().map(|line| line.trim_end_matches('\r'));
662 if lines.next()?.trim() != "---" {
663 return None;
664 }
665 for line in lines {
666 if line.trim() == "---" {
667 break;
668 }
669 if line.starts_with([' ', '\t']) {
670 continue;
671 }
672 if let Some(value) = line.strip_prefix("description:") {
673 return frontmatter_text(value);
674 }
675 }
676 None
677}
678
679pub fn frontmatter_name(skill: &str) -> Option<String> {
682 let mut lines = skill.lines().map(|line| line.trim_end_matches('\r'));
683 if lines.next()?.trim() != "---" {
684 return None;
685 }
686 for line in lines {
687 if line.trim() == "---" {
688 break;
689 }
690 if line.starts_with([' ', '\t']) {
691 continue;
692 }
693 if let Some(value) = line.strip_prefix("name:") {
694 return frontmatter_scalar(value);
695 }
696 }
697 None
698}
699
700fn frontmatter_text(value: &str) -> Option<String> {
702 let value = value.trim();
703 let value = value
704 .strip_prefix('"')
705 .and_then(|rest| rest.strip_suffix('"'))
706 .or_else(|| {
707 value
708 .strip_prefix('\'')
709 .and_then(|rest| rest.strip_suffix('\''))
710 })
711 .unwrap_or(value)
712 .trim();
713 if value.is_empty() || value.starts_with(['>', '|']) {
715 return None;
716 }
717 Some(value.to_string())
718}
719
720fn frontmatter_scalar(value: &str) -> Option<String> {
721 let value = value.trim();
722 let value = value
723 .strip_prefix('"')
724 .and_then(|rest| rest.strip_suffix('"'))
725 .or_else(|| {
726 value
727 .strip_prefix('\'')
728 .and_then(|rest| rest.strip_suffix('\''))
729 })
730 .unwrap_or(value)
731 .trim();
732 (!value.is_empty() && !value.contains(char::is_whitespace)).then(|| value.to_string())
733}
734
735pub fn synthetic_manifest(
736 skill_dir: &Path,
737 name: &str,
738 version: &str,
739) -> Result<CapabilityManifest> {
740 validate_capability_id(name)?;
741 let skill_file = skill_dir.join("SKILL.md");
742 if !skill_file.exists() {
743 return Err(TuffError::not_found(format!(
744 "skill entrypoint not found: {}",
745 skill_file.display()
746 )));
747 }
748 let mut files = Vec::new();
749 walk_skill_dir(skill_dir, "", &mut files)?;
750 files.sort();
751
752 Ok(CapabilityManifest {
753 id: name.to_string(),
754 version: version.to_string(),
755 capability_type: CapabilityType::Skill,
756 description: "Installed from git source.".to_string(),
757 files,
758 parameters: None,
759 implementation: None,
760 hook: None,
761 server: None,
762 policy: None,
763 targets: Vec::new(),
764 x: Default::default(),
765 root: skill_dir.to_path_buf(),
766 })
767}
768
769fn walk_skill_dir(base: &Path, prefix: &str, files: &mut Vec<String>) -> Result<()> {
770 for entry in std::fs::read_dir(base)? {
771 let entry = entry?;
772 let path = entry.path();
773 let metadata = std::fs::symlink_metadata(&path)?;
774 if metadata.file_type().is_symlink() {
775 return Err(TuffError::refused(format!(
776 "symbolic links are not allowed in capability sources: {}",
777 path.display()
778 )));
779 }
780 let rel = if prefix.is_empty() {
781 entry.file_name().to_string_lossy().to_string()
782 } else {
783 format!("{}/{}", prefix, entry.file_name().to_string_lossy())
784 };
785 if metadata.is_dir() {
786 walk_skill_dir(&path, &rel, files)?;
787 } else if metadata.is_file() && rel != "tuff.toml" {
788 files.push(rel);
789 }
790 }
791 Ok(())
792}
793
794#[cfg(test)]
795mod tests {
796 use super::*;
797 use std::fs;
798 use tempfile::TempDir;
799
800 fn write_manifest(dir: &std::path::Path, content: &str) {
801 fs::write(dir.join("tuff.toml"), content).unwrap();
802 }
803
804 #[test]
805 fn frontmatter_name_reads_the_top_level_name_only() {
806 assert_eq!(
807 frontmatter_name("---\nname: pdf\ndescription: x\n---\n").as_deref(),
808 Some("pdf")
809 );
810 assert_eq!(
811 frontmatter_name("---\nname: \"quoted\"\n---\n").as_deref(),
812 Some("quoted")
813 );
814 assert_eq!(
815 frontmatter_name("---\nmetadata:\n name: nested\n---\n"),
816 None
817 );
818 assert_eq!(frontmatter_name("# no frontmatter\nname: x\n"), None);
819 }
820
821 #[test]
822 fn frontmatter_version_reads_top_level_then_metadata() {
823 assert_eq!(
824 frontmatter_version("---\nname: x\nversion: 1.2.0\n---\n# X\n").as_deref(),
825 Some("1.2.0")
826 );
827 assert_eq!(
828 frontmatter_version("---\nname: x\nversion: \"1.2.0\"\n---\n").as_deref(),
829 Some("1.2.0")
830 );
831 assert_eq!(
833 frontmatter_version(
834 "---\nname: x\nmetadata:\n author: org\n version: \"1.0\"\n---\n"
835 )
836 .as_deref(),
837 Some("1.0")
838 );
839 assert_eq!(
841 frontmatter_version("---\nmetadata:\n version: 0.9.0\nversion: 1.2.0\n---\n")
842 .as_deref(),
843 Some("1.2.0")
844 );
845 assert_eq!(
847 frontmatter_version("---\nname: x\nextra:\n version: 3.0.0\n---\n"),
848 None
849 );
850 assert_eq!(
851 frontmatter_version("# no frontmatter\nversion: 1.0.0\n"),
852 None
853 );
854 assert_eq!(
855 frontmatter_version("---\nname: x\n---\nversion: 9.9.9\n"),
856 None
857 );
858 assert_eq!(frontmatter_version("---\nversion:\n---\n"), None);
859 assert_eq!(frontmatter_version("---\nversion: 1.2.0 beta\n---\n"), None);
860 assert_eq!(
861 frontmatter_version("---\r\nname: x\r\nversion: 2.0.0\r\n---\r\n").as_deref(),
862 Some("2.0.0")
863 );
864 }
865
866 #[test]
867 fn declared_description_reads_the_frontmatter_and_prefers_the_manifest() {
868 let tmp = TempDir::new().unwrap();
869 fs::write(
870 tmp.path().join("SKILL.md"),
871 "---\nname: x\ndescription: Reviews a diff for security problems.\n---\n# X\n",
872 )
873 .unwrap();
874 assert_eq!(
875 declared_description(tmp.path()).as_deref(),
876 Some("Reviews a diff for security problems.")
877 );
878
879 write_manifest(
880 tmp.path(),
881 r#"id = "x"
882version = "1.0.0"
883type = "skill"
884description = "From the manifest"
885files = ["SKILL.md"]
886"#,
887 );
888 assert_eq!(
889 declared_description(tmp.path()).as_deref(),
890 Some("From the manifest")
891 );
892 }
893
894 #[test]
895 fn a_multi_line_description_is_left_alone_rather_than_half_read() {
896 assert_eq!(
899 frontmatter_description("---\nname: x\ndescription: >\n Long text here.\n---\n"),
900 None
901 );
902 assert_eq!(
905 frontmatter_description("---\nmetadata:\n description: Nested.\n---\n"),
906 None
907 );
908 assert_eq!(frontmatter_description("# Just a heading\n"), None);
910 }
911
912 #[test]
913 fn declared_version_prefers_the_manifest_over_the_frontmatter() {
914 let tmp = TempDir::new().unwrap();
915 fs::write(
916 tmp.path().join("SKILL.md"),
917 "---\nname: x\nversion: 2.0.0\n---\n# X\n",
918 )
919 .unwrap();
920 assert_eq!(declared_version(tmp.path()).as_deref(), Some("2.0.0"));
921 fs::write(
922 tmp.path().join("tuff.toml"),
923 "id = \"x\"\nversion = \"1.0.0\"\ntype = \"skill\"\ndescription = \"d\"\nfiles = [\"SKILL.md\"]\n",
924 )
925 .unwrap();
926 assert_eq!(declared_version(tmp.path()).as_deref(), Some("1.0.0"));
927
928 let bare = TempDir::new().unwrap();
929 fs::write(bare.path().join("SKILL.md"), "# no version\n").unwrap();
930 assert_eq!(declared_version(bare.path()), None);
931 }
932
933 #[test]
934 fn load_skill_manifest_succeeds() {
935 let tmp = TempDir::new().unwrap();
936 fs::create_dir_all(tmp.path().join("src")).unwrap();
937 fs::write(tmp.path().join("src").join("SKILL.md"), "# Skill").unwrap();
938 write_manifest(
939 tmp.path(),
940 r#"id = "test"
941version = "1.0.0"
942type = "skill"
943description = "A test skill"
944files = ["src/SKILL.md"]
945"#,
946 );
947 let m = load_manifest(tmp.path()).unwrap();
948 assert_eq!(m.id, "test");
949 assert_eq!(m.capability_type, CapabilityType::Skill);
950 }
951
952 #[test]
953 fn load_tool_manifest_succeeds() {
954 let tmp = TempDir::new().unwrap();
955 fs::write(tmp.path().join("run.sh"), "echo ok").unwrap();
956 write_manifest(
957 tmp.path(),
958 r#"id = "tool1"
959version = "1.0.0"
960type = "tool"
961description = "A test tool"
962files = ["run.sh"]
963
964[parameters]
965type = "object"
966required = ["x"]
967[parameters.properties.x]
968type = "string"
969description = "x"
970
971[implementation]
972language = "bash"
973entrypoint = "run.sh"
974"#,
975 );
976 let m = load_manifest(tmp.path()).unwrap();
977 assert_eq!(m.capability_type, CapabilityType::Tool);
978 assert!(m.implementation.is_some());
979 }
980
981 #[test]
982 fn load_hook_manifest_succeeds() {
983 let tmp = TempDir::new().unwrap();
984 write_manifest(
985 tmp.path(),
986 r#"id = "hook1"
987version = "1.0.0"
988type = "hook"
989description = "A test hook"
990
991[hook]
992event = "before_finish"
993command = "cargo test"
994"#,
995 );
996 let m = load_manifest(tmp.path()).unwrap();
997 assert_eq!(m.capability_type, CapabilityType::Hook);
998 assert!(m.hook.is_some());
999 }
1000
1001 #[test]
1002 fn load_rejects_unsupported_type() {
1003 let tmp = TempDir::new().unwrap();
1004 write_manifest(
1005 tmp.path(),
1006 r#"id = "bad"
1007version = "1.0.0"
1008type = "unknown"
1009description = "Bad"
1010files = ["SKILL.md"]
1011"#,
1012 );
1013 assert!(load_manifest(tmp.path()).is_err());
1014 }
1015
1016 #[test]
1017 fn load_rejects_missing_manifest() {
1018 let tmp = TempDir::new().unwrap();
1019 assert!(load_manifest(tmp.path()).is_err());
1020 }
1021
1022 #[test]
1023 fn source_files_resolves_paths() {
1024 let tmp = TempDir::new().unwrap();
1025 fs::create_dir_all(tmp.path().join("src")).unwrap();
1026 fs::write(tmp.path().join("src").join("SKILL.md"), "skill").unwrap();
1027 let m = CapabilityManifest {
1028 id: "t".into(),
1029 version: "1.0".into(),
1030 capability_type: CapabilityType::Skill,
1031 description: "desc".into(),
1032 files: vec!["src/SKILL.md".into()],
1033 parameters: None,
1034 implementation: None,
1035 hook: None,
1036 server: None,
1037 policy: None,
1038 targets: vec![],
1039 x: Default::default(),
1040 root: tmp.path().to_path_buf(),
1041 };
1042 let files = m.source_files().unwrap();
1043 assert_eq!(files.len(), 1);
1044 assert!(files[0].ends_with("SKILL.md"));
1045 }
1046
1047 fn manifest_listing(root: &Path, files: &[&str]) -> CapabilityManifest {
1048 CapabilityManifest {
1049 id: "t".into(),
1050 version: "1.0".into(),
1051 capability_type: CapabilityType::Hook,
1052 description: "desc".into(),
1053 files: files.iter().map(|f| f.to_string()).collect(),
1054 parameters: None,
1055 implementation: None,
1056 hook: None,
1057 server: None,
1058 policy: None,
1059 targets: vec![],
1060 x: Default::default(),
1061 root: root.to_path_buf(),
1062 }
1063 }
1064
1065 #[test]
1066 fn source_files_refuse_a_path_that_climbs_out_of_the_capability() {
1067 let tmp = TempDir::new().unwrap();
1072 let capability = tmp.path().join("capability");
1073 fs::create_dir_all(&capability).unwrap();
1074 fs::write(tmp.path().join("outside.txt"), "outside").unwrap();
1075 fs::write(capability.join("inside.txt"), "inside").unwrap();
1076
1077 for entry in [
1078 "../outside.txt",
1079 "sub/../../outside.txt",
1080 "./../outside.txt",
1081 ] {
1082 let error = manifest_listing(&capability, &["inside.txt", entry])
1083 .source_files()
1084 .unwrap_err();
1085 assert_eq!(error.kind(), crate::error::ErrorKind::Refused, "{entry}");
1086 assert!(
1087 error
1088 .to_string()
1089 .contains("must stay inside the capability directory"),
1090 "{entry}: {error}"
1091 );
1092 }
1093 let absolute = tmp.path().join("outside.txt");
1094 let error = manifest_listing(&capability, &[absolute.to_str().unwrap()])
1095 .source_files()
1096 .unwrap_err();
1097 assert_eq!(error.kind(), crate::error::ErrorKind::Refused);
1098 }
1099
1100 #[cfg(unix)]
1101 #[test]
1102 fn source_files_refuse_a_symbolic_link_anywhere_along_the_path() {
1103 let tmp = TempDir::new().unwrap();
1104 let capability = tmp.path().join("capability");
1105 let secrets = tmp.path().join("secrets");
1106 fs::create_dir_all(capability.join("docs")).unwrap();
1107 fs::create_dir_all(&secrets).unwrap();
1108 fs::write(secrets.join("key.txt"), "pretend secret").unwrap();
1109 std::os::unix::fs::symlink(secrets.join("key.txt"), capability.join("notes.md")).unwrap();
1110 std::os::unix::fs::symlink(&secrets, capability.join("docs").join("linked")).unwrap();
1111
1112 for entry in ["notes.md", "docs/linked/key.txt"] {
1113 let error = manifest_listing(&capability, &[entry])
1114 .source_files()
1115 .unwrap_err();
1116 assert_eq!(error.kind(), crate::error::ErrorKind::Refused, "{entry}");
1117 assert!(
1118 error.to_string().contains("symbolic links are not allowed"),
1119 "{entry}: {error}"
1120 );
1121 }
1122 }
1123
1124 #[test]
1125 fn source_files_accept_plain_nested_and_dot_slash_paths() {
1126 let tmp = TempDir::new().unwrap();
1127 fs::create_dir_all(tmp.path().join("src/lib")).unwrap();
1128 fs::write(tmp.path().join("src/lib/check.sh"), "x").unwrap();
1129 fs::write(tmp.path().join("run.sh"), "x").unwrap();
1130
1131 let files = manifest_listing(tmp.path(), &["./run.sh", "src/lib/check.sh"])
1132 .source_files()
1133 .unwrap();
1134 assert_eq!(
1135 files,
1136 vec![
1137 tmp.path().join("run.sh"),
1138 tmp.path().join("src/lib/check.sh")
1139 ]
1140 );
1141 let error = manifest_listing(tmp.path(), &["src"])
1142 .source_files()
1143 .unwrap_err();
1144 assert!(error.to_string().contains("must be a file"), "{error}");
1145 }
1146
1147 #[test]
1148 fn listed_files_that_install_to_the_same_path_are_refused_but_a_repeat_is_not() {
1149 let tmp = TempDir::new().unwrap();
1150 fs::create_dir_all(tmp.path().join("src")).unwrap();
1151 fs::write(tmp.path().join("check.sh"), "top").unwrap();
1152 fs::write(tmp.path().join("src/check.sh"), "src").unwrap();
1153
1154 let repeated = manifest_listing(tmp.path(), &["check.sh", "./check.sh", "check.sh"])
1155 .read_source_contents_with_names()
1156 .unwrap();
1157 assert_eq!(repeated, vec![("check.sh".to_string(), b"top".to_vec())]);
1158
1159 let error = manifest_listing(tmp.path(), &["check.sh", "src/check.sh"])
1160 .read_source_contents_with_names()
1161 .unwrap_err();
1162 assert_eq!(error.kind(), crate::error::ErrorKind::Refused);
1163 assert!(
1164 error.to_string().contains("would install as 'check.sh'"),
1165 "{error}"
1166 );
1167 }
1168
1169 #[test]
1170 fn source_files_rejects_missing_file() {
1171 let tmp = TempDir::new().unwrap();
1172 let m = CapabilityManifest {
1173 id: "t".into(),
1174 version: "1.0".into(),
1175 capability_type: CapabilityType::Skill,
1176 description: "desc".into(),
1177 files: vec!["src/MISSING.md".into()],
1178 parameters: None,
1179 implementation: None,
1180 hook: None,
1181 server: None,
1182 policy: None,
1183 targets: vec![],
1184 x: Default::default(),
1185 root: tmp.path().to_path_buf(),
1186 };
1187 assert!(m.source_files().is_err());
1188 }
1189
1190 #[test]
1191 fn a_capability_id_is_a_relative_path_of_plain_names() {
1192 for id in [
1195 "release-checklist",
1196 "tuff-cli-guide",
1197 "a.b",
1198 "x_1",
1199 "...x",
1200 "security/security-review",
1201 "a/b/c",
1202 ] {
1203 assert!(validate_capability_id(id).is_ok(), "{id}");
1204 }
1205 for id in [
1206 "",
1207 ".",
1208 "..",
1209 "../victim",
1210 "../../victim",
1211 "a/../b",
1212 "a/..",
1213 "./a",
1214 "a/./b",
1215 "/abs",
1216 "a/",
1217 "a//b",
1218 "a\\b",
1219 "nul\0x",
1220 " padded",
1221 "padded ",
1222 ] {
1223 let error = validate_capability_id(id).unwrap_err();
1224 assert_eq!(error.kind(), crate::error::ErrorKind::Refused, "{id:?}");
1225 }
1226 }
1227
1228 #[test]
1229 fn a_manifest_with_an_escaping_id_is_refused_at_load() {
1230 let tmp = TempDir::new().unwrap();
1231 fs::write(
1232 tmp.path().join("tuff.toml"),
1233 "id = \"../../victim\"\ntype = \"hook\"\nversion = \"1.0.0\"\ndescription = \"d\"\n[hook]\nevent = \"stop\"\ncommand = \"true\"\n",
1234 )
1235 .unwrap();
1236 let error = load_manifest(tmp.path()).unwrap_err();
1237 assert!(
1238 error.to_string().contains("relative path of plain names"),
1239 "{error}"
1240 );
1241 }
1242
1243 #[test]
1244 fn a_policy_manifest_loads_and_refuses_files() {
1245 let tmp = TempDir::new().unwrap();
1246 let head = "id = \"guard\"\ntype = \"policy\"\nversion = \"1.0.0\"\ndescription = \"d\"\n";
1247 let rules =
1248 "[[policy.rules]]\neffect = \"deny\"\ncommand = [\"git\", \"push\", \"--force\"]\n";
1249 fs::write(tmp.path().join("tuff.toml"), format!("{head}{rules}")).unwrap();
1250 let manifest = load_manifest(tmp.path()).unwrap();
1251 assert_eq!(manifest.policy.unwrap().rules.len(), 1);
1252
1253 fs::write(tmp.path().join("tuff.toml"), head).unwrap();
1254 let error = load_manifest(tmp.path()).unwrap_err();
1255 assert!(
1256 error.to_string().contains("requires a [policy] section"),
1257 "{error}"
1258 );
1259
1260 fs::write(tmp.path().join("x.sh"), "x").unwrap();
1261 fs::write(
1262 tmp.path().join("tuff.toml"),
1263 format!("{head}files = [\"x.sh\"]\n{rules}"),
1264 )
1265 .unwrap();
1266 let error = load_manifest(tmp.path()).unwrap_err();
1267 assert!(error.to_string().contains("installs no files"), "{error}");
1268 }
1269
1270 #[test]
1271 fn validate_non_empty_rejects_empty() {
1272 assert!(validate_non_empty("id", "").is_err());
1273 assert!(validate_non_empty("id", "ok").is_ok());
1274 }
1275
1276 fn load_mcp(toml_body: &str) -> Result<CapabilityManifest> {
1277 let tmp = TempDir::new().unwrap();
1278 fs::write(tmp.path().join("tuff.toml"), toml_body).unwrap();
1279 load_manifest(tmp.path())
1280 }
1281
1282 const MCP_HEAD: &str =
1283 "id = \"srv\"\nversion = \"1.0.0\"\ntype = \"mcp-server\"\ndescription = \"d\"\n";
1284
1285 #[test]
1286 fn mcp_server_requires_server_section() {
1287 let error = load_mcp(MCP_HEAD).unwrap_err().to_string();
1288 assert!(error.contains("requires a [server] section"), "{error}");
1289 }
1290
1291 #[test]
1292 fn mcp_server_stdio_requires_command_and_http_requires_url() {
1293 let error = load_mcp(&format!("{MCP_HEAD}[server]\ntransport = \"stdio\"\n"))
1294 .unwrap_err()
1295 .to_string();
1296 assert!(error.contains("requires a non-empty 'command'"), "{error}");
1297 let error = load_mcp(&format!("{MCP_HEAD}[server]\ntransport = \"http\"\n"))
1298 .unwrap_err()
1299 .to_string();
1300 assert!(error.contains("requires a non-empty 'url'"), "{error}");
1301 let ok = load_mcp(&format!(
1302 "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n"
1303 ))
1304 .unwrap();
1305 assert_eq!(ok.server.unwrap().transport, McpTransport::Http);
1306 }
1307
1308 #[test]
1309 fn mcp_server_env_must_be_a_reference_not_a_literal() {
1310 let error = load_mcp(&format!(
1311 "{MCP_HEAD}[server]\ncommand = \"npx\"\n[server.env]\nTOKEN = \"literal\"\n"
1312 ))
1313 .unwrap_err()
1314 .to_string();
1315 assert!(error.contains("from_env"), "{error}");
1316
1317 let ok = load_mcp(&format!(
1318 "{MCP_HEAD}[server]\ncommand = \"npx\"\n[server.env]\nTOKEN = {{ from_env = \"MY_TOKEN\" }}\n"
1319 ))
1320 .unwrap();
1321 assert_eq!(ok.server.unwrap().env["TOKEN"].from_env, "MY_TOKEN");
1322 }
1323
1324 #[test]
1325 fn mcp_server_headers_must_be_references_not_literals() {
1326 let error = load_mcp(&format!(
1327 "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
1328 [server.headers]\nAuthorization = \"Bearer secret\"\n"
1329 ))
1330 .unwrap_err()
1331 .to_string();
1332 assert!(error.contains("[server.headers]"), "{error}");
1333 assert!(error.contains("from_env"), "{error}");
1334 }
1335
1336 #[test]
1337 fn mcp_server_header_reference_carries_an_optional_format() {
1338 let server = load_mcp(&format!(
1339 "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
1340 [server.headers]\n\
1341 Authorization = {{ from_env = \"NOTION_TOKEN\", format = \"Bearer {{}}\" }}\n\
1342 X-Api-Key = {{ from_env = \"API_KEY\" }}\n"
1343 ))
1344 .unwrap()
1345 .server
1346 .unwrap();
1347 assert_eq!(server.headers["Authorization"].from_env, "NOTION_TOKEN");
1348 assert_eq!(
1349 server.headers["Authorization"].render("${NOTION_TOKEN}"),
1350 "Bearer ${NOTION_TOKEN}"
1351 );
1352 assert_eq!(server.headers["X-Api-Key"].format, None);
1353 assert_eq!(
1354 server.headers["X-Api-Key"].render("${API_KEY}"),
1355 "${API_KEY}"
1356 );
1357 }
1358
1359 #[test]
1360 fn mcp_server_header_format_needs_exactly_one_placeholder() {
1361 for format in ["Bearer", "Bearer {} {}"] {
1362 let error = load_mcp(&format!(
1363 "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
1364 [server.headers]\n\
1365 Authorization = {{ from_env = \"TOKEN\", format = \"{format}\" }}\n"
1366 ))
1367 .unwrap_err()
1368 .to_string();
1369 assert!(error.contains("Authorization"), "{format}: {error}");
1370 }
1371 }
1372
1373 #[test]
1374 fn mcp_server_headers_are_refused_on_stdio() {
1375 let error = load_mcp(&format!(
1376 "{MCP_HEAD}[server]\ncommand = \"npx\"\n\
1377 [server.headers]\nAuthorization = {{ from_env = \"TOKEN\" }}\n"
1378 ))
1379 .unwrap_err()
1380 .to_string();
1381 assert!(error.contains("http"), "{error}");
1382 }
1383
1384 #[test]
1387 fn a_server_without_headers_serializes_without_the_table() {
1388 let server = load_mcp(&format!("{MCP_HEAD}[server]\ncommand = \"npx\"\n"))
1389 .unwrap()
1390 .server
1391 .unwrap();
1392 let wire = toml::to_string_pretty(&server).unwrap();
1393 assert!(!wire.contains("headers"), "{wire}");
1394 }
1395
1396 #[test]
1397 fn capability_type_round_trips_the_hyphenated_name() {
1398 assert_eq!(CapabilityType::McpServer.as_str(), "mcp-server");
1399 assert_eq!(
1400 CapabilityType::parse("mcp-server"),
1401 Some(CapabilityType::McpServer)
1402 );
1403 assert_eq!(
1404 CapabilityType::parse("mcp"),
1405 Some(CapabilityType::McpServer)
1406 );
1407 #[derive(serde::Serialize)]
1408 struct Wire {
1409 #[serde(rename = "type")]
1410 capability_type: CapabilityType,
1411 }
1412 let wire = toml::to_string(&Wire {
1413 capability_type: CapabilityType::McpServer,
1414 })
1415 .unwrap();
1416 assert!(wire.contains("type = \"mcp-server\""), "{wire}");
1417 assert_eq!(CapabilityType::parse("workflow"), None);
1418 }
1419}