Skip to content

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

Rust

feat(install-hooks): wire Codex SessionEnd hook (Codex CLI 0.145.0)

holocastere37becbaf631
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa882713..fa626e4f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- `install-hooks --agent codex` now wires Codex's `SessionEnd` hook, so a
+ finished Codex session gets the same automatic end-of-session summary
+ and cross-agent handoff Claude Code already gets. Codex shipped a
+ first-class `SessionEnd` event in Codex CLI 0.145.0 (openai/codex#33895);
+ the `hooks/codex/session-end.{sh,ps1}` scripts already existed and only
+ needed adding to the Codex hook profile. On older Codex the event key is
+ inert; `ai-memory finalize-session --agent codex` remains the fallback.
+ `merge_codex_payload` no longer strips a `SessionEnd` key on every apply
+ — a third-party `SessionEnd` hook is preserved alongside ours. ([#604])
+
### Fixed
- `as_of` time-travel queries and the entity retrieval stream now work
on real stores. Both read the entity index, which was populated only
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 595199ca..986e02f8 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -1912,8 +1912,8 @@ fn merge_codex_hooks(
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).
+ // to Claude Code's matcher + nested hooks form — the event list
+ // differs only by the Claude-Code-only subagent events.
let payload = build_profile_payload_for_agent(
&super::render_shared::CODEX_PROFILE,
staged,
@@ -1939,12 +1939,6 @@ fn merge_codex_payload(payload: serde_json::Value, config_path: &Path) -> Result
.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 {
overlay_event_hooks(hooks, event, value);
}
@@ -5939,8 +5933,9 @@ command = "AI_MEMORY_HOOK_URL=http://h AI_MEMORY_PROJECT_STRATEGY=repo-root /x/a
&[CODEX_PROFILE.events],
);
assert!(codex.contains("stop"));
+ assert!(codex.contains("session-end"));
assert!(
- !codex.contains("session-end") && !codex.contains("subagent-start"),
+ !codex.contains("subagent-start") && !codex.contains("subagent-stop"),
"Codex manual output must omit scripts outside Codex's hook vocabulary: {codex}"
);
}
@@ -8071,6 +8066,7 @@ model = "gpt-5"
"post-tool-use.sh",
"pre-compact.sh",
"stop.sh",
+ "session-end.sh",
],
);
@@ -8099,13 +8095,13 @@ model = "gpt-5"
"SessionStart hook should be present"
);
assert!(
- parsed["hooks"].get("SessionEnd").is_none(),
- "Codex has no reliable true SessionEnd hook; install must omit it"
+ parsed["hooks"]["SessionEnd"].is_array(),
+ "SessionEnd is wired for Codex since Codex CLI 0.145.0"
);
}
#[test]
- fn codex_removes_stale_session_end_key() {
+ fn codex_session_end_preserves_third_party_and_adds_ours() {
let hooks_tmp = TempDir::new().unwrap();
stub_scripts(
hooks_tmp.path(),
@@ -8116,16 +8112,16 @@ model = "gpt-5"
"post-tool-use.sh",
"pre-compact.sh",
"stop.sh",
+ "session-end.sh",
],
);
let config_tmp = TempDir::new().unwrap();
let config_path = config_tmp.path().join("hooks.json");
- // Simulate a file with a stale SessionEnd entry from a previous
- // install that mistakenly included the Claude-Code-only event.
+ // A third-party SessionEnd hook the user wired up themselves.
fs::write(
&config_path,
- r#"{"hooks":{"SessionEnd":[{"matcher":"","hooks":[{"type":"command","command":"stale.sh"}]}]}}"#,
+ r#"{"hooks":{"SessionEnd":[{"matcher":"","hooks":[{"type":"command","command":"user-own.sh"}]}]}}"#,
)
.unwrap();
@@ -8141,13 +8137,19 @@ model = "gpt-5"
let parsed: serde_json::Value =
serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();
- // SessionEnd must be gone.
+ let session_end = parsed["hooks"]["SessionEnd"].as_array().unwrap();
+ let rendered = serde_json::to_string(&parsed["hooks"]["SessionEnd"]).unwrap();
+ // Third-party entry survives.
assert!(
- parsed["hooks"].get("SessionEnd").is_none(),
- "stale SessionEnd must be removed; got: {:?}",
- parsed["hooks"]
+ rendered.contains("user-own.sh"),
+ "third-party SessionEnd entry must survive: {rendered}"
);
- // Our hooks are present.
+ // Our managed entry was added alongside it.
+ assert!(
+ rendered.contains("session-end"),
+ "ai-memory SessionEnd entry must be added: {rendered}"
+ );
+ assert_eq!(session_end.len(), 2);
assert!(parsed["hooks"]["SessionStart"].is_array());
}
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 12110310..c7251fa3 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -754,16 +754,20 @@ pub(crate) struct HookProfile {
}
/// Codex's hook-event vocabulary (per the openai/codex source —
-/// see `codex-rs/config/src/hooks_tests.rs`). Same shape as Claude
-/// Code's six common events, EXCEPT: Codex has no `SessionEnd` (it
-/// uses `Stop` for both turn-end and session-end signalling).
-pub(crate) const CODEX_EVENTS: [(&str, &str); 6] = [
+/// see `codex-rs/config/src/hook_config.rs`). Same nested shape as
+/// Claude Code. `SessionEnd` shipped in Codex CLI 0.145.0 (openai/codex
+/// PR #33895, "Add SessionEnd hooks for thread teardown"); it is a
+/// root-session-only event that runs synchronously during thread
+/// teardown. Codex still has no `SubagentStart`/`SubagentStop` in a
+/// first-party-supported form here, so those stay Claude-Code-only.
+pub(crate) const CODEX_EVENTS: [(&str, &str); 7] = [
("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"),
+ ("SessionEnd", "session-end.sh"),
];
/// Command Code's stable shell-hook vocabulary. Mods expose more lifecycle
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index 30ce3174..f729d9d7 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -11,7 +11,7 @@
| Windows via WSL2 | Supported | Use the Linux install path inside WSL2 when the agent runs there. |
| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Local supported profiles default to host-native hook commands; Claude Code may use its Windows exec form, while other agents use native single command strings matching their hook schema. PowerShell/Git Bash scripts are compatibility fallbacks. See [`docs/windows.md`](docs/windows.md). |
| Claude Code | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. `install-mcp --session-aware` optionally enables per-session auto-scope isolation through a local stdio bridge. Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default). |
-| Codex | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. No automatic true session-end hook, so run `ai-memory finalize-session` when you need a final summary/handoff. |
+| Codex | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. `SessionEnd` is wired since Codex CLI 0.145.0 (openai/codex#33895), so finished sessions get an automatic end-of-session summary/handoff; on older Codex the event is inert and `ai-memory finalize-session --agent codex` is the fallback. |
| Command Code | Supported | MCP config (`~/.commandcode/mcp.json`) + its four stable lifecycle-hook events (`~/.commandcode/settings.json`); native commands enforce capture exclusions and `SessionStart` injects handoffs. `Stop` is only a turn boundary, so use `ai-memory finalize-session --agent command-code` after the final turn. `ai-memory run command-code` adds exact v3 native-session resume and visible-event import; experimental unsandboxed Mods remain excluded. |
| Devin CLI | Supported | MCP config + lifecycle hooks. Hooks use Devin's `PostCompaction` event, inject handoffs via `hookSpecificOutput.additionalContext`, and omit subagent events because Devin does not expose them. |
| OpenCode | Supported | Remote MCP config + generated TypeScript plugin; generated plugin enforces capture exclusions. |