skillctl 0.1.5

CLI to manage your personal agent skills library across projects
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
use std::fs;
use std::path::PathBuf;

use anyhow::{Context as _, Result};
use cliclack::{input, select};

use crate::prompt::multiselect;
use serde_json::{Value, json};
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;

use crate::cli::{AddArgs, OnConflict};
use crate::commands::shared::{matches_tags, short_hint};
use crate::config;
use crate::context::Context;
use crate::error::AppError;
use crate::fs_util;
use crate::git;
use crate::lock;
use crate::project_config::{self, InstalledSkill};
use crate::skill::{self, Skill};
use crate::ui;

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
enum DestChoice {
    Existing(PathBuf),
    Preset { label: &'static str, path: PathBuf },
    Custom,
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
enum ConflictAction {
    Overwrite,
    Skip,
    Abort,
}

impl From<OnConflict> for ConflictAction {
    fn from(v: OnConflict) -> Self {
        match v {
            OnConflict::Overwrite => Self::Overwrite,
            OnConflict::Skip => Self::Skip,
            OnConflict::Abort => Self::Abort,
        }
    }
}

pub fn run(args: AddArgs, ctx: &Context) -> Result<()> {
    ui::intro(ctx, "skillctl add")?;

    let cfg = config::load()?;
    let library = cfg.library.ok_or_else(|| {
        AppError::Config("no library configured — run `skillctl init<github-url>` first".into())
    })?;

    let library_root =
        config::library_cache_path(&library.url).map_err(|e| AppError::Config(e.to_string()))?;
    if !library_root.exists() {
        return Err(AppError::Config(format!(
            "library cache not found at {} — run `skillctl init{}` again",
            library_root.display(),
            library.url
        ))
        .into());
    }
    // Serialise all library-cache mutations across concurrent skillctl
    // processes. Released on function return.
    let _cache_lock = lock::acquire_exclusive(&library_root, "library cache")?;

    if let Err(e) = git::fetch_and_fast_forward(&library_root) {
        ui::log_warning(
            ctx,
            format!("could not refresh library cache ({e}); using cached version"),
        )?;
    }

    let skills = skill::discover(&library_root, false)?;
    if skills.is_empty() {
        ui::outro(ctx, format!("no skills found in {}", library.url))?;
        emit_json(ctx, None, &[]);
        return Ok(());
    }

    let selected = select_skills(&args, ctx, &skills)?;
    if selected.is_empty() {
        ui::outro(ctx, "no skills selected")?;
        emit_json(ctx, None, &[]);
        return Ok(());
    }

    let cwd = std::env::current_dir().context("reading current directory")?;
    // Serialise concurrent skillctl runs on this project's .skills.toml.
    let _project_lock = lock::acquire_exclusive(&cwd, "project")?;
    let dest_root = resolve_destination(&args, ctx, &cwd)?;
    let conflict_policy: Option<ConflictAction> = args.on_conflict.map(Into::into);

    let source_sha = git::head_sha(&library_root).map_err(|e| AppError::Git(e.to_string()))?;
    let installed_at = OffsetDateTime::now_utc()
        .format(&Rfc3339)
        .context("formatting installation timestamp")?;

    let mut project_cfg = project_config::load(&cwd)?;
    let mut results: Vec<Value> = Vec::new();
    let mut aborted = false;

    for skill in selected {
        let folder_name = skill.path.file_name().ok_or_else(|| {
            AppError::Config(format!(
                "skill has no folder name: {}",
                skill.path.display()
            ))
        })?;
        let dest = dest_root.join(folder_name);

        if dest.exists() {
            let action = resolve_conflict(ctx, &dest, conflict_policy.clone())?;
            match action {
                ConflictAction::Overwrite => {
                    fs::remove_dir_all(&dest)
                        .with_context(|| format!("removing {}", dest.display()))?;
                }
                ConflictAction::Skip => {
                    ui::log_info(ctx, format!("skipped {}", skill.name))?;
                    results.push(json!({
                        "name": skill.name,
                        "status": "skipped",
                        "reason": format!("destination {} already exists", dest.display()),
                    }));
                    continue;
                }
                ConflictAction::Abort => {
                    project_config::save(&cwd, &project_cfg)?;
                    ui::outro_cancel(ctx, "aborted")?;
                    results.push(json!({
                        "name": skill.name,
                        "status": "aborted",
                        "reason": format!("destination {} already exists", dest.display()),
                    }));
                    aborted = true;
                    break;
                }
            }
        }

        fs_util::copy_dir_all(&skill.path, &dest)?;
        let source_path = skill
            .path
            .strip_prefix(&library_root)
            .with_context(|| {
                format!(
                    "computing path of {} relative to library at {}",
                    skill.path.display(),
                    library_root.display()
                )
            })?
            .to_path_buf();
        let destination_rel = fs_util::relative_to_or_self(&dest, &cwd);
        project_cfg.installed.push(InstalledSkill {
            name: skill.name.clone(),
            source_path,
            source_sha: source_sha.clone(),
            destination: destination_rel.clone(),
            installed_at: installed_at.clone(),
        });
        ui::log_success(ctx, format!("{}{}", skill.name, dest.display()))?;
        results.push(json!({
            "name": skill.name,
            "status": "installed",
            "path": destination_rel.display().to_string(),
            "source_sha": source_sha,
        }));
    }

    project_config::save(&cwd, &project_cfg)?;

    if !aborted {
        ui::outro(ctx, summary_text(&results))?;
    }
    emit_json(ctx, Some(&dest_root), &results);
    Ok(())
}

fn emit_json(ctx: &Context, destination: Option<&PathBuf>, results: &[Value]) {
    if !ctx.json {
        return;
    }
    let installed = results
        .iter()
        .filter(|r| r["status"] == "installed")
        .count();
    let skipped = results.iter().filter(|r| r["status"] == "skipped").count();
    let aborted = results.iter().filter(|r| r["status"] == "aborted").count();
    let out = json!({
        "command": "add",
        "destination": destination.map(|d| d.display().to_string()),
        "results": results,
        "summary": {
            "installed": installed,
            "skipped": skipped,
            "aborted": aborted,
        },
    });
    println!("{out}");
}

fn summary_text(results: &[Value]) -> String {
    let installed = results
        .iter()
        .filter(|r| r["status"] == "installed")
        .count();
    let skipped = results.iter().filter(|r| r["status"] == "skipped").count();
    let aborted = results.iter().filter(|r| r["status"] == "aborted").count();
    if aborted > 0 {
        format!("{installed} installed, {skipped} skipped, {aborted} aborted")
    } else if skipped > 0 {
        format!("{installed} installed, {skipped} skipped")
    } else {
        format!("{installed} skill(s) installed")
    }
}

fn select_skills(args: &AddArgs, ctx: &Context, skills: &[Skill]) -> Result<Vec<Skill>> {
    if args.all {
        return Ok(skills.to_vec());
    }
    if !args.skills.is_empty() {
        let mut chosen = Vec::with_capacity(args.skills.len());
        for name in &args.skills {
            let skill = skills.iter().find(|s| s.name == *name).ok_or_else(|| {
                AppError::Config(format!("no skill named `{name}` in the library"))
            })?;
            chosen.push(skill.clone());
        }
        return Ok(chosen);
    }
    if !args.tags.is_empty() {
        let matched: Vec<Skill> = skills
            .iter()
            .filter(|s| matches_tags(&s.tags, &args.tags, args.all_tags))
            .cloned()
            .collect();
        if matched.is_empty() {
            return Err(AppError::Config(format!(
                "no skills match the requested tag(s): {}",
                args.tags.join(", ")
            ))
            .into());
        }
        if !ctx.interactive {
            return Ok(matched);
        }
        let mut prompt = multiselect("Skills to install (tag-filtered)").required(true);
        for s in &matched {
            let hint = s.description.as_deref().map(short_hint).unwrap_or_default();
            prompt = prompt.item(s.clone(), &s.name, hint);
        }
        return prompt.interact();
    }
    if !ctx.interactive {
        return Err(AppError::Config(
            "no skills selected — pass --skill <name> (repeatable), --tag <name>, or --all".into(),
        )
        .into());
    }
    let mut prompt = multiselect("Skills to install").required(true);
    for s in skills {
        let hint = s.description.as_deref().map(short_hint).unwrap_or_default();
        prompt = prompt.item(s.clone(), &s.name, hint);
    }
    prompt.interact()
}

fn resolve_destination(args: &AddArgs, ctx: &Context, cwd: &std::path::Path) -> Result<PathBuf> {
    if let Some(dest) = &args.dest {
        // Reject parent traversal unconditionally — there is no legitimate
        // workflow that needs `..` in `--dest`. Reject absolute paths in
        // non-interactive mode (agent-mode threat model: flag values may be
        // attacker-supplied via the agent's prompt). In interactive mode the
        // operator is typing the value themselves, so absolute is allowed.
        for component in dest.components() {
            if matches!(component, std::path::Component::ParentDir) {
                return Err(AppError::Config(format!(
                    "invalid --dest `{}`: parent traversal (`..`) is not allowed",
                    dest.display()
                ))
                .into());
            }
        }
        if dest.is_absolute() && !ctx.interactive {
            return Err(AppError::Config(format!(
                "invalid --dest `{}`: absolute paths are not allowed in non-interactive mode (the operator's flag values may be agent-supplied; use a path relative to the current directory)",
                dest.display()
            ))
            .into());
        }
        return Ok(dest.clone());
    }
    if !ctx.interactive {
        return Err(AppError::Config("no install destination — pass --dest <path>".into()).into());
    }
    let existing = skill::find_skills_folders(cwd)?
        .into_iter()
        .map(fs_util::strip_dot_prefix)
        .collect();
    pick_destination_interactive(existing)
}

fn resolve_conflict(
    ctx: &Context,
    dest: &std::path::Path,
    policy: Option<ConflictAction>,
) -> Result<ConflictAction> {
    if let Some(policy) = policy {
        return Ok(policy);
    }
    if !ctx.interactive {
        return Err(AppError::Conflict(format!(
            "destination `{}` already exists — pass --on-conflict overwrite|skip|abort",
            dest.display()
        ))
        .into());
    }
    Ok(select(format!(
        "`{}` already exists — what do you want to do?",
        dest.display()
    ))
    .item(
        ConflictAction::Overwrite,
        "Overwrite",
        "replace the existing folder",
    )
    .item(
        ConflictAction::Skip,
        "Skip",
        "leave it and don't record this skill",
    )
    .item(
        ConflictAction::Abort,
        "Abort",
        "stop now and save what's been installed so far",
    )
    .interact()?)
}

fn pick_destination_interactive(existing: Vec<PathBuf>) -> Result<PathBuf> {
    let mut prompt = select("Install destination");

    if existing.is_empty() {
        prompt = prompt
            .item(
                DestChoice::Preset {
                    label: "claude",
                    path: PathBuf::from(".claude/skills"),
                },
                "claude",
                ".claude/skills",
            )
            .item(
                DestChoice::Preset {
                    label: "codex",
                    path: PathBuf::from(".codex/skills"),
                },
                "codex",
                ".codex/skills",
            )
            .item(
                DestChoice::Preset {
                    label: "cursor",
                    path: PathBuf::from(".cursor/skills"),
                },
                "cursor",
                ".cursor/skills",
            )
            .item(
                DestChoice::Preset {
                    label: "agents",
                    path: PathBuf::from(".agents/skills"),
                },
                "agents",
                ".agents/skills",
            );
    } else {
        for p in existing {
            let display = p.display().to_string();
            prompt = prompt.item(DestChoice::Existing(p), display, "");
        }
    }
    prompt = prompt.item(DestChoice::Custom, "Custom path…", "type your own");

    let answer = prompt.interact()?;
    match answer {
        DestChoice::Existing(p) => Ok(p),
        DestChoice::Preset { path, .. } => Ok(path),
        DestChoice::Custom => {
            let typed: String = input("Path")
                .placeholder(".claude/skills")
                .validate(|s: &String| {
                    if s.trim().is_empty() {
                        Err("path cannot be empty")
                    } else {
                        Ok(())
                    }
                })
                .interact()?;
            Ok(PathBuf::from(typed.trim()))
        }
    }
}