Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat: add Windows hook support

AkitaOnRails80c068b95e28
diff --git a/README.md b/README.md
index 2d22a185..44b93391 100644
--- a/README.md
+++ b/README.md
@@ -137,9 +137,9 @@ ai-memory install-mcp --client claude-code --apply
ai-memory install-hooks --agent claude-code --apply
```
-That's it. Start a Claude Code session as usual - every prompt and
-tool call now lands in ai-memory, and the next session you open in
-this project will see a handoff with where you left off.
+On Linux/macOS, that's it. Start a Claude Code session as usual - every
+prompt and tool call now lands in ai-memory, and the next session you
+open in this project will see a handoff with where you left off.
The `install-mcp` / `install-hooks` commands default to
`http://127.0.0.1:49374` (matching the server above) and no bearer
@@ -151,6 +151,14 @@ write. The hook scripts are staged into
overwrites them so future image updates ship updated hooks. Drop
`--apply` to print the snippet instead of mutating.
+### Windows Status
+
+Windows support has two separate modes. If your agent runs inside WSL2,
+use the Linux quick start inside WSL2. If your agent runs as a native
+Windows process, use the PowerShell wrapper and `.ps1` hooks. Do not mix
+the two path worlds. See [`docs/windows.md`](docs/windows.md) for the
+native Windows, WSL2, and current real-world testing notes.
+
> **Prefer docker compose?** Clone the repo and run
> `docker compose -f docker/docker-compose.yml up -d` instead of
> step 2. The bundled compose file already has
@@ -704,6 +712,7 @@ data-flow diagram + crate breakdown + cross-cutting invariants.
| File | What it is |
|---|---|
| [`docs/install.md`](docs/install.md) | **Installation cookbook.** Every agent CLI, every alternative (curl, source build, no-docker, no-auth), and the server-on-a-different-machine (homelab/LAN) walkthrough. Read after the Quick start if your setup doesn't match the happy path. |
+| [`docs/windows.md`](docs/windows.md) | Windows install modes: full WSL2, native Windows with Docker Desktop, native source builds, and current hook/MCP harness caveats. |
| [`docs/mcp-install.md`](docs/mcp-install.md) | Per-client MCP config snippets (Cursor, Claude Desktop, Gemini CLI, OpenClaw, OMP). |
| [`docs/deploy.md`](docs/deploy.md) | Homelab deploy: bin/deploy, bearer-token auth, TLS via cloudflared. |
| [`docs/lifecycle-ops.md`](docs/lifecycle-ops.md) | **Read before running purge / rename / backup / restore / reset.** Safety matrix for the state-touching commands, per-project disk layout (how isolation actually works), and operator workflows for "fresh start", "snapshot before risky op", "drop one project". |
diff --git a/bin/ai-memory b/bin/ai-memory
index 22a8ae51..dea2073d 100755
--- a/bin/ai-memory
+++ b/bin/ai-memory
@@ -213,6 +213,8 @@ for var in \
AI_MEMORY_EMBEDDING_BASE_URL \
AI_MEMORY_EMBEDDING_DIM \
AI_MEMORY_ALLOWED_HOSTS \
+ AI_MEMORY_HOOK_PLATFORM \
+ AI_MEMORY_HOOKS_HOST_ROOT \
ANTHROPIC_API_KEY \
OPENAI_API_KEY \
VOYAGE_API_KEY \
diff --git a/bin/ai-memory.cmd b/bin/ai-memory.cmd
new file mode 100644
index 00000000..27ac8cf9
--- /dev/null
+++ b/bin/ai-memory.cmd
@@ -0,0 +1,4 @@
+@echo off
+setlocal
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0ai-memory.ps1" %*
+exit /b %ERRORLEVEL%
diff --git a/bin/ai-memory.ps1 b/bin/ai-memory.ps1
new file mode 100644
index 00000000..45398a01
--- /dev/null
+++ b/bin/ai-memory.ps1
@@ -0,0 +1,96 @@
+# ai-memory.ps1 - Windows PowerShell wrapper for the Docker image.
+#
+# This mirrors bin/ai-memory for Windows users who run Docker Desktop.
+# It forwards CLI commands into the Linux container with the user's home
+# directory mounted at /host-home and the current project mounted at /work.
+#
+# The wrapper tells the Linux container to render Windows PowerShell hook
+# commands that point at the host's staged .ps1 scripts.
+[CmdletBinding()]
+param(
+ [Parameter(ValueFromRemainingArguments = $true)]
+ [string[]]$CommandArgs
+)
+
+$ErrorActionPreference = "Stop"
+
+function Get-EnvOrDefault {
+ param(
+ [Parameter(Mandatory = $true)][string]$Name,
+ [Parameter(Mandatory = $true)][string]$Default
+ )
+ $value = [Environment]::GetEnvironmentVariable($Name)
+ if ([string]::IsNullOrWhiteSpace($value)) {
+ return $Default
+ }
+ return $value
+}
+
+$Image = Get-EnvOrDefault "AI_MEMORY_IMAGE" "akitaonrails/ai-memory:latest"
+$Docker = Get-EnvOrDefault "AI_MEMORY_DOCKER" "docker"
+$DataVolume = Get-EnvOrDefault "AI_MEMORY_DATA_VOLUME" "ai-memory-data"
+
+if (-not (Get-Command $Docker -ErrorAction SilentlyContinue)) {
+ Write-Error "Could not find Docker command '$Docker'. Install Docker Desktop or set AI_MEMORY_DOCKER."
+ exit 127
+}
+
+if ($CommandArgs.Count -gt 0 -and $CommandArgs[0] -eq "upgrade") {
+ & $Docker pull $Image
+ exit $LASTEXITCODE
+}
+
+$HomePath = (Resolve-Path -LiteralPath $HOME).Path
+$WorkPath = (Get-Location).Path
+$HookHostRoot = ($HomePath -replace '\\', '/') + "/.local/share/ai-memory/hooks"
+
+$DockerArgs = @("run", "--rm")
+if (-not $env:AI_MEMORY_NO_TTY -and -not [Console]::IsInputRedirected -and -not [Console]::IsOutputRedirected) {
+ $DockerArgs += "-it"
+}
+
+$DockerArgs += @(
+ "-v", "${HomePath}:/host-home",
+ "-v", "${WorkPath}:/work",
+ "-w", "/work",
+ "-e", "HOME=/host-home",
+ "-e", "AI_MEMORY_HOST_CWD=$WorkPath",
+ "-e", "AI_MEMORY_DATA_DIR=/data",
+ "-e", "AI_MEMORY_HOOK_PLATFORM=windows",
+ "-e", "AI_MEMORY_HOOKS_HOST_ROOT=$HookHostRoot"
+)
+
+if ($env:AI_MEMORY_DATA_DIR -and (Test-Path -LiteralPath $env:AI_MEMORY_DATA_DIR -PathType Container)) {
+ $DataPath = (Resolve-Path -LiteralPath $env:AI_MEMORY_DATA_DIR).Path
+ $DockerArgs += @("-v", "${DataPath}:/data")
+} else {
+ $DockerArgs += @("-v", "${DataVolume}:/data")
+}
+
+foreach ($Name in @(
+ "AI_MEMORY_SERVER_URL",
+ "AI_MEMORY_AUTH_TOKEN",
+ "AI_MEMORY_LLM_PROVIDER",
+ "AI_MEMORY_LLM_MODEL",
+ "AI_MEMORY_LLM_BASE_URL",
+ "AI_MEMORY_EMBEDDING_PROVIDER",
+ "AI_MEMORY_EMBEDDING_MODEL",
+ "AI_MEMORY_EMBEDDING_BASE_URL",
+ "AI_MEMORY_EMBEDDING_DIM",
+ "AI_MEMORY_ALLOWED_HOSTS",
+ "ANTHROPIC_API_KEY",
+ "OPENAI_API_KEY",
+ "VOYAGE_API_KEY",
+ "LLM_API_KEY",
+ "RUST_LOG"
+)) {
+ if (-not [string]::IsNullOrEmpty([Environment]::GetEnvironmentVariable($Name))) {
+ $DockerArgs += @("-e", $Name)
+ }
+}
+
+$DockerArgs += $Image
+$DockerArgs += $CommandArgs
+
+& $Docker @DockerArgs
+exit $LASTEXITCODE
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 90f3441c..b3fba286 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -23,7 +23,7 @@ use crate::cli::{AgentChoice, InstallHooksArgs};
use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json};
use crate::commands::render_shared::{
CURSOR_PROFILE, GEMINI_PROFILE, build_claude_code_payload, build_codex_payload,
- build_profile_payload,
+ build_profile_payload, hook_script_for_current_platform,
};
use crate::config::Config;
@@ -117,7 +117,8 @@ fn apply_to_claude_code_settings(
.join("settings.json"),
};
let staged = stage_hook_scripts(hooks_dir, "claude-code")?;
- let payload = build_claude_code_payload(&staged, server_url, auth_token);
+ let command_dir = staged_command_dir(&staged, "claude-code");
+ let payload = build_claude_code_payload(&command_dir, server_url, auth_token);
let our_hooks = payload
.get("hooks")
.and_then(|v| v.as_object())
@@ -190,7 +191,8 @@ fn apply_to_codex_settings(
.join("hooks.json"),
};
let staged = stage_hook_scripts(hooks_dir, "codex")?;
- let outcome = merge_codex_hooks(&staged, server_url, auth_token, &path)?;
+ let command_dir = staged_command_dir(&staged, "codex");
+ let outcome = merge_codex_hooks(&command_dir, server_url, auth_token, &path)?;
println!(
"✓ {} {} ({})",
outcome.verb(),
@@ -284,7 +286,8 @@ fn apply_to_cursor_settings(
.join("hooks.json"),
};
let staged = stage_hook_scripts(hooks_dir, "cursor")?;
- let outcome = merge_cursor_hooks(&staged, server_url, auth_token, &path)?;
+ let command_dir = staged_command_dir(&staged, "cursor");
+ let outcome = merge_cursor_hooks(&command_dir, server_url, auth_token, &path)?;
println!(
"✓ {} {} ({})",
outcome.verb(),
@@ -359,7 +362,8 @@ fn apply_to_gemini_settings(
.join("settings.json"),
};
let staged = stage_hook_scripts(hooks_dir, "gemini-cli")?;
- let outcome = merge_gemini_hooks(&staged, server_url, auth_token, &path)?;
+ let command_dir = staged_command_dir(&staged, "gemini-cli");
+ let outcome = merge_gemini_hooks(&command_dir, server_url, auth_token, &path)?;
println!(
"✓ {} {} ({})",
outcome.verb(),
@@ -939,7 +943,7 @@ fn render_agent(
for entry in std::fs::read_dir(hooks_dir)? {
let entry = entry?;
let p = entry.path();
- if p.is_file() && p.extension().is_some_and(|e| e == "sh") {
+ if p.is_file() && p.extension().is_some_and(|e| e == hook_script_extension()) {
println!("- {}", p.display());
}
}
@@ -991,7 +995,7 @@ fn stage_hook_scripts(source_dir: &Path, agent_label: &str) -> Result<PathBuf> {
if let Ok(entries) = fs::read_dir(&dest_root) {
for entry in entries.flatten() {
let p = entry.path();
- if p.is_file() && p.extension().is_some_and(|e| e == "sh") {
+ if p.is_file() && is_hook_script_file(&p) {
fs::remove_file(&p).ok();
}
}
@@ -1003,7 +1007,7 @@ fn stage_hook_scripts(source_dir: &Path, agent_label: &str) -> Result<PathBuf> {
{
let entry = entry?;
let from = entry.path();
- if !from.is_file() || from.extension().and_then(|s| s.to_str()) != Some("sh") {
+ if !from.is_file() || !is_hook_script_file(&from) {
continue;
}
let to = dest_root.join(from.file_name().context("bad source file name")?);
@@ -1021,10 +1025,63 @@ fn stage_hook_scripts(source_dir: &Path, agent_label: &str) -> Result<PathBuf> {
copied += 1;
}
+ copy_support_hook_scripts(source_dir, &dest_root)?;
+
eprintln!("✓ staged {copied} hook script(s) → {}", dest_root.display());
Ok(dest_root)
}
+fn copy_support_hook_scripts(source_dir: &Path, dest_root: &Path) -> Result<()> {
+ let Some(source_hooks_root) = source_dir.parent() else {
+ return Ok(());
+ };
+ let source_lib = source_hooks_root.join("lib");
+ if !source_lib.is_dir() {
+ return Ok(());
+ }
+ let Some(dest_hooks_root) = dest_root.parent() else {
+ return Ok(());
+ };
+ let dest_lib = dest_hooks_root.join("lib");
+ fs::create_dir_all(&dest_lib)
+ .with_context(|| format!("creating hook support dir {}", dest_lib.display()))?;
+ for entry in fs::read_dir(&source_lib)
+ .with_context(|| format!("reading hook support dir {}", source_lib.display()))?
+ {
+ let entry = entry?;
+ let from = entry.path();
+ if !from.is_file() || from.extension().and_then(|s| s.to_str()) != Some("ps1") {
+ continue;
+ }
+ let to = dest_lib.join(from.file_name().context("bad support file name")?);
+ fs::copy(&from, &to)
+ .with_context(|| format!("copying {} → {}", from.display(), to.display()))?;
+ }
+ Ok(())
+}
+
+fn staged_command_dir(staged: &Path, agent_label: &str) -> PathBuf {
+ match std::env::var("AI_MEMORY_HOOKS_HOST_ROOT") {
+ Ok(root) if !root.trim().is_empty() => PathBuf::from(root).join(agent_label),
+ _ => staged.to_path_buf(),
+ }
+}
+
+fn hook_script_extension() -> &'static str {
+ if hook_script_for_current_platform("x.sh").ends_with(".ps1") {
+ "ps1"
+ } else {
+ "sh"
+ }
+}
+
+fn is_hook_script_file(path: &Path) -> bool {
+ matches!(
+ path.extension().and_then(|s| s.to_str()),
+ Some("sh" | "ps1")
+ )
+}
+
fn resolve_hooks_dir(explicit: Option<&Path>, agent: AgentChoice) -> Result<PathBuf> {
let sub = match agent {
AgentChoice::ClaudeCode => "claude-code",
@@ -1084,7 +1141,8 @@ fn render_claude_code(hooks_dir: &Path, server_url: &str, auth_token: Option<&st
// that exists only on the host's filesystem — bailing would
// sabotage the docker-only flow `setup-agent` enables.
for (_, script) in super::render_shared::CLAUDE_CODE_EVENTS {
- let abs = hooks_dir.join(script);
+ let script = hook_script_for_current_platform(script);
+ let abs = hooks_dir.join(script.as_ref());
if !abs.exists() {
eprintln!(
"# warning: {} not present on this filesystem. \
@@ -1102,7 +1160,7 @@ fn render_claude_code(hooks_dir: &Path, server_url: &str, auth_token: Option<&st
println!("# Hook scripts: {}", hooks_dir.display());
println!("# AI-memory server URL: {server_url}");
if auth_token.is_some() {
- println!("# Auth: AI_MEMORY_AUTH_TOKEN embedded in each hook's env block below.");
+ println!("# Auth: AI_MEMORY_AUTH_TOKEN embedded in each hook command below.");
println!("# Treat ~/.claude/settings.json as sensitive (chmod 600).");
}
println!();
@@ -1113,6 +1171,7 @@ fn render_claude_code(hooks_dir: &Path, server_url: &str, auth_token: Option<&st
#[cfg(test)]
mod tests {
use super::*;
+ use std::collections::BTreeMap;
use std::fs;
#[cfg(unix)]
use std::process::Command;
@@ -1132,6 +1191,107 @@ mod tests {
}
}
+ #[test]
+ fn bundled_posix_and_powershell_hooks_stay_in_parity() {
+ let hooks_root = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("..")
+ .join("..")
+ .join("hooks");
+ assert!(
+ hooks_root.join("lib").join("ai-memory-hook.ps1").is_file(),
+ "PowerShell hooks require the shared lib helper"
+ );
+
+ for agent_dir in ["claude-code", "codex", "cursor", "gemini-cli", "opencode"] {
+ let dir = hooks_root.join(agent_dir);
+ let mut sh = BTreeMap::new();
+ let mut ps1 = BTreeMap::new();
+ for entry in fs::read_dir(&dir).unwrap_or_else(|e| {
+ panic!("failed to read bundled hook dir {}: {e}", dir.display())
+ }) {
+ let path = entry.unwrap().path();
+ if !path.is_file() {
+ continue;
+ }
+ let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
+ continue;
+ };
+ match path.extension().and_then(|s| s.to_str()) {
+ Some("sh") => {
+ sh.insert(stem.to_string(), extract_sh_hook_metadata(&path));
+ }
+ Some("ps1") => {
+ ps1.insert(stem.to_string(), extract_ps1_hook_metadata(&path));
+ }
+ _ => {}
+ }
+ }
+ assert_eq!(
+ sh.keys().collect::<Vec<_>>(),
+ ps1.keys().collect::<Vec<_>>(),
+ "{agent_dir}: every .sh hook must have a .ps1 peer"
+ );
+ for (stem, sh_meta) in sh {
+ assert_eq!(
+ Some(sh_meta),
+ ps1.remove(&stem),
+ "{agent_dir}/{stem}: .sh and .ps1 must post the same event/agent"
+ );
+ }
+ }
+ }
+
+ fn extract_sh_hook_metadata(path: &Path) -> (String, String) {
+ let text = fs::read_to_string(path).unwrap();
+ let marker = "hook?event=";
+ let start = text
+ .find(marker)
+ .unwrap_or_else(|| panic!("{} missing hook endpoint", path.display()))
+ + marker.len();
+ let rest = &text[start..];
+ let event = rest
+ .split('&')
+ .next()
+ .unwrap_or_else(|| panic!("{} missing event", path.display()))
+ .to_string();
+ let agent_marker = "&agent=";
+ let agent_start = rest
+ .find(agent_marker)
+ .unwrap_or_else(|| panic!("{} missing agent", path.display()))
+ + agent_marker.len();
+ let agent = rest[agent_start..]
+ .split(['"', '\'', ' ', '\n', '\r'])
+ .next()
+ .unwrap_or_else(|| panic!("{} missing agent value", path.display()))
+ .to_string();
+ (event, agent)
+ }
+
+ fn extract_ps1_hook_metadata(path: &Path) -> (String, String) {
+ let text = fs::read_to_string(path).unwrap();
+ let line = text
+ .lines()
+ .find(|line| line.contains("Invoke-AiMemoryHook"))
+ .unwrap_or_else(|| panic!("{} missing Invoke-AiMemoryHook", path.display()));
+ (
+ extract_ps1_arg(line, "Event", path),
+ extract_ps1_arg(line, "Agent", path),
+ )
+ }
+
+ fn extract_ps1_arg(line: &str, name: &str, path: &Path) -> String {
+ let marker = format!("-{name} \"");
+ let start = line
+ .find(&marker)
+ .unwrap_or_else(|| panic!("{} missing {name} argument", path.display()))
+ + marker.len();
+ line[start..]
+ .split('"')
+ .next()
+ .unwrap_or_else(|| panic!("{} missing {name} value", path.display()))
+ .to_string()
+ }
+
// ----------------------------------------------------------------
// OpenCode tests
// ----------------------------------------------------------------
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index d2dd9c41..0ab29c2d 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -16,17 +16,18 @@
//! client and is the part that makes the printout readable). What
//! lives here is only the *data* both consume.
+use std::borrow::Cow;
use std::path::Path;
use serde_json::json;
/// Claude Code lifecycle events ai-memory hooks. Each pair is
-/// `(event-name-in-Claude-Code-settings, hook-script-filename)`.
+/// `(event-name-in-Claude-Code-settings, POSIX hook-script-filename)`.
///
/// Adding a hook event means updating this list AND adding the
-/// matching `hooks/{claude-code,codex,cursor,gemini-cli,opencode}/<filename>` script —
-/// the e2e test + the generator in `bin/regen-hooks` (if added) both
-/// key off this constant.
+/// matching `.sh` and `.ps1` files under
+/// `hooks/{claude-code,codex,cursor,gemini-cli,opencode}/`. The
+/// install-hooks parity test fails if the bundle drifts.
pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 7] = [
("SessionStart", "session-start.sh"),
("UserPromptSubmit", "user-prompt-submit.sh"),
@@ -58,7 +59,7 @@ pub(crate) fn bearer_header_value(token: Option<&str>) -> Option<String> {
/// - `setup-agent --agent claude-code` (script paths are where
/// `--host-prefix` says they'll live on the host)
///
-/// `emit_root` is the directory that will contain `*.sh`; it is
+/// `emit_root` is the directory that will contain hook scripts; it is
/// expected to be an absolute path on the system that will run the
/// agent CLI. This function does NOT verify the path exists on the
/// local filesystem — that decision belongs to the caller because
@@ -108,8 +109,9 @@ pub(crate) struct HookProfile {
/// `(EventName, script_basename)` tuples in the order the
/// agent surfaces them. Event names are case-sensitive and
/// agent-specific — Claude Code uses `SessionStart` while
- /// Cursor uses `sessionStart`. The script basename resolves
- /// against `hooks/<agent-dir>/`.
+ /// Cursor uses `sessionStart`. The POSIX script filename resolves
+ /// against `hooks/<agent-dir>/`; Windows rendering rewrites the
+ /// `.sh` suffix to `.ps1`.
pub events: &'static [(&'static str, &'static str)],
/// JSON shape the file uses.
pub shape: HookShape,
@@ -209,10 +211,48 @@ fn build_hook_payload(
server_url: &str,
auth_token: Option<&str>,
shape: HookShape,
+) -> serde_json::Value {
+ build_hook_payload_for_platform(
+ events,
+ emit_root,
+ server_url,
+ auth_token,
+ shape,
+ HookCommandPlatform::current(),
+ )
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum HookCommandPlatform {
+ Posix,
+ Windows,
+}
+
+impl HookCommandPlatform {
+ fn current() -> Self {
+ match std::env::var("AI_MEMORY_HOOK_PLATFORM") {
+ Ok(v) if v.eq_ignore_ascii_case("windows") => Self::Windows,
+ Ok(v) if v.eq_ignore_ascii_case("posix") || v.eq_ignore_ascii_case("unix") => {
+ Self::Posix
+ }
+ _ if cfg!(windows) => Self::Windows,
+ _ => Self::Posix,
+ }
+ }
+}
+
+fn build_hook_payload_for_platform(
+ events: &[(&str, &str)],
+ emit_root: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ shape: HookShape,
+ platform: HookCommandPlatform,
) -> serde_json::Value {
let mut hooks_block = serde_json::Map::new();
for (event, script) in events {
- let abs = emit_root.join(script);
+ let script = script_for_platform(script, platform);
+ let abs = emit_root.join(script.as_ref());
// Claude Code's hook schema (per
// https://code.claude.com/docs/en/hooks):
@@ -235,12 +275,9 @@ fn build_hook_payload(
// `VAR=val command` syntax is universally honoured.
// 3. The hook scripts already read those env vars (see
// `hooks/claude-code/session-start.sh` etc.), so no
- // script changes are required.
- let mut prefix = format!("AI_MEMORY_HOOK_URL={} ", shell_quote(server_url));
- if let Some(t) = auth_token {
- prefix.push_str(&format!("AI_MEMORY_AUTH_TOKEN={} ", shell_quote(t)));
- }
- let command = format!("{prefix}{}", abs.to_string_lossy());
+ // 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, platform);
// Empty matcher = fire on every event of this kind. Right
// for ai-memory's capture hooks (every prompt, every tool
@@ -264,6 +301,50 @@ fn build_hook_payload(
json!({ "hooks": hooks_block })
}
+fn script_for_platform(script: &str, platform: HookCommandPlatform) -> Cow<'_, str> {
+ match platform {
+ HookCommandPlatform::Posix => Cow::Borrowed(script),
+ HookCommandPlatform::Windows => match script.strip_suffix(".sh") {
+ Some(stem) => Cow::Owned(format!("{stem}.ps1")),
+ None => Cow::Borrowed(script),
+ },
+ }
+}
+
+pub(crate) fn hook_script_for_current_platform(script: &str) -> Cow<'_, str> {
+ script_for_platform(script, HookCommandPlatform::current())
+}
+
+fn hook_command(
+ script: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ platform: HookCommandPlatform,
+) -> String {
+ match platform {
+ HookCommandPlatform::Posix => {
+ let mut prefix = format!("AI_MEMORY_HOOK_URL={} ", shell_quote(server_url));
+ if let Some(t) = auth_token {
+ prefix.push_str(&format!("AI_MEMORY_AUTH_TOKEN={} ", shell_quote(t)));
+ }
+ format!("{prefix}{}", script.to_string_lossy())
+ }
+ HookCommandPlatform::Windows => {
+ let mut setup = format!("$env:AI_MEMORY_HOOK_URL={}", powershell_quote(server_url));
+ if let Some(t) = auth_token {
+ setup.push_str(&format!(
+ "; $env:AI_MEMORY_AUTH_TOKEN={}",
+ powershell_quote(t)
+ ));
+ }
+ format!(
+ "powershell.exe -NoProfile -ExecutionPolicy Bypass -Command \"{setup}; & {}\"",
+ powershell_quote(&script.to_string_lossy())
+ )
+ }
+ }
+}
+
/// Minimal shell quoting for embedding values into a `VAR=val cmd`
/// prefix. Wraps in single quotes; embedded `'` is escaped via
/// `'\''`. Safe for the URLs and bearer tokens we embed (no
@@ -276,6 +357,10 @@ fn shell_quote(s: &str) -> String {
format!("'{escaped}'")
}
+fn powershell_quote(s: &str) -> String {
+ format!("'{}'", s.replace('\'', "''"))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -484,7 +569,9 @@ mod tests {
#[test]
fn claude_code_payload_emits_absolute_paths() {
- let root = PathBuf::from("/home/user/.ai-memory/hooks/claude-code");
+ let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("hooks")
+ .join("claude-code");
let v = build_claude_code_payload(&root, "http://localhost:49374", None);
let cmd = v
.pointer("/hooks/SessionStart/0/hooks/0/command")
@@ -492,9 +579,38 @@ mod tests {
.unwrap();
// The command now has the env prefix + the absolute path,
// joined by a single space.
+ let expected = root.join("session-start.sh").to_string_lossy().to_string();
assert!(
- cmd.ends_with("/home/user/.ai-memory/hooks/claude-code/session-start.sh"),
+ cmd.ends_with(&expected),
"command should end with the absolute script path: {cmd}"
);
}
+
+ #[test]
+ fn windows_payload_uses_powershell_and_ps1_hooks() {
+ let root = PathBuf::from("C:/Users/alice/.local/share/ai-memory/hooks/claude-code");
+ let v = build_hook_payload_for_platform(
+ &CLAUDE_CODE_EVENTS,
+ &root,
+ "http://localhost:49374",
+ Some("tok'en"),
+ HookShape::Nested,
+ HookCommandPlatform::Windows,
+ );
+ let cmd = v
+ .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.contains("session-start.ps1"),
+ "expected ps1 script path: {cmd}"
+ );
+ assert!(
+ !cmd.contains("session-start.sh"),
+ "Windows command must not use sh: {cmd}"
+ );
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 48fcea4d..6f7b9c7e 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -18,11 +18,11 @@
//! --host-prefix "$HOME/.ai-memory/hooks" \
//! --auth-token "$TOKEN"
//!
-//! 1. Copies `/usr/local/share/ai-memory/hooks/claude-code/*.sh` into
+//! 1. Copies `/usr/local/share/ai-memory/hooks/claude-code/*.{sh,ps1}` into
//! `/host/hooks/claude-code/` (which on the host is
//! `$HOME/.ai-memory/hooks/claude-code/`).
//! 2. Prints the JSON config snippet whose `command` fields point at
-//! `$HOME/.ai-memory/hooks/claude-code/*.sh` (via `--host-prefix`)
+//! `$HOME/.ai-memory/hooks/claude-code/*.{sh,ps1}` (via `--host-prefix`)
//! so Claude Code on the host can exec them.
//!
//! When `--host-prefix` is omitted it defaults to `--to`, which is
@@ -35,7 +35,9 @@ use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use crate::cli::{AgentChoice, SetupAgentArgs};
-use crate::commands::render_shared::{CLAUDE_CODE_EVENTS, build_claude_code_payload};
+use crate::commands::render_shared::{
+ CLAUDE_CODE_EVENTS, build_claude_code_payload, hook_script_for_current_platform,
+};
use crate::config::Config;
/// Run the `setup-agent` subcommand.
@@ -82,7 +84,7 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
{
let entry = entry?;
let from = entry.path();
- if !from.is_file() || from.extension().and_then(|s| s.to_str()) != Some("sh") {
+ if !from.is_file() || !is_hook_script_file(&from) {
continue;
}
let file_name = from
@@ -103,6 +105,8 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
copied += 1;
}
+ copy_support_hook_scripts(&source, &dest_dir)?;
+
eprintln!(
"✓ Extracted {copied} hook script(s) from {} to {}",
source.display(),
@@ -200,13 +204,53 @@ fn emit_other(emit_root: &Path, label: &str, args: &SetupAgentArgs) {
}
println!();
for (_, script) in CLAUDE_CODE_EVENTS {
- println!("- {}", emit_root.join(script).display());
+ let script = hook_script_for_current_platform(script);
+ println!("- {}", emit_root.join(script.as_ref()).display());
}
println!();
println!("Set AI_MEMORY_HOOK_URL in each hook's environment to override the default.");
println!("Also run `ai-memory install-mcp --client {label}` to wire MCP separately.");
}
+fn is_hook_script_file(path: &Path) -> bool {
+ matches!(
+ path.extension().and_then(|s| s.to_str()),
+ Some("sh" | "ps1")
+ )
+}
+
+fn copy_support_hook_scripts(source_dir: &Path, dest_dir: &Path) -> Result<()> {
+ let Some(source_hooks_root) = source_dir.parent() else {
+ return Ok(());
+ };
+ let source_lib = source_hooks_root.join("lib");
+ if !source_lib.is_dir() {
+ return Ok(());
+ }
+ let Some(dest_hooks_root) = dest_dir.parent() else {
+ return Ok(());
+ };
+ let dest_lib = dest_hooks_root.join("lib");
+ fs::create_dir_all(&dest_lib)
+ .with_context(|| format!("creating hook support dir {}", dest_lib.display()))?;
+ for entry in fs::read_dir(&source_lib)
+ .with_context(|| format!("reading hook support dir {}", source_lib.display()))?
+ {
+ let entry = entry?;
+ let from = entry.path();
+ if !from.is_file() || from.extension().and_then(|s| s.to_str()) != Some("ps1") {
+ continue;
+ }
+ let to = dest_lib.join(
+ from.file_name()
+ .with_context(|| format!("invalid hook support path {}", from.display()))?,
+ );
+ fs::copy(&from, &to)
+ .with_context(|| format!("copying {} → {}", from.display(), to.display()))?;
+ }
+ Ok(())
+}
+
fn resolve_source(explicit: Option<&Path>, sub: &str) -> Result<PathBuf> {
let candidates: Vec<PathBuf> = if let Some(p) = explicit {
vec![p.join(sub)]
diff --git a/crates/ai-memory-web/build.rs b/crates/ai-memory-web/build.rs
index cc1ec7f2..c8867697 100644
--- a/crates/ai-memory-web/build.rs
+++ b/crates/ai-memory-web/build.rs
@@ -20,6 +20,14 @@ use sha2::{Digest, Sha256};
const TAILWIND_VERSION: &str = "3.4.17";
const TAILWIND_LINUX_X64_SHA256: &str =
"7d24f7fa191d2193b78cd5f5a42a6093e14409521908529f42d80b11fde1f1d4";
+const TAILWIND_LINUX_ARM64_SHA256: &str =
+ "69b1378b8133192d7d2feb12a116fa12d035594f58db3eff215879e4ad8cf39b";
+const TAILWIND_MACOS_X64_SHA256: &str =
+ "6cbdad74be776c087ffa5e9a057512c54898f9fe8828d3362212dfe32fc933a3";
+const TAILWIND_MACOS_ARM64_SHA256: &str =
+ "a1d0c7985759accca0bf12e51ac1dcbf0f6cf2fffb62e6e0f62d091c477a10a3";
+const TAILWIND_WINDOWS_X64_SHA256: &str =
+ "67f1c5e3f5a03406a7bf5badf5ada09b79f3ae78ec43450c15f7e983068da346";
fn main() {
// Re-run triggers.
@@ -131,6 +139,10 @@ fn tailwind_slug() -> &'static str {
fn expected_tailwind_sha256() -> &'static str {
match tailwind_slug() {
"tailwindcss-linux-x64" => TAILWIND_LINUX_X64_SHA256,
+ "tailwindcss-linux-arm64" => TAILWIND_LINUX_ARM64_SHA256,
+ "tailwindcss-macos-x64" => TAILWIND_MACOS_X64_SHA256,
+ "tailwindcss-macos-arm64" => TAILWIND_MACOS_ARM64_SHA256,
+ "tailwindcss-windows-x64.exe" => TAILWIND_WINDOWS_X64_SHA256,
other => panic!(
"No pinned Tailwind SHA-256 for {other}. Set TAILWIND_SKIP=1 and provide static/tailwind.css manually."
),
@@ -180,13 +192,15 @@ fn download_tailwind(out_dir: &Path) -> PathBuf {
let url = tailwind_url();
eprintln!("cargo:warning=Downloading Tailwind CSS CLI v{TAILWIND_VERSION} from {url}");
- // Try curl first, then wget.
- let success = try_download_curl(&url, &dest) || try_download_wget(&url, &dest);
+ // Try ubiquitous Unix tools first, then PowerShell for stock Windows.
+ let success = try_download_curl(&url, &dest)
+ || try_download_wget(&url, &dest)
+ || try_download_powershell(&url, &dest);
if !success {
panic!(
- "Could not download Tailwind CSS CLI — curl and wget both failed.\n\
- Either install curl or wget, OR set TAILWIND_SKIP=1 and place a compiled \
+ "Could not download Tailwind CSS CLI — curl, wget, and PowerShell all failed.\n\
+ Either install one of those download tools, OR set TAILWIND_SKIP=1 and place a compiled \
tailwind.css in crates/ai-memory-web/static/tailwind.css."
);
}
@@ -225,6 +239,25 @@ fn try_download_wget(url: &str, dest: &Path) -> bool {
.unwrap_or(false)
}
+fn try_download_powershell(url: &str, dest: &Path) -> bool {
+ try_download_with_powershell("pwsh", url, dest)
+ || try_download_with_powershell("powershell", url, dest)
+}
+
+fn try_download_with_powershell(binary: &str, url: &str, dest: &Path) -> bool {
+ Command::new(binary)
+ .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command"])
+ .arg(
+ "$ProgressPreference='SilentlyContinue'; \
+ Invoke-WebRequest -Uri $args[0] -OutFile $args[1]",
+ )
+ .arg(url)
+ .arg(dest)
+ .status()
+ .map(|s| s.success())
+ .unwrap_or(false)
+}
+
/// Invoke the Tailwind CLI to produce `out_css`.
fn compile_tailwind(binary: &Path, crate_dir: &Path, out_css: &Path) {
let input_css = crate_dir.join("static/input.css");
diff --git a/docs/install.md b/docs/install.md
index a9f3ffec..5a8a5aca 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -256,9 +256,16 @@ cargo build --release --workspace
```
Data dir defaults to `~/.local/share/ai-memory` on Linux,
-`~/Library/Application Support/ai-memory` on macOS. Override with
-`AI_MEMORY_DATA_DIR=/path`. To require bearer-token auth, set
-`AI_MEMORY_AUTH_TOKEN` in the server's environment.
+`~/Library/Application Support/ai-memory` on macOS, and the platform
+local-data directory on Windows, typically
+`%LOCALAPPDATA%\ai-memory`. Override with `AI_MEMORY_DATA_DIR=/path`.
+To require bearer-token auth, set `AI_MEMORY_AUTH_TOKEN` in the
+server's environment.
+
+On Windows, see [`docs/windows.md`](windows.md). The short version: run
+the install commands from the same environment that launches the agent.
+WSL2-launched agents need WSL paths and POSIX `.sh` hooks; native Windows
+agents need Windows paths and PowerShell `.ps1` hooks.
When run from source, `install-hooks` finds the bundled scripts in
the repo's `hooks/` automatically:
diff --git a/docs/windows.md b/docs/windows.md
new file mode 100644
index 00000000..3f6a5856
--- /dev/null
+++ b/docs/windows.md
@@ -0,0 +1,176 @@
+# Windows Support
+
+Windows support has two modes. Pick the mode that matches where your
+agent CLI actually runs.
+
+## Rule Of Thumb
+
+Run `install-mcp` and `install-hooks` from the same environment that
+launches Claude Code, Codex, Cursor, Gemini CLI, or another agent.
+
+- If the agent runs inside WSL2, install ai-memory inside WSL2.
+- If the agent runs as a native Windows process, install ai-memory from
+ PowerShell on Windows.
+- Do not mix the Windows wrapper with WSL2-launched agents unless you
+ deliberately override every config and hook path.
+
+The difference matters because hook configs contain executable paths.
+WSL2 agents need Linux paths and POSIX `.sh` hooks. Native Windows
+agents need Windows paths and PowerShell `.ps1` hooks.
+
+## Scenario A: Everything Inside WSL2
+
+This is the most Linux-like Windows setup. Use it when your agent CLI is
+installed and launched inside a WSL2 distro.
+
+```bash
+# Inside WSL2.
+mkdir -p ~/.local/bin
+curl -fsSL https://raw.githubusercontent.com/akitaonrails/ai-memory/main/bin/ai-memory \
+ -o ~/.local/bin/ai-memory
+chmod +x ~/.local/bin/ai-memory
+export PATH="$HOME/.local/bin:$PATH"
+
+docker run -d --name ai-memory \
+ --restart unless-stopped \
+ -p 127.0.0.1:49374:49374 \
+ -v ai-memory-data:/data \
+ akitaonrails/ai-memory:latest
+
+ai-memory install-mcp --client claude-code --apply
+ai-memory install-hooks --agent claude-code --apply
+```
+
+In this mode, ai-memory behaves like Linux:
+
+- Config files are written under your WSL2 home directory.
+- Hook scripts are staged under `~/.local/share/ai-memory/hooks/`.
+- Hook commands point at `.sh` scripts.
+- The agent should also be launched from WSL2 so it can execute those
+ WSL paths.
+
+If Docker Desktop provides the Docker engine to WSL2, enable WSL
+integration for the distro first. If you run a native Docker engine
+inside WSL2, no Windows wrapper is involved.
+
+## Scenario B: Native Windows With Docker Desktop
+
+Use this when the agent CLI runs as a native Windows process and you want
+the ai-memory server to run from the Docker image.
+
+```powershell
+# Install the Windows Docker wrapper.
+$UserBin = "$HOME\bin"
+New-Item -ItemType Directory -Force $UserBin | Out-Null
+foreach ($File in @("ai-memory.ps1", "ai-memory.cmd")) {
+ Invoke-WebRequest `
+ -Uri "https://raw.githubusercontent.com/akitaonrails/ai-memory/main/bin/$File" `
+ -OutFile "$UserBin\$File"
+}
+Get-ChildItem "$UserBin\ai-memory.*" | Unblock-File
+
+# Put the wrapper directory on your user PATH for future terminals.
+$UserPath = [Environment]::GetEnvironmentVariable("Path", "User")
+if (($UserPath -split ';') -notcontains $UserBin) {
+ $NewUserPath = (($UserPath, $UserBin) | Where-Object { $_ }) -join ";"
+ [Environment]::SetEnvironmentVariable("Path", $NewUserPath, "User")
+ $env:Path = "$env:Path;$UserBin"
+}
+
+# Start the server with Docker Desktop.
+docker run -d --name ai-memory `
+ --restart unless-stopped `
+ -p 127.0.0.1:49374:49374 `
+ -v ai-memory-data:/data `
+ akitaonrails/ai-memory:latest
+
+# Verify the wrapper can reach the server.
+ai-memory status
+
+# Wire MCP and lifecycle hooks for a native Windows agent.
+ai-memory install-mcp --client claude-code --apply
+ai-memory install-hooks --agent claude-code --apply
+```
+
+In this mode, the PowerShell wrapper runs the Linux container but tells
+the CLI to render Windows hook commands:
+
+- Config files are written through the mounted Windows home directory.
+- Hook scripts are staged under `$HOME\.local\share\ai-memory\hooks\`.
+- Hook commands explicitly call `powershell.exe`.
+- Hook commands point at `.ps1` scripts.
+
+Use the matching `--client` / `--agent` values for other clients, for
+example `codex`, `cursor`, or `gemini-cli`.
+
+## Scenario C: Native Windows Source Build
+
+Use this when developing ai-memory itself on Windows or when you do not
+want the Docker wrapper for CLI commands.
+
+```powershell
+git clone https://github.com/akitaonrails/ai-memory .\ai-memory
+Set-Location .\ai-memory
+cargo build --workspace
+cargo test --workspace
+
+target\debug\ai-memory.exe init
+target\debug\ai-memory.exe serve --transport http --bind 127.0.0.1:49374
+```
+
+The Tailwind build step supports the pinned
+`tailwindcss-windows-x64.exe` binary and falls back to PowerShell
+`Invoke-WebRequest` when `curl`/`wget` are unavailable. You should not
+need `TAILWIND_SKIP=1` for normal Windows builds.
+
+From another PowerShell window in the repo:
+
+```powershell
+target\debug\ai-memory.exe install-mcp --client claude-code --apply
+target\debug\ai-memory.exe install-hooks --agent claude-code --apply
+```
+
+Native Windows builds automatically render `.ps1` lifecycle hooks. The
+hook bundle ships matching `.sh` and `.ps1` event scripts, and tests
+enforce one-to-one event/agent parity between them.
+
+## Current Harness Caveats
+
+Windows hook support is new and needs real-world testing against native
+Windows agent builds.
+
+- Claude Code may be used natively on Windows or from inside WSL2. Test
+ which process launches the hooks before assuming path format.
+- Codex, OpenCode, Cursor, and Gemini CLI may each choose different
+ Windows config locations or shell execution behavior. ai-memory uses
+ the current best-known defaults, but they need validation on real
+ installations.
+- MCP over HTTP should be less path-sensitive than hooks, but
+ `install-mcp --apply` still writes to a client-specific config file;
+ confirm the agent actually loads it.
+- OpenCode and OMP/Pi use generated TypeScript integrations rather than
+ the shell hook bundle, so their Windows behavior depends on the host
+ runtime loading those files correctly.
+
+## Suggested Test Checklist
+
+For WSL2:
+
+1. Run all install commands inside WSL2.
+2. Confirm generated hook commands reference `.sh` files under WSL paths.
+3. Launch the agent from WSL2.
+4. Call `memory_status` from the agent.
+5. Send a prompt, then run `ai-memory status` or `ai-memory recent`.
+
+For native Windows:
+
+1. Run all install commands from PowerShell or `cmd.exe` using
+ `ai-memory` / `ai-memory.ps1`.
+2. Confirm generated hook commands reference `.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`.
+
+Report which mode you tested, which agent and version you used, and
+whether the hook command executed or failed with a path/shell error.
diff --git a/hooks/claude-code/post-tool-use.ps1 b/hooks/claude-code/post-tool-use.ps1
new file mode 100644
index 00000000..63dffcb9
--- /dev/null
+++ b/hooks/claude-code/post-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "post-tool-use" -Agent "claude-code"
+exit 0
diff --git a/hooks/claude-code/pre-compact.ps1 b/hooks/claude-code/pre-compact.ps1
new file mode 100644
index 00000000..d1bd77a3
--- /dev/null
+++ b/hooks/claude-code/pre-compact.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-compact" -Agent "claude-code"
+exit 0
diff --git a/hooks/claude-code/pre-tool-use.ps1 b/hooks/claude-code/pre-tool-use.ps1
new file mode 100644
index 00000000..9d382550
--- /dev/null
+++ b/hooks/claude-code/pre-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "claude-code"
+exit 0
diff --git a/hooks/claude-code/session-end.ps1 b/hooks/claude-code/session-end.ps1
new file mode 100644
index 00000000..baea5153
--- /dev/null
+++ b/hooks/claude-code/session-end.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-end" -Agent "claude-code"
+exit 0
diff --git a/hooks/claude-code/session-start.ps1 b/hooks/claude-code/session-start.ps1
new file mode 100644
index 00000000..309675d5
--- /dev/null
+++ b/hooks/claude-code/session-start.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-start" -Agent "claude-code" -FetchHandoff
+exit 0
diff --git a/hooks/claude-code/stop.ps1 b/hooks/claude-code/stop.ps1
new file mode 100644
index 00000000..ae13b6a1
--- /dev/null
+++ b/hooks/claude-code/stop.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "stop" -Agent "claude-code"
+exit 0
diff --git a/hooks/claude-code/user-prompt-submit.ps1 b/hooks/claude-code/user-prompt-submit.ps1
new file mode 100644
index 00000000..0f95a474
--- /dev/null
+++ b/hooks/claude-code/user-prompt-submit.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "user-prompt" -Agent "claude-code"
+exit 0
diff --git a/hooks/codex/post-tool-use.ps1 b/hooks/codex/post-tool-use.ps1
new file mode 100644
index 00000000..af65103e
--- /dev/null
+++ b/hooks/codex/post-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "post-tool-use" -Agent "codex"
+exit 0
diff --git a/hooks/codex/pre-compact.ps1 b/hooks/codex/pre-compact.ps1
new file mode 100644
index 00000000..05fa17bc
--- /dev/null
+++ b/hooks/codex/pre-compact.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-compact" -Agent "codex"
+exit 0
diff --git a/hooks/codex/pre-tool-use.ps1 b/hooks/codex/pre-tool-use.ps1
new file mode 100644
index 00000000..a88c776d
--- /dev/null
+++ b/hooks/codex/pre-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "codex"
+exit 0
diff --git a/hooks/codex/session-end.ps1 b/hooks/codex/session-end.ps1
new file mode 100644
index 00000000..a3f68620
--- /dev/null
+++ b/hooks/codex/session-end.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-end" -Agent "codex"
+exit 0
diff --git a/hooks/codex/session-start.ps1 b/hooks/codex/session-start.ps1
new file mode 100644
index 00000000..2b6257bd
--- /dev/null
+++ b/hooks/codex/session-start.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-start" -Agent "codex" -FetchHandoff
+exit 0
diff --git a/hooks/codex/stop.ps1 b/hooks/codex/stop.ps1
new file mode 100644
index 00000000..19b9bcb4
--- /dev/null
+++ b/hooks/codex/stop.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "stop" -Agent "codex"
+exit 0
diff --git a/hooks/codex/user-prompt-submit.ps1 b/hooks/codex/user-prompt-submit.ps1
new file mode 100644
index 00000000..fc215dc0
--- /dev/null
+++ b/hooks/codex/user-prompt-submit.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "user-prompt" -Agent "codex"
+exit 0
diff --git a/hooks/cursor/post-tool-use.ps1 b/hooks/cursor/post-tool-use.ps1
new file mode 100644
index 00000000..01d4b5a5
--- /dev/null
+++ b/hooks/cursor/post-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "post-tool-use" -Agent "cursor"
+exit 0
diff --git a/hooks/cursor/pre-compact.ps1 b/hooks/cursor/pre-compact.ps1
new file mode 100644
index 00000000..f1e1f7a5
--- /dev/null
+++ b/hooks/cursor/pre-compact.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-compact" -Agent "cursor"
+exit 0
diff --git a/hooks/cursor/pre-tool-use.ps1 b/hooks/cursor/pre-tool-use.ps1
new file mode 100644
index 00000000..91955f9f
--- /dev/null
+++ b/hooks/cursor/pre-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "cursor"
+exit 0
diff --git a/hooks/cursor/session-end.ps1 b/hooks/cursor/session-end.ps1
new file mode 100644
index 00000000..f1cc9be7
--- /dev/null
+++ b/hooks/cursor/session-end.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-end" -Agent "cursor"
+exit 0
diff --git a/hooks/cursor/session-start.ps1 b/hooks/cursor/session-start.ps1
new file mode 100644
index 00000000..be324ece
--- /dev/null
+++ b/hooks/cursor/session-start.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-start" -Agent "cursor" -FetchHandoff
+exit 0
diff --git a/hooks/cursor/stop.ps1 b/hooks/cursor/stop.ps1
new file mode 100644
index 00000000..b0f2dde1
--- /dev/null
+++ b/hooks/cursor/stop.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "stop" -Agent "cursor"
+exit 0
diff --git a/hooks/cursor/user-prompt-submit.ps1 b/hooks/cursor/user-prompt-submit.ps1
new file mode 100644
index 00000000..8843a514
--- /dev/null
+++ b/hooks/cursor/user-prompt-submit.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "user-prompt" -Agent "cursor"
+exit 0
diff --git a/hooks/gemini-cli/post-tool-use.ps1 b/hooks/gemini-cli/post-tool-use.ps1
new file mode 100644
index 00000000..1e23bd79
--- /dev/null
+++ b/hooks/gemini-cli/post-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "post-tool-use" -Agent "gemini-cli"
+exit 0
diff --git a/hooks/gemini-cli/pre-compact.ps1 b/hooks/gemini-cli/pre-compact.ps1
new file mode 100644
index 00000000..c909dd69
--- /dev/null
+++ b/hooks/gemini-cli/pre-compact.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-compact" -Agent "gemini-cli"
+exit 0
diff --git a/hooks/gemini-cli/pre-tool-use.ps1 b/hooks/gemini-cli/pre-tool-use.ps1
new file mode 100644
index 00000000..96967374
--- /dev/null
+++ b/hooks/gemini-cli/pre-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "gemini-cli"
+exit 0
diff --git a/hooks/gemini-cli/session-end.ps1 b/hooks/gemini-cli/session-end.ps1
new file mode 100644
index 00000000..d0107e5e
--- /dev/null
+++ b/hooks/gemini-cli/session-end.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-end" -Agent "gemini-cli"
+exit 0
diff --git a/hooks/gemini-cli/session-start.ps1 b/hooks/gemini-cli/session-start.ps1
new file mode 100644
index 00000000..4adf003a
--- /dev/null
+++ b/hooks/gemini-cli/session-start.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-start" -Agent "gemini-cli" -FetchHandoff
+exit 0
diff --git a/hooks/gemini-cli/stop.ps1 b/hooks/gemini-cli/stop.ps1
new file mode 100644
index 00000000..0f66c5a9
--- /dev/null
+++ b/hooks/gemini-cli/stop.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "stop" -Agent "gemini-cli"
+exit 0
diff --git a/hooks/gemini-cli/user-prompt-submit.ps1 b/hooks/gemini-cli/user-prompt-submit.ps1
new file mode 100644
index 00000000..50fb06e0
--- /dev/null
+++ b/hooks/gemini-cli/user-prompt-submit.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "user-prompt" -Agent "gemini-cli"
+exit 0
diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1
new file mode 100644
index 00000000..636dd940
--- /dev/null
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -0,0 +1,41 @@
+function Invoke-AiMemoryHook {
+ param(
+ [Parameter(Mandatory = $true)] [string] $Event,
+ [Parameter(Mandatory = $true)] [string] $Agent,
+ [switch] $FetchHandoff
+ )
+
+ $Server = if ($env:AI_MEMORY_HOOK_URL) { $env:AI_MEMORY_HOOK_URL } else { "http://127.0.0.1:49374" }
+ $Payload = [Console]::In.ReadToEnd()
+ $Headers = @{}
+
+ if ($env:AI_MEMORY_AUTH_TOKEN) {
+ $Headers["Authorization"] = "Bearer $env:AI_MEMORY_AUTH_TOKEN"
+ }
+
+ try {
+ Invoke-WebRequest `
+ -UseBasicParsing `
+ -TimeoutSec 1 `
+ -Method Post `
+ -Uri "$Server/hook?event=$Event&agent=$Agent" `
+ -Headers $Headers `
+ -ContentType "application/json" `
+ -Body $Payload | Out-Null
+ } catch {
+ }
+
+ if ($FetchHandoff) {
+ try {
+ $Response = Invoke-WebRequest `
+ -UseBasicParsing `
+ -TimeoutSec 1 `
+ -Uri "$Server/handoff?agent=$Agent" `
+ -Headers $Headers
+ if ($null -ne $Response -and $null -ne $Response.Content) {
+ [Console]::Out.Write($Response.Content)
+ }
+ } catch {
+ }
+ }
+}
diff --git a/hooks/opencode/post-tool-use.ps1 b/hooks/opencode/post-tool-use.ps1
new file mode 100644
index 00000000..4a36b371
--- /dev/null
+++ b/hooks/opencode/post-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "post-tool-use" -Agent "open-code"
+exit 0
diff --git a/hooks/opencode/pre-compact.ps1 b/hooks/opencode/pre-compact.ps1
new file mode 100644
index 00000000..915c8699
--- /dev/null
+++ b/hooks/opencode/pre-compact.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-compact" -Agent "open-code"
+exit 0
diff --git a/hooks/opencode/pre-tool-use.ps1 b/hooks/opencode/pre-tool-use.ps1
new file mode 100644
index 00000000..d49c79a9
--- /dev/null
+++ b/hooks/opencode/pre-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "open-code"
+exit 0
diff --git a/hooks/opencode/session-end.ps1 b/hooks/opencode/session-end.ps1
new file mode 100644
index 00000000..43bb5567
--- /dev/null
+++ b/hooks/opencode/session-end.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-end" -Agent "open-code"
+exit 0
diff --git a/hooks/opencode/session-start.ps1 b/hooks/opencode/session-start.ps1
new file mode 100644
index 00000000..70a68afa
--- /dev/null
+++ b/hooks/opencode/session-start.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-start" -Agent "open-code" -FetchHandoff
+exit 0
diff --git a/hooks/opencode/stop.ps1 b/hooks/opencode/stop.ps1
new file mode 100644
index 00000000..9efb9a0d
--- /dev/null
+++ b/hooks/opencode/stop.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "stop" -Agent "open-code"
+exit 0
diff --git a/hooks/opencode/user-prompt-submit.ps1 b/hooks/opencode/user-prompt-submit.ps1
new file mode 100644
index 00000000..8e2ee2b0
--- /dev/null
+++ b/hooks/opencode/user-prompt-submit.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "user-prompt" -Agent "open-code"
+exit 0