Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(ingest): drop configured hook event kinds before storage
Djalma Júnior6c0f5630017c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 59954396..ad22c586 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,20 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]+### Added+- Added `[ingest] drop_events` (env `AI_MEMORY_INGEST__DROP_EVENTS`), an+ opt-in list of hook event kinds the server drops before storing them, next+ to the existing `drop_tool_use_id_prefixes` and `drop_tool_names`. A dropped+ event gets the same 202, `dropped_by_policy` metric and log as the other+ policy drops, before the rate limiter, the ingest semaphore and the+ sanitizer. The default drops nothing. `Config::load` checks each value+ against the typed event kind and rejects unknown kinds and `session-start`+ and `session-end`, which open and close sessions. The motivating case is+ `pre-tool-use`: in one production store about 87% of those observations had+ an empty body, and each pairs with a `post-tool-use` that carries the+ content. With `pre-tool-use` dropped, a session whose only work was a tool+ call that never finished now ends as lifecycle-only. (#PRNUM)+## [3.1.0] - 2026-10-16### Addeddiff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 39ac68c8..a85faae2 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -1294,8 +1294,9 @@ pub struct RoutingSettings {}/// `[ingest]`: tool events the server drops whatever the client sends-/// (#1241). Both lists are empty by default and apply to every project on the-/// server. Validated once by [`Config::load`] into [`Self::drop_list`].+/// (#1241). The tool lists and the event-kind list are all empty by default+/// and apply to every project on the server. Validated once by+/// [`Config::load`] into [`Self::drop_list`].#[derive(Debug, Clone, Default, Serialize, Deserialize)]#[serde(default)]pub struct IngestSettings {@@ -1303,6 +1304,17 @@ pub struct IngestSettings {pub drop_tool_use_id_prefixes: Vec<String>,/// Drop a tool event whose tool name equals one of these exactly.pub drop_tool_names: Vec<String>,+ /// Drop whole hook event kinds, whatever the client sends. Each value is a+ /// hook event kind (e.g. `pre-tool-use`); a matching event is acknowledged+ /// and discarded before it is stored. Empty by default (nothing dropped).+ ///+ /// `session-start` and `session-end` are rejected at load: the router uses+ /// them to open and close a session, so dropping them would strand the+ /// session state machine. Accepts either a TOML/JSON sequence+ /// (`["pre-tool-use"]`) or a comma-separated env string+ /// (`AI_MEMORY_INGEST__DROP_EVENTS=pre-tool-use`).+ #[serde(default, deserialize_with = "deserialize_string_or_vec")]+ pub drop_events: Vec<String>,/// The validated list the hook router checks. Set by [`Config::load`];/// never read from or written to a config file.#[serde(skip)]@@ -2453,6 +2465,7 @@ impl Config {config.ingest.drop_list = ai_memory_hooks::IngestDropList::new(config.ingest.drop_tool_use_id_prefixes.clone(),config.ingest.drop_tool_names.clone(),+ &config.ingest.drop_events,).map_err(|message| anyhow::anyhow!(message))?;// A4 entropy filter thresholds: reject an unusable threshold at startup@@ -4997,7 +5010,8 @@ input_token_safety_margin = {margin}config.ingest.drop_list,ai_memory_hooks::IngestDropList::new(vec!["toolu_plugin_".into()],- vec!["mcp__noisy__poll".into()]+ vec!["mcp__noisy__poll".into()],+ &[]).unwrap());@@ -5016,6 +5030,106 @@ input_token_safety_margin = {margin});}+ /// `[ingest] drop_events` names whole hook event kinds to drop (#1241+ /// sibling). It loads into the same validated list the hook router checks,+ /// defaults to empty (nothing dropped), and rejects a session-state kind+ /// and an unknown kind at load.+ #[test]+ fn ingest_drop_events_load_into_the_router_list_and_reject_bad_kinds() {+ let tmp = TempDir::new().unwrap();+ let config_path = tmp.path().join("config.toml");+ std::fs::write(&config_path, "[ingest]\ndrop_events = [\"pre-tool-use\"]\n").unwrap();+ let config = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap();+ // The raw value survives, and the validated list is built from it.+ assert_eq!(config.ingest.drop_events, vec!["pre-tool-use".to_string()]);+ assert_eq!(+ config.ingest.drop_list,+ ai_memory_hooks::IngestDropList::new(Vec::new(), Vec::new(), &["pre-tool-use".into()])+ .unwrap()+ );++ // A session-state kind fails startup with a clear error (session start…)+ std::fs::write(+ &config_path,+ "[ingest]\ndrop_events = [\"session-start\"]\n",+ )+ .unwrap();+ let error = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap_err();+ assert!(+ format!("{error:#}").contains("session-start")+ && format!("{error:#}").contains("session state"),+ "{error:#}"+ );++ // …and session end.+ std::fs::write(&config_path, "[ingest]\ndrop_events = [\"session-end\"]\n").unwrap();+ let error = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap_err();+ assert!(+ format!("{error:#}").contains("session-end")+ && format!("{error:#}").contains("session state"),+ "{error:#}"+ );++ // An unknown kind fails startup naming the value.+ std::fs::write(&config_path, "[ingest]\ndrop_events = [\"pre-tool-us\"]\n").unwrap();+ let error = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap_err();+ assert!(+ format!("{error:#}").contains("pre-tool-us")+ && format!("{error:#}").contains("not a known hook event kind"),+ "{error:#}"+ );++ // Default: empty, so nothing is dropped.+ assert_eq!(Config::default().ingest.drop_events, Vec::<String>::new());+ assert_eq!(+ Config::default().ingest.drop_list,+ ai_memory_hooks::IngestDropList::default()+ );+ }++ /// The env form of `[ingest] drop_events` (`AI_MEMORY_INGEST__DROP_EVENTS`,+ /// a comma-separated string) loads into the same validated list. Uses the+ /// child-process marker pattern because `std::env::set_var` is unsafe and+ /// forbidden in this crate's multi-threaded test binary.+ #[test]+ fn ingest_drop_events_env_overrides_default() {+ const CHILD_MARKER: &str = "AI_MEMORY_TEST_DROP_EVENTS_CHILD";+ if std::env::var_os(CHILD_MARKER).is_some() {+ let tmp = TempDir::new().unwrap();+ let config_path = tmp.path().join("config.toml");+ // No drop_events in the file; the env var supplies it.+ std::fs::write(&config_path, "[ingest]\n").unwrap();+ let config = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap();+ assert_eq!(+ config.ingest.drop_events,+ vec!["pre-tool-use".to_string(), "stop".to_string()]+ );+ println!("drop-events-env-applied");+ return;+ }++ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .arg("--exact")+ .arg("config::tests::ingest_drop_events_env_overrides_default")+ .arg("--test-threads=1")+ .arg("--nocapture")+ .env(CHILD_MARKER, "1")+ .env("AI_MEMORY_INGEST__DROP_EVENTS", "pre-tool-use,stop")+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "child test failed:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(+ String::from_utf8_lossy(&output.stdout).contains("drop-events-env-applied"),+ "child stdout: {}",+ String::from_utf8_lossy(&output.stdout)+ );+ }+#[test]fn load_accepts_a_small_context_consolidation_budget() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-cli/templates/config.default.toml b/crates/ai-memory-cli/templates/config.default.tomlindex 817cd2a2..7db7a4cf 100644--- a/crates/ai-memory-cli/templates/config.default.toml+++ b/crates/ai-memory-cli/templates/config.default.toml@@ -64,6 +64,34 @@ log_level = "info"# [ingest]# drop_tool_use_id_prefixes = ["toolu_plugin_"]# drop_tool_names = ["mcp__noisy__poll"]+#+# Drop whole hook event kinds instead of individual tool calls. In production+# ~87% of pre-tool-use observations have an empty body and pre-tool-use pairs+# 1:1 with post-tool-use, which carries the content. Dropping a kind also+# turns off everything that kind's processing does:+# user-prompt loses prompts: session summaries, baton open questions+# and profile learning; with pre-tool-use, it also stops+# the project fallback pointer advancing (session-start+# still advances it)+# pre-tool-use loses the pre-call evidence; a call that never produced+# a post-tool-use then leaves no trace, so the session may+# end lifecycle-only+# post-tool-use loses results, the completed-call count and file-work+# evidence+# stop loses the opt-in assistant reply and the+# normal-completion signal; OpenCode loses its turn+# checkpoint/baton+# pre-compact / lose the compaction checkpoint and its rewrite job+# post-compaction (the session is not ended)+# notification loses the observation (search/consolidation context)+# subagent-start / lose the subagent metadata (when stored, they become+# subagent-stop `other` observations)+# session-start and session-end are rejected at startup (they open/close the+# session state machine); any other known kind may be named. The portable+# workstream ledger (`ai-memory run`) is not filtered by this key. Empty by+# default (nothing dropped).+# Env equivalent: AI_MEMORY_INGEST__DROP_EVENTS=pre-tool-use+# drop_events = ["pre-tool-use"]# Strip root-level anyOf/oneOf/allOf from MCP tool input schemas on every# tools/list, even without a `?flavor=moonshot` / `?flavor=bedrock` marker.diff --git a/crates/ai-memory-hooks/src/drop_list.rs b/crates/ai-memory-hooks/src/drop_list.rsindex f694cf3c..fc248d3a 100644--- a/crates/ai-memory-hooks/src/drop_list.rs+++ b/crates/ai-memory-hooks/src/drop_list.rs@@ -1,11 +1,14 @@-//! Server-side drop list for tool events (`[ingest]`, #1241).+//! Server-side ingest drop list (`[ingest]`, #1241).//!-//! An operator can name tool calls the server should never store, whatever the-//! client sends: tool-use ids by prefix (Claude Code marks plugin tool calls-//! with their own id prefix) and tool names exactly. A matching event is-//! acknowledged like any other policy drop, before it reaches the sanitizer,-//! the rate limiter, the ingest semaphore or storage. The lists are read once-//! at startup and bounded, so the check stays cheap on the hook path.+//! An operator can name what the server should never store, whatever the+//! client sends: tool calls by tool-use id prefix (Claude Code marks plugin+//! tool calls with their own id prefix) and tool names exactly, plus whole+//! hook event kinds (`drop_events`). A matching event is acknowledged like+//! any other policy drop — the tool lists right after the client capture+//! protocol, the whole kinds right after the subagent exclusion, in both the+//! single and the batch ingress — before it reaches the rate limiter, the+//! ingest semaphore, the sanitizer or storage. The lists are read once at+//! startup and bounded, so the checks stay cheap on the hook path.use crate::payload::{HookEnvelope, HookEvent};@@ -14,11 +17,23 @@ pub const MAX_DROP_ENTRIES: usize = 64;/// Longest entry, in characters.pub const MAX_DROP_ENTRY_CHARS: usize = 128;-/// Tool events the server drops by tool-use id prefix or exact tool name.+/// Tool events the server drops by tool-use id prefix or exact tool name,+/// plus whole hook event kinds dropped outright (`drop_events`). A matching+/// event is acknowledged like any other policy drop, before it reaches the+/// sanitizer, the rate limiter, the ingest semaphore or storage. The lists+/// are read once at startup and bounded, so the checks stay cheap on the hook+/// path.+///+/// The two checks run at different router positions, on purpose: [`matches`]+/// (the tool id/name lists) runs right after the client capture protocol, and+/// [`matches_event_kind`] runs right after the subagent exclusion, so a+/// marked subagent event still seeds the tracking set its unmarked tail is+/// dropped against even when its kind is listed.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct IngestDropList {tool_use_id_prefixes: Vec<String>,tool_names: Vec<String>,+ drop_events: IngestDropEvents,}impl IngestDropList {@@ -28,16 +43,27 @@ impl IngestDropList {/// Returns a message naming the offending list when either holds more than/// [`MAX_DROP_ENTRIES`] entries, or an entry that is blank, longer than/// [`MAX_DROP_ENTRY_CHARS`] characters, or contains a control character.- pub fn new(tool_use_id_prefixes: Vec<String>, tool_names: Vec<String>) -> Result<Self, String> {+ /// A `drop_events` entry that is not a droppable hook event kind is+ /// rejected with a message naming it.+ pub fn new(+ tool_use_id_prefixes: Vec<String>,+ tool_names: Vec<String>,+ drop_events: &[String],+ ) -> Result<Self, String> {validate("drop_tool_use_id_prefixes", &tool_use_id_prefixes)?;validate("drop_tool_names", &tool_names)?;+ let drop_events = IngestDropEvents::new(drop_events)?;Ok(Self {tool_use_id_prefixes,tool_names,+ drop_events,})}- /// Whether this tool event is on the list. Only tool events can match.+ /// Whether this event's tool id or name is on the tool drop lists.+ ///+ /// Matches only tool events (`pre-tool-use` / `post-tool-use`); whole-kind+ /// drops (`drop_events`) are checked by [`Self::matches_event_kind`].#[must_use]pub fn matches(&self, env: &HookEnvelope) -> bool {if self.tool_use_id_prefixes.is_empty() && self.tool_names.is_empty() {@@ -66,6 +92,117 @@ impl IngestDropList {}name.is_some_and(|name| self.tool_names.contains(&name))}++ /// Whether this event's whole kind is dropped by `[ingest] drop_events`.+ ///+ /// Unlike [`Self::matches`] this ignores the tool id/name and looks only+ /// at the event kind, so it applies to every tool, agent and payload+ /// shape. The router runs it right after the subagent exclusion (so a+ /// marked subagent event still seeds the tail tracking) and before the+ /// rate limiter, the ingest semaphore, the sanitizer and storage.+ #[must_use]+ pub fn matches_event_kind(&self, env: &HookEnvelope) -> bool {+ self.drop_events.matches(env)+ }+}++/// Hook event kinds the server drops outright (`[ingest] drop_events`).+///+/// Unlike [`IngestDropList`] (which matches on a tool's id or name within a+/// tool event), this drops a whole event *kind* whatever the client sends. The+/// motivating case is `pre-tool-use`: on claude-code its body is at most+/// `tool_family`/`tool_call_id` and is empty when the call carries no+/// `tool_input`, while its 1:1 `post-tool-use` pair carries the content. An+/// operator who wants to stop storing the redundant half can name the kind+/// here. A matching event is acknowledged like any other policy drop, before+/// it reaches the sanitizer, the rate limiter, the ingest semaphore or+/// storage. The set is read once at startup and bounded, so the check stays+/// cheap on the hook path.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct IngestDropEvents {+ kinds: Vec<HookEvent>,+}++/// The droppable kinds, as their canonical kebab-case wire names, for error+/// and config docs.+const DROPPABLE_KINDS: &str = "user-prompt, pre-tool-use, post-tool-use, \+ pre-compact, post-compaction, notification, stop, subagent-start, \+ subagent-stop";++/// Whether an event kind may be named in `[ingest] drop_events`.+///+/// `session-start` and `session-end` are excluded: the router uses them to+/// open and close a session, so dropping them would strand the session state+/// machine (a session never opened, or never ended). The unrecognized-event+/// bucket (`other`) is excluded too: naming it would drop every event without+/// a typed kind — a much broader drop than an operator asking for one kind+/// intends. A kind not listed here is intentionally non-droppable: when a new+/// variant is added to [`HookEvent`], the reviewer must consciously decide+/// whether it may be dropped rather than have it silently join the set.+const fn is_droppable_event(event: HookEvent) -> bool {+ matches!(+ event,+ HookEvent::UserPrompt+ | HookEvent::PreToolUse+ | HookEvent::PostToolUse+ | HookEvent::PreCompact+ | HookEvent::PostCompaction+ | HookEvent::Notification+ | HookEvent::Stop+ | HookEvent::SubagentStart+ | HookEvent::SubagentStop+ )+}++impl IngestDropEvents {+ /// Validate and build the drop set.+ ///+ /// Each value is parsed with the typed [`HookEvent::parse`] (never a free+ /// string compare). Duplicates collapse to one kind. The set is bounded by+ /// the number of droppable kinds, so no separate size limit is needed.+ ///+ /// # Errors+ /// Returns a message naming the offending value when it is blank, not a+ /// known hook event kind, or a kind that drives session state.+ pub fn new(raw: &[String]) -> Result<Self, String> {+ let mut kinds: Vec<HookEvent> = Vec::with_capacity(raw.len());+ for value in raw {+ if value.trim().is_empty() {+ return Err("[ingest].drop_events has a blank entry".to_string());+ }+ let event = HookEvent::parse(value);+ if !is_droppable_event(event) {+ let reason = match event {+ HookEvent::SessionStart | HookEvent::SessionEnd => {+ "drives session state (the router opens and closes sessions with it) \+ and cannot be dropped"+ }+ HookEvent::Other => "is not a known hook event kind",+ // A kind outside the droppable set that is neither+ // session-state nor the unrecognized bucket: currently+ // none, but a newly added enum variant lands here so the+ // failure is explicit rather than silently droppable.+ _ => "cannot be dropped",+ };+ return Err(format!(+ "[ingest].drop_events: {value} {reason}. Droppable kinds: \+ {DROPPABLE_KINDS}"+ ));+ }+ if !kinds.contains(&event) {+ kinds.push(event);+ }+ }+ Ok(Self { kinds })+ }++ /// Whether this event's kind is dropped. Unlike [`IngestDropList::matches`]+ /// this ignores the tool id/name and looks only at the event kind, so it+ /// applies to every tool, agent and payload shape.+ #[must_use]+ pub fn matches(&self, env: &HookEnvelope) -> bool {+ !self.kinds.is_empty() && self.kinds.contains(&env.event)+ }}fn validate(list: &str, entries: &[String]) -> Result<(), String> {@@ -117,6 +254,7 @@ mod tests {IngestDropList::new(vec!["toolu_plugin_".into()],vec!["mcp__noisy__poll".into()],+ &[],).unwrap()}@@ -158,7 +296,8 @@ mod tests {#[test]fn each_agent_is_matched_on_its_own_tool_fields() {- let list = IngestDropList::new(vec!["plugin-".into()], vec!["noisy_poll".into()]).unwrap();+ let list =+ IngestDropList::new(vec!["plugin-".into()], vec!["noisy_poll".into()], &[]).unwrap();// OpenCode, Pi and OMP carry the call id as `callID` and the name as `tool`.let opencode = agent_event("opencode",@@ -237,13 +376,126 @@ mod tests {#[test]fn entries_are_bounded_and_must_be_printable() {- assert!(IngestDropList::new(vec![" ".into()], Vec::new()).is_err());- assert!(IngestDropList::new(Vec::new(), vec!["a\nb".into()]).is_err());+ assert!(IngestDropList::new(vec![" ".into()], Vec::new(), &[]).is_err());+ assert!(IngestDropList::new(Vec::new(), vec!["a\nb".into()], &[]).is_err());assert!(- IngestDropList::new(vec!["x".repeat(MAX_DROP_ENTRY_CHARS + 1)], Vec::new()).is_err()+ IngestDropList::new(vec!["x".repeat(MAX_DROP_ENTRY_CHARS + 1)], Vec::new(), &[])+ .is_err());let too_many = (0..=MAX_DROP_ENTRIES).map(|i| format!("t{i}")).collect();- assert!(IngestDropList::new(Vec::new(), too_many).is_err());- assert!(IngestDropList::new(vec!["x".repeat(MAX_DROP_ENTRY_CHARS)], Vec::new()).is_ok());+ assert!(IngestDropList::new(Vec::new(), too_many, &[]).is_err());+ assert!(+ IngestDropList::new(vec!["x".repeat(MAX_DROP_ENTRY_CHARS)], Vec::new(), &[]).is_ok()+ );+ }++ #[test]+ fn drop_events_default_drops_nothing() {+ let list = IngestDropEvents::default();+ assert!(list.kinds.is_empty());+ // Nothing is dropped by default: every kind, incl. pre-tool-use, matches no.+ assert!(!list.matches(&event(+ "pre-tool-use",+ serde_json::json!({ "session_id": "s" })+ )));+ assert!(!list.matches(&event(+ "post-tool-use",+ serde_json::json!({ "session_id": "s" })+ )));+ }++ #[test]+ fn drop_events_named_kind_matches_its_events_only() {+ let list = IngestDropEvents::new(&["pre-tool-use".into()]).unwrap();+ // The named kind is dropped, on any agent and any payload shape.+ assert!(list.matches(&event(+ "pre-tool-use",+ serde_json::json!({ "session_id": "s" })+ )));+ assert!(list.matches(&agent_event(+ "opencode",+ "pre-tool-use",+ serde_json::json!({ "sessionID": "s" })+ )));+ // Its 1:1 pair and every other kind are untouched.+ assert!(!list.matches(&event(+ "post-tool-use",+ serde_json::json!({ "session_id": "s" })+ )));+ assert!(!list.matches(&event(+ "user-prompt",+ serde_json::json!({ "session_id": "s", "prompt": "hi" })+ )));+ assert!(!list.matches(&event("session-start", serde_json::json!({}))));+ assert!(!list.matches(&event(+ "session-end",+ serde_json::json!({ "session_id": "s" })+ )));+ assert!(!list.matches(&event("stop", serde_json::json!({ "session_id": "s" }))));+ }++ #[test]+ fn drop_events_accepts_case_and_underscore_wire_spellings() {+ // The typed parser, not a string compare: every accepted spelling of+ // the same kind collapses to one entry and matches.+ let list = IngestDropEvents::new(&[+ "PreToolUse".into(),+ "pre_tool_use".into(),+ "pre-tool-use".into(),+ ])+ .unwrap();+ assert_eq!(list.kinds.len(), 1, "duplicate kinds collapse");+ assert!(list.matches(&event(+ "preToolUse",+ serde_json::json!({ "session_id": "s" })+ )));+ }++ #[test]+ fn drop_events_rejects_session_state_kinds() {+ for value in [+ "session-start",+ "session-end",+ "SessionStart",+ "session_end",+ ] {+ let error = IngestDropEvents::new(&[value.into()]).unwrap_err();+ assert!(+ error.contains(value) && error.contains("session state"),+ "{value}: {error}"+ );+ }+ }++ #[test]+ fn drop_events_rejects_unknown_and_unrecognized_bucket() {+ for value in ["bogus", "", "other", "notification-2"] {+ let error = IngestDropEvents::new(&[value.into()]).unwrap_err();+ assert!(error.contains("drop_events"), "{value}: {error}");+ }+ // The error names the offending value for an operator to fix.+ let error = IngestDropEvents::new(&["pre-tool-us".into()]).unwrap_err();+ assert!(+ error.contains("pre-tool-us"),+ "unknown kinds name the value: {error}"+ );+ assert!(+ error.contains("Droppable kinds"),+ "and list the valid ones: {error}"+ );+ }++ #[test]+ fn drop_events_multiple_kinds() {+ let list = IngestDropEvents::new(&["pre-tool-use".into(), "stop".into()]).unwrap();+ assert!(list.matches(&event(+ "pre-tool-use",+ serde_json::json!({ "session_id": "s" })+ )));+ assert!(list.matches(&event("stop", serde_json::json!({ "session_id": "s" }))));+ assert!(!list.matches(&event(+ "post-tool-use",+ serde_json::json!({ "session_id": "s" })+ )));}}diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex fd834892..d2a375b8 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -552,7 +552,10 @@ pub struct HookState {pub profile: ai_memory_core::profile::ProfileSettings,/// `[ingest]` drop list: tool events matching a listed tool-use id prefix/// or tool name are acknowledged and dropped before any capacity is spent- /// (#1241). Empty by default.+ /// (#1241), checked right after the client capture protocol; events whose+ /// whole kind is listed (`drop_events`, e.g. `pre-tool-use`) are dropped+ /// the same way, checked right after the subagent exclusion so a marked+ /// subagent event still seeds its tail tracking. Empty by default.pub ingest_drop_list: crate::drop_list::IngestDropList,}@@ -695,8 +698,9 @@ async fn admit_hook(HookProcessingOutcome::DroppedInvalid.record(&state.ingest_metrics);return (StatusCode::ACCEPTED, "cursor draft placeholder dropped");}- // The operator's server-side drop list (#1241): acknowledged as a policy- // drop before the rate limiter or the semaphore, so it costs nothing.+ // The operator's server-side tool drop list (#1241): acknowledged as a+ // policy drop before the rate limiter or the semaphore, so it costs+ // nothing.if state.ingest_drop_list.matches(&env) {HookProcessingOutcome::DroppedPolicy.record(&state.ingest_metrics);return (StatusCode::ACCEPTED, "ingest drop list");@@ -724,6 +728,14 @@ async fn admit_hook(HookProcessingOutcome::DroppedSubagent.record(&state.ingest_metrics);return (StatusCode::ACCEPTED, "subagent capture dropped");}+ // Whole-kind drops (`[ingest] drop_events`): after the subagent exclusion,+ // so a marked subagent event still seeds the tracking set its unmarked+ // tail is dropped against, but before the rate limiter and the semaphore,+ // so a dropped event still costs nothing.+ if state.ingest_drop_list.matches_event_kind(&env) {+ HookProcessingOutcome::DroppedPolicy.record(&state.ingest_metrics);+ return (StatusCode::ACCEPTED, "ingest drop list");+ }let Ok(permit) = state.ingest_semaphore.clone().try_acquire_owned() else {state.ingest_metrics.record_shed_saturated();warn!("hook ingest saturated; dropping event with 429");@@ -978,7 +990,7 @@ async fn handle_hook_batch(accepted_indices.push(idx);continue;}- // Server-side drop list (#1241), acknowledged like a policy drop.+ // Server-side tool drop list (#1241), acknowledged like a policy drop.if state.ingest_drop_list.matches(&env) {HookProcessingOutcome::DroppedPolicy.record(&state.ingest_metrics);results.push(HookBatchResult {@@ -1000,6 +1012,18 @@ async fn handle_hook_batch(accepted_indices.push(idx);continue;}+ // Whole-kind drops (`[ingest] drop_events`): after the subagent+ // exclusion (a marked event still seeds its tail tracking), before the+ // semaphore, the rate limiter and storage.+ if state.ingest_drop_list.matches_event_kind(&env) {+ HookProcessingOutcome::DroppedPolicy.record(&state.ingest_metrics);+ results.push(HookBatchResult {+ index: idx,+ outcome: HookProcessingOutcome::DroppedPolicy,+ });+ accepted_indices.push(idx);+ continue;+ }// An event with no session id that is not a SessionStart can never be// stored. Reporting it as failed made the drain retry it until its// attempt budget ran out, stalling every item queued behind it (#1062),@@ -8730,6 +8754,7 @@ pub(crate) mod tests {state.ingest_drop_list = crate::drop_list::IngestDropList::new(vec!["toolu_plugin_".into()],vec!["mcp__noisy__poll".into()],+ &[],).unwrap();}@@ -8828,6 +8853,440 @@ pub(crate) mod tests {assert_eq!(snap.accepted, 1, "control: the unlisted item is ingested");}+ /// Install a `[ingest] drop_events` list dropping one whole event kind.+ fn with_drop_events(state: &mut HookState, kinds: &[&str]) {+ state.ingest_drop_list = crate::drop_list::IngestDropList::new(+ Vec::new(),+ Vec::new(),+ &kinds.iter().map(|s| (*s).to_string()).collect::<Vec<_>>(),+ )+ .unwrap();+ }++ /// Poll a session's stored observations until every kind in `expected` is+ /// present (the hook path stores through a spawned task), or give up after+ /// a generous deadline and return what landed. A session-end event also+ /// creates a handoff (a wiki write + git checkpoint), which is slower than+ /// a plain observation store, so the deadline is generous and the poll+ /// waits for the specific kinds rather than a bare count.+ async fn wait_for_kinds(+ state: &HookState,+ sid: &str,+ expected: &[ObservationKind],+ ) -> Vec<ai_memory_core::Observation> {+ // The store keys observations on the native id resolved the way the+ // hook path does (`from_native`: a UUID as-is, anything else hashed to+ // a deterministic v5), so the lookup must use the same rule rather+ // than a bare UUID parse.+ let sid = SessionId::from_native(sid);+ for _ in 0..300 {+ let obs = state.reader.observations_for_session(sid).await.unwrap();+ let kinds: Vec<ObservationKind> = obs.iter().map(|o| o.kind).collect();+ if expected.iter().all(|kind| kinds.contains(kind)) {+ return obs;+ }+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ state.reader.observations_for_session(sid).await.unwrap()+ }++ /// #1241 sibling: naming a whole event kind in `[ingest] drop_events`+ /// drops every event of that kind (any agent, any payload) while the rest+ /// are acknowledged and stored. `pre-tool-use` is the motivating case: its+ /// 1:1 `post-tool-use` pair carries the content; only a call that never+ /// finished leaves no trace.+ #[tokio::test]+ async fn the_ingest_drop_events_drops_the_named_kind_and_keeps_the_rest() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ with_drop_events(&mut state, &["pre-tool-use"]);+ let metrics = state.ingest_metrics.clone();+ let state = Arc::new(state);+ let session = "drop-events-1";+ let cwd = tmp.path().to_path_buf();+ let query = |event: &str| HookQuery {+ event: event.into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ };+ let body = |extra: serde_json::Value| {+ let mut b = serde_json::json!({ "session_id": session, "cwd": cwd.to_string_lossy().into_owned() });+ b.as_object_mut()+ .unwrap()+ .extend(extra.as_object().cloned().unwrap());+ b+ };++ // The named kind is dropped before any capacity is spent.+ let (status, reason) = admit_hook(+ state.clone(),+ query("pre-tool-use"),+ None,+ None,+ None,+ HeaderMap::new(),+ body(serde_json::json!({ "tool_name": "Read", "tool_use_id": "toolu_1" })),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "ingest drop list"),+ "pre-tool-use is dropped by its kind"+ );++ // Its 1:1 pair, the prompt, and a lifecycle event are all kept.+ for (event, extra) in [+ (+ "post-tool-use",+ serde_json::json!({ "tool_name": "Read", "tool_use_id": "toolu_1" }),+ ),+ (+ "user-prompt-submit",+ serde_json::json!({ "prompt": "do the thing" }),+ ),+ ("session-end", serde_json::json!({})),+ ] {+ let (status, reason) = admit_hook(+ state.clone(),+ query(event),+ None,+ None,+ None,+ HeaderMap::new(),+ body(extra),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "queued"),+ "{event} must not be dropped by the pre-tool-use drop"+ );+ }++ let snap = metrics.snapshot();+ assert_eq!(+ snap.dropped_by_policy, 1,+ "only the named kind is a policy drop"+ );+ assert_eq!(+ snap.accepted, 3,+ "the pair, the prompt and session-end are ingested"+ );++ // What actually landed in the store: the kept tool pair and the+ // prompt, and no pre-tool-use. We assert storage only for these: the+ // session-end event is handled concurrently and, if its task runs+ // before the substantive stores, treats the session as lifecycle-only,+ // so its own observation is not a reliable assertion. It is proven+ // *not dropped* by the "queued" response above.+ let obs = wait_for_kinds(+ &state,+ session,+ &[ObservationKind::PostToolUse, ObservationKind::UserPrompt],+ )+ .await;+ let kinds: Vec<_> = obs.iter().map(|o| o.kind).collect();+ assert!(+ !kinds.contains(&ObservationKind::PreToolUse),+ "the dropped kind must not be stored: {kinds:?}"+ );+ assert!(kinds.contains(&ObservationKind::PostToolUse), "{kinds:?}");+ assert!(kinds.contains(&ObservationKind::UserPrompt), "{kinds:?}");+ }++ /// The batch route drops the named kind as committed (so the client clears+ /// it from its spool) and stores the rest — same treatment as the tool drop+ /// list.+ #[tokio::test]+ async fn the_ingest_drop_events_applies_to_hook_batches() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ with_drop_events(&mut state, &["pre-tool-use"]);+ let metrics = state.ingest_metrics.clone();+ let response = handle_hook_batch(+ State(Arc::new(state)),+ None,+ None,+ None,+ HeaderMap::new(),+ Json(vec![+ HookBatchItem {+ url: "http://h/hook?event=pre-tool-use&agent=claude-code".into(),+ body: serde_json::json!({ "session_id": "drop-ev-b", "tool_name": "Read", "tool_use_id": "toolu_9" }),+ },+ HookBatchItem {+ url: "http://h/hook?event=post-tool-use&agent=claude-code".into(),+ body: serde_json::json!({ "session_id": "drop-ev-b", "tool_name": "Read", "tool_use_id": "toolu_9" }),+ },+ HookBatchItem {+ url: "http://h/hook?event=user-prompt-submit&agent=claude-code".into(),+ body: serde_json::json!({ "session_id": "drop-ev-b", "prompt": "hi" }),+ },+ ]),+ )+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::OK);+ let snap = metrics.snapshot();+ assert_eq!(snap.dropped_by_policy, 1, "the named kind is a policy drop");+ assert_eq!(snap.accepted, 2, "the pair and the prompt are ingested");+ }++ /// Sibling of the #1241 tool-list capacity test: with the semaphore+ /// exhausted, a whole-kind drop still answers 202 while an ordinary event+ /// of a kept kind gets the 429 (control).+ #[tokio::test]+ async fn the_ingest_drop_events_drops_before_any_capacity_is_spent() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ with_drop_events(&mut state, &["pre-tool-use"]);+ state.ingest_semaphore = Arc::new(tokio::sync::Semaphore::new(0));+ let metrics = state.ingest_metrics.clone();+ let state = Arc::new(state);+ let query = |event: &str| HookQuery {+ event: event.into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ };++ // The named kind is dropped before any capacity is spent.+ let (status, reason) = admit_hook(+ state.clone(),+ query("pre-tool-use"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "session_id": "drop-ev-sat", "tool_name": "Read", "tool_use_id": "toolu_1" }),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "ingest drop list"),+ "the named kind is dropped before any capacity is spent"+ );++ // Control: a kept kind needs capacity and gets the 429.+ let (status, _) = admit_hook(+ state.clone(),+ query("post-tool-use"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "session_id": "drop-ev-sat", "tool_name": "Read", "tool_use_id": "toolu_1" }),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::TOO_MANY_REQUESTS,+ "control: a kept kind needs capacity"+ );++ let snap = metrics.snapshot();+ assert_eq!(snap.dropped_by_policy, 1);+ assert_eq!(snap.accepted, 0, "the kind drop spends no ingress capacity");+ }++ /// Whole-kind drops spend no per-source rate token: with burst 1 and no+ /// refill, dropped events of the named kind never exhaust the budget, so+ /// the source's first kept event is still admitted (control: its next+ /// kept event is over budget).+ #[tokio::test]+ async fn the_ingest_drop_events_consumes_no_rate_budget() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ with_drop_events(&mut state, &["pre-tool-use"]);+ // burst=1, ~no refill within the test window (same pattern as+ // `handle_hook_rate_limits_a_flooding_source_but_not_others`).+ state.ingest_rate = Arc::new(tokio::sync::Mutex::new(IngestRateLimiter::new(0.001, 1.0)));+ let metrics = state.ingest_metrics.clone();+ let state = Arc::new(state);+ let query = |event: &str| HookQuery {+ event: event.into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ };++ // Two events of the named kind: both dropped, neither spends a token.+ for _ in 0..2 {+ let (status, reason) = admit_hook(+ state.clone(),+ query("pre-tool-use"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "session_id": "drop-ev-rl", "tool_name": "Read", "tool_use_id": "toolu_1" }),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "ingest drop list"),+ "the named kind is dropped without spending a rate token"+ );+ }++ // The source's first kept event still gets its single token.+ let (status, reason) = admit_hook(+ state.clone(),+ query("post-tool-use"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "session_id": "drop-ev-rl", "tool_name": "Read", "tool_use_id": "toolu_1" }),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "queued"),+ "kind drops spend no rate token"+ );++ // Control: the source's next kept event is over budget.+ let (status, _) = admit_hook(+ state.clone(),+ query("user-prompt-submit"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "session_id": "drop-ev-rl", "prompt": "over budget" }),+ )+ .await;+ assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);++ let snap = metrics.snapshot();+ assert_eq!(snap.dropped_by_policy, 2);+ assert_eq!(snap.accepted, 1);+ assert_eq!(snap.shed_rate_limited, 1);+ }++ /// The batch ack contract for whole-kind drops: a mixed batch reports the+ /// per-index outcomes (`dropped_policy` for the named kind, `stored` for+ /// the kept ones), persists only the kept events, and counts the drop.+ #[tokio::test]+ async fn the_ingest_drop_events_batch_reports_per_index_outcomes_and_only_stores_the_kept() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ with_drop_events(&mut state, &["pre-tool-use"]);+ let metrics = state.ingest_metrics.clone();+ let state = Arc::new(state);+ let response = handle_hook_batch(+ State(state.clone()),+ None,+ None,+ None,+ HeaderMap::new(),+ Json(vec![+ HookBatchItem {+ url: "http://h/hook?event=pre-tool-use&agent=claude-code".into(),+ body: serde_json::json!({ "session_id": "drop-ev-ack", "tool_name": "Read", "tool_use_id": "toolu_9" }),+ },+ HookBatchItem {+ url: "http://h/hook?event=post-tool-use&agent=claude-code".into(),+ body: serde_json::json!({ "session_id": "drop-ev-ack", "tool_name": "Read", "tool_use_id": "toolu_9" }),+ },+ HookBatchItem {+ url: "http://h/hook?event=user-prompt-submit&agent=claude-code".into(),+ body: serde_json::json!({ "session_id": "drop-ev-ack", "prompt": "hi" }),+ },+ ]),+ )+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)+ .await+ .unwrap();+ let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(+ ack["accepted"], 3,+ "every item is acknowledged (dropped ones too)"+ );+ let results = ack["results"].as_array().unwrap();+ assert_eq!(results.len(), 3, "one result per acknowledged index");+ assert_eq!(results[0]["index"], 0);+ assert_eq!(+ results[0]["outcome"], "dropped_policy",+ "the named kind is a policy drop: {ack}"+ );+ assert_eq!(results[1]["index"], 1);+ assert_eq!(results[1]["outcome"], "stored");+ assert_eq!(results[2]["index"], 2);+ assert_eq!(results[2]["outcome"], "stored");++ // The batch processes inline, so the kept events are persisted by the+ // time the response returns — and the dropped one is not.+ let sid = SessionId::from_native("drop-ev-ack");+ let obs = state.reader.observations_for_session(sid).await.unwrap();+ let kinds: Vec<_> = obs.iter().map(|o| o.kind).collect();+ assert!(+ !kinds.contains(&ObservationKind::PreToolUse),+ "the dropped kind must not be stored: {kinds:?}"+ );+ assert!(kinds.contains(&ObservationKind::PostToolUse), "{kinds:?}");+ assert!(kinds.contains(&ObservationKind::UserPrompt), "{kinds:?}");++ let snap = metrics.snapshot();+ assert_eq!(snap.dropped_by_policy, 1);+ assert_eq!(snap.accepted, 2);+ }++ /// The drop is specific to the named kind: with `stop` dropped, tool events+ /// and prompts are untouched (control for a too-broad drop).+ #[tokio::test]+ async fn the_ingest_drop_events_leaves_other_kinds_untouched() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ with_drop_events(&mut state, &["stop"]);+ let metrics = state.ingest_metrics.clone();+ let state = Arc::new(state);+ let query = |event: &str| HookQuery {+ event: event.into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ };+ // Tool events and the prompt are not named, so they are ingested.+ for event in ["pre-tool-use", "post-tool-use", "user-prompt-submit"] {+ let (status, reason) = admit_hook(+ state.clone(),+ query(event),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "session_id": "drop-ev-c", "tool_name": "Read" }),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "queued"),+ "{event} is not named and must be ingested"+ );+ }+ // The named kind is dropped.+ let (status, reason) = admit_hook(+ state.clone(),+ query("stop"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "session_id": "drop-ev-c" }),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "ingest drop list"),+ "the named kind is dropped"+ );+ let snap = metrics.snapshot();+ assert_eq!(snap.dropped_by_policy, 1);+ assert_eq!(snap.accepted, 3);+ }+/// Both accept-but-drop branches, in one batch: a client-protocol Drop and/// the subagent tail-drop. They are separate call sites in/// `handle_hook_batch`, so a single-branch case would leave the other@@ -9723,6 +10182,281 @@ pub(crate) mod tests {);}+ /// `[ingest] drop_events` and the subagent exclusion compose (single+ /// path): with `subagent-start` itself named in the drop list, the marked+ /// start still seeds the tracking set — the exclusion runs first — so the+ /// unmarked tail of the subagent session is dropped too. Control: a+ /// non-subagent session's prompt is stored.+ #[tokio::test]+ async fn the_ingest_drop_events_keeps_dropping_the_unmarked_subagent_tail() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ with_drop_events(&mut state, &["subagent-start"]);+ let metrics = state.ingest_metrics.clone();+ let state = Arc::new(state);+ let query = |event: &str| HookQuery {+ event: event.into(),+ agent: Some("grok".into()),+ drop_subagent: Some("1".into()),+ ..Default::default()+ };++ // The marked start is dropped (as a subagent capture) and seeds+ // "sub-drop-ev" — it is never stored, whatever the drop list says.+ let (status, reason) = admit_hook(+ state.clone(),+ query("subagent-start"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "sessionId": "sub-drop-ev" }),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "subagent capture dropped"),+ "the marked start seeds the tracking before it can be dropped by kind"+ );++ // The unmarked tail of the same session is dropped via tracking.+ let (status, reason) = admit_hook(+ state.clone(),+ query("user-prompt-submit"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "sessionId": "sub-drop-ev", "prompt": "go" }),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "subagent capture dropped"),+ "the unmarked tail of a tracked subagent session is dropped"+ );++ // Control: a non-subagent session's prompt is kept.+ let (status, reason) = admit_hook(+ state.clone(),+ query("user-prompt-submit"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "sessionId": "top-drop-ev", "prompt": "top" }),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "queued"),+ "a non-subagent session is unaffected"+ );++ let snap = metrics.snapshot();+ assert_eq!(snap.dropped_by_policy, 2);+ assert_eq!(snap.accepted, 1);++ // The tail never reached the store; the control prompt did.+ let sub_sid = SessionId::from_native("sub-drop-ev");+ assert!(+ state+ .reader+ .observations_for_session(sub_sid)+ .await+ .unwrap()+ .is_empty(),+ "the unmarked tail of a tracked subagent session is not stored"+ );+ let obs = wait_for_kinds(&state, "top-drop-ev", &[ObservationKind::UserPrompt]).await;+ let kinds: Vec<_> = obs.iter().map(|o| o.kind).collect();+ assert!(kinds.contains(&ObservationKind::UserPrompt), "{kinds:?}");+ }++ /// `[ingest] drop_events` and the subagent exclusion compose (batch+ /// path): same scenario as the single-path sibling, with the per-index+ /// outcomes asserted from the ack.+ #[tokio::test]+ async fn the_ingest_drop_events_keeps_dropping_the_unmarked_subagent_tail_in_batches() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ with_drop_events(&mut state, &["subagent-start"]);+ let metrics = state.ingest_metrics.clone();+ let state = Arc::new(state);+ let items = vec![+ // (1) the marked start seeds the session and is dropped;+ // (2) the unmarked tail of that session is dropped via tracking;+ // (3) an unmarked prompt of a non-subagent session is kept.+ HookBatchItem {+ url: "http://h/hook?event=subagent-start&agent=grok&drop_subagent=1".into(),+ body: serde_json::json!({ "sessionId": "sub-b-drop-ev" }),+ },+ HookBatchItem {+ url: "http://h/hook?event=user-prompt-submit&agent=grok&drop_subagent=1".into(),+ body: serde_json::json!({ "sessionId": "sub-b-drop-ev", "prompt": "go" }),+ },+ HookBatchItem {+ url: "http://h/hook?event=user-prompt-submit&agent=grok&drop_subagent=1".into(),+ body: serde_json::json!({ "sessionId": "top-b-drop-ev", "prompt": "top" }),+ },+ ];++ 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(), 64 * 1024)+ .await+ .unwrap();+ let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(+ ack["accepted"], 3,+ "all three items are acknowledged: {ack}"+ );+ let results = ack["results"].as_array().unwrap();+ assert_eq!(+ results[0]["outcome"], "dropped_subagent",+ "the marked start seeds the tracking and is dropped: {ack}"+ );+ assert_eq!(+ results[1]["outcome"], "dropped_subagent",+ "the unmarked tail of the tracked session still drops: {ack}"+ );+ assert_eq!(+ results[2]["outcome"], "stored",+ "a non-subagent prompt is kept: {ack}"+ );++ let sub_sid = SessionId::from_native("sub-b-drop-ev");+ assert!(+ state+ .reader+ .observations_for_session(sub_sid)+ .await+ .unwrap()+ .is_empty(),+ "the unmarked tail of a tracked subagent session is not stored"+ );+ let top_envelope = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "user-prompt-submit".into(),+ agent: Some("grok".into()),+ ..Default::default()+ },+ serde_json::json!({ "sessionId": "top-b-drop-ev", "prompt": "top" }),+ );+ let top_sid = resolve_session_id(&top_envelope).unwrap();+ let obs = state+ .reader+ .observations_for_session(top_sid)+ .await+ .unwrap();+ let kinds: Vec<_> = obs.iter().map(|o| o.kind).collect();+ assert!(kinds.contains(&ObservationKind::UserPrompt), "{kinds:?}");++ let snap = metrics.snapshot();+ assert_eq!(snap.dropped_by_policy, 2);+ assert_eq!(snap.accepted, 1);+ }++ /// A marked subagent event whose kind is listed in `[ingest] drop_events`+ /// still seeds the tracking set: the subagent exclusion runs before the+ /// whole-kind drop, so the unmarked tail of its session is dropped even+ /// though the marking event itself was a named kind. Control: an unmarked+ /// prompt of a never-seeded session is kept.+ #[tokio::test]+ async fn a_marked_event_of_a_dropped_kind_still_seeds_subagent_tracking() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ with_drop_events(&mut state, &["pre-tool-use"]);+ let metrics = state.ingest_metrics.clone();+ let state = Arc::new(state);+ let query = |event: &str| HookQuery {+ event: event.into(),+ agent: Some("grok".into()),+ drop_subagent: Some("1".into()),+ ..Default::default()+ };++ // The marked pre-tool-use: its kind is dropped, but the exclusion+ // (which runs first) seeds the session.+ let (status, reason) = admit_hook(+ state.clone(),+ query("pre-tool-use"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "sessionId": "seed-drop-ev", "subagentType": "general-purpose", "toolName": "x" }),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "subagent capture dropped"),+ "the marked event seeds the tracking before it is dropped"+ );++ // The unmarked tail of the same session is dropped via tracking —+ // not by the kind list (user-prompt-submit is not named).+ let (status, reason) = admit_hook(+ state.clone(),+ query("user-prompt-submit"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "sessionId": "seed-drop-ev", "prompt": "go" }),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "subagent capture dropped"),+ "the tail drops via the tracking seeded by the marked event"+ );++ // Control: an unmarked prompt of a never-seeded session is kept.+ let (status, reason) = admit_hook(+ state.clone(),+ query("user-prompt-submit"),+ None,+ None,+ None,+ HeaderMap::new(),+ serde_json::json!({ "sessionId": "top-seed-drop-ev", "prompt": "top" }),+ )+ .await;+ assert_eq!(+ (status, reason),+ (StatusCode::ACCEPTED, "queued"),+ "a non-subagent session is unaffected"+ );++ let snap = metrics.snapshot();+ assert_eq!(snap.dropped_by_policy, 2);+ assert_eq!(snap.accepted, 1);++ let sub_sid = SessionId::from_native("seed-drop-ev");+ assert!(+ state+ .reader+ .observations_for_session(sub_sid)+ .await+ .unwrap()+ .is_empty(),+ "the tail of the seeded session is not stored"+ );+ let obs = wait_for_kinds(&state, "top-seed-drop-ev", &[ObservationKind::UserPrompt]).await;+ let kinds: Vec<_> = obs.iter().map(|o| o.kind).collect();+ assert!(kinds.contains(&ObservationKind::UserPrompt), "{kinds:?}");+ }+#[tokio::test]async fn drop_subagent_tracking_is_scoped_by_project() {let tmp = TempDir::new().unwrap();@@ -19708,6 +20442,65 @@ pub(crate) mod tests {);}+ /// Dropping `pre-tool-use` (via `[ingest] drop_events`) must not change+ /// the ephemeral verdict for a session whose tool activity also produced a+ /// `post-tool-use` (or any other substantive event): the positive+ /// predicate still sees a substantive observation, so the session stays+ /// substantive exactly as it would with the pre-tool-use present.+ #[test]+ fn dropping_pre_tool_use_keeps_a_tool_session_substantive() {+ // The session as stored WITH the pre-tool-use present (baseline).+ let with_pre = vec![+ mk_obs(ObservationKind::SessionStart, "start", ""),+ mk_obs(ObservationKind::PreToolUse, "Read", "README.md"),+ mk_obs(ObservationKind::PostToolUse, "Read", "README.md"),+ mk_obs(ObservationKind::SessionEnd, "end", ""),+ ];+ // The same session after the operator dropped pre-tool-use: that+ // observation is absent, but the post-tool-use remains.+ let dropped_pre = vec![+ mk_obs(ObservationKind::SessionStart, "start", ""),+ mk_obs(ObservationKind::PostToolUse, "Read", "README.md"),+ mk_obs(ObservationKind::SessionEnd, "end", ""),+ ];+ assert_eq!(+ is_ephemeral_session(&with_pre),+ is_ephemeral_session(&dropped_pre),+ "the verdict is unchanged by the drop"+ );+ assert!(+ !is_ephemeral_session(&dropped_pre),+ "dropping pre-tool-use must not turn a tool session ephemeral"+ );+ }++ /// The one case where dropping pre-tool-use DOES change the verdict: a+ /// session whose only substantive event was the pre-tool-use — a tool call+ /// that started but never produced a post-tool-use, with no user prompt.+ /// With the drop on, such a session looks ephemeral (lifecycle-only); the+ /// server intentionally never stored the pre-tool-use, so it cannot count+ /// it as work. Documented in `docs/ARCHITECTURE.md` next to the key.+ #[test]+ fn dropping_pre_tool_use_makes_an_unfinished_tool_call_look_ephemeral() {+ let tool_started_never_finished = vec![+ mk_obs(ObservationKind::SessionStart, "start", ""),+ mk_obs(ObservationKind::PreToolUse, "Read", "README.md"),+ mk_obs(ObservationKind::SessionEnd, "end", ""),+ ];+ assert!(+ !is_ephemeral_session(&tool_started_never_finished),+ "control: a started tool call is substantive while stored"+ );+ let after_drop = vec![+ mk_obs(ObservationKind::SessionStart, "start", ""),+ mk_obs(ObservationKind::SessionEnd, "end", ""),+ ];+ assert!(+ is_ephemeral_session(&after_drop),+ "once the only pre-tool-use is dropped, the session is lifecycle-only"+ );+ }+#[test]fn open_questions_extracts_question_mark_prompt() {let obs = vec![diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex b5291550..ce1f97d6 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -1286,6 +1286,33 @@ drop_tool_use_id_prefixes = [] # e.g. ["toolu_plugin_"]: drop a tool event whdrop_tool_names = [] # exact tool names to drop; both lists apply to every project,# at most 64 entries of 128 characters, checked before the# sanitizer, rate limiter and ingest semaphore+drop_events = [] # whole hook event kinds to drop (e.g. ["pre-tool-use"]); a+ # matching event is acknowledged and discarded before storage,+ # checked right after the subagent exclusion (a marked+ # subagent event still seeds its tail tracking) and before the+ # rate limiter, the ingest semaphore and the sanitizer.+ # session-start/session-end are rejected (they open/close the+ # session state machine); unknown kinds are rejected. Dropping+ # a kind also turns off everything that kind's processing+ # does: user-prompt loses prompts (summaries, baton open+ # questions, profile learning); pre-tool-use loses the+ # pre-call evidence, so a session whose only work was a tool+ # call that never finished ends lifecycle-only; post-tool-use+ # loses results and the completed-call count; stop loses the+ # opt-in assistant reply,+ # the normal-completion signal and OpenCode's turn checkpoint;+ # pre-compact/post-compaction lose the compaction checkpoint+ # and its rewrite job (the session is not ended);+ # notification loses the observation;+ # subagent-start/subagent-stop lose subagent metadata (stored+ # as `other`). user-prompt and pre-tool-use (with+ # session-start) advance the project fallback pointer; dropping+ # them removes those updates. The portable workstream ledger+ # (`ai-memory run`) is not filtered by this key. In production+ # ~87% of pre-tool-use observations have an empty body and+ # each pairs 1:1 with a post-tool-use that carries the+ # content. Empty by default. Env:+ # AI_MEMORY_INGEST__DROP_EVENTS=pre-tool-use```The zero-LLM `query_intent` router also recognizes explicit Brazilian Portuguesediff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex b5f1eaf4..0256e101 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -79,7 +79,7 @@ means the boundary is not built yet.| 10e | Reconcile-tombstone of a disk-deleted page is opt-in, soft, scope-bound, and false-positive-guarded (invariant #16, #929 delete-half) | `ai-memory-wiki/src/watcher.rs` — off by default (`[maintenance] reconcile_tombstones_deleted_pages`); a page is tombstoned only after its file is observed missing on two consecutive passes (streak resets if the path's `PageId` changed), re-verified against the live filesystem immediately before acting, with reserved/indexed-but-unwalked paths (`bootstrap.md`, `_meta.md`, `_pending/`, `sessions/*.md`) excluded and a circuit breaker that skips a whole scope when `> max(3, 50%)` of its pages look missing or a non-partial walk finds nothing; `ai-memory-store/src/ops.rs` `soft_delete_for_reconcile_if_latest` is a soft tombstone (`is_latest=0` + `superseded_at`, decay's shape) through the single writer actor in one transaction — never a filesystem write — scoped to the page's own `(workspace_id, project_id)` | `watcher.rs` `reconcile_delete_disabled_by_default_never_tombstones_a_missing_page`, `reconcile_delete_cross_project_isolation` (project A's deletion never tombstones project B's same-path page), `reconcile_tombstone_refuses_a_stale_latest_id`, `reconcile_tombstone_refuses_when_the_file_still_exists`, `reconcile_tombstone_never_touches_the_filesystem`; `ops.rs` `reconcile_tombstone_resurrects_instead_of_orphaning_on_recreate` | STRONG || 10f | Session-time repair is scope-bound (no cross-project timestamp rewrite) | `ai-memory-store/src/ops.rs` `repair_session_times` — every candidate is read back and updated with `WHERE id=? AND workspace_id=? AND project_id=?`; a row outside that 3-tuple is reported `NotFound` and untouched, same code path as an id that does not exist at all; `ai-memory-mcp/src/admin.rs` `handle_repair_session_times` passes the caller's `(workspace, project)` straight through, never the candidate's own | `ops.rs` `repair_session_times_does_not_touch_a_session_of_another_project` (control: sibling session in-scope repaired in the same batch); `admin_repair_session_times.rs` `cross_project_session_is_not_found_and_untouched`; both bite-checked by dropping the `project_id` filter | STRONG || 10g | The event-ledger age sweep deletes only closed ledger files of the swept project: opt-in, content-gated, admission-gated, never the writer's months (invariant #16) | `ai-memory-consolidate/src/sweep.rs` `sweep_event_ledgers` + `ledger_is_expired` (off at `[decay] ledger_retention_months = 0`; never the current or previous UTC month, whatever the age; a dry run only lists; a per-file delete failure is counted in `ledgers_undeleted`, kept and retried — the sweep does not abort, exactly as a refused page delete is kept and retried); `ai-memory-wiki/src/wiki.rs` `list_event_ledgers` / `delete_event_ledger` — rotated `log-YYYY-MM.md` name AND `log_ledger` content gate (checked before and after the admission round-trip under the mutation guard), a project-confined path, no symlink, never `log.md`, no store write; then the same blocking admission check a page delete runs (`remove_page_locked`): webhooks subscribed to `delete_event_ledger` are notified BEFORE the unlink, a `reject`-policy webhook refuses and the file stays, and the non-blocking observers are told only after the removal is durable | `consolidate` `tests/suite/ledger_sweep.rs` `an_ordinary_page_named_like_a_ledger_is_never_deleted` (a page, a frontmatter page and `log.md` are kept; the real ledger is the control), `another_projects_ledgers_are_untouched`, `the_current_and_previous_month_survive_even_a_one_month_retention`, `the_default_configuration_deletes_no_ledger`, `a_dry_run_reports_files_and_bytes_and_deletes_nothing`, `a_rejecting_admission_webhook_keeps_the_ledger_and_the_report_says_so` (adversarial: a `reject`-policy webhook on `delete_event_ledger` — the file stays intact, the report counts it in `ledgers_undeleted`, the sweep keeps the rest going), `an_accepting_admission_webhook_is_told_after_the_file_is_gone` (legitimate control: an accepting gate lets the delete through and the non-blocking observer receives the op only after removal); `sweep.rs` `ledger_guard_protects_the_current_and_previous_month_regardless_of_age`; `wiki` `tests/suite/ledger_files.rs` `an_admission_webhook_cannot_swap_a_ledger_for_an_ordinary_page_before_delete` (the webhook overwrites the accepted ledger while deletion awaits its response; the final gate preserves that page, while a no-swap webhook is the legitimate delete control), `a_page_wearing_a_ledger_name_is_not_deleted_even_when_asked_by_name`, `only_a_rotated_ledger_name_is_accepted` (traversal and `log.md` refused), `deleting_in_one_project_leaves_the_neighbours_ledger` | STRONG |-| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter; batch acknowledgements retain only processed indices and classify terminal drops without consuming capacity | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded`; `router.rs` `handle_hook_batch_skips_rate_limited_first_item_and_accepts_later_source`, `handle_hook_batch_reports_failed_index_after_rate_limited_skip`, `handle_hook_batch_drops_subagent_events_before_capacity_check` (each asserts result indices and includes an accepted control) | STRONG |+| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter; batch acknowledgements retain only processed indices and classify terminal drops without consuming capacity (the `[ingest] drop_events` whole-kind drop, 11k, is one such terminal drop) | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded`; `router.rs` `handle_hook_batch_skips_rate_limited_first_item_and_accepts_later_source`, `handle_hook_batch_reports_failed_index_after_rate_limited_skip`, `handle_hook_batch_drops_subagent_events_before_capacity_check` (each asserts result indices and includes an accepted control) and `the_ingest_drop_events_drops_before_any_capacity_is_spent` (a whole-kind drop answers 202 with the semaphore exhausted; a kept kind gets the 429 control) | STRONG || 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized, and every word that holds several words, such as a quoted `sh -c` script or a `"$(…)"` substitution, re-split to four levels by `ShellCommand::split`/`push_nested_words`, a deeper script metadata-only; ANSI-C strings decoded and a backslash before an ordinary letter dropped (`shell_words`, `push_word`); backslash-newline continuations joined (`shell_words`); a parameter default's operand, a value glued to a short flag and a `file:` URL's path read as candidates (`parameter_operands`, `shell_arguments`, `file_url_path`); PowerShell and cmd escape characters read out under the `PowerShell` tool or on a Windows host (`without_windows_escapes`); `~+` resolved to the cwd and a `~-`/`~N`/`~name` prefix metadata-only (`names_unknown_directory`); shell and interpreter options that take a value skipped while looking for a `-c` script or inline code (`takes_shell_value`, `runs_inline_code`, which also lists `lua`/`Rscript`/`osascript -e`, and `su -c`/`script -c` as script runners); paths compared without regard to case on a macOS host (`fold_case`, set by `resolve`; patterns and candidates composed to NFC and lowercased in full by `fold_path`, TS `captureFold`; client-only, the server's sentinel re-inspection never depends on it); a `file:` URL cut at its query or fragment before decoding (`file_url_path`); a parameter default nested past four levels metadata-only and a default read again after backslash removal (`parameter_operands`, `push_word_reading`); a tilde expanded or treated as an unknown directory only when the shell expands it, unquoted and in a script rather than a quoted message or argv element, every tilde under PowerShell (`marked_shell_words`, `literal_tildes`, `expand_tilde`); a file or shell read of a harness's saved tool output, or a glob that could match one, metadata-only under an active policy (`output_spool`: Claude Code `tool-results/` and `tasks/*.output`, OpenCode `tool-output/`, Pi `pi-bash-*.log`; glob segments fit a name they share a match with, `globs_intersect`, TS `captureGlobsIntersect`, and one fitting segment must spell three characters in a row of that name's distinctive text literally, `spells`, TS `captureSpells`, so `*.log` is not read as `pi-bash-*.log`, a trade-off that leaves a glob with no such literal run, `/tmp/p?-b*`, outside the rule; the TS matcher applies it to `read_many_files` entries too); every other marker governing a file-tool target (an `apply_patch`'s header paths, read after leading whitespace, `patch_paths`), a search/list tool's directory, file or path-like glob argument (`search_scope`, Hermes `file_glob` included; a grep `pattern` is not read) or a separator-bearing shell argument also inspects the call, found by the lexical marker walk from each location's nearest existing directory, each directory's answer remembered for every lookup that passes it (`marker.rs` `MarkerMemo`, TS `captureMemoMarker`, seeded with the event's own walk, `remember`, TS `captureMemoRemember`), bounded (4,096 locations, 16 markers, and 16,384 probes sharing the glob walk's 50 ms, `MAX_LOOKUP_PROBES`, TS `CAPTURE_MAX_LOOKUP_PROBES`; locations outside the own checkout are looked up first, a glob's literal root before the walk below it (whose single listing can spend the time budget on a large directory), and past a bound fail closed as under an invalid policy, while running out inside the own checkout, whose locations are looked up shallowest first, ends the lookup, its own policy governing there) and combined strictest-first (`capture_lookup_locations`, `CaptureDecision::stricter`, `hook.rs` `foreign_capture_decision`, also applied by `transcript_capture.rs` `decide_call`; TS `captureForeignConfigs`, `captureDecide`, `captureSearchScope`, `capturePatchPaths`); a location with glob syntax is looked up from its literal root and, when that root lies outside the event's `.git` checkout, every directory the glob could pass through is checked for a marker (`glob_walk`, `hook.rs` `GlobBudget::markers_below`; TS `captureGlobWalk`, `captureMarkersBelow`, `captureOwnCheckout`: a `*`/`?` segment lists the child directories it matches, a class/brace/group every child, a `**` the subtree except the event's checkout's; a glob rooted inside the event's checkout is not walked; a checkout root at or above the home directory, or the filesystem root, is never the own checkout for these rules (`own_checkout`), so a dotfiles `~/.git` does not stop the walk from `~/Projects`; symlinks never followed; 256 directories, counted as a `**` lists, 32,768 entries and 50 ms, `MAX_GLOB_TIME`, TS `CAPTURE_MAX_GLOB_MS`, injectable clock, past which, or for a brace/group spanning a separator, a `..`/`~` alternative or one a bounded brace expansion builds, `brace_alternatives`, TS `captureBraceAlternatives`, a directory alternative bash before 5.2 expands to `..` (`.{*,x}/`), or an expansion too large to list whose pieces could build one of these (`brace_overflow_could_leave`, TS `captureBraceOverflowLeaves`: integer and letter sequences cannot, so `file{1..200}.txt` is walked like any glob), the call fails closed); a `..` after a `**` is read both as the `**` matching no directory and as matching some, by the event's own matcher and the lookup (`normalize_readings`, TS `captureReadings`, at most 16 readings, past which the call fails closed), and so is a directory segment that bash before 5.2 can expand to `..` (`could_name_parent`, `class_glob_matches` with POSIX classes such as `[[:punct:]]` and extglob groups such as `@(.)`, `?(.)`, `*(.)`, `+(.)`, `!(x)`; TS `captureCouldNameParent`, `captureClassGlob`, `captureNamedClass`), read as `..` too; inside double quotes a backslash before `$` or a backquote is dropped, so a quoted script (`bash -c "…"`, `eval "…"`) re-split for its words reads an ANSI-C string as the shell it runs does (`shell_tokens`, TS `captureMarkedWords`); a zsh glob group kept in its word and ANSI-C numeric escapes decoded are fed to the lookup (`shell_tokens` with `expand`, `ShellWords::expanded`, `glob_group`, `ansi_c_numeric_escape`; TS `captureMarkedWords(…, true)`, `captureGlobGroup`, `captureAnsiNumeric`); a file tool whose targets cannot be read or resolved, and a search/list argument that is not a string, fail closed; the path of a git `REV:path` object name tried from the cwd and the marker directory (`git_object_path`); Antigravity `run_command` resolved from its `Cwd`); an invalid marker makes file, search/list and shell calls metadata-only; an active one makes a shell call metadata-only when a word uses unquoted brace expansion, a bracket class (a leading `]` included), a zsh glob group or extglob, or a numeric/control ANSI-C escape (`has_unevaluated_expansion`, also run on scripts given to `sh -c`, `eval` or a substitution), or when it runs inline interpreter code (`runs_inline_code`: `python -c`, `node -e`, `ruby -e`, `perl -e`, `php -r`, `deno eval`), and either makes tools that read back an earlier command's output metadata-only (`reads_earlier_output`: `BashOutput`, `TaskOutput`, `write_stdin`, `process`, `read_bash`/`write_bash` and PowerShell twins); the server admits a metadata-only shell or unknown-family body only under an active or invalid marker, with no paths and an `extracted` state (`router.rs` `metadata_protocol_is_legal`), and its own re-inspection strips an older client's keep for either; a Gemini `read_many_files` literal entry is also read as `entry/**` (`glob_matches_below`), and Copilot CLI's runtime `view`/`create`/`str_replace_editor` are file tools for that agent only (`agent_family`); Factory Droid's Claude-shaped payload is read by `extract`, its `Create` and `ApplyPatch` are file tools for that agent only (`agent_family`), `ApplyPatch` reads its `input` envelope like Codex `apply_patch`, and its `LS` `directory_path`, `Glob` `folder`/`patterns` and `Grep` `glob_pattern` locate the call for the cross-checkout lookup (`search_direct_paths`, `search_scope`) (#1240); Meta Muse Code's Claude-shaped payload is read by `extract` with its `tool_use_id`, its `read_file`/`write_file`/`edit_file` `path` resolves lexically against `cwd`, its `read_memory`/`add_memory`/`edit_memory` are file tools for that agent only whose `project`-scope `path` is placed under `.agents/memory/` and whose personal scopes fail closed to metadata-only (`muse_memory_paths`), `monitor` is a shell for that agent only, and `bash_input` is an output reader for that agent only; CodeBuddy Code's payload carries Claude Code's tool names and fields and is read by the same `extract` arm (#1299); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`, `captureShellSplit`, `captureUnevaluatedExpansion`, `captureInlineCode`, `captureGitObjectPath`, `captureGlobBelow`, the `reader` flag). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected; `hook.rs` `--check-capture` preflight uses the same capture policy before any spool or spawn; transcript imports (`ai-memory backfill`, including the automatic first-boot run, the `ai-memory run` ledger upload, and `ai-memory recover`'s finish-failed re-import and degraded-run replay in `recovery.rs` `recover_finish_failed`/`recover_degraded_run`, each built for the journaled checkout's `cwd`) apply the same decision table through `commands/transcript_capture.rs`: each recorded tool call is rebuilt in its agent's hook shape (`capture_policy.rs` `tool_call_payload`) and inspected by the checkout's policy, and by a reroute destination's policy too; a Drop removes the call and its result (paired by native id, else the strictest call of the turn when the result has no id; a result whose id matches no call, or with no call, follows the orphan rule: dropped under a policy, content-free without one), metadata-only posts the hook's metadata-only body with its protocol (backfill) or a withheld placeholder keeping only the family and a call id that passes the server's `valid_call_id` (ledger), and a shell call whose recorded arguments cannot be parsed drops; both imports also apply the hook's repository admission gate (`hook.rs` `checkout_admits_capture`: persisted capture mode, marker opt-in, readable routing marker — the same helpers the hook's own gate uses), so under allowlist mode an unmarked checkout imports nothing, prompts included: `backfill` stops before contacting the server and the run ledger finishes with no events; a tool the transcript names differently from the hook is rebuilt under the hook's name and fields (`capture_policy.rs` `hook_tool_call`: Codex `exec_command` `{cmd, workdir}` → `Bash` `{command, workdir}`); the Claude Code and Codex JSONL adapters label each event with its record's cwd (`transcript.rs` `stamp_record_cwd`, `RECORD_CWD_KEY`), from which the import resolves arguments, policy and reroutes, falling back to the session cwd, and which is removed before a ledger upload; a rerouted call, and an event whose record cwd lies outside the checkout, must pass that directory's admission gate, resolve to the same server-profile route as the checkout and to the same project scope (`transcript_capture.rs` `admits_elsewhere` → `hook.rs` `checkout_admits_capture` + `delivers_to_same_server`, which compares two `resolve_hook_route` results and never matches a refused selection, + `routes_to_same_project`, which compares the two `hook_scope` hint sets and, when they leave the project to the server, under `repo-root` the repository/marker anchor or the directory itself, under the default `basename` the directory itself or a destination inside the repository whose root is the source), else it drops with its result, since the import files every event under the importing project; compaction, checkpoint and annotation events answer to the same record-cwd checks; Claude Code `!` shell-mode output (a user message opening with a `<bash-stdout>`/`<bash-stderr>`/`<local-command-stdout>` block, whatever it holds) is dropped (`shell_mode_output`); the Claude Code adapter excludes harness-written background-task turns (`transcript.rs` `claude_task_notification`: `origin.kind` `task-notification` in any case, or a first text block opening with a `<task-notification` tag in any case, attributes allowed, after a byte-order mark, zero-width characters or whitespace) and records a compaction summary (`isCompactSummary` true, `"true"` or `1`, `truthy`) as a compaction event, which backfill does not post; a tool the matcher does not recognize (unknown family: MCP tools, Codex `view_image`, …) keeps only its family whatever the policy, as the live server stores for it (`EventCapture::Unrecognized`: backfill posts title `tool unknown` and body `tool_family: unknown`, the ledger a withheld placeholder), and so does a result with no call to inherit from ; in a Windows session every candidate, shell argument and `workdir` is read as the file Windows opens before matching (`windows_spelling`, `windows_segment`, `command_base`; TS `captureWindowsSpelling`/`captureResolve`/`captureBase`): Git Bash/MSYS2/Cygwin `/c/…` and `/cygdrive/c/…`, a drive-less rooted path on the cwd's drive, the `\\?\`/`\\.\`/`\??\` and `UNC` prefixes, the local administrative share (`\\localhost\C$`), and per-segment alternate-data-stream suffixes and trailing dots/spaces, any other device path unusable (metadata-only for a file tool); `/c/…` and `/cygdrive/c/…` are also read from the root of the cwd's drive, as a native tool reads them, and either reading matching drops (`windows_spellings`, `normalize_candidates`, `normalize_readings`; TS `captureWindowsSpellings`/`captureAllReadings`); the cwd, the marker directory, home and an absolute pattern get the same reading so every side shares one spelling (`normalize_root`, `compile`; TS `captureRoot`, the marker directory cut lexically); a Windows session also reads each shell command and argv element with every backslash literal, as PowerShell and cmd do, so a bare or double-quoted `\\server\share\…` or `\\?\C:\…` argument keeps its prefix (`literal_shell_words`, threaded through `push_nested_words`/`push_argv_item`; TS `captureMarkedWords(…, literal)`); the harness-spool check is linear in the path and charged to the match budget, past it fail-closed (`output_spool`, TS `captureOutputSpool`); a shell command over `MAX_SHELL_COMMAND_CHARS` (1 MiB) is metadata-only and its marker lookup unprovable (`ShellCommand::oversized`, TS `captureCommandOversized`); Hermes `execute_code` is metadata-only under an active policy (`INLINE_CODE_TOOL_NAMES`); the TS file/search/non-file/inline-code/output-reader tool lists and the command limit are generated from the native constants (`FILE_TOOL_NAMES` and siblings, spliced by `ts_capture_policy_v1`), and the TS marker reader honours every TOML spelling of the capture table toml_edit does (dotted `capture.ignore_paths`, quoted or spaced `[capture]` headers) and fails closed on the shapes it rejects (inline table, `[[capture]]`, `[capture.x]`, a second definition) (`captureTomlKey` and the `captureConfigAt` section loop), tracks every multi-line array so a line inside one (`["docs"]`) is never a header, and fails closed on a line that is neither header nor key/value, a key line swallowed by an open array, text after a continued array closes, or an inline table left open at a line end (`captureValueScan`); the TS glob walk reads a directory one entry at a time with `opendirSync`, stopping at the entry bound; in a Windows session a shell argument or `workdir` that is drive-relative (`C:docs\x`, a bare `C:`) or a device path naming no drive or share (`\\?\GLOBALROOT\…`, `\\.\HarddiskVolume3\…`) makes the command metadata-only, a POSIX shell's reading of a placeable native path (`C:\repo\x` read as `C:repox`) excused and a device reading never (`windows_unplaceable`, `match_command`, the `workdir` check in `inspect`; TS `captureWindowsUnplaceable`, `captureMatchCommand`, `captureDecide`); a PowerShell `FileSystem::`/`Microsoft.PowerShell.Core\FileSystem::` provider prefix is dropped before a Windows path is read (`strip_powershell_provider` in `candidate_raw`/`command_base`; TS `captureStripProvider` in `captureResolve`/`captureBase`); a POSIX absolute pattern in a Windows marker makes the marker invalid (`compile`; TS `captureConfigAt`) (GHSA-gcpc-88hm-3xqr); server re-inspection compiles an Active never-match sentinel in the cwd's path flavor (`inspection_sentinel`, `capture_inspector`) (#1250) | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec` and `PowerShell`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `claude_code_powershell_honors_ignored_paths_on_a_windows_host` (#1186: Windows-spelled and `-Param:value` paths drop, public-path and `git status` controls kept, invalid marker metadata-only), `gemini_cli_shell_and_read_many_files_honor_ignored_paths` (Gemini `run_shell_command` incl. `dir_path`/`directory`, and `read_many_files` globs via `match_globs`: excluded literal, mixed public+excluded, `docs/*`, recursive `**` and case-variant entries drop, an `exclude` list cannot rescue them, unsupported glob syntax and malformed lists are metadata-only, public entries kept, POSIX and Windows hosts) and `globstar_reaches_lets_double_star_span_any_depth`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell admitted for an unevaluated expansion, inactive refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused), `capture_protocol_active_keep_on_a_windows_cwd_keeps_provable_bodies` (#1250: a kept Read and Bash on `C:\repo` and a UNC cwd stay Keep; brace-expansion still metadata-only); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`, `gemini_cli_shell_and_read_many_files_exclusions_drop_before_spool` (pre- and post-tool events with an excluded path are never spooled; public controls spool with their family); `capture_policy.rs` `read_many_files_directory_entries_cannot_reach_ignored_paths` (shared `read_many_files_directories` vectors: `docs`, `.`, `./`, `docs/`, case and `..` variants drop; `src`, `README.md`, `docs/adrx` kept), `output_reader_tools_are_metadata_only_only_under_a_policy` (active and invalid strip, inactive and an unrelated unknown tool keep), `copilot_cli_runtime_file_tools_are_scoped_to_copilot`, `unevaluated_shell_expansions_respect_quoting` (also leading-`]` classes, zsh groups and extglobs, ANSI-C numeric escapes; subshells, `$((…))`, `<(…)`, array assignments kept), the shell fixture's brace/class vectors (quoted, escaped, `${…}`, `{}`, `[ … ]`, `HEAD@{1}` controls kept); `quoted_scripts_in_string_commands_are_read_like_command_lines` (`sh -c`, `timeout … bash -c`, `"$(…)"`, `NAME="$(…)"`, backquotes, two nested shells and an inline-interpreter literal drop; `bash -c 'cargo test'` and `"$(git rev-parse HEAD)"` kept; four levels read, a fifth metadata-only), `inline_interpreter_code_is_metadata_only_under_an_active_policy` (inline code metadata-only, kept with no policy; modules, script files and `grep -e` unaffected), `git_object_names_are_path_candidates` (`HEAD:`, `:`, `:N:` and `@{n}` names drop, also from a subdirectory; drive letters, URLs, `NAME=a:b` and flags are not object names; a public object name kept), `ansi_c_strings_and_escaped_letters_are_read_like_the_shell`, `antigravity_run_command_resolves_arguments_from_its_cwd` (absolute and relative `Cwd` drop, a public `Cwd` kept, another agent's `Cwd` key ignored), `windows_escape_characters_are_read_on_a_windows_host` (caret and backquote spellings drop on a Windows host, public controls kept, a POSIX host reads both literally), `a_case_folding_host_matches_paths_without_regard_to_case` (file tool and shell drop with folding, keep without, public control kept; folding injected through `resolve_for_host` so it runs on every CI OS), the shell fixture's continuation, PowerShell/cmd escape, option-value, runner, interpreter, glued-flag, `file:` URL, tilde, parameter-default and `fold_case` vectors with their controls, the near-miss controls added to `common_commands_stay_kept_under_an_active_policy` (also quoted tildes, a `file:` URL with a query, a shallow nested default and a scratchpad log), the shell fixture's `file:` query/fragment, deep-default, escaped-default, quoted/argv/script tilde, PowerShell tilde, harness-output and Unicode `fold_case` vectors and the `decisions` harness-output vectors with their controls, `reading_a_harness_output_spool_is_metadata_only_under_a_policy` (active and invalid strip, inactive keeps, same-named files elsewhere kept, an ignored path still drops), `capture_lookup_locations_name_every_path_a_call_spells`, the Unicode rows of `a_case_folding_host_matches_paths_without_regard_to_case`, **`hook.rs` `another_checkouts_exclusions_hold_for_a_call_made_elsewhere`** (relative, absolute, glob and unmarked-Hermes shell calls naming another checkout's excluded file never spool; a broken foreign marker and too many foreign markers spool metadata-only; public, own-file and few-marker controls spool with content), **`hook.rs` `globs_searches_and_unreadable_targets_answer_to_another_checkout`** (sibling and parent-folder `*`, brace, bracket, `**` and separator-spanning-brace shell globs, a Grep path, a Glob pattern, a parent-folder Grep filter, a Gemini `search_file_content` directory, a Codex `apply_patch` header and a target-less Read never spool content; public-glob, own-glob, own-`**`, own-search, own-Glob-`**`, public-search and own-patch controls spool with content), `transcript_capture.rs` `globs_and_searches_reaching_another_checkout_honor_its_policy`, `capture_policy.rs` `glob_walk_follows_every_segment_a_glob_could_pass_through`, `an_invalid_policy_makes_a_search_metadata_only`, `a_brace_that_builds_a_parent_step_cannot_be_walked`, `a_parent_step_after_a_globstar_is_read_both_ways`, `glob_groups_and_ansi_c_escapes_reach_the_marker_lookup`, `a_saved_output_glob_needs_its_distinctive_name_in_literal_text`, `indented_patch_headers_and_hermes_file_globs_reach_the_marker_lookup`, `a_dot_glob_directory_that_can_match_the_parent_is_read_as_it` (POSIX classes and extglob groups included), `an_oversized_brace_expansion_is_walked_unless_its_pieces_could_leave` (each attack with its control), the shell fixture's double-quoted `bash -c`/`eval` ANSI-C vectors and their controls, `marker.rs` `marker_memo_answers_like_find_marker_once_per_directory`, **`hook.rs` `a_globstar_above_the_checkout_skips_the_own_subtree`** (regression: `ls ../**/README.md` from a 300-directory checkout with no policy is not metadata-only; the sibling `cat ../**/secrets.env` drops), **`hook.rs` `marker_lookups_in_a_deep_tree_cost_one_probe_per_directory`** (regression: 300 paths in a 300-level tree cost fewer than five probes per level; out of budget inside the checkout kept, outside it metadata-only, the sibling checkout's location looked up before a long list inside the checkout, and a shallow nested marker before a deep list), **`hook.rs` `a_dotfiles_checkout_at_home_is_not_the_own_checkout`** (with `~/.git`, `cat */secrets.env` from `~/Projects` drops; a harmless glob kept), the shell fixture's dot-glob directory vectors and their controls, the shell fixture's `**`-then-`..` and `*.log` vectors and the `read_many_files_directories` `**`-then-`..` vectors, **`hook.rs` `constructed_parent_steps_answer_to_another_checkout`** (a `..` after a `**` through a shell, a Glob pattern and a Grep filter, four brace expansions that build a parent step, two zsh glob groups, hex and octal ANSI-C escapes, two dot-glob directory segments, a POSIX-class and four extglob dot-glob segments, a brace-built dot-glob, an oversized brace sequence over `.`, ANSI-C strings in a double-quoted `bash -c` and `eval`, an indented `apply_patch` header next to an unindented one and a Hermes `file_glob` never spool content; the same shapes inside the checkout spool with it, and so do four brace expansions too large to list that cannot leave it, which v2.6.3 kept), **`hook.rs` `a_monorepo_glob_inside_the_own_checkout_is_not_walked`** (in a 300-package checkout, with and without a policy of its own, `packages/*` shell globs stay kept and the sibling `../*/secrets.env` and `../a/*.env` attacks still drop), `hook.rs` `a_glob_walk_outside_the_checkout_stops_at_its_bounds` (directory bound counted while a `**` lists, time budget through an injected clock, no walk inside the checkout), the Node evidence test's `monorepo-*`, `walk-*`, `con-*`, `globstar-*`, `deep-*` and `dotfiles-*` checks, and the Node evidence test's `glob-*`, `search-*`, `patch-*` and `unreadable-target` checks with their controls and `transcript_capture.rs` `a_shell_command_naming_another_checkouts_file_honors_its_policy`, both failing with the foreign lookup disabled, and the Node evidence test's `cross-*` and `fold-unicode` checks, which fail with `captureForeignConfigs` disabled, and the shell fixture's quoted-script, git-object, ANSI-C, escaped-letter and inline-interpreter vectors with their controls (`cargo test`, `git status`/`log`, `pytest`, `python3 -m pytest`, `node build.js`, `npm run test`, a quoted commit message with braces); `router.rs` `capture_protocol_active_keep_of_unprovable_output_is_stripped`; `hook.rs` `excluded_content_cannot_reach_the_spool_through_unevaluated_tool_shapes` (directory entries and Copilot `view`/`create` never spool, readers and brace shells spool without content, public controls spool with it); `capture_policy.rs` `droid_tool_calls_honor_capture_exclusions` (`Read`/`Create`/`Edit` naming an ignored path drop and a control path keeps, `ApplyPatch` is metadata-only like Codex `apply_patch` and its headers name the lookup location, `LS`/`Grep`/`Glob` drop and their directory and glob arguments locate the call, `Execute` naming an ignored path drops; every excluded case keeps under `AgentKind::Other`, so it fails with the Droid `extract` arm or the `Create`/`ApplyPatch` mapping removed) and the `droid` `decisions` fixture vectors (#1240); `capture_policy.rs` `muse_tool_calls_honor_capture_exclusions` (`read_file`/`write_file`/`edit_file` naming an ignored path, relative or absolute, and the project-scope memory tools naming an ignored `.agents/memory` path drop while a control path keeps, personal-scope memory calls are metadata-only, `apply_patch` is metadata-only like Codex's, `search` drops, `bash`/`monitor` naming an ignored path from their `workdir` drop, `bash_input` is metadata-only; each excluded case keeps under `AgentKind::Other`, so it fails with the Muse `extract` arm removed), `muse_tool_payload_fields_carry_the_call_id` and the `muse` `decisions` fixture vectors, taken from Muse Code 1.4.7 hook payloads; `capture_policy.rs` `codebuddy_tool_calls_honor_capture_exclusions` (`Read`/`Write`/`Edit`/`Bash` naming an ignored path drop, a control path keeps, and every excluded case keeps under `AgentKind::Other`, so it fails with the CodeBuddy `extract` arm removed) and the `codebuddy` `decisions` fixture vectors; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 and Gemini `read_many_files`/`run_shell_command` vectors, plus unsupported-glob, empty-list and recursive-`**` checks, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job); `hook.rs` `check_capture_refuses_partial_scope_and_excluded_content` (ignored-path and partial-scope violations refused, complete public-path control passes), `check_capture_bounds_marker_hints_and_refuses_oversized_scope` (513-byte hints refused, 512-byte control passes; native routing preserved); **`backfill.rs` `backfill_never_posts_tool_content_the_capture_policy_excludes`** (planted Claude transcript: the excluded read's call and output never reach `/hook/batch`, a malformed read posts only the metadata-only body, public read control posted) and **`run.rs` `ledger_upload_drops_tool_content_the_capture_policy_excludes`** (excluded call and output absent from the finish request, public control present, cursor still advances), both failing with the guard removed; **`recovery.rs` `finish_failed_recovery_never_posts_content_the_capture_policy_excludes`** and **`degraded_run_recovery_never_posts_content_the_capture_policy_excludes`** (a full `recover` pass over a journaled Claude transcript with exact digests and cursor, marker `ignore_paths = ["secrets/**"]`: the excluded read's path and `SENTINEL_RECOVERY_MUST_NOT_POST` output never reach `/workstream/runs/{id}/recover` or `/hook/batch`, the public read's output does; each fails when its own call site's capture is built for `/` instead of the entry's `cwd`, on the control since a foreign-scoped capture fails closed, and both fail on the sentinel when `for_checkout` loses the marker's policy); `transcript_capture.rs` `an_excluded_read_drops_its_call_and_result_by_id`, `id_less_results_take_the_strictest_call_of_their_turn`, `unrecoverable_arguments_and_orphan_results_fail_closed_under_a_policy`, `a_call_into_another_checkout_honors_its_policy`, `ledger_events_are_dropped_or_stripped_before_upload`, `without_a_policy_every_event_is_kept` (control); `capture_policy.rs` `tool_call_payload_reaches_the_live_decision_for_every_supported_agent`; **`backfill.rs` `allowlist_mode_backfills_nothing_from_an_unmarked_checkout`** (no request reaches the server; marked-checkout and denylist controls do), **`run.rs` `ledger_upload_under_allowlist_mode_carries_nothing_from_an_unmarked_checkout`** (finish carries no prompt or tool content; marked and denylist controls upload both), `transcript_capture.rs` `allowlist_mode_admits_nothing_from_an_unmarked_checkout`, all failing with the admission gate removed; **`backfill.rs` `backfill_inspects_codex_exec_command_as_the_hook_shell_call`** and **`run.rs` `ledger_upload_inspects_codex_exec_command_as_the_hook_shell_call`** (a planted Codex `exec_command` whose `workdir`-relative argument names an ignored file never posts its call or output; the same command from a public `workdir` does), `capture_policy.rs` `codex_transcript_exec_command_is_inspected_as_the_hook_bash_call` (absolute, relative and absent `workdir` and an argv `cmd` drop, public control kept, the `workdir` locates the call, another agent's `exec_command` stays unknown), all failing with `hook_tool_call` removed; **`backfill.rs` `backfill_resolves_each_call_from_its_record_cwd`** (`cat adr/x.md` recorded from `docs/` never posts; the same command from the root does) and `transcript.rs` `jsonl_events_carry_their_record_cwd` (Claude per line, Codex per turn context, a relative cwd ignored), failing with the record cwd ignored or unstamped; **`backfill.rs` `backfill_drops_reroutes_the_live_hook_would_not_deliver_here`** (under allowlist mode, reads rerouted to an unmarked git repository, to a marker selecting an unregistered profile, and to a marker selecting a registered profile while the source uses the install default are never posted; a read in a marked checkout with no server selection is the posted control), failing with either the admission check or the route comparison removed (each refused case checked on its own); `transcript_capture.rs` `a_record_cwd_answers_to_the_hook_admission_gate_there` (prompt, call and result recorded in an unmarked repository drop under allowlist; a subdirectory of the opted-in checkout is kept and its record cwd never reaches the ledger) and `claude_shell_mode_output_is_not_imported` (stdout, stderr, local-command and size-capped blocks drop; `<bash-input>`, a prompt quoting a tag, and another agent's message kept); **`backfill.rs` `backfill_posts_no_content_for_unrecognized_tools`** (a planted Codex MCP call's arguments and output never post, the call and output post as `tool unknown`; a recognized shell output is the posted control) and `transcript_capture.rs` `unrecognized_tools_keep_no_content_with_or_without_a_policy` (no policy and an active one; ledger content withheld; public read kept; a call-less result content-free), failing with the unknown-family rule removed, the backfill one also with its content-free body removed; **`backfill.rs` `backfill_keeps_reroutes_to_the_same_server_profile_only`** (a reroute into a checkout selecting the source's registered profile and project is posted; one selecting a different registered profile is not, nor one of another project on the same profile, nor a prompt recorded there), failing with the profile comparison forced either way and with the project comparison removed; `transcript_capture.rs` `a_record_cwd_in_another_project_is_dropped` and `a_reroute_into_another_project_is_dropped` (prompt, call and result recorded in, or a read reaching into, a checkout declaring another project drop; one declaring the same project is kept), failing with `routes_to_same_project` removed; `hook.rs` `subdirectories_of_one_repository_are_one_project_only_under_repo_root` (two subdirectories of an unmarked repository, and a subdirectory importing its root, are two projects; the same directory, the root importing a subdirectory and a `repo-root` marker agree), failing with the basename rule removed; **`backfill.rs` `backfill_posts_no_task_notification_or_compact_summary_as_a_prompt`** and `transcript.rs` `claude_adapter_keeps_task_notifications_and_compact_summaries_out_of_prompts` (a monitored command's notification, a background agent's report and an origin-tagged notice are excluded, also behind a byte-order mark and zero-width characters, in another case, with attributes, after a non-text block, or with an origin kind in another case; a compact summary, also flagged `"true"` or `1`, becomes a compaction event; the typed prompt, also one quoting the tag, and a look-alike tag are the controls), failing with either adapter rule removed or with the spelling rules reverted; `transcript_capture.rs` `boundary_events_answer_to_the_record_cwd_admission_gate` (compaction and annotation recorded in a refused directory drop; in the checkout kept), `a_result_whose_id_matches_no_call_is_an_orphan` (an unmatched id cannot borrow a public read's keep; the read's own result kept), `claude_shell_mode_output_is_not_imported` (a block holding a literal closing tag drops) and `unrecognized_tools_keep_no_content_with_or_without_a_policy` (ledger keeps no tool name and no invalid call id), each failing with its rule reverted; `windows_spelling_fixture_vectors` (shared `capture-policy.json` `windows` drop vectors for every spelling above, file tool and shell, with other-drive, other-share, longer-name and pipe controls, and `windows_posix_controls` proving a POSIX session keeps `/c/…`, trailing-dot and colon names; `windows_scopes` drop vectors for a `\\?\C:\`, `\\?\UNC\…`, `\\localhost\C$\…` or UNC cwd and marker directory with relative patterns, a `\\?\C:\…` absolute pattern from `C:\repo`, bare and double-quoted `\\server\share\…`/`\\?\…`/`\\.\…`/`\\localhost\c$\…` PowerShell, cmd, `run_shell_command` and argv commands, and both readings of `/a/x` from `D:\a\…`, each with public-path, other-drive and other-share keep controls; the Node runtime evidence runs the same vectors with the marker spelled in the Windows cwd), `tool_family_fixture_vectors` (shared `tool_families`, every native name per family), new `decisions` vectors (`execute_code` metadata-only, `read_file`/`patch`/`fs_read` operations drop, `write_to_file`/`browser_navigate` keep), `output_spool_work_is_linear_and_budgeted` (a 2,040-wildcard-segment path stays under a linear work bound; 32 such paths fail closed; one long or 32 short paths keep), `an_oversized_shell_command_is_unprovable` (one character over the limit is metadata-only and unlooked-up, at the limit keeps, argv summed, inactive untouched), `inline_code_tools_are_unprovable_under_a_policy`, `hook_capture::capture_section_spellings_match_toml_semantics` (shared `marker_spellings`, including a nested-array line `["docs"]` before a dotted `capture.ignore_paths` that must still drop, and a key line inside an open array, text after a closed array and a multi-line inline table that must fail closed), and the Node evidence test running all of these vectors against the generated TypeScript plus its entry-bound read count for the directory walk; each fails with its rule reverted (Windows reading off, spool memo dropped or budget failing open, length check off, inline-code rule off, a name dropped from the list, TS dotted key or inline-table rule reverted, TS walk back on `readdirSync`, Windows reading of the cwd/marker directory or of an absolute pattern off, literal-backslash reading off, the cwd-drive reading of `/a/x` off, TS array tracking or any `captureValueScan` refusal off, Rust and TS alike); new `windows_scopes` vectors (drive-relative, device-namespace and Git Bash doubled-backslash shell words and a `C:docs` `workdir` metadata-only, `FileSystem::` file paths, shell words and `workdir` dropping, a POSIX absolute pattern in a Windows marker failing closed, with `type README.md`, `dir /s /q`, `git status`, a URL, `type C:\repo\README.md` and `Get-Content -Path C:\repo\README.md` kept) and `windows_marker_rejects_posix_absolute_patterns` (the same pattern stays active in a POSIX marker) fail natively and in the Node evidence test with the unplaceable check, its device branch, the `workdir` check, the provider strip or the marker rejection removed; `inspection_sentinel_matches_cwd_flavor` (#1250: POSIX sentinel Invalid on a Windows cwd, Windows-flavored sentinel Active there and on UNC, POSIX sentinel Active on `/repo` and Git Bash `/c/repo`) is native only, since `inspection_sentinel` is server re-inspection with no TypeScript counterpart, and fails with the cwd-flavored sentinel or the marker rejection removed; removing the POSIX-reading excusal makes `type C:\repo\README.md` metadata-only, and excusing a device reading keeps the doubled-backslash device path; `capture_policy.rs` `windows_lookup_locations_keep_glob_segments_whole` (a Windows session trims trailing dots from plain segments only, so `{.,}.` still reaches `..` and the sibling checkout's marker; bites with the glob-segment exemption removed) | STRONG with listed residuals. Matching is lexical by design, so these stay open: shell variables (`$VAR`, `FILE=… sh -c 'cat $FILE'`) and the output of a command substitution, a `cd` inside the command, a script read from a file or a heredoc fed to an interpreter (read only for the words it spells out), git's repository root approximated by the marker directory, symlinks (paths are never resolved on disk), a recursive search of a parent directory (`grep -r x docs`, `rg x`) through a shell, a search tool rooted at a literal directory above another checkout (it is not walked) and a glob whose literal root lies inside the event's own checkout reaching a checkout nested there (it is not walked), a marker nested inside the own checkout below what the lookup budget reaches, a `.git` the same command creates (`touch .git; cat */x`: the hook reads the tree after the command ran, so that directory counts as the own checkout; a `.git` at or above the home directory never does), a parameter expansion next to glob syntax (`${X}/*/x`, not walked), a glob through a symlinked directory, a tool's own directory option (`git -C`), script runners and interpreters the matcher does not list (their words are still read, but expansion or inline code in them is not recognized), a value glued after the first letter of a short-flag cluster, non-ASCII percent-escapes in a `file:` URL, a bare word naming another checkout's directory (only separator-bearing arguments are looked up for another marker), harness output files outside the listed default locations, and tools the matcher does not list, which keep their current unknown-tool behavior. Transcript imports add: assistant prose quoting an excluded file is kept (as live prompt/assistant capture keeps it), harnesses whose hook schema the matcher does not read (Crush, Kimi Code) keep their tool events as live capture would, adapters that record no per-record cwd (Pi, OMP, OpenCode, Crush, Kimi Code, Command Code, Kiro, Grok) judge every event from the session cwd, a Codex ledger upload resumed from a mid-file cursor judges the events before the next turn context from the session cwd, and id-less adapters over-drop a whole turn's results when one call is excluded, and when the routing hints leave the project to the server, events from inside one repository count as the importing project even where the server has a separate project registered for a subdirectory (anywhere under `repo-root`; under `basename` only when the import runs from the repository root); a metadata-only import keeps an `event_id` (ledger) and `ingest_key` (backfill) derived from a SHA-256 of the original content plus session and record ids, left in place because those ids are the retry-dedupe keys and a content-free id would merge distinct events — it only confirms a guess of low-entropy content. Under allowlist mode a refused checkout's `ai-memory run` still records repository checkpoint metadata (HEAD, branch, a status hash and changed-path names, never file content), which the run also sends at launch. Re-splitting quoted words over-drops a quoted message naming an ignored path, and inline interpreter code is metadata-only under an active policy. Mitigation: allowlist capture mode (`install-hooks --capture-mode allowlist`) for sensitive projects. Bite checks: removing the nested re-split, the git object path or its marker-root base, Antigravity's `Cwd` key, the leading-`]` rule, either zsh-group rule, ANSI-C decoding or its numeric-escape rule, the `\o` reading, the inline-code rule, the nesting-depth rule, the nested-script scan, the line-continuation join, the Windows escape reading, the shell-option and interpreter-option value skips, the added runners and interpreters, the glued-flag value, the `file:` URL path, the `~+` resolution, the unknown-tilde rule, the parameter-default reading or case folding each fails the Rust tests, and each TypeScript counterpart fails the Node evidence test; so does reverting the `file:` URL cut, the deep-default rule, the escaped-default reading, the quoted-tilde rule, the harness-output rule or Unicode folding (the new fixture vectors fail against the previous matchers in both languages), and disabling the foreign-marker lookup fails the native, import and Node cross-checkout tests; reading every glob location as literal, skipping search/list locations, or skipping a file tool whose targets cannot be read each fails the native, import and Node glob/search/unreadable tests, removing `apply_patch` header reading fails the own-patch control, and reverting the saved-output glob rule fails the new fixture vectors in both languages; walking globs rooted inside the event's checkout fails the monorepo tests, accepting any literal text for a saved-output glob fails the `*.log` vectors, removing the time budget or counting a `**`'s directories only after it lists fails the bounds tests, and removing the `**`-then-`..` readings, the brace-expansion check, the expanded lookup words, the patch-header trim, the `file_glob` key or the dot-glob parent reading each fails the Rust tests and the Node evidence test; treating every oversized brace expansion as leaving, dropping the brace-built dot-glob check, listing the own checkout's subtree under a `**`, looking up locations in their given order (outside before inside, then shallowest first), dropping the per-directory memo, counting a checkout at home as the own one, keeping the backslash before `$` in double quotes, or dropping the POSIX-class or extglob reading each fails its Rust test and the Node evidence test; in a Windows session a shell `workdir` spelled `/c/x` is read only as Git Bash reads it, so arguments resolved from it miss a native tool's `D:\c\x` reading, the TS marker reader rejects structural errors anywhere in the marker but does not validate other values' TOML (`x = nope` invalidates the policy only natively), an administrative share reached through a loopback or host alias other than `localhost`/`127.0.0.1` (`\\127.0.0.2\c$`, `\\127.1\c$`, `\\<hostname>\c$`) or a `\\wsl$\…` path is matched as the UNC path it spells, Windows matching folds ASCII case only, and a drive-relative word counts as placed when a placeable argument's POSIX reading spells it; a `**/` matches one or more directories, never zero (documented in `marker-file.md`) || 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH || 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL; once `[auth].bearer_token_file` names `auth-tokens/default` (this install's root bearer), `commands/server.rs` `refuse_the_root_token_name` refuses `server add default` and `server remove default` so no profile can be handed, overwrite or delete the root bearer | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `muse_hooks_honour_marker_scope_profiles_exclusions_and_allowlist` (the Meta Muse Code settings-hook front door: marker workspace/project, the profile's server and token never the install's, the payload's session id, an ignored relative `read_file` dropped with a kept control, allowlist silence from an unmarked checkout with a denylist control), `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does); `server.rs` `the_root_bearer_file_name_cannot_be_registered_or_removed` (refused at the root bearer path; another name and an install without a root bearer file are the controls); `server_profiles.rs` `a_default_profile_shares_the_root_bearer_only_at_its_path`, `clear_tokens_keeps_the_root_bearer_and_removes_profile_tokens` | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |@@ -89,7 +89,7 @@ means the boundary is not built yet.| 11h | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks`, upgrade refreshes, and every `hook`/`hook-drain` invocation through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network; a hook config that calls the wrapper never runs in the helper container, and an unavailable client drops the event with exit 0 instead of falling back to it. Only an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` retains the documented script compatibility path and its warning; `AI_MEMORY_NATIVE_BIN` may not point back to the wrapper. For a server initialized on the named volume, `bin/ai-memory` `refresh_volume_token` (run only by `install-hooks`) copies `/data/auth-tokens/default` (only when `/data/config.toml` names it) to an owner-only `native-runner/server-token` through the helper's stdout, and `use_volume_token` points the native client at that copy (the managed host commands and `mcp-bridge` only read it and never enter the container engine) with `AI_MEMORY_AUTH__BEARER_TOKEN_FILE`, so it is a file-sourced token (never rendered into a harness config) and never an argv; a refresh that reads no token from a reachable volume deletes the copy, and a successful full `uninstall --apply` deletes it after the container returns; a bind-mounted `AI_MEMORY_DATA_DIR` is read directly and an explicit `AI_MEMORY_AUTH_TOKEN` wins | `scripts/check-native-packaging.sh` `Checking host-launch wrapper routing`: a default allowlist install reaches the fake native client while a Docker executable that always fails proves no container fallback occurred; the explicit `posix` control reaches fake Docker and adds no native invocation; the self-referential native override is refused. `tests/wrapper_upgrade.sh` `lifecycle hook native host routing`: `hook --event session-start` and `hook-drain` reach the fake native client with the stdin payload while `docker`/`podman` stubs on PATH and in `AI_MEMORY_DOCKER` stay unused, and a non-executable `AI_MEMORY_NATIVE_BIN` exits 0 without reaching the engine; `Checking the wrapper hands host commands the volume's root bearer`: for `mcp-bridge`, `install-hooks` and `run` the fake native client receives the token file (mode 600, right content) and the token is absent from its argv; controls: a bind-mounted data dir and an explicit `AI_MEMORY_AUTH_TOKEN` make no copy and ask no container (bite: dropping the export fails the check); `Checking the host token copy goes with the volume's token and with uninstall`: a volume answering with no token removes the copy and hands none over, while an unreachable engine keeps it; a dry-run, `--only hooks` or failing `uninstall` keeps it and a successful `uninstall --apply` removes it (bite: without either removal the check fails); `auth_default_e2e.rs` `a_host_client_given_the_token_file_by_env_authenticates` (the native side of the handoff, with a no-variable control) | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 || 11j | Offline recovery journal and transcript replay | `ai-memory-cli/src/commands/recovery.rs` keeps bounded locators, ordered semantic transcript digests, pre-launch cursors and persistent correlated-delivery/loss evidence in an atomic journal, refuses a symlinked data dir and any symlinked component inside it (ancestors above the data dir are trusted, so macOS `/var` → `/private/var` works), sanitizes/caps failure reasons, and bounds each replay plus the whole pass; `hook_spool` coordinates enqueue and quarantine with short filesystem locks, canonically resolves partial scope from the recorded cwd, bounds per-file reads and current global occupancy across the main spool and recovery directories, sweeps completed tombstones, and holds correlated events outside drain until replay succeeds or restores them on failure; degraded resumes use `ai-memory-workstream`'s adapter-validated delta export, whose blocking parse and baseline scans are capped by record, event-count, source-byte and serialized-byte totals; `backfill::import_exact_session` chunks by item and byte limits and requires per-item durable acknowledgements; `run.rs` journals every session launch, including explicit spool-only evidence for unsupported exporters, and journals a resumed export only after capturing its exact pre-launch cursor; `workstream.rs` `/recover/finish` retains owner/project authorization, rejects superseded runs, and validates a finished retry by durable transcript/native/cursor/exit identity without regenerating its checkpoint; validated recovery ingest keys bind session, agent, event kind and sanitized event identity until session purge | `transcript.rs` `persisted_baseline_exports_only_offline_append_and_rejects_rewrite`, parser/baseline cap and ordered-semantic digest tests; CLI `run_offline.rs` real degraded spool-only and overlap/idempotency tests; `recovery.rs` `spool_only_without_correlated_evidence_never_auto_clears`, `a_dropped_spool_event_stays_lost_on_the_next_empty_pass`, loss/time-budget tests, `symlinked_journal_and_ancestor_are_refused`, `a_symlinked_ancestor_of_the_data_dir_is_trusted`, `a_symlink_inside_a_data_dir_under_a_symlinked_ancestor_is_refused`; `hook_spool.rs` partial-scope late enqueue, completion-race, occupancy churn/active-cap, bounded-read and tombstone-sweep tests, plus interval isolation (`completed_tombstone_keeps_a_later_resume_of_the_same_session` proves a post-interval resume hook is delivered, `completing_one_recovery_interval_leaves_the_other_intervals_entries_intact` proves one interval's completion never consumes another's evidence and ambiguous entries fail closed into the main spool); `backfill.rs` `two_sequential_recovery_intervals_on_one_resumed_session_replay_exactly_once` proves the second interval's content and session-end are stored with end-of-session effects while reruns stay pure replays; `transcript.rs` `an_oversized_first_record_is_skipped_by_session_listing_caps` proves the first-record byte caps bite before allocation; store `insert_observation_ingest_dedups_on_key` rejects cross-session and changed-event preclaims; hooks `expired_run_recovery_is_owner_only_and_refuses_superseded_runs` proves changed transcript refusal and changed-checkpoint no-op | STRONG on Unix integration coverage; Unix lock opens use no-follow and atomic replacement rechecks the destination. Windows owner-only ACL/reparse and lock semantics require the PR `windows` lane || 11i | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label |-| 11k | Server-side tool drop list (#1241) | `ai-memory-hooks/src/drop_list.rs` `IngestDropList::matches`, checked in `router.rs` `admit_hook` and the `handle_hook_batch` loop right after the client capture protocol and before the rate limiter, the ingest semaphore, the sanitizer and storage; lists from `[ingest] drop_tool_use_id_prefixes` / `drop_tool_names`, validated once in `Config::load` (at most 64 entries of 128 printable characters each). Only tool events match: a tool-call id by prefix, a tool name exactly, both read through the per-agent mapping `capture_policy::tool_payload_fields` that tool metadata uses (generic Claude-style fields for an agent without one; Factory Droid sends no tool-call id, so only its tool name can match; Meta Muse Code sends its provider call id in `tool_use_id`, and CodeBuddy Code Claude Code's `tool_use_id`, so both can). A drop answers 202 and counts as `dropped_by_policy`; the matched value is never logged | `router.rs` `the_ingest_drop_list_drops_before_any_capacity_is_spent` (with the semaphore exhausted a listed event still answers 202; control: an unlisted one gets 429) and `the_ingest_drop_list_applies_to_hook_batches` (listed items acknowledged as policy drops, the unlisted item ingested); `drop_list.rs` unit tests (prefix only at the start, names only exact, non-tool events never match, bounds refused; `each_agent_is_matched_on_its_own_tool_fields` matches OpenCode `callID`, Hermes `extra.tool_call_id`, Antigravity `toolCall.name`, Muse and CodeBuddy `tool_use_id` and CodeBuddy `tool_name`, with same-agent controls kept, and fails when only the generic fields are read). Both router tests fail with `matches` forced to `false` | STRONG. The list applies to every project on the server; it narrows what is stored and never widens access |+| 11k | Server-side ingest drop list: tool id/name lists (#1241) and whole event kinds (`[ingest] drop_events`) | `ai-memory-hooks/src/drop_list.rs` `IngestDropList`: `matches` for the tool lists (a tool-call id by prefix, a tool name exactly) and `matches_event_kind` for the whole kinds (every `[ingest] drop_events` value parsed with the typed `HookEvent::parse`; `session-start`/`session-end` and the `other` bucket rejected), both validated once in `Config::load` (tool lists: at most 64 entries of 128 printable characters each). Checked in `router.rs` `admit_hook` and the `handle_hook_batch` loop, both before the rate limiter, the ingest semaphore, the sanitizer and storage: the tool lists right after the client capture protocol, the whole kinds right after the subagent exclusion (`should_drop_subagent`), so a marked subagent event seeds the tracking set its unmarked tail is dropped against even when its kind is listed. The tool lists match only tool events and are read through the per-agent mapping `capture_policy::tool_payload_fields` that tool metadata uses (generic Claude-style fields for an agent without one; Factory Droid sends no tool-call id, so only its tool name can match; Meta Muse Code sends its provider call id in `tool_use_id`, and CodeBuddy Code Claude Code's `tool_use_id`, so both can). A drop answers 202 and counts as `dropped_by_policy`; the matched value is never logged | tool lists: `router.rs` `the_ingest_drop_list_drops_before_any_capacity_is_spent` (with the semaphore exhausted a listed event still answers 202; control: an unlisted one gets 429) and `the_ingest_drop_list_applies_to_hook_batches` (listed items acknowledged as policy drops, the unlisted item ingested); `drop_list.rs` unit tests (prefix only at the start, names only exact, non-tool events never match, bounds refused; `each_agent_is_matched_on_its_own_tool_fields` matches OpenCode `callID`, Hermes `extra.tool_call_id`, Antigravity `toolCall.name`, Muse and CodeBuddy `tool_use_id` and CodeBuddy `tool_name`, with same-agent controls kept, and fails when only the generic fields are read). Both router tests fail with `matches` forced to `false`. whole kinds: `router.rs` `the_ingest_drop_events_drops_the_named_kind_and_keeps_the_rest` (the named kind acknowledged and not stored; the pair, the prompt and a lifecycle event stored; lifecycle not dropped), `the_ingest_drop_events_drops_before_any_capacity_is_spent` (semaphore exhausted: the named kind still answers 202, a kept kind gets 429), `the_ingest_drop_events_consumes_no_rate_budget` (burst 1: kind drops spend no rate token, the source's first kept event is admitted, the second is 429), `the_ingest_drop_events_batch_reports_per_index_outcomes_and_only_stores_the_kept` (per-index `dropped_policy`/`stored` results; kept events persisted, the dropped one absent), `the_ingest_drop_events_keeps_dropping_the_unmarked_subagent_tail` and `the_ingest_drop_events_keeps_dropping_the_unmarked_subagent_tail_in_batches` (with `drop_events = ["subagent-start"]` the marked start seeds the tracking, the unmarked tail drops on both ingresses, and a non-subagent prompt is kept), `a_marked_event_of_a_dropped_kind_still_seeds_subagent_tracking` (a marked `pre-tool-use` listed in `drop_events` still seeds before it is dropped); `drop_list.rs` `drop_events_*` unit tests (kind-only matching, wire spellings, session-state and unknown kinds refused). Mutants: the kind check moved back before the subagent exclusion fails the two tail tests and the seeding test; removing the batch kind check, or its result entry, fails the batch contract test | STRONG. The list applies to every project on the server; it narrows what is stored and never widens access || 11l | Marketplace plugin front door: a plugin-launched event gets exactly the native hook's capture policy, scope and server routing, is captured once beside settings-file hooks, and sends nothing without the binary (#1166) | `plugins/*/scripts/ai-memory-hook` (rendered from `crates/ai-memory-cli/templates/plugin/ai-memory-hook.sh` by `render_plugins.rs`) has no capture logic: it only finds the binary (an `ai_memory_bin` option is honoured only as an absolute path, so a checkout cannot plant a relative one) and runs `ai-memory hook` with `AI_MEMORY_HOOK_ORIGIN=<agent>-plugin`, `hook` first so the Docker wrapper routes it, omitting `--server-url` when the option is empty (a pre-3.0 binary's usage error, exit 2 before it reads stdin, is retried once against the default local server with a stderr hint), and without a binary drains stdin, prints `{}` (guidance on `session-start` only) and exits 0; `hook.rs` `is_dropped_plugin_copy` + `plugin_origin.rs` `drops_plugin_event` drop a plugin copy when the user `settings.json` (honouring `CLAUDE_CONFIG_DIR`) or the checkout's `.claude/settings.local.json` carries an ai-memory hook for the same event (`install_hooks::hooks_file_delivers_ai_memory_event`); a Droid-launched copy (`droid-plugin`) is checked against the one file Droid reads hooks from (`~/.factory/hooks.json`, else the `hooks` key of `~/.factory/settings.json`); a Muse-launched copy (`muse-plugin`, recognized by `MUSE_PLUGIN_ID` with `MUSE_SESSION_ID`) is checked against the `hooks` key of `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`, and its subagent events are dropped; both drop a folderless session (no `cwd`, or a Claude desktop `scratch-workspaces` cwd); Codex plugin events are never de-duplicated (an untrusted settings hook is skipped silently, so dropping could lose the event); the drift test keeps every plugin hook on the native path (no `hooks/<agent>/*.sh`, no credential in any plugin file) | CLI `tests/suite/plugins.rs` through the committed launcher and the real binary: `ignore_paths_hold_through_the_plugin` (ignored path never spooled; public-file control kept), `allowlist_mode_holds_through_the_plugin` (unmarked checkout emits nothing, prompts included; marked control captured), `marker_scope_routes_plugin_events`, `server_profiles_route_plugin_events` (profile URL and token, never the plugin's URL), `a_settings_hook_for_the_same_event_drops_the_plugin_copy` (user and project settings; unwired-event and no-settings controls), `a_droid_hook_for_the_same_event_drops_the_droid_plugin_copy` (Droid `hooks.json`; no-Droid-hook, Claude-settings-only, unwired-event and folderless controls), `a_muse_hook_for_the_same_event_drops_the_muse_plugin_copy` (Muse `settings.json`; no-Muse-hook, Claude-settings-only and unwired-event controls; subagent and folderless events dropped), `plugin_origin.rs` `muse_plugin_copy_is_dropped_when_muse_settings_hooks_deliver_the_event` (a matcher-narrowed hook does not count) and `test_plugin_launcher.sh` (an inherited `MUSE_SESSION_ID` without `MUSE_PLUGIN_ID` stays `claude-code`), `folderless_sessions_are_not_captured_through_the_plugin`, `without_a_binary_nothing_is_sent_and_the_agent_is_not_blocked`, `foreign_hosts_are_attributed_or_ignored`, `committed_plugins_match_the_renderer`, `plugin_tree_carries_no_credentials`; `plugin_origin.rs` unit tests (`codex_plugin_events_are_never_deduplicated_against_settings`, `droid_settings_hooks_count_only_while_hooks_json_is_absent`, `only_a_catch_all_matcher_suppresses_the_plugin_copy`: a settings hook narrowed by a matcher never drops the plugin copy); `hook.rs` `plugin_copy_is_dropped_only_with_the_plugin_origin`; `tests/hooks/test_plugin_launcher.sh` (a relative `ai_memory_bin` planted in the checkout is never run; PATH control); `tests/e2e/claude_plugin_smoke.py` (real `claude -p`: settings hook plus plugin give one `user-prompt`) | STRONG. Verified 2026-10-13: removing the `is_dropped_plugin_copy` guard fails the de-duplication and folderless tests (and the smoke reports `user-prompt x2`); disabling the native `Drop` disposition or the allowlist gate fails the `ignore_paths` and allowlist tests through the launcher. Not covered: tool events from a live model turn (no credential in CI), Windows Git Bash, Cowork and the desktop Code tab (see `docs/design-marketplace-plugins.md`) || 12 | Network/auth posture, including auth on by default for new installs (an existing install keeps loopback no-auth until `ai-memory auth enable`) | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart`; new-install default: `commands/init.rs` `root_bearer_for_new_config` mints a root bearer only on a fresh data dir (no config file and no database) and only when no bearer is supplied otherwise, via `local_auth.rs` `provision_root_token` (`auth-tokens/` `0700`, file `0600`, atomic, reused when present) and records the relative `[auth].bearer_token_file`; `config.rs` `apply_bearer_token_file` reads it once (`AI_MEMORY_AUTH_TOKEN` wins, inline + file together refused, a missing or blank file leaves no bearer) and `discover_root_token` lets a packaged install's client commands use `<data_dir>/auth-tokens/default` only with no config file at the probed path, a loopback server URL and no registered `default` profile; `serve.rs` `refuse_a_missing_token_file` stops a server whose configured file holds no token; `AuthSettings::renderable_bearer_token` keeps a file-sourced token out of every renderer: `install_mcp.rs` `route_file_token` (Claude Code gets the session-aware `ai-memory mcp-bridge` entry, Codex and Prime Agent name `AI_MEMORY_AUTH_TOKEN`, every other client a `stdio_bridge_entry` that runs `mcp-bridge --no-session-id` in its documented stdio shape, Pi keeps its extension, ZCode (HTTP-only) is refused) and `mcp_bridge.rs`, which authenticates with the config-resolved bearer and connects upstream before serving stdio, so a refused token ends it with `401 Unauthorized` instead of hanging; `uninstall.rs` `mcp_entry_is_ours` / `toml_mcp_entry_targets` recognise bridge entries by `install_mcp::bridge_entry_url`; `auth_enable.rs` `rewire_clients` re-registers every client whose entry targets this server, `install_hooks.rs` (persisted to the hook credential files, never inlined, not even on the F5 persist-failure fallback), `setup_agent.rs`, `run_autowire.rs`, `setup.rs` (runs `init`, adopts the minted token in memory through `adopt_token_file`, and calls the installers with no explicit token; the rendered user unit carries none; `user_service.rs` `is_rendered_by_setup` lets `uninstall` stop and delete only a unit carrying `setup`'s identity line whose SHA-256 still matches, never a hand-written or edited one); `local_auth.rs` `seed_hook_credential` gives hooks the token through `auth-token`/`auth-header` and keeps a different stored credential; `uninstall.rs` keeps the root bearer (`server_profiles::clear_tokens` `keep`); `commands/auth_enable.rs` is the idempotent opt-in | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls; `cli/tests/suite/auth_default_e2e.rs` against the shipped binary: `a_fresh_install_requires_the_token_and_its_own_clients_still_work` (after `init`, unauthenticated `/mcp`, `/hook`, `/api/v1/projects`, `/admin/status` → 401 and `/healthz` → 200; the same requests with the token succeed; the native hook delivers with no token in its environment, `status` authenticates through config, `mcp-bridge` lists tools; the token is in neither process's `/proc/<pid>/cmdline`; after `install-hooks`, `install-mcp --apply` for every client it writes (21, by default config path under the test home), a refused ZCode install and `auth enable` twice, a scan of the whole home finds the token nowhere and a scan of the data dir finds it only in the token file and the two hook credential files), `an_existing_install_is_unchanged_until_auth_enable` (control: a pre-default install serves every route open and `status` names the fix; `auth enable` twice is idempotent, rewires Claude Code to the bridge, and after a restart the routes refuse and the hook still delivers), `a_packaged_install_with_an_external_config_wires_its_clients`, `uninstall_keeps_the_root_bearer_and_a_missing_one_stops_the_server`, `a_host_client_given_the_token_file_by_env_authenticates`; `init.rs` `a_fresh_init_mints_a_root_bearer_the_loader_reads`, `init_on_an_existing_install_does_not_turn_auth_on`, `init_with_a_supplied_bearer_mints_nothing`, `re_running_init_keeps_the_same_root_bearer`; `config.rs` `a_relative_bearer_token_file_resolves_against_the_data_dir`, `a_missing_or_blank_bearer_token_file_is_reported_not_guessed`, `the_env_token_wins_over_the_bearer_token_file`, `an_inline_bearer_and_a_bearer_token_file_together_are_refused`, `a_client_without_a_config_file_discovers_the_root_bearer`, `root_bearer_discovery_is_refused_outside_its_narrow_case` (existing config, remote URL, `default` profile, env token); `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (`tools/list` and a scoped `memory_query` through `mcp-bridge --no-session-id` against a fresh auth-on server, the token in neither the bridge's `/proc/<pid>/cmdline` nor its `/proc/<pid>/environ`; control: the session-aware mode still refuses to start without `CLAUDE_CODE_SESSION_ID`) and `a_bridge_without_the_token_is_refused_cleanly_not_hung` (exits promptly naming `401 Unauthorized`); `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id`, `a_session_less_upstream_config_carries_no_session_header`, `stdio_bridge_forwards_tools_and_session_header_in_both_http_modes` (control); `install_mcp.rs` `a_file_sourced_token_wires_every_client_without_entering_its_config` (every written client: no token, no header, an entry that reaches the server; ZCode refused and unwritten), `stdio_bridge_entries_follow_each_clients_documented_shape`, `inline_and_explicit_tokens_still_embed_as_before` (control); `uninstall.rs` `bridge_entries_are_recognised_by_their_upstream_url` (JSON, OpenCode array and TOML shapes; a bridge to another server and a foreign command are kept); `install_hooks.rs` `a_file_sourced_token_is_persisted_but_never_embedded`; `auth_enable.rs` `enable_twice_is_idempotent_and_leaks_the_token_into_no_harness_config` (every client pre-wired over HTTP is re-registered, ZCode reported as manual, the second run byte-identical), `enable_leaves_an_entry_for_another_server_alone`, `enable_refuses_while_a_default_profile_would_share_the_token`; `local_auth.rs` `the_root_bearer_is_owner_only`, `seeding_never_replaces_a_different_hook_credential`; `setup_e2e.rs` `setup_installs_wires_is_idempotent_and_uninstall_removes_its_unit` (one `setup --yes` in a fresh temp home: the token is in no file under the home but the token file and the two hook credential files, not in the user unit and not in `setup`'s output; the self-check's `memory_status` and a hook event authenticate through the file; `uninstall` then disables and deletes the unit once and a second `uninstall` calls nothing), `uninstall_leaves_a_unit_it_did_not_write` (adversarial: the packaged unit copied by hand is kept, no `systemctl` call); `user_service.rs` `a_foreign_or_edited_unit_is_left_alone`, `rendered_units_carry_an_identity_that_survives_only_unedited` | STRONG. Bite checks for the new-install default: with fresh-install minting disabled the fresh e2e routes answer without a token and the `init` tests fail; with `renderable_bearer_token` returning the file token, `install-mcp`, `install-hooks`, `auth enable` and the e2e scans find it in harness configs; without the `serve` refusal a server whose token file was deleted keeps running (the e2e times out on it); without the hook seeding the fresh e2e hook is refused; without `clear_tokens` `keep` uninstall deletes the root bearer; with `route_file_token` no longer choosing the stdio bridge the every-client and `auth enable` tests fail; with `auth enable` skipping the re-registration its test fails; with the session-less mode forwarding an inherited id the bridge unit test fails; without the 401 naming the refusal e2e fails; without bridge-entry recognition the uninstall test fails; with `setup` handing the token to `install-mcp` its scan finds it in `.claude.json`; with `is_rendered_by_setup` accepting any unit, the foreign-unit tests fail; with discovery removed the packaged e2e gets 401, and with each discovery guard removed the matching case of `root_bearer_discovery_is_refused_outside_its_narrow_case` fails. Residual: a hand-edited `servers.toml` that adds a `default` profile after the root bearer exists would read the root bearer as that profile's token (`server add` refuses it, `auth enable` refuses while it exists); ZCode takes only HTTP entries and is refused, so it needs a manual entry; the stdio entries for Zero, Muse Code and DeepSeek Harness follow their documented or source-level format but were not run against those clients || 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten |