devboy-cli 0.28.0

Command-line interface for devboy-tools — `devboy` binary. Primary distribution is npm (@devboy-tools/cli); `cargo install devboy-cli` is the secondary channel.
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
//! Handlers for the `devboy skills {list,show,install,upgrade,remove}`
//! CLI subcommand family. The real logic lives in `devboy_skills`; this
//! module only translates between CLI flags and the crate's API and
//! handles user-facing output.

use anyhow::{Context, Result};
use devboy_skills::{
    Agent, Category, EmbeddedSkillSource, Environment, InstallOptions, InstallOutcome,
    InstallReport, InstallSpec, Manifest, SkillSource, detect_installed_agents,
    install_skills_to_target, remove_skills_from_target, resolve_targets,
};

use crate::{SkillsCommands, TraceCommands};

/// Dispatch a `devboy trace` subcommand.
pub async fn handle_trace(command: TraceCommands) -> Result<()> {
    use devboy_skills::{TraceTarget, append_event, create_session, finalise_session};
    match command {
        TraceCommands::Begin { skill, global, dir } => {
            let target = if let Some(p) = dir {
                TraceTarget::Custom(std::path::PathBuf::from(p))
            } else if global {
                TraceTarget::Global
            } else {
                TraceTarget::RepoLocal
            };
            let (session_id, session_dir) =
                create_session(&skill, &target).context("failed to begin session")?;
            let trace_path = session_dir.join("trace.jsonl");
            let out = serde_json::json!({
                "session_id": session_id,
                "session_dir": session_dir.display().to_string(),
                "trace_path": trace_path.display().to_string(),
            });
            println!("{out}");
            Ok(())
        }
        TraceCommands::Event {
            session_dir,
            session_id,
            skill,
            phase,
            payload,
        } => {
            let phase = parse_phase(&phase)?;
            let payload: serde_json::Value =
                serde_json::from_str(&payload).context("invalid JSON payload")?;
            append_event(
                std::path::Path::new(&session_dir),
                &session_id,
                &skill,
                phase,
                payload,
            )
            .context("failed to append event")
        }
        TraceCommands::End {
            session_dir,
            session_id,
            skill,
            outcome,
            summary,
        } => {
            let outcome = parse_outcome(&outcome)?;
            finalise_session(
                std::path::Path::new(&session_dir),
                &session_id,
                &skill,
                outcome,
                &summary,
            )
            .context("failed to finalise session")
        }
    }
}

fn parse_phase(raw: &str) -> Result<devboy_skills::TracePhase> {
    use devboy_skills::TracePhase as P;
    Ok(match raw {
        "start" => P::Start,
        "decision" => P::Decision,
        "tool_call" => P::ToolCall,
        "tool_result" => P::ToolResult,
        "verify" => P::Verify,
        "artifact" => P::Artifact,
        "note" => P::Note,
        "end" => P::End,
        other => anyhow::bail!(
            "unknown trace phase `{other}` (expected start | decision | tool_call | tool_result | verify | artifact | note | end)"
        ),
    })
}

fn parse_outcome(raw: &str) -> Result<devboy_skills::TraceOutcome> {
    use devboy_skills::TraceOutcome as O;
    Ok(match raw {
        "success" => O::Success,
        "failure" => O::Failure,
        "aborted" => O::Aborted,
        other => anyhow::bail!("unknown outcome `{other}` (expected success | failure | aborted)"),
    })
}

/// Dispatch a `devboy skills` subcommand.
pub async fn handle(command: SkillsCommands) -> Result<()> {
    match command {
        SkillsCommands::List { category } => handle_list(category).await,
        SkillsCommands::Show { name } => handle_show(&name).await,
        SkillsCommands::Install {
            names,
            all,
            category,
            global,
            local,
            agents,
            force,
            dry_run,
        } => handle_install(names, all, category, global, local, agents, force, dry_run).await,
        SkillsCommands::Upgrade {
            names,
            global,
            local,
            agents,
            force,
            dry_run,
        } => handle_upgrade(names, global, local, agents, force, dry_run).await,
        SkillsCommands::Remove {
            names,
            global,
            local,
            agents,
            strict,
            dry_run,
        } => handle_remove(names, global, local, agents, strict, dry_run).await,
    }
}

// ---------------------------------------------------------------------------
// list / show
// ---------------------------------------------------------------------------

async fn handle_list(category_filter: Option<String>) -> Result<()> {
    let source = EmbeddedSkillSource::new();
    let summaries = source
        .list()
        .await
        .context("failed to enumerate embedded skills")?;

    let filtered: Vec<_> = match category_filter.as_deref() {
        None => summaries,
        Some(raw) => {
            let cat = Category::parse(raw).with_context(|| {
                format!(
                    "unknown category `{raw}` (expected one of: self-bootstrap, issue-tracking, code-review, self-feedback, meeting-notes, messenger)"
                )
            })?;
            summaries
                .into_iter()
                .filter(|s| s.category == cat)
                .collect()
        }
    };

    if filtered.is_empty() {
        println!("no skills found");
        return Ok(());
    }

    let mut current_category: Option<Category> = None;
    for s in &filtered {
        if Some(s.category) != current_category {
            current_category = Some(s.category);
            println!("\n[{}]", s.category);
        }
        println!("  {:<32} v{:<3} {}", s.name, s.version, s.description);
    }
    println!();
    Ok(())
}

async fn handle_show(name: &str) -> Result<()> {
    let source = EmbeddedSkillSource::new();
    let skill = source
        .load(name)
        .await
        .with_context(|| format!("failed to load skill `{name}`"))?;
    let yaml =
        serde_yaml::to_string(&skill.frontmatter).context("failed to serialise frontmatter")?;
    println!("---");
    print!("{yaml}");
    if !yaml.ends_with('\n') {
        println!();
    }
    println!("---");
    print!("{}", skill.body);
    if !skill.body.ends_with('\n') {
        println!();
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// install / upgrade
// ---------------------------------------------------------------------------

#[allow(clippy::too_many_arguments)]
async fn handle_install(
    names: Vec<String>,
    all: bool,
    category: Option<String>,
    global: bool,
    local: bool,
    agent_flags: Vec<String>,
    force: bool,
    dry_run: bool,
) -> Result<()> {
    let skills_to_install = select_skills(&names, all, category.as_deref()).await?;
    if skills_to_install.is_empty() {
        println!("no skills matched the selection");
        return Ok(());
    }

    let env = Environment::detect().context("failed to detect environment")?;
    let spec = build_install_spec(global, local, &agent_flags, &env)?;
    let targets = resolve_targets(&env, &spec).map_err(format_target_error)?;

    let history = devboy_skills::HistoricalHashes::load_embedded()
        .context("failed to load embedded historical hashes")?;
    let options = InstallOptions {
        force,
        dry_run,
        installed_from: Some(format!("devboy-tools {}", env!("CARGO_PKG_VERSION"))),
    };

    let mut any_written = false;
    let mut any_failed = false;

    for target in &targets {
        println!("-> {}", target.label);
        match install_skills_to_target(target, &skills_to_install, &history, &options) {
            Ok(report) => {
                print_report(&report);
                if report.outcomes.values().any(|o| {
                    matches!(
                        o,
                        InstallOutcome::Installed
                            | InstallOutcome::Upgraded { .. }
                            | InstallOutcome::OverwrittenWithForce
                    )
                }) {
                    any_written = true;
                }
            }
            Err(e) => {
                eprintln!("   error: {e}");
                any_failed = true;
            }
        }
    }

    if any_failed && !any_written {
        anyhow::bail!("every install target failed; see errors above");
    }
    if dry_run {
        println!("\n(dry-run) no filesystem changes were made");
    }
    Ok(())
}

async fn handle_upgrade(
    names: Vec<String>,
    global: bool,
    local: bool,
    agent_flags: Vec<String>,
    force: bool,
    dry_run: bool,
) -> Result<()> {
    let env = Environment::detect().context("failed to detect environment")?;
    let spec = build_install_spec(global, local, &agent_flags, &env)?;
    let targets = resolve_targets(&env, &spec).map_err(format_target_error)?;

    let source = EmbeddedSkillSource::new();
    let history = devboy_skills::HistoricalHashes::load_embedded()
        .context("failed to load embedded historical hashes")?;
    let options = InstallOptions {
        force,
        dry_run,
        installed_from: Some(format!("devboy-tools {}", env!("CARGO_PKG_VERSION"))),
    };

    let mut any_written = false;
    let mut any_failed = false;

    for target in &targets {
        println!("-> {}", target.label);
        let manifest_path = target.skills_dir.join(devboy_skills::MANIFEST_FILE);
        let manifest = match Manifest::load(&manifest_path) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("   error: manifest load failed: {e}");
                any_failed = true;
                continue;
            }
        };
        let candidates: Vec<String> = if names.is_empty() {
            manifest.skills.keys().cloned().collect()
        } else {
            names.clone()
        };
        if candidates.is_empty() {
            println!("   (no installed skills)");
            continue;
        }
        let mut skills = Vec::new();
        for n in &candidates {
            match source.load(n).await {
                Ok(s) => skills.push(s),
                Err(e) => eprintln!("   {n}: skipped ({e})"),
            }
        }
        match install_skills_to_target(target, &skills, &history, &options) {
            Ok(report) => {
                print_report(&report);
                if report.outcomes.values().any(|o| {
                    matches!(
                        o,
                        InstallOutcome::Installed
                            | InstallOutcome::Upgraded { .. }
                            | InstallOutcome::OverwrittenWithForce
                    )
                }) {
                    any_written = true;
                }
            }
            Err(e) => {
                eprintln!("   error: {e}");
                any_failed = true;
            }
        }
    }

    if any_failed && !any_written {
        anyhow::bail!("every upgrade target failed; see errors above");
    }
    if dry_run {
        println!("\n(dry-run) no filesystem changes were made");
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// remove
// ---------------------------------------------------------------------------

async fn handle_remove(
    names: Vec<String>,
    global: bool,
    local: bool,
    agent_flags: Vec<String>,
    strict: bool,
    dry_run: bool,
) -> Result<()> {
    let env = Environment::detect().context("failed to detect environment")?;
    let spec = build_install_spec(global, local, &agent_flags, &env)?;
    let targets = resolve_targets(&env, &spec).map_err(format_target_error)?;

    for target in &targets {
        println!("-> {}", target.label);
        match remove_skills_from_target(target, &names, strict, dry_run) {
            Ok(removed) => {
                if removed.is_empty() {
                    println!("   (nothing matched)");
                } else {
                    for n in removed {
                        println!("   removed {n}");
                    }
                }
            }
            Err(e) => eprintln!("   error: {e}"),
        }
    }
    if dry_run {
        println!("\n(dry-run) no filesystem changes were made");
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// helpers
// ---------------------------------------------------------------------------

async fn select_skills(
    names: &[String],
    all: bool,
    category_filter: Option<&str>,
) -> Result<Vec<devboy_skills::Skill>> {
    let source = EmbeddedSkillSource::new();
    if all {
        let summaries = source.list().await?;
        let mut out = Vec::with_capacity(summaries.len());
        for s in summaries {
            out.push(source.load(&s.name).await?);
        }
        return Ok(out);
    }
    if let Some(raw) = category_filter {
        let cat = Category::parse(raw).with_context(|| format!("unknown category `{raw}`"))?;
        let summaries = source.list().await?;
        let mut out = Vec::new();
        for s in summaries.into_iter().filter(|s| s.category == cat) {
            out.push(source.load(&s.name).await?);
        }
        return Ok(out);
    }
    if names.is_empty() {
        anyhow::bail!(
            "no skills specified. Pass one or more names, `--all`, or `--category <id>`."
        );
    }
    let mut out = Vec::with_capacity(names.len());
    for name in names {
        out.push(source.load(name).await?);
    }
    Ok(out)
}

fn build_install_spec(
    global: bool,
    local: bool,
    agent_flags: &[String],
    env: &Environment,
) -> Result<InstallSpec> {
    let mut spec = InstallSpec {
        global,
        local,
        ..Default::default()
    };
    let mut include_vendor_neutral = false;
    for raw in agent_flags {
        if raw == "all" {
            for a in detect_installed_agents(&env.home) {
                if !spec.agents.contains(&a) {
                    spec.agents.push(a);
                }
            }
            include_vendor_neutral = true;
        } else if let Some(a) = Agent::parse(raw) {
            if !spec.agents.contains(&a) {
                spec.agents.push(a);
            }
        } else {
            anyhow::bail!(
                "unknown agent `{raw}` (expected one of: claude, codex, cursor, kimi, all)"
            );
        }
    }
    spec.include_vendor_neutral_global = include_vendor_neutral;
    Ok(spec)
}

fn format_target_error(err: devboy_skills::SkillError) -> anyhow::Error {
    // The install-target resolver reuses `MissingRequiredField` to signal
    // "no repo + no flag" — it sets `skill` to the sentinel
    // `<install-target>` so we can pattern-match on it specifically. Any
    // other `MissingRequiredField` (e.g. frontmatter validation) must
    // pass through unchanged so users see the real error.
    if let devboy_skills::SkillError::MissingRequiredField { ref skill, .. } = err
        && skill == "<install-target>"
    {
        return anyhow::anyhow!(
            "no git repository / .devboy.toml at the current path\n\n\
             skills are installed repo-locally by default. choose one:\n  \
             devboy skills install <name> --global           # install to ~/.agents/skills/\n  \
             devboy skills install <name> --agent claude     # install to ~/.claude/skills/\n  \
             devboy skills install <name> --agent all        # every detected agent\n  \
             cd <your-project> && devboy skills install <name>"
        );
    }
    anyhow::Error::new(err)
}

fn print_report(report: &InstallReport) {
    if report.outcomes.is_empty() {
        println!("   (no skills applied)");
        return;
    }
    let mut installed = 0usize;
    let mut unchanged = 0usize;
    let mut upgraded = 0usize;
    let mut skipped_user = 0usize;
    let mut overwritten = 0usize;
    let mut skipped_unknown = 0usize;
    for (name, outcome) in &report.outcomes {
        match outcome {
            InstallOutcome::Installed => {
                installed += 1;
                println!("   installed {name}");
            }
            InstallOutcome::Unchanged => {
                unchanged += 1;
                println!("   unchanged  {name}");
            }
            InstallOutcome::Upgraded { from_version } => {
                upgraded += 1;
                match from_version {
                    Some(v) => println!("   upgraded  {name} (from v{v})"),
                    None => println!("   upgraded  {name}"),
                }
            }
            InstallOutcome::SkippedUserModified => {
                skipped_user += 1;
                println!("   skipped   {name} (user-modified — pass --force to overwrite)");
            }
            InstallOutcome::OverwrittenWithForce => {
                overwritten += 1;
                println!("   forced    {name} (user-modified, overwritten)");
            }
            InstallOutcome::SkippedUnknown => {
                skipped_unknown += 1;
                println!("   skipped   {name} (unknown history — pass --force to overwrite)");
            }
        }
    }
    let _ = (
        installed,
        unchanged,
        upgraded,
        skipped_user,
        overwritten,
        skipped_unknown,
    );
}