Skip to main content

ati/core/
skill.rs

1/// Skill management — structured metadata, registry, and scope-driven resolution.
2///
3/// Each skill directory contains:
4///   - `SKILL.md`    — methodology content with optional YAML frontmatter (Anthropic spec)
5///   - `skill.toml`  — optional ATI extension for tool/provider/category bindings
6///   - `references/` — optional supporting documentation
7///   - `scripts/`    — optional helper scripts
8///   - `assets/`     — optional templates, configs, data files
9///
10/// Metadata priority: YAML frontmatter in SKILL.md > skill.toml > inferred from content.
11/// Skills reference manifests (tools, providers, categories), never the reverse.
12/// Installing a skill never requires editing existing manifests.
13use 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/// Anthropic Agent Skills spec frontmatter (YAML in SKILL.md).
37#[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    /// Space-delimited allowed tools string, e.g. "Bash(git:*) Read"
46    #[serde(rename = "allowed-tools")]
47    pub allowed_tools: Option<String>,
48}
49
50/// Parse YAML frontmatter from SKILL.md content.
51///
52/// Returns `(Some(frontmatter), body)` if `---` delimiters found and YAML parses,
53/// or `(None, original_content)` on any failure (graceful fallback).
54pub 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    // Find the closing `---` after the opening one
61    let after_open = &trimmed[3..];
62    // Skip the rest of the opening `---` line
63    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..]; // skip \n---
72                                                         // Skip rest of closing --- line
73            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), // Malformed YAML → treat as no frontmatter
81            }
82        }
83        None => (None, content),
84    }
85}
86
87/// Strip YAML frontmatter from SKILL.md content, returning only the body.
88pub fn strip_frontmatter(content: &str) -> &str {
89    let (_, body) = parse_frontmatter(content);
90    body
91}
92
93/// Compute SHA-256 hash of content, returning lowercase hex string.
94pub 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
101/// Validate a skill name against the Anthropic Agent Skills naming rules.
102///
103/// Rules: 1-64 chars, lowercase letters + digits + hyphens, no consecutive hyphens,
104/// must start/end with a letter or digit.
105pub 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    // Must start and end with alphanumeric
111    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    // Only lowercase, digits, hyphens; no consecutive hyphens
118    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/// Skill metadata format — indicates how the metadata was sourced.
135#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
136pub enum SkillFormat {
137    /// Anthropic spec: YAML frontmatter in SKILL.md
138    #[serde(rename = "anthropic")]
139    Anthropic,
140    /// ATI legacy: skill.toml only
141    #[serde(rename = "legacy-toml")]
142    LegacyToml,
143    /// Inferred: SKILL.md without frontmatter or skill.toml
144    #[serde(rename = "inferred")]
145    Inferred,
146}
147
148/// Structured metadata from `skill.toml` and/or YAML frontmatter.
149#[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    // --- Tool/provider/category bindings (auto-load when these are in scope) ---
160    /// Exact tool names this skill covers (e.g., ["ca_business_sanctions_search"])
161    #[serde(default)]
162    pub tools: Vec<String>,
163    /// Provider names this skill covers (e.g., ["complyadvantage"])
164    #[serde(default)]
165    pub providers: Vec<String>,
166    /// Provider categories this skill covers (e.g., ["compliance"])
167    #[serde(default)]
168    pub categories: Vec<String>,
169
170    // --- Discovery metadata ---
171    #[serde(default)]
172    pub keywords: Vec<String>,
173    #[serde(default)]
174    pub hint: Option<String>,
175
176    // --- Dependencies ---
177    /// Skills that must be transitively loaded with this one
178    #[serde(default)]
179    pub depends_on: Vec<String>,
180    /// Informational suggestions (not auto-loaded)
181    #[serde(default)]
182    pub suggests: Vec<String>,
183
184    // --- Anthropic spec fields ---
185    /// SPDX license identifier (from frontmatter)
186    #[serde(default)]
187    pub license: Option<String>,
188    /// Compatibility notes (from frontmatter, max 500 chars)
189    #[serde(default)]
190    pub compatibility: Option<String>,
191    /// Arbitrary metadata key-value pairs (from frontmatter `metadata:` block)
192    #[serde(default)]
193    pub extra_metadata: HashMap<String, String>,
194    /// Space-delimited allowed tools (from frontmatter `allowed-tools:`)
195    #[serde(default)]
196    pub allowed_tools: Option<String>,
197    /// Whether the skill has YAML frontmatter in SKILL.md
198    #[serde(default)]
199    pub has_frontmatter: bool,
200    /// How metadata was sourced
201    #[serde(default = "default_format")]
202    pub format: SkillFormat,
203
204    // --- Supply chain integrity (stored in [ati.integrity] section of skill.toml) ---
205    /// Source URL this skill was installed from
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub source_url: Option<String>,
208    /// SHA-256 hash of SKILL.md content at install time
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub content_hash: Option<String>,
211    /// Pinned git SHA (from source@SHA syntax)
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub pinned_sha: Option<String>,
214
215    // --- Runtime (not in TOML, set after loading) ---
216    /// Absolute path to the skill directory
217    #[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/// Wrapper for the `[skill]` table in skill.toml.
258#[derive(Debug, Deserialize)]
259struct SkillToml {
260    skill: SkillMeta,
261}
262
263/// Registry of all loaded skills with indexes for fast lookup.
264pub struct SkillRegistry {
265    skills: Vec<SkillMeta>,
266    /// skill name → index
267    name_index: HashMap<String, usize>,
268    /// tool name → skill indices
269    tool_index: HashMap<String, Vec<usize>>,
270    /// provider name → skill indices
271    provider_index: HashMap<String, Vec<usize>>,
272    /// category name → skill indices
273    category_index: HashMap<String, Vec<usize>>,
274    /// Cached files for non-filesystem skills (e.g. GCS).
275    /// Key: (skill_name, relative_path), Value: file bytes.
276    files_cache: HashMap<(String, String), Vec<u8>>,
277}
278
279impl SkillRegistry {
280    /// Load all skills from a directory. Each subdirectory is a skill.
281    ///
282    /// If `skill.toml` exists, parse it for full metadata.
283    /// Otherwise, fall back to reading `SKILL.md` for name + description only.
284    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            // Not an error — just an empty registry
293            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    /// Merge skills from a remote source (e.g. GCS).
348    /// Local skills take precedence on name collision.
349    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                // Local wins — skip this GCS skill entirely
355                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        // Only merge files for skills that were actually added (not skipped).
379        // This preserves "local wins" at the content layer too.
380        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    /// Get a skill by name.
388    pub fn get_skill(&self, name: &str) -> Option<&SkillMeta> {
389        self.name_index.get(name).map(|&idx| &self.skills[idx])
390    }
391
392    /// List all loaded skills.
393    pub fn list_skills(&self) -> &[SkillMeta] {
394        &self.skills
395    }
396
397    /// Skills that cover a specific tool name.
398    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    /// Skills that cover a specific provider name.
406    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    /// Skills that cover a specific category.
414    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    /// Search skills by fuzzy matching on name, description, keywords, hint, and tool names.
422    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                    // Name match (highest weight)
436                    if name_lower.contains(term) {
437                        score += 10;
438                    }
439                    // Description match
440                    if desc_lower.contains(term) {
441                        score += 5;
442                    }
443                    // Keyword match
444                    if skill
445                        .keywords
446                        .iter()
447                        .any(|k| k.to_lowercase().contains(term))
448                    {
449                        score += 8;
450                    }
451                    // Tool name match
452                    if skill.tools.iter().any(|t| t.to_lowercase().contains(term)) {
453                        score += 6;
454                    }
455                    // Hint match
456                    if let Some(hint) = &skill.hint {
457                        if hint.to_lowercase().contains(term) {
458                            score += 4;
459                        }
460                    }
461                    // Provider match
462                    if skill
463                        .providers
464                        .iter()
465                        .any(|p| p.to_lowercase().contains(term))
466                    {
467                        score += 6;
468                    }
469                    // Category match
470                    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        // Sort by score descending
488        scored.sort_by(|a, b| b.0.cmp(&a.0));
489        scored.into_iter().map(|(_, skill)| skill).collect()
490    }
491
492    /// Read the SKILL.md content for a skill, stripping any YAML frontmatter.
493    /// Checks the in-memory files cache first (for GCS skills), then falls back to filesystem.
494    pub fn read_content(&self, name: &str) -> Result<String, SkillError> {
495        // Check files cache (GCS / remote skills)
496        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        // Fall back to filesystem (local skills)
505        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    /// List reference files for a skill.
518    /// Checks files cache first (GCS), then filesystem.
519    pub fn list_references(&self, name: &str) -> Result<Vec<String>, SkillError> {
520        // Check files cache for references/*
521        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        // Fall back to filesystem
535        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    /// Read a specific reference file.
556    /// Checks files cache first (GCS), then filesystem.
557    pub fn read_reference(&self, skill_name: &str, ref_name: &str) -> Result<String, SkillError> {
558        // Path traversal protection: reject names with path components
559        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        // Check files cache (GCS / remote skills)
570        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        // Canonicalize and verify the resolved path is inside the references directory
584        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    /// Get all files in a skill as a map of relative_path → bytes.
604    /// Works for both local (filesystem) and remote (cached) skills.
605    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        // Collect from files_cache (GCS / remote skills)
613        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 nothing from cache, read from filesystem
620        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    /// Number of loaded skills.
631    pub fn skill_count(&self) -> usize {
632        self.skills.len()
633    }
634
635    /// Validate a skill's tool bindings against a ManifestRegistry.
636    /// Returns (valid_tools, unknown_tools).
637    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
661/// Resolve which skills should be auto-loaded based on scopes and a ManifestRegistry.
662///
663/// Resolution cascade:
664/// 1. Explicit skill scopes: "skill:X" → load X directly
665/// 2. Tool binding: "tool:Y" → skills where tools contains "Y"
666/// 3. Provider binding: tool Y belongs to provider P → skills where providers contains "P"
667/// 4. Category binding: provider P has category C → skills where categories contains "C"
668/// 5. Dependency resolution: loaded skill depends_on Z → transitively load Z
669///
670/// Wildcard scope (*) = all skills available but not auto-loaded.
671pub 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        // 1. Explicit skill scopes
681        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        // 2. Tool binding → skills covering that tool
690        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            // 3. Provider binding → skills covering the tool's provider
700            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                // 4. Category binding → skills covering the provider's category
710                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    // 5. Dependency resolution (transitive)
724    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
743/// Maximum size of skill content injected into LLM system prompts (32 KB).
744/// Prevents prompt injection via extremely large SKILL.md files.
745const MAX_SKILL_INJECT_SIZE: usize = 32 * 1024;
746
747/// Build a skill context string for LLM system prompts.
748/// For each skill: name, description, hint, covered tools.
749/// Content is bounded and delimited to mitigate prompt injection.
750pub 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
786// --- Private helpers ---
787
788/// Load a single skill from a directory.
789///
790/// Priority:
791///   (A) SKILL.md with YAML frontmatter → primary source; merge ATI extensions from skill.toml
792/// Recursively collect all files in a directory into a map of relative_path → bytes.
793fn 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
816///   (B) No frontmatter + skill.toml → current legacy behavior
817///   (C) No frontmatter + no skill.toml + SKILL.md exists → infer from content
818fn 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    // Try to read and parse frontmatter from SKILL.md
829    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        // We need owned body for description inference later
834        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        // --- (A) Frontmatter exists → primary source ---
842        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        // Extract author/version from frontmatter metadata if present
856        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        // Merge ATI-extension fields from skill.toml if it exists
864        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                // ATI-specific fields not in frontmatter
870                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        // --- (B) No frontmatter + skill.toml → legacy behavior ---
884        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        // --- (C) No frontmatter + no skill.toml + SKILL.md exists → infer ---
898        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
919/// Parse skill metadata from raw SKILL.md content and optional skill.toml content.
920///
921/// Used by both local filesystem loading and remote sources (GCS).
922/// The `name` parameter is the skill directory name (used as fallback if not in metadata).
923pub 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        // (A) Frontmatter exists → primary source
937        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        // Merge ATI extensions from skill.toml if provided
957        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        // (B) No frontmatter + skill.toml → legacy
973        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        // (C) SKILL.md without frontmatter or skill.toml → infer
983        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
1002/// Read [ati.integrity] section from skill.toml and populate SkillMeta fields.
1003fn 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
1032/// Generate a skeleton `skill.toml` for a new skill.
1033pub 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
1067/// Generate a skeleton `SKILL.md` (legacy format without frontmatter).
1068pub 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
1101/// Generate a skeleton `SKILL.md` with Anthropic-spec YAML frontmatter.
1102pub 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
1142/// Generate an ATI extension `skill.toml` for fields not in the Anthropic spec.
1143/// Used alongside a SKILL.md with frontmatter.
1144pub 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()); // No tool bindings without skill.toml
1264    }
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        // tool_x → only skill-a
1275        let skills = registry.skills_for_tool("tool_x");
1276        assert_eq!(skills.len(), 1);
1277        assert_eq!(skills[0].name, "skill-a");
1278
1279        // tool_y → both skills
1280        let skills = registry.skills_for_tool("tool_y");
1281        assert_eq!(skills.len(), 2);
1282
1283        // tool_z → only skill-b
1284        let skills = registry.skills_for_tool("tool_z");
1285        assert_eq!(skills.len(), 1);
1286        assert_eq!(skills[0].name, "skill-b");
1287
1288        // nonexistent → empty
1289        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        // Search for "sanctions"
1332        let results = registry.search("sanctions");
1333        assert!(!results.is_empty());
1334        assert_eq!(results[0].name, "sanctions-screening");
1335
1336        // Search for "web"
1337        let results = registry.search("web");
1338        assert!(!results.is_empty());
1339        assert_eq!(results[0].name, "web-search");
1340
1341        // Search for something absent
1342        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        // Create skill-a that depends on skill-b
1436        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        // Create skill-b (dependency)
1451        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        // Should resolve both skill-a (via tool binding) and skill-b (via dependency)
1480        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}