Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): harden subagent capture drops
AkitaOnRailsc8b303857576
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex 4d4485a8..8b4fce5f 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -205,9 +205,10 @@ pub enum BatchOutcome {/// the server stopped on that item (fail-fast) — the caller deletes the/// prefix and charges the next item a retry.Accepted(usize),- /// `429` — ingest saturated; nothing was processed. Keep the whole batch and- /// retry it later WITHOUT bumping attempts (saturation isn't a failure).- Saturated,+ /// `429` — ingest saturated after committing this many leading items. The+ /// caller deletes that prefix and retries the rest later WITHOUT bumping+ /// attempts (saturation isn't a failure).+ Saturated(usize),/// `404`/`405` — the server has no `/hook/batch` (a pre-upgrade build). The/// caller falls back to per-event `POST /hook` for the rest of the drain.Unsupported,@@ -252,7 +253,13 @@ pub async fn post_batch(Err(_) => BatchOutcome::Failed,}} else if status == reqwest::StatusCode::TOO_MANY_REQUESTS {- BatchOutcome::Saturated+ let accepted = resp+ .json::<serde_json::Value>()+ .await+ .ok()+ .and_then(|v| v.get("accepted").and_then(serde_json::Value::as_u64))+ .unwrap_or(0) as usize;+ BatchOutcome::Saturated(accepted)} else if status == reqwest::StatusCode::NOT_FOUND|| status == reqwest::StatusCode::METHOD_NOT_ALLOWED{diff --git a/crates/ai-memory-cli/src/commands/hook_spool.rs b/crates/ai-memory-cli/src/commands/hook_spool.rsindex bd2ff63d..da786b97 100644--- a/crates/ai-memory-cli/src/commands/hook_spool.rs+++ b/crates/ai-memory-cli/src/commands/hook_spool.rs@@ -195,9 +195,10 @@ pub struct DrainResult {/// drain transparently falls back to per-event `POST /hook`.////// A delivered event is deleted; a failed one is charged a retry attempt-/// (dropped at `MAX_ATTEMPTS`); a `429` (saturation) is retried untouched so it-/// never burns the retry budget. OIDC bearer is resolved + refreshed at most-/// once per drain and cached.+/// (dropped at `MAX_ATTEMPTS`); a `429` (saturation) deletes any accepted prefix+/// the server reports, then retries the rest untouched so it never burns the+/// retry budget. OIDC bearer is resolved + refreshed at most once per drain and+/// cached.////// Best-effort: returns counts and never errors, so a session boundary is never/// blocked beyond the budget and never fails the agent.@@ -307,10 +308,18 @@ pub async fn drain(break;}}- BatchOutcome::Saturated => {- // Server ingest is full; further batches would 429 too. Leave- // everything queued, no attempt bump (parity with per-event).- result.remaining += chunk.len() + files.len().saturating_sub(idx);+ BatchOutcome::Saturated(k) => {+ // Server ingest filled after committing a leading prefix.+ // Delete only that prefix; leave the saturated item and all+ // later entries queued without bumping attempts (parity with+ // per-event 429 handling).+ let k = k.min(chunk.len());+ for (path, _) in &chunk[..k] {+ let _ = std::fs::remove_file(path);+ }+ result.sent += k;+ result.remaining +=+ chunk.len().saturating_sub(k) + files.len().saturating_sub(idx);break;}BatchOutcome::Unsupported => {@@ -808,6 +817,46 @@ mod tests {assert_eq!(loaded.attempts, 0, "429 must not consume the retry budget");}+ #[tokio::test]+ async fn partial_429_deletes_prefix_without_bumping_saturated_item() {+ let req_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let addr =+ serve_counting_hook_with_accept(req_count.clone(), "429 Too Many Requests", Some(1))+ .await;+ let tmp = tempfile::tempdir().unwrap();+ let spool = spool_dir(tmp.path());+ for i in 0..3 {+ write_spool_entry(+ &spool,+ &format!("evt-{i}.json"),+ format!("http://{addr}/hook?event=e{i}"),+ );+ }++ let r = drain(+ &spool,+ tmp.path(),+ Duration::from_secs(5),+ Duration::from_secs(2),+ )+ .await;++ assert_eq!(r.sent, 1);+ assert_eq!(r.dropped, 0);+ assert_eq!(r.remaining, 2);+ assert_eq!(req_count.load(std::sync::atomic::Ordering::SeqCst), 1);+ let mut files = list_entries(&spool).unwrap();+ files.sort();+ assert_eq!(files.len(), 2);+ assert!(files[0].ends_with("evt-1.json"));+ assert!(files[1].ends_with("evt-2.json"));+ assert_eq!(+ sorted_attempts(&spool),+ vec![0, 0],+ "saturation must not bump retry attempts for the first unaccepted item"+ );+ }+/// A mock hook server: answers `200 {"accepted":N}` to `POST /hook/batch`/// (N = array length in the body) and `202 queued` to a per-event/// `POST /hook`. Counts every request so a test can assert batching. Readsdiff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 063cec1b..9895a13f 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -25,7 +25,8 @@ use crate::commands::install_mcp;use crate::commands::openclaw_plugin;use crate::commands::path_util::home_dir;use crate::commands::render_shared::{- CURSOR_PROFILE, GEMINI_PROFILE, build_antigravity_payload_with_data_dir,+ ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, CURSOR_PROFILE,+ GEMINI_PROFILE, build_antigravity_payload_with_data_dir,build_claude_code_payload_with_data_dir, build_grok_payload_with_data_dir,build_profile_payload_for_agent, hook_script_for_claude_code, hook_script_for_current_platform,ts_string_literal,@@ -184,19 +185,47 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {}AgentChoice::Codex => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- render_agent("codex", &hooks_dir, &server_url, auth, strategy)+ render_agent(+ "codex",+ &hooks_dir,+ &server_url,+ auth,+ strategy,+ &[CODEX_PROFILE.events],+ )}AgentChoice::Cursor => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- render_agent("cursor", &hooks_dir, &server_url, auth, strategy)+ render_agent(+ "cursor",+ &hooks_dir,+ &server_url,+ auth,+ strategy,+ &[CURSOR_PROFILE.events],+ )}AgentChoice::GeminiCli => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- render_agent("gemini-cli", &hooks_dir, &server_url, auth, strategy)+ render_agent(+ "gemini-cli",+ &hooks_dir,+ &server_url,+ auth,+ strategy,+ &[GEMINI_PROFILE.events],+ )}AgentChoice::AntigravityCli => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- render_agent("antigravity-cli", &hooks_dir, &server_url, auth, strategy)+ render_agent(+ "antigravity-cli",+ &hooks_dir,+ &server_url,+ auth,+ strategy,+ &[&ANTIGRAVITY_TOOL_EVENTS, &ANTIGRAVITY_LIFECYCLE_EVENTS],+ )}AgentChoice::Grok => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;@@ -1029,9 +1058,11 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {const workspace = tomlKey(body, "workspace");const project = tomlKey(body, "project");const projectStrategy = tomlKey(body, "project_strategy");+ const dropSubagent = tomlKey(body, "drop_subagent_captures");if (workspace) url.searchParams.set("workspace", workspace);if (project) url.searchParams.set("project", project);if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);+ if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {const repoProject = repoRootProject(cwd);if (repoProject) url.searchParams.set("project", repoProject);@@ -1047,6 +1078,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {let workspace: string | undefined;let project: string | undefined;let projectStrategy: string | undefined;+ let dropSubagent: string | undefined;const marker = findMarker(cwd);if (marker) {try {@@ -1054,6 +1086,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {workspace = tomlKey(body, "workspace");project = tomlKey(body, "project");projectStrategy = tomlKey(body, "project_strategy");+ dropSubagent = tomlKey(body, "drop_subagent_captures");} catch (_e) {}}@@ -1065,6 +1098,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {if (workspace) url.searchParams.set("workspace", workspace);if (project) url.searchParams.set("project", project);if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);+ if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);}"#;format!("const DEFAULT_PROJECT_STRATEGY = {};\n{body}",@@ -1636,10 +1670,18 @@ fn render_agent(server_url: &str,auth_token: Option<&str>,project_strategy: Option<&str>,+ event_lists: &[&[(&str, &str)]],) -> Result<()> {print!("{}",- render_agent_output(label, hooks_dir, server_url, auth_token, project_strategy)?+ render_agent_output(+ label,+ hooks_dir,+ server_url,+ auth_token,+ project_strategy,+ event_lists,+ ));Ok(())}@@ -1650,7 +1692,8 @@ fn render_agent_output(server_url: &str,auth_token: Option<&str>,project_strategy: Option<&str>,-) -> Result<String> {+ event_lists: &[&[(&str, &str)]],+) -> String {let mut out = String::new();out.push_str(&format!("# {label} hook scripts (manual install — wire each to the matching event)\n"@@ -1666,11 +1709,13 @@ fn render_agent_output(out.push_str("# --auth-token here AND set AI_MEMORY_AUTH_TOKEN on the server.\n");}out.push('\n');- for entry in std::fs::read_dir(hooks_dir)? {- let entry = entry?;- let p = entry.path();- if p.is_file() && p.extension().is_some_and(|e| e == hook_script_extension()) {- out.push_str(&format!("- {}\n", p.display()));+ for events in event_lists {+ for (_, script) in *events {+ let script = hook_script_for_current_platform(script);+ out.push_str(&format!(+ "- {}\n",+ hooks_dir.join(script.as_ref()).display()+ ));}}out.push('\n');@@ -1679,7 +1724,7 @@ fn render_agent_output(out.push_str(&instruction);out.push('\n');}- Ok(out)+ out}fn manual_agent_project_strategy_instruction(project_strategy: Option<&str>) -> Option<String> {@@ -1878,14 +1923,6 @@ fn staged_command_dir(staged: &Path, agent_label: &str) -> PathBuf {}}-fn hook_script_extension() -> &'static str {- if hook_script_for_current_platform("x.sh").ends_with(".ps1") {- "ps1"- } else {- "sh"- }-}-fn is_hook_script_file(path: &Path) -> bool {matches!(path.extension().and_then(|s| s.to_str()),@@ -2269,8 +2306,8 @@ mod tests {"http://127.0.0.1:49374",None,Some("repo-root"),- )- .unwrap_or_else(|err| panic!("failed to render {agent}: {err}"));+ &[CODEX_PROFILE.events],+ );assert!(output.contains("AI_MEMORY_PROJECT_STRATEGY=repo-root"),"{agent} manual output must tell users to set the strategy env: {output}"@@ -2282,12 +2319,64 @@ mod tests {fn manual_agent_render_omits_project_strategy_by_default() {let temp = TempDir::new().unwrap();stub_scripts(temp.path(), &["session-start.sh"]);- let output =- render_agent_output("codex", temp.path(), "http://127.0.0.1:49374", None, None)- .unwrap();+ let output = render_agent_output(+ "codex",+ temp.path(),+ "http://127.0.0.1:49374",+ None,+ None,+ &[CODEX_PROFILE.events],+ );assert!(!output.contains("AI_MEMORY_PROJECT_STRATEGY"));}+ #[test]+ fn manual_agent_render_uses_agent_profile_not_physical_bundle_listing() {+ let temp = TempDir::new().unwrap();+ stub_scripts(+ temp.path(),+ &[+ "session-start.sh",+ "session-end.sh",+ "user-prompt-submit.sh",+ "stop.sh",+ "subagent-start.sh",+ "subagent-stop.sh",+ ],+ );++ let gemini = render_agent_output(+ "gemini-cli",+ temp.path(),+ "http://127.0.0.1:49374",+ None,+ None,+ &[GEMINI_PROFILE.events],+ );+ assert!(gemini.contains("session-start"));+ assert!(gemini.contains("session-end"));+ assert!(+ !gemini.contains("user-prompt-submit")+ && !gemini.contains("subagent-start")+ && !gemini.contains("subagent-stop"),+ "Gemini manual output must omit scripts outside Gemini's hook vocabulary: {gemini}"+ );++ let codex = render_agent_output(+ "codex",+ temp.path(),+ "http://127.0.0.1:49374",+ None,+ None,+ &[CODEX_PROFILE.events],+ );+ assert!(codex.contains("stop"));+ assert!(+ !codex.contains("session-end") && !codex.contains("subagent-start"),+ "Codex manual output must omit scripts outside Codex's hook vocabulary: {codex}"+ );+ }+#[test]fn hook_server_url_defaults_to_configured_server_url() {let config = Config {@@ -2499,6 +2588,7 @@ model = "gpt-5""codex","cursor","gemini-cli",+ "grok","opencode","antigravity-cli",] {@@ -2796,7 +2886,9 @@ model = "gpt-5"assert!(plugin.contains("readFileSync(marker, \"utf8\")"));assert!(plugin.contains("text.split(/\\r?\\n/)"));assert!(plugin.contains("tomlKey(body, \"project_strategy\")"));+ assert!(plugin.contains("tomlKey(body, \"drop_subagent_captures\")"));assert!(plugin.contains("url.searchParams.set(\"project_strategy\", projectStrategy)"));+ assert!(plugin.contains("url.searchParams.set(\"drop_subagent\", dropSubagent)"));assert!(plugin.contains("applyMarkerParams(url, typeof payload.cwd === \"string\" ? payload.cwd : undefined);"));@@ -2887,7 +2979,9 @@ model = "gpt-5"assert!(extension.contains("readFileSync(marker, \"utf8\")"));assert!(extension.contains("text.split(/\\r?\\n/)"));assert!(extension.contains("tomlKey(body, \"project_strategy\")"));+ assert!(extension.contains("tomlKey(body, \"drop_subagent_captures\")"));assert!(extension.contains("url.searchParams.set(\"project_strategy\", projectStrategy)"));+ assert!(extension.contains("url.searchParams.set(\"drop_subagent\", dropSubagent)"));assert!(extension.contains("applyMarkerParams(url, typeof payload.cwd === \"string\" ? payload.cwd : undefined);"));diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rsindex edfb65ee..4460d44a 100644--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs@@ -213,9 +213,11 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {const workspace = tomlKey(body, "workspace");const project = tomlKey(body, "project");const projectStrategy = tomlKey(body, "project_strategy");+ const dropSubagent = tomlKey(body, "drop_subagent_captures");if (workspace) url.searchParams.set("workspace", workspace);if (project) url.searchParams.set("project", project);if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);+ if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {const repoProject = repoRootProject(cwd);if (repoProject) url.searchParams.set("project", repoProject);@@ -231,6 +233,7 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {let workspace: string | undefined;let project: string | undefined;let projectStrategy: string | undefined;+ let dropSubagent: string | undefined;const marker = findMarker(cwd);if (marker) {try {@@ -238,6 +241,7 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {workspace = tomlKey(body, "workspace");project = tomlKey(body, "project");projectStrategy = tomlKey(body, "project_strategy");+ dropSubagent = tomlKey(body, "drop_subagent_captures");} catch (_e) {}}@@ -249,6 +253,7 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {if (workspace) url.searchParams.set("workspace", workspace);if (project) url.searchParams.set("project", project);if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);+ if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);}"#;format!("const DEFAULT_PROJECT_STRATEGY = {};\n{body}",@@ -521,6 +526,8 @@ mod tests {assert!(plugin.contains("postHook(\"user-prompt\""));assert!(plugin.contains("function applyMarkerParams"));assert!(plugin.contains("tomlKey(body, \"project_strategy\")"));+ assert!(plugin.contains("tomlKey(body, \"drop_subagent_captures\")"));+ assert!(plugin.contains("url.searchParams.set(\"drop_subagent\", dropSubagent)"));assert!(plugin.contains("import { execFileSync } from \"node:child_process\";"));assert!(plugin.contains("import { basename, dirname, join, resolve } from \"node:path\";"));assert!(plugin.contains("function repoRootProject"));diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex cacb4a69..20f9033d 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -4,9 +4,11 @@//! `setup-agent`) all emit configuration snippets that share two//! pieces of state://!-//! 1. The Claude Code lifecycle-hook events ai-memory wires up-//! (see `CLAUDE_CODE_EVENTS`) — kept in sync between hook-bundle-//! generation (setup-agent) and JSON-config rendering (install-hooks).+//! 1. The per-agent lifecycle-hook event lists ai-memory wires up+//! (Claude/Grok share `CLAUDE_CODE_EVENTS`; Codex, Cursor, Gemini,+//! and Antigravity define their own profiles) — kept in sync between+//! hook-bundle generation (setup-agent) and config rendering+//! (install-hooks).//! 2. The optional `Authorization: Bearer <token>` header used by//! both MCP client configs (install-mcp) and hook env blocks//! (install-hooks / setup-agent).@@ -26,10 +28,10 @@ use crate::commands::path_util::strip_windows_verbatim_prefix;/// Claude Code lifecycle events ai-memory hooks. Each pair is/// `(event-name-in-Claude-Code-settings, POSIX hook-script-filename)`.///-/// Adding a hook event means updating this list AND adding the-/// matching `.sh` and `.ps1` files under-/// `hooks/{claude-code,codex,cursor,gemini-cli,grok,opencode}/`. The-/// install-hooks parity test fails if the bundle drifts.+/// Adding a hook event means updating this list AND adding the matching `.sh`+/// and `.ps1` files under the agents that use this profile (`claude-code` and+/// `grok`). Agents with different vocabularies keep their own event arrays+/// below. The install-hooks parity test fails if a bundle drifts.pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 9] = [("SessionStart", "session-start.sh"),("UserPromptSubmit", "user-prompt-submit.sh"),diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex 9109c2ec..70bd1daf 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -36,7 +36,8 @@ use anyhow::{Context, Result, bail};use crate::cli::{AgentChoice, SetupAgentArgs};use crate::commands::render_shared::{- CLAUDE_CODE_EVENTS, build_claude_code_payload, build_grok_payload,+ ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, CURSOR_PROFILE,+ GEMINI_PROFILE, build_claude_code_payload, build_grok_payload,hook_script_for_current_platform,};use crate::config::{Config, DEFAULT_SERVER_URL};@@ -130,12 +131,17 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {match args.agent {AgentChoice::ClaudeCode => emit_claude_code(&emit_root, &args)?,AgentChoice::Grok => emit_grok(&emit_root, &args)?,- AgentChoice::Codex- | AgentChoice::Cursor- | AgentChoice::GeminiCli- | AgentChoice::AntigravityCli => {- emit_other(&emit_root, agent_sub, &args);+ AgentChoice::Codex => emit_other(&emit_root, agent_sub, &args, &[CODEX_PROFILE.events]),+ AgentChoice::Cursor => emit_other(&emit_root, agent_sub, &args, &[CURSOR_PROFILE.events]),+ AgentChoice::GeminiCli => {+ emit_other(&emit_root, agent_sub, &args, &[GEMINI_PROFILE.events]);}+ AgentChoice::AntigravityCli => emit_other(+ &emit_root,+ agent_sub,+ &args,+ &[&ANTIGRAVITY_TOOL_EVENTS, &ANTIGRAVITY_LIFECYCLE_EVENTS],+ ),AgentChoice::OpenCode => unreachable!("opencode handled above"),AgentChoice::Omp => unreachable!("omp handled above"),AgentChoice::Openclaw => {@@ -226,7 +232,12 @@ fn emit_grok(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {Ok(())}-fn emit_other(emit_root: &Path, label: &str, args: &SetupAgentArgs) {+fn emit_other(+ emit_root: &Path,+ label: &str,+ args: &SetupAgentArgs,+ event_lists: &[&[(&str, &str)]],+) {// These clients have hook surfaces, but their print-mode config// snippets are intentionally conservative: apply-mode owns the// exact merge/plugin generation where ai-memory knows the format.@@ -238,15 +249,25 @@ fn emit_other(emit_root: &Path, label: &str, args: &SetupAgentArgs) {println!("# value you passed via --auth-token (not echoed).");}println!();- for (_, script) in CLAUDE_CODE_EVENTS {- let script = hook_script_for_current_platform(script);- println!("- {}", emit_root.join(script.as_ref()).display());+ for path in event_script_paths(emit_root, event_lists) {+ println!("- {}", path.display());}println!();println!("Set AI_MEMORY_HOOK_URL in each hook's environment to override the default.");println!("Also run `ai-memory install-mcp --client {label}` to wire MCP separately.");}+fn event_script_paths(emit_root: &Path, event_lists: &[&[(&str, &str)]]) -> Vec<PathBuf> {+ let mut paths = Vec::new();+ for events in event_lists {+ for (_, script) in *events {+ let script = hook_script_for_current_platform(script);+ paths.push(emit_root.join(script.as_ref()));+ }+ }+ paths+}+fn is_hook_script_file(path: &Path) -> bool {matches!(path.extension().and_then(|s| s.to_str()),@@ -379,4 +400,29 @@ mod tests {let candidates = source_candidates(Some(Path::new("/custom/src")), "codex", None);assert_eq!(candidates, vec![PathBuf::from("/custom/src/codex")]);}++ #[test]+ fn manual_script_paths_use_agent_specific_events() {+ let root = Path::new("/hooks/gemini-cli");+ let paths = event_script_paths(root, &[GEMINI_PROFILE.events]);+ let rendered = paths+ .iter()+ .map(|path| path.to_string_lossy())+ .collect::<Vec<_>>()+ .join("\n");++ assert!(rendered.contains("session-start"));+ assert!(rendered.contains("session-end"));+ assert!(rendered.contains("pre-tool-use"));+ assert!(rendered.contains("post-tool-use"));+ assert!(rendered.contains("pre-compact"));+ assert!(+ !rendered.contains("user-prompt-submit"),+ "Gemini has no UserPromptSubmit hook; setup-agent must not print Claude-only scripts"+ );+ assert!(+ !rendered.contains("subagent-start") && !rendered.contains("subagent-stop"),+ "Gemini has no subagent hook events; setup-agent must not print nonexistent scripts"+ );+ }}diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex cc437b85..a120ffda 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -14,8 +14,9 @@ use std::sync::Arc;use ai_memory_consolidate::Consolidator;use ai_memory_core::{- ActiveProject, AgentKind, DEFAULT_WORKSPACE_NAME, Handoff, NewHandoff, NewObservation,- NewSession, ObservationKind, ProjectId, Sanitized, Sanitizer, SessionId, WorkspaceId,+ ActiveProject, ActorKey, AgentKind, DEFAULT_WORKSPACE_NAME, Handoff, NewHandoff,+ NewObservation, NewSession, ObservationKind, ProjectId, Sanitized, Sanitizer, SessionId,+ WorkspaceId,};use ai_memory_store::WriterHandle;use ai_memory_wiki::Wiki;@@ -52,9 +53,10 @@ pub const MAX_HOOK_BATCH_ITEMS: usize = 256;/// an optimization only; evicted entries are re-resolved through the writer.pub const DEFAULT_PROJECT_CACHE_MAX_ENTRIES: usize = 4096;-/// Cap on session ids tracked as subagents for the `drop_subagent_captures`-/// tail-drop. Bounded LRU: a missed `SubagentStop` can never grow it without-/// bound — the oldest id evicts once the cap is hit.+/// Cap on scoped session ids tracked as subagents for the+/// `drop_subagent_captures` tail-drop. Mirrors the project-cache order of+/// magnitude: enough for high fan-out harnesses, still bounded if a client never+/// sends a terminal `SessionEnd`.const SUBAGENT_SESSIONS_MAX: usize = 4096;/// Resolved-project cache key:@@ -148,19 +150,27 @@ impl ProjectCacheStore {}}-/// Shared bounded set of session ids known to belong to a SUBAGENT.+/// Shared bounded set of scoped session keys known to belong to a SUBAGENT.pub type SubagentSessions = Arc<tokio::sync::Mutex<SubagentSessionSet>>;-/// Tracks the session ids of subagent (nested/spawned) sessions so that the-/// `drop_subagent_captures` gate can also drop the **unmarked tail** of those+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+struct SubagentSessionKey {+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ session_id: SessionId,+}++/// 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/// is seeded when a `SubagentStart` or any marker-bearing event arrives, and-/// forgotten on `SubagentStop`. Bounded LRU so a missed stop cannot leak memory.+/// forgotten on `SessionEnd` after the tail has been dropped. Bounded LRU so a+/// missed terminal event cannot leak memory.#[derive(Debug)]pub struct SubagentSessionSet {- ids: HashSet<SessionId>,- order: VecDeque<SessionId>,+ ids: HashSet<SubagentSessionKey>,+ order: VecDeque<SubagentSessionKey>,max: usize,}@@ -175,33 +185,41 @@ impl Default for SubagentSessionSet {}impl SubagentSessionSet {- /// Mark a session id as a subagent (idempotent). Evicts the oldest id once- /// the cap is exceeded.- fn insert(&mut self, id: SessionId) {- if self.ids.insert(id) {- self.order.push_back(id);- while self.ids.len() > self.max {- if let Some(oldest) = self.order.pop_front() {- self.ids.remove(&oldest);- } else {- break;- }+ /// Mark a scoped session id as a subagent (idempotent). Refreshes recency+ /// and evicts the oldest id once the cap is exceeded.+ fn insert(&mut self, key: SubagentSessionKey) {+ if self.ids.contains(&key) {+ self.touch(&key);+ return;+ }+ self.ids.insert(key);+ self.order.push_back(key);+ while self.ids.len() > self.max {+ if let Some(oldest) = self.order.pop_front() {+ self.ids.remove(&oldest);+ } else {+ break;}}}- /// Whether this session id is a known subagent.+ /// Whether this scoped session id is a known subagent.#[must_use]- fn contains(&self, id: &SessionId) -> bool {- self.ids.contains(id)+ fn contains(&self, key: &SubagentSessionKey) -> bool {+ self.ids.contains(key)}- /// Forget a session id (on `SubagentStop`).- fn remove(&mut self, id: &SessionId) {- if self.ids.remove(id) {- self.order.retain(|k| k != id);+ /// Forget a scoped session id (after `SessionEnd`).+ fn remove(&mut self, key: &SubagentSessionKey) {+ if self.ids.remove(key) {+ self.order.retain(|k| k != key);}}++ fn touch(&mut self, key: &SubagentSessionKey) {+ self.order.retain(|k| k != key);+ self.order.push_back(*key);+ }}/// Shared state passed to the hook handler.@@ -246,7 +264,7 @@ pub struct HookState {/// session close stays cheap; the LLM checkpoint otherwise happens on/// PreCompact and via manual `memory_consolidate`.pub consolidate_on_session_end: bool,- /// Session ids known to be subagents (seeded by `SubagentStart` / any+ /// Scoped session keys known to be subagents (seeded by `SubagentStart` / any/// marker-bearing event). For a project that opted into/// `drop_subagent_captures` (via its `.ai-memory.toml`, forwarded as the/// per-event `drop_subagent` flag), every event of a tracked session is@@ -281,9 +299,6 @@ async fn handle_hook(// subagent sessions) when the operator opts in. Returning 202 (not an error)// means the client treats the event as delivered and never retries/spools// it. Runs before the semaphore so a dropped event consumes no capacity.- if should_drop_subagent(&state, &env).await {- return (StatusCode::ACCEPTED, "subagent capture dropped");- }// The auth middleware in front of `/hook` injects the request's// [`ActorContext`] (rung 1 root, rung 2 DB user, or anonymous). We// capture its `user` field NOW — before the spawn drops the request@@ -292,6 +307,13 @@ async fn handle_hook(let actor_user = actor_ext.map(|axum::Extension(ctx)| ctx.user).unwrap_or_default();+ let actor_key = ActorKey {+ user: actor_user.clone(),+ session_id: env.session_id.clone(),+ };+ if should_drop_subagent(&state, &env, &actor_key).await {+ return (StatusCode::ACCEPTED, "subagent capture dropped");+ }let Ok(permit) = state.ingest_semaphore.clone().try_acquire_owned() else {warn!("hook ingest saturated; dropping event with 429");return (StatusCode::TOO_MANY_REQUESTS, "hook queue full");@@ -359,33 +381,34 @@ async fn handle_hook_batch(let actor_user = actor_ext.map(|axum::Extension(ctx)| ctx.user).unwrap_or_default();- // Hold capacity proportional to the batch size so batch ingress cannot- // exceed the same in-flight event bound as single `/hook` requests. Empty- // batches still acquire one permit to respect backpressure consistently.- let permits = u32::try_from(items.len().max(1)).unwrap_or(u32::MAX);- let Ok(permit) = state- .ingest_semaphore- .clone()- .try_acquire_many_owned(permits)- else {- warn!("hook batch ingest saturated; rejecting with 429");- return (- StatusCode::TOO_MANY_REQUESTS,- Json(HookBatchAck { accepted: 0 }),- );- };- let _permit = permit;let mut accepted = 0usize;for item in items {let query = parse_hook_query(&item.url);let env = HookEnvelope::from_query_and_body(query, item.body);+ let actor_key = ActorKey {+ user: actor_user.clone(),+ session_id: env.session_id.clone(),+ };// Accept-but-drop subagent captures (see `handle_hook`): count the item// as committed so the client clears it from its spool, but do not store// it. Keeps the contiguous-prefix ack contract intact.- if should_drop_subagent(&state, &env).await {+ if should_drop_subagent(&state, &env, &actor_key).await {accepted += 1;continue;}+ // Mirror single `/hook`: subagent drops consume no ingest capacity, and+ // only events we will actually process acquire a permit. The batch loop+ // is sequential, so one permit held across this item preserves the+ // server-wide in-flight bound without making all-droppable batches 429+ // under saturation.+ let Ok(permit) = state.ingest_semaphore.clone().try_acquire_owned() else {+ warn!(accepted, "hook batch ingest saturated; rejecting with 429");+ return (+ StatusCode::TOO_MANY_REQUESTS,+ Json(HookBatchAck { accepted }),+ );+ };+ let _permit = permit;if let Err(e) = process(&state, env, actor_user.clone()).await {warn!(error = %e, accepted, "hook batch item failed; stopping (fail-fast)");break;@@ -397,41 +420,50 @@ async fn handle_hook_batch(/// Decide whether to accept-but-drop this event under `drop_subagent_captures`,/// maintaining the subagent-session set. Returns `true` to drop. Seeds the-/// session on `SubagentStart` and on any marker-bearing event; forgets it on+/// session on `SubagentStart` and on any marker-bearing event; keeps it through/// `SubagentStop`; and drops the **unmarked tail** (`user_prompt_submit` //// `stop` / `session_end`) of a session already known to be a subagent. No-op/// (returns `false`) unless this event's project opted in via the per-event/// `drop_subagent` flag (sourced from its `.ai-memory.toml`).-async fn should_drop_subagent(state: &HookState, env: &HookEnvelope) -> bool {+async fn should_drop_subagent(state: &HookState, env: &HookEnvelope, actor: &ActorKey) -> bool {if !env.drop_subagent_requested {return false;}- let sid = resolve_session_id(env).ok();- match env.event {- HookEvent::SubagentStop => {- if let Some(s) = sid {- state.subagent_sessions.lock().await.remove(&s);- }- true- }- HookEvent::SubagentStart => {- if let Some(s) = sid {- state.subagent_sessions.lock().await.insert(s);- }- true- }- _ if body_is_subagent(&env.raw) => {- if let Some(s) = sid {- state.subagent_sessions.lock().await.insert(s);- }- true- }- // Unmarked event: drop only when its session is a known subagent (tail).- _ => match sid {- Some(s) => state.subagent_sessions.lock().await.contains(&s),- None => false,- },+ let Ok(session_id) = resolve_session_id(env) else {+ return false;+ };+ let Ok((workspace_id, project_id)) = resolve_project_ids(+ state,+ env.cwd.as_deref(),+ env.workspace_override.as_deref(),+ env.project_override.as_deref(),+ env.project_strategy,+ actor,+ )+ .await+ else {+ return false;+ };+ let key = SubagentSessionKey {+ workspace_id,+ project_id,+ session_id,+ };+ let marked = matches!(+ env.event,+ HookEvent::SubagentStart | HookEvent::SubagentStop+ ) || body_is_subagent(&env.raw);++ if marked {+ state.subagent_sessions.lock().await.insert(key);+ return true;+ }++ let tracked = state.subagent_sessions.lock().await.contains(&key);+ if tracked && matches!(env.event, HookEvent::SessionEnd) {+ state.subagent_sessions.lock().await.remove(&key);}+ tracked}/// Parse the `?event=…&agent=…` query of a spooled hook URL into [`HookQuery`],@@ -1676,6 +1708,111 @@ mod tests {);}+ #[tokio::test]+ async fn drop_subagent_tracking_is_scoped_by_project() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let actor = ai_memory_core::ActorKey::default();++ let marked_project_a = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "pre-tool-use".into(),+ agent: Some("grok".into()),+ project: Some("project-a".into()),+ drop_subagent: Some("1".into()),+ ..Default::default()+ },+ serde_json::json!({+ "sessionId": "shared-session", "subagentType": "general-purpose"+ }),+ );+ assert!(should_drop_subagent(&state, &marked_project_a, &actor).await);++ let unmarked_project_b = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "pre-tool-use".into(),+ agent: Some("grok".into()),+ project: Some("project-b".into()),+ drop_subagent: Some("1".into()),+ ..Default::default()+ },+ serde_json::json!({ "sessionId": "shared-session", "toolName": "kept" }),+ );+ assert!(+ !should_drop_subagent(&state, &unmarked_project_b, &actor).await,+ "a subagent session tracked in project-a must not drop same-id events in project-b"+ );++ let unmarked_project_a = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "pre-tool-use".into(),+ agent: Some("grok".into()),+ project: Some("project-a".into()),+ drop_subagent: Some("1".into()),+ ..Default::default()+ },+ serde_json::json!({ "sessionId": "shared-session", "toolName": "dropped" }),+ );+ assert!(+ should_drop_subagent(&state, &unmarked_project_a, &actor).await,+ "the originally tracked project's unmarked tail still drops"+ );+ }++ #[tokio::test]+ async fn subagent_stop_keeps_session_tracked_until_session_end_tail_drops() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let actor = ai_memory_core::ActorKey::default();++ let query = |event: &str| HookQuery {+ event: event.into(),+ agent: Some("grok".into()),+ project: Some("tail-project".into()),+ drop_subagent: Some("1".into()),+ ..Default::default()+ };++ let start = HookEnvelope::from_query_and_body(+ query("subagent-start"),+ serde_json::json!({ "sessionId": "tail-session" }),+ );+ assert!(should_drop_subagent(&state, &start, &actor).await);++ let subagent_stop = HookEnvelope::from_query_and_body(+ query("subagent-stop"),+ serde_json::json!({ "sessionId": "tail-session" }),+ );+ assert!(should_drop_subagent(&state, &subagent_stop, &actor).await);++ let unmarked_stop_tail = HookEnvelope::from_query_and_body(+ query("stop"),+ serde_json::json!({ "sessionId": "tail-session" }),+ );+ assert!(+ should_drop_subagent(&state, &unmarked_stop_tail, &actor).await,+ "SubagentStop must not clear tracking before the unmarked stop tail"+ );++ let session_end_tail = HookEnvelope::from_query_and_body(+ query("session-end"),+ serde_json::json!({ "sessionId": "tail-session" }),+ );+ assert!(+ should_drop_subagent(&state, &session_end_tail, &actor).await,+ "SessionEnd tail is dropped and then clears tracking"+ );++ let after_session_end = HookEnvelope::from_query_and_body(+ query("pre-tool-use"),+ serde_json::json!({ "sessionId": "tail-session", "toolName": "kept" }),+ );+ assert!(+ !should_drop_subagent(&state, &after_session_end, &actor).await,+ "SessionEnd clears tracking for that scoped session"+ );+ }+#[tokio::test]async fn handle_hook_batch_returns_429_when_saturated() {let tmp = TempDir::new().unwrap();@@ -1695,6 +1832,69 @@ mod tests {assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);}+ #[tokio::test]+ async fn handle_hook_batch_drops_subagent_events_before_capacity_check() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.ingest_semaphore = Arc::new(tokio::sync::Semaphore::new(0));++ let response = handle_hook_batch(+ State(Arc::new(state)),+ None,+ Json(vec![HookBatchItem {+ url: "http://h/hook?event=pre-tool-use&agent=grok&drop_subagent=1".into(),+ body: serde_json::json!({+ "sessionId": "saturated-subagent", "subagentType": "general-purpose"+ }),+ }]),+ )+ .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"], 1,+ "droppable subagent batch items should clear the spool even when ingest capacity is saturated"+ );+ }++ #[tokio::test]+ async fn handle_hook_batch_saturated_after_prefix_reports_accepted_prefix() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.ingest_semaphore = Arc::new(tokio::sync::Semaphore::new(0));++ let response = handle_hook_batch(+ State(Arc::new(state)),+ None,+ Json(vec![+ HookBatchItem {+ url: "http://h/hook?event=pre-tool-use&agent=grok&drop_subagent=1".into(),+ body: serde_json::json!({+ "sessionId": "saturated-prefix", "subagentType": "general-purpose"+ }),+ },+ HookBatchItem {+ url: "http://h/hook?event=user-prompt-submit&agent=grok".into(),+ body: serde_json::json!({+ "sessionId": "saturated-prefix", "prompt": "retry later"+ }),+ },+ ]),+ )+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);+ 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"], 1, "429 still reports the committed prefix");+ }+#[tokio::test]async fn handle_hook_batch_rejects_over_client_item_cap() {let tmp = TempDir::new().unwrap();@@ -1719,7 +1919,7 @@ mod tests {}#[tokio::test]- async fn handle_hook_batch_acquires_capacity_per_item() {+ async fn handle_hook_batch_processes_sequentially_with_one_permit() {let tmp = TempDir::new().unwrap();let mut state = make_state(&tmp).await;state.ingest_semaphore = Arc::new(tokio::sync::Semaphore::new(1));@@ -1738,7 +1938,15 @@ mod tests {.await.into_response();- assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);+ 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"], 2,+ "batch processing is sequential, so one permit is enough for processed items"+ );}#[test]