Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(plugins): attribute the Claude plugin to Muse Code when Muse runs it
AkitaOnRailsf5914c86e3f7
diff --git a/crates/ai-memory-cli/src/commands/plugin_origin.rs b/crates/ai-memory-cli/src/commands/plugin_origin.rsindex 053b720c..3bae08a5 100644--- a/crates/ai-memory-cli/src/commands/plugin_origin.rs+++ b/crates/ai-memory-cli/src/commands/plugin_origin.rs@@ -21,7 +21,7 @@use std::path::{Component, Path, PathBuf};use super::install_hooks::{self, HooksFileShape};-use super::render_shared::{CLAUDE_CODE_EVENTS, DROID_EVENTS};+use super::render_shared::{CLAUDE_CODE_EVENTS, DROID_EVENTS, MUSE_EVENTS};/// The environment variable the plugin launcher sets.pub(crate) const HOOK_ORIGIN_ENV: &str = "AI_MEMORY_HOOK_ORIGIN";@@ -36,6 +36,10 @@ pub(crate) enum PluginOrigin {/// The Claude Code plugin loaded by Factory Droid through its Claude/// plugin compatibility (the launcher re-attributes it to `droid`).Droid,+ /// The Claude Code plugin loaded by Meta Muse Code, which reads+ /// `.claude-plugin/plugin.json` plugins (the launcher re-attributes it to+ /// `muse`).+ Muse,}impl PluginOrigin {@@ -46,6 +50,7 @@ impl PluginOrigin {"claude-code-plugin" => Some(Self::ClaudeCode),"codex-plugin" => Some(Self::Codex),"droid-plugin" => Some(Self::Droid),+ "muse-plugin" => Some(Self::Muse),_ => None,}}@@ -68,7 +73,10 @@ pub(crate) fn drops_plugin_event(return true;}let Some(name) = settings_event_name(origin, event) else {- return false;+ // Muse's subagent events come from its built-in reminder observers,+ // each under its own session id, every turn; `install-hooks --agent+ // muse` leaves them out, and so does the plugin.+ return origin == PluginOrigin::Muse;};settings_files.iter()@@ -92,6 +100,12 @@ pub(crate) fn drops_plugin_event(/// exists; otherwise the `hooks` key of `~/.factory/settings.json`, which/// Droid reads only while `hooks.json` is absent. Checking a file Droid/// ignores could drop the plugin copy of an event nothing else delivers.+///+/// Muse: the `hooks` key of `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`,+/// the one file `install-hooks --agent muse` writes. Muse runs hooks with a+/// cleared environment (`HOME`, `PATH`, `PWD` and its own `MUSE_*`), so an+/// `XDG_CONFIG_HOME` Muse itself honoured is usually not visible here and the+/// default location is checked; the plugin copy is then kept, never lost.pub(crate) fn settings_files_for(origin: PluginOrigin,cwd: Option<&str>,@@ -138,6 +152,16 @@ pub(crate) fn settings_files_for()]}}+ PluginOrigin::Muse => {+ let home = lookup("AI_MEMORY_HOME")+ .filter(|home| !home.trim().is_empty())+ .map(PathBuf::from)+ .or_else(super::path_util::home_dir);+ let xdg = lookup("XDG_CONFIG_HOME").map(std::ffi::OsString::from);+ super::install_mcp::muse_settings_path_in(xdg, home)+ .map(|settings| vec![(settings, HooksFileShape::HooksKey)])+ .unwrap_or_default()+ }}}@@ -153,6 +177,10 @@ fn settings_event_name(origin: PluginOrigin, event: &str) -> Option<&'static str.iter().find(|(_, script)| script.strip_suffix(".sh") == Some(event)).map(|(name, _)| *name),+ PluginOrigin::Muse => MUSE_EVENTS+ .iter()+ .find(|(_, script)| script.strip_suffix(".sh") == Some(event))+ .map(|(name, _)| *name),PluginOrigin::Codex => None,}}@@ -212,6 +240,10 @@ mod tests {PluginOrigin::from_env(lookup(&[(HOOK_ORIGIN_ENV, "droid-plugin")])),Some(PluginOrigin::Droid));+ assert_eq!(+ PluginOrigin::from_env(lookup(&[(HOOK_ORIGIN_ENV, "muse-plugin")])),+ Some(PluginOrigin::Muse)+ );for other in ["", "claude-code", "cursor-plugin", "settings"] {assert_eq!(PluginOrigin::from_env(lookup(&[(HOOK_ORIGIN_ENV, other)])),@@ -406,6 +438,88 @@ mod tests {));}+ const MUSE_SETTINGS: &str = r#"{"schema_version":1,"hooks":{"SessionStart":[{"matcher":"","hooks":[{"type":"command","command":"/usr/bin/ai-memory hook --event session-start --agent muse --server-url http://127.0.0.1:49374","timeout":30}]}],"Stop":[{"matcher":"write_file","hooks":[{"type":"command","command":"/usr/bin/ai-memory hook --event stop --agent muse --server-url http://127.0.0.1:49374"}]}]}}"#;++ fn muse_drops(home: &Path, xdg: Option<&Path>, event: &str) -> bool {+ let home = home.to_string_lossy().into_owned();+ let xdg = xdg.map(|dir| dir.to_string_lossy().into_owned());+ let mut pairs = vec![("AI_MEMORY_HOME", home.as_str())];+ if let Some(xdg) = &xdg {+ pairs.push(("XDG_CONFIG_HOME", xdg.as_str()));+ }+ let files = settings_files_for(PluginOrigin::Muse, Some("/work/repo"), lookup(&pairs));+ drops_plugin_event(PluginOrigin::Muse, event, Some("/work/repo"), &files)+ }++ /// Adversarial: Muse running the Claude Code plugin next to an+ /// `install-hooks --agent muse` install delivers each event twice unless+ /// the plugin copy is dropped. Only a catch-all matcher counts: a hook+ /// narrowed to one tool does not deliver every occurrence. Controls: no+ /// Muse settings at all, and an event the settings do not wire, keep the+ /// plugin copy. The plugin's subagent events are always dropped, as+ /// `install-hooks --agent muse` never wires them.+ #[test]+ fn muse_plugin_copy_is_dropped_when_muse_settings_hooks_deliver_the_event() {+ let temp = tempfile::tempdir().unwrap();+ let muse = temp.path().join(".config").join("muse");+ std::fs::create_dir_all(&muse).unwrap();+ assert!(+ !muse_drops(temp.path(), None, "session-start"),+ "nothing installed"+ );++ std::fs::write(muse.join("settings.json"), MUSE_SETTINGS).unwrap();+ assert!(muse_drops(temp.path(), None, "session-start"));+ assert!(+ !muse_drops(temp.path(), None, "stop"),+ "a Stop hook narrowed by a matcher does not deliver every event"+ );+ assert!(+ !muse_drops(temp.path(), None, "user-prompt-submit"),+ "an event settings.json does not wire stays with the plugin"+ );+ for event in ["subagent-start", "subagent-stop"] {+ assert!(muse_drops(temp.path(), None, event), "{event}");+ }+ assert!(+ !drops_plugin_event(+ PluginOrigin::ClaudeCode,+ "subagent-start",+ Some("/work/repo"),+ &[]+ ),+ "control: Claude Code keeps its subagent events"+ );+ }++ /// When the hook can see `XDG_CONFIG_HOME`, the settings file under it is+ /// the one checked, and the default location no longer counts.+ #[test]+ fn muse_settings_follow_a_visible_xdg_config_home() {+ let temp = tempfile::tempdir().unwrap();+ let xdg = temp.path().join("xdg");+ std::fs::create_dir_all(xdg.join("muse")).unwrap();+ std::fs::write(xdg.join("muse").join("settings.json"), MUSE_SETTINGS).unwrap();+ assert!(muse_drops(temp.path(), Some(&xdg), "session-start"));+ assert!(!muse_drops(temp.path(), None, "session-start"));+ }++ #[test]+ fn muse_plugin_skips_folderless_sessions() {+ assert!(drops_plugin_event(+ PluginOrigin::Muse,+ "user-prompt-submit",+ None,+ &[]+ ));+ assert!(!drops_plugin_event(+ PluginOrigin::Muse,+ "user-prompt-submit",+ Some("/work/repo"),+ &[]+ ));+ }+#[test]fn settings_files_honour_claude_config_dir_and_project_dir() {let files = settings_files_for(diff --git a/crates/ai-memory-cli/templates/plugin/ai-memory-hook.sh b/crates/ai-memory-cli/templates/plugin/ai-memory-hook.shindex f4826031..9d74df35 100644--- a/crates/ai-memory-cli/templates/plugin/ai-memory-hook.sh+++ b/crates/ai-memory-cli/templates/plugin/ai-memory-hook.sh@@ -28,9 +28,14 @@ reply_without_binary() {# Other harnesses can read the Claude Code plugin through their Claude# fallbacks. Attribute the event to the harness that really ran it, or stay# out of the way when ai-memory has no agent for it.+# Muse Code sets CLAUDE_PLUGIN_ROOT for the Claude plugins it loads, so it is+# told apart by the MUSE_PLUGIN_ID it adds for plugin hooks, next to the+# MUSE_SESSION_ID every Muse hook gets.if [ "$agent" = "claude-code" ]; thenif [ -n "${DROID_PLUGIN_ROOT:-}" ]; thenagent="droid"+ elif [ -n "${MUSE_PLUGIN_ID:-}" ] && [ -n "${MUSE_SESSION_ID:-}" ]; then+ agent="muse"elif [ -z "${CLAUDE_PLUGIN_ROOT:-}" ]; thenif [ -n "${PLUGIN_ROOT:-}" ]; thenagent="codex"diff --git a/crates/ai-memory-cli/tests/suite/plugins.rs b/crates/ai-memory-cli/tests/suite/plugins.rsindex 4b3eec81..2110e961 100644--- a/crates/ai-memory-cli/tests/suite/plugins.rs+++ b/crates/ai-memory-cli/tests/suite/plugins.rs@@ -227,6 +227,9 @@ mod launcher {.env_remove("CLAUDE_PROJECT_DIR").env_remove("PLUGIN_ROOT").env_remove("DROID_PLUGIN_ROOT")+ .env_remove("MUSE_PLUGIN_ID")+ .env_remove("MUSE_SESSION_ID")+ .env_remove("XDG_CONFIG_HOME").env("RUST_LOG", "off").stdin(Stdio::piped()).stdout(Stdio::piped())@@ -554,6 +557,77 @@ mod launcher {assert_eq!(sb.spooled().len(), 2, "folderless Droid session");}+ /// Front door 4 for Muse Code (adversarial): Muse loads the Claude Code+ /// plugin with `CLAUDE_PLUGIN_ROOT` set and adds `MUSE_PLUGIN_ID` and+ /// `MUSE_SESSION_ID`, and the launcher re-attributes it to `muse`. With+ /// the `install-hooks --agent muse` hook for the same event under the+ /// `hooks` key of `~/.config/muse/settings.json` the plugin copy is+ /// dropped. Controls: no Muse hooks keeps it, and so does a Claude+ /// settings hook, which Muse never runs; an unwired event stays with the+ /// plugin. The plugin's subagent events and a folderless session are+ /// never captured.+ #[test]+ fn a_muse_hook_for_the_same_event_drops_the_muse_plugin_copy() {+ let sb = Sandbox::new();+ let muse = [+ ("MUSE_PLUGIN_ID", "ai-memory"),+ ("MUSE_SESSION_ID", "01a13669-dc61-7a72-b5ec-ad2f300ffd26"),+ ];++ sb.settings_hook(+ &sb.claude.join("settings.json"),+ "UserPromptSubmit",+ "user-prompt-submit",+ );+ sb.launch("user-prompt-submit", &sb.prompt(), &muse);+ assert_eq!(sb.spooled().len(), 1, "control: no Muse hook");+ assert!(+ sb.spooled()[0]["url"]+ .as_str()+ .unwrap()+ .contains("agent=muse")+ );++ let settings = sb.home.join(".config").join("muse");+ std::fs::create_dir_all(&settings).unwrap();+ let command = format!(+ "{BIN} hook --event user-prompt-submit --agent muse --server-url {}",+ sb.server+ );+ std::fs::write(+ settings.join("settings.json"),+ json!({+ "schema_version": 1,+ "hooks": {"UserPromptSubmit": [{"matcher": "", "hooks": [{"type": "command", "command": command, "timeout": 30}]}]}+ })+ .to_string(),+ )+ .unwrap();+ sb.launch("user-prompt-submit", &sb.prompt(), &muse);+ assert_eq!(+ sb.spooled().len(),+ 1,+ "Muse settings.json: plugin copy dropped"+ );++ sb.launch("post-tool-use", &sb.read_tool("README.md"), &muse);+ assert_eq!(+ sb.spooled().len(),+ 2,+ "an unwired event stays with the plugin"+ );++ sb.launch("subagent-start", &sb.prompt(), &muse);+ assert_eq!(sb.spooled().len(), 2, "Muse subagent events are dropped");++ sb.launch(+ "user-prompt-submit",+ &json!({"session_id": "s", "prompt": "no cwd"}),+ &muse,+ );+ assert_eq!(sb.spooled().len(), 2, "folderless Muse session");+ }+/// The committed hooks.json command still works when the launcher lost/// its exec bit (a desktop zip upload, a Windows checkout): Claude Code/// runs the command line through a shell, and it starts the launcher@@ -591,6 +665,9 @@ mod launcher {.env_remove("CLAUDE_PROJECT_DIR").env_remove("PLUGIN_ROOT").env_remove("DROID_PLUGIN_ROOT")+ .env_remove("MUSE_PLUGIN_ID")+ .env_remove("MUSE_SESSION_ID")+ .env_remove("XDG_CONFIG_HOME").env("RUST_LOG", "off").stdin(Stdio::piped()).stdout(Stdio::piped())@@ -662,6 +739,14 @@ mod launcher {&sb.prompt(),&[("CLAUDE_PLUGIN_ROOT", ""), ("PLUGIN_ROOT", &root)],);+ sb.launch(+ "user-prompt-submit",+ &sb.prompt(),+ &[+ ("MUSE_PLUGIN_ID", "ai-memory"),+ ("MUSE_SESSION_ID", "01a13669-dc61-7a72-b5ec-ad2f300ffd26"),+ ],+ );let out = sb.launch("user-prompt-submit",&sb.prompt(),@@ -680,6 +765,6 @@ mod launcher {}).collect();agents.sort();- assert_eq!(agents, vec!["codex", "droid"]);+ assert_eq!(agents, vec!["codex", "droid", "muse"]);}}diff --git a/docs/design-marketplace-plugins.md b/docs/design-marketplace-plugins.mdindex 8c24ecfa..079c1694 100644--- a/docs/design-marketplace-plugins.md+++ b/docs/design-marketplace-plugins.md@@ -401,7 +401,15 @@ our repository would install the Claude plugin and send events tagged`~/.factory/settings.json`). Cursor is not remapped: when Cursor runs Claudehooks the event already reaches the existing #721 path as `claude-code`with `cursor_version`, and whether Cursor runs *plugin* hooks at all is- one of the Cursor unknowns;+ one of the Cursor unknowns. *Shipped:* Meta Muse Code sets+ `CLAUDE_PLUGIN_ROOT` for the Claude plugins it loads, so it is told apart+ by `MUSE_PLUGIN_ID` together with `MUSE_SESSION_ID` (both seen in a Muse+ Code 1.4.7 plugin hook) → `muse`, with `AI_MEMORY_HOOK_ORIGIN=muse-plugin`,+ the folderless skip, de-duplication against the `hooks` key of+ `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`, and the plugin's+ subagent events dropped. Muse Code 1.4.7 refuses to install the published+ plugin because its `.mcp.json` uses `${user_config.*}` placeholders, so this+ path is exercised only with a copy that has no `.mcp.json`;- we ship a native catalog for each harness we support, so the fallback isnever used.diff --git a/plugins/claude-code/scripts/ai-memory-hook b/plugins/claude-code/scripts/ai-memory-hookindex f4826031..9d74df35 100755--- a/plugins/claude-code/scripts/ai-memory-hook+++ b/plugins/claude-code/scripts/ai-memory-hook@@ -28,9 +28,14 @@ reply_without_binary() {# Other harnesses can read the Claude Code plugin through their Claude# fallbacks. Attribute the event to the harness that really ran it, or stay# out of the way when ai-memory has no agent for it.+# Muse Code sets CLAUDE_PLUGIN_ROOT for the Claude plugins it loads, so it is+# told apart by the MUSE_PLUGIN_ID it adds for plugin hooks, next to the+# MUSE_SESSION_ID every Muse hook gets.if [ "$agent" = "claude-code" ]; thenif [ -n "${DROID_PLUGIN_ROOT:-}" ]; thenagent="droid"+ elif [ -n "${MUSE_PLUGIN_ID:-}" ] && [ -n "${MUSE_SESSION_ID:-}" ]; then+ agent="muse"elif [ -z "${CLAUDE_PLUGIN_ROOT:-}" ]; thenif [ -n "${PLUGIN_ROOT:-}" ]; thenagent="codex"diff --git a/plugins/codex/scripts/ai-memory-hook b/plugins/codex/scripts/ai-memory-hookindex f4826031..9d74df35 100755--- a/plugins/codex/scripts/ai-memory-hook+++ b/plugins/codex/scripts/ai-memory-hook@@ -28,9 +28,14 @@ reply_without_binary() {# Other harnesses can read the Claude Code plugin through their Claude# fallbacks. Attribute the event to the harness that really ran it, or stay# out of the way when ai-memory has no agent for it.+# Muse Code sets CLAUDE_PLUGIN_ROOT for the Claude plugins it loads, so it is+# told apart by the MUSE_PLUGIN_ID it adds for plugin hooks, next to the+# MUSE_SESSION_ID every Muse hook gets.if [ "$agent" = "claude-code" ]; thenif [ -n "${DROID_PLUGIN_ROOT:-}" ]; thenagent="droid"+ elif [ -n "${MUSE_PLUGIN_ID:-}" ] && [ -n "${MUSE_SESSION_ID:-}" ]; then+ agent="muse"elif [ -z "${CLAUDE_PLUGIN_ROOT:-}" ]; thenif [ -n "${PLUGIN_ROOT:-}" ]; thenagent="codex"diff --git a/tests/hooks/test_plugin_launcher.sh b/tests/hooks/test_plugin_launcher.shindex 44867915..175f07d2 100755--- a/tests/hooks/test_plugin_launcher.sh+++ b/tests/hooks/test_plugin_launcher.sh@@ -176,6 +176,19 @@ rm -f "$TMP/home/.local/bin/ai-memory"printf '{}' | run_launcher DROID_PLUGIN_ROOT="$TMP" CLAUDE_PLUGIN_ROOT="$PLUGIN_ROOT_DIR" \CLAUDE_PLUGIN_OPTION_AI_MEMORY_BIN="$STUB_DIR/ai-memory" sh "$LAUNCHER" claude-code stop >/dev/nullassert_eq "Droid is attributed to droid" "droid" "$(sed -n 5p "$TMP/argv")"+# Muse Code loads the Claude plugin with CLAUDE_PLUGIN_ROOT set and adds+# MUSE_PLUGIN_ID beside the MUSE_SESSION_ID every Muse hook gets.+printf '{}' | run_launcher MUSE_PLUGIN_ID="ai-memory" MUSE_SESSION_ID="01a13669-dc61-7a72-b5ec-ad2f300ffd26" \+ CLAUDE_PLUGIN_ROOT="$PLUGIN_ROOT_DIR" \+ CLAUDE_PLUGIN_OPTION_AI_MEMORY_BIN="$STUB_DIR/ai-memory" sh "$LAUNCHER" claude-code stop >/dev/null+assert_eq "Muse is attributed to muse" "muse" "$(sed -n 5p "$TMP/argv")"+assert_eq "the Muse copy marks its origin" "muse-plugin" "$(cat "$TMP/origin")"+# A Claude Code started from a Muse shell may inherit MUSE_SESSION_ID; without+# MUSE_PLUGIN_ID its events stay Claude Code's.+printf '{}' | run_launcher MUSE_SESSION_ID="01a13669-dc61-7a72-b5ec-ad2f300ffd26" \+ CLAUDE_PLUGIN_ROOT="$PLUGIN_ROOT_DIR" \+ CLAUDE_PLUGIN_OPTION_AI_MEMORY_BIN="$STUB_DIR/ai-memory" sh "$LAUNCHER" claude-code stop >/dev/null+assert_eq "an inherited MUSE_SESSION_ID alone stays claude-code" "claude-code" "$(sed -n 5p "$TMP/argv")"printf '{}' | run_launcher PLUGIN_ROOT="$TMP" \CLAUDE_PLUGIN_OPTION_AI_MEMORY_BIN="$STUB_DIR/ai-memory" sh "$LAUNCHER" claude-code stop >/dev/nullassert_eq "Codex reading the Claude plugin is attributed to codex" "codex" "$(sed -n 5p "$TMP/argv")"