Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(routing): harden managed skill installation
AkitaOnRailsb2845c6f70cd
diff --cc CHANGELOG.mdindex be9b9137,a89fa8eb..bc6009ab--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -7,16 -7,15 +7,29 @@@ and this project adheres to [Semantic V## [Unreleased]+### Changed+- `install-instructions` now refreshes a slim markered CLAUDE.md/AGENTS.md+ snippet and installs or updates managed ai-memory Agent Skills by default,+ with `--no-skills` for snippet-only refreshes and `--skills-*` flags for+ scope, agent family, target root, and forced unmanaged replacement. Added+ `install-skills` for refreshing those prompt-packaging skills directly, and+ `memory_install_self_routing` now returns the slim block, managed skill+ payloads, target hints, and overwrite guidance for agents that install+ routing through MCP.++ ### Added+ - The native `session-end` hook now emits a one-line stderr note when the spool+ drain leaves events queued for a later boundary: it reports how many events+ were flushed, how many remain queued, whether any events were dropped as+ undeliverable, and names the knobs to bound the backlog+ (`AI_MEMORY_HOOK_END_BUDGET_MINUTES`, `AI_MEMORY_HOOK_INCREMENTAL_THRESHOLD`),+ turning an otherwise silent, scary cancelled-hook symptom into an actionable,+ self-documenting message. A fully-drained session stays silent. (#130)++- `ai-memory uninstall --only skills` now removes ai-memory-managed Agent Skill++ files from the default project/global `.claude/skills` and `.agents/skills`++ roots after marker validation; custom `--target-dir` skill roots remain a++ manual cleanup path.+## [1.3.0] - 2026-06-24### Addeddiff --cc Cargo.lockindex a954ac34,a954ac34..13eb0d7c--- a/Cargo.lock+++ b/Cargo.lock@@@ -101,6 -101,6 +101,7 @@@ dependencies ="schemars","serde","serde_json",++ "serde_yaml","thiserror 2.0.18","tracing","uuid",diff --cc README.mdindex e66eb31a,9ce52c88..e5f56ab4--- a/README.md+++ b/README.md@@@ -290,11 -290,10 +290,12 @@@ loopback server. With the local Docker`AI_MEMORY_SERVER_URL` override is needed.To remove ai-memory later, run `ai-memory uninstall --apply` from the-same host environment. It removes ai-memory-owned config entries and-generated plugin files only after matching their ai-memory signatures;-use `--mcp-url` if you installed MCP with a custom endpoint, and-`--mcp-name` only when you need to narrow removal to one matching entry.+same host environment. It removes ai-memory-owned config entries, instruction- blocks, managed skill files, and generated plugin files only after matching- their ai-memory signatures; use `--mcp-url` if you installed MCP with a custom- endpoint, and `--mcp-name` only when you need to narrow removal to one matching- entry.++blocks, default-root managed skill files, and generated plugin files only after++matching their ai-memory signatures; custom skill roots installed with++`--target-dir` are cleaned up manually. Use `--mcp-url` if you installed MCP++with a custom endpoint, and `--mcp-name` only when you need to narrow removal to++one matching entry.### Install Notesdiff --cc crates/ai-memory-cli/src/cli.rsindex 6fa6aec0,88759ed8..01eef68a--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@@ -106,8 -106,8 +106,8 @@@ pub enum Command/// project that's been around for a while. Requires/// AI_MEMORY_LLM_PROVIDER configured on the server.Bootstrap(BootstrapArgs),-- /// Install the ai-memory usage snippet into the project's-- /// CLAUDE.md / AGENTS.md (or any markdown file you specify).++ /// Install the ai-memory usage snippet and managed Agent Skills into the++ /// project (or any markdown file / skill root you specify)./// Idempotent — bracketed by `<!-- ai-memory:start -->` //// `<!-- ai-memory:end -->` markers so re-running replaces the/// block in place without duplicating.@@@ -135,8 -133,8 +135,8 @@@/// copy+purge (only durable pages migrate, source purged). Either way the/// operation is irreversible — requires `--confirm`.MoveProject(MoveProjectArgs),-- /// Remove ai-memory's wiring (hooks, MCP, instructions) from all-- /// detected agents. Dry-run unless `--apply`.++ /// Remove ai-memory's wiring (hooks, MCP, instructions, and default-root++ /// managed skills) from all detected agents. Dry-run unless `--apply`.Uninstall(UninstallArgs),/// Manage optional upstream LLM provider authentication.Auth(AuthArgs),@@@ -435,72 -432,13 +435,73 @@@ pub struct InstallInstructionsArgs/// to override the auto-detection.#[arg(long)]pub target: Option<PathBuf>,-- /// Print the snippet to stdout instead of mutating the file.++ /// Print the snippet to stdout instead of mutating files./// The default IS mutation here (the print form is also/// available without this command — copy the block from the/// README). Pass `--print` to preview what would land in-- /// the file.++ /// the file. This does not print skill payloads; use++ /// `install-skills --print` to preview managed Agent Skills.#[arg(long)]pub print: bool,+ /// Skip installing/updating the managed ai-memory Agent Skills.+ #[arg(long)]+ pub no_skills: bool,+ /// Scope for managed ai-memory skill installation.+ #[arg(long = "skills-scope", value_enum)]+ pub skills_scope: Option<InstallSkillsScope>,+ /// Agent skill directory family for managed ai-memory skill installation.+ #[arg(long = "skills-agent", value_enum)]+ pub skills_agent: Option<InstallSkillsAgent>,+ /// Override the managed skill root directory.+ #[arg(long = "skills-target-dir")]+ pub skills_target_dir: Option<PathBuf>,+ /// Overwrite same-named unmanaged skills while installing from `install-instructions`.+ #[arg(long = "skills-force")]+ pub skills_force: 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`.diff --cc crates/ai-memory-cli/src/commands/install_instructions.rsindex 4839d9d2,12b13551..24bf1aa9--- a/crates/ai-memory-cli/src/commands/install_instructions.rs+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs@@@ -34,45 -29,33 +34,50 @@@ use ai_memory_core::{MARKER_END, MARKER/// # Errors/// Returns an error if the target path can't be written or if the/// existing file isn't valid UTF-8.- pub fn run(config: &Config, args: InstallInstructionsArgs) -> Result<()> {+ pub fn run(_config: &Config, args: InstallInstructionsArgs) -> Result<()> {let block = full_block();let targets = resolve_targets(args.target.as_ref())?;+ let skill_args = if args.no_skills {+ None+ } else {+ Some(skill_args_from_instruction_args(&args, &targets))+ };++ let prepared_skills = if !args.print {++ skill_args++ .as_ref()++ .map(install_skills::prepare_install)++ .transpose()?++ } else {++ None++ };if args.print {for t in &targets {println!("# Would write into: {}\n", t.display());println!("{block}");}- return Ok(());+ } else {- if let Some(skill_args) = &skill_args {- install_skills::preflight_overwrite_safety(skill_args)?;- }+ for target in &targets {+ let outcome = apply_atomic(target, |existing| {+ Ok(merge_instructions_block(existing, &block))+ })?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ target.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ }}- if let Some(skill_args) = skill_args {- install_skills::run(config, skill_args)?;- for target in &targets {- let outcome = apply_atomic(target, |existing| {- Ok(merge_instructions_block(existing, &block))- })?;- println!(- "✓ {} {} ({})",- outcome.verb(),- target.display(),- match outcome {- ApplyOutcome::Created => "new file",- ApplyOutcome::Updated => "backup written next to it",- ApplyOutcome::NoOp => "already up to date",- }- );++ if let Some(prepared_skills) = prepared_skills {++ install_skills::run_prepared(prepared_skills)?;}+Ok(())}diff --cc crates/ai-memory-cli/src/commands/install_skills.rsindex a864dfb7,00000000..bb97676bmode 100644,000000..100644--- a/crates/ai-memory-cli/src/commands/install_skills.rs+++ b/crates/ai-memory-cli/src/commands/install_skills.rs@@@ -1,342 -1,0 +1,364 @@@+//! `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 ai_memory_core::routing_skills::{++ AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, MANAGED_MARKER, MANAGED_SKILLS, ManagedSkill, SKILLS_DIR,++};+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,+}+++#[derive(Debug, Clone, Eq, PartialEq)]++pub(super) struct PreparedInstall {++ plans: Vec<(PathBuf, &'static ManagedSkill)>,++}+++/// 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 roots = resolve_target_roots_from_env(&args)?;++ if args.print {+ print_install_plan(&roots);+ return Ok(());+ }+- for report in install_managed_skills(&roots, args.force)? {++ let prepared = prepare_install(&args)?;++ print_reports(apply_prepared_install(prepared)?);++++ Ok(())++}++++pub(super) fn prepare_install(args: &InstallSkillsArgs) -> Result<PreparedInstall> {++ let roots = resolve_target_roots_from_env(args)?;++ let plans = skill_file_plans(&roots);++ validate_overwrite_safety(&plans, args.force)?;++ Ok(PreparedInstall { plans })++}++++pub(super) fn run_prepared(prepared: PreparedInstall) -> Result<()> {++ print_reports(apply_prepared_install(prepared)?);++ Ok(())++}++++fn print_reports(reports: Vec<InstallReport>) {++ for report in reports {+ println!(+ "✓ {} {} ({})",+ report.outcome.verb(),+ report.path.display(),+ outcome_detail(report.outcome),+ );+ }-- Ok(())- }-- pub(super) fn preflight_overwrite_safety(args: &InstallSkillsArgs) -> Result<()> {- let roots = resolve_target_roots_from_env(args)?;- let plans = skill_file_plans(&roots);- validate_overwrite_safety(&plans, args.force)+}++fn resolve_target_roots_from_env(args: &InstallSkillsArgs) -> Result<Vec<TargetRoot>> {+ let cwd = std::env::current_dir().context("getting CWD for install-skills target")?;+ let home = dirs::home_dir();+ resolve_target_roots(args, &cwd, home.as_deref())+}++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",++ SkillRootKind::Claude => CLAUDE_SKILL_DIR,++ SkillRootKind::Agents => AGENTS_SKILL_DIR,+ };- Ok(base.join(agent_dir).join("skills"))++ Ok(base.join(agent_dir).join(SKILLS_DIR))+}+++#[cfg(test)]+fn install_managed_skills(roots: &[TargetRoot], force: bool) -> Result<Vec<InstallReport>> {+ let plans = skill_file_plans(roots);+ validate_overwrite_safety(&plans, force)?;++ apply_prepared_install(PreparedInstall { plans })++}+- let mut reports = Vec::with_capacity(plans.len());- for (path, skill) in plans {++fn apply_prepared_install(prepared: PreparedInstall) -> Result<Vec<InstallReport>> {++ let mut reports = Vec::with_capacity(prepared.plans.len());++ for (path, skill) in prepared.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 --cc crates/ai-memory-cli/src/commands/uninstall.rsindex 423a6563,6dbf78d0..487cd9cf--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@@ -13,7 -13,6 +13,9 @@@ use crate::commands::apply_shared::mutause 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::routing_skills::{++ AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, MANAGED_MARKER, MANAGED_SKILLS, SKILLS_DIR,++};use ai_memory_core::{MARKER_END, MARKER_START};use anyhow::{Context, Result};use std::io::IsTerminal;@@@ -253,23 -235,6 +255,23 @@@ fn build_plan(args: &UninstallArgs) ->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"));++ push_unique_skill_root(&mut roots, cwd.join(CLAUDE_SKILL_DIR).join(SKILLS_DIR));++ push_unique_skill_root(&mut roots, cwd.join(AGENTS_SKILL_DIR).join(SKILLS_DIR));+ 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"));++ push_unique_skill_root(&mut roots, home.join(CLAUDE_SKILL_DIR).join(SKILLS_DIR));++ push_unique_skill_root(&mut roots, home.join(AGENTS_SKILL_DIR).join(SKILLS_DIR));+ }+ 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() {diff --cc crates/ai-memory-cli/tests/install_instructions.rsindex 199d77c9,00000000..11c07d83mode 100644,000000..100644--- a/crates/ai-memory-cli/tests/install_instructions.rs+++ b/crates/ai-memory-cli/tests/install_instructions.rs@@@ -1,299 -1,0 +1,299 @@@+//! Integration tests for installing ai-memory instructions.++use std::fs;+use std::path::Path;+use std::process::{Command, Output};++use ai_memory_core::routing_skills::MANAGED_MARKER;+use ai_memory_core::{MARKER_END, MARKER_START};++fn bin() -> &'static str {+ env!("CARGO_BIN_EXE_ai-memory")+}++fn run_ai_memory(project: &Path, home: &Path, args: &[&str]) -> Output {+ Command::new(bin())+ .args(args)+ .current_dir(project)+ .env("HOME", home)+ .env("AI_MEMORY_DATA_DIR", home.join(".ai-memory-data"))+ .output()+ .unwrap()+}++fn assert_success(output: Output) -> String {+ assert!(+ output.status.success(),+ "command failed\nstdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ String::from_utf8(output.stdout).unwrap()+}++fn assert_failure(output: Output) -> String {+ assert!(+ !output.status.success(),+ "command unexpectedly succeeded\nstdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ String::from_utf8(output.stderr).unwrap()+}++#[test]+fn skill_conflict_preflight_keeps_instruction_file_unchanged_until_force() {+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let target = project.path().join("CLAUDE.md");+ let original = b"# Project\n\nKeep this exact.\n".to_vec();+ fs::write(&target, &original).unwrap();++ let unmanaged = project+ .path()+ .join(".claude/skills/ai-memory-retrieval/SKILL.md");+ let unmanaged_content = b"---\nname: ai-memory-retrieval\n---\nuser skill\n".to_vec();+ fs::create_dir_all(unmanaged.parent().unwrap()).unwrap();+ fs::write(&unmanaged, &unmanaged_content).unwrap();++ let output = run_ai_memory(project.path(), home.path(), &["install-instructions"]);+ let stderr = assert_failure(output);+ assert!(stderr.contains("refusing to overwrite unmanaged skill"));+ assert_eq!(fs::read(&target).unwrap(), original);+ assert_eq!(fs::read(&unmanaged).unwrap(), unmanaged_content);+ assert!(+ !project+ .path()+ .join(".claude/skills/ai-memory-handoff/SKILL.md")+ .exists()+ );++ let output = run_ai_memory(+ project.path(),+ home.path(),+ &["install-instructions", "--skills-force"],+ );+ assert_success(output);++ let updated = fs::read_to_string(&target).unwrap();+ assert!(updated.contains(MARKER_START));+ assert!(updated.contains("# Project"));+ assert!(+ fs::read_to_string(&unmanaged)+ .unwrap()+ .contains(MANAGED_MARKER)+ );+ assert!(+ project+ .path()+ .join(".claude/skills/ai-memory-handoff/SKILL.md")+ .exists()+ );+}++#[test]+fn no_skills_writes_only_instruction_snippet() {+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();++ let output = run_ai_memory(+ project.path(),+ home.path(),+ &["install-instructions", "--no-skills"],+ );+ assert_success(output);++ let claude_md = fs::read_to_string(project.path().join("CLAUDE.md")).unwrap();+ assert!(claude_md.contains(MARKER_START));+ assert!(claude_md.contains("Use the installed ai-memory Agent Skills"));+ assert!(!project.path().join(".claude/skills").exists());+ assert!(!project.path().join(".agents/skills").exists());+}++#[test]- fn print_shows_snippet_and_skill_plan_without_mutating() {++fn print_shows_only_snippet_without_mutating() {+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();++ let output = run_ai_memory(+ project.path(),+ home.path(),+ &["install-instructions", "--print"],+ );+ let stdout = assert_success(output);++ assert!(stdout.contains("# Would write into:"));+ assert!(stdout.contains(MARKER_START));+ assert!(stdout.contains("Use the installed ai-memory Agent Skills"));- assert!(stdout.contains("# Skill root:"));- assert!(stdout.contains("ai-memory-retrieval/SKILL.md"));- assert!(stdout.contains(MANAGED_MARKER));++ assert!(!stdout.contains("# Skill root:"));++ assert!(!stdout.contains("ai-memory-retrieval/SKILL.md"));++ assert!(!stdout.contains(MANAGED_MARKER));+ assert!(!project.path().join("CLAUDE.md").exists());+ assert!(!project.path().join(".claude/skills").exists());+ assert!(!project.path().join(".agents/skills").exists());+}++#[test]+fn no_skills_print_omits_skill_plan_and_does_not_mutate() {+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();++ let output = run_ai_memory(+ project.path(),+ home.path(),+ &["install-instructions", "--print", "--no-skills"],+ );+ let stdout = assert_success(output);++ assert!(stdout.contains(MARKER_START));+ assert!(!stdout.contains("# Skill root:"));+ assert!(!stdout.contains("ai-memory-retrieval/SKILL.md"));+ assert!(!project.path().join("CLAUDE.md").exists());+ assert!(!project.path().join(".claude/skills").exists());+}++#[test]+fn inferred_instruction_targets_select_matching_skill_agents() {+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ fs::write(project.path().join("AGENTS.md"), "# Agents\n").unwrap();++ let output = run_ai_memory(project.path(), home.path(), &["install-instructions"]);+ assert_success(output);++ assert!(+ project+ .path()+ .join(".agents/skills/ai-memory-retrieval/SKILL.md")+ .exists()+ );+ assert!(!project.path().join(".claude/skills").exists());++ let both_project = tempfile::tempdir().unwrap();+ let both_home = tempfile::tempdir().unwrap();+ fs::write(both_project.path().join("CLAUDE.md"), "# Claude\n").unwrap();+ fs::write(both_project.path().join("AGENTS.md"), "# Agents\n").unwrap();++ let output = run_ai_memory(+ both_project.path(),+ both_home.path(),+ &["install-instructions"],+ );+ assert_success(output);++ assert!(+ both_project+ .path()+ .join(".claude/skills/ai-memory-retrieval/SKILL.md")+ .exists()+ );+ assert!(+ both_project+ .path()+ .join(".agents/skills/ai-memory-retrieval/SKILL.md")+ .exists()+ );+}++#[test]+fn explicit_skill_scope_and_agent_override_instruction_target_inference() {+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();++ let output = run_ai_memory(+ project.path(),+ home.path(),+ &[+ "install-instructions",+ "--target",+ "AGENTS.md",+ "--skills-scope",+ "global",+ "--skills-agent",+ "claude-code",+ ],+ );+ assert_success(output);++ assert!(+ home.path()+ .join(".claude/skills/ai-memory-retrieval/SKILL.md")+ .exists()+ );+ assert!(!home.path().join(".agents/skills").exists());+ assert!(!project.path().join(".claude/skills").exists());+ assert!(!project.path().join(".agents/skills").exists());+}++#[test]+fn explicit_skill_overrides_win_over_instruction_target_inference() {+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let custom_root = project.path().join("custom-skills");+ let unmanaged = custom_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 custom_root_arg = custom_root.to_str().unwrap();+ let output = run_ai_memory(+ project.path(),+ home.path(),+ &[+ "install-instructions",+ "--target",+ "AGENTS.md",+ "--skills-scope",+ "global",+ "--skills-agent",+ "both",+ "--skills-target-dir",+ custom_root_arg,+ "--skills-force",+ ],+ );+ assert_success(output);++ let overwritten = fs::read_to_string(&unmanaged).unwrap();+ assert!(overwritten.contains(MANAGED_MARKER));+ assert!(custom_root.join("ai-memory-handoff/SKILL.md").exists());+ assert!(!project.path().join(".agents/skills").exists());+ assert!(!project.path().join(".claude/skills").exists());+ assert!(!home.path().join(".agents/skills").exists());+ assert!(!home.path().join(".claude/skills").exists());+}++#[test]+fn legacy_long_marker_block_rerun_upgrades_in_place_to_slim_snippet() {+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let original = format!(+ "# Project\n\n{MARKER_START}\n## Long-term memory (ai-memory)\n\n### When to reach for each tool\n\n|User says / situation|Tool|\n|---|---|\n|search memory|`memory_query`|\n{MARKER_END}\n\nKeep me.\n"+ );+ fs::write(project.path().join("CLAUDE.md"), original).unwrap();++ let output = run_ai_memory(+ project.path(),+ home.path(),+ &["install-instructions", "--no-skills"],+ );+ assert_success(output);++ let updated = fs::read_to_string(project.path().join("CLAUDE.md")).unwrap();+ assert!(updated.contains("# Project"));+ assert!(updated.contains("Keep me."));+ assert!(updated.contains("Use the installed ai-memory Agent Skills"));+ assert!(!updated.contains("When to reach for each tool"));+ assert!(!updated.contains("|User says / situation|Tool|"));+ assert_eq!(+ updated.lines().filter(|line| *line == MARKER_START).count(),+ 1+ );+ assert_eq!(+ updated.lines().filter(|line| *line == MARKER_END).count(),+ 1+ );+}diff --cc crates/ai-memory-cli/tests/uninstall.rsindex 67743f5c,a8c7024e..5d0ef69e--- a/crates/ai-memory-cli/tests/uninstall.rs+++ b/crates/ai-memory-cli/tests/uninstall.rs@@@ -428,168 -401,6 +428,216 @@@ 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_only_skills_leaves_custom_target_dir_for_manual_cleanup() {++ let _guard = cli_test_lock();++ let project = tempfile::tempdir().unwrap();++ let home = tempfile::tempdir().unwrap();++ let custom_root = project.path().join("custom-skills");++++ let install = Command::new(bin())++ .args([++ "install-skills",++ "--target-dir",++ custom_root.to_str().unwrap(),++ ])++ .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)++ );++++ let custom_skill = custom_root.join(MANAGED_SKILLS[0].relative_path);++ assert!(custom_skill.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!(++ custom_skill.exists(),++ "custom --target-dir skill roots are intentionally left for manual cleanup"++ );++ assert!(!project.path().join(".claude/skills").exists());++ assert!(!project.path().join(".agents/skills").exists());++}+++#[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();diff --cc crates/ai-memory-core/Cargo.tomlindex 03c900a4,03c900a4..8fe95df1--- a/crates/ai-memory-core/Cargo.toml+++ b/crates/ai-memory-core/Cargo.toml@@@ -22,5 -22,5 +22,8 @@@ tracing.workspace = tru# the model invent integer tier values).schemars.workspace = true++[dev-dependencies]++serde_yaml.workspace = true++[lints]workspace = truediff --cc crates/ai-memory-core/src/routing_skills.rsindex 7092527a,00000000..9472160emode 100644,000000..100644--- a/crates/ai-memory-core/src/routing_skills.rs+++ b/crates/ai-memory-core/src/routing_skills.rs@@@ -1,203 -1,0 +1,212 @@@+//! Canonical managed ai-memory Agent Skill assets.+//!+//! The installer-facing crates consume these definitions so every path that+//! writes ai-memory routing skills uses the same metadata and `SKILL.md` bytes.++/// Stable ownership marker embedded in every managed ai-memory skill file.+pub const MANAGED_MARKER: &str = "<!-- ai-memory-managed: routing-skill -->";+++/// Claude-compatible Agent Skill directory below a project or home root.++pub const CLAUDE_SKILL_DIR: &str = ".claude";++/// AGENTS-aware cross-client Agent Skill directory below a project or home root.++pub const AGENTS_SKILL_DIR: &str = ".agents";++/// Leaf directory that contains individual Agent Skill directories.++pub const SKILLS_DIR: &str = "skills";+++const RETRIEVAL_DESCRIPTION: &str = "Use this skill for any request whose goal is read-only retrieval from ai-memory: project history, prior context, decisions, rules, gotchas, recent activity, full wiki pages, or status/briefing. Trigger by semantic intent rather than exact wording, including when ai-memory is not named.";+const HANDOFF_DESCRIPTION: &str = "Use this skill for any request whose goal is session continuity across agents or time: finding a pending handoff, resuming previous work, saving next-session context, wrapping up, or discarding a mistaken handoff. Trigger by semantic intent rather than exact wording.";+const DURABLE_PAGES_DESCRIPTION: &str = "Use this skill for any explicit durable wiki mutation in ai-memory: saving project knowledge, recording a rule or annotation, updating a permanent note, or deleting a memory page. Trigger by semantic intent rather than exact wording; routine session capture is not a durable-page request.";+const LEARNING_MAINTENANCE_DESCRIPTION: &str = "Use this skill for any ai-memory knowledge-base maintenance request: consolidating observations, reviewing session lessons, proposing durable learnings, auditing or linting the wiki, finding contradictions, pruning stale memory, or running auto-improvement. Trigger by semantic intent rather than exact wording.";+const ROUTING_INSTALL_DESCRIPTION: &str = "Use this skill for any request to install, refresh, repair, inspect, or remove ai-memory's agent-facing routing: managed instruction snippets, Agent Skills, CLAUDE.md/AGENTS.md integration, or local/global skill roots. Trigger by semantic intent rather than exact wording.";++/// One ai-memory-managed Agent Skill file bundled by the core crate.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub struct ManagedSkill {+ /// Skill directory name and frontmatter `name` value.+ pub name: &'static str,+ /// Trigger-rich frontmatter `description` value.+ pub description: &'static str,+ /// File path relative to an agent skill root.+ pub relative_path: &'static str,+ /// Complete `SKILL.md` contents.+ pub content: &'static str,+}++/// Canonical managed ai-memory routing skills.+pub const MANAGED_SKILLS: &[ManagedSkill] = &[+ ManagedSkill {+ name: "ai-memory-retrieval",+ description: RETRIEVAL_DESCRIPTION,+ relative_path: "ai-memory-retrieval/SKILL.md",+ content: include_str!("routing_skills/ai-memory-retrieval/SKILL.md"),+ },+ ManagedSkill {+ name: "ai-memory-handoff",+ description: HANDOFF_DESCRIPTION,+ relative_path: "ai-memory-handoff/SKILL.md",+ content: include_str!("routing_skills/ai-memory-handoff/SKILL.md"),+ },+ ManagedSkill {+ name: "ai-memory-durable-pages",+ description: DURABLE_PAGES_DESCRIPTION,+ relative_path: "ai-memory-durable-pages/SKILL.md",+ content: include_str!("routing_skills/ai-memory-durable-pages/SKILL.md"),+ },+ ManagedSkill {+ name: "ai-memory-learning-maintenance",+ description: LEARNING_MAINTENANCE_DESCRIPTION,+ relative_path: "ai-memory-learning-maintenance/SKILL.md",+ content: include_str!("routing_skills/ai-memory-learning-maintenance/SKILL.md"),+ },+ ManagedSkill {+ name: "ai-memory-routing-install",+ description: ROUTING_INSTALL_DESCRIPTION,+ relative_path: "ai-memory-routing-install/SKILL.md",+ content: include_str!("routing_skills/ai-memory-routing-install/SKILL.md"),+ },+];++#[cfg(test)]+mod tests {+ use std::collections::BTreeMap;++ use std::ffi::OsStr;++ use std::path::{Component, Path};++ use super::{MANAGED_MARKER, MANAGED_SKILLS, ManagedSkill};++ const EXPECTED_SKILLS: &[&str] = &[+ "ai-memory-retrieval",+ "ai-memory-handoff",+ "ai-memory-durable-pages",+ "ai-memory-learning-maintenance",+ "ai-memory-routing-install",+ ];++ const EXPECTED_TOOL_CLUSTERS: &[(&str, &str)] = &[+ ("memory_query", "ai-memory-retrieval"),+ ("memory_recent", "ai-memory-retrieval"),+ ("memory_read_page", "ai-memory-retrieval"),+ ("memory_status", "ai-memory-retrieval"),+ ("memory_briefing", "ai-memory-retrieval"),+ ("memory_explore", "ai-memory-retrieval"),+ ("memory_handoff_accept", "ai-memory-handoff"),+ ("memory_handoff_begin", "ai-memory-handoff"),+ ("memory_handoff_cancel", "ai-memory-handoff"),+ ("memory_write_page", "ai-memory-durable-pages"),+ ("memory_delete_page", "ai-memory-durable-pages"),+ ("memory_consolidate", "ai-memory-learning-maintenance"),+ ("memory_auto_improve", "ai-memory-learning-maintenance"),+ ("memory_lint", "ai-memory-learning-maintenance"),+ ("memory_forget_sweep", "ai-memory-learning-maintenance"),+ ("memory_install_self_routing", "ai-memory-routing-install"),+ ];+- #[derive(Debug)]- struct Frontmatter<'a> {- name: &'a str,- description: &'a str,++ #[derive(Debug, serde::Deserialize)]++ struct Frontmatter {++ name: String,++ description: String,+ }++ #[test]+ fn exposes_exact_managed_skill_set() {+ let names: Vec<_> = MANAGED_SKILLS.iter().map(|skill| skill.name).collect();+ assert_eq!(names, EXPECTED_SKILLS);+ }++ #[test]+ fn skill_frontmatter_is_valid_and_matches_metadata() {+ for skill in MANAGED_SKILLS {+ let frontmatter = parse_frontmatter(skill);+ assert_eq!(frontmatter.name, skill.name);+ assert_eq!(frontmatter.description, skill.description);+ assert_eq!(frontmatter.name, directory_name(skill));+ assert!(!frontmatter.description.trim().is_empty());+ assert!(+ frontmatter.description.chars().count() <= 1024,+ "{} description is over the Agent Skills limit",+ skill.name+ );+ }+ }++ #[test]+ fn every_skill_has_managed_marker() {+ assert!(!MANAGED_MARKER.is_empty());+ for skill in MANAGED_SKILLS {+ assert!(+ skill.content.contains(MANAGED_MARKER),+ "{} is missing the managed ownership marker",+ skill.name+ );+ }+ }++ #[test]- fn relative_paths_are_skill_markdown_files() {++ fn relative_paths_are_safe_relative_skill_markdown_files() {+ for skill in MANAGED_SKILLS {+ let expected_suffix = format!("{}/SKILL.md", skill.name);+ assert_eq!(skill.relative_path, expected_suffix);++ assert!(++ !skill.name.contains(['/', '\\']),++ "{} must be a single skill directory name",++ skill.name++ );++++ let path = Path::new(skill.relative_path);++ assert!(++ !path.is_absolute(),++ "{} relative_path must not be absolute",++ skill.name++ );++ let components: Vec<_> = path.components().collect();++ assert_eq!(++ components,++ vec![++ Component::Normal(OsStr::new(skill.name)),++ Component::Normal(OsStr::new("SKILL.md")),++ ],++ "{} relative_path must be exactly <skill>/SKILL.md with no parent/current/root components",++ skill.name++ );+ }+ }++ #[test]+ fn every_routing_tool_appears_only_in_its_intended_cluster() {+ let expected_by_tool: BTreeMap<_, _> = EXPECTED_TOOL_CLUSTERS.iter().copied().collect();+ assert_eq!(expected_by_tool.len(), EXPECTED_TOOL_CLUSTERS.len());++ for (tool, expected_skill) in expected_by_tool {+ let containing_skills: Vec<_> = MANAGED_SKILLS+ .iter()+ .filter(|skill| skill.content.contains(tool))+ .map(|skill| skill.name)+ .collect();++ assert_eq!(+ containing_skills,+ vec![expected_skill],+ "{tool} should appear in exactly one intended skill"+ );+ }+ }+- fn parse_frontmatter(skill: &ManagedSkill) -> Frontmatter<'_> {- let mut lines = skill.content.lines();- assert_eq!(- lines.next(),- Some("---"),- "{} must start with frontmatter",- skill.name- );-- let mut name = None;- let mut description = None;- let mut closed = false;- for line in lines.by_ref() {- if line == "---" {- closed = true;- break;- }-- if let Some(value) = line.strip_prefix("name: ") {- name = Some(value.trim());- } else if let Some(value) = line.strip_prefix("description: ") {- description = Some(value.trim());- }- }- assert!(closed, "{} must close frontmatter", skill.name);-- Frontmatter {- name: name.unwrap_or_else(|| panic!("{} is missing frontmatter name", skill.name)),- description: description- .unwrap_or_else(|| panic!("{} is missing frontmatter description", skill.name)),- }++ fn parse_frontmatter(skill: &ManagedSkill) -> Frontmatter {++ let Some(rest) = skill.content.strip_prefix("---\n") else {++ panic!("{} must start with frontmatter", skill.name);++ };++ let Some((frontmatter, _body)) = rest.split_once("\n---\n") else {++ panic!("{} must close frontmatter", skill.name);++ };++ serde_yaml::from_str(frontmatter)++ .unwrap_or_else(|e| panic!("{} frontmatter must be valid YAML: {e}", skill.name))+ }++ fn directory_name(skill: &ManagedSkill) -> &str {+ skill+ .relative_path+ .split('/')+ .next()+ .unwrap_or_else(|| panic!("{} has an empty relative path", skill.name))+ }+}diff --cc crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.mdindex fb439cdf,00000000..e334eff3mode 100644,000000..100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md@@@ -1,32 -1,0 +1,32 @@@+---+name: ai-memory-durable-pages- description: Use this skill for any explicit durable wiki mutation in ai-memory: saving project knowledge, recording a rule or annotation, updating a permanent note, or deleting a memory page. Trigger by semantic intent rather than exact wording; routine session capture is not a durable-page request.++description: "Use this skill for any explicit durable wiki mutation in ai-memory: saving project knowledge, recording a rule or annotation, updating a permanent note, or deleting a memory page. Trigger by semantic intent rather than exact wording; routine session capture is not a durable-page request."+---+<!-- ai-memory-managed: routing-skill -->++# ai-memory durable pages++Use this skill only for deliberate durable wiki mutations. Routine session capture is automatic, and permanent notes require an explicit user request.++## Tools in this cluster++- `memory_write_page` writes a durable wiki page for permanent project knowledge.+- `memory_delete_page` removes a durable wiki page by exact path.++## Writing durable memory++Write a page only when the user explicitly asks to remember something permanently, save a note, add an annotation, or record project knowledge. Do not use durable pages for transient progress, normal status updates, or next-session context.++Put the page title as a `# H1` on the first line of the body and omit the separate title argument. ai-memory derives the title from that H1. Keep the content concise and fact-like, with enough context that a future agent can apply it without rereading the whole session.++## Project rules belong in instructions first++If the user asks to create a durable project rule such as always do X or never do Y, update the project's canonical agent instruction file when the repository says one exists. Use a durable page only when the user explicitly wants the rule in the wiki too, or when no canonical instruction file applies.++## Deleting durable memory++Delete only by exact path. If the user gives a vague title or topic, first resolve it to the page path using read-only lookup. Preserve sibling projects unless the user explicitly names them.++## Scope default++Default to the current project. Pass workspace and project together only when the user explicitly names a different project. Never pass scope arguments for phrases like this project, here, we, or our work.diff --cc crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.mdindex c362f2e8,00000000..bca27f2bmode 100644,000000..100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md@@@ -1,35 -1,0 +1,35 @@@+---+name: ai-memory-handoff- description: Use this skill for any request whose goal is session continuity across agents or time: finding a pending handoff, resuming previous work, saving next-session context, wrapping up, or discarding a mistaken handoff. Trigger by semantic intent rather than exact wording.++description: "Use this skill for any request whose goal is session continuity across agents or time: finding a pending handoff, resuming previous work, saving next-session context, wrapping up, or discarding a mistaken handoff. Trigger by semantic intent rather than exact wording."+---+<!-- ai-memory-managed: routing-skill -->++# ai-memory handoff++Use this skill for single-use cross-session handoffs. Handoffs are for the next agent, not durable project documentation.++## Tools in this cluster++- `memory_handoff_accept` consumes the pending handoff when the user asks where we left off and no already-fetched handoff block is visible.+- `memory_handoff_begin` creates a terse next-session handoff only when the user is wrapping up, ending the session, or explicitly asks to save context for the next session.+- `memory_handoff_cancel` expires a mistaken pending handoff by exact handoff id.++## Single-use handoff behavior++The SessionStart hook usually fetches and consumes any pending handoff before the agent sees its first prompt. If the current context already contains a pending handoff block, answer from that block directly. Do not call the accept tool again to find it in another project, because handoffs are single-use and the tool will normally return null after SessionStart consumed it.++If no pending handoff block is visible and the user asks where we left off, then use the accept tool. Keep the default current-project scope unless the user explicitly names a sibling workspace and project.++## Creating a handoff++Create a handoff only at session end or when the user explicitly asks to save context for the next session. Do not use handoffs for status checks, briefings, project notes, or permanent memory. Keep the summary to two or three concise sentences, and put details in open questions and next steps bullets.++Lifecycle hooks already capture routine prompts and tool calls, so do not manually write a handoff just to record normal progress.++## Canceling a handoff++Cancel only when the user asks to discard a handoff or you created one by mistake. Use the exact handoff id returned by the begin tool. Cancellation is idempotent from the user's point of view, but it should still target only the known handoff.++## Scope default++Default to the current project. Pass workspace and project together only when the user names a different project. Never pass scope arguments just because the user says this project, here, we, or our work.diff --cc crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.mdindex 875a74aa,00000000..d2a4e8b6mode 100644,000000..100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md@@@ -1,38 -1,0 +1,38 @@@+---+name: ai-memory-learning-maintenance- description: Use this skill for any ai-memory knowledge-base maintenance request: consolidating observations, reviewing session lessons, proposing durable learnings, auditing or linting the wiki, finding contradictions, pruning stale memory, or running auto-improvement. Trigger by semantic intent rather than exact wording.++description: "Use this skill for any ai-memory knowledge-base maintenance request: consolidating observations, reviewing session lessons, proposing durable learnings, auditing or linting the wiki, finding contradictions, pruning stale memory, or running auto-improvement. Trigger by semantic intent rather than exact wording."+---+<!-- ai-memory-managed: routing-skill -->++# ai-memory learning and maintenance++Use this skill for compilation, learning review, wiki linting, and cleanup of ai-memory's durable knowledge base.++## Tools in this cluster++- `memory_consolidate` compiles raw session observations into topical wiki pages on demand.+- `memory_auto_improve` reviews a completed session for durable lessons and project-rule proposals.+- `memory_lint` audits the wiki for contradictions, stale guidance, and candidate rule placement.+- `memory_forget_sweep` prunes or proposes removal of old pages when the user asks for memory cleanup.++## Consolidation and learning review++The server may already run consolidation on PreCompact and at session end when configured. Use on-demand consolidation only when the user asks to compile or consolidate what happened.++Use the auto-improvement tool when the user asks what durable lessons should be proposed from a completed session, or during an explicit wrap-up learning review. It reads the latest completed session by default when no session id is provided.++## Approval path++Scheduled and manual learning reviews apply or stage validated edits through the auto-improvement approval path. Admins can disable scheduling, or require proposal approval so pending writes remain staged until approved. Do not imply a proposal was applied unless the tool result says it was applied.++## Dry-run and destructive caution++Prefer read-only linting or proposal mode before destructive cleanup. When a maintenance tool exposes dry-run behavior, use it first unless the user explicitly requested immediate deletion. If no dry run exists for a destructive action, report what would be removed and ask before proceeding.++## What not to learn++Generic ai-memory routing guidance, Agent Skill installation details, and temporary prompt-packaging instructions are not durable project knowledge. Do not turn them into wiki pages or project rules unless the user explicitly asks to remember a project-specific decision.++## Scope default++Default to the current project. Pass workspace and project together only when the user explicitly names a different project.diff --cc crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.mdindex 3ed303f1,00000000..c73dd31amode 100644,000000..100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md@@@ -1,51 -1,0 +1,52 @@@+---+name: ai-memory-retrieval- description: Use this skill for any request whose goal is read-only retrieval from ai-memory: project history, prior context, decisions, rules, gotchas, recent activity, full wiki pages, or status/briefing. Trigger by semantic intent rather than exact wording, including when ai-memory is not named.++description: "Use this skill for any request whose goal is read-only retrieval from ai-memory: project history, prior context, decisions, rules, gotchas, recent activity, full wiki pages, or status/briefing. Trigger by semantic intent rather than exact wording, including when ai-memory is not named."+---+<!-- ai-memory-managed: routing-skill -->++# ai-memory retrieval++Use this skill for read-only ai-memory lookups, catch-up, and applying remembered project knowledge before you design, debug, or edit.++## Tools in this cluster++- `memory_query` searches the current project's wiki for prior decisions, gotchas, procedures, rules, and session notes.+- `memory_recent` lists the most recently updated pages when the user wants a light activity check.+- `memory_read_page` fetches a full page body after a search hit or direct path lookup.+- `memory_status` reports whether ai-memory is healthy and how large the knowledge base is.+- `memory_briefing` returns a structured read-only snapshot for agent consumption.+- `memory_explore` returns a prose digest when the user asks for an open-ended catch-up.++## Scope default++Default to the current project. The tools auto-scope from the working directory, so omit project, workspace, and cwd arguments unless the user explicitly names a different project. Phrases like this project, here, we, our work, and where did we leave off mean the current project.++## Choose the smallest useful lookup++- Use the search tool when the user asks whether something was discussed, before proposing architecture, or before non-trivial coding in a subsystem with possible prior decisions.++- Before non-trivial coding, debugging, deployment, release, auth, scope, migration, PR review, or data-preservation work, search memory for the subsystem and task type first. If the first search is thin, broaden or query more specific subsystem/error terms before designing a fix.+- Use the recent-pages tool for a quick what changed lately view.+- Use the status tool only for health and size questions.+- Use the structured briefing when code needs counts, windows, pending-handoff counts, current rules, or recent pages as JSON-like data.+- Use the prose exploration tool for broad catch-up questions like what is important right now or I have been away.++## Broaden on miss++If a current-project search is empty or thin, do not conclude the knowledge was never recorded. It may live in a sibling project such as infra, ops, or a related app.+- - If the user named the sibling project or you know the likely sibling, search explicit scopes.- - If you do not know where it lives, search globally across every project.- - Do not combine global search with explicit scopes or project and workspace arguments.++- If the user named the sibling project or you know the likely sibling, search explicit `scopes`, for example `scopes: [{ "workspace": "default", "project": "infra" }]`.++- If you do not know where it lives, search globally across every project with `global=true`.++- Do not combine `global=true` with `scopes`, `project`, or `workspace` arguments.++## Snippets are not full pages++Search returns snippets, not complete bodies. An empty-looking or short snippet does not prove the page is empty because the match can be outside the snippet window. Fetch the full page when the path or title looks relevant, especially for rules, procedures, decisions, and gotchas.++## Apply retrieved guidance++Treat matching pages under `_rules/`, `gotchas/`, `procedures/`, and `decisions/` as operating constraints.++- Apply rules as current project policy.+- Check gotchas before editing the same subsystem.+- Follow procedures as checklists for releases, PR review, deploys, migrations, and other repeatable workflows.+- Treat decisions as prior architecture unless the user asks to revisit them.diff --cc crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.mdindex 03563029,00000000..c5d14b1emode 100644,000000..100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md@@@ -1,52 -1,0 +1,52 @@@+---+name: ai-memory-routing-install- description: Use this skill for any request to install, refresh, repair, inspect, or remove ai-memory's agent-facing routing: managed instruction snippets, Agent Skills, CLAUDE.md/AGENTS.md integration, or local/global skill roots. Trigger by semantic intent rather than exact wording.++description: "Use this skill for any request to install, refresh, repair, inspect, or remove ai-memory's agent-facing routing: managed instruction snippets, Agent Skills, CLAUDE.md/AGENTS.md integration, or local/global skill roots. Trigger by semantic intent rather than exact wording."+---+<!-- ai-memory-managed: routing-skill -->++# ai-memory routing install++Use this skill when the user wants ai-memory's agent-facing routing instructions or managed Agent Skills installed, refreshed, repaired, or removed.++## Tools in this cluster++- `memory_install_self_routing` returns the canonical markered instruction block, marker strings, filename hints, notes, and managed skill payloads for agents that cannot let the MCP server write the host filesystem directly.++## Managed instruction marker++The always-loaded instruction block is owned by ai-memory only between these markers.++- Start marker: `<!-- ai-memory:start -->`+- End marker: `<!-- ai-memory:end -->`++Refresh must replace the first complete marker-bounded block in place, preserving unrelated content before and after it. If no complete block exists, append the canonical block with one blank line of separation. Never edit unrelated instructions while refreshing ai-memory routing.++## Managed skill marker++Every ai-memory-managed `SKILL.md` file contains this ownership marker.++`<!-- ai-memory-managed: routing-skill -->`++Installers and uninstallers should overwrite or remove same-name skill files only when that marker is present, unless the user supplied an explicit force option. If a same-name skill lacks the marker, skip it with an actionable message so user-authored skills are preserved.++## Skill install targets++Managed skills are ordinary Agent Skills. Their relative file path is `<skill>/SKILL.md`, and the installer prepends the selected skill root.++Project-local targets:++- `.claude/skills/<skill>/SKILL.md` for Claude-compatible installs.+- `.agents/skills/<skill>/SKILL.md` for cross-client installs.++Global targets:++- `~/.claude/skills/<skill>/SKILL.md` for Claude-compatible installs.+- `~/.agents/skills/<skill>/SKILL.md` for cross-client installs.++Use platform-aware path joining. Do not build paths by string concatenation.++## Refresh guidance++For an agent-side refresh, call the install-routing tool, choose the right instruction filename from its hints, write the markered block with the agent's file-edit tool, and write each managed skill file to the selected skill roots. Claude Code normally uses `CLAUDE.md` and `.claude/skills`; Codex, OpenCode, Cursor, Gemini CLI, and AGENTS-aware clients normally use `AGENTS.md` and `.agents/skills` unless the project says otherwise.++For a CLI refresh, prefer the canonical install command. The snippet and skills must be updated from the same core-owned assets so they do not drift.diff --cc crates/ai-memory-mcp/src/server.rsindex dd7a7b75,962afa22..ee1a6818--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@@ -238,10 -238,10 +238,14 @@@ should be proposed from a completed sespages (idempotent, supports dry-run).\n\- `memory_install_self_routing` — when the user asks to 'install \ai-memory routing into this project' or 'add ai-memory to \-- CLAUDE.md / AGENTS.md'. Returns the canonical routing snippet + \-- filename hints; you then use your own Write/Edit tool to land it \-- in the right rules file (Claude Code → CLAUDE.md, Codex / \-- OpenCode / Cursor / Gemini → AGENTS.md).\n\++ CLAUDE.md / AGENTS.md'. Returns the managed routing package: the \++ slim markered snippet (`markered_block`), filename hints, \++ `managed_skills` payloads, `target_hints` for `.claude/skills` or \++ `.agents/skills`, and overwrite guidance. Use your own Write/Edit \++ tool to replace only the ai-memory marker block in the rules file, \++ then write each managed skill under the selected skill root. Only \++ replace same-name skill files that contain the ai-memory managed \++ marker unless the human explicitly forces replacement.\n\\n\**When the current project comes up empty, broaden — don't stop.** \`memory_query` searches only ONE project (the current one) by default. \@@@ -271,10 -271,10 +275,12 @@@ deployment, release, auth, scope, migradata-preservation work, search memory for the subsystem and task type \first.\n\\n\--The routing snippet this very text comes from can also be installed \--into the project's CLAUDE.md / AGENTS.md so the guidance survives \--across sessions. From the agent: ask 'install ai-memory routing'. \--From the terminal: `ai-memory install-instructions`.";++The managed routing package this text points to can also be installed \++into the project's CLAUDE.md / AGENTS.md plus ai-memory-managed Agent \++Skills so the guidance survives across sessions. From the agent: ask \++'install ai-memory routing' and use the returned `managed_skills` + \++`target_hints`. From the terminal: `ai-memory install-instructions` \++(or `ai-memory install-skills` to refresh only the skill files).";/// MCP server backed by the ai-memory store.#[derive(Clone)]@@@ -2401,6 -2370,6 +2407,8 @@@ fn test_parts_default() -> axum::http::#[cfg(test)]mod tests {use super::*;++ use std::collections::BTreeSet;++use ai_memory_core::{ActorContext, AuthLevel, NewObservation, NewPage, NewSession, NewUser, ObservationKind,PagePath, Tier,@@@ -2571,20 -2468,35 +2579,36 @@@let (_tmp, _store, _server, _ws, _pj) = setup_server().await;}-- #[test]-- fn prompts_cover_every_mcp_tool() {- for tool in MCP_TOOL_NAMES {- let tools = [- "memory_query",- "memory_recent",- "memory_status",- "memory_briefing",- "memory_explore",- "memory_handoff_accept",- "memory_handoff_begin",- "memory_handoff_cancel",- "memory_consolidate",- "memory_auto_improve",- "memory_write_page",- "memory_read_page",- "memory_delete_page",- "memory_lint",- "memory_forget_sweep",- "memory_install_self_routing",- ];- let routing = ai_memory_core::full_block();- for tool in tools {++ #[tokio::test]++ async fn prompts_cover_every_registered_mcp_tool() {++ let (_tmp, _store, server, _ws, _pj) = setup_server().await;++ let actual_tools: BTreeSet<String> = server++ .tool_router++ .list_all()++ .into_iter()++ .map(|tool| tool.name.to_string())++ .collect();++ let expected_tools: BTreeSet<String> = MCP_TOOL_NAMES++ .iter()++ .map(|tool| (*tool).to_string())++ .collect();++ assert_eq!(++ actual_tools, expected_tools,++ "MCP_TOOL_NAMES must match the registered tool router set"++ );++++ for tool in &actual_tools {assert!(-- MEMORY_INSTRUCTIONS.contains(tool),++ MEMORY_INSTRUCTIONS.contains(tool.as_str()),"MCP handshake instructions omit {tool}");+ }++ let installed = installed_ai_memory_prompt_surface();- for tool in MCP_TOOL_NAMES {++ for tool in &actual_tools {assert!(- installed.contains(tool),- routing.contains(tool),- "routing snippet omit {tool}; update ai_memory_core::SNIPPET_BODY"++ installed.contains(tool.as_str()),+ "installed snippet and managed skills omit {tool}");}}@@@ -2711,10 -2563,10 +2735,22 @@@for phrase in no_global_phrases {assert!(!prompt.contains(phrase),- "prompt must not contain the contradictory phrase {phrase:?}"+ "{label} must not contain the contradictory phrase {phrase:?}");}- }+ });++ let installed = installed_ai_memory_prompt_surface();++ assert!(++ installed.contains("scopes") && installed.contains("global=true"),++ "installed prompt surface must include exact cross-project broadening args"++ );++ assert!(++ installed.contains("deployment")++ && installed.contains("PR review")++ && installed.contains("migration")++ && installed.contains("data-preservation"),++ "installed prompt surface must preserve high-risk retrieval preflight guidance"++ );}#[test]diff --cc docs/install.mdindex e3038f20,bc0e482e..16fc5388--- a/docs/install.md+++ b/docs/install.md@@@ -946,70 -943,9 +946,77 @@@ docker run --rm akitaonrails/ai-memory:| `install-mcp --client` | `docker run --rm` | MCP-config snippet per client || `install-hooks --agent` | `docker run --rm` | Hook-config snippet for an existing hooks dir || `setup-agent --agent --to --host-prefix` | `docker run --rm -v` | Extract bundled scripts + print config (one-shot) |-| `uninstall --apply` | same host environment used for install | Remove only ai-memory-owned hooks, MCP entries, and instruction blocks; generated plugin files are deleted only after content validation. Use `--mcp-url` for custom MCP endpoints and `--mcp-name` only to narrow removal. |+| `install-instructions [--target] [--print] [--no-skills]` | same host environment used for the agent prompt files | Install or update the slim CLAUDE.md / AGENTS.md routing block and, by default, the managed ai-memory Agent Skills |- | `install-skills --scope --agent` | same host environment used for the agent skill dirs | Install or update only the managed ai-memory Agent Skills |++| `install-skills [--scope] [--agent]` | same host environment used for the agent skill dirs | Install or update only the managed ai-memory Agent Skills |+| `uninstall --apply` | same host environment used for install | Remove only ai-memory-owned hooks, MCP entries, instruction blocks, managed skill files, and generated plugin files after content/marker validation. Use `--mcp-url` for custom MCP endpoints and `--mcp-name` only to narrow removal. || `llm-test --provider …` | `docker run --rm -e …` | Smoke-test an LLM provider |+### Managed routing snippets and Agent Skills++ai-memory's routing install is agent-facing prompt packaging. It does not add a+runtime skill router, and `SKILL.md` files are not durable memory pages. The+wiki remains the durable source of truth.++`ai-memory install-instructions` now writes two managed prompt artifacts by+default:++1. A slim instruction block in `CLAUDE.md`, `AGENTS.md`, or the file passed with+ `--target`. The block is bounded by `<!-- ai-memory:start -->` and+ `<!-- ai-memory:end -->`.+2. Managed ai-memory Agent Skills containing the detailed tool-routing guidance.++Re-running the command is safe. If a project still has the old long ai-memory+block between those markers, the refresh replaces that block in place with the+slim snippet and leaves unrelated instructions before and after it alone.+Managed skill files contain an ai-memory ownership marker; same-name user skills+without that marker are preserved unless you explicitly force replacement.++`install-instructions --print` previews only the instruction snippet; run++`install-skills --print` when you want to preview the managed skill payloads.++`install-instructions` flags for skills:++| Flag | Meaning |+|---|---|+| `--no-skills` | Refresh only the markered instruction block. |+| `--skills-scope <scope>` | Choose project-local or user-global skill roots. Values: `project`, `global`. Defaults to `project`. |+| `--skills-agent <agent>` | Choose `.claude/skills`, `.agents/skills`, or both. Values: `claude-code`, `agents`, `both`. By default, `CLAUDE.md` targets imply `claude-code`, `AGENTS.md` targets imply `agents`, and both instruction files imply `both`. |+| `--skills-target-dir <dir>` | Write managed skill directories below an explicit root instead of inferring from scope and agent. |+| `--skills-force` | Replace unmanaged same-name skills during `install-instructions`; without it, they are left untouched and the command exits with an actionable error. |++Use `install-skills` when the instruction block is already right and only the+Agent Skill files need a refresh:++```bash+ai-memory install-skills+ai-memory install-skills --scope global --agent agents+ai-memory install-skills --agent both --print+ai-memory install-skills --target-dir .custom/skills --force+```++`install-skills` flags:++| Flag | Meaning |+|---|---|+| `--scope <scope>` | Install into this project or the current user's global skill roots. Values: `project`, `global`. Defaults to `project`. |+| `--agent <agent>` | Install into Claude Code's skill root, the cross-agent skill root, or both. Values: `claude-code`, `agents`, `both`. Defaults to `claude-code`. |+| `--target-dir <dir>` | Write managed skill directories below an explicit root; `--scope` and `--agent` are ignored. |+| `--print` | Print target paths and `SKILL.md` contents without writing files. |+| `--force` | Replace unmanaged same-name skills; without it, user-authored same-name skills are preserved. |++Default skill target roots:++| Scope | `--agent claude-code` | `--agent agents` |+|---|---|---|+| `project` | `.claude/skills` | `.agents/skills` |+| `global` | `~/.claude/skills` | `~/.agents/skills` |++Each managed skill is written as `<root>/<skill-name>/SKILL.md`.+++`ai-memory uninstall --only skills --apply` removes managed skill files only++from the default project/global roots shown above, after validating the++ai-memory ownership marker. If you installed with `--target-dir` or++`--skills-target-dir`, clean up that custom root manually.++Data dir inside the container is `/data` (mounted via the composevolume). Outside docker, override with `AI_MEMORY_DATA_DIR=/path`.diff --cc docs/usage.mdindex 5f32a6ad,eba0f52d..7187056f--- a/docs/usage.md+++ b/docs/usage.md@@@ -89,42 -87,11 +89,46 @@@ From a terminalai-memory install-instructionsai-memory install-instructions --target AGENTS.mdai-memory install-instructions --print+ai-memory install-instructions --no-skills```+`install-instructions` installs or updates managed skills by default. Use- `--no-skills` only when you intentionally want a snippet-only refresh. Skill- flags mirror `install-skills` with an `--skills-` prefix:++`--no-skills` only when you intentionally want a snippet-only refresh.++`install-instructions --print` previews the instruction snippet only; use++`install-skills --print` to preview skill payloads. Skill flags mirror++`install-skills` with an `--skills-` prefix:+`--skills-scope project|global`, `--skills-agent claude-code|agents|both`,+`--skills-target-dir <dir>`, and `--skills-force`.+Auto-detect extends `CLAUDE.md` when it exists, `AGENTS.md` when it-exists, both when both exist, or creates `CLAUDE.md` when neither-exists. Use `--target AGENTS.md` for non-Claude-only projects.+exists, both when both exist, or creates `CLAUDE.md` when neither exists. Use+`--target AGENTS.md` for non-Claude-only projects. The skill target follows the+instruction target unless you override it: `CLAUDE.md` implies+`.claude/skills`, `AGENTS.md` implies `.agents/skills`, and both files imply+both skill roots.++To refresh only the managed Agent Skills:++```bash+ai-memory install-skills+ai-memory install-skills --scope global --agent agents+ai-memory install-skills --agent both --print+ai-memory install-skills --target-dir .custom/skills --force+```++Project-local skill roots are `.claude/skills` for Claude-compatible installs+and `.agents/skills` for cross-client installs. Global roots are+`~/.claude/skills` and `~/.agents/skills`. `--target-dir` points at an explicit+skill root and bypasses scope/agent inference. `--print` previews target paths+and `SKILL.md` contents. `--force` allows replacement of unmanaged same-name- skills; without it, user-authored skills are preserved.++skills; without it, user-authored skills are preserved. Uninstall removes++ai-memory-managed skills from the default project/global roots after marker++validation; custom `--target-dir` roots are a manual cleanup path.++This is prompt packaging only. ai-memory does not run a runtime skill router,+does not store durable memory in `SKILL.md`, and does not turn the+auto-improvement loop into a skill-authoring system. Durable knowledge still+lives in the wiki.## Bootstrap an existing project