Skip to main content

trusty_code/skills/
mod.rs

1//! Progressive-disclosure skill discovery for `.claude/skills/` (#2069, vision
2//! spec §5.3, Resolved Decision #7).
3//!
4//! Why: A project's `.claude/skills/` catalog can hold dozens of skills, but
5//! any given task only ever invokes a handful of them. Injecting every
6//! skill's full Markdown body into the system prompt up front wastes
7//! 500-1000+ tokens per session for a 20-skill catalog (spec §5.3 impact
8//! estimate) when ~80% of skills are never invoked. Splitting a skill into
9//! cheap, always-cached metadata (name + one-line description, ~100 tokens
10//! per skill) and an on-demand-loaded body lets the PM/agents see the full
11//! catalog for free and pay the body's token cost only for skills they
12//! actually use. This module mirrors `agents::discover_agents`'s directory
13//! scanning pattern, adapted for the Claude-Code skill layout: one
14//! subdirectory per skill, each holding a `SKILL.md` with YAML-ish
15//! frontmatter (`name:`, `description:`, …) followed by the Markdown body.
16//! What: [`SkillMetadata`] (the cached catalog entry), [`locate_skills_dir`]
17//! (resolves `<project_root>/.claude/skills` — the Claude-Code-compatible
18//! path; deliberately NOT `~/.trusty-mpm/skills/`), [`discover_skill_metadata`]
19//! (scans the directory and parses just the frontmatter of every skill),
20//! [`load_skill_body`] (the lazy, on-invoke full-body loader), and
21//! [`format_skill_catalog`] (renders the metadata list for prompt injection).
22//! [`FsSkillResolver`] implements `tools::traits::SkillResolver` over this
23//! discovery layer, giving the tool-registry layer a ready-to-register
24//! concrete resolver.
25//! Test: `skills::tests::*` — discovery over tempdir fixtures (happy path,
26//! missing dir, missing `SKILL.md`, malformed/no-frontmatter file), lazy body
27//! load (found + unknown-name), catalog formatting (empty + populated), and
28//! `FsSkillResolver`'s `SkillResolver` trait conformance.
29
30mod frontmatter;
31
32use std::path::{Path, PathBuf};
33
34use thiserror::Error;
35
36use crate::tools::traits::SkillResolver;
37use frontmatter::{parse_frontmatter, strip_frontmatter};
38
39/// Cheap, always-cached catalog entry for one discovered skill.
40///
41/// Why: The PM/agents need to see what skills exist and when to reach for
42/// them without paying for every skill's full body up front.
43/// What: `name` (frontmatter `name:`, falling back to the skill's directory
44/// name) and `description` (frontmatter `description:`, empty string if
45/// absent).
46/// Test: `discover_skill_metadata_reads_name_and_description`.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct SkillMetadata {
49    pub name: String,
50    pub description: String,
51}
52
53/// Errors from lazily loading a skill's full body.
54///
55/// Why: A named error type lets `SkillResolver::resolve` and the `use_skill`
56/// tool distinguish "unknown skill" (an LLM hallucinated a name) from a
57/// genuine IO failure, both without panicking.
58/// What: `Unknown` — the name is not in the discovered catalog; `Io` — the
59/// `SKILL.md` file could not be read even though the name is known.
60/// Test: `load_skill_body_rejects_unknown_name`, `load_skill_body_io_error`.
61#[derive(Debug, Error)]
62pub enum SkillError {
63    #[error("skill '{0}' is not in the discovered catalog")]
64    Unknown(String),
65    #[error("failed to read skill body for '{name}': {source}")]
66    Io {
67        name: String,
68        #[source]
69        source: std::io::Error,
70    },
71}
72
73/// Locate the Claude-Code-compatible skills directory for a project root.
74///
75/// Why: #2069 pins this to `.claude/skills/` exactly — the Claude-Code-native
76/// convention — and explicitly NOT the legacy `~/.trusty-mpm/skills/` path
77/// trusty-mpm uses, so a project's skill catalog resolves identically whether
78/// browsed by a human in Claude Code or discovered by `tcode`.
79/// What: Returns `<project_root>/.claude/skills` (may not exist yet — callers
80/// handle absence via `discover_skill_metadata`'s empty-Vec fallback).
81/// Test: `locate_skills_dir_is_dot_claude_skills`.
82pub fn locate_skills_dir(project_root: &Path) -> PathBuf {
83    project_root.join(".claude").join("skills")
84}
85
86/// Discover skill metadata from every `<dir>/<skill-name>/SKILL.md`.
87///
88/// Why: The catalog must be built once, cheaply, from cheap-to-read
89/// frontmatter only — the whole point of progressive disclosure is to avoid
90/// reading full skill bodies until they are actually invoked.
91/// What: Scans immediate subdirectories of `dir`; a subdirectory without a
92/// readable `SKILL.md` is skipped (not an error — mirrors
93/// `agents::discover_agents`'s graceful-skip convention). Returns entries
94/// sorted by `name`. A missing/unreadable `dir` yields an empty Vec.
95/// Test: `discover_skill_metadata_reads_name_and_description`,
96/// `discover_skill_metadata_skips_dir_without_skill_md`,
97/// `discover_skill_metadata_missing_dir_is_empty`,
98/// `discover_skill_metadata_falls_back_to_dirname`.
99pub fn discover_skill_metadata(dir: &Path) -> Vec<SkillMetadata> {
100    let Ok(entries) = std::fs::read_dir(dir) else {
101        tracing::debug!("skills dir not found or unreadable: {}", dir.display());
102        return vec![];
103    };
104
105    let mut skills: Vec<SkillMetadata> = entries
106        .flatten()
107        .filter_map(|entry| load_metadata_from_skill_dir(&entry.path()))
108        .collect();
109    skills.sort_by(|a, b| a.name.cmp(&b.name));
110    skills
111}
112
113/// Load one skill directory's metadata, if it holds a readable `SKILL.md`.
114///
115/// Why: Factored out of `discover_skill_metadata` so each rejection reason
116/// (not a directory, no `SKILL.md`, unreadable) can be logged distinctly.
117/// What: Returns `None` (with a debug log) for anything that is not a skill
118/// directory; otherwise parses frontmatter and falls back to the directory
119/// name when `name:` is absent.
120/// Test: covered via `discover_skill_metadata`'s tests above.
121fn load_metadata_from_skill_dir(path: &Path) -> Option<SkillMetadata> {
122    if !path.is_dir() {
123        return None;
124    }
125    let dirname = path.file_name()?.to_str()?.to_string();
126    let skill_md = path.join("SKILL.md");
127    let raw = match std::fs::read_to_string(&skill_md) {
128        Ok(raw) => raw,
129        Err(e) => {
130            tracing::debug!("skipping skill dir '{dirname}': no readable SKILL.md ({e})");
131            return None;
132        }
133    };
134    let front = parse_frontmatter(&raw);
135    let name = front.get("name").cloned().unwrap_or(dirname);
136    let description = front.get("description").cloned().unwrap_or_default();
137    Some(SkillMetadata { name, description })
138}
139
140/// Lazily load one skill's full Markdown body (the frontmatter stripped off).
141///
142/// Why: This is the "on invoke" half of progressive disclosure — the body is
143/// read from disk only when a caller (the `use_skill` tool, or a resolver's
144/// `resolve`) actually needs it.
145/// What: Rejects any `name` not present in `known` (the cached catalog) up
146/// front — this doubles as the path-traversal guard, since the join'd path is
147/// only ever built from a name the catalog itself already discovered on disk.
148/// Reads `<skills_dir>/<name>/SKILL.md` and returns the body after the
149/// frontmatter fence, trimmed.
150/// Test: `load_skill_body_returns_body_without_frontmatter`,
151/// `load_skill_body_rejects_unknown_name`.
152pub fn load_skill_body(
153    skills_dir: &Path,
154    name: &str,
155    known: &[SkillMetadata],
156) -> Result<String, SkillError> {
157    if !known.iter().any(|m| m.name == name) {
158        return Err(SkillError::Unknown(name.to_string()));
159    }
160    let path = skills_dir.join(name).join("SKILL.md");
161    let raw = std::fs::read_to_string(&path).map_err(|source| SkillError::Io {
162        name: name.to_string(),
163        source,
164    })?;
165    Ok(strip_frontmatter(&raw).trim().to_string())
166}
167
168/// Render the compact, always-injected skill catalog for prompt assembly.
169///
170/// Why: This is the entire token-efficiency payoff — a one-line-per-skill
171/// listing instead of every skill's full body.
172/// What: Returns an empty string when `skills` is empty (callers treat an
173/// empty section as "omit it", matching `assemble_system_prompt`'s
174/// empty-section-skipping convention). Otherwise a header line plus one
175/// `- name: description` line per skill, in the given order (callers pass
176/// already name-sorted `Vec`s from `discover_skill_metadata`).
177/// Test: `format_skill_catalog_empty_is_empty_string`,
178/// `format_skill_catalog_lists_every_skill`.
179pub fn format_skill_catalog(skills: &[SkillMetadata]) -> String {
180    if skills.is_empty() {
181        return String::new();
182    }
183    let mut out = String::from(
184        "Available skills (invoke the `use_skill` tool with the skill name to load its full instructions):\n",
185    );
186    for s in skills {
187        out.push_str(&format!("- {}: {}\n", s.name, s.description));
188    }
189    out.trim_end().to_string()
190}
191
192/// Filesystem-backed [`SkillResolver`] over a `.claude/skills/` directory.
193///
194/// Why: Gives the tool-registry layer (the `use_skill` tool) a ready
195/// concrete resolver: metadata is discovered once at construction (cheap,
196/// cached); `resolve` reads a single skill's body lazily, on demand.
197/// What: Wraps `skills_dir` plus the metadata discovered from it at
198/// construction time. `metadata()`/`list()` return the cached catalog;
199/// `resolve()` calls `load_skill_body` per invocation.
200/// Test: `fs_skill_resolver_resolves_known_skill`,
201/// `fs_skill_resolver_list_matches_metadata_names`,
202/// `fs_skill_resolver_resolve_unknown_returns_none`.
203pub struct FsSkillResolver {
204    skills_dir: PathBuf,
205    metadata: Vec<SkillMetadata>,
206}
207
208impl FsSkillResolver {
209    /// Construct a resolver, eagerly discovering (cheap) metadata.
210    ///
211    /// Why: Metadata discovery is a directory scan plus frontmatter parsing
212    /// only — cheap enough to do once at construction so every later
213    /// `metadata()`/`list()` call is a clone of an in-memory `Vec`.
214    /// What: Calls `discover_skill_metadata(&skills_dir)` and stores both.
215    /// Test: `fs_skill_resolver_resolves_known_skill`.
216    pub fn new(skills_dir: impl Into<PathBuf>) -> Self {
217        let skills_dir = skills_dir.into();
218        let metadata = discover_skill_metadata(&skills_dir);
219        Self {
220            skills_dir,
221            metadata,
222        }
223    }
224}
225
226impl SkillResolver for FsSkillResolver {
227    fn resolve(&self, name: &str) -> Option<String> {
228        load_skill_body(&self.skills_dir, name, &self.metadata).ok()
229    }
230
231    fn list(&self) -> Vec<String> {
232        self.metadata.iter().map(|m| m.name.clone()).collect()
233    }
234
235    fn metadata(&self) -> Vec<SkillMetadata> {
236        self.metadata.clone()
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    fn write_skill(root: &Path, name: &str, frontmatter: &str, body: &str) {
245        let dir = root.join(name);
246        std::fs::create_dir_all(&dir).expect("mkdir skill dir");
247        std::fs::write(dir.join("SKILL.md"), format!("{frontmatter}{body}")).expect("write");
248    }
249
250    /// `locate_skills_dir` returns `<project_root>/.claude/skills` exactly.
251    ///
252    /// Why: Pins the Claude-Code-compatible path (#2069) so a future edit
253    /// cannot silently drift back to `~/.trusty-mpm/skills/`.
254    /// Test: this test.
255    #[test]
256    fn locate_skills_dir_is_dot_claude_skills() {
257        let root = Path::new("/fake/project");
258        assert_eq!(locate_skills_dir(root), root.join(".claude").join("skills"));
259    }
260
261    /// Discovery reads `name`/`description` from frontmatter for every
262    /// skill directory containing a `SKILL.md`.
263    ///
264    /// Why: This is the core "always cached, cheap" discovery contract.
265    /// What: Two skill dirs; asserts both appear, sorted by name, with the
266    /// exact frontmatter values.
267    /// Test: this test.
268    #[test]
269    fn discover_skill_metadata_reads_name_and_description() {
270        let tmp = tempfile::tempdir().expect("tempdir");
271        write_skill(
272            tmp.path(),
273            "zeta-skill",
274            "---\nname: zeta-skill\ndescription: Does zeta things\n---\n",
275            "# Zeta\nbody\n",
276        );
277        write_skill(
278            tmp.path(),
279            "alpha-skill",
280            "---\nname: alpha-skill\ndescription: Does alpha things\n---\n",
281            "# Alpha\nbody\n",
282        );
283
284        let skills = discover_skill_metadata(tmp.path());
285        assert_eq!(skills.len(), 2);
286        assert_eq!(skills[0].name, "alpha-skill");
287        assert_eq!(skills[0].description, "Does alpha things");
288        assert_eq!(skills[1].name, "zeta-skill");
289        assert_eq!(skills[1].description, "Does zeta things");
290    }
291
292    /// A subdirectory with no `SKILL.md` is skipped, not an error.
293    ///
294    /// Why: `.claude/skills/` may contain scratch or in-progress
295    /// directories; discovery must degrade gracefully (no panic).
296    /// Test: this test.
297    #[test]
298    fn discover_skill_metadata_skips_dir_without_skill_md() {
299        let tmp = tempfile::tempdir().expect("tempdir");
300        std::fs::create_dir_all(tmp.path().join("not-a-skill")).expect("mkdir");
301        write_skill(
302            tmp.path(),
303            "real-skill",
304            "---\nname: real-skill\ndescription: A real one\n---\n",
305            "body\n",
306        );
307
308        let skills = discover_skill_metadata(tmp.path());
309        assert_eq!(skills.len(), 1);
310        assert_eq!(skills[0].name, "real-skill");
311    }
312
313    /// A missing skills directory yields an empty catalog, not an error.
314    ///
315    /// Why: Most projects will not have a `.claude/skills/` dir at all;
316    /// this must never panic or hard-fail discovery.
317    /// Test: this test.
318    #[test]
319    fn discover_skill_metadata_missing_dir_is_empty() {
320        let skills = discover_skill_metadata(Path::new("/nonexistent/skills/dir"));
321        assert!(skills.is_empty());
322    }
323
324    /// A `SKILL.md` with no frontmatter fence falls back to the directory
325    /// name and an empty description, rather than being rejected.
326    ///
327    /// Why: Malformed skill files must degrade gracefully (no panic).
328    /// Test: this test.
329    #[test]
330    fn discover_skill_metadata_falls_back_to_dirname() {
331        let tmp = tempfile::tempdir().expect("tempdir");
332        write_skill(tmp.path(), "no-frontmatter", "", "# Just a body\n");
333
334        let skills = discover_skill_metadata(tmp.path());
335        assert_eq!(skills.len(), 1);
336        assert_eq!(skills[0].name, "no-frontmatter");
337        assert_eq!(skills[0].description, "");
338    }
339
340    /// `load_skill_body` returns the body with frontmatter stripped, for a
341    /// name present in the known catalog.
342    ///
343    /// Why: This is the lazy on-invoke load path.
344    /// Test: this test.
345    #[test]
346    fn load_skill_body_returns_body_without_frontmatter() {
347        let tmp = tempfile::tempdir().expect("tempdir");
348        write_skill(
349            tmp.path(),
350            "demo-skill",
351            "---\nname: demo-skill\ndescription: Demo\n---\n",
352            "# Demo Skill\nFull instructions here.\n",
353        );
354        let known = discover_skill_metadata(tmp.path());
355
356        let body = load_skill_body(tmp.path(), "demo-skill", &known).expect("load body");
357        assert!(body.contains("# Demo Skill"));
358        assert!(body.contains("Full instructions here."));
359        assert!(!body.contains("description: Demo"));
360    }
361
362    /// `load_skill_body` rejects a name absent from the known catalog.
363    ///
364    /// Why: This is the safety guard against an LLM hallucinating a skill
365    /// name — no path is ever built from a name outside the discovered set.
366    /// Test: this test.
367    #[test]
368    fn load_skill_body_rejects_unknown_name() {
369        let tmp = tempfile::tempdir().expect("tempdir");
370        let known = discover_skill_metadata(tmp.path());
371        let err = load_skill_body(tmp.path(), "ghost-skill", &known);
372        assert!(matches!(err, Err(SkillError::Unknown(_))));
373    }
374
375    /// `format_skill_catalog` returns an empty string for an empty catalog.
376    ///
377    /// Why: An empty section must contribute nothing to the assembled
378    /// prompt, matching `assemble_system_prompt`'s empty-section-skipping.
379    /// Test: this test.
380    #[test]
381    fn format_skill_catalog_empty_is_empty_string() {
382        assert_eq!(format_skill_catalog(&[]), "");
383    }
384
385    /// `format_skill_catalog` lists every skill as a `- name: description`
386    /// line.
387    ///
388    /// Why: This is the token-efficient catalog the prompt actually sees.
389    /// Test: this test.
390    #[test]
391    fn format_skill_catalog_lists_every_skill() {
392        let skills = vec![
393            SkillMetadata {
394                name: "alpha".into(),
395                description: "First".into(),
396            },
397            SkillMetadata {
398                name: "beta".into(),
399                description: "Second".into(),
400            },
401        ];
402        let catalog = format_skill_catalog(&skills);
403        assert!(catalog.contains("- alpha: First"));
404        assert!(catalog.contains("- beta: Second"));
405    }
406
407    /// `FsSkillResolver::resolve` lazily loads a known skill's body.
408    ///
409    /// Why: Verifies the concrete `SkillResolver` impl end-to-end.
410    /// Test: this test.
411    #[test]
412    fn fs_skill_resolver_resolves_known_skill() {
413        let tmp = tempfile::tempdir().expect("tempdir");
414        write_skill(
415            tmp.path(),
416            "demo-skill",
417            "---\nname: demo-skill\ndescription: Demo\n---\n",
418            "Full body content.\n",
419        );
420        let resolver = FsSkillResolver::new(tmp.path());
421        let body = resolver.resolve("demo-skill").expect("resolve");
422        assert!(body.contains("Full body content."));
423    }
424
425    /// `FsSkillResolver::list` returns exactly the discovered metadata names.
426    ///
427    /// Test: this test.
428    #[test]
429    fn fs_skill_resolver_list_matches_metadata_names() {
430        let tmp = tempfile::tempdir().expect("tempdir");
431        write_skill(
432            tmp.path(),
433            "demo-skill",
434            "---\nname: demo-skill\ndescription: Demo\n---\n",
435            "body\n",
436        );
437        let resolver = FsSkillResolver::new(tmp.path());
438        assert_eq!(resolver.list(), vec!["demo-skill".to_string()]);
439        assert_eq!(resolver.metadata().len(), 1);
440    }
441
442    /// `FsSkillResolver::resolve` returns `None` for an unknown skill name.
443    ///
444    /// Why: Guards against a panic or leaked IO error surfacing through the
445    /// trait's `Option`-returning API.
446    /// Test: this test.
447    #[test]
448    fn fs_skill_resolver_resolve_unknown_returns_none() {
449        let tmp = tempfile::tempdir().expect("tempdir");
450        let resolver = FsSkillResolver::new(tmp.path());
451        assert!(resolver.resolve("ghost").is_none());
452    }
453}