craftbag-cli 0.3.0

CLI to list, load, why, and validate Agent Skills
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
//! craftbag CLI: list, load, why, validate, new.

use std::io::{self, Write};
use std::path::PathBuf;
use std::process::ExitCode;

/// `print!` / `println!` panic on a closed pipe (`list | head`). Treat
/// `BrokenPipe` as a clean stop.
fn write_stdout(text: &str) -> Result<(), String> {
    let mut out = io::stdout();
    match out.write_all(text.as_bytes()).and_then(|_| out.flush()) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(()),
        Err(e) => Err(e.to_string()),
    }
}

fn writeln_stdout(text: &str) -> Result<(), String> {
    write_stdout(&format!("{text}\n"))
}

use clap::{Parser, Subcommand};
use craftbag::{
    DiscoveryOptions, FormatOptions, ListFormat, LoadView, SkillSource, SkillSummary, discover,
    find_skill_by_name, format_available_skills_xml, format_catalog, format_list_tsv,
    format_load_view, format_skip_tsv, format_watch_dirs, format_why_text, normalize_skill_name,
    parse_list_format, present_disabled_vendors, progressive_budgets,
    unknown_or_skipped_skill_named, validate_path_with_options, validate_skill_name, watch_dirs,
    watch_host_skips, why,
};

#[derive(Parser)]
#[command(
    name = "craftbag",
    version,
    about = "Discover and load Agent Skills (SKILL.md) for CLI and MCP hosts"
)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(clap::Args, Debug, Clone)]
struct DiscoveryArgs {
    /// Extra package or collection root (not a project walk). Refuses a line separator or a token that collapses after whitespace (` /..`). A missing path is reported as unreadable. Example: --path ./my-skill
    #[arg(long = "path", value_name = "PATH")]
    paths: Vec<String>,
    /// Opt-in vendor trees: bline, claude, cursor, grok. Example: --vendor claude
    #[arg(long, value_delimiter = ',')]
    vendor: Vec<String>,
    /// User skills root (child dirs are packages). Refuses a line separator or a token that collapses after whitespace (` /..`). A missing path is reported as unreadable. Example: --user-dir ~/myskills
    #[arg(long = "user-dir")]
    user_dir: Option<PathBuf>,
    /// Reject names outside `a-z0-9-`. Default still allows Unicode / NFKC.
    #[arg(long = "ascii-names")]
    ascii_names: bool,
    /// Skip cwd-to-git .agents / vendor trees and $HOME/.agents / vendor trees. Default is on. Extra --path and --user-dir still load.
    #[arg(long = "no-implicit-roots")]
    no_implicit_roots: bool,
    /// Skill names never loaded (silent; no skip row). Same NFKC identity as load / why. Example: --disabled secret
    #[arg(long = "disabled", value_name = "NAME")]
    disabled: Vec<String>,
    /// Path prefix never loaded (silent; no skip row). Relative prefixes join cwd. Example: --ignore ./secret
    #[arg(long = "ignore", value_name = "PATH")]
    ignore: Vec<String>,
}

#[derive(Subcommand)]
enum Cmd {
    /// Catalog discovered skills.
    List {
        /// Print `{ skills, skips }` (same shape as MCP skills_list).
        #[arg(long)]
        json: bool,
        /// Official skills-ref `<available_skills>` XML inventory (includes disable_model_invocation for slash palettes).
        #[arg(long, conflicts_with = "json")]
        xml: bool,
        /// Markdown catalog (name + description) for model prompts. Omits disable_model_invocation (official client-guide). JSON, XML, and TSV still list those rows.
        #[arg(long, conflicts_with_all = ["json", "xml"])]
        catalog: bool,
        /// Print notify-watch roots (same walk as discover). Does not load SKILL.md. A refused `--path` or `--user-dir` is a skip on stderr, not a watch root.
        #[arg(long = "watch-dirs", conflicts_with_all = ["json", "xml", "catalog"])]
        watch_dirs: bool,
        /// Same tokens as MCP skills_list format: json (`{ skills, skips }`), xml (`<available_skills>`), catalog, watch.
        /// catalog omits disable_model_invocation (official client-guide); json, xml, and TSV still list those rows.
        /// xml, catalog, and watch also emit `skip\tkind\tpath\tdetail` (CLI stderr; MCP text after the prompt fragment).
        /// `watch-dirs` and `watch_dirs` are the `--watch-dirs` flag name.
        #[arg(long = "format", value_name = "FORMAT", conflicts_with_all = ["json", "xml", "catalog", "watch_dirs"])]
        format: Option<String>,
        #[command(flatten)]
        discovery: DiscoveryArgs,
        /// Catalog ranking text (`--catalog` / `--format catalog`). JSON, XML, TSV, and watch ignore this. A leading hyphen is text. Example: --context rebase
        #[arg(long, allow_hyphen_values = true)]
        context: Option<String>,
        /// Model context window size for catalog listing (default 8000). Used by `--catalog` / `--format catalog`.
        #[arg(long, default_value_t = 8_000)]
        context_tokens: usize,
    },
    /// Print one skill body plus package envelope (includes argument-hint, when-to-use, triggers, allowed-tools, license, compatibility, and metadata when set). --outline prints heading keys; --section KEY prints one heading. Does not dump scripts/ or references/ file bodies.
    Load {
        /// Frontmatter skill name (not a package path). Discover with list --path DIR.
        name: String,
        /// Success is `{ name, path, source, text }` (text is the envelope, including --outline / --section). On a miss, print `{ error_kind, error }` (same peel as `why --json` / `validate --json`), and `path` when a skip is known. A `name_collision` skip also peels `winner_path`. Exit 2 on a miss.
        #[arg(long)]
        json: bool,
        /// Print SKILL.md heading keys and token costs instead of the body.
        #[arg(long, conflicts_with = "section")]
        outline: bool,
        /// Print one SKILL.md heading section (key from --outline).
        #[arg(long, value_name = "KEY", conflicts_with = "outline")]
        section: Option<String>,
        /// Copied into the envelope as User arguments. Matches argument-hint. Example: --args --fix
        #[arg(long = "args", default_value = "", allow_hyphen_values = true)]
        args: String,
        #[command(flatten)]
        discovery: DiscoveryArgs,
    },
    /// Explain loaded, skipped, and activation decisions.
    Why {
        /// Optional frontmatter skill name filter (not a package path).
        name: Option<String>,
        /// Print `{ loaded, skips, activation }` (same shape as MCP skills_why). On a name miss, print `{ error_kind, error }` (same peel as `validate --json`), and `path` when a skip is known. A `name_collision` skip also peels `winner_path`. Exit 2 on a name miss. Exit 1 on a tool error.
        #[arg(long)]
        json: bool,
        /// Activation context text. A leading hyphen is text (a diff line). Example: --context rebase
        #[arg(long, allow_hyphen_values = true)]
        context: Option<String>,
        /// Model context window size (default 8000).
        #[arg(long, default_value_t = 8_000)]
        context_tokens: usize,
        #[command(flatten)]
        discovery: DiscoveryArgs,
    },
    /// Validate one SKILL.md file or package directory. `--json` success is ValidationReport (no error_kind).
    Validate {
        /// SKILL.md file, or a package directory that contains SKILL.md / skill.md. Refuses a line separator or a token that collapses after whitespace (` /..`). A missing path is reported as unreadable. Example: ./my-skill
        path: PathBuf,
        /// Reject unknown frontmatter keys (skills-ref default).
        #[arg(long)]
        strict: bool,
        /// Success is ValidationReport (no error_kind). Same `{ error_kind, error }` peel as `why --json` on failure, plus `path`. A `name_collision` skip also peels `winner_path`.
        #[arg(long)]
        json: bool,
    },
    /// Write `.agents/skills/NAME/SKILL.md` with a matching name and a placeholder description.
    New {
        /// Frontmatter name. Also the package directory name.
        name: String,
        /// Collection root. Default is `.agents/skills` under the current directory.
        #[arg(long, value_name = "DIR")]
        dir: Option<PathBuf>,
    },
}

fn main() -> ExitCode {
    match run(Cli::parse()) {
        Ok(code) => code,
        Err(e) => {
            let _ = writeln!(io::stderr(), "{e}");
            ExitCode::from(1)
        }
    }
}

fn run(cli: Cli) -> Result<ExitCode, String> {
    match cli.cmd {
        Cmd::List {
            json,
            xml,
            catalog,
            watch_dirs: watch,
            format,
            discovery,
            context,
            context_tokens,
        } => {
            let mode = list_output_mode(json, xml, catalog, watch, format)?;
            let (cwd, opts) = discovery_opts(&discovery)?;
            if matches!(mode, ListOutput::Watch) {
                write_stdout(&format_watch_dirs(&watch_dirs(&cwd, &opts)))?;
                let _ = write!(
                    io::stderr(),
                    "{}",
                    format_skip_tsv(&watch_host_skips(&cwd, &opts))
                );
                return Ok(ExitCode::SUCCESS);
            }
            let report = discover(&cwd, &opts);
            if matches!(mode, ListOutput::Catalog) {
                write_stdout(&format_catalog(
                    &report.skills,
                    context.as_deref().unwrap_or(""),
                    progressive_budgets(context_tokens),
                    FormatOptions::default(),
                ))?;
            } else if matches!(mode, ListOutput::Xml) {
                write_stdout(&format_available_skills_xml(&report.skills))?;
            } else if matches!(mode, ListOutput::Json) {
                let v = serde_json::json!({
                    "skills": report.skills.iter().map(SkillSummary::from).collect::<Vec<_>>(),
                    "skips": report.skips,
                });
                writeln_stdout(&serde_json::to_string_pretty(&v).map_err(|e| e.to_string())?)?;
            } else {
                write_stdout(&format_list_tsv(&report.skills))?;
            }
            if !matches!(mode, ListOutput::Json) {
                let _ = write!(io::stderr(), "{}", format_skip_tsv(&report.skips));
            }
            if report.skills.is_empty()
                && report.skips.is_empty()
                && !matches!(mode, ListOutput::Json | ListOutput::Xml)
            {
                write_empty_tree_note(&cwd, &opts);
            }
            Ok(ExitCode::SUCCESS)
        }
        Cmd::Load {
            name,
            json,
            outline,
            section,
            args,
            discovery,
        } => {
            let report = discover_cwd(&discovery)?;
            match find_skill_by_name(&report.skills, &name) {
                Some(skill) => {
                    let view = if outline {
                        LoadView::Outline
                    } else if let Some(key) = section.as_deref() {
                        LoadView::Section(key)
                    } else {
                        LoadView::Body
                    };
                    match format_load_view(skill, &args, FormatOptions::default(), view) {
                        Ok(text) => {
                            if json {
                                let v = serde_json::json!({
                                    "name": skill.name,
                                    "path": skill.source_path.as_ref().map(|p| p.display().to_string()),
                                    "source": skill.source.as_str(),
                                    "text": text,
                                });
                                writeln_stdout(
                                    &serde_json::to_string_pretty(&v).map_err(|e| e.to_string())?,
                                )?;
                            } else {
                                write_stdout(&text)?;
                            }
                            Ok(ExitCode::SUCCESS)
                        }
                        Err(msg) => {
                            let _ = writeln!(io::stderr(), "{msg}");
                            if json {
                                let v = serde_json::json!({
                                    "error_kind": "unknown_section",
                                    "error": msg,
                                });
                                writeln_stdout(
                                    &serde_json::to_string_pretty(&v).map_err(|e| e.to_string())?,
                                )?;
                            }
                            Ok(ExitCode::from(2))
                        }
                    }
                }
                None => {
                    let miss = unknown_or_skipped_skill_named(
                        &name,
                        &report.skips,
                        report.skills.iter().map(|s| s.name.as_str()),
                    );
                    let _ = writeln!(io::stderr(), "{miss}");
                    if json {
                        writeln_stdout(
                            &serde_json::to_string_pretty(&miss).map_err(|e| e.to_string())?,
                        )?;
                    }
                    Ok(ExitCode::from(2))
                }
            }
        }
        Cmd::Why {
            name,
            json,
            context,
            context_tokens,
            discovery,
        } => {
            let (cwd, opts) = discovery_opts(&discovery)?;
            let report = discover(&cwd, &opts);
            let budgets = progressive_budgets(context_tokens);
            let why = why(&report, name.as_deref(), context.as_deref(), Some(budgets));
            if let Some(miss) = why.unknown_skill_miss() {
                let _ = writeln!(io::stderr(), "{miss}");
                if json {
                    writeln_stdout(
                        &serde_json::to_string_pretty(&miss).map_err(|e| e.to_string())?,
                    )?;
                }
                return Ok(ExitCode::from(2));
            }
            if json {
                writeln_stdout(&serde_json::to_string_pretty(&why).map_err(|e| e.to_string())?)?;
            } else {
                write_stdout(&format_why_text(&why))?;
                if report.skills.is_empty() && report.skips.is_empty() {
                    write_empty_tree_note(&cwd, &opts);
                }
            }
            Ok(ExitCode::SUCCESS)
        }
        Cmd::New { name, dir } => write_new_skill(&name, dir.as_deref()),
        Cmd::Validate { path, strict, json } => {
            let report = validate_path_with_options(&path, strict);
            if report.ok {
                if json {
                    writeln_stdout(
                        &serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?,
                    )?;
                } else {
                    writeln_stdout(&format!("ok\t{}", report.name.as_deref().unwrap_or("-")))?;
                }
                Ok(ExitCode::SUCCESS)
            } else if let (true, Some(miss)) = (json, report.miss()) {
                let _ = writeln!(io::stderr(), "{miss}");
                writeln_stdout(&serde_json::to_string_pretty(&miss).map_err(|e| e.to_string())?)?;
                Ok(ExitCode::from(1))
            } else {
                for e in &report.errors {
                    let _ = writeln!(io::stderr(), "{e}");
                }
                Ok(ExitCode::from(1))
            }
        }
    }
}

enum ListOutput {
    Tsv,
    Json,
    Xml,
    Catalog,
    Watch,
}

fn list_output_mode(
    json: bool,
    xml: bool,
    catalog: bool,
    watch: bool,
    format: Option<String>,
) -> Result<ListOutput, String> {
    if let Some(format) = format {
        return Ok(match parse_list_format(&format)? {
            ListFormat::Json => ListOutput::Json,
            ListFormat::Xml => ListOutput::Xml,
            ListFormat::Catalog => ListOutput::Catalog,
            ListFormat::Watch => ListOutput::Watch,
        });
    }
    if watch {
        return Ok(ListOutput::Watch);
    }
    if catalog {
        return Ok(ListOutput::Catalog);
    }
    if xml {
        return Ok(ListOutput::Xml);
    }
    if json {
        return Ok(ListOutput::Json);
    }
    Ok(ListOutput::Tsv)
}

fn discovery_opts(discovery: &DiscoveryArgs) -> Result<(PathBuf, DiscoveryOptions), String> {
    let cwd = std::env::current_dir().map_err(|e| e.to_string())?;
    let vendor_roots = SkillSource::parse_vendor_roots(&discovery.vendor)?;
    let opts = DiscoveryOptions {
        paths: discovery.paths.clone(),
        ignore: discovery.ignore.clone(),
        disabled: discovery.disabled.clone(),
        vendor_roots,
        user_skills_dir: discovery.user_dir.clone(),
        ascii_names: discovery.ascii_names,
        implicit_roots: !discovery.no_implicit_roots,
    };
    Ok((cwd, opts))
}

fn write_empty_tree_note(cwd: &std::path::Path, opts: &DiscoveryOptions) {
    let dirs = watch_dirs(cwd, opts);
    let _ = writeln!(io::stderr(), "no skills found. searched:");
    let implicit_miss = dirs.is_empty() && opts.implicit_roots;
    if implicit_miss {
        let _ = writeln!(
            io::stderr(),
            "  (no .agents/skills directory on the cwd-to-git walk or under $HOME)"
        );
    } else if dirs.is_empty() {
        let _ = writeln!(
            io::stderr(),
            "  (no walk roots; pass --path DIR for a collection)"
        );
    } else {
        for dir in &dirs {
            let _ = writeln!(
                io::stderr(),
                "  {}",
                craftbag::sanitize_error_token(&dir.display().to_string())
            );
        }
    }
    if implicit_miss {
        let _ = writeln!(
            io::stderr(),
            "hint: run craftbag new NAME, or pass --path DIR for a collection root"
        );
    } else {
        let _ = writeln!(
            io::stderr(),
            "hint: a skill is a directory containing SKILL.md; pass --path DIR for a collection root"
        );
    }
    for name in present_disabled_vendors(cwd, opts) {
        let _ = writeln!(
            io::stderr(),
            "hint: .{name}/skills is present; pass --vendor {name}"
        );
    }
}

fn write_new_skill(raw_name: &str, dir: Option<&std::path::Path>) -> Result<ExitCode, String> {
    let name = normalize_skill_name(raw_name);
    match validate_skill_name(&name) {
        Ok(()) => {}
        Err(craftbag::ParseError::InvalidYaml(msg)) => return Err(msg),
        Err(err) => return Err(err.to_string()),
    }
    if let Some(path) = dir {
        refuse_new_dir(path)?;
    }
    let cwd = std::env::current_dir().map_err(|e| e.to_string())?;
    let root = match dir {
        Some(path) if path.is_absolute() => path.to_path_buf(),
        Some(path) => cwd.join(path),
        None => cwd.join(".agents").join("skills"),
    };
    let package = root.join(&name);
    if let Some(err) = package_symlink_escapes(&root, &package) {
        return Err(err);
    }
    let skill_md = package.join("SKILL.md");
    let skill_md_lower = package.join("skill.md");
    if skill_md.exists() || skill_md_lower.exists() {
        let shown = if skill_md.exists() {
            skill_md
        } else {
            skill_md_lower
        };
        return Err(format!(
            "skill already exists: {}",
            craftbag::sanitize_error_token(&shown.display().to_string())
        ));
    }
    std::fs::create_dir_all(&package).map_err(|err| {
        // io::Error does not name the path. Windows reports
        // AlreadyExists (os error 183) when a parent component is a
        // file. Unix reports NotADirectory. Either way, name that file.
        if let Some(blocked) = file_blocking_create(&package) {
            let shown = craftbag::sanitize_error_token(&blocked.display().to_string());
            return format!("not a directory: {shown}");
        }
        let shown = craftbag::sanitize_error_token(&package.display().to_string());
        format!(
            "{shown}: {}",
            craftbag::sanitize_error_token(&err.to_string())
        )
    })?;
    // Quote the name. Unquoted `on` / `null` are YAML booleans and null,
    // which this parser rejects even when the directory name is legal.
    let body = format!(
        "---\nname: \"{name}\"\ndescription: Describe when to use this skill.\n---\n\n# {name}\n\nInstructions for the agent.\n"
    );
    let file = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&skill_md);
    let mut file = match file {
        Ok(file) => file,
        Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
            return Err(format!(
                "skill already exists: {}",
                craftbag::sanitize_error_token(&skill_md.display().to_string())
            ));
        }
        Err(err) => return Err(err.to_string()),
    };
    if let Err(err) = std::io::Write::write_all(&mut file, body.as_bytes()) {
        drop(file);
        let _ = std::fs::remove_file(&skill_md);
        return Err(craftbag::sanitize_error_token(&err.to_string()));
    }
    writeln_stdout(&craftbag::sanitize_error_token(
        &skill_md.display().to_string(),
    ))?;
    Ok(ExitCode::SUCCESS)
}

/// A package directory symlink whose target is outside the collection
/// root would make `new` write that target's `SKILL.md`.
fn package_symlink_escapes(root: &std::path::Path, package: &std::path::Path) -> Option<String> {
    let meta = std::fs::symlink_metadata(package).ok()?;
    if !meta.file_type().is_symlink() {
        return None;
    }
    let Some(root_c) = root.canonicalize().ok() else {
        let shown = craftbag::sanitize_error_token(&package.display().to_string());
        return Some(format!(
            "package directory escapes collection root: {shown}"
        ));
    };
    // A dangling link fails closed in create_dir_all. Do not invent a target.
    let pkg_c = package.canonicalize().ok()?;
    if pkg_c.starts_with(&root_c) {
        return None;
    }
    let shown = craftbag::sanitize_error_token(&package.display().to_string());
    Some(format!(
        "package directory escapes collection root: {shown}"
    ))
}

fn file_blocking_create(path: &std::path::Path) -> Option<std::path::PathBuf> {
    let mut prefix = std::path::PathBuf::new();
    for component in path.components() {
        prefix.push(component);
        if prefix.is_file() {
            return Some(prefix);
        }
    }
    None
}

fn refuse_new_dir(path: &std::path::Path) -> Result<(), String> {
    for component in path.components() {
        match component.as_os_str().to_str() {
            None => return Err("--dir is not valid UTF-8".to_owned()),
            Some(text)
                if text
                    .chars()
                    .any(|c| matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}')) =>
            {
                return Err("--dir contains a line separator".to_owned());
            }
            Some(_) => {}
        }
    }
    Ok(())
}

fn discover_cwd(discovery: &DiscoveryArgs) -> Result<craftbag::DiscoveryReport, String> {
    let (cwd, opts) = discovery_opts(discovery)?;
    Ok(discover(&cwd, &opts))
}