upskill 0.2.0

Author and distribute AI-assistance content across coding agents
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
use anyhow::Context;
use clap::{Parser, Subcommand, error::ErrorKind};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};

use upskill::fmt::{FmtReport, fmt};
use upskill::lint::{LintReport, lint};
use upskill::pipeline::{
    DoctorReport, InstallReport, ItemKind, ListReport, ListedBundle, ListedItem, OrphanReason,
    RemoveFilter, RemoveReport, UpdateMode, UpdateReport, UpdateStatus, doctor,
    install_with_lockfile, list, remove, update,
};
use upskill::scaffold::{NewKind, ScaffoldReport, scaffold};
use upskill::search;
use upskill::source::parse_install_source;

const EXIT_SUCCESS: i32 = 0;
const EXIT_ERROR: i32 = 1;
const EXIT_USAGE: i32 = 2;
const EXIT_INTERRUPTED: i32 = 130;

static INTERRUPTED: AtomicBool = AtomicBool::new(false);

#[derive(Parser, Debug)]
#[command(name = "upskill")]
#[command(about = "Author and distribute AI-assistance content across coding agents")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Install rules / skills / agents from a source.
    ///
    /// Runs the v0.2 SSOT generation pipeline: parses each item from the
    /// source, renders per-client output, and records the install in
    /// `.upskill-lock.json`. Per format-spec ยง7 / ADR-0003.
    Add {
        /// Source: `owner/repo[@ref][:subfolder]`, full https URL, or local path.
        source: String,
        /// Install into `$HOME` instead of the current directory.
        #[arg(short = 'g', long = "global")]
        global: bool,
    },
    /// Remove installed content.
    ///
    /// Either name one or more items, or pass `--source <label>` to
    /// remove every item that came from a single source. Bare
    /// `upskill remove` is rejected โ€” be explicit per ADR-0004. Ancillary
    /// files (`CLAUDE.md`, `opencode.json`, `.vscode/settings.json`) are
    /// not touched.
    Remove {
        /// Item names to remove. Mutually exclusive with `--source`.
        names: Vec<String>,
        /// Remove every item whose lockfile `source` label matches this
        /// string. Use the value reported by the install or shown in
        /// `.upskill-lock.json` (e.g. `local:/path` or
        /// `github:owner/repo`).
        #[arg(long = "source")]
        source: Option<String>,
        /// Operate on `$HOME` instead of the current directory.
        #[arg(short = 'g', long = "global")]
        global: bool,
    },
    /// Pull latest sources and regenerate changed items.
    ///
    /// Re-fetches the source for every (or just the named) lockfile
    /// entries and reinstalls those sources. With `--dry-run`, hashes
    /// the new SSOT and reports what would change without writing.
    /// `update` always fetches per ADR-0004.
    Update {
        /// Item names to update (omit to update everything).
        names: Vec<String>,
        /// Report what would change without writing.
        #[arg(long = "dry-run")]
        dry_run: bool,
        /// Operate on `$HOME` instead of the current directory.
        #[arg(short = 'g', long = "global")]
        global: bool,
    },
    /// List installed content recorded in `.upskill-lock.json`.
    ///
    /// Items are grouped by kind (rules, skills, agents). Bundles, when
    /// present, are surfaced as a separate section. The command never
    /// fetches and never inspects per-client output files โ€” for that, run
    /// `upskill doctor`.
    List {
        /// Read `$HOME/.upskill-lock.json` instead of the current directory.
        #[arg(short = 'g', long = "global")]
        global: bool,
    },
    /// Verify installed-state consistency.
    ///
    /// Three independent buckets per ADR-0004:
    /// - missing per-client output files (reinstall fixes)
    /// - SSOT hash drift on `local:` sources (update fixes)
    /// - lockfile entries with no recoverable source (manual remove)
    ///
    /// Doctor never fetches; remote-source drift detection is
    /// `update --dry-run`. Exit 0 when clean, 1 when any drift is found.
    Doctor {
        /// Operate on `$HOME` instead of the current directory.
        #[arg(short = 'g', long = "global")]
        global: bool,
    },
    /// Search the public skills registry.
    Search {
        /// Search query.
        query: String,
        /// Maximum number of results.
        #[arg(long, default_value = "10")]
        limit: usize,
    },
    /// Validate SSOT files against the format spec.
    ///
    /// Author command โ€” runs only inside a source registry. Refuses to
    /// run inside a consumer project (detected by `.upskill-lock.json`).
    /// Default mode emits warnings and exits 0 unless an error rule
    /// fires; `--strict` promotes warnings to errors (CI mode). With no
    /// paths, lints the current directory.
    Lint {
        /// Files or directories to lint. Empty = current directory.
        paths: Vec<PathBuf>,
        /// Promote warnings to errors. Use in CI.
        #[arg(long)]
        strict: bool,
    },
    /// Canonicalise YAML frontmatter in SSOT files.
    ///
    /// Author command โ€” runs only inside a source registry. Body
    /// markdown is left untouched (dprint's job). Refuses to run inside
    /// a consumer project (detected by `.upskill-lock.json`). With no
    /// paths, formats the current directory.
    Fmt {
        /// Files or directories to format. Empty = current directory.
        paths: Vec<PathBuf>,
    },
    /// Scaffold a new rule, skill, or agent.
    ///
    /// Writes the minimum frontmatter the format spec requires plus
    /// kind-specific defaults (e.g. `mode: subagent` / `model: sonnet`
    /// for agents) into `<cwd>/<kind>s/<name>/<KIND>.md`. Author
    /// command โ€” refuses to run inside a consumer project.
    New {
        /// One of `rule`, `skill`, `agent`.
        kind: String,
        /// Item name. Lowercase letters, digits, hyphens; max 64 chars
        /// per format-spec ยง2.1.
        name: String,
    },
}

fn main() {
    if let Err(err) = install_signal_handlers() {
        eprintln!("error: {}", err);
        std::process::exit(EXIT_ERROR);
    }

    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(err) => {
            let code = map_clap_error(&err);
            let _ = err.print();
            std::process::exit(code);
        }
    };

    let mut exit_code = match cli.command {
        Commands::Add { source, global } => run_add(&source, global),
        Commands::Remove {
            names,
            source,
            global,
        } => run_remove(&names, source.as_deref(), global),
        Commands::Update {
            names,
            dry_run,
            global,
        } => run_update(&names, dry_run, global),
        Commands::List { global } => run_list(global),
        Commands::Doctor { global } => run_doctor(global),
        Commands::Search { query, limit } => run_search(&query, limit),
        Commands::Lint { paths, strict } => run_lint(&paths, strict),
        Commands::Fmt { paths } => run_fmt(&paths),
        Commands::New { kind, name } => run_new(&kind, &name),
    };

    if was_interrupted() {
        exit_code = EXIT_INTERRUPTED;
    }

    std::process::exit(exit_code);
}

fn install_signal_handlers() -> anyhow::Result<()> {
    ctrlc::set_handler(|| {
        INTERRUPTED.store(true, Ordering::SeqCst);
    })
    .context("failed to install signal handler")
}

fn was_interrupted() -> bool {
    INTERRUPTED.load(Ordering::SeqCst)
}

fn map_clap_error(err: &clap::Error) -> i32 {
    match err.kind() {
        ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => EXIT_SUCCESS,
        _ => EXIT_USAGE,
    }
}

fn run_add(source: &str, global: bool) -> i32 {
    let parsed = match parse_install_source(source) {
        Ok(s) => s,
        Err(err) => {
            eprintln!("error: {}", err);
            return EXIT_USAGE;
        }
    };

    let target = match install_target(global) {
        Ok(t) => t,
        Err(err) => {
            eprintln!("error: {}", err);
            return EXIT_ERROR;
        }
    };

    match install_with_lockfile(&parsed, &target) {
        Ok(report) => {
            print_install_report(&report, source);
            EXIT_SUCCESS
        }
        Err(err) => {
            eprintln!("error: {:#}", err);
            EXIT_ERROR
        }
    }
}

fn install_target(global: bool) -> anyhow::Result<PathBuf> {
    if global {
        std::env::var_os("HOME")
            .map(PathBuf::from)
            .ok_or_else(|| anyhow::anyhow!("HOME is not set"))
    } else {
        std::env::current_dir().context("failed to get current directory")
    }
}

fn print_install_report(report: &InstallReport, source: &str) {
    use std::collections::BTreeMap;

    println!("Installed {} files from {}", report.items.len(), source);

    let mut grouped: BTreeMap<(ItemKind, String), Vec<&'static str>> = BTreeMap::new();
    for item in &report.items {
        grouped
            .entry((item.kind, item.name.clone()))
            .or_default()
            .push(item.client.name());
    }
    for ((kind, name), clients) in grouped {
        let kind_label = match kind {
            ItemKind::Rule => "rule ",
            ItemKind::Skill => "skill",
            ItemKind::Agent => "agent",
        };
        println!("  {} {:<32} โ†’ {}", kind_label, name, clients.join(", "));
    }
}

fn run_remove(names: &[String], source: Option<&str>, global: bool) -> i32 {
    let filter = match (names.is_empty(), source) {
        (true, Some(s)) => RemoveFilter::BySource(s.to_string()),
        (false, None) => RemoveFilter::ByNames(names.to_vec()),
        (true, None) => {
            eprintln!(
                "error: nothing to remove โ€” pass one or more item names, or `--source <label>`"
            );
            return EXIT_USAGE;
        }
        (false, Some(_)) => {
            eprintln!("error: `--source` and item names are mutually exclusive");
            return EXIT_USAGE;
        }
    };

    let target = match install_target(global) {
        Ok(t) => t,
        Err(err) => {
            eprintln!("error: {}", err);
            return EXIT_ERROR;
        }
    };

    match remove(&target, filter) {
        Ok(report) => {
            print_remove_report(&report);
            EXIT_SUCCESS
        }
        Err(err) => {
            eprintln!("error: {:#}", err);
            EXIT_ERROR
        }
    }
}

fn print_remove_report(report: &RemoveReport) {
    if report.items.is_empty() {
        println!("no matching items in lockfile");
        return;
    }
    println!("Removed {} item(s)", report.items.len());
    for item in &report.items {
        let kind_label = match item.kind {
            ItemKind::Rule => "rule ",
            ItemKind::Skill => "skill",
            ItemKind::Agent => "agent",
        };
        println!(
            "  {} {:<32} ({} file(s))",
            kind_label,
            item.name,
            item.deleted_files.len()
        );
    }
}

fn run_update(names: &[String], dry_run: bool, global: bool) -> i32 {
    let target = match install_target(global) {
        Ok(t) => t,
        Err(err) => {
            eprintln!("error: {}", err);
            return EXIT_ERROR;
        }
    };
    let mode = if dry_run {
        UpdateMode::DryRun
    } else {
        UpdateMode::Apply
    };

    match update(&target, names, mode) {
        Ok(report) => {
            print_update_report(&report, dry_run);
            EXIT_SUCCESS
        }
        Err(err) => {
            eprintln!("error: {:#}", err);
            EXIT_ERROR
        }
    }
}

fn print_update_report(report: &UpdateReport, dry_run: bool) {
    if report.items.is_empty() {
        println!("nothing to update โ€” lockfile is empty");
        return;
    }
    let header = if dry_run {
        "Dry-run: would update"
    } else {
        "Updated"
    };
    let changes = report
        .items
        .iter()
        .filter(|i| !matches!(i.status, UpdateStatus::UpToDate))
        .count();
    println!("{header} {} of {} item(s)", changes, report.items.len());
    for item in &report.items {
        let kind_label = match item.kind {
            ItemKind::Rule => "rule ",
            ItemKind::Skill => "skill",
            ItemKind::Agent => "agent",
        };
        let status = match &item.status {
            UpdateStatus::UpToDate => "up to date".to_string(),
            UpdateStatus::Updated { new_hash, .. } => format!("updated โ†’ {}", short(new_hash)),
            UpdateStatus::WouldChange { new_hash, .. } => {
                format!("would change โ†’ {}", short(new_hash))
            }
        };
        println!("  {} {:<32} {}", kind_label, item.name, status);
    }
}

fn short(h: &Option<String>) -> String {
    match h {
        Some(s) if s.len() >= 8 => s[..8].to_string(),
        Some(s) => s.clone(),
        None => "<no hash>".to_string(),
    }
}

fn run_doctor(global: bool) -> i32 {
    let target = match install_target(global) {
        Ok(t) => t,
        Err(err) => {
            eprintln!("error: {}", err);
            return EXIT_ERROR;
        }
    };

    match doctor(&target) {
        Ok(report) => {
            print_doctor_report(&report);
            if report.is_clean() {
                EXIT_SUCCESS
            } else {
                EXIT_ERROR
            }
        }
        Err(err) => {
            eprintln!("error: {:#}", err);
            EXIT_ERROR
        }
    }
}

fn print_doctor_report(report: &DoctorReport) {
    if report.is_clean() {
        println!("doctor: clean");
        return;
    }

    if !report.missing_outputs.is_empty() {
        println!(
            "doctor: missing per-client outputs ({} item(s)) โ€” reinstall to fix",
            report.missing_outputs.len()
        );
        for m in &report.missing_outputs {
            println!("  {} {}", kind_label(m.kind), m.name);
            for path in &m.missing_files {
                println!("    - {}", path.display());
            }
        }
    }

    if !report.stale_hashes.is_empty() {
        println!(
            "doctor: SSOT hash drift on local sources ({} item(s)) โ€” `upskill update` to fix",
            report.stale_hashes.len()
        );
        for s in &report.stale_hashes {
            println!("  {} {} ({})", kind_label(s.kind), s.name, s.source);
        }
    }

    if !report.orphan_entries.is_empty() {
        println!(
            "doctor: lockfile entries with no recoverable source ({} item(s)) โ€” `upskill remove` to clear",
            report.orphan_entries.len()
        );
        for o in &report.orphan_entries {
            let reason = match o.reason {
                OrphanReason::LocalPathGone => "local path gone",
                OrphanReason::ItemMissingInSource => "item not in source",
            };
            println!(
                "  {} {} ({}) โ€” {}",
                kind_label(o.kind),
                o.name,
                o.source,
                reason
            );
        }
    }
}

fn kind_label(kind: ItemKind) -> &'static str {
    match kind {
        ItemKind::Rule => "rule ",
        ItemKind::Skill => "skill",
        ItemKind::Agent => "agent",
    }
}

fn run_list(global: bool) -> i32 {
    let target = match install_target(global) {
        Ok(t) => t,
        Err(err) => {
            eprintln!("error: {}", err);
            return EXIT_ERROR;
        }
    };

    match list(&target) {
        Ok(report) => {
            print_list_report(&report);
            EXIT_SUCCESS
        }
        Err(err) => {
            eprintln!("error: {:#}", err);
            EXIT_ERROR
        }
    }
}

fn print_list_report(report: &ListReport) {
    if report.is_empty() {
        println!("no items installed");
        return;
    }

    print_list_section("rules", &report.rules);
    print_list_section("skills", &report.skills);
    print_list_section("agents", &report.agents);
    print_list_bundles(&report.bundles);
}

fn print_list_section(label: &str, items: &[ListedItem]) {
    if items.is_empty() {
        return;
    }
    println!("{label} ({})", items.len());
    for item in items {
        let pinned = match &item.git_ref {
            Some(r) => format!("@{r}"),
            None => String::new(),
        };
        println!("  {:<32} {}{}", item.name, item.source, pinned);
    }
}

fn print_list_bundles(bundles: &[ListedBundle]) {
    if bundles.is_empty() {
        return;
    }
    println!("bundles ({})", bundles.len());
    for bundle in bundles {
        let pinned = match &bundle.git_ref {
            Some(r) => format!("@{r}"),
            None => String::new(),
        };
        println!("  {:<32} {}{}", bundle.name, bundle.source, pinned);
    }
}

fn run_lint(paths: &[PathBuf], strict: bool) -> i32 {
    match lint(paths, strict) {
        Ok(report) => {
            print_lint_report(&report);
            if report.has_errors() {
                EXIT_ERROR
            } else {
                EXIT_SUCCESS
            }
        }
        Err(err) => {
            eprintln!("error: {:#}", err);
            // Author-command misuse (consumer-project / unreadable
            // path) maps to usage error. The lint module surfaces
            // those as Err(_); per-rule findings travel inside Ok.
            EXIT_USAGE
        }
    }
}

fn print_lint_report(report: &LintReport) {
    for f in &report.findings {
        let line = f.line.map(|n| format!(":{n}")).unwrap_or_default();
        println!(
            "{}: {}{} [{}] {}",
            f.severity.label(),
            f.path.display(),
            line,
            f.rule_id,
            f.message
        );
    }
    println!(
        "{} file(s) checked, {} findings",
        report.files_checked,
        report.findings.len()
    );
}

fn run_fmt(paths: &[PathBuf]) -> i32 {
    match fmt(paths) {
        Ok(report) => {
            print_fmt_report(&report);
            EXIT_SUCCESS
        }
        Err(err) => {
            eprintln!("error: {:#}", err);
            EXIT_USAGE
        }
    }
}

fn print_fmt_report(report: &FmtReport) {
    if report.files_changed.is_empty() {
        println!("{} file(s) checked, all formatted", report.files_checked);
        return;
    }
    for path in &report.files_changed {
        println!("formatted: {}", path.display());
    }
    println!(
        "{} file(s) checked, {} file(s) changed",
        report.files_checked,
        report.files_changed.len()
    );
}

fn run_new(kind: &str, name: &str) -> i32 {
    let parsed_kind = match NewKind::parse(kind) {
        Ok(k) => k,
        Err(err) => {
            eprintln!("error: {}", err);
            return EXIT_USAGE;
        }
    };
    let cwd = match std::env::current_dir() {
        Ok(p) => p,
        Err(err) => {
            eprintln!("error: get current directory: {}", err);
            return EXIT_ERROR;
        }
    };
    match scaffold(&cwd, parsed_kind, name) {
        Ok(report) => {
            print_scaffold_report(&report);
            EXIT_SUCCESS
        }
        Err(err) => {
            let msg = format!("{:#}", err);
            eprintln!("error: {}", msg);
            // Author-command misuse (consumer-project) โ†’ usage error;
            // every other failure โ†’ 1.
            if msg.contains("consumer project") {
                EXIT_USAGE
            } else {
                EXIT_ERROR
            }
        }
    }
}

fn print_scaffold_report(report: &ScaffoldReport) {
    let kind_label = match report.kind {
        NewKind::Rule => "rule",
        NewKind::Skill => "skill",
        NewKind::Agent => "agent",
    };
    println!(
        "scaffolded {kind_label} `{}` at {}",
        report.name,
        report.written.display()
    );
    println!("edit the file and replace the TODO body before publishing.");
}

fn run_search(query: &str, limit: usize) -> i32 {
    match search::search(query, limit) {
        Err(err) => {
            eprintln!("error: {}", err);
            EXIT_ERROR
        }
        Ok(results) if results.is_empty() => {
            println!("no skills found for '{}'", query);
            EXIT_SUCCESS
        }
        Ok(results) => {
            for skill in &results {
                let repo = skill
                    .source
                    .trim_start_matches("github/")
                    .trim_start_matches("gitlab/");
                println!(
                    "{}\t{} installs\tupskill add {} --skill {}",
                    skill.name, skill.installs, repo, skill.name
                );
            }
            EXIT_SUCCESS
        }
    }
}