1use std::collections::HashSet;
15use std::path::{Path, PathBuf};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum SkillSource {
20 Project,
22 User,
24}
25
26#[derive(Debug, Clone)]
28pub struct Skill {
29 pub name: String,
30 pub description: String,
31 pub body: String,
33 pub dir: PathBuf,
35 pub source: SkillSource,
36}
37
38#[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 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 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
104fn 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
135fn 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
159fn parse_frontmatter(fm: &str) -> ParsedFrontmatter {
163 let mut out = ParsedFrontmatter::default();
164 for line in fm.lines() {
165 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 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 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(); std::fs::write(root.join("loose-file.md"), "x").unwrap(); 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}