trusty_code/plugins/skills.rs
1//! Phase-1 plugin SKILL ingestion: discovery, namespacing, and body
2//! resolution (issue #3539).
3//!
4//! Why: a plugin's `skills/<name>/SKILL.md` files are the exact same
5//! progressive-disclosure format `crate::skills` already parses for project
6//! skills — cheap frontmatter (`name`/`description`) at discovery time, the
7//! full body only on demand. This module adds namespacing
8//! (`<plugin>:<name>`) on top; it deliberately does NOT interact with
9//! `crate::skills::discover_skill_metadata`'s bundled/project
10//! whole-catalog-replacement threshold (PR #3465) — plugin skills are an
11//! independent additive tier that is listed and resolved regardless of
12//! which side of that threshold a project's own `.claude/skills/` falls on
13//! (#3539's locked precedence-interaction requirement).
14//! What: [`discover_plugin_skills`] lists every plugin skill's cheap
15//! metadata, namespaced (used by `skills::protocol::skills_list`'s `plugin`
16//! tier and `skills::FsSkillResolver`'s cached catalog).
17//! [`resolve_plugin_skill_body`] lazily loads one namespaced skill's full
18//! body on demand (used by `skills::FsSkillResolver::resolve`).
19//! Test: `tests::*` — discovery finds and namespaces skills, a skill
20//! directory without `SKILL.md` is skipped, body resolution finds/misses a
21//! namespaced name, a symlinked `<name>`/`SKILL.md` is rejected at both the
22//! discovery and resolution paths (issue #3547 CRITICAL 5).
23
24use std::path::Path;
25
26use crate::skills::SkillMetadata;
27
28use super::{PluginRoot, discover_plugin_roots};
29
30/// List every plugin skill's cheap metadata across every discovered plugin,
31/// namespaced `<plugin>:<local-name>`.
32///
33/// Why: the additive `plugin` tier `skills::protocol::skills_list` and
34/// `skills::FsSkillResolver`'s cached catalog both need.
35/// What: for each [`PluginRoot`], scans immediate subdirectories of
36/// `skills_dir` for a readable `SKILL.md`; a subdirectory without one is
37/// skipped (mirrors `skills::discover_skill_metadata`'s graceful-skip
38/// convention, never an error). `name`/`description` come from frontmatter,
39/// falling back to the skill's directory name when `name:` is absent.
40/// Sorted by the final namespaced name.
41/// Test: `tests::discover_plugin_skills_namespaces_entries`,
42/// `tests::discover_plugin_skills_skips_dir_without_skill_md`,
43/// `tests::discover_plugin_skills_missing_plugins_dir_is_empty`.
44pub fn discover_plugin_skills(project_root: &Path) -> Vec<SkillMetadata> {
45 let mut out: Vec<SkillMetadata> = discover_plugin_roots(project_root)
46 .iter()
47 .flat_map(discover_one_plugin_skills)
48 .collect();
49 out.sort_by(|a, b| a.name.cmp(&b.name));
50 out
51}
52
53/// Scan a single plugin's `skills_dir` for its `<name>/SKILL.md` skills.
54///
55/// Why: factored out of [`discover_plugin_skills`] so the per-plugin scan
56/// (mirroring `skills::load_metadata_from_skill_dir`'s shape) is
57/// independently readable. This is the ONE place a plugin skill's
58/// `SKILL.md` content is read for listing purposes, so it is also the
59/// enforcement point for the leaf-file-identity guard (code-critic PR
60/// #3547 re-review, CRITICAL 5, CWE-59) — see [`super::path_is_contained`].
61/// What: a missing/unreadable `skills_dir` yields an empty `Vec` (not an
62/// error — most plugins ship agents only, or vice versa). `path.is_dir()`
63/// FOLLOWS symlinks (so a symlinked `<name>` directory is not rejected by
64/// this check alone), but every candidate's full `<name>/SKILL.md` leaf
65/// path is additionally required to canonicalize within `skills_dir`'s own
66/// canonicalization before its content is read — this single check catches
67/// a symlinked `<name>` directory, a symlinked `SKILL.md` leaf file inside
68/// a real `<name>` directory, or both, uniformly (see
69/// [`super::path_is_contained`]'s doc). A rejected candidate is skipped
70/// with a `WARN`, never surfacing the escaped target's content.
71/// Test: covered via `discover_plugin_skills`'s tests above,
72/// `tests::discover_plugin_skills_excludes_symlinked_skill_md`.
73fn discover_one_plugin_skills(root: &PluginRoot) -> Vec<SkillMetadata> {
74 let Ok(entries) = std::fs::read_dir(&root.skills_dir) else {
75 return Vec::new();
76 };
77 entries
78 .flatten()
79 .filter_map(|entry| {
80 let path = entry.path();
81 if !path.is_dir() {
82 return None;
83 }
84 let dirname = path.file_name()?.to_str()?.to_string();
85 let skill_md = path.join("SKILL.md");
86 if !super::path_is_contained(&skill_md, &root.skills_dir) {
87 tracing::warn!(
88 "plugin '{}' skill dir '{dirname}' SKILL.md at {} is a symlink (or resolves \
89 through one) outside the plugin's skills directory — rejected as a \
90 potential host-file disclosure (#3547)",
91 root.name,
92 skill_md.display()
93 );
94 return None;
95 }
96 let raw = std::fs::read_to_string(&skill_md).ok()?;
97 let front = crate::skills::frontmatter::parse_frontmatter(&raw);
98 let local_name = front.get("name").cloned().unwrap_or(dirname);
99 let description = front.get("description").cloned().unwrap_or_default();
100 Some(SkillMetadata {
101 name: format!("{}:{local_name}", root.name),
102 description,
103 })
104 })
105 .collect()
106}
107
108/// Lazily load one namespaced plugin skill's full body (frontmatter
109/// stripped), or `None` when the plugin or the skill is unknown.
110///
111/// Why: `skills::FsSkillResolver::resolve`'s namespaced-name entry point —
112/// the "on invoke" half of progressive disclosure for a plugin skill,
113/// mirroring `skills::load_skill_body`'s lazy-load contract. This is the
114/// LLM-reachable path — `tools::skill::UseSkillTool::execute` forwards the
115/// model's raw `name` argument straight through
116/// `skills::FsSkillResolver::resolve` to here — so `skill_name` is HOSTILE
117/// input (code-critic PR #3547 review, CRITICAL 2).
118/// What: validates `plugin:skill_name` via `plugins::is_valid_namespaced_name`
119/// FIRST, before any path is built — rejects a traversal/unsafe-charset
120/// payload like `skill_name = "../../../../x"` outright (this alone makes
121/// escaping `skills_dir` syntactically impossible, since the accepted
122/// charset contains no `/` or `.`). Then finds the [`PluginRoot`] whose
123/// resolved `name` equals `plugin`; as a second, independent guard,
124/// additionally requires `<plugin>:<skill_name>` to be a name
125/// [`discover_plugin_skills`] actually found on disk this scan — mirroring
126/// `skills::load_skill_body`'s "reject anything not in `known`" contract —
127/// which also closes the residual gap where a plugin's own `SKILL.md`
128/// frontmatter could declare a spoofed `name:` that passed the charset
129/// check but was never a real, scanned skill. Because
130/// [`discover_one_plugin_skills`] itself now rejects a symlinked
131/// `<name>`/`SKILL.md` (code-critic PR #3547 re-review, CRITICAL 5), a
132/// symlinked skill is never "found on disk" and this membership check
133/// alone already excludes it — a THIRD, independent
134/// [`super::path_is_contained`] check is still applied immediately before
135/// the read below as defense in depth, so the guard holds even if the two
136/// callers of [`discover_one_plugin_skills`] ever drift. Only once all
137/// guards pass does it read `<skills_dir>/<skill_name>/SKILL.md` and strip
138/// the frontmatter fence via `skills::frontmatter::strip_frontmatter` (the
139/// same generic stripper project/embedded skill bodies use). `None` on any
140/// miss (failed validation, unknown plugin, unknown/symlinked skill,
141/// unreadable file) — the resolver trait's `Option`-returning API has no
142/// separate error channel, matching `FsSkillResolver::resolve`'s existing
143/// unknown-name handling.
144/// Test: `tests::resolve_plugin_skill_body_returns_body`,
145/// `tests::resolve_plugin_skill_body_unknown_plugin_is_none`,
146/// `tests::resolve_plugin_skill_body_unknown_skill_is_none`,
147/// `tests::resolve_plugin_skill_body_rejects_traversal_name`,
148/// `tests::resolve_plugin_skill_body_rejects_symlinked_file`.
149pub fn resolve_plugin_skill_body(
150 project_root: &Path,
151 plugin: &str,
152 skill_name: &str,
153) -> Option<String> {
154 if !super::is_valid_namespaced_name(&format!("{plugin}:{skill_name}")) {
155 return None;
156 }
157 let root = discover_plugin_roots(project_root)
158 .into_iter()
159 .find(|p| p.name == plugin)?;
160
161 let namespaced = format!("{}:{skill_name}", root.name);
162 if !discover_one_plugin_skills(&root)
163 .iter()
164 .any(|m| m.name == namespaced)
165 {
166 return None;
167 }
168
169 let skill_md = root.skills_dir.join(skill_name).join("SKILL.md");
170 if !super::path_is_contained(&skill_md, &root.skills_dir) {
171 tracing::warn!(
172 "plugin skill '{namespaced}' SKILL.md at {} is a symlink (or resolves through one) \
173 outside the plugin's skills directory — rejected as a potential host-file \
174 disclosure (#3547)",
175 skill_md.display()
176 );
177 return None;
178 }
179
180 let raw = std::fs::read_to_string(&skill_md).ok()?;
181 Some(
182 crate::skills::frontmatter::strip_frontmatter(&raw)
183 .trim()
184 .to_string(),
185 )
186}
187
188#[cfg(test)]
189#[path = "skills_tests.rs"]
190mod tests;