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