Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(cli): protect Windows hook commands from expansion
AkitaOnRails31ce54597549
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fccd9106..fda686e4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0native commands and close the residual local-wire vector ([#196]).### Fixed+- Windows `.ps1` fallback hook commands now use PowerShell `-EncodedCommand`+ instead of embedding `$env:` setup inside a nested quoted command. This+ prevents outer Windows hook runners such as Antigravity CLI from expanding+ the setup before the inner PowerShell process receives it. Existing Windows+ Docker-wrapper installs should rerun `install-hooks --agent <agent> --apply`+ after upgrading ([#214]).- `install-mcp --client claude-code` and `uninstall` now honour`CLAUDE_CONFIG_DIR`: MCP registrations go to`$CLAUDE_CONFIG_DIR/.claude.json` when the variable is set (non-empty),diff --git a/README.md b/README.mdindex 233abf74..286984c5 100644--- a/README.md+++ b/README.md@@ -380,7 +380,11 @@ one matching entry.- **Windows:** use the Linux path inside WSL2, or the native Windows wrapperfrom PowerShell/cmd. Local supported profiles default to host-native commands:Claude Code may use its supported `ai-memory.exe` exec form, while other- agents use native single command strings matching their hook schema.+ agents use native single command strings matching their hook schema. The+ Docker wrapper protects `.ps1` fallback commands from nested PowerShell+ expansion with `-EncodedCommand`; rerun+ `install-hooks --agent <agent> --apply` after upgrading so existing hook+ entries receive the current form.PowerShell/Git Bash script bundles are compatibility fallbacks and do notenforce capture-policy v1. Do not mix path worlds. See[`docs/windows.md`](docs/windows.md).diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex de202de2..75280fce 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -21,6 +21,7 @@use std::borrow::Cow;use std::path::Path;+use base64::Engine as _;use serde_json::{Value, json};use crate::commands::path_util::strip_windows_verbatim_prefix;@@ -738,6 +739,8 @@ fn kimi_code_hook_commands_for_platform(#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum HookCommandPlatform {Posix,+ /// Windows script fallback: invoke the staged `.ps1` hook through an+ /// encoded PowerShell program so a host runner cannot expand its env setup.Windows,/// Claude Code on Windows invokes hooks through bash (Git for/// Windows), not PowerShell. Commands use POSIX `.sh` scripts@@ -753,9 +756,9 @@ pub(crate) enum HookCommandPlatform {/// POSIX (Linux/macOS), native: invoke the `ai-memory` binary directly/// (`<exe> hook --event …`) instead of the `.sh` script, so the hook gets/// the local spool + OIDC-token fallback. The **default** for native- /// Linux/macOS Claude Code installs (mirrors `WindowsNative`). The Docker- /// wrapper forces `posix` so its host-rendered config keeps the `.sh` path- /// (the host has no local binary). Override with+ /// Linux/macOS Claude Code installs (mirrors `WindowsNative`). The+ /// Linux/macOS Docker wrapper forces `posix` so its host-rendered config+ /// keeps the `.sh` path (the host has no local binary). Override with/// `AI_MEMORY_HOOK_PLATFORM=posix` to get the shell scripts.PosixNative,}@@ -831,8 +834,8 @@ impl HookCommandPlatform {/// Windows unless overridden by `AI_MEMORY_HOOK_PLATFORM`.fn for_bash_runner() -> Self {// Native macOS / Linux defaults to the binary hook command (spool +- // OIDC), same as Windows. The Docker wrapper forces `posix` so its- // host-rendered config keeps using the `.sh` scripts.+ // OIDC), same as Windows. The Linux/macOS Docker wrapper forces+ // `posix` so its host-rendered config keeps using the `.sh` scripts.Self::from_env_override().unwrap_or(if cfg!(windows) {Self::WindowsNative} else {@@ -1012,9 +1015,10 @@ fn hook_command(powershell_quote(s)));}+ let program = format!("{setup}; & {}", powershell_quote(&script.to_string_lossy()));+ let encoded = powershell_encoded_command(&program);format!(- "powershell.exe -NoProfile -ExecutionPolicy Bypass -Command \"{setup}; & {}\"",- powershell_quote(&script.to_string_lossy())+ "powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand {encoded}")}HookCommandPlatform::WindowsBash => {@@ -1096,6 +1100,14 @@ fn hook_command(}}+fn powershell_encoded_command(program: &str) -> String {+ let utf16_le = program+ .encode_utf16()+ .flat_map(u16::to_le_bytes)+ .collect::<Vec<_>>();+ base64::engine::general_purpose::STANDARD.encode(utf16_le)+}+fn windows_native_exec_spec(script: &Path,server_url: &str,@@ -1231,8 +1243,31 @@ fn win_double_quote(s: &str) -> String {mod tests {use super::*;use std::fs;+ #[cfg(windows)]+ use std::io::Write as _;use std::path::{Path, PathBuf};use std::process::Command;+ #[cfg(windows)]+ use std::process::Stdio;++ fn decode_powershell_encoded_command(command: &str) -> String {+ let (_, encoded) = command+ .split_once(" -EncodedCommand ")+ .expect("missing PowerShell -EncodedCommand payload");+ assert!(+ !encoded.contains(char::is_whitespace),+ "encoded payload must be one command-line token"+ );+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(encoded)+ .expect("invalid base64 PowerShell program");+ assert_eq!(bytes.len() % 2, 0, "UTF-16LE payload has an odd length");+ let utf16 = bytes+ .chunks_exact(2)+ .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))+ .collect::<Vec<_>>();+ String::from_utf16(&utf16).expect("invalid UTF-16 PowerShell program")+ }fn build_posix_hook_payload(events: &[(&str, &str)],@@ -2020,17 +2055,123 @@ check(activeKeep.disposition === "keep" && activeKeep.protocol?.version === 1 &&.pointer("/hooks/SessionStart/0/hooks/0/command").and_then(|s| s.as_str()).unwrap();- assert!(cmd.starts_with("powershell.exe -NoProfile -ExecutionPolicy Bypass -Command"));- assert!(cmd.contains("$env:AI_MEMORY_HOOK_URL='http://localhost:49374'"));- assert!(cmd.contains("$env:AI_MEMORY_AUTH_TOKEN='tok''en'"));+ assert!(cmd.starts_with(+ "powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand "+ ));assert!(- cmd.contains("session-start.ps1"),- "expected ps1 script path: {cmd}"+ !cmd.contains("$env:"),+ "outer command must be opaque: {cmd}");assert!(- !cmd.contains("session-start.sh"),- "Windows command must not use sh: {cmd}"+ !cmd.contains("http://localhost:49374"),+ "outer command must not expose values to its caller: {cmd}"+ );+ let program = decode_powershell_encoded_command(cmd);+ assert!(program.contains("$env:AI_MEMORY_HOOK_URL='http://localhost:49374'"));+ assert!(program.contains("$env:AI_MEMORY_AUTH_TOKEN='tok''en'"));+ assert!(+ program.contains("session-start.ps1"),+ "expected ps1 script path: {program}"+ );+ assert!(+ !program.contains("session-start.sh"),+ "Windows command must not use sh: {program}"+ );+ }++ #[test]+ fn antigravity_windows_commands_survive_an_outer_powershell_runner() {+ let root = PathBuf::from("C:/Users/alice/.local/share/ai-memory/hooks/antigravity-cli");+ let v = build_antigravity_payload_for_platform(+ &root,+ "http://localhost:49374",+ Some("tok'en"),+ HookCommandPlatform::Windows,+ "antigravity-cli",+ None,+ Some("repo-root"),+ );++ for pointer in [+ "/ai-memory/PreInvocation/0/command",+ "/ai-memory/PreToolUse/0/hooks/0/command",+ ] {+ let command = v.pointer(pointer).and_then(Value::as_str).unwrap();+ assert!(+ command.contains(" -EncodedCommand "),+ "{pointer}: {command}"+ );+ assert!(+ !command.contains("$env:")+ && !command.contains("localhost:49374")+ && !command.contains(".ps1"),+ "{pointer}: outer runner must see only an opaque program: {command}"+ );++ let program = decode_powershell_encoded_command(command);+ assert!(+ program.contains("$env:AI_MEMORY_HOOK_URL='http://localhost:49374'"),+ "{pointer}: {program}"+ );+ assert!(+ program.contains("$env:AI_MEMORY_AUTH_TOKEN='tok''en'"),+ "{pointer}: {program}"+ );+ assert!(+ program.contains("$env:AI_MEMORY_PROJECT_STRATEGY='repo-root'"),+ "{pointer}: {program}"+ );+ assert!(program.contains(".ps1"), "{pointer}: {program}");+ }+ }++ #[cfg(windows)]+ #[test]+ fn windows_encoded_hook_executes_through_an_outer_powershell() {+ let temp = tempfile::tempdir().unwrap();+ let script = temp.path().join("hook with spaces.ps1");+ fs::write(+ &script,+ r#"if ($env:AI_MEMORY_HOOK_URL -ne "http://localhost:49374") { exit 9 }+if ($env:AI_MEMORY_AUTH_TOKEN -ne "tok'en") { exit 10 }+$payload = [Console]::In.ReadToEnd()+[Console]::Out.Write($payload)+"#,+ )+ .unwrap();+ let command = hook_command(+ &script,+ "http://localhost:49374",+ Some("tok'en"),+ HookCommandContext::new(HookCommandPlatform::Windows, "antigravity-cli", None, None),+ );++ let mut child = Command::new("powershell.exe")+ .args([+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ &command,+ ])+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ child+ .stdin+ .take()+ .unwrap()+ .write_all(br#"{"hook":"ok"}"#)+ .unwrap();+ let output = child.wait_with_output().unwrap();+ assert!(+ output.status.success(),+ "nested PowerShell failed: {}",+ String::from_utf8_lossy(&output.stderr));+ assert_eq!(output.stdout, br#"{"hook":"ok"}"#);}#[test]@@ -2158,8 +2299,9 @@ check(activeKeep.disposition === "keep" && activeKeep.protocol?.version === 1 &&None,);let (_, cmd) = &commands[0];- assert!(cmd.contains("session-start.ps1"), "{cmd}");- assert!(!cmd.contains("session-start.sh"), "{cmd}");+ let program = decode_powershell_encoded_command(cmd);+ assert!(program.contains("session-start.ps1"), "{program}");+ assert!(!program.contains("session-start.sh"), "{program}");}#[test]@@ -2265,9 +2407,10 @@ check(activeKeep.disposition === "keep" && activeKeep.protocol?.version === 1 &&#[test]fn windows_ps_hook_command_bakes_project_strategy_env() {let cmd = strategy_cmd(HookCommandPlatform::Windows, Some("repo-root"));+ let program = decode_powershell_encoded_command(&cmd);assert!(- cmd.contains("$env:AI_MEMORY_PROJECT_STRATEGY='repo-root'"),- "powershell must bake the strategy env: {cmd}"+ program.contains("$env:AI_MEMORY_PROJECT_STRATEGY='repo-root'"),+ "powershell must bake the strategy env: {program}");}@@ -2309,13 +2452,18 @@ check(activeKeep.disposition === "keep" && activeKeep.protocol?.version === 1 &&HookCommandPlatform::WindowsNative,] {let cmd = strategy_cmd(platform, None);+ let inspect = if platform == HookCommandPlatform::Windows {+ decode_powershell_encoded_command(&cmd)+ } else {+ cmd+ };assert!(- !cmd.contains("AI_MEMORY_PROJECT_STRATEGY"),- "{platform:?}: no strategy env when None: {cmd}"+ !inspect.contains("AI_MEMORY_PROJECT_STRATEGY"),+ "{platform:?}: no strategy env when None: {inspect}");assert!(- !cmd.contains("--project-strategy"),- "{platform:?}: no strategy flag when None: {cmd}"+ !inspect.contains("--project-strategy"),+ "{platform:?}: no strategy flag when None: {inspect}");}}diff --git a/docs/install.md b/docs/install.mdindex 9c6ce1e4..06411fd1 100644--- a/docs/install.md+++ b/docs/install.md@@ -886,8 +886,9 @@ The 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`, theDocker 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-hook-agents use PowerShell `.ps1` defaults.+form with a real `ai-memory.exe` by default; the Windows Docker wrapper renders+other native Windows script-hook agents through encoded PowerShell `.ps1`+fallback commands.When run from source, `install-hooks` finds the bundled scripts inthe repo's `hooks/` automatically. Extracted release archives alsodiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 4aca26da..2434cebb 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -333,8 +333,8 @@ parallel subagent support. It uses a separate `mcp_config.json``serverUrl` (not `httpUrl`) for streamable-HTTP endpoints.```bash-# One-shot via CLI:-ai-memory install-mcp --client antigravity-cli+# Merge the MCP entry into the Antigravity config:+ai-memory install-mcp --client antigravity-cli --apply```The rendered snippet writes to `mcp_config.json` under `mcpServers`:@@ -408,7 +408,15 @@ The rendered hooks config looks like:**Gotchas:**- Antigravity CLI uses `serverUrl` for HTTP MCP endpoints, not `url`or `httpUrl`. The `--apply` flag writes the correct key.+- MCP and hooks use separate files: MCP belongs in+ `~/.gemini/antigravity-cli/mcp_config.json`, while hooks belong in+ `~/.gemini/config/hooks.json`.- Hook scripts are staged under `~/.local/share/ai-memory/hooks/antigravity-cli/`.+- Native Windows Docker-wrapper installs render hook entries as+ `powershell.exe ... -EncodedCommand <payload>` so Antigravity's outer command+ runner cannot expand the inner `$env:` setup. Rerun+ `install-hooks --agent antigravity-cli --apply` after upgrading to refresh+ existing entries.- The `PreInvocation` event fires before each model call (not just atsession start). ai-memory uses it as the closest equivalent to GeminiCLI's `SessionStart`; when a pending handoff exists, the hook injectsdiff --git a/docs/windows.md b/docs/windows.mdindex 0c646ebf..02ba9d1d 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -91,6 +91,8 @@ docker run -d --name ai-memory `-v ai-memory-data:/data `akitaonrails/ai-memory:latest+# Do not also run `ai-memory serve`; the long-lived container above is the server.+# Verify the wrapper can reach the server.ai-memory status@@ -106,9 +108,15 @@ the CLI to render hook commands for the native Windows agent:- Hook scripts are staged under `$HOME\.local\share\ai-memory\hooks\`.- Local supported profiles default to host-native commands. Claude Code may useits exec form (`command` executable + `args` argv array), while other agents- use native single command strings matching their hook schema. PowerShell/Git- Bash script bundles are compatibility fallbacks and do not enforce- capture-policy v1.+ use native single command strings matching their hook schema. The wrapper+ renders those `.ps1` fallback commands with PowerShell `-EncodedCommand` so a+ hook runner cannot expand their `$env:` setup before the inner PowerShell+ process receives it. PowerShell/Git Bash script bundles are compatibility+ fallbacks and do not enforce capture-policy v1.++After upgrading the wrapper/image, rerun `install-hooks --agent <agent> --apply`+for each native Windows agent so existing hook entries receive the current+command form.Use the matching `--client` / `--agent` values for other clients, forexample `codex`, `devin`, `kimi-code`, `cursor`, or `gemini-cli`.@@ -242,19 +250,23 @@ native on an i7-6700HQ). Notes:`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:+- `AI_MEMORY_HOOK_PLATFORM` accepts five values:- `windows-native` — Claude exec-form direct binary call (default on native Windows).+ - `windows` — PowerShell `-EncodedCommand` + staged `.ps1` script. The native+ Windows Docker-wrapper default because the helper container cannot install+ its Linux binary into a host hook entry.- `windows-bash` — `bash -c` + `.sh` through Git Bash (the previousdefault; set this to opt back in, or as a fallback for older Claude Codebuilds that do not support exec form).- - `posix` — POSIX `.sh`. The Docker-wrapper default (the host has no local- binary); set it explicitly to opt a native install back into the scripts.+ - `posix` — POSIX `.sh`. The Linux/macOS Docker-wrapper default (the host has+ no local binary); set it explicitly to opt a native install back into the+ scripts.- `posix-native` — direct binary call on macOS / Linux (`<exe> hook--event …`) instead of the `.sh` script, so the hook uses the local eventspool + OIDC-token fallback. The **default for native macOS / LinuxClaude Code installs** (cargo / release binary), mirroring- `windows-native`. The Docker wrapper forces `posix`, so its host-rendered- config keeps the `.sh` scripts.+ `windows-native`. The Linux/macOS Docker wrapper forces `posix`, so its+ host-rendered config keeps the `.sh` scripts.Set the env var before running `install-hooks` so the chosen platformis baked into the rendered hook commands.@@ -342,8 +354,8 @@ For native Windows:2. Confirm generated hook commands match the agent: Claude Code should usethe native `"…ai-memory.exe" hook --event …` command (or `bash -c` + `.sh`when `AI_MEMORY_HOOK_PLATFORM=windows-bash`); other script-hook agents- should use their generated script-command hook entries under your Windows- home directory.+ should use `powershell.exe ... -EncodedCommand <payload>` entries for the+ generated `.ps1` hooks 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`.