Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): drop Cursor's duplicate event from Claude Code hooks (fixes #721)
Gaalbuf4aee70b7e10
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f82367a3..de63bfab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed+- Cursor lifecycle events are no longer stored twice on a host where both+ `install-hooks --agent cursor` and `install-hooks --agent claude-code` are+ applied. Cursor also runs the commands in Claude Code's settings, and since+ 2.1.0 that copy is re-attributed to `cursor` by its `cursor_version`, so it+ landed in the same session as the native event. The `--agent claude-code`+ hook now drops a Cursor-marked payload when `~/.cursor/hooks.json` already+ registers an ai-memory `--agent cursor` hook; without Cursor's own hooks the+ Claude Code path keeps capturing Cursor sessions as before (#721).+## [2.2.1] - 2026-09-12### Fixeddiff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex fd6ba9be..cf2b330b 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -416,6 +416,21 @@ fn should_process_hook_event(agent: AgentKind, event: HookEvent, raw: &serde_jsotrue}+/// A `--agent claude-code` hook invoked by Cursor (it runs Claude Code's+/// settings too) is a duplicate when Cursor's own ai-memory hooks are also+/// installed: the native `--agent cursor` hook already delivers the same+/// event. Dropping it keeps one observation per Cursor event (#721). The+/// installed check runs last so ordinary Claude Code events never touch disk.+fn is_redundant_cursor_copy(+ agent: AgentKind,+ raw: &serde_json::Value,+ cursor_hooks_installed: impl FnOnce() -> bool,+) -> bool {+ agent == AgentKind::ClaudeCode+ && ai_memory_hooks::agent_from_payload(raw) == Some(AgentKind::Cursor)+ && cursor_hooks_installed()+}+fn write_success_response<W: std::io::Write>(stdout: &mut W,agent: AgentKind,@@ -496,7 +511,13 @@ where// fires before every model call; invocation zero is the only startup// boundary. Fail closed when the documented counter is absent so a later// invocation can never consume a handoff intended for the next session.- if !should_process_hook_event(agent_kind, hook_event, &json) {+ if !should_process_hook_event(agent_kind, hook_event, &json)+ || is_redundant_cursor_copy(+ agent_kind,+ &json,+ super::install_hooks::cursor_native_hooks_installed,+ )+ {write_success_response(stdout, agent_kind, hook_event)?;return Ok(());}@@ -1213,6 +1234,38 @@ mod tests {);}+ #[test]+ fn cursor_copy_via_claude_code_hooks_is_dropped_only_when_cursor_hooks_exist() {+ let cursor = serde_json::json!({+ "cursor_version": "2026.09.02-c22c1a3",+ "conversation_id": "c1",+ });+ let claude = serde_json::json!({"session_id": "s1"});+ assert!(is_redundant_cursor_copy(+ AgentKind::ClaudeCode,+ &cursor,+ || true+ ));+ // Without Cursor's own hooks the Claude Code path is the only capture.+ assert!(!is_redundant_cursor_copy(+ AgentKind::ClaudeCode,+ &cursor,+ || false+ ));+ // The native Cursor hook itself is never dropped.+ assert!(!is_redundant_cursor_copy(+ AgentKind::Cursor,+ &cursor,+ || true+ ));+ // A real Claude Code payload never consults the filesystem.+ assert!(!is_redundant_cursor_copy(+ AgentKind::ClaudeCode,+ &claude,+ || { panic!("must not check Cursor hooks for a Claude Code payload") }+ ));+ }+#[tokio::test]async fn antigravity_native_pre_tool_use_allows_and_spools_valid_input() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 81e0ba81..93f2d2e7 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -105,6 +105,70 @@ pub(crate) fn cursor_hooks_path() -> anyhow::Result<std::path::PathBuf> {.join("hooks.json"))}+/// True when `~/.cursor/hooks.json` already registers a native ai-memory hook+/// declared `--agent cursor`.+///+/// The Cursor CLI also runs the commands in Claude Code's settings, so on a+/// host with both installs every Cursor event reaches `ai-memory hook` twice:+/// once as `--agent cursor` and once as `--agent claude-code` carrying+/// `cursor_version`. The hook uses this to drop the second copy (#721).+/// Unreadable or malformed files count as "not installed" so the Claude Code+/// path keeps capturing Cursor sessions on hosts without Cursor's own hooks.+pub(crate) fn cursor_native_hooks_installed() -> bool {+ cursor_hooks_path().is_ok_and(|path| cursor_native_hooks_installed_in(&path))+}++const MAX_CURSOR_HOOKS_BYTES: u64 = 1024 * 1024;++pub(crate) fn cursor_native_hooks_installed_in(path: &Path) -> bool {+ use std::io::Read as _;+ let Ok(file) = fs::File::open(path) else {+ return false;+ };+ let mut raw = String::new();+ if file+ .take(MAX_CURSOR_HOOKS_BYTES)+ .read_to_string(&mut raw)+ .is_err()+ {+ return false;+ }+ let Ok(root) = serde_json::from_str::<serde_json::Value>(&raw) else {+ return false;+ };+ root.get("hooks")+ .and_then(serde_json::Value::as_object)+ .is_some_and(|hooks| {+ hooks+ .values()+ .filter_map(serde_json::Value::as_array)+ .flatten()+ .any(|entry| is_ai_memory_hook_entry(entry) && declares_cursor_agent(entry))+ })+}++fn declares_cursor_agent(entry: &serde_json::Value) -> bool {+ if let Some(args) = entry.get("args").and_then(serde_json::Value::as_array) {+ return args+ .windows(2)+ .any(|pair| pair[0] == "--agent" && pair[1] == "cursor");+ }+ entry+ .get("command")+ .and_then(serde_json::Value::as_str)+ .is_some_and(|command| {+ let tokens: Vec<&str> = command+ .split_whitespace()+ .map(|t| t.trim_matches(['"', '\'']))+ .collect();+ tokens+ .windows(2)+ .any(|pair| pair[0] == "--agent" && pair[1] == "cursor")+ || tokens.contains(&"--agent=cursor")+ || command.contains("agent=cursor")+ })+}+/// `~/.gemini/settings.json`.pub(crate) fn gemini_settings_path() -> anyhow::Result<std::path::PathBuf> {Ok(home_dir()@@ -8966,6 +9030,50 @@ model = "gpt-5");}+ #[test]+ fn cursor_native_hooks_detection_requires_an_ai_memory_cursor_entry() {+ let tmp = TempDir::new().unwrap();+ let path = tmp.path().join("hooks.json");+ assert!(!cursor_native_hooks_installed_in(&path), "missing file");++ fs::write(&path, "not json").unwrap();+ assert!(!cursor_native_hooks_installed_in(&path), "malformed file");++ fs::write(+ &path,+ r#"{"version":1,"hooks":{"sessionStart":[+ {"command":"/opt/third-party","args":["--agent","cursor"]},+ {"command":"/usr/bin/ai-memory","args":["hook","--event","session-start","--agent","claude-code","--server-url","http://h"]}+ ]}}"#,+ )+ .unwrap();+ assert!(+ !cursor_native_hooks_installed_in(&path),+ "third-party or non-cursor entries do not count"+ );++ fs::write(+ &path,+ r#"{"version":1,"hooks":{"stop":[+ {"command":"/usr/bin/ai-memory","args":["hook","--event","stop","--agent","cursor","--server-url","http://h"]}+ ]}}"#,+ )+ .unwrap();+ assert!(cursor_native_hooks_installed_in(&path), "exec form");++ fs::write(+ &path,+ r#"{"version":1,"hooks":{"stop":[+ {"command":"/usr/bin/ai-memory hook --event stop --agent cursor --server-url http://h"}+ ]}}"#,+ )+ .unwrap();+ assert!(+ cursor_native_hooks_installed_in(&path),+ "command-string form"+ );+ }+#[test]fn cursor_apply_is_idempotent() {let hooks_tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex efb83bb0..5eb86445 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -45,7 +45,7 @@ pub use capture_policy::{};pub use payload::{HookEnvelope, HookEvent, NOTIFICATION_EXCERPT_MAX_BYTES, POST_COMPACTION_EXCERPT_MAX_BYTES,- USER_PROMPT_EXCERPT_MAX_BYTES, cap_lifecycle_body_for_client,+ USER_PROMPT_EXCERPT_MAX_BYTES, agent_from_payload, cap_lifecycle_body_for_client,};pub use router::{DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, DEFAULT_INGEST_GATE_MAX_ENTRIES,