trusty-mpm 0.19.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Skill deployment — writes skill directories into `~/.claude/skills/`.
//!
//! Why: Claude Code discovers skills from `~/.claude/skills/<name>/SKILL.md`
//! (directory per skill, entry-point file named `SKILL.md`). trusty-mpm must
//! keep that directory populated with up-to-date skills in that format, while
//! never destroying files the user owns or has hand-edited. Skills carry no
//! inheritance, so — unlike agents — deployment is a plain content copy, but
//! the manifest-based ownership tracking is identical.
//! What: [`deploy_skills`] reads every `*.md` file from a source directory,
//! derives the skill name by stripping the `.md` extension, and writes each
//! one as `~/.claude/skills/<name>/SKILL.md`. It consults the
//! [`SkillManifest`] to classify each target file and writes only the files it
//! safely may. It returns a [`DeployStats`] summarising what happened.
//! Test: `cargo test -p trusty-mpm skill_deployer` covers a new deploy, a
//! skipped user-modified file, an unchanged file, and a user-owned file.

use std::path::Path;

use crate::core::agent_manifest::{atomic_write, checksum};
use crate::core::error::Error;
use crate::core::skill_manifest::{SkillManifest, SkillManifestEntry};

/// Summary of one [`deploy_skills`] run.
///
/// Why: callers print per-file status; they need the file lists split by
/// outcome to render that summary and to know whether any work was skipped.
/// What: filenames grouped into freshly written, skipped (user-owned or
/// user-modified), and unchanged (checksum already current).
/// Test: every `deploy_*` test asserts on these vectors.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DeployStats {
    /// Filenames successfully (re)written this run.
    pub deployed: Vec<String>,
    /// Filenames skipped because the user owns or modified them, or because
    /// the name collides with a Claude Code built-in slash command (e.g.
    /// contains "mcp" — see [`deploy_skills_filtered`]).
    pub skipped: Vec<String>,
    /// Filenames left untouched because their checksum already matched.
    pub unchanged: Vec<String>,
}

/// Whether a source filename names a skill file to deploy.
///
/// Why: the source directory holds `.md` files; only those should be deployed,
/// and any manifest file or hidden file must be ignored.
/// What: returns `true` for `*.md` files that do not start with `.`.
/// Test: covered indirectly by `deploy_new_skill`.
fn is_skill_file(name: &str) -> bool {
    !name.starts_with('.') && name.ends_with(".md")
}

/// Derive the skill name (manifest key and target directory name) from a
/// source filename.
///
/// Why: sources are flat `<name>.md` files but the deploy target is
/// `<dest>/<name>/SKILL.md`. Stripping `.md` gives the shared name.
/// What: returns the filename without its `.md` suffix.
/// Test: covered indirectly by every `deploy_*` test.
fn skill_stem(filename: &str) -> &str {
    filename.strip_suffix(".md").unwrap_or(filename)
}

/// Deploy all skills from `source` to `dest`.
///
/// Why: ensures `~/.claude/skills/` has up-to-date skill files without
/// clobbering user-owned or user-modified files.
///
/// Rules:
///   - Name (stem) contains "mcp" (case-insensitive) → collides with Claude
///     Code's built-in `/mcp` command → skip, never written (#2186)
///   - Not in manifest, file exists → user-owned → skip silently
///   - In manifest, checksum matches deployed copy → overwrite when stale
///   - In manifest, checksum differs → user-modified → skip
///   - New trusty-mpm skill → write + add to manifest
///
/// Test: `deploy_new_skill`, `deploy_skips_user_modified`,
/// `deploy_unchanged_no_write`, `deploy_user_owned_skipped`,
/// `deploy_skips_mcp_named_skill`.
pub fn deploy_skills(source: &Path, dest: &Path) -> Result<DeployStats, Error> {
    // Default policy: deploy every skill in the source directory.
    deploy_skills_filtered(source, dest, |_name| true)
}

/// Deploy skills from `source`, restricting to those `select` accepts.
///
/// Why: HR-2 manifests describe a skill *set* (include/exclude globs); the
/// session-launch path must deploy a subset of the source skills without copying
/// the whole directory. Factoring the selection into a predicate keeps the
/// manifest logic in `session_launch` while reusing the identical
/// ownership/atomic-write machinery here.
/// What: identical to [`deploy_skills`] except a source skill whose stem (the
/// `.md`-stripped name) `select` rejects is skipped before any write.
/// [`deploy_skills`] delegates here with an accept-all predicate, so existing
/// behavior is unchanged. Deselecting a skill does not remove a previously
/// deployed copy (an HR-3 concern).
/// Test: `deploy_filtered_respects_predicate`.
pub fn deploy_skills_filtered(
    source: &Path,
    dest: &Path,
    select: impl Fn(&str) -> bool,
) -> Result<DeployStats, Error> {
    let mut stats = DeployStats::default();

    // No source directory means nothing to deploy — an empty result, not an
    // error, so a fresh install with no skills still succeeds. This is a
    // legitimate state for a fresh checkout, but it is also indistinguishable
    // from a misconfigured `skill_source_dir()` (e.g. a submodule that failed
    // to initialise) unless we log it — silently returning an empty
    // `DeployStats` previously left operators with no signal that zero
    // skills were ever considered (A2, tm-skills-portfolio epic).
    if !source.is_dir() {
        tracing::warn!(
            source = %source.display(),
            "skill source directory missing — no skills will be deployed"
        );
        return Ok(stats);
    }

    let mut manifest = SkillManifest::load(dest);
    let now = chrono::Utc::now().to_rfc3339();

    // Collect skill filenames deterministically so output and tests are stable.
    let mut names: Vec<String> = Vec::new();
    let mut source_file_count = 0usize;
    for entry in std::fs::read_dir(source)? {
        let entry = entry?;
        let file_name = entry.file_name();
        let Some(name) = file_name.to_str() else {
            continue;
        };
        if entry.file_type()?.is_file() && is_skill_file(name) {
            source_file_count += 1;
            // Honour the manifest's skill-set selection (HR-2). The stem is the
            // `.md`-stripped name used as the skill id and target dir name.
            if select(skill_stem(name)) {
                names.push(name.to_string());
            }
        }
    }
    names.sort_unstable();

    // An existing but empty source directory is just as silent a failure mode
    // as a missing one — e.g. a populated `agents/skills/` submodule checked
    // out shallow, or a source dir pointed at the wrong path (A2).
    if source_file_count == 0 {
        tracing::warn!(
            source = %source.display(),
            "skill source directory is empty — no skills will be deployed"
        );
    }

    for filename in names {
        let stem = skill_stem(&filename).to_string();

        // Claude Code ships a built-in `/mcp` slash command. A deployed skill
        // whose invocable name (the stem, i.e. the directory Claude Code
        // exposes as `/<stem>`) contains "mcp" shadows that built-in and
        // makes `/mcp` unreachable for the user (#2186). Reject before any
        // file I/O or manifest write so a bad name never lands on disk.
        if stem.to_lowercase().contains("mcp") {
            tracing::warn!(
                skill = %stem,
                "refusing to deploy skill whose name contains \"mcp\" — it would shadow Claude Code's built-in /mcp command"
            );
            stats.skipped.push(stem);
            continue;
        }

        let source_path = source.join(&filename);
        let content = std::fs::read_to_string(&source_path)?;
        // Claude Code discovers skills from <dest>/<name>/SKILL.md.
        let skill_dir = dest.join(&stem);
        let target_path = skill_dir.join("SKILL.md");

        // Classify the existing target file, if any.
        if target_path.exists() {
            if !manifest.is_managed(&stem) {
                // User dropped their own file here — never touch it.
                stats.skipped.push(stem);
                continue;
            }
            let current = std::fs::read_to_string(&target_path)?;
            if manifest.checksum_matches(&stem, &current) {
                if checksum(&content) == checksum(&current) {
                    // Deployed copy is already the latest content.
                    stats.unchanged.push(stem);
                    continue;
                }
                // Managed and unmodified by the user → safe to refresh.
            } else {
                // Managed but the user edited it → preserve their changes.
                stats.skipped.push(stem);
                continue;
            }
        }

        // Write (new file, or safe refresh of a managed file) atomically.
        // Create <dest>/<name>/ if needed, then write SKILL.md via
        // write-temp-then-rename so a crash between the content write and the
        // subsequent manifest save leaves the old file intact.
        std::fs::create_dir_all(&skill_dir)?;
        atomic_write(&target_path, &content)?;
        manifest.managed.insert(
            stem.clone(),
            SkillManifestEntry {
                checksum: checksum(&content),
                deployed_at: now.clone(),
            },
        );
        stats.deployed.push(stem);
    }

    manifest.save(dest)?;

    Ok(stats)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// A two-file skill source set.
    fn write_sources(dir: &Path) {
        fs::write(
            dir.join("tm-doctor.md"),
            "---\nname: tm-doctor\n---\n\n# Doctor\n\nDiagnostic skill.\n",
        )
        .unwrap();
        fs::write(
            dir.join("example-skill.md"),
            "---\nname: example-skill\n---\n\n# Example\n\nExample skill.\n",
        )
        .unwrap();
    }

    #[test]
    fn deploy_new_skill() {
        // A first-ever deploy must write every skill as <dest>/<name>/SKILL.md
        // and record the skill name (stem) in the manifest.
        let src = TempDir::new().unwrap();
        let tgt = TempDir::new().unwrap();
        write_sources(src.path());

        let stats = deploy_skills(src.path(), tgt.path()).unwrap();
        assert_eq!(stats.deployed.len(), 2);
        // Stats report stems, not filenames.
        assert!(stats.deployed.contains(&"tm-doctor".to_string()));
        assert!(stats.skipped.is_empty());
        assert!(stats.unchanged.is_empty());

        // Each skill lands at <dest>/<name>/SKILL.md — not a flat .md file.
        let doctor = fs::read_to_string(tgt.path().join("tm-doctor").join("SKILL.md")).unwrap();
        assert!(doctor.contains("Diagnostic skill."));

        let manifest = SkillManifest::load(tgt.path());
        assert!(manifest.is_managed("tm-doctor"));
    }

    #[test]
    fn deploy_filtered_respects_predicate() {
        // HR-2: a selection predicate restricts which source skills deploy.
        let src = TempDir::new().unwrap();
        let tgt = TempDir::new().unwrap();
        write_sources(src.path()); // tm-doctor.md + example-skill.md

        let stats =
            deploy_skills_filtered(src.path(), tgt.path(), |name| name == "example-skill").unwrap();

        assert!(stats.deployed.contains(&"example-skill".to_string()));
        assert!(!stats.deployed.contains(&"tm-doctor".to_string()));
        assert!(tgt.path().join("example-skill").join("SKILL.md").exists());
        assert!(!tgt.path().join("tm-doctor").exists());
    }

    #[test]
    fn deploy_skips_user_modified() {
        // A managed file the user edited must be skipped, not overwritten.
        let src = TempDir::new().unwrap();
        let tgt = TempDir::new().unwrap();
        write_sources(src.path());

        deploy_skills(src.path(), tgt.path()).unwrap();

        // Simulate the user editing the deployed SKILL.md.
        fs::write(
            tgt.path().join("tm-doctor").join("SKILL.md"),
            "---\nname: tm-doctor\n---\n\nUSER HAND-EDIT\n",
        )
        .unwrap();

        let stats = deploy_skills(src.path(), tgt.path()).unwrap();
        assert!(stats.skipped.contains(&"tm-doctor".to_string()));
        assert!(!stats.deployed.contains(&"tm-doctor".to_string()));

        let still = fs::read_to_string(tgt.path().join("tm-doctor").join("SKILL.md")).unwrap();
        assert!(still.contains("USER HAND-EDIT"));
    }

    #[test]
    fn deploy_unchanged_no_write() {
        // A second deploy with no source changes must report files unchanged
        // and not rewrite them.
        let src = TempDir::new().unwrap();
        let tgt = TempDir::new().unwrap();
        write_sources(src.path());

        deploy_skills(src.path(), tgt.path()).unwrap();
        let skill_md = tgt.path().join("tm-doctor").join("SKILL.md");
        let before = fs::metadata(&skill_md).unwrap().modified().unwrap();

        let stats = deploy_skills(src.path(), tgt.path()).unwrap();
        assert!(stats.unchanged.contains(&"tm-doctor".to_string()));
        assert!(stats.deployed.is_empty());

        let after = fs::metadata(&skill_md).unwrap().modified().unwrap();
        assert_eq!(before, after, "unchanged file must not be rewritten");
    }

    #[test]
    fn deploy_user_owned_skipped() {
        // A SKILL.md in the target that trusty-mpm never deployed (absent from
        // the manifest) must be left completely untouched.
        let src = TempDir::new().unwrap();
        let tgt = TempDir::new().unwrap();
        write_sources(src.path());

        // Pre-create a user-owned skill directory for tm-doctor.
        let user_dir = tgt.path().join("tm-doctor");
        fs::create_dir_all(&user_dir).unwrap();
        fs::write(user_dir.join("SKILL.md"), "USER OWNED — not trusty-mpm's\n").unwrap();

        let stats = deploy_skills(src.path(), tgt.path()).unwrap();
        assert!(stats.skipped.contains(&"tm-doctor".to_string()));

        let content = fs::read_to_string(user_dir.join("SKILL.md")).unwrap();
        assert_eq!(content, "USER OWNED — not trusty-mpm's\n");

        // example-skill had no conflict, so it deploys normally.
        assert!(stats.deployed.contains(&"example-skill".to_string()));
    }

    #[test]
    fn deploy_refreshes_stale_managed_skill() {
        // A managed, unmodified file whose source changed must be refreshed.
        let src = TempDir::new().unwrap();
        let tgt = TempDir::new().unwrap();
        write_sources(src.path());

        deploy_skills(src.path(), tgt.path()).unwrap();

        // The framework updates the source skill.
        fs::write(
            src.path().join("tm-doctor.md"),
            "---\nname: tm-doctor\n---\n\n# Doctor v2\n",
        )
        .unwrap();

        let stats = deploy_skills(src.path(), tgt.path()).unwrap();
        assert!(stats.deployed.contains(&"tm-doctor".to_string()));
        let refreshed = fs::read_to_string(tgt.path().join("tm-doctor").join("SKILL.md")).unwrap();
        assert!(refreshed.contains("Doctor v2"));
    }

    #[test]
    fn deploy_skips_mcp_named_skill() {
        // #2186: a skill whose name (stem) contains "mcp" must never be
        // deployed — Claude Code's built-in `/mcp` command would be shadowed
        // by `/toolchains-ai-protocols-mcp` (or any other mcp-containing
        // name). It must be recorded as skipped, not deployed, and must not
        // block sibling skills in the same batch from deploying normally.
        let src = TempDir::new().unwrap();
        let tgt = TempDir::new().unwrap();
        write_sources(src.path()); // tm-doctor.md + example-skill.md
        fs::write(
            src.path().join("toolchains-ai-protocols-mcp.md"),
            "---\nname: toolchains-ai-protocols-mcp\n---\n\n# AI Protocols\n\nMCP guidance.\n",
        )
        .unwrap();

        let stats = deploy_skills(src.path(), tgt.path()).unwrap();

        assert!(
            stats
                .skipped
                .contains(&"toolchains-ai-protocols-mcp".to_string())
        );
        assert!(
            !stats
                .deployed
                .contains(&"toolchains-ai-protocols-mcp".to_string())
        );
        assert!(
            !tgt.path()
                .join("toolchains-ai-protocols-mcp")
                .join("SKILL.md")
                .exists(),
            "an mcp-named skill must never be written to disk"
        );

        // Sibling non-mcp skills in the same batch must still deploy.
        assert!(stats.deployed.contains(&"tm-doctor".to_string()));
        assert!(stats.deployed.contains(&"example-skill".to_string()));
    }

    #[test]
    fn deploy_skips_mcp_named_skill_case_insensitive() {
        // The guard must match "mcp" regardless of case (e.g. `Foo-MCP.md`).
        let src = TempDir::new().unwrap();
        let tgt = TempDir::new().unwrap();
        write_sources(src.path()); // tm-doctor.md + example-skill.md
        fs::write(
            src.path().join("Foo-MCP.md"),
            "---\nname: Foo-MCP\n---\n\n# Foo MCP\n\nSomething.\n",
        )
        .unwrap();

        let stats = deploy_skills(src.path(), tgt.path()).unwrap();

        assert!(stats.skipped.contains(&"Foo-MCP".to_string()));
        assert!(!stats.deployed.contains(&"Foo-MCP".to_string()));
        assert!(!tgt.path().join("Foo-MCP").exists());
    }

    #[test]
    fn deploy_missing_source_dir_is_empty_result() {
        // Deploying from a non-existent source directory is a no-op success.
        let tgt = TempDir::new().unwrap();
        let stats = deploy_skills(Path::new("/nonexistent/trusty-mpm/skills"), tgt.path()).unwrap();
        assert_eq!(stats, DeployStats::default());
    }
}