Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(plugins): setup, run, doctor, upgrade and uninstall know the plugins (#1166)
AkitaOnRailsb72dd971a8ea
diff --git a/crates/ai-memory-cli/src/commands/agent_plugins.rs b/crates/ai-memory-cli/src/commands/agent_plugins.rsnew file mode 100644index 00000000..22ff7d75--- /dev/null+++ b/crates/ai-memory-cli/src/commands/agent_plugins.rs@@ -0,0 +1,385 @@+//! The ai-memory marketplace plugins (#1166) as Claude Code and Codex record+//! them on this machine: whether one is installed and enabled, and at which+//! version. `setup` and `ai-memory run` use it to stop writing the parallel+//! settings-file wiring, `doctor` to report the plugin and any double+//! install, `upgrade` to update the Claude Code plugin with the binary, and+//! `uninstall` to remove the plugins.+//!+//! Only the user-level install is read: Claude Code's+//! `<config dir>/plugins/installed_plugins.json` plus `enabledPlugins` in the+//! user `settings.json`, and Codex's `[plugins."ai-memory@ai-memory"]` in+//! `config.toml`. A plugin enabled only in one project's settings is not seen.++use std::ffi::OsString;+use std::path::{Path, PathBuf};++use serde::Serialize;++use super::user_service::CommandRunner;++/// The id both harnesses record the plugin under: plugin `ai-memory` from+/// marketplace `ai-memory`.+pub(crate) const PLUGIN_ID: &str = "ai-memory@ai-memory";+/// The marketplace name, for `marketplace update`.+const MARKETPLACE: &str = "ai-memory";++/// Which harness a plugin belongs to.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "kebab-case")]+pub(crate) enum PluginHarness {+ /// Claude Code (`plugins/claude-code`).+ ClaudeCode,+ /// Codex (`plugins/codex`).+ Codex,+}++impl PluginHarness {+ /// The agent name, as `--agent` spells it.+ pub(crate) fn agent(self) -> &'static str {+ match self {+ Self::ClaudeCode => "claude-code",+ Self::Codex => "codex",+ }+ }++ /// The command that removes the plugin.+ pub(crate) fn uninstall_command(self) -> (&'static str, [&'static str; 3]) {+ match self {+ Self::ClaudeCode => ("claude", ["plugin", "uninstall", PLUGIN_ID]),+ Self::Codex => ("codex", ["plugin", "remove", PLUGIN_ID]),+ }+ }+}++/// An installed ai-memory plugin.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub(crate) struct InstalledPlugin {+ /// The harness it is installed in.+ pub(crate) harness: PluginHarness,+ /// The installed plugin version, when the harness records one.+ pub(crate) version: Option<String>,+ /// Whether the harness loads it.+ pub(crate) enabled: bool,+}++impl InstalledPlugin {+ /// The plugin version when it differs from this binary's.+ pub(crate) fn version_skew(&self) -> Option<&str> {+ self.version+ .as_deref()+ .filter(|version| *version != env!("CARGO_PKG_VERSION"))+ }+}++/// Claude Code's config root: `CLAUDE_CONFIG_DIR`, else `<home>/.claude`.+pub(crate) fn claude_root(home: &Path, env: &dyn Fn(&str) -> Option<OsString>) -> PathBuf {+ super::path_util::claude_config_dir(env("CLAUDE_CONFIG_DIR"))+ .unwrap_or_else(|| home.join(".claude"))+}++/// Codex's home: `CODEX_HOME`, else `<home>/.codex`.+pub(crate) fn codex_home(home: &Path, env: &dyn Fn(&str) -> Option<OsString>) -> PathBuf {+ super::path_util::agent_config_home(env("CODEX_HOME")).unwrap_or_else(|| home.join(".codex"))+}++/// Both plugins as installed under `home`, honouring the relocation+/// variables `env` reports.+pub(crate) fn installed(+ home: &Path,+ env: &dyn Fn(&str) -> Option<OsString>,+) -> Vec<InstalledPlugin> {+ [+ claude_code_at(&claude_root(home, env)),+ codex_at(&codex_home(home, env)),+ ]+ .into_iter()+ .flatten()+ .collect()+}++/// The enabled plugin for `harness` under `home`, if any.+pub(crate) fn enabled(+ harness: PluginHarness,+ home: &Path,+ env: &dyn Fn(&str) -> Option<OsString>,+) -> Option<InstalledPlugin> {+ installed(home, env)+ .into_iter()+ .find(|plugin| plugin.harness == harness && plugin.enabled)+}++fn read_json(path: &Path) -> Option<serde_json::Value> {+ serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()+}++/// The Claude Code plugin under the config root `root`.+pub(crate) fn claude_code_at(root: &Path) -> Option<InstalledPlugin> {+ let installed = read_json(&root.join("plugins").join("installed_plugins.json"))?;+ let entries = installed.get("plugins")?.get(PLUGIN_ID)?.as_array()?;+ let entry = entries+ .iter()+ .find(|entry| entry.get("scope").and_then(serde_json::Value::as_str) == Some("user"))+ .or_else(|| entries.first())?;+ let version = entry+ .get("version")+ .and_then(serde_json::Value::as_str)+ .map(str::to_owned);+ let enabled = read_json(&root.join("settings.json"))+ .and_then(|settings| settings.get("enabledPlugins")?.get(PLUGIN_ID)?.as_bool())+ .unwrap_or(false);+ Some(InstalledPlugin {+ harness: PluginHarness::ClaudeCode,+ version,+ enabled,+ })+}++/// The Codex plugin under `codex_home`. Codex keeps one cache directory per+/// installed version; the newest one names the version.+pub(crate) fn codex_at(codex_home: &Path) -> Option<InstalledPlugin> {+ let config = std::fs::read_to_string(codex_home.join("config.toml")).ok()?;+ let document = config.parse::<toml_edit::DocumentMut>().ok()?;+ let entry = document.get("plugins")?.get(PLUGIN_ID)?;+ let enabled = entry+ .get("enabled")+ .and_then(toml_edit::Item::as_bool)+ .unwrap_or(true);+ let cache = codex_home+ .join("plugins")+ .join("cache")+ .join(MARKETPLACE)+ .join("ai-memory");+ let version = std::fs::read_dir(&cache)+ .ok()+ .into_iter()+ .flatten()+ .flatten()+ .filter_map(|dir| {+ let modified = dir.metadata().and_then(|m| m.modified()).ok()?;+ let manifest = read_json(&dir.path().join(".codex-plugin").join("plugin.json"))?;+ let version = manifest.get("version")?.as_str()?.to_owned();+ Some((modified, version))+ })+ .max()+ .map(|(_, version)| version);+ Some(InstalledPlugin {+ harness: PluginHarness::Codex,+ version,+ enabled,+ })+}++/// Bring the Claude Code plugin up to the newest release the marketplace+/// lists. Third-party marketplaces do not auto-update by default, so+/// `upgrade` runs this after replacing the binary to keep the two in step.+/// Returns what to tell the operator; a failure is reported, never fatal.+pub(crate) fn update_claude_code(runner: &dyn CommandRunner) -> Vec<String> {+ let steps: [&[&str]; 2] = [+ &["plugin", "marketplace", "update", MARKETPLACE],+ &["plugin", "update", PLUGIN_ID],+ ];+ let mut lines = Vec::new();+ for args in steps {+ let shown = format!("claude {}", args.join(" "));+ match runner.run("claude", args) {+ Ok(outcome) if outcome.success => lines.push(format!("✓ {shown}")),+ Ok(outcome) => {+ lines.push(format!(+ "⚠ {shown} failed: {}; run it yourself",+ outcome.stderr.trim()+ ));+ break;+ }+ Err(error) => {+ lines.push(format!(+ "⚠ {shown} could not start ({error:#}); run it yourself"+ ));+ break;+ }+ }+ }+ lines+}++/// Fixtures shared by the plugin-aware commands' tests.+#[cfg(test)]+pub(crate) mod test_support {+ use std::cell::RefCell;+ use std::path::Path;++ use super::super::user_service::{CommandOutcome, CommandRunner};++ /// Records every command; the call numbered `fail_at` (1-based) fails.+ pub(crate) struct RecordingRunner {+ pub(crate) calls: RefCell<Vec<String>>,+ fail_at: Option<usize>,+ }++ impl RecordingRunner {+ pub(crate) fn new(fail_at: Option<usize>) -> Self {+ Self {+ calls: RefCell::new(Vec::new()),+ fail_at,+ }+ }+ }++ impl CommandRunner for RecordingRunner {+ fn run(&self, program: &str, args: &[&str]) -> anyhow::Result<CommandOutcome> {+ let mut calls = self.calls.borrow_mut();+ calls.push(format!("{program} {}", args.join(" ")));+ Ok(CommandOutcome {+ success: self.fail_at != Some(calls.len()),+ stdout: String::new(),+ stderr: "boom".to_owned(),+ })+ }+ }++ /// Record the Claude Code plugin as installed (at `version`) under+ /// `<home>/.claude`, enabled or not.+ pub(crate) fn install_claude_plugin(home: &Path, version: &str, enabled: bool) {+ let root = home.join(".claude");+ std::fs::create_dir_all(root.join("plugins")).unwrap();+ std::fs::write(+ root.join("plugins/installed_plugins.json"),+ format!(+ r#"{{"version":2,"plugins":{{"ai-memory@ai-memory":[{{"scope":"user","version":"{version}"}}]}}}}"#+ ),+ )+ .unwrap();+ let settings = root.join("settings.json");+ let mut doc: serde_json::Value = std::fs::read_to_string(&settings)+ .ok()+ .and_then(|text| serde_json::from_str(&text).ok())+ .unwrap_or_else(|| serde_json::json!({}));+ doc["enabledPlugins"]["ai-memory@ai-memory"] = enabled.into();+ std::fs::write(settings, doc.to_string()).unwrap();+ }++ /// Record the Codex plugin as installed and enabled under `<home>/.codex`.+ pub(crate) fn install_codex_plugin(home: &Path) {+ let root = home.join(".codex");+ std::fs::create_dir_all(&root).unwrap();+ std::fs::write(+ root.join("config.toml"),+ "[plugins.\"ai-memory@ai-memory\"]\nenabled = true\n",+ )+ .unwrap();+ }+}++#[cfg(test)]+mod tests {+ use super::test_support::RecordingRunner;+ use super::*;++ fn no_env(_: &str) -> Option<OsString> {+ None+ }++ fn write(path: &Path, body: &str) {+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, body).unwrap();+ }++ #[test]+ fn claude_code_plugin_is_read_from_installed_plugins_and_settings() {+ let home = tempfile::tempdir().unwrap();+ let root = home.path().join(".claude");+ assert_eq!(claude_code_at(&root), None);++ write(+ &root.join("plugins/installed_plugins.json"),+ r#"{"version":2,"plugins":{"ai-memory@ai-memory":[{"scope":"project","version":"0.1.0"},{"scope":"user","installPath":"/x","version":"3.0.0"}],"other@x":[{"scope":"user","version":"9"}]}}"#,+ );+ let plugin = claude_code_at(&root).unwrap();+ assert_eq!(plugin.version.as_deref(), Some("3.0.0"));+ assert!(!plugin.enabled, "installed but not enabled");++ write(+ &root.join("settings.json"),+ r#"{"enabledPlugins":{"ai-memory@ai-memory":true}}"#,+ );+ assert!(claude_code_at(&root).unwrap().enabled);+ assert!(enabled(PluginHarness::ClaudeCode, home.path(), &no_env).is_some());+ assert!(enabled(PluginHarness::Codex, home.path(), &no_env).is_none());++ write(+ &root.join("settings.json"),+ r#"{"enabledPlugins":{"ai-memory@ai-memory":false}}"#,+ );+ assert!(enabled(PluginHarness::ClaudeCode, home.path(), &no_env).is_none());+ }++ #[test]+ fn claude_root_honours_claude_config_dir() {+ let home = Path::new("/home/me");+ assert_eq!(claude_root(home, &no_env), home.join(".claude"));+ let relocated = |name: &str| (name == "CLAUDE_CONFIG_DIR").then(|| OsString::from("/cc"));+ assert_eq!(claude_root(home, &relocated), PathBuf::from("/cc"));+ }++ #[test]+ fn codex_plugin_is_read_from_config_and_the_newest_cache_dir() {+ let home = tempfile::tempdir().unwrap();+ let codex = home.path().join(".codex");+ assert_eq!(codex_at(&codex), None);+ write(+ &codex.join("config.toml"),+ "[plugins.\"other@x\"]\nenabled = true\n",+ );+ assert_eq!(codex_at(&codex), None);++ write(+ &codex.join("config.toml"),+ "model = \"m\"\n[plugins.\"ai-memory@ai-memory\"]\nenabled = true\n",+ );+ write(+ &codex.join("plugins/cache/ai-memory/ai-memory/3.0.0/.codex-plugin/plugin.json"),+ r#"{"name":"ai-memory","version":"3.0.0"}"#,+ );+ let plugin = codex_at(&codex).unwrap();+ assert_eq!(plugin.version.as_deref(), Some("3.0.0"));+ assert!(plugin.enabled);++ write(+ &codex.join("config.toml"),+ "[plugins.\"ai-memory@ai-memory\"]\nenabled = false\n",+ );+ assert!(!codex_at(&codex).unwrap().enabled);+ }++ #[test]+ fn version_skew_compares_with_this_binary() {+ let mut plugin = InstalledPlugin {+ harness: PluginHarness::ClaudeCode,+ version: Some(env!("CARGO_PKG_VERSION").to_owned()),+ enabled: true,+ };+ assert_eq!(plugin.version_skew(), None);+ plugin.version = Some("0.0.1".to_owned());+ assert_eq!(plugin.version_skew(), Some("0.0.1"));+ plugin.version = None;+ assert_eq!(plugin.version_skew(), None);+ }++ #[test]+ fn update_refreshes_the_marketplace_then_the_plugin() {+ let runner = RecordingRunner::new(None);+ let lines = update_claude_code(&runner);+ assert_eq!(+ *runner.calls.borrow(),+ vec![+ "claude plugin marketplace update ai-memory",+ "claude plugin update ai-memory@ai-memory"+ ]+ );+ assert!(lines.iter().all(|line| line.starts_with('✓')), "{lines:?}");++ let runner = RecordingRunner::new(Some(1));+ let lines = update_claude_code(&runner);+ assert_eq!(runner.calls.borrow().len(), 1, "stops after a failure");+ assert!(lines[0].contains("failed: boom"), "{lines:?}");+ }+}diff --git a/crates/ai-memory-cli/src/commands/codex_hook_trust.rs b/crates/ai-memory-cli/src/commands/codex_hook_trust.rsindex 92741349..f9c67df9 100644--- a/crates/ai-memory-cli/src/commands/codex_hook_trust.rs+++ b/crates/ai-memory-cli/src/commands/codex_hook_trust.rs@@ -46,16 +46,31 @@ struct HookMetadata {source_path: String,#[serde(default)]command: Option<String>,+ #[serde(default)]+ plugin_id: Option<String>,+}++/// Which ai-memory hooks a probe reports on.+#[derive(Debug, Clone, Copy)]+pub(crate) enum HookSource<'a> {+ /// The hooks `install-hooks` wrote to this hooks file.+ File(&'a Path),+ /// The hooks of the installed plugin with this id (#1166).+ Plugin(&'a str),}/// Ask `codex` (the program at `program`) for the trust state of the/// ai-memory hooks in `hooks_file`. `None` when Codex is not installed, does/// not answer in time, speaks a protocol this does not understand, or lists/// no ai-memory hook in that file — the caller reports the state as unknown.-pub(crate) async fn probe(program: &Path, hooks_file: &Path, cwd: &Path) -> Option<CodexHookTrust> {+pub(crate) async fn probe(+ program: &Path,+ source: HookSource<'_>,+ cwd: &Path,+) -> Option<CodexHookTrust> {let result = tokio::time::timeout(PROBE_TIMEOUT, list_hooks(program, cwd)).await;let response = result.ok()??;- summarize(&response, hooks_file)+ summarize(&response, source)}async fn list_hooks(program: &Path, cwd: &Path) -> Option<serde_json::Value> {@@ -96,20 +111,27 @@ async fn list_hooks(program: &Path, cwd: &Path) -> Option<serde_json::Value> {None}-/// The trust state of the ai-memory hooks `hooks_file` declares, from a-/// `hooks/list` result. A hook is ai-memory's when its command runs-/// `ai-memory ... hook --event ...`, the form `install-hooks` writes.-fn summarize(result: &serde_json::Value, hooks_file: &Path) -> Option<CodexHookTrust> {+/// The trust state of the ai-memory hooks `source` names, from a+/// `hooks/list` result. A hooks-file hook is ai-memory's when its command runs+/// `ai-memory ... hook --event ...`, the form `install-hooks` writes; a plugin+/// hook is ai-memory's when Codex reports it under the plugin's id.+fn summarize(result: &serde_json::Value, source: HookSource<'_>) -> Option<CodexHookTrust> {let response = serde_json::from_value::<ListResponse>(result.clone()).ok()?;let mut trust = CodexHookTrust {trusted: Vec::new(),skipped: Vec::new(),};for hook in response.data.into_iter().flat_map(|entry| entry.hooks) {- let ours = hook.command.as_deref().is_some_and(|command| {- command.contains("ai-memory") && command.contains(" hook --event ")- });- if !ours || Path::new(&hook.source_path) != hooks_file {+ let ours = match source {+ HookSource::File(hooks_file) => {+ Path::new(&hook.source_path) == hooks_file+ && hook.command.as_deref().is_some_and(|command| {+ command.contains("ai-memory") && command.contains(" hook --event ")+ })+ }+ HookSource::Plugin(id) => hook.plugin_id.as_deref() == Some(id),+ };+ if !ours {continue;}match hook.trust_status.as_str() {@@ -142,7 +164,7 @@ mod tests {hook("postToolUse", "untrusted", file, "/usr/bin/other-tool --check"),hook("userPromptSubmit", "untrusted", "/repo/.codex/hooks.json", ours),]}]});- let trust = summarize(&result, Path::new(file)).unwrap();+ let trust = summarize(&result, HookSource::File(Path::new(file))).unwrap();assert_eq!(trust.trusted, vec!["sessionStart"]);assert_eq!(trust.skipped,@@ -153,15 +175,46 @@ mod tests {);}+ /// Plugin hooks run the launcher, not `ai-memory hook`, so they are+ /// recognised by the plugin id Codex reports; another plugin's hooks and+ /// the hooks-file hooks are not counted.+ #[test]+ fn summarizes_the_ai_memory_plugin_hooks_by_plugin_id() {+ let cache = "/home/me/.codex/plugins/cache/ai-memory/ai-memory/3.0.0/hooks/hooks.json";+ let launcher = "sh \"/home/me/.codex/plugins/cache/ai-memory/ai-memory/3.0.0/scripts/ai-memory-hook\" codex stop";+ let mut ours = hook("sessionStart", "trusted", cache, launcher);+ ours["pluginId"] = "ai-memory@ai-memory".into();+ let mut stale = hook("stop", "modified", cache, launcher);+ stale["pluginId"] = "ai-memory@ai-memory".into();+ let mut other = hook("stop", "untrusted", "/x/hooks.json", "other");+ other["pluginId"] = "other@market".into();+ let file = hook(+ "preToolUse",+ "untrusted",+ "/home/me/.codex/hooks.json",+ "ai-memory hook --event pre-tool-use --agent codex",+ );+ let result = serde_json::json!({"data": [{"hooks": [ours, stale, other, file]}]});+ let trust = summarize(&result, HookSource::Plugin("ai-memory@ai-memory")).unwrap();+ assert_eq!(trust.trusted, vec!["sessionStart"]);+ assert_eq!(+ trust.skipped,+ vec![("stop".to_owned(), "modified".to_owned())]+ );+ }+#[test]fn no_ai_memory_hook_or_an_unknown_shape_is_unknown() {let file = Path::new("/home/me/.codex/hooks.json");let other = serde_json::json!({"data": [{"hooks": [hook("stop", "untrusted", "/home/me/.codex/hooks.json", "/usr/bin/other-tool"),]}]});- assert_eq!(summarize(&other, file), None);+ assert_eq!(summarize(&other, HookSource::File(file)), None);assert_eq!(- summarize(&serde_json::json!({"unexpected": true}), file),+ summarize(+ &serde_json::json!({"unexpected": true}),+ HookSource::File(file)+ ),None);}@@ -188,14 +241,21 @@ mod tests {.unwrap();std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();- let trust = probe(&fake, &hooks_file, temp.path()).await.unwrap();+ let trust = probe(&fake, HookSource::File(&hooks_file), temp.path())+ .await+ .unwrap();assert!(trust.trusted.is_empty());assert_eq!(trust.skipped,vec![("sessionStart".to_owned(), "modified".to_owned())]);assert_eq!(- probe(&temp.path().join("missing"), &hooks_file, temp.path()).await,+ probe(+ &temp.path().join("missing"),+ HookSource::File(&hooks_file),+ temp.path()+ )+ .await,None);}diff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rsindex 5251c1ce..93bb032f 100644--- a/crates/ai-memory-cli/src/commands/doctor.rs+++ b/crates/ai-memory-cli/src/commands/doctor.rs@@ -189,6 +189,29 @@ struct DoctorReport {/// agentmemory MCP entries and rules-file guideline blocks still present/// after a migration. Detected only; never changed.agentmemory_residue: Vec<super::agentmemory_residue::ResidueFinding>,+ /// The ai-memory marketplace plugins installed for Claude Code and Codex,+ /// with version skew and any parallel settings-file wiring (#1166).+ plugins: Vec<PluginReport>,+}++/// One installed ai-memory marketplace plugin and what else wires the same+/// harness.+#[derive(Debug, Clone, Serialize)]+struct PluginReport {+ #[serde(flatten)]+ plugin: super::agent_plugins::InstalledPlugin,+ /// This binary's version, for the skew check.+ binary_version: &'static str,+ /// Settings-file ai-memory hooks for the same harness.+ settings_hooks: Option<PathBuf>,+ /// The managed routing skills installed in the harness's skill dir too.+ installed_skills: Option<PathBuf>,+ /// A settings-file `ai-memory` MCP entry for the same harness.+ settings_mcp: Option<PathBuf>,+ /// A Claude Code setting that stops plugin hooks from running.+ hooks_disabled_by: Option<&'static str>,+ /// Codex: whether Codex will run the plugin's hooks.+ hook_trust: Option<super::codex_hook_trust::CodexHookTrust>,}#[derive(Debug, Clone, Serialize)]@@ -612,6 +635,16 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {}),);+ let plugins = plugin_reports(&home, &cwd, &|name| {+ config+ .runtime_env+ .process_env()+ .iter()+ .find(|(key, _)| key.as_os_str() == name)+ .map(|(_, value)| value.clone())+ })+ .await;+let auth_posture = identity.as_ref().map(|identity| {crate::local_auth::AuthPosture::classify(identity.level == "anonymous", &ep.url)});@@ -633,6 +666,7 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {server_unreachable,codex_hooks,agentmemory_residue,+ plugins,};if args.json {@@ -652,7 +686,199 @@ async fn codex_hook_trust(cwd: &Path) -> Option<super::codex_hook_trust::CodexHoif !installed.contains("ai-memory") {return None;}- super::codex_hook_trust::probe(Path::new("codex"), &hooks_file, cwd).await+ super::codex_hook_trust::probe(+ Path::new("codex"),+ super::codex_hook_trust::HookSource::File(&hooks_file),+ cwd,+ )+ .await+}++/// The installed ai-memory plugins, each with what else wires its harness.+/// Asking Codex for hook trust starts it, so that runs only when the Codex+/// plugin is enabled.+async fn plugin_reports(+ home: &Path,+ cwd: &Path,+ env: &dyn Fn(&str) -> Option<std::ffi::OsString>,+) -> Vec<PluginReport> {+ use super::agent_plugins::PluginHarness;+ let mut reports = Vec::new();+ for plugin in super::agent_plugins::installed(home, env) {+ let mut report = PluginReport {+ binary_version: env!("CARGO_PKG_VERSION"),+ settings_hooks: None,+ installed_skills: None,+ settings_mcp: None,+ hooks_disabled_by: None,+ hook_trust: None,+ plugin,+ };+ match report.plugin.harness {+ PluginHarness::ClaudeCode => {+ let root = super::agent_plugins::claude_root(home, env);+ let user = root.join("settings.json");+ let project = super::install_hooks::project_claude_settings_local(cwd);+ report.settings_hooks = [user.clone(), project]+ .into_iter()+ .find(|path| super::install_hooks::settings_file_carries_ai_memory_hooks(path));+ let skills = root.join("skills");+ report.installed_skills = managed_skill_installed(&skills).then_some(skills);+ // `install-mcp`'s target: `.claude.json` in CLAUDE_CONFIG_DIR+ // when set, else in the home.+ let mcp = super::path_util::claude_config_dir(env("CLAUDE_CONFIG_DIR"))+ .unwrap_or_else(|| home.to_path_buf())+ .join(".claude.json");+ report.settings_mcp = json_mcp_entry(&mcp).then_some(mcp);+ report.hooks_disabled_by = claude_hooks_disabled_by(&user);+ }+ PluginHarness::Codex => {+ let codex = super::agent_plugins::codex_home(home, env);+ let hooks = codex.join("hooks.json");+ report.settings_hooks = std::fs::read_to_string(&hooks)+ .is_ok_and(|text| text.contains("ai-memory") && text.contains(" hook --event "))+ .then_some(hooks);+ let config = codex.join("config.toml");+ report.settings_mcp = std::fs::read_to_string(&config)+ .ok()+ .and_then(|text| text.parse::<toml_edit::DocumentMut>().ok())+ .is_some_and(|doc| {+ doc.get("mcp_servers")+ .and_then(|servers| servers.get("ai-memory"))+ .is_some()+ })+ .then_some(config);+ if report.plugin.enabled {+ report.hook_trust = super::codex_hook_trust::probe(+ Path::new("codex"),+ super::codex_hook_trust::HookSource::Plugin(+ super::agent_plugins::PLUGIN_ID,+ ),+ cwd,+ )+ .await;+ }+ }+ }+ reports.push(report);+ }+ reports+}++/// Whether an ai-memory-managed routing skill sits under `skills`.+fn managed_skill_installed(skills: &Path) -> bool {+ ai_memory_core::routing_skills::MANAGED_SKILLS+ .iter()+ .any(|skill| {+ std::fs::read_to_string(skills.join(skill.relative_path))+ .is_ok_and(|text| text.contains(ai_memory_core::routing_skills::MANAGED_MARKER))+ })+}++/// Whether the JSON MCP config at `path` registers an `ai-memory` server.+fn json_mcp_entry(path: &Path) -> bool {+ std::fs::read_to_string(path)+ .ok()+ .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())+ .is_some_and(|doc| {+ doc.get("mcpServers")+ .and_then(|s| s.get("ai-memory"))+ .is_some()+ })+}++/// The Claude Code user setting that keeps plugin hooks from running.+fn claude_hooks_disabled_by(settings: &Path) -> Option<&'static str> {+ let doc: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(settings).ok()?).ok()?;+ let set = |key: &str| doc.get(key).and_then(serde_json::Value::as_bool) == Some(true);+ if set("disableAllHooks") {+ Some("disableAllHooks")+ } else if set("allowManagedHooksOnly") {+ Some("allowManagedHooksOnly")+ } else {+ None+ }+}++/// Human lines for the installed plugins; empty without any.+fn render_plugins(plugins: &[PluginReport]) -> String {+ use super::agent_plugins::{PLUGIN_ID, PluginHarness};+ let mut out = String::new();+ for report in plugins {+ let plugin = &report.plugin;+ let agent = plugin.harness.agent();+ out.push_str(&format!(+ " plugin: {PLUGIN_ID} {} for {agent} ({})\n",+ plugin.version.as_deref().unwrap_or("(version unknown)"),+ if plugin.enabled {+ "enabled"+ } else {+ "disabled"+ },+ ));+ if !plugin.enabled {+ continue;+ }+ if let Some(version) = plugin.version_skew() {+ out.push_str(&format!(+ "⚠ The {agent} plugin is {version} but this binary is {}. Run `ai-memory \+ upgrade` (it updates the Claude Code plugin too) or update the plugin in {agent}.\n",+ report.binary_version+ ));+ }+ if let Some(path) = &report.settings_hooks {+ let consequence = match plugin.harness {+ PluginHarness::ClaudeCode => {+ "The settings hooks win and the plugin skips every event they deliver, so \+ nothing is captured twice"+ }+ PluginHarness::Codex => "Codex runs both, so each event is captured twice",+ };+ out.push_str(&format!(+ "⚠ {agent} also has ai-memory settings-file hooks in {}. {consequence}. Keep \+ one: remove the ai-memory entries from that file, or run `{}`.\n",+ path.display(),+ uninstall_line(plugin.harness),+ ));+ }+ if let Some(path) = &report.installed_skills {+ out.push_str(&format!(+ "⚠ The ai-memory routing skills are installed in {} as well as in the plugin, so \+ {agent} loads both copies. Keep one: `ai-memory uninstall --only skills --apply` \+ removes the installed ones.\n",+ path.display()+ ));+ }+ if let Some(path) = &report.settings_mcp {+ out.push_str(&format!(+ "⚠ An ai-memory MCP server is registered in {} as well as by the plugin, so \+ {agent} lists the memory tools twice. Keep one.\n",+ path.display()+ ));+ }+ if let Some(setting) = report.hooks_disabled_by {+ out.push_str(&format!(+ "⚠ {setting} is set in your Claude Code settings: the plugin's hooks do not run \+ and sessions are not captured.\n"+ ));+ }+ if let Some(trust) = &report.hook_trust+ && !trust.skipped.is_empty()+ {+ out.push_str(&format!(+ "⚠ Codex skips {} of the plugin's hooks (untrusted or modified). Open Codex, run \+ /hooks, and trust them; until then Codex sessions are not captured.\n",+ trust.skipped.len()+ ));+ }+ }+ out+}++fn uninstall_line(harness: super::agent_plugins::PluginHarness) -> String {+ let (program, args) = harness.uninstall_command();+ format!("{program} {}", args.join(" "))}/// Human lines for the spool, the server and the Codex hook trust; empty@@ -800,6 +1026,7 @@ fn render_human(report: &DoctorReport) {println!(" capture coverage: unavailable ({})", problem.reason);}print!("{}", render_capture_health(report));+ print!("{}", render_plugins(&report.plugins));print!("{}",super::agentmemory_residue::render(&report.agentmemory_residue)@@ -930,7 +1157,66 @@ mod tests {server_unreachable,codex_hooks,agentmemory_residue: Vec::new(),+ plugins: Vec::new(),+ }+ }++ /// Doctor reports the plugin and every way the same harness is wired+ /// twice: settings hooks, installed skills, a second MCP entry, a setting+ /// that disables plugin hooks, and version skew. A plugin alone is quiet.+ #[tokio::test]+ async fn plugin_report_names_double_wiring_and_skew() {+ use crate::commands::agent_plugins::test_support::install_claude_plugin;+ let home = tempfile::tempdir().unwrap();+ let cwd = home.path().join("work");+ std::fs::create_dir_all(&cwd).unwrap();+ let env = |_: &str| None;+ assert!(plugin_reports(home.path(), &cwd, &env).await.is_empty());++ install_claude_plugin(home.path(), env!("CARGO_PKG_VERSION"), true);+ let reports = plugin_reports(home.path(), &cwd, &env).await;+ assert_eq!(reports.len(), 1);+ let quiet = render_plugins(&reports);+ assert!(quiet.contains("plugin: ai-memory@ai-memory"), "{quiet}");+ assert!(!quiet.contains('⚠'), "{quiet}");++ install_claude_plugin(home.path(), "0.0.1", true);+ let root = home.path().join(".claude");+ let settings = root.join("settings.json");+ let mut doc: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();+ doc["hooks"] = serde_json::json!({"Stop": [{"matcher": "", "hooks": [{"type": "command",+ "command": "/bin/ai-memory hook --event stop --agent claude-code --server-url http://h"}]}]});+ doc["disableAllHooks"] = true.into();+ std::fs::write(&settings, doc.to_string()).unwrap();+ let skill = &ai_memory_core::routing_skills::MANAGED_SKILLS[0];+ let skill_path = root.join("skills").join(skill.relative_path);+ std::fs::create_dir_all(skill_path.parent().unwrap()).unwrap();+ std::fs::write(&skill_path, skill.content).unwrap();+ std::fs::write(+ home.path().join(".claude.json"),+ r#"{"mcpServers":{"ai-memory":{"command":"ai-memory"}}}"#,+ )+ .unwrap();+ let reports = plugin_reports(home.path(), &cwd, &env).await;+ let report = &reports[0];+ assert_eq!(report.settings_hooks.as_deref(), Some(settings.as_path()));+ assert!(report.installed_skills.is_some());+ assert!(report.settings_mcp.is_some());+ assert_eq!(report.hooks_disabled_by, Some("disableAllHooks"));+ let out = render_plugins(&reports);+ for needle in [+ "is 0.0.1 but this binary is",+ "settings-file hooks",+ "loads both copies",+ "lists the memory tools twice",+ "disableAllHooks is set",+ ] {+ assert!(out.contains(needle), "{needle}: {out}");}+ let json = serde_json::to_value(report).unwrap();+ assert_eq!(json["harness"], "claude-code");+ assert_eq!(json["version"], "0.0.1");}/// A dead server, a full spool and Codex hooks Codex skips are each silentdiff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 1b3564b6..6ea42772 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -26,6 +26,7 @@ pub(crate) fn is_scope_ambiguous(error: &anyhow::Error) -> bool {})}+pub(crate) mod agent_plugins;pub(crate) mod agentmemory_residue;pub mod api_key;pub mod apply_shared;diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rsindex cb5b4a35..7ecfda74 100644--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@ -484,6 +484,22 @@ pub(crate) fn ensure_wired_with_env(if targets.sentinel.exists() {return;}+ if let Some(harness) = plugin_harness(targets.agent)+ && let Some(home) = super::run::native_home(config)+ && super::agent_plugins::enabled(harness, &home, &|name| {+ effective_env.get(name).map(OsStr::to_os_string)+ })+ .is_some()+ {+ // No sentinel: the check is two small file reads, and a later+ // `claude plugin uninstall` must let the next launch wire again.+ eprintln!(+ "ai-memory: the ai-memory plugin is enabled in {}; it carries the hooks and MCP \+ entry, so this launch wires nothing for it.",+ harness.agent()+ );+ return;+ }let agent = targets.agent;let sentinel = targets.sentinel.clone();let project_hooks = targets.project_hooks.clone();@@ -611,6 +627,15 @@ pub(crate) fn ensure_wired_with_env(}}+/// The marketplace plugin that covers `agent`'s wiring, when one exists.+fn plugin_harness(agent: AgentChoice) -> Option<super::agent_plugins::PluginHarness> {+ match agent {+ AgentChoice::ClaudeCode => Some(super::agent_plugins::PluginHarness::ClaudeCode),+ AgentChoice::Codex => Some(super::agent_plugins::PluginHarness::Codex),+ _ => None,+ }+}+/// The `--scope project` Claude Code install covering `launch_cwd`, if any./// The operator chose per-checkout capture there, so auto-wire must not add/// the same hooks to the user-level file on top of it. The path also keys the@@ -1671,6 +1696,66 @@ mod tests {assert!(sentinel.exists(), "the completed wiring is recorded");}+ /// An enabled ai-memory Claude Code plugin already carries the hooks and+ /// MCP entry, so a managed launch writes neither (adversarial: the files+ /// stay absent). Control: with the plugin disabled the same launch wires+ /// both, so the plugin state is what decided it.+ #[test]+ fn an_enabled_plugin_leaves_the_harness_unwired() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ crate::commands::agent_plugins::test_support::install_claude_plugin(+ home.path(),+ "3.0.0",+ true,+ );+ let claude = home.path().join(".claude");+ let settings = claude.join("settings.json");+ let mcp = claude.join(".claude.json");++ let mut config = test_config(home.path(), data.path());+ config.home_dir = Some(home.path().to_string_lossy().into_owned());+ let overrides = WireOverrides {+ hooks_dir: Some(repo_hooks()),+ hooks_config_file: Some(settings.clone()),+ mcp_config_file: Some(mcp.clone()),+ ..WireOverrides::default()+ };+ let run_env = env_pair("CLAUDE_CONFIG_DIR", &claude);+ ensure_wired_with(+ &config,+ ManagedHarness::Claude,+ &overrides,+ &run_env,+ &config.data_dir,+ );+ assert!(+ !std::fs::read_to_string(&settings)+ .unwrap()+ .contains("\"hooks\""),+ "no settings hooks beside the plugin"+ );+ assert!(!mcp.exists(), "no MCP entry beside the plugin");++ crate::commands::agent_plugins::test_support::install_claude_plugin(+ home.path(),+ "3.0.0",+ false,+ );+ ensure_wired_with(+ &config,+ ManagedHarness::Claude,+ &overrides,+ &run_env,+ &config.data_dir,+ );+ assert!(+ install_hooks::settings_file_carries_ai_memory_hooks(&settings),+ "a disabled plugin is wired around as before"+ );+ assert!(mcp.exists());+ }+/// The load-bearing "won't mess up any harness" guarantee: auto-wire installs/// the harness's hooks + MCP while preserving unrelated user config, and a/// second launch is a clean no-op (no duplication, no churn). Paths arediff --git a/crates/ai-memory-cli/src/commands/setup.rs b/crates/ai-memory-cli/src/commands/setup.rsindex 6d193aa8..d2b98e04 100644--- a/crates/ai-memory-cli/src/commands/setup.rs+++ b/crates/ai-memory-cli/src/commands/setup.rs@@ -34,7 +34,9 @@ use ai_memory_workstream::{ManagedHarness, OpenCodeDialect, native_store_root};use anyhow::{Context as _, Result, bail};use super::user_service::{self, CommandRunner, ServiceChange, ServiceManager, ServiceUnit};-use super::{doctor, init, install_hooks, install_mcp, install_skills, run_autowire};+use super::{+ agent_plugins, doctor, init, install_hooks, install_mcp, install_skills, run_autowire,+};use crate::cli::{AgentChoice, DoctorArgs, HookInstallScope, InitArgs, InstallHooksArgs, InstallMcpArgs,InstallSkillsAgent, InstallSkillsArgs, InstallSkillsScope, McpClient, SetupArgs,@@ -80,6 +82,9 @@ struct AgentPlan {agent: AgentChoice,mcp: Option<McpClient>,skills: InstallSkillsAgent,+ /// The ai-memory marketplace plugin is enabled for this agent: it carries+ /// the hooks, MCP entry and skills, so setup writes none of them (#1166).+ plugin: bool,}impl AgentPlan {@@ -88,6 +93,21 @@ impl AgentPlan {agent,mcp: install_hooks::mcp_client_for_agent(agent),skills: skills_for(agent),+ plugin: false,+ }+ }++ /// [`Self::new`], with the plugin state of `agent` under `home`.+ fn detect(agent: AgentChoice, home: &Path, env: &dyn Fn(&str) -> Option<OsString>) -> Self {+ let harness = match agent {+ AgentChoice::ClaudeCode => Some(agent_plugins::PluginHarness::ClaudeCode),+ AgentChoice::Codex => Some(agent_plugins::PluginHarness::Codex),+ _ => None,+ };+ Self {+ plugin: harness+ .is_some_and(|harness| agent_plugins::enabled(harness, home, env).is_some()),+ ..Self::new(agent)}}}@@ -169,7 +189,10 @@ pub async fn run(config: &Config, args: SetupArgs, config_path: Option<&Path>) -fresh: !written_config.exists(),config_path: written_config,service,- agents: agents.into_iter().map(AgentPlan::new).collect(),+ agents: agents+ .into_iter()+ .map(|agent| AgentPlan::detect(agent, &home, &env))+ .collect(),detected: args.agents.is_empty(),};@@ -290,6 +313,14 @@ fn print_plan(plan: &SetupPlan) {}for agent in &plan.agents {let name = agent.agent.kind().as_str();+ if agent.plugin {+ println!(+ " - leave {name} to its enabled ai-memory plugin ({}), which carries the \+ hooks, MCP entry and skills",+ agent_plugins::PLUGIN_ID+ );+ continue;+ }let mcp = if agent.mcp.is_some() {"MCP + hooks"} else {@@ -457,6 +488,18 @@ async fn wait_until_reachable(endpoint: &ServerEndpoint, timeout: Duration) -> b/// failures.fn wire_agent(config: &Config, plan: AgentPlan, skills_done: &mut BTreeSet<String>) -> Vec<String> {let mut problems = Vec::new();+ if plan.plugin {+ // Writing the settings-file wiring as well would load every skill+ // twice and register a second MCP server; the hook copies would be+ // de-duplicated, but nothing would be gained.+ println!(+ "plugin: {} is enabled; leaving the settings-file hooks, MCP entry and skills \+ alone (run `ai-memory install-hooks --agent {} --apply` to add them anyway)",+ agent_plugins::PLUGIN_ID,+ plan.agent.kind().as_str()+ );+ return problems;+ }let dialect = opencode_dialect(plan.agent);if let Some(client) = plan.mcp {if install_mcp::existing_entry_is_session_aware(client, None, ENTRY_NAME) {@@ -582,6 +625,28 @@ async fn memory_status(config: &Config) -> Result<()> {mod tests {use super::*;+ /// An enabled plugin takes an agent's wiring over; a disabled or absent+ /// one, and an agent the plugins do not cover, keep the full plan.+ #[test]+ fn an_enabled_plugin_takes_over_the_agents_wiring() {+ use crate::commands::agent_plugins::test_support::{+ install_claude_plugin, install_codex_plugin,+ };+ let home = tempfile::tempdir().unwrap();+ let env = |_: &str| None;+ assert!(!AgentPlan::detect(AgentChoice::ClaudeCode, home.path(), &env).plugin);++ install_claude_plugin(home.path(), "3.0.0", false);+ assert!(!AgentPlan::detect(AgentChoice::ClaudeCode, home.path(), &env).plugin);+ install_claude_plugin(home.path(), "3.0.0", true);+ assert!(AgentPlan::detect(AgentChoice::ClaudeCode, home.path(), &env).plugin);+ assert!(!AgentPlan::detect(AgentChoice::Codex, home.path(), &env).plugin);+ assert!(!AgentPlan::detect(AgentChoice::Grok, home.path(), &env).plugin);++ install_codex_plugin(home.path());+ assert!(AgentPlan::detect(AgentChoice::Codex, home.path(), &env).plugin);+ }+/// A token-file install learns how to open the web UI: the URL and the/// file to read, never the token. An inline or absent token prints no hint.#[test]diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex c789f866..c8a43cff 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -15,7 +15,7 @@ use crate::commands::path_util::{agent_config_home, claude_config_dir, claude_config_paths, home_dir,};use crate::commands::user_service::{self, ServiceManager};-use crate::commands::{data_purge, install_hooks, install_mcp, openclaw_plugin};+use crate::commands::{agent_plugins, data_purge, install_hooks, install_mcp, openclaw_plugin};use crate::config::Config;use ai_memory_core::routing_skills::{AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, COPILOT_SKILL_DIR, DEVIN_SKILL_DIR, GITHUB_SKILL_DIR,@@ -729,6 +729,17 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {let plan = build_plan(&args, &config.data_dir)?;print_plan(&plan);+ // The marketplace plugins carry hooks, MCP and skills together, so only a+ // full uninstall removes them; the harness's own CLI does the removal.+ let plugins = if args.only.is_none() {+ installed_plugins(config)+ } else {+ Vec::new()+ };+ for plugin in &plugins {+ let (program, plugin_args) = plugin.harness.uninstall_command();+ println!("would run `{program} {}`", plugin_args.join(" "));+ }let service = if args.only.is_none() {setup_service(config)} else {@@ -756,7 +767,7 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {println!("(dry-run; pass --apply to remove)");return Ok(());}- if plan.is_empty() && !args.purge_data && !remove_service {+ if plan.is_empty() && plugins.is_empty() && !args.purge_data && !remove_service {return Ok(());}@@ -810,6 +821,8 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {apply_change(change, private_backup.as_ref(), name.as_deref(), &url)?;}+ uninstall_plugins(&plugins, &user_service::SystemRunner);+// Removing the hooks removes the only readers of the stored bearer, so// leaving it on disk would strand a live credential (#552). An uninstall// that keeps the hooks (`--only mcp|instructions|skills`) keeps it: the@@ -846,6 +859,43 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {Ok(())}+/// The ai-memory marketplace plugins installed for this user.+fn installed_plugins(config: &Config) -> Vec<agent_plugins::InstalledPlugin> {+ let Some(home) = crate::commands::run::native_home(config) else {+ return Vec::new();+ };+ agent_plugins::installed(&home, &|name| {+ config+ .runtime_env+ .process_env()+ .iter()+ .find(|(key, _)| key.as_os_str() == name)+ .map(|(_, value)| value.clone())+ })+}++/// Remove each plugin through its harness's CLI. A failure is reported with+/// the command to run, and never stops the rest of the teardown.+fn uninstall_plugins(+ plugins: &[agent_plugins::InstalledPlugin],+ runner: &dyn user_service::CommandRunner,+) {+ for plugin in plugins {+ let (program, args) = plugin.harness.uninstall_command();+ let shown = format!("{program} {}", args.join(" "));+ match runner.run(program, &args) {+ Ok(outcome) if outcome.success => println!("✓ {shown}"),+ Ok(outcome) => eprintln!(+ "ai-memory uninstall warning: `{shown}` failed ({}); run it yourself",+ outcome.stderr.trim()+ ),+ Err(error) => eprintln!(+ "ai-memory uninstall warning: could not run `{shown}` ({error:#}); run it yourself"+ ),+ }+ }+}+/// The user service `setup` installs on this platform and what uninstall/// would do about it; `None` on a platform without one or with no home.fn setup_service(config: &Config) -> Option<(ServiceManager, user_service::Removal)> {@@ -1584,6 +1634,35 @@ fn strip_mcp_toml(content: &str, name: Option<&str>, url: &str) -> Result<(Strinmod tests {use super::*;+ /// Each installed plugin is removed through its own harness CLI, and one+ /// failure does not stop the next.+ #[test]+ fn uninstall_removes_each_plugin_through_its_harness() {+ use crate::commands::agent_plugins::test_support::{+ RecordingRunner, install_claude_plugin, install_codex_plugin,+ };+ let home = tempfile::tempdir().unwrap();+ let config = Config {+ home_dir: Some(home.path().to_string_lossy().into_owned()),+ ..Config::default()+ };+ assert!(installed_plugins(&config).is_empty());+ install_claude_plugin(home.path(), "3.0.0", false);+ install_codex_plugin(home.path());+ let plugins = installed_plugins(&config);+ assert_eq!(plugins.len(), 2, "a disabled plugin is still removed");++ let runner = RecordingRunner::new(Some(1));+ uninstall_plugins(&plugins, &runner);+ assert_eq!(+ *runner.calls.borrow(),+ vec![+ "claude plugin uninstall ai-memory@ai-memory",+ "codex plugin remove ai-memory@ai-memory"+ ]+ );+ }+/// The Windows global Devin skill root (`%APPDATA%\devin\skills`) is/// swept alongside the cwd/home roots — `install-skills --scope global`/// writes there on Windows, so uninstall must plan its removal too.diff --git a/crates/ai-memory-cli/src/commands/upgrade.rs b/crates/ai-memory-cli/src/commands/upgrade.rsindex bb8fc511..6a52f127 100644--- a/crates/ai-memory-cli/src/commands/upgrade.rs+++ b/crates/ai-memory-cli/src/commands/upgrade.rs@@ -72,6 +72,7 @@ pub async fn run(config: &Config, args: UpgradeArgs) -> Result<()> {let base = release_base_url(config);let tag = resolve_tag(&fetcher, &base, args.version.as_deref()).await?;if skip_when_current(&tag, args.force) {+ refresh_plugins(config, &super::user_service::SystemRunner);return Ok(());}@@ -80,6 +81,7 @@ pub async fn run(config: &Config, args: UpgradeArgs) -> Result<()> {// Sync FS after await is intentional for this CLI one-shot path.refresh_staged_hooks(config)?;+ refresh_plugins(config, &super::user_service::SystemRunner);warn_remote_server(config);println!("✓ upgraded to {tag}");info!(%tag, path = %exe.display(), "native upgrade complete");@@ -802,6 +804,41 @@ fn refresh_staged_hooks(config: &Config) -> Result<()> {Ok(())}+/// Keep the marketplace plugins in step with the binary (#1166). Claude Code+/// does not auto-update a third-party marketplace unless the user turned that+/// on, so the Claude Code plugin is updated here. Codex is only told what to+/// run: its hooks must be re-trusted only when a command changes, and the+/// operator should see that happen in Codex itself.+fn refresh_plugins(config: &Config, runner: &dyn super::user_service::CommandRunner) {+ use super::agent_plugins::{self, PluginHarness};+ let Some(home) = super::run::native_home(config) else {+ return;+ };+ let env = |name: &str| {+ config+ .runtime_env+ .process_env()+ .iter()+ .find(|(key, _)| key.as_os_str() == name)+ .map(|(_, value)| value.clone())+ };+ for plugin in agent_plugins::installed(&home, &env) {+ match plugin.harness {+ PluginHarness::ClaudeCode => {+ println!("→ updating the ai-memory Claude Code plugin");+ for line in agent_plugins::update_claude_code(runner) {+ println!(" {line}");+ }+ }+ PluginHarness::Codex => println!(+ "→ the ai-memory Codex plugin is installed: run `codex plugin marketplace upgrade \+ ai-memory` and `codex plugin add {}` to update it",+ agent_plugins::PLUGIN_ID+ ),+ }+ }+}+fn staged_hooks_root(config: &Config) -> PathBuf {install_hooks::hook_staging_root(&config.data_dir,@@ -1041,6 +1078,37 @@ mod tests {use zip::ZipWriter;use zip::write::SimpleFileOptions;+ /// `upgrade` keeps an installed Claude Code plugin in step with the+ /// binary: marketplace update, then plugin update. Without the plugin,+ /// and for the Codex plugin, it runs nothing.+ #[test]+ fn upgrade_updates_an_installed_claude_code_plugin_only() {+ use crate::commands::agent_plugins::test_support::{+ RecordingRunner, install_claude_plugin, install_codex_plugin,+ };+ let home = tempfile::tempdir().unwrap();+ let config = Config {+ home_dir: Some(home.path().to_string_lossy().into_owned()),+ ..Config::default()+ };++ let runner = RecordingRunner::new(None);+ refresh_plugins(&config, &runner);+ install_codex_plugin(home.path());+ refresh_plugins(&config, &runner);+ assert!(runner.calls.borrow().is_empty(), "{:?}", runner.calls);++ install_claude_plugin(home.path(), "0.0.1", true);+ refresh_plugins(&config, &runner);+ assert_eq!(+ *runner.calls.borrow(),+ vec![+ "claude plugin marketplace update ai-memory",+ "claude plugin update ai-memory@ai-memory"+ ]+ );+ }+#[test]fn release_asset_name_for_covers_unix_and_windows_matrix() {// Table-driven so Linux CI still guards macos-* and windows mapping.