skillpack 0.6.2

Generate and verify the agent-distribution layer for any OSS project (Claude Code, Cursor, Codex, OpenCode, GitHub Copilot).
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
//! Generate the three distribution files from a [`ProjectProfile`] + [`Intent`]
//! via Tera templates. Pure (no disk writes here): returns [`GeneratedFile`]s;
//! the CLI dispatcher decides whether to write them (after pre-commit verify).
//!
//! Design §5.1 step 3 + §6.3. Idempotent: identical inputs produce byte-identical
//! output across runs (templates use sorted/stable iteration where order
//! matters, and `default(value=...)` keeps fields present rather than
//! conditionally-present).

use anyhow::{Context, Result};
use once_cell::sync::Lazy;
use tera::{Context as TeraContext, Tera};

use crate::cli::Target;
use crate::types::{Intent, ProjectProfile};

/// Name → template source. Embedded via `include_str!` so templates ship inside
/// the binary but still live as editable `.tera` files in the repo for
/// non-Rust contributors (design §6.3).
const MARKETPLACE_TPL: &str = include_str!("../templates/marketplace.json.tera");
const PLUGIN_TPL: &str = include_str!("../templates/plugin.json.tera");
const SKILL_TPL: &str = include_str!("../templates/SKILL.md.tera");
const CURSOR_RULE_TPL: &str = include_str!("../templates/cursor-rule.mdc.tera");
const OPENCODE_AGENT_TPL: &str = include_str!("../templates/opencode-agent.md.tera");
const COPILOT_INSTRUCTIONS_TPL: &str = include_str!("../templates/copilot-instructions.md.tera");

static TERA: Lazy<Tera> = Lazy::new(|| {
    let mut tera = Tera::default();
    tera.add_raw_template("marketplace.json", MARKETPLACE_TPL)
        .expect("marketplace template is valid");
    tera.add_raw_template("plugin.json", PLUGIN_TPL)
        .expect("plugin template is valid");
    tera.add_raw_template("SKILL.md", SKILL_TPL)
        .expect("SKILL template is valid");
    tera.add_raw_template("cursor-rule.mdc", CURSOR_RULE_TPL)
        .expect("cursor rule template is valid");
    tera.add_raw_template("opencode-agent.md", OPENCODE_AGENT_TPL)
        .expect("opencode agent template is valid");
    tera.add_raw_template("copilot-instructions.md", COPILOT_INSTRUCTIONS_TPL)
        .expect("copilot instructions template is valid");
    // json_encode is built into Tera; nothing custom to register.
    tera
});

/// The three files `init` emits, relative to the project root. Documented for
/// external tooling/tests; the renderer computes paths itself.
#[allow(dead_code)]
pub const OUTPUT_PATHS: [&str; 3] = [
    ".claude-plugin/marketplace.json",
    ".claude-plugin/plugin.json",
    "skills/<tool>/SKILL.md",
];

/// Build the full Tera context from profile + intent.
pub fn build_context(profile: &ProjectProfile, intent: &Intent) -> TeraContext {
    let name = coerce_kebab(&profile.name);
    let keywords = Keywords {
        inner: derive_keywords(profile, intent),
    };
    // `display_name` is the human label for the tool in prose ("Do not use
    // this skill if the user only wants to *read* {{ display_name }}"). It is
    // the tool *name*, not the README blurp (which can read as a sentence and
    // mangle the surrounding prose).
    let display_name = name.clone();
    let has_cli = profile.has_cli;
    // `cli_binary` is the bare name agents/users would type to invoke the tool
    // (e.g. `chronicle`). The actual *spawn* path (which may be absolute, for
    // the verifier) lives in `cli_command` and is never used in the generated
    // prose — that keeps machine-specific absolute paths out of the published
    // SKILL.md.
    let cli_binary = name.clone();
    // `documented_flags` come from the captured --help output: the flags a
    // user can actually pass. Used to populate the "Documented flags" list.
    let documented_flags = profile
        .cli_help_output
        .as_deref()
        .map(crate::verify::invocation::extract_flags)
        .unwrap_or_default();

    // Subcommands: each advertised subcommand + the flags its own `--help`
    // exposes (parsed from the captured per-sub help). Order = declaration
    // order (clap), preserved by the `Vec` on the profile → deterministic
    // snapshots. Empty for non-subcommand CLIs and pure libraries.
    let documented_subcommands: Vec<serde_json::Value> = profile
        .cli_subcommand_help
        .iter()
        .map(|(name, help)| {
            // Drop the universal --help/-h/--version/-V meta-flags (per
            // invocation::is_meta_flag) so a subcommand bullet shows the
            // tool-specific flags an agent would actually pass, not the
            // help/version every CLI implicitly answers to.
            let flags: Vec<String> = crate::verify::invocation::extract_flags(help)
                .into_iter()
                .filter(|f| !crate::verify::invocation::is_meta_flag(f))
                .collect();
            serde_json::json!({ "name": name, "flags": flags })
        })
        .collect();

    // Precompute the joined when-to-use list so the template stays a thin
    // presentation layer (no Tera filter syntax for non-Rust contributors to
    // trip over). Empty list -> empty string: we deliberately do NOT emit a
    // placeholder like "(unspecified)" here, because that non-empty sentinel
    // would bypass verify's own `when_to_use` emptiness warning (design §5.3 —
    // the worst failure mode is a skill pack that looks fine but has no real
    // triggers). An empty `when_to_use:` keeps the verifier honest.
    let when_concat = intent.when_to_use_phrases.join(", ");

    tera::Context::from_serialize(serde_json::json!({
        "name": name,
        "display_name": display_name,
        "one_line_description": one_line_description_yaml(&intent.one_line_description),
        "one_line_description_raw": &intent.one_line_description,
        "when_to_use_phrases": intent.when_to_use_phrases,
        "when_concat": escape_yaml(&when_concat),
        "author": intent.author.as_deref().or(profile.authors.as_deref()),
        "license": intent.license,
        "repo_url": profile.repo_url,
        "keywords": keywords,
        "version": profile.version.as_deref().unwrap_or_default(),
        "has_cli": has_cli,
        "cli_binary": cli_binary,
        "invocation_command": intent.invocation_command,
        "import_pattern": intent.import_pattern,
        "documented_flags": documented_flags,
        "documented_subcommands": documented_subcommands,
        "category_hint": category_hint(profile.language),
        "allowed_tools": allowed_tools_hint(profile.language),
    }))
    .expect("Tera context serializes from JSON literal")
}

/// Escape a string so it's safe to embed inside YAML double-quoted scalar.
/// We escape backslash and double-quote — colons-followed-by-space are fine
/// inside quotes so we don't touch them.
fn escape_yaml(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// The one-line description can itself contain a colon; wrap it through the
/// same YAML escaper so the `description: "..."` line stays a single scalar.
fn one_line_description_yaml(s: &str) -> String {
    escape_yaml(s)
}

/// Renders all three files and returns them with their root-relative paths.
/// The skill path uses the kebab name.
pub fn render(profile: &ProjectProfile, intent: &Intent) -> Result<Vec<GeneratedFileOutput>> {
    let ctx = build_context(profile, intent);
    let name = coerce_kebab(&profile.name);

    let marketplace = TERA
        .render("marketplace.json", &ctx)
        .context("rendering marketplace.json")?;
    let plugin = TERA
        .render("plugin.json", &ctx)
        .context("rendering plugin.json")?;
    let skill = TERA
        .render("SKILL.md", &ctx)
        .context("rendering SKILL.md")?;

    Ok(vec![
        GeneratedFileOutput {
            rel_path: ".claude-plugin/marketplace.json".to_string(),
            contents: marketplace,
        },
        GeneratedFileOutput {
            rel_path: ".claude-plugin/plugin.json".to_string(),
            contents: plugin,
        },
        GeneratedFileOutput {
            rel_path: format!("skills/{name}/SKILL.md"),
            contents: skill,
        },
    ])
}

/// Render distribution files for one or more agent ecosystems. Calls
/// [`render`] for Claude (the three-file set) and emits additional files
/// for each extra target in `targets`. Dedupes: if `targets` contains
/// `Claude` plus others, Claude files are emitted once.
pub fn render_targets(
    profile: &ProjectProfile,
    intent: &Intent,
    targets: &[Target],
) -> Result<Vec<GeneratedFileOutput>> {
    let ctx = build_context(profile, intent);
    let name = coerce_kebab(&profile.name);
    let mut out = Vec::new();

    // Dedupe: emit each target once.
    let mut seen = std::collections::HashSet::new();
    for &target in targets {
        if !seen.insert(target) {
            continue;
        }
        match target {
            Target::Claude => out.extend(render(profile, intent)?),
            Target::Cursor => {
                let mdc = TERA
                    .render("cursor-rule.mdc", &ctx)
                    .context("rendering cursor-rule.mdc")?;
                out.push(GeneratedFileOutput {
                    rel_path: format!(".cursor/rules/{name}.mdc"),
                    contents: mdc,
                });
            }
            Target::Codex => {
                // Codex reads SKILL.md with the same frontmatter as Claude —
                // reuse the same template, different output path.
                let skill = TERA
                    .render("SKILL.md", &ctx)
                    .context("rendering codex SKILL.md")?;
                out.push(GeneratedFileOutput {
                    rel_path: format!(".codex/skills/{name}/SKILL.md"),
                    contents: skill,
                });
            }
            Target::OpenCode => {
                // OpenCode: .opencode/agents/<name>.md with `description`
                // (required) + `mode` frontmatter. Per opencode.ai/docs/agents.
                let agent = TERA
                    .render("opencode-agent.md", &ctx)
                    .context("rendering opencode-agent.md")?;
                out.push(GeneratedFileOutput {
                    rel_path: format!(".opencode/agents/{name}.md"),
                    contents: agent,
                });
            }
            Target::Copilot => {
                // GitHub Copilot: .github/copilot-instructions.md — plain
                // markdown, no frontmatter. Per docs.github.com/copilot.
                let instr = TERA
                    .render("copilot-instructions.md", &ctx)
                    .context("rendering copilot-instructions.md")?;
                out.push(GeneratedFileOutput {
                    rel_path: ".github/copilot-instructions.md".to_string(),
                    contents: instr,
                });
            }
        }
    }

    Ok(out)
}

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

/// A transparent newtype wrapper so the JSON / Tera context exposes the inner
/// array under the field name directly (the templates iterate `keywords` as a
/// list, not `keywords.inner`).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct Keywords {
    pub inner: Vec<String>,
}

/// Derive a small, stable keyword list from language + intent so the generated
/// marketplace entry is discoverable without the maintainer hand-curating it.
fn derive_keywords(profile: &ProjectProfile, intent: &Intent) -> Vec<String> {
    let mut kws = vec![profile.language.as_str().to_string()];
    if profile.has_cli {
        kws.push("cli".to_string());
    } else {
        kws.push("library".to_string());
    }
    // First trigger phrase, lowercased + first-word, as a cheap extra keyword.
    if let Some(first) = intent.when_to_use_phrases.first() {
        let kw = first
            .split_whitespace()
            .next()
            .unwrap_or("")
            .trim_matches(|c: char| !c.is_alphanumeric())
            .to_lowercase();
        if !kw.is_empty() && !kws.contains(&kw) {
            kws.push(kw);
        }
    }
    kws
}

fn category_hint(lang: crate::types::Language) -> &'static str {
    match lang {
        crate::types::Language::Rust => "the Rust tooling",
        crate::types::Language::Node => "the JavaScript/Node tooling",
        crate::types::Language::Python => "the Python tooling",
        crate::types::Language::Go => "the Go tooling",
        crate::types::Language::Ruby => "the Ruby tooling",
        crate::types::Language::Unknown => "the tooling",
    }
}

fn allowed_tools_hint(lang: crate::types::Language) -> Option<&'static str> {
    // The skill describes a CLI a user runs; it can use Bash to run the CLI
    // and Read to consult output. We keep this conservative — a library skill
    // leans on the host project's tooling, so we leave it blank.
    if let crate::types::Language::Unknown = lang {
        None
    } else {
        Some("Read Bash")
    }
}

/// Coerce an arbitrary detected name into valid kebab-case for the plugin/skill
/// namespace. Lowercases, replaces runs of non-[a-z0-9] with a single hyphen,
/// strips leading/trailing hyphens.
pub fn coerce_kebab(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    let mut prev_dash = false;
    for c in name.chars() {
        if c.is_ascii_alphanumeric() {
            out.push(c.to_ascii_lowercase());
            prev_dash = false;
        } else if !prev_dash {
            out.push('-');
            prev_dash = true;
        }
    }
    // Strip leading/trailing hyphens, then strip leading digits: the schema
    // regex `^[a-z]...` requires the name to start with a letter, so a
    // numeric-prefixed name like "123foo" → "foo" (not "123foo", which
    // would fail verify's own `is_valid_kebab` check). Re-trim hyphens
    // (stripping "123" from "123-foo" leaves "-foo") and re-check empty.
    let s = out.trim_matches('-');
    let s = s.trim_start_matches(|c: char| c.is_ascii_digit());
    let s = s.trim_matches('-');
    if s.is_empty() {
        return "tool".to_string();
    }
    if s.len() == 1 {
        return s.to_string();
    }
    s.to_string()
}

/// Output path + rendered contents, root-relative. Re-exports the shared
/// [`GeneratedFile`](crate::types::GeneratedFile) shape; kept as its own type
/// so callers don't need to import the path tuple awkwardly.
#[derive(Debug, Clone)]
pub struct GeneratedFileOutput {
    pub rel_path: String,
    pub contents: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{Intent, Language, ProjectProfile};

    fn cli_profile() -> ProjectProfile {
        let mut p = ProjectProfile::test_default();
        p.name = "chronicle".into();
        p.language = Language::Rust;
        p.has_cli = true;
        p.cli_command = Some(vec!["chronicle".to_string(), "--help".to_string()]);
        p.cli_help_output = Some("Usage: chronicle [OPTIONS]\n  --new <entry>   Create an entry\n  --verbose        verbose\n".into());
        p.cli_subcommand_help = Vec::new();
        p.license = Some("MIT".into());
        p
    }

    fn cli_intent() -> Intent {
        Intent {
            one_line_description: "Journal events to a chronological log".into(),
            when_to_use_phrases: vec!["log a journal entry".into(), "record an incident".into()],
            invocation_command: Some("chronicle --new \"entry\"".into()),
            import_pattern: None,
            author: Some("Mikey".into()),
            license: Some("MIT".into()),
        }
    }

    #[test]
    fn renders_three_files_with_valid_paths() {
        let p = cli_profile();
        let i = cli_intent();
        let files = render(&p, &i).unwrap();
        assert_eq!(files.len(), 3);
        assert_eq!(files[0].rel_path, ".claude-plugin/marketplace.json");
        assert_eq!(files[1].rel_path, ".claude-plugin/plugin.json");
        assert_eq!(files[2].rel_path, "skills/chronicle/SKILL.md");
    }

    #[test]
    fn rendered_marketplace_is_valid_json_and_points_at_dot_slash() {
        let p = cli_profile();
        let i = cli_intent();
        let mp = render(&p, &i).unwrap()[0].contents.clone();
        let v: serde_json::Value = serde_json::from_str(&mp).unwrap();
        assert_eq!(v["plugins"][0]["source"], "./");
        assert_eq!(v["plugins"][0]["name"], "chronicle");
    }

    #[test]
    fn rendered_plugin_json_has_kebab_name_and_license() {
        let p = cli_profile();
        let i = cli_intent();
        let pj = render(&p, &i).unwrap()[1].contents.clone();
        let v: serde_json::Value = serde_json::from_str(&pj).unwrap();
        assert_eq!(v["name"], "chronicle");
        assert_eq!(v["license"], "MIT");
    }

    #[test]
    fn skill_md_has_description_and_when_to_use_in_frontmatter() {
        let p = cli_profile();
        let i = cli_intent();
        let skill = render(&p, &i).unwrap()[2].contents.clone();
        assert!(skill.starts_with("---\n"));
        // description holds the one-liner only; when_to_use carries the triggers.
        assert!(skill.contains("description: \"Journal events to a chronological log\""));
        assert!(skill.contains("when_to_use: \"log a journal entry, record an incident\""));
    }

    #[test]
    fn pure_library_renders_import_pattern_not_cli() {
        let mut p = cli_profile();
        p.has_cli = false;
        p.cli_command = None;
        p.cli_help_output = None;
        let i = Intent {
            one_line_description: "Parse CSV files fast".into(),
            when_to_use_phrases: vec!["ingest csv".into()],
            invocation_command: None,
            import_pattern: Some("import { parse } from 'fastcsv'".into()),
            author: None,
            license: Some("MIT".into()),
        };
        let files = render(&p, &i).unwrap();
        let skill = &files[2].contents;
        assert!(skill.contains("import { parse } from 'fastcsv'"));
        assert!(!skill.contains("Invocation"));
    }

    #[test]
    fn coerce_kebab_handles_messy_names() {
        assert_eq!(coerce_kebab("My Cool Tool"), "my-cool-tool");
        assert_eq!(coerce_kebab("foo__bar--baz"), "foo-bar-baz");
        assert_eq!(coerce_kebab("UPPER_CASE"), "upper-case");
        assert_eq!(coerce_kebab("a"), "a");
        assert_eq!(coerce_kebab("!!!"), "tool");
        // Leading digits must be stripped — the schema regex `^[a-z]`
        // requires a letter first, so "123foo" → "foo", not "123foo".
        assert_eq!(coerce_kebab("123foo"), "foo");
        assert_eq!(coerce_kebab("123-foo"), "foo");
        // All-digits → fallback, not an empty string.
        assert_eq!(coerce_kebab("123"), "tool");
        assert_eq!(coerce_kebab("9"), "tool");
    }

    #[test]
    fn idempotent_byte_identical_renders() {
        let p = cli_profile();
        let i = cli_intent();
        let a = render(&p, &i).unwrap();
        let b = render(&p, &i).unwrap();
        for (x, y) in a.iter().zip(b.iter()) {
            assert_eq!(x.contents, y.contents);
        }
    }

    // Bug 1: empty when_to_use_phrases must NOT emit a "(unspecified)"
    // placeholder that bypasses verify's emptiness warning. The frontmatter
    // should carry an empty when_to_use so the discovery check fires honestly.
    #[test]
    fn empty_when_to_use_emits_empty_not_placeholder() {
        let mut p = cli_profile();
        p.has_cli = false;
        p.cli_command = None;
        p.cli_help_output = None;
        let i = Intent {
            one_line_description: "Do a thing".into(),
            when_to_use_phrases: vec![],
            invocation_command: None,
            import_pattern: Some("import { x } from 'y'".into()),
            author: None,
            license: Some("MIT".into()),
        };
        let skill = render(&p, &i).unwrap()[2].contents.clone();
        assert!(
            skill.contains("when_to_use: \"\""),
            "empty phrases must yield when_to_use: \"\", got:\n{skill}"
        );
        assert!(
            !skill.contains("(unspecified)"),
            "the placeholder must not leak into the skill, got:\n{skill}"
        );
    }
}