Skip to content

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

Rust

fix(hooks): harden native hook auth flow

AkitaOnRails30527447bea7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 847b528f..a6b8c2bc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
+### Added
+- Native Claude Code hooks on macOS/Linux now use the direct
+ `ai-memory hook --event ...` command by default, matching native Windows.
+ Native hook commands spool events locally and can authenticate with a stored
+ per-developer OIDC device token instead of a shared static hook token.
+- `ai-memory auth login oidc-device --issuer <url> --client-id <id>` stores a
+ generic OIDC device-flow token for native hook authentication.
+
+### Fixed
+- `ai-memory uninstall --only hooks` now recognizes and removes native
+ `ai-memory hook ...` commands as well as legacy script commands.
## [0.15.0] - 2026-06-11
### Added
diff --git a/README.md b/README.md
index c251f0f0..b0967ca7 100644
--- a/README.md
+++ b/README.md
@@ -31,7 +31,7 @@
| Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. |
| OpenClaw | Supported | MCP config + native plugin lifecycle hooks. |
| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). |
-| LLM providers | Supported | Anthropic, OpenAI, OpenAI OAuth/Codex, GitHub Copilot, Gemini, and OpenAI-compatible endpoints. |
+| LLM/auth providers | Supported | Anthropic, OpenAI, OpenAI OAuth/Codex, GitHub Copilot, Gemini, OpenAI-compatible endpoints, and generic OIDC device auth for native hooks. |
| Embedding providers | Supported | OpenAI, Voyage, and Google Gemini. |
## What it is
@@ -304,6 +304,23 @@ Bearer auth protects `/mcp`, `/hook`, `/handoff`, `/admin/*`, and
as the password. Non-loopback binds should also set
`AI_MEMORY_ALLOWED_HOSTS` to guard against DNS rebinding.
+For shared servers where each developer should authenticate their own hook
+writes, native Claude Code hooks can use a stored OIDC device token instead of
+embedding a shared static token:
+
+```bash
+ai-memory auth login oidc-device \
+ --issuer "https://issuer.example.com/realms/team" \
+ --client-id "ai-memory-cli"
+
+ai-memory install-hooks --agent claude-code --apply \
+ --server-url "http://<server-ip>:49374"
+```
+
+OIDC hook auth requires the native `ai-memory hook ...` command path. The Docker
+wrapper keeps shell-script hooks by default; set up OIDC from a native release
+binary or source install.
+
**Want HTTPS?** ai-memory deliberately does not terminate TLS itself —
the right answer is a battle-tested reverse proxy in front of it.
[`docs/https-via-proxy.md`](docs/https-via-proxy.md) is the deployment
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index bb2eff86..f18a6037 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -151,13 +151,34 @@ pub async fn get_handoff(
if let Some(t) = token {
req = req.bearer_auth(t);
}
- let body = req.send().await.ok()?.text().await.ok()?;
+ let resp = req.send().await.ok()?;
+ if !resp.status().is_success() {
+ return None;
+ }
+ let body = resp.text().await.ok()?;
if body.is_empty() { None } else { Some(body) }
}
#[cfg(test)]
mod tests {
use super::*;
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ async fn serve_once(status: &'static str, body: &'static str) -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let (mut stream, _) = listener.accept().await.unwrap();
+ let mut buf = [0_u8; 1024];
+ let _ = stream.read(&mut buf).await;
+ let response = format!(
+ "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ });
+ format!("http://{addr}/handoff")
+ }
#[test]
fn extracts_top_level_cwd() {
@@ -199,6 +220,13 @@ mod tests {
assert!(!ok);
}
+ #[tokio::test]
+ async fn get_handoff_ignores_non_success_status() {
+ let url = serve_once("401 Unauthorized", "unauthorized").await;
+ let got = get_handoff(&build_client(), &url, None, Duration::from_secs(1)).await;
+ assert!(got.is_none(), "non-2xx body must not become context");
+ }
+
/// Happy-path TOML parser: extracts each declared root-level
/// `key = "value"` pair. Mirrors the shell `ai_memory_parse_toml_key`.
#[test]
diff --git a/crates/ai-memory-cli/src/commands/hook_spool.rs b/crates/ai-memory-cli/src/commands/hook_spool.rs
index 64311f03..940ef4ba 100644
--- a/crates/ai-memory-cli/src/commands/hook_spool.rs
+++ b/crates/ai-memory-cli/src/commands/hook_spool.rs
@@ -33,6 +33,12 @@ const MAX_ATTEMPTS: u32 = 8;
/// Drop a spooled event older than this regardless of attempts (7 days), so a
/// long-dead instance can't leave the spool growing without bound.
const MAX_AGE_MS: u64 = 7 * 24 * 60 * 60 * 1000;
+/// Hard cap on queued events per data dir. Enqueue prunes oldest files beyond
+/// this so a down server cannot grow the hook spool without bound.
+#[cfg(not(test))]
+const MAX_SPOOL_FILES: usize = 10_000;
+#[cfg(test)]
+const MAX_SPOOL_FILES: usize = 3;
/// How a spooled event authenticates to the server when drained.
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
@@ -97,7 +103,9 @@ pub fn enqueue(spool: &Path, entry: &SpoolEntry) -> std::io::Result<()> {
let final_path = spool.join(&name);
let bytes = serde_json::to_vec(entry)?;
write_private(&tmp, &bytes)?;
- std::fs::rename(&tmp, &final_path)
+ std::fs::rename(&tmp, &final_path)?;
+ prune_spool_file_count(spool);
+ Ok(())
}
fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
@@ -220,7 +228,7 @@ pub async fn drain(
let _ = std::fs::remove_file(&path);
result.sent += 1;
} else {
- entry.attempts += 1;
+ entry.attempts = entry.attempts.saturating_add(1);
if entry.attempts >= MAX_ATTEMPTS {
let _ = std::fs::remove_file(&path);
result.dropped += 1;
@@ -264,15 +272,30 @@ pub async fn resolve_bearer(
async fn resolve_oidc(client: &reqwest::Client, data_dir: &Path) -> Option<String> {
let auth_path = data_dir.join("auth.json");
let mut token = OidcToken::load(&auth_path).ok().flatten()?;
- if token.needs_refresh()
- && let Ok(refreshed) = refresh_access_token(client, &token).await
- {
+ if token.needs_refresh() {
+ let Ok(refreshed) = refresh_access_token(client, &token).await else {
+ return None;
+ };
let _ = refreshed.save(&auth_path);
token = refreshed;
}
Some(token.access.expose_secret().to_string())
}
+fn prune_spool_file_count(spool: &Path) {
+ let Some(mut files) = list_entries(spool) else {
+ return;
+ };
+ let excess = files.len().saturating_sub(MAX_SPOOL_FILES);
+ if excess == 0 {
+ return;
+ }
+ files.sort();
+ for path in files.into_iter().take(excess) {
+ let _ = std::fs::remove_file(path);
+ }
+}
+
/// List `*.json` spool files (ignoring in-flight `*.json.tmp`), or None when the
/// directory doesn't exist yet.
fn list_entries(spool: &Path) -> Option<Vec<PathBuf>> {
@@ -325,6 +348,31 @@ mod tests {
assert_eq!(loaded.token.as_deref(), Some("tok"));
}
+ #[test]
+ fn enqueue_prunes_oldest_files_when_spool_exceeds_limit() {
+ let tmp = tempfile::tempdir().unwrap();
+ let spool = spool_dir(tmp.path());
+ for i in 0..(MAX_SPOOL_FILES + 2) {
+ let mut entry = entry_for(
+ format!("https://x/hook?event=e{i}"),
+ "{}".into(),
+ None,
+ false,
+ );
+ entry.created_ms = i as u64;
+ enqueue(&spool, &entry).unwrap();
+ }
+
+ let mut files = list_entries(&spool).unwrap();
+ files.sort();
+ assert_eq!(files.len(), MAX_SPOOL_FILES);
+ let bodies: Vec<SpoolEntry> = files
+ .iter()
+ .map(|path| serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap())
+ .collect();
+ assert!(bodies.iter().all(|entry| entry.created_ms >= 2));
+ }
+
#[tokio::test]
async fn drain_unreachable_leaves_events_queued() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index f79221af..a2cefd03 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -24,9 +24,9 @@ use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json};
use crate::commands::install_mcp;
use crate::commands::openclaw_plugin;
use crate::commands::render_shared::{
- CURSOR_PROFILE, GEMINI_PROFILE, build_antigravity_payload, build_claude_code_payload,
- build_codex_payload, build_profile_payload, hook_script_for_claude_code,
- hook_script_for_current_platform, ts_string_literal,
+ CURSOR_PROFILE, GEMINI_PROFILE, build_antigravity_payload_with_data_dir,
+ build_claude_code_payload_with_data_dir, build_profile_payload_for_agent,
+ hook_script_for_claude_code, hook_script_for_current_platform, ts_string_literal,
};
use crate::config::{Config, DEFAULT_SERVER_URL};
@@ -126,23 +126,35 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {
AgentChoice::Omp => apply_to_omp_extension(&server_url, auth, &args),
AgentChoice::ClaudeCode => {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
- apply_to_claude_code_settings(&hooks_dir, &server_url, auth, &args)
+ apply_to_claude_code_settings(
+ &hooks_dir,
+ &server_url,
+ auth,
+ &config.data_dir,
+ &args,
+ )
}
AgentChoice::Codex => {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
- apply_to_codex_settings(&hooks_dir, &server_url, auth, &args)
+ apply_to_codex_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)
}
AgentChoice::Cursor => {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
- apply_to_cursor_settings(&hooks_dir, &server_url, auth, &args)
+ apply_to_cursor_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)
}
AgentChoice::GeminiCli => {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
- apply_to_gemini_settings(&hooks_dir, &server_url, auth, &args)
+ apply_to_gemini_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)
}
AgentChoice::AntigravityCli => {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
- apply_to_antigravity_settings(&hooks_dir, &server_url, auth, &args)
+ apply_to_antigravity_settings(
+ &hooks_dir,
+ &server_url,
+ auth,
+ &config.data_dir,
+ &args,
+ )
}
AgentChoice::Openclaw => openclaw_plugin::apply(&server_url, auth, &args),
};
@@ -152,7 +164,7 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {
AgentChoice::Omp => render_omp_extension(&server_url, auth),
AgentChoice::ClaudeCode => {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
- render_claude_code(&hooks_dir, &server_url, auth)
+ render_claude_code(&hooks_dir, &server_url, auth, &config.data_dir)
}
AgentChoice::Codex => {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
@@ -419,6 +431,7 @@ fn apply_to_claude_code_settings(
hooks_dir: &Path,
server_url: &str,
auth_token: Option<&str>,
+ data_dir: &Path,
args: &InstallHooksArgs,
) -> Result<()> {
let path = match &args.config_file {
@@ -427,7 +440,12 @@ fn apply_to_claude_code_settings(
};
let staged = stage_hook_scripts(hooks_dir, "claude-code")?;
let command_dir = staged_command_dir(&staged, "claude-code");
- let payload = build_claude_code_payload(&command_dir, server_url, auth_token);
+ let payload = build_claude_code_payload_with_data_dir(
+ &command_dir,
+ server_url,
+ auth_token,
+ Some(data_dir),
+ );
let our_hooks = payload
.get("hooks")
.and_then(|v| v.as_object())
@@ -491,6 +509,7 @@ fn apply_to_codex_settings(
hooks_dir: &Path,
server_url: &str,
auth_token: Option<&str>,
+ data_dir: &Path,
args: &InstallHooksArgs,
) -> Result<()> {
let path = match &args.config_file {
@@ -499,7 +518,7 @@ fn apply_to_codex_settings(
};
let staged = stage_hook_scripts(hooks_dir, "codex")?;
let command_dir = staged_command_dir(&staged, "codex");
- let outcome = merge_codex_hooks(&command_dir, server_url, auth_token, &path)?;
+ let outcome = merge_codex_hooks(&command_dir, server_url, auth_token, data_dir, &path)?;
println!(
"✓ {} {} ({})",
outcome.verb(),
@@ -528,12 +547,20 @@ fn merge_codex_hooks(
staged: &Path,
server_url: &str,
auth_token: Option<&str>,
+ data_dir: &Path,
config_path: &Path,
) -> Result<ApplyOutcome> {
// Build the Codex-flavoured payload. The JSON shape is identical
// to Claude Code's matcher + nested hooks form — only the event
// list differs (no `SessionEnd`, which Codex doesn't recognise).
- let payload = build_codex_payload(staged, server_url, auth_token);
+ let payload = build_profile_payload_for_agent(
+ &super::render_shared::CODEX_PROFILE,
+ staged,
+ server_url,
+ auth_token,
+ "codex",
+ Some(data_dir),
+ );
let our_hooks = payload
.get("hooks")
.and_then(|v| v.as_object())
@@ -583,6 +610,7 @@ fn apply_to_cursor_settings(
hooks_dir: &Path,
server_url: &str,
auth_token: Option<&str>,
+ data_dir: &Path,
args: &InstallHooksArgs,
) -> Result<()> {
let path = match &args.config_file {
@@ -591,7 +619,7 @@ fn apply_to_cursor_settings(
};
let staged = stage_hook_scripts(hooks_dir, "cursor")?;
let command_dir = staged_command_dir(&staged, "cursor");
- let outcome = merge_cursor_hooks(&command_dir, server_url, auth_token, &path)?;
+ let outcome = merge_cursor_hooks(&command_dir, server_url, auth_token, data_dir, &path)?;
println!(
"✓ {} {} ({})",
outcome.verb(),
@@ -609,9 +637,17 @@ fn merge_cursor_hooks(
staged: &Path,
server_url: &str,
auth_token: Option<&str>,
+ data_dir: &Path,
config_path: &Path,
) -> Result<ApplyOutcome> {
- let payload = build_profile_payload(&CURSOR_PROFILE, staged, server_url, auth_token);
+ let payload = build_profile_payload_for_agent(
+ &CURSOR_PROFILE,
+ staged,
+ server_url,
+ auth_token,
+ "cursor",
+ Some(data_dir),
+ );
let our_hooks = payload
.get("hooks")
.and_then(|v| v.as_object())
@@ -656,6 +692,7 @@ fn apply_to_gemini_settings(
hooks_dir: &Path,
server_url: &str,
auth_token: Option<&str>,
+ data_dir: &Path,
args: &InstallHooksArgs,
) -> Result<()> {
let path = match &args.config_file {
@@ -664,7 +701,7 @@ fn apply_to_gemini_settings(
};
let staged = stage_hook_scripts(hooks_dir, "gemini-cli")?;
let command_dir = staged_command_dir(&staged, "gemini-cli");
- let outcome = merge_gemini_hooks(&command_dir, server_url, auth_token, &path)?;
+ let outcome = merge_gemini_hooks(&command_dir, server_url, auth_token, data_dir, &path)?;
println!(
"✓ {} {} ({})",
outcome.verb(),
@@ -682,9 +719,17 @@ fn merge_gemini_hooks(
staged: &Path,
server_url: &str,
auth_token: Option<&str>,
+ data_dir: &Path,
config_path: &Path,
) -> Result<ApplyOutcome> {
- let payload = build_profile_payload(&GEMINI_PROFILE, staged, server_url, auth_token);
+ let payload = build_profile_payload_for_agent(
+ &GEMINI_PROFILE,
+ staged,
+ server_url,
+ auth_token,
+ "gemini-cli",
+ Some(data_dir),
+ );
let our_hooks = payload
.get("hooks")
.and_then(|v| v.as_object())
@@ -721,6 +766,7 @@ fn apply_to_antigravity_settings(
hooks_dir: &Path,
server_url: &str,
auth_token: Option<&str>,
+ data_dir: &Path,
args: &InstallHooksArgs,
) -> Result<()> {
let path = match &args.config_file {
@@ -729,7 +775,7 @@ fn apply_to_antigravity_settings(
};
let staged = stage_hook_scripts(hooks_dir, "antigravity-cli")?;
let command_dir = staged_command_dir(&staged, "antigravity-cli");
- let outcome = merge_antigravity_hooks(&command_dir, server_url, auth_token, &path)?;
+ let outcome = merge_antigravity_hooks(&command_dir, server_url, auth_token, data_dir, &path)?;
println!(
"✓ {} {} ({})",
outcome.verb(),
@@ -747,9 +793,11 @@ fn merge_antigravity_hooks(
staged: &Path,
server_url: &str,
auth_token: Option<&str>,
+ data_dir: &Path,
config_path: &Path,
) -> Result<ApplyOutcome> {
- let payload = build_antigravity_payload(staged, server_url, auth_token);
+ let payload =
+ build_antigravity_payload_with_data_dir(staged, server_url, auth_token, Some(data_dir));
let our_group = payload
.get("ai-memory")
.and_then(|v| v.as_object())
@@ -1645,7 +1693,12 @@ fn repo_root_guess() -> Option<PathBuf> {
// CLAUDE_CODE_EVENTS + build_claude_code_payload now live in
// `super::render_shared`, shared with `setup-agent`.
-fn render_claude_code(hooks_dir: &Path, server_url: &str, auth_token: Option<&str>) -> Result<()> {
+fn render_claude_code(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+) -> Result<()> {
// Soft check: warn (don't bail) if a script is missing. The user
// may be running this command inside docker against a host path
// that exists only on the host's filesystem — bailing would
@@ -1663,7 +1716,8 @@ fn render_claude_code(hooks_dir: &Path, server_url: &str, auth_token: Option<&st
);
}
}
- let payload = build_claude_code_payload(hooks_dir, server_url, auth_token);
+ let payload =
+ build_claude_code_payload_with_data_dir(hooks_dir, server_url, auth_token, Some(data_dir));
let serialized =
serde_json::to_string_pretty(&payload).context("serializing claude code hook config")?;
println!("# Claude Code hook config — merge into ~/.claude/settings.json");
@@ -2478,6 +2532,7 @@ model = "gpt-5"
hooks_tmp.path(),
"http://127.0.0.1:49374",
None,
+ config_tmp.path(),
&config_path,
)
.unwrap();
@@ -2524,6 +2579,7 @@ model = "gpt-5"
hooks_tmp.path(),
"http://127.0.0.1:49374",
None,
+ config_tmp.path(),
&config_path,
)
.unwrap();
@@ -2537,6 +2593,7 @@ model = "gpt-5"
hooks_tmp.path(),
"http://127.0.0.1:49374",
None,
+ config_tmp.path(),
&config_path,
)
.unwrap();
@@ -2571,6 +2628,7 @@ model = "gpt-5"
hooks_tmp.path(),
"http://127.0.0.1:49374",
None,
+ config_tmp.path(),
&config_path,
)
.unwrap();
@@ -2615,6 +2673,7 @@ model = "gpt-5"
hooks_tmp.path(),
"http://127.0.0.1:49374",
None,
+ config_tmp.path(),
&config_path,
)
.unwrap();
@@ -2658,6 +2717,7 @@ model = "gpt-5"
hooks_tmp.path(),
"http://127.0.0.1:49374",
None,
+ config_tmp.path(),
&config_path,
)
.unwrap();
@@ -2715,6 +2775,7 @@ model = "gpt-5"
hooks_tmp.path(),
"http://127.0.0.1:49374",
None,
+ config_tmp.path(),
&config_path,
)
.unwrap();
@@ -2765,6 +2826,7 @@ model = "gpt-5"
hooks_tmp.path(),
"http://127.0.0.1:49374",
None,
+ config_tmp.path(),
&config_path,
)
.unwrap();
@@ -2778,6 +2840,7 @@ model = "gpt-5"
hooks_tmp.path(),
"http://127.0.0.1:49374",
None,
+ config_tmp.path(),
&config_path,
)
.unwrap();
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 29274931..7adf3019 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -103,7 +103,31 @@ pub(crate) fn build_claude_code_payload(
server_url,
auth_token,
HookShape::Nested,
- HookCommandPlatform::for_bash_runner(),
+ HookCommandContext::new(
+ HookCommandPlatform::for_bash_script_runner(),
+ "claude-code",
+ None,
+ ),
+ )
+}
+
+pub(crate) fn build_claude_code_payload_with_data_dir(
+ emit_root: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: Option<&Path>,
+) -> serde_json::Value {
+ build_hook_payload_for_platform(
+ &CLAUDE_CODE_EVENTS,
+ emit_root,
+ server_url,
+ auth_token,
+ HookShape::Nested,
+ HookCommandContext::new(
+ HookCommandPlatform::for_bash_runner(),
+ "claude-code",
+ data_dir,
+ ),
)
}
@@ -223,17 +247,19 @@ pub(crate) const ANTIGRAVITY_LIFECYCLE_EVENTS: [(&str, &str); 2] =
/// list where matcher is ignored.
///
/// The output is `{ "ai-memory": { <events> } }`.
-#[must_use]
-pub(crate) fn build_antigravity_payload(
+pub(crate) fn build_antigravity_payload_with_data_dir(
emit_root: &Path,
server_url: &str,
auth_token: Option<&str>,
+ data_dir: Option<&Path>,
) -> serde_json::Value {
build_antigravity_payload_for_platform(
emit_root,
server_url,
auth_token,
HookCommandPlatform::current(),
+ "antigravity-cli",
+ data_dir,
)
}
@@ -242,6 +268,8 @@ fn build_antigravity_payload_for_platform(
server_url: &str,
auth_token: Option<&str>,
platform: HookCommandPlatform,
+ agent: &str,
+ data_dir: Option<&Path>,
) -> serde_json::Value {
let mut group = serde_json::Map::new();
@@ -249,7 +277,12 @@ 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(&abs, server_url, auth_token, platform);
+ let command = hook_command(
+ &abs,
+ server_url,
+ auth_token,
+ HookCommandContext::new(platform, agent, data_dir),
+ );
group.insert(
(*event).to_string(),
json!([{
@@ -266,7 +299,12 @@ 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(&abs, server_url, auth_token, platform);
+ let command = hook_command(
+ &abs,
+ server_url,
+ auth_token,
+ HookCommandContext::new(platform, agent, data_dir),
+ );
group.insert(
(*event).to_string(),
json!([{
@@ -279,25 +317,34 @@ fn build_antigravity_payload_for_platform(
json!({ "ai-memory": group })
}
-/// Build a Codex-flavoured hook payload. Thin alias for back-compat;
-/// new code should call `build_profile_payload(&CODEX_PROFILE, …)`.
-pub(crate) fn build_codex_payload(
+/// Build a hook payload for `profile`. The output is always
+/// `{ "hooks": { "<EventName>": <profile-specific-array> } }`; the
+/// caller is responsible for any sibling top-level keys (e.g.
+/// Cursor's `"version": 1`).
+#[cfg(test)]
+pub(crate) fn build_profile_payload(
+ profile: &HookProfile,
emit_root: &Path,
server_url: &str,
auth_token: Option<&str>,
) -> serde_json::Value {
- build_profile_payload(&CODEX_PROFILE, emit_root, server_url, auth_token)
+ build_profile_payload_for_agent(
+ profile,
+ emit_root,
+ server_url,
+ auth_token,
+ "claude-code",
+ None,
+ )
}
-/// Build a hook payload for `profile`. The output is always
-/// `{ "hooks": { "<EventName>": <profile-specific-array> } }`; the
-/// caller is responsible for any sibling top-level keys (e.g.
-/// Cursor's `"version": 1`).
-pub(crate) fn build_profile_payload(
+pub(crate) fn build_profile_payload_for_agent(
profile: &HookProfile,
emit_root: &Path,
server_url: &str,
auth_token: Option<&str>,
+ agent: &str,
+ data_dir: Option<&Path>,
) -> serde_json::Value {
build_hook_payload(
profile.events,
@@ -305,6 +352,7 @@ pub(crate) fn build_profile_payload(
server_url,
auth_token,
profile.shape,
+ HookCommandContext::new(HookCommandPlatform::current(), agent, data_dir),
)
}
@@ -314,15 +362,9 @@ fn build_hook_payload(
server_url: &str,
auth_token: Option<&str>,
shape: HookShape,
+ context: HookCommandContext<'_>,
) -> serde_json::Value {
- build_hook_payload_for_platform(
- events,
- emit_root,
- server_url,
- auth_token,
- shape,
- HookCommandPlatform::current(),
- )
+ build_hook_payload_for_platform(events, emit_root, server_url, auth_token, shape, context)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -350,6 +392,27 @@ pub(crate) enum HookCommandPlatform {
PosixNative,
}
+#[derive(Clone, Copy)]
+struct HookCommandContext<'a> {
+ platform: HookCommandPlatform,
+ agent: &'a str,
+ data_dir: Option<&'a Path>,
+}
+
+impl<'a> HookCommandContext<'a> {
+ const fn new(
+ platform: HookCommandPlatform,
+ agent: &'a str,
+ data_dir: Option<&'a Path>,
+ ) -> Self {
+ Self {
+ platform,
+ agent,
+ data_dir,
+ }
+ }
+}
+
impl HookCommandPlatform {
fn current() -> Self {
match std::env::var("AI_MEMORY_HOOK_PLATFORM") {
@@ -384,6 +447,23 @@ impl HookCommandPlatform {
_ => Self::PosixNative,
}
}
+
+ /// Script fallback for setup-agent / docker-host snippets. Respects an
+ /// explicit override, but defaults to the shell command because setup-agent
+ /// copies scripts, not a host-local native binary.
+ fn for_bash_script_runner() -> 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
+ }
+ Ok(v) if v.eq_ignore_ascii_case("windows-bash") => Self::WindowsBash,
+ Ok(v) if v.eq_ignore_ascii_case("windows-native") => Self::WindowsNative,
+ Ok(v) if v.eq_ignore_ascii_case("posix-native") => Self::PosixNative,
+ _ if cfg!(windows) => Self::WindowsBash,
+ _ => Self::Posix,
+ }
+ }
}
fn build_hook_payload_for_platform(
@@ -392,11 +472,11 @@ fn build_hook_payload_for_platform(
server_url: &str,
auth_token: Option<&str>,
shape: HookShape,
- platform: HookCommandPlatform,
+ context: HookCommandContext<'_>,
) -> serde_json::Value {
let mut hooks_block = serde_json::Map::new();
for (event, script) in events {
- let script = script_for_platform(script, platform);
+ let script = script_for_platform(script, context.platform);
let abs = emit_root.join(script.as_ref());
// Claude Code's hook schema (per
@@ -422,7 +502,7 @@ 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, platform);
+ let command = hook_command(&abs, server_url, auth_token, context);
// Empty matcher = fire on every event of this kind. Right
// for ai-memory's capture hooks (every prompt, every tool
@@ -471,9 +551,9 @@ fn hook_command(
script: &Path,
server_url: &str,
auth_token: Option<&str>,
- platform: HookCommandPlatform,
+ context: HookCommandContext<'_>,
) -> String {
- match platform {
+ match context.platform {
HookCommandPlatform::Posix => {
let mut prefix = format!("AI_MEMORY_HOOK_URL={} ", shell_quote(server_url));
if let Some(t) = auth_token {
@@ -523,9 +603,11 @@ fn hook_command(
.and_then(|s| s.to_str())
.unwrap_or_default();
let mut cmd = format!(
- "{} hook --event {event} --agent claude-code --server-url {}",
+ "{}{} hook --event {event} --agent {agent} --server-url {}",
win_double_quote(&exe),
+ native_data_dir_arg(context.data_dir, NativeQuote::Windows),
win_double_quote(server_url),
+ agent = context.agent,
);
if let Some(t) = auth_token {
cmd.push_str(&format!(" --auth-token {}", win_double_quote(t)));
@@ -545,9 +627,11 @@ fn hook_command(
.and_then(|s| s.to_str())
.unwrap_or_default();
let mut cmd = format!(
- "{} hook --event {event} --agent claude-code --server-url {}",
+ "{}{} hook --event {event} --agent {agent} --server-url {}",
shell_quote(&exe),
+ native_data_dir_arg(context.data_dir, NativeQuote::Posix),
shell_quote(server_url),
+ agent = context.agent,
);
if let Some(t) = auth_token {
cmd.push_str(&format!(" --auth-token {}", shell_quote(t)));
@@ -557,6 +641,23 @@ fn hook_command(
}
}
+#[derive(Clone, Copy)]
+enum NativeQuote {
+ Posix,
+ Windows,
+}
+
+fn native_data_dir_arg(data_dir: Option<&Path>, quote: NativeQuote) -> String {
+ let Some(data_dir) = data_dir else {
+ return String::new();
+ };
+ let path = data_dir.to_string_lossy();
+ match quote {
+ NativeQuote::Posix => format!(" --data-dir {}", shell_quote(&path)),
+ NativeQuote::Windows => format!(" --data-dir {}", win_double_quote(&path)),
+ }
+}
+
/// Convert a Windows path to Git Bash (MSYS2) format.
/// `C:\Users\alice\hooks\x.sh` → `/c/Users/alice/hooks/x.sh`
fn to_git_bash_path(path: &str) -> String {
@@ -620,7 +721,7 @@ mod tests {
server_url,
auth_token,
shape,
- HookCommandPlatform::Posix,
+ HookCommandContext::new(HookCommandPlatform::Posix, "claude-code", None),
)
}
@@ -848,7 +949,7 @@ mod tests {
"http://h:49374",
Some("tok"),
HookShape::Nested,
- HookCommandPlatform::WindowsNative,
+ HookCommandContext::new(HookCommandPlatform::WindowsNative, "claude-code", None),
);
// Each native command must carry `hook --event <stem>` where <stem>
// matches the .sh script the other platforms invoke — so the server
@@ -905,7 +1006,7 @@ mod tests {
&PathBuf::from("/tmp/hooks dir/session-start.sh"),
"http://localhost:49374/mcp?x=1&y=2",
Some("tok;rm -rf /"),
- HookCommandPlatform::Posix,
+ HookCommandContext::new(HookCommandPlatform::Posix, "claude-code", None),
);
assert!(
@@ -931,7 +1032,7 @@ mod tests {
"http://localhost:49374",
Some("tok'en"),
HookShape::Nested,
- HookCommandPlatform::Windows,
+ HookCommandContext::new(HookCommandPlatform::Windows, "claude-code", None),
);
let cmd = v
.pointer("/hooks/SessionStart/0/hooks/0/command")
@@ -958,6 +1059,8 @@ mod tests {
"http://localhost:49374",
Some("tok"),
HookCommandPlatform::Posix,
+ "antigravity-cli",
+ None,
);
// Top-level key is the named group "ai-memory", not "hooks"
@@ -1060,7 +1163,7 @@ mod tests {
),
"https://my-server.example.com",
Some("tok123"),
- HookCommandPlatform::WindowsBash,
+ HookCommandContext::new(HookCommandPlatform::WindowsBash, "claude-code", None),
);
assert!(
cmd.starts_with("bash -c "),
@@ -1090,7 +1193,7 @@ mod tests {
&PathBuf::from(r"C:\Users\alice\hooks\session-start.sh"),
"http://localhost:49374",
None,
- HookCommandPlatform::WindowsBash,
+ HookCommandContext::new(HookCommandPlatform::WindowsBash, "claude-code", None),
);
assert!(cmd.starts_with("bash -c "));
assert!(
@@ -1111,7 +1214,7 @@ mod tests {
&PathBuf::from("/home/alice/.local/share/ai-memory/hooks/claude-code/session-start.sh"),
"https://my-server.example.com",
Some("tok123"),
- HookCommandPlatform::PosixNative,
+ HookCommandContext::new(HookCommandPlatform::PosixNative, "claude-code", None),
);
assert!(
cmd.contains("hook --event session-start"),
@@ -1136,9 +1239,18 @@ mod tests {
&PathBuf::from("/home/alice/hooks/pre-tool-use.sh"),
"http://localhost:49374",
None,
- HookCommandPlatform::PosixNative,
+ HookCommandContext::new(
+ HookCommandPlatform::PosixNative,
+ "codex",
+ Some(Path::new("/home/alice/.local/share/custom memory")),
+ ),
);
assert!(cmd.contains("hook --event pre-tool-use"), "{cmd}");
+ assert!(cmd.contains("--agent codex"), "{cmd}");
+ assert!(
+ cmd.contains("--data-dir '/home/alice/.local/share/custom memory'"),
+ "{cmd}"
+ );
assert!(!cmd.contains("--auth-token"), "no token expected: {cmd}");
}
@@ -1151,7 +1263,7 @@ mod tests {
"https://my-server.example.com",
Some("tok123"),
HookShape::Nested,
- HookCommandPlatform::WindowsBash,
+ HookCommandContext::new(HookCommandPlatform::WindowsBash, "claude-code", None),
);
let cmd = v
.pointer("/hooks/SessionStart/0/hooks/0/command")
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index e066cbc8..d67b7fed 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -403,13 +403,20 @@ fn strip_instructions_block(content: &str) -> (String, bool) {
(format!("{head}{tail}"), true)
}
-/// True when a hook command string was written by ai-memory. Install
-/// inlines `AI_MEMORY_HOOK_URL=<url> [AI_MEMORY_AUTH_TOKEN=…] <path>`
-/// into the command (render_shared.rs); the `AI_MEMORY_HOOK_URL=`
-/// prefix is unconditional, so it is the reliable signature —
-/// independent of auth, --server-url, --hooks-dir, --host-prefix.
+/// True when a hook command string was written by ai-memory. Legacy script
+/// commands carry the unconditional `AI_MEMORY_HOOK_URL=` env prefix; native
+/// commands invoke the `ai-memory hook --event ... --server-url ...` subcommand.
+/// Keep both signatures narrow so uninstall does not remove unrelated hooks that
+/// happen to use the same event names or script basenames.
fn hook_command_is_ours(command: &str) -> bool {
- command.contains("AI_MEMORY_HOOK_URL=")
+ if command.contains("AI_MEMORY_HOOK_URL=") {
+ return true;
+ }
+ let lower = command.to_ascii_lowercase();
+ lower.contains("ai-memory")
+ && lower.contains(" hook --event ")
+ && lower.contains(" --agent ")
+ && lower.contains(" --server-url ")
}
/// Result of stripping ai-memory entries from a hooks JSON file.
@@ -759,11 +766,26 @@ mod tests {
assert!(hook_command_is_ours(cmd));
}
+ #[test]
+ fn hook_signature_matches_native_posix_command() {
+ let cmd = "'/home/alice/.cargo/bin/ai-memory' --data-dir '/tmp/custom data' hook --event session-start --agent claude-code --server-url http://h:49374";
+ assert!(hook_command_is_ours(cmd));
+ }
+
+ #[test]
+ fn hook_signature_matches_native_windows_command() {
+ let cmd = r#""C:\Users\alice\bin\ai-memory.exe" --data-dir "C:\Users\alice\AppData\Local\ai-memory" hook --event session-start --agent claude-code --server-url "http://h:49374""#;
+ assert!(hook_command_is_ours(cmd));
+ }
+
#[test]
fn hook_signature_rejects_third_party_with_generic_name() {
// A user's own hook that happens to be named stop.sh — no prefix.
assert!(!hook_command_is_ours("/usr/local/bin/my-stop.sh"));
assert!(!hook_command_is_ours("/opt/tools/hooks/session-start.sh"));
+ assert!(!hook_command_is_ours(
+ "/usr/local/bin/something hook --event stop --agent claude-code --server-url http://h"
+ ));
}
#[test]
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index a3a8b6bc..b7234ae6 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -26,7 +26,11 @@ use config::Config;
#[tokio::main]
async fn main() -> Result<()> {
- let cli = Cli::parse();
+ let Cli {
+ data_dir,
+ config: config_path,
+ command,
+ } = 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
@@ -34,17 +38,12 @@ async fn main() -> Result<()> {
// its server URL + token from flags; it only needs the data-dir to locate
// a stored OIDC token when no explicit `--auth-token` is given, so we pass
// the bare path rather than loading the full config.
- if matches!(cli.command, Command::Hook(_)) {
- let data_dir = cli.data_dir.clone();
- let Command::Hook(args) = cli.command else {
- unreachable!()
- };
- return commands::hook::run(data_dir, args).await;
- }
-
- let config_path = cli.config.clone();
+ let command = match command {
+ Command::Hook(args) => return commands::hook::run(data_dir, args).await,
+ other => other,
+ };
- let config = Arc::new(Config::load(cli.config.as_deref(), cli.data_dir.clone())?);
+ let config = Arc::new(Config::load(config_path.as_deref(), data_dir)?);
let _logging_guard = logging::init(&config)?;
info!(
@@ -54,7 +53,7 @@ async fn main() -> Result<()> {
"ai-memory starting",
);
- match cli.command {
+ match command {
Command::Init(args) => commands::init::run(&config, args, config_path.as_deref()),
Command::Status(args) => commands::status::run(&config, args).await,
Command::Search(args) => commands::search::run(&config, args).await,
@@ -68,7 +67,7 @@ async fn main() -> Result<()> {
Command::Reindex(args) => commands::reindex::run(&config, args).await,
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::Hook(args) => commands::hook::run(Some(config.data_dir.clone()), args).await,
Command::InstallMcp(args) => commands::install_mcp::run(&config, args),
Command::Commit(args) => commands::commit::run(&config, args).await,
Command::Checkpoints(args) => commands::checkpoints::run(&config, args).await,
diff --git a/docs/install.md b/docs/install.md
index 136da7a3..ddd2ab7f 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -282,8 +282,17 @@ sudo -u ai-memory ai-memory \
auth login openai-oauth
```
-Use `auth login copilot` the same way for GitHub Copilot. Restart the service
-after changing provider settings:
+Use `auth login copilot` the same way for GitHub Copilot. For per-developer
+native hook auth against an OIDC issuer, run `auth login oidc-device` in the
+developer's selected data dir instead:
+
+```bash
+ai-memory auth login oidc-device \
+ --issuer "https://issuer.example.com/realms/team" \
+ --client-id "ai-memory-cli"
+```
+
+Restart the service after changing provider settings:
```bash
systemctl --user restart ai-memory.service # user mode
@@ -868,6 +877,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree
| `generate-auth-token` | `docker run --rm` | Print a random hex bearer token |
| `auth login openai-oauth` | same data volume as the server | Store a ChatGPT/Codex OAuth refresh token for the optional `openai-oauth` LLM provider |
| `auth login copilot` | same data volume as the server | Store a GitHub token for the optional `copilot` LLM provider |
+| `auth login oidc-device` | same developer data dir as native hooks | Store a per-developer OIDC device token for native hook authentication |
| `install-mcp --client` | `docker run --rm` | MCP-config snippet per client |
| `install-hooks --agent` | `docker run --rm` | Hook-config snippet for an existing hooks dir |
| `setup-agent --agent --to --host-prefix` | `docker run --rm -v` | Extract bundled scripts + print config (one-shot) |
diff --git a/docs/users.md b/docs/users.md
index 244293b6..3202e661 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -285,8 +285,7 @@ the bearer authenticates, attribution flows from the token's owner
- **Root token is single.** `[auth].bearer_token` is the admin token
for operational `/admin/*` endpoints. DB users created with
`user add` are normal users, not additional admins.
-- **No federation / OIDC / OAuth.** Per
- [`design-decisions.md`](design-decisions.md) §13, ai-memory v1
- stays self-contained. If you need SSO, terminate it at a
- reverse proxy and configure the proxy to inject
- `Authorization: Bearer <root-token>`.
+- **OIDC is hook authentication, not page authorization.** Native hooks can use
+ a per-developer OIDC device token, but ai-memory still has one shared wiki per
+ server and no per-page RBAC. If you need data isolation, run separate
+ ai-memory servers or isolate at a reverse proxy.
diff --git a/docs/windows.md b/docs/windows.md
index 7e03a1b2..8956136d 100644
--- a/docs/windows.md
+++ b/docs/windows.md
@@ -216,9 +216,10 @@ native on an i7-6700HQ). Notes:
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 event
- spool + OIDC-token fallback. The **default for a native macOS / Linux
- install** (cargo / release binary), mirroring `windows-native`. The Docker
- wrapper forces `posix`, so its host-rendered config keeps the `.sh` scripts.
+ spool + OIDC-token fallback. The **default for native macOS / Linux
+ Claude Code installs** (cargo / release binary), mirroring
+ `windows-native`. The Docker wrapper forces `posix`, so its host-rendered
+ config keeps the `.sh` scripts.
Set the env var before running `install-hooks` so the chosen platform
is baked into the rendered hook commands.