Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

Remove managed skills on uninstall

Thiago Silva0008318c0b29
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 0c51bbe8..6fa6aec0 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -311,12 +311,13 @@ pub struct AuthLogoutArgs {
#[derive(Debug, Args)]
pub struct AuthStatusArgs {}
-/// Which concern `uninstall` should touch. Omitted = all three.
+/// Which concern `uninstall` should touch. Omitted = all four.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum UninstallOnly {
Hooks,
Mcp,
Instructions,
+ Skills,
}
/// Arguments for `uninstall`.
@@ -331,7 +332,7 @@ pub struct UninstallArgs {
/// meaningful with `--apply`.
#[arg(long)]
pub purge_data: bool,
- /// Limit to one concern. Omitted = hooks + mcp + instructions.
+ /// Limit to one concern. Omitted = hooks + mcp + instructions + skills.
#[arg(long, value_enum)]
pub only: Option<UninstallOnly>,
/// Optional MCP server entry-name filter. Uninstall never matches by name
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index 6dbf78d0..0e36312f 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -13,6 +13,7 @@ use crate::commands::apply_shared::mutate_json;
use crate::commands::apply_shared::mutate_toml;
use crate::commands::{data_purge, install_hooks, install_mcp, openclaw_plugin};
use crate::config::Config;
+use ai_memory_core::routing_skills::{MANAGED_MARKER, MANAGED_SKILLS};
use ai_memory_core::{MARKER_END, MARKER_START};
use anyhow::{Context, Result};
use std::io::IsTerminal;
@@ -41,6 +42,7 @@ enum DeleteKind {
OpenClawPackageJson,
OpenClawManifest,
OpenClawEntrypoint,
+ ManagedSkill,
}
impl DeleteKind {
@@ -51,6 +53,7 @@ impl DeleteKind {
Self::OpenClawPackageJson => "OpenClaw package manifest",
Self::OpenClawManifest => "OpenClaw plugin manifest",
Self::OpenClawEntrypoint => "OpenClaw plugin entrypoint",
+ Self::ManagedSkill => "managed Agent Skill",
}
}
}
@@ -232,9 +235,42 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {
}
}
+
+ // ---- Managed Agent Skills (project + global roots) ----
+ if want(crate::cli::UninstallOnly::Skills) {
+ let cwd = std::env::current_dir().context("getting CWD for skill removal")?;
+ let home = dirs::home_dir();
+ for root in skill_roots(&cwd, home.as_deref()) {
+ for skill in MANAGED_SKILLS {
+ push_generated_delete(
+ &mut plan,
+ root.join(skill.relative_path),
+ DeleteKind::ManagedSkill,
+ );
+ }
+ }
+ }
+
Ok(plan)
}
+fn skill_roots(cwd: &Path, home: Option<&Path>) -> Vec<PathBuf> {
+ let mut roots = Vec::with_capacity(4);
+ push_unique_skill_root(&mut roots, cwd.join(".claude").join("skills"));
+ push_unique_skill_root(&mut roots, cwd.join(".agents").join("skills"));
+ if let Some(home) = home {
+ push_unique_skill_root(&mut roots, home.join(".claude").join("skills"));
+ push_unique_skill_root(&mut roots, home.join(".agents").join("skills"));
+ }
+ roots
+}
+
+fn push_unique_skill_root(roots: &mut Vec<PathBuf>, root: PathBuf) {
+ if !roots.iter().any(|existing| existing == &root) {
+ roots.push(root);
+ }
+}
+
/// Print the plan, one line per file, mirroring `reset`'s dry-run style.
fn print_plan(plan: &[PlannedChange]) {
if plan.is_empty() {
@@ -276,6 +312,9 @@ fn apply_change(change: &PlannedChange, name: Option<&str>, url: &str) -> anyhow
}
std::fs::remove_file(path).with_context(|| format!("deleting {}", path.display()))?;
println!("✓ deleted {}", path.display());
+ if *kind == DeleteKind::ManagedSkill {
+ remove_empty_skill_dirs(path)?;
+ }
}
PlannedChange::Rewrite { path, ops, .. } => {
let outcome = apply_atomic(path, |existing| {
@@ -299,6 +338,36 @@ fn apply_change(change: &PlannedChange, name: Option<&str>, url: &str) -> anyhow
Ok(())
}
+fn remove_empty_skill_dirs(skill_file: &Path) -> Result<()> {
+ let Some(skill_dir) = skill_file.parent() else {
+ return Ok(());
+ };
+ let root = skill_dir.parent().map(Path::to_path_buf);
+
+ remove_dir_if_empty(skill_dir)?;
+ if let Some(root) = root {
+ remove_dir_if_empty(&root)?;
+ }
+
+ Ok(())
+}
+
+fn remove_dir_if_empty(path: &Path) -> Result<()> {
+ if !path.is_dir() {
+ return Ok(());
+ }
+
+ let mut entries =
+ std::fs::read_dir(path).with_context(|| format!("reading {}", path.display()))?;
+ if entries.next().is_some() {
+ return Ok(());
+ }
+
+ std::fs::remove_dir(path).with_context(|| format!("removing {}", path.display()))?;
+ println!("✓ removed empty directory {}", path.display());
+ Ok(())
+}
+
/// Run the `uninstall` subcommand.
///
/// # Errors
@@ -577,6 +646,7 @@ fn generated_file_is_ours(path: &Path, kind: DeleteKind) -> bool {
.and_then(|additional| additional.as_bool())
== Some(false)
}),
+ DeleteKind::ManagedSkill => content.contains(MANAGED_MARKER),
}
}
diff --git a/crates/ai-memory-cli/tests/uninstall.rs b/crates/ai-memory-cli/tests/uninstall.rs
index a8c7024e..eaaf9dc6 100644
--- a/crates/ai-memory-cli/tests/uninstall.rs
+++ b/crates/ai-memory-cli/tests/uninstall.rs
@@ -1,9 +1,12 @@
//! End-to-end: install hooks into a temp HOME, then uninstall, and
//! assert the file round-trips (our entries gone, third-party intact).
+use std::path::Path;
use std::process::Command;
use std::sync::{Mutex, MutexGuard};
+use ai_memory_core::routing_skills::{MANAGED_MARKER, MANAGED_SKILLS};
+
static CLI_TEST_LOCK: Mutex<()> = Mutex::new(());
fn cli_test_lock() -> MutexGuard<'static, ()> {
@@ -14,6 +17,30 @@ fn bin() -> &'static str {
env!("CARGO_BIN_EXE_ai-memory")
}
+fn run_uninstall(project: &Path, home: &Path, args: &[&str]) -> std::process::Output {
+ Command::new(bin())
+ .args(args)
+ .current_dir(project)
+ .env("HOME", home)
+ .env("XDG_CONFIG_HOME", home.join(".config"))
+ .env("XDG_DATA_HOME", home.join(".local/share"))
+ .env("AI_MEMORY_DATA_DIR", home.join(".ai-memory-data"))
+ .output()
+ .unwrap()
+}
+
+fn write_file(path: &Path, content: &str) {
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(path, content).unwrap();
+}
+
+fn managed_skill_content() -> String {
+ format!(
+ "---\nname: test\n---\n{}\nmanaged test skill\n",
+ MANAGED_MARKER
+ )
+}
+
#[test]
fn install_then_uninstall_round_trip_claude_hooks() {
let _guard = cli_test_lock();
@@ -401,6 +428,151 @@ fn uninstall_dry_run_changes_nothing() {
assert_eq!(after, original, "dry-run must not modify the file");
}
+#[test]
+fn default_uninstall_removes_managed_skills_across_roots_and_preserves_user_content() {
+ let _guard = cli_test_lock();
+ let project = tempfile::tempdir().unwrap();
+ let home = tempfile::tempdir().unwrap();
+ let managed_content = managed_skill_content();
+
+ let project_claude = project.path().join(".claude/skills");
+ let project_agents = project.path().join(".agents/skills");
+ let global_claude = home.path().join(".claude/skills");
+ let global_agents = home.path().join(".agents/skills");
+
+ let managed_paths = [
+ project_claude.join(MANAGED_SKILLS[0].relative_path),
+ project_agents.join(MANAGED_SKILLS[2].relative_path),
+ global_claude.join(MANAGED_SKILLS[3].relative_path),
+ global_agents.join(MANAGED_SKILLS[4].relative_path),
+ ];
+ for path in &managed_paths {
+ write_file(path, &managed_content);
+ }
+
+ let unmanaged_same_name = project_claude.join(MANAGED_SKILLS[1].relative_path);
+ let unmanaged_content = "---\nname: ai-memory-handoff\n---\nuser-owned same-name skill\n";
+ write_file(&unmanaged_same_name, unmanaged_content);
+
+ let unrelated_sibling = project_claude.join("user-skill/SKILL.md");
+ write_file(&unrelated_sibling, "---\nname: user-skill\n---\nkeep me\n");
+
+ let extra_file_in_managed_dir = managed_paths[1].parent().unwrap().join("notes.txt");
+ write_file(&extra_file_in_managed_dir, "keep this sibling file\n");
+
+ let output = run_uninstall(project.path(), home.path(), &["uninstall", "--apply", "--yes"]);
+ assert!(
+ output.status.success(),
+ "uninstall failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ for path in &managed_paths {
+ assert!(!path.exists(), "managed skill file should be removed: {path:?}");
+ }
+ assert_eq!(
+ std::fs::read_to_string(&unmanaged_same_name).unwrap(),
+ unmanaged_content,
+ "unmanaged same-name skill must be preserved"
+ );
+ assert!(unrelated_sibling.exists(), "unrelated sibling skill survives");
+ assert!(
+ extra_file_in_managed_dir.exists(),
+ "non-empty managed skill directory must not be removed"
+ );
+ assert!(
+ !managed_paths[0].parent().unwrap().exists(),
+ "empty managed skill directory should be removed"
+ );
+ assert!(
+ !global_claude.exists() && !global_agents.exists(),
+ "empty global skill roots should be removed"
+ );
+}
+
+#[test]
+fn install_skills_then_uninstall_only_skills_round_trips() {
+ let _guard = cli_test_lock();
+ let project = tempfile::tempdir().unwrap();
+ let home = tempfile::tempdir().unwrap();
+
+ let install = Command::new(bin())
+ .args(["install-skills", "--scope", "project", "--agent", "both"])
+ .current_dir(project.path())
+ .env("HOME", home.path())
+ .env("XDG_CONFIG_HOME", home.path().join(".config"))
+ .env("XDG_DATA_HOME", home.path().join(".local/share"))
+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data"))
+ .output()
+ .unwrap();
+ assert!(
+ install.status.success(),
+ "install-skills failed: {}",
+ String::from_utf8_lossy(&install.stderr)
+ );
+
+ for root in [
+ project.path().join(".claude/skills"),
+ project.path().join(".agents/skills"),
+ ] {
+ for skill in MANAGED_SKILLS {
+ assert!(root.join(skill.relative_path).exists());
+ }
+ }
+
+ let uninstall = run_uninstall(
+ project.path(),
+ home.path(),
+ &["uninstall", "--only", "skills", "--apply", "--yes"],
+ );
+ assert!(
+ uninstall.status.success(),
+ "uninstall failed: {}",
+ String::from_utf8_lossy(&uninstall.stderr)
+ );
+
+ assert!(
+ !project.path().join(".claude/skills").exists(),
+ "empty Claude skills root should be removed"
+ );
+ assert!(
+ !project.path().join(".agents/skills").exists(),
+ "empty .agents skills root should be removed"
+ );
+}
+
+#[test]
+fn uninstall_skills_dry_run_reports_plan_without_mutating() {
+ let _guard = cli_test_lock();
+ let project = tempfile::tempdir().unwrap();
+ let home = tempfile::tempdir().unwrap();
+ let skill_path = project
+ .path()
+ .join(".claude/skills")
+ .join(MANAGED_SKILLS[0].relative_path);
+ let original = managed_skill_content();
+ write_file(&skill_path, &original);
+
+ let output = run_uninstall(project.path(), home.path(), &["uninstall", "--only", "skills"]);
+ assert!(
+ output.status.success(),
+ "dry-run failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = String::from_utf8(output.stdout).unwrap();
+ assert!(stdout.contains("would delete"), "stdout was: {stdout}");
+ assert!(stdout.contains("managed Agent Skill"), "stdout was: {stdout}");
+ assert!(
+ stdout.contains(&skill_path.display().to_string()),
+ "stdout was: {stdout}"
+ );
+ assert_eq!(
+ std::fs::read_to_string(&skill_path).unwrap(),
+ original,
+ "dry-run must not remove or rewrite managed skill"
+ );
+}
+
#[test]
fn uninstall_purge_data_apply_wipes() {
let _guard = cli_test_lock();