Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(cli): add backup-agents and restore-agents commands
Barba2k29aaa7f73a33b
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex f6043de6..ea27cc9b 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -115,10 +115,16 @@ pub enum Command {ReclaimLedgerVersions(ReclaimLedgerVersionsArgs),/// Snapshot wiki/, db/, and config.toml into a gzipped tarball.Backup(BackupArgs),+ /// Snapshot AI agent configurations, skills, and plugins into a portable archive.+ #[command(name = "backup-agents")]+ BackupAgents(BackupAgentsArgs),/// Export one project's wiki as an OKF v0.2 bundle tarball.ExportOkf(ExportOkfArgs),/// Restore a backup tarball into the data directory.Restore(RestoreArgs),+ /// Restore AI agent configurations, skills, and plugins from an archive.+ #[command(name = "restore-agents")]+ RestoreAgents(RestoreAgentsArgs),/// Rebuild the SQLite index from the wiki/ markdown (the "DB is/// rebuildable from files" guarantee). Recreates workspaces/projects from/// each scope's `_meta.md` manifest and reindexes every page. Run with the@@ -1746,6 +1752,37 @@ pub struct BackupArgs {pub to: PathBuf,}+/// Scope of assets to collect for `backup-agents`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]+pub enum AgentBackupScope {+ /// Global user assets only.+ Global,+ /// Project assets only.+ Project,+ /// Both global and project assets.+ Both,+}++/// Arguments for `backup-agents`.+#[derive(Debug, Args)]+pub struct BackupAgentsArgs {+ /// Destination tarball (`.tar.gz`).+ #[arg(long, short = 'o')]+ pub to: PathBuf,+ /// Comma-separated list of agent names to include (e.g. `claude,codex,antigravity`). Defaults to all detected.+ #[arg(long, value_delimiter = ',')]+ pub agents: Option<Vec<String>>,+ /// Scope of assets to collect: `global`, `project`, or `both`.+ #[arg(long, default_value = "both")]+ pub scope: AgentBackupScope,+ /// Include raw un-redacted credentials and tokens in MCP configs (sets file mode 0600 on archive).+ #[arg(long)]+ pub include_secrets: bool,+ /// Preview assets that would be backed up without creating an archive.+ #[arg(long)]+ pub dry_run: bool,+}+/// Arguments for `export-okf`.#[derive(Debug, Args)]pub struct ExportOkfArgs {@@ -1771,6 +1808,23 @@ pub struct RestoreArgs {pub force: bool,}+/// Arguments for `restore-agents`.+#[derive(Debug, Args)]+pub struct RestoreAgentsArgs {+ /// Source archive (`.tar.gz`).+ #[arg(long, short = 'i')]+ pub from: PathBuf,+ /// Optional comma-separated list of agents to restore. Defaults to all present in archive.+ #[arg(long, value_delimiter = ',')]+ pub agents: Option<Vec<String>>,+ /// Actually write restored files to disk (default is dry-run inspection).+ #[arg(long)]+ pub apply: bool,+ /// Overwrite existing target files even if they differ.+ #[arg(long)]+ pub force: bool,+}+/// Arguments for `checkpoints`.#[derive(Debug, Args)]pub struct CheckpointsArgs {diff --git a/crates/ai-memory-cli/src/commands/backup_agents.rs b/crates/ai-memory-cli/src/commands/backup_agents.rsnew file mode 100644index 00000000..f904f6e9--- /dev/null+++ b/crates/ai-memory-cli/src/commands/backup_agents.rs@@ -0,0 +1,808 @@+//! `ai-memory backup-agents` — snapshot AI agent configurations,+//! skills, plugins, and instructions into a portable archive.++use std::fs::{self, File};+use std::io::Cursor;+use std::path::{Path, PathBuf};++use ai_memory_core::agent_backup::{+ AgentAssetKind, AgentAssetScope, AgentBackupEntry, AgentBackupManifest, HostInfo,+};+use ai_memory_core::ids::AgentKind;+use ai_memory_core::sanitize::{SanitizeConfig, Sanitizer};+use anyhow::{Context, Result};+use flate2::Compression;+use flate2::write::GzEncoder;+use sha2::{Digest, Sha256};+use tar::{Builder, Header};+use tracing::info;++use crate::cli::{AgentBackupScope, BackupAgentsArgs};+use crate::commands::path_util::{claude_config_dir, home_dir};+use crate::config::Config;++/// An asset candidate discovered on the host filesystem.+#[derive(Debug, Clone)]+pub struct DiscoveredAsset {+ /// Agent owning the asset.+ pub agent: AgentKind,+ /// Kind of asset.+ pub kind: AgentAssetKind,+ /// Global or project-scoped.+ pub scope: AgentAssetScope,+ /// Absolute path on host disk.+ pub source_path: PathBuf,+ /// Target path relative to destination root (home or cwd).+ pub target_relative: String,+ /// Archive destination path inside the tarball.+ pub archive_path: String,+}++/// Run the `backup-agents` subcommand.+///+/// # Errors+/// Returns an error if directory traversal fails, source files cannot be read,+/// or writing the output archive fails.+pub fn run(_config: &Config, args: BackupAgentsArgs) -> Result<()> {+ let home = home_dir().context("locating user home directory")?;+ let cwd = std::env::current_dir().context("locating current working directory")?;++ let discovered = discover_assets(&home, &cwd, &args)?;++ if discovered.is_empty() {+ println!("No AI agent assets detected for backup.");+ return Ok(());+ }++ if args.dry_run {+ print_dry_run(&discovered);+ return Ok(());+ }++ let dest = &args.to;+ if let Some(parent) = dest.parent()+ && !parent.as_os_str().is_empty()+ {+ fs::create_dir_all(parent)+ .with_context(|| format!("creating parent dir for {}", dest.display()))?;+ }++ let file = File::create(dest)+ .with_context(|| format!("creating output archive at {}", dest.display()))?;++ let count = build_archive(file, &discovered, args.include_secrets, &home)?;++ #[cfg(unix)]+ if args.include_secrets {+ use std::os::unix::fs::PermissionsExt;+ if let Ok(metadata) = fs::metadata(dest) {+ let mut perms = metadata.permissions();+ perms.set_mode(0o600);+ let _ = fs::set_permissions(dest, perms);+ }+ }++ let size = fs::metadata(dest).map(|m| m.len()).unwrap_or(0);+ info!(path = %dest.display(), bytes = size, count, "agent assets backup written");++ println!(+ "✓ Backed up {} agent assets to {} ({})",+ count,+ dest.display(),+ human_bytes(size)+ );++ if args.include_secrets {+ eprintln!(+ "⚠️ Warning: Secrets were included without sanitization. Archive permissions set to 0600."+ );+ }++ Ok(())+}++fn print_dry_run(discovered: &[DiscoveredAsset]) {+ println!(+ "Found {} assets across AI agents (dry-run):",+ discovered.len()+ );+ for asset in discovered {+ println!(+ " [{:?}] {:<12} {:<8} -> {}",+ asset.agent,+ asset.kind.label(),+ match asset.scope {+ AgentAssetScope::Global => "global",+ AgentAssetScope::Project => "project",+ },+ asset.source_path.display()+ );+ }+}++/// Discover agent assets based on configuration and scopes.+pub fn discover_assets(+ home: &Path,+ cwd: &Path,+ args: &BackupAgentsArgs,+) -> Result<Vec<DiscoveredAsset>> {+ let mut assets = Vec::new();+ let want_global = matches!(+ args.scope,+ AgentBackupScope::Global | AgentBackupScope::Both+ );+ let want_project = matches!(+ args.scope,+ AgentBackupScope::Project | AgentBackupScope::Both+ );++ let filter_agent = |agent: AgentKind| -> bool {+ let Some(filter) = &args.agents else {+ return true;+ };+ let agent_str = format!("{agent:?}").to_lowercase();+ filter.iter().any(|f| {+ let fl = f.trim().to_lowercase();+ agent_str.contains(&fl) || fl.contains(&agent_str)+ })+ };++ // 1. Claude Code / Desktop+ if filter_agent(AgentKind::ClaudeCode) {+ if want_global {+ let claude_dir = claude_config_dir(std::env::var_os("CLAUDE_CONFIG_DIR"))+ .unwrap_or_else(|| home.join(".claude"));+ // Global MCP / Settings+ push_if_file(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ claude_dir.join("settings.json"),+ ".claude/settings.json",+ "claude/mcp/settings.json",+ );+ push_if_file(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ home.join(".claude.json"),+ ".claude.json",+ "claude/mcp/claude.json",+ );+ // Global Skills+ collect_dir_assets(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &claude_dir.join("skills"),+ ".claude/skills",+ "claude/skills",+ )?;+ // Plugins+ collect_dir_assets(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::Plugin,+ AgentAssetScope::Global,+ &claude_dir.join("plugins"),+ ".claude/plugins",+ "claude/plugins",+ )?;+ }+ if want_project {+ // Project Skills+ collect_dir_assets(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::Skill,+ AgentAssetScope::Project,+ &cwd.join(".claude").join("skills"),+ ".claude/skills",+ "project/claude/skills",+ )?;+ // Project Instructions+ push_if_file(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ cwd.join("CLAUDE.md"),+ "CLAUDE.md",+ "project/CLAUDE.md",+ );+ }+ }++ // 2. OpenAI Codex CLI+ if filter_agent(AgentKind::Codex) {+ if want_global {+ let codex_dir = home.join(".codex");+ push_if_file(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ codex_dir.join("config.toml"),+ ".codex/config.toml",+ "codex/config.toml",+ );+ push_if_file(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ codex_dir.join("mcp.json"),+ ".codex/mcp.json",+ "codex/mcp.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &home.join(".agents").join("skills"),+ ".agents/skills",+ "codex/skills/agents",+ )?;+ collect_dir_assets(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &codex_dir.join("skills"),+ ".codex/skills",+ "codex/skills/codex",+ )?;+ collect_dir_assets(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::Plugin,+ AgentAssetScope::Global,+ &codex_dir.join("plugins"),+ ".codex/plugins",+ "codex/plugins",+ )?;+ }+ if want_project {+ collect_dir_assets(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::Skill,+ AgentAssetScope::Project,+ &cwd.join(".agents").join("skills"),+ ".agents/skills",+ "project/agents/skills",+ )?;+ push_if_file(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ cwd.join("AGENTS.md"),+ "AGENTS.md",+ "project/AGENTS.md",+ );+ }+ }++ // 3. Antigravity CLI / Gemini CLI+ if filter_agent(AgentKind::AntigravityCli) || filter_agent(AgentKind::GeminiCli) {+ if want_global {+ let gemini_dir = home.join(".gemini");+ push_if_file(+ &mut assets,+ AgentKind::AntigravityCli,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ gemini_dir.join("config").join("mcp_config.json"),+ ".gemini/config/mcp_config.json",+ "antigravity/mcp_config.json",+ );+ push_if_file(+ &mut assets,+ AgentKind::GeminiCli,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ gemini_dir.join("settings.json"),+ ".gemini/settings.json",+ "gemini/settings.json",+ );+ push_if_file(+ &mut assets,+ AgentKind::AntigravityCli,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ gemini_dir.join("antigravity-cli").join("mcp_config.json"),+ ".gemini/antigravity-cli/mcp_config.json",+ "antigravity/antigravity_mcp.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::AntigravityCli,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &gemini_dir.join("antigravity-cli").join("skills"),+ ".gemini/antigravity-cli/skills",+ "antigravity/skills",+ )?;+ collect_dir_assets(+ &mut assets,+ AgentKind::GeminiCli,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &gemini_dir.join("skills"),+ ".gemini/skills",+ "gemini/skills",+ )?;+ collect_dir_assets(+ &mut assets,+ AgentKind::AntigravityCli,+ AgentAssetKind::Plugin,+ AgentAssetScope::Global,+ &gemini_dir.join("antigravity-cli").join("plugins"),+ ".gemini/antigravity-cli/plugins",+ "antigravity/plugins",+ )?;+ }+ if want_project {+ collect_dir_assets(+ &mut assets,+ AgentKind::AntigravityCli,+ AgentAssetKind::Skill,+ AgentAssetScope::Project,+ &cwd.join(".gemini").join("skills"),+ ".gemini/skills",+ "project/gemini/skills",+ )?;+ push_if_file(+ &mut assets,+ AgentKind::GeminiCli,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ cwd.join("GEMINI.md"),+ "GEMINI.md",+ "project/GEMINI.md",+ );+ }+ }++ // 4. Cursor+ if filter_agent(AgentKind::Cursor) {+ if want_global {+ push_if_file(+ &mut assets,+ AgentKind::Cursor,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ home.join(".cursor").join("mcp.json"),+ ".cursor/mcp.json",+ "cursor/mcp.json",+ );+ }+ if want_project {+ push_if_file(+ &mut assets,+ AgentKind::Cursor,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Project,+ cwd.join(".cursor").join("mcp.json"),+ ".cursor/mcp.json",+ "project/cursor/mcp.json",+ );+ push_if_file(+ &mut assets,+ AgentKind::Cursor,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ cwd.join(".cursorrules"),+ ".cursorrules",+ "project/cursor/.cursorrules",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::Cursor,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ &cwd.join(".cursor").join("rules"),+ ".cursor/rules",+ "project/cursor/rules",+ )?;+ }+ }++ // 5. OpenCode (v1 / v2)+ if filter_agent(AgentKind::OpenCode) {+ if want_global {+ let opencode_dir = home.join(".config").join("opencode");+ push_if_file(+ &mut assets,+ AgentKind::OpenCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ opencode_dir.join("opencode.json"),+ ".config/opencode/opencode.json",+ "opencode/opencode.json",+ );+ push_if_file(+ &mut assets,+ AgentKind::OpenCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ opencode_dir.join("opencode.jsonc"),+ ".config/opencode/opencode.jsonc",+ "opencode/opencode.jsonc",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::OpenCode,+ AgentAssetKind::Plugin,+ AgentAssetScope::Global,+ &opencode_dir.join("plugins"),+ ".config/opencode/plugins",+ "opencode/plugins",+ )?;+ }+ if want_project {+ push_if_file(+ &mut assets,+ AgentKind::OpenCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Project,+ cwd.join("opencode.json"),+ "opencode.json",+ "project/opencode/opencode.json",+ );+ push_if_file(+ &mut assets,+ AgentKind::OpenCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Project,+ cwd.join("opencode.jsonc"),+ "opencode.jsonc",+ "project/opencode/opencode.jsonc",+ );+ }+ }++ // 6. Devin+ if filter_agent(AgentKind::Devin) {+ if want_global {+ let devin_dir = home.join(".devin");+ push_if_file(+ &mut assets,+ AgentKind::Devin,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ devin_dir.join("config.json"),+ ".devin/config.json",+ "devin/config.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::Devin,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &devin_dir.join("skills"),+ ".devin/skills",+ "devin/skills",+ )?;+ }+ if want_project {+ collect_dir_assets(+ &mut assets,+ AgentKind::Devin,+ AgentAssetKind::Skill,+ AgentAssetScope::Project,+ &cwd.join(".devin").join("skills"),+ ".devin/skills",+ "project/devin/skills",+ )?;+ }+ }++ // 7. Grok+ if filter_agent(AgentKind::Grok) {+ if want_global {+ let grok_dir = home.join(".grok");+ push_if_file(+ &mut assets,+ AgentKind::Grok,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ grok_dir.join("config.toml"),+ ".grok/config.toml",+ "grok/config.toml",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::Grok,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &grok_dir.join("skills"),+ ".grok/skills",+ "grok/skills",+ )?;+ }+ if want_project {+ push_if_file(+ &mut assets,+ AgentKind::Grok,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Project,+ cwd.join(".grok").join("config.toml"),+ ".grok/config.toml",+ "project/grok/config.toml",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::Grok,+ AgentAssetKind::Skill,+ AgentAssetScope::Project,+ &cwd.join(".grok").join("skills"),+ ".grok/skills",+ "project/grok/skills",+ )?;+ }+ }++ // 8. Kiro CLI+ if filter_agent(AgentKind::KiroCli) && want_global {+ let kiro_dir = home.join(".kiro");+ push_if_file(+ &mut assets,+ AgentKind::KiroCli,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ kiro_dir.join("settings").join("mcp.json"),+ ".kiro/settings/mcp.json",+ "kiro/mcp.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::KiroCli,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &kiro_dir.join("agents"),+ ".kiro/agents",+ "kiro/agents",+ )?;+ }++ // 9. OpenClaw+ if filter_agent(AgentKind::OpenClaw) && want_global {+ let openclaw_dir = home.join(".openclaw");+ push_if_file(+ &mut assets,+ AgentKind::OpenClaw,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ openclaw_dir.join("config.json"),+ ".openclaw/config.json",+ "openclaw/config.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::OpenClaw,+ AgentAssetKind::Plugin,+ AgentAssetScope::Global,+ &openclaw_dir.join("extensions"),+ ".openclaw/extensions",+ "openclaw/extensions",+ )?;+ }++ // 10. Command Code+ if filter_agent(AgentKind::CommandCode) && want_global {+ let cmdc_dir = home.join(".commandcode");+ push_if_file(+ &mut assets,+ AgentKind::CommandCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ cmdc_dir.join("mcp.json"),+ ".commandcode/mcp.json",+ "commandcode/mcp.json",+ );+ }++ // 11. VS Code / Copilot+ if want_project {+ push_if_file(+ &mut assets,+ AgentKind::Other,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Project,+ cwd.join(".vscode").join("mcp.json"),+ ".vscode/mcp.json",+ "project/vscode/mcp.json",+ );+ }++ Ok(assets)+}++fn push_if_file(+ assets: &mut Vec<DiscoveredAsset>,+ agent: AgentKind,+ kind: AgentAssetKind,+ scope: AgentAssetScope,+ source: PathBuf,+ target_relative: &str,+ archive_path: &str,+) {+ if source.is_file() {+ assets.push(DiscoveredAsset {+ agent,+ kind,+ scope,+ source_path: source,+ target_relative: target_relative.to_string(),+ archive_path: archive_path.to_string(),+ });+ }+}++fn collect_dir_assets(+ assets: &mut Vec<DiscoveredAsset>,+ agent: AgentKind,+ kind: AgentAssetKind,+ scope: AgentAssetScope,+ dir: &Path,+ target_prefix: &str,+ archive_prefix: &str,+) -> Result<()> {+ if !dir.is_dir() {+ return Ok(());+ }+ for entry in fs::read_dir(dir)? {+ let entry = entry?;+ let path = entry.path();+ let file_type = entry.file_type()?;+ if file_type.is_dir() {+ let dir_name = entry.file_name();+ let dir_name_str = dir_name.to_string_lossy();+ if dir_name_str.starts_with('.')+ || dir_name_str == "cache"+ || dir_name_str == "node_modules"+ || dir_name_str == "target"+ || dir_name_str == "venv"+ || dir_name_str == "__pycache__"+ || dir_name_str == "site-packages"+ {+ continue;+ }+ let sub_target = format!("{target_prefix}/{dir_name_str}");+ let sub_archive = format!("{archive_prefix}/{dir_name_str}");+ collect_dir_assets(assets, agent, kind, scope, &path, &sub_target, &sub_archive)?;+ } else if file_type.is_file() {+ let file_name = entry.file_name();+ let file_name_str = file_name.to_string_lossy();+ if file_name_str == ".DS_Store"+ || file_name_str.ends_with(".pyc")+ || file_name_str.ends_with(".pyo")+ {+ continue;+ }+ let target_rel = format!("{target_prefix}/{file_name_str}");+ let archive_path = format!("{archive_prefix}/{file_name_str}");+ assets.push(DiscoveredAsset {+ agent,+ kind,+ scope,+ source_path: path,+ target_relative: target_rel,+ archive_path,+ });+ }+ }+ Ok(())+}++fn build_archive(+ output_file: File,+ discovered: &[DiscoveredAsset],+ include_secrets: bool,+ home: &Path,+) -> Result<usize> {+ let encoder = GzEncoder::new(output_file, Compression::default());+ let mut tar = Builder::new(encoder);+ tar.mode(tar::HeaderMode::Deterministic);+ tar.follow_symlinks(false);++ let sanitizer = if include_secrets {+ None+ } else {+ Some(Sanitizer::new(&SanitizeConfig::default())?)+ };++ let mut entries = Vec::with_capacity(discovered.len());++ for asset in discovered {+ let raw_bytes = fs::read(&asset.source_path)+ .with_context(|| format!("reading {}", asset.source_path.display()))?;++ let (final_bytes, is_sanitized) = if let Some(ref sc) = sanitizer+ && matches!(asset.kind, AgentAssetKind::McpConfig)+ {+ if let Ok(text) = std::str::from_utf8(&raw_bytes) {+ let sanitized_text = sc.scrub(text);+ let changed = sanitized_text != text;+ (sanitized_text.into_bytes(), changed)+ } else {+ (raw_bytes, false)+ }+ } else {+ (raw_bytes, false)+ };++ let mut hasher = Sha256::new();+ hasher.update(&final_bytes);+ let sha256 = format!("{:x}", hasher.finalize());++ let mut header = Header::new_gnu();+ header.set_size(final_bytes.len() as u64);+ header.set_mode(0o644);+ header.set_mtime(0);+ header.set_cksum();++ tar.append_data(&mut header, &asset.archive_path, Cursor::new(&final_bytes))+ .with_context(|| format!("archiving {}", asset.archive_path))?;++ entries.push(AgentBackupEntry {+ agent: asset.agent,+ asset_kind: asset.kind,+ scope: asset.scope,+ archive_path: asset.archive_path.clone(),+ target_relative: asset.target_relative.clone(),+ sanitized: is_sanitized,+ sha256: Some(sha256),+ });+ }++ let manifest = AgentBackupManifest::new(+ HostInfo {+ os: std::env::consts::OS.to_string(),+ arch: std::env::consts::ARCH.to_string(),+ home_dir: Some(home.display().to_string()),+ },+ !include_secrets,+ entries,+ );++ let manifest_bytes =+ serde_json::to_vec_pretty(&manifest).context("serializing agent backup manifest")?;++ let mut manifest_header = Header::new_gnu();+ manifest_header.set_size(manifest_bytes.len() as u64);+ manifest_header.set_mode(0o644);+ manifest_header.set_mtime(0);+ manifest_header.set_cksum();++ tar.append_data(+ &mut manifest_header,+ "manifest.json",+ Cursor::new(&manifest_bytes),+ )+ .context("archiving manifest.json")?;++ tar.finish().context("finalising tar archive")?;+ Ok(discovered.len())+}++fn human_bytes(n: u64) -> String {+ const UNITS: &[&str] = &["B", "KiB", "MiB", "GiB"];+ let mut value = n as f64;+ let mut unit = 0;+ while value >= 1024.0 && unit + 1 < UNITS.len() {+ value /= 1024.0;+ unit += 1;+ }+ if unit == 0 {+ format!("{n} {}", UNITS[0])+ } else {+ format!("{value:.2} {}", UNITS[unit])+ }+}diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 9e8b352a..3054846c 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 auto_improve;pub mod auto_improve_report;pub mod backfill;pub mod backup;+pub mod backup_agents;pub mod bootstrap;pub mod checkpoints;pub mod commit;@@ -74,6 +75,7 @@ pub mod render_shared;pub mod reorg;pub mod reset;pub mod restore;+pub mod restore_agents;pub mod restore_page;pub mod resume;pub mod run;diff --git a/crates/ai-memory-cli/src/commands/restore_agents.rs b/crates/ai-memory-cli/src/commands/restore_agents.rsnew file mode 100644index 00000000..1c03a63d--- /dev/null+++ b/crates/ai-memory-cli/src/commands/restore_agents.rs@@ -0,0 +1,220 @@+//! `ai-memory restore-agents` — restore AI agent configurations,+//! skills, plugins, and instructions from an archive.++use std::collections::HashMap;+use std::fs::{self, File};+use std::io::Read;+use std::path::PathBuf;++use ai_memory_core::agent_backup::{+ AGENT_BACKUP_SCHEMA_VERSION, AgentAssetScope, AgentBackupManifest,+};+use anyhow::{Context, Result, bail};+use flate2::read::GzDecoder;+use tar::Archive;+use tracing::info;++use crate::cli::RestoreAgentsArgs;+use crate::commands::apply_shared::{ApplyOutcome, apply_atomic};+use crate::commands::path_util::home_dir;+use crate::config::Config;++/// Run the `restore-agents` subcommand.+///+/// # Errors+/// Returns an error if the archive cannot be read, contains path traversal,+/// has an unsupported schema version, or writes fail.+pub fn run(_config: &Config, args: RestoreAgentsArgs) -> Result<()> {+ let home = home_dir().context("locating user home directory")?;+ let cwd = std::env::current_dir().context("locating current working directory")?;++ let src = &args.from;+ if !src.is_file() {+ bail!("backup archive not found at {}", src.display());+ }++ let file = File::open(src).with_context(|| format!("opening archive at {}", src.display()))?;+ let tar = GzDecoder::new(file);+ let mut archive = Archive::new(tar);++ // Read all archive entries into memory keyed by archive_path+ let mut files_by_path: HashMap<String, Vec<u8>> = HashMap::new();+ let mut manifest_bytes: Option<Vec<u8>> = None;++ for entry in archive.entries()? {+ let mut entry = entry?;+ let path = entry.path()?.to_string_lossy().to_string();++ validate_archive_path(&path)?;++ let mut buf = Vec::new();+ entry.read_to_end(&mut buf)?;++ if path == "manifest.json" {+ manifest_bytes = Some(buf);+ } else {+ files_by_path.insert(path, buf);+ }+ }++ let Some(manifest_raw) = manifest_bytes else {+ bail!("archive at {} is missing manifest.json", src.display());+ };++ let manifest: AgentBackupManifest =+ serde_json::from_slice(&manifest_raw).context("parsing agent backup manifest")?;++ if manifest.version > AGENT_BACKUP_SCHEMA_VERSION {+ bail!(+ "archive manifest schema version {} is newer than supported version {}",+ manifest.version,+ AGENT_BACKUP_SCHEMA_VERSION+ );+ }++ let filter_agent = |agent_name: &str| -> bool {+ let Some(filter) = &args.agents else {+ return true;+ };+ let agent_str = agent_name.to_lowercase();+ filter.iter().any(|f| {+ let fl = f.trim().to_lowercase();+ agent_str.contains(&fl) || fl.contains(&agent_str)+ })+ };++ let mut planned = Vec::new();+ let mut identical_count = 0;++ for entry in &manifest.entries {+ let agent_name = format!("{:?}", entry.agent);+ if !filter_agent(&agent_name) {+ continue;+ }++ validate_archive_path(&entry.target_relative)?;++ let target_path = match entry.scope {+ AgentAssetScope::Global => home.join(&entry.target_relative),+ AgentAssetScope::Project => cwd.join(&entry.target_relative),+ };++ let Some(content) = files_by_path.get(&entry.archive_path) else {+ warn_missing_asset(&entry.archive_path);+ continue;+ };++ let exists = target_path.is_file();+ let is_identical = if exists {+ let existing_bytes = fs::read(&target_path)+ .with_context(|| format!("reading existing {}", target_path.display()))?;+ existing_bytes == *content+ } else {+ false+ };++ if is_identical {+ identical_count += 1;+ } else {+ planned.push((entry, target_path, content.clone(), exists));+ }+ }++ if planned.is_empty() && identical_count > 0 {+ println!(+ "✓ All {} assets are already identical on host. Nothing to restore.",+ identical_count+ );+ return Ok(());+ }++ if !args.apply {+ print_dry_run(&planned, identical_count);+ return Ok(());+ }++ let mut created = 0;+ let mut updated = 0;++ for (_entry, target_path, content, exists) in planned {+ if exists && !args.force {+ println!(+ " [SKIP] {} (already exists, pass --force to overwrite)",+ target_path.display()+ );+ continue;+ }++ if let Some(parent) = target_path.parent() {+ fs::create_dir_all(parent)+ .with_context(|| format!("creating parent dir {}", parent.display()))?;+ }++ let content_str = String::from_utf8_lossy(&content);+ let outcome = apply_atomic(&target_path, |_old| Ok(content_str.to_string()))?;++ match outcome {+ ApplyOutcome::Created => {+ println!(" ✓ created {}", target_path.display());+ created += 1;+ }+ ApplyOutcome::Updated => {+ println!(" ✓ updated {}", target_path.display());+ updated += 1;+ }+ ApplyOutcome::NoOp => {+ identical_count += 1;+ }+ }+ }++ info!(created, updated, identical_count, "restored agent assets");+ println!(+ "\n✓ Restoration complete: {} created, {} updated, {} unchanged.",+ created, updated, identical_count+ );++ Ok(())+}++fn print_dry_run(+ planned: &[(+ &ai_memory_core::agent_backup::AgentBackupEntry,+ PathBuf,+ Vec<u8>,+ bool,+ )],+ identical_count: usize,+) {+ println!("Restore preview (dry-run, pass --apply to execute):\n");+ for (entry, target_path, content, exists) in planned {+ let status = if *exists { "[OVERWRITE]" } else { "[CREATE]" };+ println!(+ " {status:<12} [{:?}] {} ({} bytes) -> {}",+ entry.agent,+ entry.asset_kind.label(),+ content.len(),+ target_path.display()+ );+ }+ if identical_count > 0 {+ println!("\n (skipped {identical_count} identical files)");+ }+ println!("\nRerun with `--apply` to perform restoration.");+}++fn validate_archive_path(path: &str) -> Result<()> {+ if path.contains("..")+ || path.starts_with('/')+ || path.starts_with('\\')+ || path.contains('\0')+ || (path.len() >= 2 && path.as_bytes()[1] == b':')+ {+ bail!("malformed or dangerous archive path: {:?}", path);+ }+ Ok(())+}++fn warn_missing_asset(path: &str) {+ tracing::warn!(path, "manifest referenced asset missing from archive body");+}diff --git a/crates/ai-memory-cli/src/lib.rs b/crates/ai-memory-cli/src/lib.rsindex 187ffb29..44774ff9 100644--- a/crates/ai-memory-cli/src/lib.rs+++ b/crates/ai-memory-cli/src/lib.rs@@ -134,8 +134,10 @@ pub async fn run() -> Result<()> {commands::reclaim_ledger_versions::run(&config, args).await}Command::Backup(args) => commands::backup::run(&config, args).await,+ Command::BackupAgents(args) => commands::backup_agents::run(&config, args),Command::ExportOkf(args) => commands::export_okf::run(&config, args).await,Command::Restore(args) => commands::restore::run(&config, args),+ Command::RestoreAgents(args) => commands::restore_agents::run(&config, args),Command::Reindex(args) => commands::reindex::run(&config, args).await,Command::InstallHooks(args) => commands::install_hooks::run(&config, args),// `Hook` is handled in the fast-path above (before config/tracing).diff --git a/crates/ai-memory-cli/tests/suite/backup_agents.rs b/crates/ai-memory-cli/tests/suite/backup_agents.rsnew file mode 100644index 00000000..94c61884--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/backup_agents.rs@@ -0,0 +1,324 @@+//! Integration tests for `ai-memory backup-agents` and `ai-memory restore-agents`.++use std::fs;+use std::path::Path;+use std::process::Command;+use std::sync::{Mutex, MutexGuard};++static CLI_TEST_LOCK: Mutex<()> = Mutex::new(());++fn cli_test_lock() -> MutexGuard<'static, ()> {+ CLI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner())+}++fn bin() -> &'static str {+ env!("CARGO_BIN_EXE_ai-memory")+}++fn command_with_env(home: &Path, cwd: &Path) -> Command {+ let mut command = Command::new(bin());+ let config_home = home.join(".config");+ let data_home = home.join(".local/share");+ for dir in [&config_home, &data_home] {+ fs::create_dir_all(dir).unwrap();+ }+ command+ .current_dir(cwd)+ .env("HOME", home)+ .env("USERPROFILE", home)+ .env("XDG_CONFIG_HOME", config_home)+ .env("XDG_DATA_HOME", data_home)+ .env("AI_MEMORY_HOME", home)+ .env("AI_MEMORY_DATA_DIR", home.join(".ai-memory-data"))+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")+ .env_remove("AI_MEMORY_SERVER_URL")+ .env_remove("AI_MEMORY_AUTH_TOKEN")+ .env_remove("CLAUDE_CONFIG_DIR")+ .env_remove("KIMI_CODE_HOME")+ .env_remove("KIRO_HOME");+ command+}++#[test]+fn backup_and_restore_agents_round_trip() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ // 1. Setup mock agent assets+ // Claude+ let claude_settings = home.path().join(".claude/settings.json");+ fs::create_dir_all(claude_settings.parent().unwrap()).unwrap();+ fs::write(+ &claude_settings,+ r#"{"mcpServers":{"local":{"command":"test"}}}"#,+ )+ .unwrap();++ let claude_skill = home.path().join(".claude/skills/test-skill/SKILL.md");+ fs::create_dir_all(claude_skill.parent().unwrap()).unwrap();+ fs::write(&claude_skill, "# Claude Skill\nDetails here").unwrap();++ let claude_md = project.path().join("CLAUDE.md");+ fs::write(&claude_md, "# Project Instructions\nClaude rules").unwrap();++ // Codex+ let codex_config = home.path().join(".codex/config.toml");+ fs::create_dir_all(codex_config.parent().unwrap()).unwrap();+ fs::write(+ &codex_config,+ "[mcp_servers.demo]\nurl = \"http://localhost\"\n",+ )+ .unwrap();++ let agents_md = project.path().join("AGENTS.md");+ fs::write(&agents_md, "# Project Rules\nCodex rules").unwrap();++ // Antigravity / Gemini+ let agy_mcp = home.path().join(".gemini/config/mcp_config.json");+ fs::create_dir_all(agy_mcp.parent().unwrap()).unwrap();+ fs::write(+ &agy_mcp,+ r#"{"mcpServers":{"agy":{"url":"http://127.0.0.1"}}}"#,+ )+ .unwrap();++ let backup_tar = project.path().join("backup.tar.gz");++ // 2. Run backup-agents+ let output = command_with_env(home.path(), project.path())+ .args([+ "backup-agents",+ "-o",+ backup_tar.to_str().unwrap(),+ "--include-secrets",+ ])+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "backup-agents failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(backup_tar.exists(), "backup tarball was not created");++ // 3. Restore into clean sandbox+ let restore_home = tempfile::tempdir().unwrap();+ let restore_project = tempfile::tempdir().unwrap();++ // Dry-run first+ let dry_run = command_with_env(restore_home.path(), restore_project.path())+ .args(["restore-agents", "-i", backup_tar.to_str().unwrap()])+ .output()+ .unwrap();+ assert!(dry_run.status.success());+ let dry_stdout = String::from_utf8_lossy(&dry_run.stdout);+ assert!(dry_stdout.contains("[CREATE]"));+ assert!(!restore_home.path().join(".claude/settings.json").exists());++ // Apply restore+ let restore = command_with_env(restore_home.path(), restore_project.path())+ .args([+ "restore-agents",+ "-i",+ backup_tar.to_str().unwrap(),+ "--apply",+ ])+ .output()+ .unwrap();+ assert!(+ restore.status.success(),+ "restore-agents failed: {}",+ String::from_utf8_lossy(&restore.stderr)+ );++ // Verify restored assets+ let restored_claude =+ fs::read_to_string(restore_home.path().join(".claude/settings.json")).unwrap();+ assert_eq!(+ restored_claude,+ r#"{"mcpServers":{"local":{"command":"test"}}}"#+ );++ let restored_skill = fs::read_to_string(+ restore_home+ .path()+ .join(".claude/skills/test-skill/SKILL.md"),+ )+ .unwrap();+ assert_eq!(restored_skill, "# Claude Skill\nDetails here");++ let restored_claude_md = fs::read_to_string(restore_project.path().join("CLAUDE.md")).unwrap();+ assert_eq!(restored_claude_md, "# Project Instructions\nClaude rules");++ let restored_codex =+ fs::read_to_string(restore_home.path().join(".codex/config.toml")).unwrap();+ assert_eq!(+ restored_codex,+ "[mcp_servers.demo]\nurl = \"http://localhost\"\n"+ );++ let restored_agents_md = fs::read_to_string(restore_project.path().join("AGENTS.md")).unwrap();+ assert_eq!(restored_agents_md, "# Project Rules\nCodex rules");++ let restored_agy =+ fs::read_to_string(restore_home.path().join(".gemini/config/mcp_config.json")).unwrap();+ assert_eq!(+ restored_agy,+ r#"{"mcpServers":{"agy":{"url":"http://127.0.0.1"}}}"#+ );+}++#[test]+fn backup_agents_sanitizes_secrets_by_default() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ let claude_settings = home.path().join(".claude/settings.json");+ fs::create_dir_all(claude_settings.parent().unwrap()).unwrap();+ fs::write(+ &claude_settings,+ r#"{"mcpServers":{"remote":{"env":{"GITHUB_TOKEN":"ghp_1234567890abcdef1234567890abcdef1234"}}}}"#,+ )+ .unwrap();++ let backup_tar = project.path().join("sanitized.tar.gz");++ let output = command_with_env(home.path(), project.path())+ .args(["backup-agents", "-o", backup_tar.to_str().unwrap()])+ .output()+ .unwrap();++ assert!(output.status.success());++ // Restore to clean sandbox+ let restore_home = tempfile::tempdir().unwrap();+ let restore_project = tempfile::tempdir().unwrap();++ let restore = command_with_env(restore_home.path(), restore_project.path())+ .args([+ "restore-agents",+ "-i",+ backup_tar.to_str().unwrap(),+ "--apply",+ ])+ .output()+ .unwrap();+ assert!(restore.status.success());++ let restored = fs::read_to_string(restore_home.path().join(".claude/settings.json")).unwrap();+ assert!(+ !restored.contains("ghp_1234567890abcdef1234567890abcdef1234"),+ "raw secret token must be redacted"+ );+ assert!(+ restored.contains("[REDACTED:"),+ "must contain redaction label, got: {restored}"+ );+}++#[test]+fn restore_agents_filters_by_agent_name() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ let claude_settings = home.path().join(".claude/settings.json");+ fs::create_dir_all(claude_settings.parent().unwrap()).unwrap();+ fs::write(&claude_settings, r#"{"mcpServers":{"claude":{}}}"#).unwrap();++ let codex_config = home.path().join(".codex/config.toml");+ fs::create_dir_all(codex_config.parent().unwrap()).unwrap();+ fs::write(&codex_config, "[mcp_servers.codex]\n").unwrap();++ let backup_tar = project.path().join("multi_agent.tar.gz");++ let backup_res = command_with_env(home.path(), project.path())+ .args(["backup-agents", "-o", backup_tar.to_str().unwrap()])+ .output()+ .unwrap();+ assert!(backup_res.status.success());++ // Restore ONLY claude+ let restore_home = tempfile::tempdir().unwrap();+ let restore_project = tempfile::tempdir().unwrap();++ let restore_res = command_with_env(restore_home.path(), restore_project.path())+ .args([+ "restore-agents",+ "-i",+ backup_tar.to_str().unwrap(),+ "--agents",+ "claude",+ "--apply",+ ])+ .output()+ .unwrap();+ assert!(restore_res.status.success());++ // Claude restored, Codex NOT restored+ assert!(restore_home.path().join(".claude/settings.json").exists());+ assert!(!restore_home.path().join(".codex/config.toml").exists());+}++#[test]+fn restore_agents_rejects_path_traversal() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ let evil_tar = project.path().join("evil.tar.gz");+ {+ let file = std::fs::File::create(&evil_tar).unwrap();+ let enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());+ let mut tar = tar::Builder::new(enc);++ let manifest = r#"{+ "version": 1,+ "created_at": "2026-09-28T00:00:00Z",+ "host": { "os": "macos", "arch": "aarch64" },+ "sanitized": true,+ "entries": [{+ "agent": "claude-code",+ "asset_kind": "mcp-config",+ "scope": "global",+ "archive_path": "evil.txt",+ "target_relative": "../../../etc/passwd"+ }]+ }"#;++ let mut h_m = tar::Header::new_gnu();+ h_m.set_size(manifest.len() as u64);+ h_m.set_cksum();+ tar.append_data(&mut h_m, "manifest.json", std::io::Cursor::new(manifest))+ .unwrap();++ let evil_body = "malicious payload";+ let mut h_b = tar::Header::new_gnu();+ h_b.set_size(evil_body.len() as u64);+ h_b.set_cksum();+ tar.append_data(&mut h_b, "evil.txt", std::io::Cursor::new(evil_body))+ .unwrap();++ tar.finish().unwrap();+ }++ let restore = command_with_env(home.path(), project.path())+ .args([+ "restore-agents",+ "-i",+ evil_tar.to_str().unwrap(),+ "--apply",+ ])+ .output()+ .unwrap();++ assert!(+ !restore.status.success(),+ "must fail on path traversal payload"+ );+ let err = String::from_utf8_lossy(&restore.stderr);+ assert!(err.contains("dangerous") || err.contains("traversal") || err.contains("malformed"));+}diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex 0e72cf45..00b50239 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -9,6 +9,7 @@ mod autoscope_env;mod backfill_dry_run;mod backfill_e2e;mod backfill_failures;+mod backup_agents;mod completions;mod doctor_e2e;mod e2e_support;diff --git a/crates/ai-memory-core/src/agent_backup.rs b/crates/ai-memory-core/src/agent_backup.rsnew file mode 100644index 00000000..6482f34d--- /dev/null+++ b/crates/ai-memory-core/src/agent_backup.rs@@ -0,0 +1,107 @@+//! Domain types for backing up and restoring AI agent assets (skills, MCP configs, plugins, instructions).++use serde::{Deserialize, Serialize};++use crate::ids::AgentKind;++/// Current version of the agent backup archive manifest schema.+pub const AGENT_BACKUP_SCHEMA_VERSION: u32 = 1;++/// Classification of an asset used by an AI agent.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum AgentAssetKind {+ /// MCP server configuration file (e.g. `settings.json`, `config.toml`, `mcp.json`).+ McpConfig,+ /// Agent skill file (e.g. `SKILL.md`).+ Skill,+ /// Agent plugin or extension asset.+ Plugin,+ /// Canonical project or agent instruction file (e.g. `CLAUDE.md`, `AGENTS.md`, `.cursorrules`).+ Instruction,+}++impl AgentAssetKind {+ /// Human-readable label for CLI reports.+ #[must_use]+ pub const fn label(self) -> &'static str {+ match self {+ Self::McpConfig => "MCP config",+ Self::Skill => "Skill",+ Self::Plugin => "Plugin",+ Self::Instruction => "Instruction",+ }+ }+}++/// Scope of the asset: global (user home / system) or project-specific.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum AgentAssetScope {+ /// Global asset stored in the user profile (e.g. `~/.claude/settings.json`, `~/.agents/skills/`).+ Global,+ /// Project-scoped asset stored in the working repository (e.g. `.claude/skills/`, `CLAUDE.md`).+ Project,+}++/// Metadata describing host environment where the backup was captured.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct HostInfo {+ /// Operating system name (e.g. "macos", "linux", "windows").+ pub os: String,+ /// Architecture (e.g. "aarch64", "x86_64").+ pub arch: String,+ /// Sanitized user home directory representation if recorded.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub home_dir: Option<String>,+}++/// A single backed-up asset entry inside the archive.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct AgentBackupEntry {+ /// AI agent harness associated with this asset.+ pub agent: AgentKind,+ /// Type of the asset (MCP config, skill, plugin, instruction).+ pub asset_kind: AgentAssetKind,+ /// Asset scope (global vs project).+ pub scope: AgentAssetScope,+ /// Relative path inside the tarball archive (e.g. `agents/claude-code/mcp/settings.json`).+ pub archive_path: String,+ /// Path relative to the destination base (e.g. home_dir for Global, project root for Project).+ pub target_relative: String,+ /// Whether this entry was sanitized to remove secrets/tokens.+ #[serde(default)]+ pub sanitized: bool,+ /// SHA-256 hash of the content for integrity verification.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub sha256: Option<String>,+}++/// Root manifest stored at `manifest.json` in the backup archive.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct AgentBackupManifest {+ /// Schema version number.+ pub version: u32,+ /// ISO 8601 creation timestamp.+ pub created_at: String,+ /// Information about host where backup was produced.+ pub host: HostInfo,+ /// Whether any entries were sanitized.+ pub sanitized: bool,+ /// List of backed-up asset entries.+ pub entries: Vec<AgentBackupEntry>,+}++impl AgentBackupManifest {+ /// Create a new manifest with default version and given entries.+ #[must_use]+ pub fn new(host: HostInfo, sanitized: bool, entries: Vec<AgentBackupEntry>) -> Self {+ Self {+ version: AGENT_BACKUP_SCHEMA_VERSION,+ created_at: jiff::Timestamp::now().to_string(),+ host,+ sanitized,+ entries,+ }+ }+}diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 038855a9..a0070f2c 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -7,6 +7,7 @@pub mod active_project;pub mod actor;+pub mod agent_backup;pub mod error;pub mod handoff;pub mod ingest_metrics;@@ -51,6 +52,10 @@ pub use actor::{SKIP_ADMISSION_CHAIN_HEADER, owner_identity, owner_stamp, parse_skip_admission_chain,skip_admission_chain_for,};+pub use agent_backup::{+ AGENT_BACKUP_SCHEMA_VERSION, AgentAssetKind, AgentAssetScope, AgentBackupEntry,+ AgentBackupManifest, HostInfo,+};pub use error::{MemoryError, MemoryResult};pub use handoff::{Handoff, HandoffAcceptance, HandoffContent, HandoffLifecycle, HandoffOrigin, HandoffScope,diff --git a/docs/design-backup-agent-assets.md b/docs/design-backup-agent-assets.mdnew file mode 100644index 00000000..4f50c3bf--- /dev/null+++ b/docs/design-backup-agent-assets.md@@ -0,0 +1,127 @@+# Design Proposal: Backup and Restore of AI Agent Assets (Skills, MCP, Plugins)++## 1. Context and Motivation++`ai-memory` coordinates memory and context across AI coding agents (Claude Code, OpenAI Codex, Antigravity CLI, Gemini CLI, Cursor, OpenCode, Devin, Grok, Kiro, etc.).++Currently:+- **Server Backup:** `ai-memory backup` takes a snapshot of the server's SQLite database (`memory.sqlite`), git wiki (`wiki/`), and `config.toml` via `POST /admin/backup`.+- **Client Configuration Knowledge:** `ai-memory` installers (`install_mcp.rs`, `install_skills.rs`, `install_hooks.rs`, `uninstall.rs`) already have detailed definitions of where each supported AI harness stores MCP servers, skills, plugins, and project instructions.+- **Gap:** There is no command to snapshot, export, backup, or restore the host agent configurations (MCP servers, agent skills, plugins, instructions). When moving to a new machine or backing up a development environment, developers must reconfigure every agent manually.++---++## 2. Target Matrix by Agent Harness++| Harness | MCP Configuration | Skills (Global / Project) | Plugins / Extensions | Instructions / Rules |+| :--- | :--- | :--- | :--- | :--- |+| **Claude Code / Desktop** | `~/.claude.json`<br>`~/.claude/settings.json`<br>`claude_desktop_config.json` | `~/.claude/skills/`<br>`.claude/skills/` | `~/.claude/plugins/`<br>`Claude Extensions/` | `CLAUDE.md` |+| **OpenAI Codex CLI** | `~/.codex/config.toml`<br>`~/.codex/mcp.json` | `~/.agents/skills/`<br>`.agents/skills/`<br>`~/.codex/skills/` | `~/.codex/plugins/` | `AGENTS.md` |+| **Antigravity CLI (`agy`) / Gemini** | `~/.gemini/settings.json`<br>`~/.gemini/config/mcp_config.json`<br>`antigravity-cli/mcp_config.json` | `~/.gemini/antigravity-cli/skills/`<br>`~/.gemini/skills/`<br>`.gemini/skills/` | `antigravity-cli/plugins/`<br>`~/.gemini/plugins/` | `GEMINI.md`<br>`AGENTS.md`<br>`rules/` |+| **Cursor IDE** | `~/.cursor/mcp.json`<br>`.cursor/mcp.json` | — | VS Code / Cursor extensions | `.cursorrules`<br>`.cursor/rules/` |+| **OpenCode (v1 / v2)** | `opencode.json`<br>`opencode.jsonc`<br>`~/.config/opencode/opencode.json` | `~/.config/opencode/skills/` | `~/.config/opencode/plugins/` | `AGENTS.md` |+| **Devin CLI** | `~/.devin/config.json` | `~/.devin/skills/` | — | Devin instructions |+| **Grok Build CLI** | `~/.grok/config.toml` | `~/.grok/skills/` | — | Grok instructions |+| **Kiro CLI (AWS)** | `~/.kiro/settings/mcp.json` | `~/.kiro/agents/*.json` | — | — |+| **OpenClaw** | `~/.openclaw/config.json` | — | `~/.openclaw/extensions/` | — |+| **VS Code Copilot** | `.vscode/mcp.json` | — | Extensions | Copilot instructions |++---++## 3. Architecture & CLI Design++### Dedicated Host CLI Subcommands: `backup-agents` and `restore-agents`++Host configurations live on the client filesystem, independent of whether the `ai-memory serve` daemon is running. Therefore, backup and restore of agent assets execute as client-side commands.++#### CLI Command Specification++```bash+# Backup all detected agents into an archive+ai-memory backup-agents -o agent-assets.tar.gz++# Filter specific agents or scopes+ai-memory backup-agents --agents claude,codex,antigravity --scope both -o backup.tar.gz++# Include raw secrets (warns loudly, sets 0600 file mode)+ai-memory backup-agents -o backup.tar.gz --include-secrets++# Dry-run inspection of an archive before restoring+ai-memory restore-agents -i backup.tar.gz --dry-run++# Apply restoration atomically+ai-memory restore-agents -i backup.tar.gz --apply+```++---++## 4. Archive Manifest Schema (`manifest.json`)++Stored in the root of the generated tarball:++```json+{+ "$schema": "https://ai-memory.dev/schemas/agent-backup-v1.json",+ "version": 1,+ "created_at": "2026-09-28T14:30:00Z",+ "host": {+ "os": "macos",+ "arch": "aarch64",+ "home_dir": "/Users/developer"+ },+ "sanitized": true,+ "entries": [+ {+ "agent": "claude-code",+ "asset_kind": "mcp-config",+ "scope": "global",+ "archive_path": "agents/claude-code/settings.json",+ "target_relative": ".claude/settings.json"+ },+ {+ "agent": "claude-code",+ "asset_kind": "skill",+ "scope": "global",+ "archive_path": "agents/claude-code/skills/custom-skill/SKILL.md",+ "target_relative": ".claude/skills/custom-skill/SKILL.md"+ },+ {+ "agent": "codex",+ "asset_kind": "mcp-config",+ "scope": "global",+ "archive_path": "agents/codex/config.toml",+ "target_relative": ".codex/config.toml"+ }+ ]+}+```++---++## 5. Security & Invariants++1. **Secret Redaction:**+ - By default, known tokens, bearer headers, and environment keys (`*_TOKEN`, `*_KEY`, `*_SECRET`) in MCP configs are sanitized using `ai-memory-hooks::sanitizer`.+ - Passing `--include-secrets` bypasses redaction; the resulting `.tar.gz` is created with `0600` permissions and a warning is logged.+2. **Symlink Safety:**+ - Archives do not traverse or include external symlinks (`follow_symlinks(false)`).+3. **Path Traversal Protection:**+ - Restoring validates that every target path resolves strictly inside the intended destination directory (`home_dir()` or project cwd).+4. **Atomic Restores:**+ - Target files are written using temporary files + rename + sync (`apply_atomic`), avoiding partial or corrupted configurations.+ - Non-managed custom files are never overwritten without explicit `--force`.++---++## 6. Implementation Stages++1. **`crates/ai-memory-core`**:+ - Add `agent_backup` module containing `AgentAssetKind`, `AgentAssetScope`, `AgentBackupEntry`, and `AgentBackupManifest`.+2. **`crates/ai-memory-cli`**:+ - `src/cli.rs`: Register `BackupAgents(BackupAgentsArgs)` and `RestoreAgents(RestoreAgentsArgs)`.+ - `src/commands/backup_agents.rs`: Scan host configs, package archive.+ - `src/commands/restore_agents.rs`: Validate manifest, present diffs, write files.+3. **Tests**:+ - Roundtrip tests: archive -> verify manifest -> extract into temporary directory -> assert equality.+ - Sanitization tests: ensure keys are redacted unless requested otherwise.+ - Security tests: reject path traversal payloads (`../../etc/passwd`).