Skip to content

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

Rust

Add install-skills CLI command

Thiago Silva47339d024ca3
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 88759ed8..d421add7 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -112,6 +112,8 @@ pub enum Command {
/// `<!-- ai-memory:end -->` markers so re-running replaces the
/// block in place without duplicating.
InstallInstructions(InstallInstructionsArgs),
+ /// Install core-managed ai-memory Agent Skills into agent skill directories.
+ InstallSkills(InstallSkillsArgs),
/// Retro-fit existing sessions + observations to per-cwd projects
/// based on the cwd captured at session-start. Pages are marked
/// `is_latest=false` (they were a multi-project mash-up) so the
@@ -441,6 +443,50 @@ pub struct InstallInstructionsArgs {
pub print: bool,
}
+/// Skill install scope for `install-skills`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
+pub enum InstallSkillsScope {
+ /// Install into this project's agent skill directories.
+ Project,
+ /// Install into the user's global agent skill directories.
+ Global,
+}
+
+/// Agent skill directory family for `install-skills`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
+pub enum InstallSkillsAgent {
+ /// Claude Code's `.claude/skills` directory.
+ ClaudeCode,
+ /// Cross-agent `.agents/skills` directory.
+ Agents,
+ /// Install into both Claude Code and `.agents` skill directories.
+ Both,
+}
+
+/// Arguments for `install-skills`.
+#[derive(Debug, Args)]
+pub struct InstallSkillsArgs {
+ /// Install project-local skills or global user skills.
+ #[arg(long, value_enum, default_value_t = InstallSkillsScope::Project)]
+ pub scope: InstallSkillsScope,
+ /// Which agent skill directory family to install into.
+ #[arg(long, value_enum, default_value_t = InstallSkillsAgent::ClaudeCode)]
+ pub agent: InstallSkillsAgent,
+ /// Override the skill root directory. When set, `--scope` and
+ /// `--agent` are ignored and the managed skill directories are
+ /// written below this root.
+ #[arg(long)]
+ pub target_dir: Option<PathBuf>,
+ /// Print target paths and SKILL.md contents without writing files.
+ #[arg(long)]
+ pub print: bool,
+ /// Overwrite same-named existing skills that do not contain the
+ /// ai-memory managed marker. Without this flag, unmanaged skills
+ /// are preserved and the command exits with an actionable error.
+ #[arg(long)]
+ pub force: bool,
+}
+
/// Arguments for `bootstrap`.
#[derive(Debug, Args)]
pub struct BootstrapArgs {
diff --git a/crates/ai-memory-cli/src/commands/install_skills.rs b/crates/ai-memory-cli/src/commands/install_skills.rs
new file mode 100644
index 00000000..f5779e17
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/install_skills.rs
@@ -0,0 +1,322 @@
+//! `ai-memory install-skills` — install core-managed ai-memory Agent Skills.
+
+use std::fs;
+use std::path::{Path, PathBuf};
+
+use ai_memory_core::routing_skills::{MANAGED_MARKER, MANAGED_SKILLS, ManagedSkill};
+use anyhow::{Context, Result, bail};
+
+use crate::cli::{InstallSkillsAgent, InstallSkillsArgs, InstallSkillsScope};
+use crate::commands::apply_shared::{ApplyOutcome, apply_atomic};
+use crate::config::Config;
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+struct TargetRoot {
+ path: PathBuf,
+}
+
+impl TargetRoot {
+ fn new(path: PathBuf) -> Self {
+ Self { path }
+ }
+}
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+struct InstallReport {
+ path: PathBuf,
+ outcome: ApplyOutcome,
+}
+
+/// Run the `install-skills` subcommand.
+///
+/// # Errors
+/// Returns an error when target roots cannot be resolved, an unmanaged
+/// same-name skill would be overwritten without `--force`, or a skill
+/// file cannot be written.
+pub fn run(_config: &Config, args: InstallSkillsArgs) -> Result<()> {
+ let cwd = std::env::current_dir().context("getting CWD for install-skills target")?;
+ let home = dirs::home_dir();
+ let roots = resolve_target_roots(&args, &cwd, home.as_deref())?;
+
+ if args.print {
+ print_install_plan(&roots);
+ return Ok(());
+ }
+
+ for report in install_managed_skills(&roots, args.force)? {
+ println!(
+ "✓ {} {} ({})",
+ report.outcome.verb(),
+ report.path.display(),
+ outcome_detail(report.outcome),
+ );
+ }
+
+ Ok(())
+}
+
+fn resolve_target_roots(
+ args: &InstallSkillsArgs,
+ cwd: &Path,
+ home: Option<&Path>,
+) -> Result<Vec<TargetRoot>> {
+ if let Some(target_dir) = &args.target_dir {
+ return Ok(vec![TargetRoot::new(target_dir.clone())]);
+ }
+
+ let roots = match args.agent {
+ InstallSkillsAgent::ClaudeCode => vec![agent_root(args.scope, SkillRootKind::Claude, cwd, home)?],
+ InstallSkillsAgent::Agents => vec![agent_root(args.scope, SkillRootKind::Agents, cwd, home)?],
+ InstallSkillsAgent::Both => vec![
+ agent_root(args.scope, SkillRootKind::Claude, cwd, home)?,
+ agent_root(args.scope, SkillRootKind::Agents, cwd, home)?,
+ ],
+ };
+
+ Ok(roots.into_iter().map(TargetRoot::new).collect())
+}
+
+#[derive(Debug, Clone, Copy)]
+enum SkillRootKind {
+ Claude,
+ Agents,
+}
+
+fn agent_root(
+ scope: InstallSkillsScope,
+ kind: SkillRootKind,
+ cwd: &Path,
+ home: Option<&Path>,
+) -> Result<PathBuf> {
+ let base = match scope {
+ InstallSkillsScope::Project => cwd,
+ InstallSkillsScope::Global => home.context("could not locate $HOME for global skill install")?,
+ };
+ let agent_dir = match kind {
+ SkillRootKind::Claude => ".claude",
+ SkillRootKind::Agents => ".agents",
+ };
+ Ok(base.join(agent_dir).join("skills"))
+}
+
+fn install_managed_skills(roots: &[TargetRoot], force: bool) -> Result<Vec<InstallReport>> {
+ let plans = skill_file_plans(roots);
+ validate_overwrite_safety(&plans, force)?;
+
+ let mut reports = Vec::with_capacity(plans.len());
+ for (path, skill) in plans {
+ let outcome = apply_atomic(&path, |_| Ok(skill.content.to_string()))?;
+ reports.push(InstallReport { path, outcome });
+ }
+ Ok(reports)
+}
+
+fn skill_file_plans(roots: &[TargetRoot]) -> Vec<(PathBuf, &'static ManagedSkill)> {
+ let mut plans = Vec::with_capacity(roots.len() * MANAGED_SKILLS.len());
+ for root in roots {
+ for skill in MANAGED_SKILLS {
+ plans.push((root.path.join(skill.relative_path), skill));
+ }
+ }
+ plans
+}
+
+fn validate_overwrite_safety(
+ plans: &[(PathBuf, &'static ManagedSkill)],
+ force: bool,
+) -> Result<()> {
+ if force {
+ return Ok(());
+ }
+
+ for (path, skill) in plans {
+ if !path.exists() {
+ continue;
+ }
+ let existing =
+ fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
+ if !existing.contains(MANAGED_MARKER) {
+ bail!(
+ "refusing to overwrite unmanaged skill `{}` at {}. \
+ Move or rename the existing skill, or rerun with --force to back it up and replace it.",
+ skill.name,
+ path.display()
+ );
+ }
+ }
+
+ Ok(())
+}
+
+fn print_install_plan(roots: &[TargetRoot]) {
+ for root in roots {
+ println!("# Skill root: {}\n", root.path.display());
+ for skill in MANAGED_SKILLS {
+ let path = root.path.join(skill.relative_path);
+ println!("# Would write: {}\n", path.display());
+ print!("{}", skill.content);
+ if !skill.content.ends_with('\n') {
+ println!();
+ }
+ println!();
+ }
+ }
+}
+
+fn outcome_detail(outcome: ApplyOutcome) -> &'static str {
+ match outcome {
+ ApplyOutcome::Created => "new file",
+ ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::NoOp => "already up to date",
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::fs;
+ use std::path::{Path, PathBuf};
+
+ use ai_memory_core::routing_skills::{MANAGED_MARKER, MANAGED_SKILLS};
+
+ use super::*;
+ use crate::cli::{InstallSkillsAgent, InstallSkillsArgs, InstallSkillsScope};
+ use crate::commands::apply_shared::ApplyOutcome;
+
+ fn args(scope: InstallSkillsScope, agent: InstallSkillsAgent) -> InstallSkillsArgs {
+ InstallSkillsArgs {
+ scope,
+ agent,
+ target_dir: None,
+ print: false,
+ force: false,
+ }
+ }
+
+ fn root_names(roots: &[TargetRoot]) -> Vec<String> {
+ roots
+ .iter()
+ .map(|root| root.path.to_string_lossy().replace('\\', "/"))
+ .collect()
+ }
+
+ #[test]
+ fn resolves_project_and_global_skill_roots_for_each_agent_selection() {
+ let cwd = Path::new("/repo");
+ let home = Path::new("/home/alice");
+
+ let project_claude = resolve_target_roots(
+ &args(InstallSkillsScope::Project, InstallSkillsAgent::ClaudeCode),
+ cwd,
+ Some(home),
+ )
+ .unwrap();
+ assert_eq!(root_names(&project_claude), ["/repo/.claude/skills"]);
+
+ let project_agents = resolve_target_roots(
+ &args(InstallSkillsScope::Project, InstallSkillsAgent::Agents),
+ cwd,
+ Some(home),
+ )
+ .unwrap();
+ assert_eq!(root_names(&project_agents), ["/repo/.agents/skills"]);
+
+ let project_both = resolve_target_roots(
+ &args(InstallSkillsScope::Project, InstallSkillsAgent::Both),
+ cwd,
+ Some(home),
+ )
+ .unwrap();
+ assert_eq!(
+ root_names(&project_both),
+ ["/repo/.claude/skills", "/repo/.agents/skills"]
+ );
+
+ let global_both = resolve_target_roots(
+ &args(InstallSkillsScope::Global, InstallSkillsAgent::Both),
+ cwd,
+ Some(home),
+ )
+ .unwrap();
+ assert_eq!(
+ root_names(&global_both),
+ ["/home/alice/.claude/skills", "/home/alice/.agents/skills"]
+ );
+ }
+
+ #[test]
+ fn explicit_target_dir_overrides_scope_and_agent_roots() {
+ let cwd = Path::new("/repo");
+ let home = Path::new("/home/alice");
+ let mut install_args = args(InstallSkillsScope::Global, InstallSkillsAgent::Both);
+ install_args.target_dir = Some(PathBuf::from("/custom/skills"));
+
+ let roots = resolve_target_roots(&install_args, cwd, Some(home)).unwrap();
+ assert_eq!(root_names(&roots), ["/custom/skills"]);
+ }
+
+ #[test]
+ fn install_is_idempotent_after_creating_managed_skills() {
+ let tmp = tempfile::tempdir().unwrap();
+ let roots = vec![TargetRoot::new(tmp.path().join(".claude/skills"))];
+
+ let first = install_managed_skills(&roots, false).unwrap();
+ assert_eq!(first.len(), MANAGED_SKILLS.len());
+ assert!(
+ first
+ .iter()
+ .all(|report| report.outcome == ApplyOutcome::Created)
+ );
+
+ let second = install_managed_skills(&roots, false).unwrap();
+ assert_eq!(second.len(), MANAGED_SKILLS.len());
+ assert!(
+ second
+ .iter()
+ .all(|report| report.outcome == ApplyOutcome::NoOp)
+ );
+ }
+
+ #[test]
+ fn refuses_to_overwrite_unmanaged_same_name_skill() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join(".claude/skills");
+ let unmanaged = root.join("ai-memory-retrieval/SKILL.md");
+ fs::create_dir_all(unmanaged.parent().unwrap()).unwrap();
+ fs::write(
+ &unmanaged,
+ "---\nname: ai-memory-retrieval\n---\nuser skill\n",
+ )
+ .unwrap();
+
+ let err = install_managed_skills(&[TargetRoot::new(root.clone())], false).unwrap_err();
+ let message = err.to_string();
+ assert!(message.contains("refusing to overwrite unmanaged skill"));
+ assert!(message.contains("--force"));
+ assert_eq!(
+ fs::read_to_string(&unmanaged).unwrap(),
+ "---\nname: ai-memory-retrieval\n---\nuser skill\n"
+ );
+ assert!(!root.join("ai-memory-handoff/SKILL.md").exists());
+ }
+
+ #[test]
+ fn force_overwrites_unmanaged_same_name_skill() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join(".claude/skills");
+ let unmanaged = root.join("ai-memory-retrieval/SKILL.md");
+ fs::create_dir_all(unmanaged.parent().unwrap()).unwrap();
+ fs::write(
+ &unmanaged,
+ "---\nname: ai-memory-retrieval\n---\nuser skill\n",
+ )
+ .unwrap();
+
+ let reports = install_managed_skills(&[TargetRoot::new(root)], true).unwrap();
+ let overwritten = reports
+ .iter()
+ .find(|report| report.path == unmanaged)
+ .expect("retrieval report");
+ assert_eq!(overwritten.outcome, ApplyOutcome::Updated);
+ assert!(fs::read_to_string(unmanaged).unwrap().contains(MANAGED_MARKER));
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index f1288602..3ede65ae 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -25,6 +25,7 @@ pub mod hook_spool;
pub mod init;
pub mod install_hooks;
pub mod install_instructions;
+pub mod install_skills;
pub mod install_mcp;
pub mod lint;
pub mod llm_test;
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index c02ff7f7..34f519a6 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -87,6 +87,7 @@ async fn main() -> Result<()> {
Command::SetupAgent(args) => commands::setup_agent::run(&config, args),
Command::Bootstrap(args) => commands::bootstrap::run(&config, args).await,
Command::InstallInstructions(args) => commands::install_instructions::run(&config, args),
+ Command::InstallSkills(args) => commands::install_skills::run(&config, args),
Command::Reorg(args) => commands::reorg::run(&config, args).await,
Command::PurgeProject(args) => commands::purge_project::run(&config, args).await,
Command::RenameProject(args) => commands::rename_project::run(&config, args).await,
diff --git a/crates/ai-memory-cli/tests/install_skills.rs b/crates/ai-memory-cli/tests/install_skills.rs
new file mode 100644
index 00000000..95318889
--- /dev/null
+++ b/crates/ai-memory-cli/tests/install_skills.rs
@@ -0,0 +1,33 @@
+use std::process::Command;
+
+fn bin() -> &'static str {
+ env!("CARGO_BIN_EXE_ai-memory")
+}
+
+#[test]
+fn install_skills_print_outputs_plan_without_mutating_target_dir() {
+ let home = tempfile::tempdir().unwrap();
+ let target = home.path().join("custom-skills");
+
+ let output = Command::new(bin())
+ .args([
+ "install-skills",
+ "--target-dir",
+ target.to_str().unwrap(),
+ "--print",
+ ])
+ .env("HOME", home.path())
+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data"))
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "install-skills --print failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = String::from_utf8(output.stdout).unwrap();
+ assert!(stdout.contains(&target.join("ai-memory-retrieval/SKILL.md").display().to_string()));
+ assert!(stdout.contains("<!-- ai-memory-managed: routing-skill -->"));
+ assert!(!target.exists(), "--print must not create the target directory");
+}