diff --git a/crates/skilld-command/src/lib.rs b/crates/skilld-command/src/lib.rs index 29248e3e..43f839db 100644 --- a/crates/skilld-command/src/lib.rs +++ b/crates/skilld-command/src/lib.rs @@ -32,7 +32,7 @@ use clap::{CommandFactory, Parser, Subcommand, error::ErrorKind}; pub use config::{ConfigStore, LocalConfig}; pub use local_store::{ AllowTransaction, LocalStore, PreparedStoreInstall, PreparedStoreUpdate, ResolvedTarget, - SkillView, StoreError, TargetInstall, TransactionGate, + SkillView, StoreDeclaration, StoreError, TargetInstall, TransactionGate, }; pub use output::{CommandPlatform, OutputContext}; pub use provenance::{RemoteProvenance, search_result_page_url}; @@ -98,6 +98,8 @@ enum Command { options: doctor::DoctorOptions, }, /// Sync declared Skills and their required Skills to Agent targets. + /// + /// Sync also removes each Skill it installed that no declaration names. Sync { /// Read declarations from this JSON file. #[arg(long, default_value = ".skills/skilld.json")] diff --git a/crates/skilld-command/src/local_store.rs b/crates/skilld-command/src/local_store.rs index 03c5deb3..77c4b88c 100644 --- a/crates/skilld-command/src/local_store.rs +++ b/crates/skilld-command/src/local_store.rs @@ -10,8 +10,9 @@ use std::time::{SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use skilld_core::{ - AgentTargetId, CommitSha, InstallMode, LockDocument, LockedDeclarationSkill, LockedSkill, - LockedSource, LockedTarget, RemoteSelector, SkillName, SourceRef, SourceSelector, SourceStatus, + AgentTargetId, CommitSha, InstallMode, InstalledBy, LockDocument, LockedDeclarationSkill, + LockedSkill, LockedSource, LockedTarget, RemoteSelector, SkillName, SourceRef, SourceSelector, + SourceStatus, }; const JOURNAL_NAME: &str = ".skilld-transaction"; @@ -253,13 +254,37 @@ impl LocalStore { Ok(file_permissions(source)? == file_permissions(&installed)?) } + /// Install a declaration and remove the `undeclared` Skills in one transaction. pub fn apply_sync_batch( &self, installs: Vec, snapshot: &LockDocument, declaration: StoreDeclaration, + undeclared: Vec, adopt: bool, known_targets: &[ResolvedTarget], + ) -> Result, StoreError> { + self.apply_sync_batch_with_gate( + installs, + snapshot, + declaration, + undeclared, + adopt, + known_targets, + &AllowTransaction, + ) + } + + #[allow(clippy::too_many_arguments)] + pub fn apply_sync_batch_with_gate( + &self, + installs: Vec, + snapshot: &LockDocument, + declaration: StoreDeclaration, + undeclared: Vec, + adopt: bool, + known_targets: &[ResolvedTarget], + gate: &G, ) -> Result, StoreError> { let updates = installs .into_iter() @@ -276,9 +301,10 @@ impl LocalStore { self.apply_batch( updates, Some(declaration), + undeclared, adopt, known_targets, - &AllowTransaction, + gate, ) } @@ -519,6 +545,8 @@ impl LocalStore { mode: target.mode, }) .collect(), + // `skilld install` owns this Skill, so sync never removes it. + installed_by: None, }, ); if let Err(error) = self.write_lock_atomic(&new_lock, &transaction) { @@ -556,20 +584,26 @@ impl LocalStore { expected_skill: Some(update.expected_skill), }) .collect(); - self.apply_batch(updates, None, false, known_targets, gate) + self.apply_batch(updates, None, Vec::new(), false, known_targets, gate) } fn apply_batch( &self, updates: Vec, requirements: Option, + undeclared: Vec, adopt: bool, known_targets: &[ResolvedTarget], gate: &G, ) -> Result, StoreError> { ensure_write_capability()?; if updates.is_empty() { - return Ok(vec![]); + if undeclared.is_empty() { + return Ok(vec![]); + } + return Err(StoreError::InvalidSource( + "a Skill sync needs at least one declared Skill".to_owned(), + )); } let mut names = BTreeSet::new(); @@ -648,6 +682,21 @@ impl LocalStore { update, }); } + let removals = undeclared + .into_iter() + .map(|name| { + if names.contains(&name) { + return Err(StoreError::InvalidSource(format!( + "Skill {name} cannot be installed and removed in one sync" + ))); + } + let old_skill = old_lock + .skills + .get(name.as_str()) + .ok_or_else(stale_update_plan)?; + self.plan_removal(name, old_skill, known_targets) + }) + .collect::, StoreError>>()?; let transaction = transaction_id(); let journal = Journal { @@ -669,6 +718,22 @@ impl LocalStore { }) .collect(), }) + .chain(removals.iter().map(|removal| { + JournalSkill { + operation: JournalOperation::Remove, + skill: removal.name.to_string(), + canonical_had_existing: removal.canonical_had_existing, + targets: removal + .targets + .iter() + .map(|target| JournalTarget { + agent: target.agent, + had_existing: true, + promote: false, + }) + .collect(), + } + })) .collect(), }; self.write_journal(&journal)?; @@ -714,10 +779,22 @@ impl LocalStore { } } } + for removal in &removals { + let canonical = self.root.join(removal.name.as_str()); + if removal.canonical_had_existing { + rename_path(&canonical, backup_path(&canonical, &transaction)?)?; + } + for target in &removal.targets { + let destination = target.destination(&removal.name); + rename_path(&destination, backup_path(&destination, &transaction)?)?; + } + } gate.before_lock_commit(&self.lockfile_path())?; let mut new_lock = old_lock; new_lock.transaction_id.clone_from(&transaction); + // Sync owns every Skill it writes. An update keeps the recorded installer. + let sync = requirements.is_some(); if let Some(declaration) = requirements { new_lock .requirements @@ -741,9 +818,21 @@ impl LocalStore { mode: target.mode, }) .collect(), + installed_by: if sync { + Some(InstalledBy::Sync) + } else { + prepared + .update + .expected_skill + .as_ref() + .and_then(|skill| skill.installed_by) + }, }, ); } + for removal in &removals { + new_lock.skills.remove(removal.name.as_str()); + } self.write_lock_atomic(&new_lock, &transaction) })(); if let Err(error) = commit_result { @@ -965,6 +1054,58 @@ impl LocalStore { Ok(()) } + /// Plan an undeclared Skill's removal. Agent target paths this store does not own stay in place. + fn plan_removal( + &self, + name: SkillName, + skill: &LockedSkill, + known_targets: &[ResolvedTarget], + ) -> Result { + if skill.installed_by != Some(InstalledBy::Sync) { + return Err(StoreError::Conflict(format!( + "sync did not install Skill {name}, so sync cannot remove it" + ))); + } + let digest = source_digest(&skill.source_status); + let canonical = self.root.join(name.as_str()); + let canonical_had_existing = path_exists(&canonical)?; + if canonical_had_existing && !hash_skill_tree(&canonical).is_ok_and(|hash| hash == digest) { + return Err(StoreError::Conflict(format!( + "canonical Skill {name} changed after installation" + ))); + } + let mut targets = Vec::new(); + for target in unique_locked_target_paths(&name, &skill.targets, known_targets)? { + let destination = target.destination(&name); + let metadata = match fs::symlink_metadata(&destination) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => continue, + Err(error) => return Err(fs_error(error)), + }; + let owned = if metadata.file_type().is_symlink() { + let link = fs::read_link(&destination).map_err(fs_error)?; + normalize_path(&target.root.join(link)) == canonical + } else { + let copied = skill.targets.iter().any(|locked| { + locked.mode == InstallMode::Copy + && find_target(known_targets, locked.agent) + .is_ok_and(|known| known.root == target.root) + }); + copied + && metadata.is_dir() + && hash_skill_tree(&destination).is_ok_and(|hash| hash == digest) + }; + if owned { + targets.push(target); + } + } + Ok(StoreRemoval { + name, + canonical_had_existing, + targets, + }) + } + fn lockfile_path(&self) -> PathBuf { self.root.join(LOCKFILE_NAME) } @@ -1262,6 +1403,14 @@ struct BatchStoreUpdate { changes: Vec, } +/// An undeclared Skill and the Agent target paths that link to or copy its store directory. +#[derive(Clone, Debug)] +struct StoreRemoval { + name: SkillName, + canonical_had_existing: bool, + targets: Vec, +} + #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct Journal { diff --git a/crates/skilld-command/src/sync.rs b/crates/skilld-command/src/sync.rs index 862da855..46f872b0 100644 --- a/crates/skilld-command/src/sync.rs +++ b/crates/skilld-command/src/sync.rs @@ -4,8 +4,9 @@ use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use skilld_core::{ - AgentTargetId, CommitSha, InstallMode, InstallScope, InstallSource, LockedDeclarationSkill, - LockedSource, LockedTarget, RemoteSelector, SkillName, SourceRef, SourceStatus, + AgentTargetId, CommitSha, InstallMode, InstallScope, InstallSource, InstalledBy, LockDocument, + LockedDeclarationSkill, LockedSource, LockedTarget, RemoteSelector, SkillName, SourceRef, + SourceStatus, }; use skilld_ui::Line; @@ -134,25 +135,54 @@ pub struct SyncRequest { pub adopt: bool, } +/// A Skill in this store's lockfile that no declaration names. +#[derive(Debug, Serialize)] +#[serde(tag = "_tag", rename_all_fields = "camelCase")] +pub enum UndeclaredSkill { + /// Sync installed this Skill, so sync removes it. + Removable { name: String }, + /// `skilld install` or an older sync installed this Skill, so sync keeps it. + Kept { + name: String, + remove_command: String, + }, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SyncReport { pub current: bool, pub changed: Vec, + pub undeclared: Vec, pub requirements_changed: bool, pub declarations_changed: bool, } impl SyncReport { + fn removable(&self) -> impl Iterator { + self.undeclared.iter().filter_map(|skill| match skill { + UndeclaredSkill::Removable { name } => Some(name.as_str()), + UndeclaredSkill::Kept { .. } => None, + }) + } + pub(crate) fn lines(&self) -> Vec { - if self.current { - vec![Line::success("Declared Skills match their Agent targets.")] + let mut lines = if self.current { + let mut lines = vec![Line::success("Declared Skills match their Agent targets.")]; + lines.extend(self.removable().map(|name| { + Line::success(format!("Removed Skill {name}. It is no longer declared.")) + })); + lines } else { let mut lines: Vec<_> = self .changed .iter() .map(|name| Line::warn(format!("Skill {name} needs sync."))) .collect(); + lines.extend( + self.removable() + .map(|name| Line::warn(format!("Skill {name} is no longer declared."))), + ); if self.requirements_changed { lines.push(Line::warn("Declared Skill requirements need sync.")); } @@ -160,10 +190,68 @@ impl SyncReport { lines.push(Line::warn("Skill declarations need sync.")); } lines + }; + for skill in &self.undeclared { + if let UndeclaredSkill::Kept { + name, + remove_command, + } = skill + { + lines.push(Line::warn(format!( + "Skill {name} is not declared. Sync did not install it, so sync keeps it." + ))); + lines.push(Line::plain(format!("To remove it, run: {remove_command}"))); + } } + lines } } +/// The command that removes a Skill from the store this sync uses. +fn remove_command(host: &LocalHost, scope: InstallScope, name: &str) -> String { + match scope { + InstallScope::Project => format!("skilld remove {name}"), + InstallScope::Global => { + let root = host.global_root.to_string_lossy(); + let safe = root.chars().all(|character| { + character.is_ascii_alphanumeric() || "/._-+:@%,".contains(character) + }); + let root = if safe { + root.into_owned() + } else { + format!("'{}'", root.replace('\'', r"'\''")) + }; + format!("SKILLD_DATA_DIR={root} skilld remove {name} --global") + } + } +} + +/// Skills in this store's lockfile that neither this manifest nor another declaration names. +fn undeclared_skills(snapshot: &LockDocument, manifest: &Manifest) -> Vec { + let mut declared = manifest + .skills + .keys() + .chain(manifest.requires.values().flatten()) + .map(SkillName::as_str) + .collect::>(); + for (owner, skills) in &snapshot.declarations { + if owner != manifest.name.as_str() { + declared.extend(skills.keys().map(String::as_str)); + } + } + for (owner, requirements) in &snapshot.requirements { + if owner != manifest.name.as_str() { + declared.extend(requirements.values().flatten().map(String::as_str)); + } + } + snapshot + .skills + .keys() + .filter(|name| !declared.contains(name.as_str())) + .cloned() + .collect() +} + pub(crate) fn sync(host: &LocalHost, request: SyncRequest) -> Result { let path = if request.manifest.is_absolute() { request.manifest @@ -203,6 +291,35 @@ pub(crate) fn sync(host: &LocalHost, request: SyncRequest) -> Result>(); let requirements_changed = snapshot.requirements.get(manifest.name.as_str()) != Some(&requirements); + let undeclared = undeclared_skills(&snapshot, &manifest) + .into_iter() + .map(|name| { + if snapshot.skills[&name].installed_by == Some(InstalledBy::Sync) { + UndeclaredSkill::Removable { name } + } else { + let remove_command = remove_command(host, request.scope, &name); + UndeclaredSkill::Kept { + name, + remove_command, + } + } + }) + .collect::>(); + let removals = undeclared + .iter() + .filter_map(|skill| match skill { + UndeclaredSkill::Removable { name } => Some(name), + UndeclaredSkill::Kept { .. } => None, + }) + .map(|name| SkillName::parse(name.clone()).map_err(CommandError::domain)) + .collect::, _>>()?; + // An older sync wrote declared entries without an installer, so sync records it now. + let installer_missing = manifest.skills.keys().any(|name| { + snapshot + .skills + .get(name.as_str()) + .is_some_and(|skill| skill.installed_by != Some(InstalledBy::Sync)) + }); let mut changed = Vec::new(); let mut installs = Vec::new(); // Keep every remote staging directory alive until the batch commits. @@ -398,13 +515,22 @@ pub(crate) fn sync(host: &LocalHost, request: SyncRequest) -> Result Result Result PathBuf { named_source(root, parent, "example", content) @@ -954,3 +959,158 @@ fn recovery_rejects_a_journal_skill_with_path_traversal() { assert_eq!(error.code(), "INVALID_LOCKFILE"); assert_eq!(fs::read_to_string(outside.join("keep")).unwrap(), "fixture"); } + +/// Prepare a sync of a fixture declaration that names each of `sources`. +fn declared_sync( + store: &LocalStore, + sources: &[&Path], + install: &TargetInstall, +) -> (Vec, LockDocument, StoreDeclaration) { + let snapshot = store + .snapshot(std::slice::from_ref(&install.target)) + .unwrap(); + let declaration = StoreDeclaration { + name: "fixture".to_owned(), + skills: sources + .iter() + .map(|source| { + ( + source.file_name().unwrap().to_str().unwrap().to_owned(), + LockedDeclarationSkill { + source: local_source(source), + targets: vec![LockedTarget { + agent: install.target.agent, + mode: install.mode, + }], + }, + ) + }) + .collect(), + requirements: BTreeMap::new(), + }; + let installs = sources + .iter() + .map(|source| PreparedStoreInstall { + source: source.to_path_buf(), + locked_source: local_source(source), + source_status: None, + targets: vec![install.clone()], + }) + .collect(); + (installs, snapshot, declaration) +} + +fn copy_target(temporary: &Path) -> TargetInstall { + TargetInstall { + target: resolved( + AgentTargetId::Codex, + temporary.join("project/.agents/skills"), + ), + mode: InstallMode::Copy, + } +} + +#[test] +fn a_lock_commit_failure_restores_every_undeclared_skill_a_sync_removed() { + let temporary = tempfile::tempdir().unwrap(); + let alpha = named_source(temporary.path(), "sources", "alpha", "alpha"); + let beta = named_source(temporary.path(), "sources", "beta", "beta"); + let store = LocalStore::new(temporary.path().join("project/.skills")); + let install = copy_target(temporary.path()); + let target = install.target.clone(); + let (installs, snapshot, declaration) = declared_sync(&store, &[&alpha, &beta], &install); + store + .apply_sync_batch( + installs, + &snapshot, + declaration, + vec![], + false, + std::slice::from_ref(&target), + ) + .unwrap(); + let lockfile = store.root().join("skilld-lock.yaml"); + let before = fs::read(&lockfile).unwrap(); + let undeclared = || vec![SkillName::parse("beta").unwrap()]; + + let (installs, snapshot, declaration) = declared_sync(&store, &[&alpha], &install); + let error = store + .apply_sync_batch_with_gate( + installs, + &snapshot, + declaration, + undeclared(), + false, + std::slice::from_ref(&target), + &RejectLockCommit, + ) + .unwrap_err(); + + assert_eq!(error.to_string(), "injected lock failure"); + assert_eq!(fs::read(&lockfile).unwrap(), before); + for root in [store.root(), target.root.as_path()] { + assert_eq!( + fs::read_to_string(root.join("beta/SKILL.md")).unwrap(), + "---\nname: beta\ndescription: Test fixture.\n---\n\nbeta\n" + ); + } + + let (installs, snapshot, declaration) = declared_sync(&store, &[&alpha], &install); + store + .apply_sync_batch( + installs, + &snapshot, + declaration, + undeclared(), + false, + std::slice::from_ref(&target), + ) + .unwrap(); + + assert!(!store.root().join("beta").exists()); + assert!(!target.root.join("beta").exists()); + assert!(target.root.join("alpha/SKILL.md").is_file()); + assert_eq!( + store.list(std::slice::from_ref(&target)).unwrap(), + ["alpha"] + ); +} + +#[test] +fn a_sync_refuses_to_remove_a_skill_that_sync_did_not_install() { + let temporary = tempfile::tempdir().unwrap(); + let alpha = named_source(temporary.path(), "sources", "alpha", "alpha"); + let gamma = named_source(temporary.path(), "sources", "gamma", "gamma"); + let store = LocalStore::new(temporary.path().join("project/.skills")); + let install = copy_target(temporary.path()); + let target = install.target.clone(); + store + .install_from( + &gamma, + local_source(&gamma), + std::slice::from_ref(&install), + std::slice::from_ref(&target), + ) + .unwrap(); + let before = fs::read(store.root().join("skilld-lock.yaml")).unwrap(); + + let (installs, snapshot, declaration) = declared_sync(&store, &[&alpha], &install); + let error = store + .apply_sync_batch( + installs, + &snapshot, + declaration, + vec![SkillName::parse("gamma").unwrap()], + false, + std::slice::from_ref(&target), + ) + .unwrap_err(); + + assert_eq!(error.code(), "TARGET_CONFLICT"); + assert_eq!( + fs::read(store.root().join("skilld-lock.yaml")).unwrap(), + before + ); + assert!(target.root.join("gamma/SKILL.md").is_file()); + assert!(!target.root.join("alpha").exists()); +} diff --git a/crates/skilld-command/tests/sync.rs b/crates/skilld-command/tests/sync.rs index fd5d036f..642fc557 100644 --- a/crates/skilld-command/tests/sync.rs +++ b/crates/skilld-command/tests/sync.rs @@ -619,3 +619,321 @@ fn a_hosted_preparation_failure_leaves_every_agent_unchanged() { .exists() ); } + +fn declare_only_alpha(root: &Path) { + let manifest = root.join("project/.skills/skilld.json"); + let mut value: serde_json::Value = + serde_json::from_slice(&fs::read(&manifest).unwrap()).unwrap(); + value["skills"] = json!({"alpha": {"source": "../sources/alpha"}}); + value["requires"] = json!({"pr": ["alpha"]}); + fs::write(manifest, value.to_string()).unwrap(); +} + +fn lock(lockfile: &Path) -> serde_json::Value { + serde_json::from_slice(&fs::read(lockfile).unwrap()).unwrap() +} + +/// Rewrite one lockfile entry as an older CLI or `skilld install` records it. +fn forget_installer(lockfile: &Path, name: &str) { + let mut value = lock(lockfile); + value["skills"][name] + .as_object_mut() + .unwrap() + .remove("installedBy") + .unwrap(); + fs::write(lockfile, value.to_string()).unwrap(); +} + +fn locked_skills(lockfile: &Path) -> Vec { + let lock: serde_json::Value = serde_json::from_slice(&fs::read(lockfile).unwrap()).unwrap(); + lock["skills"] + .as_object() + .unwrap() + .keys() + .cloned() + .collect() +} + +const AGENT_TARGETS: [&str; 3] = [".agents/skills", ".claude/skills", ".opencode/skills"]; + +#[test] +fn check_names_each_undeclared_skill_and_sync_removes_it() { + let (root, host) = fixture(); + assert_eq!(command(&host, &["skilld", "sync"]).0, 0); + declare_only_alpha(root.path()); + let project = root.path().join("project"); + let lockfile = project.join(".skills/skilld-lock.yaml"); + let before = fs::read(&lockfile).unwrap(); + + let checked = command(&host, &["skilld", "sync", "--check"]); + assert_eq!(checked.0, 1, "{}", checked.2); + assert!( + checked.1.contains("Skill beta is no longer declared."), + "{}", + checked.1 + ); + let json = command(&host, &["skilld", "sync", "--check", "--json"]); + assert_eq!(json.0, 1, "{}", json.2); + let report: serde_json::Value = serde_json::from_str(&json.1).unwrap(); + assert_eq!(report["data"]["current"], false); + assert_eq!( + report["data"]["undeclared"], + json!([{"_tag": "Removable", "name": "beta"}]) + ); + assert_eq!(fs::read(&lockfile).unwrap(), before); + assert!(project.join(".skills/beta/SKILL.md").is_file()); + for target in AGENT_TARGETS { + assert!(project.join(target).join("beta/SKILL.md").is_file()); + } + + let synced = command(&host, &["skilld", "sync"]); + assert_eq!(synced.0, 0, "{}", synced.2); + assert!( + synced + .1 + .contains("Removed Skill beta. It is no longer declared."), + "{}", + synced.1 + ); + assert!(!project.join(".skills/beta").exists()); + for target in AGENT_TARGETS { + assert!(fs::symlink_metadata(project.join(target).join("beta")).is_err()); + assert!(project.join(target).join("alpha/SKILL.md").is_file()); + } + assert_eq!(locked_skills(&lockfile), ["alpha"]); + assert_eq!(command(&host, &["skilld", "sync", "--check"]).0, 0); +} + +#[test] +fn sync_keeps_and_reports_a_skill_that_skilld_install_added_to_its_store() { + let (root, host) = fixture(); + assert_eq!(command(&host, &["skilld", "sync", "--global"]).0, 0); + let gamma = root.path().join("project/sources/gamma"); + fs::create_dir_all(&gamma).unwrap(); + fs::write( + gamma.join("SKILL.md"), + "---\nname: gamma\ndescription: Test.\n---\nOriginal.\n", + ) + .unwrap(); + let installed = command( + &host, + &[ + "skilld", + "install", + "./sources/gamma", + "--global", + "--agent", + "codex", + ], + ); + assert_eq!(installed.0, 0, "{}", installed.2); + let data_root = root.path().join("global"); + let lockfile = data_root.join("skills/skilld-lock.yaml"); + let locked = lock(&lockfile); + assert_eq!(locked["skills"]["alpha"]["installedBy"], "sync"); + assert!(locked["skills"]["gamma"].get("installedBy").is_none()); + let remove = format!( + "SKILLD_DATA_DIR={} skilld remove gamma --global", + data_root.display() + ); + + let checked = command(&host, &["skilld", "sync", "--global", "--check"]); + assert_eq!(checked.0, 0, "{}", checked.2); + assert!( + checked + .1 + .contains("Skill gamma is not declared. Sync did not install it, so sync keeps it."), + "{}", + checked.1 + ); + assert!( + checked.1.contains(&format!("To remove it, run: {remove}")), + "{}", + checked.1 + ); + let json = command(&host, &["skilld", "sync", "--global", "--check", "--json"]); + assert_eq!(json.0, 0, "{}", json.2); + let report: serde_json::Value = serde_json::from_str(&json.1).unwrap(); + assert_eq!(report["data"]["current"], true); + assert_eq!( + report["data"]["undeclared"], + json!([{"_tag": "Kept", "name": "gamma", "removeCommand": remove}]) + ); + + let synced = command(&host, &["skilld", "sync", "--global"]); + assert_eq!(synced.0, 0, "{}", synced.2); + assert!(synced.1.contains("Sync did not install it"), "{}", synced.1); + assert!(data_root.join("skills/gamma/SKILL.md").is_file()); + assert!(root.path().join(".agents/skills/gamma/SKILL.md").is_file()); + assert_eq!(locked_skills(&lockfile), ["alpha", "beta", "gamma"]); + + let removed = command(&host, &["skilld", "remove", "gamma", "--global"]); + assert_eq!(removed.0, 0, "{}", removed.2); + assert!(!data_root.join("skills/gamma").exists()); + assert!(fs::symlink_metadata(root.path().join(".agents/skills/gamma")).is_err()); +} + +#[test] +fn sync_keeps_and_reports_an_undeclared_entry_that_an_older_sync_wrote() { + let (root, host) = fixture(); + assert_eq!(command(&host, &["skilld", "sync"]).0, 0); + let project = root.path().join("project"); + let lockfile = project.join(".skills/skilld-lock.yaml"); + forget_installer(&lockfile, "beta"); + declare_only_alpha(root.path()); + + let checked = command(&host, &["skilld", "sync", "--check"]); + assert!( + checked + .1 + .contains("Skill beta is not declared. Sync did not install it, so sync keeps it."), + "{}", + checked.1 + ); + assert!( + checked.1.contains("To remove it, run: skilld remove beta"), + "{}", + checked.1 + ); + assert!(!checked.1.contains("no longer declared"), "{}", checked.1); + let synced = command(&host, &["skilld", "sync"]); + assert_eq!(synced.0, 0, "{}", synced.2); + assert!(project.join(".skills/beta/SKILL.md").is_file()); + for target in AGENT_TARGETS { + assert!(project.join(target).join("beta/SKILL.md").is_file()); + } + assert_eq!(locked_skills(&lockfile), ["alpha", "beta"]); + assert_eq!(command(&host, &["skilld", "sync", "--check"]).0, 0); + + let removed = command(&host, &["skilld", "remove", "beta"]); + assert_eq!(removed.0, 0, "{}", removed.2); + assert!(!project.join(".skills/beta").exists()); +} + +#[test] +fn sync_records_its_installer_on_declared_entries_that_an_older_sync_wrote() { + let (root, host) = fixture(); + assert_eq!(command(&host, &["skilld", "sync"]).0, 0); + let lockfile = root.path().join("project/.skills/skilld-lock.yaml"); + for name in ["alpha", "beta"] { + forget_installer(&lockfile, name); + } + let before = fs::read(&lockfile).unwrap(); + assert_eq!(command(&host, &["skilld", "sync", "--check"]).0, 0); + assert_eq!(fs::read(&lockfile).unwrap(), before); + + let synced = command(&host, &["skilld", "sync"]); + assert_eq!(synced.0, 0, "{}", synced.2); + let locked = lock(&lockfile); + for name in ["alpha", "beta"] { + assert_eq!(locked["skills"][name]["installedBy"], "sync", "{name}"); + } +} + +#[test] +fn sync_removes_the_store_entry_when_its_links_were_deleted_by_hand() { + let (root, host) = fixture(); + assert_eq!(command(&host, &["skilld", "sync", "--global"]).0, 0); + declare_only_alpha(root.path()); + for target in [ + ".agents/skills", + ".claude/skills", + ".config/opencode/skills", + ] { + fs::remove_file(root.path().join(target).join("beta")).unwrap(); + } + let checked = command(&host, &["skilld", "sync", "--global", "--check"]); + assert_eq!(checked.0, 1, "{}", checked.2); + assert!(checked.1.contains("Skill beta is no longer declared.")); + let synced = command(&host, &["skilld", "sync", "--global"]); + assert_eq!(synced.0, 0, "{}", synced.2); + assert!(!root.path().join("global/skills/beta").exists()); + assert_eq!( + locked_skills(&root.path().join("global/skills/skilld-lock.yaml")), + ["alpha"] + ); +} + +#[cfg(unix)] +#[test] +fn sync_keeps_agent_target_links_that_point_outside_its_store() { + let (root, host) = fixture(); + assert_eq!(command(&host, &["skilld", "sync", "--global"]).0, 0); + let other = root.path().join("other/skills/beta"); + fs::create_dir_all(&other).unwrap(); + fs::write( + other.join("SKILL.md"), + "---\nname: beta\ndescription: Other.\n---\nOther store.\n", + ) + .unwrap(); + let link = root.path().join(".claude/skills/beta"); + fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&other, &link).unwrap(); + declare_only_alpha(root.path()); + + let synced = command(&host, &["skilld", "sync", "--global"]); + assert_eq!(synced.0, 0, "{}", synced.2); + assert_eq!(fs::read_link(&link).unwrap(), other); + assert!(other.join("SKILL.md").is_file()); + for target in [".agents/skills", ".config/opencode/skills"] { + assert!(fs::symlink_metadata(root.path().join(target).join("beta")).is_err()); + } + assert!(!root.path().join("global/skills/beta").exists()); + assert_eq!( + locked_skills(&root.path().join("global/skills/skilld-lock.yaml")), + ["alpha"] + ); +} + +#[test] +fn sync_removes_matching_copies_and_keeps_edited_copies_of_an_undeclared_skill() { + let (root, host) = fixture(); + let manifest = root.path().join("project/.skills/skilld.json"); + let mut value: serde_json::Value = + serde_json::from_slice(&fs::read(&manifest).unwrap()).unwrap(); + value["mode"] = json!("copy"); + fs::write(&manifest, value.to_string()).unwrap(); + assert_eq!(command(&host, &["skilld", "sync"]).0, 0); + let project = root.path().join("project"); + let edited = project.join(".claude/skills/beta/SKILL.md"); + fs::write( + &edited, + "---\nname: beta\ndescription: Test.\n---\nUser edits.\n", + ) + .unwrap(); + declare_only_alpha(root.path()); + + let synced = command(&host, &["skilld", "sync"]); + assert_eq!(synced.0, 0, "{}", synced.2); + assert!(fs::read_to_string(&edited).unwrap().contains("User edits.")); + for target in [".agents/skills", ".opencode/skills"] { + assert!(!project.join(target).join("beta").exists()); + } + assert!(!project.join(".skills/beta").exists()); +} + +#[test] +fn sync_keeps_skills_that_another_declaration_in_the_store_names() { + let (root, host) = fixture(); + assert_eq!(command(&host, &["skilld", "sync"]).0, 0); + let one = declaration( + root.path(), + "one", + &["codex"], + "../sources/alpha", + "symlink", + ); + let checked = command(&host, &["skilld", "sync", "--manifest", &one, "--check"]); + assert!(!checked.1.contains("no longer declared"), "{}", checked.1); + assert_eq!(command(&host, &["skilld", "sync", "--manifest", &one]).0, 0); + let project = root.path().join("project"); + assert!(project.join(".skills/beta/SKILL.md").is_file()); + for target in AGENT_TARGETS { + assert!(project.join(target).join("beta/SKILL.md").is_file()); + } + assert_eq!( + command(&host, &["skilld", "sync", "--manifest", &one, "--check"]).0, + 0 + ); + assert_eq!(command(&host, &["skilld", "sync", "--check"]).0, 0); +} diff --git a/crates/skilld-core/src/lib.rs b/crates/skilld-core/src/lib.rs index d8808ee4..4671cd3c 100644 --- a/crates/skilld-core/src/lib.rs +++ b/crates/skilld-core/src/lib.rs @@ -16,8 +16,8 @@ pub use behavior::{ }; pub use lock::{ - LockDocument, LockedDeclarationSkill, LockedSkill, LockedSource, LockedTarget, SOURCE_STATUSES, - SourceStatus, + InstalledBy, LockDocument, LockedDeclarationSkill, LockedSkill, LockedSource, LockedTarget, + SOURCE_STATUSES, SourceStatus, }; pub use reference::{ListedOrigin, ListedSkill, MultiSkillRef, SkillListing, SkillRef}; pub use release::{ diff --git a/crates/skilld-core/src/lock.rs b/crates/skilld-core/src/lock.rs index ac9dbebe..75f90441 100644 --- a/crates/skilld-core/src/lock.rs +++ b/crates/skilld-core/src/lock.rs @@ -55,12 +55,23 @@ pub struct LockedTarget { pub mode: InstallMode, } +/// The command that wrote a lockfile entry, when that command removes the entry later. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum InstalledBy { + /// `skilld sync` installed the entry and removes it once no declaration names it. + Sync, +} + #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct LockedSkill { pub source: LockedSource, pub source_status: SourceStatus, pub targets: Vec, + /// Absent for `skilld install` and for entries from a CLI that did not record it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub installed_by: Option, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] diff --git a/skills/skilld/references/declared-skills.md b/skills/skilld/references/declared-skills.md index a1ad7a2c..f59df039 100644 --- a/skills/skilld/references/declared-skills.md +++ b/skills/skilld/references/declared-skills.md @@ -44,8 +44,21 @@ Sync prepares every source before changing Agent targets. One transaction writes installed Skills, targets, requirements, and declarations. Preparation failures and target conflicts leave existing targets unchanged. Repeated sync uses installed bytes when a remote source still matches its exact commit. -Sync preserves installed Skills omitted from the declaration. -Remove those Skills explicitly after releasing their requirements. + +Sync records `"installedBy": "sync"` in each lockfile entry it writes. +On its next run, sync also records it on declared entries that an older sync wrote. +If no declaration in the store names a Skill with that record, sync removes the Skill. +A required Skill counts as declared. +Sync removes an Agent target link only when it points into this store. +Sync removes an Agent target copy only when its files match the store. +Other Agent target paths stay unchanged. +The same transaction removes the store directory and the lockfile entry. +`skilld sync --check` exits `1` and names each Skill that sync will remove. + +Sync never removes a Skill without that record. +These Skills come from `skilld install` or from a CLI that did not record the installer. +Sync and `skilld sync --check` name each one with the `skilld remove` command that removes it. +These Skills alone do not make `skilld sync --check` exit `1`. Declarations in one store can share a Skill with the same source. Local sources must resolve to the same directory. @@ -68,6 +81,7 @@ Sync preserves the original source directory. Use a CLI containing `sync` to read lockfiles with recorded requirements. Older CLIs reject those fields. +A CLI that does not record `installedBy` rejects a lockfile that contains it. Keep legacy v2 stores separate; sync does not migrate their lockfiles. ## Keep the skilld-maintained Skill current