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