agent-first-data 0.13.2

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
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
//! 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";
const FNV1A64_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV1A64_PRIME: u64 = 0x0000_0100_0000_01b3;

/// 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> {
    validate_spec(spec)?;
    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 let Some(kind) = skill_path_file_type(&target.skill_path)? {
            if kind.is_symlink() && !options.force {
                return Err(SkillError::invalid_request(
                    format!(
                        "refusing to overwrite symlinked skill at {}",
                        target.skill_path.display()
                    ),
                    Some(
                        "pass --force to replace the symlink itself, or choose another --skills-dir"
                            .to_string(),
                    ),
                ));
            }
            if !kind.is_symlink()
                && !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()),
                ));
            }
        }
        write_skill_atomic(target, &content)?;
        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 {
        let Some(kind) = skill_path_file_type(&target.skill_path)? else {
            removed.push(target_uninstall_status(target, false));
            continue;
        };
        if kind.is_symlink() && !options.force {
            return Err(SkillError::invalid_request(
                format!(
                    "refusing to remove symlinked skill at {}",
                    target.skill_path.display()
                ),
                Some("pass --force to remove the symlink itself".to_string()),
            ));
        }
        if !kind.is_symlink()
            && !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 Some(kind) = skill_path_file_type(&target.skill_path)? else {
        return Ok(SkillTargetStatus {
            agent: target.agent,
            scope: target.scope,
            skills_dir: target.skills_dir.clone(),
            skill_path: target.skill_path.clone(),
            installed: false,
            managed: false,
            valid: false,
            current: false,
            validation_error: None,
        });
    };
    let installed = true;
    let mut valid = false;
    let mut current = false;
    let mut validation_error = None;
    let mut managed = false;
    if kind.is_symlink() {
        validation_error = Some("target SKILL.md is a symlink; refusing to follow it".to_string());
    } else if kind.is_file() {
        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_text(spec, &text) {
            Ok(()) => valid = true,
            Err(err) => validation_error = Some(err.message),
        }
    } else {
        validation_error = Some("target SKILL.md is not a regular file".to_string());
    }
    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 source_hash(spec: &SkillSpec) -> String {
    let mut hash = FNV1A64_OFFSET;
    for byte in spec.source.as_bytes() {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(FNV1A64_PRIME);
    }
    format!("{hash:016x}")
}

fn managed_marker_block(spec: &SkillSpec) -> String {
    let slug = spec.marker_slug;
    format!(
        "<!--\n{}\n{}-managed-skill: true\n{}-managed-skill-name: {}\n{}-managed-skill-source-hash-fnv1a64: {}\n-->",
        generated_by(spec),
        slug,
        slug,
        spec.name,
        slug,
        source_hash(spec)
    )
}

fn managed_skill_contents(spec: &SkillSpec) -> String {
    let block = managed_marker_block(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(&block);
            output.push_str("\n\n");
            inserted = true;
        }
    }
    if !inserted {
        output.push_str(&block);
        output.push('\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> {
    let frontmatter = 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()),
        )
    })?;
    if frontmatter.name != spec.name {
        return Err(SkillError::invalid_request(
            format!(
                "invalid {} skill front matter: name {:?} does not match expected {:?}",
                spec.title, frontmatter.name, spec.name
            ),
            Some(format!("set front matter name to {}", spec.name)),
        ));
    }
    Ok(())
}

struct SkillFrontmatter {
    name: String,
}

fn validate_skill_frontmatter(text: &str) -> Result<SkillFrontmatter, 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 name = None;
    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" {
            name = Some(parse_frontmatter_scalar(value));
        }
        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());
    }
    let Some(name) = name else {
        return Err("missing required name field".to_string());
    };
    if !has_description {
        return Err("missing required description field".to_string());
    }
    Ok(SkillFrontmatter { name })
}

fn parse_frontmatter_scalar(value: &str) -> String {
    let value = value.trim();
    if value.len() >= 2 {
        let bytes = value.as_bytes();
        if (bytes[0] == b'"' && bytes[value.len() - 1] == b'"')
            || (bytes[0] == b'\'' && bytes[value.len() - 1] == b'\'')
        {
            return value[1..value.len() - 1].to_string();
        }
    }
    value.to_string()
}

fn is_managed_or_bundled_skill(spec: &SkillSpec, path: &Path) -> Result<bool, SkillError> {
    let Some(kind) = skill_path_file_type(path)? else {
        return Ok(false);
    };
    if kind.is_symlink() {
        return Err(SkillError::invalid_request(
            format!("refusing to inspect symlinked skill at {}", path.display()),
            Some("pass --force to replace or remove the symlink itself".to_string()),
        ));
    }
    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 {
    skill_text_has_current_marker(spec, text)
        || normalize_skill_text(spec, text) == normalize_skill_text(spec, spec.source)
}

fn skill_text_has_current_marker(spec: &SkillSpec, text: &str) -> bool {
    text.replace("\r\n", "\n")
        .contains(&managed_marker_block(spec))
}

fn normalize_skill_text(spec: &SkillSpec, text: &str) -> String {
    let text = text
        .replace("\r\n", "\n")
        .replace(&managed_marker_block(spec), "");
    // Drop the managed-marker blocks, 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.is_empty() && out.last().is_some_and(|prev| prev.trim().is_empty()) {
            continue;
        }
        out.push(line);
    }
    out.join("\n").trim().to_string()
}

fn validate_spec(spec: &SkillSpec) -> Result<(), SkillError> {
    validate_slug("skill name", spec.name)?;
    validate_slug("marker slug", spec.marker_slug)?;
    validate_skill_text(spec, spec.source)
}

fn validate_slug(field: &str, value: &str) -> Result<(), SkillError> {
    if slug_is_valid(value) {
        return Ok(());
    }
    Err(SkillError::invalid_request(
        format!(
            "invalid {field} {value:?}: expected a lowercase slug matching [a-z0-9][a-z0-9-]*[a-z0-9]"
        ),
        Some("use lowercase ASCII letters, digits, and single hyphen-separated words".to_string()),
    ))
}

fn slug_is_valid(value: &str) -> bool {
    let bytes = value.as_bytes();
    if bytes.is_empty() {
        return false;
    }
    fn is_lower_alnum(byte: u8) -> bool {
        byte.is_ascii_lowercase() || byte.is_ascii_digit()
    }
    if !is_lower_alnum(bytes[0]) || !is_lower_alnum(bytes[bytes.len() - 1]) {
        return false;
    }
    bytes
        .iter()
        .all(|byte| is_lower_alnum(*byte) || *byte == b'-')
}

fn skill_path_file_type(path: &Path) -> Result<Option<std::fs::FileType>, SkillError> {
    match std::fs::symlink_metadata(path) {
        Ok(metadata) => Ok(Some(metadata.file_type())),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(err) => Err(SkillError::io("inspect skill path", err)),
    }
}

fn write_skill_atomic(target: &SkillTarget, content: &str) -> Result<(), SkillError> {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let tmp_path = target.skill_dir.join(format!(
        ".{SKILL_FILE_NAME}.{}.{}.tmp",
        std::process::id(),
        nanos
    ));
    let result = (|| {
        std::fs::write(&tmp_path, content)
            .map_err(|e| SkillError::io("write temporary skill", e))?;
        std::fs::rename(&tmp_path, &target.skill_path)
            .map_err(|e| SkillError::io("replace skill", e))?;
        Ok(())
    })();
    if result.is_err() {
        let _ = std::fs::remove_file(&tmp_path);
    }
    result
}

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 managed_skill_with_body(body: &str) -> String {
        format!(
            "---\nname: agent-first-test\ndescription: test skill\n---\n{}\n\n{body}",
            managed_marker_block(&spec())
        )
    }

    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(&managed_marker_block(&spec())));
        assert!(text.contains("aftest-managed-skill-name: agent-first-test"));
        assert!(text.contains("aftest-managed-skill-source-hash-fnv1a64:"));

        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 = managed_skill_with_body("# Body\n\nOLD rules.\n");
        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());
        let refreshed = std::fs::read_to_string(&skill_path).unwrap_or_default();
        assert!(refreshed.contains(&managed_marker_block(&spec())));
        assert!(!refreshed.contains("<!-- aftest-managed-skill: true -->"));
        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 random_text_with_marker_words_is_not_managed() {
        let dir = temp_skills_dir("marker-words");
        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());
        let random = format!(
            "---\nname: agent-first-test\ndescription: test skill\n---\n\nThis mentions {} and {} but is not a generated block.\n",
            generated_by(&spec()),
            "aftest-managed-skill: true"
        );
        assert!(std::fs::write(&skill_path, random).is_ok());

        if let Ok(SkillReport::Status { targets, .. }) =
            run_skill_admin(&spec(), SkillAction::Status, &opts)
        {
            assert_eq!(targets.first().map(|t| t.managed), Some(false));
        }
        assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_err());
        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 invalid_spec_slugs_are_rejected_before_path_resolution() {
        for name in ["", "../x", "x/y", ".hidden", "bad_name", "Bad"] {
            let bad = SkillSpec {
                name,
                source: SKILL_SOURCE,
                title: "Bad",
                marker_slug: "aftest",
            };
            let opts = options(SkillAgentSelection::Codex, Path::new("/tmp/afdata"), false);
            assert!(
                run_skill_admin(&bad, SkillAction::Status, &opts).is_err(),
                "{name:?}"
            );
        }

        let bad_marker = SkillSpec {
            name: "agent-first-test",
            source: SKILL_SOURCE,
            title: "Bad",
            marker_slug: "../aftest",
        };
        let opts = options(SkillAgentSelection::Codex, Path::new("/tmp/afdata"), false);
        assert!(run_skill_admin(&bad_marker, SkillAction::Status, &opts).is_err());
    }

    #[test]
    fn frontmatter_name_must_match_spec_name() {
        let bad = SkillSpec {
            name: "agent-first-test",
            source: "---\nname: other-skill\ndescription: test skill\n---\n",
            title: "Bad",
            marker_slug: "aftest",
        };
        let dir = temp_skills_dir("frontmatter-name");
        let opts = options(SkillAgentSelection::Codex, &dir, false);
        assert!(run_skill_admin(&bad, SkillAction::Install, &opts).is_err());
        let _ = std::fs::remove_dir_all(dir);
    }

    #[cfg(unix)]
    #[test]
    fn symlink_target_is_rejected_by_default_and_force_does_not_follow() {
        use std::os::unix::fs::symlink;

        let dir = temp_skills_dir("symlink-install");
        let opts = options(SkillAgentSelection::Codex, &dir, false);
        let force_opts = options(SkillAgentSelection::Codex, &dir, true);
        let skill_dir = dir.join("agent-first-test");
        let skill_path = skill_dir.join(SKILL_FILE_NAME);
        let external = dir.join("external.md");
        assert!(std::fs::create_dir_all(&skill_dir).is_ok());
        assert!(std::fs::write(&external, "external").is_ok());
        assert!(symlink(&external, &skill_path).is_ok());

        assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_err());
        assert_eq!(
            std::fs::read_to_string(&external).unwrap_or_default(),
            "external"
        );
        assert!(run_skill_admin(&spec(), SkillAction::Uninstall, &opts).is_err());
        assert!(skill_path.is_symlink());

        assert!(run_skill_admin(&spec(), SkillAction::Install, &force_opts).is_ok());
        assert_eq!(
            std::fs::read_to_string(&external).unwrap_or_default(),
            "external"
        );
        assert!(skill_path.is_file());
        assert!(!skill_path.is_symlink());
        let _ = std::fs::remove_dir_all(dir);
    }

    #[cfg(unix)]
    #[test]
    fn force_uninstall_removes_symlink_without_following() {
        use std::os::unix::fs::symlink;

        let dir = temp_skills_dir("symlink-uninstall");
        let force_opts = options(SkillAgentSelection::Codex, &dir, true);
        let skill_dir = dir.join("agent-first-test");
        let skill_path = skill_dir.join(SKILL_FILE_NAME);
        let external = dir.join("external.md");
        assert!(std::fs::create_dir_all(&skill_dir).is_ok());
        assert!(std::fs::write(&external, "external").is_ok());
        assert!(symlink(&external, &skill_path).is_ok());

        assert!(run_skill_admin(&spec(), SkillAction::Uninstall, &force_opts).is_ok());
        assert!(!skill_path.exists());
        assert_eq!(
            std::fs::read_to_string(&external).unwrap_or_default(),
            "external"
        );
        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());
    }
}