skillpack 0.13.1

Generate, verify, and maintain AI agent guidance (skills, plugins, AGENTS.md) for Claude Code, Cursor, Codex, Copilot, and 10+ AI coding ecosystems — one command turns any CLI or library into an agent-discoverable skill pack.
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
//! Generate the three distribution files from a [`ProjectProfile`] + [`Intent`]
//! via Tera templates. Pure (no disk writes here): returns [`GeneratedFileOutput`]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::{bail, Context, Result};
use once_cell::sync::Lazy;
use std::path::Path;
use tera::{Context as TeraContext, Tera};

use crate::cli::Target;
use crate::types::{Intent, Language, ProjectProfile, SubcommandNode};
use crate::verify::schema;

/// 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");
const AGENTS_MD_TPL: &str = include_str!("../templates/AGENTS.md.tera");
const CLAUDE_MD_TPL: &str = include_str!("../templates/CLAUDE.md.tera");
const GEMINI_MD_TPL: &str = include_str!("../templates/GEMINI.md.tera");
const CONVENTIONS_MD_TPL: &str = include_str!("../templates/CONVENTIONS.md.tera");
const WINDSURF_RULE_TPL: &str = include_str!("../templates/windsurf-rule.md.tera");
const SKILL_BODY_TPL: &str = include_str!("../templates/skill_body.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("skill_body_partial", SKILL_BODY_TPL)
        .expect("skill body partial template is valid");
    tera.add_raw_template("copilot-instructions.md", COPILOT_INSTRUCTIONS_TPL)
        .expect("copilot instructions template is valid");
    tera.add_raw_template("AGENTS.md", AGENTS_MD_TPL)
        .expect("AGENTS.md template is valid");
    tera.add_raw_template("CLAUDE.md", CLAUDE_MD_TPL)
        .expect("CLAUDE.md template is valid");
    tera.add_raw_template("GEMINI.md", GEMINI_MD_TPL)
        .expect("GEMINI.md template is valid");
    tera.add_raw_template("CONVENTIONS.md", CONVENTIONS_MD_TPL)
        .expect("CONVENTIONS.md template is valid");
    tera.add_raw_template("windsurf-rule.md", WINDSURF_RULE_TPL)
        .expect("windsurf rule template is valid");
    // json_encode is built into Tera; nothing custom to register.
    tera
});

/// The four files the Claude target emits, relative to the project root.
/// Documented for external tooling/tests; the renderer computes paths itself.
#[allow(dead_code)]
pub const OUTPUT_PATHS: [&str; 4] = [
    ".claude-plugin/marketplace.json",
    ".claude-plugin/plugin.json",
    "skills/<tool>/SKILL.md",
    ".claude/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: intent
            .keywords
            .clone()
            .unwrap_or_else(|| 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. `fd`, not the crate name `fd-find`). Derive from the actual CLI
    // command argv (the built binary path) so a `[[bin]].name` rename surfaces
    // in the invocation prose. Falls back to the skill `name` for libraries.
    let cli_binary = profile
        .cli_command
        .as_ref()
        .and_then(|c| c.first())
        .and_then(|cmd| {
            std::path::Path::new(cmd)
                .file_stem()
                .and_then(|s| s.to_str())
                .map(|s| s.to_string())
        })
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| 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), flattened pre-order
    // with a per-node indent so the template renders nested bullets from a
    // flat list (Tera has no recursive macros). 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> =
        flatten_subcommands(&profile.cli_subcommand_tree)
            .into_iter()
            .map(|(name, help, depth)| {
                // 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,
                    // Two spaces per depth — matches the template's nested-bullet
                    // indentation and verify's indentation-aware parser.
                    "indent": "  ".repeat(depth),
                })
            })
            .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(", ");

    // `homepage` is the human-facing URL (`.git` suffix stripped, SSH
    // normalized to https); `repo_url` stays the raw git-clone URL for the
    // `repository` field. The URL-drift check compares both against the git
    // origin via `urls_equivalent` (which normalizes), so they stay in sync.
    let homepage = profile
        .repo_url
        .as_deref()
        .map(crate::introspect::normalize_git_url)
        .unwrap_or_default();

    // Derived-field overrides (skillpack.toml) — power users can pin the
    // otherwise language-derived values. Each falls back to the language hint
    // when the config omits it, so existing packs render byte-identically.
    let category = intent
        .category
        .clone()
        .unwrap_or_else(|| category_hint(profile.language).to_string());
    let allowed_tools = intent
        .allowed_tools
        .clone()
        .or_else(|| allowed_tools_hint(profile.language).map(str::to_string));
    let globs_list = intent
        .globs
        .clone()
        .unwrap_or_else(|| cursor_globs_hint(profile.language));
    let globs_yaml = globs_to_yaml(&globs_list);
    let opencode_mode = intent
        .opencode_mode
        .clone()
        .unwrap_or_else(|| opencode_mode_hint(profile.language).to_string());

    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,
        "homepage": homepage,
        "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,
        "allowed_tools": allowed_tools,
        "globs": globs_yaml,
        "opencode_mode": opencode_mode,
        "footguns": &intent.footguns,
    }))
    .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, and normalize carriage returns and newlines
/// to spaces so the scalar stays clean on a single line.
fn escape_yaml(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\r', "")
        .replace('\n', " ")
}

/// 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 the Claude distribution files and returns them with their
/// root-relative paths. The skill path uses the kebab name, emitted at BOTH
/// the plugin path (`skills/<name>/SKILL.md`) and the native Claude Code path
/// (`.claude/skills/<name>/SKILL.md`) — same content, two directories.
pub fn render(
    profile: &ProjectProfile,
    intent: &Intent,
    template_dir: Option<&Path>,
) -> Result<Vec<GeneratedFileOutput>> {
    let tera = build_tera(template_dir)?;
    let mut ctx = build_context(profile, intent);
    ctx.insert("noun", "skill");
    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.clone(),
        },
        GeneratedFileOutput {
            rel_path: format!(".claude/skills/{name}/SKILL.md"),
            contents: skill,
        },
    ])
}
pub fn render_targets(
    profile: &ProjectProfile,
    intent: &Intent,
    targets: &[Target],
    template_dir: Option<&Path>,
) -> Result<Vec<GeneratedFileOutput>> {
    let tera = build_tera(template_dir)?;
    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;
        }
        out.extend(render_one_target(&tera, &ctx, target, &name)?);
    }
    Ok(out)
}

/// Render every distribution file for a multi-skill pack. The FIRST skill is
/// the primary: it feeds the pack-level files (marketplace.json, plugin.json,
/// copilot-instructions.md, AGENTS.md) and its own skill file. Every
/// additional skill renders only its per-skill file — `skills/<name>/SKILL.md`
/// (Claude + Codex), `.cursor/rules/<name>.mdc`, `.opencode/agents/<name>.md`
/// — under its own directory name. Copilot/AGENTS.md have no per-skill form
/// (single instructions file per repo).
///
/// A single-skill pack renders exactly what [`render_targets`] produces
/// (the primary's name/dir drive every path), so `update`/`diff` behave
/// identically for existing configs.
pub fn render_all(
    profile: &ProjectProfile,
    skills: &[(String, Intent)],
    targets: &[Target],
    template_dir: Option<&Path>,
) -> Result<Vec<GeneratedFileOutput>> {
    if skills.is_empty() {
        bail!("cannot render an empty skill list (no [skill]/[[skills]] entries)");
    }
    let tera = build_tera(template_dir)?;
    let mut out = Vec::new();
    let (primary_name, primary_intent) = &skills[0];
    let primary_ctx = build_context(profile, primary_intent);
    let primary_dir = coerce_kebab(primary_name);

    let mut seen = std::collections::HashSet::new();
    for &target in targets {
        if !seen.insert(target) {
            continue;
        }
        // Pack-level files + the primary skill's file, from the primary intent.
        out.extend(render_one_target(
            &tera,
            &primary_ctx,
            target,
            &primary_dir,
        )?);
        // Each additional skill contributes only its per-skill file. The
        // context's `name` must be overridden to the SKILL's name — the
        // build_context default is the pack name, which would put the primary
        // skill's `name:` in every additional skill's frontmatter (and trip
        // verify's dir_name_mismatch check).
        for (skill_name, intent) in &skills[1..] {
            let mut ctx = build_context(profile, intent);
            let dir = coerce_kebab(skill_name);
            ctx.insert("name", &dir);
            out.extend(render_skill_file_only(&tera, &ctx, target, &dir)?);
        }
    }
    Ok(out)
}

/// Render the full file set for one target from one skill context. The
/// Claude arm emits the pack-level pair + the skill file; other targets emit
/// their single file. `name` is the skill directory name for the per-skill
/// rel-path.
fn render_one_target(
    tera: &tera::Tera,
    ctx: &tera::Context,
    target: Target,
    name: &str,
) -> Result<Vec<GeneratedFileOutput>> {
    let mut out = Vec::new();
    match target {
        Target::Claude => {
            // Inline the four-file Claude render so we reuse the `tera`
            // built above — `render()` would rebuild it (and re-derive
            // the context) for no reason. Output order matches `render()`:
            // marketplace, plugin, skills/<name>/SKILL.md, and the native
            // .claude/skills/<name>/SKILL.md.
            let mut c = ctx.clone();
            c.insert("noun", "skill");
            let marketplace = tera
                .render("marketplace.json", &c)
                .context("rendering marketplace.json")?;
            let plugin = tera
                .render("plugin.json", &c)
                .context("rendering plugin.json")?;
            let skill = tera.render("SKILL.md", &c).context("rendering SKILL.md")?;
            out.push(GeneratedFileOutput {
                rel_path: ".claude-plugin/marketplace.json".to_string(),
                contents: marketplace,
            });
            out.push(GeneratedFileOutput {
                rel_path: ".claude-plugin/plugin.json".to_string(),
                contents: plugin,
            });
            out.push(GeneratedFileOutput {
                rel_path: format!("skills/{name}/SKILL.md"),
                contents: skill.clone(),
            });
            out.push(GeneratedFileOutput {
                rel_path: format!(".claude/skills/{name}/SKILL.md"),
                contents: skill,
            });
        }
        Target::Cursor => {
            let mut c = ctx.clone();
            c.insert("noun", "rule");
            let mdc = tera
                .render("cursor-rule.mdc", &c)
                .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 mut c = ctx.clone();
            c.insert("noun", "skill");
            let skill = tera
                .render("SKILL.md", &c)
                .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 mut c = ctx.clone();
            c.insert("noun", "agent");
            let agent = tera
                .render("opencode-agent.md", &c)
                .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 mut c = ctx.clone();
            c.insert("noun", "tool");
            let instr = tera
                .render("copilot-instructions.md", &c)
                .context("rendering copilot-instructions.md")?;
            out.push(GeneratedFileOutput {
                rel_path: ".github/copilot-instructions.md".to_string(),
                contents: instr,
            });
        }
        Target::AgentsMd => {
            // AGENTS.md: root-level instructions file, plain markdown, no
            // frontmatter. Per agents.md (Linux Foundation stewarded) —
            // read natively by 60k+ projects' agents.
            let mut c = ctx.clone();
            c.insert("noun", "tool");
            let agents = tera
                .render("AGENTS.md", &c)
                .context("rendering AGENTS.md")?;
            out.push(GeneratedFileOutput {
                rel_path: schema::AGENTS_MD_PATH.to_string(),
                contents: agents,
            });
        }
        Target::ClaudeMd => {
            // CLAUDE.md: root-level instructions file read by Claude Code,
            // Cline, Roo Code. Plain markdown — same body as AGENTS.md.
            let mut c = ctx.clone();
            c.insert("noun", "tool");
            let claude_md = tera
                .render("CLAUDE.md", &c)
                .context("rendering CLAUDE.md")?;
            out.push(GeneratedFileOutput {
                rel_path: schema::CLAUDE_MD_PATH.to_string(),
                contents: claude_md,
            });
        }
        Target::Gemini => {
            // GEMINI.md: root-level instructions file read natively by the
            // Gemini CLI. Plain markdown.
            let mut c = ctx.clone();
            c.insert("noun", "tool");
            let gemini = tera
                .render("GEMINI.md", &c)
                .context("rendering GEMINI.md")?;
            out.push(GeneratedFileOutput {
                rel_path: schema::GEMINI_MD_PATH.to_string(),
                contents: gemini,
            });
        }
        Target::Windsurf => {
            // Windsurf (Cascade) rules: `.windsurf/rules/<name>.md` with
            // the same frontmatter as Cursor rules.
            let mut c = ctx.clone();
            c.insert("noun", "rule");
            let rule = tera
                .render("windsurf-rule.md", &c)
                .context("rendering windsurf-rule.md")?;
            out.push(GeneratedFileOutput {
                rel_path: format!(".windsurf/rules/{name}.md"),
                contents: rule,
            });
        }
        Target::Aider => {
            // CONVENTIONS.md: root-level conventions file read by aider.
            // Plain markdown.
            let mut c = ctx.clone();
            c.insert("noun", "tool");
            let conventions = tera
                .render("CONVENTIONS.md", &c)
                .context("rendering CONVENTIONS.md")?;
            out.push(GeneratedFileOutput {
                rel_path: schema::CONVENTIONS_MD_PATH.to_string(),
                contents: conventions,
            });
        }
        Target::Cline => {
            // Cline workspace rules: `.clinerules/<name>.md`, plain markdown
            // (no frontmatter → always active). Per docs.cline.bot.
            let mut c = ctx.clone();
            c.insert("noun", "rule");
            let rule = tera
                .render("CLAUDE.md", &c)
                .context("rendering cline rule")?;
            out.push(GeneratedFileOutput {
                rel_path: format!(".clinerules/{name}.md"),
                contents: rule,
            });
        }
        Target::Roo => {
            // Roo Code workspace rules: `.roo/rules/<name>.md`, plain markdown.
            let mut c = ctx.clone();
            c.insert("noun", "rule");
            let rule = tera.render("CLAUDE.md", &c).context("rendering roo rule")?;
            out.push(GeneratedFileOutput {
                rel_path: format!(".roo/rules/{name}.md"),
                contents: rule,
            });
        }
        Target::Kilo => {
            // Kilo Code rules: `.kilocode/rules/<name>.md`, plain markdown,
            // auto-included via the backward-compatible directory.
            let mut c = ctx.clone();
            c.insert("noun", "rule");
            let rule = tera
                .render("CLAUDE.md", &c)
                .context("rendering kilo rule")?;
            out.push(GeneratedFileOutput {
                rel_path: format!(".kilocode/rules/{name}.md"),
                contents: rule,
            });
        }
        Target::Goose => {
            // Goose: `.goose/instructions.md`, root-level plain markdown.
            let mut c = ctx.clone();
            c.insert("noun", "tool");
            let instructions = tera
                .render("CLAUDE.md", &c)
                .context("rendering goose instructions")?;
            out.push(GeneratedFileOutput {
                rel_path: schema::GOOSE_INSTRUCTIONS_PATH.to_string(),
                contents: instructions,
            });
        }
    }
    Ok(out)
}

/// Render the per-skill file(s) for one target from one skill context — the
/// file(s) a multi-skill pack emits for every additional skill. Returns an
/// empty vec for targets without a per-skill form (Copilot and AGENTS.md are
/// single instructions files per repo, not per skill).
fn render_skill_file_only(
    tera: &tera::Tera,
    ctx: &tera::Context,
    target: Target,
    name: &str,
) -> Result<Vec<GeneratedFileOutput>> {
    match target {
        Target::Claude | Target::Codex => {
            let mut c = ctx.clone();
            c.insert("noun", "skill");
            let skill = tera.render("SKILL.md", &c).context("rendering SKILL.md")?;
            let mut out = Vec::new();
            if target == Target::Claude {
                out.push(GeneratedFileOutput {
                    rel_path: format!("skills/{name}/SKILL.md"),
                    contents: skill.clone(),
                });
                out.push(GeneratedFileOutput {
                    rel_path: format!(".claude/skills/{name}/SKILL.md"),
                    contents: skill,
                });
            } else {
                out.push(GeneratedFileOutput {
                    rel_path: format!(".codex/skills/{name}/SKILL.md"),
                    contents: skill,
                });
            }
            Ok(out)
        }
        Target::Cursor => {
            let mut c = ctx.clone();
            c.insert("noun", "rule");
            let mdc = tera
                .render("cursor-rule.mdc", &c)
                .context("rendering cursor-rule.mdc")?;
            Ok(vec![GeneratedFileOutput {
                rel_path: format!(".cursor/rules/{name}.mdc"),
                contents: mdc,
            }])
        }
        Target::Windsurf => {
            let mut c = ctx.clone();
            c.insert("noun", "rule");
            let rule = tera
                .render("windsurf-rule.md", &c)
                .context("rendering windsurf-rule.md")?;
            Ok(vec![GeneratedFileOutput {
                rel_path: format!(".windsurf/rules/{name}.md"),
                contents: rule,
            }])
        }
        Target::OpenCode => {
            let mut c = ctx.clone();
            c.insert("noun", "agent");
            let agent = tera
                .render("opencode-agent.md", &c)
                .context("rendering opencode-agent.md")?;
            Ok(vec![GeneratedFileOutput {
                rel_path: format!(".opencode/agents/{name}.md"),
                contents: agent,
            }])
        }
        Target::Cline | Target::Roo | Target::Kilo => {
            let mut c = ctx.clone();
            c.insert("noun", "rule");
            let rule = tera
                .render("CLAUDE.md", &c)
                .context("rendering rule file")?;
            let rel_path = match target {
                Target::Cline => format!(".clinerules/{name}.md"),
                Target::Roo => format!(".roo/rules/{name}.md"),
                _ => format!(".kilocode/rules/{name}.md"),
            };
            Ok(vec![GeneratedFileOutput {
                rel_path,
                contents: rule,
            }])
        }
        Target::Copilot
        | Target::AgentsMd
        | Target::ClaudeMd
        | Target::Gemini
        | Target::Aider
        | Target::Goose => Ok(Vec::new()),
    }
}

/// Map `.tera` filenames → embedded Tera template names.
/// Most are identity after stripping `.tera`; the two exceptions are
/// `skill_body.md.tera` → `skill_body_partial` (a shared partial)
/// and the `.mdc` file → `cursor-rule.mdc`.
const TEMPLATE_MAP: &[(&str, &str)] = &[
    ("marketplace.json.tera", "marketplace.json"),
    ("plugin.json.tera", "plugin.json"),
    ("SKILL.md.tera", "SKILL.md"),
    ("cursor-rule.mdc.tera", "cursor-rule.mdc"),
    ("opencode-agent.md.tera", "opencode-agent.md"),
    ("copilot-instructions.md.tera", "copilot-instructions.md"),
    ("AGENTS.md.tera", "AGENTS.md"),
    ("CLAUDE.md.tera", "CLAUDE.md"),
    ("GEMINI.md.tera", "GEMINI.md"),
    ("CONVENTIONS.md.tera", "CONVENTIONS.md"),
    ("windsurf-rule.md.tera", "windsurf-rule.md"),
    ("skill_body.md.tera", "skill_body_partial"),
];

/// Build a `Tera` instance, optionally overriding embedded templates from
/// a directory of `.tera` files. Missing templates fall back to the embedded
/// defaults — a user can override just one or two templates without
/// re-declaring the others. Template names must match the `.tera` filenames
/// in `templates/` (see `TEMPLATE_MAP`).
fn build_tera(template_dir: Option<&Path>) -> Result<Tera> {
    let Some(dir) = template_dir else {
        return Ok(TERA.clone());
    };
    let mut tera = Tera::clone(&*TERA);
    for (filename, internal_name) in TEMPLATE_MAP {
        let path = dir.join(filename);
        if let Ok(src) = std::fs::read_to_string(&path) {
            tera.add_raw_template(internal_name, &src)
                .map_err(|e| anyhow::anyhow!("failed to load template {filename}: {e}"))?;
        }
    }
    Ok(tera)
}

// ----- 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>,
}

/// Pre-order flatten of the subcommand tree, carrying each node's depth so the
/// template can render nested bullets from a flat list (Tera has no recursive
/// macros). Declaration order is preserved at every level, so snapshots stay
/// deterministic.
fn flatten_subcommands(nodes: &[SubcommandNode]) -> Vec<(String, String, usize)> {
    fn walk(nodes: &[SubcommandNode], depth: usize, out: &mut Vec<(String, String, usize)>) {
        for n in nodes {
            out.push((n.name.clone(), n.help.clone(), depth));
            walk(&n.children, depth + 1, out);
        }
    }
    let mut out = Vec::new();
    walk(nodes, 0, &mut out);
    out
}

/// Recursively collect every subcommand name (declaration order) for the
/// marketplace keyword list.
fn collect_subcommand_names(nodes: &[SubcommandNode], out: &mut Vec<String>) {
    for n in nodes {
        out.push(n.name.clone());
        collect_subcommand_names(&n.children, out);
    }
}

/// Derive a small, stable keyword list from language + intent + CLI surface
/// so the generated marketplace entry is discoverable without the maintainer
/// hand-curating it. Always seeded with language + cli/library, then enriched:
///   - all trigger-phrase first-words (deduped)
///   - CLI subcommand NAMES (from the subcommand tree) — high-signal verbs
///     like `init`, `verify`, `doctor` that a marketplace searcher would type
///   - one content word from the README `description_hint` (longest non-stopword)
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());
    }

    // All trigger-phrase first-words (deduped, lowercased, alphanumeric only).
    for phrase in &intent.when_to_use_phrases {
        if let Some(word) = phrase.split_whitespace().next().map(|w| {
            w.trim_matches(|c: char| !c.is_alphanumeric())
                .to_lowercase()
        }) {
            if !word.is_empty() && !kws.contains(&word) {
                kws.push(word);
            }
        }
    }

    // CLI subcommand NAMES (recursively) — high-signal marketplace keywords.
    let mut names = Vec::new();
    collect_subcommand_names(&profile.cli_subcommand_tree, &mut names);
    for name in names {
        let sub = name.to_lowercase();
        if !sub.is_empty() && !kws.contains(&sub) {
            kws.push(sub);
        }
    }

    // One content word from the README description_hint — the longest non-stopword.
    if let Some(hint) = &profile.description_hint {
        let best = hint
            .split_whitespace()
            .map(|w| w.trim_matches(|c: char| !c.is_alphanumeric()))
            .filter(|w| w.len() > 4 && w.chars().all(|c| c.is_alphanumeric()) && !is_stopword(w))
            .max_by_key(|w| w.len());
        if let Some(w) = best {
            let w = w.to_lowercase();
            if !w.is_empty() && !kws.contains(&w) {
                kws.push(w);
            }
        }
    }

    kws
}

/// Tiny stopword set for keyword extraction. Keeps "generate" but drops
/// "this", "with", "about". Ponytail: inline set beats pulling a crate.
fn is_stopword(w: &str) -> bool {
    matches!(
        w.to_lowercase().as_str(),
        "the"
            | "this"
            | "that"
            | "with"
            | "from"
            | "about"
            | "your"
            | "have"
            | "will"
            | "they"
            | "them"
            | "their"
            | "what"
            | "when"
            | "which"
            | "would"
            | "could"
            | "should"
            | "into"
            | "onto"
            | "over"
            | "under"
            | "also"
            | "just"
            | "only"
            | "than"
            | "then"
            | "these"
            | "those"
            | "using"
            | "being"
            | "been"
            | "more"
            | "most"
            | "such"
            | "some"
    )
}

fn category_hint(lang: Language) -> &'static str {
    match lang {
        Language::Rust => "the Rust tooling",
        Language::Node => "the JavaScript/Node tooling",
        Language::Python => "the Python tooling",
        Language::Go => "the Go tooling",
        Language::Ruby => "the Ruby tooling",
        Language::Php => "the PHP tooling",
        Language::Jvm => "the JVM tooling",
        Language::CSharp => "the .NET/C# tooling",
        Language::Zig => "the Zig tooling",
        Language::Swift => "the Swift tooling",
        Language::CCpp => "the C/C++ tooling",
        Language::Elixir => "the Elixir tooling",
        Language::Deno => "the Deno tooling",
        Language::Unknown => "the tooling",
    }
}

fn allowed_tools_hint(lang: 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. Comma-
    // separated per the Anthropic `allowed-tools` grammar (matches
    // `verify`'s discovery.skill.allowed_tools grammar check).
    if let Language::Unknown = lang {
        None
    } else {
        Some("Read, Bash")
    }
}

/// Cursor auto-attach is driven by `globs` (file-pattern match) OR
/// `alwaysApply: true`. With neither, generated rules won't auto-trigger.
/// Derive glob patterns from the detected language so the rule activates on
/// the relevant files. Empty for Unknown — the maintainer should curate.
fn cursor_globs_hint(lang: Language) -> Vec<String> {
    match lang {
        Language::Rust => vec!["*.rs".into()],
        Language::Node => vec![
            "*.js".into(),
            "*.ts".into(),
            "*.jsx".into(),
            "*.tsx".into(),
            "package.json".into(),
        ],
        Language::Python => vec!["*.py".into()],
        Language::Go => vec!["*.go".into(), "go.mod".into()],
        Language::Ruby => vec!["*.rb".into(), "*.gemspec".into(), "Gemfile".into()],
        Language::Php => vec!["*.php".into(), "composer.json".into()],
        Language::Jvm => vec![
            "*.java".into(),
            "*.kt".into(),
            "*.scala".into(),
            "pom.xml".into(),
            "build.gradle".into(),
            "build.gradle.kts".into(),
        ],
        Language::CSharp => vec!["*.cs".into(), "*.csproj".into(), "*.sln".into()],
        Language::Zig => vec!["*.zig".into(), "build.zig".into(), "build.zig.zon".into()],
        Language::Swift => vec!["*.swift".into(), "Package.swift".into()],
        Language::CCpp => vec![
            "*.c".into(),
            "*.cpp".into(),
            "*.cc".into(),
            "*.h".into(),
            "*.hpp".into(),
            "CMakeLists.txt".into(),
            "Makefile".into(),
        ],
        Language::Elixir => vec!["*.ex".into(), "*.exs".into(), "mix.exs".into()],
        Language::Deno => vec![
            "*.ts".into(),
            "*.js".into(),
            "deno.json".into(),
            "deno.jsonc".into(),
        ],
        Language::Unknown => vec![],
    }
}

/// Format a glob list as a YAML flow-sequence string with quoted entries:
/// `"*.rs", "*.go"`. Empty vec → empty string (template's `{% if globs %}`
/// gates the line). The template wraps with `globs: [{{ globs }}]` →
/// `globs: ["*.rs"]`.
fn globs_to_yaml(globs: &[String]) -> String {
    globs
        .iter()
        .map(|g| format!("\"{g}\""))
        .collect::<Vec<_>>()
        .join(", ")
}

/// OpenCode `mode` frontmatter: `primary` for CLI tools (standalone agent),
/// `subagent` for pure libraries (invoked by a parent agent). Conservative
/// default `subagent` for Unknown since the maintainer should confirm.
fn opencode_mode_hint(lang: Language) -> &'static str {
    if let Language::Unknown = lang {
        "subagent"
    } else {
        "primary"
    }
}

/// 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 repeatedly strip leading digits and
    // hyphens: the schema regex `^[a-z]...` requires the name to start with a
    // letter, so numeric prefixes like "123foo" or "123-456-foo" → "foo"
    // (not "456-foo", which would fail verify's own `is_valid_kebab` check).
    let mut s = out.trim_matches('-');
    while let Some(first) = s.chars().next() {
        if first.is_ascii_digit() || first == '-' {
            s = s.trim_start_matches(|c: char| c.is_ascii_digit() || c == '-');
        } else {
            break;
        }
    }
    let s = s.trim_matches('-');
    if s.is_empty() || !s.chars().next().unwrap().is_ascii_alphabetic() {
        return "tool".to_string();
    }
    s.to_string()
}

/// Output path + rendered contents, root-relative.
#[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_tree = 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()),
            ..Default::default()
        }
    }

    #[test]
    fn renders_four_files_with_valid_paths() {
        let p = cli_profile();
        let i = cli_intent();
        let files = render(&p, &i, None).unwrap();
        assert_eq!(files.len(), 4);
        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");
        assert_eq!(files[3].rel_path, ".claude/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, None).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, None).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, None).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()),
            license: Some("MIT".into()),
            ..Default::default()
        };
        let files = render(&p, &i, None).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");
        assert_eq!(coerce_kebab("123-456-tool"), "tool");
        assert_eq!(coerce_kebab("123-456-foo-bar"), "foo-bar");
        // All-digits → fallback, not an empty string.
        assert_eq!(coerce_kebab("123"), "tool");
        assert_eq!(coerce_kebab("123-456"), "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, None).unwrap();
        let b = render(&p, &i, None).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()),
            license: Some("MIT".into()),
            ..Default::default()
        };
        let skill = render(&p, &i, None).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}"
        );
    }
    // Bug: non-interactive `init` replay from a skillpack.toml that omits
    // `invocation_command` (elided by `skip_serializing_if = "Option::is_none"`)
    // produced an empty fenced invocation block — the template rendered
    // `{{ invocation_command }}` as the empty string for a CLI project. The
    // template's `default(value=cli_binary)` falls back to the bare binary
    // name derived from `cli_command` (e.g. `chronicle`), so agents see a
    // runnable command instead of empty ticks.
    #[test]
    fn invocation_block_falls_back_to_cli_binary_when_intent_omits_command() {
        let p = cli_profile(); // has_cli=true, cli_command=["chronicle","--help"]
        let mut i = cli_intent();
        i.invocation_command = None; // simulates config replay without the field
        let skill = render(&p, &i, None).unwrap()[2].contents.clone();
        assert!(
            skill.contains("## Invocation"),
            "CLI project must still emit an Invocation section, got:\n{skill}"
        );
        // The fenced block must contain the bare binary name, not be empty.
        assert!(
            skill.contains("```\nchronicle\n```"),
            "invocation block must fall back to cli_binary `chronicle`, got:\n{skill}"
        );
    }

    // Multi-skill: render_all emits the pack-level files once (from the
    // primary) and a per-skill file for EVERY skill under its own directory
    // name — with the skill's OWN name/description in the frontmatter, not
    // the pack's.
    #[test]
    fn render_all_emits_every_skill_under_its_own_name() {
        let p = cli_profile();
        let side_intent = Intent {
            one_line_description: "Handle auxiliary chores".into(),
            when_to_use_phrases: vec!["aux task".into()],
            invocation_command: Some("chronicle aux".into()),
            import_pattern: None,
            author: None,
            license: None,
            ..Default::default()
        };
        let skills = vec![
            ("chronicle".to_string(), cli_intent()),
            ("sidekick".to_string(), side_intent),
        ];
        let targets = vec![
            Target::Claude,
            Target::Cursor,
            Target::Codex,
            Target::OpenCode,
            Target::Copilot,
            Target::AgentsMd,
        ];
        let files = render_all(&p, &skills, &targets, None).unwrap();

        // Pack-level files appear exactly once.
        let mp_count = files
            .iter()
            .filter(|f| f.rel_path == ".claude-plugin/marketplace.json")
            .count();
        let ag_count = files.iter().filter(|f| f.rel_path == "AGENTS.md").count();
        assert_eq!(mp_count, 1, "marketplace.json is pack-level, emitted once");
        assert_eq!(ag_count, 1, "AGENTS.md is pack-level, emitted once");

        // Every skill has its own per-skill file, at BOTH the plugin path
        // and the native `.claude/skills/` path.
        for rel in [
            "skills/chronicle/SKILL.md",
            "skills/sidekick/SKILL.md",
            ".claude/skills/chronicle/SKILL.md",
            ".claude/skills/sidekick/SKILL.md",
            ".codex/skills/sidekick/SKILL.md",
            ".cursor/rules/sidekick.mdc",
            ".opencode/agents/sidekick.md",
        ] {
            assert!(
                files.iter().any(|f| f.rel_path == rel),
                "missing expected rel_path {rel}"
            );
        }

        // The secondary skill's frontmatter carries ITS name + description.
        let side = files
            .iter()
            .find(|f| f.rel_path == "skills/sidekick/SKILL.md")
            .unwrap();
        assert!(
            side.contents.contains("name: sidekick"),
            "secondary skill must use its own name, got:\n{}",
            side.contents
        );
        assert!(
            side.contents.contains("Handle auxiliary chores"),
            "secondary skill must use its own description, got:\n{}",
            side.contents
        );
        // The primary's skill keeps the pack name.
        let prim = files
            .iter()
            .find(|f| f.rel_path == "skills/chronicle/SKILL.md")
            .unwrap();
        assert!(prim.contents.contains("name: chronicle"));
    }

    /// An empty skill list must be a clean error, not an index-out-of-bounds
    /// panic (`&skills[0]`) that `main`'s catch_unwind would mask as a generic
    /// crash. Callers guard today, but this is a public API.
    #[test]
    fn render_all_rejects_empty_skill_list() {
        let p = cli_profile();
        let err = render_all(&p, &[], &[Target::Claude], None).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("empty skill list"),
            "expected a clear empty-skill error, got: {msg}"
        );
    }

    /// The four new rule/instructions targets (Cline, Roo, Kilo, Goose)
    /// render plain-markdown files at their native paths — no frontmatter.
    #[test]
    fn renders_new_rule_and_instructions_targets() {
        let p = cli_profile();
        let i = cli_intent();
        let files = render_targets(
            &p,
            &i,
            &[Target::Cline, Target::Roo, Target::Kilo, Target::Goose],
            None,
        )
        .unwrap();

        let cline = files
            .iter()
            .find(|f| f.rel_path == ".clinerules/chronicle.md")
            .unwrap();
        assert!(
            !cline.contents.trim_start().starts_with("---"),
            "Cline rule must be plain markdown, got:\n{}",
            cline.contents
        );
        assert!(cline.contents.starts_with("# chronicle"));
        assert!(cline.contents.contains("Invoke this rule when"));

        assert!(files
            .iter()
            .any(|f| f.rel_path == ".roo/rules/chronicle.md"));
        assert!(files
            .iter()
            .any(|f| f.rel_path == ".kilocode/rules/chronicle.md"));

        let goose = files
            .iter()
            .find(|f| f.rel_path == ".goose/instructions.md")
            .unwrap();
        assert!(!goose.contents.trim_start().starts_with("---"));
        assert!(goose.contents.starts_with("# chronicle"));
    }

    /// Derived fields (allowed-tools, globs, category, opencode mode,
    /// keywords) are overridable from the intent; the override wins over the
    /// language hint, and the fallback stays byte-identical when omitted.
    #[test]
    fn derived_field_overrides_win_over_language_hints() {
        let p = cli_profile();
        let mut i = cli_intent();
        i.allowed_tools = Some("Read, Bash(npm test:*)".into());
        i.globs = Some(vec!["src/**".into(), "*.md".into()]);
        i.category = Some("the data tooling".into());
        i.opencode_mode = Some("subagent".into());
        i.keywords = Some(vec!["journal".into(), "log".into()]);

        let skill = render(&p, &i, None).unwrap()[2].contents.clone();
        assert!(
            skill.contains("allowed-tools: Read, Bash(npm test:*)"),
            "allowed-tools override must win, got:\n{skill}"
        );
        assert!(
            skill.contains("the data tooling"),
            "category override must win, got:\n{skill}"
        );

        let mdc = render_targets(&p, &i, &[Target::Cursor], None).unwrap()[0]
            .contents
            .clone();
        assert!(
            mdc.contains("globs: [\"src/**\", \"*.md\"]"),
            "globs override must win, got:\n{mdc}"
        );

        let agent = render_targets(&p, &i, &[Target::OpenCode], None).unwrap()[0]
            .contents
            .clone();
        assert!(
            agent.contains("mode: subagent"),
            "opencode mode override must win, got:\n{agent}"
        );

        // Marketplace keywords override.
        let mp = render(&p, &i, None).unwrap()[0].contents.clone();
        assert!(
            mp.contains("\"journal\""),
            "keywords override must win, got:\n{mp}"
        );

        // The fallback (no override) still renders the language hint.
        let base = render(&p, &cli_intent(), None).unwrap()[2].contents.clone();
        assert!(base.contains("allowed-tools: Read, Bash"));
    }

    #[test]
    fn test_renders_custom_footguns_into_guidance() {
        let p = cli_profile();
        let mut intent = cli_intent();
        intent.footguns = vec![
            "Do not combine --max-results with -x (fd rejects this).".to_string(),
            "Flags like -e and -E are case-sensitive.".to_string(),
        ];
        let files = render_targets(&p, &intent, &[Target::Claude, Target::AgentsMd], None).unwrap();
        let agents = files.iter().find(|f| f.rel_path == "AGENTS.md").unwrap();
        assert!(agents
            .contents
            .contains("- Do not combine --max-results with -x (fd rejects this)."));
        assert!(agents
            .contents
            .contains("- Flags like -e and -E are case-sensitive."));
        assert!(agents
            .contents
            .contains("- Verify the tool is installed before relying on it"));
    }
}