Skip to main content

agent_first_data/
skill.rs

1//! Reusable Agent Skill installer for spore CLIs.
2//!
3//! A spore that embeds its `SKILL.md` describes itself with a [`SkillSpec`] and calls
4//! [`run_skill_admin`] to install, uninstall, or report status of that skill across supported
5//! coding agents (Codex, Claude Code, opencode, Hermes).
6//!
7//! The function performs the filesystem work and returns a typed [`SkillReport`] (the caller
8//! serializes it for output) or a [`SkillError`]. It never writes to stdout/stderr itself.
9//!
10//! Requires the `skill-admin` feature.
11
12use serde::Serialize;
13use std::path::{Path, PathBuf};
14
15const SKILL_FILE_NAME: &str = "SKILL.md";
16const FNV1A64_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
17const FNV1A64_PRIME: u64 = 0x0000_0100_0000_01b3;
18
19/// A bundled auxiliary file installed alongside `SKILL.md` under the skill
20/// directory — for example a `references/` document a skill points its agent to.
21///
22/// The file is written verbatim; unlike `SKILL.md` it carries no managed marker.
23#[derive(Clone, Copy, Debug)]
24pub struct SkillAsset<'a> {
25    /// Path relative to the skill directory, using `/` separators
26    /// (e.g. `references/naming-output.md`). Must be relative with no `.` or `..`
27    /// segment, so an asset can never escape the skill directory.
28    pub path: &'a str,
29    /// Bundled file contents (typically `include_str!`).
30    pub contents: &'a str,
31}
32
33/// Identity of the skill being managed and the tool that manages it.
34///
35/// `name` is both the skill directory name and the `name:` front-matter field. `source` is the
36/// bundled `SKILL.md` (typically `include_str!`). `title` is a human label for error messages.
37/// `marker_slug` seeds the managed-skill marker and the `Generated by <slug> skill install`
38/// comment, and is referenced in hints (e.g. `afwidget`). `assets` are auxiliary files bundled
39/// under the skill directory (e.g. `references/`); empty for a single-file skill.
40#[derive(Clone, Copy, Debug)]
41pub struct SkillSpec<'a> {
42    /// Skill directory name and front-matter `name` (e.g. `agent-first-widget`).
43    pub name: &'a str,
44    /// Bundled `SKILL.md` contents.
45    pub source: &'a str,
46    /// Human-readable skill title for error messages (e.g. `Agent-First Widget`).
47    pub title: &'a str,
48    /// Short tool slug used in the managed marker, generated-by comment, and hints (e.g. `afwidget`).
49    pub marker_slug: &'a str,
50    /// Auxiliary files bundled under the skill directory alongside `SKILL.md`
51    /// (e.g. `references/`). Installed and removed with the skill; empty `&[]`
52    /// for a single-file skill.
53    pub assets: &'a [SkillAsset<'a>],
54}
55
56/// Which agent target(s) to manage.
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
58#[serde(rename_all = "kebab-case")]
59pub enum SkillAgentSelection {
60    /// Every agent that supports the requested scope.
61    All,
62    /// Codex.
63    Codex,
64    /// Claude Code.
65    ClaudeCode,
66    /// opencode.
67    Opencode,
68    /// Hermes Agent.
69    Hermes,
70}
71
72/// A concrete agent a skill is installed for (no `All`).
73#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
74#[serde(rename_all = "kebab-case")]
75pub enum SkillAgent {
76    /// Codex (`$CODEX_HOME/skills`, `~/.codex/skills`, or `.codex/skills`).
77    Codex,
78    /// Claude Code (`~/.claude/skills` or `.claude/skills`).
79    ClaudeCode,
80    /// opencode (`~/.config/opencode/skills` or `.opencode/skills`).
81    Opencode,
82    /// Hermes Agent (`$HERMES_HOME/skills`, `~/.hermes/skills`, or `.hermes/skills`).
83    Hermes,
84}
85
86/// Where to install the skill.
87#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
88#[serde(rename_all = "lowercase")]
89pub enum SkillScope {
90    /// User-level skills directory.
91    Personal,
92    /// Current workspace's skills directory.
93    Workspace,
94}
95
96/// Options shared by every skill action.
97#[derive(Clone, Debug, Serialize)]
98pub struct SkillOptions {
99    /// Agent target selection.
100    pub agent: SkillAgentSelection,
101    /// Skill scope.
102    pub scope: SkillScope,
103    /// Explicit skills directory; requires a single concrete `agent`.
104    pub skills_dir: Option<String>,
105    /// Overwrite or remove a skill that this tool did not manage.
106    pub force: bool,
107}
108
109/// The skill action to perform.
110#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
111#[serde(rename_all = "lowercase")]
112pub enum SkillAction {
113    /// Report whether the skill is installed, valid, managed, and current.
114    Status,
115    /// Install (or refresh) the skill.
116    Install,
117    /// Remove a managed skill.
118    Uninstall,
119}
120
121/// Per-target outcome of `status` / `install`.
122#[derive(Clone, Debug, Serialize)]
123pub struct SkillTargetStatus {
124    /// The agent this target belongs to.
125    pub agent: SkillAgent,
126    /// The scope this target belongs to.
127    pub scope: SkillScope,
128    /// Directory that holds skill folders.
129    pub skills_dir: PathBuf,
130    /// Directory for this skill under `skills_dir`.
131    pub skill_dir: PathBuf,
132    /// Full path to the target `SKILL.md`.
133    pub skill_path: PathBuf,
134    /// Whether a skill file exists at `skill_path`.
135    pub installed: bool,
136    /// Whether the installed file was generated by this tool (or is byte-equal to the bundle).
137    pub managed: bool,
138    /// Whether the installed file has valid front matter.
139    pub valid: bool,
140    /// Whether the installed content matches the bundled skill (up to date).
141    pub current: bool,
142    /// Front-matter validation error, when the installed file is invalid.
143    pub validation_error: Option<String>,
144}
145
146/// Per-target outcome of `uninstall`.
147#[derive(Clone, Debug, Serialize)]
148pub struct SkillUninstallStatus {
149    /// The agent this target belongs to.
150    pub agent: SkillAgent,
151    /// The scope this target belongs to.
152    pub scope: SkillScope,
153    /// Directory that holds skill folders.
154    pub skills_dir: PathBuf,
155    /// Directory for this skill under `skills_dir`.
156    pub skill_dir: PathBuf,
157    /// Full path to the target `SKILL.md`.
158    pub skill_path: PathBuf,
159    /// Whether the skill file itself was removed (false if nothing was installed).
160    pub removed: bool,
161    /// Bundled asset paths, relative to the skill directory, that were removed
162    /// with it. Empty for a single-file skill, and for a target that had
163    /// nothing installed.
164    pub assets_removed: Vec<String>,
165    /// Whether the skill's own directory outlived the uninstall — which happens
166    /// when it holds files this tool did not install. They are left untouched,
167    /// and saying so is the difference between a clean removal and one that
168    /// left something behind.
169    pub directory_retained: bool,
170}
171
172/// The result of a skill action. Serializes to the protocol shape, carrying a `code`
173/// discriminator (`skill_status` / `skill_install` / `skill_uninstall`).
174#[derive(Clone, Debug, Serialize)]
175#[serde(tag = "code")]
176pub enum SkillReport {
177    /// `status` result.
178    #[serde(rename = "skill_status")]
179    Status {
180        /// Skill name.
181        skill: String,
182        /// True when every target is installed.
183        installed_all: bool,
184        /// True when every target has valid front matter.
185        valid_all: bool,
186        /// True when every target is up to date with the bundle.
187        current_all: bool,
188        /// Per-target detail.
189        targets: Vec<SkillTargetStatus>,
190    },
191    /// `install` result.
192    #[serde(rename = "skill_install")]
193    Install {
194        /// Skill name.
195        skill: String,
196        /// Always true (install succeeded for every target).
197        installed: bool,
198        /// Per-target detail after writing.
199        targets: Vec<SkillTargetStatus>,
200        /// Operator hint.
201        hint: &'static str,
202    },
203    /// `uninstall` result.
204    #[serde(rename = "skill_uninstall")]
205    Uninstall {
206        /// Skill name.
207        skill: String,
208        /// True when at least one file was removed.
209        removed_any: bool,
210        /// Per-target detail.
211        targets: Vec<SkillUninstallStatus>,
212    },
213}
214
215/// What kind of failure a [`SkillError`] is, so a caller can pick an exit
216/// status and a stable code without parsing the message.
217#[derive(Clone, Copy, Debug, PartialEq, Eq)]
218pub enum SkillErrorKind {
219    /// The options cannot name a target: `--skills-dir` with every agent, or
220    /// no usable home directory. Nothing was touched.
221    Usage,
222    /// The embedding program's [`SkillSpec`] is malformed — a defect in the
223    /// program, not in the call.
224    InvalidSpec,
225    /// A target holds something afdata will not overwrite or remove: an
226    /// unmanaged or invalid skill, a symlink, a path outside the skills
227    /// directory.
228    Refused,
229    /// The filesystem failed while reading or writing a target.
230    Io,
231}
232
233impl SkillErrorKind {
234    /// The stable `error.code` for this kind.
235    #[must_use]
236    pub fn code(self) -> &'static str {
237        match self {
238            Self::Usage => "skill_usage_error",
239            Self::InvalidSpec => "skill_spec_invalid",
240            Self::Refused => "skill_refused",
241            Self::Io => "skill_io_failed",
242        }
243    }
244}
245
246/// A skill admin failure with an operator-facing message and optional hint.
247#[derive(Clone, Debug)]
248pub struct SkillError {
249    /// What kind of failure this is.
250    pub kind: SkillErrorKind,
251    /// What went wrong.
252    pub message: String,
253    /// Optional remediation hint.
254    pub hint: Option<String>,
255    /// Per-target report captured after a multi-target operation failed.
256    pub partial_report: Option<Box<SkillReport>>,
257}
258
259impl std::fmt::Display for SkillError {
260    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261        formatter.write_str(&self.message)
262    }
263}
264
265impl std::error::Error for SkillError {}
266
267impl SkillError {
268    fn new(kind: SkillErrorKind, message: String, hint: Option<String>) -> Self {
269        Self {
270            kind,
271            message,
272            hint,
273            partial_report: None,
274        }
275    }
276
277    fn io(action: &str, err: std::io::Error) -> Self {
278        Self {
279            kind: SkillErrorKind::Io,
280            message: format!("{action} failed: {err}"),
281            hint: None,
282            partial_report: None,
283        }
284    }
285
286    /// A failed atomic installation, which names the step it failed at.
287    fn write_failed(action: &str, err: crate::atomic_file::AtomicError) -> Self {
288        // Only the closing directory fsync can fail with the new file already
289        // in place. Saying so is the difference between "nothing happened" and
290        // "it happened but may not survive a crash", and only the second one
291        // asks the operator to re-run.
292        let hint = err.commit_uncertain().then(|| {
293            "the file is installed but its durability is unconfirmed; re-run to be sure".to_string()
294        });
295        Self {
296            kind: SkillErrorKind::Io,
297            message: format!("{action} failed: {err}"),
298            hint,
299            partial_report: None,
300        }
301    }
302
303    fn with_partial_report(mut self, report: SkillReport) -> Self {
304        self.partial_report = Some(Box::new(report));
305        self
306    }
307}
308
309/// Install, uninstall, or report status of `spec`'s skill across the selected agent target(s).
310///
311/// Returns a typed [`SkillReport`] (caller serializes it for output) or a [`SkillError`].
312/// Does not touch stdout/stderr.
313pub fn run_skill_admin(
314    spec: &SkillSpec,
315    action: SkillAction,
316    options: &SkillOptions,
317) -> Result<SkillReport, SkillError> {
318    validate_spec(spec)?;
319    match action {
320        SkillAction::Status => status(spec, options),
321        SkillAction::Install => install(spec, options),
322        SkillAction::Uninstall => uninstall(spec, options),
323    }
324}
325
326fn status(spec: &SkillSpec, options: &SkillOptions) -> Result<SkillReport, SkillError> {
327    let targets = resolve_targets(spec, options)?;
328    let mut statuses = Vec::with_capacity(targets.len());
329    for target in &targets {
330        statuses.push(target_status(spec, target)?);
331    }
332    Ok(SkillReport::Status {
333        skill: spec.name.to_string(),
334        installed_all: statuses.iter().all(|s| s.installed),
335        valid_all: statuses.iter().all(|s| s.valid),
336        current_all: statuses.iter().all(|s| s.current),
337        targets: statuses,
338    })
339}
340
341fn install(spec: &SkillSpec, options: &SkillOptions) -> Result<SkillReport, SkillError> {
342    validate_skill_text(spec, spec.source, SkillErrorKind::InvalidSpec)?;
343    for asset in spec.assets {
344        validate_asset_path(asset.path)?;
345    }
346    let targets = resolve_targets(spec, options)?;
347    let content = managed_skill_contents(spec);
348    preflight_install_targets(spec, options, &targets)?;
349    for target in &targets {
350        if let Err(err) = std::fs::create_dir_all(&target.skill_dir)
351            .map_err(|e| SkillError::io("create skill dir", e))
352        {
353            return Err(err.with_partial_report(install_report_lossy(spec, &targets, false)));
354        }
355    }
356    install_targets(spec, &targets, &content)
357}
358
359fn preflight_install_targets(
360    spec: &SkillSpec,
361    options: &SkillOptions,
362    targets: &[SkillTarget],
363) -> Result<(), SkillError> {
364    let mut failures = Vec::new();
365    let mut escaped = false;
366    for target in targets {
367        // Before anything about the file itself: nothing on the way down to it
368        // may be a link out of the skills directory.
369        if let Err(err) = containment_failure(spec, target) {
370            failures.push(err);
371            escaped = true;
372            continue;
373        }
374        // An asset path is checked before anything is written, for the same
375        // reason the skill file is: a directory found there halfway through
376        // leaves `SKILL.md` installed beside a missing reference, and a file the
377        // user put there is theirs until a managed `SKILL.md` claims the
378        // directory. Byte-equal content is already what install would write.
379        let skill_dir_managed = skill_path_file_type(&target.skill_path)?
380            .is_some_and(|kind| kind.is_file())
381            && is_managed_or_bundled_skill(spec, &target.skill_path)?;
382        for asset in spec.assets {
383            let dest = asset_target_path(&target.skill_dir, asset.path);
384            let Some(kind) = skill_path_file_type(&dest)? else {
385                continue;
386            };
387            if !kind.is_file() && !kind.is_symlink() {
388                failures.push(format!(
389                    "refusing to overwrite non-regular skill asset at {}",
390                    dest.display()
391                ));
392            } else if !skill_dir_managed
393                && !options.force
394                && (kind.is_symlink()
395                    || std::fs::read(&dest).map_err(|e| SkillError::io("read skill asset", e))?
396                        != asset.contents.as_bytes())
397            {
398                failures.push(format!(
399                    "refusing to overwrite unmanaged skill asset at {}",
400                    dest.display()
401                ));
402            }
403        }
404        if let Some(kind) = skill_path_file_type(&target.skill_path)? {
405            if kind.is_symlink() {
406                if !options.force {
407                    failures.push(format!(
408                        "refusing to overwrite symlinked skill at {}",
409                        target.skill_path.display()
410                    ));
411                }
412                continue;
413            }
414            if !kind.is_file() {
415                failures.push(format!(
416                    "refusing to overwrite non-regular skill at {}",
417                    target.skill_path.display()
418                ));
419                continue;
420            }
421            if !is_managed_or_bundled_skill(spec, &target.skill_path)? && !options.force {
422                failures.push(format!(
423                    "refusing to overwrite unmanaged skill at {}",
424                    target.skill_path.display()
425                ));
426            }
427        }
428    }
429    if failures.is_empty() {
430        return Ok(());
431    }
432    // `--force` replaces an unmanaged file inside the skills directory. It is
433    // not permission to write outside it, so a containment failure must not be
434    // answered with a hint that reads like one.
435    let hint = if escaped {
436        "--force does not permit writing outside the skills directory"
437    } else {
438        "pass --force to replace unmanaged files or symlinks"
439    };
440    Err(SkillError::new(
441        SkillErrorKind::Refused,
442        failures.join("; "),
443        Some(hint.to_string()),
444    )
445    .with_partial_report(install_report_lossy(spec, targets, false)))
446}
447
448fn install_targets(
449    spec: &SkillSpec,
450    targets: &[SkillTarget],
451    content: &str,
452) -> Result<SkillReport, SkillError> {
453    let mut installed = Vec::with_capacity(targets.len());
454    for target in targets {
455        if let Err(err) = write_skill_atomic(target, content) {
456            return Err(err.with_partial_report(install_report_lossy(spec, targets, false)));
457        }
458        if let Err(err) = install_target_assets(spec, target) {
459            return Err(err.with_partial_report(install_report_lossy(spec, targets, false)));
460        }
461        if let Err(err) = validate_installed_skill(spec, &target.skill_path) {
462            return Err(err.with_partial_report(install_report_lossy(spec, targets, false)));
463        }
464        match target_status(spec, target) {
465            Ok(status) => installed.push(status),
466            Err(err) => {
467                return Err(err.with_partial_report(install_report_lossy(spec, targets, false)));
468            }
469        }
470    }
471    Ok(SkillReport::Install {
472        skill: spec.name.to_string(),
473        installed: true,
474        targets: installed,
475        hint: "restart the agent so it reloads installed skills",
476    })
477}
478
479fn uninstall(spec: &SkillSpec, options: &SkillOptions) -> Result<SkillReport, SkillError> {
480    let targets = resolve_targets(spec, options)?;
481    preflight_uninstall_targets(spec, options, &targets)?;
482    let mut removed = Vec::with_capacity(targets.len());
483    for target in &targets {
484        let Some(kind) = skill_path_file_type(&target.skill_path)? else {
485            removed.push(target_uninstall_status(target, false));
486            continue;
487        };
488        if !kind.is_file() && !kind.is_symlink() {
489            let err = SkillError::new(
490                SkillErrorKind::Refused,
491                format!(
492                    "refusing to remove non-regular skill at {}",
493                    target.skill_path.display()
494                ),
495                None,
496            );
497            return Err(err.with_partial_report(uninstall_report_lossy(spec, &targets, &removed)));
498        }
499        if let Err(err) = ensure_no_symlinked_dirs(&target.skills_dir, &target.skill_path) {
500            return Err(err.with_partial_report(uninstall_report_lossy(spec, &targets, &removed)));
501        }
502        // Assets go first and `SKILL.md` last, so `SKILL.md` keeps marking the
503        // directory as this tool's until everything else is gone. A target that
504        // fails partway therefore still reads as installed, and running
505        // uninstall again finishes the job instead of skipping a directory whose
506        // marker was already removed.
507        let assets_removed = match remove_target_assets(spec, target) {
508            Ok(assets_removed) => assets_removed,
509            Err(err) => {
510                return Err(
511                    err.with_partial_report(uninstall_report_lossy(spec, &targets, &removed))
512                );
513            }
514        };
515        if let Err(err) =
516            std::fs::remove_file(&target.skill_path).map_err(|e| SkillError::io("remove skill", e))
517        {
518            return Err(err.with_partial_report(uninstall_report_lossy(spec, &targets, &removed)));
519        }
520        let _ = std::fs::remove_dir(&target.skill_dir);
521        removed.push(SkillUninstallStatus {
522            assets_removed,
523            ..target_uninstall_status(target, true)
524        });
525    }
526    Ok(SkillReport::Uninstall {
527        skill: spec.name.to_string(),
528        removed_any: removed.iter().any(|s| s.removed),
529        targets: removed,
530    })
531}
532
533fn preflight_uninstall_targets(
534    spec: &SkillSpec,
535    options: &SkillOptions,
536    targets: &[SkillTarget],
537) -> Result<(), SkillError> {
538    let mut failures = Vec::new();
539    let mut escaped = false;
540    for target in targets {
541        if let Err(err) = containment_failure(spec, target) {
542            failures.push(err);
543            escaped = true;
544            continue;
545        }
546        // A managed asset path now holding a directory is checked here rather
547        // than discovered halfway through: by then the skill file is gone and
548        // the target is half-removed.
549        for asset in spec.assets {
550            let dest = asset_target_path(&target.skill_dir, asset.path);
551            if let Some(kind) = skill_path_file_type(&dest)?
552                && kind.is_dir()
553            {
554                failures.push(format!(
555                    "refusing to remove bundled asset {} because it is a directory",
556                    dest.display()
557                ));
558            }
559        }
560        let Some(kind) = skill_path_file_type(&target.skill_path)? else {
561            continue;
562        };
563        if kind.is_symlink() {
564            if !options.force {
565                failures.push(format!(
566                    "refusing to remove symlinked skill at {}",
567                    target.skill_path.display()
568                ));
569            }
570            continue;
571        }
572        if !kind.is_file() {
573            failures.push(format!(
574                "refusing to remove non-regular skill at {}",
575                target.skill_path.display()
576            ));
577            continue;
578        }
579        if !is_managed_or_bundled_skill(spec, &target.skill_path)? && !options.force {
580            failures.push(format!(
581                "refusing to remove unmanaged skill at {}",
582                target.skill_path.display()
583            ));
584        }
585    }
586    if failures.is_empty() {
587        return Ok(());
588    }
589    let hint = if escaped {
590        "--force does not permit removing files outside the skills directory".to_string()
591    } else {
592        format!(
593            "only skills generated by {} skill install can be removed without --force",
594            spec.marker_slug
595        )
596    };
597    Err(
598        SkillError::new(SkillErrorKind::Refused, failures.join("; "), Some(hint))
599            .with_partial_report(uninstall_report_lossy(spec, targets, &[])),
600    )
601}
602
603struct SkillTarget {
604    agent: SkillAgent,
605    scope: SkillScope,
606    skills_dir: PathBuf,
607    skill_dir: PathBuf,
608    skill_path: PathBuf,
609}
610
611fn resolve_targets(
612    spec: &SkillSpec,
613    options: &SkillOptions,
614) -> Result<Vec<SkillTarget>, SkillError> {
615    if options.skills_dir.is_some() && options.agent == SkillAgentSelection::All {
616        return Err(SkillError::new(
617            SkillErrorKind::Usage,
618            "--skills-dir requires a single --agent".to_string(),
619            Some("custom skills directories are ambiguous when --agent all is used".to_string()),
620        ));
621    }
622    match (options.agent, options.scope) {
623        (SkillAgentSelection::All, SkillScope::Personal) => Ok(vec![
624            resolve_target(spec, SkillAgent::Codex, SkillScope::Personal, None)?,
625            resolve_target(spec, SkillAgent::ClaudeCode, SkillScope::Personal, None)?,
626            resolve_target(spec, SkillAgent::Opencode, SkillScope::Personal, None)?,
627            resolve_target(spec, SkillAgent::Hermes, SkillScope::Personal, None)?,
628        ]),
629        (SkillAgentSelection::All, SkillScope::Workspace) => Ok(vec![
630            resolve_target(spec, SkillAgent::Codex, SkillScope::Workspace, None)?,
631            resolve_target(spec, SkillAgent::ClaudeCode, SkillScope::Workspace, None)?,
632            resolve_target(spec, SkillAgent::Opencode, SkillScope::Workspace, None)?,
633            resolve_target(spec, SkillAgent::Hermes, SkillScope::Workspace, None)?,
634        ]),
635        (SkillAgentSelection::Codex, SkillScope::Workspace) => Ok(vec![resolve_target(
636            spec,
637            SkillAgent::Codex,
638            SkillScope::Workspace,
639            options.skills_dir.as_deref(),
640        )?]),
641        (SkillAgentSelection::Codex, SkillScope::Personal) => Ok(vec![resolve_target(
642            spec,
643            SkillAgent::Codex,
644            SkillScope::Personal,
645            options.skills_dir.as_deref(),
646        )?]),
647        (SkillAgentSelection::ClaudeCode, scope) => Ok(vec![resolve_target(
648            spec,
649            SkillAgent::ClaudeCode,
650            scope,
651            options.skills_dir.as_deref(),
652        )?]),
653        (SkillAgentSelection::Opencode, scope) => Ok(vec![resolve_target(
654            spec,
655            SkillAgent::Opencode,
656            scope,
657            options.skills_dir.as_deref(),
658        )?]),
659        (SkillAgentSelection::Hermes, scope) => Ok(vec![resolve_target(
660            spec,
661            SkillAgent::Hermes,
662            scope,
663            options.skills_dir.as_deref(),
664        )?]),
665    }
666}
667
668fn resolve_target(
669    spec: &SkillSpec,
670    agent: SkillAgent,
671    scope: SkillScope,
672    skills_dir: Option<&str>,
673) -> Result<SkillTarget, SkillError> {
674    let skills_dir = match skills_dir {
675        Some(dir) => expand_tilde(dir)?,
676        None => default_skills_dir(agent, scope)?,
677    };
678    let skill_dir = skills_dir.join(spec.name);
679    let skill_path = skill_dir.join(SKILL_FILE_NAME);
680    Ok(SkillTarget {
681        agent,
682        scope,
683        skills_dir,
684        skill_dir,
685        skill_path,
686    })
687}
688
689fn default_skills_dir(agent: SkillAgent, scope: SkillScope) -> Result<PathBuf, SkillError> {
690    match (agent, scope) {
691        (SkillAgent::Codex, SkillScope::Personal) => {
692            if let Some(codex_home) = env_dir("CODEX_HOME") {
693                Ok(codex_home.join("skills"))
694            } else {
695                Ok(home_dir()?.join(".codex").join("skills"))
696            }
697        }
698        (SkillAgent::Codex, SkillScope::Workspace) => workspace_skills_dir(".codex"),
699        (SkillAgent::ClaudeCode, SkillScope::Personal) => {
700            Ok(home_dir()?.join(".claude").join("skills"))
701        }
702        (SkillAgent::ClaudeCode, SkillScope::Workspace) => workspace_skills_dir(".claude"),
703        (SkillAgent::Opencode, SkillScope::Personal) => {
704            if let Some(xdg) = env_dir("XDG_CONFIG_HOME") {
705                Ok(xdg.join("opencode").join("skills"))
706            } else {
707                Ok(home_dir()?.join(".config").join("opencode").join("skills"))
708            }
709        }
710        (SkillAgent::Opencode, SkillScope::Workspace) => workspace_skills_dir(".opencode"),
711        (SkillAgent::Hermes, SkillScope::Personal) => {
712            if let Some(hermes_home) = env_dir("HERMES_HOME") {
713                Ok(hermes_home.join("skills"))
714            } else {
715                Ok(home_dir()?.join(".hermes").join("skills"))
716            }
717        }
718        (SkillAgent::Hermes, SkillScope::Workspace) => workspace_skills_dir(".hermes"),
719    }
720}
721
722fn workspace_skills_dir(agent_dir: &str) -> Result<PathBuf, SkillError> {
723    std::env::current_dir()
724        .map(|dir| dir.join(agent_dir).join("skills"))
725        .map_err(|e| SkillError::io("resolve current directory", e))
726}
727
728fn target_status(spec: &SkillSpec, target: &SkillTarget) -> Result<SkillTargetStatus, SkillError> {
729    // Reported rather than raised: one target reachable only through a link
730    // must not cost the operator the status of every other target. Nothing is
731    // read through it, so this says what is wrong without following it.
732    if let Err(message) = containment_failure(spec, target) {
733        return Ok(SkillTargetStatus {
734            agent: target.agent,
735            scope: target.scope,
736            skills_dir: target.skills_dir.clone(),
737            skill_dir: target.skill_dir.clone(),
738            skill_path: target.skill_path.clone(),
739            installed: false,
740            managed: false,
741            valid: false,
742            current: false,
743            validation_error: Some(message),
744        });
745    }
746    let Some(kind) = skill_path_file_type(&target.skill_path)? else {
747        return Ok(SkillTargetStatus {
748            agent: target.agent,
749            scope: target.scope,
750            skills_dir: target.skills_dir.clone(),
751            skill_dir: target.skill_dir.clone(),
752            skill_path: target.skill_path.clone(),
753            installed: false,
754            managed: false,
755            valid: false,
756            current: false,
757            validation_error: None,
758        });
759    };
760    let installed = true;
761    let mut valid = false;
762    let mut current = false;
763    let mut validation_error = None;
764    let mut managed = false;
765    if kind.is_symlink() {
766        validation_error = Some("target SKILL.md is a symlink; refusing to follow it".to_string());
767    } else if kind.is_file() {
768        let text = std::fs::read_to_string(&target.skill_path)
769            .map_err(|e| SkillError::io("read skill", e))?;
770        managed = skill_text_is_managed_or_bundled(spec, &text);
771        current = normalized_content_hash(spec, &text) == source_hash(spec)
772            && assets_current(spec, &target.skill_dir);
773        match validate_skill_text(spec, &text, SkillErrorKind::Refused) {
774            Ok(()) => valid = true,
775            Err(err) => validation_error = Some(err.message),
776        }
777    } else {
778        validation_error = Some("target SKILL.md is not a regular file".to_string());
779    }
780    Ok(SkillTargetStatus {
781        agent: target.agent,
782        scope: target.scope,
783        skills_dir: target.skills_dir.clone(),
784        skill_dir: target.skill_dir.clone(),
785        skill_path: target.skill_path.clone(),
786        installed,
787        managed,
788        valid,
789        current,
790        validation_error,
791    })
792}
793
794fn target_uninstall_status(target: &SkillTarget, removed: bool) -> SkillUninstallStatus {
795    SkillUninstallStatus {
796        agent: target.agent,
797        scope: target.scope,
798        skills_dir: target.skills_dir.clone(),
799        skill_dir: target.skill_dir.clone(),
800        skill_path: target.skill_path.clone(),
801        removed,
802        assets_removed: Vec::new(),
803        directory_retained: std::fs::symlink_metadata(&target.skill_dir).is_ok(),
804    }
805}
806
807fn target_status_lossy(spec: &SkillSpec, target: &SkillTarget) -> SkillTargetStatus {
808    target_status(spec, target).unwrap_or_else(|err| {
809        let installed = std::fs::symlink_metadata(&target.skill_path).is_ok();
810        SkillTargetStatus {
811            agent: target.agent,
812            scope: target.scope,
813            skills_dir: target.skills_dir.clone(),
814            skill_dir: target.skill_dir.clone(),
815            skill_path: target.skill_path.clone(),
816            installed,
817            managed: false,
818            valid: false,
819            current: false,
820            validation_error: Some(err.message),
821        }
822    })
823}
824
825fn install_report_lossy(spec: &SkillSpec, targets: &[SkillTarget], installed: bool) -> SkillReport {
826    SkillReport::Install {
827        skill: spec.name.to_string(),
828        installed,
829        targets: targets
830            .iter()
831            .map(|target| target_status_lossy(spec, target))
832            .collect(),
833        hint: "restart the agent so it reloads installed skills",
834    }
835}
836
837fn uninstall_report_lossy(
838    spec: &SkillSpec,
839    targets: &[SkillTarget],
840    removed: &[SkillUninstallStatus],
841) -> SkillReport {
842    let mut statuses = Vec::with_capacity(targets.len());
843    for target in targets {
844        if let Some(status) = removed.iter().find(|status| {
845            status.agent == target.agent
846                && status.scope == target.scope
847                && status.skill_path == target.skill_path
848        }) {
849            statuses.push(status.clone());
850        } else {
851            statuses.push(target_uninstall_status(target, false));
852        }
853    }
854    SkillReport::Uninstall {
855        skill: spec.name.to_string(),
856        removed_any: statuses.iter().any(|status| status.removed),
857        targets: statuses,
858    }
859}
860
861fn generated_by(spec: &SkillSpec) -> String {
862    format!("Generated by {} skill install", spec.marker_slug)
863}
864
865fn text_hash(text: &str) -> String {
866    let mut hash = FNV1A64_OFFSET;
867    for byte in text.as_bytes() {
868        hash ^= u64::from(*byte);
869        hash = hash.wrapping_mul(FNV1A64_PRIME);
870    }
871    format!("{hash:016x}")
872}
873
874fn source_hash(spec: &SkillSpec) -> String {
875    normalized_content_hash(spec, spec.source)
876}
877
878fn normalized_content_hash(spec: &SkillSpec, text: &str) -> String {
879    text_hash(&normalize_skill_text(spec, text))
880}
881
882fn managed_marker_block(spec: &SkillSpec) -> String {
883    let slug = spec.marker_slug;
884    format!(
885        "<!--\n{}\n{}-managed-skill: true\n{}-managed-skill-name: {}\n{}-managed-skill-owner: {}\n{}-managed-skill-content-hash-fnv1a64: {}\n-->",
886        generated_by(spec),
887        slug,
888        slug,
889        spec.name,
890        slug,
891        slug,
892        slug,
893        source_hash(spec)
894    )
895}
896
897fn managed_skill_contents(spec: &SkillSpec) -> String {
898    let block = managed_marker_block(spec);
899    let mut lines = spec.source.lines();
900    let mut output = String::new();
901    let mut inserted = false;
902    if let Some(first) = lines.next() {
903        output.push_str(first);
904        output.push('\n');
905    }
906    for line in lines {
907        output.push_str(line);
908        output.push('\n');
909        if !inserted && line.trim() == "---" {
910            output.push_str(&block);
911            output.push_str("\n\n");
912            inserted = true;
913        }
914    }
915    if !inserted {
916        output.push_str(&block);
917        output.push('\n');
918    }
919    output
920}
921
922fn validate_installed_skill(spec: &SkillSpec, path: &Path) -> Result<(), SkillError> {
923    let text =
924        std::fs::read_to_string(path).map_err(|e| SkillError::io("read installed skill", e))?;
925    // The source was validated before writing, so a rejection here means the
926    // file on disk is not what was written.
927    validate_skill_text(spec, &text, SkillErrorKind::Io)
928}
929
930fn validate_skill_text(
931    spec: &SkillSpec,
932    text: &str,
933    kind: SkillErrorKind,
934) -> Result<(), SkillError> {
935    crate::skill::validate_skill_named(text, spec.name).map_err(|err| {
936        SkillError::new(
937            kind,
938            format!("invalid {} skill front matter: {err}", spec.title),
939            Some(format!(
940                "make SKILL.md metadata conform to the Agent Skills specification and set name to {}",
941                spec.name
942            )),
943        )
944    })?;
945    Ok(())
946}
947
948fn is_managed_or_bundled_skill(spec: &SkillSpec, path: &Path) -> Result<bool, SkillError> {
949    let Some(kind) = skill_path_file_type(path)? else {
950        return Ok(false);
951    };
952    if kind.is_symlink() {
953        return Err(SkillError::new(
954            SkillErrorKind::Refused,
955            format!("refusing to inspect symlinked skill at {}", path.display()),
956            Some("pass --force to replace or remove the symlink itself".to_string()),
957        ));
958    }
959    let text = std::fs::read_to_string(path).map_err(|e| SkillError::io("read skill", e))?;
960    Ok(skill_text_is_managed_or_bundled(spec, &text))
961}
962
963fn skill_text_is_managed_or_bundled(spec: &SkillSpec, text: &str) -> bool {
964    skill_text_has_managed_identity(spec, text)
965        || normalize_skill_text(spec, text) == normalize_skill_text(spec, spec.source)
966}
967
968fn skill_text_has_managed_identity(spec: &SkillSpec, text: &str) -> bool {
969    for block in html_comment_blocks(text) {
970        if managed_marker_block_has_identity(spec, &block) {
971            return true;
972        }
973    }
974    false
975}
976
977fn managed_marker_block_has_identity(spec: &SkillSpec, block: &str) -> bool {
978    let slug = spec.marker_slug;
979    let generated_by_line = generated_by(spec);
980    let managed_line = format!("{slug}-managed-skill: true");
981    let name_line = format!("{slug}-managed-skill-name: {}", spec.name);
982    let owner_line = format!("{slug}-managed-skill-owner: {slug}");
983    let mut has_generated_by = false;
984    let mut has_managed = false;
985    let mut has_name = false;
986    let mut has_owner = false;
987    for line in block.replace("\r\n", "\n").lines() {
988        let trimmed = line.trim();
989        has_generated_by |= trimmed == generated_by_line;
990        has_managed |= trimmed == managed_line;
991        has_name |= trimmed == name_line;
992        has_owner |= trimmed == owner_line;
993    }
994    has_generated_by && has_managed && has_name && has_owner
995}
996
997fn html_comment_blocks(text: &str) -> Vec<String> {
998    let normalized = text.replace("\r\n", "\n");
999    let mut blocks = Vec::new();
1000    let mut lines = normalized.lines();
1001    while let Some(line) = lines.next() {
1002        if line.trim() != "<!--" {
1003            continue;
1004        }
1005        let mut block = vec![line.to_string()];
1006        for next in lines.by_ref() {
1007            block.push(next.to_string());
1008            if next.trim() == "-->" {
1009                blocks.push(block.join("\n"));
1010                break;
1011            }
1012        }
1013    }
1014    blocks
1015}
1016
1017fn strip_managed_marker_blocks(spec: &SkillSpec, text: &str) -> String {
1018    let normalized = text.replace("\r\n", "\n");
1019    let mut output = Vec::new();
1020    let mut lines = normalized.lines();
1021    while let Some(line) = lines.next() {
1022        if line.trim() != "<!--" {
1023            output.push(line.to_string());
1024            continue;
1025        }
1026        let mut block = vec![line.to_string()];
1027        let mut closed = false;
1028        for next in lines.by_ref() {
1029            block.push(next.to_string());
1030            if next.trim() == "-->" {
1031                closed = true;
1032                break;
1033            }
1034        }
1035        if closed {
1036            let block_text = block.join("\n");
1037            if managed_marker_block_has_identity(spec, &block_text) {
1038                continue;
1039            }
1040        }
1041        output.extend(block);
1042    }
1043    output.join("\n")
1044}
1045
1046fn normalize_skill_text(spec: &SkillSpec, text: &str) -> String {
1047    let text = strip_managed_marker_blocks(spec, text);
1048    // Drop the managed-marker blocks, then collapse runs of blank lines to one so that the blank
1049    // line `managed_skill_contents` inserts after the marker block does not make a managed install
1050    // compare unequal to the bundled source.
1051    let mut out: Vec<&str> = Vec::new();
1052    for line in text.lines() {
1053        let trimmed = line.trim();
1054        if trimmed.is_empty() && out.last().is_some_and(|prev| prev.trim().is_empty()) {
1055            continue;
1056        }
1057        out.push(line);
1058    }
1059    out.join("\n").trim().to_string()
1060}
1061
1062fn validate_spec(spec: &SkillSpec) -> Result<(), SkillError> {
1063    validate_slug("skill name", spec.name)?;
1064    validate_slug("marker slug", spec.marker_slug)?;
1065    validate_skill_text(spec, spec.source, SkillErrorKind::InvalidSpec)
1066}
1067
1068fn validate_slug(field: &str, value: &str) -> Result<(), SkillError> {
1069    if slug_is_valid(value) {
1070        return Ok(());
1071    }
1072    Err(SkillError::new(
1073        SkillErrorKind::InvalidSpec,
1074        format!(
1075            "invalid {field} {value:?}: expected a lowercase slug matching [a-z0-9][a-z0-9-]*[a-z0-9]"
1076        ),
1077        Some("use lowercase ASCII letters, digits, and single hyphen-separated words".to_string()),
1078    ))
1079}
1080
1081fn slug_is_valid(value: &str) -> bool {
1082    let bytes = value.as_bytes();
1083    if bytes.is_empty() {
1084        return false;
1085    }
1086    fn is_lower_alnum(byte: u8) -> bool {
1087        byte.is_ascii_lowercase() || byte.is_ascii_digit()
1088    }
1089    if !is_lower_alnum(bytes[0]) || !is_lower_alnum(bytes[bytes.len() - 1]) {
1090        return false;
1091    }
1092    bytes
1093        .iter()
1094        .all(|byte| is_lower_alnum(*byte) || *byte == b'-')
1095}
1096
1097fn skill_path_file_type(path: &Path) -> Result<Option<std::fs::FileType>, SkillError> {
1098    match std::fs::symlink_metadata(path) {
1099        Ok(metadata) => Ok(Some(metadata.file_type())),
1100        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
1101        Err(err) => Err(SkillError::io("inspect skill path", err)),
1102    }
1103}
1104
1105/// Refuse to reach `path` through a symbolic link somewhere below `root`.
1106///
1107/// Everything a skill install writes goes to a fixed name under a skills root
1108/// the caller named, and the final file's own type is judged separately — a
1109/// symlink there is replaced, never followed. What nothing else judges is the
1110/// directories in between. `create_dir_all` walks straight through a link
1111/// without complaint, so a workspace that ships `.claude/skills/<name>` as a
1112/// link to another directory would silently redirect a fixed-name write, and
1113/// the matching uninstall would delete files wherever it pointed.
1114///
1115/// `--force` does not relax this. It permits replacing an unmanaged file
1116/// *inside* the root; it is not permission to write outside it.
1117///
1118/// `root` itself is deliberately not checked: the caller chose it, and a home
1119/// directory that is a link onto another volume is ordinary.
1120///
1121/// This is a check, so a link swapped in between it and the write that follows
1122/// is still possible. Closing that window needs directory-handle-relative
1123/// opens, which Rust's standard library does not expose; an attacker able to
1124/// win that race can already write inside the tree being installed into.
1125fn ensure_no_symlinked_dirs(root: &Path, path: &Path) -> Result<(), SkillError> {
1126    let Ok(relative) = path.strip_prefix(root) else {
1127        return Err(SkillError::new(
1128            SkillErrorKind::Refused,
1129            format!(
1130                "{} is not inside the skills directory {}",
1131                path.display(),
1132                root.display()
1133            ),
1134            Some("pass --skills-dir to install where you mean to".to_string()),
1135        ));
1136    };
1137    let mut current = root.to_path_buf();
1138    let mut components = relative.components().peekable();
1139    while let Some(component) = components.next() {
1140        current.push(component);
1141        // The last component is the file itself, and installing over it is a
1142        // rename that replaces a link rather than following it.
1143        if components.peek().is_none() {
1144            break;
1145        }
1146        match std::fs::symlink_metadata(&current) {
1147            Ok(metadata) if metadata.file_type().is_symlink() => {
1148                return Err(SkillError::new(
1149                    SkillErrorKind::Refused,
1150                    format!(
1151                        "refusing to reach {} through the symlinked directory {}",
1152                        path.display(),
1153                        current.display()
1154                    ),
1155                    Some(
1156                        "replace the link with a real directory, or pass --skills-dir".to_string(),
1157                    ),
1158                ));
1159            }
1160            Ok(_) => {}
1161            // Nothing exists below here yet, so nothing below here is a link.
1162            Err(err) if err.kind() == std::io::ErrorKind::NotFound => break,
1163            Err(err) => return Err(SkillError::io("inspect skill path", err)),
1164        }
1165    }
1166    Ok(())
1167}
1168
1169/// The containment message for a target whose skill file or bundled assets
1170/// cannot be reached without following a link out of the skills directory, or
1171/// `Ok(())` when every one of them stays inside it.
1172fn containment_failure(spec: &SkillSpec, target: &SkillTarget) -> Result<(), String> {
1173    let mut paths = vec![target.skill_path.clone()];
1174    paths.extend(
1175        spec.assets
1176            .iter()
1177            .map(|asset| asset_target_path(&target.skill_dir, asset.path)),
1178    );
1179    for path in paths {
1180        if let Err(err) = ensure_no_symlinked_dirs(&target.skills_dir, &path) {
1181            return Err(err.message);
1182        }
1183    }
1184    Ok(())
1185}
1186
1187fn write_skill_atomic(target: &SkillTarget, content: &str) -> Result<(), SkillError> {
1188    ensure_no_symlinked_dirs(&target.skills_dir, &target.skill_path)?;
1189    write_file_atomic(&target.skill_path, content, "install skill file")
1190}
1191
1192/// Atomically install `content` at `path` through the crate's one atomic file
1193/// installation, so a reader never sees a partial file, a pre-existing symlink
1194/// is replaced rather than followed, and the new directory entry is synced
1195/// before this reports success.
1196///
1197/// An existing regular file keeps its own permissions; a file created here is
1198/// world-readable, which is what a skill an agent must load has to be.
1199fn write_file_atomic(path: &Path, content: &str, action: &str) -> Result<(), SkillError> {
1200    let preserved = match std::fs::symlink_metadata(path) {
1201        Ok(metadata) if metadata.file_type().is_file() => Some(metadata.permissions()),
1202        _ => None,
1203    };
1204    let unix_mode = if preserved.is_some() {
1205        None
1206    } else {
1207        Some(0o644)
1208    };
1209    crate::AtomicWrite::new(content.as_bytes())
1210        .with_permissions(preserved)
1211        .with_unix_mode(unix_mode)
1212        .write(path)
1213        .map_err(|err| SkillError::write_failed(action, err))
1214}
1215
1216/// Reject an asset path that is absolute or carries a `.`/`..`/empty segment, so
1217/// a bundled asset can only ever land inside the skill directory.
1218fn validate_asset_path(path: &str) -> Result<(), SkillError> {
1219    let bad = path.is_empty()
1220        || Path::new(path).is_absolute()
1221        || path
1222            .split(['/', '\\'])
1223            .any(|seg| seg.is_empty() || seg == "." || seg == "..");
1224    if bad {
1225        return Err(SkillError::new(
1226            SkillErrorKind::InvalidSpec,
1227            format!("invalid skill asset path: {path}"),
1228            Some(
1229                "asset paths must be relative to the skill directory with no `.`/`..` segments"
1230                    .to_string(),
1231            ),
1232        ));
1233    }
1234    Ok(())
1235}
1236
1237/// Resolve an asset's `/`-separated relative path to an absolute path under
1238/// `skill_dir`, one segment at a time so it works on every platform.
1239fn asset_target_path(skill_dir: &Path, rel_path: &str) -> PathBuf {
1240    let mut out = skill_dir.to_path_buf();
1241    for seg in rel_path.split(['/', '\\']) {
1242        out.push(seg);
1243    }
1244    out
1245}
1246
1247/// Write every bundled asset under the target skill directory, creating parent
1248/// directories as needed. Paths are assumed already validated by `install`.
1249fn install_target_assets(spec: &SkillSpec, target: &SkillTarget) -> Result<(), SkillError> {
1250    for asset in spec.assets {
1251        let dest = asset_target_path(&target.skill_dir, asset.path);
1252        // Re-checked here rather than only in the preflight: the asset tree is
1253        // several directories deep, and this is the last moment before the
1254        // write that could land outside the root.
1255        ensure_no_symlinked_dirs(&target.skills_dir, &dest)?;
1256        if let Some(parent) = dest.parent() {
1257            std::fs::create_dir_all(parent)
1258                .map_err(|e| SkillError::io("create skill asset dir", e))?;
1259        }
1260        write_file_atomic(&dest, asset.contents, "install skill asset")?;
1261    }
1262    Ok(())
1263}
1264
1265/// True when every bundled asset is present on disk and byte-equal to the
1266/// bundle. A single-file skill (`assets == []`) is trivially current.
1267fn assets_current(spec: &SkillSpec, skill_dir: &Path) -> bool {
1268    spec.assets.iter().all(|asset| {
1269        let dest = asset_target_path(skill_dir, asset.path);
1270        std::fs::read_to_string(&dest)
1271            .map(|text| text == asset.contents)
1272            .unwrap_or(false)
1273    })
1274}
1275
1276/// Remove the bundled asset files, then their now-empty parent directories,
1277/// deepest first.
1278///
1279/// The two halves are not the same promise, and used to be reported as if they
1280/// were. Every managed *file* must go: one that survives is a stale reference
1281/// the next `status` cannot see, because that reads `SKILL.md` — which is
1282/// already gone — and calls the target uninstalled. So a failed `remove_file`
1283/// is returned, not swallowed. A *directory* that refuses to go is the normal
1284/// case rather than a fault: `remove_dir` fails exactly when the user put
1285/// something of their own in it, and their file is not this tool's to delete.
1286/// That outcome is reported instead of raising.
1287fn remove_target_assets(spec: &SkillSpec, target: &SkillTarget) -> Result<Vec<String>, SkillError> {
1288    let mut removed = Vec::new();
1289    let mut dirs: Vec<PathBuf> = Vec::new();
1290    for asset in spec.assets {
1291        let dest = asset_target_path(&target.skill_dir, asset.path);
1292        ensure_no_symlinked_dirs(&target.skills_dir, &dest)?;
1293        match std::fs::remove_file(&dest) {
1294            Ok(()) => removed.push(asset.path.to_string()),
1295            // Already absent: the end state this asked for.
1296            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
1297            Err(err) => {
1298                return Err(SkillError::io(
1299                    &format!("remove bundled skill asset {}", asset.path),
1300                    err,
1301                ));
1302            }
1303        }
1304        let mut dir = dest.parent().map(Path::to_path_buf);
1305        while let Some(current) = dir {
1306            if current == target.skill_dir || !current.starts_with(&target.skill_dir) {
1307                break;
1308            }
1309            if !dirs.contains(&current) {
1310                dirs.push(current.clone());
1311            }
1312            dir = current.parent().map(Path::to_path_buf);
1313        }
1314    }
1315    dirs.sort_by_key(|d| std::cmp::Reverse(d.components().count()));
1316    for dir in dirs {
1317        let _ = std::fs::remove_dir(&dir);
1318    }
1319    Ok(removed)
1320}
1321
1322/// An environment variable naming a directory, ignored when empty or
1323/// relative: either would put a personal skill under the current directory.
1324fn env_dir(name: &str) -> Option<PathBuf> {
1325    std::env::var_os(name)
1326        .map(PathBuf::from)
1327        .filter(|path| path.is_absolute())
1328}
1329
1330fn home_dir() -> Result<PathBuf, SkillError> {
1331    env_dir("HOME")
1332        .or_else(|| env_dir("USERPROFILE"))
1333        .ok_or_else(|| {
1334            SkillError::new(
1335                SkillErrorKind::Usage,
1336                "cannot determine home directory".to_string(),
1337                Some("pass --skills-dir explicitly".to_string()),
1338            )
1339        })
1340}
1341
1342fn expand_tilde(input: &str) -> Result<PathBuf, SkillError> {
1343    if input == "~" {
1344        return home_dir();
1345    }
1346    if let Some(rest) = input.strip_prefix("~/") {
1347        return Ok(home_dir()?.join(rest));
1348    }
1349    Ok(PathBuf::from(input))
1350}
1351
1352#[cfg(test)]
1353mod tests {
1354    use super::*;
1355    use std::time::{SystemTime, UNIX_EPOCH};
1356
1357    const SKILL_SOURCE: &str =
1358        "---\nname: agent-first-test\ndescription: test skill\n---\n\n# Body\n\nrules.\n";
1359
1360    fn spec() -> SkillSpec<'static> {
1361        SkillSpec {
1362            name: "agent-first-test",
1363            source: SKILL_SOURCE,
1364            title: "Agent-First Test",
1365            marker_slug: "aftest",
1366            assets: &[],
1367        }
1368    }
1369
1370    fn managed_skill_with_body(body: &str) -> String {
1371        format!(
1372            "---\nname: agent-first-test\ndescription: test skill\n---\n{}\n\n{body}",
1373            managed_marker_block(&spec())
1374        )
1375    }
1376
1377    fn temp_skills_dir(name: &str) -> PathBuf {
1378        let suffix = SystemTime::now()
1379            .duration_since(UNIX_EPOCH)
1380            .map(|d| d.as_nanos())
1381            .unwrap_or(0);
1382        std::env::temp_dir().join(format!(
1383            "afdata_skill_{name}_{}_{}",
1384            std::process::id(),
1385            suffix
1386        ))
1387    }
1388
1389    fn options(agent: SkillAgentSelection, dir: &Path, force: bool) -> SkillOptions {
1390        SkillOptions {
1391            agent,
1392            scope: SkillScope::Personal,
1393            skills_dir: Some(dir.to_string_lossy().to_string()),
1394            force,
1395        }
1396    }
1397
1398    fn custom_target(agent: SkillAgent, dir: &Path) -> SkillTarget {
1399        let skill_dir = dir.join("agent-first-test");
1400        SkillTarget {
1401            agent,
1402            scope: SkillScope::Personal,
1403            skills_dir: dir.to_path_buf(),
1404            skill_path: skill_dir.join(SKILL_FILE_NAME),
1405            skill_dir,
1406        }
1407    }
1408
1409    #[test]
1410    fn validates_bundled_frontmatter() {
1411        assert!(crate::skill::validate_skill_named(SKILL_SOURCE, "agent-first-test").is_ok());
1412    }
1413
1414    #[test]
1415    fn rejects_unquoted_colon_space() {
1416        let bad = "---\nname: x\ndescription: broken: yaml\n---\n";
1417        assert!(crate::skill::validate_skill(bad).is_err());
1418    }
1419
1420    fn install_status_uninstall_for(agent: SkillAgentSelection, expect: SkillAgent, tag: &str) {
1421        let dir = temp_skills_dir(tag);
1422        let opts = options(agent, &dir, false);
1423        let skill_path = dir.join("agent-first-test").join(SKILL_FILE_NAME);
1424
1425        let installed = run_skill_admin(&spec(), SkillAction::Install, &opts);
1426        assert!(installed.is_ok());
1427        assert!(skill_path.is_file());
1428        let text = std::fs::read_to_string(&skill_path).unwrap_or_default();
1429        assert!(text.contains(&managed_marker_block(&spec())));
1430        assert!(text.contains("aftest-managed-skill-name: agent-first-test"));
1431        assert!(text.contains("aftest-managed-skill-owner: aftest"));
1432        assert!(text.contains("aftest-managed-skill-content-hash-fnv1a64:"));
1433        assert!(!text.contains("aftest-managed-skill-source-hash-fnv1a64:"));
1434
1435        let status = run_skill_admin(&spec(), SkillAction::Status, &opts);
1436        assert!(status.is_ok());
1437        if let Ok(SkillReport::Status {
1438            installed_all,
1439            valid_all,
1440            current_all,
1441            targets,
1442            ..
1443        }) = status
1444        {
1445            assert!(installed_all);
1446            assert!(valid_all);
1447            assert!(current_all);
1448            assert_eq!(targets.first().map(|t| t.agent), Some(expect));
1449            assert_eq!(targets.first().map(|t| t.current), Some(true));
1450        }
1451
1452        let removed = run_skill_admin(&spec(), SkillAction::Uninstall, &opts);
1453        assert!(removed.is_ok());
1454        assert!(!skill_path.exists());
1455        let _ = std::fs::remove_dir_all(dir);
1456    }
1457
1458    #[test]
1459    fn install_status_uninstall_codex() {
1460        install_status_uninstall_for(SkillAgentSelection::Codex, SkillAgent::Codex, "codex");
1461    }
1462
1463    #[test]
1464    fn install_status_uninstall_claude_code() {
1465        install_status_uninstall_for(
1466            SkillAgentSelection::ClaudeCode,
1467            SkillAgent::ClaudeCode,
1468            "claude",
1469        );
1470    }
1471
1472    #[test]
1473    fn install_status_uninstall_opencode() {
1474        install_status_uninstall_for(
1475            SkillAgentSelection::Opencode,
1476            SkillAgent::Opencode,
1477            "opencode",
1478        );
1479    }
1480
1481    #[test]
1482    fn install_status_uninstall_hermes() {
1483        install_status_uninstall_for(SkillAgentSelection::Hermes, SkillAgent::Hermes, "hermes");
1484    }
1485
1486    fn spec_with_assets() -> SkillSpec<'static> {
1487        const ASSETS: &[SkillAsset] = &[
1488            SkillAsset {
1489                path: "references/guide.md",
1490                contents: "# guide\n",
1491            },
1492            SkillAsset {
1493                path: "references/registry.json",
1494                contents: "{\"ok\":true}\n",
1495            },
1496        ];
1497        SkillSpec {
1498            name: "agent-first-test",
1499            source: SKILL_SOURCE,
1500            title: "Agent-First Test",
1501            marker_slug: "aftest",
1502            assets: ASSETS,
1503        }
1504    }
1505
1506    #[test]
1507    fn install_writes_and_uninstall_removes_bundled_assets() {
1508        let dir = temp_skills_dir("assets");
1509        let opts = options(SkillAgentSelection::Codex, &dir, false);
1510        let skill_dir = dir.join("agent-first-test");
1511        let guide = skill_dir.join("references").join("guide.md");
1512        let registry = skill_dir.join("references").join("registry.json");
1513
1514        assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
1515        assert_eq!(
1516            std::fs::read_to_string(&guide).unwrap_or_default(),
1517            "# guide\n"
1518        );
1519        assert_eq!(
1520            std::fs::read_to_string(&registry).unwrap_or_default(),
1521            "{\"ok\":true}\n"
1522        );
1523
1524        // A SKILL.md-only install (a bundled asset missing) must report
1525        // not-current so a plain re-install repopulates it — the exact
1526        // regression this fixes.
1527        std::fs::remove_file(&guide).unwrap();
1528        match run_skill_admin(&spec_with_assets(), SkillAction::Status, &opts) {
1529            Ok(SkillReport::Status { current_all, .. }) => {
1530                assert!(
1531                    !current_all,
1532                    "a missing asset must make the skill not-current"
1533                );
1534            }
1535            other => panic!("unexpected status: {other:?}"),
1536        }
1537        assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
1538        assert!(guide.is_file(), "re-install must restore the missing asset");
1539
1540        assert!(run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts).is_ok());
1541        assert!(!skill_dir.join(SKILL_FILE_NAME).exists());
1542        assert!(!guide.exists(), "uninstall must remove bundled assets");
1543        assert!(
1544            !skill_dir.join("references").exists(),
1545            "uninstall must remove now-empty asset directories"
1546        );
1547        assert!(
1548            !skill_dir.exists(),
1549            "uninstall must remove the skill directory"
1550        );
1551        let _ = std::fs::remove_dir_all(dir);
1552    }
1553
1554    #[test]
1555    fn install_rejects_escaping_asset_path() {
1556        const ESCAPE: &[SkillAsset] = &[SkillAsset {
1557            path: "../evil.md",
1558            contents: "x",
1559        }];
1560        let dir = temp_skills_dir("assets-escape");
1561        let opts = options(SkillAgentSelection::Codex, &dir, false);
1562        let spec = SkillSpec {
1563            name: "agent-first-test",
1564            source: SKILL_SOURCE,
1565            title: "Agent-First Test",
1566            marker_slug: "aftest",
1567            assets: ESCAPE,
1568        };
1569        assert!(
1570            run_skill_admin(&spec, SkillAction::Install, &opts).is_err(),
1571            "an asset path escaping the skill dir must be rejected"
1572        );
1573        assert!(!dir.join("evil.md").exists());
1574        let _ = std::fs::remove_dir_all(dir);
1575    }
1576
1577    #[test]
1578    fn status_reports_stale_install_as_not_current() {
1579        let dir = temp_skills_dir("stale");
1580        let opts = options(SkillAgentSelection::Opencode, &dir, false);
1581        let skill_dir = dir.join("agent-first-test");
1582        let skill_path = skill_dir.join(SKILL_FILE_NAME);
1583        assert!(std::fs::create_dir_all(&skill_dir).is_ok());
1584        // A managed marker but stale body: valid + managed, but not current.
1585        let stale = managed_skill_with_body("# Body\n\nOLD rules.\n");
1586        assert!(std::fs::write(&skill_path, stale).is_ok());
1587
1588        let status = run_skill_admin(&spec(), SkillAction::Status, &opts);
1589        if let Ok(SkillReport::Status {
1590            current_all,
1591            targets,
1592            ..
1593        }) = status
1594        {
1595            assert!(!current_all);
1596            if let Some(t) = targets.first() {
1597                assert!(t.installed);
1598                assert!(t.valid);
1599                assert!(t.managed);
1600                assert!(!t.current);
1601            }
1602        }
1603
1604        // Reinstall makes it current again.
1605        assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_ok());
1606        let refreshed = std::fs::read_to_string(&skill_path).unwrap_or_default();
1607        assert!(refreshed.contains(&managed_marker_block(&spec())));
1608        assert!(!refreshed.contains("<!-- aftest-managed-skill: true -->"));
1609        if let Ok(SkillReport::Status { targets, .. }) =
1610            run_skill_admin(&spec(), SkillAction::Status, &opts)
1611        {
1612            assert_eq!(targets.first().map(|t| t.current), Some(true));
1613        }
1614        let _ = std::fs::remove_dir_all(dir);
1615    }
1616
1617    #[test]
1618    fn random_text_with_marker_words_is_not_managed() {
1619        let dir = temp_skills_dir("marker-words");
1620        let opts = options(SkillAgentSelection::Opencode, &dir, false);
1621        let skill_dir = dir.join("agent-first-test");
1622        let skill_path = skill_dir.join(SKILL_FILE_NAME);
1623        assert!(std::fs::create_dir_all(&skill_dir).is_ok());
1624        let random = format!(
1625            "---\nname: agent-first-test\ndescription: test skill\n---\n\nThis mentions {} and {} but is not a generated block.\n",
1626            generated_by(&spec()),
1627            "aftest-managed-skill: true"
1628        );
1629        assert!(std::fs::write(&skill_path, random).is_ok());
1630
1631        if let Ok(SkillReport::Status { targets, .. }) =
1632            run_skill_admin(&spec(), SkillAction::Status, &opts)
1633        {
1634            assert_eq!(targets.first().map(|t| t.managed), Some(false));
1635        }
1636        assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_err());
1637        let _ = std::fs::remove_dir_all(dir);
1638    }
1639
1640    #[test]
1641    fn old_marker_format_is_not_managed() {
1642        let dir = temp_skills_dir("old-marker");
1643        let opts = options(SkillAgentSelection::Opencode, &dir, false);
1644        let skill_dir = dir.join("agent-first-test");
1645        let skill_path = skill_dir.join(SKILL_FILE_NAME);
1646        assert!(std::fs::create_dir_all(&skill_dir).is_ok());
1647        let old_marker = concat!(
1648            "---\n",
1649            "name: agent-first-test\n",
1650            "description: test skill\n",
1651            "---\n",
1652            "<!--\n",
1653            "Generated by aftest skill install\n",
1654            "aftest-managed-skill: true\n",
1655            "aftest-managed-skill-name: agent-first-test\n",
1656            "aftest-managed-skill-source-hash-fnv1a64: deadbeef\n",
1657            "-->\n",
1658            "\n",
1659            "# Body\n",
1660            "\n",
1661            "rules.\n"
1662        );
1663        assert!(std::fs::write(&skill_path, old_marker).is_ok());
1664
1665        if let Ok(SkillReport::Status { targets, .. }) =
1666            run_skill_admin(&spec(), SkillAction::Status, &opts)
1667            && let Some(t) = targets.first()
1668        {
1669            assert!(t.installed);
1670            assert!(t.valid);
1671            assert!(!t.managed);
1672            assert!(!t.current);
1673        }
1674        assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_err());
1675        let _ = std::fs::remove_dir_all(dir);
1676    }
1677
1678    #[test]
1679    fn install_preflight_reports_all_targets_without_writing() {
1680        let dir = temp_skills_dir("install-preflight");
1681        let codex = custom_target(SkillAgent::Codex, &dir.join("codex"));
1682        let opencode = custom_target(SkillAgent::Opencode, &dir.join("opencode"));
1683        assert!(std::fs::create_dir_all(&opencode.skill_dir).is_ok());
1684        assert!(
1685            std::fs::write(
1686                &opencode.skill_path,
1687                "---\nname: custom\ndescription: custom\n---\n"
1688            )
1689            .is_ok()
1690        );
1691        let opts = SkillOptions {
1692            agent: SkillAgentSelection::All,
1693            scope: SkillScope::Personal,
1694            skills_dir: None,
1695            force: false,
1696        };
1697
1698        let result = preflight_install_targets(&spec(), &opts, &[codex, opencode]);
1699        assert!(result.is_err());
1700        let Err(err) = result else {
1701            return;
1702        };
1703        assert!(
1704            err.message
1705                .contains("refusing to overwrite unmanaged skill")
1706        );
1707        assert!(!dir.join("codex").join("agent-first-test").exists());
1708        let partial_report = err.partial_report.map(|report| *report);
1709        assert!(matches!(partial_report, Some(SkillReport::Install { .. })));
1710        let Some(SkillReport::Install {
1711            installed, targets, ..
1712        }) = partial_report
1713        else {
1714            return;
1715        };
1716        assert!(!installed);
1717        assert_eq!(targets.len(), 2);
1718        assert_eq!(targets.first().map(|target| target.installed), Some(false));
1719        assert_eq!(targets.get(1).map(|target| target.installed), Some(true));
1720        assert_eq!(targets.get(1).map(|target| target.managed), Some(false));
1721        let _ = std::fs::remove_dir_all(dir);
1722    }
1723
1724    #[test]
1725    fn uninstall_preflight_reports_all_targets_without_removing() {
1726        let dir = temp_skills_dir("uninstall-preflight");
1727        let codex = custom_target(SkillAgent::Codex, &dir.join("codex"));
1728        let opencode = custom_target(SkillAgent::Opencode, &dir.join("opencode"));
1729        assert!(std::fs::create_dir_all(&codex.skill_dir).is_ok());
1730        assert!(std::fs::create_dir_all(&opencode.skill_dir).is_ok());
1731        assert!(std::fs::write(&codex.skill_path, managed_skill_contents(&spec())).is_ok());
1732        assert!(
1733            std::fs::write(
1734                &opencode.skill_path,
1735                "---\nname: custom\ndescription: custom\n---\n"
1736            )
1737            .is_ok()
1738        );
1739        let opts = SkillOptions {
1740            agent: SkillAgentSelection::All,
1741            scope: SkillScope::Personal,
1742            skills_dir: None,
1743            force: false,
1744        };
1745
1746        let result = preflight_uninstall_targets(&spec(), &opts, &[codex, opencode]);
1747        assert!(result.is_err());
1748        let Err(err) = result else {
1749            return;
1750        };
1751        assert!(err.message.contains("refusing to remove unmanaged skill"));
1752        assert!(
1753            dir.join("codex")
1754                .join("agent-first-test")
1755                .join(SKILL_FILE_NAME)
1756                .exists()
1757        );
1758        let partial_report = err.partial_report.map(|report| *report);
1759        assert!(matches!(
1760            partial_report,
1761            Some(SkillReport::Uninstall { .. })
1762        ));
1763        let Some(SkillReport::Uninstall {
1764            removed_any,
1765            targets,
1766            ..
1767        }) = partial_report
1768        else {
1769            return;
1770        };
1771        assert!(!removed_any);
1772        assert_eq!(targets.len(), 2);
1773        assert!(targets.iter().all(|target| !target.removed));
1774        let _ = std::fs::remove_dir_all(dir);
1775    }
1776
1777    #[test]
1778    fn install_and_uninstall_refuse_unmanaged() {
1779        let dir = temp_skills_dir("unmanaged");
1780        let skill_dir = dir.join("agent-first-test");
1781        let skill_path = skill_dir.join(SKILL_FILE_NAME);
1782        assert!(std::fs::create_dir_all(&skill_dir).is_ok());
1783        assert!(
1784            std::fs::write(&skill_path, "---\nname: custom\ndescription: custom\n---\n").is_ok()
1785        );
1786        let opts = options(SkillAgentSelection::Codex, &dir, false);
1787
1788        assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_err());
1789        assert!(run_skill_admin(&spec(), SkillAction::Uninstall, &opts).is_err());
1790        assert!(skill_path.exists());
1791        let _ = std::fs::remove_dir_all(dir);
1792    }
1793
1794    #[test]
1795    fn invalid_spec_slugs_are_rejected_before_path_resolution() {
1796        for name in ["", "../x", "x/y", ".hidden", "bad_name", "Bad"] {
1797            let bad = SkillSpec {
1798                name,
1799                source: SKILL_SOURCE,
1800                title: "Bad",
1801                marker_slug: "aftest",
1802                assets: &[],
1803            };
1804            let opts = options(SkillAgentSelection::Codex, Path::new("/tmp/afdata"), false);
1805            assert!(
1806                run_skill_admin(&bad, SkillAction::Status, &opts).is_err(),
1807                "{name:?}"
1808            );
1809        }
1810
1811        let bad_marker = SkillSpec {
1812            name: "agent-first-test",
1813            source: SKILL_SOURCE,
1814            title: "Bad",
1815            marker_slug: "../aftest",
1816            assets: &[],
1817        };
1818        let opts = options(SkillAgentSelection::Codex, Path::new("/tmp/afdata"), false);
1819        assert!(run_skill_admin(&bad_marker, SkillAction::Status, &opts).is_err());
1820    }
1821
1822    #[test]
1823    fn frontmatter_name_must_match_spec_name() {
1824        let bad = SkillSpec {
1825            name: "agent-first-test",
1826            source: "---\nname: other-skill\ndescription: test skill\n---\n",
1827            title: "Bad",
1828            marker_slug: "aftest",
1829            assets: &[],
1830        };
1831        let dir = temp_skills_dir("frontmatter-name");
1832        let opts = options(SkillAgentSelection::Codex, &dir, false);
1833        assert!(run_skill_admin(&bad, SkillAction::Install, &opts).is_err());
1834        let _ = std::fs::remove_dir_all(dir);
1835    }
1836
1837    #[cfg(unix)]
1838    #[test]
1839    fn symlink_target_is_rejected_by_default_and_force_does_not_follow() {
1840        use std::os::unix::fs::symlink;
1841
1842        let dir = temp_skills_dir("symlink-install");
1843        let opts = options(SkillAgentSelection::Codex, &dir, false);
1844        let force_opts = options(SkillAgentSelection::Codex, &dir, true);
1845        let skill_dir = dir.join("agent-first-test");
1846        let skill_path = skill_dir.join(SKILL_FILE_NAME);
1847        let external = dir.join("external.md");
1848        assert!(std::fs::create_dir_all(&skill_dir).is_ok());
1849        assert!(std::fs::write(&external, "external").is_ok());
1850        assert!(symlink(&external, &skill_path).is_ok());
1851
1852        assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_err());
1853        assert_eq!(
1854            std::fs::read_to_string(&external).unwrap_or_default(),
1855            "external"
1856        );
1857        assert!(run_skill_admin(&spec(), SkillAction::Uninstall, &opts).is_err());
1858        assert!(skill_path.is_symlink());
1859
1860        assert!(run_skill_admin(&spec(), SkillAction::Install, &force_opts).is_ok());
1861        assert_eq!(
1862            std::fs::read_to_string(&external).unwrap_or_default(),
1863            "external"
1864        );
1865        assert!(skill_path.is_file());
1866        assert!(!skill_path.is_symlink());
1867        let _ = std::fs::remove_dir_all(dir);
1868    }
1869
1870    #[cfg(unix)]
1871    #[test]
1872    fn a_symlinked_skill_directory_never_receives_a_write() {
1873        use std::os::unix::fs::symlink;
1874
1875        let dir = temp_skills_dir("symlink-skill-dir");
1876        let outside = temp_skills_dir("symlink-skill-dir-outside");
1877        assert!(std::fs::create_dir_all(&dir).is_ok());
1878        assert!(std::fs::create_dir_all(&outside).is_ok());
1879        let sentinel = outside.join(SKILL_FILE_NAME);
1880        assert!(std::fs::write(&sentinel, "sentinel").is_ok());
1881        // The shape a hostile checkout ships: the skill's own directory is a
1882        // link somewhere else, and every path below it is a fixed name.
1883        assert!(symlink(&outside, dir.join("agent-first-test")).is_ok());
1884
1885        for force in [false, true] {
1886            let opts = options(SkillAgentSelection::Codex, &dir, force);
1887            let err = run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts)
1888                .expect_err("install through a symlinked skill directory must fail");
1889            assert!(
1890                err.message.contains("symlinked directory"),
1891                "unexpected message: {}",
1892                err.message
1893            );
1894            assert_eq!(
1895                err.hint.as_deref(),
1896                Some("--force does not permit writing outside the skills directory"),
1897                "--force must not read as permission to escape the root"
1898            );
1899            assert!(
1900                run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts).is_err(),
1901                "uninstall must refuse the same path"
1902            );
1903        }
1904
1905        assert_eq!(
1906            std::fs::read_to_string(&sentinel).unwrap_or_default(),
1907            "sentinel",
1908            "the file outside the skills directory must be untouched"
1909        );
1910        assert!(!outside.join("references").exists());
1911        let _ = std::fs::remove_dir_all(dir);
1912        let _ = std::fs::remove_dir_all(outside);
1913    }
1914
1915    #[cfg(unix)]
1916    #[test]
1917    fn a_symlinked_asset_directory_never_receives_a_write() {
1918        use std::os::unix::fs::symlink;
1919
1920        let dir = temp_skills_dir("symlink-asset-dir");
1921        let outside = temp_skills_dir("symlink-asset-dir-outside");
1922        let skill_dir = dir.join("agent-first-test");
1923        assert!(std::fs::create_dir_all(&skill_dir).is_ok());
1924        assert!(std::fs::create_dir_all(&outside).is_ok());
1925        let sentinel = outside.join("guide.md");
1926        assert!(std::fs::write(&sentinel, "sentinel").is_ok());
1927        // One level deeper than the skill directory: the bundled asset tree's
1928        // own parent is the link.
1929        assert!(symlink(&outside, skill_dir.join("references")).is_ok());
1930
1931        let opts = options(SkillAgentSelection::Codex, &dir, true);
1932        assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_err());
1933
1934        assert_eq!(
1935            std::fs::read_to_string(&sentinel).unwrap_or_default(),
1936            "sentinel"
1937        );
1938        assert!(!skill_dir.join(SKILL_FILE_NAME).exists());
1939        let _ = std::fs::remove_dir_all(dir);
1940        let _ = std::fs::remove_dir_all(outside);
1941    }
1942
1943    #[cfg(unix)]
1944    #[test]
1945    fn status_names_a_symlinked_skill_directory_instead_of_reading_through_it() {
1946        use std::os::unix::fs::symlink;
1947
1948        let dir = temp_skills_dir("symlink-status");
1949        let outside = temp_skills_dir("symlink-status-outside");
1950        assert!(std::fs::create_dir_all(&dir).is_ok());
1951        assert!(std::fs::create_dir_all(&outside).is_ok());
1952        assert!(std::fs::write(outside.join(SKILL_FILE_NAME), "sentinel").is_ok());
1953        assert!(symlink(&outside, dir.join("agent-first-test")).is_ok());
1954
1955        let opts = options(SkillAgentSelection::Codex, &dir, false);
1956        let report = run_skill_admin(&spec(), SkillAction::Status, &opts)
1957            .expect("status must report every target rather than fail outright");
1958        let SkillReport::Status { targets, .. } = report else {
1959            panic!("expected a status report");
1960        };
1961        let target = targets.first().expect("one target");
1962        assert!(!target.installed, "nothing may be read through the link");
1963        assert!(
1964            target
1965                .validation_error
1966                .as_deref()
1967                .unwrap_or_default()
1968                .contains("symlinked directory")
1969        );
1970        let _ = std::fs::remove_dir_all(dir);
1971        let _ = std::fs::remove_dir_all(outside);
1972    }
1973
1974    #[test]
1975    fn uninstall_reports_the_assets_it_removed_and_a_directory_the_user_kept() {
1976        let dir = temp_skills_dir("uninstall-report");
1977        let opts = options(SkillAgentSelection::Codex, &dir, false);
1978        assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
1979        // A file this tool did not install, in the directory it is about to
1980        // try to remove.
1981        let mine = dir.join("agent-first-test").join("notes.md");
1982        assert!(std::fs::write(&mine, "mine").is_ok());
1983
1984        let report = run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts)
1985            .expect("uninstall must succeed");
1986        let SkillReport::Uninstall { targets, .. } = report else {
1987            panic!("expected an uninstall report");
1988        };
1989        let target = targets.first().expect("one target");
1990        assert!(target.removed);
1991        assert_eq!(
1992            target.assets_removed,
1993            vec![
1994                "references/guide.md".to_string(),
1995                "references/registry.json".to_string()
1996            ]
1997        );
1998        assert!(
1999            target.directory_retained,
2000            "a directory holding the user's own file survives, and the report says so"
2001        );
2002        assert_eq!(std::fs::read_to_string(&mine).unwrap_or_default(), "mine");
2003        let _ = std::fs::remove_dir_all(dir);
2004    }
2005
2006    #[test]
2007    fn install_leaves_a_users_own_reference_alone_without_force() {
2008        let dir = temp_skills_dir("unmanaged-asset");
2009        let opts = options(SkillAgentSelection::Codex, &dir, false);
2010        let skill_dir = dir.join("agent-first-test");
2011        let guide = skill_dir.join("references").join("guide.md");
2012        std::fs::create_dir_all(guide.parent().unwrap()).unwrap();
2013        std::fs::write(&guide, "my notes\n").unwrap();
2014
2015        let err = run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts)
2016            .expect_err("a file the user put there is not this tool's to replace");
2017        assert!(
2018            err.message.contains("unmanaged skill asset"),
2019            "{}",
2020            err.message
2021        );
2022        assert_eq!(std::fs::read_to_string(&guide).unwrap(), "my notes\n");
2023        assert!(!skill_dir.join(SKILL_FILE_NAME).exists());
2024
2025        // Content identical to the bundle is already what install would write.
2026        std::fs::write(&guide, "# guide\n").unwrap();
2027        assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
2028
2029        // Once a managed SKILL.md owns the directory, a changed asset is a
2030        // stale copy to refresh, not the user's file.
2031        std::fs::write(&guide, "older bundle\n").unwrap();
2032        assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
2033        assert_eq!(std::fs::read_to_string(&guide).unwrap(), "# guide\n");
2034
2035        std::fs::remove_file(skill_dir.join(SKILL_FILE_NAME)).unwrap();
2036        std::fs::write(&guide, "my notes\n").unwrap();
2037        let forced = options(SkillAgentSelection::Codex, &dir, true);
2038        assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &forced).is_ok());
2039        assert_eq!(std::fs::read_to_string(&guide).unwrap(), "# guide\n");
2040        let _ = std::fs::remove_dir_all(dir);
2041    }
2042
2043    #[test]
2044    fn install_refuses_a_directory_at_an_asset_path_before_writing_anything() {
2045        let dir = temp_skills_dir("asset-is-dir");
2046        let opts = options(SkillAgentSelection::Codex, &dir, true);
2047        let skill_dir = dir.join("agent-first-test");
2048        std::fs::create_dir_all(skill_dir.join("references").join("guide.md")).unwrap();
2049
2050        let err = run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts)
2051            .expect_err("a directory cannot be replaced by an asset file");
2052        assert!(
2053            err.message.contains("non-regular skill asset"),
2054            "{}",
2055            err.message
2056        );
2057        assert!(!skill_dir.join(SKILL_FILE_NAME).exists());
2058        let _ = std::fs::remove_dir_all(dir);
2059    }
2060
2061    /// `SKILL.md` is the marker uninstall goes by, so it has to be the last
2062    /// thing removed: a run that fails on an asset must leave a target the
2063    /// next run still recognises and can finish.
2064    #[cfg(unix)]
2065    #[test]
2066    fn an_uninstall_that_fails_partway_can_be_run_again() {
2067        use std::os::unix::fs::PermissionsExt;
2068        let dir = temp_skills_dir("uninstall-retry");
2069        let opts = options(SkillAgentSelection::Codex, &dir, false);
2070        let skill_dir = dir.join("agent-first-test");
2071        let references = skill_dir.join("references");
2072        assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
2073
2074        std::fs::set_permissions(&references, std::fs::Permissions::from_mode(0o555)).unwrap();
2075        let failed = run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts);
2076        std::fs::set_permissions(&references, std::fs::Permissions::from_mode(0o755)).unwrap();
2077        assert!(failed.is_err());
2078        assert!(skill_dir.join(SKILL_FILE_NAME).is_file());
2079
2080        assert!(run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts).is_ok());
2081        assert!(!references.join("guide.md").exists());
2082        assert!(!skill_dir.exists());
2083        let _ = std::fs::remove_dir_all(dir);
2084    }
2085
2086    #[test]
2087    fn uninstall_reports_a_bundled_asset_it_could_not_remove() {
2088        let dir = temp_skills_dir("uninstall-stuck-asset");
2089        let opts = options(SkillAgentSelection::Codex, &dir, false);
2090        assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
2091        // A directory where a managed file belongs: `remove_file` cannot take
2092        // it, and the old code reported the target removed anyway.
2093        let asset = dir
2094            .join("agent-first-test")
2095            .join("references")
2096            .join("guide.md");
2097        assert!(std::fs::remove_file(&asset).is_ok());
2098        assert!(std::fs::create_dir(&asset).is_ok());
2099        assert!(std::fs::write(asset.join("kept.md"), "kept").is_ok());
2100
2101        let err = run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts)
2102            .expect_err("a managed asset that cannot be removed is not a clean uninstall");
2103        // The spec spells a bundled asset with `/` because that is one fixed
2104        // name for every platform; the message names the file the operator has
2105        // to go and look at, which is spelled the local way.
2106        let named = Path::new("references").join("guide.md");
2107        assert!(
2108            err.message.contains(&named.display().to_string()),
2109            "unexpected message: {}",
2110            err.message
2111        );
2112        assert!(
2113            asset.join("kept.md").exists(),
2114            "the user's file must survive the refusal"
2115        );
2116        let _ = std::fs::remove_dir_all(dir);
2117    }
2118
2119    #[cfg(unix)]
2120    #[test]
2121    fn force_uninstall_removes_symlink_without_following() {
2122        use std::os::unix::fs::symlink;
2123
2124        let dir = temp_skills_dir("symlink-uninstall");
2125        let force_opts = options(SkillAgentSelection::Codex, &dir, true);
2126        let skill_dir = dir.join("agent-first-test");
2127        let skill_path = skill_dir.join(SKILL_FILE_NAME);
2128        let external = dir.join("external.md");
2129        assert!(std::fs::create_dir_all(&skill_dir).is_ok());
2130        assert!(std::fs::write(&external, "external").is_ok());
2131        assert!(symlink(&external, &skill_path).is_ok());
2132
2133        assert!(run_skill_admin(&spec(), SkillAction::Uninstall, &force_opts).is_ok());
2134        assert!(!skill_path.exists());
2135        assert_eq!(
2136            std::fs::read_to_string(&external).unwrap_or_default(),
2137            "external"
2138        );
2139        let _ = std::fs::remove_dir_all(dir);
2140    }
2141
2142    #[test]
2143    fn serializes_to_protocol_shape() {
2144        let dir = temp_skills_dir("serialize");
2145        let opts = options(SkillAgentSelection::Opencode, &dir, false);
2146        if let Ok(report) = run_skill_admin(&spec(), SkillAction::Install, &opts) {
2147            let value = serde_json::to_value(&report).unwrap_or(serde_json::Value::Null);
2148            assert_eq!(value["code"], "skill_install");
2149            assert_eq!(value["installed"], true);
2150            assert_eq!(value["targets"][0]["agent"], "opencode");
2151            assert_eq!(value["targets"][0]["current"], true);
2152            assert_eq!(
2153                value["targets"][0]["skill_dir"],
2154                serde_json::json!(dir.join("agent-first-test").to_string_lossy().to_string())
2155            );
2156        }
2157        let _ = std::fs::remove_dir_all(dir);
2158    }
2159
2160    #[test]
2161    fn all_personal_resolves_four_targets() {
2162        let opts = SkillOptions {
2163            agent: SkillAgentSelection::All,
2164            scope: SkillScope::Personal,
2165            skills_dir: None,
2166            force: false,
2167        };
2168        let targets = resolve_targets(&spec(), &opts);
2169        assert!(targets.is_ok());
2170        if let Ok(targets) = targets {
2171            assert_eq!(targets.len(), 4);
2172            assert_eq!(targets[0].agent, SkillAgent::Codex);
2173            assert_eq!(targets[1].agent, SkillAgent::ClaudeCode);
2174            assert_eq!(targets[2].agent, SkillAgent::Opencode);
2175            assert_eq!(targets[3].agent, SkillAgent::Hermes);
2176        }
2177    }
2178
2179    #[test]
2180    fn all_workspace_resolves_four_targets() {
2181        let opts = SkillOptions {
2182            agent: SkillAgentSelection::All,
2183            scope: SkillScope::Workspace,
2184            skills_dir: None,
2185            force: false,
2186        };
2187        let targets = resolve_targets(&spec(), &opts);
2188        assert!(targets.is_ok());
2189        if let Ok(targets) = targets {
2190            assert_eq!(targets.len(), 4);
2191            assert_eq!(targets[0].agent, SkillAgent::Codex);
2192            assert_eq!(targets[0].scope, SkillScope::Workspace);
2193            assert_eq!(targets[1].agent, SkillAgent::ClaudeCode);
2194            assert_eq!(targets[1].scope, SkillScope::Workspace);
2195            assert_eq!(targets[2].agent, SkillAgent::Opencode);
2196            assert_eq!(targets[2].scope, SkillScope::Workspace);
2197            assert_eq!(targets[3].agent, SkillAgent::Hermes);
2198            assert_eq!(targets[3].scope, SkillScope::Workspace);
2199        }
2200    }
2201
2202    #[test]
2203    fn codex_workspace_scope_uses_codex_skills_dir() {
2204        let opts = SkillOptions {
2205            agent: SkillAgentSelection::Codex,
2206            scope: SkillScope::Workspace,
2207            skills_dir: None,
2208            force: false,
2209        };
2210        let targets = resolve_targets(&spec(), &opts);
2211        assert!(targets.is_ok());
2212        if let Ok(targets) = targets {
2213            assert_eq!(targets.len(), 1);
2214            assert_eq!(targets[0].agent, SkillAgent::Codex);
2215            assert_eq!(targets[0].scope, SkillScope::Workspace);
2216            assert!(targets[0].skills_dir.ends_with(".codex/skills"));
2217        }
2218    }
2219
2220    #[test]
2221    fn hermes_workspace_scope_uses_hermes_skills_dir() {
2222        let opts = SkillOptions {
2223            agent: SkillAgentSelection::Hermes,
2224            scope: SkillScope::Workspace,
2225            skills_dir: None,
2226            force: false,
2227        };
2228        let targets = resolve_targets(&spec(), &opts);
2229        assert!(targets.is_ok());
2230        if let Ok(targets) = targets {
2231            assert_eq!(targets.len(), 1);
2232            assert_eq!(targets[0].agent, SkillAgent::Hermes);
2233            assert_eq!(targets[0].scope, SkillScope::Workspace);
2234            assert!(targets[0].skills_dir.ends_with(".hermes/skills"));
2235        }
2236    }
2237}