Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(hooks): per-project drop_subagent_captures opt-in with tail tracking
Djalma Júniorb8cf2cf7f21b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bfd1c62f..904d0104 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Per-project `drop_subagent_captures` opt-in. A project sets+ `drop_subagent_captures = "true"` in its `.ai-memory.toml`; the host-side hook+ forwards it (as the `drop_subagent` query flag, alongside the existing+ `workspace`/`project`/`project_strategy` marker fields) so the ingest router+ **accepts but does not persist** that project's subagent-session captures,+ keeping only top-level sessions. A multi-agent harness fans one goal out to+ many subagent sessions, each firing lifecycle hooks; on a small shared+ instance that flood can saturate ingest and bloat the store. Scoping the+ opt-in to the project that asked for it avoids a server-global switch that+ would shed subagent captures for every project on the instance. Captures are+ accepted (HTTP 202 / counted in the `/hook/batch` ack) so clients do not retry+ or spool them, but they are not stored. Detection combines a per-event marker+ (`subagentType` for grok, `agent_type`/`agent_id` for Claude Code) with+ stateful, bounded tracking of subagent session ids: the router seeds the set+ from any marked event and from the newly registered+ `SubagentStart`/`SubagentStop` lifecycle hooks (claude-code and grok), and+ clears it on `SubagentStop`, so the unmarked tail of a subagent session (its+ `user_prompt_submit`/`stop`/`session_end`, which carry no marker) is dropped+ too — not just the marker-bearing tool-use events.+## [1.4.1] - 2026-06-28## [1.4.0] - 2026-06-26diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex 1755e7bf..9cb4f97a 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -50,11 +50,12 @@ pub fn url_encode(s: &str) -> String {/// server cannot see this checkout.pub fn marker_query_suffix(cwd: &str, default_strategy: Option<&str>) -> String {let mut qs = format!("&cwd={}", url_encode(cwd));- let (mut workspace, mut project, mut strategy) = (None, None, None);+ let (mut workspace, mut project, mut strategy, mut drop_subagent) = (None, None, None, None);if let Some(marker) = find_marker(cwd) {workspace = parse_toml_key(&marker, "workspace");project = parse_toml_key(&marker, "project");strategy = parse_toml_key(&marker, "project_strategy");+ drop_subagent = parse_toml_key(&marker, "drop_subagent_captures");}if strategy.is_none() {strategy = default_strategy.map(str::to_owned);@@ -71,6 +72,12 @@ pub fn marker_query_suffix(cwd: &str, default_strategy: Option<&str>) -> Stringif let Some(val) = strategy {qs.push_str(&format!("&project_strategy={}", url_encode(&val)));}+ // Per-project `drop_subagent_captures` opt-in: forward the marker's value as+ // the `drop_subagent` flag so the server scopes the drop to this project.+ // The server interprets truthiness (`1`/`true`/…).+ if let Some(val) = drop_subagent.filter(|v| !v.is_empty()) {+ qs.push_str(&format!("&drop_subagent={}", url_encode(&val)));+ }qs}@@ -427,8 +434,8 @@ project = "infra" # this is fine}/// `marker_query_suffix` appends `&workspace=…&project=…` (and- /// `&project_strategy=…`) when the marker declares them. Each value is- /// URL-encoded, so a workspace with a space round-trips as `%20`.+ /// `&project_strategy=…`, `&drop_subagent=…`) when the marker declares them.+ /// Each value is URL-encoded, so a workspace with a space round-trips as `%20`.#[test]fn marker_query_suffix_appends_marker_fields() {let tmp = tempfile::TempDir::new().unwrap();@@ -439,6 +446,7 @@ project = "infra" # this is fineworkspace = "acme corp"project = "infra"project_strategy = "repo-root"+drop_subagent_captures = "true""#,).unwrap();@@ -449,6 +457,21 @@ project_strategy = "repo-root"assert!(qs.contains("&workspace=acme%20corp"), "{qs}");assert!(qs.contains("&project=infra"), "{qs}");assert!(qs.contains("&project_strategy=repo-root"), "{qs}");+ assert!(qs.contains("&drop_subagent=true"), "{qs}");+ }++ /// A marker WITHOUT `drop_subagent_captures` does not forward the flag, so+ /// the server keeps that project's subagent captures (opt-in only).+ #[test]+ fn marker_query_suffix_omits_drop_subagent_when_unset() {+ let tmp = tempfile::TempDir::new().unwrap();+ std::fs::write(+ tmp.path().join(".ai-memory.toml"),+ "workspace = \"acme\"\nproject = \"infra\"\n",+ )+ .unwrap();+ let qs = marker_query_suffix(tmp.path().to_str().unwrap(), None);+ assert!(!qs.contains("drop_subagent"), "{qs}");}#[test]diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 25a89a53..af3b72f9 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -452,9 +452,9 @@ fn overlay_event_hooks(map.insert(event.to_string(), serde_json::Value::Array(entries));}-/// Mutate `~/.claude/settings.json` in place: replace the seven hook-/// entries ai-memory cares about; preserve every other hook the user-/// has wired up to other tools.+/// Mutate `~/.claude/settings.json` in place: replace the hook entries+/// ai-memory cares about (`CLAUDE_CODE_EVENTS`); preserve every other hook the+/// user has wired up to other tools.fn apply_to_claude_code_settings(hooks_dir: &Path,server_url: &str,@@ -514,7 +514,7 @@ fn apply_to_claude_code_settings(/// Mutate `~/.grok/hooks/ai-memory.json` so Grok Build CLI fires the ai-memory/// lifecycle hooks. Grok's hook config is structurally identical to Claude-/// Code's nested hook JSON and uses the same seven CamelCase event names, but+/// Code's nested hook JSON and uses the same CamelCase event names, but/// its script bundle carries `agent=grok` and skips destructive SessionStart/// handoff fetches. We merge into a dedicated `ai-memory.json` (Grok discovers/// every `~/.grok/hooks/*.json`), so a pre-existing third-party hook file isdiff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 1f2a0a0d..38a1c1b8 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -4,9 +4,9 @@//! `setup-agent`) all emit configuration snippets that share two//! pieces of state://!-//! 1. The seven Claude Code lifecycle-hook events ai-memory wires-//! up — kept in sync between hook-bundle generation (setup-agent)-//! and JSON-config rendering (install-hooks).+//! 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).//! 2. The optional `Authorization: Bearer <token>` header used by//! both MCP client configs (install-mcp) and hook env blocks//! (install-hooks / setup-agent).@@ -30,7 +30,7 @@ use crate::commands::path_util::strip_windows_verbatim_prefix;/// 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.-pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 7] = [+pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 9] = [("SessionStart", "session-start.sh"),("UserPromptSubmit", "user-prompt-submit.sh"),("PreToolUse", "pre-tool-use.sh"),@@ -38,6 +38,11 @@ pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 7] = [("PreCompact", "pre-compact.sh"),("Stop", "stop.sh"),("SessionEnd", "session-end.sh"),+ // Subagent boundaries — let the server seed/forget a subagent session id so+ // `drop_subagent_captures` can drop the whole nested session (Claude Code ++ // grok both emit these; other agents keep their own event lists).+ ("SubagentStart", "subagent-start.sh"),+ ("SubagentStop", "subagent-stop.sh"),];/// Format an `Authorization: Bearer <token>` header value, or `None`@@ -77,7 +82,7 @@ pub(crate) fn ts_string_literal(s: &str) -> String {}/// Build the Claude Code `settings.json` fragment that wires the-/// seven hooks. Used by both:+/// lifecycle hooks (`CLAUDE_CODE_EVENTS`). Used by both:/// - `install-hooks --agent claude-code` (script paths are/// wherever the user told us via `--hooks-dir`)/// - `setup-agent --agent claude-code` (script paths are where@@ -841,11 +846,11 @@ mod tests {}#[test]- fn claude_code_payload_has_seven_events() {+ fn claude_code_payload_has_all_events() {let root = PathBuf::from("/host/hooks/claude-code");let v = build_claude_code_payload(&root, "http://localhost:49374", None);let hooks = v.get("hooks").and_then(|h| h.as_object()).unwrap();- assert_eq!(hooks.len(), 7);+ assert_eq!(hooks.len(), CLAUDE_CODE_EVENTS.len());for (event, _) in CLAUDE_CODE_EVENTS {assert!(hooks.contains_key(event), "missing event {event}");}diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 11dbd1a6..586cd55f 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -286,6 +286,9 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,)),consolidate_on_session_end: config.consolidate_on_session_end,+ subagent_sessions: std::sync::Arc::new(tokio::sync::Mutex::new(+ ai_memory_hooks::SubagentSessionSet::default(),+ )),home_dir: config.home_dir.clone(),});let admin = admin_router(AdminState {diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex b7aba0e9..c0f171ee 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -29,6 +29,6 @@ pub use ai_memory_core::{SanitizeConfig, Sanitized, Sanitizer};pub use payload::{HookEnvelope, HookEvent};pub use router::{DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, DEFAULT_PROJECT_CACHE_MAX_ENTRIES, HookState, ProjectCache,- ProjectCacheStore, hook_router,+ ProjectCacheStore, SubagentSessionSet, SubagentSessions, hook_router,};pub use synth::synthesize_session_page;diff --git a/crates/ai-memory-hooks/src/log.rs b/crates/ai-memory-hooks/src/log.rsindex c8613e16..994e99da 100644--- a/crates/ai-memory-hooks/src/log.rs+++ b/crates/ai-memory-hooks/src/log.rs@@ -92,6 +92,8 @@ fn format_line(when: Timestamp, event: HookEvent, title: &str) -> String {HookEvent::Notification => "notification",HookEvent::Stop => "stop",HookEvent::SessionEnd => "session-end",+ HookEvent::SubagentStart => "subagent-start",+ HookEvent::SubagentStop => "subagent-stop",HookEvent::Other => "other",};let one_line: String = titlediff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 33103ffb..e4d140f5 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -34,6 +34,13 @@ pub struct HookQuery {/// When omitted and `extension` is present, unknown `event` values/// are preserved as the source event.pub source_event: Option<String>,+ /// Per-project opt-in for `drop_subagent_captures`, forwarded by the+ /// host-side hook from a project's `.ai-memory.toml`. A truthy value+ /// (`1`/`true`/…) makes the server accept-but-drop this project's subagent+ /// captures; absent/falsy leaves them stored. Scoping the drop to the+ /// project that asked for it avoids a server-global switch that would shed+ /// subagent captures for every project on a shared instance.+ pub drop_subagent: Option<String>,}/// Coalesced view of an incoming hook event after light parsing of the@@ -58,6 +65,11 @@ pub struct HookEnvelope {pub project_override: Option<String>,/// Project derivation strategy declared by the hook marker.pub project_strategy: ProjectStrategy,+ /// Whether this project opted into `drop_subagent_captures` via its+ /// `.ai-memory.toml` (forwarded as the `drop_subagent` query flag). The+ /// ingest router consults this per-event so the drop is scoped to the+ /// project that asked for it.+ pub drop_subagent_requested: bool,/// Optional third-party extension namespace.pub extension: Option<String>,/// Optional source event name from the extension vocabulary.@@ -70,6 +82,36 @@ pub struct HookEnvelope {pub raw: serde_json::Value,}+/// 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"];++/// 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+/// consults this to optionally drop subagent captures (the+/// `drop_subagent_captures` setting). Only top-level string keys are inspected.+pub(crate) fn body_is_subagent(raw: &serde_json::Value) -> bool {+ SUBAGENT_MARKER_KEYS.iter().any(|key| {+ raw.get(*key)+ .and_then(serde_json::Value::as_str)+ .is_some_and(|value| !value.trim().is_empty())+ })+}++/// Truthy interpretation of a query-string flag (`1`/`true`/`yes`/`on`,+/// case-insensitive). Used for the per-project `drop_subagent` opt-in the+/// host-side hook forwards from a project's `.ai-memory.toml`.+fn query_flag_truthy(value: Option<&str>) -> bool {+ matches!(+ value.map(|v| v.trim().to_ascii_lowercase()).as_deref(),+ Some("1" | "true" | "yes" | "on")+ )+}+/// How the hook router derives a project name when no explicit/// `project` override is present.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]@@ -123,6 +165,10 @@ pub enum HookEvent {Stop,/// Session ended (final).SessionEnd,+ /// A subagent (nested/spawned child session) started.+ SubagentStart,+ /// A subagent finished.+ SubagentStop,/// Anything else.Other,}@@ -148,6 +194,11 @@ impl HookEvent {"notification" | "Notification" => Self::Notification,"stop" | "Stop" => Self::Stop,"session-end" | "session_end" | "SessionEnd" | "sessionEnd" => Self::SessionEnd,+ "subagent-start" | "subagent_start" | "SubagentStart" | "subagentStart" => {+ Self::SubagentStart+ }+ "subagent-stop" | "subagent_stop" | "SubagentStop" | "subagentStop"+ | "subagent-end" | "SubagentEnd" => Self::SubagentStop,_ => Self::Other,}}@@ -164,6 +215,9 @@ impl HookEvent {Self::Notification => ObservationKind::Notification,Self::Stop => ObservationKind::Stop,Self::SessionEnd => ObservationKind::SessionEnd,+ // Subagent lifecycle events are normally dropped (drop_subagent_captures);+ // bucket as Other for the flag-off path rather than growing ObservationKind.+ Self::SubagentStart | Self::SubagentStop => ObservationKind::Other,Self::Other => ObservationKind::Other,}}@@ -238,6 +292,7 @@ impl HookEnvelope {let workspace_override = query.workspace.filter(|s| !s.is_empty());let project_override = query.project.filter(|s| !s.is_empty());let project_strategy = ProjectStrategy::parse(query.project_strategy.as_deref());+ let drop_subagent_requested = query_flag_truthy(query.drop_subagent.as_deref());let extension = normalize_extension_name(query.extension.as_deref());let source_event = extension.as_ref().and_then(|_| {let raw_source = query@@ -269,6 +324,7 @@ impl HookEnvelope {workspace_override,project_override,project_strategy,+ drop_subagent_requested,extension,source_event,title_hint,@@ -546,6 +602,40 @@ fn normalize_token(value: &str, max_len: usize) -> Option<String> {mod tests {use super::*;+ #[test]+ fn body_is_subagent_detects_harness_markers() {+ // grok tags subagent tool-use events with `subagentType`.+ assert!(body_is_subagent(+ &serde_json::json!({ "sessionId": "s", "subagentType": "general-purpose" })+ ));+ // Claude Code tags its subagent events with `agent_type` / `agent_id`.+ assert!(body_is_subagent(+ &serde_json::json!({ "session_id": "s", "agent_type": "workflow-subagent" })+ ));+ assert!(body_is_subagent(+ &serde_json::json!({ "agent_id": "agent-abc123" })+ ));+ }++ #[test]+ fn body_is_subagent_false_for_top_level_and_empty_markers() {+ // A normal top-level event carries no marker.+ assert!(!body_is_subagent(+ &serde_json::json!({ "session_id": "s", "tool_name": "Write" })+ ));+ // An empty / blank or non-string marker does not count as a subagent.+ assert!(!body_is_subagent(+ &serde_json::json!({ "subagentType": "" })+ ));+ assert!(!body_is_subagent(+ &serde_json::json!({ "subagentType": " " })+ ));+ assert!(!body_is_subagent(+ &serde_json::json!({ "agent_type": null })+ ));+ assert!(!body_is_subagent(&serde_json::json!({})));+ }+#[test]fn parses_known_events() {assert_eq!(HookEvent::parse("session-start"), HookEvent::SessionStart);diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 18628574..280fca74 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -8,7 +8,7 @@//! basic-memory #763). The agent never blocks on us thanks to the//! fire-and-forget client side.-use std::collections::{HashMap, VecDeque};+use std::collections::{HashMap, HashSet, VecDeque};use std::str::FromStr;use std::sync::Arc;@@ -31,7 +31,9 @@ use tracing::{debug, info, warn};use uuid::Uuid;use crate::log;-use crate::payload::{HookEnvelope, HookEvent, HookQuery, ProjectStrategy, parse_agent};+use crate::payload::{+ HookEnvelope, HookEvent, HookQuery, ProjectStrategy, body_is_subagent, parse_agent,+};use crate::synth::synthesize_session_page;/// Default maximum number of hook events allowed to be processing at once.@@ -50,6 +52,11 @@ 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.+const SUBAGENT_SESSIONS_MAX: usize = 4096;+/// Resolved-project cache key:/// `(cwd, workspace_override, project_override, project_strategy)`.pub type ProjectCacheKey = (String, String, String, String);@@ -141,6 +148,62 @@ impl ProjectCacheStore {}}+/// Shared bounded set of session ids 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+/// 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.+#[derive(Debug)]+pub struct SubagentSessionSet {+ ids: HashSet<SessionId>,+ order: VecDeque<SessionId>,+ max: usize,+}++impl Default for SubagentSessionSet {+ fn default() -> Self {+ Self {+ ids: HashSet::new(),+ order: VecDeque::new(),+ max: SUBAGENT_SESSIONS_MAX,+ }+ }+}++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;+ }+ }+ }+ }++ /// Whether this session id is a known subagent.+ #[must_use]+ fn contains(&self, id: &SessionId) -> bool {+ self.ids.contains(id)+ }++ /// Forget a session id (on `SubagentStop`).+ fn remove(&mut self, id: &SessionId) {+ if self.ids.remove(id) {+ self.order.retain(|k| k != id);+ }+ }+}+/// Shared state passed to the hook handler.#[derive(Clone)]pub struct HookState {@@ -183,6 +246,13 @@ 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+ /// 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+ /// dropped — closing the unmarked tail+ /// (`user_prompt_submit`/`stop`/`session_end`) the per-event marker misses.+ pub subagent_sessions: SubagentSessions,/// Operator home directory, sourced from `Config` once at startup. The/// cwd->project resolver never prefix-matches a stored `repo_path` equal/// to this, so `$HOME` cannot become a catch-all (issue #103). `None`@@ -207,6 +277,13 @@ async fn handle_hook(Json(body): Json<serde_json::Value>,) -> impl IntoResponse {let env = HookEnvelope::from_query_and_body(query, body);+ // Accept-but-drop subagent captures (incl. the unmarked tail of tracked+ // 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@@ -302,6 +379,13 @@ async fn handle_hook_batch(for item in items {let query = parse_hook_query(&item.url);let env = HookEnvelope::from_query_and_body(query, item.body);+ // 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 {+ accepted += 1;+ continue;+ }if let Err(e) = process(&state, env, actor_user.clone()).await {warn!(error = %e, accepted, "hook batch item failed; stopping (fail-fast)");break;@@ -311,6 +395,45 @@ async fn handle_hook_batch((StatusCode::OK, Json(HookBatchAck { accepted }))}+/// 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+/// `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 {+ 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,+ },+ }+}+/// Parse the `?event=…&agent=…` query of a spooled hook URL into [`HookQuery`],/// mirroring axum's `Query` extractor (both use `serde_urlencoded`). A URL with/// no query, or an unparseable one, yields the default query; downstream@@ -1086,7 +1209,10 @@ const fn importance_for(event: HookEvent) -> u8 {HookEvent::UserPrompt => 8,HookEvent::PostToolUse | HookEvent::PreToolUse => 5,HookEvent::Stop | HookEvent::PreCompact => 6,- HookEvent::Notification | HookEvent::Other => 3,+ HookEvent::Notification+ | HookEvent::Other+ | HookEvent::SubagentStart+ | HookEvent::SubagentStop => 3,}}@@ -1128,6 +1254,7 @@ mod tests {project_cache: Arc::new(tokio::sync::Mutex::new(ProjectCacheStore::default())),active_project: ActiveProject::new(),consolidate_on_session_end: false,+ subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),home_dir: None,ingest_semaphore: Arc::new(tokio::sync::Semaphore::new(DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,@@ -1243,6 +1370,231 @@ mod tests {assert_eq!(ack["accepted"], 2, "both events committed, oldest-first");}+ /// `pre-tool-use` query+agent for building an env to recompute a SessionId.+ fn grok_tool_query() -> HookQuery {+ HookQuery {+ event: "pre-tool-use".into(),+ agent: Some("grok".into()),+ ..Default::default()+ }+ }++ #[tokio::test]+ async fn handle_hook_batch_drops_subagent_events_when_enabled() {+ let tmp = TempDir::new().unwrap();+ let state = Arc::new(make_state(&tmp).await);++ // A grok subagent tool-use event (carries `subagentType`) alongside a+ // top-level event (no marker), in ONE batch.+ let sub_body = serde_json::json!({+ "sessionId": "sub-s1", "subagentType": "general-purpose", "toolName": "x"+ });+ let top_body = serde_json::json!({ "sessionId": "top-s1", "toolName": "x" });+ // The project opted in (`.ai-memory.toml` → `drop_subagent=1`), so every+ // event carries the flag; only the actual subagent capture is dropped.+ let items = vec![+ HookBatchItem {+ url: "http://h/hook?event=pre-tool-use&agent=grok&drop_subagent=1".into(),+ body: sub_body.clone(),+ },+ HookBatchItem {+ url: "http://h/hook?event=pre-tool-use&agent=grok&drop_subagent=1".into(),+ body: top_body.clone(),+ },+ ];++ let response = handle_hook_batch(State(state.clone()), None, 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();+ // Accept-but-drop: BOTH are acked so the client clears its spool…+ assert_eq!(+ ack["accepted"], 2,+ "both acked so the client clears its spool"+ );++ // …but only the top-level event was persisted; the subagent left nothing.+ let sub_sid = resolve_session_id(&HookEnvelope::from_query_and_body(+ grok_tool_query(),+ sub_body,+ ))+ .unwrap();+ let top_sid = resolve_session_id(&HookEnvelope::from_query_and_body(+ grok_tool_query(),+ top_body,+ ))+ .unwrap();+ assert!(+ state+ .reader+ .observations_for_session(sub_sid)+ .await+ .unwrap()+ .is_empty(),+ "subagent capture must not be persisted"+ );+ assert_eq!(+ state+ .reader+ .observations_for_session(top_sid)+ .await+ .unwrap()+ .len(),+ 1,+ "top-level capture is persisted as usual"+ );+ }++ #[tokio::test]+ async fn handle_hook_batch_keeps_subagent_events_when_disabled() {+ let tmp = TempDir::new().unwrap();+ let state = Arc::new(make_state(&tmp).await);++ // No `drop_subagent` flag on the request → the project did not opt in,+ // so its subagent captures are stored as usual.+ let sub_body = serde_json::json!({+ "sessionId": "sub-s2", "subagentType": "general-purpose", "toolName": "x"+ });+ let items = vec![HookBatchItem {+ url: "http://h/hook?event=pre-tool-use&agent=grok".into(),+ body: sub_body.clone(),+ }];++ let response = handle_hook_batch(State(state.clone()), None, Json(items))+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::OK);++ let sub_sid = resolve_session_id(&HookEnvelope::from_query_and_body(+ grok_tool_query(),+ sub_body,+ ))+ .unwrap();+ assert_eq!(+ state+ .reader+ .observations_for_session(sub_sid)+ .await+ .unwrap()+ .len(),+ 1,+ "without the per-project opt-in, subagent captures are stored (default behavior)"+ );+ }++ #[tokio::test]+ async fn drop_subagent_captures_drops_unmarked_tail_of_tracked_session() {+ let tmp = TempDir::new().unwrap();+ let state = Arc::new(make_state(&tmp).await);++ // (1) marked subagent event seeds session "sub" (and is dropped);+ // (2) a later UNMARKED event on "sub" is the tail → dropped via tracking;+ // (3) an UNMARKED event on a never-seeded session "top" → kept.+ let marked = serde_json::json!({+ "sessionId": "sub", "subagentType": "general-purpose", "toolName": "x"+ });+ let tail = serde_json::json!({ "sessionId": "sub", "toolName": "y" });+ let top = serde_json::json!({ "sessionId": "top", "toolName": "z" });+ let items = vec![+ HookBatchItem {+ url: "http://h/hook?event=pre-tool-use&agent=grok&drop_subagent=1".into(),+ body: marked,+ },+ HookBatchItem {+ url: "http://h/hook?event=pre-tool-use&agent=grok&drop_subagent=1".into(),+ body: tail.clone(),+ },+ HookBatchItem {+ url: "http://h/hook?event=pre-tool-use&agent=grok&drop_subagent=1".into(),+ body: top.clone(),+ },+ ];++ let response = handle_hook_batch(State(state.clone()), None, 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"], 3, "all acked: 2 dropped + 1 processed");++ let sub_sid =+ resolve_session_id(&HookEnvelope::from_query_and_body(grok_tool_query(), tail))+ .unwrap();+ let top_sid =+ resolve_session_id(&HookEnvelope::from_query_and_body(grok_tool_query(), top)).unwrap();+ assert!(+ state+ .reader+ .observations_for_session(sub_sid)+ .await+ .unwrap()+ .is_empty(),+ "the unmarked tail of a tracked subagent session is dropped"+ );+ assert_eq!(+ state+ .reader+ .observations_for_session(top_sid)+ .await+ .unwrap()+ .len(),+ 1,+ "an unmarked event on a non-subagent session is kept"+ );+ }++ #[tokio::test]+ async fn subagent_start_event_seeds_the_session_so_its_tail_drops() {+ let tmp = TempDir::new().unwrap();+ let state = Arc::new(make_state(&tmp).await);++ // SubagentStart seeds session "ss" BEFORE its first content event, so even+ // the leading unmarked user_prompt_submit is dropped.+ let start = serde_json::json!({ "sessionId": "ss" });+ let lead = serde_json::json!({ "sessionId": "ss", "prompt": "go" });+ let items = vec![+ HookBatchItem {+ url: "http://h/hook?event=subagent-start&agent=grok&drop_subagent=1".into(),+ body: start,+ },+ HookBatchItem {+ url: "http://h/hook?event=user-prompt-submit&agent=grok&drop_subagent=1".into(),+ body: lead.clone(),+ },+ ];++ let response = handle_hook_batch(State(state.clone()), None, Json(items))+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::OK);++ let sid = resolve_session_id(&HookEnvelope::from_query_and_body(+ HookQuery {+ event: "user-prompt-submit".into(),+ agent: Some("grok".into()),+ ..Default::default()+ },+ lead,+ ))+ .unwrap();+ assert!(+ state+ .reader+ .observations_for_session(sid)+ .await+ .unwrap()+ .is_empty(),+ "SubagentStart seeds the session so the leading unmarked event drops too"+ );+ }+#[tokio::test]async fn handle_hook_batch_returns_429_when_saturated() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs b/crates/ai-memory-mcp/tests/autoscope_multiuser.rsindex 2acd7518..41839c37 100644--- a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs+++ b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs@@ -19,7 +19,8 @@use ai_memory_core::{ActiveProject, ActiveProjectMode, ActorContext, NewUser, Tier};use ai_memory_hooks::{- DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore, hook_router,+ DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore, SubagentSessionSet,+ hook_router,};use ai_memory_mcp::AiMemoryServer;use ai_memory_store::{Store, TokenPepper, generate_token, hash_token};@@ -157,6 +158,7 @@ impl MultiUserHarness {DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,)),consolidate_on_session_end: false,+ subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),home_dir: None,});diff --git a/crates/ai-memory-mcp/tests/autoscope_stress.rs b/crates/ai-memory-mcp/tests/autoscope_stress.rsindex 447484a5..629502f2 100644--- a/crates/ai-memory-mcp/tests/autoscope_stress.rs+++ b/crates/ai-memory-mcp/tests/autoscope_stress.rs@@ -19,7 +19,8 @@use ai_memory_core::{ActiveProject, ActiveProjectMode, ActorContext};use ai_memory_hooks::{- DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore, hook_router,+ DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore, SubagentSessionSet,+ hook_router,};use ai_memory_mcp::AiMemoryServer;use ai_memory_store::Store;@@ -156,6 +157,7 @@ impl Harness {DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,)),consolidate_on_session_end: false,+ subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),home_dir: None,});diff --git a/docs/marker-file.md b/docs/marker-file.mdindex 635b5608..51a2f5f8 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -33,7 +33,8 @@ handoff lookups.The marker path is shared by the POSIX/PowerShell hook scripts and thegenerated OpenCode / OMP / OpenClaw TypeScript integrations. In all cases,hook capture and handoff lookup send the same `cwd`, `workspace`, `project`,-and `project_strategy` query params to the server when a marker is present;+`project_strategy`, and `drop_subagent` query params to the server when a+marker is present;handoff lookup also sends `cwd` when no marker exists so the default`project = basename(cwd)` route works consistently.@@ -53,6 +54,14 @@ project = "pe-portais"# linked worktrees and subdirectories share one project. Ignored when# `project` is present.project_strategy = "repo-root"++# Optional. Opt this project into drop_subagent_captures: set it to "true"+# and the server accepts but does NOT store this project's subagent-session+# captures. A multi-agent harness fans one goal out to many subagent+# sessions whose per-event captures can flood a small instance; scoping the+# opt-in here keeps the drop from affecting other projects on the same+# server. Off by default (absent / "false").+drop_subagent_captures = "true"```**Naming rules** for `workspace` and `project`, validated server-side:@@ -67,6 +76,13 @@ defensively but the server's regex is the source of truth.`project_strategy` accepts `repo-root` (or `repo_root`) only. Unknownvalues are ignored and behave like the default `basename(cwd)` strategy.+`drop_subagent_captures` accepts a truthy string (`"true"` / `"1"` /+`"yes"` / `"on"`); any other value, or its absence, leaves this project's+subagent 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.+## Four canonical examples### Multi-clientdiff --git a/hooks/_lib.sh b/hooks/_lib.shindex 3bf00053..9b33321a 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -104,11 +104,13 @@ ai_memory_marker_qs() {ws=""pr=""st=""+ ds=""marker=$(ai_memory_find_marker "$cwd")if [ -n "$marker" ]; thenws=$(ai_memory_parse_toml_key "$marker" workspace)pr=$(ai_memory_parse_toml_key "$marker" project)st=$(ai_memory_parse_toml_key "$marker" project_strategy)+ ds=$(ai_memory_parse_toml_key "$marker" drop_subagent_captures)fi# Install-time default baked into the hook command by# `install-hooks --project-strategy` fills the strategy only when no marker@@ -130,6 +132,9 @@ ai_memory_marker_qs() {[ -n "$ws" ] && qs="${qs}&workspace=$(ai_memory_url_encode "$ws")"[ -n "$pr" ] && qs="${qs}&project=$(ai_memory_url_encode "$pr")"[ -n "$st" ] && qs="${qs}&project_strategy=$(ai_memory_url_encode "$st")"+ # Per-project drop_subagent_captures opt-in: forward to the server, which+ # interprets truthiness (1/true/...) and scopes the drop to this project.+ [ -n "$ds" ] && qs="${qs}&drop_subagent=$(ai_memory_url_encode "$ds")"printf '%s' "$qs"}diff --git a/hooks/claude-code/subagent-start.ps1 b/hooks/claude-code/subagent-start.ps1new file mode 100644index 00000000..fd1fb259--- /dev/null+++ b/hooks/claude-code/subagent-start.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "subagent-start" -Agent "claude-code"+exit 0diff --git a/hooks/claude-code/subagent-start.sh b/hooks/claude-code/subagent-start.shnew file mode 100755index 00000000..f8d341ba--- /dev/null+++ b/hooks/claude-code/subagent-start.sh@@ -0,0 +1,17 @@+#!/bin/sh+# Claude Code subagent-start hook — forwards the event so the server can seed+# the subagent's session id for drop_subagent_captures (so the whole nested+# session, incl. the unmarked tail, is dropped). Mirrors stop.sh.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=subagent-start&agent=claude-code${QS}" >/dev/null 2>&1 || true+printf '{}\n'+exit 0diff --git a/hooks/claude-code/subagent-stop.ps1 b/hooks/claude-code/subagent-stop.ps1new file mode 100644index 00000000..4ab30f6f--- /dev/null+++ b/hooks/claude-code/subagent-stop.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "subagent-stop" -Agent "claude-code"+exit 0diff --git a/hooks/claude-code/subagent-stop.sh b/hooks/claude-code/subagent-stop.shnew file mode 100755index 00000000..fc9b4b41--- /dev/null+++ b/hooks/claude-code/subagent-stop.sh@@ -0,0 +1,16 @@+#!/bin/sh+# Claude Code subagent-stop hook — forwards the event so the server can forget+# the subagent's session id (drop_subagent_captures). Mirrors stop.sh.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=subagent-stop&agent=claude-code${QS}" >/dev/null 2>&1 || true+printf '{}\n'+exit 0diff --git a/hooks/grok/subagent-start.ps1 b/hooks/grok/subagent-start.ps1new file mode 100644index 00000000..d36f471d--- /dev/null+++ b/hooks/grok/subagent-start.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "subagent-start" -Agent "grok"+exit 0diff --git a/hooks/grok/subagent-start.sh b/hooks/grok/subagent-start.shnew file mode 100755index 00000000..ede72f12--- /dev/null+++ b/hooks/grok/subagent-start.sh@@ -0,0 +1,17 @@+#!/bin/sh+# Grok Build CLI subagent-start hook — forwards the event so the server can seed+# the subagent's session id for drop_subagent_captures (so the whole nested+# session, incl. the unmarked tail, is dropped). Mirrors stop.sh.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=subagent-start&agent=grok${QS}" >/dev/null 2>&1 || true+printf '{}\n'+exit 0diff --git a/hooks/grok/subagent-stop.ps1 b/hooks/grok/subagent-stop.ps1new file mode 100644index 00000000..333887ba--- /dev/null+++ b/hooks/grok/subagent-stop.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "subagent-stop" -Agent "grok"+exit 0diff --git a/hooks/grok/subagent-stop.sh b/hooks/grok/subagent-stop.shnew file mode 100755index 00000000..a94ae2e2--- /dev/null+++ b/hooks/grok/subagent-stop.sh@@ -0,0 +1,16 @@+#!/bin/sh+# Grok Build CLI subagent-stop hook — forwards the event so the server can forget+# the subagent's session id (drop_subagent_captures). Mirrors stop.sh.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=subagent-stop&agent=grok${QS}" >/dev/null 2>&1 || true+printf '{}\n'+exit 0diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index fddefd06..339c25c9 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -71,11 +71,13 @@ function Get-AiMemoryMarkerQuery {$ws = $null$proj = $null$strategy = $null+ $dropSubagent = $null$marker = Get-AiMemoryMarkerToml -Cwd $Cwdif ($marker) {$ws = Get-AiMemoryTomlKey -File $marker -Key "workspace"$proj = Get-AiMemoryTomlKey -File $marker -Key "project"$strategy = Get-AiMemoryTomlKey -File $marker -Key "project_strategy"+ $dropSubagent = Get-AiMemoryTomlKey -File $marker -Key "drop_subagent_captures"}# Install-time default baked into the hook command by# `install-hooks --project-strategy` fills the strategy only when no marker@@ -91,6 +93,9 @@ function Get-AiMemoryMarkerQuery {if ($ws) { $qs += "&workspace=$([uri]::EscapeDataString($ws))" }if ($proj) { $qs += "&project=$([uri]::EscapeDataString($proj))" }if ($strategy) { $qs += "&project_strategy=$([uri]::EscapeDataString($strategy))" }+ # Per-project drop_subagent_captures opt-in: forward to the server, which+ # interprets truthiness (1/true/...) and scopes the drop to this project.+ if ($dropSubagent) { $qs += "&drop_subagent=$([uri]::EscapeDataString($dropSubagent))" }return $qs}