skls 0.3.2

TUI for listing and managing agent skills across Cursor, Claude Code, and Codex
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
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
//! Orchestrate add / delete / update across adapters and filesystem.

use crate::adapters::command::CommandRunner;
use crate::adapters::gh_skill::GhSkillCli;
use crate::adapters::npx_skills::NpxSkillsCli;
use crate::model::{Agent, InstallSource, Scope, SkillRecord};
use anyhow::{anyhow, Context, Result};
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AddBackend {
    GhSkill,
    NpxSkills,
}

impl AddBackend {
    pub fn as_str(self) -> &'static str {
        match self {
            AddBackend::GhSkill => "gh skill",
            AddBackend::NpxSkills => "npx skills",
        }
    }
}

#[derive(Debug, Clone)]
pub struct DeletePlan {
    pub skill_name: String,
    pub scope: Scope,
    pub agents: Vec<Agent>,
    pub paths: Vec<std::path::PathBuf>,
    pub source: InstallSource,
    pub shared_warning: Option<String>,
}

pub fn plan_delete(skill: &SkillRecord, agents: &[Agent]) -> DeletePlan {
    let selected: Vec<_> = skill
        .locations
        .iter()
        .filter(|l| agents.contains(&l.agent))
        .cloned()
        .collect();
    let mut paths: Vec<_> = selected.iter().map(|l| l.path.clone()).collect();
    paths.sort();
    paths.dedup();
    let mut shared_warning = None;
    for loc in &selected {
        let candidates = [
            Some(loc.path.as_path()),
            loc.resolved.as_deref(),
        ];
        for path in candidates.into_iter().flatten() {
            let s = path.to_string_lossy();
            if s.contains("/.agents/skills/") {
                shared_warning = Some(format!(
                    "Removing shared store path may affect other agents: {s}"
                ));
                break;
            }
        }
        if shared_warning.is_some() {
            break;
        }
    }
    DeletePlan {
        skill_name: skill.name.clone(),
        scope: skill.scope,
        agents: agents.to_vec(),
        paths,
        source: skill.source,
        shared_warning,
    }
}

pub fn execute_delete(
    runner: &impl CommandRunner,
    plan: &DeletePlan,
    npx_available: bool,
) -> Result<Vec<String>> {
    let mut messages = Vec::new();

    // Remove inventory paths first so the TUI stays responsive even if the
    // subsequent `npx skills remove` is slow.
    for path in &plan.paths {
        match remove_skill_path(path) {
            Ok(()) => messages.push(format!("removed {}", path.display())),
            Err(err) => messages.push(format!("failed {}: {err}", path.display())),
        }
    }

    // For npx-sourced skills, always run `npx skills remove` too so the lockfile
    // / shared store stay consistent (not only when inventory paths are empty).
    if npx_available && plan.source == InstallSource::Npx {
        let cli = NpxSkillsCli { runner };
        if plan.agents.is_empty() {
            messages.push(format!(
                "npx skills remove skipped for {}: no agents selected",
                plan.skill_name
            ));
        } else {
            for agent in &plan.agents {
                match cli.remove(&plan.skill_name, *agent, plan.scope) {
                    Ok(out) => {
                        let detail = out.stdout.trim();
                        if detail.is_empty() {
                            messages.push(format!(
                                "npx skills remove {} @{}",
                                plan.skill_name, agent
                            ));
                        } else {
                            messages.push(format!(
                                "npx skills remove {} @{}: {detail}",
                                plan.skill_name, agent
                            ));
                        }
                    }
                    Err(err) => {
                        messages.push(format!("npx remove failed for {agent}: {err}"));
                    }
                }
            }
        }
    }

    if messages.is_empty() {
        return Err(anyhow!("nothing to delete for {}", plan.skill_name));
    }
    Ok(messages)
}

pub fn remove_skill_path(path: &Path) -> Result<()> {
    let meta = fs::symlink_metadata(path)
        .with_context(|| format!("stat {}", path.display()))?;
    if meta.file_type().is_symlink() {
        fs::remove_file(path).with_context(|| format!("unlink {}", path.display()))?;
    } else if meta.is_dir() {
        fs::remove_dir_all(path).with_context(|| format!("rm -rf {}", path.display()))?;
    } else {
        fs::remove_file(path).with_context(|| format!("rm {}", path.display()))?;
    }
    Ok(())
}

pub fn execute_add(
    runner: &impl CommandRunner,
    backend: AddBackend,
    package_or_repo: &str,
    skill: &str,
    agents: &[Agent],
    scope: Scope,
) -> Result<String> {
    if agents.is_empty() {
        return Err(anyhow!("no agents selected"));
    }
    let mut msgs = Vec::new();
    for &agent in agents {
        let msg = match backend {
            AddBackend::GhSkill => {
                let cli = GhSkillCli { runner };
                let out = cli.install(package_or_repo, skill, agent, scope)?;
                format!(
                    "gh skill install ok ({agent})\n{}\n{}",
                    out.stdout.trim(),
                    out.stderr.trim()
                )
            }
            AddBackend::NpxSkills => {
                let cli = NpxSkillsCli { runner };
                let out = cli.add(package_or_repo, Some(skill), agent, scope)?;
                format!(
                    "npx skills add ok ({agent})\n{}\n{}",
                    out.stdout.trim(),
                    out.stderr.trim()
                )
            }
        };
        msgs.push(msg);
    }
    Ok(msgs.join("\n\n"))
}

#[derive(Debug, Clone)]
pub struct UpdateJob {
    pub name: String,
    pub scope: Scope,
    pub dirs: Vec<PathBuf>,
}

pub fn execute_update(
    runner: &impl CommandRunner,
    backend: AddBackend,
    jobs: &[UpdateJob],
) -> Result<String> {
    match backend {
        AddBackend::GhSkill => execute_update_gh(runner, jobs),
        AddBackend::NpxSkills => execute_update_npx(runner, jobs),
    }
}

fn execute_update_npx(runner: &impl CommandRunner, jobs: &[UpdateJob]) -> Result<String> {
    let cli = NpxSkillsCli { runner };
    let mut msgs = Vec::new();
    for scope in [Scope::User, Scope::Project] {
        let names: Vec<&str> = jobs
            .iter()
            .filter(|j| j.scope == scope)
            .map(|j| j.name.as_str())
            .collect();
        if names.is_empty() {
            continue;
        }
        let out = cli.update(&names, scope)?;
        msgs.push(format!(
            "npx skills update ({scope})\n{}\n{}",
            out.stdout.trim(),
            out.stderr.trim()
        ));
    }
    if msgs.is_empty() {
        return Err(anyhow!("no skills to update via npx"));
    }
    Ok(msgs.join("\n\n"))
}

fn execute_update_gh(runner: &impl CommandRunner, jobs: &[UpdateJob]) -> Result<String> {
    let cli = GhSkillCli { runner };
    let mut msgs = Vec::new();
    for job in jobs {
        let mut attempts: Vec<String> = Vec::new();
        let mut try_dirs: Vec<Option<&Path>> =
            job.dirs.iter().map(|d| Some(d.as_path())).collect();
        if try_dirs.is_empty() {
            try_dirs.push(None);
        }

        let mut done = false;
        for dir in try_dirs {
            match cli.update(&job.name, dir) {
                Ok(out) => {
                    let dir_note = dir
                        .map(|d| format!("\n(dir: {})", d.display()))
                        .unwrap_or_default();
                    let body = format!(
                        "gh skill update {}{dir_note}\n{}\n{}",
                        job.name,
                        out.stdout.trim(),
                        out.stderr.trim()
                    );
                    let missing = body.contains("none of the specified skills are installed");
                    if missing {
                        attempts.push(body);
                        continue;
                    }
                    msgs.push(body);
                    done = true;
                    break;
                }
                Err(err) => {
                    attempts.push(format!(
                        "dir {}: {err}",
                        dir.map(|d| d.display().to_string())
                            .unwrap_or_else(|| "(default)".into())
                    ));
                }
            }
        }
        if !done {
            msgs.push(format!(
                "update {} failed after {} attempt(s):\n{}",
                job.name,
                attempts.len(),
                attempts.join("\n---\n")
            ));
        }
    }
    Ok(msgs.join("\n\n"))
}

/// Best-effort backend guess for the update picker.
pub fn suggested_update_backend(skill: &SkillRecord) -> Option<AddBackend> {
    if skill.source == InstallSource::Gh || skill_has_gh_metadata(skill) {
        return Some(AddBackend::GhSkill);
    }
    if skill.source == InstallSource::Npx {
        return Some(AddBackend::NpxSkills);
    }
    let only_agents = !skill.locations.is_empty()
        && skill.locations.iter().all(|l| {
            let p = l.resolved.as_ref().unwrap_or(&l.path);
            p.to_string_lossy().contains("/.agents/skills")
        });
    if only_agents {
        return Some(AddBackend::NpxSkills);
    }
    None
}

pub fn suggested_update_backend_for(skills: &[SkillRecord]) -> Option<AddBackend> {
    let mut iter = skills.iter().map(suggested_update_backend);
    let first = iter.next()??;
    for next in iter {
        match next {
            Some(b) if b == first => {}
            _ => return None,
        }
    }
    Some(first)
}

fn skill_has_gh_metadata(skill: &SkillRecord) -> bool {
    skill.locations.iter().any(|l| skill_path_has_github_metadata(&l.path))
}

/// Ordered skill-root dirs for `gh skill update --dir`, preferring copies
/// that already carry GitHub metadata in SKILL.md.
///
/// Only locations whose agent is in `agents` are considered.
pub fn prefer_update_dirs(skill: &SkillRecord, agents: &[Agent]) -> Vec<PathBuf> {
    let score = |path: &Path| -> i32 {
        let s = path.to_string_lossy();
        let mut n = if s.contains("/.agents/skills") {
            0
        } else if s.contains("/.cursor/skills")
            || s.contains("/.claude/skills")
            || s.contains("/.codex/skills")
        {
            2
        } else {
            1
        };
        if skill_path_has_github_metadata(path) {
            n += 10;
        }
        n
    };
    let mut scored: Vec<(i32, PathBuf)> = skill
        .locations
        .iter()
        .filter(|l| agents.contains(&l.agent))
        .filter_map(|l| {
            let parent = l.path.parent()?.to_path_buf();
            Some((score(&l.path), parent))
        })
        .collect();
    scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
    let mut out = Vec::new();
    for (_, dir) in scored {
        if !out.contains(&dir) {
            out.push(dir);
        }
    }
    out
}

fn skill_path_has_github_metadata(skill_dir: &Path) -> bool {
    let md = skill_dir.join("SKILL.md");
    let Ok(content) = fs::read_to_string(md) else {
        return false;
    };
    let lower = content.to_lowercase();
    lower.contains("github-repo:")
        || lower.contains("sourceurl:")
        || lower.contains("source_url:")
}

pub fn require_cli(name: &str) -> Result<()> {
    if crate::adapters::command::which_ok(name) {
        Ok(())
    } else {
        Err(anyhow!("{name} not found on PATH"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{InstallKind, InstallSource, SkillLocation, SkillStats};
    use std::path::PathBuf;

    #[test]
    fn plan_delete_warns_on_shared_agents_target() {
        let skill = SkillRecord {
            id: "x".into(),
            name: "x".into(),
            description: String::new(),
            scope: Scope::User,
            agents: vec![Agent::Cursor],
            locations: vec![SkillLocation {
                agent: Agent::Cursor,
                scope: Scope::User,
                path: PathBuf::from("/home/.cursor/skills/x"),
                kind: InstallKind::Symlink,
                resolved: Some(PathBuf::from("/home/.agents/skills/x")),
            }],
            install_kind: InstallKind::Symlink,
            source: InstallSource::Manual,
            source_url: None,
            version: None,
            pinned: false,
            stats: SkillStats::default(),
        };
        let plan = plan_delete(&skill, &[Agent::Cursor]);
        assert!(plan.shared_warning.is_some());
        assert_eq!(plan.source, InstallSource::Manual);
    }

    #[test]
    fn execute_delete_calls_npx_even_when_paths_exist() {
        use crate::adapters::command::{CommandOutput, FakeCommandRunner};

        let tmp = tempfile::tempdir().unwrap();
        let skill_dir = tmp.path().join("find-skills");
        fs::create_dir_all(&skill_dir).unwrap();
        fs::write(skill_dir.join("SKILL.md"), "---\nname: find-skills\n---\n").unwrap();

        let plan = DeletePlan {
            skill_name: "find-skills".into(),
            scope: Scope::User,
            agents: vec![Agent::Cursor, Agent::ClaudeCode],
            paths: vec![skill_dir.clone()],
            source: InstallSource::Npx,
            shared_warning: None,
        };
        let runner = FakeCommandRunner::with_responses(vec![
            CommandOutput {
                status: 0,
                stdout: "ok".into(),
                stderr: String::new(),
            },
            CommandOutput {
                status: 0,
                stdout: "ok".into(),
                stderr: String::new(),
            },
        ]);

        let msgs = execute_delete(&runner, &plan, true).unwrap();
        assert!(msgs.iter().any(|m| m.contains("removed")));
        assert!(!skill_dir.exists());

        let calls = runner.calls();
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0].0, "npx");
        assert!(calls[0].1.contains(&"remove".into()));
        assert!(calls[0].1.contains(&"find-skills".into()));
        assert!(calls[0].1.contains(&"-y".into()));
        assert!(calls[0].1.contains(&"cursor".into()));
        assert!(calls[1].1.contains(&"claude-code".into()));
    }

    #[test]
    fn execute_delete_skips_npx_for_non_npx_source() {
        use crate::adapters::command::{CommandOutput, FakeCommandRunner};

        let tmp = tempfile::tempdir().unwrap();
        let skill_dir = tmp.path().join("manual");
        fs::create_dir_all(&skill_dir).unwrap();
        fs::write(skill_dir.join("SKILL.md"), "---\nname: manual\n---\n").unwrap();

        let plan = DeletePlan {
            skill_name: "manual".into(),
            scope: Scope::User,
            agents: vec![Agent::Cursor],
            paths: vec![skill_dir],
            source: InstallSource::Manual,
            shared_warning: None,
        };
        let runner = FakeCommandRunner::with_responses(vec![CommandOutput {
            status: 0,
            stdout: String::new(),
            stderr: String::new(),
        }]);

        execute_delete(&runner, &plan, true).unwrap();
        assert!(runner.calls().is_empty());
    }

    #[test]
    fn remove_symlink_only() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("target");
        fs::create_dir_all(&target).unwrap();
        fs::write(target.join("SKILL.md"), "---\nname: x\n---\n").unwrap();
        let link = tmp.path().join("link");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        remove_skill_path(&link).unwrap();
        assert!(!link.exists());
        assert!(target.exists());
    }

    #[test]
    fn suggested_backend_prefers_gh_metadata_over_npx_lock_source() {
        let tmp = tempfile::tempdir().unwrap();
        let cursor = tmp.path().join(".cursor/skills/tdd");
        fs::create_dir_all(&cursor).unwrap();
        fs::write(
            cursor.join("SKILL.md"),
            "---\nname: tdd\nmetadata:\n  github-repo: https://github.com/ex/skills\n  github-tree-sha: abc\n---\n",
        )
        .unwrap();
        let skill = SkillRecord {
            id: "tdd".into(),
            name: "tdd".into(),
            description: String::new(),
            scope: Scope::User,
            agents: vec![Agent::Cursor],
            locations: vec![SkillLocation {
                agent: Agent::Cursor,
                scope: Scope::User,
                path: cursor,
                kind: InstallKind::Copy,
                resolved: None,
            }],
            install_kind: InstallKind::Copy,
            source: InstallSource::Npx,
            source_url: Some("https://github.com/mattpocock/skills.git".into()),
            version: None,
            pinned: false,
            stats: SkillStats::default(),
        };
        assert_eq!(
            suggested_update_backend(&skill),
            Some(AddBackend::GhSkill)
        );
    }

    #[test]
    fn prefer_update_dirs_puts_metadata_host_first() {
        let tmp = tempfile::tempdir().unwrap();
        let claude = tmp.path().join(".claude/skills/tdd");
        let cursor = tmp.path().join(".cursor/skills/tdd");
        fs::create_dir_all(&claude).unwrap();
        fs::create_dir_all(&cursor).unwrap();
        fs::write(claude.join("SKILL.md"), "---\nname: tdd\n---\n").unwrap();
        fs::write(
            cursor.join("SKILL.md"),
            "---\nname: tdd\nmetadata:\n  github-repo: https://github.com/ex/skills\n---\n",
        )
        .unwrap();
        let skill = SkillRecord {
            id: "tdd".into(),
            name: "tdd".into(),
            description: String::new(),
            scope: Scope::User,
            agents: vec![Agent::ClaudeCode, Agent::Cursor],
            locations: vec![
                SkillLocation {
                    agent: Agent::ClaudeCode,
                    scope: Scope::User,
                    path: claude,
                    kind: InstallKind::Copy,
                    resolved: None,
                },
                SkillLocation {
                    agent: Agent::Cursor,
                    scope: Scope::User,
                    path: cursor.clone(),
                    kind: InstallKind::Copy,
                    resolved: None,
                },
            ],
            install_kind: InstallKind::Copy,
            source: InstallSource::Gh,
            source_url: Some("https://github.com/ex/skills".into()),
            version: None,
            pinned: false,
            stats: SkillStats::default(),
        };
        let dirs = prefer_update_dirs(&skill, Agent::all());
        assert_eq!(dirs[0], cursor.parent().unwrap());
    }

    #[test]
    fn prefer_update_dirs_filters_by_agent() {
        let tmp = tempfile::tempdir().unwrap();
        let claude = tmp.path().join(".claude/skills/tdd");
        let cursor = tmp.path().join(".cursor/skills/tdd");
        fs::create_dir_all(&claude).unwrap();
        fs::create_dir_all(&cursor).unwrap();
        fs::write(claude.join("SKILL.md"), "---\nname: tdd\n---\n").unwrap();
        fs::write(cursor.join("SKILL.md"), "---\nname: tdd\n---\n").unwrap();
        let skill = SkillRecord {
            id: "tdd".into(),
            name: "tdd".into(),
            description: String::new(),
            scope: Scope::User,
            agents: vec![Agent::ClaudeCode, Agent::Cursor],
            locations: vec![
                SkillLocation {
                    agent: Agent::ClaudeCode,
                    scope: Scope::User,
                    path: claude.clone(),
                    kind: InstallKind::Copy,
                    resolved: None,
                },
                SkillLocation {
                    agent: Agent::Cursor,
                    scope: Scope::User,
                    path: cursor,
                    kind: InstallKind::Copy,
                    resolved: None,
                },
            ],
            install_kind: InstallKind::Copy,
            source: InstallSource::Gh,
            source_url: None,
            version: None,
            pinned: false,
            stats: SkillStats::default(),
        };
        let dirs = prefer_update_dirs(&skill, &[Agent::ClaudeCode]);
        assert_eq!(dirs, vec![claude.parent().unwrap().to_path_buf()]);
    }
}