use serde::Serialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
const SKILL_FILE_NAME: &str = "SKILL.md";
const FNV1A64_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV1A64_PRIME: u64 = 0x0000_0100_0000_01b3;
#[derive(Clone, Copy, Debug)]
pub struct SkillAsset<'a> {
pub path: &'a str,
pub contents: &'a str,
}
#[derive(Clone, Copy, Debug)]
pub struct SkillSpec<'a> {
pub name: &'a str,
pub source: &'a str,
pub title: &'a str,
pub marker_slug: &'a str,
pub assets: &'a [SkillAsset<'a>],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SkillScope {
Personal,
Workspace,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SkillLocation {
Standard(SkillScope),
Directory(String),
}
#[derive(Clone, Debug, Serialize)]
pub struct SkillOptions {
pub location: SkillLocation,
pub force: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SkillAction {
Status,
Install,
Uninstall,
}
#[derive(Clone, Debug, Serialize)]
pub struct SkillTargetStatus {
pub scope: Option<SkillScope>,
pub skills_dir: PathBuf,
pub skill_dir: PathBuf,
pub skill_path: PathBuf,
pub installed: bool,
pub managed: bool,
pub valid: bool,
pub current: bool,
pub validation_error: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct SkillUninstallStatus {
pub scope: Option<SkillScope>,
pub skills_dir: PathBuf,
pub skill_dir: PathBuf,
pub skill_path: PathBuf,
pub removed: bool,
pub assets_removed: Vec<String>,
pub directory_retained: bool,
}
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "code")]
pub enum SkillReport {
#[serde(rename = "skill_status")]
Status {
skill: String,
installed_all: bool,
valid_all: bool,
current_all: bool,
targets: Vec<SkillTargetStatus>,
},
#[serde(rename = "skill_install")]
Install {
skill: String,
installed: bool,
targets: Vec<SkillTargetStatus>,
stale_assets_removed: Vec<PathBuf>,
hint: &'static str,
},
#[serde(rename = "skill_uninstall")]
Uninstall {
skill: String,
removed_any: bool,
targets: Vec<SkillUninstallStatus>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SkillErrorKind {
Usage,
InvalidSpec,
Refused,
Io,
}
impl SkillErrorKind {
#[must_use]
pub fn code(self) -> &'static str {
match self {
Self::Usage => "skill_usage_error",
Self::InvalidSpec => "skill_spec_invalid",
Self::Refused => "skill_refused",
Self::Io => "skill_io_failed",
}
}
}
#[derive(Clone, Debug)]
pub struct SkillError {
pub kind: SkillErrorKind,
pub message: String,
pub hint: Option<String>,
pub partial_report: Option<Box<SkillReport>>,
}
impl std::fmt::Display for SkillError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.message)
}
}
impl std::error::Error for SkillError {}
impl SkillError {
fn new(kind: SkillErrorKind, message: String, hint: Option<String>) -> Self {
Self {
kind,
message,
hint,
partial_report: None,
}
}
fn io(action: &str, err: std::io::Error) -> Self {
Self {
kind: SkillErrorKind::Io,
message: format!("{action} failed: {err}"),
hint: None,
partial_report: None,
}
}
fn write_failed(action: &str, err: crate::atomic_file::AtomicError) -> Self {
let hint = err.commit_uncertain().then(|| {
"the file is installed but its durability is unconfirmed; re-run to be sure".to_string()
});
Self {
kind: SkillErrorKind::Io,
message: format!("{action} failed: {err}"),
hint,
partial_report: None,
}
}
fn with_partial_report(mut self, report: SkillReport) -> Self {
self.partial_report = Some(Box::new(report));
self
}
}
pub fn run_skill_admin(
spec: &SkillSpec,
action: SkillAction,
options: &SkillOptions,
) -> Result<SkillReport, SkillError> {
run_with_resolver(spec, action, options, standard_skills_dirs)
}
pub fn run_personal_in(
spec: &SkillSpec,
action: SkillAction,
env: &BTreeMap<String, String>,
) -> Result<SkillReport, SkillError> {
let options = SkillOptions {
location: SkillLocation::Standard(SkillScope::Personal),
force: false,
};
run_with_resolver(spec, action, &options, |_| personal_skills_dirs(env))
}
fn run_with_resolver(
spec: &SkillSpec,
action: SkillAction,
options: &SkillOptions,
standard_dirs: impl Fn(SkillScope) -> Result<Vec<PathBuf>, SkillError>,
) -> Result<SkillReport, SkillError> {
validate_spec(spec)?;
let targets = resolve_targets(spec, &options.location, standard_dirs)?;
match action {
SkillAction::Status => status(spec, &targets),
SkillAction::Install => install(spec, options, &targets),
SkillAction::Uninstall => uninstall(spec, options, &targets),
}
}
fn status(spec: &SkillSpec, targets: &[SkillTarget]) -> Result<SkillReport, SkillError> {
let mut statuses = Vec::with_capacity(targets.len());
for target in targets {
statuses.push(target_status(spec, target)?);
}
Ok(SkillReport::Status {
skill: spec.name.to_string(),
installed_all: statuses.iter().all(|s| s.installed),
valid_all: statuses.iter().all(|s| s.valid),
current_all: statuses.iter().all(|s| s.current),
targets: statuses,
})
}
fn install(
spec: &SkillSpec,
options: &SkillOptions,
targets: &[SkillTarget],
) -> Result<SkillReport, SkillError> {
validate_skill_text(spec, spec.source, SkillErrorKind::InvalidSpec)?;
for asset in spec.assets {
validate_asset_path(asset.path)?;
}
let content = managed_skill_contents(spec);
preflight_install_targets(spec, options, targets)?;
for target in targets {
if let Err(err) = std::fs::create_dir_all(&target.skill_dir)
.map_err(|e| SkillError::io("create skill dir", e))
{
return Err(err.with_partial_report(install_report_lossy(spec, targets, false)));
}
}
install_targets(spec, targets, &content)
}
fn preflight_install_targets(
spec: &SkillSpec,
options: &SkillOptions,
targets: &[SkillTarget],
) -> Result<(), SkillError> {
let mut failures = Vec::new();
let mut escaped = false;
for target in targets {
if let Err(err) = containment_failure(spec, target) {
failures.push(err);
escaped = true;
continue;
}
let skill_dir_managed = skill_path_file_type(&target.skill_path)?
.is_some_and(|kind| kind.is_file())
&& is_managed_or_bundled_skill(spec, &target.skill_path)?;
for asset in spec.assets {
let dest = asset_target_path(&target.skill_dir, asset.path);
let Some(kind) = skill_path_file_type(&dest)? else {
continue;
};
if !kind.is_file() && !kind.is_symlink() {
failures.push(format!(
"refusing to overwrite non-regular skill asset at {}",
dest.display()
));
} else if !skill_dir_managed
&& !options.force
&& (kind.is_symlink()
|| std::fs::read(&dest).map_err(|e| SkillError::io("read skill asset", e))?
!= asset.contents.as_bytes())
{
failures.push(format!(
"refusing to overwrite unmanaged skill asset at {}",
dest.display()
));
}
}
if let Some(kind) = skill_path_file_type(&target.skill_path)? {
if kind.is_symlink() {
if !options.force {
failures.push(format!(
"refusing to overwrite symlinked skill at {}",
target.skill_path.display()
));
}
continue;
}
if !kind.is_file() {
failures.push(format!(
"refusing to overwrite non-regular skill at {}",
target.skill_path.display()
));
continue;
}
if !is_managed_or_bundled_skill(spec, &target.skill_path)? && !options.force {
failures.push(format!(
"refusing to overwrite unmanaged skill at {}",
target.skill_path.display()
));
}
}
}
if failures.is_empty() {
return Ok(());
}
let hint = if escaped {
"--force does not permit writing outside the skills directory"
} else {
"pass --force to replace unmanaged files or symlinks"
};
Err(SkillError::new(
SkillErrorKind::Refused,
failures.join("; "),
Some(hint.to_string()),
)
.with_partial_report(install_report_lossy(spec, targets, false)))
}
fn install_targets(
spec: &SkillSpec,
targets: &[SkillTarget],
content: &str,
) -> Result<SkillReport, SkillError> {
let mut installed = Vec::with_capacity(targets.len());
let mut stale_assets_removed = Vec::new();
for target in targets {
let stale = match stale_recorded_assets(spec, target) {
Ok(stale) => stale,
Err(err) => {
return Err(err.with_partial_report(install_report_lossy(spec, targets, false)));
}
};
match remove_target_assets(target, stale.iter().map(String::as_str)) {
Ok(removed) => stale_assets_removed.extend(
removed
.iter()
.map(|path| asset_target_path(&target.skill_dir, path)),
),
Err(err) => {
return Err(err.with_partial_report(install_report_lossy(spec, targets, false)));
}
}
if let Err(err) = write_skill_atomic(target, content) {
return Err(err.with_partial_report(install_report_lossy(spec, targets, false)));
}
if let Err(err) = install_target_assets(spec, target) {
return Err(err.with_partial_report(install_report_lossy(spec, targets, false)));
}
if let Err(err) = validate_installed_skill(spec, &target.skill_path) {
return Err(err.with_partial_report(install_report_lossy(spec, targets, false)));
}
match target_status(spec, target) {
Ok(status) => installed.push(status),
Err(err) => {
return Err(err.with_partial_report(install_report_lossy(spec, targets, false)));
}
}
}
Ok(SkillReport::Install {
skill: spec.name.to_string(),
installed: true,
targets: installed,
stale_assets_removed,
hint: "restart the agent so it reloads installed skills",
})
}
fn uninstall(
spec: &SkillSpec,
options: &SkillOptions,
targets: &[SkillTarget],
) -> Result<SkillReport, SkillError> {
preflight_uninstall_targets(spec, options, targets)?;
let mut removed = Vec::with_capacity(targets.len());
for target in targets {
let Some(kind) = skill_path_file_type(&target.skill_path)? else {
removed.push(target_uninstall_status(target, false));
continue;
};
if !kind.is_file() && !kind.is_symlink() {
let err = SkillError::new(
SkillErrorKind::Refused,
format!(
"refusing to remove non-regular skill at {}",
target.skill_path.display()
),
None,
);
return Err(err.with_partial_report(uninstall_report_lossy(spec, targets, &removed)));
}
if let Err(err) = ensure_no_symlinked_dirs(&target.skills_dir, &target.skill_path) {
return Err(err.with_partial_report(uninstall_report_lossy(spec, targets, &removed)));
}
let recorded = match recorded_assets_on_disk(spec, target) {
Ok(recorded) => recorded,
Err(err) => {
return Err(
err.with_partial_report(uninstall_report_lossy(spec, targets, &removed))
);
}
};
let mut paths: Vec<&str> = spec.assets.iter().map(|asset| asset.path).collect();
for path in &recorded {
if !paths.contains(&path.as_str()) {
paths.push(path);
}
}
let assets_removed = match remove_target_assets(target, paths.into_iter()) {
Ok(assets_removed) => assets_removed,
Err(err) => {
return Err(
err.with_partial_report(uninstall_report_lossy(spec, targets, &removed))
);
}
};
if let Err(err) =
std::fs::remove_file(&target.skill_path).map_err(|e| SkillError::io("remove skill", e))
{
return Err(err.with_partial_report(uninstall_report_lossy(spec, targets, &removed)));
}
let _ = std::fs::remove_dir(&target.skill_dir);
removed.push(SkillUninstallStatus {
assets_removed,
..target_uninstall_status(target, true)
});
}
Ok(SkillReport::Uninstall {
skill: spec.name.to_string(),
removed_any: removed.iter().any(|s| s.removed),
targets: removed,
})
}
fn preflight_uninstall_targets(
spec: &SkillSpec,
options: &SkillOptions,
targets: &[SkillTarget],
) -> Result<(), SkillError> {
let mut failures = Vec::new();
let mut escaped = false;
for target in targets {
if let Err(err) = containment_failure(spec, target) {
failures.push(err);
escaped = true;
continue;
}
for asset in spec.assets {
let dest = asset_target_path(&target.skill_dir, asset.path);
if let Some(kind) = skill_path_file_type(&dest)?
&& kind.is_dir()
{
failures.push(format!(
"refusing to remove bundled asset {} because it is a directory",
dest.display()
));
}
}
let Some(kind) = skill_path_file_type(&target.skill_path)? else {
continue;
};
if kind.is_symlink() {
if !options.force {
failures.push(format!(
"refusing to remove symlinked skill at {}",
target.skill_path.display()
));
}
continue;
}
if !kind.is_file() {
failures.push(format!(
"refusing to remove non-regular skill at {}",
target.skill_path.display()
));
continue;
}
if !is_managed_or_bundled_skill(spec, &target.skill_path)? && !options.force {
failures.push(format!(
"refusing to remove unmanaged skill at {}",
target.skill_path.display()
));
}
}
if failures.is_empty() {
return Ok(());
}
let hint = if escaped {
"--force does not permit removing files outside the skills directory".to_string()
} else {
format!(
"only skills generated by {} skill install can be removed without --force",
spec.marker_slug
)
};
Err(
SkillError::new(SkillErrorKind::Refused, failures.join("; "), Some(hint))
.with_partial_report(uninstall_report_lossy(spec, targets, &[])),
)
}
struct SkillTarget {
scope: Option<SkillScope>,
skills_dir: PathBuf,
skill_dir: PathBuf,
skill_path: PathBuf,
}
fn resolve_targets(
spec: &SkillSpec,
location: &SkillLocation,
standard_dirs: impl Fn(SkillScope) -> Result<Vec<PathBuf>, SkillError>,
) -> Result<Vec<SkillTarget>, SkillError> {
Ok(match location {
SkillLocation::Standard(scope) => standard_dirs(*scope)?
.into_iter()
.map(|dir| SkillTarget::new(spec, dir, Some(*scope)))
.collect(),
SkillLocation::Directory(dir) => vec![SkillTarget::new(spec, expand_tilde(dir)?, None)],
})
}
impl SkillTarget {
fn new(spec: &SkillSpec, skills_dir: PathBuf, scope: Option<SkillScope>) -> Self {
let skill_dir = skills_dir.join(spec.name);
let skill_path = skill_dir.join(SKILL_FILE_NAME);
Self {
scope,
skills_dir,
skill_dir,
skill_path,
}
}
}
const SHARED_SKILL_FOLDERS: [&str; 2] = [".agents/skills", ".claude/skills"];
const PERSONAL_ONLY_SKILL_FOLDER: &str = ".gemini/config/skills";
fn standard_skills_dirs(scope: SkillScope) -> Result<Vec<PathBuf>, SkillError> {
match scope {
SkillScope::Personal => personal_skills_dirs(
&std::env::vars_os()
.filter_map(|(key, value)| {
Some((key.into_string().ok()?, value.into_string().ok()?))
})
.collect(),
),
SkillScope::Workspace => {
let cwd = std::env::current_dir()
.map_err(|e| SkillError::io("resolve current directory", e))?;
Ok(SHARED_SKILL_FOLDERS
.iter()
.map(|folder| cwd.join(folder))
.collect())
}
}
}
fn personal_skills_dirs(env: &BTreeMap<String, String>) -> Result<Vec<PathBuf>, SkillError> {
let home = resolve_home(|name| {
env.get(name)
.map(PathBuf::from)
.filter(|path| path.is_absolute())
})?;
Ok(SHARED_SKILL_FOLDERS
.iter()
.chain([&PERSONAL_ONLY_SKILL_FOLDER])
.map(|folder| home.join(folder))
.collect())
}
fn target_status(spec: &SkillSpec, target: &SkillTarget) -> Result<SkillTargetStatus, SkillError> {
if let Err(message) = containment_failure(spec, target) {
return Ok(SkillTargetStatus {
scope: target.scope,
skills_dir: target.skills_dir.clone(),
skill_dir: target.skill_dir.clone(),
skill_path: target.skill_path.clone(),
installed: false,
managed: false,
valid: false,
current: false,
validation_error: Some(message),
});
}
let Some(kind) = skill_path_file_type(&target.skill_path)? else {
return Ok(SkillTargetStatus {
scope: target.scope,
skills_dir: target.skills_dir.clone(),
skill_dir: target.skill_dir.clone(),
skill_path: target.skill_path.clone(),
installed: false,
managed: false,
valid: false,
current: false,
validation_error: None,
});
};
let installed = true;
let mut valid = false;
let mut current = false;
let mut validation_error = None;
let mut managed = false;
if kind.is_symlink() {
validation_error = Some("target SKILL.md is a symlink; refusing to follow it".to_string());
} else if kind.is_file() {
let text = std::fs::read_to_string(&target.skill_path)
.map_err(|e| SkillError::io("read skill", e))?;
managed = skill_text_is_managed_or_bundled(spec, &text);
current = normalized_content_hash(spec, &text) == source_hash(spec)
&& assets_current(spec, &target.skill_dir)
&& stale_assets(spec, &text).iter().all(|path| {
skill_path_file_type(&asset_target_path(&target.skill_dir, path))
.is_ok_and(|kind| kind.is_none())
});
match validate_skill_text(spec, &text, SkillErrorKind::Refused) {
Ok(()) => valid = true,
Err(err) => validation_error = Some(err.message),
}
} else {
validation_error = Some("target SKILL.md is not a regular file".to_string());
}
Ok(SkillTargetStatus {
scope: target.scope,
skills_dir: target.skills_dir.clone(),
skill_dir: target.skill_dir.clone(),
skill_path: target.skill_path.clone(),
installed,
managed,
valid,
current,
validation_error,
})
}
fn target_uninstall_status(target: &SkillTarget, removed: bool) -> SkillUninstallStatus {
SkillUninstallStatus {
scope: target.scope,
skills_dir: target.skills_dir.clone(),
skill_dir: target.skill_dir.clone(),
skill_path: target.skill_path.clone(),
removed,
assets_removed: Vec::new(),
directory_retained: std::fs::symlink_metadata(&target.skill_dir).is_ok(),
}
}
fn target_status_lossy(spec: &SkillSpec, target: &SkillTarget) -> SkillTargetStatus {
target_status(spec, target).unwrap_or_else(|err| {
let installed = std::fs::symlink_metadata(&target.skill_path).is_ok();
SkillTargetStatus {
scope: target.scope,
skills_dir: target.skills_dir.clone(),
skill_dir: target.skill_dir.clone(),
skill_path: target.skill_path.clone(),
installed,
managed: false,
valid: false,
current: false,
validation_error: Some(err.message),
}
})
}
fn install_report_lossy(spec: &SkillSpec, targets: &[SkillTarget], installed: bool) -> SkillReport {
SkillReport::Install {
skill: spec.name.to_string(),
installed,
targets: targets
.iter()
.map(|target| target_status_lossy(spec, target))
.collect(),
stale_assets_removed: Vec::new(),
hint: "restart the agent so it reloads installed skills",
}
}
fn uninstall_report_lossy(
spec: &SkillSpec,
targets: &[SkillTarget],
removed: &[SkillUninstallStatus],
) -> SkillReport {
let mut statuses = Vec::with_capacity(targets.len());
for target in targets {
if let Some(status) = removed
.iter()
.find(|status| status.scope == target.scope && status.skill_path == target.skill_path)
{
statuses.push(status.clone());
} else {
statuses.push(target_uninstall_status(target, false));
}
}
SkillReport::Uninstall {
skill: spec.name.to_string(),
removed_any: statuses.iter().any(|status| status.removed),
targets: statuses,
}
}
fn generated_by(spec: &SkillSpec) -> String {
format!("Generated by {} skill install", spec.marker_slug)
}
fn text_hash(text: &str) -> String {
let mut hash = FNV1A64_OFFSET;
for byte in text.as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(FNV1A64_PRIME);
}
format!("{hash:016x}")
}
fn source_hash(spec: &SkillSpec) -> String {
normalized_content_hash(spec, spec.source)
}
fn normalized_content_hash(spec: &SkillSpec, text: &str) -> String {
text_hash(&normalize_skill_text(spec, text))
}
fn managed_marker_block(spec: &SkillSpec) -> String {
let slug = spec.marker_slug;
let mut block = format!(
"<!--\n{}\n{}-managed-skill: true\n{}-managed-skill-name: {}\n{}-managed-skill-owner: {}\n{}-managed-skill-content-hash-fnv1a64: {}\n",
generated_by(spec),
slug,
slug,
spec.name,
slug,
slug,
slug,
source_hash(spec)
);
for asset in spec.assets {
block.push_str(&format!("{slug}-managed-skill-asset: {}\n", asset.path));
}
block.push_str("-->");
block
}
fn recorded_assets(spec: &SkillSpec, text: &str) -> Vec<String> {
let prefix = format!("{}-managed-skill-asset: ", spec.marker_slug);
let mut paths = Vec::new();
for block in html_comment_blocks(text) {
if !managed_marker_block_has_identity(spec, &block) {
continue;
}
for line in block.lines() {
if let Some(path) = line.trim().strip_prefix(&prefix)
&& validate_asset_path(path).is_ok()
&& !paths.iter().any(|known| known == path)
{
paths.push(path.to_string());
}
}
}
paths
}
fn stale_assets(spec: &SkillSpec, text: &str) -> Vec<String> {
recorded_assets(spec, text)
.into_iter()
.filter(|path| !spec.assets.iter().any(|asset| asset.path == path))
.collect()
}
fn recorded_assets_on_disk(
spec: &SkillSpec,
target: &SkillTarget,
) -> Result<Vec<String>, SkillError> {
let is_file = skill_path_file_type(&target.skill_path)?.is_some_and(|kind| kind.is_file());
if !is_file {
return Ok(Vec::new());
}
let text =
std::fs::read_to_string(&target.skill_path).map_err(|e| SkillError::io("read skill", e))?;
if !skill_text_has_managed_identity(spec, &text) {
return Ok(Vec::new());
}
Ok(recorded_assets(spec, &text))
}
fn stale_recorded_assets(
spec: &SkillSpec,
target: &SkillTarget,
) -> Result<Vec<String>, SkillError> {
Ok(recorded_assets_on_disk(spec, target)?
.into_iter()
.filter(|path| !spec.assets.iter().any(|asset| asset.path == path))
.collect())
}
fn managed_skill_contents(spec: &SkillSpec) -> String {
let block = managed_marker_block(spec);
let mut lines = spec.source.lines();
let mut output = String::new();
let mut inserted = false;
if let Some(first) = lines.next() {
output.push_str(first);
output.push('\n');
}
for line in lines {
output.push_str(line);
output.push('\n');
if !inserted && line.trim() == "---" {
output.push_str(&block);
output.push_str("\n\n");
inserted = true;
}
}
if !inserted {
output.push_str(&block);
output.push('\n');
}
output
}
fn validate_installed_skill(spec: &SkillSpec, path: &Path) -> Result<(), SkillError> {
let text =
std::fs::read_to_string(path).map_err(|e| SkillError::io("read installed skill", e))?;
validate_skill_text(spec, &text, SkillErrorKind::Io)
}
fn validate_skill_text(
spec: &SkillSpec,
text: &str,
kind: SkillErrorKind,
) -> Result<(), SkillError> {
crate::skill::validate_skill_named(text, spec.name).map_err(|err| {
SkillError::new(
kind,
format!("invalid {} skill front matter: {err}", spec.title),
Some(format!(
"make SKILL.md metadata conform to the Agent Skills specification and set name to {}",
spec.name
)),
)
})?;
Ok(())
}
fn is_managed_or_bundled_skill(spec: &SkillSpec, path: &Path) -> Result<bool, SkillError> {
let Some(kind) = skill_path_file_type(path)? else {
return Ok(false);
};
if kind.is_symlink() {
return Err(SkillError::new(
SkillErrorKind::Refused,
format!("refusing to inspect symlinked skill at {}", path.display()),
Some("pass --force to replace or remove the symlink itself".to_string()),
));
}
let text = std::fs::read_to_string(path).map_err(|e| SkillError::io("read skill", e))?;
Ok(skill_text_is_managed_or_bundled(spec, &text))
}
fn skill_text_is_managed_or_bundled(spec: &SkillSpec, text: &str) -> bool {
skill_text_has_managed_identity(spec, text)
|| normalize_skill_text(spec, text) == normalize_skill_text(spec, spec.source)
}
fn skill_text_has_managed_identity(spec: &SkillSpec, text: &str) -> bool {
for block in html_comment_blocks(text) {
if managed_marker_block_has_identity(spec, &block) {
return true;
}
}
false
}
fn managed_marker_block_has_identity(spec: &SkillSpec, block: &str) -> bool {
let slug = spec.marker_slug;
let generated_by_line = generated_by(spec);
let managed_line = format!("{slug}-managed-skill: true");
let name_line = format!("{slug}-managed-skill-name: {}", spec.name);
let owner_line = format!("{slug}-managed-skill-owner: {slug}");
let mut has_generated_by = false;
let mut has_managed = false;
let mut has_name = false;
let mut has_owner = false;
for line in block.replace("\r\n", "\n").lines() {
let trimmed = line.trim();
has_generated_by |= trimmed == generated_by_line;
has_managed |= trimmed == managed_line;
has_name |= trimmed == name_line;
has_owner |= trimmed == owner_line;
}
has_generated_by && has_managed && has_name && has_owner
}
fn html_comment_blocks(text: &str) -> Vec<String> {
let normalized = text.replace("\r\n", "\n");
let mut blocks = Vec::new();
let mut lines = normalized.lines();
while let Some(line) = lines.next() {
if line.trim() != "<!--" {
continue;
}
let mut block = vec![line.to_string()];
for next in lines.by_ref() {
block.push(next.to_string());
if next.trim() == "-->" {
blocks.push(block.join("\n"));
break;
}
}
}
blocks
}
fn strip_managed_marker_blocks(spec: &SkillSpec, text: &str) -> String {
let normalized = text.replace("\r\n", "\n");
let mut output = Vec::new();
let mut lines = normalized.lines();
while let Some(line) = lines.next() {
if line.trim() != "<!--" {
output.push(line.to_string());
continue;
}
let mut block = vec![line.to_string()];
let mut closed = false;
for next in lines.by_ref() {
block.push(next.to_string());
if next.trim() == "-->" {
closed = true;
break;
}
}
if closed {
let block_text = block.join("\n");
if managed_marker_block_has_identity(spec, &block_text) {
continue;
}
}
output.extend(block);
}
output.join("\n")
}
fn normalize_skill_text(spec: &SkillSpec, text: &str) -> String {
let text = strip_managed_marker_blocks(spec, text);
let mut out: Vec<&str> = Vec::new();
for line in text.lines() {
let trimmed = line.trim();
if trimmed.is_empty() && out.last().is_some_and(|prev| prev.trim().is_empty()) {
continue;
}
out.push(line);
}
out.join("\n").trim().to_string()
}
fn validate_spec(spec: &SkillSpec) -> Result<(), SkillError> {
validate_slug("skill name", spec.name)?;
validate_slug("marker slug", spec.marker_slug)?;
validate_skill_text(spec, spec.source, SkillErrorKind::InvalidSpec)
}
fn validate_slug(field: &str, value: &str) -> Result<(), SkillError> {
if slug_is_valid(value) {
return Ok(());
}
Err(SkillError::new(
SkillErrorKind::InvalidSpec,
format!(
"invalid {field} {value:?}: expected a lowercase slug matching [a-z0-9][a-z0-9-]*[a-z0-9]"
),
Some("use lowercase ASCII letters, digits, and single hyphen-separated words".to_string()),
))
}
fn slug_is_valid(value: &str) -> bool {
let bytes = value.as_bytes();
if bytes.is_empty() {
return false;
}
fn is_lower_alnum(byte: u8) -> bool {
byte.is_ascii_lowercase() || byte.is_ascii_digit()
}
if !is_lower_alnum(bytes[0]) || !is_lower_alnum(bytes[bytes.len() - 1]) {
return false;
}
bytes
.iter()
.all(|byte| is_lower_alnum(*byte) || *byte == b'-')
}
fn skill_path_file_type(path: &Path) -> Result<Option<std::fs::FileType>, SkillError> {
match std::fs::symlink_metadata(path) {
Ok(metadata) => Ok(Some(metadata.file_type())),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(SkillError::io("inspect skill path", err)),
}
}
fn ensure_no_symlinked_dirs(root: &Path, path: &Path) -> Result<(), SkillError> {
let Ok(relative) = path.strip_prefix(root) else {
return Err(SkillError::new(
SkillErrorKind::Refused,
format!(
"{} is not inside the skills directory {}",
path.display(),
root.display()
),
Some("pass --skills-dir to install where you mean to".to_string()),
));
};
let mut current = root.to_path_buf();
let mut components = relative.components().peekable();
while let Some(component) = components.next() {
current.push(component);
if components.peek().is_none() {
break;
}
match std::fs::symlink_metadata(¤t) {
Ok(metadata) if metadata.file_type().is_symlink() => {
return Err(SkillError::new(
SkillErrorKind::Refused,
format!(
"refusing to reach {} through the symlinked directory {}",
path.display(),
current.display()
),
Some(
"replace the link with a real directory, or pass --skills-dir".to_string(),
),
));
}
Ok(_) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => break,
Err(err) => return Err(SkillError::io("inspect skill path", err)),
}
}
Ok(())
}
fn containment_failure(spec: &SkillSpec, target: &SkillTarget) -> Result<(), String> {
let mut paths = vec![target.skill_path.clone()];
paths.extend(
spec.assets
.iter()
.map(|asset| asset_target_path(&target.skill_dir, asset.path)),
);
for path in paths {
if let Err(err) = ensure_no_symlinked_dirs(&target.skills_dir, &path) {
return Err(err.message);
}
}
Ok(())
}
fn write_skill_atomic(target: &SkillTarget, content: &str) -> Result<(), SkillError> {
ensure_no_symlinked_dirs(&target.skills_dir, &target.skill_path)?;
write_file_atomic(&target.skill_path, content, "install skill file")
}
fn write_file_atomic(path: &Path, content: &str, action: &str) -> Result<(), SkillError> {
let preserved = match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() => Some(metadata),
_ => None,
};
let unix_mode = if preserved.is_some() {
None
} else {
Some(0o644)
};
crate::AtomicWrite::new(content.as_bytes())
.with_target_metadata(preserved)
.with_unix_mode(unix_mode)
.write(path)
.map_err(|err| SkillError::write_failed(action, err))
}
fn validate_asset_path(path: &str) -> Result<(), SkillError> {
let bad = path.is_empty()
|| Path::new(path).is_absolute()
|| path
.split(['/', '\\'])
.any(|seg| seg.is_empty() || seg == "." || seg == "..");
if bad {
return Err(SkillError::new(
SkillErrorKind::InvalidSpec,
format!("invalid skill asset path: {path}"),
Some(
"asset paths must be relative to the skill directory with no `.`/`..` segments"
.to_string(),
),
));
}
Ok(())
}
fn asset_target_path(skill_dir: &Path, rel_path: &str) -> PathBuf {
let mut out = skill_dir.to_path_buf();
for seg in rel_path.split(['/', '\\']) {
out.push(seg);
}
out
}
fn install_target_assets(spec: &SkillSpec, target: &SkillTarget) -> Result<(), SkillError> {
for asset in spec.assets {
let dest = asset_target_path(&target.skill_dir, asset.path);
ensure_no_symlinked_dirs(&target.skills_dir, &dest)?;
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| SkillError::io("create skill asset dir", e))?;
}
write_file_atomic(&dest, asset.contents, "install skill asset")?;
}
Ok(())
}
fn assets_current(spec: &SkillSpec, skill_dir: &Path) -> bool {
spec.assets.iter().all(|asset| {
let dest = asset_target_path(skill_dir, asset.path);
std::fs::read_to_string(&dest)
.map(|text| text == asset.contents)
.unwrap_or(false)
})
}
fn remove_target_assets<'p>(
target: &SkillTarget,
paths: impl Iterator<Item = &'p str>,
) -> Result<Vec<String>, SkillError> {
let mut removed = Vec::new();
let mut dirs: Vec<PathBuf> = Vec::new();
for path in paths {
let dest = asset_target_path(&target.skill_dir, path);
ensure_no_symlinked_dirs(&target.skills_dir, &dest)?;
match std::fs::remove_file(&dest) {
Ok(()) => removed.push(path.to_string()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => {
return Err(SkillError::io(
&format!("remove bundled skill asset {path}"),
err,
));
}
}
let mut dir = dest.parent().map(Path::to_path_buf);
while let Some(current) = dir {
if current == target.skill_dir || !current.starts_with(&target.skill_dir) {
break;
}
if !dirs.contains(¤t) {
dirs.push(current.clone());
}
dir = current.parent().map(Path::to_path_buf);
}
}
dirs.sort_by_key(|d| std::cmp::Reverse(d.components().count()));
for dir in dirs {
let _ = std::fs::remove_dir(&dir);
}
Ok(removed)
}
fn env_dir(name: &str) -> Option<PathBuf> {
std::env::var_os(name)
.map(PathBuf::from)
.filter(|path| path.is_absolute())
}
fn home_dir() -> Result<PathBuf, SkillError> {
resolve_home(env_dir)
}
fn resolve_home(env_dir: impl Fn(&str) -> Option<PathBuf>) -> Result<PathBuf, SkillError> {
env_dir("HOME")
.or_else(|| env_dir("USERPROFILE"))
.ok_or_else(|| {
SkillError::new(
SkillErrorKind::Usage,
"cannot determine home directory".to_string(),
Some("pass --skills-dir explicitly".to_string()),
)
})
}
fn expand_tilde(input: &str) -> Result<PathBuf, SkillError> {
if input.is_empty() {
return Err(SkillError::new(
SkillErrorKind::Usage,
"--skills-dir requires a non-empty path".to_string(),
None,
));
}
if input == "~" {
return home_dir();
}
if let Some(rest) = input.strip_prefix("~/") {
return Ok(home_dir()?.join(rest));
}
Ok(PathBuf::from(input))
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{SystemTime, UNIX_EPOCH};
const SKILL_SOURCE: &str =
"---\nname: agent-first-test\ndescription: test skill\n---\n\n# Body\n\nrules.\n";
fn spec() -> SkillSpec<'static> {
SkillSpec {
name: "agent-first-test",
source: SKILL_SOURCE,
title: "Agent-First Test",
marker_slug: "aftest",
assets: &[],
}
}
fn managed_skill_with_body(body: &str) -> String {
format!(
"---\nname: agent-first-test\ndescription: test skill\n---\n{}\n\n{body}",
managed_marker_block(&spec())
)
}
fn temp_skills_dir(name: &str) -> PathBuf {
let suffix = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
std::env::temp_dir().join(format!(
"afdata_skill_{name}_{}_{}",
std::process::id(),
suffix
))
}
fn options(dir: &Path, force: bool) -> SkillOptions {
SkillOptions {
location: SkillLocation::Directory(dir.to_string_lossy().to_string()),
force,
}
}
fn custom_target(dir: &Path) -> SkillTarget {
let skill_dir = dir.join("agent-first-test");
SkillTarget {
scope: None,
skills_dir: dir.to_path_buf(),
skill_path: skill_dir.join(SKILL_FILE_NAME),
skill_dir,
}
}
#[test]
fn validates_bundled_frontmatter() {
assert!(crate::skill::validate_skill_named(SKILL_SOURCE, "agent-first-test").is_ok());
}
#[test]
fn rejects_unquoted_colon_space() {
let bad = "---\nname: x\ndescription: broken: yaml\n---\n";
assert!(crate::skill::validate_skill(bad).is_err());
}
#[test]
fn install_status_uninstall_directory() {
let dir = temp_skills_dir("directory");
let opts = options(&dir, false);
let skill_path = dir.join("agent-first-test").join(SKILL_FILE_NAME);
let installed = run_skill_admin(&spec(), SkillAction::Install, &opts);
assert!(installed.is_ok());
assert!(skill_path.is_file());
let text = std::fs::read_to_string(&skill_path).unwrap_or_default();
assert!(text.contains(&managed_marker_block(&spec())));
assert!(text.contains("aftest-managed-skill-name: agent-first-test"));
assert!(text.contains("aftest-managed-skill-owner: aftest"));
assert!(text.contains("aftest-managed-skill-content-hash-fnv1a64:"));
assert!(!text.contains("aftest-managed-skill-source-hash-fnv1a64:"));
let status = run_skill_admin(&spec(), SkillAction::Status, &opts);
assert!(status.is_ok());
if let Ok(SkillReport::Status {
installed_all,
valid_all,
current_all,
targets,
..
}) = status
{
assert!(installed_all);
assert!(valid_all);
assert!(current_all);
assert_eq!(targets.first().map(|t| t.scope), Some(None));
assert_eq!(targets.first().map(|t| t.current), Some(true));
}
let removed = run_skill_admin(&spec(), SkillAction::Uninstall, &opts);
assert!(removed.is_ok());
assert!(!skill_path.exists());
let _ = std::fs::remove_dir_all(dir);
}
fn spec_with_assets() -> SkillSpec<'static> {
const ASSETS: &[SkillAsset] = &[
SkillAsset {
path: "references/guide.md",
contents: "# guide\n",
},
SkillAsset {
path: "references/registry.json",
contents: "{\"ok\":true}\n",
},
];
SkillSpec {
name: "agent-first-test",
source: SKILL_SOURCE,
title: "Agent-First Test",
marker_slug: "aftest",
assets: ASSETS,
}
}
#[test]
fn install_writes_and_uninstall_removes_bundled_assets() {
let dir = temp_skills_dir("assets");
let opts = options(&dir, false);
let skill_dir = dir.join("agent-first-test");
let guide = skill_dir.join("references").join("guide.md");
let registry = skill_dir.join("references").join("registry.json");
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
assert_eq!(
std::fs::read_to_string(&guide).unwrap_or_default(),
"# guide\n"
);
assert_eq!(
std::fs::read_to_string(®istry).unwrap_or_default(),
"{\"ok\":true}\n"
);
std::fs::remove_file(&guide).unwrap();
match run_skill_admin(&spec_with_assets(), SkillAction::Status, &opts) {
Ok(SkillReport::Status { current_all, .. }) => {
assert!(
!current_all,
"a missing asset must make the skill not-current"
);
}
other => panic!("unexpected status: {other:?}"),
}
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
assert!(guide.is_file(), "re-install must restore the missing asset");
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts).is_ok());
assert!(!skill_dir.join(SKILL_FILE_NAME).exists());
assert!(!guide.exists(), "uninstall must remove bundled assets");
assert!(
!skill_dir.join("references").exists(),
"uninstall must remove now-empty asset directories"
);
assert!(
!skill_dir.exists(),
"uninstall must remove the skill directory"
);
let _ = std::fs::remove_dir_all(dir);
}
fn spec_without_registry() -> SkillSpec<'static> {
const ASSETS: &[SkillAsset] = &[SkillAsset {
path: "references/guide.md",
contents: "# guide\n",
}];
SkillSpec {
assets: ASSETS,
..spec_with_assets()
}
}
#[test]
fn install_removes_assets_an_earlier_bundle_installed_and_this_one_dropped() {
let dir = temp_skills_dir("stale-assets");
let opts = options(&dir, false);
let skill_dir = dir.join("agent-first-test");
let registry = skill_dir.join("references").join("registry.json");
let own = skill_dir.join("references").join("notes.md");
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
std::fs::write(&own, "mine\n").unwrap();
match run_skill_admin(&spec_without_registry(), SkillAction::Status, &opts) {
Ok(SkillReport::Status { current_all, .. }) => {
assert!(!current_all, "a dropped asset left behind is not current");
}
other => panic!("unexpected status: {other:?}"),
}
match run_skill_admin(&spec_without_registry(), SkillAction::Install, &opts) {
Ok(SkillReport::Install {
stale_assets_removed,
..
}) => assert_eq!(stale_assets_removed, vec![registry.clone()]),
other => panic!("unexpected install: {other:?}"),
}
assert!(!registry.exists(), "the dropped asset must be removed");
assert!(own.is_file(), "a file the user put there is not ours");
match run_skill_admin(&spec_without_registry(), SkillAction::Status, &opts) {
Ok(SkillReport::Status { current_all, .. }) => assert!(current_all),
other => panic!("unexpected status: {other:?}"),
}
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn uninstall_removes_assets_recorded_by_an_earlier_bundle() {
let dir = temp_skills_dir("stale-uninstall");
let opts = options(&dir, false);
let skill_dir = dir.join("agent-first-test");
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
assert!(run_skill_admin(&spec_without_registry(), SkillAction::Uninstall, &opts).is_ok());
assert!(
!skill_dir.exists(),
"an asset only the older bundle named must still go with the skill"
);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_recorded_asset_path_cannot_leave_the_skill_directory() {
let spec = spec_without_registry();
let text = managed_skill_contents(&spec).replace(
"aftest-managed-skill-asset: references/guide.md",
"aftest-managed-skill-asset: references/guide.md\naftest-managed-skill-asset: ../outside.md",
);
assert_eq!(recorded_assets(&spec, &text), vec!["references/guide.md"]);
}
#[test]
fn install_rejects_escaping_asset_path() {
const ESCAPE: &[SkillAsset] = &[SkillAsset {
path: "../evil.md",
contents: "x",
}];
let dir = temp_skills_dir("assets-escape");
let opts = options(&dir, false);
let spec = SkillSpec {
name: "agent-first-test",
source: SKILL_SOURCE,
title: "Agent-First Test",
marker_slug: "aftest",
assets: ESCAPE,
};
assert!(
run_skill_admin(&spec, SkillAction::Install, &opts).is_err(),
"an asset path escaping the skill dir must be rejected"
);
assert!(!dir.join("evil.md").exists());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn status_reports_stale_install_as_not_current() {
let dir = temp_skills_dir("stale");
let opts = options(&dir, false);
let skill_dir = dir.join("agent-first-test");
let skill_path = skill_dir.join(SKILL_FILE_NAME);
assert!(std::fs::create_dir_all(&skill_dir).is_ok());
let stale = managed_skill_with_body("# Body\n\nOLD rules.\n");
assert!(std::fs::write(&skill_path, stale).is_ok());
let status = run_skill_admin(&spec(), SkillAction::Status, &opts);
if let Ok(SkillReport::Status {
current_all,
targets,
..
}) = status
{
assert!(!current_all);
if let Some(t) = targets.first() {
assert!(t.installed);
assert!(t.valid);
assert!(t.managed);
assert!(!t.current);
}
}
assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_ok());
let refreshed = std::fs::read_to_string(&skill_path).unwrap_or_default();
assert!(refreshed.contains(&managed_marker_block(&spec())));
assert!(!refreshed.contains("<!-- aftest-managed-skill: true -->"));
if let Ok(SkillReport::Status { targets, .. }) =
run_skill_admin(&spec(), SkillAction::Status, &opts)
{
assert_eq!(targets.first().map(|t| t.current), Some(true));
}
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn random_text_with_marker_words_is_not_managed() {
let dir = temp_skills_dir("marker-words");
let opts = options(&dir, false);
let skill_dir = dir.join("agent-first-test");
let skill_path = skill_dir.join(SKILL_FILE_NAME);
assert!(std::fs::create_dir_all(&skill_dir).is_ok());
let random = format!(
"---\nname: agent-first-test\ndescription: test skill\n---\n\nThis mentions {} and {} but is not a generated block.\n",
generated_by(&spec()),
"aftest-managed-skill: true"
);
assert!(std::fs::write(&skill_path, random).is_ok());
if let Ok(SkillReport::Status { targets, .. }) =
run_skill_admin(&spec(), SkillAction::Status, &opts)
{
assert_eq!(targets.first().map(|t| t.managed), Some(false));
}
assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_err());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn old_marker_format_is_not_managed() {
let dir = temp_skills_dir("old-marker");
let opts = options(&dir, false);
let skill_dir = dir.join("agent-first-test");
let skill_path = skill_dir.join(SKILL_FILE_NAME);
assert!(std::fs::create_dir_all(&skill_dir).is_ok());
let old_marker = concat!(
"---\n",
"name: agent-first-test\n",
"description: test skill\n",
"---\n",
"<!--\n",
"Generated by aftest skill install\n",
"aftest-managed-skill: true\n",
"aftest-managed-skill-name: agent-first-test\n",
"aftest-managed-skill-source-hash-fnv1a64: deadbeef\n",
"-->\n",
"\n",
"# Body\n",
"\n",
"rules.\n"
);
assert!(std::fs::write(&skill_path, old_marker).is_ok());
if let Ok(SkillReport::Status { targets, .. }) =
run_skill_admin(&spec(), SkillAction::Status, &opts)
&& let Some(t) = targets.first()
{
assert!(t.installed);
assert!(t.valid);
assert!(!t.managed);
assert!(!t.current);
}
assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_err());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn install_preflight_reports_all_targets_without_writing() {
let dir = temp_skills_dir("install-preflight");
let first = custom_target(&dir.join("first"));
let second = custom_target(&dir.join("second"));
assert!(std::fs::create_dir_all(&second.skill_dir).is_ok());
assert!(
std::fs::write(
&second.skill_path,
"---\nname: custom\ndescription: custom\n---\n"
)
.is_ok()
);
let opts = SkillOptions {
location: SkillLocation::Standard(SkillScope::Personal),
force: false,
};
let result = preflight_install_targets(&spec(), &opts, &[first, second]);
assert!(result.is_err());
let Err(err) = result else {
return;
};
assert!(
err.message
.contains("refusing to overwrite unmanaged skill")
);
assert!(!dir.join("first").join("agent-first-test").exists());
let partial_report = err.partial_report.map(|report| *report);
assert!(matches!(partial_report, Some(SkillReport::Install { .. })));
let Some(SkillReport::Install {
installed, targets, ..
}) = partial_report
else {
return;
};
assert!(!installed);
assert_eq!(targets.len(), 2);
assert_eq!(targets.first().map(|target| target.installed), Some(false));
assert_eq!(targets.get(1).map(|target| target.installed), Some(true));
assert_eq!(targets.get(1).map(|target| target.managed), Some(false));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn uninstall_preflight_reports_all_targets_without_removing() {
let dir = temp_skills_dir("uninstall-preflight");
let first = custom_target(&dir.join("first"));
let second = custom_target(&dir.join("second"));
assert!(std::fs::create_dir_all(&first.skill_dir).is_ok());
assert!(std::fs::create_dir_all(&second.skill_dir).is_ok());
assert!(std::fs::write(&first.skill_path, managed_skill_contents(&spec())).is_ok());
assert!(
std::fs::write(
&second.skill_path,
"---\nname: custom\ndescription: custom\n---\n"
)
.is_ok()
);
let opts = SkillOptions {
location: SkillLocation::Standard(SkillScope::Personal),
force: false,
};
let result = preflight_uninstall_targets(&spec(), &opts, &[first, second]);
assert!(result.is_err());
let Err(err) = result else {
return;
};
assert!(err.message.contains("refusing to remove unmanaged skill"));
assert!(
dir.join("first")
.join("agent-first-test")
.join(SKILL_FILE_NAME)
.exists()
);
let partial_report = err.partial_report.map(|report| *report);
assert!(matches!(
partial_report,
Some(SkillReport::Uninstall { .. })
));
let Some(SkillReport::Uninstall {
removed_any,
targets,
..
}) = partial_report
else {
return;
};
assert!(!removed_any);
assert_eq!(targets.len(), 2);
assert!(targets.iter().all(|target| !target.removed));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn install_and_uninstall_refuse_unmanaged() {
let dir = temp_skills_dir("unmanaged");
let skill_dir = dir.join("agent-first-test");
let skill_path = skill_dir.join(SKILL_FILE_NAME);
assert!(std::fs::create_dir_all(&skill_dir).is_ok());
assert!(
std::fs::write(&skill_path, "---\nname: custom\ndescription: custom\n---\n").is_ok()
);
let opts = options(&dir, false);
assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_err());
assert!(run_skill_admin(&spec(), SkillAction::Uninstall, &opts).is_err());
assert!(skill_path.exists());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn invalid_spec_slugs_are_rejected_before_path_resolution() {
for name in ["", "../x", "x/y", ".hidden", "bad_name", "Bad"] {
let bad = SkillSpec {
name,
source: SKILL_SOURCE,
title: "Bad",
marker_slug: "aftest",
assets: &[],
};
let opts = options(Path::new("/tmp/afdata"), false);
assert!(
run_skill_admin(&bad, SkillAction::Status, &opts).is_err(),
"{name:?}"
);
}
let bad_marker = SkillSpec {
name: "agent-first-test",
source: SKILL_SOURCE,
title: "Bad",
marker_slug: "../aftest",
assets: &[],
};
let opts = options(Path::new("/tmp/afdata"), false);
assert!(run_skill_admin(&bad_marker, SkillAction::Status, &opts).is_err());
}
#[test]
fn frontmatter_name_must_match_spec_name() {
let bad = SkillSpec {
name: "agent-first-test",
source: "---\nname: other-skill\ndescription: test skill\n---\n",
title: "Bad",
marker_slug: "aftest",
assets: &[],
};
let dir = temp_skills_dir("frontmatter-name");
let opts = options(&dir, false);
assert!(run_skill_admin(&bad, SkillAction::Install, &opts).is_err());
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[test]
fn symlink_target_is_rejected_by_default_and_force_does_not_follow() {
use std::os::unix::fs::symlink;
let dir = temp_skills_dir("symlink-install");
let opts = options(&dir, false);
let force_opts = options(&dir, true);
let skill_dir = dir.join("agent-first-test");
let skill_path = skill_dir.join(SKILL_FILE_NAME);
let external = dir.join("external.md");
assert!(std::fs::create_dir_all(&skill_dir).is_ok());
assert!(std::fs::write(&external, "external").is_ok());
assert!(symlink(&external, &skill_path).is_ok());
assert!(run_skill_admin(&spec(), SkillAction::Install, &opts).is_err());
assert_eq!(
std::fs::read_to_string(&external).unwrap_or_default(),
"external"
);
assert!(run_skill_admin(&spec(), SkillAction::Uninstall, &opts).is_err());
assert!(skill_path.is_symlink());
assert!(run_skill_admin(&spec(), SkillAction::Install, &force_opts).is_ok());
assert_eq!(
std::fs::read_to_string(&external).unwrap_or_default(),
"external"
);
assert!(skill_path.is_file());
assert!(!skill_path.is_symlink());
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[test]
fn a_symlinked_skill_directory_never_receives_a_write() {
use std::os::unix::fs::symlink;
let dir = temp_skills_dir("symlink-skill-dir");
let outside = temp_skills_dir("symlink-skill-dir-outside");
assert!(std::fs::create_dir_all(&dir).is_ok());
assert!(std::fs::create_dir_all(&outside).is_ok());
let sentinel = outside.join(SKILL_FILE_NAME);
assert!(std::fs::write(&sentinel, "sentinel").is_ok());
assert!(symlink(&outside, dir.join("agent-first-test")).is_ok());
for force in [false, true] {
let opts = options(&dir, force);
let err = run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts)
.expect_err("install through a symlinked skill directory must fail");
assert!(
err.message.contains("symlinked directory"),
"unexpected message: {}",
err.message
);
assert_eq!(
err.hint.as_deref(),
Some("--force does not permit writing outside the skills directory"),
"--force must not read as permission to escape the root"
);
assert!(
run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts).is_err(),
"uninstall must refuse the same path"
);
}
assert_eq!(
std::fs::read_to_string(&sentinel).unwrap_or_default(),
"sentinel",
"the file outside the skills directory must be untouched"
);
assert!(!outside.join("references").exists());
let _ = std::fs::remove_dir_all(dir);
let _ = std::fs::remove_dir_all(outside);
}
#[cfg(unix)]
#[test]
fn a_symlinked_asset_directory_never_receives_a_write() {
use std::os::unix::fs::symlink;
let dir = temp_skills_dir("symlink-asset-dir");
let outside = temp_skills_dir("symlink-asset-dir-outside");
let skill_dir = dir.join("agent-first-test");
assert!(std::fs::create_dir_all(&skill_dir).is_ok());
assert!(std::fs::create_dir_all(&outside).is_ok());
let sentinel = outside.join("guide.md");
assert!(std::fs::write(&sentinel, "sentinel").is_ok());
assert!(symlink(&outside, skill_dir.join("references")).is_ok());
let opts = options(&dir, true);
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_err());
assert_eq!(
std::fs::read_to_string(&sentinel).unwrap_or_default(),
"sentinel"
);
assert!(!skill_dir.join(SKILL_FILE_NAME).exists());
let _ = std::fs::remove_dir_all(dir);
let _ = std::fs::remove_dir_all(outside);
}
#[cfg(unix)]
#[test]
fn status_names_a_symlinked_skill_directory_instead_of_reading_through_it() {
use std::os::unix::fs::symlink;
let dir = temp_skills_dir("symlink-status");
let outside = temp_skills_dir("symlink-status-outside");
assert!(std::fs::create_dir_all(&dir).is_ok());
assert!(std::fs::create_dir_all(&outside).is_ok());
assert!(std::fs::write(outside.join(SKILL_FILE_NAME), "sentinel").is_ok());
assert!(symlink(&outside, dir.join("agent-first-test")).is_ok());
let opts = options(&dir, false);
let report = run_skill_admin(&spec(), SkillAction::Status, &opts)
.expect("status must report every target rather than fail outright");
let SkillReport::Status { targets, .. } = report else {
panic!("expected a status report");
};
let target = targets.first().expect("one target");
assert!(!target.installed, "nothing may be read through the link");
assert!(
target
.validation_error
.as_deref()
.unwrap_or_default()
.contains("symlinked directory")
);
let _ = std::fs::remove_dir_all(dir);
let _ = std::fs::remove_dir_all(outside);
}
#[test]
fn uninstall_reports_the_assets_it_removed_and_a_directory_the_user_kept() {
let dir = temp_skills_dir("uninstall-report");
let opts = options(&dir, false);
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
let mine = dir.join("agent-first-test").join("notes.md");
assert!(std::fs::write(&mine, "mine").is_ok());
let report = run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts)
.expect("uninstall must succeed");
let SkillReport::Uninstall { targets, .. } = report else {
panic!("expected an uninstall report");
};
let target = targets.first().expect("one target");
assert!(target.removed);
assert_eq!(
target.assets_removed,
vec![
"references/guide.md".to_string(),
"references/registry.json".to_string()
]
);
assert!(
target.directory_retained,
"a directory holding the user's own file survives, and the report says so"
);
assert_eq!(std::fs::read_to_string(&mine).unwrap_or_default(), "mine");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn install_leaves_a_users_own_reference_alone_without_force() {
let dir = temp_skills_dir("unmanaged-asset");
let opts = options(&dir, false);
let skill_dir = dir.join("agent-first-test");
let guide = skill_dir.join("references").join("guide.md");
std::fs::create_dir_all(guide.parent().unwrap()).unwrap();
std::fs::write(&guide, "my notes\n").unwrap();
let err = run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts)
.expect_err("a file the user put there is not this tool's to replace");
assert!(
err.message.contains("unmanaged skill asset"),
"{}",
err.message
);
assert_eq!(std::fs::read_to_string(&guide).unwrap(), "my notes\n");
assert!(!skill_dir.join(SKILL_FILE_NAME).exists());
std::fs::write(&guide, "# guide\n").unwrap();
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
std::fs::write(&guide, "older bundle\n").unwrap();
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
assert_eq!(std::fs::read_to_string(&guide).unwrap(), "# guide\n");
std::fs::remove_file(skill_dir.join(SKILL_FILE_NAME)).unwrap();
std::fs::write(&guide, "my notes\n").unwrap();
let forced = options(&dir, true);
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &forced).is_ok());
assert_eq!(std::fs::read_to_string(&guide).unwrap(), "# guide\n");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn install_refuses_a_directory_at_an_asset_path_before_writing_anything() {
let dir = temp_skills_dir("asset-is-dir");
let opts = options(&dir, true);
let skill_dir = dir.join("agent-first-test");
std::fs::create_dir_all(skill_dir.join("references").join("guide.md")).unwrap();
let err = run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts)
.expect_err("a directory cannot be replaced by an asset file");
assert!(
err.message.contains("non-regular skill asset"),
"{}",
err.message
);
assert!(!skill_dir.join(SKILL_FILE_NAME).exists());
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[test]
fn an_uninstall_that_fails_partway_can_be_run_again() {
use std::os::unix::fs::PermissionsExt;
let dir = temp_skills_dir("uninstall-retry");
let opts = options(&dir, false);
let skill_dir = dir.join("agent-first-test");
let references = skill_dir.join("references");
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
std::fs::set_permissions(&references, std::fs::Permissions::from_mode(0o555)).unwrap();
let failed = run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts);
std::fs::set_permissions(&references, std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(failed.is_err());
assert!(skill_dir.join(SKILL_FILE_NAME).is_file());
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts).is_ok());
assert!(!references.join("guide.md").exists());
assert!(!skill_dir.exists());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn uninstall_reports_a_bundled_asset_it_could_not_remove() {
let dir = temp_skills_dir("uninstall-stuck-asset");
let opts = options(&dir, false);
assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
let asset = dir
.join("agent-first-test")
.join("references")
.join("guide.md");
assert!(std::fs::remove_file(&asset).is_ok());
assert!(std::fs::create_dir(&asset).is_ok());
assert!(std::fs::write(asset.join("kept.md"), "kept").is_ok());
let err = run_skill_admin(&spec_with_assets(), SkillAction::Uninstall, &opts)
.expect_err("a managed asset that cannot be removed is not a clean uninstall");
let named = Path::new("references").join("guide.md");
assert!(
err.message.contains(&named.display().to_string()),
"unexpected message: {}",
err.message
);
assert!(
asset.join("kept.md").exists(),
"the user's file must survive the refusal"
);
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[test]
fn force_uninstall_removes_symlink_without_following() {
use std::os::unix::fs::symlink;
let dir = temp_skills_dir("symlink-uninstall");
let force_opts = options(&dir, true);
let skill_dir = dir.join("agent-first-test");
let skill_path = skill_dir.join(SKILL_FILE_NAME);
let external = dir.join("external.md");
assert!(std::fs::create_dir_all(&skill_dir).is_ok());
assert!(std::fs::write(&external, "external").is_ok());
assert!(symlink(&external, &skill_path).is_ok());
assert!(run_skill_admin(&spec(), SkillAction::Uninstall, &force_opts).is_ok());
assert!(!skill_path.exists());
assert_eq!(
std::fs::read_to_string(&external).unwrap_or_default(),
"external"
);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn serializes_to_protocol_shape() {
let dir = temp_skills_dir("serialize");
let opts = options(&dir, false);
if let Ok(report) = run_skill_admin(&spec(), SkillAction::Install, &opts) {
let value = serde_json::to_value(&report).unwrap_or(serde_json::Value::Null);
assert_eq!(value["code"], "skill_install");
assert_eq!(value["installed"], true);
assert_eq!(value["targets"][0]["scope"], serde_json::Value::Null);
assert_eq!(value["targets"][0]["current"], true);
assert_eq!(
value["targets"][0]["skill_dir"],
serde_json::json!(dir.join("agent-first-test").to_string_lossy().to_string())
);
}
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn personal_folders_use_the_supplied_environment() -> Result<(), SkillError> {
let home = std::env::temp_dir().join("h");
let env = BTreeMap::from([("HOME".into(), home.display().to_string())]);
assert_eq!(
personal_skills_dirs(&env)?,
[
home.join(".agents/skills"),
home.join(".claude/skills"),
home.join(".gemini/config/skills"),
]
);
let env = BTreeMap::from([("HOME".into(), "relative".into())]);
assert!(matches!(
personal_skills_dirs(&env),
Err(SkillError {
kind: SkillErrorKind::Usage,
..
})
));
Ok(())
}
#[test]
fn personal_install_writes_every_standard_folder_and_refuses_unmanaged()
-> Result<(), Box<dyn std::error::Error>> {
let home = tempfile::tempdir()?;
let env = BTreeMap::from([("HOME".into(), home.path().display().to_string())]);
let spec = spec();
let report = run_personal_in(&spec, SkillAction::Install, &env)?;
assert!(matches!(report, SkillReport::Install { targets, .. }
if targets.len() == 3
&& targets.iter().all(|target| target.skill_path.is_file()
&& target.scope == Some(SkillScope::Personal))));
assert!(matches!(
run_personal_in(&spec, SkillAction::Status, &env)?,
SkillReport::Status {
current_all: true,
..
}
));
let claude = home
.path()
.join(".claude/skills")
.join(spec.name)
.join(SKILL_FILE_NAME);
std::fs::write(&claude, "manual")?;
let result = run_personal_in(&spec, SkillAction::Install, &env);
assert!(matches!(
result,
Err(SkillError {
kind: SkillErrorKind::Refused,
partial_report: Some(_),
..
})
));
assert_eq!(std::fs::read_to_string(claude)?, "manual");
Ok(())
}
#[test]
fn workspace_standard_resolves_each_shared_folder_once() -> Result<(), SkillError> {
let cwd = std::env::current_dir().map_err(|e| SkillError::io("cwd", e))?;
let targets = resolve_targets(
&spec(),
&SkillLocation::Standard(SkillScope::Workspace),
standard_skills_dirs,
)?;
assert_eq!(
targets
.iter()
.map(|target| target.skills_dir.clone())
.collect::<Vec<_>>(),
[cwd.join(".agents/skills"), cwd.join(".claude/skills")]
);
assert!(
targets
.iter()
.all(|target| target.scope == Some(SkillScope::Workspace))
);
Ok(())
}
#[test]
fn an_explicit_directory_is_one_target_without_scope() -> Result<(), SkillError> {
let targets = resolve_targets(
&spec(),
&SkillLocation::Directory("/tmp/qwen/skills".to_string()),
|_| {
Err(SkillError::new(
SkillErrorKind::Usage,
"unused".into(),
None,
))
},
)?;
assert_eq!(targets.len(), 1);
assert_eq!(targets[0].scope, None);
assert_eq!(targets[0].skills_dir, Path::new("/tmp/qwen/skills"));
assert!(matches!(
resolve_targets(&spec(), &SkillLocation::Directory(String::new()), |_| Ok(
Vec::new()
)),
Err(SkillError {
kind: SkillErrorKind::Usage,
..
})
));
Ok(())
}
}