Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(capture): record tool names behind [ingest] record_tool_names
geeksilva977b0b6d882e59
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f764ab50..a59b2799 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,15 @@ version in [`docs/changelog/`](docs/changelog/):### Added+- Added `[ingest] record_tool_names` (`AI_MEMORY_INGEST__RECORD_TOOL_NAMES`),+ off by default. When it is on, each tool call keeps its own name, so a+ Claude Code shell call is stored as `tool non-file: Bash` instead of+ `tool non-file`. A `Skill` call also keeps the skill it ran, and an `Agent`+ call keeps its subagent type. Session pages count calls by name and+ handoffs list them by name. Only short identifiers are kept, never a tool's+ arguments, and a call that a capture policy reduced to metadata stays+ unnamed (#PRNUM).+- `global_scope_hits` now include their workspace, project, and global scope,and `memory_read_page` accepts `scope: "global"`. Supplemental global searchresults can therefore be read directly without risking a same-path lookup indiff --git a/crates/ai-memory-cli/src/commands/backfill.rs b/crates/ai-memory-cli/src/commands/backfill.rsindex 0a410253..8b528afc 100644--- a/crates/ai-memory-cli/src/commands/backfill.rs+++ b/crates/ai-memory-cli/src/commands/backfill.rs@@ -1932,6 +1932,7 @@ mod tests {mid_session_routing: ai_memory_core::MidSessionRouting::default(),profile: ai_memory_core::profile::ProfileSettings::default(),ingest_drop_list: ai_memory_hooks::IngestDropList::default(),+ record_tool_names: false,skip_wiki_checkpoints: false,};let endpoint = ServerEndpoint::for_hook_target("http://localhost".into(), None);@@ -2134,6 +2135,7 @@ mod tests {mid_session_routing: ai_memory_core::MidSessionRouting::default(),profile: ai_memory_core::profile::ProfileSettings::default(),ingest_drop_list: ai_memory_hooks::IngestDropList::default(),+ record_tool_names: false,skip_wiki_checkpoints: false,};let endpoint = ServerEndpoint::for_hook_target("http://localhost".into(), None);diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex e58ecfd6..02b2ed2a 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -1687,6 +1687,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {mid_session_routing: config.routing.mid_session,profile: config.profile.clone(),ingest_drop_list: (*config.ingest.drop_list).clone(),+ record_tool_names: config.ingest.record_tool_names,// Benchmark-only escape (docs/benchmarks/README.md), read once// here so the hooks crate keeps making no environment reads.skip_wiki_checkpoints: benchmark_skip_wiki_checkpoints(),diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 95f48947..9c4bce0b 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -1359,6 +1359,12 @@ pub struct IngestSettings {/// (`AI_MEMORY_INGEST__DROP_EVENTS=pre-tool-use`).#[serde(default, deserialize_with = "deserialize_string_or_vec")]pub drop_events: Vec<String>,+ /// Name each tool call in its observation: `tool non-file: Bash` instead+ /// of `tool non-file`, plus the skill (`Skill`) or subagent type+ /// (`Agent`) a Claude Code call ran. Only identifiers are kept, never a+ /// tool's arguments, and a call a capture policy reduced to metadata stays+ /// unnamed. Off by default (`AI_MEMORY_INGEST__RECORD_TOOL_NAMES`).+ pub record_tool_names: bool,/// The validated list the hook router checks. Set by [`Config::load`];/// never read from or written to a config file. Kept off the `Config`/// stack frame because that value is constructed in short-stack CLI@@ -5426,6 +5432,57 @@ input_token_safety_margin = {margin}/// `[ingest]` is read once into the validated drop list the hook router/// checks, and an out-of-bounds entry fails startup instead of being/// silently ignored (#1241).+ /// `[ingest] record_tool_names` is off unless the file turns it on.+ #[test]+ fn ingest_record_tool_names_defaults_off_and_loads_from_file() {+ let tmp = TempDir::new().unwrap();+ let config_path = tmp.path().join("config.toml");+ std::fs::write(&config_path, "").unwrap();+ let config = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap();+ assert!(!config.ingest.record_tool_names);++ std::fs::write(&config_path, "[ingest]\nrecord_tool_names = true\n").unwrap();+ let config = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap();+ assert!(config.ingest.record_tool_names);+ }++ /// The env form of `[ingest] record_tool_names`. Same child-process marker+ /// pattern as `ingest_drop_events_env_overrides_default`.+ #[test]+ fn ingest_record_tool_names_env_turns_it_on() {+ const CHILD_MARKER: &str = "AI_MEMORY_TEST_RECORD_TOOL_NAMES_CHILD";+ if std::env::var_os(CHILD_MARKER).is_some() {+ let tmp = TempDir::new().unwrap();+ let config_path = tmp.path().join("config.toml");+ std::fs::write(&config_path, "[ingest]\n").unwrap();+ let config = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap();+ assert!(config.ingest.record_tool_names);+ println!("record-tool-names-env-applied");+ return;+ }++ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .arg("--exact")+ .arg("config::tests::ingest_record_tool_names_env_turns_it_on")+ .arg("--test-threads=1")+ .arg("--nocapture")+ .env(CHILD_MARKER, "1")+ .env("AI_MEMORY_INGEST__RECORD_TOOL_NAMES", "true")+ .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("record-tool-names-env-applied"),+ "child stdout: {}",+ String::from_utf8_lossy(&output.stdout)+ );+ }+#[test]fn ingest_drop_lists_load_into_the_router_list_and_reject_bad_entries() {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 5832dec2..264a1197 100644--- a/crates/ai-memory-cli/templates/config.default.toml+++ b/crates/ai-memory-cli/templates/config.default.toml@@ -378,6 +378,15 @@ ledger_retention_months = 0 # 0 = never delete hook event ledgers# default (nothing dropped).# Env equivalent: AI_MEMORY_INGEST__DROP_EVENTS=pre-tool-use# drop_events = ["pre-tool-use"]+#+# Name each tool call in its observation instead of only its family: the title+# `tool non-file` becomes `tool non-file: Bash`, and a Claude Code `Skill` or+# `Agent` call also keeps the skill or subagent type it ran. Session pages and+# handoffs then count calls by name. Only identifiers are kept, never a tool's+# arguments (a shell command, a prompt, a path), and a call a capture policy+# reduced to metadata stays unnamed. Off by default.+# Env equivalent: AI_MEMORY_INGEST__RECORD_TOOL_NAMES=true+# record_tool_names = true# Privacy strip.#diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex af964265..61027356 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -187,6 +187,85 @@ pub(crate) fn mcp_tool_name(name: &str) -> Option<McpToolName> {})}+/// Longest harness tool name kept by `[ingest] record_tool_names`, the same+/// bound as an MCP tool name: every documented harness tool name fits.+const MAX_TOOL_NAME_CHARS: usize = 64;++/// Longest skill or subagent identifier kept by `[ingest] record_tool_names`.+/// Plugin skills carry a `plugin:skill` prefix, so this is wider than a name.+const MAX_TOOL_DESCRIPTOR_CHARS: usize = 128;++/// A closed-tool call's own name, plus the one identifier that says which+/// skill or subagent it ran. Kept only when the operator opts in with+/// `[ingest] record_tool_names`; [`crate::HookEnvelope::record_tool_name`]+/// writes it into the observation.+///+/// Never an argument. A shell command, a prompt, a path or a URL stays out:+/// the name and the two descriptors are kept only when they are short+/// identifiers, so free text a harness put in those fields is refused whole.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct RecordedToolName {+ pub(crate) name: String,+ /// `tool_input.skill` of Claude Code's `Skill` tool.+ pub(crate) skill: Option<String>,+ /// `tool_input.subagent_type` of Claude Code's `Agent` (formerly `Task`)+ /// tool.+ pub(crate) subagent_type: Option<String>,+}++/// The tool name a closed-tool event carries, read from the same adapter+/// fields [`tool_observation_metadata`] uses, and refused unless it is at most+/// 64 ASCII letters, digits, `_` or `-`.+///+/// The skill and subagent identifiers are Claude Code's own `tool_input`+/// fields (<https://code.claude.com/docs/en/hooks>, "PreToolUse input": the+/// `Agent` tool's `subagent_type`; the `Skill` tool's `skill`), so they are+/// read for Claude Code only. Each is kept when it is at most 128 ASCII+/// letters, digits, `_`, `-`, `.` or `:`.+pub(crate) fn recorded_tool_name(agent: AgentKind, raw: &Value) -> Option<RecordedToolName> {+ let (name, _) = tool_payload_fields(agent, raw)?;+ if !valid_tool_name(name) {+ return None;+ }+ let input = if agent == AgentKind::ClaudeCode {+ raw.get("tool_input")+ } else {+ None+ };+ let descriptor = |key: &str| {+ input+ .and_then(|input| input.get(key))+ .and_then(Value::as_str)+ .filter(|value| valid_tool_descriptor(value))+ .map(str::to_owned)+ };+ Some(RecordedToolName {+ name: name.to_owned(),+ skill: (name == "Skill").then(|| descriptor("skill")).flatten(),+ subagent_type: matches!(name, "Agent" | "Task")+ .then(|| descriptor("subagent_type"))+ .flatten(),+ })+}++/// A harness tool name as `[ingest] record_tool_names` keeps it: an+/// identifier, never free text.+pub(crate) fn valid_tool_name(name: &str) -> bool {+ !name.is_empty()+ && name.len() <= MAX_TOOL_NAME_CHARS+ && name+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')+}++fn valid_tool_descriptor(value: &str) -> bool {+ !value.is_empty()+ && value.len() <= MAX_TOOL_DESCRIPTOR_CHARS+ && value+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.' | b':'))+}+/// Safe outcome class for a completed tool call.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum ToolOutcome {diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 72a0f48b..0da80d6b 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -207,6 +207,12 @@ pub struct HookEnvelope {/// [`HookEnvelope::occurred_at_micros`]; never trust it unchecked.#[serde(default)]pub occurred_at: Option<String>,+ /// The closed-tool call's validated name and skill/subagent identifier,+ /// read at parse time and written into the title and body only by+ /// [`HookEnvelope::record_tool_name`] (`[ingest] record_tool_names`).+ /// The metadata-only rebuilds clear it.+ #[serde(skip)]+ pub(crate) recorded_tool: Option<crate::capture_policy::RecordedToolName>,/// The agent's raw JSON, kept for forensics.pub raw: serde_json::Value,}@@ -257,6 +263,7 @@ impl std::fmt::Debug for HookEnvelope {"body_excerpt",&self.body_excerpt.as_ref().map(|_| "<redacted>"),)+ .field("recorded_tool", &self.recorded_tool.is_some()).field("raw", &"<redacted>").finish()}@@ -690,6 +697,11 @@ impl HookEnvelope {let tool_metadata = tool_observation_metadata(agent, &raw, event == HookEvent::PreToolUse);let closed_tool_event = matches!(event, HookEvent::PreToolUse | HookEvent::PostToolUse)&& closed_tool_agent(agent);+ let recorded_tool = if closed_tool_event && tool_metadata.is_some() {+ crate::capture_policy::recorded_tool_name(agent, &raw)+ } else {+ None+ };let title_hint = if closed_tool_event {tool_metadata.as_ref().map(safe_tool_title).or_else(|| {(event == HookEvent::PostToolUse && agent == AgentKind::OpenCode)@@ -764,10 +776,53 @@ impl HookEnvelope {title_hint,body_excerpt,occurred_at,+ recorded_tool,raw,}}+ /// Name a closed-tool call (`[ingest] record_tool_names`): the title+ /// `tool <family>` becomes `tool <family>: <name>`, and the body gains a+ /// `tool_name:` line, plus `skill:` or `subagent_type:` when the call ran+ /// one. The family stays first, so [`tool_family_from_title`] still reads+ /// it.+ ///+ /// Does nothing unless the title is still the family label this module+ /// wrote. A metadata-only rebuild writes a bare family and clears+ /// [`Self::recorded_tool`], so a call a capture policy reduced to metadata+ /// never gets its name back.+ pub fn record_tool_name(&mut self) {+ let Some(tool) = self.recorded_tool.take() else {+ return;+ };+ let Some(title) = self+ .title_hint+ .as_deref()+ .filter(|title| matches!(split_tool_title(title), Some((_, None))))+ .filter(|title| title.starts_with("tool "))+ else {+ return;+ };+ self.title_hint = Some(format!("{title}: {}", tool.name));+ if let Some(body) = self.body_excerpt.take() {+ let mut lines = format!("tool_name: {}", tool.name);+ for (key, value) in [+ ("skill", &tool.skill),+ ("subagent_type", &tool.subagent_type),+ ] {+ if let Some(value) = value {+ lines.push_str(&format!("\n{key}: {value}"));+ }+ }+ // The body opens with the `tool_family:` line; the name goes+ // right under it, above the call id and the output.+ self.body_excerpt = Some(match body.split_once('\n') {+ Some((family, rest)) => format!("{family}\n{lines}\n{rest}"),+ None => format!("{body}\n{lines}"),+ });+ }+ }+/// Parse and bound [`Self::occurred_at`] into a microsecond timestamp/// suitable for `NewSession`/`NewObservation::occurred_at`.///@@ -889,7 +944,8 @@ fn safe_tool_title(metadata: &ToolObservationMetadata) -> String {}/// `true` when `title` is one this module produced from a [`ToolFamily`]-/// rather than from the harness's own tool name.+/// rather than from the harness's own tool name: `tool <family>`, or+/// `tool <family>: <name>` once `[ingest] record_tool_names` named the call.////// Derived from the same serde representation [`safe_tool_title`] writes, so/// a new `ToolFamily` variant is recognised here without a second edit — the@@ -899,16 +955,59 @@ fn safe_tool_title(metadata: &ToolObservationMetadata) -> String {/// not a name for what they did, so a reader gains nothing from being told a/// session spent itself "across tool non-file and tool unknown".pub(crate) fn is_safe_tool_title(title: &str) -> bool {- title.strip_prefix("tool ").is_some_and(|family| {- serde_json::from_value::<ToolFamily>(serde_json::Value::String(family.to_owned())).is_ok()- })+ title.starts_with("tool ") && split_tool_title(title).is_some()+}++/// Split a tool label this crate wrote into its family and, when+/// `[ingest] record_tool_names` named the call, the tool name: `tool <family>`,+/// `tool <family>: <name>`, or the bare `<family>` the reserved-protocol path+/// writes. `None` for anything else, a harness's own raw tool name included.+fn split_tool_title(title: &str) -> Option<(ToolFamily, Option<&str>)> {+ let (label, name) = match title.strip_prefix("tool ") {+ Some(rest) => match rest.split_once(": ") {+ Some((family, name)) if crate::capture_policy::valid_tool_name(name) => {+ (family, Some(name))+ }+ Some(_) => return None,+ None => (rest, None),+ },+ None => (title, None),+ };+ let family =+ serde_json::from_value::<ToolFamily>(serde_json::Value::String(label.to_owned())).ok()?;+ Some((family, name))+}++/// The name a reader should see for a tool observation title: the recorded+/// tool name of a `tool <family>: <name>` label, or `None` for a bare family+/// label, which names no tool. Any other title is a harness's own tool name+/// and is returned as is.+pub(crate) fn listable_tool_name(title: &str) -> Option<&str> {+ if title.is_empty() {+ return None;+ }+ match split_tool_title(title) {+ Some((_, name)) => name,+ None => Some(title),+ }+}++/// The text to show for a tool observation title in a count: the recorded+/// name when there is one, the title itself otherwise, so a bare family label+/// still shows as `tool non-file`.+pub(crate) fn tool_title_display(title: &str) -> &str {+ match split_tool_title(title) {+ Some((_, Some(name))) => name,+ _ => title,+ }}/// Map a stored observation title back to the [`ToolFamily`] it was derived/// from, recognising **both** spellings this crate emits for a family label:/// the bare `canonical_tool_name` form the reserved-protocol path writes/// ("file" / "search-list" / "non-file" / "unknown") and the `"tool "`-prefixed-/// [`safe_tool_title`] form every closed-tool agent writes ("tool file", …).+/// [`safe_tool_title`] form every closed-tool agent writes ("tool file", …),+/// with or without the `: <name>` that [`HookEnvelope::record_tool_name`] adds.////// Returns `None` for a harness's own raw tool name ("edit", "bash", "Read"),/// which is never one of these labels. That distinction is load-bearing: it is@@ -917,8 +1016,7 @@ pub(crate) fn is_safe_tool_title(title: &str) -> bool {/// representation with [`safe_tool_title`] and [`is_safe_tool_title`], so a new/// `ToolFamily` variant is recognised here without a second edit.pub(crate) fn tool_family_from_title(title: &str) -> Option<ToolFamily> {- let family = title.strip_prefix("tool ").unwrap_or(title);- serde_json::from_value::<ToolFamily>(serde_json::Value::String(family.to_owned())).ok()+ split_tool_title(title).map(|(family, _)| family)}fn safe_tool_body(@@ -4427,4 +4525,212 @@ mod tests {Some("tool_family: non-file\ntool_call_id: omp-1\noutcome: unknown\n---\ntests passed"));}++ fn claude_tool_event(event: &str, body: serde_json::Value) -> HookEnvelope {+ HookEnvelope::from_query_and_body(+ HookQuery {+ event: event.into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ body,+ )+ }++ /// `[ingest] record_tool_names`: a Claude Code shell call keeps its family+ /// first and gains its name, never its command.+ #[test]+ fn record_tool_name_names_the_call_and_never_keeps_its_arguments() {+ let mut env = claude_tool_event(+ "PostToolUse",+ serde_json::json!({+ "session_id": "s",+ "tool_name": "Bash",+ "tool_use_id": "toolu_1",+ "tool_input": {"command": "curl -H 'Authorization: Bearer sk-secret' https://x"},+ "tool_response": {"stdout": "ok"}+ }),+ );+ assert_eq!(env.title_hint.as_deref(), Some("tool non-file"));+ env.record_tool_name();+ assert_eq!(env.title_hint.as_deref(), Some("tool non-file: Bash"));+ let body = env.body_excerpt.as_deref().unwrap();+ assert!(+ body.starts_with("tool_family: non-file\ntool_name: Bash\ntool_call_id: toolu_1\n"),+ "{body}"+ );+ assert!(+ !body.contains("curl") && !body.contains("sk-secret"),+ "{body}"+ );+ assert_eq!(+ tool_family_from_title(env.title_hint.as_deref().unwrap()),+ Some(ToolFamily::NonFile)+ );+ }++ /// Claude Code's `Skill` and `Agent` calls also keep the skill and the+ /// subagent type (<https://code.claude.com/docs/en/hooks>), and nothing+ /// else from their input.+ #[test]+ fn record_tool_name_keeps_the_skill_and_the_subagent_type() {+ let mut skill = claude_tool_event(+ "PreToolUse",+ serde_json::json!({+ "session_id": "s",+ "tool_name": "Skill",+ "tool_use_id": "toolu_2",+ "tool_input": {"skill": "visual-explainer:diff-review", "args": "free text the user typed"}+ }),+ );+ skill.record_tool_name();+ assert_eq!(skill.title_hint.as_deref(), Some("tool unknown: Skill"));+ let body = skill.body_excerpt.as_deref().unwrap();+ assert!(+ body.contains("\ntool_name: Skill\nskill: visual-explainer:diff-review\n"),+ "{body}"+ );+ assert!(!body.contains("free text"), "{body}");++ for name in ["Agent", "Task"] {+ let mut agent = claude_tool_event(+ "PreToolUse",+ serde_json::json!({+ "session_id": "s",+ "tool_name": name,+ "tool_input": {"subagent_type": "Explore", "prompt": "find the auth code", "description": "search"}+ }),+ );+ agent.record_tool_name();+ assert_eq!(+ agent.title_hint.as_deref(),+ Some(format!("tool unknown: {name}").as_str())+ );+ let body = agent.body_excerpt.as_deref().unwrap();+ assert!(body.contains("\nsubagent_type: Explore"), "{body}");+ assert!(!body.contains("find the auth code"), "{body}");+ }+ }++ /// Free text in a name or descriptor field is refused whole: no partial+ /// name, no truncated skill.+ #[test]+ fn record_tool_name_refuses_free_text_names_and_descriptors() {+ let mut spaced = claude_tool_event(+ "PreToolUse",+ serde_json::json!({+ "session_id": "s",+ "tool_name": "Bash; rm -rf /",+ "tool_input": {"command": "ls"}+ }),+ );+ spaced.record_tool_name();+ assert_eq!(spaced.title_hint.as_deref(), Some("tool unknown"));+ assert!(+ !spaced+ .body_excerpt+ .as_deref()+ .unwrap()+ .contains("tool_name")+ );++ let mut long = claude_tool_event(+ "PreToolUse",+ serde_json::json!({"session_id": "s", "tool_name": "x".repeat(65), "tool_input": {}}),+ );+ long.record_tool_name();+ assert_eq!(long.title_hint.as_deref(), Some("tool unknown"));++ let mut skill = claude_tool_event(+ "PreToolUse",+ serde_json::json!({+ "session_id": "s",+ "tool_name": "Skill",+ "tool_input": {"skill": "review then email [email protected]"}+ }),+ );+ skill.record_tool_name();+ assert_eq!(skill.title_hint.as_deref(), Some("tool unknown: Skill"));+ let body = skill.body_excerpt.as_deref().unwrap();+ assert!(+ !body.contains("skill:") && !body.contains("alice"),+ "{body}"+ );+ }++ /// The descriptors are Claude Code's own fields: another agent's `Skill`+ /// tool keeps its name only.+ #[test]+ fn record_tool_name_reads_descriptors_for_claude_code_only() {+ let mut env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "PreToolUse".into(),+ agent: Some("codex".into()),+ ..Default::default()+ },+ serde_json::json!({"session_id": "s", "tool_name": "Skill", "tool_input": {"skill": "x"}}),+ );+ env.record_tool_name();+ assert_eq!(env.title_hint.as_deref(), Some("tool unknown: Skill"));+ assert!(!env.body_excerpt.as_deref().unwrap().contains("skill:"));+ }++ /// Off by default: without the call, the envelope is what it always was.+ #[test]+ fn an_envelope_is_unnamed_until_record_tool_name_runs() {+ let env = claude_tool_event(+ "PostToolUse",+ serde_json::json!({+ "session_id": "s",+ "tool_name": "Edit",+ "tool_use_id": "toolu_3",+ "tool_input": {"file_path": "/repo/a.rs", "old_string": "a", "new_string": "b"},+ "tool_response": {"filePath": "/repo/a.rs"}+ }),+ );+ assert_eq!(env.title_hint.as_deref(), Some("tool file"));+ assert!(!env.body_excerpt.as_deref().unwrap().contains("tool_name"));+ }++ /// A title that is not this module's bare family label (a metadata-only+ /// rebuild's bare `non-file`, or one already named) is never renamed.+ #[test]+ fn record_tool_name_leaves_other_titles_alone() {+ let mut env = claude_tool_event(+ "PreToolUse",+ serde_json::json!({"session_id": "s", "tool_name": "Bash", "tool_input": {"command": "ls"}}),+ );+ env.title_hint = Some("non-file".into());+ env.record_tool_name();+ assert_eq!(env.title_hint.as_deref(), Some("non-file"));++ let mut twice = claude_tool_event(+ "PreToolUse",+ serde_json::json!({"session_id": "s", "tool_name": "Bash", "tool_input": {"command": "ls"}}),+ );+ twice.record_tool_name();+ twice.record_tool_name();+ assert_eq!(twice.title_hint.as_deref(), Some("tool non-file: Bash"));+ }++ #[test]+ fn named_tool_titles_keep_their_family_and_list_by_name() {+ assert!(is_safe_tool_title("tool file: Edit"));+ assert_eq!(+ tool_family_from_title("tool file: Edit"),+ Some(ToolFamily::File)+ );+ assert_eq!(listable_tool_name("tool file: Edit"), Some("Edit"));+ assert_eq!(tool_title_display("tool file: Edit"), "Edit");++ assert_eq!(listable_tool_name("tool non-file"), None);+ assert_eq!(tool_title_display("tool non-file"), "tool non-file");+ assert_eq!(listable_tool_name("edit"), Some("edit"));+ assert_eq!(listable_tool_name(""), None);++ for not_ours in ["tool file: two words", "tool nope: Bash", "Tool file: Edit"] {+ assert!(!is_safe_tool_title(not_ours), "{not_ours}");+ assert_eq!(tool_family_from_title(not_ours), None, "{not_ours}");+ }+ }}diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 6284e9f4..6c2e49f7 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -643,6 +643,11 @@ pub struct HookState {/// subagent exclusion so a marked event still seeds its tail tracking./// Empty by default.pub ingest_drop_list: crate::drop_list::IngestDropList,+ /// `[ingest] record_tool_names` (default `false`): name each closed-tool+ /// call in its observation (`tool non-file: Bash`, plus the skill or+ /// subagent it ran) instead of only its family. Never its arguments.+ /// Held here because the hooks crate makes no config reads.+ pub record_tool_names: bool,/// Benchmark escape hatch (`AI_MEMORY_EVAL_SKIP_WIKI_CHECKPOINTS=1`, set/// only by the retrieval-benchmark harness in `evals/`): skip the/// SessionEnd auto-commits of the wiki git tree. The LongMemEval replay@@ -832,10 +837,14 @@ async fn admit_hook(HookProcessingOutcome::DroppedInvalid.record(&state.ingest_metrics);return (StatusCode::ACCEPTED, "invalid marker aliases");}- let Some(env) = inspect_capture_envelope(env) else {+ let Some(mut env) = inspect_capture_envelope(env) else {HookProcessingOutcome::DroppedPolicy.record(&state.ingest_metrics);return (StatusCode::ACCEPTED, "capture policy dropped");};+ // After the capture policy: a call it reduced to metadata has no name left.+ if state.record_tool_names {+ env.record_tool_name();+ }if is_cursor_draft_placeholder(&env) {HookProcessingOutcome::DroppedInvalid.record(&state.ingest_metrics);return (StatusCode::ACCEPTED, "cursor draft placeholder dropped");@@ -1105,7 +1114,7 @@ async fn handle_hook_batch(accepted_indices.push(idx);continue;}- let Some(env) = inspect_capture_envelope(env) else {+ let Some(mut env) = inspect_capture_envelope(env) else {// A protocol-directed drop is committed from the spool's point of// view, but intentionally spends neither ingress capacity nor a// source-rate token.@@ -1117,6 +1126,9 @@ async fn handle_hook_batch(accepted_indices.push(idx);continue;};+ if state.record_tool_names {+ env.record_tool_name();+ }if is_cursor_draft_placeholder(&env) {HookProcessingOutcome::DroppedInvalid.record(&state.ingest_metrics);results.push(HookBatchResult {@@ -1377,6 +1389,9 @@ fn metadata_only_protocol_envelope(object.get("tool_call_id"),"unknown",);+ // The client already replaced the tool name with the family; nothing a+ // metadata-only event carries may be recorded as a tool name.+ env.recorded_tool = None;env.raw = serde_json::Value::Object(raw);Some(env)}@@ -1476,6 +1491,7 @@ fn metadata_envelope(raw.get("tool_call_id"),outcome.as_str(),);+ env.recorded_tool = None;env.raw = raw;env}@@ -7853,6 +7869,7 @@ pub(crate) mod tests {mid_session_routing: MidSessionRouting::default(),profile: ai_memory_core::profile::ProfileSettings::default(),ingest_drop_list: crate::drop_list::IngestDropList::default(),+ record_tool_names: false,skip_wiki_checkpoints: false,}}@@ -24237,6 +24254,124 @@ pub(crate) mod tests {);}+ /// Post one session's tool events through the batch route and return the+ /// stored tool observations as `(title, body)`.+ async fn stored_tool_events(+ state: Arc<HookState>,+ session: &str,+ events: Vec<serde_json::Value>,+ ) -> Vec<(String, String)> {+ let mut items = vec![HookBatchItem {+ url: "http://h/hook?event=session-start&agent=claude-code".into(),+ body: serde_json::json!({ "session_id": session }),+ }];+ items.extend(events.into_iter().map(|body| HookBatchItem {+ url: "http://h/hook?event=post-tool-use&agent=claude-code".into(),+ body,+ }));+ let response = handle_hook_batch(+ State(state.clone()),+ None,+ None,+ None,+ HeaderMap::new(),+ Json(items),+ )+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::OK);+ let sid = resolve_session_id(&HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-start".into(),+ ..Default::default()+ },+ serde_json::json!({ "session_id": session }),+ ))+ .unwrap();+ state+ .reader+ .observations_for_session(sid)+ .await+ .unwrap()+ .into_iter()+ .filter(|o| o.kind == ObservationKind::PostToolUse)+ .map(|o| (o.title, o.body))+ .collect()+ }++ /// `[ingest] record_tool_names` names a kept call, and never a call a+ /// capture policy reduced to metadata: not one the client stripped, and+ /// not a shell call the server strips itself because its marker is+ /// invalid, although that payload still carries the real `Bash` name.+ /// No call keeps its arguments.+ #[tokio::test]+ async fn record_tool_names_names_kept_calls_and_never_metadata_only_ones() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.record_tool_names = true;+ let stored = stored_tool_events(+ Arc::new(state),+ "named-tools",+ vec![+ serde_json::json!({+ "session_id": "named-tools", "tool_name": "Bash", "tool_use_id": "toolu_k",+ "tool_input": { "command": "echo SENTINEL_SECRET" },+ "tool_response": { "stdout": "done" },+ }),+ serde_json::json!({+ "session_id": "named-tools", "tool_family": "file", "tool_name": "file",+ "_ai_memory_capture": capture_protocol("metadata-only", "active", "file", 1, "extracted"),+ }),+ serde_json::json!({+ "session_id": "named-tools", "tool_name": "Bash", "tool_use_id": "toolu_m",+ "tool_input": { "command": "cat .env # SENTINEL_SECRET" },+ "tool_response": { "stdout": "SENTINEL_SECRET" },+ "_ai_memory_capture": "not a protocol",+ }),+ ],+ )+ .await;+ let titles: Vec<&str> = stored.iter().map(|(title, _)| title.as_str()).collect();+ assert_eq!(titles, ["tool non-file: Bash", "file", "non-file"]);+ assert!(+ stored[0].1.contains("\ntool_name: Bash\n"),+ "{}",+ stored[0].1+ );+ for (title, body) in &stored[1..] {+ assert!(+ !body.contains("tool_name") && !body.contains("Bash"),+ "{title}: {body}"+ );+ }+ assert!(+ stored+ .iter()+ .all(|(_, body)| !body.contains("SENTINEL_SECRET"))+ );+ }++ /// Control: with `[ingest] record_tool_names` off (the default), the same+ /// call keeps today's family-only title and body.+ #[tokio::test]+ async fn tool_calls_stay_unnamed_when_record_tool_names_is_off() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ assert!(!state.record_tool_names);+ let stored = stored_tool_events(+ Arc::new(state),+ "unnamed-tools",+ vec![serde_json::json!({+ "session_id": "unnamed-tools", "tool_name": "Bash", "tool_use_id": "toolu_k",+ "tool_input": { "command": "ls" }, "tool_response": { "stdout": "done" },+ })],+ )+ .await;+ assert_eq!(stored.len(), 1);+ assert_eq!(stored[0].0, "tool non-file");+ assert!(!stored[0].1.contains("tool_name"), "{}", stored[0].1);+ }+#[tokio::test]async fn parsed_impossible_drop_is_acked_without_ingest_capacity() {let tmp = TempDir::new().unwrap();@@ -24555,6 +24690,53 @@ pub(crate) mod tests {);}+ /// `[ingest] record_tool_names` titles (`tool <family>: <name>`) list by+ /// their name in `Tools used:`, while the family they still carry keeps+ /// the file-activity heuristic firing.+ #[test]+ fn auto_handoff_lists_recorded_tool_names_and_keeps_the_file_heuristic() {+ use ai_memory_core::{ProjectId, WorkspaceId};+ let observations = vec![+ mk_obs(ObservationKind::UserPrompt, "fix bug", "fix the bug"),+ mk_obs(+ ObservationKind::PostToolUse,+ "tool non-file: Bash",+ "tool_family: non-file\ntool_name: Bash\noutcome: unknown",+ ),+ mk_obs(+ ObservationKind::PostToolUse,+ "tool file: Edit",+ "tool_family: file\ntool_name: Edit\noutcome: unknown",+ ),+ ];+ let handoff = build_auto_handoff(+ WorkspaceId::new(),+ ProjectId::new(),+ AgentKind::ClaudeCode,+ SessionId::new(),+ None,+ &observations,+ None,+ false,+ );+ assert!(+ handoff+ .next_steps+ .iter()+ .any(|s| s == "Tools used: Bash, Edit"),+ "recorded names must be listed by name; got: {:?}",+ handoff.next_steps+ );+ assert!(+ handoff+ .open_questions+ .iter()+ .any(|q| q.contains("while working with files")),+ "a named file tool must still drive the file heuristic; got: {:?}",+ handoff.open_questions+ );+ }+const TASK_NOTIFICATION: &str = "<task-notification>\n<task-id>abc</task-id>\n\<status>completed</status>\n<summary>Agent \"review\" completed</summary>\n\</task-notification>";diff --git a/crates/ai-memory-hooks/src/synth.rs b/crates/ai-memory-hooks/src/synth.rsindex 4b37efbd..d35a11c8 100644--- a/crates/ai-memory-hooks/src/synth.rs+++ b/crates/ai-memory-hooks/src/synth.rs@@ -29,7 +29,9 @@ use jiff::Timestamp;use jiff::tz::TimeZone;use crate::capture_policy::ToolFamily;-use crate::payload::{is_safe_tool_title, tool_family_from_title};+use crate::payload::{+ is_safe_tool_title, listable_tool_name, tool_family_from_title, tool_title_display,+};const RAW_OBSERVATION_MAX_LINES: usize = 500;const RAW_OBSERVATION_HEAD_LINES: usize = 250;@@ -325,14 +327,6 @@ fn session_line(obs: &Observation) -> SessionLine {}}-/// Tool names worth listing: a harness's own tool name. Skip `tool <family>` /-/// bare-`<family>` labels: a family is a partition of the calls, not a name-/// for a tool, so "Tools used: tool file, tool non-file" tells the receiver-/// nothing.-fn is_listable_tool_title(title: &str) -> bool {- !title.is_empty() && tool_family_from_title(title).is_none()-}-fn build_digest(snapshot: &SessionObservationSnapshot<'_>,session_id: SessionId,@@ -394,7 +388,12 @@ fn build_digest(};let tools = snapshot.tool_titles()?;- let tool_counts: BTreeMap<String, usize> = tools.completed.into_iter().collect();+ let mut tool_counts: BTreeMap<String, usize> = BTreeMap::new();+ for (title, count) in tools.completed {+ *tool_counts+ .entry(tool_title_display(&title).to_owned())+ .or_insert(0) += count;+ }let handoff = HandoffFacts {first_prompt: if summary.prompts > 0 {@@ -438,8 +437,9 @@ fn build_digest(has_session_end: summary.last_session_end_at.is_some(),tools: tools.titles- .into_iter()- .filter(|title| is_listable_tool_title(title))+ .iter()+ .filter_map(|title| listable_tool_name(title))+ .map(str::to_owned).collect(),};@@ -913,7 +913,9 @@ impl SessionDigest {let mut tool_counts = BTreeMap::new();for obs in observations {if obs.kind == ObservationKind::PostToolUse && !obs.title.is_empty() {- *tool_counts.entry(obs.title.clone()).or_insert(0) += 1;+ *tool_counts+ .entry(tool_title_display(&obs.title).to_owned())+ .or_insert(0) += 1;}}let prompt_titles_all: Vec<String> = observations@@ -985,9 +987,10 @@ impl HandoffFacts {matches!(o.kind,ObservationKind::PostToolUse | ObservationKind::PreToolUse- ) && is_listable_tool_title(&o.title)+ )})- .map(|o| o.title.clone())+ .filter_map(|o| listable_tool_name(&o.title))+ .map(str::to_owned).collect(),}}@@ -1563,6 +1566,48 @@ mod tests {assert!(page.body.contains("build the thing"));}+ /// `[ingest] record_tool_names` titles count under their tool name, a bare+ /// family label still counts under the label, and the file family they+ /// carry still marks an abrupt ending.+ #[test]+ fn recorded_tool_names_count_by_name_and_keep_the_file_signal() {+ let observations = vec![+ obs(ObservationKind::SessionStart, "session"),+ obs(ObservationKind::UserPrompt, "rework the retry loop"),+ obs(ObservationKind::PostToolUse, "tool non-file: Bash"),+ obs(ObservationKind::PostToolUse, "tool non-file: Bash"),+ obs(ObservationKind::PostToolUse, "tool unknown: Skill"),+ obs(ObservationKind::PostToolUse, "tool non-file"),+ obs(ObservationKind::PostToolUse, "tool file: Edit"),+ ];+ let page = synthesize_session_page(+ WorkspaceId::new(),+ ProjectId::new(),+ SessionId::new(),+ AgentKind::ClaudeCode,+ &observations,+ );+ assert!(page.body.contains("- `Bash`: 2\n"), "{}", page.body);+ assert!(page.body.contains("- `Skill`: 1\n"), "{}", page.body);+ assert!(page.body.contains("- `Edit`: 1\n"), "{}", page.body);+ assert!(+ page.body.contains("- `tool non-file`: 1\n"),+ "{}",+ page.body+ );+ assert!(+ !page.body.contains("`tool non-file: Bash`"),+ "{}",+ page.body+ );+ assert!(+ page.body+ .contains("Session ended without a normal stop while working with files"),+ "{}",+ page.body+ );+ }+#[test]fn pre_only_tool_calls_are_not_counted() {// A PreToolUse without a matching PostToolUse (cancelled / crasheddiff --git a/crates/ai-memory-hooks/tests/suite/idle_end.rs b/crates/ai-memory-hooks/tests/suite/idle_end.rsindex cf0281ef..1ccf5c8d 100644--- a/crates/ai-memory-hooks/tests/suite/idle_end.rs+++ b/crates/ai-memory-hooks/tests/suite/idle_end.rs@@ -85,6 +85,7 @@ async fn harness() -> (TempDir, Store, Wiki, HookState) {mid_session_routing: ai_memory_core::MidSessionRouting::default(),profile: ai_memory_core::profile::ProfileSettings::default(),ingest_drop_list: crate::drop_list::IngestDropList::default(),+ record_tool_names: false,skip_wiki_checkpoints: false,};(tmp, store, wiki, state)diff --git a/crates/ai-memory-mcp/tests/suite/admin_metrics.rs b/crates/ai-memory-mcp/tests/suite/admin_metrics.rsindex 3de346d0..a58c2b12 100644--- a/crates/ai-memory-mcp/tests/suite/admin_metrics.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_metrics.rs@@ -92,6 +92,7 @@ async fn harness() -> Harness {mid_session_routing: ai_memory_core::MidSessionRouting::default(),profile: ai_memory_core::profile::ProfileSettings::default(),ingest_drop_list: ai_memory_hooks::IngestDropList::default(),+ record_tool_names: false,skip_wiki_checkpoints: false,subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),ingest_rate: Arc::new(tokio::sync::Mutex::new(diff --git a/crates/ai-memory-mcp/tests/suite/autoscope_multiuser.rs b/crates/ai-memory-mcp/tests/suite/autoscope_multiuser.rsindex b93854c3..8daaf546 100644--- a/crates/ai-memory-mcp/tests/suite/autoscope_multiuser.rs+++ b/crates/ai-memory-mcp/tests/suite/autoscope_multiuser.rs@@ -184,6 +184,7 @@ impl MultiUserHarness {mid_session_routing: ai_memory_core::MidSessionRouting::default(),profile: ai_memory_core::profile::ProfileSettings::default(),ingest_drop_list: ai_memory_hooks::IngestDropList::default(),+ record_tool_names: false,skip_wiki_checkpoints: false,subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),ingest_rate: Arc::new(tokio::sync::Mutex::new(diff --git a/crates/ai-memory-mcp/tests/suite/recap_identity.rs b/crates/ai-memory-mcp/tests/suite/recap_identity.rsindex f5be1009..5c1c27bd 100644--- a/crates/ai-memory-mcp/tests/suite/recap_identity.rs+++ b/crates/ai-memory-mcp/tests/suite/recap_identity.rs@@ -69,6 +69,7 @@ async fn harness() -> Harness {ingest_gates: ai_memory_hooks::IngestGates::default(),cwd_probes: ai_memory_hooks::CwdProbes::default(),ingest_drop_list: ai_memory_hooks::IngestDropList::default(),+ record_tool_names: false,skip_wiki_checkpoints: false,consolidate_on_session_end: false,session_consolidation_notify: None,diff --git a/crates/ai-memory-mcp/tests/suite/stress_autoscope.rs b/crates/ai-memory-mcp/tests/suite/stress_autoscope.rsindex ef039446..d49a51e1 100644--- a/crates/ai-memory-mcp/tests/suite/stress_autoscope.rs+++ b/crates/ai-memory-mcp/tests/suite/stress_autoscope.rs@@ -172,6 +172,7 @@ impl Harness {mid_session_routing: ai_memory_core::MidSessionRouting::default(),profile: ai_memory_core::profile::ProfileSettings::default(),ingest_drop_list: ai_memory_hooks::IngestDropList::default(),+ record_tool_names: false,skip_wiki_checkpoints: false,subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),ingest_rate: Arc::new(tokio::sync::Mutex::new(diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 3d37653b..0539eb34 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -1520,6 +1520,14 @@ drop_events = [] # whole hook event kinds to drop (e.g. ["pre-t# 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+record_tool_names = false # name each closed-tool call: title `tool non-file: Bash`,+ # body `tool_name:` plus `skill:` / `subagent_type:` for a+ # Claude Code Skill / Agent call. Identifiers only (a name of+ # at most 64 [A-Za-z0-9_-], a descriptor of at most 128+ # [A-Za-z0-9_.:-]); never arguments. Applied after the capture+ # policy, so a metadata-only call stays unnamed. Session pages+ # and handoffs then count and list calls by name. Env:+ # AI_MEMORY_INGEST__RECORD_TOOL_NAMES=true```The privacy and fidelity tradeoff behind `[consolidation].verbatim_residue`,diff --git a/docs/config-properties.md b/docs/config-properties.mdindex 4a4abff0..00d70776 100644--- a/docs/config-properties.md+++ b/docs/config-properties.md@@ -275,6 +275,7 @@ Defined by `SanitizeConfig` in `ai-memory-core`. Built-in redaction patterns alw| `drop_tool_use_id_prefixes` | `[]` | `AI_MEMORY_INGEST__DROP_TOOL_USE_ID_PREFIXES` | Drop a tool event whose `tool_use_id` starts with one of these. || `drop_tool_names` | `[]` | `AI_MEMORY_INGEST__DROP_TOOL_NAMES` | Drop a tool event whose tool name equals one of these exactly. || `drop_events` | `[]` | `AI_MEMORY_INGEST__DROP_EVENTS` | Drop whole hook event kinds. `session-start` and `session-end` are rejected at load. |+| `record_tool_names` | `false` | `AI_MEMORY_INGEST__RECORD_TOOL_NAMES` | Name each tool call in its observation (`tool non-file: Bash`, plus a Claude Code skill or subagent type) instead of only its family. Never a tool's arguments. |## `[hook_spool]`diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex f034f456..307851f7 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -119,6 +119,7 @@ the legitimate restricted-project control and the failed-query cases.| 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 after the subagent exclusion (`should_drop_subagent`) and before the rate limiter, ingest semaphore, sanitizer, and storage, so a marked subagent event seeds the tracking set its unmarked tail is dropped against even when its tool id, tool name, or event 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. 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`, `the_ingest_drop_list_applies_to_hook_batches`, `marked_tool_policy_drops_seed_subagent_tracking_before_single_ingress_matching`, and `marked_tool_policy_drops_seed_subagent_tracking_before_batch_matching` cover capacity, batch acknowledgements, id-prefix and exact-name seeding order, unmarked tails, and stored controls; `drop_list.rs` unit tests cover bounds, exact matching, and each agent's native fields. Whole kinds: `router.rs` `the_ingest_drop_events_drops_the_named_kind_and_keeps_the_rest`, `the_ingest_drop_events_drops_before_any_capacity_is_spent`, `the_ingest_drop_events_consumes_no_rate_budget`, `the_ingest_drop_events_batch_reports_per_index_outcomes_and_only_stores_the_kept`, `the_ingest_drop_events_keeps_dropping_the_unmarked_subagent_tail`, `the_ingest_drop_events_keeps_dropping_the_unmarked_subagent_tail_in_batches`, and `a_marked_event_of_a_dropped_kind_still_seeds_subagent_tracking`; `drop_list.rs` `drop_events_*` tests cover typed matching and rejected state/unknown kinds. Moving any matcher before subagent exclusion fails its single/batch tail tests; removing either batch matcher fails its batch contract | 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`) || 11m | The server never opens a filesystem path named in a hook payload | `ai-memory-hooks/src/payload.rs` `HookEnvelope::from_query_and_body` (run by `/hook` and every `/hook/batch` item) only reads the posted JSON; Antigravity step-log enrichment (`antigravity.rs` `enrich_antigravity_step_output`, which opens `<artifactDirectoryPath or transcriptPath dir>/.system_generated/steps/<stepIdx>/output.txt`) runs only client-side in `ai-memory-cli/src/commands/hook.rs` against the client's own home, and the server stores whatever `tool_response` the client sent | `router.rs` `a_hook_payload_cannot_make_the_server_read_its_own_disk` (an Antigravity `PostToolUse` batch naming a server-only directory through `artifactDirectoryPath` and through `transcriptPath`; no stored observation or file contains the server-side sentinel); `payload.rs` `envelope_parsing_never_reads_a_payload_named_antigravity_artifact` and `antigravity_post_tool_use_renders_client_enriched_output` (control: client-supplied output still rendered) | STRONG. Both adversarial tests fail with the server-side enrichment call reinstated (the sentinel file content is stored and readable through search) |+| 11n | Opt-in tool names (`[ingest] record_tool_names`) name only a kept call and never carry its arguments | `ai-memory-hooks/src/capture_policy.rs` `recorded_tool_name` keeps the adapter tool name only when it is at most 64 `[A-Za-z0-9_-]`, and Claude Code's `skill` / `subagent_type` only when at most 128 `[A-Za-z0-9_.:-]`, refusing free text whole; `payload.rs` `HookEnvelope::record_tool_name` renames only a title that is still the bare `tool <family>` label; `router.rs` calls it after `inspect_capture_envelope`, and `metadata_envelope` / `metadata_only_protocol_envelope` clear the recorded name, so a call the client stripped, or a shell call the server strips under an invalid marker, stays unnamed | `router.rs` `record_tool_names_names_kept_calls_and_never_metadata_only_ones` (a kept Bash call is named; a client-stripped file call and a server-stripped invalid-marker shell call whose payload still says `Bash` are not; no argument text is stored) fails with both the title guard and the two clears removed, with the control `tool_calls_stay_unnamed_when_record_tool_names_is_off`; `payload.rs` `record_tool_name_refuses_free_text_names_and_descriptors` | STRONG || 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 (`http_client.rs` `is_loopback_url`, shared by every caller, decides loopback from the host `reqwest` parses and refuses any URL carrying user information); `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; `mcp_bridge.rs` `bridge_bearer` sends a configured bearer, else the hook key stored in `<data_dir>/auth-token`, else the discovered loopback root token (`AuthSettings::configured_bearer_token` leaves discovery out, so a server+client host never sends root over a stored user key), and the fallback is in the bridge only (`Config::load` never reads that file, so `serve` neither requires nor accepts it); `install_mcp.rs` `store_bridge_key` stores an explicit `--auth-token` there for the Claude Code and Muse bridge entries on `--apply` and writes the entry with `--data-dir` and no key, keeping the key inline when a configured bearer would win, a different key is stored, the hooks use OIDC, the store fails or the Docker helper runs; `uninstall.rs` keeps the stored key on `--only hooks` while `install_mcp::bridge_entry_remains`; `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, a remote host behind loopback-looking user information, `default` profile, env token); `http_client.rs` `loopback_url_is_decided_by_the_parsed_host` (user-information, fragment and query forms, look-alike domains, `localhost.`, `0.0.0.0` and IPv4-mapped IPv6 refused; `127.0.0.0/8`, `[::1]` and `localhost` in any case accepted); `mcp_bridge.rs` `discovered_root_never_leaves_loopback_but_the_stored_user_key_follows_the_entry` (adversarial: remote and user-information `--server-url` forms get no root key; control: an unnamed loopback server does); `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); `config.rs` `config_load_never_adopts_the_stored_hook_key` (adversarial: a stored hook key leaves the loaded bearer empty, so `serve` on that data dir neither requires nor accepts it; control: a `bearer_token_file` naming the same file is adopted); `mcp_bridge.rs` `bridge_bearer_puts_the_stored_hook_key_below_a_configured_bearer` (a configured bearer wins, a blank one does not), `a_stored_user_key_outranks_the_discovered_root_token` (adversarial: discoverable loopback root plus a stored key sends the stored key; control: discovery alone still sends root); `install_mcp.rs` `an_explicit_key_for_a_bridge_is_stored_instead_of_written_inline` (Claude Code and Muse entries carry no key and name the data dir, the stored pair is the hooks' format; controls keeping the key inline and storing nothing: print path, configured bearer, a different stored key, OIDC hooks, Docker helper, HTTP entry); `removal.rs` `an_explicit_bridge_key_is_stored_and_outlives_only_hooks_removal`; `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 `Config::load` adopting the stored hook key, without the bridge fallback, with discovery counted as a configured bearer, or with `install-mcp` never storing the key, the matching new 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 || 12c | Browser cross-origin writes refused on an unauthenticated server (a foreign page in the operator's browser, DNS rebinding, and a LAN host where browsers send no fetch metadata) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403; and `is_non_script_browser_request`: any `Sec-Fetch-Dest` other than `empty` (case-insensitive; non-UTF-8 refused) → 403 whatever `Sec-Fetch-Site` says, so links, images, navigations, iframes and form posts are refused even as `same-origin` or `none`. Browsers send fetch metadata over plain HTTP only to a potentially trustworthy host, so on any other `Host` (a LAN address or name in the allowlist, `0.0.0.0`, `host.docker.internal`; `is_loopback_host` admits only `localhost`, `*.localhost`, `127.0.0.0/8` and `[::1]`) `handoff_fetch_lacks_client_marker` also refuses `GET`/`HEAD /handoff` without a non-empty `X-AI-Memory-Client` header (`ai_memory_hooks::CLIENT_MARKER_HEADER`) → 403 whose body names both remedies (re-stage hooks, or set a bearer token). A page cannot add that header without a preflight these routes never answer. `/handoff` is the one state-changing `GET` on these routes; the other `GET`s are reads a foreign page cannot see the answer to, and every cross-origin `POST` carries `Origin`. Every first-party client sends the marker: the native hook (`hook_capture.rs` `post_hook`/`post_batch`/`get_handoff`), CLI subcommands (`http_client.rs` `ServerEndpoint::authenticate`), every curl in `hooks/_lib.sh`, both header tables in `hooks/lib/ai-memory-hook.ps1`, and the generated TypeScript integrations (`render_shared.rs` `ts_auth_headers_fn` plus the spool drain). Loopback hosts keep accepting a fetch without it, so hooks staged before the header existed still work on a default install, except that a request carrying any proxy forwarding header (`Forwarded`, `X-Forwarded-For`/`-Host`/`-Proto`/`-Server`/`-Port`, `X-Original-Forwarded-For`, `X-Real-IP`, `X-Client-IP`, `CF-Connecting-IP`, `True-Client-IP`, `Via`; `PROXY_HEADERS`) counts as non-loopback, since a plain-HTTP proxy can rewrite `Host` to loopback while the browser behind it sent no fetch metadata. No first-party client sends those headers. Hooks, the CLI and MCP clients send none of these headers; the web UI's same-origin `/admin/pending-writes` calls are `fetch()` (`Sec-Fetch-Dest: empty`) and pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment Every `/web` surface (built-in pages including `/web/pending`, the login page, a custom SPA and `/api/v1`) answers `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'` (`ai-memory-web/src/mount.rs` `deny_framing`), because a framed page's own Approve/Reject `fetch()` is same-origin and the guard rightly lets it through | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`; `GET /handoff` as a same-origin `document` or `image` and as a `Sec-Fetch-Site: none` `document` → 403 with the baton still open. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` and `non_script_browser_request_detection` (header tables) and `cross_origin_browser_guard_applies_only_without_auth` (same-origin `image` and `none` `document` refused, same-origin `empty` passes, both pass with auth on); `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control. `cross_origin_e2e.rs` `handoff_fetch_on_a_lan_host_requires_the_client_marker`, against a `serve` that allowlists a LAN name and address: `GET` and `HEAD /handoff` through either without the marker, and with an empty one → 403 carrying the remedy text, with the baton still open and the active-project pointer unmoved; controls: a marked fetch through the LAN name claims the baton, and a marker-less fetch through `127.0.0.1` (a hook staged before the marker) claims the next one; then a `127.0.0.1` fetch carrying each proxy forwarding header and no marker → 403 with the baton still open, and the same fetch with the marker claims it. `serve.rs` `loopback_host_detection`, `handoff_fetch_client_marker_decision` (incl. a loopback `Host` with each proxy header, refused without the marker and admitted with it, and a named row per header so none can drop out of the list) and `handoff_client_marker_guard_on_lan_hosts_and_under_a_base_path` (also under a `--base-path` nest; inactive with auth on). Front-door parity: `hook_capture.rs` `every_native_hook_request_carries_the_client_marker` (handoff GET, hook POST, batch POST), `http_client.rs` `authenticate_no_token_sets_only_the_client_marker`, the client-marker block of `tests/hooks/test_lib.sh` (every curl branch of the GET, the POST and the drain, plus a static check that every PowerShell header table carries it and every `Invoke-WebRequest` passes one), `render_shared.rs` `assert_every_ts_request_carries_client_marker` run for OpenCode, OpenCode 2, OMP, Pi and OpenClaw, `external_capture_ts.rs` (the rendered OpenCode plugin under Node sends no unmarked request) and `external_capture_powershell.rs` `every_request_carries_the_client_marker` (Windows leg); `ai-memory-web/src/mount.rs` `web_surfaces_refuse_to_be_framed` (`/web`, `/web/pending`, `/web/login`, `/api/v1/projects` all carry both headers; bites with `deny_framing` neutralized) | STRONG with listed residuals. Bite checks: with the marker check disabled, the LAN e2e marker-less `GET /handoff` returns 200 and the unit layer test fails; with the proxy-header rule disabled, the proxied loopback e2e fetch claims the baton and the unit decision test fails; dropping the marker from the native handoff GET, the shell token-drain curl, a PowerShell header table or the TypeScript spool drain fails the matching front-door test. With the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the `Sec-Fetch-Dest` check removed, the same-origin `document` `GET /handoff` returns 200 and the unit guard test lets a same-origin image through; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residual, closed by setting a bearer token: a browser that sends no fetch metadata even to a loopback host (Safari before 16.4) sends no `Sec-Fetch-*` header and no `Origin` on an image `GET` or a link click, so such a request to a loopback host still reaches `/handoff` (loopback keeps accepting marker-less legacy hooks) and the other, read-only `GET` routes. On a non-loopback host the marker requirement closes `/handoff` for every browser. A plain-HTTP proxy that rewrites `Host` to its loopback upstream and adds no forwarding header (nginx's default `proxy_pass`) looks exactly like a local client, so in front of an unauthenticated server it must add `X-Forwarded-For` or keep `proxy_set_header Host $host`, or the server must sit behind TLS or use a bearer token (`security.md`, `https-via-proxy.md`). Browsers that send fetch metadata no longer have the earlier link residuals: a link opened from another app (`Sec-Fetch-Site: none`) and a link clicked in a stored page (`same-origin` navigation) both carry a non-`empty` destination and are refused. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op |