Skip to main content

trusty_code/skills/
protocol.rs

1//! `skills.*` JSON-RPC methods — the daemon's SKILL CATALOG management
2//! surface (issue #3449), backing the Foundry GUI's Skills management tab.
3//!
4//! Why: the GUI's Agents tab (`crate::agents::protocol`) and Skills tab are
5//! siblings in the same issue, but tcode's skill model is genuinely
6//! narrower than its agent model — worth stating explicitly rather than
7//! papering over with a symmetric-looking API that implies a tier that
8//! doesn't exist. `crate::skills::discover_skill_metadata` (the ONLY
9//! consumer of a project's `.claude/skills/`, wired at `run_task`/
10//! `task::executor` time) recognises exactly TWO tiers: the embedded/bundled
11//! catalog (`crate::assets::DEFAULT_SKILLS`, trusty-mpm's universal set
12//! minus `tm-*` orchestration skills) and ONE project-scoped disk directory
13//! (`<project_root>/.claude/skills/<name>/SKILL.md`) — there is NO
14//! user-level `~/.claude/skills` tier the way `crate::agents::agents_dir`
15//! has for agents (`skills::locate_skills_dir` takes a `project_root`
16//! directly; every call site passes the bound project's root, never
17//! `$HOME`). This module's `tier` values are therefore `"bundled"` and
18//! `"project"` ONLY — never `"user"` — and `skills.create`/`skills.delete`
19//! require an actually-bound project (there is nowhere else on disk for a
20//! projectless daemon to persist a user-added skill); a projectless caller
21//! gets a clear `-32003 invalid_argument`, not a silent no-op or an
22//! invented user-level path nothing else in this crate would ever read.
23//! What: [`register`] wires three methods onto a shared, immutable
24//! [`SkillsCatalogState`] (an `Option<PathBuf>` project skills dir — `None`
25//! when projectless):
26//!   - `skills.list` -> `{"skills": [{name, tier, description}]}` — WHOLE-
27//!     CATALOG REPLACEMENT, mirroring `discover_skill_metadata`'s own
28//!     `if !skills.is_empty() { return skills }` threshold (see that
29//!     function's docs) exactly, at the catalog level rather than per-name:
30//!     when a project is bound and its disk skills directory has at least
31//!     one entry, the response is ONLY those disk skills (`tier:
32//!     "project"`) — the bundled catalog is entirely absent, because that
33//!     is what actually resolves at `task.run` time (`FsSkillResolver`
34//!     discards the whole bundled set the instant disk has anything).
35//!     Otherwise (projectless, or a bound project with no/empty disk
36//!     skills) the response is the full bundled catalog (`tier: "bundled"`).
37//!     A per-name bundled-∪-disk overlay would be WRONG here — it would
38//!     report bundled skills as available for a project whose real
39//!     `use_skill` catalog resolves only its own custom entries
40//!     (code-critic PR #3465 re-review, MEDIUM).
41//!   - `skills.create{name, content}` -> writes
42//!     `<skills_dir>/<name>/SKILL.md` from the caller-supplied
43//!     Markdown+frontmatter body. Same name-validation contract as
44//!     `agents::protocol::validate_agent_name` (shared, not reimplemented —
45//!     see that function's docs): rejects a name colliding with a bundled
46//!     skill (`-32001 permission_denied`, 403) or an already-existing disk
47//!     skill (`-32009 already_exists`, 409). `-32003
48//!     invalid_argument` (400) when projectless.
49//!   - `skills.delete{name}` -> removes `<skills_dir>/<name>/` recursively.
50//!     `-32002 not_found` (404) absent; `-32001 permission_denied` (403) for
51//!     a bundled name; `-32003 invalid_argument` (400) when projectless.
52//!
53//! Test: `tests::*`.
54
55use std::path::PathBuf;
56
57use serde::Deserialize;
58use serde_json::{Value, json};
59
60use crate::agents::protocol::validate_agent_name as validate_skill_name;
61use crate::jsonrpc::{ConnectionContext, Router, RpcError};
62
63use super::SkillMetadata;
64
65/// Shared, immutable state every `skills.*` handler in this module closes
66/// over: the project-scoped skills directory, or `None` when projectless.
67///
68/// Why: unlike [`crate::agents::protocol::AgentsCatalogState`], there is no
69/// user-level fallback directory for skills (see module docs) — `None` is a
70/// real, valid state (a projectless daemon can still LIST the bundled
71/// catalog), not a placeholder for "not wired up yet".
72#[derive(Clone)]
73pub struct SkillsCatalogState {
74    /// `<project_root>/.claude/skills`, or `None` when no project is bound.
75    pub dir: Option<PathBuf>,
76}
77
78impl SkillsCatalogState {
79    /// Build state from an optional bound project root.
80    ///
81    /// Why: keeps "resolve the skills dir from the binding, or None" in one
82    /// place (today: `crate::serve::build_router_at`).
83    /// What: `Some(super::locate_skills_dir(root))` when `project_root` is
84    /// `Some`, else `None`.
85    pub fn new(project_root: Option<&std::path::Path>) -> Self {
86        Self {
87            dir: project_root.map(super::locate_skills_dir),
88        }
89    }
90}
91
92/// Register `skills.list`, `skills.create`, `skills.delete` onto `router`.
93///
94/// Why: mirrors `crate::agents::protocol::register`'s shape for this
95/// namespace.
96/// Test: `tests::register_wires_all_three_methods`.
97pub fn register(router: &mut Router, state: SkillsCatalogState) {
98    let s = state.clone();
99    router.register(
100        "skills.list",
101        move |params: Value, ctx: ConnectionContext| {
102            let s = s.clone();
103            async move { skills_list(&s, params, ctx).await }
104        },
105    );
106
107    let s = state.clone();
108    router.register(
109        "skills.create",
110        move |params: Value, ctx: ConnectionContext| {
111            let s = s.clone();
112            async move { skills_create(&s, params, ctx).await }
113        },
114    );
115
116    let s = state;
117    router.register(
118        "skills.delete",
119        move |params: Value, ctx: ConnectionContext| {
120            let s = s.clone();
121            async move { skills_delete(&s, params, ctx).await }
122        },
123    );
124}
125
126/// Wire shape for one catalog entry.
127fn entry_json(m: &SkillMetadata, tier: &str) -> Value {
128    json!({ "name": m.name, "tier": tier, "description": m.description })
129}
130
131/// `skills.list` -> the catalog that will ACTUALLY resolve for this project
132/// at `task.run` time.
133///
134/// Why: the GUI's Skills tab roster fetch. The runtime resolver
135/// (`discover_skill_metadata`, wired through `FsSkillResolver` at
136/// `task::executor::daily_driver_skills_catalog`) does WHOLE-CATALOG
137/// REPLACEMENT, not a per-name overlay: the instant a project's
138/// `.claude/skills/` has even one entry, the ENTIRE bundled catalog is
139/// discarded — every bundled name becomes unresolvable
140/// (`skills::SkillError::Unknown` on `use_skill`), disk or not. An earlier
141/// version of this handler built a bundled ∪ disk union with per-name
142/// override (disk winning only for names it actually shadowed), which made
143/// `skills.list` report every bundled skill as available for a project that
144/// had, say, one custom skill and nothing else — the catalog lied about
145/// what would actually resolve (code-critic PR #3465 re-review, MEDIUM:
146/// "half-fixed" — the agents side already mirrored its resolver correctly,
147/// this side did not). Fixed by mirroring `discover_skill_metadata`'s own
148/// `if !skills.is_empty() { return skills }` threshold exactly, at the
149/// catalog level rather than per-name.
150/// What: ignores `params`. When `state.dir` is `Some` and
151/// `discover_disk_skill_metadata` returns anything non-empty, the response
152/// is EXACTLY those disk entries (`tier: "project"`) — no bundled entries
153/// at all. Otherwise (`state.dir` is `None`, i.e. projectless, OR the
154/// project's skills dir is missing/empty) the response is the full bundled
155/// catalog (`tier: "bundled"`). Sorted by name either way.
156///
157/// A FOURTH tier, `"plugin"`, is layered on top when `state.dir` is `Some`
158/// and a project root can be recovered from it (issue #3539 — Phase 1
159/// Claude Code plugin support): every skill discovered under
160/// `<project_root>/.claude/plugins/*/skills/` is added, namespaced
161/// `<plugin>:<name>` by `plugins::skills::discover_plugin_skills`. This
162/// layer is DELIBERATELY INDEPENDENT of the bundled-vs-project threshold
163/// above — it is added identically whether the response above was the
164/// bundled catalog or the project's own disk skills, so a project with one
165/// custom skill AND a plugin still sees both its custom skill and every
166/// plugin skill (#3539's locked precedence-interaction requirement; see
167/// `tests::list_plugin_skills_are_additive_alongside_project_custom_skill`).
168/// Test: `tests::list_returns_bundled_when_projectless`,
169/// `tests::list_returns_bundled_when_disk_empty`,
170/// `tests::list_returns_disk_only_when_disk_non_empty_no_bundled_entries`,
171/// `tests::list_plugin_skills_are_additive_alongside_project_custom_skill`.
172async fn skills_list(
173    state: &SkillsCatalogState,
174    _params: Value,
175    _ctx: ConnectionContext,
176) -> Result<Value, RpcError> {
177    let disk = state
178        .dir
179        .as_ref()
180        .map(|dir| super::discover_disk_skill_metadata(dir))
181        .unwrap_or_default();
182
183    let mut entries: Vec<(String, Value)> = if disk.is_empty() {
184        super::embedded_skill_metadata()
185            .iter()
186            .map(|m| (m.name.clone(), entry_json(m, "bundled")))
187            .collect()
188    } else {
189        disk.iter()
190            .map(|m| (m.name.clone(), entry_json(m, "project")))
191            .collect()
192    };
193
194    if let Some(dir) = &state.dir
195        && let Some(project_root) = crate::plugins::project_root_two_levels_up(dir)
196    {
197        for m in crate::plugins::skills::discover_plugin_skills(&project_root) {
198            entries.push((m.name.clone(), entry_json(&m, "plugin")));
199        }
200    }
201
202    entries.sort_by(|a, b| a.0.cmp(&b.0));
203    let skills: Vec<Value> = entries.into_iter().map(|(_, v)| v).collect();
204    Ok(json!({ "skills": skills }))
205}
206
207/// `params` shape for `skills.create`.
208#[derive(Deserialize)]
209struct CreateParams {
210    name: String,
211    content: String,
212}
213
214/// `skills.create` -> write `<skills_dir>/<name>/SKILL.md` from `content`.
215///
216/// Why: the GUI's Skills tab add-flow.
217/// What: `{"name", "tier": "project"}` on success. `-32003 invalid_argument`
218/// when projectless (nowhere to write); invalid `name`; embedded/bundled
219/// name collision (`-32001`, 403); existing disk skill (`-32009
220/// already_exists`, 409). The existence check is NOT a separate
221/// `skill_md.exists()` pre-check — the same TOCTOU hole
222/// `agents::protocol::agents_create` had (code-critic PR #3465 review,
223/// HIGH 2). Instead: `create_dir_all` the skill directory unconditionally
224/// (idempotent — an existing dir is fine, only the `SKILL.md` inside it is
225/// the conflict unit), then `agents::protocol::write_new_file`'s atomic
226/// `O_CREAT|O_EXCL` create on `SKILL.md` itself.
227/// Test: `tests::create_writes_file_and_returns_project_tier`,
228/// `tests::create_rejects_when_projectless`,
229/// `tests::create_rejects_bundled_name_collision`,
230/// `tests::create_rejects_existing_disk_skill`,
231/// `tests::create_conflict_does_not_clobber_existing_skill`.
232async fn skills_create(
233    state: &SkillsCatalogState,
234    params: Value,
235    _ctx: ConnectionContext,
236) -> Result<Value, RpcError> {
237    let p: CreateParams = serde_json::from_value(params)
238        .map_err(|e| RpcError::invalid_params(format!("skills.create: {e}")))?;
239    validate_skill_name(&p.name)?;
240
241    let Some(dir) = &state.dir else {
242        return Err(RpcError::invalid_argument(
243            "skills are project-scoped; bind a project before adding one",
244        ));
245    };
246
247    if super::embedded_skill_metadata()
248        .iter()
249        .any(|m| m.name == p.name)
250    {
251        return Err(RpcError::permission_denied(format!(
252            "'{}' is a bundled skill and cannot be overridden by name via this endpoint",
253            p.name
254        )));
255    }
256
257    let skill_dir = dir.join(&p.name);
258    let skill_md = skill_dir.join("SKILL.md");
259    std::fs::create_dir_all(&skill_dir)
260        .map_err(|e| RpcError::internal(format!("creating skill dir: {e}")))?;
261    crate::agents::protocol::write_new_file(&skill_md, &p.content, || {
262        format!("skill '{}' already exists on disk", p.name)
263    })?;
264
265    Ok(json!({ "name": p.name, "tier": "project" }))
266}
267
268/// `params` shape for `skills.delete`.
269#[derive(Deserialize)]
270struct DeleteParams {
271    name: String,
272}
273
274/// `skills.delete` -> remove `<skills_dir>/<name>/` recursively.
275///
276/// Why: the GUI's Skills tab remove-flow.
277/// What: `{}` on success. `-32003 invalid_argument` when projectless;
278/// `-32002 not_found` (404) when no disk skill directory exists under
279/// `name` and it is not bundled; `-32001 permission_denied` (403) for a
280/// bundled name.
281/// Test: `tests::delete_removes_disk_skill_dir`,
282/// `tests::delete_rejects_when_projectless`,
283/// `tests::delete_missing_name_returns_not_found`,
284/// `tests::delete_bundled_name_returns_permission_denied`.
285async fn skills_delete(
286    state: &SkillsCatalogState,
287    params: Value,
288    _ctx: ConnectionContext,
289) -> Result<Value, RpcError> {
290    let p: DeleteParams = serde_json::from_value(params)
291        .map_err(|e| RpcError::invalid_params(format!("skills.delete: {e}")))?;
292    validate_skill_name(&p.name)?;
293
294    let Some(dir) = &state.dir else {
295        return Err(RpcError::invalid_argument(
296            "skills are project-scoped; bind a project before deleting one",
297        ));
298    };
299
300    let skill_dir = dir.join(&p.name);
301    if !skill_dir.exists() {
302        if super::embedded_skill_metadata()
303            .iter()
304            .any(|m| m.name == p.name)
305        {
306            return Err(RpcError::permission_denied(format!(
307                "'{}' is a bundled skill and cannot be deleted",
308                p.name
309            )));
310        }
311        return Err(RpcError::not_found(format!(
312            "no disk skill named '{}'",
313            p.name
314        )));
315    }
316
317    std::fs::remove_dir_all(&skill_dir)
318        .map_err(|e| RpcError::internal(format!("deleting skill dir: {e}")))?;
319    Ok(json!({}))
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    fn ctx() -> ConnectionContext {
327        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
328        ConnectionContext::new(tx)
329    }
330
331    #[test]
332    fn locate_skills_dir_matches_project_only_tier() {
333        // Pins the module doc's central claim: no user-level fallback. The
334        // directory itself is trusty-code's own (#5426) — nothing on disk here,
335        // so the resolver returns the native default.
336        let root = std::path::Path::new("/fake/project");
337        let s = SkillsCatalogState::new(Some(root));
338        assert_eq!(s.dir, Some(root.join(".trusty-code").join("skills")));
339        let projectless = SkillsCatalogState::new(None);
340        assert_eq!(projectless.dir, None);
341    }
342
343    #[tokio::test]
344    async fn list_returns_bundled_when_projectless() {
345        let s = SkillsCatalogState::new(None);
346        let result = skills_list(&s, Value::Null, ctx()).await.expect("list");
347        let skills = result["skills"].as_array().expect("array");
348        assert_eq!(skills.len(), crate::assets::DEFAULT_SKILLS.len());
349        assert!(skills.iter().all(|sk| sk["tier"] == "bundled"));
350    }
351
352    /// A bound project with an EXISTING BUT EMPTY skills directory still
353    /// falls back to the bundled catalog — the same threshold
354    /// `discover_skill_metadata`'s own `if !skills.is_empty()` uses, pinned
355    /// here at the `skills.list` handler level too (code-critic PR #3465
356    /// re-review, MEDIUM).
357    #[tokio::test]
358    async fn list_returns_bundled_when_disk_empty() {
359        let tmp = tempfile::tempdir().expect("tempdir");
360        let s = SkillsCatalogState {
361            dir: Some(tmp.path().to_path_buf()),
362        };
363        let result = skills_list(&s, Value::Null, ctx()).await.expect("list");
364        let skills = result["skills"].as_array().expect("array");
365        assert_eq!(skills.len(), crate::assets::DEFAULT_SKILLS.len());
366        assert!(skills.iter().all(|sk| sk["tier"] == "bundled"));
367    }
368
369    /// The core fix under test (code-critic PR #3465 re-review, MEDIUM): a
370    /// project with even ONE custom disk skill must see ONLY that skill —
371    /// zero bundled entries — because that is exactly what
372    /// `FsSkillResolver`/`discover_skill_metadata` will actually resolve at
373    /// `task.run` time (whole-catalog replacement, not a per-name overlay).
374    /// A prior version of `skills_list` built a bundled ∪ disk union here,
375    /// which reported every bundled skill as available even though none of
376    /// them would actually dispatch — this test pins the corrected,
377    /// resolver-matching behavior.
378    #[tokio::test]
379    async fn list_returns_disk_only_when_disk_non_empty_no_bundled_entries() {
380        let tmp = tempfile::tempdir().expect("tempdir");
381        let dir = tmp.path().join("my-custom-skill");
382        std::fs::create_dir_all(&dir).expect("mkdir");
383        std::fs::write(
384            dir.join("SKILL.md"),
385            "---\nname: my-custom-skill\ndescription: Custom\n---\n\nBody.\n",
386        )
387        .expect("write");
388
389        let s = SkillsCatalogState {
390            dir: Some(tmp.path().to_path_buf()),
391        };
392        let result = skills_list(&s, Value::Null, ctx()).await.expect("list");
393        let skills = result["skills"].as_array().expect("array");
394        assert_eq!(
395            skills.len(),
396            1,
397            "must be ONLY the one disk skill — no bundled entries alongside it"
398        );
399        assert_eq!(skills[0]["name"], "my-custom-skill");
400        assert_eq!(skills[0]["tier"], "project");
401        assert!(
402            skills.iter().all(|sk| sk["tier"] != "bundled"),
403            "the bundled catalog must be entirely absent once disk is non-empty"
404        );
405    }
406
407    #[tokio::test]
408    async fn create_writes_file_and_returns_project_tier() {
409        let tmp = tempfile::tempdir().expect("tempdir");
410        let s = SkillsCatalogState {
411            dir: Some(tmp.path().to_path_buf()),
412        };
413        let result = skills_create(
414            &s,
415            json!({"name": "my-skill", "content": "---\nname: my-skill\n---\n\nBody.\n"}),
416            ctx(),
417        )
418        .await
419        .expect("create");
420        assert_eq!(result["name"], "my-skill");
421        assert_eq!(result["tier"], "project");
422        assert!(tmp.path().join("my-skill").join("SKILL.md").exists());
423    }
424
425    #[tokio::test]
426    async fn create_rejects_when_projectless() {
427        let s = SkillsCatalogState::new(None);
428        let err = skills_create(&s, json!({"name": "my-skill", "content": "x"}), ctx())
429            .await
430            .expect_err("must reject projectless create");
431        assert_eq!(err.code, -32003);
432    }
433
434    #[tokio::test]
435    async fn create_rejects_bundled_name_collision() {
436        let tmp = tempfile::tempdir().expect("tempdir");
437        let bundled_name = crate::assets::DEFAULT_SKILLS[0].name;
438        let s = SkillsCatalogState {
439            dir: Some(tmp.path().to_path_buf()),
440        };
441        let err = skills_create(&s, json!({"name": bundled_name, "content": "x"}), ctx())
442            .await
443            .expect_err("must reject bundled collision");
444        assert_eq!(err.code, -32001);
445    }
446
447    #[tokio::test]
448    async fn create_rejects_existing_disk_skill() {
449        let tmp = tempfile::tempdir().expect("tempdir");
450        let dir = tmp.path().join("dup-skill");
451        std::fs::create_dir_all(&dir).expect("mkdir");
452        std::fs::write(dir.join("SKILL.md"), "---\nname: dup-skill\n---\n\nBody.\n")
453            .expect("write");
454
455        let s = SkillsCatalogState {
456            dir: Some(tmp.path().to_path_buf()),
457        };
458        let err = skills_create(&s, json!({"name": "dup-skill", "content": "new"}), ctx())
459            .await
460            .expect_err("must reject existing disk skill");
461        // `-32009 already_exists` — NOT `-32008 active_conflict` (code-critic
462        // PR #3465 review, LOW).
463        assert_eq!(err.code, -32009);
464        assert_eq!(err.data.as_ref().unwrap()["error_type"], "already_exists");
465    }
466
467    /// The conflict path must go through `write_new_file`'s atomic
468    /// `O_CREAT|O_EXCL` create — a losing `skills.create` can NEVER have
469    /// truncated or overwritten the existing `SKILL.md`, even transiently
470    /// (code-critic PR #3465 review, HIGH 2).
471    #[tokio::test]
472    async fn create_conflict_does_not_clobber_existing_skill() {
473        let tmp = tempfile::tempdir().expect("tempdir");
474        let dir = tmp.path().join("dup-skill");
475        std::fs::create_dir_all(&dir).expect("mkdir");
476        let original = "---\nname: dup-skill\ndescription: ORIGINAL\n---\n\nBody.\n";
477        std::fs::write(dir.join("SKILL.md"), original).expect("write");
478
479        let s = SkillsCatalogState {
480            dir: Some(tmp.path().to_path_buf()),
481        };
482        let err = skills_create(
483            &s,
484            json!({"name": "dup-skill", "content": "CLOBBER"}),
485            ctx(),
486        )
487        .await
488        .expect_err("must conflict");
489        assert_eq!(err.code, -32009);
490
491        let on_disk = std::fs::read_to_string(dir.join("SKILL.md")).expect("read");
492        assert_eq!(on_disk, original, "existing SKILL.md must be untouched");
493    }
494
495    #[tokio::test]
496    async fn delete_removes_disk_skill_dir() {
497        let tmp = tempfile::tempdir().expect("tempdir");
498        let dir = tmp.path().join("my-skill");
499        std::fs::create_dir_all(&dir).expect("mkdir");
500        std::fs::write(dir.join("SKILL.md"), "---\nname: my-skill\n---\n\nBody.\n").expect("write");
501
502        let s = SkillsCatalogState {
503            dir: Some(tmp.path().to_path_buf()),
504        };
505        skills_delete(&s, json!({"name": "my-skill"}), ctx())
506            .await
507            .expect("delete");
508        assert!(!dir.exists());
509    }
510
511    #[tokio::test]
512    async fn delete_rejects_when_projectless() {
513        let s = SkillsCatalogState::new(None);
514        let err = skills_delete(&s, json!({"name": "my-skill"}), ctx())
515            .await
516            .expect_err("must reject projectless delete");
517        assert_eq!(err.code, -32003);
518    }
519
520    #[tokio::test]
521    async fn delete_missing_name_returns_not_found() {
522        let tmp = tempfile::tempdir().expect("tempdir");
523        let s = SkillsCatalogState {
524            dir: Some(tmp.path().to_path_buf()),
525        };
526        let err = skills_delete(&s, json!({"name": "totally-bogus"}), ctx())
527            .await
528            .expect_err("must 404");
529        assert_eq!(err.code, -32002);
530    }
531
532    #[tokio::test]
533    async fn delete_bundled_name_returns_permission_denied() {
534        let tmp = tempfile::tempdir().expect("tempdir");
535        let bundled_name = crate::assets::DEFAULT_SKILLS[0].name;
536        let s = SkillsCatalogState {
537            dir: Some(tmp.path().to_path_buf()),
538        };
539        let err = skills_delete(&s, json!({"name": bundled_name}), ctx())
540            .await
541            .expect_err("must 403");
542        assert_eq!(err.code, -32001);
543    }
544
545    #[tokio::test]
546    async fn register_wires_all_three_methods() {
547        use trusty_mcp::Request;
548
549        let mut router = Router::new();
550        register(&mut router, SkillsCatalogState::new(None));
551
552        let req = Request {
553            jsonrpc: Some("2.0".to_string()),
554            id: Some(Value::from(1)),
555            method: "skills.list".to_string(),
556            params: None,
557        };
558        let resp = router.dispatch(req, &ctx()).await;
559        assert!(resp.result.is_some(), "skills.list must be wired");
560        assert!(resp.result.unwrap()["skills"].is_array());
561    }
562
563    /// `skills.list`'s `plugin` tier is independent of the bundled-vs-project
564    /// whole-catalog-replacement threshold (PR #3465): a project with ONE
565    /// custom skill (which alone would suppress the bundled catalog, see
566    /// `list_returns_disk_only_when_disk_non_empty_no_bundled_entries`)
567    /// PLUS a plugin still shows both the project's custom skill and every
568    /// namespaced plugin skill (issue #3539's locked precedence-interaction
569    /// requirement).
570    ///
571    /// Why: this is the exact test #3539 calls for — proof that neither
572    /// side of the interaction suppresses the other.
573    /// Test: this test.
574    #[tokio::test]
575    async fn list_plugin_skills_are_additive_alongside_project_custom_skill() {
576        let tmp = tempfile::tempdir().expect("tempdir");
577        let skills_dir = tmp.path().join(".claude").join("skills");
578        let custom_dir = skills_dir.join("my-custom-skill");
579        std::fs::create_dir_all(&custom_dir).expect("mkdir");
580        std::fs::write(
581            custom_dir.join("SKILL.md"),
582            "---\nname: my-custom-skill\ndescription: Custom\n---\n\nBody.\n",
583        )
584        .expect("write");
585
586        let plugin_skill_dir = tmp
587            .path()
588            .join(".claude")
589            .join("plugins")
590            .join("my-plugin")
591            .join("skills")
592            .join("plugin-skill");
593        std::fs::create_dir_all(&plugin_skill_dir).expect("mkdir");
594        std::fs::write(
595            plugin_skill_dir.join("SKILL.md"),
596            "---\nname: plugin-skill\ndescription: From a plugin\n---\n\nBody.\n",
597        )
598        .expect("write");
599
600        let s = SkillsCatalogState {
601            dir: Some(skills_dir),
602        };
603        let result = skills_list(&s, Value::Null, ctx()).await.expect("list");
604        let skills = result["skills"].as_array().expect("array");
605
606        let project_entry = skills
607            .iter()
608            .find(|sk| sk["name"] == "my-custom-skill")
609            .expect("the project's own custom skill must still be listed");
610        assert_eq!(project_entry["tier"], "project");
611
612        let plugin_entry = skills
613            .iter()
614            .find(|sk| sk["name"] == "my-plugin:plugin-skill")
615            .expect("the namespaced plugin skill must be listed too");
616        assert_eq!(plugin_entry["tier"], "plugin");
617
618        assert!(
619            skills.iter().all(|sk| sk["tier"] != "bundled"),
620            "the bundled catalog must still be entirely absent (unrelated to the plugin tier)"
621        );
622    }
623}