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 !manifest.files.is_empty() {
407 manifest.source_files()?;
408 }
409 }
410 CapabilityType::Hook => {
411 let hook_cfg = manifest
412 .hook
413 .as_ref()
414 .ok_or_else(|| TuffError::usage("hook capability requires a [hook] section"))?;
415
416 if hook_cfg.event.trim().is_empty() {
417 return Err(TuffError::usage("hook 'event' must be a non-empty string"));
418 }
419 if hook_cfg.command.trim().is_empty() {
420 return Err(TuffError::usage(
421 "hook 'command' must be a non-empty string",
422 ));
423 }
424
425 crate::tool::check_path_traversal(&hook_cfg.working_directory)?;
426
427 if !manifest.files.is_empty() {
428 manifest.source_files()?;
429 }
430 }
431 CapabilityType::Policy => {
432 let policy = manifest.policy.as_ref().ok_or_else(|| {
433 TuffError::usage(
434 "policy capability requires a [policy] section with at least one [[policy.rules]] entry",
435 )
436 })?;
437 crate::policy::validate_policy(policy)?;
438 if !manifest.files.is_empty() {
439 return Err(TuffError::usage(
440 "a policy capability installs no files; remove `files` from its tuff.toml",
441 ));
442 }
443 }
444 CapabilityType::McpServer => {
445 let server = manifest.server.as_ref().ok_or_else(|| {
446 TuffError::usage("mcp-server capability requires a [server] section")
447 })?;
448 validate_mcp_server(server)?;
449
450 if !manifest.files.is_empty() {
451 manifest.source_files()?;
452 }
453 }
454 }
455
456 Ok(manifest)
457}
458
459pub fn install_notes(manifest: &CapabilityManifest) -> Vec<String> {
463 let mut notes = Vec::new();
464 if let Some(implementation) = &manifest.implementation
465 && manifest.capability_type == CapabilityType::Tool
466 && !implementation.runtime_deps.is_empty()
467 {
468 notes.push(format!(
469 "this tool requires runtime dependencies: {}",
470 implementation.runtime_deps.join(", ")
471 ));
472 }
473 if let Some(hook) = &manifest.hook
474 && manifest.capability_type == CapabilityType::Hook
475 {
476 notes.push(format!(
477 "this hook runs '{}' on event '{}' — it will not be executed during install",
478 hook.command, hook.event
479 ));
480 }
481 notes
482}
483
484pub fn validate_mcp_server(server: &McpServerConfig) -> Result<()> {
485 match server.transport {
486 McpTransport::Stdio => {
487 if server
488 .command
489 .as_deref()
490 .is_none_or(|c| c.trim().is_empty())
491 {
492 return Err(TuffError::usage(
493 "mcp-server with transport = \"stdio\" requires a non-empty 'command'",
494 ));
495 }
496 }
497 McpTransport::Http => {
498 if server.url.as_deref().is_none_or(|u| u.trim().is_empty()) {
499 return Err(TuffError::usage(
500 "mcp-server with transport = \"http\" requires a non-empty 'url'",
501 ));
502 }
503 }
504 }
505 for (name, reference) in &server.env {
506 if name.trim().is_empty() {
507 return Err(TuffError::usage("[server.env] keys must be non-empty"));
508 }
509 if reference.from_env.trim().is_empty() {
510 return Err(TuffError::usage(format!(
511 "[server.env] {name} must reference a variable: {name} = {{ from_env = \"VAR\" }}"
512 )));
513 }
514 }
515 validate_mcp_headers(server)?;
516 Ok(())
517}
518
519fn validate_mcp_headers(server: &McpServerConfig) -> Result<()> {
523 if !server.headers.is_empty() && server.transport != McpTransport::Http {
524 return Err(TuffError::usage(
525 "[server.headers] applies to transport = \"http\"; a stdio server passes \
526 secrets through [server.env]",
527 ));
528 }
529 for (name, reference) in &server.headers {
530 if name.trim().is_empty() {
531 return Err(TuffError::usage("[server.headers] keys must be non-empty"));
532 }
533 if reference.from_env.trim().is_empty() {
534 return Err(TuffError::usage(format!(
535 "[server.headers] {name} must reference a variable: \
536 {name} = {{ from_env = \"VAR\" }}"
537 )));
538 }
539 if let Some(format) = &reference.format {
540 let placeholders = format.matches(FORMAT_PLACEHOLDER).count();
541 if placeholders != 1 {
542 let problem = if placeholders == 0 {
543 "would discard the value"
544 } else {
545 "would repeat the value"
546 };
547 return Err(TuffError::usage(format!(
548 "[server.headers] {name}: format \"{format}\" {problem}"
549 ))
550 .with_hint("format must contain exactly one {} placeholder, as in \"Bearer {}\""));
551 }
552 }
553 }
554 Ok(())
555}
556
557fn parse_manifest(raw: &str, manifest_path: &Path) -> Result<CapabilityManifest> {
561 toml::from_str(raw).map_err(|error: toml::de::Error| {
562 let message = error.to_string();
563 let looks_literal =
564 message.contains("invalid type: string") || message.contains("expected a table");
565 let literal_table = looks_literal
566 .then(|| {
567 ["[server.env]", "[server.headers]"]
568 .into_iter()
569 .find(|table| raw.contains(table))
570 })
571 .flatten();
572 if let Some(table) = literal_table {
573 let example = if table == "[server.headers]" {
574 "Authorization = { from_env = \"TOKEN\", format = \"Bearer {}\" }"
575 } else {
576 "NAME = { from_env = \"NAME\" }"
577 };
578 TuffError::usage(format!(
579 "invalid manifest at {}: {} values must be references, never \
580 literals — write {} ({})",
581 manifest_path.display(),
582 table,
583 example,
584 message.trim()
585 ))
586 } else if message.contains("unknown variant `workflow`") {
587 TuffError::usage(format!(
588 "invalid manifest at {}: Tuff no longer has workflow capabilities",
589 manifest_path.display()
590 ))
591 .with_hint("install the skills, tools, and hooks the workflow listed on their own, or group them in a pack")
592 } else {
593 TuffError::from(error)
594 }
595 })
596}
597
598pub fn write_manifest(path: &Path, manifest: &CapabilityManifest) -> Result<()> {
604 std::fs::write(path, toml::to_string_pretty(manifest)?)?;
605 Ok(())
606}
607
608pub fn declared_version(dir: &Path) -> Option<String> {
614 if dir.join("tuff.toml").is_file() {
615 return load_manifest(dir).ok().map(|manifest| manifest.version);
616 }
617 let skill = std::fs::read_to_string(dir.join("SKILL.md")).ok()?;
618 frontmatter_version(&skill)
619}
620
621pub fn frontmatter_version(skill: &str) -> Option<String> {
626 let mut lines = skill.lines().map(|line| line.trim_end_matches('\r'));
627 if lines.next()?.trim() != "---" {
628 return None;
629 }
630 let mut in_metadata = false;
631 let mut nested = None;
632 for line in lines {
633 if line.trim() == "---" {
634 break;
635 }
636 let indented = line.starts_with([' ', '\t']);
637 if !indented {
638 in_metadata = line.trim_end() == "metadata:";
639 if let Some(value) = line.strip_prefix("version:") {
640 return frontmatter_scalar(value);
641 }
642 continue;
643 }
644 if in_metadata
645 && nested.is_none()
646 && let Some(value) = line.trim_start().strip_prefix("version:")
647 {
648 nested = frontmatter_scalar(value);
649 }
650 }
651 nested
652}
653
654pub fn declared_description(dir: &Path) -> Option<String> {
661 if dir.join("tuff.toml").is_file() {
662 return load_manifest(dir).ok().map(|manifest| manifest.description);
663 }
664 let skill = std::fs::read_to_string(dir.join("SKILL.md")).ok()?;
665 frontmatter_description(&skill)
666}
667
668pub fn frontmatter_description(skill: &str) -> Option<String> {
674 let mut lines = skill.lines().map(|line| line.trim_end_matches('\r'));
675 if lines.next()?.trim() != "---" {
676 return None;
677 }
678 for line in lines {
679 if line.trim() == "---" {
680 break;
681 }
682 if line.starts_with([' ', '\t']) {
683 continue;
684 }
685 if let Some(value) = line.strip_prefix("description:") {
686 return frontmatter_text(value);
687 }
688 }
689 None
690}
691
692pub fn frontmatter_name(skill: &str) -> Option<String> {
695 let mut lines = skill.lines().map(|line| line.trim_end_matches('\r'));
696 if lines.next()?.trim() != "---" {
697 return None;
698 }
699 for line in lines {
700 if line.trim() == "---" {
701 break;
702 }
703 if line.starts_with([' ', '\t']) {
704 continue;
705 }
706 if let Some(value) = line.strip_prefix("name:") {
707 return frontmatter_scalar(value);
708 }
709 }
710 None
711}
712
713fn frontmatter_text(value: &str) -> Option<String> {
715 let value = value.trim();
716 let value = value
717 .strip_prefix('"')
718 .and_then(|rest| rest.strip_suffix('"'))
719 .or_else(|| {
720 value
721 .strip_prefix('\'')
722 .and_then(|rest| rest.strip_suffix('\''))
723 })
724 .unwrap_or(value)
725 .trim();
726 if value.is_empty() || value.starts_with(['>', '|']) {
728 return None;
729 }
730 Some(value.to_string())
731}
732
733fn frontmatter_scalar(value: &str) -> Option<String> {
734 let value = value.trim();
735 let value = value
736 .strip_prefix('"')
737 .and_then(|rest| rest.strip_suffix('"'))
738 .or_else(|| {
739 value
740 .strip_prefix('\'')
741 .and_then(|rest| rest.strip_suffix('\''))
742 })
743 .unwrap_or(value)
744 .trim();
745 (!value.is_empty() && !value.contains(char::is_whitespace)).then(|| value.to_string())
746}
747
748pub fn synthetic_manifest(
749 skill_dir: &Path,
750 name: &str,
751 version: &str,
752) -> Result<CapabilityManifest> {
753 validate_capability_id(name)?;
754 let skill_file = skill_dir.join("SKILL.md");
755 if !skill_file.exists() {
756 return Err(TuffError::not_found(format!(
757 "skill entrypoint not found: {}",
758 skill_file.display()
759 )));
760 }
761 let mut files = Vec::new();
762 walk_skill_dir(skill_dir, "", &mut files)?;
763 files.sort();
764
765 Ok(CapabilityManifest {
766 id: name.to_string(),
767 version: version.to_string(),
768 capability_type: CapabilityType::Skill,
769 description: "Installed from git source.".to_string(),
770 files,
771 parameters: None,
772 implementation: None,
773 hook: None,
774 server: None,
775 policy: None,
776 targets: Vec::new(),
777 x: Default::default(),
778 root: skill_dir.to_path_buf(),
779 })
780}
781
782fn walk_skill_dir(base: &Path, prefix: &str, files: &mut Vec<String>) -> Result<()> {
783 for entry in std::fs::read_dir(base)? {
784 let entry = entry?;
785 let path = entry.path();
786 let metadata = std::fs::symlink_metadata(&path)?;
787 if metadata.file_type().is_symlink() {
788 return Err(TuffError::refused(format!(
789 "symbolic links are not allowed in capability sources: {}",
790 path.display()
791 )));
792 }
793 let rel = if prefix.is_empty() {
794 entry.file_name().to_string_lossy().to_string()
795 } else {
796 format!("{}/{}", prefix, entry.file_name().to_string_lossy())
797 };
798 if metadata.is_dir() {
799 walk_skill_dir(&path, &rel, files)?;
800 } else if metadata.is_file() && rel != "tuff.toml" {
801 files.push(rel);
802 }
803 }
804 Ok(())
805}
806
807#[cfg(test)]
808mod tests {
809 use super::*;
810 use std::fs;
811 use tempfile::TempDir;
812
813 fn write_manifest(dir: &std::path::Path, content: &str) {
814 fs::write(dir.join("tuff.toml"), content).unwrap();
815 }
816
817 #[test]
818 fn frontmatter_name_reads_the_top_level_name_only() {
819 assert_eq!(
820 frontmatter_name("---\nname: pdf\ndescription: x\n---\n").as_deref(),
821 Some("pdf")
822 );
823 assert_eq!(
824 frontmatter_name("---\nname: \"quoted\"\n---\n").as_deref(),
825 Some("quoted")
826 );
827 assert_eq!(
828 frontmatter_name("---\nmetadata:\n name: nested\n---\n"),
829 None
830 );
831 assert_eq!(frontmatter_name("# no frontmatter\nname: x\n"), None);
832 }
833
834 #[test]
835 fn frontmatter_version_reads_top_level_then_metadata() {
836 assert_eq!(
837 frontmatter_version("---\nname: x\nversion: 1.2.0\n---\n# X\n").as_deref(),
838 Some("1.2.0")
839 );
840 assert_eq!(
841 frontmatter_version("---\nname: x\nversion: \"1.2.0\"\n---\n").as_deref(),
842 Some("1.2.0")
843 );
844 assert_eq!(
846 frontmatter_version(
847 "---\nname: x\nmetadata:\n author: org\n version: \"1.0\"\n---\n"
848 )
849 .as_deref(),
850 Some("1.0")
851 );
852 assert_eq!(
854 frontmatter_version("---\nmetadata:\n version: 0.9.0\nversion: 1.2.0\n---\n")
855 .as_deref(),
856 Some("1.2.0")
857 );
858 assert_eq!(
860 frontmatter_version("---\nname: x\nextra:\n version: 3.0.0\n---\n"),
861 None
862 );
863 assert_eq!(
864 frontmatter_version("# no frontmatter\nversion: 1.0.0\n"),
865 None
866 );
867 assert_eq!(
868 frontmatter_version("---\nname: x\n---\nversion: 9.9.9\n"),
869 None
870 );
871 assert_eq!(frontmatter_version("---\nversion:\n---\n"), None);
872 assert_eq!(frontmatter_version("---\nversion: 1.2.0 beta\n---\n"), None);
873 assert_eq!(
874 frontmatter_version("---\r\nname: x\r\nversion: 2.0.0\r\n---\r\n").as_deref(),
875 Some("2.0.0")
876 );
877 }
878
879 #[test]
880 fn declared_description_reads_the_frontmatter_and_prefers_the_manifest() {
881 let tmp = TempDir::new().unwrap();
882 fs::write(
883 tmp.path().join("SKILL.md"),
884 "---\nname: x\ndescription: Reviews a diff for security problems.\n---\n# X\n",
885 )
886 .unwrap();
887 assert_eq!(
888 declared_description(tmp.path()).as_deref(),
889 Some("Reviews a diff for security problems.")
890 );
891
892 write_manifest(
893 tmp.path(),
894 r#"id = "x"
895version = "1.0.0"
896type = "skill"
897description = "From the manifest"
898files = ["SKILL.md"]
899"#,
900 );
901 assert_eq!(
902 declared_description(tmp.path()).as_deref(),
903 Some("From the manifest")
904 );
905 }
906
907 #[test]
908 fn a_multi_line_description_is_left_alone_rather_than_half_read() {
909 assert_eq!(
912 frontmatter_description("---\nname: x\ndescription: >\n Long text here.\n---\n"),
913 None
914 );
915 assert_eq!(
918 frontmatter_description("---\nmetadata:\n description: Nested.\n---\n"),
919 None
920 );
921 assert_eq!(frontmatter_description("# Just a heading\n"), None);
923 }
924
925 #[test]
926 fn declared_version_prefers_the_manifest_over_the_frontmatter() {
927 let tmp = TempDir::new().unwrap();
928 fs::write(
929 tmp.path().join("SKILL.md"),
930 "---\nname: x\nversion: 2.0.0\n---\n# X\n",
931 )
932 .unwrap();
933 assert_eq!(declared_version(tmp.path()).as_deref(), Some("2.0.0"));
934 fs::write(
935 tmp.path().join("tuff.toml"),
936 "id = \"x\"\nversion = \"1.0.0\"\ntype = \"skill\"\ndescription = \"d\"\nfiles = [\"SKILL.md\"]\n",
937 )
938 .unwrap();
939 assert_eq!(declared_version(tmp.path()).as_deref(), Some("1.0.0"));
940
941 let bare = TempDir::new().unwrap();
942 fs::write(bare.path().join("SKILL.md"), "# no version\n").unwrap();
943 assert_eq!(declared_version(bare.path()), None);
944 }
945
946 #[test]
947 fn load_skill_manifest_succeeds() {
948 let tmp = TempDir::new().unwrap();
949 fs::create_dir_all(tmp.path().join("src")).unwrap();
950 fs::write(tmp.path().join("src").join("SKILL.md"), "# Skill").unwrap();
951 write_manifest(
952 tmp.path(),
953 r#"id = "test"
954version = "1.0.0"
955type = "skill"
956description = "A test skill"
957files = ["src/SKILL.md"]
958"#,
959 );
960 let m = load_manifest(tmp.path()).unwrap();
961 assert_eq!(m.id, "test");
962 assert_eq!(m.capability_type, CapabilityType::Skill);
963 }
964
965 #[test]
966 fn load_tool_manifest_succeeds() {
967 let tmp = TempDir::new().unwrap();
968 fs::write(tmp.path().join("run.sh"), "echo ok").unwrap();
969 write_manifest(
970 tmp.path(),
971 r#"id = "tool1"
972version = "1.0.0"
973type = "tool"
974description = "A test tool"
975files = ["run.sh"]
976
977[parameters]
978type = "object"
979required = ["x"]
980[parameters.properties.x]
981type = "string"
982description = "x"
983
984[implementation]
985language = "bash"
986entrypoint = "run.sh"
987"#,
988 );
989 let m = load_manifest(tmp.path()).unwrap();
990 assert_eq!(m.capability_type, CapabilityType::Tool);
991 assert!(m.implementation.is_some());
992 }
993
994 #[test]
995 fn load_hook_manifest_succeeds() {
996 let tmp = TempDir::new().unwrap();
997 write_manifest(
998 tmp.path(),
999 r#"id = "hook1"
1000version = "1.0.0"
1001type = "hook"
1002description = "A test hook"
1003
1004[hook]
1005event = "before_finish"
1006command = "cargo test"
1007"#,
1008 );
1009 let m = load_manifest(tmp.path()).unwrap();
1010 assert_eq!(m.capability_type, CapabilityType::Hook);
1011 assert!(m.hook.is_some());
1012 }
1013
1014 #[test]
1015 fn load_rejects_unsupported_type() {
1016 let tmp = TempDir::new().unwrap();
1017 write_manifest(
1018 tmp.path(),
1019 r#"id = "bad"
1020version = "1.0.0"
1021type = "unknown"
1022description = "Bad"
1023files = ["SKILL.md"]
1024"#,
1025 );
1026 assert!(load_manifest(tmp.path()).is_err());
1027 }
1028
1029 #[test]
1030 fn load_rejects_missing_manifest() {
1031 let tmp = TempDir::new().unwrap();
1032 assert!(load_manifest(tmp.path()).is_err());
1033 }
1034
1035 #[test]
1036 fn source_files_resolves_paths() {
1037 let tmp = TempDir::new().unwrap();
1038 fs::create_dir_all(tmp.path().join("src")).unwrap();
1039 fs::write(tmp.path().join("src").join("SKILL.md"), "skill").unwrap();
1040 let m = CapabilityManifest {
1041 id: "t".into(),
1042 version: "1.0".into(),
1043 capability_type: CapabilityType::Skill,
1044 description: "desc".into(),
1045 files: vec!["src/SKILL.md".into()],
1046 parameters: None,
1047 implementation: None,
1048 hook: None,
1049 server: None,
1050 policy: None,
1051 targets: vec![],
1052 x: Default::default(),
1053 root: tmp.path().to_path_buf(),
1054 };
1055 let files = m.source_files().unwrap();
1056 assert_eq!(files.len(), 1);
1057 assert!(files[0].ends_with("SKILL.md"));
1058 }
1059
1060 fn manifest_listing(root: &Path, files: &[&str]) -> CapabilityManifest {
1061 CapabilityManifest {
1062 id: "t".into(),
1063 version: "1.0".into(),
1064 capability_type: CapabilityType::Hook,
1065 description: "desc".into(),
1066 files: files.iter().map(|f| f.to_string()).collect(),
1067 parameters: None,
1068 implementation: None,
1069 hook: None,
1070 server: None,
1071 policy: None,
1072 targets: vec![],
1073 x: Default::default(),
1074 root: root.to_path_buf(),
1075 }
1076 }
1077
1078 #[test]
1079 fn source_files_refuse_a_path_that_climbs_out_of_the_capability() {
1080 let tmp = TempDir::new().unwrap();
1085 let capability = tmp.path().join("capability");
1086 fs::create_dir_all(&capability).unwrap();
1087 fs::write(tmp.path().join("outside.txt"), "outside").unwrap();
1088 fs::write(capability.join("inside.txt"), "inside").unwrap();
1089
1090 for entry in [
1091 "../outside.txt",
1092 "sub/../../outside.txt",
1093 "./../outside.txt",
1094 ] {
1095 let error = manifest_listing(&capability, &["inside.txt", entry])
1096 .source_files()
1097 .unwrap_err();
1098 assert_eq!(error.kind(), crate::error::ErrorKind::Refused, "{entry}");
1099 assert!(
1100 error
1101 .to_string()
1102 .contains("must stay inside the capability directory"),
1103 "{entry}: {error}"
1104 );
1105 }
1106 let absolute = tmp.path().join("outside.txt");
1107 let error = manifest_listing(&capability, &[absolute.to_str().unwrap()])
1108 .source_files()
1109 .unwrap_err();
1110 assert_eq!(error.kind(), crate::error::ErrorKind::Refused);
1111 }
1112
1113 #[cfg(unix)]
1114 #[test]
1115 fn source_files_refuse_a_symbolic_link_anywhere_along_the_path() {
1116 let tmp = TempDir::new().unwrap();
1117 let capability = tmp.path().join("capability");
1118 let secrets = tmp.path().join("secrets");
1119 fs::create_dir_all(capability.join("docs")).unwrap();
1120 fs::create_dir_all(&secrets).unwrap();
1121 fs::write(secrets.join("key.txt"), "pretend secret").unwrap();
1122 std::os::unix::fs::symlink(secrets.join("key.txt"), capability.join("notes.md")).unwrap();
1123 std::os::unix::fs::symlink(&secrets, capability.join("docs").join("linked")).unwrap();
1124
1125 for entry in ["notes.md", "docs/linked/key.txt"] {
1126 let error = manifest_listing(&capability, &[entry])
1127 .source_files()
1128 .unwrap_err();
1129 assert_eq!(error.kind(), crate::error::ErrorKind::Refused, "{entry}");
1130 assert!(
1131 error.to_string().contains("symbolic links are not allowed"),
1132 "{entry}: {error}"
1133 );
1134 }
1135 }
1136
1137 #[test]
1138 fn source_files_accept_plain_nested_and_dot_slash_paths() {
1139 let tmp = TempDir::new().unwrap();
1140 fs::create_dir_all(tmp.path().join("src/lib")).unwrap();
1141 fs::write(tmp.path().join("src/lib/check.sh"), "x").unwrap();
1142 fs::write(tmp.path().join("run.sh"), "x").unwrap();
1143
1144 let files = manifest_listing(tmp.path(), &["./run.sh", "src/lib/check.sh"])
1145 .source_files()
1146 .unwrap();
1147 assert_eq!(
1148 files,
1149 vec![
1150 tmp.path().join("run.sh"),
1151 tmp.path().join("src/lib/check.sh")
1152 ]
1153 );
1154 let error = manifest_listing(tmp.path(), &["src"])
1155 .source_files()
1156 .unwrap_err();
1157 assert!(error.to_string().contains("must be a file"), "{error}");
1158 }
1159
1160 #[test]
1161 fn listed_files_that_install_to_the_same_path_are_refused_but_a_repeat_is_not() {
1162 let tmp = TempDir::new().unwrap();
1163 fs::create_dir_all(tmp.path().join("src")).unwrap();
1164 fs::write(tmp.path().join("check.sh"), "top").unwrap();
1165 fs::write(tmp.path().join("src/check.sh"), "src").unwrap();
1166
1167 let repeated = manifest_listing(tmp.path(), &["check.sh", "./check.sh", "check.sh"])
1168 .read_source_contents_with_names()
1169 .unwrap();
1170 assert_eq!(repeated, vec![("check.sh".to_string(), b"top".to_vec())]);
1171
1172 let error = manifest_listing(tmp.path(), &["check.sh", "src/check.sh"])
1173 .read_source_contents_with_names()
1174 .unwrap_err();
1175 assert_eq!(error.kind(), crate::error::ErrorKind::Refused);
1176 assert!(
1177 error.to_string().contains("would install as 'check.sh'"),
1178 "{error}"
1179 );
1180 }
1181
1182 #[test]
1183 fn source_files_rejects_missing_file() {
1184 let tmp = TempDir::new().unwrap();
1185 let m = CapabilityManifest {
1186 id: "t".into(),
1187 version: "1.0".into(),
1188 capability_type: CapabilityType::Skill,
1189 description: "desc".into(),
1190 files: vec!["src/MISSING.md".into()],
1191 parameters: None,
1192 implementation: None,
1193 hook: None,
1194 server: None,
1195 policy: None,
1196 targets: vec![],
1197 x: Default::default(),
1198 root: tmp.path().to_path_buf(),
1199 };
1200 assert!(m.source_files().is_err());
1201 }
1202
1203 #[test]
1204 fn a_capability_id_is_a_relative_path_of_plain_names() {
1205 for id in [
1208 "release-checklist",
1209 "tuff-cli-guide",
1210 "a.b",
1211 "x_1",
1212 "...x",
1213 "security/security-review",
1214 "a/b/c",
1215 ] {
1216 assert!(validate_capability_id(id).is_ok(), "{id}");
1217 }
1218 for id in [
1219 "",
1220 ".",
1221 "..",
1222 "../victim",
1223 "../../victim",
1224 "a/../b",
1225 "a/..",
1226 "./a",
1227 "a/./b",
1228 "/abs",
1229 "a/",
1230 "a//b",
1231 "a\\b",
1232 "nul\0x",
1233 " padded",
1234 "padded ",
1235 ] {
1236 let error = validate_capability_id(id).unwrap_err();
1237 assert_eq!(error.kind(), crate::error::ErrorKind::Refused, "{id:?}");
1238 }
1239 }
1240
1241 #[test]
1242 fn a_manifest_with_an_escaping_id_is_refused_at_load() {
1243 let tmp = TempDir::new().unwrap();
1244 fs::write(
1245 tmp.path().join("tuff.toml"),
1246 "id = \"../../victim\"\ntype = \"hook\"\nversion = \"1.0.0\"\ndescription = \"d\"\n[hook]\nevent = \"stop\"\ncommand = \"true\"\n",
1247 )
1248 .unwrap();
1249 let error = load_manifest(tmp.path()).unwrap_err();
1250 assert!(
1251 error.to_string().contains("relative path of plain names"),
1252 "{error}"
1253 );
1254 }
1255
1256 #[test]
1257 fn a_policy_manifest_loads_and_refuses_files() {
1258 let tmp = TempDir::new().unwrap();
1259 let head = "id = \"guard\"\ntype = \"policy\"\nversion = \"1.0.0\"\ndescription = \"d\"\n";
1260 let rules =
1261 "[[policy.rules]]\neffect = \"deny\"\ncommand = [\"git\", \"push\", \"--force\"]\n";
1262 fs::write(tmp.path().join("tuff.toml"), format!("{head}{rules}")).unwrap();
1263 let manifest = load_manifest(tmp.path()).unwrap();
1264 assert_eq!(manifest.policy.unwrap().rules.len(), 1);
1265
1266 fs::write(tmp.path().join("tuff.toml"), head).unwrap();
1267 let error = load_manifest(tmp.path()).unwrap_err();
1268 assert!(
1269 error.to_string().contains("requires a [policy] section"),
1270 "{error}"
1271 );
1272
1273 fs::write(tmp.path().join("x.sh"), "x").unwrap();
1274 fs::write(
1275 tmp.path().join("tuff.toml"),
1276 format!("{head}files = [\"x.sh\"]\n{rules}"),
1277 )
1278 .unwrap();
1279 let error = load_manifest(tmp.path()).unwrap_err();
1280 assert!(error.to_string().contains("installs no files"), "{error}");
1281 }
1282
1283 #[test]
1284 fn validate_non_empty_rejects_empty() {
1285 assert!(validate_non_empty("id", "").is_err());
1286 assert!(validate_non_empty("id", "ok").is_ok());
1287 }
1288
1289 fn load_mcp(toml_body: &str) -> Result<CapabilityManifest> {
1290 let tmp = TempDir::new().unwrap();
1291 fs::write(tmp.path().join("tuff.toml"), toml_body).unwrap();
1292 load_manifest(tmp.path())
1293 }
1294
1295 const MCP_HEAD: &str =
1296 "id = \"srv\"\nversion = \"1.0.0\"\ntype = \"mcp-server\"\ndescription = \"d\"\n";
1297
1298 #[test]
1299 fn mcp_server_requires_server_section() {
1300 let error = load_mcp(MCP_HEAD).unwrap_err().to_string();
1301 assert!(error.contains("requires a [server] section"), "{error}");
1302 }
1303
1304 #[test]
1305 fn mcp_server_stdio_requires_command_and_http_requires_url() {
1306 let error = load_mcp(&format!("{MCP_HEAD}[server]\ntransport = \"stdio\"\n"))
1307 .unwrap_err()
1308 .to_string();
1309 assert!(error.contains("requires a non-empty 'command'"), "{error}");
1310 let error = load_mcp(&format!("{MCP_HEAD}[server]\ntransport = \"http\"\n"))
1311 .unwrap_err()
1312 .to_string();
1313 assert!(error.contains("requires a non-empty 'url'"), "{error}");
1314 let ok = load_mcp(&format!(
1315 "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n"
1316 ))
1317 .unwrap();
1318 assert_eq!(ok.server.unwrap().transport, McpTransport::Http);
1319 }
1320
1321 #[test]
1322 fn mcp_server_env_must_be_a_reference_not_a_literal() {
1323 let error = load_mcp(&format!(
1324 "{MCP_HEAD}[server]\ncommand = \"npx\"\n[server.env]\nTOKEN = \"literal\"\n"
1325 ))
1326 .unwrap_err()
1327 .to_string();
1328 assert!(error.contains("from_env"), "{error}");
1329
1330 let ok = load_mcp(&format!(
1331 "{MCP_HEAD}[server]\ncommand = \"npx\"\n[server.env]\nTOKEN = {{ from_env = \"MY_TOKEN\" }}\n"
1332 ))
1333 .unwrap();
1334 assert_eq!(ok.server.unwrap().env["TOKEN"].from_env, "MY_TOKEN");
1335 }
1336
1337 #[test]
1338 fn mcp_server_headers_must_be_references_not_literals() {
1339 let error = load_mcp(&format!(
1340 "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
1341 [server.headers]\nAuthorization = \"Bearer secret\"\n"
1342 ))
1343 .unwrap_err()
1344 .to_string();
1345 assert!(error.contains("[server.headers]"), "{error}");
1346 assert!(error.contains("from_env"), "{error}");
1347 }
1348
1349 #[test]
1350 fn mcp_server_header_reference_carries_an_optional_format() {
1351 let server = load_mcp(&format!(
1352 "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
1353 [server.headers]\n\
1354 Authorization = {{ from_env = \"NOTION_TOKEN\", format = \"Bearer {{}}\" }}\n\
1355 X-Api-Key = {{ from_env = \"API_KEY\" }}\n"
1356 ))
1357 .unwrap()
1358 .server
1359 .unwrap();
1360 assert_eq!(server.headers["Authorization"].from_env, "NOTION_TOKEN");
1361 assert_eq!(
1362 server.headers["Authorization"].render("${NOTION_TOKEN}"),
1363 "Bearer ${NOTION_TOKEN}"
1364 );
1365 assert_eq!(server.headers["X-Api-Key"].format, None);
1366 assert_eq!(
1367 server.headers["X-Api-Key"].render("${API_KEY}"),
1368 "${API_KEY}"
1369 );
1370 }
1371
1372 #[test]
1373 fn mcp_server_header_format_needs_exactly_one_placeholder() {
1374 for format in ["Bearer", "Bearer {} {}"] {
1375 let error = load_mcp(&format!(
1376 "{MCP_HEAD}[server]\ntransport = \"http\"\nurl = \"https://example.test/mcp\"\n\
1377 [server.headers]\n\
1378 Authorization = {{ from_env = \"TOKEN\", format = \"{format}\" }}\n"
1379 ))
1380 .unwrap_err()
1381 .to_string();
1382 assert!(error.contains("Authorization"), "{format}: {error}");
1383 }
1384 }
1385
1386 #[test]
1387 fn mcp_server_headers_are_refused_on_stdio() {
1388 let error = load_mcp(&format!(
1389 "{MCP_HEAD}[server]\ncommand = \"npx\"\n\
1390 [server.headers]\nAuthorization = {{ from_env = \"TOKEN\" }}\n"
1391 ))
1392 .unwrap_err()
1393 .to_string();
1394 assert!(error.contains("http"), "{error}");
1395 }
1396
1397 #[test]
1400 fn a_server_without_headers_serializes_without_the_table() {
1401 let server = load_mcp(&format!("{MCP_HEAD}[server]\ncommand = \"npx\"\n"))
1402 .unwrap()
1403 .server
1404 .unwrap();
1405 let wire = toml::to_string_pretty(&server).unwrap();
1406 assert!(!wire.contains("headers"), "{wire}");
1407 }
1408
1409 #[test]
1410 fn capability_type_round_trips_the_hyphenated_name() {
1411 assert_eq!(CapabilityType::McpServer.as_str(), "mcp-server");
1412 assert_eq!(
1413 CapabilityType::parse("mcp-server"),
1414 Some(CapabilityType::McpServer)
1415 );
1416 assert_eq!(
1417 CapabilityType::parse("mcp"),
1418 Some(CapabilityType::McpServer)
1419 );
1420 #[derive(serde::Serialize)]
1421 struct Wire {
1422 #[serde(rename = "type")]
1423 capability_type: CapabilityType,
1424 }
1425 let wire = toml::to_string(&Wire {
1426 capability_type: CapabilityType::McpServer,
1427 })
1428 .unwrap();
1429 assert!(wire.contains("type = \"mcp-server\""), "{wire}");
1430 assert_eq!(CapabilityType::parse("workflow"), None);
1431 }
1432}