Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(cli): native Windows hook command for Claude Code
Gustavo Cateim5e783b62af33
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex b060f5e6..b0d66a91 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -54,6 +54,10 @@ pub enum Command {Restore(RestoreArgs),/// Print (or apply) lifecycle-hook configuration for an agent CLI.InstallHooks(InstallHooksArgs),+ /// Emit a single lifecycle hook natively (reads the event payload+ /// from stdin), avoiding a shell spawn. Used by the WindowsNative+ /// hook config; mirrors hooks/<agent>/<event>.sh.+ Hook(HookArgs),/// Print MCP server registration snippets for any supported client/// (Claude Code, Codex, OpenCode, Cursor, Claude Desktop, Gemini/// CLI, OpenClaw, pi). See docs/mcp-install.md for the full guide.@@ -794,6 +798,23 @@ pub struct LlmTestArgs {pub api_key: Option<String>,}+/// Arguments for `hook` — emit one lifecycle event natively.+#[derive(Debug, Args)]+pub struct HookArgs {+ /// Lifecycle event, e.g. `pre-tool-use`, `session-start`.+ #[arg(long)]+ pub event: String,+ /// Agent name to attribute the event to, e.g. `claude-code`.+ #[arg(long)]+ pub agent: String,+ /// Base URL of the ai-memory hook server.+ #[arg(long)]+ pub server_url: String,+ /// Optional bearer token (`Authorization: Bearer <token>`).+ #[arg(long, hide_env_values = true)]+ pub auth_token: Option<String>,+}+/// Arguments for `install-hooks`.#[derive(Debug, Args)]pub struct InstallHooksArgs {diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsnew file mode 100644index 00000000..f25f8e38--- /dev/null+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -0,0 +1,49 @@+//! `ai-memory hook` — emit a single lifecycle event natively.+//!+//! Reads the event payload from stdin and issues the same HTTP request+//! the shell hook scripts do, without spawning a shell or child+//! processes. See `docs/windows-native-hooks.md`.++use std::io::Read;++use crate::cli::HookArgs;++use super::hook_capture::{build_client, extract_cwd, get_handoff, marker_query_suffix, post_hook};++/// Run a single hook end-to-end. Always returns Ok and always writes a+/// JSON object to stdout — a hook must never fail the agent.+pub async fn run(args: HookArgs) -> anyhow::Result<()> {+ let mut payload = String::new();+ std::io::stdin().read_to_string(&mut payload).ok();+ let json: serde_json::Value = serde_json::from_str(&payload).unwrap_or(serde_json::Value::Null);++ let qs = extract_cwd(&json)+ .map(|cwd| marker_query_suffix(&cwd))+ .unwrap_or_default();+ let base = args.server_url.trim_end_matches('/');+ let token = args.auth_token.as_deref();+ let client = build_client();++ // Every event records itself via POST /hook (best-effort).+ let post_url = format!("{base}/hook?event={}&agent={}{qs}", args.event, args.agent);+ let _ = post_hook(&client, &post_url, &payload, token).await;++ // session-start ALSO pulls the pending handoff and injects it as+ // context for the resuming agent.+ if args.event == "session-start" {+ let handoff_url = format!("{base}/handoff?agent={}{qs}", args.agent);+ if let Some(handoff) = get_handoff(&client, &handoff_url, token).await {+ let envelope = serde_json::json!({+ "hookSpecificOutput": {+ "hookEventName": "SessionStart",+ "additionalContext": handoff,+ }+ });+ println!("{envelope}");+ return Ok(());+ }+ }++ println!("{{}}");+ Ok(())+}diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsnew file mode 100644index 00000000..ecd6ba52--- /dev/null+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -0,0 +1,190 @@+//! Native lifecycle-hook capture helpers.+//!+//! Mirrors the POSIX `hooks/lib/_lib.sh` logic so the native+//! `ai-memory hook` subcommand produces the same HTTP request the shell+//! scripts do: extract cwd from the payload, walk up for a+//! `.ai-memory.toml` marker, and build the query-string suffix. The two+//! request helpers are best-effort with shell-parity timeouts.++use std::path::{Path, PathBuf};+use std::time::Duration;++/// First top-level `cwd` string in the payload (parity with+/// `ai_memory_extract_cwd`: take the top-level value, ignore nested+/// `cwd` fields in tool payloads).+pub fn extract_cwd(payload: &serde_json::Value) -> Option<String> {+ payload+ .get("cwd")+ .and_then(|v| v.as_str())+ .map(str::to_owned)+}++/// URL-encode the reserved characters `ai_memory_url_encode` handles.+pub fn url_encode(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ for c in s.chars() {+ match c {+ '%' => out.push_str("%25"),+ '+' => out.push_str("%2B"),+ '&' => out.push_str("%26"),+ '=' => out.push_str("%3D"),+ '?' => out.push_str("%3F"),+ '#' => out.push_str("%23"),+ ' ' => out.push_str("%20"),+ '/' => out.push_str("%2F"),+ other => out.push(other),+ }+ }+ out+}++/// Build `&cwd=…[&workspace=…&project=…&project_strategy=…]`, mirroring+/// `ai_memory_marker_qs`: always include cwd; append marker-declared+/// fields when a `.ai-memory.toml` is found walking up toward $HOME.+pub fn marker_query_suffix(cwd: &str) -> String {+ let mut qs = format!("&cwd={}", url_encode(cwd));+ if let Some(marker) = find_marker(cwd) {+ for key in ["workspace", "project", "project_strategy"] {+ if let Some(val) = parse_toml_key(&marker, key) {+ qs.push_str(&format!("&{key}={}", url_encode(&val)));+ }+ }+ }+ qs+}++/// Walk up from `cwd` toward `$HOME` (or the filesystem root) looking+/// for `.ai-memory.toml`. Stops at `$HOME` to avoid leaking a parent+/// user's declaration on shared machines (parity with+/// `ai_memory_find_marker`).+fn find_marker(cwd: &str) -> Option<PathBuf> {+ let home = dirs::home_dir();+ let mut dir = Path::new(cwd);+ loop {+ let candidate = dir.join(".ai-memory.toml");+ if candidate.is_file() {+ return Some(candidate);+ }+ if home.as_deref() == Some(dir) {+ return None;+ }+ match dir.parent() {+ Some(parent) if parent != dir => dir = parent,+ _ => return None,+ }+ }+}++/// Parse a root-level `key = "value"` line (no nesting, arrays, or+/// tables), mirroring `ai_memory_parse_toml_key`. Returns the first+/// match. Avoids pulling in a TOML parser dependency.+fn parse_toml_key(file: &Path, key: &str) -> Option<String> {+ let text = std::fs::read_to_string(file).ok()?;+ for line in text.lines() {+ let trimmed = line.trim_start();+ let Some(after_key) = trimmed.strip_prefix(key) else {+ continue;+ };+ let Some(rest) = after_key.trim_start().strip_prefix('=') else {+ continue;+ };+ let Some(rest) = rest.trim_start().strip_prefix('"') else {+ continue;+ };+ if let Some(end) = rest.find('"') {+ return Some(rest[..end].to_string());+ }+ }+ None+}++/// Build a reqwest client for the hook's one-shot requests. `no_proxy`+/// skips Windows proxy auto-detection (registry / WinINET lookups), which+/// is pure overhead for a loopback/LAN POST. Built once per invocation and+/// reused for both the event POST and the handoff GET. Default root certs+/// are kept so HTTPS targets (e.g. a TLS proxy) still work.+pub fn build_client() -> reqwest::Client {+ reqwest::Client::builder()+ .no_proxy()+ .build()+ .unwrap_or_else(|_| reqwest::Client::new())+}++/// POST the payload as JSON, best-effort. 0.5s budget (parity with the+/// shell `--max-time 0.5`). Network errors are swallowed — a hook must+/// never block or fail the agent.+pub async fn post_hook(+ client: &reqwest::Client,+ url: &str,+ body: &str,+ token: Option<&str>,+) -> anyhow::Result<()> {+ let mut req = client+ .post(url)+ .header("Content-Type", "application/json")+ .timeout(Duration::from_millis(500))+ .body(body.to_owned());+ if let Some(t) = token {+ req = req.bearer_auth(t);+ }+ let _ = req.send().await; // best-effort: ignore the result+ Ok(())+}++/// GET the handoff text, 1s budget (parity with the shell handoff GET).+/// Returns None on any error or an empty body.+pub async fn get_handoff(+ client: &reqwest::Client,+ url: &str,+ token: Option<&str>,+) -> Option<String> {+ let mut req = client.get(url).timeout(Duration::from_millis(1000));+ if let Some(t) = token {+ req = req.bearer_auth(t);+ }+ let body = req.send().await.ok()?.text().await.ok()?;+ if body.is_empty() { None } else { Some(body) }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn extracts_top_level_cwd() {+ let p: serde_json::Value =+ serde_json::from_str(r#"{"cwd":"/d/proj","tool_input":{"cwd":"/nested"}}"#).unwrap();+ assert_eq!(extract_cwd(&p).as_deref(), Some("/d/proj"));+ }++ #[test]+ fn missing_cwd_is_none() {+ let p: serde_json::Value = serde_json::from_str(r#"{"x":1}"#).unwrap();+ assert_eq!(extract_cwd(&p), None);+ }++ #[test]+ fn query_suffix_without_marker_has_only_cwd() {+ let qs = marker_query_suffix("/nonexistent/path/xyz");+ assert_eq!(qs, "&cwd=%2Fnonexistent%2Fpath%2Fxyz");+ }++ #[test]+ fn url_encode_escapes_reserved() {+ assert_eq!(url_encode("a b&c=d"), "a%20b%26c%3Dd");+ }++ #[tokio::test]+ async fn post_hook_returns_ok_even_when_server_unreachable() {+ // Port 1 is unroutable; best-effort means this still resolves Ok.+ let client = build_client();+ let r = post_hook(+ &client,+ "http://127.0.0.1:1/hook?event=pre-tool-use",+ "{}",+ None,+ )+ .await;+ assert!(r.is_ok());+ }+}diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 8fa5b8f9..54c541a1 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -14,6 +14,8 @@ pub mod delete_page;pub mod embed;pub mod forget_sweep;pub mod generate_auth_token;+pub mod hook;+pub mod hook_capture;pub mod init;pub mod install_hooks;pub mod install_instructions;diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex a7f847d6..c5bbce2c 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -334,6 +334,11 @@ pub(crate) enum HookCommandPlatform {/// wrapped in `bash -c '...'` with drive-letter paths converted/// to Git Bash format (`C:\x` → `/c/x`).WindowsBash,+ /// Windows, native: invoke the `ai-memory` binary directly+ /// (`<exe> hook --event … --agent …`) with no shell or child+ /// processes — ~3.5× faster per hook than `WindowsBash`. Default for+ /// Claude Code on Windows; see docs/windows-native-hooks.md.+ WindowsNative,}impl HookCommandPlatform {@@ -344,6 +349,7 @@ impl HookCommandPlatform {Self::Posix}Ok(v) if v.eq_ignore_ascii_case("windows-bash") => Self::WindowsBash,+ Ok(v) if v.eq_ignore_ascii_case("windows-native") => Self::WindowsNative,_ if cfg!(windows) => Self::Windows,_ => Self::Posix,}@@ -359,7 +365,8 @@ impl HookCommandPlatform {Self::Posix}Ok(v) if v.eq_ignore_ascii_case("windows-bash") => Self::WindowsBash,- _ if cfg!(windows) => Self::WindowsBash,+ Ok(v) if v.eq_ignore_ascii_case("windows-native") => Self::WindowsNative,+ _ if cfg!(windows) => Self::WindowsNative,_ => Self::Posix,}}@@ -427,7 +434,9 @@ fn build_hook_payload_for_platform(fn script_for_platform(script: &str, platform: HookCommandPlatform) -> Cow<'_, str> {match platform {- HookCommandPlatform::Posix | HookCommandPlatform::WindowsBash => Cow::Borrowed(script),+ HookCommandPlatform::Posix+ | HookCommandPlatform::WindowsBash+ | HookCommandPlatform::WindowsNative => Cow::Borrowed(script),HookCommandPlatform::Windows => match script.strip_suffix(".sh") {Some(stem) => Cow::Owned(format!("{stem}.ps1")),None => Cow::Borrowed(script),@@ -479,6 +488,35 @@ fn hook_command(inner.push_str(&shell_quote(&bash_path));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.+ //+ // 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.+ let exe = std::env::current_exe()+ .map(|p| p.to_string_lossy().into_owned())+ .unwrap_or_else(|_| "ai-memory".to_string());+ let event = script+ .file_stem()+ .and_then(|s| s.to_str())+ .unwrap_or_default();+ let mut cmd = format!(+ "{} hook --event {event} --agent claude-code --server-url {}",+ win_double_quote(&exe),+ win_double_quote(server_url),+ );+ if let Some(t) = auth_token {+ cmd.push_str(&format!(" --auth-token {}", win_double_quote(t)));+ }+ cmd+ }}}@@ -517,6 +555,16 @@ fn powershell_quote(s: &str) -> String {format!("'{}'", s.replace('\'', "''"))}+/// Wrap a value in double quotes for the `WindowsNative` hook command.+/// Claude Code on Windows runs hook commands via cmd.exe, which does not+/// honour POSIX single quotes; double quotes work in both cmd.exe and Git+/// Bash. The quoted values (binary path, URL, hex auth token) never+/// contain a literal `"`; any is stripped defensively rather than risk a+/// broken command line.+fn win_double_quote(s: &str) -> String {+ format!("\"{}\"", s.replace('"', ""))+}+#[cfg(test)]mod tests {use super::*;@@ -741,13 +789,56 @@ mod tests {.pointer("/hooks/SessionStart/0/hooks/0/command").and_then(|s| s.as_str()).unwrap();- assert!(command.contains("AI_MEMORY_HOOK_URL="));+ // Format-agnostic: POSIX/WindowsBash inline `AI_MEMORY_HOOK_URL=…`,+ // WindowsNative passes `--server-url …`. Both carry the host:port,+ // and neither must carry a token when none was supplied.assert!(- !command.contains("AI_MEMORY_AUTH_TOKEN="),+ command.contains("localhost:49374"),+ "server url expected: {command}"+ );+ assert!(+ !command.contains("AUTH_TOKEN") && !command.contains("--auth-token"),"no token expected in command: {command}");}+ #[test]+ fn windows_native_emits_binary_command_with_event_token() {+ let root = PathBuf::from(r"C:\hooks");+ let v = build_hook_payload_for_platform(+ &CLAUDE_CODE_EVENTS,+ &root,+ "http://h:49374",+ Some("tok"),+ HookShape::Nested,+ HookCommandPlatform::WindowsNative,+ );+ // 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.+ 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();+ assert!(+ cmd.contains(&format!("hook --event {stem}")),+ "{event}: {cmd}"+ );+ assert!(cmd.contains("--agent claude-code"), "{event}: {cmd}");+ assert!(+ cmd.contains("--server-url \"http://h:49374\""),+ "{event}: {cmd}"+ );+ assert!(cmd.contains("--auth-token \"tok\""), "{event}: {cmd}");+ assert!(+ !cmd.contains("bash -c"),+ "{event}: must not spawn a shell: {cmd}"+ );+ }+ }+#[test]fn claude_code_payload_emits_absolute_paths() {let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rsindex cf00e7af..81598bf5 100644--- a/crates/ai-memory-cli/src/main.rs+++ b/crates/ai-memory-cli/src/main.rs@@ -27,6 +27,18 @@ use config::Config;#[tokio::main]async fn main() -> Result<()> {let cli = Cli::parse();++ // Hooks fire on every tool call: they must be cheap and must emit ONLY+ // their JSON object to stdout. Short-circuit before config load and+ // tracing init (added latency + possible stdout noise). The hook reads+ // its server URL + token from flags, so it needs no config.+ if matches!(cli.command, Command::Hook(_)) {+ let Command::Hook(args) = cli.command else {+ unreachable!()+ };+ return commands::hook::run(args).await;+ }+let config_path = cli.config.clone();let config = Arc::new(Config::load(cli.config.as_deref(), cli.data_dir.clone())?);@@ -51,6 +63,8 @@ async fn main() -> Result<()> {Command::Backup(args) => commands::backup::run(&config, args).await,Command::Restore(args) => commands::restore::run(&config, args),Command::InstallHooks(args) => commands::install_hooks::run(&config, args),+ // `Hook` is handled in the fast-path above (before config/tracing).+ Command::Hook(_) => unreachable!("hook handled before config load"),Command::InstallMcp(args) => commands::install_mcp::run(&config, args),Command::Commit(args) => commands::commit::run(&config, args).await,Command::LlmTest(args) => commands::llm_test::run(&config, args).await,diff --git a/docs/windows.md b/docs/windows.mdindex dee4b750..bb157b3b 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -17,10 +17,13 @@ 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 hooks through Git Bash, so ai-memory renders-`bash -c` commands that call `.sh` scripts with Git Bash paths-(`/c/Users/...`). Other native Windows script-hook agents keep the-PowerShell `.ps1` default until their harness behavior is verified.+Claude Code invokes its hooks as a direct native binary call+(`"…ai-memory.exe" hook --event …`) with no shell — see [Native Hook+Command](#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+agents keep the PowerShell `.ps1` default until their harness behavior+is verified.## Scenario A: Everything Inside WSL2@@ -101,8 +104,10 @@ 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 `bash -c` and point at `.sh` scripts using- Git Bash paths such as `/c/Users/alice/...`.+- Claude Code hook commands call the `ai-memory` binary directly+ (`"…ai-memory.exe" hook --event …`), 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` andpoint at `.ps1` scripts.@@ -136,11 +141,37 @@ target\debug\ai-memory.exe install-mcp --client claude-code --applytarget\debug\ai-memory.exe install-hooks --agent claude-code --apply```-Native Windows builds render agent-specific lifecycle hooks. Claude Code uses-Git Bash-compatible `.sh` commands on native Windows; other script-hook agents-use the PowerShell `.ps1` default. The hook bundle ships matching `.sh` and-`.ps1` event scripts, and tests enforce one-to-one event/agent parity between-them.+Native Windows builds render agent-specific lifecycle hooks. Claude Code+defaults to the native binary command (see below); other script-hook agents+use the PowerShell `.ps1` default. The hook bundle still ships matching `.sh`+and `.ps1` event scripts as a fallback, and tests enforce one-to-one+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:++```+"C:\Users\you\.cargo\bin\ai-memory.exe" 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+every tool call. Process spawning is expensive on Windows, so the native+path is roughly 3-5× faster per hook (measured ~735 ms shell → ~150-205 ms+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.+- The `.sh`/`.ps1` scripts stay bundled as a fallback — the Docker /+ `setup-agent` flow (no local binary) keeps emitting the shell command.+- To force the old Git Bash behavior, set+ `AI_MEMORY_HOOK_PLATFORM=windows-bash` before running `install-hooks`.## Current Harness Caveats@@ -148,8 +179,9 @@ Windows hook support is new and needs real-world testing against nativeWindows agent builds.- Claude Code may be used natively on Windows or from inside WSL2. Native- Claude Code invokes hooks through Git Bash; WSL2 Claude Code uses normal- WSL paths.+ Claude Code invokes hooks as a direct binary call (no shell) by default;+ `AI_MEMORY_HOOK_PLATFORM=windows-bash` restores the Git Bash `bash -c`+ path. WSL2 Claude Code uses normal WSL `.sh` paths.- Codex, OpenCode, Cursor, Gemini CLI, and OpenClaw may each choose differentWindows config locations or shell execution behavior. ai-memory usesthe current best-known defaults, but they need validation on real@@ -176,8 +208,9 @@ For native Windows:1. Run all install commands from PowerShell or `cmd.exe` using`ai-memory` / `ai-memory.ps1`.2. Confirm generated hook commands match the agent: Claude Code should use- `bash -c` plus `.sh` files with `/c/...` Git Bash paths; other script-hook- agents should use `.ps1` files under your Windows home directory.+ the native `"…ai-memory.exe" hook --event …` command (or `bash -c` + `.sh`+ when `AI_MEMORY_HOOK_PLATFORM=windows-bash`); other script-hook agents+ should use `.ps1` files under your Windows home directory.3. Launch the native Windows agent.4. Call `memory_status` from the agent.5. Send a prompt, then run `ai-memory status` or `ai-memory recent`.