Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(uninstall): make removal ownership checks conservative
AkitaOnRails6bef9bc5aefc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6ba9ddcf..299a8bda 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -107,7 +107,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0CLAUDE.md/AGENTS.md instruction block across all detected agents (dry-run bydefault; `--apply` to execute, with timestamped backups). `--purge-data`wipes wiki/db/raw via the reset guard. `--only hooks|mcp|instructions` to- narrow. Docker/volume teardown is printed as a hint, not executed.+ narrow. MCP matching is endpoint-based by default; pass `--mcp-url` when the+ server was installed with a custom endpoint and `--mcp-name` only to narrow+ removal to one matching entry. Docker/volume teardown is printed as a hint,+ not executed.### Changed- `ai-memory uninstall --purge-data` now previews the `wiki/`/`db/`/`raw/`@@ -115,6 +118,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`ai-memory` process is alive (all-or-nothing) instead of removing thewiring and then skipping the purge. The data wipe is now shared with`reset` via a single internal helper.+- `ai-memory uninstall` only deletes generated plugin/extension files after+ re-validating their ai-memory-generated content, and never treats a matching+ filename or MCP server name alone as proof of ownership.## [0.1.3] - 2026-05-24diff --git a/README.md b/README.mdindex ddcd1567..8232b155 100644--- a/README.md+++ b/README.md@@ -177,6 +177,12 @@ write. The hook scripts are staged intooverwrites them so future image updates ship updated hooks. Drop`--apply` to print the snippet instead of mutating.+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.+### Install Notes- **Windows:** use the Linux path inside WSL2, or the native PowerShelldiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex f69647d0..2d3884a5 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -120,6 +120,15 @@ pub struct UninstallArgs {/// Limit to one concern. Omitted = hooks + mcp + instructions.#[arg(long, value_enum)]pub only: Option<UninstallOnly>,+ /// Optional MCP server entry-name filter. Uninstall never matches by name+ /// alone; when this is set, the entry must match both name and `--mcp-url`.+ #[arg(long = "mcp-name")]+ pub mcp_name: Option<String>,+ /// MCP endpoint URL used to identify ai-memory server entries. Defaults to+ /// the standard local endpoint; pass this when you installed with a custom+ /// `install-mcp --server-url`.+ #[arg(long = "mcp-url", visible_alias = "server-url", default_value_t = crate::config::DEFAULT_MCP_URL.to_string())]+ pub mcp_url: String,/// Skip the interactive confirmation when a TTY is attached.#[arg(long)]pub yes: bool,@@ -406,7 +415,7 @@ pub enum AgentChoice {/// hook-capable agents (Claude Code / Codex / OpenCode — same MCP/// surface, also covered by `install-hooks`) and the MCP-only/// clients researched in docs/mcp-install.md.-#[derive(Debug, Clone, Copy, clap::ValueEnum)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]pub enum McpClient {/// Anthropic Claude Code — `claude mcp add`.ClaudeCode,diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex b61b76ba..c7452759 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -61,6 +61,15 @@ pub(crate) fn gemini_settings_path() -> anyhow::Result<std::path::PathBuf> {.join("settings.json"))}+/// `~/.gemini/config/hooks.json` — Antigravity CLI lifecycle hooks.+pub(crate) fn antigravity_hooks_path() -> anyhow::Result<std::path::PathBuf> {+ Ok(dirs::home_dir()+ .context("could not locate $HOME for ~/.gemini/config/hooks.json")?+ .join(".gemini")+ .join("config")+ .join("hooks.json"))+}+/// `~/.config/opencode/plugins/ai-memory.ts` — OpenCode's plugin file.pub(crate) fn opencode_plugin_path() -> anyhow::Result<std::path::PathBuf> {Ok(dirs::home_dir()@@ -71,6 +80,16 @@ pub(crate) fn opencode_plugin_path() -> anyhow::Result<std::path::PathBuf> {.join("ai-memory.ts"))}+/// `~/.omp/agent/extensions/ai-memory.ts` — OMP lifecycle extension.+pub(crate) fn omp_extension_path() -> anyhow::Result<std::path::PathBuf> {+ Ok(dirs::home_dir()+ .context("could not locate $HOME for ~/.omp/agent/extensions")?+ .join(".omp")+ .join("agent")+ .join("extensions")+ .join("ai-memory.ts"))+}+/// Run the `install-hooks` subcommand.////// # Errors@@ -450,11 +469,7 @@ fn apply_to_antigravity_settings() -> Result<()> {let path = match &args.config_file {Some(p) => p.clone(),- None => dirs::home_dir()- .context("could not locate $HOME for ~/.gemini/config/hooks.json")?- .join(".gemini")- .join("config")- .join("hooks.json"),+ None => antigravity_hooks_path()?,};let staged = stage_hook_scripts(hooks_dir, "antigravity-cli")?;let command_dir = staged_command_dir(&staged, "antigravity-cli");@@ -830,12 +845,7 @@ fn resolve_omp_extension_path(args: &InstallHooksArgs) -> Result<PathBuf> {if let Some(p) = &args.config_file {return Ok(p.clone());}- Ok(dirs::home_dir()- .context("could not locate $HOME for ~/.omp/agent/extensions")?- .join(".omp")- .join("agent")- .join("extensions")- .join("ai-memory.ts"))+ omp_extension_path()}fn build_omp_extension(server_url: &str, auth_token: Option<&str>) -> String {diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rsindex dec4174e..2d47c636 100644--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs@@ -10,11 +10,11 @@ use crate::cli::InstallHooksArgs;use crate::commands::apply_shared::{ApplyOutcome, apply_atomic};use crate::commands::render_shared::ts_string_literal;-const PLUGIN_ID: &str = "ai-memory";-const PACKAGE_NAME: &str = "@ai-memory/openclaw-plugin";-const PACKAGE_JSON: &str = "package.json";-const MANIFEST_JSON: &str = "openclaw.plugin.json";-const ENTRYPOINT_TS: &str = "index.ts";+pub(crate) const PLUGIN_ID: &str = "ai-memory";+pub(crate) const PACKAGE_NAME: &str = "@ai-memory/openclaw-plugin";+pub(crate) const PACKAGE_JSON: &str = "package.json";+pub(crate) const MANIFEST_JSON: &str = "openclaw.plugin.json";+pub(crate) const ENTRYPOINT_TS: &str = "index.ts";const OPENCLAW_BIN: &str = "openclaw";/// Write and install the generated OpenClaw plugin package.@@ -86,6 +86,10 @@ fn resolve_plugin_dir(args: &InstallHooksArgs) -> Result<PathBuf> {if let Some(path) = &args.config_file {return Ok(path.clone());}+ default_plugin_dir()+}++pub(crate) fn default_plugin_dir() -> Result<PathBuf> {Ok(dirs::data_local_dir().context("could not locate the user data-local directory")?.join("ai-memory")@@ -152,7 +156,7 @@ fn install_plugin(plugin_dir: &Path) -> Result<InstallStatus> {Ok(InstallStatus::Installed)}-fn package_json() -> String {+pub(crate) fn package_json() -> String {serde_json::to_string_pretty(&serde_json::json!({"name": PACKAGE_NAME,"version": env!("CARGO_PKG_VERSION"),@@ -166,7 +170,7 @@ fn package_json() -> String {+ "\n"}-fn manifest_json() -> String {+pub(crate) fn manifest_json() -> String {serde_json::to_string_pretty(&serde_json::json!({"id": PLUGIN_ID,"name": "ai-memory",diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex df64a63f..4e5ba45b 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -11,20 +11,94 @@ use crate::cli::UninstallArgs;use crate::commands::apply_shared::apply_atomic;use crate::commands::apply_shared::mutate_json;use crate::commands::apply_shared::mutate_toml;-use crate::commands::{data_purge, install_hooks, install_mcp};-use crate::config::{Config, DEFAULT_MCP_URL};+use crate::commands::{data_purge, install_hooks, install_mcp, openclaw_plugin};+use crate::config::Config;use ai_memory_core::{MARKER_END, MARKER_START};use anyhow::{Context, Result};use std::io::IsTerminal;-use std::path::PathBuf;+use std::path::{Path, PathBuf};++/// One rewrite operation to apply to a config file.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum RewriteOp {+ /// CLAUDE.md / AGENTS.md routing block.+ Instructions,+ /// Standard JSON hook table under `hooks`.+ HooksJson,+ /// Antigravity CLI named hook group under top-level `ai-memory`.+ AntigravityHooksJson,+ /// MCP JSON config for one client shape.+ McpJson(McpClient),+ /// Codex TOML MCP config.+ McpToml,+}++/// Generated files that uninstall may delete after content re-validation.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum DeleteKind {+ OpenCodePlugin,+ OmpExtension,+ OpenClawPackageJson,+ OpenClawManifest,+ OpenClawEntrypoint,+}++impl DeleteKind {+ const fn label(self) -> &'static str {+ match self {+ Self::OpenCodePlugin => "OpenCode plugin",+ Self::OmpExtension => "OMP extension",+ Self::OpenClawPackageJson => "OpenClaw package manifest",+ Self::OpenClawManifest => "OpenClaw plugin manifest",+ Self::OpenClawEntrypoint => "OpenClaw plugin entrypoint",+ }+ }+}/// One file the uninstall will touch, plus what it will do to it.#[derive(Debug)]enum PlannedChange {/// JSON/TOML rewrite removing the listed items (events or server names).- Rewrite { path: PathBuf, removed: Vec<String> },- /// Whole-file delete (OpenCode plugin).- DeleteFile { path: PathBuf },+ Rewrite {+ path: PathBuf,+ removed: Vec<String>,+ ops: Vec<RewriteOp>,+ },+ /// Whole-file delete, limited to generated files whose contents still+ /// prove they are ai-memory-owned at apply time.+ DeleteFile { path: PathBuf, kind: DeleteKind },+}++fn push_rewrite(plan: &mut Vec<PlannedChange>, path: PathBuf, removed: Vec<String>, op: RewriteOp) {+ if removed.is_empty() {+ return;+ }+ for change in plan.iter_mut() {+ if let PlannedChange::Rewrite {+ path: existing,+ removed: existing_removed,+ ops,+ } = change+ && *existing == path+ {+ existing_removed.extend(removed);+ if !ops.contains(&op) {+ ops.push(op);+ }+ return;+ }+ }+ plan.push(PlannedChange::Rewrite {+ path,+ removed,+ ops: vec![op],+ });+}++fn push_generated_delete(plan: &mut Vec<PlannedChange>, path: PathBuf, kind: DeleteKind) {+ if generated_file_is_ours(&path, kind) {+ plan.push(PlannedChange::DeleteFile { path, kind });+ }}/// Build the full removal plan by reading each existing config file and@@ -33,8 +107,8 @@ enum PlannedChange {fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {let mut plan = Vec::new();let want = |k: crate::cli::UninstallOnly| args.only.is_none() || args.only == Some(k);- let name = "ai-memory";- let url = DEFAULT_MCP_URL;+ let name = args.mcp_name.as_deref();+ let url = args.mcp_url.as_str();// ---- Hooks (JSON configs) ----if want(crate::cli::UninstallOnly::Hooks) {@@ -51,17 +125,49 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {let content = std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;let removal = strip_ai_memory_hooks(&content)?;- if !removal.removed_events.is_empty() {- plan.push(PlannedChange::Rewrite {- path,- removed: removal.removed_events,- });- }+ push_rewrite(+ &mut plan,+ path,+ removal.removed_events,+ RewriteOp::HooksJson,+ );}- let plugin = install_hooks::opencode_plugin_path()?;- if plugin.exists() {- plan.push(PlannedChange::DeleteFile { path: plugin });++ let antigravity = install_hooks::antigravity_hooks_path()?;+ if antigravity.exists() {+ let content = std::fs::read_to_string(&antigravity)+ .with_context(|| format!("reading {}", antigravity.display()))?;+ let removal = strip_antigravity_hooks(&content)?;+ push_rewrite(+ &mut plan,+ antigravity,+ removal.removed_events,+ RewriteOp::AntigravityHooksJson,+ );}++ let plugin = install_hooks::opencode_plugin_path()?;+ push_generated_delete(&mut plan, plugin, DeleteKind::OpenCodePlugin);++ let omp = install_hooks::omp_extension_path()?;+ push_generated_delete(&mut plan, omp, DeleteKind::OmpExtension);++ let openclaw_dir = openclaw_plugin::default_plugin_dir()?;+ push_generated_delete(+ &mut plan,+ openclaw_dir.join(openclaw_plugin::PACKAGE_JSON),+ DeleteKind::OpenClawPackageJson,+ );+ push_generated_delete(+ &mut plan,+ openclaw_dir.join(openclaw_plugin::MANIFEST_JSON),+ DeleteKind::OpenClawManifest,+ );+ push_generated_delete(+ &mut plan,+ openclaw_dir.join(openclaw_plugin::ENTRYPOINT_TS),+ DeleteKind::OpenClawEntrypoint,+ );}// ---- MCP (per client) ----@@ -75,6 +181,8 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {ClaudeDesktop,GeminiCli,Openclaw,+ Pi,+ AntigravityCli,] {let Ok(path) = install_mcp::mcp_config_path(client) else {continue;@@ -89,9 +197,12 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {} else {strip_mcp_json(&content, client, name, url)?};- if !removed.is_empty() {- plan.push(PlannedChange::Rewrite { path, removed });- }+ let op = if matches!(client, Codex) {+ RewriteOp::McpToml+ } else {+ RewriteOp::McpJson(client)+ };+ push_rewrite(&mut plan, path, removed, op);}}@@ -107,10 +218,12 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {.with_context(|| format!("reading {}", path.display()))?;let (_new, found) = strip_instructions_block(&content);if found {- plan.push(PlannedChange::Rewrite {+ push_rewrite(+ &mut plan,path,- removed: vec!["instruction block".to_string()],- });+ vec!["instruction block".to_string()],+ RewriteOp::Instructions,+ );}}}@@ -126,68 +239,55 @@ fn print_plan(plan: &[PlannedChange]) {}for change in plan {match change {- PlannedChange::Rewrite { path, removed } => {+ PlannedChange::Rewrite { path, removed, .. } => {println!("would remove {} from {}",removed.join(", "),path.display());}- PlannedChange::DeleteFile { path } => {- println!("would delete {}", path.display());+ PlannedChange::DeleteFile { path, kind } => {+ println!("would delete {} ({})", path.display(), kind.label());}}}}-/// Re-run the matching stripper inside `apply_atomic` so the actual-/// write is atomic + backed up. The stripper is chosen by filename.-/// `only` gates which strippers run in the JSON `else` branch so that-/// `--only hooks` does not accidentally strip `mcpServers` from a-/// shared file (e.g. `~/.gemini/settings.json`).-fn apply_change(- change: &PlannedChange,- name: &str,- url: &str,- only: Option<crate::cli::UninstallOnly>,-) -> anyhow::Result<()> {+/// Re-run the planned strippers inside `apply_atomic` so the actual write is+/// atomic + backed up. Planning records exact operations per file, so shared+/// files such as `~/.gemini/settings.json` only apply the selected concerns.+fn apply_change(change: &PlannedChange, name: Option<&str>, url: &str) -> anyhow::Result<()> {match change {- PlannedChange::DeleteFile { path } => {+ PlannedChange::DeleteFile { path, kind } => {+ if !path.exists() {+ return Ok(());+ }+ if !generated_file_is_ours(path, *kind) {+ println!(+ "skipped {} because it no longer looks like an ai-memory-generated {}",+ path.display(),+ kind.label()+ );+ return Ok(());+ }std::fs::remove_file(path).with_context(|| format!("deleting {}", path.display()))?;println!("✓ deleted {}", path.display());}- PlannedChange::Rewrite { path, .. } => {- let file = path.file_name().and_then(|f| f.to_str()).unwrap_or("");+ PlannedChange::Rewrite { path, ops, .. } => {let outcome = apply_atomic(path, |existing| {- if file == "CLAUDE.md" || file == "AGENTS.md" {- // build_plan only puts these in the plan under- // Instructions; no gating needed here.- Ok(strip_instructions_block(existing).0)- } else if file == "config.toml" {- // build_plan only puts config.toml in the plan under- // Mcp; no gating needed here.- Ok(strip_mcp_toml(existing, name, url)?.0)- } else {- // hooks settings/hooks.json OR a shared file with both- // hooks and mcpServers (e.g. ~/.gemini/settings.json).- // Gate each stripper on the --only filter so that- // `--only hooks` never strips mcpServers and vice-versa.- use crate::cli::UninstallOnly;- let mut out = existing.to_string();- if only.is_none() || only == Some(UninstallOnly::Hooks) {- out = strip_ai_memory_hooks(&out)?.new_content;- }- if only.is_none() || only == Some(UninstallOnly::Mcp) {- for client in [- crate::cli::McpClient::ClaudeCode,- crate::cli::McpClient::OpenCode,- crate::cli::McpClient::Openclaw,- ] {- out = strip_mcp_json(&out, client, name, url)?.0;+ let mut out = existing.to_string();+ for op in ops {+ out = match *op {+ RewriteOp::Instructions => strip_instructions_block(&out).0,+ RewriteOp::HooksJson => strip_ai_memory_hooks(&out)?.new_content,+ RewriteOp::AntigravityHooksJson => {+ strip_antigravity_hooks(&out)?.new_content}- }- Ok(out)+ RewriteOp::McpJson(client) => strip_mcp_json(&out, client, name, url)?.0,+ RewriteOp::McpToml => strip_mcp_toml(&out, name, url)?.0,+ };}+ Ok(out)})?;println!("✓ {} {}", outcome.verb(), path.display());}@@ -201,8 +301,8 @@ fn apply_change(/// Returns an error if a config file is malformed or a removal write/// fails. Absent files / nothing-to-remove are not errors.pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {- let name = "ai-memory";- let url = crate::config::DEFAULT_MCP_URL;+ let name = args.mcp_name.clone();+ let url = args.mcp_url.clone();let plan = build_plan(&args)?;print_plan(&plan);@@ -243,7 +343,7 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {}for change in &plan {- apply_change(change, name, url, args.only)?;+ apply_change(change, name.as_deref(), &url)?;}if args.purge_data {@@ -373,6 +473,63 @@ fn strip_ai_memory_hooks(content: &str) -> Result<HookRemoval> {})}+/// Remove ai-memory's named Antigravity CLI hook group entries. The group+/// name alone is not enough to prove ownership; every removed entry must still+/// carry ai-memory's hook command signature.+fn strip_antigravity_hooks(content: &str) -> Result<HookRemoval> {+ let mut removed_events = Vec::new();+ let new_content = mutate_json(content, |root| {+ let Some(group) = root.get_mut("ai-memory").and_then(|g| g.as_object_mut()) else {+ return Ok(());+ };+ let events: Vec<String> = group.keys().cloned().collect();+ for event in events {+ let Some(arr) = group.get_mut(&event).and_then(|v| v.as_array_mut()) else {+ continue;+ };+ let before = arr.len();+ arr.retain(|entry| !hook_entry_is_ours(entry));+ if arr.len() != before {+ removed_events.push(format!("ai-memory.{event}"));+ }+ if arr.is_empty() {+ group.remove(&event);+ }+ }+ if group.is_empty() {+ root.remove("ai-memory");+ }+ Ok(())+ })?;+ Ok(HookRemoval {+ new_content,+ removed_events,+ })+}++fn generated_file_is_ours(path: &Path, kind: DeleteKind) -> bool {+ let Ok(content) = std::fs::read_to_string(path) else {+ return false;+ };+ match kind {+ DeleteKind::OpenCodePlugin => {+ content.contains("Auto-generated by `ai-memory install-hooks --agent opencode --apply`")+ && content.contains("const AGENT = \"open-code\";")+ }+ DeleteKind::OmpExtension => {+ content.contains("Auto-generated by `ai-memory install-hooks --agent omp --apply`")+ && content.contains("const AGENT = \"omp\";")+ }+ DeleteKind::OpenClawEntrypoint => {+ content.contains("Auto-generated by `ai-memory install-hooks --agent openclaw --apply`")+ && content.contains("definePluginEntry")+ && content.contains("id: \"ai-memory\"")+ }+ DeleteKind::OpenClawPackageJson => content == openclaw_plugin::package_json(),+ DeleteKind::OpenClawManifest => content == openclaw_plugin::manifest_json(),+ }+}+/// Where the servers object lives in each JSON client's config./// (Codex is TOML — handled separately in Task 5.)fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {@@ -380,21 +537,25 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {McpClient::ClaudeCode| McpClient::ClaudeDesktop| McpClient::Cursor- | McpClient::GeminiCli => Some(&["mcpServers"]),+ | McpClient::GeminiCli+ | McpClient::Pi+ | McpClient::AntigravityCli => Some(&["mcpServers"]),McpClient::OpenCode => Some(&["mcp"]),McpClient::Openclaw => Some(&["mcp", "servers"]),- McpClient::Codex | McpClient::Pi => None,+ McpClient::Codex => None,}}-/// True when an MCP server entry is ai-memory's: keyed by the expected-/// name, OR its url/httpUrl equals the endpoint, OR it is a-/// `mcp-remote` stdio shim whose args contain the endpoint.-fn mcp_entry_is_ours(key: &str, entry: &serde_json::Value, name: &str, url: &str) -> bool {- if key == name {- return true;+/// True when an MCP server entry is ai-memory's: its url/httpUrl/serverUrl+/// equals the endpoint, or it is a `mcp-remote` stdio shim whose args contain+/// the endpoint. The key/name alone is intentionally not enough: users may+/// have unrelated entries named `ai-memory`, and uninstall must not remove+/// them unless the endpoint also matches.+fn mcp_entry_is_ours(key: &str, entry: &serde_json::Value, name: Option<&str>, url: &str) -> bool {+ if name.is_some_and(|name| key != name) {+ return false;}- for field in ["url", "httpUrl"] {+ for field in ["url", "httpUrl", "serverUrl"] {if entry.get(field).and_then(|v| v.as_str()) == Some(url) {return true;}@@ -415,7 +576,7 @@ fn mcp_entry_is_ours(key: &str, entry: &serde_json::Value, name: &str, url: &strfn strip_mcp_json(content: &str,client: McpClient,- name: &str,+ name: Option<&str>,url: &str,) -> Result<(String, Vec<String>)> {let Some(path) = mcp_servers_path(client) else {@@ -457,7 +618,7 @@ fn strip_mcp_json(/// Remove ai-memory's Codex MCP table by name or `url`. Returns new/// content and removed names. Preserves comments + other tables.-fn strip_mcp_toml(content: &str, name: &str, url: &str) -> Result<(String, Vec<String>)> {+fn strip_mcp_toml(content: &str, name: Option<&str>, url: &str) -> Result<(String, Vec<String>)> {let mut removed = Vec::new();let new_content = mutate_toml(content, |doc| {let Some(servers) = doc.get_mut("mcp_servers").and_then(|i| i.as_table_mut()) else {@@ -471,7 +632,7 @@ fn strip_mcp_toml(content: &str, name: &str, url: &str) -> Result<(String, Vec<S.and_then(|t| t.get("url")).and_then(|u| u.as_str())== Some(url);- if k == name || matches_url {+ if name.is_none_or(|name| k == name) && matches_url {servers.remove(&k);removed.push(k);}@@ -610,13 +771,94 @@ mod tests {assert!(out.removed_events.is_empty());}+ #[test]+ fn strip_antigravity_hooks_removes_only_signed_entries() {+ let content = r#"{+ "ai-memory": {+ "PreInvocation": [+ {"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/session-start.sh"},+ {"type":"command","command":"/usr/bin/user-hook"}+ ],+ "Stop": [+ {"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/stop.sh"}+ ]+ },+ "my-group": {+ "Stop": [{"type":"command","command":"/usr/bin/other"}]+ }+ }"#;++ let out = strip_antigravity_hooks(content).unwrap();+ assert_eq!(+ out.removed_events,+ vec![+ "ai-memory.PreInvocation".to_string(),+ "ai-memory.Stop".to_string()+ ]+ );+ let v: serde_json::Value = serde_json::from_str(&out.new_content).unwrap();+ assert_eq!(v["ai-memory"]["PreInvocation"].as_array().unwrap().len(), 1);+ assert!(v["ai-memory"].get("Stop").is_none());+ assert!(v.get("my-group").is_some());+ }++ #[test]+ fn generated_file_detection_rejects_user_files_at_ours_path() {+ let tmp = tempfile::tempdir().unwrap();+ let path = tmp.path().join("ai-memory.ts");+ std::fs::write(&path, "// my personal plugin named ai-memory\n").unwrap();++ assert!(!generated_file_is_ours(&path, DeleteKind::OpenCodePlugin));++ std::fs::write(+ &path,+ "// Auto-generated by `ai-memory install-hooks --agent opencode --apply`.\nconst AGENT = \"open-code\";\n",+ )+ .unwrap();+ assert!(generated_file_is_ours(&path, DeleteKind::OpenCodePlugin));+ }++ #[test]+ fn generated_openclaw_package_detection_requires_our_shape() {+ let tmp = tempfile::tempdir().unwrap();+ let path = tmp.path().join("package.json");+ std::fs::write(&path, r#"{"name":"@ai-memory/openclaw-plugin"}"#).unwrap();++ assert!(!generated_file_is_ours(+ &path,+ DeleteKind::OpenClawPackageJson+ ));++ std::fs::write(&path, openclaw_plugin::package_json()).unwrap();+ assert!(generated_file_is_ours(+ &path,+ DeleteKind::OpenClawPackageJson+ ));+ }++ #[test]+ fn generated_openclaw_manifest_detection_requires_exact_metadata() {+ let tmp = tempfile::tempdir().unwrap();+ let path = tmp.path().join("openclaw.plugin.json");+ std::fs::write(+ &path,+ r#"{"id":"ai-memory","name":"ai-memory","description":"custom user plugin"}"#,+ )+ .unwrap();++ assert!(!generated_file_is_ours(&path, DeleteKind::OpenClawManifest));++ std::fs::write(&path, openclaw_plugin::manifest_json()).unwrap();+ assert!(generated_file_is_ours(&path, DeleteKind::OpenClawManifest));+ }+#[test]fn strip_mcp_claude_by_name_keeps_others() {let content = r#"{"mcpServers":{"ai-memory":{"type":"http","url":"http://127.0.0.1:49374/mcp"},"other":{"url":"http://x"}}}"#;let (out, removed) = strip_mcp_json(content,McpClient::ClaudeCode,- "ai-memory",+ Some("ai-memory"),"http://127.0.0.1:49374/mcp",).unwrap();@@ -632,7 +874,7 @@ mod tests {let (out, removed) = strip_mcp_json(content,McpClient::ClaudeCode,- "ai-memory",+ None,"http://127.0.0.1:49374/mcp",).unwrap();@@ -648,13 +890,62 @@ mod tests {);}+ #[test]+ fn strip_mcp_name_only_does_not_remove_user_entry() {+ let content = r#"{"mcpServers":{"ai-memory":{"url":"http://example.invalid/mcp"}}}"#;+ let (out, removed) = strip_mcp_json(+ content,+ McpClient::ClaudeCode,+ Some("ai-memory"),+ "http://127.0.0.1:49374/mcp",+ )+ .unwrap();++ assert!(removed.is_empty());+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert!(v["mcpServers"].get("ai-memory").is_some());+ }++ #[test]+ fn strip_mcp_antigravity_server_url() {+ let content = r#"{"mcpServers":{"mem":{"serverUrl":"http://127.0.0.1:49374/mcp"},"other":{"serverUrl":"http://x"}}}"#;+ let (out, removed) = strip_mcp_json(+ content,+ McpClient::AntigravityCli,+ None,+ "http://127.0.0.1:49374/mcp",+ )+ .unwrap();++ assert_eq!(removed, vec!["mem".to_string()]);+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert!(v["mcpServers"].get("mem").is_none());+ assert!(v["mcpServers"].get("other").is_some());+ }++ #[test]+ fn strip_mcp_pi_root_servers() {+ let content = r#"{"mcpServers":{"ai-memory":{"type":"http","url":"http://127.0.0.1:49374/mcp","enabled":true}}}"#;+ let (out, removed) = strip_mcp_json(+ content,+ McpClient::Pi,+ Some("ai-memory"),+ "http://127.0.0.1:49374/mcp",+ )+ .unwrap();++ assert_eq!(removed, vec!["ai-memory".to_string()]);+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert!(v.get("mcpServers").is_none());+ }+#[test]fn strip_mcp_claude_desktop_mcp_remote_args() {let content = r#"{"mcpServers":{"weird-name":{"command":"npx","args":["-y","mcp-remote","http://127.0.0.1:49374/mcp"]}}}"#;let (_out, removed) = strip_mcp_json(content,McpClient::ClaudeDesktop,- "ai-memory",+ None,"http://127.0.0.1:49374/mcp",).unwrap();@@ -667,7 +958,7 @@ mod tests {let (out, removed) = strip_mcp_json(content,McpClient::Openclaw,- "ai-memory",+ Some("ai-memory"),"http://127.0.0.1:49374/mcp",).unwrap();@@ -682,7 +973,7 @@ mod tests {let (_out, removed) = strip_mcp_json(content,McpClient::ClaudeCode,- "ai-memory",+ Some("ai-memory"),"http://127.0.0.1:49374/mcp",).unwrap();@@ -693,7 +984,7 @@ mod tests {fn strip_mcp_toml_by_name_keeps_comments_and_tables() {let content = "# my codex config\n[other]\nkeep = true\n\n[mcp_servers.ai-memory]\nurl = \"http://127.0.0.1:49374/mcp\"\n";let (out, removed) =- strip_mcp_toml(content, "ai-memory", "http://127.0.0.1:49374/mcp").unwrap();+ strip_mcp_toml(content, Some("ai-memory"), "http://127.0.0.1:49374/mcp").unwrap();assert_eq!(removed, vec!["ai-memory".to_string()]);assert!(out.contains("# my codex config"));assert!(out.contains("[other]"));@@ -703,8 +994,7 @@ mod tests {#[test]fn strip_mcp_toml_by_url_under_custom_name() {let content = "[mcp_servers.custom]\nurl = \"http://127.0.0.1:49374/mcp\"\n";- let (out, removed) =- strip_mcp_toml(content, "ai-memory", "http://127.0.0.1:49374/mcp").unwrap();+ let (out, removed) = strip_mcp_toml(content, None, "http://127.0.0.1:49374/mcp").unwrap();assert_eq!(removed, vec!["custom".to_string()]);assert!(!out.contains("custom"));}@@ -713,7 +1003,7 @@ mod tests {fn strip_mcp_toml_no_match_is_noop() {let content = "[mcp_servers.other]\nurl = \"http://x\"\n";let (_out, removed) =- strip_mcp_toml(content, "ai-memory", "http://127.0.0.1:49374/mcp").unwrap();+ strip_mcp_toml(content, Some("ai-memory"), "http://127.0.0.1:49374/mcp").unwrap();assert!(removed.is_empty());}}diff --git a/crates/ai-memory-cli/tests/uninstall.rs b/crates/ai-memory-cli/tests/uninstall.rsindex b7d6d53a..7d609365 100644--- a/crates/ai-memory-cli/tests/uninstall.rs+++ b/crates/ai-memory-cli/tests/uninstall.rs@@ -2,6 +2,13 @@//! assert the file round-trips (our entries gone, third-party intact).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")@@ -9,6 +16,7 @@ fn bin() -> &'static str {#[test]fn install_then_uninstall_round_trip_claude_hooks() {+ let _guard = cli_test_lock();let home = tempfile::tempdir().unwrap();let claude = home.path().join(".claude");std::fs::create_dir_all(&claude).unwrap();@@ -23,6 +31,8 @@ fn install_then_uninstall_round_trip_claude_hooks() {let status = Command::new(bin()).args(["install-hooks", "--agent", "claude-code", "--apply"]).env("HOME", home.path())+ .env("XDG_DATA_HOME", home.path().join(".local/share"))+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "install-hooks failed");@@ -31,6 +41,8 @@ fn install_then_uninstall_round_trip_claude_hooks() {let status = Command::new(bin()).args(["uninstall", "--apply", "--only", "hooks", "--yes"]).env("HOME", home.path())+ .env("XDG_DATA_HOME", home.path().join(".local/share"))+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success(), "uninstall failed");@@ -59,6 +71,7 @@ fn install_then_uninstall_round_trip_claude_hooks() {#[test]fn uninstall_apply_is_idempotent() {+ let _guard = cli_test_lock();let home = tempfile::tempdir().unwrap();let claude = home.path().join(".claude");std::fs::create_dir_all(&claude).unwrap();@@ -72,6 +85,7 @@ fn uninstall_apply_is_idempotent() {std::process::Command::new(bin()).args(["uninstall", "--apply", "--only", "hooks", "--yes"]).env("HOME", home.path())+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap()};@@ -96,6 +110,7 @@ fn uninstall_apply_is_idempotent() {#[test]fn only_hooks_preserves_mcp_in_same_file() {+ let _guard = cli_test_lock();// Gemini-style: hooks + mcpServers in one settings.json.let home = tempfile::tempdir().unwrap();let gem = home.path().join(".gemini");@@ -109,6 +124,7 @@ fn only_hooks_preserves_mcp_in_same_file() {let status = std::process::Command::new(bin()).args(["uninstall", "--apply", "--only", "hooks", "--yes"]).env("HOME", home.path())+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success());@@ -127,8 +143,246 @@ fn only_hooks_preserves_mcp_in_same_file() {);}+#[test]+fn uninstall_preserves_user_opencode_plugin_at_ai_memory_path() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let plugins = home.path().join(".config/opencode/plugins");+ std::fs::create_dir_all(&plugins).unwrap();+ let plugin = plugins.join("ai-memory.ts");+ let original = "// user-owned plugin that happens to use this filename\nexport default {};\n";+ std::fs::write(&plugin, original).unwrap();++ let status = Command::new(bin())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .env("HOME", home.path())+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data"))+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ assert_eq!(std::fs::read_to_string(&plugin).unwrap(), original);+}++#[test]+fn uninstall_deletes_generated_opencode_plugin_only() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let plugins = home.path().join(".config/opencode/plugins");+ std::fs::create_dir_all(&plugins).unwrap();+ let plugin = plugins.join("ai-memory.ts");+ std::fs::write(+ &plugin,+ "// Auto-generated by `ai-memory install-hooks --agent opencode --apply`.\nconst AGENT = \"open-code\";\n",+ )+ .unwrap();+ let sibling = plugins.join("other.ts");+ std::fs::write(&sibling, "keep me\n").unwrap();++ let status = Command::new(bin())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .env("HOME", home.path())+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data"))+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ assert!(!plugin.exists(), "generated plugin should be deleted");+ assert!(sibling.exists(), "unrelated plugin must be preserved");+}++#[test]+fn uninstall_omp_extension_deletes_only_generated_file() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let extensions = home.path().join(".omp/agent/extensions");+ std::fs::create_dir_all(&extensions).unwrap();+ let extension = extensions.join("ai-memory.ts");+ let user_content = "// user-owned extension that happens to use this filename\n";+ std::fs::write(&extension, user_content).unwrap();++ let status = Command::new(bin())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .env("HOME", home.path())+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data"))+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");+ assert_eq!(std::fs::read_to_string(&extension).unwrap(), user_content);++ std::fs::write(+ &extension,+ "// Auto-generated by `ai-memory install-hooks --agent omp --apply`.\nconst AGENT = \"omp\";\n",+ )+ .unwrap();++ let status = Command::new(bin())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .env("HOME", home.path())+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data"))+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");+ assert!(!extension.exists(), "generated extension should be deleted");+}++#[test]+fn uninstall_preserves_user_openclaw_package_at_ai_memory_path() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let data = home.path().join(".local/share");+ let plugin_dir = data.join("ai-memory/openclaw-plugin");+ std::fs::create_dir_all(&plugin_dir).unwrap();+ let package = plugin_dir.join("package.json");+ let original = r#"{"name":"@ai-memory/openclaw-plugin","private":true}"#;+ std::fs::write(&package, original).unwrap();++ let status = Command::new(bin())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .env("HOME", home.path())+ .env("XDG_DATA_HOME", &data)+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data"))+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ assert_eq!(std::fs::read_to_string(&package).unwrap(), original);+}++#[test]+fn uninstall_antigravity_hooks_preserves_user_entries() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let config = home.path().join(".gemini/config");+ std::fs::create_dir_all(&config).unwrap();+ let hooks = config.join("hooks.json");+ std::fs::write(+ &hooks,+ r#"{+ "ai-memory": {+ "PreInvocation": [+ {"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/session-start.sh"},+ {"type":"command","command":"/usr/bin/user-pre-invocation"}+ ],+ "Stop": [+ {"type":"command","command":"AI_MEMORY_HOOK_URL=http://h /x/stop.sh"}+ ]+ },+ "other-group": {+ "Stop": [{"type":"command","command":"/usr/bin/other"}]+ }+ }"#,+ )+ .unwrap();++ let status = Command::new(bin())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .env("HOME", home.path())+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data"))+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ let after: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&hooks).unwrap()).unwrap();+ assert_eq!(+ after["ai-memory"]["PreInvocation"]+ .as_array()+ .unwrap()+ .len(),+ 1,+ "third-party entry in same group/event must survive"+ );+ assert!(after["ai-memory"].get("Stop").is_none());+ assert!(after.get("other-group").is_some());+}++#[test]+fn uninstall_mcp_custom_url_removes_antigravity_only_by_endpoint() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let config = home.path().join(".gemini/antigravity-cli");+ std::fs::create_dir_all(&config).unwrap();+ let mcp = config.join("mcp_config.json");+ std::fs::write(+ &mcp,+ r#"{+ "mcpServers": {+ "ai-memory": {"serverUrl":"http://example.invalid/mcp"},+ "custom-memory": {"serverUrl":"http://lan:49374/mcp"},+ "other": {"serverUrl":"http://other/mcp"}+ }+ }"#,+ )+ .unwrap();++ let status = Command::new(bin())+ .args([+ "uninstall",+ "--apply",+ "--only",+ "mcp",+ "--mcp-url",+ "http://lan:49374/mcp",+ "--yes",+ ])+ .env("HOME", home.path())+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data"))+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ let after: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&mcp).unwrap()).unwrap();+ assert!(after["mcpServers"].get("custom-memory").is_none());+ assert!(+ after["mcpServers"].get("ai-memory").is_some(),+ "same name with a different endpoint must survive"+ );+ assert!(after["mcpServers"].get("other").is_some());+}++#[test]+fn uninstall_mcp_name_narrows_endpoint_match() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let claude = home.path().join(".claude.json");+ std::fs::write(+ &claude,+ r#"{+ "mcpServers": {+ "ai-memory": {"url":"http://127.0.0.1:49374/mcp"},+ "ai-memory-alt": {"url":"http://127.0.0.1:49374/mcp"}+ }+ }"#,+ )+ .unwrap();++ let status = Command::new(bin())+ .args([+ "uninstall",+ "--apply",+ "--only",+ "mcp",+ "--mcp-name",+ "ai-memory",+ "--yes",+ ])+ .env("HOME", home.path())+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data"))+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ let after: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&claude).unwrap()).unwrap();+ assert!(after["mcpServers"].get("ai-memory").is_none());+ assert!(after["mcpServers"].get("ai-memory-alt").is_some());+}+#[test]fn uninstall_dry_run_changes_nothing() {+ let _guard = cli_test_lock();let home = tempfile::tempdir().unwrap();let claude = home.path().join(".claude");std::fs::create_dir_all(&claude).unwrap();@@ -138,6 +392,7 @@ fn uninstall_dry_run_changes_nothing() {let status = Command::new(bin()).args(["uninstall", "--only", "hooks"]) // no --apply.env("HOME", home.path())+ .env("AI_MEMORY_DATA_DIR", home.path().join(".ai-memory-data")).status().unwrap();assert!(status.success());@@ -148,6 +403,7 @@ fn uninstall_dry_run_changes_nothing() {#[test]fn uninstall_purge_data_apply_wipes() {+ let _guard = cli_test_lock();let home = tempfile::tempdir().unwrap();let data = tempfile::tempdir().unwrap();for sub in ["wiki", "db", "raw"] {@@ -183,6 +439,7 @@ fn uninstall_purge_data_apply_wipes() {#[test]fn uninstall_dry_run_previews_purge() {+ let _guard = cli_test_lock();let home = tempfile::tempdir().unwrap();let data = tempfile::tempdir().unwrap();for sub in ["wiki", "db", "raw"] {@@ -218,6 +475,7 @@ fn uninstall_dry_run_previews_purge() {#[test]#[ignore]fn purge_data_refuses_when_sibling_alive() {+ let _guard = cli_test_lock();let home = tempfile::tempdir().unwrap();let data = tempfile::tempdir().unwrap();let claude = home.path().join(".claude");diff --git a/docs/install.md b/docs/install.mdindex 567fdf17..b22007b5 100644--- a/docs/install.md+++ b/docs/install.md@@ -422,6 +422,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree| `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. || `llm-test --provider …` | `docker run --rm -e …` | Smoke-test an LLM provider |Data dir inside the container is `/data` (mounted via the compose