trusty-code 0.8.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! Progressive-disclosure skill discovery for `.claude/skills/` (#2069, vision
//! spec §5.3, Resolved Decision #7).
//!
//! Why: A project's `.claude/skills/` catalog can hold dozens of skills, but
//! any given task only ever invokes a handful of them. Injecting every
//! skill's full Markdown body into the system prompt up front wastes
//! 500-1000+ tokens per session for a 20-skill catalog (spec §5.3 impact
//! estimate) when ~80% of skills are never invoked. Splitting a skill into
//! cheap, always-cached metadata (name + one-line description, ~100 tokens
//! per skill) and an on-demand-loaded body lets the PM/agents see the full
//! catalog for free and pay the body's token cost only for skills they
//! actually use. This module mirrors `agents::discover_agents`'s directory
//! scanning pattern, adapted for the Claude-Code skill layout: one
//! subdirectory per skill, each holding a `SKILL.md` with YAML-ish
//! frontmatter (`name:`, `description:`, …) followed by the Markdown body.
//! What: [`SkillMetadata`] (the cached catalog entry), [`locate_skills_dir`]
//! (resolves `<project_root>/.claude/skills` — the Claude-Code-compatible
//! path; deliberately NOT `~/.trusty-mpm/skills/`), [`discover_skill_metadata`]
//! (scans the directory and parses just the frontmatter of every skill),
//! [`load_skill_body`] (the lazy, on-invoke full-body loader), and
//! [`format_skill_catalog`] (renders the metadata list for prompt injection).
//! [`FsSkillResolver`] implements `tools::traits::SkillResolver` over this
//! discovery layer, giving the tool-registry layer a ready-to-register
//! concrete resolver.
//! `discover_skill_metadata` falls back to the default catalog
//! (`crate::assets::DEFAULT_SKILL_NAMES`, #2895; read from content since
//! #9013) when the disk directory has no skills — a project with no
//! `.claude/skills/` (or an empty one) still gets trusty-mpm's universal
//! skill catalog. No content means no default skills, under one error naming
//! the remedy. A disk directory with even one skill is used as-is (never
//! merged with the embedded set) — disk always wins.
//! Test: `skills::tests::*` — discovery over tempdir fixtures (happy path,
//! missing dir, missing `SKILL.md`, malformed/no-frontmatter file), lazy body
//! load (found + unknown-name), catalog formatting (empty + populated),
//! embedded-fallback threshold, and `FsSkillResolver`'s `SkillResolver` trait
//! conformance.
//!
//! [`SkillMetadata`]: crate::skills::SkillMetadata
//! [`locate_skills_dir`]: crate::skills::locate_skills_dir
//! [`discover_skill_metadata`]: crate::skills::discover_skill_metadata
//! [`load_skill_body`]: crate::skills::load_skill_body
//! [`format_skill_catalog`]: crate::skills::format_skill_catalog
//! [`FsSkillResolver`]: crate::skills::FsSkillResolver

// `pub(crate)`: also reused by `plugins::agents`/`plugins::skills` (#3539)
// — both are generic frontmatter helpers, not skill-specific, so a plugin
// agent's unsupported-field detection and a plugin skill's body-stripping
// share this one parser rather than forking a second copy.
pub(crate) mod frontmatter;
pub mod protocol;

use std::path::{Path, PathBuf};

use thiserror::Error;

use crate::tools::traits::SkillResolver;
use frontmatter::{parse_frontmatter, strip_frontmatter};

/// Cheap, always-cached catalog entry for one discovered skill.
///
/// Why: The PM/agents need to see what skills exist and when to reach for
/// them without paying for every skill's full body up front.
/// What: `name` (frontmatter `name:`, falling back to the skill's directory
/// name) and `description` (frontmatter `description:`, empty string if
/// absent).
/// Test: `discover_skill_metadata_reads_name_and_description`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillMetadata {
    pub name: String,
    pub description: String,
}

/// Errors from lazily loading a skill's full body.
///
/// Why: A named error type lets `SkillResolver::resolve` and the `use_skill`
/// tool distinguish "unknown skill" (an LLM hallucinated a name) from a
/// genuine IO failure, both without panicking.
/// What: `Unknown` — the name is not in the discovered catalog; `Io` — the
/// `SKILL.md` file could not be read even though the name is known.
/// Test: `load_skill_body_rejects_unknown_name`, `load_skill_body_io_error`.
#[derive(Debug, Error)]
pub enum SkillError {
    #[error("skill '{0}' is not in the discovered catalog")]
    Unknown(String),
    #[error("failed to read skill body for '{name}': {source}")]
    Io {
        name: String,
        #[source]
        source: std::io::Error,
    },
    /// #9013: a default skill's text could not be read from content; the
    /// message names the remedy.
    #[error("default skill '{name}' is unavailable: {source}")]
    Content {
        name: String,
        #[source]
        source: trusty_agents_common::agent_content::AgentContentError,
    },
}

/// Locate the skills directory for a project root.
///
/// Why: #2069 pinned this to `.claude/skills/` exactly. #5426 unpins it: Trusty
/// Code owns `<project_root>/.trusty-code/skills/`, and `.claude/skills/` stays
/// readable behind it so a project's existing catalog keeps resolving whether
/// browsed by a human in Claude Code or discovered by `tcode`. It is still
/// explicitly NOT the `~/.trusty-mpm/skills/` path trusty-mpm uses.
/// What: delegates to [`crate::paths::skills_dir`] and keeps its path — the
/// single precedence rule, shared with agents, plugins, and settings. May not
/// exist yet; callers handle absence via `discover_skill_metadata`'s empty-Vec
/// fallback.
/// Test: `locate_skills_dir_is_dot_claude_skills`,
/// `paths::tests::skills_dir_prefers_trusty_code`.
pub fn locate_skills_dir(project_root: &Path) -> PathBuf {
    // #5426: one resolver, not a second copy of the precedence chain.
    crate::paths::skills_dir(project_root).path
}

/// Discover skill metadata from every `<dir>/<skill-name>/SKILL.md`.
///
/// Why: The catalog must be built once, cheaply, from cheap-to-read
/// frontmatter only — the whole point of progressive disclosure is to avoid
/// reading full skill bodies until they are actually invoked. A project that
/// has not yet created `.claude/skills/` (or has created it but left it
/// empty) must not start with zero skills — see the embedded-fallback note
/// below.
/// What: Scans immediate subdirectories of `dir`; a subdirectory without a
/// readable `SKILL.md` is skipped (not an error — mirrors
/// `agents::discover_agents`'s graceful-skip convention). Returns entries
/// sorted by `name`. If the scan yields zero entries (missing/unreadable
/// `dir`, or an existing-but-empty one — empty is the fallback threshold; a
/// disk directory with even one discoverable skill is used as-is, never
/// merged with the default set), falls back to `embedded_skill_metadata`
/// (`crate::assets::DEFAULT_SKILL_NAMES`, #2895, read from content since
/// #9013). Disk skills always win when present.
/// Test: `discover_skill_metadata_reads_name_and_description`,
/// `discover_skill_metadata_skips_dir_without_skill_md`,
/// `discover_skill_metadata_falls_back_to_embedded_when_disk_empty`,
/// `discover_skill_metadata_disk_wins_when_present`,
/// `discover_skill_metadata_falls_back_to_dirname`.
pub fn discover_skill_metadata(dir: &Path) -> Vec<SkillMetadata> {
    let skills = discover_disk_skill_metadata(dir);
    if skills.is_empty() {
        return embedded_skill_metadata();
    }
    skills
}

/// Scan `dir` for disk skills WITHOUT the embedded-fallback threshold —
/// returns an empty `Vec` for a missing/empty directory rather than
/// substituting `embedded_skill_metadata()` (#3449).
///
/// Why: `protocol::skills_list` needs to distinguish "this project genuinely
/// has zero custom skills" from "here is the bundled catalog" — merging the
/// two (as [`discover_skill_metadata`]'s fallback does, correctly, for the
/// *tool-facing* discovery/prompt-injection path) would mislabel every
/// bundled entry as `tier: "project"` in the catalog endpoint whenever a
/// project's `.claude/skills/` happens to be empty. Factored out of
/// [`discover_skill_metadata`] so the fallback threshold lives in exactly
/// one place; the tool-facing function above is unchanged in behavior.
/// What: identical directory scan/sort to [`discover_skill_metadata`], minus
/// the embedded-fallback branch.
/// Test: `protocol::tests::list_returns_disk_only_when_disk_non_empty_no_bundled_entries`,
/// `protocol::tests::list_returns_bundled_when_projectless`,
/// `protocol::tests::list_returns_bundled_when_disk_empty`.
pub(crate) fn discover_disk_skill_metadata(dir: &Path) -> Vec<SkillMetadata> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        tracing::debug!("skills dir not found or unreadable: {}", dir.display());
        return Vec::new();
    };

    let mut skills: Vec<SkillMetadata> = entries
        .flatten()
        .filter_map(|entry| load_metadata_from_skill_dir(&entry.path()))
        .collect();
    skills.sort_by(|a, b| a.name.cmp(&b.name));
    skills
}

/// Build the default skill catalog from content (#9013).
///
/// Why: The fallback path for `discover_skill_metadata` — parses each default
/// `SKILL.md`'s frontmatter in-memory, exactly as
/// `load_metadata_from_skill_dir` does for a disk file, so the resulting
/// `SkillMetadata` is indistinguishable from a disk-discovered one.
/// What: reads every `crate::assets::DEFAULT_SKILL_NAMES` skill through
/// `crate::assets::content::load_default_skills` and maps each through
/// `parse_frontmatter`, sorted by name. With no content, or a content release
/// lacking a default skill, the catalog is empty under one ERROR per process
/// naming the remedy (ADR-0064: runtime-only, fail closed) — never a partial
/// catalog.
/// Test: `discover_skill_metadata_falls_back_to_embedded_when_disk_empty`.
fn embedded_skill_metadata() -> Vec<SkillMetadata> {
    const UNAVAILABLE: &str = "tcode's default skills are unavailable";
    let Ok(defaults) = crate::assets::content::load_default_skills().inspect_err(|e| {
        if !trusty_agents_common::agent_content::report_not_installed(e, UNAVAILABLE) {
            tracing::error!("{UNAVAILABLE}: {e}");
        }
    }) else {
        return Vec::new();
    };
    let mut skills: Vec<SkillMetadata> = defaults
        .iter()
        .map(|embedded| {
            let front = parse_frontmatter(&embedded.skill_md);
            SkillMetadata {
                name: front
                    .get("name")
                    .cloned()
                    .unwrap_or_else(|| embedded.name.to_string()),
                description: front.get("description").cloned().unwrap_or_default(),
            }
        })
        .collect();
    skills.sort_by(|a, b| a.name.cmp(&b.name));
    skills
}

/// Load one skill directory's metadata, if it holds a readable `SKILL.md`.
///
/// Why: Factored out of `discover_skill_metadata` so each rejection reason
/// (not a directory, no `SKILL.md`, unreadable) can be logged distinctly.
/// What: Returns `None` (with a debug log) for anything that is not a skill
/// directory; otherwise parses frontmatter and falls back to the directory
/// name when `name:` is absent.
/// Test: covered via `discover_skill_metadata`'s tests above.
fn load_metadata_from_skill_dir(path: &Path) -> Option<SkillMetadata> {
    if !path.is_dir() {
        return None;
    }
    let dirname = path.file_name()?.to_str()?.to_string();
    let skill_md = path.join("SKILL.md");
    let raw = match std::fs::read_to_string(&skill_md) {
        Ok(raw) => raw,
        Err(e) => {
            tracing::debug!("skipping skill dir '{dirname}': no readable SKILL.md ({e})");
            return None;
        }
    };
    let front = parse_frontmatter(&raw);
    let name = front.get("name").cloned().unwrap_or(dirname);
    let description = front.get("description").cloned().unwrap_or_default();
    Some(SkillMetadata { name, description })
}

/// Lazily load one skill's full Markdown body (the frontmatter stripped off).
///
/// Why: This is the "on invoke" half of progressive disclosure — the body is
/// read from disk only when a caller (the `use_skill` tool, or a resolver's
/// `resolve`) actually needs it.
/// What: Rejects any `name` not present in `known` (the cached catalog) up
/// front — this doubles as the path-traversal guard, since the join'd path is
/// only ever built from a name the catalog itself already discovered (on disk
/// or embedded). Reads `<skills_dir>/<name>/SKILL.md`; if that read fails
/// (the disk fallback case: `known` came from `embedded_skill_metadata`, so
/// there is no such file) and `name` is a `crate::assets::DEFAULT_SKILL_NAMES`
/// entry, returns that default body from content instead (#2895, #9013); a
/// content failure is `SkillError::Content` naming the remedy. Otherwise
/// propagates the disk `Io` error. Either way, the
/// frontmatter fence is stripped and the body trimmed.
/// Test: `load_skill_body_returns_body_without_frontmatter`,
/// `load_skill_body_rejects_unknown_name`,
/// `load_skill_body_falls_back_to_embedded_when_disk_read_fails`.
pub fn load_skill_body(
    skills_dir: &Path,
    name: &str,
    known: &[SkillMetadata],
) -> Result<String, SkillError> {
    if !known.iter().any(|m| m.name == name) {
        return Err(SkillError::Unknown(name.to_string()));
    }
    let path = skills_dir.join(name).join("SKILL.md");
    let raw = match std::fs::read_to_string(&path) {
        Ok(raw) => raw,
        Err(source) => {
            // #9013: the default body is content, read only for a default name.
            let default = crate::assets::content::load_default_skill(name).map_err(|source| {
                SkillError::Content {
                    name: name.to_string(),
                    source,
                }
            })?;
            if let Some(md) = default {
                return Ok(strip_frontmatter(&md).trim().to_string());
            }
            return Err(SkillError::Io {
                name: name.to_string(),
                source,
            });
        }
    };
    Ok(strip_frontmatter(&raw).trim().to_string())
}

/// Render the compact, always-injected skill catalog for prompt assembly.
///
/// Why: This is the entire token-efficiency payoff — a one-line-per-skill
/// listing instead of every skill's full body.
/// What: Returns an empty string when `skills` is empty (callers treat an
/// empty section as "omit it", matching `assemble_system_prompt`'s
/// empty-section-skipping convention). Otherwise a header line plus one
/// `- name: description` line per skill, in the given order (callers pass
/// already name-sorted `Vec`s from `discover_skill_metadata`).
/// Test: `format_skill_catalog_empty_is_empty_string`,
/// `format_skill_catalog_lists_every_skill`.
pub fn format_skill_catalog(skills: &[SkillMetadata]) -> String {
    if skills.is_empty() {
        return String::new();
    }
    let mut out = String::from(
        "Available skills (invoke the `use_skill` tool with the skill name to load its full instructions):\n",
    );
    for s in skills {
        out.push_str(&format!("- {}: {}\n", s.name, s.description));
    }
    out.trim_end().to_string()
}

/// Filesystem-backed [`SkillResolver`] over a `.claude/skills/` directory.
///
/// Why: Gives the tool-registry layer (the `use_skill` tool) a ready
/// concrete resolver: metadata is discovered once at construction (cheap,
/// cached); `resolve` reads a single skill's body lazily, on demand.
/// What: Wraps `skills_dir` plus the metadata discovered from it at
/// construction time. `metadata()`/`list()` return the cached catalog;
/// `resolve()` calls `load_skill_body` per invocation.
/// As of #3539 (Phase 1 Claude Code plugin support), also namespaces and
/// resolves plugin skills (`<plugin>:<name>`) — see `plugins::skills`,
/// which this struct delegates to additively (never suppressing, never
/// suppressed by, the project/embedded threshold above).
/// Test: `fs_skill_resolver_resolves_known_skill`,
/// `fs_skill_resolver_list_matches_metadata_names`,
/// `fs_skill_resolver_resolve_unknown_returns_none`,
/// `fs_skill_resolver_resolves_namespaced_plugin_skill`,
/// `fs_skill_resolver_metadata_includes_plugin_skills_alongside_project_skill`.
pub struct FsSkillResolver {
    skills_dir: PathBuf,
    metadata: Vec<SkillMetadata>,
    /// The project root recovered from `skills_dir`
    /// (`crate::plugins::project_root_two_levels_up`), or `None` when
    /// `skills_dir` isn't shaped `<root>/.claude/skills` (e.g. a bare
    /// tempdir in a unit test that doesn't exercise plugins). Cached once at
    /// construction so `resolve` never re-derives it per call.
    project_root: Option<PathBuf>,
}

impl FsSkillResolver {
    /// Construct a resolver, eagerly discovering (cheap) metadata.
    ///
    /// Why: Metadata discovery is a directory scan plus frontmatter parsing
    /// only — cheap enough to do once at construction so every later
    /// `metadata()`/`list()` call is a clone of an in-memory `Vec`.
    /// What: Calls `discover_skill_metadata(&skills_dir)`, then additively
    /// extends it with `plugins::skills::discover_plugin_skills` when a
    /// project root can be recovered from `skills_dir` (#3539) — plugin
    /// skills are independent of the project/embedded threshold
    /// `discover_skill_metadata` applies, so they are appended regardless
    /// of whether that call returned the project's own catalog or the
    /// embedded fallback.
    /// Test: `fs_skill_resolver_resolves_known_skill`,
    /// `fs_skill_resolver_metadata_includes_plugin_skills_alongside_project_skill`.
    pub fn new(skills_dir: impl Into<PathBuf>) -> Self {
        let skills_dir = skills_dir.into();
        let mut metadata = discover_skill_metadata(&skills_dir);
        let project_root = crate::plugins::project_root_two_levels_up(&skills_dir);
        if let Some(root) = &project_root {
            metadata.extend(crate::plugins::skills::discover_plugin_skills(root));
        }
        Self {
            skills_dir,
            metadata,
            project_root,
        }
    }
}

impl SkillResolver for FsSkillResolver {
    /// A namespaced `<plugin>:<name>` (the exact shape a plugin skill
    /// listing surfaces, and — via `tools::skill::UseSkillTool` — the exact
    /// shape an LLM's raw `use_skill` argument can be) routes to
    /// `plugins::skills::resolve_plugin_skill_body`, which is itself the
    /// authoritative traversal guard (validates the namespaced shape and
    /// discovered-catalog membership before ever building a path — issue
    /// #3547 CRITICAL 2). This wrapper does not re-validate; it only
    /// recovers the cached `project_root` (`None` short-circuits to `None`
    /// rather than falling through to the plain-name path below, since a
    /// namespaced name is never a valid plain skill name either way).
    fn resolve(&self, name: &str) -> Option<String> {
        if let Some((plugin, skill_name)) = name.split_once(':') {
            return self.project_root.as_deref().and_then(|root| {
                crate::plugins::skills::resolve_plugin_skill_body(root, plugin, skill_name)
            });
        }
        load_skill_body(&self.skills_dir, name, &self.metadata).ok()
    }

    fn list(&self) -> Vec<String> {
        self.metadata.iter().map(|m| m.name.clone()).collect()
    }

    fn metadata(&self) -> Vec<SkillMetadata> {
        self.metadata.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn write_skill(root: &Path, name: &str, frontmatter: &str, body: &str) {
        let dir = root.join(name);
        std::fs::create_dir_all(&dir).expect("mkdir skill dir");
        std::fs::write(dir.join("SKILL.md"), format!("{frontmatter}{body}")).expect("write");
    }

    /// `locate_skills_dir` defaults to `.trusty-code/skills` and still finds an
    /// existing `.claude/skills` (#5426).
    ///
    /// Why: pins both halves — the native default (so a clean project needs no
    /// `.claude/`) and the compatibility fallback (so an existing catalog keeps
    /// resolving) — and keeps either from drifting to `~/.trusty-mpm/skills/`.
    /// What: an empty project resolves native; adding `.claude/skills` makes it
    /// win; adding `.trusty-code/skills` takes precedence back.
    /// Test: this function IS the test.
    #[test]
    fn locate_skills_dir_is_dot_claude_skills() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path();
        assert_eq!(
            locate_skills_dir(root),
            root.join(".trusty-code").join("skills"),
            "a clean project must resolve skills under trusty-code's own directory"
        );

        std::fs::create_dir_all(root.join(".claude").join("skills")).expect("mkdir");
        assert_eq!(
            locate_skills_dir(root),
            root.join(".claude").join("skills"),
            "an existing .claude/skills must still resolve"
        );

        std::fs::create_dir_all(root.join(".trusty-code").join("skills")).expect("mkdir");
        assert_eq!(
            locate_skills_dir(root),
            root.join(".trusty-code").join("skills"),
            ".trusty-code/skills must win when both exist"
        );
    }

    /// Discovery reads `name`/`description` from frontmatter for every
    /// skill directory containing a `SKILL.md`.
    ///
    /// Why: This is the core "always cached, cheap" discovery contract.
    /// What: Two skill dirs; asserts both appear, sorted by name, with the
    /// exact frontmatter values.
    /// Test: this test.
    #[test]
    fn discover_skill_metadata_reads_name_and_description() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_skill(
            tmp.path(),
            "zeta-skill",
            "---\nname: zeta-skill\ndescription: Does zeta things\n---\n",
            "# Zeta\nbody\n",
        );
        write_skill(
            tmp.path(),
            "alpha-skill",
            "---\nname: alpha-skill\ndescription: Does alpha things\n---\n",
            "# Alpha\nbody\n",
        );

        let skills = discover_skill_metadata(tmp.path());
        assert_eq!(skills.len(), 2);
        assert_eq!(skills[0].name, "alpha-skill");
        assert_eq!(skills[0].description, "Does alpha things");
        assert_eq!(skills[1].name, "zeta-skill");
        assert_eq!(skills[1].description, "Does zeta things");
    }

    /// A subdirectory with no `SKILL.md` is skipped, not an error.
    ///
    /// Why: `.claude/skills/` may contain scratch or in-progress
    /// directories; discovery must degrade gracefully (no panic).
    /// Test: this test.
    #[test]
    fn discover_skill_metadata_skips_dir_without_skill_md() {
        let tmp = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir_all(tmp.path().join("not-a-skill")).expect("mkdir");
        write_skill(
            tmp.path(),
            "real-skill",
            "---\nname: real-skill\ndescription: A real one\n---\n",
            "body\n",
        );

        let skills = discover_skill_metadata(tmp.path());
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].name, "real-skill");
    }

    /// A missing skills directory falls back to the embedded default
    /// catalog, not an empty one (#2895).
    ///
    /// Why: Most projects will not have a `.claude/skills/` dir at all; a
    /// fresh project must still see trusty-mpm's universal skill set rather
    /// than starting with zero skills.
    /// What: Discover from a nonexistent path; expect the full embedded
    /// catalog (28 skills, sorted by name — matches
    /// `crate::assets::tests::default_skills_names_are_unique`'s count).
    /// Test: this test.
    #[test]
    fn discover_skill_metadata_falls_back_to_embedded_when_disk_empty() {
        let skills = discover_skill_metadata(Path::new("/nonexistent/skills/dir"));
        assert_eq!(skills.len(), 28);
        assert!(skills.iter().any(|s| s.name == "systematic-debugging"));
        assert!(
            skills.windows(2).all(|w| w[0].name <= w[1].name),
            "embedded fallback must be sorted by name"
        );
    }

    /// A disk directory with even one discoverable skill is used as-is; the
    /// embedded defaults are never merged in alongside it.
    ///
    /// Why: Pins the fallback threshold (empty disk scan only) so a project
    /// that has deliberately curated its own skill catalog is not silently
    /// joined by the 28 embedded defaults it did not ask for.
    /// Test: this test.
    #[test]
    fn discover_skill_metadata_disk_wins_when_present() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_skill(
            tmp.path(),
            "only-skill",
            "---\nname: only-skill\ndescription: The only one\n---\n",
            "body\n",
        );

        let skills = discover_skill_metadata(tmp.path());
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].name, "only-skill");
    }

    /// A `SKILL.md` with no frontmatter fence falls back to the directory
    /// name and an empty description, rather than being rejected.
    ///
    /// Why: Malformed skill files must degrade gracefully (no panic).
    /// Test: this test.
    #[test]
    fn discover_skill_metadata_falls_back_to_dirname() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_skill(tmp.path(), "no-frontmatter", "", "# Just a body\n");

        let skills = discover_skill_metadata(tmp.path());
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].name, "no-frontmatter");
        assert_eq!(skills[0].description, "");
    }

    /// `load_skill_body` returns the body with frontmatter stripped, for a
    /// name present in the known catalog.
    ///
    /// Why: This is the lazy on-invoke load path.
    /// Test: this test.
    #[test]
    fn load_skill_body_returns_body_without_frontmatter() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_skill(
            tmp.path(),
            "demo-skill",
            "---\nname: demo-skill\ndescription: Demo\n---\n",
            "# Demo Skill\nFull instructions here.\n",
        );
        let known = discover_skill_metadata(tmp.path());

        let body = load_skill_body(tmp.path(), "demo-skill", &known).expect("load body");
        assert!(body.contains("# Demo Skill"));
        assert!(body.contains("Full instructions here."));
        assert!(!body.contains("description: Demo"));
    }

    /// `load_skill_body` rejects a name absent from the known catalog.
    ///
    /// Why: This is the safety guard against an LLM hallucinating a skill
    /// name — no path is ever built from a name outside the discovered set.
    /// What: `tmp` is an empty tempdir, so `discover_skill_metadata` returns
    /// the embedded-fallback catalog (the 28 names in
    /// `crate::assets::DEFAULT_SKILL_NAMES`, #2895), not a truly empty one;
    /// `"ghost-skill"` is absent from that catalog too, so this now exercises
    /// unknown-name rejection against the embedded fallback rather than an
    /// empty set — the guard behaves identically either way.
    /// Test: this test.
    #[test]
    fn load_skill_body_rejects_unknown_name() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let known = discover_skill_metadata(tmp.path());
        let err = load_skill_body(tmp.path(), "ghost-skill", &known);
        assert!(matches!(err, Err(SkillError::Unknown(_))));
    }

    /// `load_skill_body` falls back to the default catalog when
    /// the disk read fails but the name is a known embedded default (#2895).
    ///
    /// Why: `known` may itself have come from `embedded_skill_metadata` (an
    /// empty disk dir); the body loader must be able to resolve those names
    /// too, not just names discovered from real files.
    /// What: An empty tempdir (so `discover_skill_metadata` returns the
    /// embedded catalog), then `load_skill_body` for a real embedded skill
    /// name returns its body without hitting disk.
    /// Test: this test.
    #[test]
    fn load_skill_body_falls_back_to_embedded_when_disk_read_fails() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let known = discover_skill_metadata(tmp.path());
        let body =
            load_skill_body(tmp.path(), "systematic-debugging", &known).expect("embedded body");
        assert!(!body.trim().is_empty());
        assert!(
            !body.contains("name: systematic-debugging"),
            "frontmatter must be stripped"
        );
    }

    /// `format_skill_catalog` returns an empty string for an empty catalog.
    ///
    /// Why: An empty section must contribute nothing to the assembled
    /// prompt, matching `assemble_system_prompt`'s empty-section-skipping.
    /// Test: this test.
    #[test]
    fn format_skill_catalog_empty_is_empty_string() {
        assert_eq!(format_skill_catalog(&[]), "");
    }

    /// `format_skill_catalog` lists every skill as a `- name: description`
    /// line.
    ///
    /// Why: This is the token-efficient catalog the prompt actually sees.
    /// Test: this test.
    #[test]
    fn format_skill_catalog_lists_every_skill() {
        let skills = vec![
            SkillMetadata {
                name: "alpha".into(),
                description: "First".into(),
            },
            SkillMetadata {
                name: "beta".into(),
                description: "Second".into(),
            },
        ];
        let catalog = format_skill_catalog(&skills);
        assert!(catalog.contains("- alpha: First"));
        assert!(catalog.contains("- beta: Second"));
    }

    /// `FsSkillResolver::resolve` lazily loads a known skill's body.
    ///
    /// Why: Verifies the concrete `SkillResolver` impl end-to-end.
    /// Test: this test.
    #[test]
    fn fs_skill_resolver_resolves_known_skill() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_skill(
            tmp.path(),
            "demo-skill",
            "---\nname: demo-skill\ndescription: Demo\n---\n",
            "Full body content.\n",
        );
        let resolver = FsSkillResolver::new(tmp.path());
        let body = resolver.resolve("demo-skill").expect("resolve");
        assert!(body.contains("Full body content."));
    }

    /// `FsSkillResolver::list` returns exactly the discovered metadata names.
    ///
    /// Test: this test.
    #[test]
    fn fs_skill_resolver_list_matches_metadata_names() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_skill(
            tmp.path(),
            "demo-skill",
            "---\nname: demo-skill\ndescription: Demo\n---\n",
            "body\n",
        );
        let resolver = FsSkillResolver::new(tmp.path());
        assert_eq!(resolver.list(), vec!["demo-skill".to_string()]);
        assert_eq!(resolver.metadata().len(), 1);
    }

    /// `FsSkillResolver::resolve` returns `None` for an unknown skill name.
    ///
    /// Why: Guards against a panic or leaked IO error surfacing through the
    /// trait's `Option`-returning API.
    /// What: `tmp` is an empty tempdir, so the resolver's cached metadata is
    /// the embedded-fallback catalog (the 28 names in
    /// `crate::assets::DEFAULT_SKILL_NAMES`, #2895), not a truly empty one;
    /// `"ghost"` is absent from that catalog too, so this now exercises
    /// unknown-name resolution against the embedded fallback rather than an
    /// empty set.
    /// Test: this test.
    #[test]
    fn fs_skill_resolver_resolve_unknown_returns_none() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let resolver = FsSkillResolver::new(tmp.path());
        assert!(resolver.resolve("ghost").is_none());
    }

    /// `FsSkillResolver::resolve` routes a namespaced `<plugin>:<name>` to
    /// the plugin's own `SKILL.md` (issue #3539).
    ///
    /// Why: this is the acceptance criterion for the resolution half of
    /// #3539's skill-namespacing decision — a namespaced skill must
    /// actually load its body via `use_skill`, not just appear in a catalog
    /// listing.
    /// Test: this test.
    #[test]
    fn fs_skill_resolver_resolves_namespaced_plugin_skill() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let skills_dir = tmp.path().join(".claude").join("skills");
        std::fs::create_dir_all(&skills_dir).expect("mkdir");
        write_skill(
            &tmp.path()
                .join(".claude")
                .join("plugins")
                .join("my-plugin")
                .join("skills"),
            "demo-skill",
            "---\nname: demo-skill\n---\n",
            "Plugin skill body.\n",
        );

        let resolver = FsSkillResolver::new(&skills_dir);
        let body = resolver
            .resolve("my-plugin:demo-skill")
            .expect("resolve namespaced plugin skill");
        assert!(body.contains("Plugin skill body."));
    }

    /// `FsSkillResolver`'s cached metadata includes plugin skills ADDITIVELY
    /// alongside a project's own custom skill catalog — the
    /// project-vs-bundled whole-catalog-replacement threshold (PR #3465)
    /// neither suppresses nor is suppressed by the plugin tier (#3539's
    /// locked precedence-interaction requirement).
    ///
    /// Test: this test.
    #[test]
    fn fs_skill_resolver_metadata_includes_plugin_skills_alongside_project_skill() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let skills_dir = tmp.path().join(".claude").join("skills");
        write_skill(
            &skills_dir,
            "project-only-skill",
            "---\nname: project-only-skill\n---\n",
            "body\n",
        );
        write_skill(
            &tmp.path()
                .join(".claude")
                .join("plugins")
                .join("my-plugin")
                .join("skills"),
            "plugin-skill",
            "---\nname: plugin-skill\n---\n",
            "body\n",
        );

        let resolver = FsSkillResolver::new(&skills_dir);
        let names = resolver.list();
        assert!(
            names.contains(&"project-only-skill".to_string()),
            "the project's own custom skill must still be listed, got: {names:?}"
        );
        assert!(
            names.contains(&"my-plugin:plugin-skill".to_string()),
            "the namespaced plugin skill must be listed too, got: {names:?}"
        );
    }
}