Skip to main content

pixie_pi/
skills.rs

1//! Skill discovery and parsing — Claude Code–compatible.
2//!
3//! A skill is a directory `<root>/<name>/SKILL.md` where `<root>` is
4//! `.claude/skills` (project) or `~/.claude/skills` (user). The `SKILL.md`
5//! begins with a small YAML frontmatter (`name`, `description`) followed by the
6//! markdown body. Following Claude Code's progressive-disclosure model, only the
7//! name + description are surfaced up front (in the system prompt); the body is
8//! loaded into context only when the model invokes the `skill` tool.
9//!
10//! Other frontmatter keys (e.g. Claude Code's `allowed-tools`) are ignored:
11//! skills do not restrict the tool set here — every registered tool remains
12//! callable while a skill runs.
13
14use std::collections::HashSet;
15use std::path::{Path, PathBuf};
16
17/// Where a skill was discovered.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum SkillSource {
20    /// `<cwd>/.claude/skills` — takes precedence over user skills.
21    Project,
22    /// `~/.claude/skills`.
23    User,
24}
25
26/// One discovered skill.
27#[derive(Debug, Clone)]
28pub struct Skill {
29    pub name: String,
30    pub description: String,
31    /// The markdown body (after the frontmatter).
32    pub body: String,
33    /// The skill's directory — supporting files live here.
34    pub dir: PathBuf,
35    pub source: SkillSource,
36}
37
38/// The set of discovered skills.
39#[derive(Debug, Clone, Default)]
40pub struct Skills {
41    pub skills: Vec<Skill>,
42}
43
44impl Skills {
45    pub fn empty() -> Self {
46        Self::default()
47    }
48
49    /// Discover skills in `<cwd>/.claude/skills` (project) and
50    /// `~/.claude/skills` (user). Project skills shadow user skills of the same
51    /// name. Returns an empty registry if neither directory exists.
52    pub fn discover(cwd: &Path) -> Self {
53        let mut roots: Vec<(PathBuf, SkillSource)> =
54            vec![(cwd.join(".claude").join("skills"), SkillSource::Project)];
55        if let Some(home) = dirs::home_dir() {
56            roots.push((home.join(".claude").join("skills"), SkillSource::User));
57        }
58        Self::discover_from_roots(&roots)
59    }
60
61    /// Discovery over an explicit list of `(root, source)`, earlier roots
62    /// shadowing later ones. Separated out so tests can supply synthetic roots
63    /// (including a fake "user" dir) without touching the real home directory.
64    pub fn discover_from_roots(roots: &[(PathBuf, SkillSource)]) -> Self {
65        let mut skills: Vec<Skill> = Vec::new();
66        let mut seen: HashSet<String> = HashSet::new();
67        for (root, source) in roots {
68            if !root.is_dir() {
69                continue;
70            }
71            let Ok(rd) = std::fs::read_dir(root) else {
72                continue;
73            };
74            let mut entries: Vec<PathBuf> = rd.filter_map(Result::ok).map(|e| e.path()).collect();
75            entries.sort();
76            for dir in entries {
77                if !dir.is_dir() {
78                    continue;
79                }
80                let skill_md = dir.join("SKILL.md");
81                if !skill_md.is_file() {
82                    continue;
83                }
84                let Some(skill) = parse_skill_file(&skill_md, &dir, *source) else {
85                    continue;
86                };
87                if seen.insert(skill.name.clone()) {
88                    skills.push(skill);
89                }
90            }
91        }
92        Skills { skills }
93    }
94
95    pub fn find(&self, name: &str) -> Option<&Skill> {
96        self.skills.iter().find(|s| s.name == name)
97    }
98
99    pub fn names(&self) -> Vec<&str> {
100        self.skills.iter().map(|s| s.name.as_str()).collect()
101    }
102}
103
104/// Read + parse a `SKILL.md`. Falls back to the directory name and an empty
105/// description when frontmatter is absent or unparsable.
106fn parse_skill_file(path: &Path, dir: &Path, source: SkillSource) -> Option<Skill> {
107    let raw = std::fs::read_to_string(path).ok()?;
108    let (fm, body) = split_frontmatter(&raw);
109    let parsed = fm.as_deref().map(parse_frontmatter);
110    let dir_name = dir.file_name()?.to_string_lossy().to_string();
111    let name = parsed
112        .as_ref()
113        .map(|p| p.name.clone())
114        .filter(|n| !n.is_empty())
115        .unwrap_or(dir_name);
116    let description = parsed
117        .as_ref()
118        .map(|p| p.description.clone())
119        .unwrap_or_default();
120    Some(Skill {
121        name,
122        description,
123        body,
124        dir: dir.to_path_buf(),
125        source,
126    })
127}
128
129#[derive(Debug, Default)]
130struct ParsedFrontmatter {
131    name: String,
132    description: String,
133}
134
135/// Split a `SKILL.md` into `(frontmatter, body)`. Frontmatter is delimited by a
136/// leading `---` line and a closing `---` (or `...`) line. Returns
137/// `(None, whole_file)` when there is no frontmatter.
138fn split_frontmatter(raw: &str) -> (Option<String>, String) {
139    let raw = raw.strip_prefix('\u{feff}').unwrap_or(raw);
140    let lines: Vec<&str> = raw.split('\n').collect();
141    if lines.first().map(|l| l.trim() == "---").unwrap_or(false) {
142        if let Some(rel) = lines
143            .iter()
144            .skip(1)
145            .position(|l| l.trim() == "---" || l.trim() == "...")
146        {
147            let close = rel + 1;
148            let fm = lines[1..close].join("\n");
149            let body = lines
150                .get(close + 1..)
151                .map(|s| s.join("\n"))
152                .unwrap_or_default();
153            return (Some(fm), body);
154        }
155    }
156    (None, raw.to_string())
157}
158
159/// Parse the small subset of YAML frontmatter skills use: scalar `name` and
160/// `description`. Every other key (and all indented/list lines) is ignored —
161/// we deliberately don't model `allowed-tools` or other fields.
162fn parse_frontmatter(fm: &str) -> ParsedFrontmatter {
163    let mut out = ParsedFrontmatter::default();
164    for line in fm.lines() {
165        // Only top-level scalar keys; skip indented lines (lists, nested maps).
166        if line.starts_with(' ') || line.starts_with('\t') {
167            continue;
168        }
169        if let Some((k, v)) = line.split_once(':') {
170            match k.trim() {
171                "name" => out.name = unquote(v.trim()),
172                "description" => out.description = unquote(v.trim()),
173                _ => {}
174            }
175        }
176    }
177    out
178}
179
180fn unquote(s: &str) -> String {
181    let s = s.trim();
182    if s.len() >= 2
183        && ((s.starts_with('"') && s.ends_with('"'))
184            || (s.starts_with('\'') && s.ends_with('\'')))
185{
186        s[1..s.len() - 1].to_string()
187    } else {
188        s.to_string()
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    fn write_skill(root: &Path, name: &str, body: &str) -> PathBuf {
197        let dir = root.join(name);
198        std::fs::create_dir_all(&dir).unwrap();
199        std::fs::write(dir.join("SKILL.md"), body).unwrap();
200        dir
201    }
202
203    #[test]
204    fn parses_name_description_and_body() {
205        let md = "---\nname: my-skill\ndescription: Use when foo\n---\n# Steps\nDo the thing.\n";
206        let (fm, body) = split_frontmatter(md);
207        let p = parse_frontmatter(&fm.unwrap());
208        assert_eq!(p.name, "my-skill");
209        assert_eq!(p.description, "Use when foo");
210        assert!(body.contains("# Steps"));
211        assert!(body.contains("Do the thing."));
212    }
213
214    #[test]
215    fn ignores_unknown_frontmatter_keys_like_allowed_tools() {
216        // `allowed-tools` (and any other unknown key) must be ignored — skills
217        // don't restrict the tool set, so we don't even parse it. name/description
218        // still parse correctly alongside it.
219        let p = parse_frontmatter("name: a\ndescription: do a thing\nallowed-tools: [bash, read]\n");
220        assert_eq!(p.name, "a");
221        assert_eq!(p.description, "do a thing");
222    }
223
224    #[test]
225    fn strips_quotes_around_values() {
226        let p = parse_frontmatter("name: \"quoted-name\"\ndescription: 'single quoted'\n");
227        assert_eq!(p.name, "quoted-name");
228        assert_eq!(p.description, "single quoted");
229    }
230
231    #[test]
232    fn no_frontmatter_falls_back_to_dir_name() {
233        let tmp = std::env::temp_dir().join(format!("pi-skills-nofm-{}", uuid::Uuid::new_v4()));
234        let dir = write_skill(&tmp, "plain-skill", "Just a body, no frontmatter.\n");
235        let skill = parse_skill_file(&dir.join("SKILL.md"), &dir, SkillSource::Project).unwrap();
236        assert_eq!(skill.name, "plain-skill");
237        assert_eq!(skill.description, "");
238        assert!(skill.body.contains("Just a body"));
239        let _ = std::fs::remove_dir_all(&tmp);
240    }
241
242    #[test]
243    fn discover_finds_project_and_user_skills() {
244        let project = std::env::temp_dir().join(format!("pi-skills-proj-{}", uuid::Uuid::new_v4()));
245        let user = std::env::temp_dir().join(format!("pi-skills-user-{}", uuid::Uuid::new_v4()));
246        write_skill(&project, "alpha", "---\nname: alpha\ndescription: a\n---\nbody-a\n");
247        write_skill(&user, "beta", "---\nname: beta\ndescription: b\n---\nbody-b\n");
248        let skills = Skills::discover_from_roots(&[
249            (project.clone(), SkillSource::Project),
250            (user.clone(), SkillSource::User),
251        ]);
252        let names = skills.names();
253        assert!(names.contains(&"alpha"), "{names:?}");
254        assert!(names.contains(&"beta"), "{names:?}");
255        let _ = std::fs::remove_dir_all(&project);
256        let _ = std::fs::remove_dir_all(&user);
257    }
258
259    #[test]
260    fn project_skill_shadows_user_skill_of_same_name() {
261        let project = std::env::temp_dir().join(format!("pi-skills-sp-{}", uuid::Uuid::new_v4()));
262        let user = std::env::temp_dir().join(format!("pi-skills-su-{}", uuid::Uuid::new_v4()));
263        write_skill(&project, "shared", "---\nname: shared\ndescription: PROJECT\n---\nproj-body\n");
264        write_skill(&user, "shared", "---\nname: shared\ndescription: USER\n---\nuser-body\n");
265        let skills = Skills::discover_from_roots(&[
266            (project.clone(), SkillSource::Project),
267            (user.clone(), SkillSource::User),
268        ]);
269        // Only one "shared", and it's the project one.
270        assert_eq!(skills.skills.iter().filter(|s| s.name == "shared").count(), 1);
271        assert_eq!(skills.find("shared").unwrap().description, "PROJECT");
272        assert_eq!(skills.find("shared").unwrap().source, SkillSource::Project);
273        let _ = std::fs::remove_dir_all(&project);
274        let _ = std::fs::remove_dir_all(&user);
275    }
276
277    #[test]
278    fn discover_ignores_files_and_dirs_without_skill_md() {
279        let root = std::env::temp_dir().join(format!("pi-skills-skip-{}", uuid::Uuid::new_v4()));
280        std::fs::create_dir_all(root.join("not-a-skill")).unwrap(); // no SKILL.md
281        std::fs::write(root.join("loose-file.md"), "x").unwrap(); // not a dir
282        write_skill(&root, "real", "---\nname: real\ndescription: r\n---\nb\n");
283        let skills = Skills::discover_from_roots(&[(root.clone(), SkillSource::Project)]);
284        assert_eq!(skills.names(), vec!["real"]);
285        let _ = std::fs::remove_dir_all(&root);
286    }
287}