craftbag 0.3.0

Discover and load Agent Skills (SKILL.md) for CLI and MCP hosts
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
//! Shared SKILL.md open / parse used by the walk and extra-path.

use std::io::Read;
use std::path::{Path, PathBuf};

use crate::parse::{parse_skill, peek_frontmatter_name, skill_name_matches_directory};
use crate::skill::{SKILL_MD_MAX_BYTES, Skill};
use crate::skip::{SkillSkip, SkipKind};
use crate::source::SkillSource;

use super::DiscoveryOptions;
use super::path::{IgnorePrefix, path_is_ignored, stays_under};

#[cfg(test)]
thread_local! {
    static READ_SKILL_MD_PATHS: std::cell::RefCell<Vec<PathBuf>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

#[cfg(test)]
pub(super) fn take_read_skill_md_paths() -> Vec<PathBuf> {
    READ_SKILL_MD_PATHS.with(|c| std::mem::take(&mut *c.borrow_mut()))
}

pub(super) fn skip_if_dir_escapes(dir: &Path, confine: &Path, skips: &mut Vec<SkillSkip>) -> bool {
    if dir.exists() && !stays_under(dir, confine) {
        skips.push(SkillSkip {
            path: dir.to_path_buf(),
            name: None,
            kind: SkipKind::Unreadable,
            detail: "skills directory symlink escapes walk root".to_owned(),
            winner_path: None,
            host_token: None,
        });
        return true;
    }
    false
}

pub(super) struct DirLoad<'a> {
    source: &'a SkillSource,
    ignore: &'a [IgnorePrefix],
    opts: &'a DiscoveryOptions,
    denylist: &'a [&'a str],
}

pub(super) fn dir_load<'a>(
    source: &'a SkillSource,
    ignore: &'a [IgnorePrefix],
    opts: &'a DiscoveryOptions,
    denylist: &'a [&'a str],
) -> DirLoad<'a> {
    DirLoad {
        source,
        ignore,
        opts,
        denylist,
    }
}

/// Symlink whose target is gone. `Path::is_dir` is false, so a broken
/// package link would otherwise look like an ignored file.
fn dangling_symlink(path: &Path) -> bool {
    let Ok(meta) = std::fs::symlink_metadata(path) else {
        return false;
    };
    if !meta.file_type().is_symlink() {
        return false;
    }
    match std::fs::metadata(path) {
        Err(err) => err.kind() == std::io::ErrorKind::NotFound,
        Ok(_) => false,
    }
}

/// Broken link text for a skip. `canonicalize` fails on a missing
/// target, and a stay-under check would call that an escape.
pub(super) fn dangling_symlink_detail(path: &Path) -> Option<String> {
    if !dangling_symlink(path) {
        return None;
    }
    Some(match std::fs::read_link(path) {
        Ok(target) => format!("dangling symlink: {}", target.display()),
        Err(_) => "dangling symlink".to_owned(),
    })
}

/// Link cycle. `canonicalize` fails, and a stay-under check would call
/// that an escape. The target never resolves, so nothing is read.
fn symlink_loop_detail(path: &Path) -> Option<String> {
    let Ok(meta) = std::fs::symlink_metadata(path) else {
        return None;
    };
    if !meta.file_type().is_symlink() {
        return None;
    }
    match std::fs::metadata(path) {
        Err(err) if is_symlink_loop(&err) => Some(loop_detail(path)),
        _ => None,
    }
}

/// `ErrorKind::FilesystemLoop` needs `io_error_more`, unstable on the
/// 1.85 MSRV. The running kind still debugs as that name.
fn is_symlink_loop(err: &std::io::Error) -> bool {
    format!("{:?}", err.kind()) == "FilesystemLoop"
}

fn loop_detail(path: &Path) -> String {
    match std::fs::read_link(path) {
        Ok(target) => format!("symbolic link loop: {}", target.display()),
        Err(_) => "symbolic link loop".to_owned(),
    }
}

/// Missing target or a link cycle. Both fail `canonicalize`. Neither is
/// an outside file.
pub(super) fn unresolved_symlink_detail(path: &Path) -> Option<String> {
    dangling_symlink_detail(path).or_else(|| symlink_loop_detail(path))
}

pub(super) fn load_skills_from_dir(
    dir: &Path,
    load: &DirLoad<'_>,
    skip: &[&Path],
    skills: &mut Vec<Skill>,
    skips: &mut Vec<SkillSkip>,
) {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        // Implicit `.agents` / vendor joins call this for a path they
        // did not stat. A missing directory and a file in its place are
        // both "no skills tree". Host-asked paths report those earlier.
        // Permission denied and other read errors still skip below.
        Err(e)
            if e.kind() == std::io::ErrorKind::NotFound
                || e.kind() == std::io::ErrorKind::NotADirectory =>
        {
            return;
        }
        Err(e) => {
            skips.push(SkillSkip {
                path: dir.to_path_buf(),
                name: None,
                kind: SkipKind::Unreadable,
                detail: e.to_string(),
                winner_path: None,
                host_token: None,
            });
            return;
        }
    };

    let mut entries: Vec<_> = entries.filter_map(Result::ok).collect();
    entries.sort_by_key(|a| a.file_name());
    for entry in entries {
        let path = entry.path();
        if skip.iter().any(|s| path == *s) {
            continue;
        }
        if !path.is_dir() {
            if !is_skill_md_filename(&path) && !path_is_ignored(&path, load.ignore) {
                // A directory symlink cycle is not a directory, so it
                // would otherwise be ignored like a stray file.
                if let Some(detail) = unresolved_symlink_detail(&path) {
                    let name = path.file_name().and_then(|n| n.to_str()).map(str::to_owned);
                    skips.push(SkillSkip {
                        path,
                        name,
                        kind: SkipKind::Unreadable,
                        detail,
                        winner_path: None,
                        host_token: None,
                    });
                    continue;
                }
            }
            if path
                .file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|n| n == "SKILL.md" || n == "skill.md")
                && !path_is_ignored(&path, load.ignore)
            {
                if let Some(detail) = unresolved_symlink_detail(&path) {
                    skips.push(SkillSkip {
                        path,
                        name: None,
                        kind: SkipKind::Unreadable,
                        detail,
                        winner_path: None,
                        host_token: None,
                    });
                    continue;
                }
                if !stays_under(&path, dir) {
                    skips.push(SkillSkip {
                        path,
                        name: None,
                        kind: SkipKind::Unreadable,
                        detail: "SKILL.md symlink escapes walk root".to_owned(),
                        winner_path: None,
                        host_token: None,
                    });
                    continue;
                }
                match read_skill_md(&path) {
                    Ok(content) => {
                        let name = peek_frontmatter_name(&content);
                        skips.push(SkillSkip {
                            path,
                            name,
                            kind: SkipKind::RootFile,
                            detail: "put the file in a named subdirectory.".to_owned(),
                            winner_path: None,
                            host_token: None,
                        });
                    }
                    Err(e) => {
                        skips.push(SkillSkip {
                            path,
                            name: None,
                            kind: SkipKind::Unreadable,
                            detail: e,
                            winner_path: None,
                            host_token: None,
                        });
                    }
                }
            }
            continue;
        }

        let skill_file = match lookup_package_skill_md(&path) {
            PackageSkillMd::Found(skill_file) => skill_file,
            PackageSkillMd::Missing => continue,
            // A searchable directory with no SKILL.md is not a package.
            // Permission denied on the child name is a package we cannot
            // read. Treating that as "no file" drops the skill with no skip.
            PackageSkillMd::Unreadable(detail) => {
                skips.push(SkillSkip {
                    path,
                    name: None,
                    kind: SkipKind::Unreadable,
                    detail,
                    winner_path: None,
                    host_token: None,
                });
                continue;
            }
        };
        if !stays_under(&path, dir) {
            skips.push(SkillSkip {
                path: skill_file,
                name: None,
                kind: SkipKind::Unreadable,
                detail: "skill package symlink escapes walk root".to_owned(),
                winner_path: None,
                host_token: None,
            });
            continue;
        }
        if skip_if_skill_md_escapes_package(&skill_file, skips) {
            continue;
        }
        try_load_skill_file(
            &skill_file,
            load.source,
            load.ignore,
            load.opts,
            load.denylist,
            skills,
            skips,
        );
    }
}

pub(super) fn skip_if_skill_md_escapes_package(
    skill_file: &Path,
    skips: &mut Vec<SkillSkip>,
) -> bool {
    if let Some(detail) = unresolved_symlink_detail(skill_file) {
        skips.push(SkillSkip {
            path: skill_file.to_path_buf(),
            name: None,
            kind: SkipKind::Unreadable,
            detail,
            winner_path: None,
            host_token: None,
        });
        return true;
    }
    if skill_md_stays_in_package(skill_file) {
        return false;
    }
    skips.push(SkillSkip {
        path: skill_file.to_path_buf(),
        name: None,
        kind: SkipKind::Unreadable,
        detail: "SKILL.md symlink escapes package root".to_owned(),
        winner_path: None,
        host_token: None,
    });
    true
}

pub(super) fn try_load_skill_file(
    skill_file: &Path,
    source: &SkillSource,
    ignore: &[IgnorePrefix],
    opts: &DiscoveryOptions,
    denylist: &[&str],
    skills: &mut Vec<Skill>,
    skips: &mut Vec<SkillSkip>,
) {
    if path_is_ignored(skill_file, ignore) {
        return;
    }

    let content = match read_skill_md(skill_file) {
        Ok(c) => c,
        Err(e) => {
            skips.push(SkillSkip {
                path: skill_file.to_path_buf(),
                name: None,
                kind: SkipKind::Unreadable,
                detail: e,
                winner_path: None,
                host_token: None,
            });
            return;
        }
    };
    finish_load_skill_file(skill_file, &content, source, opts, denylist, skills, skips);
}

pub(super) fn finish_load_skill_file(
    skill_file: &Path,
    content: &str,
    source: &SkillSource,
    opts: &DiscoveryOptions,
    denylist: &[&str],
    skills: &mut Vec<Skill>,
    skips: &mut Vec<SkillSkip>,
) {
    match parse_skill(content) {
        Ok(skill) => {
            finish_load_parsed_skill(skill_file, skill, source, opts, denylist, skills, skips);
        }
        Err(e) => {
            skips.push(SkillSkip {
                path: skill_file.to_path_buf(),
                name: peek_frontmatter_name(content),
                kind: SkipKind::ParseError,
                detail: e.to_string(),
                winner_path: None,
                host_token: None,
            });
        }
    }
}

/// Skip text when `--ascii-names` / MCP `ascii_names` rejects a valid
/// Unicode name. Not invalid YAML; name the flag so the user can omit it.
pub(super) fn ascii_names_policy_detail() -> String {
    "name must be lowercase alphanumeric and hyphens only (omit --ascii-names / ascii_names to allow Unicode)".to_owned()
}

/// True when both paths name the same SKILL.md.
///
/// String equality covers a repeated walk. Canonicalize covers a symlink
/// and macOS `/tmp` versus `/private/tmp`. A failed canonicalize stays
/// false so a real second package is still a collision. Hardlinks stay
/// distinct.
fn same_skill_file(winner: &Path, candidate: &Path) -> bool {
    if winner == candidate {
        return true;
    }
    match (winner.canonicalize(), candidate.canonicalize()) {
        (Ok(left), Ok(right)) => left == right,
        _ => false,
    }
}

pub(super) fn finish_load_parsed_skill(
    skill_file: &Path,
    mut skill: Skill,
    source: &SkillSource,
    opts: &DiscoveryOptions,
    denylist: &[&str],
    skills: &mut Vec<Skill>,
    skips: &mut Vec<SkillSkip>,
) {
    if opts.ascii_names && !crate::parse::skill_name_is_ascii_policy(&skill.name) {
        skips.push(SkillSkip {
            path: skill_file.to_path_buf(),
            name: Some(skill.name.clone()),
            kind: SkipKind::ParseError,
            detail: ascii_names_policy_detail(),
            winner_path: None,
            host_token: None,
        });
        return;
    }
    if opts
        .disabled
        .iter()
        .any(|d| crate::parse::skill_names_equal(d, &skill.name))
    {
        return;
    }
    if denylist
        .iter()
        .any(|d| crate::parse::skill_names_equal(d, &skill.name))
    {
        return;
    }
    if !skill_name_matches_directory(skill_file, &skill.name) {
        skips.push(SkillSkip {
            path: skill_file.to_path_buf(),
            name: Some(skill.name.clone()),
            kind: SkipKind::NameDirectoryMismatch,
            detail: format!(
                "frontmatter name `{}` must match parent directory name",
                skill.name
            ),
            winner_path: None,
            host_token: None,
        });
        return;
    }
    if let Some(winner) = skills
        .iter()
        .find(|s| crate::parse::skill_names_equal(&s.name, &skill.name))
    {
        let winner_path = winner
            .source_path
            .clone()
            .unwrap_or_else(|| PathBuf::from("<already-loaded>"));
        // Repeated `--path`, or `--path` over a tree the implicit walk
        // already loaded, opens this same SKILL.md again. That is not a
        // second package, so it must not look like a name collision.
        if same_skill_file(&winner_path, skill_file) {
            return;
        }
        skips.push(SkillSkip {
            path: skill_file.to_path_buf(),
            name: Some(skill.name.clone()),
            kind: SkipKind::NameCollision,
            detail: format!("lost to {}", winner_path.display()),
            winner_path: Some(winner_path),
            host_token: None,
        });
        return;
    }
    skill.source = source.clone();
    skill.source_path = Some(skill_file.to_path_buf());
    skills.push(skill);
}

pub(super) fn is_skill_md_filename(path: &Path) -> bool {
    path.file_name()
        .is_some_and(|n| n == "SKILL.md" || n == "skill.md")
}

/// Join `SKILL.md` / `skill.md` when `path` is a package directory.
///
/// Same filenames as extra-path. A collection root (no package file)
/// is an error so validate does not walk children.
pub(super) fn resolve_validate_target(path: &Path) -> Result<PathBuf, String> {
    if !skill_md_is_dir(path) {
        // A cycle never resolves. Do not call it a misnamed file.
        // A dangling SKILL.md still falls through so the caller can
        // say the path does not exist.
        if let Some(detail) = symlink_loop_detail(path) {
            return Err(detail);
        }
        // Discover loads SKILL.md only. An existing README.md whose
        // frontmatter name matches the directory must not validate as
        // a package. A missing path stays missing so the caller can
        // say it does not exist.
        if skill_md_inode_exists(path) && !is_skill_md_filename(path) {
            let shown = path
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or("file");
            let shown = crate::sanitize_error_token(shown);
            return Err(format!(
                "file must be named SKILL.md (got {shown}). Pass a SKILL.md file or a package directory that contains SKILL.md"
            ));
        }
        return Ok(path.to_path_buf());
    }
    // `skill_md_inode_exists` is false for both NotFound and
    // permission denied. Discover already separates those. Validate
    // must not call a locked package "no SKILL.md".
    let joined = match lookup_package_skill_md(path) {
        PackageSkillMd::Found(joined) => joined,
        PackageSkillMd::Missing => {
            return Err("directory is not a skill package (no SKILL.md)".to_owned());
        }
        PackageSkillMd::Unreadable(detail) => return Err(detail),
    };
    // Joined SKILL.md is this package unless the inode is a symlink
    // out of the directory (same as extra-path classify).
    if let Some(detail) = unresolved_symlink_detail(&joined) {
        return Err(detail);
    }
    if !skill_md_stays_in_package(&joined) {
        return Err("SKILL.md symlink escapes package root".to_owned());
    }
    Ok(joined)
}

enum PackageSkillMd {
    Found(PathBuf),
    Missing,
    Unreadable(String),
}

/// Look up `SKILL.md` / `skill.md` inside a package directory.
///
/// `NotFound` is not a package. Any other stat error, including
/// permission denied, means the directory cannot be searched.
fn lookup_package_skill_md(dir: &Path) -> PackageSkillMd {
    let mut denied = None;
    for name in ["SKILL.md", "skill.md"] {
        let candidate = dir.join(name);
        match std::fs::symlink_metadata(&candidate) {
            Ok(_) => return PackageSkillMd::Found(candidate),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotADirectory => {
                return PackageSkillMd::Missing;
            }
            Err(e) => {
                denied = Some(e.to_string());
            }
        }
    }
    match denied {
        Some(detail) => PackageSkillMd::Unreadable(detail),
        None => PackageSkillMd::Missing,
    }
}

/// True when `dir` contains a skill file, or that file cannot be stat'd.
///
/// Collection detection uses this so an unreadable child is walked and
/// recorded. A readable directory with no `SKILL.md` stays a non-package.
pub(super) fn child_dir_counts_as_skill_package(dir: &Path) -> bool {
    matches!(
        lookup_package_skill_md(dir),
        PackageSkillMd::Found(_) | PackageSkillMd::Unreadable(_)
    )
}

/// True when `path` exists as any inode (regular, FIFO, socket, device, symlink).
///
/// `Path::is_file` follows links and is false for FIFO/socket/device, so a
/// package or extra-path SKILL.md of those types would be skipped before
/// [`read_skill_md`] could report unreadable.
pub(super) fn skill_md_inode_exists(path: &Path) -> bool {
    std::fs::symlink_metadata(path).is_ok()
}

pub(super) fn skill_md_is_dir(path: &Path) -> bool {
    std::fs::metadata(path).map(|m| m.is_dir()).unwrap_or(false)
}

pub(super) fn read_skill_md(path: &Path) -> Result<String, String> {
    #[cfg(test)]
    READ_SKILL_MD_PATHS.with(|c| c.borrow_mut().push(path.to_path_buf()));
    // A cycle fails `metadata` with a platform errno. Name it the same
    // way validate does, and do not open the link.
    if let Some(detail) = symlink_loop_detail(path) {
        return Err(detail);
    }
    // Stat before open. `File::open` on a FIFO waits for a writer, so a
    // hostile tree can hang discover / validate.
    let meta = std::fs::metadata(path).map_err(|e| e.to_string())?;
    if !meta.is_file() {
        return Err("SKILL.md is not a regular file".to_owned());
    }
    if meta.len() > SKILL_MD_MAX_BYTES {
        return Err(format!("SKILL.md exceeds {SKILL_MD_MAX_BYTES} bytes"));
    }
    let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
    let mut buf = String::new();
    let n = file
        .take(SKILL_MD_MAX_BYTES.saturating_add(1))
        .read_to_string(&mut buf)
        .map_err(|e| e.to_string())?;
    if n as u64 > SKILL_MD_MAX_BYTES {
        return Err(format!("SKILL.md exceeds {SKILL_MD_MAX_BYTES} bytes"));
    }
    Ok(buf)
}

pub(super) fn skill_md_stays_in_package(skill_file: &Path) -> bool {
    let Some(pkg) = skill_file.parent() else {
        return false;
    };
    let Ok(pkg_canon) = pkg.canonicalize() else {
        return false;
    };
    let Ok(file_canon) = skill_file.canonicalize() else {
        return false;
    };
    file_canon.starts_with(&pkg_canon)
}