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//! `discover_skill_metadata` falls back to `crate::assets::DEFAULT_SKILLS`
26//! (#2895) when the disk directory has no skills — a project with no
27//! `.claude/skills/` (or an empty one) still gets trusty-mpm's universal
28//! skill catalog. A disk directory with even one skill is used as-is (never
29//! merged with the embedded set) — disk always wins.
30//! Test: `skills::tests::*` — discovery over tempdir fixtures (happy path,
31//! missing dir, missing `SKILL.md`, malformed/no-frontmatter file), lazy body
32//! load (found + unknown-name), catalog formatting (empty + populated),
33//! embedded-fallback threshold, and `FsSkillResolver`'s `SkillResolver` trait
34//! conformance.
35//!
36//! [`SkillMetadata`]: crate::skills::SkillMetadata
37//! [`locate_skills_dir`]: crate::skills::locate_skills_dir
38//! [`discover_skill_metadata`]: crate::skills::discover_skill_metadata
39//! [`load_skill_body`]: crate::skills::load_skill_body
40//! [`format_skill_catalog`]: crate::skills::format_skill_catalog
41//! [`FsSkillResolver`]: crate::skills::FsSkillResolver
42
43// `pub(crate)`: also reused by `plugins::agents`/`plugins::skills` (#3539)
44// — both are generic frontmatter helpers, not skill-specific, so a plugin
45// agent's unsupported-field detection and a plugin skill's body-stripping
46// share this one parser rather than forking a second copy.
47pub(crate) mod frontmatter;
48pub mod protocol;
49
50use std::path::{Path, PathBuf};
51
52use thiserror::Error;
53
54use crate::tools::traits::SkillResolver;
55use frontmatter::{parse_frontmatter, strip_frontmatter};
56
57/// Cheap, always-cached catalog entry for one discovered skill.
58///
59/// Why: The PM/agents need to see what skills exist and when to reach for
60/// them without paying for every skill's full body up front.
61/// What: `name` (frontmatter `name:`, falling back to the skill's directory
62/// name) and `description` (frontmatter `description:`, empty string if
63/// absent).
64/// Test: `discover_skill_metadata_reads_name_and_description`.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct SkillMetadata {
67    pub name: String,
68    pub description: String,
69}
70
71/// Errors from lazily loading a skill's full body.
72///
73/// Why: A named error type lets `SkillResolver::resolve` and the `use_skill`
74/// tool distinguish "unknown skill" (an LLM hallucinated a name) from a
75/// genuine IO failure, both without panicking.
76/// What: `Unknown` — the name is not in the discovered catalog; `Io` — the
77/// `SKILL.md` file could not be read even though the name is known.
78/// Test: `load_skill_body_rejects_unknown_name`, `load_skill_body_io_error`.
79#[derive(Debug, Error)]
80pub enum SkillError {
81    #[error("skill '{0}' is not in the discovered catalog")]
82    Unknown(String),
83    #[error("failed to read skill body for '{name}': {source}")]
84    Io {
85        name: String,
86        #[source]
87        source: std::io::Error,
88    },
89}
90
91/// Locate the Claude-Code-compatible skills directory for a project root.
92///
93/// Why: #2069 pins this to `.claude/skills/` exactly — the Claude-Code-native
94/// convention — and explicitly NOT the legacy `~/.trusty-mpm/skills/` path
95/// trusty-mpm uses, so a project's skill catalog resolves identically whether
96/// browsed by a human in Claude Code or discovered by `tcode`.
97/// What: Returns `<project_root>/.claude/skills` (may not exist yet — callers
98/// handle absence via `discover_skill_metadata`'s empty-Vec fallback).
99/// Test: `locate_skills_dir_is_dot_claude_skills`.
100pub fn locate_skills_dir(project_root: &Path) -> PathBuf {
101    project_root.join(".claude").join("skills")
102}
103
104/// Discover skill metadata from every `<dir>/<skill-name>/SKILL.md`.
105///
106/// Why: The catalog must be built once, cheaply, from cheap-to-read
107/// frontmatter only — the whole point of progressive disclosure is to avoid
108/// reading full skill bodies until they are actually invoked. A project that
109/// has not yet created `.claude/skills/` (or has created it but left it
110/// empty) must not start with zero skills — see the embedded-fallback note
111/// below.
112/// What: Scans immediate subdirectories of `dir`; a subdirectory without a
113/// readable `SKILL.md` is skipped (not an error — mirrors
114/// `agents::discover_agents`'s graceful-skip convention). Returns entries
115/// sorted by `name`. If the scan yields zero entries (missing/unreadable
116/// `dir`, or an existing-but-empty one — empty is the fallback threshold; a
117/// disk directory with even one discoverable skill is used as-is, never
118/// merged with the embedded set), falls back to `embedded_skill_metadata`
119/// (`crate::assets::DEFAULT_SKILLS`, #2895). Disk skills always win when
120/// present.
121/// Test: `discover_skill_metadata_reads_name_and_description`,
122/// `discover_skill_metadata_skips_dir_without_skill_md`,
123/// `discover_skill_metadata_falls_back_to_embedded_when_disk_empty`,
124/// `discover_skill_metadata_disk_wins_when_present`,
125/// `discover_skill_metadata_falls_back_to_dirname`.
126pub fn discover_skill_metadata(dir: &Path) -> Vec<SkillMetadata> {
127    let skills = discover_disk_skill_metadata(dir);
128    if skills.is_empty() {
129        return embedded_skill_metadata();
130    }
131    skills
132}
133
134/// Scan `dir` for disk skills WITHOUT the embedded-fallback threshold —
135/// returns an empty `Vec` for a missing/empty directory rather than
136/// substituting `embedded_skill_metadata()` (#3449).
137///
138/// Why: `protocol::skills_list` needs to distinguish "this project genuinely
139/// has zero custom skills" from "here is the bundled catalog" — merging the
140/// two (as [`discover_skill_metadata`]'s fallback does, correctly, for the
141/// *tool-facing* discovery/prompt-injection path) would mislabel every
142/// bundled entry as `tier: "project"` in the catalog endpoint whenever a
143/// project's `.claude/skills/` happens to be empty. Factored out of
144/// [`discover_skill_metadata`] so the fallback threshold lives in exactly
145/// one place; the tool-facing function above is unchanged in behavior.
146/// What: identical directory scan/sort to [`discover_skill_metadata`], minus
147/// the embedded-fallback branch.
148/// Test: `protocol::tests::list_returns_disk_only_when_disk_non_empty_no_bundled_entries`,
149/// `protocol::tests::list_returns_bundled_when_projectless`,
150/// `protocol::tests::list_returns_bundled_when_disk_empty`.
151pub(crate) fn discover_disk_skill_metadata(dir: &Path) -> Vec<SkillMetadata> {
152    let Ok(entries) = std::fs::read_dir(dir) else {
153        tracing::debug!("skills dir not found or unreadable: {}", dir.display());
154        return Vec::new();
155    };
156
157    let mut skills: Vec<SkillMetadata> = entries
158        .flatten()
159        .filter_map(|entry| load_metadata_from_skill_dir(&entry.path()))
160        .collect();
161    skills.sort_by(|a, b| a.name.cmp(&b.name));
162    skills
163}
164
165/// Build the embedded-default skill catalog from `crate::assets::DEFAULT_SKILLS`.
166///
167/// Why: The embedded-fallback path for `discover_skill_metadata` — parses
168/// each bundled `SKILL.md`'s frontmatter in-memory, exactly as
169/// `load_metadata_from_skill_dir` does for a disk file, so the resulting
170/// `SkillMetadata` is indistinguishable from a disk-discovered one.
171/// What: Maps every `EmbeddedSkill` through `parse_frontmatter`, sorted by
172/// name (the table is already declared in name order, but this does not
173/// depend on that).
174/// Test: `discover_skill_metadata_falls_back_to_embedded_when_disk_empty`.
175fn embedded_skill_metadata() -> Vec<SkillMetadata> {
176    let mut skills: Vec<SkillMetadata> = crate::assets::DEFAULT_SKILLS
177        .iter()
178        .map(|embedded| {
179            let front = parse_frontmatter(embedded.skill_md);
180            SkillMetadata {
181                name: front
182                    .get("name")
183                    .cloned()
184                    .unwrap_or_else(|| embedded.name.to_string()),
185                description: front.get("description").cloned().unwrap_or_default(),
186            }
187        })
188        .collect();
189    skills.sort_by(|a, b| a.name.cmp(&b.name));
190    skills
191}
192
193/// Load one skill directory's metadata, if it holds a readable `SKILL.md`.
194///
195/// Why: Factored out of `discover_skill_metadata` so each rejection reason
196/// (not a directory, no `SKILL.md`, unreadable) can be logged distinctly.
197/// What: Returns `None` (with a debug log) for anything that is not a skill
198/// directory; otherwise parses frontmatter and falls back to the directory
199/// name when `name:` is absent.
200/// Test: covered via `discover_skill_metadata`'s tests above.
201fn load_metadata_from_skill_dir(path: &Path) -> Option<SkillMetadata> {
202    if !path.is_dir() {
203        return None;
204    }
205    let dirname = path.file_name()?.to_str()?.to_string();
206    let skill_md = path.join("SKILL.md");
207    let raw = match std::fs::read_to_string(&skill_md) {
208        Ok(raw) => raw,
209        Err(e) => {
210            tracing::debug!("skipping skill dir '{dirname}': no readable SKILL.md ({e})");
211            return None;
212        }
213    };
214    let front = parse_frontmatter(&raw);
215    let name = front.get("name").cloned().unwrap_or(dirname);
216    let description = front.get("description").cloned().unwrap_or_default();
217    Some(SkillMetadata { name, description })
218}
219
220/// Lazily load one skill's full Markdown body (the frontmatter stripped off).
221///
222/// Why: This is the "on invoke" half of progressive disclosure — the body is
223/// read from disk only when a caller (the `use_skill` tool, or a resolver's
224/// `resolve`) actually needs it.
225/// What: Rejects any `name` not present in `known` (the cached catalog) up
226/// front — this doubles as the path-traversal guard, since the join'd path is
227/// only ever built from a name the catalog itself already discovered (on disk
228/// or embedded). Reads `<skills_dir>/<name>/SKILL.md`; if that read fails
229/// (the disk fallback case: `known` came from `embedded_skill_metadata`, so
230/// there is no such file) and `name` matches an entry in
231/// `crate::assets::DEFAULT_SKILLS`, returns that embedded body instead
232/// (#2895). Otherwise propagates the disk `Io` error. Either way, the
233/// frontmatter fence is stripped and the body trimmed.
234/// Test: `load_skill_body_returns_body_without_frontmatter`,
235/// `load_skill_body_rejects_unknown_name`,
236/// `load_skill_body_falls_back_to_embedded_when_disk_read_fails`.
237pub fn load_skill_body(
238    skills_dir: &Path,
239    name: &str,
240    known: &[SkillMetadata],
241) -> Result<String, SkillError> {
242    if !known.iter().any(|m| m.name == name) {
243        return Err(SkillError::Unknown(name.to_string()));
244    }
245    let path = skills_dir.join(name).join("SKILL.md");
246    let raw = match std::fs::read_to_string(&path) {
247        Ok(raw) => raw,
248        Err(source) => {
249            if let Some(embedded) = crate::assets::DEFAULT_SKILLS
250                .iter()
251                .find(|e| e.name == name)
252            {
253                return Ok(strip_frontmatter(embedded.skill_md).trim().to_string());
254            }
255            return Err(SkillError::Io {
256                name: name.to_string(),
257                source,
258            });
259        }
260    };
261    Ok(strip_frontmatter(&raw).trim().to_string())
262}
263
264/// Render the compact, always-injected skill catalog for prompt assembly.
265///
266/// Why: This is the entire token-efficiency payoff — a one-line-per-skill
267/// listing instead of every skill's full body.
268/// What: Returns an empty string when `skills` is empty (callers treat an
269/// empty section as "omit it", matching `assemble_system_prompt`'s
270/// empty-section-skipping convention). Otherwise a header line plus one
271/// `- name: description` line per skill, in the given order (callers pass
272/// already name-sorted `Vec`s from `discover_skill_metadata`).
273/// Test: `format_skill_catalog_empty_is_empty_string`,
274/// `format_skill_catalog_lists_every_skill`.
275pub fn format_skill_catalog(skills: &[SkillMetadata]) -> String {
276    if skills.is_empty() {
277        return String::new();
278    }
279    let mut out = String::from(
280        "Available skills (invoke the `use_skill` tool with the skill name to load its full instructions):\n",
281    );
282    for s in skills {
283        out.push_str(&format!("- {}: {}\n", s.name, s.description));
284    }
285    out.trim_end().to_string()
286}
287
288/// Filesystem-backed [`SkillResolver`] over a `.claude/skills/` directory.
289///
290/// Why: Gives the tool-registry layer (the `use_skill` tool) a ready
291/// concrete resolver: metadata is discovered once at construction (cheap,
292/// cached); `resolve` reads a single skill's body lazily, on demand.
293/// What: Wraps `skills_dir` plus the metadata discovered from it at
294/// construction time. `metadata()`/`list()` return the cached catalog;
295/// `resolve()` calls `load_skill_body` per invocation.
296/// As of #3539 (Phase 1 Claude Code plugin support), also namespaces and
297/// resolves plugin skills (`<plugin>:<name>`) — see `plugins::skills`,
298/// which this struct delegates to additively (never suppressing, never
299/// suppressed by, the project/embedded threshold above).
300/// Test: `fs_skill_resolver_resolves_known_skill`,
301/// `fs_skill_resolver_list_matches_metadata_names`,
302/// `fs_skill_resolver_resolve_unknown_returns_none`,
303/// `fs_skill_resolver_resolves_namespaced_plugin_skill`,
304/// `fs_skill_resolver_metadata_includes_plugin_skills_alongside_project_skill`.
305pub struct FsSkillResolver {
306    skills_dir: PathBuf,
307    metadata: Vec<SkillMetadata>,
308    /// The project root recovered from `skills_dir`
309    /// (`crate::plugins::project_root_two_levels_up`), or `None` when
310    /// `skills_dir` isn't shaped `<root>/.claude/skills` (e.g. a bare
311    /// tempdir in a unit test that doesn't exercise plugins). Cached once at
312    /// construction so `resolve` never re-derives it per call.
313    project_root: Option<PathBuf>,
314}
315
316impl FsSkillResolver {
317    /// Construct a resolver, eagerly discovering (cheap) metadata.
318    ///
319    /// Why: Metadata discovery is a directory scan plus frontmatter parsing
320    /// only — cheap enough to do once at construction so every later
321    /// `metadata()`/`list()` call is a clone of an in-memory `Vec`.
322    /// What: Calls `discover_skill_metadata(&skills_dir)`, then additively
323    /// extends it with `plugins::skills::discover_plugin_skills` when a
324    /// project root can be recovered from `skills_dir` (#3539) — plugin
325    /// skills are independent of the project/embedded threshold
326    /// `discover_skill_metadata` applies, so they are appended regardless
327    /// of whether that call returned the project's own catalog or the
328    /// embedded fallback.
329    /// Test: `fs_skill_resolver_resolves_known_skill`,
330    /// `fs_skill_resolver_metadata_includes_plugin_skills_alongside_project_skill`.
331    pub fn new(skills_dir: impl Into<PathBuf>) -> Self {
332        let skills_dir = skills_dir.into();
333        let mut metadata = discover_skill_metadata(&skills_dir);
334        let project_root = crate::plugins::project_root_two_levels_up(&skills_dir);
335        if let Some(root) = &project_root {
336            metadata.extend(crate::plugins::skills::discover_plugin_skills(root));
337        }
338        Self {
339            skills_dir,
340            metadata,
341            project_root,
342        }
343    }
344}
345
346impl SkillResolver for FsSkillResolver {
347    /// A namespaced `<plugin>:<name>` (the exact shape a plugin skill
348    /// listing surfaces, and — via `tools::skill::UseSkillTool` — the exact
349    /// shape an LLM's raw `use_skill` argument can be) routes to
350    /// `plugins::skills::resolve_plugin_skill_body`, which is itself the
351    /// authoritative traversal guard (validates the namespaced shape and
352    /// discovered-catalog membership before ever building a path — issue
353    /// #3547 CRITICAL 2). This wrapper does not re-validate; it only
354    /// recovers the cached `project_root` (`None` short-circuits to `None`
355    /// rather than falling through to the plain-name path below, since a
356    /// namespaced name is never a valid plain skill name either way).
357    fn resolve(&self, name: &str) -> Option<String> {
358        if let Some((plugin, skill_name)) = name.split_once(':') {
359            return self.project_root.as_deref().and_then(|root| {
360                crate::plugins::skills::resolve_plugin_skill_body(root, plugin, skill_name)
361            });
362        }
363        load_skill_body(&self.skills_dir, name, &self.metadata).ok()
364    }
365
366    fn list(&self) -> Vec<String> {
367        self.metadata.iter().map(|m| m.name.clone()).collect()
368    }
369
370    fn metadata(&self) -> Vec<SkillMetadata> {
371        self.metadata.clone()
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    fn write_skill(root: &Path, name: &str, frontmatter: &str, body: &str) {
380        let dir = root.join(name);
381        std::fs::create_dir_all(&dir).expect("mkdir skill dir");
382        std::fs::write(dir.join("SKILL.md"), format!("{frontmatter}{body}")).expect("write");
383    }
384
385    /// `locate_skills_dir` returns `<project_root>/.claude/skills` exactly.
386    ///
387    /// Why: Pins the Claude-Code-compatible path (#2069) so a future edit
388    /// cannot silently drift back to `~/.trusty-mpm/skills/`.
389    /// Test: this test.
390    #[test]
391    fn locate_skills_dir_is_dot_claude_skills() {
392        let root = Path::new("/fake/project");
393        assert_eq!(locate_skills_dir(root), root.join(".claude").join("skills"));
394    }
395
396    /// Discovery reads `name`/`description` from frontmatter for every
397    /// skill directory containing a `SKILL.md`.
398    ///
399    /// Why: This is the core "always cached, cheap" discovery contract.
400    /// What: Two skill dirs; asserts both appear, sorted by name, with the
401    /// exact frontmatter values.
402    /// Test: this test.
403    #[test]
404    fn discover_skill_metadata_reads_name_and_description() {
405        let tmp = tempfile::tempdir().expect("tempdir");
406        write_skill(
407            tmp.path(),
408            "zeta-skill",
409            "---\nname: zeta-skill\ndescription: Does zeta things\n---\n",
410            "# Zeta\nbody\n",
411        );
412        write_skill(
413            tmp.path(),
414            "alpha-skill",
415            "---\nname: alpha-skill\ndescription: Does alpha things\n---\n",
416            "# Alpha\nbody\n",
417        );
418
419        let skills = discover_skill_metadata(tmp.path());
420        assert_eq!(skills.len(), 2);
421        assert_eq!(skills[0].name, "alpha-skill");
422        assert_eq!(skills[0].description, "Does alpha things");
423        assert_eq!(skills[1].name, "zeta-skill");
424        assert_eq!(skills[1].description, "Does zeta things");
425    }
426
427    /// A subdirectory with no `SKILL.md` is skipped, not an error.
428    ///
429    /// Why: `.claude/skills/` may contain scratch or in-progress
430    /// directories; discovery must degrade gracefully (no panic).
431    /// Test: this test.
432    #[test]
433    fn discover_skill_metadata_skips_dir_without_skill_md() {
434        let tmp = tempfile::tempdir().expect("tempdir");
435        std::fs::create_dir_all(tmp.path().join("not-a-skill")).expect("mkdir");
436        write_skill(
437            tmp.path(),
438            "real-skill",
439            "---\nname: real-skill\ndescription: A real one\n---\n",
440            "body\n",
441        );
442
443        let skills = discover_skill_metadata(tmp.path());
444        assert_eq!(skills.len(), 1);
445        assert_eq!(skills[0].name, "real-skill");
446    }
447
448    /// A missing skills directory falls back to the embedded default
449    /// catalog, not an empty one (#2895).
450    ///
451    /// Why: Most projects will not have a `.claude/skills/` dir at all; a
452    /// fresh project must still see trusty-mpm's universal skill set rather
453    /// than starting with zero skills.
454    /// What: Discover from a nonexistent path; expect the full embedded
455    /// catalog (28 skills, sorted by name — matches
456    /// `crate::assets::tests::default_skills_names_are_unique`'s count).
457    /// Test: this test.
458    #[test]
459    fn discover_skill_metadata_falls_back_to_embedded_when_disk_empty() {
460        let skills = discover_skill_metadata(Path::new("/nonexistent/skills/dir"));
461        assert_eq!(skills.len(), 28);
462        assert!(skills.iter().any(|s| s.name == "systematic-debugging"));
463        assert!(
464            skills.windows(2).all(|w| w[0].name <= w[1].name),
465            "embedded fallback must be sorted by name"
466        );
467    }
468
469    /// A disk directory with even one discoverable skill is used as-is; the
470    /// embedded defaults are never merged in alongside it.
471    ///
472    /// Why: Pins the fallback threshold (empty disk scan only) so a project
473    /// that has deliberately curated its own skill catalog is not silently
474    /// joined by the 28 embedded defaults it did not ask for.
475    /// Test: this test.
476    #[test]
477    fn discover_skill_metadata_disk_wins_when_present() {
478        let tmp = tempfile::tempdir().expect("tempdir");
479        write_skill(
480            tmp.path(),
481            "only-skill",
482            "---\nname: only-skill\ndescription: The only one\n---\n",
483            "body\n",
484        );
485
486        let skills = discover_skill_metadata(tmp.path());
487        assert_eq!(skills.len(), 1);
488        assert_eq!(skills[0].name, "only-skill");
489    }
490
491    /// A `SKILL.md` with no frontmatter fence falls back to the directory
492    /// name and an empty description, rather than being rejected.
493    ///
494    /// Why: Malformed skill files must degrade gracefully (no panic).
495    /// Test: this test.
496    #[test]
497    fn discover_skill_metadata_falls_back_to_dirname() {
498        let tmp = tempfile::tempdir().expect("tempdir");
499        write_skill(tmp.path(), "no-frontmatter", "", "# Just a body\n");
500
501        let skills = discover_skill_metadata(tmp.path());
502        assert_eq!(skills.len(), 1);
503        assert_eq!(skills[0].name, "no-frontmatter");
504        assert_eq!(skills[0].description, "");
505    }
506
507    /// `load_skill_body` returns the body with frontmatter stripped, for a
508    /// name present in the known catalog.
509    ///
510    /// Why: This is the lazy on-invoke load path.
511    /// Test: this test.
512    #[test]
513    fn load_skill_body_returns_body_without_frontmatter() {
514        let tmp = tempfile::tempdir().expect("tempdir");
515        write_skill(
516            tmp.path(),
517            "demo-skill",
518            "---\nname: demo-skill\ndescription: Demo\n---\n",
519            "# Demo Skill\nFull instructions here.\n",
520        );
521        let known = discover_skill_metadata(tmp.path());
522
523        let body = load_skill_body(tmp.path(), "demo-skill", &known).expect("load body");
524        assert!(body.contains("# Demo Skill"));
525        assert!(body.contains("Full instructions here."));
526        assert!(!body.contains("description: Demo"));
527    }
528
529    /// `load_skill_body` rejects a name absent from the known catalog.
530    ///
531    /// Why: This is the safety guard against an LLM hallucinating a skill
532    /// name — no path is ever built from a name outside the discovered set.
533    /// What: `tmp` is an empty tempdir, so `discover_skill_metadata` returns
534    /// the embedded-fallback catalog (the 28 names in
535    /// `crate::assets::DEFAULT_SKILLS`, #2895), not a truly empty one;
536    /// `"ghost-skill"` is absent from that catalog too, so this now exercises
537    /// unknown-name rejection against the embedded fallback rather than an
538    /// empty set — the guard behaves identically either way.
539    /// Test: this test.
540    #[test]
541    fn load_skill_body_rejects_unknown_name() {
542        let tmp = tempfile::tempdir().expect("tempdir");
543        let known = discover_skill_metadata(tmp.path());
544        let err = load_skill_body(tmp.path(), "ghost-skill", &known);
545        assert!(matches!(err, Err(SkillError::Unknown(_))));
546    }
547
548    /// `load_skill_body` falls back to `crate::assets::DEFAULT_SKILLS` when
549    /// the disk read fails but the name is a known embedded default (#2895).
550    ///
551    /// Why: `known` may itself have come from `embedded_skill_metadata` (an
552    /// empty disk dir); the body loader must be able to resolve those names
553    /// too, not just names discovered from real files.
554    /// What: An empty tempdir (so `discover_skill_metadata` returns the
555    /// embedded catalog), then `load_skill_body` for a real embedded skill
556    /// name returns its body without hitting disk.
557    /// Test: this test.
558    #[test]
559    fn load_skill_body_falls_back_to_embedded_when_disk_read_fails() {
560        let tmp = tempfile::tempdir().expect("tempdir");
561        let known = discover_skill_metadata(tmp.path());
562        let body =
563            load_skill_body(tmp.path(), "systematic-debugging", &known).expect("embedded body");
564        assert!(!body.trim().is_empty());
565        assert!(
566            !body.contains("name: systematic-debugging"),
567            "frontmatter must be stripped"
568        );
569    }
570
571    /// `format_skill_catalog` returns an empty string for an empty catalog.
572    ///
573    /// Why: An empty section must contribute nothing to the assembled
574    /// prompt, matching `assemble_system_prompt`'s empty-section-skipping.
575    /// Test: this test.
576    #[test]
577    fn format_skill_catalog_empty_is_empty_string() {
578        assert_eq!(format_skill_catalog(&[]), "");
579    }
580
581    /// `format_skill_catalog` lists every skill as a `- name: description`
582    /// line.
583    ///
584    /// Why: This is the token-efficient catalog the prompt actually sees.
585    /// Test: this test.
586    #[test]
587    fn format_skill_catalog_lists_every_skill() {
588        let skills = vec![
589            SkillMetadata {
590                name: "alpha".into(),
591                description: "First".into(),
592            },
593            SkillMetadata {
594                name: "beta".into(),
595                description: "Second".into(),
596            },
597        ];
598        let catalog = format_skill_catalog(&skills);
599        assert!(catalog.contains("- alpha: First"));
600        assert!(catalog.contains("- beta: Second"));
601    }
602
603    /// `FsSkillResolver::resolve` lazily loads a known skill's body.
604    ///
605    /// Why: Verifies the concrete `SkillResolver` impl end-to-end.
606    /// Test: this test.
607    #[test]
608    fn fs_skill_resolver_resolves_known_skill() {
609        let tmp = tempfile::tempdir().expect("tempdir");
610        write_skill(
611            tmp.path(),
612            "demo-skill",
613            "---\nname: demo-skill\ndescription: Demo\n---\n",
614            "Full body content.\n",
615        );
616        let resolver = FsSkillResolver::new(tmp.path());
617        let body = resolver.resolve("demo-skill").expect("resolve");
618        assert!(body.contains("Full body content."));
619    }
620
621    /// `FsSkillResolver::list` returns exactly the discovered metadata names.
622    ///
623    /// Test: this test.
624    #[test]
625    fn fs_skill_resolver_list_matches_metadata_names() {
626        let tmp = tempfile::tempdir().expect("tempdir");
627        write_skill(
628            tmp.path(),
629            "demo-skill",
630            "---\nname: demo-skill\ndescription: Demo\n---\n",
631            "body\n",
632        );
633        let resolver = FsSkillResolver::new(tmp.path());
634        assert_eq!(resolver.list(), vec!["demo-skill".to_string()]);
635        assert_eq!(resolver.metadata().len(), 1);
636    }
637
638    /// `FsSkillResolver::resolve` returns `None` for an unknown skill name.
639    ///
640    /// Why: Guards against a panic or leaked IO error surfacing through the
641    /// trait's `Option`-returning API.
642    /// What: `tmp` is an empty tempdir, so the resolver's cached metadata is
643    /// the embedded-fallback catalog (the 28 names in
644    /// `crate::assets::DEFAULT_SKILLS`, #2895), not a truly empty one;
645    /// `"ghost"` is absent from that catalog too, so this now exercises
646    /// unknown-name resolution against the embedded fallback rather than an
647    /// empty set.
648    /// Test: this test.
649    #[test]
650    fn fs_skill_resolver_resolve_unknown_returns_none() {
651        let tmp = tempfile::tempdir().expect("tempdir");
652        let resolver = FsSkillResolver::new(tmp.path());
653        assert!(resolver.resolve("ghost").is_none());
654    }
655
656    /// `FsSkillResolver::resolve` routes a namespaced `<plugin>:<name>` to
657    /// the plugin's own `SKILL.md` (issue #3539).
658    ///
659    /// Why: this is the acceptance criterion for the resolution half of
660    /// #3539's skill-namespacing decision — a namespaced skill must
661    /// actually load its body via `use_skill`, not just appear in a catalog
662    /// listing.
663    /// Test: this test.
664    #[test]
665    fn fs_skill_resolver_resolves_namespaced_plugin_skill() {
666        let tmp = tempfile::tempdir().expect("tempdir");
667        let skills_dir = tmp.path().join(".claude").join("skills");
668        std::fs::create_dir_all(&skills_dir).expect("mkdir");
669        write_skill(
670            &tmp.path()
671                .join(".claude")
672                .join("plugins")
673                .join("my-plugin")
674                .join("skills"),
675            "demo-skill",
676            "---\nname: demo-skill\n---\n",
677            "Plugin skill body.\n",
678        );
679
680        let resolver = FsSkillResolver::new(&skills_dir);
681        let body = resolver
682            .resolve("my-plugin:demo-skill")
683            .expect("resolve namespaced plugin skill");
684        assert!(body.contains("Plugin skill body."));
685    }
686
687    /// `FsSkillResolver`'s cached metadata includes plugin skills ADDITIVELY
688    /// alongside a project's own custom skill catalog — the
689    /// project-vs-bundled whole-catalog-replacement threshold (PR #3465)
690    /// neither suppresses nor is suppressed by the plugin tier (#3539's
691    /// locked precedence-interaction requirement).
692    ///
693    /// Test: this test.
694    #[test]
695    fn fs_skill_resolver_metadata_includes_plugin_skills_alongside_project_skill() {
696        let tmp = tempfile::tempdir().expect("tempdir");
697        let skills_dir = tmp.path().join(".claude").join("skills");
698        write_skill(
699            &skills_dir,
700            "project-only-skill",
701            "---\nname: project-only-skill\n---\n",
702            "body\n",
703        );
704        write_skill(
705            &tmp.path()
706                .join(".claude")
707                .join("plugins")
708                .join("my-plugin")
709                .join("skills"),
710            "plugin-skill",
711            "---\nname: plugin-skill\n---\n",
712            "body\n",
713        );
714
715        let resolver = FsSkillResolver::new(&skills_dir);
716        let names = resolver.list();
717        assert!(
718            names.contains(&"project-only-skill".to_string()),
719            "the project's own custom skill must still be listed, got: {names:?}"
720        );
721        assert!(
722            names.contains(&"my-plugin:plugin-skill".to_string()),
723            "the namespaced plugin skill must be listed too, got: {names:?}"
724        );
725    }
726}