1use serde::{Deserialize, Serialize};
14use sha2::{Digest, Sha256};
15use std::collections::HashMap;
16use std::path::{Path, PathBuf};
17use thiserror::Error;
18
19use crate::core::manifest::ManifestRegistry;
20use crate::core::scope::ScopeConfig;
21
22#[derive(Error, Debug)]
23pub enum SkillError {
24 #[error("Failed to read skill file {0}: {1}")]
25 Io(String, std::io::Error),
26 #[error("Failed to parse skill.toml {0}: {1}")]
27 Parse(String, toml::de::Error),
28 #[error("Skill not found: {0}")]
29 NotFound(String),
30 #[error("Skills directory not found: {0}")]
31 NoDirectory(String),
32 #[error("Invalid skill: {0}")]
33 Invalid(String),
34}
35
36#[derive(Debug, Clone, Deserialize, Default)]
38pub struct AnthropicFrontmatter {
39 pub name: Option<String>,
40 pub description: Option<String>,
41 pub license: Option<String>,
42 pub compatibility: Option<String>,
43 #[serde(default)]
44 pub metadata: HashMap<String, String>,
45 #[serde(rename = "allowed-tools")]
47 pub allowed_tools: Option<String>,
48}
49
50pub fn parse_frontmatter(content: &str) -> (Option<AnthropicFrontmatter>, &str) {
55 let trimmed = content.trim_start();
56 if !trimmed.starts_with("---") {
57 return (None, content);
58 }
59
60 let after_open = &trimmed[3..];
62 let after_open = match after_open.find('\n') {
64 Some(pos) => &after_open[pos + 1..],
65 None => return (None, content),
66 };
67
68 match after_open.find("\n---") {
69 Some(end_pos) => {
70 let yaml_str = &after_open[..end_pos];
71 let body_start = &after_open[end_pos + 4..]; let body = match body_start.find('\n') {
74 Some(pos) => &body_start[pos + 1..],
75 None => "",
76 };
77
78 match serde_yaml::from_str::<AnthropicFrontmatter>(yaml_str) {
79 Ok(fm) => (Some(fm), body),
80 Err(_) => (None, content), }
82 }
83 None => (None, content),
84 }
85}
86
87pub fn strip_frontmatter(content: &str) -> &str {
89 let (_, body) = parse_frontmatter(content);
90 body
91}
92
93pub fn compute_content_hash(content: &str) -> String {
95 let mut hasher = Sha256::new();
96 hasher.update(content.as_bytes());
97 let result = hasher.finalize();
98 hex::encode(result)
99}
100
101pub fn is_anthropic_valid_name(name: &str) -> bool {
106 if name.is_empty() || name.len() > 64 {
107 return false;
108 }
109 let bytes = name.as_bytes();
110 if !bytes[0].is_ascii_lowercase() && !bytes[0].is_ascii_digit() {
112 return false;
113 }
114 if !bytes[bytes.len() - 1].is_ascii_lowercase() && !bytes[bytes.len() - 1].is_ascii_digit() {
115 return false;
116 }
117 let mut prev_hyphen = false;
119 for &b in bytes {
120 if b == b'-' {
121 if prev_hyphen {
122 return false;
123 }
124 prev_hyphen = true;
125 } else if b.is_ascii_lowercase() || b.is_ascii_digit() {
126 prev_hyphen = false;
127 } else {
128 return false;
129 }
130 }
131 true
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
136pub enum SkillFormat {
137 #[serde(rename = "anthropic")]
139 Anthropic,
140 #[serde(rename = "legacy-toml")]
142 LegacyToml,
143 #[serde(rename = "inferred")]
145 Inferred,
146}
147
148#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct SkillMeta {
151 pub name: String,
152 #[serde(default = "default_version")]
153 pub version: String,
154 #[serde(default)]
155 pub description: String,
156 #[serde(default)]
157 pub author: Option<String>,
158
159 #[serde(default)]
162 pub tools: Vec<String>,
163 #[serde(default)]
165 pub providers: Vec<String>,
166 #[serde(default)]
168 pub categories: Vec<String>,
169
170 #[serde(default)]
172 pub keywords: Vec<String>,
173 #[serde(default)]
174 pub hint: Option<String>,
175
176 #[serde(default)]
179 pub depends_on: Vec<String>,
180 #[serde(default)]
182 pub suggests: Vec<String>,
183
184 #[serde(default)]
187 pub license: Option<String>,
188 #[serde(default)]
190 pub compatibility: Option<String>,
191 #[serde(default)]
193 pub extra_metadata: HashMap<String, String>,
194 #[serde(default)]
196 pub allowed_tools: Option<String>,
197 #[serde(default)]
199 pub has_frontmatter: bool,
200 #[serde(default = "default_format")]
202 pub format: SkillFormat,
203
204 #[serde(default, skip_serializing_if = "Option::is_none")]
207 pub source_url: Option<String>,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub content_hash: Option<String>,
211 #[serde(default, skip_serializing_if = "Option::is_none")]
213 pub pinned_sha: Option<String>,
214
215 #[serde(skip)]
218 pub dir: PathBuf,
219}
220
221impl Default for SkillMeta {
222 fn default() -> Self {
223 Self {
224 name: String::new(),
225 version: default_version(),
226 description: String::new(),
227 author: None,
228 tools: Vec::new(),
229 providers: Vec::new(),
230 categories: Vec::new(),
231 keywords: Vec::new(),
232 hint: None,
233 depends_on: Vec::new(),
234 suggests: Vec::new(),
235 license: None,
236 compatibility: None,
237 extra_metadata: HashMap::new(),
238 allowed_tools: None,
239 has_frontmatter: false,
240 format: SkillFormat::Inferred,
241 source_url: None,
242 content_hash: None,
243 pinned_sha: None,
244 dir: PathBuf::new(),
245 }
246 }
247}
248
249fn default_format() -> SkillFormat {
250 SkillFormat::Inferred
251}
252
253fn default_version() -> String {
254 "0.1.0".to_string()
255}
256
257#[derive(Debug, Deserialize)]
259struct SkillToml {
260 skill: SkillMeta,
261}
262
263pub struct SkillRegistry {
265 skills: Vec<SkillMeta>,
266 name_index: HashMap<String, usize>,
268 tool_index: HashMap<String, Vec<usize>>,
270 provider_index: HashMap<String, Vec<usize>>,
272 category_index: HashMap<String, Vec<usize>>,
274 files_cache: HashMap<(String, String), Vec<u8>>,
277}
278
279impl SkillRegistry {
280 pub fn load(skills_dir: &Path) -> Result<Self, SkillError> {
285 let mut skills = Vec::new();
286 let mut name_index = HashMap::new();
287 let mut tool_index: HashMap<String, Vec<usize>> = HashMap::new();
288 let mut provider_index: HashMap<String, Vec<usize>> = HashMap::new();
289 let mut category_index: HashMap<String, Vec<usize>> = HashMap::new();
290
291 if !skills_dir.is_dir() {
292 return Ok(SkillRegistry {
294 skills,
295 name_index,
296 tool_index,
297 provider_index,
298 category_index,
299 files_cache: HashMap::new(),
300 });
301 }
302
303 let entries = std::fs::read_dir(skills_dir)
304 .map_err(|e| SkillError::Io(skills_dir.display().to_string(), e))?;
305
306 for entry in entries {
307 let entry = entry.map_err(|e| SkillError::Io(skills_dir.display().to_string(), e))?;
308 let path = entry.path();
309 if !path.is_dir() {
310 continue;
311 }
312
313 let skill = load_skill_from_dir(&path)?;
314
315 let idx = skills.len();
316 name_index.insert(skill.name.clone(), idx);
317
318 for tool in &skill.tools {
319 tool_index.entry(tool.clone()).or_default().push(idx);
320 }
321 for provider in &skill.providers {
322 provider_index
323 .entry(provider.clone())
324 .or_default()
325 .push(idx);
326 }
327 for category in &skill.categories {
328 category_index
329 .entry(category.clone())
330 .or_default()
331 .push(idx);
332 }
333
334 skills.push(skill);
335 }
336
337 Ok(SkillRegistry {
338 skills,
339 name_index,
340 tool_index,
341 provider_index,
342 category_index,
343 files_cache: HashMap::new(),
344 })
345 }
346
347 pub fn merge(&mut self, source: crate::core::gcs::GcsSkillSource) {
350 let mut added: std::collections::HashSet<String> = std::collections::HashSet::new();
351
352 for skill in source.skills {
353 if self.name_index.contains_key(&skill.name) {
354 continue;
356 }
357 added.insert(skill.name.clone());
358 let idx = self.skills.len();
359 self.name_index.insert(skill.name.clone(), idx);
360 for tool in &skill.tools {
361 self.tool_index.entry(tool.clone()).or_default().push(idx);
362 }
363 for provider in &skill.providers {
364 self.provider_index
365 .entry(provider.clone())
366 .or_default()
367 .push(idx);
368 }
369 for category in &skill.categories {
370 self.category_index
371 .entry(category.clone())
372 .or_default()
373 .push(idx);
374 }
375 self.skills.push(skill);
376 }
377
378 for ((skill_name, rel_path), data) in source.files {
381 if added.contains(&skill_name) {
382 self.files_cache.insert((skill_name, rel_path), data);
383 }
384 }
385 }
386
387 pub fn get_skill(&self, name: &str) -> Option<&SkillMeta> {
389 self.name_index.get(name).map(|&idx| &self.skills[idx])
390 }
391
392 pub fn list_skills(&self) -> &[SkillMeta] {
394 &self.skills
395 }
396
397 pub fn skills_for_tool(&self, tool_name: &str) -> Vec<&SkillMeta> {
399 self.tool_index
400 .get(tool_name)
401 .map(|indices| indices.iter().map(|&i| &self.skills[i]).collect())
402 .unwrap_or_default()
403 }
404
405 pub fn skills_for_provider(&self, provider_name: &str) -> Vec<&SkillMeta> {
407 self.provider_index
408 .get(provider_name)
409 .map(|indices| indices.iter().map(|&i| &self.skills[i]).collect())
410 .unwrap_or_default()
411 }
412
413 pub fn skills_for_category(&self, category: &str) -> Vec<&SkillMeta> {
415 self.category_index
416 .get(category)
417 .map(|indices| indices.iter().map(|&i| &self.skills[i]).collect())
418 .unwrap_or_default()
419 }
420
421 pub fn search(&self, query: &str) -> Vec<&SkillMeta> {
423 let q = query.to_lowercase();
424 let terms: Vec<&str> = q.split_whitespace().collect();
425
426 let mut scored: Vec<(usize, &SkillMeta)> = self
427 .skills
428 .iter()
429 .filter_map(|skill| {
430 let mut score = 0usize;
431 let name_lower = skill.name.to_lowercase();
432 let desc_lower = skill.description.to_lowercase();
433
434 for term in &terms {
435 if name_lower.contains(term) {
437 score += 10;
438 }
439 if desc_lower.contains(term) {
441 score += 5;
442 }
443 if skill
445 .keywords
446 .iter()
447 .any(|k| k.to_lowercase().contains(term))
448 {
449 score += 8;
450 }
451 if skill.tools.iter().any(|t| t.to_lowercase().contains(term)) {
453 score += 6;
454 }
455 if let Some(hint) = &skill.hint {
457 if hint.to_lowercase().contains(term) {
458 score += 4;
459 }
460 }
461 if skill
463 .providers
464 .iter()
465 .any(|p| p.to_lowercase().contains(term))
466 {
467 score += 6;
468 }
469 if skill
471 .categories
472 .iter()
473 .any(|c| c.to_lowercase().contains(term))
474 {
475 score += 4;
476 }
477 }
478
479 if score > 0 {
480 Some((score, skill))
481 } else {
482 None
483 }
484 })
485 .collect();
486
487 scored.sort_by(|a, b| b.0.cmp(&a.0));
489 scored.into_iter().map(|(_, skill)| skill).collect()
490 }
491
492 pub fn read_content(&self, name: &str) -> Result<String, SkillError> {
495 if let Some(bytes) = self
497 .files_cache
498 .get(&(name.to_string(), "SKILL.md".to_string()))
499 {
500 let raw = std::str::from_utf8(bytes).unwrap_or("");
501 return Ok(strip_frontmatter(raw).to_string());
502 }
503
504 let skill = self
506 .get_skill(name)
507 .ok_or_else(|| SkillError::NotFound(name.to_string()))?;
508 let skill_md = skill.dir.join("SKILL.md");
509 if !skill_md.exists() {
510 return Ok(String::new());
511 }
512 let raw = std::fs::read_to_string(&skill_md)
513 .map_err(|e| SkillError::Io(skill_md.display().to_string(), e))?;
514 Ok(strip_frontmatter(&raw).to_string())
515 }
516
517 pub fn list_references(&self, name: &str) -> Result<Vec<String>, SkillError> {
520 let prefix = "references/";
522 let cached_refs: Vec<String> = self
523 .files_cache
524 .keys()
525 .filter(|(skill, path)| skill == name && path.starts_with(prefix))
526 .map(|(_, path)| path.strip_prefix(prefix).unwrap_or(path).to_string())
527 .collect();
528 if !cached_refs.is_empty() {
529 let mut refs = cached_refs;
530 refs.sort();
531 return Ok(refs);
532 }
533
534 let skill = self
536 .get_skill(name)
537 .ok_or_else(|| SkillError::NotFound(name.to_string()))?;
538 let refs_dir = skill.dir.join("references");
539 if !refs_dir.is_dir() {
540 return Ok(Vec::new());
541 }
542 let mut refs = Vec::new();
543 let entries = std::fs::read_dir(&refs_dir)
544 .map_err(|e| SkillError::Io(refs_dir.display().to_string(), e))?;
545 for entry in entries {
546 let entry = entry.map_err(|e| SkillError::Io(refs_dir.display().to_string(), e))?;
547 if let Some(name) = entry.file_name().to_str() {
548 refs.push(name.to_string());
549 }
550 }
551 refs.sort();
552 Ok(refs)
553 }
554
555 pub fn read_reference(&self, skill_name: &str, ref_name: &str) -> Result<String, SkillError> {
558 if ref_name.contains("..")
560 || ref_name.contains('/')
561 || ref_name.contains('\\')
562 || ref_name.contains('\0')
563 {
564 return Err(SkillError::NotFound(format!(
565 "Invalid reference name '{ref_name}' — path traversal not allowed"
566 )));
567 }
568
569 let cache_key = (skill_name.to_string(), format!("references/{ref_name}"));
571 if let Some(bytes) = self.files_cache.get(&cache_key) {
572 return std::str::from_utf8(bytes)
573 .map(|s| s.to_string())
574 .map_err(|e| SkillError::Invalid(format!("invalid UTF-8 in reference: {e}")));
575 }
576
577 let skill = self
578 .get_skill(skill_name)
579 .ok_or_else(|| SkillError::NotFound(skill_name.to_string()))?;
580 let refs_dir = skill.dir.join("references");
581 let ref_path = refs_dir.join(ref_name);
582
583 if let (Ok(canonical_ref), Ok(canonical_dir)) =
585 (ref_path.canonicalize(), refs_dir.canonicalize())
586 {
587 if !canonical_ref.starts_with(&canonical_dir) {
588 return Err(SkillError::NotFound(format!(
589 "Reference '{ref_name}' resolves outside references directory"
590 )));
591 }
592 }
593
594 if !ref_path.exists() {
595 return Err(SkillError::NotFound(format!(
596 "Reference '{ref_name}' in skill '{skill_name}'"
597 )));
598 }
599 std::fs::read_to_string(&ref_path)
600 .map_err(|e| SkillError::Io(ref_path.display().to_string(), e))
601 }
602
603 pub fn bundle_files(&self, name: &str) -> Result<HashMap<String, Vec<u8>>, SkillError> {
606 let _skill = self
607 .get_skill(name)
608 .ok_or_else(|| SkillError::NotFound(name.to_string()))?;
609
610 let mut files: HashMap<String, Vec<u8>> = HashMap::new();
611
612 for ((skill_name, rel_path), data) in &self.files_cache {
614 if skill_name == name {
615 files.insert(rel_path.clone(), data.clone());
616 }
617 }
618
619 if files.is_empty() {
621 let skill = self.get_skill(name).unwrap();
622 if skill.dir.is_dir() {
623 collect_dir_files(&skill.dir, &skill.dir, &mut files)?;
624 }
625 }
626
627 Ok(files)
628 }
629
630 pub fn skill_count(&self) -> usize {
632 self.skills.len()
633 }
634
635 pub fn validate_tool_bindings(
638 &self,
639 name: &str,
640 manifest_registry: &ManifestRegistry,
641 ) -> Result<(Vec<String>, Vec<String>), SkillError> {
642 let skill = self
643 .get_skill(name)
644 .ok_or_else(|| SkillError::NotFound(name.to_string()))?;
645
646 let mut valid = Vec::new();
647 let mut unknown = Vec::new();
648
649 for tool_name in &skill.tools {
650 if manifest_registry.get_tool(tool_name).is_some() {
651 valid.push(tool_name.clone());
652 } else {
653 unknown.push(tool_name.clone());
654 }
655 }
656
657 Ok((valid, unknown))
658 }
659}
660
661pub fn resolve_skills<'a>(
672 skill_registry: &'a SkillRegistry,
673 manifest_registry: &ManifestRegistry,
674 scopes: &ScopeConfig,
675) -> Vec<&'a SkillMeta> {
676 let mut resolved_indices: Vec<usize> = Vec::new();
677 let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new();
678
679 for scope in &scopes.scopes {
680 if let Some(skill_name) = scope.strip_prefix("skill:") {
682 if let Some(&idx) = skill_registry.name_index.get(skill_name) {
683 if seen.insert(idx) {
684 resolved_indices.push(idx);
685 }
686 }
687 }
688
689 if let Some(tool_name) = scope.strip_prefix("tool:") {
691 if let Some(indices) = skill_registry.tool_index.get(tool_name) {
692 for &idx in indices {
693 if seen.insert(idx) {
694 resolved_indices.push(idx);
695 }
696 }
697 }
698
699 if let Some((provider, _)) = manifest_registry.get_tool(tool_name) {
701 if let Some(indices) = skill_registry.provider_index.get(&provider.name) {
702 for &idx in indices {
703 if seen.insert(idx) {
704 resolved_indices.push(idx);
705 }
706 }
707 }
708
709 if let Some(category) = &provider.category {
711 if let Some(indices) = skill_registry.category_index.get(category) {
712 for &idx in indices {
713 if seen.insert(idx) {
714 resolved_indices.push(idx);
715 }
716 }
717 }
718 }
719 }
720 }
721 }
722
723 let mut i = 0;
725 while i < resolved_indices.len() {
726 let skill = &skill_registry.skills[resolved_indices[i]];
727 for dep_name in &skill.depends_on {
728 if let Some(&dep_idx) = skill_registry.name_index.get(dep_name) {
729 if seen.insert(dep_idx) {
730 resolved_indices.push(dep_idx);
731 }
732 }
733 }
734 i += 1;
735 }
736
737 resolved_indices
738 .into_iter()
739 .map(|idx| &skill_registry.skills[idx])
740 .collect()
741}
742
743const MAX_SKILL_INJECT_SIZE: usize = 32 * 1024;
746
747pub fn build_skill_context(skills: &[&SkillMeta]) -> String {
751 if skills.is_empty() {
752 return String::new();
753 }
754
755 let mut total_size = 0;
756 let mut sections = Vec::new();
757 for skill in skills {
758 let mut section = format!(
759 "--- BEGIN SKILL: {} ---\n- **{}**: {}",
760 skill.name, skill.name, skill.description
761 );
762 if let Some(hint) = &skill.hint {
763 section.push_str(&format!("\n Hint: {hint}"));
764 }
765 if !skill.tools.is_empty() {
766 section.push_str(&format!("\n Covers tools: {}", skill.tools.join(", ")));
767 }
768 if !skill.suggests.is_empty() {
769 section.push_str(&format!(
770 "\n Related skills: {}",
771 skill.suggests.join(", ")
772 ));
773 }
774 section.push_str(&format!("\n--- END SKILL: {} ---", skill.name));
775
776 total_size += section.len();
777 if total_size > MAX_SKILL_INJECT_SIZE {
778 sections.push("(remaining skills truncated due to size limit)".to_string());
779 break;
780 }
781 sections.push(section);
782 }
783 sections.join("\n\n")
784}
785
786fn collect_dir_files(
794 base: &Path,
795 current: &Path,
796 files: &mut HashMap<String, Vec<u8>>,
797) -> Result<(), SkillError> {
798 let entries =
799 std::fs::read_dir(current).map_err(|e| SkillError::Io(current.display().to_string(), e))?;
800 for entry in entries {
801 let entry = entry.map_err(|e| SkillError::Io(current.display().to_string(), e))?;
802 let path = entry.path();
803 if path.is_dir() {
804 collect_dir_files(base, &path, files)?;
805 } else if let Ok(rel) = path.strip_prefix(base) {
806 if let Some(rel_str) = rel.to_str() {
807 if let Ok(data) = std::fs::read(&path) {
808 files.insert(rel_str.to_string(), data);
809 }
810 }
811 }
812 }
813 Ok(())
814}
815
816fn load_skill_from_dir(dir: &Path) -> Result<SkillMeta, SkillError> {
819 let skill_toml_path = dir.join("skill.toml");
820 let skill_md_path = dir.join("SKILL.md");
821
822 let dir_name = dir
823 .file_name()
824 .and_then(|n| n.to_str())
825 .unwrap_or("unknown")
826 .to_string();
827
828 let (frontmatter, _body) = if skill_md_path.exists() {
830 let content = std::fs::read_to_string(&skill_md_path)
831 .map_err(|e| SkillError::Io(skill_md_path.display().to_string(), e))?;
832 let (fm, body) = parse_frontmatter(&content);
833 let body_owned = body.to_string();
835 (fm, Some((content, body_owned)))
836 } else {
837 (None, None)
838 };
839
840 if let Some(fm) = frontmatter {
841 let mut meta = SkillMeta {
843 name: fm.name.unwrap_or_else(|| dir_name.clone()),
844 description: fm.description.unwrap_or_default(),
845 license: fm.license,
846 compatibility: fm.compatibility,
847 extra_metadata: fm.metadata,
848 allowed_tools: fm.allowed_tools,
849 has_frontmatter: true,
850 format: SkillFormat::Anthropic,
851 dir: dir.to_path_buf(),
852 ..Default::default()
853 };
854
855 if let Some(author) = meta.extra_metadata.get("author").cloned() {
857 meta.author = Some(author);
858 }
859 if let Some(version) = meta.extra_metadata.get("version").cloned() {
860 meta.version = version;
861 }
862
863 if skill_toml_path.exists() {
865 let contents = std::fs::read_to_string(&skill_toml_path)
866 .map_err(|e| SkillError::Io(skill_toml_path.display().to_string(), e))?;
867 if let Ok(parsed) = toml::from_str::<SkillToml>(&contents) {
868 let ext = parsed.skill;
869 meta.tools = ext.tools;
871 meta.providers = ext.providers;
872 meta.categories = ext.categories;
873 meta.keywords = ext.keywords;
874 meta.hint = ext.hint;
875 meta.depends_on = ext.depends_on;
876 meta.suggests = ext.suggests;
877 }
878 }
879
880 load_integrity_info(&mut meta);
881 Ok(meta)
882 } else if skill_toml_path.exists() {
883 let contents = std::fs::read_to_string(&skill_toml_path)
885 .map_err(|e| SkillError::Io(skill_toml_path.display().to_string(), e))?;
886 let parsed: SkillToml = toml::from_str(&contents)
887 .map_err(|e| SkillError::Parse(skill_toml_path.display().to_string(), e))?;
888 let mut meta = parsed.skill;
889 meta.dir = dir.to_path_buf();
890 meta.format = SkillFormat::LegacyToml;
891 if meta.name.is_empty() {
892 meta.name = dir_name;
893 }
894 load_integrity_info(&mut meta);
895 Ok(meta)
896 } else if let Some((_full_content, body)) = _body {
897 let description = body
899 .lines()
900 .find(|l| !l.is_empty() && !l.starts_with('#'))
901 .map(|l| l.trim().to_string())
902 .unwrap_or_default();
903
904 Ok(SkillMeta {
905 name: dir_name,
906 description,
907 format: SkillFormat::Inferred,
908 dir: dir.to_path_buf(),
909 ..Default::default()
910 })
911 } else {
912 Err(SkillError::Invalid(format!(
913 "Directory '{}' has neither skill.toml nor SKILL.md",
914 dir.display()
915 )))
916 }
917}
918
919pub fn parse_skill_metadata(
924 name: &str,
925 skill_md_content: &str,
926 skill_toml_content: Option<&str>,
927) -> Result<SkillMeta, SkillError> {
928 let (frontmatter, body) = if !skill_md_content.is_empty() {
929 let (fm, body) = parse_frontmatter(skill_md_content);
930 (fm, Some(body.to_string()))
931 } else {
932 (None, None)
933 };
934
935 if let Some(fm) = frontmatter {
936 let mut meta = SkillMeta {
938 name: fm.name.unwrap_or_else(|| name.to_string()),
939 description: fm.description.unwrap_or_default(),
940 license: fm.license,
941 compatibility: fm.compatibility,
942 extra_metadata: fm.metadata,
943 allowed_tools: fm.allowed_tools,
944 has_frontmatter: true,
945 format: SkillFormat::Anthropic,
946 ..Default::default()
947 };
948
949 if let Some(author) = meta.extra_metadata.get("author").cloned() {
950 meta.author = Some(author);
951 }
952 if let Some(version) = meta.extra_metadata.get("version").cloned() {
953 meta.version = version;
954 }
955
956 if let Some(toml_str) = skill_toml_content {
958 if let Ok(parsed) = toml::from_str::<SkillToml>(toml_str) {
959 let ext = parsed.skill;
960 meta.tools = ext.tools;
961 meta.providers = ext.providers;
962 meta.categories = ext.categories;
963 meta.keywords = ext.keywords;
964 meta.hint = ext.hint;
965 meta.depends_on = ext.depends_on;
966 meta.suggests = ext.suggests;
967 }
968 }
969
970 Ok(meta)
971 } else if let Some(toml_str) = skill_toml_content {
972 let parsed: SkillToml = toml::from_str(toml_str)
974 .map_err(|e| SkillError::Parse(format!("{name}/skill.toml"), e))?;
975 let mut meta = parsed.skill;
976 meta.format = SkillFormat::LegacyToml;
977 if meta.name.is_empty() {
978 meta.name = name.to_string();
979 }
980 Ok(meta)
981 } else if let Some(body) = body {
982 let description = body
984 .lines()
985 .find(|l| !l.is_empty() && !l.starts_with('#'))
986 .map(|l| l.trim().to_string())
987 .unwrap_or_default();
988
989 Ok(SkillMeta {
990 name: name.to_string(),
991 description,
992 format: SkillFormat::Inferred,
993 ..Default::default()
994 })
995 } else {
996 Err(SkillError::Invalid(format!(
997 "Skill '{name}' has neither skill.toml nor SKILL.md content"
998 )))
999 }
1000}
1001
1002fn load_integrity_info(meta: &mut SkillMeta) {
1004 let toml_path = meta.dir.join("skill.toml");
1005 if !toml_path.exists() {
1006 return;
1007 }
1008 let contents = match std::fs::read_to_string(&toml_path) {
1009 Ok(c) => c,
1010 Err(_) => return,
1011 };
1012 let parsed: toml::Value = match toml::from_str(&contents) {
1013 Ok(v) => v,
1014 Err(_) => return,
1015 };
1016 if let Some(integrity) = parsed.get("ati").and_then(|a| a.get("integrity")) {
1017 meta.content_hash = integrity
1018 .get("content_hash")
1019 .and_then(|v| v.as_str())
1020 .map(|s| s.to_string());
1021 meta.source_url = integrity
1022 .get("source_url")
1023 .and_then(|v| v.as_str())
1024 .map(|s| s.to_string());
1025 meta.pinned_sha = integrity
1026 .get("pinned_sha")
1027 .and_then(|v| v.as_str())
1028 .map(|s| s.to_string());
1029 }
1030}
1031
1032pub fn scaffold_skill_toml(name: &str, tools: &[String], provider: Option<&str>) -> String {
1034 let mut toml = format!(
1035 r#"[skill]
1036name = "{name}"
1037version = "0.1.0"
1038description = ""
1039"#
1040 );
1041
1042 if !tools.is_empty() {
1043 let tools_str: Vec<String> = tools.iter().map(|t| format!("\"{t}\"")).collect();
1044 toml.push_str(&format!("tools = [{}]\n", tools_str.join(", ")));
1045 } else {
1046 toml.push_str("tools = []\n");
1047 }
1048
1049 if let Some(p) = provider {
1050 toml.push_str(&format!("providers = [\"{p}\"]\n"));
1051 } else {
1052 toml.push_str("providers = []\n");
1053 }
1054
1055 toml.push_str(
1056 r#"categories = []
1057keywords = []
1058hint = ""
1059depends_on = []
1060suggests = []
1061"#,
1062 );
1063
1064 toml
1065}
1066
1067pub fn scaffold_skill_md(name: &str) -> String {
1069 let title = name
1070 .split('-')
1071 .map(|w| {
1072 let mut c = w.chars();
1073 match c.next() {
1074 None => String::new(),
1075 Some(f) => f.to_uppercase().to_string() + c.as_str(),
1076 }
1077 })
1078 .collect::<Vec<_>>()
1079 .join(" ");
1080
1081 format!(
1082 r#"# {title} Skill
1083
1084TODO: Describe what this skill does and when to use it.
1085
1086## Tools Available
1087
1088- TODO: List the tools this skill covers
1089
1090## Decision Tree
1091
10921. TODO: Step-by-step methodology
1093
1094## Examples
1095
1096TODO: Add example workflows
1097"#
1098 )
1099}
1100
1101pub fn scaffold_skill_md_with_frontmatter(name: &str, description: &str) -> String {
1103 let title = name
1104 .split('-')
1105 .map(|w| {
1106 let mut c = w.chars();
1107 match c.next() {
1108 None => String::new(),
1109 Some(f) => f.to_uppercase().to_string() + c.as_str(),
1110 }
1111 })
1112 .collect::<Vec<_>>()
1113 .join(" ");
1114
1115 format!(
1116 r#"---
1117name: {name}
1118description: {description}
1119metadata:
1120 version: "0.1.0"
1121---
1122
1123# {title} Skill
1124
1125TODO: Describe what this skill does and when to use it.
1126
1127## Tools Available
1128
1129- TODO: List the tools this skill covers
1130
1131## Decision Tree
1132
11331. TODO: Step-by-step methodology
1134
1135## Examples
1136
1137TODO: Add example workflows
1138"#
1139 )
1140}
1141
1142pub fn scaffold_ati_extension_toml(name: &str, tools: &[String], provider: Option<&str>) -> String {
1145 let mut toml = format!(
1146 r#"# ATI extension fields for skill '{name}'
1147# Core metadata (name, description, license) lives in SKILL.md frontmatter.
1148
1149[skill]
1150name = "{name}"
1151"#
1152 );
1153
1154 if !tools.is_empty() {
1155 let tools_str: Vec<String> = tools.iter().map(|t| format!("\"{t}\"")).collect();
1156 toml.push_str(&format!("tools = [{}]\n", tools_str.join(", ")));
1157 } else {
1158 toml.push_str("tools = []\n");
1159 }
1160
1161 if let Some(p) = provider {
1162 toml.push_str(&format!("providers = [\"{p}\"]\n"));
1163 } else {
1164 toml.push_str("providers = []\n");
1165 }
1166
1167 toml.push_str(
1168 r#"categories = []
1169keywords = []
1170depends_on = []
1171suggests = []
1172"#,
1173 );
1174
1175 toml
1176}
1177
1178#[cfg(test)]
1179mod tests {
1180 use super::*;
1181 use std::fs;
1182
1183 fn create_test_skill(
1184 dir: &Path,
1185 name: &str,
1186 tools: &[&str],
1187 providers: &[&str],
1188 categories: &[&str],
1189 ) {
1190 let skill_dir = dir.join(name);
1191 fs::create_dir_all(&skill_dir).unwrap();
1192
1193 let tools_toml: Vec<String> = tools.iter().map(|t| format!("\"{t}\"")).collect();
1194 let providers_toml: Vec<String> = providers.iter().map(|p| format!("\"{p}\"")).collect();
1195 let categories_toml: Vec<String> = categories.iter().map(|c| format!("\"{c}\"")).collect();
1196
1197 let toml_content = format!(
1198 r#"[skill]
1199name = "{name}"
1200version = "1.0.0"
1201description = "Test skill for {name}"
1202tools = [{tools}]
1203providers = [{providers}]
1204categories = [{categories}]
1205keywords = ["test", "{name}"]
1206hint = "Use for testing {name}"
1207depends_on = []
1208suggests = []
1209"#,
1210 tools = tools_toml.join(", "),
1211 providers = providers_toml.join(", "),
1212 categories = categories_toml.join(", "),
1213 );
1214
1215 fs::write(skill_dir.join("skill.toml"), toml_content).unwrap();
1216 fs::write(
1217 skill_dir.join("SKILL.md"),
1218 format!("# {name}\n\nTest skill content."),
1219 )
1220 .unwrap();
1221 }
1222
1223 #[test]
1224 fn test_load_skill_with_toml() {
1225 let tmp = tempfile::tempdir().unwrap();
1226 create_test_skill(
1227 tmp.path(),
1228 "sanctions",
1229 &["ca_business_sanctions_search"],
1230 &["complyadvantage"],
1231 &["compliance"],
1232 );
1233
1234 let registry = SkillRegistry::load(tmp.path()).unwrap();
1235 assert_eq!(registry.skill_count(), 1);
1236
1237 let skill = registry.get_skill("sanctions").unwrap();
1238 assert_eq!(skill.version, "1.0.0");
1239 assert_eq!(skill.tools, vec!["ca_business_sanctions_search"]);
1240 assert_eq!(skill.providers, vec!["complyadvantage"]);
1241 assert_eq!(skill.categories, vec!["compliance"]);
1242 }
1243
1244 #[test]
1245 fn test_load_skill_md_fallback() {
1246 let tmp = tempfile::tempdir().unwrap();
1247 let skill_dir = tmp.path().join("legacy-skill");
1248 fs::create_dir_all(&skill_dir).unwrap();
1249 fs::write(
1250 skill_dir.join("SKILL.md"),
1251 "# Legacy Skill\n\nA skill with only SKILL.md, no skill.toml.\n",
1252 )
1253 .unwrap();
1254
1255 let registry = SkillRegistry::load(tmp.path()).unwrap();
1256 assert_eq!(registry.skill_count(), 1);
1257
1258 let skill = registry.get_skill("legacy-skill").unwrap();
1259 assert_eq!(
1260 skill.description,
1261 "A skill with only SKILL.md, no skill.toml."
1262 );
1263 assert!(skill.tools.is_empty()); }
1265
1266 #[test]
1267 fn test_tool_index() {
1268 let tmp = tempfile::tempdir().unwrap();
1269 create_test_skill(tmp.path(), "skill-a", &["tool_x", "tool_y"], &[], &[]);
1270 create_test_skill(tmp.path(), "skill-b", &["tool_y", "tool_z"], &[], &[]);
1271
1272 let registry = SkillRegistry::load(tmp.path()).unwrap();
1273
1274 let skills = registry.skills_for_tool("tool_x");
1276 assert_eq!(skills.len(), 1);
1277 assert_eq!(skills[0].name, "skill-a");
1278
1279 let skills = registry.skills_for_tool("tool_y");
1281 assert_eq!(skills.len(), 2);
1282
1283 let skills = registry.skills_for_tool("tool_z");
1285 assert_eq!(skills.len(), 1);
1286 assert_eq!(skills[0].name, "skill-b");
1287
1288 assert!(registry.skills_for_tool("nope").is_empty());
1290 }
1291
1292 #[test]
1293 fn test_provider_and_category_index() {
1294 let tmp = tempfile::tempdir().unwrap();
1295 create_test_skill(
1296 tmp.path(),
1297 "compliance-skill",
1298 &[],
1299 &["complyadvantage"],
1300 &["compliance", "aml"],
1301 );
1302
1303 let registry = SkillRegistry::load(tmp.path()).unwrap();
1304
1305 assert_eq!(registry.skills_for_provider("complyadvantage").len(), 1);
1306 assert_eq!(registry.skills_for_category("compliance").len(), 1);
1307 assert_eq!(registry.skills_for_category("aml").len(), 1);
1308 assert!(registry.skills_for_provider("serpapi").is_empty());
1309 }
1310
1311 #[test]
1312 fn test_search() {
1313 let tmp = tempfile::tempdir().unwrap();
1314 create_test_skill(
1315 tmp.path(),
1316 "sanctions-screening",
1317 &["ca_business_sanctions_search"],
1318 &["complyadvantage"],
1319 &["compliance"],
1320 );
1321 create_test_skill(
1322 tmp.path(),
1323 "web-search",
1324 &["web_search"],
1325 &["serpapi"],
1326 &["search"],
1327 );
1328
1329 let registry = SkillRegistry::load(tmp.path()).unwrap();
1330
1331 let results = registry.search("sanctions");
1333 assert!(!results.is_empty());
1334 assert_eq!(results[0].name, "sanctions-screening");
1335
1336 let results = registry.search("web");
1338 assert!(!results.is_empty());
1339 assert_eq!(results[0].name, "web-search");
1340
1341 let results = registry.search("nonexistent");
1343 assert!(results.is_empty());
1344 }
1345
1346 #[test]
1347 fn test_read_content_and_references() {
1348 let tmp = tempfile::tempdir().unwrap();
1349 let skill_dir = tmp.path().join("test-skill");
1350 let refs_dir = skill_dir.join("references");
1351 fs::create_dir_all(&refs_dir).unwrap();
1352
1353 fs::write(
1354 skill_dir.join("skill.toml"),
1355 r#"[skill]
1356name = "test-skill"
1357description = "Test"
1358"#,
1359 )
1360 .unwrap();
1361 fs::write(skill_dir.join("SKILL.md"), "# Test\n\nContent here.").unwrap();
1362 fs::write(refs_dir.join("guide.md"), "Reference guide content").unwrap();
1363
1364 let registry = SkillRegistry::load(tmp.path()).unwrap();
1365
1366 let content = registry.read_content("test-skill").unwrap();
1367 assert!(content.contains("Content here."));
1368
1369 let refs = registry.list_references("test-skill").unwrap();
1370 assert_eq!(refs, vec!["guide.md"]);
1371
1372 let ref_content = registry.read_reference("test-skill", "guide.md").unwrap();
1373 assert!(ref_content.contains("Reference guide content"));
1374 }
1375
1376 #[test]
1377 fn test_resolve_skills_explicit() {
1378 let tmp = tempfile::tempdir().unwrap();
1379 create_test_skill(tmp.path(), "skill-a", &[], &[], &[]);
1380 create_test_skill(tmp.path(), "skill-b", &[], &[], &[]);
1381
1382 let skill_reg = SkillRegistry::load(tmp.path()).unwrap();
1383 let manifest_reg = ManifestRegistry::empty();
1384
1385 let scopes = ScopeConfig {
1386 scopes: vec!["skill:skill-a".to_string()],
1387 sub: String::new(),
1388 expires_at: 0,
1389 rate_config: None,
1390 };
1391
1392 let resolved = resolve_skills(&skill_reg, &manifest_reg, &scopes);
1393 assert_eq!(resolved.len(), 1);
1394 assert_eq!(resolved[0].name, "skill-a");
1395 }
1396
1397 #[test]
1398 fn test_resolve_skills_by_tool_binding() {
1399 let tmp = tempfile::tempdir().unwrap();
1400 create_test_skill(
1401 tmp.path(),
1402 "sanctions-skill",
1403 &["ca_sanctions_search"],
1404 &[],
1405 &[],
1406 );
1407 create_test_skill(
1408 tmp.path(),
1409 "unrelated-skill",
1410 &["some_other_tool"],
1411 &[],
1412 &[],
1413 );
1414
1415 let skill_reg = SkillRegistry::load(tmp.path()).unwrap();
1416
1417 let manifest_reg = ManifestRegistry::empty();
1418
1419 let scopes = ScopeConfig {
1420 scopes: vec!["tool:ca_sanctions_search".to_string()],
1421 sub: String::new(),
1422 expires_at: 0,
1423 rate_config: None,
1424 };
1425
1426 let resolved = resolve_skills(&skill_reg, &manifest_reg, &scopes);
1427 assert_eq!(resolved.len(), 1);
1428 assert_eq!(resolved[0].name, "sanctions-skill");
1429 }
1430
1431 #[test]
1432 fn test_resolve_skills_with_dependencies() {
1433 let tmp = tempfile::tempdir().unwrap();
1434
1435 let dir_a = tmp.path().join("skill-a");
1437 fs::create_dir_all(&dir_a).unwrap();
1438 fs::write(
1439 dir_a.join("skill.toml"),
1440 r#"[skill]
1441name = "skill-a"
1442description = "Skill A"
1443tools = ["tool_a"]
1444depends_on = ["skill-b"]
1445"#,
1446 )
1447 .unwrap();
1448 fs::write(dir_a.join("SKILL.md"), "# Skill A").unwrap();
1449
1450 let dir_b = tmp.path().join("skill-b");
1452 fs::create_dir_all(&dir_b).unwrap();
1453 fs::write(
1454 dir_b.join("skill.toml"),
1455 r#"[skill]
1456name = "skill-b"
1457description = "Skill B"
1458tools = ["tool_b"]
1459"#,
1460 )
1461 .unwrap();
1462 fs::write(dir_b.join("SKILL.md"), "# Skill B").unwrap();
1463
1464 let skill_reg = SkillRegistry::load(tmp.path()).unwrap();
1465
1466 let manifest_tmp = tempfile::tempdir().unwrap();
1467 fs::create_dir_all(manifest_tmp.path()).unwrap();
1468 let manifest_reg = ManifestRegistry::load(manifest_tmp.path())
1469 .unwrap_or_else(|_| panic!("cannot load empty manifest dir"));
1470
1471 let scopes = ScopeConfig {
1472 scopes: vec!["tool:tool_a".to_string()],
1473 sub: String::new(),
1474 expires_at: 0,
1475 rate_config: None,
1476 };
1477
1478 let resolved = resolve_skills(&skill_reg, &manifest_reg, &scopes);
1479 assert_eq!(resolved.len(), 2);
1481 let names: Vec<&str> = resolved.iter().map(|s| s.name.as_str()).collect();
1482 assert!(names.contains(&"skill-a"));
1483 assert!(names.contains(&"skill-b"));
1484 }
1485
1486 #[test]
1487 fn test_scaffold() {
1488 let toml = scaffold_skill_toml(
1489 "my-skill",
1490 &["tool_a".into(), "tool_b".into()],
1491 Some("provider_x"),
1492 );
1493 assert!(toml.contains("name = \"my-skill\""));
1494 assert!(toml.contains("\"tool_a\""));
1495 assert!(toml.contains("\"provider_x\""));
1496
1497 let md = scaffold_skill_md("my-cool-skill");
1498 assert!(md.contains("# My Cool Skill Skill"));
1499 }
1500
1501 #[test]
1502 fn test_build_skill_context() {
1503 let skill = SkillMeta {
1504 name: "test-skill".to_string(),
1505 version: "1.0.0".to_string(),
1506 description: "A test skill".to_string(),
1507 tools: vec!["tool_a".to_string(), "tool_b".to_string()],
1508 hint: Some("Use for testing".to_string()),
1509 suggests: vec!["other-skill".to_string()],
1510 ..Default::default()
1511 };
1512
1513 let ctx = build_skill_context(&[&skill]);
1514 assert!(ctx.contains("**test-skill**"));
1515 assert!(ctx.contains("A test skill"));
1516 assert!(ctx.contains("Use for testing"));
1517 assert!(ctx.contains("tool_a, tool_b"));
1518 assert!(ctx.contains("other-skill"));
1519 }
1520
1521 #[test]
1522 fn test_empty_directory() {
1523 let tmp = tempfile::tempdir().unwrap();
1524 let registry = SkillRegistry::load(tmp.path()).unwrap();
1525 assert_eq!(registry.skill_count(), 0);
1526 }
1527
1528 #[test]
1529 fn test_nonexistent_directory() {
1530 let registry = SkillRegistry::load(Path::new("/nonexistent/path")).unwrap();
1531 assert_eq!(registry.skill_count(), 0);
1532 }
1533}