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.
334 let root = std::path::Path::new("/fake/project");
335 let s = SkillsCatalogState::new(Some(root));
336 assert_eq!(s.dir, Some(root.join(".claude").join("skills")));
337 let projectless = SkillsCatalogState::new(None);
338 assert_eq!(projectless.dir, None);
339 }
340
341 #[tokio::test]
342 async fn list_returns_bundled_when_projectless() {
343 let s = SkillsCatalogState::new(None);
344 let result = skills_list(&s, Value::Null, ctx()).await.expect("list");
345 let skills = result["skills"].as_array().expect("array");
346 assert_eq!(skills.len(), crate::assets::DEFAULT_SKILLS.len());
347 assert!(skills.iter().all(|sk| sk["tier"] == "bundled"));
348 }
349
350 /// A bound project with an EXISTING BUT EMPTY skills directory still
351 /// falls back to the bundled catalog — the same threshold
352 /// `discover_skill_metadata`'s own `if !skills.is_empty()` uses, pinned
353 /// here at the `skills.list` handler level too (code-critic PR #3465
354 /// re-review, MEDIUM).
355 #[tokio::test]
356 async fn list_returns_bundled_when_disk_empty() {
357 let tmp = tempfile::tempdir().expect("tempdir");
358 let s = SkillsCatalogState {
359 dir: Some(tmp.path().to_path_buf()),
360 };
361 let result = skills_list(&s, Value::Null, ctx()).await.expect("list");
362 let skills = result["skills"].as_array().expect("array");
363 assert_eq!(skills.len(), crate::assets::DEFAULT_SKILLS.len());
364 assert!(skills.iter().all(|sk| sk["tier"] == "bundled"));
365 }
366
367 /// The core fix under test (code-critic PR #3465 re-review, MEDIUM): a
368 /// project with even ONE custom disk skill must see ONLY that skill —
369 /// zero bundled entries — because that is exactly what
370 /// `FsSkillResolver`/`discover_skill_metadata` will actually resolve at
371 /// `task.run` time (whole-catalog replacement, not a per-name overlay).
372 /// A prior version of `skills_list` built a bundled ∪ disk union here,
373 /// which reported every bundled skill as available even though none of
374 /// them would actually dispatch — this test pins the corrected,
375 /// resolver-matching behavior.
376 #[tokio::test]
377 async fn list_returns_disk_only_when_disk_non_empty_no_bundled_entries() {
378 let tmp = tempfile::tempdir().expect("tempdir");
379 let dir = tmp.path().join("my-custom-skill");
380 std::fs::create_dir_all(&dir).expect("mkdir");
381 std::fs::write(
382 dir.join("SKILL.md"),
383 "---\nname: my-custom-skill\ndescription: Custom\n---\n\nBody.\n",
384 )
385 .expect("write");
386
387 let s = SkillsCatalogState {
388 dir: Some(tmp.path().to_path_buf()),
389 };
390 let result = skills_list(&s, Value::Null, ctx()).await.expect("list");
391 let skills = result["skills"].as_array().expect("array");
392 assert_eq!(
393 skills.len(),
394 1,
395 "must be ONLY the one disk skill — no bundled entries alongside it"
396 );
397 assert_eq!(skills[0]["name"], "my-custom-skill");
398 assert_eq!(skills[0]["tier"], "project");
399 assert!(
400 skills.iter().all(|sk| sk["tier"] != "bundled"),
401 "the bundled catalog must be entirely absent once disk is non-empty"
402 );
403 }
404
405 #[tokio::test]
406 async fn create_writes_file_and_returns_project_tier() {
407 let tmp = tempfile::tempdir().expect("tempdir");
408 let s = SkillsCatalogState {
409 dir: Some(tmp.path().to_path_buf()),
410 };
411 let result = skills_create(
412 &s,
413 json!({"name": "my-skill", "content": "---\nname: my-skill\n---\n\nBody.\n"}),
414 ctx(),
415 )
416 .await
417 .expect("create");
418 assert_eq!(result["name"], "my-skill");
419 assert_eq!(result["tier"], "project");
420 assert!(tmp.path().join("my-skill").join("SKILL.md").exists());
421 }
422
423 #[tokio::test]
424 async fn create_rejects_when_projectless() {
425 let s = SkillsCatalogState::new(None);
426 let err = skills_create(&s, json!({"name": "my-skill", "content": "x"}), ctx())
427 .await
428 .expect_err("must reject projectless create");
429 assert_eq!(err.code, -32003);
430 }
431
432 #[tokio::test]
433 async fn create_rejects_bundled_name_collision() {
434 let tmp = tempfile::tempdir().expect("tempdir");
435 let bundled_name = crate::assets::DEFAULT_SKILLS[0].name;
436 let s = SkillsCatalogState {
437 dir: Some(tmp.path().to_path_buf()),
438 };
439 let err = skills_create(&s, json!({"name": bundled_name, "content": "x"}), ctx())
440 .await
441 .expect_err("must reject bundled collision");
442 assert_eq!(err.code, -32001);
443 }
444
445 #[tokio::test]
446 async fn create_rejects_existing_disk_skill() {
447 let tmp = tempfile::tempdir().expect("tempdir");
448 let dir = tmp.path().join("dup-skill");
449 std::fs::create_dir_all(&dir).expect("mkdir");
450 std::fs::write(dir.join("SKILL.md"), "---\nname: dup-skill\n---\n\nBody.\n")
451 .expect("write");
452
453 let s = SkillsCatalogState {
454 dir: Some(tmp.path().to_path_buf()),
455 };
456 let err = skills_create(&s, json!({"name": "dup-skill", "content": "new"}), ctx())
457 .await
458 .expect_err("must reject existing disk skill");
459 // `-32009 already_exists` — NOT `-32008 active_conflict` (code-critic
460 // PR #3465 review, LOW).
461 assert_eq!(err.code, -32009);
462 assert_eq!(err.data.as_ref().unwrap()["error_type"], "already_exists");
463 }
464
465 /// The conflict path must go through `write_new_file`'s atomic
466 /// `O_CREAT|O_EXCL` create — a losing `skills.create` can NEVER have
467 /// truncated or overwritten the existing `SKILL.md`, even transiently
468 /// (code-critic PR #3465 review, HIGH 2).
469 #[tokio::test]
470 async fn create_conflict_does_not_clobber_existing_skill() {
471 let tmp = tempfile::tempdir().expect("tempdir");
472 let dir = tmp.path().join("dup-skill");
473 std::fs::create_dir_all(&dir).expect("mkdir");
474 let original = "---\nname: dup-skill\ndescription: ORIGINAL\n---\n\nBody.\n";
475 std::fs::write(dir.join("SKILL.md"), original).expect("write");
476
477 let s = SkillsCatalogState {
478 dir: Some(tmp.path().to_path_buf()),
479 };
480 let err = skills_create(
481 &s,
482 json!({"name": "dup-skill", "content": "CLOBBER"}),
483 ctx(),
484 )
485 .await
486 .expect_err("must conflict");
487 assert_eq!(err.code, -32009);
488
489 let on_disk = std::fs::read_to_string(dir.join("SKILL.md")).expect("read");
490 assert_eq!(on_disk, original, "existing SKILL.md must be untouched");
491 }
492
493 #[tokio::test]
494 async fn delete_removes_disk_skill_dir() {
495 let tmp = tempfile::tempdir().expect("tempdir");
496 let dir = tmp.path().join("my-skill");
497 std::fs::create_dir_all(&dir).expect("mkdir");
498 std::fs::write(dir.join("SKILL.md"), "---\nname: my-skill\n---\n\nBody.\n").expect("write");
499
500 let s = SkillsCatalogState {
501 dir: Some(tmp.path().to_path_buf()),
502 };
503 skills_delete(&s, json!({"name": "my-skill"}), ctx())
504 .await
505 .expect("delete");
506 assert!(!dir.exists());
507 }
508
509 #[tokio::test]
510 async fn delete_rejects_when_projectless() {
511 let s = SkillsCatalogState::new(None);
512 let err = skills_delete(&s, json!({"name": "my-skill"}), ctx())
513 .await
514 .expect_err("must reject projectless delete");
515 assert_eq!(err.code, -32003);
516 }
517
518 #[tokio::test]
519 async fn delete_missing_name_returns_not_found() {
520 let tmp = tempfile::tempdir().expect("tempdir");
521 let s = SkillsCatalogState {
522 dir: Some(tmp.path().to_path_buf()),
523 };
524 let err = skills_delete(&s, json!({"name": "totally-bogus"}), ctx())
525 .await
526 .expect_err("must 404");
527 assert_eq!(err.code, -32002);
528 }
529
530 #[tokio::test]
531 async fn delete_bundled_name_returns_permission_denied() {
532 let tmp = tempfile::tempdir().expect("tempdir");
533 let bundled_name = crate::assets::DEFAULT_SKILLS[0].name;
534 let s = SkillsCatalogState {
535 dir: Some(tmp.path().to_path_buf()),
536 };
537 let err = skills_delete(&s, json!({"name": bundled_name}), ctx())
538 .await
539 .expect_err("must 403");
540 assert_eq!(err.code, -32001);
541 }
542
543 #[tokio::test]
544 async fn register_wires_all_three_methods() {
545 use trusty_mcp::Request;
546
547 let mut router = Router::new();
548 register(&mut router, SkillsCatalogState::new(None));
549
550 let req = Request {
551 jsonrpc: Some("2.0".to_string()),
552 id: Some(Value::from(1)),
553 method: "skills.list".to_string(),
554 params: None,
555 };
556 let resp = router.dispatch(req, &ctx()).await;
557 assert!(resp.result.is_some(), "skills.list must be wired");
558 assert!(resp.result.unwrap()["skills"].is_array());
559 }
560
561 /// `skills.list`'s `plugin` tier is independent of the bundled-vs-project
562 /// whole-catalog-replacement threshold (PR #3465): a project with ONE
563 /// custom skill (which alone would suppress the bundled catalog, see
564 /// `list_returns_disk_only_when_disk_non_empty_no_bundled_entries`)
565 /// PLUS a plugin still shows both the project's custom skill and every
566 /// namespaced plugin skill (issue #3539's locked precedence-interaction
567 /// requirement).
568 ///
569 /// Why: this is the exact test #3539 calls for — proof that neither
570 /// side of the interaction suppresses the other.
571 /// Test: this test.
572 #[tokio::test]
573 async fn list_plugin_skills_are_additive_alongside_project_custom_skill() {
574 let tmp = tempfile::tempdir().expect("tempdir");
575 let skills_dir = tmp.path().join(".claude").join("skills");
576 let custom_dir = skills_dir.join("my-custom-skill");
577 std::fs::create_dir_all(&custom_dir).expect("mkdir");
578 std::fs::write(
579 custom_dir.join("SKILL.md"),
580 "---\nname: my-custom-skill\ndescription: Custom\n---\n\nBody.\n",
581 )
582 .expect("write");
583
584 let plugin_skill_dir = tmp
585 .path()
586 .join(".claude")
587 .join("plugins")
588 .join("my-plugin")
589 .join("skills")
590 .join("plugin-skill");
591 std::fs::create_dir_all(&plugin_skill_dir).expect("mkdir");
592 std::fs::write(
593 plugin_skill_dir.join("SKILL.md"),
594 "---\nname: plugin-skill\ndescription: From a plugin\n---\n\nBody.\n",
595 )
596 .expect("write");
597
598 let s = SkillsCatalogState {
599 dir: Some(skills_dir),
600 };
601 let result = skills_list(&s, Value::Null, ctx()).await.expect("list");
602 let skills = result["skills"].as_array().expect("array");
603
604 let project_entry = skills
605 .iter()
606 .find(|sk| sk["name"] == "my-custom-skill")
607 .expect("the project's own custom skill must still be listed");
608 assert_eq!(project_entry["tier"], "project");
609
610 let plugin_entry = skills
611 .iter()
612 .find(|sk| sk["name"] == "my-plugin:plugin-skill")
613 .expect("the namespaced plugin skill must be listed too");
614 assert_eq!(plugin_entry["tier"], "plugin");
615
616 assert!(
617 skills.iter().all(|sk| sk["tier"] != "bundled"),
618 "the bundled catalog must still be entirely absent (unrelated to the plugin tier)"
619 );
620 }
621}