Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
test(hooks): do not accept Grok handoffs the model cannot see
Giovanni Coutinho1e5d6a6bbfb9
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex d241446b..b6f09e0b 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -765,12 +765,12 @@ where}}- // user-prompt: agents whose SessionStart stdout is discarded (Kimi Code)- // receive the handoff here instead — kimi injects UserPromptSubmit stdout- // into the turn verbatim as a `hook_result` user message. The payload- // carries the native session id when available, so the destructive GET- // can also link the managed run to the native session, same as- // session-start does.+ // user-prompt: agents whose SessionStart stdout is discarded AND whose+ // UserPromptSubmit stdout is injected (Kimi Code) receive the handoff+ // here. Grok discards both, so it must not take this path: the GET+ // accepts the handoff. The payload carries the native session id when+ // available, so the destructive GET can also link the managed run to the+ // native session, same as session-start does.// The installed kimi hook passes the script stem (`user-prompt-submit`)// while the legacy shell path posts `user-prompt`; HookEvent::parse// canonicalizes both (and the snake/native spellings) to UserPrompt.@@ -2427,6 +2427,19 @@ mod tests {}}+ fn grok_hook_args(event: &str, server_url: &str) -> HookArgs {+ HookArgs {+ event: event.into(),+ agent: "grok".into(),+ server_url: server_url.into(),+ auth_token: None,+ project_strategy: None,+ check_capture: false,+ capture_assistant: false,+ capture_mode: None,+ }+ }+fn kimi_hook_args(event: &str, server_url: &str) -> HookArgs {HookArgs {event: event.into(),@@ -2905,6 +2918,91 @@ mod tests {assert!(!data_dir.join("briefed").exists());}+ #[tokio::test]+ async fn grok_session_start_never_fetches_the_handoff() {+ let tmp = tempfile::tempdir().unwrap();+ let (base, mut requests) = serve_requests("200 OK", "AMWS-HANDOFF-DELTA").await;+ let mut stdout = Vec::new();+ run_with_payload(+ Some(tmp.path().to_path_buf()),+ grok_hook_args("session-start", &base),+ serde_json::json!({"session_id": "grok-session", "cwd": tmp.path()}).to_string(),+ &mut stdout,+ |_, _| Ok(()),+ )+ .await+ .unwrap();++ assert_eq!(stdout, b"{}\n");+ while let Some(request) = first_request(&mut requests).await {+ assert!(!request.starts_with("GET /handoff"), "{request}");+ }+ }++ #[tokio::test]+ async fn grok_user_prompt_does_not_fetch_the_handoff() {+ let tmp = tempfile::tempdir().unwrap();+ let (base, mut requests) = serve_requests("200 OK", "AMWS-HANDOFF-DELTA").await;+ let mut stdout = Vec::new();+ run_with_payload(+ Some(tmp.path().to_path_buf()),+ grok_hook_args("user-prompt", &base),+ serde_json::json!({+ "session_id": "grok-session",+ "cwd": tmp.path(),+ "prompt": "hello"+ })+ .to_string(),+ &mut stdout,+ |_, _| Ok(()),+ )+ .await+ .unwrap();++ // Grok discards allowing UserPromptSubmit stdout. Fetching would+ // accept the handoff and then throw the body away.+ assert_eq!(stdout, b"{}\n");+ while let Some(request) = first_request(&mut requests).await {+ assert!(+ !request.starts_with("GET /handoff"),+ "grok user-prompt must not accept the handoff: {request}"+ );+ }+ }++ #[tokio::test]+ async fn grok_user_prompt_submit_stem_does_not_fetch_the_handoff() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let cwd = tmp.path().join("repo");+ std::fs::create_dir(&cwd).unwrap();+ write_briefing_marker(&cwd);+ let (base, mut requests) = serve_requests("200 OK", "AMWS-HANDOFF-DELTA").await;+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir),+ grok_hook_args("user-prompt-submit", &base),+ serde_json::json!({+ "session_id": "grok-session",+ "cwd": cwd,+ "prompt": "hi"+ })+ .to_string(),+ &mut stdout,+ |_, _| Ok(()),+ )+ .await+ .unwrap();++ assert_eq!(stdout, b"{}\n");+ while let Some(request) = first_request(&mut requests).await {+ assert!(+ !request.starts_with("GET /handoff"),+ "briefing opt-in must not make grok fetch /handoff: {request}"+ );+ }+ }+#[test]fn briefed_markers_are_bounded_and_keep_current() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex d779627f..662da827 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -414,6 +414,13 @@ impl AgentKind {/// `session/hooks/user-prompt.ts`, verified in the v0.28.1 source)./// Empty stdout injects nothing, so the hook prints the raw handoff body/// or nothing at all — never a JSON envelope.+ ///+ /// Grok Build also ignores `SessionStart` stdout, but it is not in this+ /// set. Its hook guide discards stdout of an allowing `UserPromptSubmit`+ /// and that event has no `additionalContext`. `GET /handoff` marks the+ /// handoff accepted, so fetching there would burn the baton and+ /// `memory_handoff_accept` could not recover it. Leave Grok out until a+ /// hook event Grok actually injects exists.#[must_use]pub fn user_prompt_injects_handoff(self) -> bool {matches!(self, Self::KimiCode)@@ -457,9 +464,10 @@ mod tests {);// Unknown tags still degrade to Other.assert_eq!(AgentKind::from_wire("grok-2"), AgentKind::Other);- // Grok cannot inject the session-start handoff (ignores hook stdout);- // every other agent can.+ // Grok cannot inject the session-start handoff (ignores hook stdout),+ // and must not fetch on UserPromptSubmit either (that stdout is discarded).assert!(!AgentKind::Grok.session_start_injects_handoff());+ assert!(!AgentKind::Grok.user_prompt_injects_handoff());assert!(!AgentKind::Zero.session_start_injects_handoff());assert!(AgentKind::ClaudeCode.session_start_injects_handoff());assert!(AgentKind::Codex.session_start_injects_handoff());diff --git a/hooks/grok/session-start.sh b/hooks/grok/session-start.shindex f2c76b39..2dcb439b 100755--- a/hooks/grok/session-start.sh+++ b/hooks/grok/session-start.sh@@ -2,7 +2,8 @@# Grok Build CLI SessionStart hook.# Grok ignores SessionStart stdout, so this hook captures the event only.# Do NOT fetch /handoff here: accepting a handoff is destructive and Grok-# would discard the returned context.+# would discard the returned context. UserPromptSubmit cannot deliver it+# either (allowing-hook stdout is discarded)._lib_dir="$(dirname "$0")"[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/..". "$_lib_dir/_lib.sh"diff --git a/hooks/grok/user-prompt-submit.ps1 b/hooks/grok/user-prompt-submit.ps1index a05c1bc7..2ef54564 100755--- a/hooks/grok/user-prompt-submit.ps1+++ b/hooks/grok/user-prompt-submit.ps1@@ -1,3 +1,5 @@+# Do not fetch /handoff. Grok discards allowing UserPromptSubmit stdout,+# and GET /handoff would accept the handoff anyway.. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"Invoke-AiMemoryHook -Event "user-prompt" -Agent "grok"exit 0diff --git a/hooks/grok/user-prompt-submit.sh b/hooks/grok/user-prompt-submit.shindex 56cfc07a..4312e349 100755--- a/hooks/grok/user-prompt-submit.sh+++ b/hooks/grok/user-prompt-submit.sh@@ -1,5 +1,9 @@#!/bin/sh# Grok Build CLI user-prompt hook.+# Do NOT fetch /handoff. Grok discards stdout of an allowing+# UserPromptSubmit (no additionalContext), and GET /handoff marks the+# handoff accepted. SessionStart must not fetch either. Recover with+# MCP memory_handoff_list then memory_handoff_accept._lib_dir="$(dirname "$0")"[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/..". "$_lib_dir/_lib.sh"