Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(hooks): Codex assistant-final-turn capture on Stop (#743)
AkitaOnRails5337c0254c5b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d23b4eb5..820950cd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Codex assistant-final-turn capture: `install-hooks --agent codex --capture-assistant`+ now captures the assistant's final message on `Stop`, the same double opt-in+ (client flag + server `capture_assistant = true`) and sanitize/bound pipeline+ as Claude Code. Codex's `Stop` payload carries `last_assistant_message`+ (verified on codex-cli 0.154.0); the installer previously refused the flag for+ Codex and now bakes it on a native hook platform. Only `(Codex, Stop)` is added+ — Codex has no `SubagentStop` (#743).- Cross-project agent messaging: a directed, claim-once inbox/queue so an agentin one project can hand a self-contained request to an agent in anotherproject without pulling that project's context into its own session. Four newdiff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 55072aa5..95b3f6bd 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -1537,11 +1537,14 @@ fn overlay_kiro_cli_event_hooks(/// ai-memory cares about (`CLAUDE_CODE_EVENTS`); preserve every other hook the/// user has wired up to other tools./// Whether `--capture-assistant` may take effect for this agent + platform-/// (#196): Claude Code on a native hook platform only. Any other agent or a-/// script-fallback platform cannot honor the opt-in, so the installer bails-/// instead of enabling it silently.+/// (#196, #743): Claude Code and Codex on a native hook platform. Both carry+/// `last_assistant_message` on their `Stop` payload (see+/// `ai_memory_hooks::assistant_capture`). Any other agent or a script-fallback+/// platform cannot honor the opt-in, so the installer bails instead of enabling+/// it silently.fn capture_assistant_allowed(agent: AgentChoice) -> bool {- matches!(agent, AgentChoice::ClaudeCode) && local_hook_policy_v1_supported()+ matches!(agent, AgentChoice::ClaudeCode | AgentChoice::Codex)+ && local_hook_policy_v1_supported()}fn prompt_capture_options_allowed(agent: AgentChoice) -> bool {@@ -1873,6 +1876,8 @@ fn apply_to_command_code_settings_with_staged("command-code",Some(data_dir),args.project_strategy.and_then(ProjectStrategyArg::baked),+ // Command Code is refused by `capture_assistant_allowed`; never bake it.+ false,);apply_to_command_code_settings_with_payload(payload, args)}@@ -1989,6 +1994,10 @@ fn apply_to_codex_settings_with_staged("codex",Some(data_dir),args.project_strategy.and_then(ProjectStrategyArg::baked),+ // Codex Stop carries last_assistant_message (#743); bake the opt-in when+ // asked. `capture_assistant_allowed` already gated it, so this only bakes+ // on a native path.+ args.capture_assistant,);apply_to_codex_settings_with_payload(payload, args)}@@ -2034,6 +2043,7 @@ fn merge_codex_hooks(data_dir: &Path,project_strategy: Option<&str>,config_path: &Path,+ capture_assistant: bool,) -> Result<ApplyOutcome> {// Build the Codex-flavoured payload. The JSON shape is identical// to Claude Code's matcher + nested hooks form — the event list@@ -2046,6 +2056,7 @@ fn merge_codex_hooks("codex",Some(data_dir),project_strategy,+ capture_assistant,);merge_codex_payload(payload, config_path)}@@ -2192,6 +2203,7 @@ fn merge_cursor_hooks("cursor",Some(data_dir),project_strategy,+ false,);let our_hooks = payload.get("hooks")@@ -2284,6 +2296,7 @@ fn merge_gemini_hooks("gemini-cli",Some(data_dir),project_strategy,+ false,);let our_hooks = payload.get("hooks")@@ -5877,12 +5890,11 @@ mod tests {use tempfile::TempDir;#[test]- fn capture_assistant_allowed_only_for_claude_native() {+ fn capture_assistant_allowed_only_for_claude_and_codex_native() {use crate::cli::AgentChoice::*;- // Every non-Claude agent is rejected regardless of platform (#196): the- // opt-in cannot take effect for them, so the installer must bail.+ // Every agent that cannot honor the opt-in is rejected regardless of+ // platform (#196): the installer must bail rather than enable it silently.for agent in [- Codex,CommandCode,Cursor,GeminiCli,@@ -5905,11 +5917,16 @@ mod tests {"{agent:?} must not allow --capture-assistant");}- // Claude Code tracks the native-platform gate exactly.+ // Claude Code and Codex (#743) both carry last_assistant_message on Stop+ // and track the native-platform gate exactly.assert_eq!(capture_assistant_allowed(ClaudeCode),local_hook_policy_v1_supported());+ assert_eq!(+ capture_assistant_allowed(Codex),+ local_hook_policy_v1_supported()+ );}#[test]@@ -9234,6 +9251,7 @@ model = "gpt-5"config_tmp.path(),None,&config_path,+ false,).unwrap();@@ -9252,6 +9270,65 @@ model = "gpt-5");}+ /// #743: with `--capture-assistant`, the Codex Stop command carries the+ /// `--capture-assistant` flag (and only Stop does); without it, no command+ /// does. Mirrors the native-command bake asserted for Claude Code.+ #[test]+ fn codex_bakes_capture_assistant_flag_on_stop_only_when_opted_in() {+ fn stop_and_start_commands(capture: bool) -> (String, String) {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(+ hooks_tmp.path(),+ &[+ "session-start.sh",+ "user-prompt-submit.sh",+ "pre-tool-use.sh",+ "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");+ merge_codex_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &config_path,+ capture,+ )+ .unwrap();+ let parsed: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ let cmd = |event: &str| {+ parsed["hooks"][event][0]["hooks"][0]["command"]+ .as_str()+ .unwrap_or_default()+ .to_string()+ };+ (cmd("Stop"), cmd("SessionStart"))+ }++ let (stop_on, start_on) = stop_and_start_commands(true);+ assert!(+ stop_on.contains("--capture-assistant"),+ "opted-in Codex Stop must bake --capture-assistant: {stop_on}"+ );+ assert!(+ !start_on.contains("--capture-assistant"),+ "only Stop carries the flag, not SessionStart: {start_on}"+ );++ let (stop_off, _) = stop_and_start_commands(false);+ assert!(+ !stop_off.contains("--capture-assistant"),+ "without the opt-in no command carries the flag: {stop_off}"+ );+ }+#[test]fn codex_session_end_preserves_third_party_and_adds_ours() {let hooks_tmp = TempDir::new().unwrap();@@ -9284,6 +9361,7 @@ model = "gpt-5"config_tmp.path(),None,&config_path,+ false,).unwrap();diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 24c63dbd..d6c6374f 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -949,9 +949,14 @@ pub(crate) fn build_profile_payload("claude-code",None,None,+ false,)}+// A hook-render builder that threads several independent render inputs (profile,+// paths, agent, scope strategy, capture opt-in); grouping them into a struct+// would not make the one call path clearer than the named parameters do.+#[allow(clippy::too_many_arguments)]pub(crate) fn build_profile_payload_for_agent(profile: &HookProfile,emit_root: &Path,@@ -960,6 +965,7 @@ pub(crate) fn build_profile_payload_for_agent(agent: &str,data_dir: Option<&Path>,project_strategy: Option<&str>,+ capture_assistant: bool,) -> serde_json::Value {build_hook_payload(profile.events,@@ -972,7 +978,8 @@ pub(crate) fn build_profile_payload_for_agent(agent,data_dir,project_strategy,- ),+ )+ .with_capture_assistant(capture_assistant),)}diff --git a/crates/ai-memory-hooks/src/assistant_capture.rs b/crates/ai-memory-hooks/src/assistant_capture.rsindex 25da028c..c6cf6ad4 100644--- a/crates/ai-memory-hooks/src/assistant_capture.rs+++ b/crates/ai-memory-hooks/src/assistant_capture.rs@@ -46,14 +46,21 @@ const ASSISTANT_MESSAGE_FIELDS: &[&str] = &["last_assistant_message"];/// The raw field that carries the assistant's final message for `(agent, event)`,/// or `None` when the pair has no verified assistant-message field.///-/// Closed table: only `ClaudeCode + Stop` is supported today. Extend-/// deliberately — a new entry opts an agent/event into capture and MUST have its-/// field name present in [`ASSISTANT_MESSAGE_FIELDS`] so the strip covers it-/// (enforced by `closed_table_fields_are_all_stripped`).+/// Closed table: `ClaudeCode + Stop` and `Codex + Stop` are supported today.+/// Extend deliberately — a new entry opts an agent/event into capture and MUST+/// have its field name present in [`ASSISTANT_MESSAGE_FIELDS`] so the strip+/// covers it (enforced by `closed_table_fields_are_all_stripped`).+///+/// Codex's `Stop` hook payload carries `last_assistant_message` (verified on+/// codex-cli 0.154.0, #743) — the same spelling Claude Code uses, so no new+/// entry in [`ASSISTANT_MESSAGE_FIELDS`] is needed. Codex has no `SubagentStop`+/// in its supported event vocabulary, so only `(Codex, Stop)` is added.#[must_use]pub fn assistant_message_field(agent: AgentKind, event: HookEvent) -> Option<&'static str> {match (agent, event) {- (AgentKind::ClaudeCode, HookEvent::Stop) => Some("last_assistant_message"),+ (AgentKind::ClaudeCode, HookEvent::Stop) | (AgentKind::Codex, HookEvent::Stop) => {+ Some("last_assistant_message")+ }_ => None,}}@@ -216,10 +223,10 @@ pub fn strip_assistant_message_raw(raw: &mut serde_json::Value) -> bool {mod tests {use super::*;- /// Only `ClaudeCode + Stop` is a capture candidate; every other agent/event- /// pair across the full agent surface must return `None`.+ /// Only `ClaudeCode + Stop` and `Codex + Stop` are capture candidates; every+ /// other agent/event pair across the full agent surface must return `None`.#[test]- fn only_claude_stop_is_a_capture_candidate() {+ fn only_claude_and_codex_stop_are_capture_candidates() {let events = [HookEvent::SessionStart,HookEvent::UserPrompt,@@ -236,7 +243,8 @@ mod tests {];for agent in AgentKind::ALL {for event in events {- let expected = agent == AgentKind::ClaudeCode && event == HookEvent::Stop;+ let expected = matches!(agent, AgentKind::ClaudeCode | AgentKind::Codex)+ && event == HookEvent::Stop;assert_eq!(assistant_message_field(agent, event).is_some(),expected,@@ -375,14 +383,26 @@ mod tests {#[test]fn client_transform_ignores_non_candidate_agent_event() {- // Non-Claude agent: raw field still stripped defensively, no protocol.+ // A non-candidate (agent, event): a candidate agent on a non-Stop event.+ // The raw field is still stripped defensively, and no protocol is spliced.let mut raw = serde_json::json!({ "last_assistant_message": "hi" });- let out = transform_for_client(&mut raw, AgentKind::Codex, HookEvent::Stop);+ let out = transform_for_client(&mut raw, AgentKind::Codex, HookEvent::PostToolUse);assert!(!out.captured);assert!(raw.get("last_assistant_message").is_none());assert!(raw.get(ASSISTANT_MARKER_KEY).is_none());}+ #[test]+ fn client_transform_captures_codex_stop() {+ // Codex Stop is now a candidate (#743): the assistant excerpt is captured+ // and the raw field removed, same as Claude Code.+ let mut raw = serde_json::json!({ "last_assistant_message": "codex done" });+ let out = transform_for_client(&mut raw, AgentKind::Codex, HookEvent::Stop);+ assert!(out.captured);+ assert!(raw.get("last_assistant_message").is_none());+ assert!(raw.get(ASSISTANT_MARKER_KEY).is_some());+ }+#[test]fn backstop_populates_body_when_all_gates_pass() {let mut raw = serde_json::json!({ "last_assistant_message": "done" });diff --git a/docs/install.md b/docs/install.mdindex b6d4fe75..8bf70726 100644--- a/docs/install.md+++ b/docs/install.md@@ -563,19 +563,21 @@ opt-in** — enable the server first, then the client:1. **Server:** set `capture_assistant = true` in the live`<data_dir>/config.toml` (or the service's configured TOML file), or set`AI_MEMORY_CAPTURE_ASSISTANT=true`, then restart `ai-memory serve`.-2. **Client:** re-install the Claude Code hooks with the flag:+2. **Client:** re-install the Claude Code (or Codex) hooks with the flag:```bashai-memory install-hooks --agent claude-code --capture-assistant --apply+ # Codex is supported too — its Stop payload carries last_assistant_message:+ ai-memory install-hooks --agent codex --capture-assistant --apply```The client sanitizes (built-in patterns) and truncates the excerpt before ittouches the spool or wire; the server re-scrubs with its `[sanitize]` patternsbefore storing. If either side is off — or the marker is malformed — the Stopstays empty. Re-running `install-hooks` without `--capture-assistant` removes-the flag (idempotent). `--capture-assistant` is Claude Code + native-platform-only; on any other agent or the script fallback the installer refuses it rather-than enabling something that cannot take effect. Assistant text is+the flag (idempotent). `--capture-assistant` is Claude Code and Codex on a+native hook platform only; on any other agent or the script fallback the+installer refuses it rather than enabling something that cannot take effect. Assistant text isprivacy-sensitive — read the `SECURITY.md` notes on what it can contain and whereit flows (consolidation/reviewer prompts, and out to a cloud LLM provider if oneis configured) before enabling it.diff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex 85d3e546..ee2f0245 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. `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. Assistant-final-turn capture (`--capture-assistant`) is Claude Code + native-platform only and is refused for Codex — see `install.md`. |+| 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. 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's `Stop` payload carries `last_assistant_message`, same as Claude Code. || 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. |