agent-first-data 0.11.0

A naming convention that lets AI agents understand your data without being told what it means.
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
//! Reusable Agent Skill installer for spore CLIs.
//!
//! A spore that embeds its `SKILL.md` describes itself with a [`SkillSpec`] and calls
//! [`run_skill_admin`] to install, uninstall, or report status of that skill across supported
//! coding agents (Codex, Claude Code, opencode).
//!
//! The function performs the filesystem work and returns a typed [`SkillReport`] (the caller
//! serializes it for output) or a [`SkillError`]. It never writes to stdout/stderr itself.
//!
//! Requires the `skill-admin` feature.

use serde::Serialize;
use std::path::{Path, PathBuf};

const SKILL_FILE_NAME: &str = "SKILL.md";

/// Identity of the skill being managed and the tool that manages it.
///
/// `name` is both the skill directory name and the `name:` front-matter field. `source` is the
/// bundled `SKILL.md` (typically `include_str!`). `title` is a human label for error messages.
/// `marker_slug` seeds the managed-skill marker and the `Generated by <slug> skill install`
/// comment, and is referenced in hints (e.g. `afwidget`).
#[derive(Clone, Copy, Debug)]
pub struct SkillSpec<'a> {
    /// Skill directory name and front-matter `name` (e.g. `agent-first-widget`).
    pub name: &'a str,
    /// Bundled `SKILL.md` contents.
    pub source: &'a str,
    /// Human-readable skill title for error messages (e.g. `Agent-First Widget`).
    pub title: &'a str,
    /// Short tool slug used in the managed marker, generated-by comment, and hints (e.g. `afwidget`).
    pub marker_slug: &'a str,
}

/// Which agent target(s) to manage.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SkillAgentSelection {
    /// Every agent that supports the requested scope.
    All,
    /// Codex (personal scope only).
    Codex,
    /// Claude Code.
    ClaudeCode,
    /// opencode.
    Opencode,
}

/// A concrete agent a skill is installed for (no `All`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SkillAgent {
    /// Codex (`$CODEX_HOME/skills` or `~/.codex/skills`).
    Codex,
    /// Claude Code (`~/.claude/skills` or `.claude/skills`).
    ClaudeCode,
    /// opencode (`~/.config/opencode/skills` or `.opencode/skills`).
    Opencode,
}

/// Where to install the skill.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SkillScope {
    /// User-level skills directory.
    Personal,
    /// Current project's skills directory.
    Project,
}

/// Options shared by every skill action.
#[derive(Clone, Debug)]
pub struct SkillOptions {
    /// Agent target selection.
    pub agent: SkillAgentSelection,
    /// Skill scope.
    pub scope: SkillScope,
    /// Explicit skills directory; requires a single concrete `agent`.
    pub skills_dir: Option<String>,
    /// Overwrite or remove a skill that this tool did not manage.
    pub force: bool,
}

/// The skill action to perform.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SkillAction {
    /// Report whether the skill is installed, valid, managed, and current.
    Status,
    /// Install (or refresh) the skill.
    Install,
    /// Remove a managed skill.
    Uninstall,
}

/// Per-target outcome of `status` / `install`.
#[derive(Clone, Debug, Serialize)]
pub struct SkillTargetStatus {
    /// The agent this target belongs to.
    pub agent: SkillAgent,
    /// The scope this target belongs to.
    pub scope: SkillScope,
    /// Directory that holds skill folders.
    pub skills_dir: PathBuf,
    /// Full path to the target `SKILL.md`.
    pub skill_path: PathBuf,
    /// Whether a skill file exists at `skill_path`.
    pub installed: bool,
    /// Whether the installed file was generated by this tool (or is byte-equal to the bundle).
    pub managed: bool,
    /// Whether the installed file has valid front matter.
    pub valid: bool,
    /// Whether the installed content matches the bundled skill (up to date).
    pub current: bool,
    /// Front-matter validation error, when the installed file is invalid.
    pub validation_error: Option<String>,
}

/// Per-target outcome of `uninstall`.
#[derive(Clone, Debug, Serialize)]
pub struct SkillUninstallStatus {
    /// The agent this target belongs to.
    pub agent: SkillAgent,
    /// The scope this target belongs to.
    pub scope: SkillScope,
    /// Directory that holds skill folders.
    pub skills_dir: PathBuf,
    /// Full path to the target `SKILL.md`.
    pub skill_path: PathBuf,
    /// Whether a file was removed (false if nothing was installed).
    pub removed: bool,
}

/// The result of a skill action. Serializes to the protocol shape, carrying a `code`
/// discriminator (`skill_status` / `skill_install` / `skill_uninstall`).
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "code")]
pub enum SkillReport {
    /// `status` result.
    #[serde(rename = "skill_status")]
    Status {
        /// Skill name.
        skill: String,
        /// True when every target is installed.
        installed_all: bool,
        /// True when every target has valid front matter.
        valid_all: bool,
        /// True when every target is up to date with the bundle.
        current_all: bool,
        /// Per-target detail.
        targets: Vec<SkillTargetStatus>,
    },
    /// `install` result.
    #[serde(rename = "skill_install")]
    Install {
        /// Skill name.
        skill: String,
        /// Always true (install succeeded for every target).
        installed: bool,
        /// Per-target detail after writing.
        targets: Vec<SkillTargetStatus>,
        /// Operator hint.
        hint: &'static str,
    },
    /// `uninstall` result.
    #[serde(rename = "skill_uninstall")]
    Uninstall {
        /// Skill name.
        skill: String,
        /// True when at least one file was removed.
        removed_any: bool,
        /// Per-target detail.
        targets: Vec<SkillUninstallStatus>,
    },
}

/// A skill admin failure with an operator-facing message and optional hint.
#[derive(Clone, Debug)]
pub struct SkillError {
    /// What went wrong.
    pub message: String,
    /// Optional remediation hint.
    pub hint: Option<String>,
}

impl SkillError {
    fn invalid_request(message: String, hint: Option<String>) -> Self {
        Self { message, hint }
    }

    fn io(action: &str, err: std::io::Error) -> Self {
        Self {
            message: format!("{action} failed: {err}"),
            hint: None,
        }
    }
}

/// Install, uninstall, or report status of `spec`'s skill across the selected agent target(s).
///
/// Returns a typed [`SkillReport`] (caller serializes it for output) or a [`SkillError`].
/// Does not touch stdout/stderr.
pub fn run_skill_admin(
    spec: &SkillSpec,
    action: SkillAction,
    options: &SkillOptions,
) -> Result<SkillReport, SkillError> {
    match action {
        SkillAction::Status => status(spec, options),
        SkillAction::Install => install(spec, options),
        SkillAction::Uninstall => uninstall(spec, options),
    }
}

fn status(spec: &SkillSpec, options: &SkillOptions) -> Result<SkillReport, SkillError> {
    let targets = resolve_targets(spec, options)?;
    let mut statuses = Vec::with_capacity(targets.len());
    for target in &targets {
        statuses.push(target_status(spec, target)?);
    }
    Ok(SkillReport::Status {
        skill: spec.name.to_string(),
        installed_all: statuses.iter().all(|s| s.installed),
        valid_all: statuses.iter().all(|s| s.valid),
        current_all: statuses.iter().all(|s| s.current),
        targets: statuses,
    })
}

fn install(spec: &SkillSpec, options: &SkillOptions) -> Result<SkillReport, SkillError> {
    validate_skill_text(spec, spec.source)?;
    let targets = resolve_targets(spec, options)?;
    let content = managed_skill_contents(spec);
    let mut installed = Vec::with_capacity(targets.len());
    for target in &targets {
        std::fs::create_dir_all(&target.skill_dir)
            .map_err(|e| SkillError::io("create skill dir", e))?;
        if target.skill_path.exists()
            && !is_managed_or_bundled_skill(spec, &target.skill_path)?
            && !options.force
        {
            return Err(SkillError::invalid_request(
                format!(
                    "refusing to overwrite unmanaged skill at {}",
                    target.skill_path.display()
                ),
                Some("pass --force to replace it, or choose another --skills-dir".to_string()),
            ));
        }
        std::fs::write(&target.skill_path, &content)
            .map_err(|e| SkillError::io("write skill", e))?;
        validate_installed_skill(spec, &target.skill_path)?;
        installed.push(target_status(spec, target)?);
    }
    Ok(SkillReport::Install {
        skill: spec.name.to_string(),
        installed: true,
        targets: installed,
        hint: "restart the agent so it reloads installed skills",
    })
}

fn uninstall(spec: &SkillSpec, options: &SkillOptions) -> Result<SkillReport, SkillError> {
    let targets = resolve_targets(spec, options)?;
    let mut removed = Vec::with_capacity(targets.len());
    for target in &targets {
        if !target.skill_path.exists() {
            removed.push(target_uninstall_status(target, false));
            continue;
        }
        if !is_managed_or_bundled_skill(spec, &target.skill_path)? && !options.force {
            return Err(SkillError::invalid_request(
                format!(
                    "refusing to remove unmanaged skill at {}",
                    target.skill_path.display()
                ),
                Some(format!(
                    "only skills generated by {} skill install can be removed without --force",
                    spec.marker_slug
                )),
            ));
        }
        std::fs::remove_file(&target.skill_path).map_err(|e| SkillError::io("remove skill", e))?;
        let _ = std::fs::remove_dir(&target.skill_dir);
        removed.push(target_uninstall_status(target, true));
    }
    Ok(SkillReport::Uninstall {
        skill: spec.name.to_string(),
        removed_any: removed.iter().any(|s| s.removed),
        targets: removed,
    })
}

struct SkillTarget {
    agent: SkillAgent,
    scope: SkillScope,
    skills_dir: PathBuf,
    skill_dir: PathBuf,
    skill_path: PathBuf,
}

fn resolve_targets(
    spec: &SkillSpec,
    options: &SkillOptions,
) -> Result<Vec<SkillTarget>, SkillError> {
    if options.skills_dir.is_some() && options.agent == SkillAgentSelection::All {
        return Err(SkillError::invalid_request(
            "--skills-dir requires a single --agent".to_string(),
            Some("custom skills directories are ambiguous when --agent all is used".to_string()),
        ));
    }
    match (options.agent, options.scope) {
        (SkillAgentSelection::All, SkillScope::Personal) => Ok(vec![
            resolve_target(spec, SkillAgent::Codex, SkillScope::Personal, None)?,
            resolve_target(spec, SkillAgent::ClaudeCode, SkillScope::Personal, None)?,
            resolve_target(spec, SkillAgent::Opencode, SkillScope::Personal, None)?,
        ]),
        // Codex has no project scope, so --agent all --scope project skips it.
        (SkillAgentSelection::All, SkillScope::Project) => Ok(vec![
            resolve_target(spec, SkillAgent::ClaudeCode, SkillScope::Project, None)?,
            resolve_target(spec, SkillAgent::Opencode, SkillScope::Project, None)?,
        ]),
        (SkillAgentSelection::Codex, SkillScope::Project) => Err(SkillError::invalid_request(
            "Codex project skill scope is not supported".to_string(),
            Some(
                "use personal scope for Codex, or --agent claude-code/opencode --scope project"
                    .to_string(),
            ),
        )),
        (SkillAgentSelection::Codex, SkillScope::Personal) => Ok(vec![resolve_target(
            spec,
            SkillAgent::Codex,
            SkillScope::Personal,
            options.skills_dir.as_deref(),
        )?]),
        (SkillAgentSelection::ClaudeCode, scope) => Ok(vec![resolve_target(
            spec,
            SkillAgent::ClaudeCode,
            scope,
            options.skills_dir.as_deref(),
        )?]),
        (SkillAgentSelection::Opencode, scope) => Ok(vec![resolve_target(
            spec,
            SkillAgent::Opencode,
            scope,
            options.skills_dir.as_deref(),
        )?]),
    }
}

fn resolve_target(
    spec: &SkillSpec,
    agent: SkillAgent,
    scope: SkillScope,
    skills_dir: Option<&str>,
) -> Result<SkillTarget, SkillError> {
    let skills_dir = match skills_dir {
        Some(dir) => expand_tilde(dir)?,
        None => default_skills_dir(agent, scope)?,
    };
    let skill_dir = skills_dir.join(spec.name);
    let skill_path = skill_dir.join(SKILL_FILE_NAME);
    Ok(SkillTarget {
        agent,
        scope,
        skills_dir,
        skill_dir,
        skill_path,
    })
}

fn default_skills_dir(agent: SkillAgent, scope: SkillScope) -> Result<PathBuf, SkillError> {
    match (agent, scope) {
        (SkillAgent::Codex, SkillScope::Personal) => {
            if let Some(codex_home) = std::env::var_os("CODEX_HOME") {
                Ok(PathBuf::from(codex_home).join("skills"))
            } else {
                Ok(home_dir()?.join(".codex").join("skills"))
            }
        }
        (SkillAgent::Codex, SkillScope::Project) => Err(SkillError::invalid_request(
            "Codex project skill scope is not supported".to_string(),
            None,
        )),
        (SkillAgent::ClaudeCode, SkillScope::Personal) => {
            Ok(home_dir()?.join(".claude").join("skills"))
        }
        (SkillAgent::ClaudeCode, SkillScope::Project) => project_skills_dir(".claude"),
        (SkillAgent::Opencode, SkillScope::Personal) => {
            if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") {
                Ok(PathBuf::from(xdg).join("opencode").join("skills"))
            } else {
                Ok(home_dir()?.join(".config").join("opencode").join("skills"))
            }
        }
        (SkillAgent::Opencode, SkillScope::Project) => project_skills_dir(".opencode"),
    }
}

fn project_skills_dir(agent_dir: &str) -> Result<PathBuf, SkillError> {
    std::env::current_dir()
        .map(|dir| dir.join(agent_dir).join("skills"))
        .map_err(|e| SkillError::io("resolve current directory", e))
}

fn target_status(spec: &SkillSpec, target: &SkillTarget) -> Result<SkillTargetStatus, SkillError> {
    let installed = target.skill_path.is_file();
    let mut valid = false;
    let mut current = false;
    let mut validation_error = None;
    let mut managed = false;
    if installed {
        let text = std::fs::read_to_string(&target.skill_path)
            .map_err(|e| SkillError::io("read skill", e))?;
        managed = skill_text_is_managed_or_bundled(spec, &text);
        current = normalize_skill_text(spec, &text) == normalize_skill_text(spec, spec.source);
        match validate_skill_frontmatter(&text) {
            Ok(()) => valid = true,
            Err(err) => validation_error = Some(err),
        }
    }
    Ok(SkillTargetStatus {
        agent: target.agent,
        scope: target.scope,
        skills_dir: target.skills_dir.clone(),
        skill_path: target.skill_path.clone(),
        installed,
        managed,
        valid,
        current,
        validation_error,
    })
}

fn target_uninstall_status(target: &SkillTarget, removed: bool) -> SkillUninstallStatus {
    SkillUninstallStatus {
        agent: target.agent,
        scope: target.scope,
        skills_dir: target.skills_dir.clone(),
        skill_path: target.skill_path.clone(),
        removed,
    }
}

fn generated_by(spec: &SkillSpec) -> String {
    format!("Generated by {} skill install", spec.marker_slug)
}

fn marker(spec: &SkillSpec) -> String {
    format!("{}-managed-skill: true", spec.marker_slug)
}

fn managed_skill_contents(spec: &SkillSpec) -> String {
    let generated_by = generated_by(spec);
    let marker = marker(spec);
    let mut lines = spec.source.lines();
    let mut output = String::new();
    let mut inserted = false;
    if let Some(first) = lines.next() {
        output.push_str(first);
        output.push('\n');
    }
    for line in lines {
        output.push_str(line);
        output.push('\n');
        if !inserted && line.trim() == "---" {
            output.push_str("<!-- ");
            output.push_str(&generated_by);
            output.push_str(" -->\n");
            output.push_str("<!-- ");
            output.push_str(&marker);
            output.push_str(" -->\n\n");
            inserted = true;
        }
    }
    if !inserted {
        output.push_str("<!-- ");
        output.push_str(&generated_by);
        output.push_str(" -->\n");
        output.push_str("<!-- ");
        output.push_str(&marker);
        output.push_str(" -->\n");
    }
    output
}

fn validate_installed_skill(spec: &SkillSpec, path: &Path) -> Result<(), SkillError> {
    let text =
        std::fs::read_to_string(path).map_err(|e| SkillError::io("read installed skill", e))?;
    validate_skill_text(spec, &text)
}

fn validate_skill_text(spec: &SkillSpec, text: &str) -> Result<(), SkillError> {
    validate_skill_frontmatter(text).map_err(|err| {
        SkillError::invalid_request(
            format!("invalid {} skill front matter: {err}", spec.title),
            Some("quote scalar values that contain ': ', especially description".to_string()),
        )
    })
}

fn validate_skill_frontmatter(text: &str) -> Result<(), String> {
    let mut lines = text.lines().enumerate();
    let Some((_, first)) = lines.next() else {
        return Err("missing YAML front matter".to_string());
    };
    if first.trim() != "---" {
        return Err("missing opening --- YAML front matter delimiter".to_string());
    }
    let mut found_end = false;
    let mut has_name = false;
    let mut has_description = false;
    for (idx, line) in lines {
        let line_no = idx + 1;
        let trimmed = line.trim();
        if trimmed == "---" {
            found_end = true;
            break;
        }
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        if line.starts_with(' ') || line.starts_with('\t') {
            return Err(format!("line {line_no}: nested YAML is not supported here"));
        }
        let Some((key, value)) = line.split_once(':') else {
            return Err(format!("line {line_no}: expected key: value"));
        };
        let key = key.trim();
        if key.is_empty() {
            return Err(format!("line {line_no}: empty key"));
        }
        let value = value.trim_start();
        if key == "name" {
            has_name = true;
        }
        if key == "description" {
            has_description = true;
        }
        if value.starts_with('"') || value.starts_with('\'') {
            continue;
        }
        if value.contains(": ") {
            return Err(format!(
                "line {line_no}: unquoted scalar contains ': '; quote the value"
            ));
        }
    }
    if !found_end {
        return Err("missing closing --- YAML front matter delimiter".to_string());
    }
    if !has_name {
        return Err("missing required name field".to_string());
    }
    if !has_description {
        return Err("missing required description field".to_string());
    }
    Ok(())
}

fn is_managed_or_bundled_skill(spec: &SkillSpec, path: &Path) -> Result<bool, SkillError> {
    if !path.exists() {
        return Ok(false);
    }
    let text = std::fs::read_to_string(path).map_err(|e| SkillError::io("read skill", e))?;
    Ok(skill_text_is_managed_or_bundled(spec, &text))
}

fn skill_text_is_managed_or_bundled(spec: &SkillSpec, text: &str) -> bool {
    let marker = marker(spec);
    let generated_by = generated_by(spec);
    (text.contains(&marker) && text.contains(&generated_by))
        || normalize_skill_text(spec, text) == normalize_skill_text(spec, spec.source)
}

fn normalize_skill_text(spec: &SkillSpec, text: &str) -> String {
    let marker = marker(spec);
    let generated_by = generated_by(spec);
    // Drop the managed-marker lines, then collapse runs of blank lines to one so that the blank
    // line `managed_skill_contents` inserts after the marker block does not make a managed install
    // compare unequal to the bundled source.
    let mut out: Vec<&str> = Vec::new();
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.contains(&marker) || trimmed.contains(&generated_by) {
            continue;
        }
        if trimmed.is_empty() && out.last().is_some_and(|prev| prev.trim().is_empty()) {
            continue;
        }
        out.push(line);
    }
    out.join("\n").trim().to_string()
}

fn home_dir() -> Result<PathBuf, SkillError> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .ok_or_else(|| {
            SkillError::invalid_request(
                "cannot determine home directory".to_string(),
                Some("pass --skills-dir explicitly".to_string()),
            )
        })
}

fn expand_tilde(input: &str) -> Result<PathBuf, SkillError> {
    if input == "~" {
        return home_dir();
    }
    if let Some(rest) = input.strip_prefix("~/") {
        return Ok(home_dir()?.join(rest));
    }
    Ok(PathBuf::from(input))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    const SKILL_SOURCE: &str =
        "---\nname: agent-first-test\ndescription: test skill\n---\n\n# Body\n\nrules.\n";

    fn spec() -> SkillSpec<'static> {
        SkillSpec {
            name: "agent-first-test",
            source: SKILL_SOURCE,
            title: "Agent-First Test",
            marker_slug: "aftest",
        }
    }

    fn temp_skills_dir(name: &str) -> PathBuf {
        let suffix = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        std::env::temp_dir().join(format!(
            "afdata_skill_{name}_{}_{}",
            std::process::id(),
            suffix
        ))
    }

    fn options(agent: SkillAgentSelection, dir: &Path, force: bool) -> SkillOptions {
        SkillOptions {
            agent,
            scope: SkillScope::Personal,
            skills_dir: Some(dir.to_string_lossy().to_string()),
            force,
        }
    }

    #[test]
    fn validates_bundled_frontmatter() {
        assert!(validate_skill_frontmatter(SKILL_SOURCE).is_ok());
    }

    #[test]
    fn rejects_unquoted_colon_space() {
        let bad = "---\nname: x\ndescription: broken: yaml\n---\n";
        assert!(validate_skill_frontmatter(bad).is_err());
    }

    fn install_status_uninstall_for(agent: SkillAgentSelection, expect: SkillAgent, tag: &str) {
        let dir = temp_skills_dir(tag);
        let opts = options(agent, &dir, false);
        let skill_path = dir.join("agent-first-test").join(SKILL_FILE_NAME);

        let installed = run_skill_admin(&spec(), SkillAction::Install, &opts);
        assert!(installed.is_ok());
        assert!(skill_path.is_file());
        let text = std::fs::read_to_string(&skill_path).unwrap_or_default();
        assert!(text.contains(&marker(&spec())));

        let status = run_skill_admin(&spec(), SkillAction::Status, &opts);
        assert!(status.is_ok());
        if let Ok(SkillReport::Status {
            installed_all,
            valid_all,
            current_all,
            targets,
            ..
        }) = status
        {
            assert!(installed_all);
            assert!(valid_all);
            assert!(current_all);
            assert_eq!(targets.first().map(|t| t.agent), Some(expect));
            assert_eq!(targets.first().map(|t| t.current), Some(true));
        }

        let removed = run_skill_admin(&spec(), SkillAction::Uninstall, &opts);
        assert!(removed.is_ok());
        assert!(!skill_path.exists());
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn install_status_uninstall_codex() {
        install_status_uninstall_for(SkillAgentSelection::Codex, SkillAgent::Codex, "codex");
    }

    #[test]
    fn install_status_uninstall_claude_code() {
        install_status_uninstall_for(
            SkillAgentSelection::ClaudeCode,
            SkillAgent::ClaudeCode,
            "claude",
        );
    }

    #[test]
    fn install_status_uninstall_opencode() {
        install_status_uninstall_for(
            SkillAgentSelection::Opencode,
            SkillAgent::Opencode,
            "opencode",
        );
    }

    #[test]
    fn status_reports_stale_install_as_not_current() {
        let dir = temp_skills_dir("stale");
        let opts = options(SkillAgentSelection::Opencode, &dir, false);
        let skill_dir = dir.join("agent-first-test");
        let skill_path = skill_dir.join(SKILL_FILE_NAME);
        assert!(std::fs::create_dir_all(&skill_dir).is_ok());
        // A managed marker but stale body: valid + managed, but not current.
        let stale = format!(
            "---\nname: agent-first-test\ndescription: test skill\n---\n<!-- {} -->\n<!-- {} -->\n\n# Body\n\nOLD rules.\n",
            generated_by(&spec()),
            marker(&spec())
        );
        assert!(std::fs::write(&skill_path, stale).is_ok());

        let status = run_skill_admin(&spec(), SkillAction::Status, &opts);
        if let Ok(SkillReport::Status {
            current_all,
            targets,
            ..
        }) = status
        {
            assert!(!current_all);
            if let Some(t) = targets.first() {
                assert!(t.installed);
                assert!(t.valid);
                assert!(t.managed);
                assert!(!t.current);
            }
        }

        // Reinstall makes it current again.
        assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_ok());
        if let Ok(SkillReport::Status { targets, .. }) =
            run_skill_admin(&spec(), SkillAction::Status, &opts)
        {
            assert_eq!(targets.first().map(|t| t.current), Some(true));
        }
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn install_and_uninstall_refuse_unmanaged() {
        let dir = temp_skills_dir("unmanaged");
        let skill_dir = dir.join("agent-first-test");
        let skill_path = skill_dir.join(SKILL_FILE_NAME);
        assert!(std::fs::create_dir_all(&skill_dir).is_ok());
        assert!(
            std::fs::write(&skill_path, "---\nname: custom\ndescription: custom\n---\n").is_ok()
        );
        let opts = options(SkillAgentSelection::Codex, &dir, false);

        assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_err());
        assert!(run_skill_admin(&spec(), SkillAction::Uninstall, &opts).is_err());
        assert!(skill_path.exists());
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn serializes_to_protocol_shape() {
        let dir = temp_skills_dir("serialize");
        let opts = options(SkillAgentSelection::Opencode, &dir, false);
        if let Ok(report) = run_skill_admin(&spec(), SkillAction::Install, &opts) {
            let value = serde_json::to_value(&report).unwrap_or(serde_json::Value::Null);
            assert_eq!(value["code"], "skill_install");
            assert_eq!(value["installed"], true);
            assert_eq!(value["targets"][0]["agent"], "opencode");
            assert_eq!(value["targets"][0]["current"], true);
        }
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn all_personal_resolves_three_targets() {
        let opts = SkillOptions {
            agent: SkillAgentSelection::All,
            scope: SkillScope::Personal,
            skills_dir: None,
            force: false,
        };
        let targets = resolve_targets(&spec(), &opts);
        assert!(targets.is_ok());
        if let Ok(targets) = targets {
            assert_eq!(targets.len(), 3);
            assert_eq!(targets[0].agent, SkillAgent::Codex);
            assert_eq!(targets[1].agent, SkillAgent::ClaudeCode);
            assert_eq!(targets[2].agent, SkillAgent::Opencode);
        }
    }

    #[test]
    fn all_project_skips_codex() {
        let opts = SkillOptions {
            agent: SkillAgentSelection::All,
            scope: SkillScope::Project,
            skills_dir: None,
            force: false,
        };
        let targets = resolve_targets(&spec(), &opts);
        assert!(targets.is_ok());
        if let Ok(targets) = targets {
            assert_eq!(targets.len(), 2);
            assert_eq!(targets[0].agent, SkillAgent::ClaudeCode);
            assert_eq!(targets[1].agent, SkillAgent::Opencode);
        }
    }

    #[test]
    fn codex_project_scope_is_rejected() {
        let opts = SkillOptions {
            agent: SkillAgentSelection::Codex,
            scope: SkillScope::Project,
            skills_dir: None,
            force: false,
        };
        assert!(resolve_targets(&spec(), &opts).is_err());
    }
}