Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): retain top-level Claude agent captures
NianJiuZst8e12dbd87c79
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c0229db6..ccb6a3fb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0provider. (#1026)### Fixed+- Fixed `drop_subagent_captures` discarding entire top-level Claude Code+ sessions launched with `--agent`. An `agent_type` alone no longer marks a+ session as a subagent; `agent_id` and Grok's `subagentType` still do, so+ actual subagent filtering remains enabled. (#1041)- Fixed interrupted launchers blocking an immediate managed-workstream restartby adding explicit `ai-memory run --force-unlock` recovery. The serveratomically expires and replaces only a lease attributed to the samediff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 02d6a9c6..d6509794 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -221,11 +221,12 @@ impl std::fmt::Debug for HookEnvelope {/// Keys by which agent harnesses tag a hook event as belonging to a SUBAGENT/// (a nested/spawned agent session) rather than the top-level session. Grok-/// sets `subagentType` (on its tool-use events); Claude Code sets `agent_type`-/// and `agent_id` (on its `SubagentStart`/`SubagentStop` and subagent tool-/// events). The set is a union so one check covers every harness that signals-/// subagent-ness; a harness that does not signal it simply never matches.-const SUBAGENT_MARKER_KEYS: &[&str] = &["subagentType", "agent_type", "agent_id"];+/// sets `subagentType` (on its tool-use events); Claude Code sets `agent_id`+/// on subagent events. `agent_type` alone is not a subagent marker: Claude+/// Code also sets it on top-level sessions launched with `--agent`. The set+/// is a union so one check covers every harness that signals subagent-ness;+/// a harness that does not signal it simply never matches.+const SUBAGENT_MARKER_KEYS: &[&str] = &["subagentType", "agent_id"];/// True when the raw hook payload carries a non-empty subagent marker — i.e./// the event originates from a spawned subagent session. The ingest router@@ -1368,15 +1369,35 @@ mod tests {assert!(body_is_subagent(&serde_json::json!({ "sessionId": "s", "subagentType": "general-purpose" })));- // Claude Code tags its subagent events with `agent_type` / `agent_id`.+ // Claude Code identifies spawned agents with `agent_id`.assert!(body_is_subagent(- &serde_json::json!({ "session_id": "s", "agent_type": "workflow-subagent" })+ &serde_json::json!({ "session_id": "s", "agent_type": "workflow-subagent", "agent_id": "agent-abc123" })));assert!(body_is_subagent(&serde_json::json!({ "agent_id": "agent-abc123" })));}+ #[test]+ fn body_is_subagent_keeps_top_level_claude_agent_sessions() {+ // `claude --agent <name>` also sets agent_type on the main session.+ let mut raw = serde_json::json!({+ "session_id": "main-session",+ "agent_type": "regulus:regulus",+ });+ assert!(!body_is_subagent(&raw), "agent_id absent");+ for agent_id in [+ serde_json::Value::Null,+ serde_json::json!(""),+ serde_json::json!(" "),+ serde_json::json!(42),+ serde_json::json!(false),+ ] {+ raw["agent_id"] = agent_id;+ assert!(!body_is_subagent(&raw), "{raw}");+ }+ }+#[test]fn body_is_subagent_false_for_top_level_and_empty_markers() {// A normal top-level event carries no marker.diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 659e761c..224371fe 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -228,7 +228,7 @@ struct SubagentSessionKey {/// Tracks the scoped session keys of subagent (nested/spawned) sessions so that/// the `drop_subagent_captures` gate can also drop the **unmarked tail** of those/// sessions (`user_prompt_submit` / `stop` / `session_end`), which the-/// per-event marker (`subagentType` / `agent_type`) does not cover. A session+/// per-event marker (`subagentType` / `agent_id`) does not cover. A session/// is seeded when a `SubagentStart` or any marker-bearing event arrives, and/// forgotten on `SessionEnd` after the tail has been dropped. Bounded LRU so a/// missed terminal event cannot leak memory.@@ -7085,6 +7085,121 @@ mod tests {);}+ #[tokio::test]+ async fn handle_hook_batch_keeps_top_level_claude_agent_sessions() {+ for null_agent_id in [false, true] {+ let tmp = TempDir::new().unwrap();+ let state = Arc::new(make_state(&tmp).await);+ let session = SessionId::new();+ let child_session = SessionId::new();+ let mut items = Vec::new();+ for event in [+ "session-start",+ "user-prompt-submit",+ "pre-tool-use",+ "post-tool-use",+ "stop",+ "session-end",+ ] {+ let mut body = serde_json::json!({+ "session_id": session.to_string(),+ "prompt": "Review the patch for the main agent",+ "tool_name": "Bash",+ "tool_response": "Review complete",+ });+ // Keep the terminal tail unmarked to catch accidental seeding+ // of the whole main session in subagent_sessions.+ if !matches!(event, "stop" | "session-end") {+ body["agent_type"] = serde_json::json!("regulus:regulus");+ if null_agent_id {+ body["agent_id"] = serde_json::Value::Null;+ }+ }+ items.push(HookBatchItem {+ url: format!("http://h/hook?event={event}&agent=claude-code&drop_subagent=1"),+ body,+ });+ }+ // OpenCode child sessions carry a parent ID as the subagent marker;+ // both the marked event and its unmarked tail must still drop.+ for body in [+ serde_json::json!({+ "session_id": child_session.to_string(),+ "agent_type": "reviewer",+ "agent_id": session.to_string(),+ "tool_name": "Bash",+ }),+ serde_json::json!({+ "session_id": child_session.to_string(),+ "tool_name": "Bash",+ }),+ ] {+ items.push(HookBatchItem {+ url: "http://h/hook?event=pre-tool-use&agent=opencode&drop_subagent=1".into(),+ body,+ });+ }+ let response = handle_hook_batch(+ State(state.clone()),+ None,+ None,+ None,+ HeaderMap::new(),+ Json(items),+ )+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(ack["accepted"], 8, "stored and dropped events are acked");++ let metrics = state.ingest_metrics.snapshot();+ assert_eq!(+ metrics.accepted, 6,+ "main session, null id: {null_agent_id}"+ );+ assert_eq!(metrics.dropped_by_policy, 2, "only the subagent is dropped");+ assert_eq!(+ state+ .reader+ .observations_for_session(session)+ .await+ .unwrap()+ .len(),+ 6,+ );+ assert!(+ state+ .reader+ .observations_for_session(child_session)+ .await+ .unwrap()+ .is_empty()+ );+ let pages = session_pages(&state).await;+ assert_eq!(pages.len(), 1, "the main session gets its durable summary");+ assert!(+ state+ .wiki+ .read_page(+ state.workspace_id,+ state.project_id,+ &ai_memory_core::PagePath::new(pages[0].clone()).unwrap(),+ )+ .unwrap()+ .body+ .contains("Review the patch for the main agent")+ );+ assert!(+ open_handoff_exists(&state).await,+ "the main session keeps its baton"+ );+ }+ }+#[tokio::test]async fn handle_hook_batch_keeps_subagent_events_when_disabled() {let tmp = TempDir::new().unwrap();diff --git a/docs/marker-file.md b/docs/marker-file.mdindex b07ee26d..154806d0 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -167,9 +167,12 @@ for instructions the agent is expected to obey every turn.`drop_subagent_captures` accepts a truthy string (`"true"` / `"1"` /`"yes"` / `"on"`); any other value, or its absence, leaves this project'ssubagent captures stored as usual. Top-level (non-subagent) sessions are-always stored regardless. This is per-project on purpose: there is no-server-global switch, so opting one noisy project in never sheds subagent-captures for the others on a shared instance.+always stored regardless, including Claude Code sessions launched with+`--agent`: `agent_type` alone describes the selected agent, while a non-empty+`agent_id` identifies a subagent. Grok's `subagentType` marker still identifies+subagent captures. This is per-project on purpose: there is no server-global+switch, so opting one noisy project in never sheds subagent captures for the+others on a shared instance.## Allowlist mode: the marker as an opt-in