Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): use exec form for Windows Claude hooks
AkitaOnRailsf5236c68e611
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 97a8cb9b..644e6aab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Fixed+- Claude Code WindowsNative hook installs now use Claude's exec form+ (`command` executable plus `args` argv array) for the native `ai-memory.exe`+ hook, avoiding shell/Git Bash/PowerShell command-string mangling. Set+ `AI_MEMORY_HOOK_PLATFORM=windows-bash` before `install-hooks` as a fallback for+ older Claude Code builds; exec form requires a real `.exe`, not `.cmd`/`.bat`+ shims.- Native `session-end` hooks now enqueue and return quickly, then drain the hookspool through a hidden detached `hook-drain` process guarded by a realsingle-flight file lock. Background drains use the new boundeddiff --git a/README.md b/README.mdindex 31db18d7..0ba5c6bb 100644--- a/README.md+++ b/README.md@@ -21,7 +21,7 @@| Linux | Supported | Primary Docker/server target and CI platform. Published Docker images support `linux/amd64` and `linux/arm64`. Native Arch/AUR packages include system and user systemd units. || macOS | Supported | Workspace tests run in CI; tagged releases publish native `ai-memory-macos-aarch64.tar.gz` and `ai-memory-macos-x86_64.tar.gz` binaries. The native binary is the recommended path on Apple Silicon. See [`docs/macos.md`](docs/macos.md). || Windows via WSL2 | Supported | Use the Linux install path inside WSL2 when the agent runs there. |-| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Claude Code uses direct native `ai-memory.exe hook` commands by default; other script-hook agents use the current PowerShell defaults pending harness feedback. See [`docs/windows.md`](docs/windows.md). |+| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Claude Code uses Claude exec form with a real native `ai-memory.exe` by default; other script-hook agents use the current PowerShell defaults pending harness feedback. See [`docs/windows.md`](docs/windows.md). || Claude Code | Supported | MCP config + lifecycle hooks. || Codex | Supported | MCP config + lifecycle hooks. || OpenCode | Supported | Remote MCP config + generated TypeScript plugin. |@@ -303,9 +303,10 @@ one matching entry.### Install Notes- **Windows:** use the Linux path inside WSL2, or the native Windows wrapper- from PowerShell/cmd. Native Claude Code uses direct `ai-memory.exe hook`- commands by default, with `AI_MEMORY_HOOK_PLATFORM=windows-bash` available for- Git Bash `.sh` hooks; other script-hook agents use PowerShell defaults. Do not+ from PowerShell/cmd. Native Claude Code uses Claude exec form with a real+ `ai-memory.exe` by default, with `AI_MEMORY_HOOK_PLATFORM=windows-bash`+ available for Git Bash `.sh` hooks and older Claude Code builds; other+ script-hook agents use PowerShell defaults. Do notmix path worlds. See[`docs/windows.md`](docs/windows.md).- **Docker compose:** `docker compose -f docker/docker-compose.yml up -d`diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 006862fb..22c690fb 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -440,22 +440,32 @@ fn bearer_token_from_header(header: &str) -> Option<String> {.map(ToOwned::to_owned)}-/// True if a hook-array entry belongs to ai-memory — i.e. some command-/// string inside it mentions the `ai-memory` binary/script. Used to-/// replace our own entries on re-apply while preserving hooks that other-/// tools registered under the same event.+/// True if a hook-array entry belongs to ai-memory — i.e. some command handler+/// inside it is one of our legacy command strings or one of our exec-form native+/// hook handlers. Used to replace our own entries on re-apply while preserving+/// hooks that other tools registered under the same event.fn is_ai_memory_hook_entry(entry: &serde_json::Value) -> bool {fn mentions_ai_memory(value: &serde_json::Value) -> bool {- value- .get("command")- .and_then(|c| c.as_str())- .map(|c| c.to_ascii_lowercase())- // Case-insensitive, and matches BOTH the binary/script path- // (`ai-memory`) AND the inlined env vars (`AI_MEMORY_HOOK_URL` /- // `AI_MEMORY_AUTH_TOKEN`). The env vars are present in every- // command shape (native, bash, PowerShell), so detection works- // even when the hooks dir path has no "ai-memory" in it.- .is_some_and(|c| c.contains("ai-memory") || c.contains("ai_memory"))+ let Some(command) = value.get("command").and_then(|c| c.as_str()) else {+ return false;+ };+ let lower = command.to_ascii_lowercase();+ let args = value.get("args").and_then(|a| a.as_array());+ let Some(args) = args else {+ // Legacy shell/string form: broad matching is intentional because+ // old installs may identify us by the binary/script path or by the+ // inlined AI_MEMORY_* env vars.+ return lower.contains("ai-memory") || lower.contains("ai_memory");+ };+ let tokens: Vec<&str> = args.iter().filter_map(|v| v.as_str()).collect();+ // Exec form: require both an ai-memory-ish executable and our hook argv+ // signature so unrelated helpers such as `ai-memory-helper.exe` are not+ // removed just because their executable name contains ai-memory.+ (lower.contains("ai-memory") || lower.contains("ai_memory"))+ && tokens.contains(&"hook")+ && tokens.contains(&"--event")+ && tokens.contains(&"--agent")+ && tokens.contains(&"--server-url")}// Flat shape (Cursor): `{ "type":"command", "command":"…" }`.// Nested shape (Claude Code / Codex / Gemini):@@ -2521,10 +2531,20 @@ mod tests {assert!(is_ai_memory_hook_entry(&serde_json::json!({ "type": "command", "command": "bash -c 'AI_MEMORY_HOOK_URL=x /c/x/ai-memory/hooks/pre.sh'" })));+ // Claude Code exec form+ assert!(is_ai_memory_hook_entry(&serde_json::json!(+ { "matcher": "", "hooks": [ { "type": "command", "command": "C:\\bin\\ai-memory.exe", "args": ["hook", "--event", "session-start", "--agent", "claude-code", "--server-url", "http://h"] } ] }+ )));// Third-party must NOT be flaggedassert!(!is_ai_memory_hook_entry(&serde_json::json!({ "hooks": [ { "type": "command", "command": "node context-mode-cache-heal.mjs" } ] })));+ assert!(!is_ai_memory_hook_entry(&serde_json::json!(+ { "hooks": [ { "type": "command", "command": "C:\\bin\\third-party.exe", "args": ["hook", "--event", "session-start", "--agent", "claude-code", "--server-url", "http://h"] } ] }+ )));+ assert!(!is_ai_memory_hook_entry(&serde_json::json!(+ { "hooks": [ { "type": "command", "command": "C:\\bin\\ai-memory-helper.exe", "args": ["--check", "project"] } ] }+ )));}fn stub_scripts(dir: &Path, names: &[&str]) {diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 20f9033d..05c48b34 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -21,7 +21,7 @@use std::borrow::Cow;use std::path::Path;-use serde_json::json;+use serde_json::{Value, json};use crate::commands::path_util::strip_windows_verbatim_prefix;@@ -139,7 +139,8 @@ pub(crate) fn build_claude_code_payload_with_data_dir("claude-code",data_dir,project_strategy,- ),+ )+ .allow_claude_windows_exec(),)}@@ -341,20 +342,17 @@ fn build_antigravity_payload_for_platform(for (event, script) in &ANTIGRAVITY_TOOL_EVENTS {let s = script_for_platform(script, platform);let abs = emit_root.join(s.as_ref());- let command = hook_command(+ let handler = hook_handler_value(HookHandlerSpec::ShellString(hook_command(&abs,server_url,auth_token,HookCommandContext::new(platform, agent, data_dir, project_strategy),- );+ )));group.insert((*event).to_string(),json!([{"matcher": "",- "hooks": [{- "type": "command",- "command": command,- }],+ "hooks": [handler],}]),);}@@ -363,19 +361,13 @@ fn build_antigravity_payload_for_platform(for (event, script) in &ANTIGRAVITY_LIFECYCLE_EVENTS {let s = script_for_platform(script, platform);let abs = emit_root.join(s.as_ref());- let command = hook_command(+ let handler = hook_handler_value(HookHandlerSpec::ShellString(hook_command(&abs,server_url,auth_token,HookCommandContext::new(platform, agent, data_dir, project_strategy),- );- group.insert(- (*event).to_string(),- json!([{- "type": "command",- "command": command,- }]),- );+ )));+ group.insert((*event).to_string(), Value::Array(vec![handler]));}json!({ "ai-memory": group })@@ -471,6 +463,11 @@ struct HookCommandContext<'a> {/// Install-time default project strategy baked into the command/// (`install-hooks --project-strategy`). `None` bakes nothing.project_strategy: Option<&'a str>,+ /// Whether this render path may use Claude Code's exec-form hook handler.+ /// Only `install-hooks --agent claude-code` sets this; setup-agent/docker+ /// snippets keep command-string script fallback even when the platform env+ /// is overridden to `windows-native`.+ claude_windows_exec_allowed: bool,}impl<'a> HookCommandContext<'a> {@@ -485,8 +482,14 @@ impl<'a> HookCommandContext<'a> {agent,data_dir,project_strategy,+ claude_windows_exec_allowed: false,}}++ const fn allow_claude_windows_exec(mut self) -> Self {+ self.claude_windows_exec_allowed = true;+ self+ }}impl HookCommandPlatform {@@ -563,10 +566,12 @@ fn build_hook_payload_for_platform(// }// ]//- // We INLINE env vars into the command string itself+ // Shell-form handlers INLINE env vars into the command string itself// (`AI_MEMORY_HOOK_URL=... AI_MEMORY_AUTH_TOKEN=... /path`)- // rather than passing them through an `env` field on the- // hook entry. Reasons:+ // rather than passing them through an `env` field on the hook entry.+ // Native Claude Code Windows installs instead use official exec form,+ // where server/auth/project options are passed as raw argv tokens.+ // Reasons shell-form handlers keep inline env vars:// 1. CC doesn't appear to honour an `env` field at this// level — observed empirically: the hook fires but// the script sees neither var and falls back to the@@ -578,7 +583,9 @@ fn build_hook_payload_for_platform(// `hooks/claude-code/session-start.sh` etc.), so no// script changes are required on POSIX. Windows uses an// explicit PowerShell command with equivalent env setup.- let command = hook_command(&abs, server_url, auth_token, context);+ let handler = hook_handler_value(hook_handler_spec(+ &abs, server_url, auth_token, context, shape,+ ));// Empty matcher = fire on every event of this kind. Right// for ai-memory's capture hooks (every prompt, every tool@@ -586,22 +593,59 @@ fn build_hook_payload_for_platform(let entry = match shape {HookShape::Nested => json!([{"matcher": "",- "hooks": [{- "type": "command",- "command": command,- }],- }]),- HookShape::Flat => json!([{- "type": "command",- "command": command,- "matcher": "",+ "hooks": [handler],}]),+ HookShape::Flat => Value::Array(vec![hook_handler_with_matcher(handler)]),};hooks_block.insert((*event).to_string(), entry);}json!({ "hooks": hooks_block })}+#[derive(Debug, Clone, PartialEq, Eq)]+enum HookHandlerSpec {+ ShellString(String),+ Exec { command: String, args: Vec<String> },+}++fn hook_handler_spec(+ script: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ context: HookCommandContext<'_>,+ shape: HookShape,+) -> HookHandlerSpec {+ if shape == HookShape::Nested+ && context.claude_windows_exec_allowed+ && context.platform == HookCommandPlatform::WindowsNative+ && context.agent == "claude-code"+ {+ return windows_native_exec_spec(script, server_url, auth_token, context);+ }+ HookHandlerSpec::ShellString(hook_command(script, server_url, auth_token, context))+}++fn hook_handler_value(spec: HookHandlerSpec) -> Value {+ match spec {+ HookHandlerSpec::ShellString(command) => json!({+ "type": "command",+ "command": command,+ }),+ HookHandlerSpec::Exec { command, args } => json!({+ "type": "command",+ "command": command,+ "args": args,+ }),+ }+}++fn hook_handler_with_matcher(mut handler: Value) -> Value {+ if let Some(obj) = handler.as_object_mut() {+ obj.insert("matcher".to_string(), Value::String(String::new()));+ }+ handler+}+fn script_for_platform(script: &str, platform: HookCommandPlatform) -> Cow<'_, str> {match platform {HookCommandPlatform::Posix@@ -672,17 +716,18 @@ fn hook_command(format!("bash -c {}", shell_quote(&inner))}HookCommandPlatform::WindowsNative => {- // Invoke the binary directly: `"<exe>" hook --event <e> --agent- // claude-code --server-url "<url>" [--auth-token "<t>"]`. The- // event token is the script stem (`pre-tool-use.sh` →- // `pre-tool-use`). No shell, no child processes.+ // Legacy/setup-agent/fallback string form: invoke the binary+ // directly as `"<exe>" hook --event <e> --agent ...`. Primary+ // Claude Code WindowsNative `install-hooks` uses exec form instead+ // (see `windows_native_exec_spec`). The event token is the script+ // stem (`pre-tool-use.sh` → `pre-tool-use`). No shell, no child+ // processes in the intended runner.//// Quote with DOUBLE quotes, not POSIX single quotes: Claude Code- // on Windows runs the hook command through cmd.exe, which treats- // '…' literally and errors out; double quotes + the native- // Windows path work in BOTH cmd.exe and Git Bash (verified). The- // event name is a fixed slug with no shell metacharacters, so it- // is left unquoted.+ // on Windows shell-form runners may treat '…' literally and error+ // out; double quotes + the native Windows path work in cmd.exe and+ // Git Bash. The event name is a fixed slug with no shell+ // metacharacters, so it is left unquoted.let exe = std::env::current_exe().map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|_| "ai-memory".to_string());@@ -737,6 +782,60 @@ fn hook_command(}}+fn windows_native_exec_spec(+ script: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ context: HookCommandContext<'_>,+) -> HookHandlerSpec {+ let exe = std::env::current_exe().unwrap_or_else(|_| Path::new("ai-memory.exe").to_path_buf());+ windows_native_exec_spec_with_exe(&exe, script, server_url, auth_token, context)+}++fn windows_native_exec_spec_with_exe(+ exe: &Path,+ script: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ context: HookCommandContext<'_>,+) -> HookHandlerSpec {+ let event = script+ .file_stem()+ .and_then(|s| s.to_str())+ .unwrap_or_default();+ let mut args = Vec::new();+ if let Some(data_dir) = context.data_dir {+ args.push("--data-dir".to_string());+ args.push(plain_windows_path_arg(data_dir));+ }+ args.extend([+ "hook".to_string(),+ "--event".to_string(),+ event.to_string(),+ "--agent".to_string(),+ context.agent.to_string(),+ "--server-url".to_string(),+ server_url.to_string(),+ ]);+ if let Some(t) = auth_token {+ args.push("--auth-token".to_string());+ args.push(t.to_string());+ }+ if let Some(strategy) = context.project_strategy {+ args.push("--project-strategy".to_string());+ args.push(strategy.to_string());+ }+ HookHandlerSpec::Exec {+ command: plain_windows_path_arg(exe),+ args,+ }+}++fn plain_windows_path_arg(path: &Path) -> String {+ let lossy = path.to_string_lossy();+ strip_windows_verbatim_prefix(&lossy).into_owned()+}+#[derive(Clone, Copy)]enum NativeQuote {Posix,@@ -1107,32 +1206,213 @@ mod tests {"claude-code",None,None,- ),+ )+ .allow_claude_windows_exec(),);- // Each native command must carry `hook --event <stem>` where <stem>- // matches the .sh script the other platforms invoke — so the server- // buckets the event identically — and must not spawn a shell.+ // Each native exec-form handler must carry `hook --event <stem>` in+ // argv, where <stem> matches the .sh script the other platforms invoke.for (event, script) in CLAUDE_CODE_EVENTS {let stem = script.strip_suffix(".sh").unwrap();- let cmd = v- .pointer(&format!("/hooks/{event}/0/hooks/0/command"))- .and_then(|s| s.as_str())- .unwrap();+ let handler = v.pointer(&format!("/hooks/{event}/0/hooks/0")).unwrap();+ let cmd = handler.get("command").and_then(|s| s.as_str()).unwrap();+ let args: Vec<&str> = handler+ .get("args")+ .and_then(|a| a.as_array())+ .unwrap()+ .iter()+ .map(|a| a.as_str().unwrap())+ .collect();+ assert!(!cmd.contains("--event"), "{event}: executable only: {cmd}");+ assert!(+ args.windows(2).any(|w| w == ["--event", stem]),+ "{event}: {args:?}"+ );+ assert!(+ args.windows(2).any(|w| w == ["--agent", "claude-code"]),+ "{event}: {args:?}"+ );assert!(- cmd.contains(&format!("hook --event {stem}")),- "{event}: {cmd}"+ args.windows(2)+ .any(|w| w == ["--server-url", "http://h:49374"]),+ "{event}: {args:?}");- assert!(cmd.contains("--agent claude-code"), "{event}: {cmd}");assert!(- cmd.contains("--server-url \"http://h:49374\""),- "{event}: {cmd}"+ args.windows(2).any(|w| w == ["--auth-token", "tok"]),+ "{event}: {args:?}"+ );+ }+ }++ #[test]+ fn windows_native_claude_code_nested_payload_uses_exec_form() {+ let root = PathBuf::from(r"C:\hooks");+ let data_dir = Path::new(r"\\?\C:\Users\me\AppData\Local\ai-memory");+ let v = build_hook_payload_for_platform(+ &[("SessionStart", "session-start.sh")],+ &root,+ "http://h:49374",+ Some("tok"),+ HookShape::Nested,+ HookCommandContext::new(+ HookCommandPlatform::WindowsNative,+ "claude-code",+ Some(data_dir),+ Some("repo-root"),+ )+ .allow_claude_windows_exec(),+ );+ let handler = v.pointer("/hooks/SessionStart/0/hooks/0").unwrap();+ let command = handler.get("command").and_then(|v| v.as_str()).unwrap();+ let args: Vec<&str> = handler+ .get("args")+ .and_then(|v| v.as_array())+ .unwrap()+ .iter()+ .map(|v| v.as_str().unwrap())+ .collect();++ assert!(command.contains("ai-memory") || command.contains("ai_memory"));+ assert!(+ !command.contains(" --event "),+ "command is executable only: {command}"+ );+ assert_eq!(+ args,+ vec![+ "--data-dir",+ r"C:\Users\me\AppData\Local\ai-memory",+ "hook",+ "--event",+ "session-start",+ "--agent",+ "claude-code",+ "--server-url",+ "http://h:49374",+ "--auth-token",+ "tok",+ "--project-strategy",+ "repo-root",+ ]+ );+ assert!(+ args.iter().all(|arg| !arg.contains('"')),+ "args are raw argv tokens"+ );+ }++ #[test]+ fn windows_native_exec_spec_strips_verbatim_exe_and_data_dir() {+ let spec = windows_native_exec_spec_with_exe(+ Path::new(r"\\?\C:\Program Files\ai-memory\ai-memory.exe"),+ Path::new(r"C:\hooks\post-tool-use.sh"),+ "http://h:49374",+ None,+ HookCommandContext::new(+ HookCommandPlatform::WindowsNative,+ "claude-code",+ Some(Path::new(r"\\?\C:\Data\ai-memory")),+ None,+ ),+ );+ let HookHandlerSpec::Exec { command, args } = spec else {+ panic!("expected exec spec")+ };+ assert_eq!(command, r"C:\Program Files\ai-memory\ai-memory.exe");+ assert_eq!(args[1], r"C:\Data\ai-memory");+ assert!(args.iter().all(|arg| !arg.contains(r"\\?\")));+ }++ #[test]+ fn exec_form_is_narrow_to_claude_code_windows_native_nested() {+ fn handler_for(+ platform: HookCommandPlatform,+ agent: &str,+ shape: HookShape,+ ) -> serde_json::Value {+ let v = build_hook_payload_for_platform(+ &[("SessionStart", "session-start.sh")],+ Path::new(r"C:\hooks"),+ "http://h:49374",+ Some("tok"),+ shape,+ HookCommandContext::new(platform, agent, None, None).allow_claude_windows_exec(),);- assert!(cmd.contains("--auth-token \"tok\""), "{event}: {cmd}");+ match shape {+ HookShape::Nested => v.pointer("/hooks/SessionStart/0/hooks/0").unwrap().clone(),+ HookShape::Flat => v.pointer("/hooks/SessionStart/0").unwrap().clone(),+ }+ }++ for (platform, agent, shape) in [+ (+ HookCommandPlatform::WindowsBash,+ "claude-code",+ HookShape::Nested,+ ),+ (+ HookCommandPlatform::Windows,+ "claude-code",+ HookShape::Nested,+ ),+ (HookCommandPlatform::Posix, "claude-code", HookShape::Nested),+ (+ HookCommandPlatform::PosixNative,+ "claude-code",+ HookShape::Nested,+ ),+ (+ HookCommandPlatform::WindowsNative,+ "grok",+ HookShape::Nested,+ ),+ (+ HookCommandPlatform::WindowsNative,+ "claude-code",+ HookShape::Flat,+ ),+ ] {+ let handler = handler_for(platform, agent, shape);assert!(- !cmd.contains("bash -c"),- "{event}: must not spawn a shell: {cmd}"+ handler.get("args").is_none(),+ "{platform:?}/{agent}/{shape:?} must keep command-string form: {handler}");}++ let setup_like = build_hook_payload_for_platform(+ &[("SessionStart", "session-start.sh")],+ Path::new(r"C:\hooks"),+ "http://h:49374",+ Some("tok"),+ HookShape::Nested,+ HookCommandContext::new(+ HookCommandPlatform::WindowsNative,+ "claude-code",+ None,+ None,+ ),+ );+ assert!(+ setup_like+ .pointer("/hooks/SessionStart/0/hooks/0/args")+ .is_none(),+ "setup-agent style Claude Code payload must not inherit exec form: {setup_like}"+ );++ let antigravity = build_antigravity_payload_for_platform(+ Path::new(r"C:\hooks"),+ "http://h:49374",+ Some("tok"),+ HookCommandPlatform::WindowsNative,+ "antigravity-cli",+ None,+ None,+ );+ assert!(+ antigravity+ .pointer("/ai-memory/PreInvocation/0/args")+ .is_none(),+ "antigravity must not inherit exec form: {antigravity}"+ );}#[test]diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex a9db75e7..f2efd558 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -499,6 +499,27 @@ fn hook_command_is_ours(command: &str) -> bool {&& lower.contains(" --server-url ")}+fn hook_entry_is_ours(entry: &serde_json::Value) -> bool {+ let Some(command) = entry.get("command").and_then(|c| c.as_str()) else {+ return false;+ };+ if hook_command_is_ours(command) {+ return true;+ }+ let lower = command.to_ascii_lowercase();+ if !(lower.contains("ai-memory") || lower.contains("ai_memory")) {+ return false;+ }+ let Some(args) = entry.get("args").and_then(|a| a.as_array()) else {+ return false;+ };+ let tokens: Vec<&str> = args.iter().filter_map(|v| v.as_str()).collect();+ tokens.contains(&"hook")+ && tokens.contains(&"--event")+ && tokens.contains(&"--agent")+ && tokens.contains(&"--server-url")+}+/// Result of stripping ai-memory entries from a hooks JSON file.struct HookRemoval {new_content: String,@@ -509,18 +530,12 @@ struct HookRemoval {/// remove_entry)`. Flat entries are removed whole; nested entries only lose the/// matching inner commands and survive when third-party inner hooks remain.fn strip_hook_entry(entry: &mut serde_json::Value) -> (bool, bool) {- if let Some(cmd) = entry.get("command").and_then(|c| c.as_str())- && hook_command_is_ours(cmd)- {+ if hook_entry_is_ours(entry) {return (true, true);}if let Some(inner) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {let before = inner.len();- inner.retain(|h| {- !h.get("command")- .and_then(|c| c.as_str())- .is_some_and(hook_command_is_ours)- });+ inner.retain(|h| !hook_entry_is_ours(h));let removed = inner.len() != before;return (removed, inner.is_empty());}@@ -965,6 +980,53 @@ mod tests {);}+ #[test]+ fn strip_hooks_removes_exec_form_ours_preserves_exec_third_party_and_sibling() {+ let content = r#"{+ "hooks": {+ "SessionStart": [+ {"matcher":"","hooks":[+ {"type":"command","command":"C:\\bin\\ai-memory.exe","args":["hook","--event","session-start","--agent","claude-code","--server-url","http://h"]},+ {"type":"command","command":"C:\\bin\\third-party.exe","args":["hook","--event","session-start","--agent","claude-code","--server-url","http://h"]}+ ]},+ {"matcher":"Tool","hooks":[+ {"type":"command","command":"C:\\bin\\other.exe","args":["--keep"]}+ ]}+ ],+ "Stop": [+ {"matcher":"","hooks":[{"type":"command","command":"\"C:\\bin\\ai-memory.exe\" hook --event stop --agent claude-code --server-url \"http://h\""}]}+ ]+ }+ }"#;++ let out = strip_ai_memory_hooks(content).unwrap();+ assert_eq!(+ out.removed_events,+ vec!["SessionStart".to_string(), "Stop".to_string()]+ );+ let v: serde_json::Value = serde_json::from_str(&out.new_content).unwrap();+ assert!(+ v["hooks"].get("Stop").is_none(),+ "legacy string hook removed"+ );+ let entries = v["hooks"]["SessionStart"].as_array().unwrap();+ assert_eq!(entries.len(), 2, "outer sibling group preserved");+ let first_inner = entries[0]["hooks"].as_array().unwrap();+ assert_eq!(+ first_inner.len(),+ 1,+ "only ai-memory inner exec hook removed"+ );+ assert_eq!(+ first_inner[0]["command"].as_str(),+ Some(r"C:\bin\third-party.exe")+ );+ assert_eq!(+ entries[1]["hooks"][0]["command"].as_str(),+ Some(r"C:\bin\other.exe")+ );+ }+#[test]fn strip_hooks_no_hooks_key_is_noop() {let content = r#"{"unrelated":true}"#;diff --git a/docs/install.md b/docs/install.mdindex eea7be7f..3add467a 100644--- a/docs/install.md+++ b/docs/install.md@@ -483,9 +483,11 @@ Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, and OpenClaw have lifecycle> bundled scripts to your home dir, (2) `docker run --rm install-hooks`> to render the config snippet.> On native Windows, Claude Code is the exception to the PowerShell default:-> it uses direct `ai-memory.exe hook` commands by default. Set+> it uses Claude exec form (`command` = real `ai-memory.exe`, `args` = argv+> tokens for `hook --event ...`) by default. Set> `AI_MEMORY_HOOK_PLATFORM=windows-bash` before `install-hooks` to opt back into-> Git Bash `bash -c` commands for the `.sh` scripts.+> Git Bash `bash -c` commands for the `.sh` scripts, including for older Claude+> Code builds that do not support exec form.> OpenClaw, OpenCode, and OMP are different: they use generated> TypeScript plugin/extension files, so no shell-script extraction is> needed for those clients.@@ -735,8 +737,8 @@ architecture: `aarch64` for Apple Silicon, `x86_64` for Intel. On Windows, seeThe short version: run the install commands from the same environment thatlaunches the agent. WSL2-launched agents need WSL paths and POSIX `.sh` hooks.Native Windows agents can use the tagged `ai-memory-windows-x86_64.zip`, the-Docker Desktop wrapper, or a source build. Native Claude Code uses direct-`ai-memory.exe hook` commands by default; other native Windows script-hook+Docker Desktop wrapper, or a source build. Native Claude Code uses Claude exec+form with a real `ai-memory.exe` by default; other native Windows script-hookagents use PowerShell `.ps1` defaults.When run from source, `install-hooks` finds the bundled scripts indiff --git a/docs/windows.md b/docs/windows.mdindex 09731155..dcf0f10d 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -17,8 +17,8 @@ launches Claude Code, Codex, Cursor, Gemini CLI, or another agent.The difference matters because hook configs contain executable paths.WSL2 agents need Linux paths and POSIX `.sh` hooks. Native Windowsagents need Windows paths, but the hook runner is agent-specific:-Claude Code invokes its hooks as a direct native binary call-(`"…ai-memory.exe" hook --event …`) with no shell — see [Native Hook+Claude Code invokes its hooks with Claude's direct exec form+(`command: "…ai-memory.exe"`, `args: ["hook", "--event", …]`) with no shell — see [Native HookCommand](#native-hook-command-claude-code-on-windows). Set`AI_MEMORY_HOOK_PLATFORM=windows-bash` to fall back to the older`bash -c` + `.sh` Git Bash commands. Other native Windows script-hook@@ -104,8 +104,8 @@ the CLI to render hook commands for the native Windows agent:- Config files are written through the mounted Windows home directory.- Hook scripts are staged under `$HOME\.local\share\ai-memory\hooks\`.-- Claude Code hook commands call the `ai-memory` binary directly- (`"…ai-memory.exe" hook --event …`), no shell — set+- Claude Code hook commands call the `ai-memory` binary directly with Claude's+ exec form (`command` executable + `args` argv array), no shell — set`AI_MEMORY_HOOK_PLATFORM=windows-bash` for the old `bash -c` + `.sh`Git Bash path.- Other native Windows script-hook agents currently call `powershell.exe` and@@ -123,7 +123,7 @@ Docker. Each tagged release publishes```powershell# Download + extract into your user data dir (any stable path works; the-# native hook command is rendered from wherever ai-memory.exe lives).+# native hook exec-form command is rendered from wherever ai-memory.exe lives).$Dest = "$env:LOCALAPPDATA\ai-memory"New-Item -ItemType Directory -Force $Dest | Out-NullInvoke-WebRequest `@@ -187,12 +187,17 @@ event/agent parity between them.## Native Hook Command (Claude Code on Windows)-By default on native Windows, Claude Code hooks are rendered as a direct-call to the `ai-memory` binary instead of a `bash -c` wrapper around a-`.sh` script:+By default on native Windows, Claude Code hooks are rendered using Claude's+exec form: `command` is the real `ai-memory.exe` path and `args` is an argv+array. This directly spawns the binary instead of sending one quoted string to a+shell or using a `bash -c` wrapper around a `.sh` script:-```-"C:\Users\you\.cargo\bin\ai-memory.exe" hook --event pre-tool-use --agent claude-code --server-url "http://host:49374" --auth-token "..."+```json+{+ "type": "command",+ "command": "C:\\Users\\you\\.cargo\\bin\\ai-memory.exe",+ "args": ["hook", "--event", "pre-tool-use", "--agent", "claude-code", "--server-url", "http://host:49374", "--auth-token", "..."]+}```This avoids spawning Git Bash plus `cat`/`sed`/`curl` child processes on@@ -203,15 +208,16 @@ native on an i7-6700HQ). Notes:- The binary path comes from the `ai-memory` that runs `install-hooks`, so`cargo install --path crates/ai-memory-cli` puts it on a stable`~/.cargo/bin` path.-- The command is double-quoted: Claude Code runs hook commands through- `cmd.exe`, which rejects POSIX single quotes; double quotes work in both- cmd.exe and Git Bash.+- Exec form requires a real executable path (`.exe`). It does not run `.cmd` or+ `.bat` shims through a shell. `install-hooks` uses the path of the running+ `ai-memory.exe`, so release binaries and Cargo-built binaries work directly.- The `.sh`/`.ps1` scripts stay bundled as a fallback — the Docker /`setup-agent` flow (no local binary) keeps emitting the shell command.- `AI_MEMORY_HOOK_PLATFORM` accepts four values:- - `windows-native` — direct binary call (default on native Windows).+ - `windows-native` — Claude exec-form direct binary call (default on native Windows).- `windows-bash` — `bash -c` + `.sh` through Git Bash (the previous- default; set this to opt back in).+ default; set this to opt back in, or as a fallback for older Claude Code+ builds that do not support exec form).- `posix` — POSIX `.sh`. The Docker-wrapper default (the host has no localbinary); set it explicitly to opt a native install back into the scripts.- `posix-native` — direct binary call on macOS / Linux (`<exe> hook