Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): do not let a Grok child session take the handoff
Giovanni Coutinho53e732d22e92
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex c0f07359..53cd0e4c 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -470,6 +470,22 @@ fn grok_post_tool_handoff_envelope(handoff: &str) -> serde_json::Value {})}+fn payload_is_subagent(raw: &serde_json::Value) -> bool {+ [+ "subagentType",+ "subagent_type",+ "agent_type",+ "agent_id",+ "parentSessionId",+ ]+ .iter()+ .any(|key| {+ raw.get(*key)+ .and_then(|value| value.as_str())+ .is_some_and(|text| !text.trim().is_empty())+ })+}+fn clip_chars(text: &str, max_chars: usize) -> String {if text.chars().count() <= max_chars {return text.to_string();@@ -887,7 +903,7 @@ wherecanonical_session_id.as_deref(),policy_cwd.as_deref(),);- if !shown.is_file() {+ if !shown.is_file() && !payload_is_subagent(&json) {let client = build_client();let bearer = hook_spool::resolve_bearer(&client, &dd, effective_token).await;let native_session_qs = canonical_session_id@@ -901,8 +917,11 @@ where);let handoff =get_handoff(&client, &handoff_url, bearer.as_deref(), handoff_timeout()).await;- mark_briefed(&shown);+ // Only a real body consumes this session's one chance. An empty+ // or failed claim must retry on the next parent tool; a child+ // session that errors must not burn the baton for the parent.if let Some(handoff) = handoff {+ mark_briefed(&shown);let envelope = grok_post_tool_handoff_envelope(&handoff);writeln!(stdout, "{envelope}")?;return Ok(());@@ -3166,6 +3185,35 @@ mod tests {);}+ #[tokio::test]+ async fn grok_post_tool_skips_a_subagent_payload() {+ 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().join("data")),+ grok_hook_args("post-tool-use", &base),+ serde_json::json!({+ "session_id": "child-session",+ "cwd": tmp.path(),+ "subagentType": "goal-plan-writer",+ "tool_name": "read_file"+ })+ .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"),+ "a child session must not accept the parent handoff: {request}"+ );+ }+ }+#[tokio::test]async fn grok_post_tool_without_handoff_prints_empty_object() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 67c23aed..b092a542 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -2932,11 +2932,6 @@ pub(crate) fn accept_handoff_in_transaction("handoff receiver session does not match the accepting scope and agent".into(),));}- if !open {- return Err(StoreError::InvalidState(- "an ended session cannot accept a handoff".into(),- ));- }let already_claimed: bool = tx.query_row("SELECT EXISTS( \SELECT 1 FROM handoffs \@@ -2951,6 +2946,15 @@ pub(crate) fn accept_handoff_in_transaction(// the first accepted row.return Ok(false);}+ if !open {+ // Grok reuses the session id after SessionEnd when the same+ // conversation restarts. The row is the receiver, not a corpse,+ // as long as it has not already taken a baton.+ tx.execute(+ "UPDATE sessions SET ended_at = NULL WHERE id = ?1",+ params![accepting_session.as_bytes()],+ )?;+ }}let metadata = tx.query_row(diff --git a/hooks/grok/post-tool-use.sh b/hooks/grok/post-tool-use.shindex 788ec9e2..a57e5045 100755--- a/hooks/grok/post-tool-use.sh+++ b/hooks/grok/post-tool-use.sh@@ -29,10 +29,16 @@ if [ -f "$SHOWN" ]; thenexit 0fi+case "$PAYLOAD" in+ *'"subagentType"'*|*'\"subagentType\"'*|*'"parentSessionId"'*)+ printf '{}\n'+ exit 0+ ;;+esacBRIEF_QS=$(ai_memory_briefing_qs "$CWD")HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=grok${QS}${SESSION_QS}${BRIEF_QS}" 2>/dev/null || true)-ai_memory_mark_briefed "$SHOWN"if [ -n "$HANDOFF" ]; then+ ai_memory_mark_briefed "$SHOWN"CTX=$(printf '%s' "$HANDOFF" | ai_memory_json_string)printf '{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":%s}}\n' "$CTX"exit 0