Skip to content

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

Rust

install-hooks: support --apply --agent codex

AkitaOnRails97da580ab365
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index ba42cedd..d8d93ad2 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -13,7 +13,7 @@ use anyhow::{Context, Result, bail};
use crate::cli::{AgentChoice, InstallHooksArgs};
use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json};
-use crate::commands::render_shared::build_claude_code_payload;
+use crate::commands::render_shared::{build_claude_code_payload, build_codex_payload};
use crate::config::Config;
/// Run the `install-hooks` subcommand.
@@ -24,14 +24,18 @@ pub fn run(_config: &Config, args: InstallHooksArgs) -> Result<()> {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
let auth = args.auth_token.as_deref();
if args.apply {
- if !matches!(args.agent, AgentChoice::ClaudeCode) {
- bail!(
- "--apply currently only supports --agent claude-code. Codex / OpenCode \
- hook config formats are still evolving upstream; print the snippet \
- (drop --apply) and merge by hand."
- );
- }
- return apply_to_claude_code_settings(&hooks_dir, &args.server_url, auth, &args);
+ return match args.agent {
+ AgentChoice::ClaudeCode => {
+ apply_to_claude_code_settings(&hooks_dir, &args.server_url, auth, &args)
+ }
+ AgentChoice::Codex => {
+ apply_to_codex_settings(&hooks_dir, &args.server_url, auth, &args)
+ }
+ AgentChoice::OpenCode => bail!(
+ "--apply does not yet support --agent open-code (no stable upstream \
+ hook schema documented). Run without --apply to print the snippet."
+ ),
+ };
}
match args.agent {
AgentChoice::ClaudeCode => render_claude_code(&hooks_dir, &args.server_url, auth),
@@ -92,6 +96,94 @@ fn apply_to_claude_code_settings(
Ok(())
}
+/// Mutate `~/.codex/hooks.json` (creating it if absent) so Codex's
+/// lifecycle hook runner fires the ai-memory scripts on every
+/// session/prompt/tool event.
+///
+/// Codex's hook config is structurally identical to Claude Code's
+/// (verified against `openai/codex/codex-rs/config/src/hooks_tests.rs`):
+///
+/// { "hooks": {
+/// "SessionStart": [
+/// { "matcher": "",
+/// "hooks": [ {"type":"command", "command":"..."} ]
+/// }
+/// ], ...
+/// } }
+///
+/// Codex looks for hooks in `~/.codex/hooks.json` by default (or
+/// wherever `hooks = "./relative-path.json"` in config.toml points).
+/// We write the standalone file and don't touch config.toml — Codex
+/// picks it up automatically.
+///
+/// Trust note: Codex refuses to RUN new hooks until the user accepts
+/// them in the TUI ("Trust all and continue") or sets
+/// `--dangerously-bypass-hook-trust`. We print a reminder.
+fn apply_to_codex_settings(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let path = match &args.config_file {
+ Some(p) => p.clone(),
+ None => dirs::home_dir()
+ .context("could not locate $HOME for ~/.codex/hooks.json")?
+ .join(".codex")
+ .join("hooks.json"),
+ };
+ // 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(hooks_dir, server_url, auth_token);
+ let our_hooks = payload
+ .get("hooks")
+ .and_then(|v| v.as_object())
+ .context("internal: payload builder didn't return a hooks object")?
+ .clone();
+ let outcome = apply_atomic(&path, |existing| {
+ mutate_json(existing, |root| {
+ let hooks = root
+ .entry("hooks")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .context("`hooks` is present in hooks.json but not an object")?;
+ // Remove any stale `SessionEnd` entry left behind by an
+ // earlier version of install-hooks that mistakenly wrote
+ // the Claude-Code-only event into Codex's file. Codex
+ // ignores unknown events but the file looks cleaner
+ // without dead keys.
+ hooks.remove("SessionEnd");
+ for (event, value) in &our_hooks {
+ hooks.insert(event.clone(), value.clone());
+ }
+ Ok(())
+ })
+ })?;
+ println!(
+ "✓ {} {} ({})",
+ outcome.verb(),
+ path.display(),
+ match outcome {
+ ApplyOutcome::Created => "new file",
+ ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::NoOp => "already up to date",
+ }
+ );
+ // First-time trust reminder. Codex's TUI flags new/changed
+ // hooks on startup; users must explicitly trust them before
+ // they fire.
+ if !matches!(outcome, ApplyOutcome::NoOp) {
+ println!();
+ println!("Codex requires explicit trust for new hooks. Next time you start `codex`:");
+ println!(" → the TUI will surface 'Hooks need review' for each new event");
+ println!(" → choose 'Trust all and continue' (or trust individually)");
+ println!("To bypass the prompt for automated installs, start with");
+ println!("`codex --dangerously-bypass-hook-trust` (review hook scripts first).");
+ }
+ Ok(())
+}
+
fn render_agent(
label: &str,
hooks_dir: &Path,
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 9b75276a..ce33203b 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -73,9 +73,45 @@ pub(crate) fn build_claude_code_payload(
emit_root: &Path,
server_url: &str,
auth_token: Option<&str>,
+) -> serde_json::Value {
+ build_hook_payload(&CLAUDE_CODE_EVENTS, emit_root, server_url, auth_token)
+}
+
+/// Codex's hook-event vocabulary (per the openai/codex source —
+/// see `codex-rs/config/src/hooks_tests.rs`). Same shape as Claude
+/// Code's seven events, EXCEPT: Codex has no `SessionEnd` (it uses
+/// `Stop` for both turn-end and session-end signalling). The other
+/// six events line up 1:1.
+pub(crate) const CODEX_EVENTS: [(&str, &str); 6] = [
+ ("SessionStart", "session-start.sh"),
+ ("UserPromptSubmit", "user-prompt-submit.sh"),
+ ("PreToolUse", "pre-tool-use.sh"),
+ ("PostToolUse", "post-tool-use.sh"),
+ ("PreCompact", "pre-compact.sh"),
+ ("Stop", "stop.sh"),
+];
+
+/// Build a Codex-flavoured hook payload. Same JSON shape as Claude
+/// Code's (verified against `openai/codex/codex-rs/config/src/hooks_tests.rs`)
+/// minus `SessionEnd`, which Codex doesn't have.
+pub(crate) fn build_codex_payload(
+ emit_root: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+) -> serde_json::Value {
+ build_hook_payload(&CODEX_EVENTS, emit_root, server_url, auth_token)
+}
+
+/// Shared helper. Given a list of `(event_name, script_basename)`,
+/// emit `{ "hooks": { "EventName": [matcher+inner-hooks] } }`.
+fn build_hook_payload(
+ events: &[(&str, &str)],
+ emit_root: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
) -> serde_json::Value {
let mut hooks_block = serde_json::Map::new();
- for (event, script) in CLAUDE_CODE_EVENTS {
+ for (event, script) in events {
let abs = emit_root.join(script);
// Claude Code's hook schema (per
@@ -110,7 +146,7 @@ pub(crate) fn build_claude_code_payload(
// for ai-memory's capture hooks (every prompt, every tool
// call, every session boundary).
hooks_block.insert(
- event.into(),
+ (*event).to_string(),
json!([{
"matcher": "",
"hooks": [{
diff --git a/docs/logo.png b/docs/logo.png
index ff49c9ce..e4ff2908 100644
Binary files a/docs/logo.png and b/docs/logo.png differ