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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use crate::error::AppError;
use crate::path_safety::validate_relative_subpath;
use crate::sanitize::validate_identifier;

const FILENAME: &str = ".skills.toml";

/// Hard cap on the number of `[[installed]]` entries we will load from a
/// `.skills.toml`. A malicious PR could otherwise bury 1M entries that each
/// trigger a `safe_join` + git fetch path, OOM'ing the diff classifier.
/// 256 is comfortably above any realistic library size.
const MAX_INSTALLED_ENTRIES: usize = 256;

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectConfig {
    #[serde(default)]
    pub installed: Vec<InstalledSkill>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InstalledSkill {
    pub name: String,
    pub source_path: PathBuf,
    pub source_sha: String,
    pub destination: PathBuf,
    pub installed_at: String,
}

impl InstalledSkill {
    /// Reject entries whose `source_path` or `destination` could escape the
    /// library/project root (absolute paths, `..` traversal).
    ///
    /// `.skills.toml` is committed to projects and exchanged via PR; without
    /// this check a single malicious PR could weaponise `pull`/`push` into
    /// deleting arbitrary directories on a maintainer's machine, or read
    /// outside the library cache on the library side.
    pub fn validate(&self) -> Result<(), AppError> {
        // `name` is single-line and ends up in commit subjects and terminal
        // output — strict identifier check.
        validate_identifier("name in .skills.toml", &self.name)?;

        // `source_sha` is later passed as a positional refspec to `git ls-tree
        // <refspec> -- <path>` (which sits before `--` in the argv). Without
        // validation, a value starting with `-` becomes a git flag, corrupting
        // the diff classifier and the downstream `pull`/`push` destructive
        // choices. Lock it down to hex (sha1: 40 chars, sha256: 64 chars).
        if !is_hex_sha(&self.source_sha) {
            return Err(AppError::Config(format!(
                "invalid source_sha for skill `{}` in .skills.toml: expected 40-64 hex characters, got `{}`",
                self.name, self.source_sha
            )));
        }

        validate_relative_subpath(&self.source_path).map_err(|e| {
            AppError::Config(format!(
                "invalid source_path for skill `{}` in .skills.toml: {e}",
                self.name
            ))
        })?;
        validate_relative_subpath(&self.destination).map_err(|e| {
            AppError::Config(format!(
                "invalid destination for skill `{}` in .skills.toml: {e}",
                self.name
            ))
        })?;
        Ok(())
    }
}

fn is_hex_sha(s: &str) -> bool {
    let len = s.len();
    (40..=64).contains(&len)
        && s.bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b) || (b'A'..=b'F').contains(&b))
}

pub fn path(project_root: &Path) -> PathBuf {
    project_root.join(FILENAME)
}

pub fn load(project_root: &Path) -> Result<ProjectConfig> {
    let p = path(project_root);
    if !p.exists() {
        return Ok(ProjectConfig::default());
    }
    let raw = fs::read_to_string(&p).with_context(|| format!("reading {}", p.display()))?;
    let cfg: ProjectConfig =
        toml::from_str(&raw).with_context(|| format!("parsing {}", p.display()))?;
    if cfg.installed.len() > MAX_INSTALLED_ENTRIES {
        return Err(AppError::Config(format!(
            "{} has {} `[[installed]]` entries (cap is {}); refusing to load",
            p.display(),
            cfg.installed.len(),
            MAX_INSTALLED_ENTRIES
        ))
        .into());
    }
    // Per-entry path + name + sha validation.
    for installed in &cfg.installed {
        installed.validate()?;
    }
    // Duplicate detection: two entries with the same `name` or same
    // `destination` would make every command ambiguous (which one wins?).
    // Better to refuse loading and let the operator de-dup by hand than to
    // silently keep one and drop the other.
    for i in 0..cfg.installed.len() {
        for j in (i + 1)..cfg.installed.len() {
            if cfg.installed[i].name == cfg.installed[j].name {
                return Err(AppError::Config(format!(
                    "{} has duplicate `[[installed]]` entries with name `{}`; remove the older one",
                    p.display(),
                    cfg.installed[i].name
                ))
                .into());
            }
            if cfg.installed[i].destination == cfg.installed[j].destination {
                return Err(AppError::Config(format!(
                    "{} has duplicate `[[installed]]` entries with destination `{}`; remove the older one",
                    p.display(),
                    cfg.installed[i].destination.display()
                ))
                .into());
            }
        }
    }
    Ok(cfg)
}

/// Atomically write `.skills.toml`. We write the new content to a sibling
/// temp file, then `fs::rename` it over the target — a crash mid-write only
/// leaves the temp file on disk (cleaned up on the next failure path); the
/// live `.skills.toml` is never truncated.
pub fn save(project_root: &Path, cfg: &ProjectConfig) -> Result<()> {
    let p = path(project_root);
    let raw = toml::to_string_pretty(cfg).context("serializing project config")?;

    let pid = std::process::id();
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let tmp = p.with_file_name(format!(".skills.toml.tmp.{pid}.{nanos}"));

    if let Err(e) = fs::write(&tmp, &raw) {
        return Err(e).with_context(|| format!("writing {}", tmp.display()));
    }
    if let Err(e) = fs::rename(&tmp, &p) {
        let _ = fs::remove_file(&tmp);
        return Err(e)
            .with_context(|| format!("atomic rename {} -> {}", tmp.display(), p.display()));
    }
    Ok(())
}

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

    const VALID_SHA: &str = "0123456789abcdef0123456789abcdef01234567";

    fn make_skill(name: &str, source_path: &str, destination: &str) -> InstalledSkill {
        InstalledSkill {
            name: name.to_string(),
            source_path: PathBuf::from(source_path),
            source_sha: VALID_SHA.to_string(),
            destination: PathBuf::from(destination),
            installed_at: "2026-05-20T00:00:00Z".to_string(),
        }
    }

    #[test]
    fn validate_accepts_safe_relative_paths() {
        let s = make_skill("foo", "skills/foo", ".claude/skills/foo");
        assert!(s.validate().is_ok());
    }

    #[test]
    fn validate_rejects_absolute_destination() {
        let s = make_skill("evil", "skills/foo", "/home/seb/.ssh");
        let err = s.validate().unwrap_err().to_string();
        assert!(err.contains("destination"));
        assert!(err.contains("absolute"));
    }

    #[test]
    fn validate_rejects_parent_traversal_destination() {
        let s = make_skill("evil", "skills/foo", "../../../etc");
        let err = s.validate().unwrap_err().to_string();
        assert!(err.contains("destination"));
        assert!(err.contains(".."));
    }

    #[test]
    fn validate_rejects_absolute_source_path() {
        let s = make_skill("evil", "/home/seb/.aws", ".claude/skills/foo");
        let err = s.validate().unwrap_err().to_string();
        assert!(err.contains("source_path"));
    }

    #[test]
    fn validate_rejects_parent_traversal_source_path() {
        let s = make_skill("evil", "../../../etc", ".claude/skills/foo");
        let err = s.validate().unwrap_err().to_string();
        assert!(err.contains("source_path"));
        assert!(err.contains(".."));
    }

    #[test]
    fn load_rejects_malicious_skills_toml_destination() {
        let work = TempDir::new().unwrap();
        let raw = r#"
[[installed]]
name = "evil"
source_path = "skills/evil"
source_sha = "0123456789abcdef0123456789abcdef01234567"
destination = "/home/seb/.ssh"
installed_at = "2026-05-20T00:00:00Z"
"#;
        fs::write(work.path().join(".skills.toml"), raw).unwrap();
        let err = load(work.path()).unwrap_err().to_string();
        assert!(
            err.contains("destination") && err.contains("absolute"),
            "expected a path-safety error, got: {err}"
        );
    }

    #[test]
    fn load_rejects_malicious_skills_toml_parent_traversal() {
        let work = TempDir::new().unwrap();
        let raw = r#"
[[installed]]
name = "evil"
source_path = "../../../etc"
source_sha = "0123456789abcdef0123456789abcdef01234567"
destination = ".claude/skills/evil"
installed_at = "2026-05-20T00:00:00Z"
"#;
        fs::write(work.path().join(".skills.toml"), raw).unwrap();
        let err = load(work.path()).unwrap_err().to_string();
        assert!(
            err.contains("source_path") && err.contains(".."),
            "expected a path-safety error, got: {err}"
        );
    }

    #[test]
    fn validate_rejects_non_hex_source_sha() {
        let mut s = make_skill("foo", "skills/foo", ".claude/skills/foo");
        s.source_sha = "--name-only".to_string();
        let err = s.validate().unwrap_err().to_string();
        assert!(err.contains("source_sha"));
        assert!(err.contains("hex"));
    }

    #[test]
    fn validate_rejects_too_short_source_sha() {
        let mut s = make_skill("foo", "skills/foo", ".claude/skills/foo");
        s.source_sha = "deadbeef".to_string();
        assert!(s.validate().is_err());
    }

    #[test]
    fn validate_rejects_too_long_source_sha() {
        let mut s = make_skill("foo", "skills/foo", ".claude/skills/foo");
        s.source_sha = "a".repeat(65);
        assert!(s.validate().is_err());
    }

    #[test]
    fn validate_accepts_sha1_and_sha256() {
        let mut s = make_skill("foo", "skills/foo", ".claude/skills/foo");
        s.source_sha = "a".repeat(40); // sha1
        assert!(s.validate().is_ok());
        s.source_sha = "a".repeat(64); // sha256
        assert!(s.validate().is_ok());
    }

    #[test]
    fn validate_rejects_newline_in_name() {
        let s = make_skill(
            "foo\nCo-Authored-By: evil",
            "skills/foo",
            ".claude/skills/foo",
        );
        let err = s.validate().unwrap_err().to_string();
        assert!(err.contains("name"));
        assert!(err.contains("control character"));
    }

    #[test]
    fn validate_rejects_ansi_in_name() {
        let s = make_skill("\x1b[31mEVIL\x1b[0m", "skills/foo", ".claude/skills/foo");
        assert!(s.validate().is_err());
    }

    #[test]
    fn load_rejects_unknown_top_level_key() {
        let work = TempDir::new().unwrap();
        let raw = r#"
mystery_field = "from the future"

[[installed]]
name = "foo"
source_path = "skills/foo"
source_sha = "0123456789abcdef0123456789abcdef01234567"
destination = ".claude/skills/foo"
installed_at = "2026-05-22T00:00:00Z"
"#;
        fs::write(work.path().join(".skills.toml"), raw).unwrap();
        // anyhow's Display only shows the outermost context by default;
        // `{:#}` walks the cause chain so the underlying serde error
        // ("unknown field `mystery_field`") surfaces.
        let err = format!("{:#}", load(work.path()).unwrap_err());
        assert!(
            err.contains("unknown field") || err.contains("mystery_field"),
            "expected an unknown-field error, got: {err}"
        );
    }

    #[test]
    fn load_rejects_unknown_installed_key() {
        let work = TempDir::new().unwrap();
        let raw = r#"
[[installed]]
name = "foo"
source_path = "skills/foo"
source_sha = "0123456789abcdef0123456789abcdef01234567"
destination = ".claude/skills/foo"
installed_at = "2026-05-22T00:00:00Z"
sneaky = true
"#;
        fs::write(work.path().join(".skills.toml"), raw).unwrap();
        let err = format!("{:#}", load(work.path()).unwrap_err());
        assert!(
            err.contains("unknown field") || err.contains("sneaky"),
            "expected an unknown-field error, got: {err}"
        );
    }

    #[test]
    fn load_rejects_duplicate_name() {
        let work = TempDir::new().unwrap();
        let raw = r#"
[[installed]]
name = "foo"
source_path = "skills/foo"
source_sha = "0123456789abcdef0123456789abcdef01234567"
destination = ".claude/skills/foo"
installed_at = "2026-05-22T00:00:00Z"

[[installed]]
name = "foo"
source_path = "skills/foo2"
source_sha = "0123456789abcdef0123456789abcdef01234567"
destination = ".claude/skills/foo-alt"
installed_at = "2026-05-22T00:00:00Z"
"#;
        fs::write(work.path().join(".skills.toml"), raw).unwrap();
        let err = load(work.path()).unwrap_err().to_string();
        assert!(
            err.contains("duplicate") && err.contains("foo"),
            "expected duplicate error, got: {err}"
        );
    }

    #[test]
    fn load_rejects_duplicate_destination() {
        let work = TempDir::new().unwrap();
        let raw = r#"
[[installed]]
name = "foo"
source_path = "skills/foo"
source_sha = "0123456789abcdef0123456789abcdef01234567"
destination = ".claude/skills/shared"
installed_at = "2026-05-22T00:00:00Z"

[[installed]]
name = "bar"
source_path = "skills/bar"
source_sha = "0123456789abcdef0123456789abcdef01234567"
destination = ".claude/skills/shared"
installed_at = "2026-05-22T00:00:00Z"
"#;
        fs::write(work.path().join(".skills.toml"), raw).unwrap();
        let err = load(work.path()).unwrap_err().to_string();
        assert!(
            err.contains("duplicate") && err.contains("destination"),
            "expected duplicate destination error, got: {err}"
        );
    }

    #[test]
    fn load_rejects_too_many_entries() {
        let work = TempDir::new().unwrap();
        let mut raw = String::new();
        for i in 0..(MAX_INSTALLED_ENTRIES + 1) {
            raw.push_str(&format!(
                "[[installed]]\nname = \"s{i}\"\nsource_path = \"skills/s{i}\"\nsource_sha = \"0123456789abcdef0123456789abcdef01234567\"\ndestination = \".claude/skills/s{i}\"\ninstalled_at = \"2026-05-22T00:00:00Z\"\n\n"
            ));
        }
        fs::write(work.path().join(".skills.toml"), &raw).unwrap();
        let err = load(work.path()).unwrap_err().to_string();
        assert!(err.contains("cap"), "expected entry-cap error, got: {err}");
    }

    #[test]
    fn load_accepts_well_formed_skills_toml() {
        let work = TempDir::new().unwrap();
        let raw = r#"
[[installed]]
name = "foo"
source_path = "skills/foo"
source_sha = "0123456789abcdef0123456789abcdef01234567"
destination = ".claude/skills/foo"
installed_at = "2026-05-20T00:00:00Z"
"#;
        fs::write(work.path().join(".skills.toml"), raw).unwrap();
        let cfg = load(work.path()).unwrap();
        assert_eq!(cfg.installed.len(), 1);
        assert_eq!(cfg.installed[0].name, "foo");
    }
}