1use 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#[derive(Clone, Copy, Debug)]
27pub struct SkillAsset<'a> {
28 pub path: &'a str,
32 pub contents: &'a str,
34}
35
36#[derive(Clone, Copy, Debug)]
44pub struct SkillSpec<'a> {
45 pub name: &'a str,
47 pub source: &'a str,
49 pub title: &'a str,
51 pub marker_slug: &'a str,
53 pub assets: &'a [SkillAsset<'a>],
57}
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
61#[serde(rename_all = "lowercase")]
62pub enum SkillScope {
63 Personal,
65 Workspace,
67}
68
69#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
71#[serde(rename_all = "lowercase")]
72pub enum SkillLocation {
73 Standard(SkillScope),
78 Directory(String),
81}
82
83#[derive(Clone, Debug, Serialize)]
85pub struct SkillOptions {
86 pub location: SkillLocation,
88 pub force: bool,
90}
91
92#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
94#[serde(rename_all = "lowercase")]
95pub enum SkillAction {
96 Status,
98 Install,
100 Uninstall,
102}
103
104#[derive(Clone, Debug, Serialize)]
106pub struct SkillTargetStatus {
107 pub scope: Option<SkillScope>,
109 pub skills_dir: PathBuf,
111 pub skill_dir: PathBuf,
113 pub skill_path: PathBuf,
115 pub installed: bool,
117 pub managed: bool,
119 pub valid: bool,
121 pub current: bool,
123 pub validation_error: Option<String>,
125}
126
127#[derive(Clone, Debug, Serialize)]
129pub struct SkillUninstallStatus {
130 pub scope: Option<SkillScope>,
132 pub skills_dir: PathBuf,
134 pub skill_dir: PathBuf,
136 pub skill_path: PathBuf,
138 pub removed: bool,
140 pub assets_removed: Vec<String>,
144 pub directory_retained: bool,
149}
150
151#[derive(Clone, Debug, Serialize)]
154#[serde(tag = "code")]
155pub enum SkillReport {
156 #[serde(rename = "skill_status")]
158 Status {
159 skill: String,
161 installed_all: bool,
163 valid_all: bool,
165 current_all: bool,
167 targets: Vec<SkillTargetStatus>,
169 },
170 #[serde(rename = "skill_install")]
172 Install {
173 skill: String,
175 installed: bool,
177 targets: Vec<SkillTargetStatus>,
179 stale_assets_removed: Vec<PathBuf>,
183 hint: &'static str,
185 },
186 #[serde(rename = "skill_uninstall")]
188 Uninstall {
189 skill: String,
191 removed_any: bool,
193 targets: Vec<SkillUninstallStatus>,
195 },
196}
197
198#[derive(Clone, Copy, Debug, PartialEq, Eq)]
201pub enum SkillErrorKind {
202 Usage,
205 InvalidSpec,
208 Refused,
212 Io,
214}
215
216impl SkillErrorKind {
217 #[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#[derive(Clone, Debug)]
231pub struct SkillError {
232 pub kind: SkillErrorKind,
234 pub message: String,
236 pub hint: Option<String>,
238 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 fn write_failed(action: &str, err: crate::atomic_file::AtomicError) -> Self {
271 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
292pub 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
304pub 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 if let Err(err) = containment_failure(spec, target) {
379 failures.push(err);
380 escaped = true;
381 continue;
382 }
383 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 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 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 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 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
688const SHARED_SKILL_FOLDERS: [&str; 2] = [".agents/skills", ".claude/skills"];
691
692const 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 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 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
905fn 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
929fn 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
937fn 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 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 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
1173fn 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 if components.peek().is_none() {
1212 break;
1213 }
1214 match std::fs::symlink_metadata(¤t) {
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 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
1237fn 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
1260fn 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
1284fn 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
1305fn 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
1315fn 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 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
1333fn 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
1344fn 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 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(¤t) {
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
1393fn 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(®istry).unwrap_or_default(),
1573 "{\"ok\":true}\n"
1574 );
1575
1576 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 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 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 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 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 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 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 std::fs::write(&guide, "# guide\n").unwrap();
2146 assert!(run_skill_admin(&spec_with_assets(), SkillAction::Install, &opts).is_ok());
2147
2148 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 #[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 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 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 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}