trusty-code 0.1.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
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
//! 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.
//! 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), and
//! `FsSkillResolver`'s `SkillResolver` trait conformance.

mod frontmatter;

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,
    },
}

/// Locate the Claude-Code-compatible skills directory for a project root.
///
/// Why: #2069 pins this to `.claude/skills/` exactly — the Claude-Code-native
/// convention — and explicitly NOT the legacy `~/.trusty-mpm/skills/` path
/// trusty-mpm uses, so a project's skill catalog resolves identically whether
/// browsed by a human in Claude Code or discovered by `tcode`.
/// What: Returns `<project_root>/.claude/skills` (may not exist yet — callers
/// handle absence via `discover_skill_metadata`'s empty-Vec fallback).
/// Test: `locate_skills_dir_is_dot_claude_skills`.
pub fn locate_skills_dir(project_root: &Path) -> PathBuf {
    project_root.join(".claude").join("skills")
}

/// 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.
/// 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`. A missing/unreadable `dir` yields an empty Vec.
/// Test: `discover_skill_metadata_reads_name_and_description`,
/// `discover_skill_metadata_skips_dir_without_skill_md`,
/// `discover_skill_metadata_missing_dir_is_empty`,
/// `discover_skill_metadata_falls_back_to_dirname`.
pub fn discover_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![];
    };

    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
}

/// 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.
/// Reads `<skills_dir>/<name>/SKILL.md` and returns the body after the
/// frontmatter fence, trimmed.
/// Test: `load_skill_body_returns_body_without_frontmatter`,
/// `load_skill_body_rejects_unknown_name`.
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 = std::fs::read_to_string(&path).map_err(|source| 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.
/// Test: `fs_skill_resolver_resolves_known_skill`,
/// `fs_skill_resolver_list_matches_metadata_names`,
/// `fs_skill_resolver_resolve_unknown_returns_none`.
pub struct FsSkillResolver {
    skills_dir: PathBuf,
    metadata: Vec<SkillMetadata>,
}

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)` and stores both.
    /// Test: `fs_skill_resolver_resolves_known_skill`.
    pub fn new(skills_dir: impl Into<PathBuf>) -> Self {
        let skills_dir = skills_dir.into();
        let metadata = discover_skill_metadata(&skills_dir);
        Self {
            skills_dir,
            metadata,
        }
    }
}

impl SkillResolver for FsSkillResolver {
    fn resolve(&self, name: &str) -> Option<String> {
        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` returns `<project_root>/.claude/skills` exactly.
    ///
    /// Why: Pins the Claude-Code-compatible path (#2069) so a future edit
    /// cannot silently drift back to `~/.trusty-mpm/skills/`.
    /// Test: this test.
    #[test]
    fn locate_skills_dir_is_dot_claude_skills() {
        let root = Path::new("/fake/project");
        assert_eq!(locate_skills_dir(root), root.join(".claude").join("skills"));
    }

    /// 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 yields an empty catalog, not an error.
    ///
    /// Why: Most projects will not have a `.claude/skills/` dir at all;
    /// this must never panic or hard-fail discovery.
    /// Test: this test.
    #[test]
    fn discover_skill_metadata_missing_dir_is_empty() {
        let skills = discover_skill_metadata(Path::new("/nonexistent/skills/dir"));
        assert!(skills.is_empty());
    }

    /// 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.
    /// 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(_))));
    }

    /// `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.
    /// 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());
    }
}