Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(capture): exclude private file-tool paths
AkitaOnRailsc4ff39d60272
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 17d9f1f1..a9f5ce68 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Per-repository capture exclusions via `[capture] ignore_paths` in the nearest+ `.ai-memory.toml` ([#194]). Supported native hooks and generated+ OpenCode/OMP/Pi/OpenClaw integrations apply the policy before local spool or+ network delivery; `ai-memory hook --check-capture` safely reports a bounded+ local decision. This changes no MCP tools and needs no database migration.- Grok Build CLI is now a first-class MCP client as well as a hook agent:`install-mcp --client grok` renders and `--apply` merges a native HTTPentry into `$GROK_HOME/config.toml` (default `~/.grok/config.toml`)diff --git a/Cargo.lock b/Cargo.lockindex f3e41cd2..04add83c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -133,9 +133,11 @@ version = "1.14.0"dependencies = ["ai-memory-consolidate","ai-memory-core",+ "ai-memory-llm","ai-memory-store","ai-memory-wiki","anyhow",+ "async-trait","axum","git2","jiff",diff --git a/README.md b/README.mdindex 18f1b218..f1845a0a 100644--- a/README.md+++ b/README.md@@ -21,17 +21,17 @@| Linux | Supported | Primary Docker/server target and CI platform. Published Docker images support `linux/amd64` and `linux/arm64`. Native Arch/AUR packages include system and user systemd units. || macOS | Supported | Workspace tests run in CI; tagged releases publish native `ai-memory-macos-aarch64.tar.gz` and `ai-memory-macos-x86_64.tar.gz` binaries. The native binary is the recommended path on Apple Silicon. See [`docs/macos.md`](docs/macos.md). || Windows via WSL2 | Supported | Use the Linux install path inside WSL2 when the agent runs there. |-| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Claude Code uses Claude exec form with a real native `ai-memory.exe` by default; other script-hook agents use the current PowerShell defaults pending harness feedback. See [`docs/windows.md`](docs/windows.md). |-| Claude Code | Supported | MCP config + lifecycle hooks. |-| Codex | Supported | MCP config + lifecycle hooks; no automatic true session-end hook, so run `ai-memory finalize-session` when you need a final summary/handoff. |+| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Local supported profiles default to host-native hook commands; Claude Code may use its Windows exec form, while other agents use native single command strings matching their hook schema. PowerShell/Git Bash scripts are compatibility fallbacks. See [`docs/windows.md`](docs/windows.md). |+| Claude Code | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. |+| Codex | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. No automatic true session-end hook, so run `ai-memory finalize-session` when you need a final summary/handoff. || Devin CLI | Supported | MCP config + lifecycle hooks. Hooks use Devin's `PostCompaction` event, inject handoffs via `hookSpecificOutput.additionalContext`, and omit subagent events because Devin does not expose them. |-| OpenCode | Supported | Remote MCP config + generated TypeScript plugin. |+| OpenCode | Supported | Remote MCP config + generated TypeScript plugin; generated plugin enforces capture exclusions. || Cursor | Supported | MCP config + lifecycle hooks. || Gemini CLI | Supported | MCP config + lifecycle hooks. |-| Oh My Pi / OMP | Supported | Use `--client omp` / `--agent omp` (or `oh-my-pi`) for native `.omp` MCP config + TypeScript extension. |-| Pi | Supported | Generated `~/.pi/agent/extensions/ai-memory.ts` extension provides lifecycle capture and an HTTP MCP bridge; use `install-hooks --agent pi --apply`. |+| Oh My Pi / OMP | Supported | Use `--client omp` / `--agent omp` (or `oh-my-pi`) for native `.omp` MCP config + TypeScript extension; generated extension enforces capture exclusions. |+| Pi | Supported | Generated `~/.pi/agent/extensions/ai-memory.ts` extension provides lifecycle capture and an HTTP MCP bridge; generated extension enforces capture exclusions. || Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. |-| OpenClaw | Supported | MCP config + native plugin lifecycle hooks. |+| OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. || Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). || Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). || Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. |@@ -59,6 +59,9 @@ priors are at the [bottom](#influences-and-prior-art).- **Zero-friction capture.** Lifecycle hooks fire-and-forget everyprompt + tool call + session boundary. You never type `write_note`.+- **Per-repository capture exclusions.** A nearest-marker `[capture]`+ `ignore_paths` policy drops matching recognized file-tool events before they+ reach the local spool or server. See [the capture policy reference](docs/marker-file.md#capture-exclusions).- **Cross-agent handoffs.** Quit Claude Code mid-task, start Codexin the same directory hours later - the next agent sees a"where you left off" block before its first prompt.@@ -320,11 +323,11 @@ one matching entry.### Install Notes- **Windows:** use the Linux path inside WSL2, or the native Windows wrapper- from PowerShell/cmd. Native Claude Code uses Claude exec form with a real- `ai-memory.exe` by default, with `AI_MEMORY_HOOK_PLATFORM=windows-bash`- available for Git Bash `.sh` hooks and older Claude Code builds; other- script-hook agents use PowerShell defaults. Do not- mix path worlds. See+ from PowerShell/cmd. Local supported profiles default to host-native commands:+ Claude Code may use its supported `ai-memory.exe` exec form, while other+ agents use native single command strings matching their hook schema.+ PowerShell/Git Bash script bundles are compatibility fallbacks and do not+ enforce capture-policy v1. Do not mix path worlds. See[`docs/windows.md`](docs/windows.md).- **Docker compose:** `docker compose -f docker/docker-compose.yml up -d`is supported; agent setup is the same as step 3 above.diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 4a60faa8..fc0dd425 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1245,6 +1245,9 @@ pub struct HookArgs {/// marker does not pin its own `project_strategy`.#[arg(long, value_enum)]pub project_strategy: Option<ProjectStrategyArg>,+ /// Inspect capture policy without spooling, draining, or contacting the server.+ #[arg(long)]+ pub check_capture: bool,}/// Arguments for hidden `hook-drain`.diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex a967fbb9..f01d5d8d 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -17,13 +17,15 @@ use std::path::{Path, PathBuf};use std::time::Duration;use ai_memory_core::{AgentKind, SessionId};+use ai_memory_hooks::capture_policy::metadata_only_body;+use ai_memory_hooks::{CaptureDisposition, PolicyState};use ai_memory_llm::OidcToken;use crate::cli::HookArgs;use super::hook_capture::{- build_client, extract_cwd, get_handoff, marker_query_suffix, resolve_cwd_with_fallbacks,- url_encode,+ build_client, canonical_context, capture_policy, extract_cwd, get_handoff, marker_query_suffix,+ resolve_cwd_with_fallbacks, url_encode,};use super::hook_drain_process;use super::hook_spool;@@ -198,7 +200,10 @@ fn cwd_query_suffix_with(current_dir: impl FnOnce() -> Option<PathBuf>,) -> String {let agent_kind = AgentKind::from_wire(agent);- let cwd = if agent_kind == AgentKind::Devin {+ let (canonical_cwd, _) = canonical_context(raw);+ let cwd = if canonical_cwd.is_some() {+ canonical_cwd+ } else if agent_kind == AgentKind::Devin {resolve_cwd_with_fallbacks(raw, env_lookup, current_dir)} else {extract_cwd(raw).filter(|s| !s.trim().is_empty())@@ -292,7 +297,7 @@ pub async fn run(data_dir: Option<PathBuf>, args: HookArgs) -> anyhow::Result<()async fn run_with_payload<W, S>(data_dir: Option<PathBuf>,args: HookArgs,- payload: String,+ mut payload: String,stdout: &mut W,spawn_background_drainer: S,) -> anyhow::Result<()>@@ -300,7 +305,59 @@ whereW: std::io::Write,S: FnOnce(&Path) -> std::io::Result<()>,{- let json: serde_json::Value = serde_json::from_str(&payload).unwrap_or(serde_json::Value::Null);+ let mut json: serde_json::Value =+ serde_json::from_str(&payload).unwrap_or(serde_json::Value::Null);+ let (policy_cwd, canonical_session_id) = hook_context(&args.agent, &json);+ let policy = policy_cwd.as_deref().map(capture_policy);+ let tool_event = is_tool_event(&args.event);+ let decision = policy.as_ref().filter(|_| tool_event).map(|policy| {+ policy.inspect(+ AgentKind::from_wire(&args.agent),+ &json,+ policy_cwd.as_deref().unwrap_or(""),+ )+ });+ if args.check_capture {+ let protocol = decision.as_ref().map(|decision| decision.protocol());+ let output = serde_json::json!({+ "version": protocol.map_or(1, |protocol| protocol.version()),+ "policy_state": protocol.map_or(PolicyState::Inactive, |protocol| protocol.policy_state()),+ "tool_family": protocol.map_or(ai_memory_hooks::ToolFamily::Unknown, |protocol| protocol.tool_family()),+ "path_count": protocol.map_or(0, |protocol| protocol.path_count()),+ "disposition": protocol.map_or(CaptureDisposition::Keep, |protocol| protocol.disposition()),+ "extraction_state": protocol.map_or(ai_memory_hooks::ExtractionState::NotApplicable, |protocol| protocol.extraction_state()),+ });+ writeln!(stdout, "{output}")?;+ return Ok(());+ }+ if let Some(decision) = decision {+ match decision.protocol().disposition() {+ CaptureDisposition::Drop => {+ writeln!(stdout, "{{}}")?;+ return Ok(());+ }+ CaptureDisposition::MetadataOnly => {+ json = metadata_only_body(+ canonical_session_id.as_deref(),+ policy_cwd.as_deref(),+ &decision,+ );+ payload = serde_json::to_string(&json)?;+ }+ CaptureDisposition::Keep+ if decision.protocol().policy_state() != PolicyState::Inactive =>+ {+ if let Some(object) = json.as_object_mut() {+ object.insert(+ "_ai_memory_capture".into(),+ serde_json::to_value(decision.protocol())?,+ );+ payload = serde_json::to_string(&json)?;+ }+ }+ CaptureDisposition::Keep => {}+ }+ }let qs = cwd_query_suffix(&args.agent,@@ -411,6 +468,31 @@ whereOk(())}+fn hook_context(agent: &str, raw: &serde_json::Value) -> (Option<String>, Option<String>) {+ let (cwd, session_id) = canonical_context(raw);+ if cwd.is_some() {+ return (cwd, session_id);+ }+ if AgentKind::from_wire(agent) == AgentKind::Devin {+ (+ resolve_cwd_with_fallbacks(raw, env_lookup, || std::env::current_dir().ok()),+ session_id,+ )+ } else {+ (+ extract_cwd(raw).filter(|cwd| !cwd.trim().is_empty()),+ session_id,+ )+ }+}++fn is_tool_event(event: &str) -> bool {+ matches!(+ event.to_ascii_lowercase().replace(['-', '_'], "").as_str(),+ "pretooluse" | "posttooluse" | "tooluse"+ )+}+/// Resolve the data dir cheaply, without loading the full config (the hook/// fast-path skips config for latency). Mirrors `config.rs`: explicit/// `--data-dir`, else `AI_MEMORY_DATA_DIR`, else the platform local-data dir.@@ -443,6 +525,7 @@ mod tests {server_url: "http://127.0.0.1:1".into(),auth_token: None,project_strategy: None,+ check_capture: false,}}@@ -912,6 +995,7 @@ mod tests {server_url: "http://127.0.0.1:1".into(),auth_token: None,project_strategy: None,+ check_capture: false,};run_with_payload(@@ -952,6 +1036,7 @@ mod tests {server_url: "http://127.0.0.1:1".into(),auth_token: None,project_strategy: None,+ check_capture: false,};run_with_payload(@@ -991,6 +1076,7 @@ mod tests {server_url: "http://127.0.0.1:1".into(),auth_token: None,project_strategy: None,+ check_capture: false,};run_with_payload(Some(data_dir), args, "{}".into(), &mut stdout, |_path| {@@ -1016,6 +1102,7 @@ mod tests {server_url: "http://127.0.0.1:1".into(),auth_token: None,project_strategy: None,+ check_capture: false,};run_with_payload(@@ -1096,4 +1183,173 @@ mod tests {Duration::from_secs(60));}++ #[tokio::test]+ async fn capture_drop_prevents_spool_and_drainer() {+ let tmp = tempfile::tempdir().unwrap();+ std::fs::write(+ tmp.path().join(".ai-memory.toml"),+ "[capture]\nignore_paths = [\"secret/**\"]\n",+ )+ .unwrap();+ let data_dir = tmp.path().join("data");+ let mut stdout = Vec::new();+ let called = std::cell::Cell::new(false);+ let mut args = devin_hook_args("post-tool-use");+ args.server_url = "http://127.0.0.1:1".into();+ run_with_payload(Some(data_dir.clone()), args, serde_json::json!({"cwd":tmp.path(),"tool_name":"Edit","tool_input":{"path":"secret/SENTINEL"}}).to_string(), &mut stdout, |_| { called.set(true); Ok(()) }).await.unwrap();+ assert_eq!(stdout, b"{}\n");+ assert!(!called.get());+ assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);+ }++ #[tokio::test]+ async fn invalid_capture_marker_spools_only_metadata() {+ let tmp = tempfile::tempdir().unwrap();+ std::fs::write(+ tmp.path().join(".ai-memory.toml"),+ "[capture]\nunknown = 1\n",+ )+ .unwrap();+ let data_dir = tmp.path().join("data");+ let mut stdout = Vec::new();+ run_with_payload(Some(data_dir.clone()), devin_hook_args("post-tool-use"), serde_json::json!({"cwd":tmp.path(),"tool_name":"Edit","tool_input":{"path":"SENTINEL_PATH","args":"SENTINEL_ARGS"},"output":"SENTINEL_OUTPUT","error":"SENTINEL_ERROR","nested":{"raw":"SENTINEL_NESTED"}}).to_string(), &mut stdout, |_| Ok(())).await.unwrap();+ let entry = read_spooled_entries(&hook_spool::spool_dir(&data_dir))+ .pop()+ .unwrap();+ for sentinel in [+ "SENTINEL_PATH",+ "SENTINEL_ARGS",+ "SENTINEL_OUTPUT",+ "SENTINEL_ERROR",+ "SENTINEL_NESTED",+ ] {+ assert!(!entry.body.contains(sentinel));+ }+ assert!(entry.body.contains("_ai_memory_capture"));+ }++ #[tokio::test]+ async fn check_capture_has_no_spool_side_effects() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let mut args = devin_hook_args("post-tool-use");+ args.check_capture = true;+ let mut stdout = Vec::new();+ run_with_payload(Some(data_dir.clone()), args, serde_json::json!({"cwd":tmp.path(),"tool_name":"Edit","tool_input":{"path":"SENTINEL"}}).to_string(), &mut stdout, |_| Err(std::io::Error::other("must not spawn"))).await.unwrap();+ let output: serde_json::Value = serde_json::from_slice(&stdout).unwrap();+ assert_eq!(output.as_object().unwrap().len(), 6);+ assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);+ assert!(!String::from_utf8(stdout).unwrap().contains("SENTINEL"));+ }++ #[tokio::test]+ async fn inactive_preserves_bytes_and_active_keep_adds_protocol() {+ let tmp = tempfile::tempdir().unwrap();+ let inactive_data = tmp.path().join("inactive-data");+ let inactive_payload =+ serde_json::json!({"cwd":tmp.path(),"tool_name":"Edit","tool_input":{"path":"public"}})+ .to_string();+ let mut stdout = Vec::new();+ run_with_payload(+ Some(inactive_data.clone()),+ devin_hook_args("post-tool-use"),+ inactive_payload.clone(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();+ assert_eq!(+ read_spooled_entries(&hook_spool::spool_dir(&inactive_data))[0].body,+ inactive_payload+ );++ std::fs::write(+ tmp.path().join(".ai-memory.toml"),+ "[capture]\nignore_paths = [\"secret/**\"]\n",+ )+ .unwrap();+ let active_data = tmp.path().join("active-data");+ run_with_payload(+ Some(active_data.clone()),+ devin_hook_args("post-tool-use"),+ serde_json::json!({"cwd":tmp.path(),"tool_name":"Edit","tool_input":{"path":"public"}})+ .to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();+ let body: serde_json::Value = serde_json::from_str(+ &read_spooled_entries(&hook_spool::spool_dir(&active_data))[0].body,+ )+ .unwrap();+ assert_eq!(body["_ai_memory_capture"]["disposition"], "keep");+ assert_eq!(body["_ai_memory_capture"]["policy_state"], "active");+ }++ #[tokio::test]+ async fn antigravity_workspace_path_drops_before_side_effects() {+ let tmp = tempfile::tempdir().unwrap();+ std::fs::write(+ tmp.path().join(".ai-memory.toml"),+ "workspace = \"canonical\"\n[capture]\nignore_paths = [\"secret/**\"]\n",+ )+ .unwrap();+ let data_dir = tmp.path().join("data");+ let mut args = devin_hook_args("post-tool-use");+ args.agent = "antigravity-cli".into();+ let mut stdout = Vec::new();+ let raw = serde_json::json!({"workspacePaths":[tmp.path()],"toolCall":{"name":"Edit","args":{"path":"secret/a"}}});+ assert!(cwd_query_suffix("antigravity-cli", &raw, None).contains("workspace=canonical"));+ run_with_payload(+ Some(data_dir.clone()),+ args,+ raw.to_string(),+ &mut stdout,+ |_| Err(std::io::Error::other("must not spawn")),+ )+ .await+ .unwrap();+ assert_eq!(stdout, b"{}\n");+ assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);+ }++ #[tokio::test]+ async fn metadata_only_canonicalizes_supported_session_aliases() {+ for (key, value) in [+ ("session_id", serde_json::json!("one")),+ ("sessionId", serde_json::json!("two")),+ ("sessionID", serde_json::json!("three")),+ ("conversationId", serde_json::json!("four")),+ ] {+ let tmp = tempfile::tempdir().unwrap();+ std::fs::write(+ tmp.path().join(".ai-memory.toml"),+ "[capture]\nunknown = true\n",+ )+ .unwrap();+ let data_dir = tmp.path().join("data");+ let mut raw = serde_json::json!({"cwd":tmp.path(),"tool_name":"Edit","tool_input":{"path":"secret"}});+ raw.as_object_mut()+ .unwrap()+ .insert(key.into(), value.clone());+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ devin_hook_args("post-tool-use"),+ raw.to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();+ let body: serde_json::Value = serde_json::from_str(+ &read_spooled_entries(&hook_spool::spool_dir(&data_dir))[0].body,+ )+ .unwrap();+ assert_eq!(body["session_id"], value, "{key}");+ }+ }}diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex bb065e87..bd2c3353 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -6,10 +6,70 @@//! `.ai-memory.toml` marker, and build the query-string suffix. The two//! request helpers are best-effort with shell-parity timeouts.+use std::io::Read;use std::path::{Path, PathBuf};use std::time::Duration;use crate::commands::path_util::home_dir;+use ai_memory_hooks::capture_policy::MAX_MARKER_BYTES;+use ai_memory_hooks::{CaptureConfig, CapturePolicy, CaptureSource};++/// Resolve the nearest marker's capture policy without changing routing parsing.+/// Root-level marker keys are intentionally ignored here; only `[capture]` is strict.+pub fn capture_policy(cwd: &str) -> CapturePolicy {+ let home = home_dir();+ let Some(marker) = find_marker(cwd) else {+ return CapturePolicy::resolve(+ CaptureSource::Absent,+ cwd,+ home.as_deref().and_then(Path::to_str),+ );+ };+ let marker_dir = marker.parent().and_then(Path::to_str).unwrap_or(cwd);+ match read_capture_config(&marker) {+ Ok(config) => CapturePolicy::resolve(+ CaptureSource::Parsed(&config),+ marker_dir,+ home.as_deref().and_then(Path::to_str),+ ),+ Err(()) => CapturePolicy::resolve(+ CaptureSource::Invalid,+ marker_dir,+ home.as_deref().and_then(Path::to_str),+ ),+ }+}++fn read_capture_config(marker: &Path) -> Result<CaptureConfig, ()> {+ let mut bytes = Vec::with_capacity(MAX_MARKER_BYTES + 1);+ std::fs::File::open(marker)+ .map_err(|_| ())?+ .take((MAX_MARKER_BYTES + 1) as u64)+ .read_to_end(&mut bytes)+ .map_err(|_| ())?;+ if bytes.len() > MAX_MARKER_BYTES {+ return Err(());+ }+ let text = String::from_utf8(bytes).map_err(|_| ())?;+ let document = text.parse::<toml_edit::DocumentMut>().map_err(|_| ())?;+ let Some(capture) = document.get("capture") else {+ return Ok(CaptureConfig::default());+ };+ let table = capture.as_table().ok_or(())?;+ if table.iter().any(|(key, _)| key != "ignore_paths") {+ return Err(());+ }+ let ignore_paths = match table.get("ignore_paths") {+ None => Vec::new(),+ Some(item) => item+ .as_array()+ .ok_or(())?+ .iter()+ .map(|value| value.as_str().map(str::to_owned).ok_or(()))+ .collect::<Result<Vec<_>, _>>()?,+ };+ Ok(CaptureConfig { ignore_paths })+}/// First top-level `cwd` string in the payload (parity with/// `ai_memory_extract_cwd`: take the top-level value, ignore nested@@ -21,6 +81,72 @@ pub fn extract_cwd(payload: &serde_json::Value) -> Option<String> {.map(str::to_owned)}+/// Fixture-backed canonical routing context shared by native marker routing and+/// pre-spool capture. Only explicit agent payload shapes are accepted.+pub fn canonical_context(payload: &serde_json::Value) -> (Option<String>, Option<String>) {+ let direct = |keys: &[&str]| {+ keys.iter().find_map(|key| {+ payload+ .get(*key)+ .and_then(serde_json::Value::as_str)+ .filter(|value| !value.trim().is_empty())+ .map(str::to_owned)+ })+ };+ let nested = |path: &[&str]| {+ path.iter()+ .try_fold(payload, |value, key| value.get(*key))+ .and_then(serde_json::Value::as_str)+ .filter(|value| !value.trim().is_empty())+ .map(str::to_owned)+ };+ let cwd = direct(&["cwd", "current_dir", "working_dir", "directory"])+ .or_else(|| {+ payload+ .get("workspacePaths")+ .and_then(serde_json::Value::as_array)+ .and_then(|paths| paths.first())+ .and_then(serde_json::Value::as_str)+ .filter(|value| !value.trim().is_empty())+ .map(str::to_owned)+ })+ .or_else(|| {+ [+ ["path", "cwd"].as_slice(),+ ["info", "directory"].as_slice(),+ ["properties", "info", "directory"].as_slice(),+ ["event", "properties", "info", "directory"].as_slice(),+ ["payload", "path", "cwd"].as_slice(),+ ["payload", "info", "directory"].as_slice(),+ ["payload", "properties", "info", "directory"].as_slice(),+ ]+ .iter()+ .find_map(|path| nested(path))+ });+ let session = direct(&[+ "session_id",+ "sessionId",+ "sessionID",+ "session",+ "conversationId",+ ])+ .or_else(|| {+ [+ ["info", "id"].as_slice(),+ ["properties", "sessionID"].as_slice(),+ ["properties", "info", "id"].as_slice(),+ ["event", "properties", "sessionID"].as_slice(),+ ["event", "properties", "info", "id"].as_slice(),+ ["payload", "info", "id"].as_slice(),+ ["payload", "properties", "sessionID"].as_slice(),+ ["payload", "properties", "info", "id"].as_slice(),+ ]+ .iter()+ .find_map(|path| nested(path))+ });+ (cwd, session)+}+fn non_empty(value: Option<String>) -> Option<String> {value.filter(|s| !s.trim().is_empty())}@@ -37,7 +163,7 @@ pub fn resolve_cwd_with_fallbacks(mut env_lookup: impl FnMut(&str) -> Option<String>,current_dir: impl FnOnce() -> Option<PathBuf>,) -> Option<String> {- non_empty(extract_cwd(payload))+ non_empty(canonical_context(payload).0).or_else(|| non_empty(env_lookup("DEVIN_PROJECT_DIR"))).or_else(|| {current_dir().and_then(|path| {@@ -612,6 +738,42 @@ project = "infra" # this is fineassert_eq!(found.as_deref(), Some(marker.as_path()));}+ #[test]+ fn capture_section_is_strict_and_marker_read_is_bounded() {+ let tmp = tempfile::TempDir::new().unwrap();+ let marker = tmp.path().join(".ai-memory.toml");+ std::fs::write(+ &marker,+ "workspace = \"allowed\"\n[capture]\nignore_paths = [\"secret/**\"]\n",+ )+ .unwrap();+ assert_eq!(+ read_capture_config(&marker).unwrap().ignore_paths,+ ["secret/**"]+ );+ std::fs::write(&marker, "[capture]\nunknown = true\n").unwrap();+ assert!(read_capture_config(&marker).is_err());+ std::fs::write(&marker, "[capture\n").unwrap();+ assert!(read_capture_config(&marker).is_err());+ std::fs::write(&marker, "x".repeat(MAX_MARKER_BYTES + 1)).unwrap();+ assert!(read_capture_config(&marker).is_err());+ }++ #[test]+ fn canonical_context_matches_supported_routing_shapes() {+ let agy =+ serde_json::json!({"workspacePaths":["/workspace/project"],"conversationId":"conv"});+ assert_eq!(+ canonical_context(&agy),+ (Some("/workspace/project".into()), Some("conv".into()))+ );+ let generated = serde_json::json!({"payload":{"properties":{"info":{"directory":"/generated"},"sessionID":"nested"}}});+ assert_eq!(+ canonical_context(&generated),+ (Some("/generated".into()), Some("nested".into()))+ );+ }+/// `marker_query_suffix` appends `&workspace=…&project=…` (and/// `&project_strategy=…`, `&drop_subagent=…`) when the marker declares them./// Each value is URL-encoded, so a workspace with a space round-trips as `%20`.diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex a89043a9..50edfb70 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -29,7 +29,8 @@ use crate::commands::render_shared::{GEMINI_PROFILE, build_antigravity_payload_with_data_dir,build_claude_code_payload_with_data_dir, build_devin_payload_with_data_dir,build_grok_payload_with_data_dir, build_profile_payload_for_agent, hook_script_for_claude_code,- hook_script_for_current_platform, ts_string_literal,+ hook_script_for_current_platform, local_hook_policy_v1_supported, ts_capture_policy_v1,+ ts_string_literal,};use crate::config::{Config, DEFAULT_SERVER_URL};@@ -168,6 +169,19 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {if let Some(user) = args.as_user.as_deref().filter(|s| !s.trim().is_empty()) {eprintln!("[ai-memory] hooks installing for user: {user}");}+ let generated = matches!(+ args.agent,+ AgentChoice::OpenCode | AgentChoice::Omp | AgentChoice::Pi | AgentChoice::Openclaw+ );+ if generated || local_hook_policy_v1_supported() {+ eprintln!(+ "[ai-memory] capture-policy capability v1 enforced by this selected integration; re-run --apply to refresh existing installs."+ );+ } else {+ eprintln!(+ "[ai-memory] selected shell/PowerShell compatibility path does not enforce capture-policy v1; use a native platform selection or generated integration."+ );+ }if args.apply {return match args.agent {AgentChoice::OpenCode => apply_to_opencode_plugin(&server_url, auth, &args),@@ -1434,6 +1448,7 @@ fn build_opencode_plugin(.map(|t| format!("const TOKEN: string | null = {};\n", ts_string_literal(t))).unwrap_or_else(|| "const TOKEN: string | null = null;\n".to_string());let apply_marker_params = ts_apply_marker_params(project_strategy);+ let capture_policy = ts_capture_policy_v1();format!(r#"// Auto-generated by `ai-memory install-hooks --agent opencode --apply`.// Edit by re-running the command, not by hand — install-hooks@@ -1442,13 +1457,14 @@ fn build_opencode_plugin(import type {{ Plugin }} from "@opencode-ai/plugin";import {{ execFileSync }} from "node:child_process";-import {{ existsSync, readFileSync }} from "node:fs";+import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync }} from "node:fs";import {{ basename, dirname, join, resolve }} from "node:path";import {{ homedir }} from "node:os";const SERVER = {server_literal}.replace(/\/+$/, "");const AGENT = "open-code";{token_line}+{capture_policy}function timeoutSignal(ms: number): AbortSignal | undefined {{if (typeof AbortSignal === "undefined") return undefined;@@ -1654,8 +1670,10 @@ function postHook(event: string, payload: Record<string, unknown>): void {{url.searchParams.set("event", event);url.searchParams.set("agent", AGENT);applyMarkerParams(url, typeof payload.cwd === "string" ? payload.cwd : undefined);+ const policy = capturePolicy(payload, typeof payload.cwd === "string" ? payload.cwd : undefined);+ if (policy.disposition === "drop") return;try {{- enqueueHook(event, url, payload);+ enqueueHook(event, url, policy.payload);}} catch (_e) {{// Best-effort capture. Hooks must never block the agent.}}@@ -2006,6 +2024,7 @@ fn build_omp_extension(.map(|t| format!("const TOKEN: string | null = {};\n", ts_string_literal(t))).unwrap_or_else(|| "const TOKEN: string | null = null;\n".to_string());let apply_marker_params = ts_apply_marker_params(project_strategy);+ let capture_policy = ts_capture_policy_v1();format!(r#"// Auto-generated by `ai-memory install-hooks --agent omp --apply`.// Edit by re-running the command, not by hand — install-hooks@@ -2013,13 +2032,14 @@ fn build_omp_extension(// re-run.import {{ execFileSync }} from "node:child_process";-import {{ existsSync, readFileSync }} from "node:fs";+import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync }} from "node:fs";import {{ basename, dirname, join, resolve }} from "node:path";import {{ homedir }} from "node:os";const SERVER = {server_literal}.replace(/\/+$/, "");const AGENT = "omp";{token_line}+{capture_policy}function timeoutSignal(ms: number): AbortSignal | undefined {{if (typeof AbortSignal === "undefined") return undefined;@@ -2209,8 +2229,10 @@ function postHook(event: string, payload: Record<string, unknown>): void {{url.searchParams.set("event", event);url.searchParams.set("agent", AGENT);applyMarkerParams(url, typeof payload.cwd === "string" ? payload.cwd : undefined);+ const policy = capturePolicy(payload, typeof payload.cwd === "string" ? payload.cwd : undefined);+ if (policy.disposition === "drop") return;try {{- enqueueHook(event, url, payload);+ enqueueHook(event, url, policy.payload);}} catch (_e) {{// Best-effort capture. Hooks must never block the agent.}}@@ -3915,7 +3937,11 @@ model = "gpt-5"assert!(generated.contains("async function drainHookQueue(): Promise<void>"));assert!(generated.contains("signal: timeoutSignal(HOOK_REQUEST_TIMEOUT_MS)"));assert!(generated.contains("await sleep(HOOK_INTER_REQUEST_DELAY_MS)"));- assert!(generated.contains("enqueueHook(event, url, payload);"));+ assert!(generated.contains("const policy = capturePolicy(payload"));+ assert!(generated.contains("if (policy.disposition === \"drop\") return;"));+ assert!(generated.contains("enqueueHook(event, url, policy.payload);"));+ assert!(generated.contains("const CAPTURE_POLICY_V1 = 1;"));+ assert!(generated.contains("const CAPTURE_MARKER_MAX_BYTES = 64 * 1024;"));assert!(generated.contains("async function fetchHandoff"));assert!(generated.contains("const response = await fetch(url, {"));assert!(generated.contains("signal: timeoutSignal(1000)"));diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rsindex 876a1e6d..7b8d5a3e 100644--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs@@ -8,7 +8,7 @@ use anyhow::{Context, Result};use crate::cli::InstallHooksArgs;use crate::commands::apply_shared::{ApplyOutcome, apply_atomic};-use crate::commands::render_shared::ts_string_literal;+use crate::commands::render_shared::{ts_capture_policy_v1, ts_string_literal};pub(crate) const PLUGIN_ID: &str = "ai-memory";pub(crate) const PACKAGE_NAME: &str = "@ai-memory/openclaw-plugin";@@ -288,6 +288,7 @@ fn build_plugin(.map(|t| format!("const TOKEN: string | null = {};\n", ts_string_literal(t))).unwrap_or_else(|| "const TOKEN: string | null = null;\n".to_string());let apply_marker_params = apply_marker_params_ts(project_strategy);+ let capture_policy = ts_capture_policy_v1();format!(r#"// Auto-generated by `ai-memory install-hooks --agent openclaw --apply`.// Edit by re-running the command, not by hand. install-hooks owns@@ -295,13 +296,14 @@ fn build_plugin(import {{ definePluginEntry }} from "openclaw/plugin-sdk/plugin-entry";import {{ execFileSync }} from "node:child_process";-import {{ existsSync, readFileSync }} from "node:fs";+import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync }} from "node:fs";import {{ basename, dirname, join, resolve }} from "node:path";import {{ homedir }} from "node:os";const SERVER = {server_literal}.replace(/\/+$/, "");const AGENT = "openclaw";{token_line}+{capture_policy}function timeoutSignal(ms: number): AbortSignal | undefined {{if (typeof AbortSignal === "undefined") return undefined;@@ -420,11 +422,13 @@ function postHook(eventName: string, body: Record<string, unknown>): void {{url.searchParams.set("event", eventName);url.searchParams.set("agent", AGENT);applyMarkerParams(url, typeof body.cwd === "string" ? body.cwd : undefined);+ const policy = capturePolicy(body, typeof body.cwd === "string" ? body.cwd : undefined);+ if (policy.disposition === "drop") return;try {{void fetch(url, {{method: "POST",headers: {{ "Content-Type": "application/json", ...authHeaders() }},- body: JSON.stringify(body),+ body: JSON.stringify(policy.payload),signal: timeoutSignal(500),}}).catch(() => undefined);}} catch (_e) {{@@ -564,6 +568,9 @@ mod tests {));assert!(plugin.contains("applyMarkerParams(url, currentCwd);"));assert!(plugin.contains("fetchHandoff"));+ assert!(plugin.contains("// capture-policy-v1 (generated; do not fork between adapters)"));+ assert!(plugin.contains("const policy = capturePolicy(body"));+ assert!(plugin.contains("body: JSON.stringify(policy.payload)"));assert!(plugin.contains("prependContext: handoff"));assert!(plugin.contains("Bearer ${TOKEN}"));assert!(plugin.contains("tok"));diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 06b5dc6a..440baca1 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -99,6 +99,38 @@ pub(crate) fn ts_string_literal(s: &str) -> String {out}+/// The single capture-policy-v1 implementation embedded in every generated+/// JavaScript integration. It deliberately has no package dependency: these+/// extensions run in several hosts with different module loaders.+#[must_use]+pub(crate) fn ts_capture_policy_v1() -> &'static str {+ r##"// capture-policy-v1 (generated; do not fork between adapters)+const CAPTURE_POLICY_V1 = 1;+const CAPTURE_MARKER_MAX_BYTES = 64 * 1024;+const CAPTURE_MAX_PATTERNS = 128;+const CAPTURE_MAX_PATTERN_CHARS = 1024;+const CAPTURE_MAX_PATH_CHARS = 4096;+const CAPTURE_MAX_CANDIDATES = 32;+const CAPTURE_MAX_WORK = 1000000;+const CAPTURE_MAX_CALL_ID_CHARS = 128;++type CaptureDisposition = "keep" | "drop" | "metadata-only";+type CaptureProtocol = { version: 1; disposition: CaptureDisposition; policy_state: "inactive" | "active" | "invalid"; tool_family: "file" | "search-list" | "non-file" | "unknown"; path_count: number; extraction_state: "not-applicable" | "extracted" | "missing-or-malformed" | "unsupported-schema" };++type CaptureConfig = { state: "inactive" | "active" | "invalid"; patterns: { path: string; windows: boolean; directory?: string }[]; base: string };+function readFileSync(path: string, encoding?: "utf8"): any { if (encoding) return readMarkerText(path, encoding); const fd = openSync(path, "r"); try { const bytes = Buffer.allocUnsafe(CAPTURE_MARKER_MAX_BYTES + 1); const count = readSync(fd, bytes, 0, bytes.length, 0); if (count > CAPTURE_MARKER_MAX_BYTES) throw new Error("marker too large"); const result = bytes.subarray(0, count); new TextDecoder("utf-8", { fatal: true }).decode(result); return result; } finally { closeSync(fd); } }+function captureTrimComment(line: string): string { let quote = ""; let escaped = false; for (let i = 0; i < line.length; i++) { const c = line[i]; if (escaped) { escaped = false; continue; } if (c === "\\" && quote === '"') { escaped = true; continue; } if ((c === '"' || c === "'") && (!quote || quote === c)) quote = quote ? "" : c; else if (c === "#" && !quote) { line = line.slice(0, i); break; } } if (line.trimStart().startsWith("[") && !/^\s*\[[^\]]+\]\s*$/.test(line)) throw new Error("invalid table header"); if (quote) throw new Error("unterminated string"); return line; }+function captureNormalize(path: string): { path: string; windows: boolean } | undefined { const p = path.replace(/\\/g, "/"); let root: string; let tail: string[]; if (p.startsWith("//")) { const x = p.slice(2).split("/").filter(Boolean); if (x.length < 2) return undefined; root = `//${x.shift()}/${x.shift()}`; tail = x; } else if (/^[A-Za-z]:\//.test(p)) { root = `${p[0].toUpperCase()}:/`; tail = p.slice(3).split("/"); } else if (p.startsWith("/")) { root = "/"; tail = p.slice(1).split("/"); } else return undefined; const out: string[] = []; for (const x of tail) { if (!x || x === ".") continue; if (x === "..") out.pop(); else out.push(x); } return { path: root + (out.length ? (root.endsWith("/") ? "" : "/") + out.join("/") : ""), windows: root !== "/" }; }+function captureJoin(base: string, child: string): string { if (/^[^A-Za-z]?:|^[A-Za-z]:[^/\\]/.test(child)) return child; return `${base.replace(/[\\/]+$/, "")}/${child}`; }+function captureValidGlob(p: string): boolean { return !!p && [...p].length <= CAPTURE_MAX_PATTERN_CHARS && !/[!{}\[\]()|^$%]/.test(p) && !p.includes("${") && !p.includes("***") && !p.replace(/\\/g, "/").split("/").includes("..") && (!p.startsWith("~") || p.startsWith("~/")) && !/^[^A-Za-z]?:/.test(p) && !/^[A-Za-z]:[^/\\]/.test(p); }+function captureParseArray(value: string): string[] | undefined { let i = 0; const out: string[] = []; const ws = () => { while (/\s/.test(value[i] ?? "")) i++; }; const basic = { b: "\b", t: "\t", n: "\n", f: "\f", r: "\r", '"': '"', "\\": "\\" } as Record<string, string>; ws(); if (value[i++] !== "[") return undefined; for (;;) { ws(); if (value[i] === "]") { i++; ws(); return i === value.length ? out : undefined; } const quote = value[i++]; if (quote !== '"' && quote !== "'") return undefined; let s = ""; for (;;) { if (i >= value.length) return undefined; const c = value[i++]; if (c === quote) break; if (c === "\\" && quote === '"') { const e = value[i++]; if (e in basic) s += basic[e]; else if (e === "u" || e === "U") { const count = e === "u" ? 4 : 8; const hex = value.slice(i, i + count); if (!new RegExp(`^[0-9A-Fa-f]{${count}}$`).test(hex)) return undefined; const n = Number.parseInt(hex, 16); if (n > 0x10ffff || (n >= 0xd800 && n <= 0xdfff)) return undefined; s += String.fromCodePoint(n); i += count; } else return undefined; } else if (c === "\n" || c === "\r") return undefined; else s += c; } out.push(s); ws(); if (value[i] === ",") { i++; continue; } if (value[i] === "]") continue; return undefined; } }+function captureConfig(cwd: string | undefined): CaptureConfig { const marker = findMarker(cwd); const fallback = captureNormalize(cwd ?? "")?.path ?? ""; if (!marker) return { state: "inactive", patterns: [], base: fallback }; try { const bytes = readFileSync(marker); const base = captureNormalize(dirname(marker))?.path ?? fallback; if (bytes.byteLength > CAPTURE_MARKER_MAX_BYTES) return { state: "invalid", patterns: [], base }; let section = ""; let value = ""; let collecting = false; let seen = false; for (const raw of bytes.toString("utf8").split(/\r?\n/)) { const line = captureTrimComment(raw).trim(); if (!line) continue; const table = /^\[([^\]]+)\]$/.exec(line); if (table) { if (collecting) return { state: "invalid", patterns: [], base }; section = table[1]; continue; } if (section !== "capture") continue; if (!seen) { const kv = /^([A-Za-z0-9_-]+)\s*=\s*(.*)$/.exec(line); if (!kv || kv[1] !== "ignore_paths") return { state: "invalid", patterns: [], base }; seen = true; value = kv[2]; collecting = !value.includes("]"); } else if (collecting) { value += ` ${line}`; collecting = !value.includes("]"); } else return { state: "invalid", patterns: [], base }; } if (collecting) return { state: "invalid", patterns: [], base }; if (!seen) return { state: "inactive", patterns: [], base }; const strings = captureParseArray(value); if (!strings || strings.length > CAPTURE_MAX_PATTERNS) return { state: "invalid", patterns: [], base }; const home = homedir(); const patterns = strings.map((source) => { if (!captureValidGlob(source)) return undefined; const expanded = source.startsWith("~/") ? captureJoin(home, source.slice(2)) : /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(source) ? source : captureJoin(base, source); const normalized = captureNormalize(expanded); if (!normalized) return undefined; return { path: normalized.path, windows: normalized.windows, directory: normalized.path.endsWith("/**") ? (normalized.path.slice(0, -3) || "/") : undefined }; }); if (patterns.some((p) => !p)) return { state: "invalid", patterns: [], base }; return patterns.length ? { state: "active", patterns: patterns as CaptureConfig["patterns"], base } : { state: "inactive", patterns: [], base }; } catch (_e) { return { state: "invalid", patterns: [], base: fallback }; } }+function captureGlob(pattern: string, candidate: string, insensitive: boolean, budget: { work: number }): boolean | undefined { const p = [...pattern]; const c = [...candidate]; const eq = (a: string, b: string) => insensitive && a.charCodeAt(0) < 128 && b.charCodeAt(0) < 128 ? a.toLowerCase() === b.toLowerCase() : a === b; const previous = new Array<boolean>(p.length + 1).fill(false); previous[0] = true; for (let j = 1; j <= p.length; j++) previous[j] = p[j - 1] === "*" && p[j] !== "*" && previous[j - 1]; for (const ch of c) { const current = new Array<boolean>(p.length + 1).fill(false); for (let j = 1; j <= p.length; j++) { if (++budget.work > CAPTURE_MAX_WORK) return undefined; const x = p[j - 1]; current[j] = x === "*" && p[j] === "*" ? false : x === "*" && j >= 2 && p[j - 2] === "*" ? current[j - 2] || previous[j] : x === "*" ? current[j - 1] || (ch !== "/" && previous[j]) : x === "?" ? ch !== "/" && previous[j - 1] : eq(x, ch) && previous[j - 1]; } for (let j = 0; j <= p.length; j++) previous[j] = current[j]; } return previous[p.length]; }+function captureTool(payload: Record<string, unknown>): { family: CaptureProtocol["tool_family"]; paths?: string[]; extraction: CaptureProtocol["extraction_state"]; callID?: string } { const name = typeof payload.tool === "string" ? payload.tool.toLowerCase() : ""; const args = payload.args as Record<string, unknown> | undefined; const call = ["tool_use_id","toolUseId","tool_call_id","toolCallId","call_id","callId","callID"].map((k) => payload[k]).find((v): v is string => typeof v === "string" && /^[A-Za-z0-9_.-]{1,128}$/.test(v)); if (["search","grep","glob","find","list","ls","list_files","read_dir"].includes(name)) return { family: "search-list", extraction: "not-applicable", callID: call }; if (["bash","shell","execute","run_command","web_search"].includes(name)) return { family: "non-file", extraction: "extracted", callID: call }; if (!["read","write","edit","apply_patch","notebookedit","notebook_edit","create_file","delete_file","rename_file","move_file","multi_edit","multiedit","replace","replace_all"].includes(name)) return { family: "unknown", extraction: "extracted", callID: call }; const direct = (o: any): string[] | undefined => { if (!o || typeof o !== "object") return undefined; const r: string[] = []; for (const k of ["file_path","filePath","path","absolute_path","AbsolutePath","notebook_path"]) if (k in o) { if (typeof o[k] !== "string") return undefined; r.push(o[k]); } if ("paths" in o) { if (!Array.isArray(o.paths) || o.paths.some((x: unknown) => typeof x !== "string")) return undefined; r.push(...o.paths); } return r.length && r.length <= CAPTURE_MAX_CANDIDATES ? r : undefined; }; let paths = direct(args); if (["multi_edit","multiedit","replace_all"].includes(name)) { const entries = args?.edits ?? args?.replacements; if (!Array.isArray(entries) || !entries.length || entries.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else { paths = paths ?? []; for (const entry of entries) { const more = direct(entry); if (!more || paths.length + more.length > CAPTURE_MAX_CANDIDATES) { paths = undefined; break; } paths.push(...more); } } } if (!paths || paths.some((p) => !p.trim() || [...p].length > CAPTURE_MAX_PATH_CHARS)) return { family: "file", extraction: "missing-or-malformed", callID: call }; return { family: "file", paths, extraction: "extracted", callID: call }; }+function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { const config = captureConfig(cwd); const tool = captureTool(payload); let disposition: CaptureDisposition = "keep"; if (config.state === "invalid" && tool.family === "file") disposition = "metadata-only"; else if (config.state === "active" && tool.family === "search-list") disposition = "drop"; else if (config.state === "active" && tool.family === "file") { if (!tool.paths) disposition = "metadata-only"; else { const candidates = tool.paths.map((p) => captureNormalize(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p))); if (candidates.some((p) => !p)) disposition = "metadata-only"; else { const budget = { work: 0 }; captureMatch: for (const candidate of candidates as { path: string; windows: boolean }[]) for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; if (pattern.directory && captureGlob(pattern.directory, candidate.path, pattern.windows, budget)) { disposition = "drop"; break captureMatch; } const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match === undefined) { disposition = "metadata-only"; break; } if (match) { disposition = "drop"; break captureMatch; } } } } } if (config.state === "inactive") return { disposition, payload }; const protocol: CaptureProtocol = { version: CAPTURE_POLICY_V1, disposition, policy_state: config.state, tool_family: tool.family, path_count: tool.paths?.length ?? 0, extraction_state: tool.extraction }; if (disposition === "metadata-only") { const session = payload.sessionID ?? payload.sessionId ?? payload.session_id; const routing = typeof payload.cwd === "string" ? payload.cwd : cwd; return { disposition, protocol, payload: { ...(typeof session === "string" ? { session_id: session } : {}), ...(typeof routing === "string" ? { cwd: routing } : {}), tool_family: tool.family, tool_name: tool.family, ...(tool.callID ? { tool_call_id: tool.callID } : {}), _ai_memory_capture: protocol } }; } if (disposition === "keep") return { disposition, protocol, payload: { ...payload, _ai_memory_capture: protocol } }; return { disposition, protocol, payload }; }+"##+}+/// Build the Claude Code `settings.json` fragment that wires the/// lifecycle hooks (`CLAUDE_CODE_EVENTS`). Used by both:/// - `install-hooks --agent claude-code` (script paths are@@ -478,12 +510,13 @@ fn build_antigravity_payload_for_platform(for (event, script) in &ANTIGRAVITY_TOOL_EVENTS {let s = script_for_platform(script, platform);let abs = emit_root.join(s.as_ref());- let handler = hook_handler_value(HookHandlerSpec::ShellString(hook_command(+ let handler = hook_handler_value(hook_handler_spec(&abs,server_url,auth_token,HookCommandContext::new(platform, agent, data_dir, project_strategy),- )));+ HookShape::Nested,+ ));group.insert((*event).to_string(),json!([{@@ -497,12 +530,13 @@ fn build_antigravity_payload_for_platform(for (event, script) in &ANTIGRAVITY_LIFECYCLE_EVENTS {let s = script_for_platform(script, platform);let abs = emit_root.join(s.as_ref());- let handler = hook_handler_value(HookHandlerSpec::ShellString(hook_command(+ let handler = hook_handler_value(hook_handler_spec(&abs,server_url,auth_token,HookCommandContext::new(platform, agent, data_dir, project_strategy),- )));+ HookShape::Flat,+ ));group.insert((*event).to_string(), Value::Array(vec![handler]));}@@ -649,9 +683,11 @@ impl HookCommandPlatform {fn current() -> Self {Self::from_env_override().unwrap_or(if cfg!(windows) {- Self::Windows+ Self::WindowsNative} else {- Self::Posix+ // Local installs use the native hook command for policy-v1.+ // `posix` remains an explicit legacy script compatibility override.+ Self::PosixNative})}@@ -749,11 +785,10 @@ fn hook_handler_spec(server_url: &str,auth_token: Option<&str>,context: HookCommandContext<'_>,- shape: HookShape,+ _shape: HookShape,) -> HookHandlerSpec {- if shape == HookShape::Nested+ if context.platform == HookCommandPlatform::WindowsNative&& context.claude_windows_exec_allowed- && context.platform == HookCommandPlatform::WindowsNative&& context.agent == "claude-code"{return windows_native_exec_spec(script, server_url, auth_token, context);@@ -803,6 +838,14 @@ pub(crate) fn hook_script_for_claude_code(script: &str) -> Cow<'_, str> {script_for_platform(script, HookCommandPlatform::for_bash_runner())}+#[must_use]+pub(crate) fn local_hook_policy_v1_supported() -> bool {+ matches!(+ HookCommandPlatform::current(),+ HookCommandPlatform::PosixNative | HookCommandPlatform::WindowsNative+ )+}+fn hook_command(script: &Path,server_url: &str,@@ -1052,7 +1095,9 @@ fn win_double_quote(s: &str) -> String {#[cfg(test)]mod tests {use super::*;+ use std::fs;use std::path::{Path, PathBuf};+ use std::process::Command;fn build_posix_hook_payload(events: &[(&str, &str)],@@ -1082,6 +1127,151 @@ mod tests {assert_eq!(h, "Bearer abc123");}+ /// Manual Node-required runtime evidence for the exact TypeScript emitted by+ /// `ts_capture_policy_v1`. This deliberately executes the emitted source,+ /// rather than maintaining a JavaScript copy in the test suite.+ #[test]+ #[ignore = "manual Node-required generated TypeScript runtime evidence"]+ fn generated_capture_policy_v1_node_runtime_evidence() {+ let strip_types = Command::new("node")+ .args(["--experimental-strip-types", "--version"])+ .output();+ let Ok(strip_types) = strip_types else {+ eprintln!(+ "skipping Node-required runtime evidence: node lacks --experimental-strip-types"+ );+ return;+ };+ if !strip_types.status.success() {+ eprintln!(+ "skipping Node-required runtime evidence: node lacks --experimental-strip-types"+ );+ return;+ }++ let temp = tempfile::tempdir().unwrap();+ let module = temp.path().join("capture-policy-runtime-evidence.ts");+ let fixture = include_str!("../../../ai-memory-hooks/tests/fixtures/capture-policy.json");+ let fixture = serde_json::to_string(fixture).unwrap();+ let source = format!(+ r#"import {{ closeSync, openSync, readFileSync as readMarkerText, readSync, writeFileSync }} from "node:fs";+import {{ dirname, join }} from "node:path";+import {{ homedir }} from "node:os";++const fixtureText = {fixture};+const markerRoot = process.argv[2]!;+const markerFixtures = new Map<string, string>();+function findMarker(cwd: string | undefined): string | undefined {{ return cwd ? markerFixtures.get(cwd) : undefined; }}+{policy}++const fixture = JSON.parse(fixtureText);+const privatePath = "/PRIVATE_PATH_SENTINEL/item";+const privatePattern = "/PRIVATE_PATTERN_SENTINEL/item";+const privateBody = "PRIVATE_BODY_SENTINEL";+let serial = 0;+function fail(label: string): never {{ throw new Error(`runtime evidence failed: ${{label}}`); }}+function check(ok: unknown, label: string): asserts ok {{ if (!ok) fail(label); }}+function marker(text: string, cwd = `/fixture/${{serial++}}`): string {{+ const file = join(markerRoot, `marker-${{serial}}.toml`);+ writeFileSync(file, text);+ markerFixtures.set(cwd, file);+ return cwd;+}}+function decision(payload: Record<string, unknown>, cwd: string) {{ return capturePolicy(payload, cwd); }}+function expectDecision(payload: Record<string, unknown>, cwd: string, disposition: string, family: string, extraction: string, count: number, label: string): void {{+ const result = decision(payload, cwd);+ check(result.disposition === disposition, `${{label}} disposition`);+ check(result.protocol?.tool_family === family, `${{label}} family`);+ check(result.protocol?.extraction_state === extraction, `${{label}} extraction`);+ check(result.protocol?.path_count === count, `${{label}} count`);+}}+const active = '[capture]\nignore_paths = ["secret/**"]\n';+for (const vector of fixture.decisions.filter((v: any) => ["open-code", "omp", "pi", "openclaw"].includes(v.agent))) {{+ const cwd = marker(active);+ expectDecision(vector.payload, cwd, vector.disposition, vector.tool_family, vector.extraction_state, vector.path_count, `fixture-${{vector.agent}}`);+}}+for (const vector of fixture.normalization) {{+ const cwd = marker(`[capture]\nignore_paths = [${{JSON.stringify(vector.pattern)}}]\n`);+ expectDecision({{ tool: "edit", args: {{ path: vector.candidate }} }}, cwd, vector.match ? "drop" : "keep", "file", "extracted", 1, "fixture-normalization");+}}+expectDecision({{ tool: "edit", args: {{ path: "private/item" }} }}, marker('[capture]\nignore_paths = ["private/**"]\n'), "drop", "file", "extracted", 1, "marker-relative");+expectDecision({{ tool: "edit", args: {{ path: `${{homedir()}}/home-private/item` }} }}, marker('[capture]\nignore_paths = ["~/home-private/**"]\n'), "drop", "file", "extracted", 1, "home-expansion");+expectDecision({{ tool: "edit", args: {{ path: "case/item" }} }}, marker('[capture]\nignore_paths = ["Case/**"]\n'), "keep", "file", "extracted", 1, "posix-case");+expectDecision({{ tool: "edit", args: {{ path: "c:/SECRET/item" }} }}, marker('[capture]\nignore_paths = ["C:/secret/**"]\n'), "drop", "file", "extracted", 1, "windows-drive-case");+expectDecision({{ tool: "edit", args: {{ path: "//SERVER/SHARE/item" }} }}, marker(`[capture]\nignore_paths = ['${{String.raw`\\server\share/**`}}']\n`), "drop", "file", "extracted", 1, "windows-unc-case");+expectDecision({{ tool: "edit", args: {{ path: "x" }} }}, marker('[capture'), "metadata-only", "file", "extracted", 1, "malformed-table");+const malformedQuoteCwd = marker('[capture]\nignore_paths = ["private/**');+expectDecision({{ tool: "edit", args: {{ path: privatePath }} }}, malformedQuoteCwd, "metadata-only", "file", "extracted", 1, "malformed-unterminated-quote");+const badUtf8Cwd = `/fixture/${{serial++}}`; const badUtf8 = join(markerRoot, "bad-utf8.toml"); writeFileSync(badUtf8, Buffer.from([0xff])); markerFixtures.set(badUtf8Cwd, badUtf8);+expectDecision({{ tool: "edit", args: {{ path: "x" }} }}, badUtf8Cwd, "metadata-only", "file", "extracted", 1, "invalid-utf8");+expectDecision({{ tool: "edit", args: {{ path: "x" }} }}, marker(`[capture]\nignore_paths = ["${{"x".repeat(65537)}}"]`), "metadata-only", "file", "extracted", 1, "large-marker");+expectDecision({{ tool: "edit", args: {{ path: "literal#item" }} }}, marker("[capture]\nignore_paths = [\n 'literal#item',\n \"basic#item\"\n]\n"), "drop", "file", "extracted", 1, "multiline-and-hash");+expectDecision({{ tool: "edit", args: {{ path: "C:relative" }} }}, marker(active), "metadata-only", "file", "extracted", 1, "drive-relative");+expectDecision({{ tool: "future-tool", args: {{ path: "secret/a" }} }}, marker(active), "keep", "unknown", "extracted", 0, "unknown-tool");+const adversarial = "a".repeat(4090);+expectDecision({{ tool: "multi_edit", args: {{ edits: [{{ path: "secret/a" }}, {{ path: adversarial }}] }} }}, marker('[capture]\nignore_paths = ["secret/**", "*'.concat("a".repeat(1022), '"]\n')), "drop", "file", "extracted", 2, "first-drop-beats-budget");++const requests: string[] = []; const queue: Record<string, unknown>[] = [];+function emit(payload: Record<string, unknown>, cwd: string): void {{ const result = capturePolicy(payload, cwd); if (result.disposition === "drop") return; queue.push(result.payload); requests.push(JSON.stringify(result.payload)); }}+const gatedCwd = marker(`[capture]\nignore_paths = [${{JSON.stringify(privatePattern)}}]\n`);+emit({{ tool: "edit", args: {{ path: "/PRIVATE_PATTERN_SENTINEL/item", nested: {{ body: privateBody }} }}, output: privateBody, error: privateBody }}, gatedCwd);+check(queue.length === 0 && requests.length === 0, "drop-gates-queue-and-fetch");+emit({{ tool: "edit", args: {{ path: privatePath, nested: {{ body: privateBody }} }}, output: privateBody, error: privateBody }}, malformedQuoteCwd);+const malformedRequest = requests.at(-1) ?? "";+const malformedQueued = JSON.stringify(queue.at(-1));+check(JSON.parse(malformedRequest)._ai_memory_capture?.policy_state === "invalid", "malformed-quote-invalid-protocol");+for (const forbidden of [privatePath, privateBody]) check(!malformedQueued.includes(forbidden) && !malformedRequest.includes(forbidden), "malformed-quote-redaction");+emit({{ tool: "edit", args: {{ path: "C:relative", nested: {{ path: privatePath, body: privateBody }} }}, output: privateBody, error: privateBody, sessionID: "session-safe", cwd: "/cwd-safe", tool_call_id: "call-safe" }}, gatedCwd);+const metadata = requests.at(-1) ?? "";+const metadataBody = JSON.parse(metadata);+check(metadataBody.session_id === "session-safe", "metadata-request-session");+check(metadataBody.cwd === "/cwd-safe", "metadata-request-cwd");+check(metadataBody.tool_family === "file", "metadata-request-family");+check(metadataBody.tool_name === "file", "metadata-request-name");+check(metadataBody.tool_call_id === "call-safe", "metadata-request-call");+check(metadataBody._ai_memory_capture?.disposition === "metadata-only" && metadataBody._ai_memory_capture?.policy_state === "active", "metadata-request-protocol");+for (const forbidden of [privatePath, privatePattern, privateBody]) check(!metadata.includes(forbidden), "metadata-request-redaction");+const inactivePayload = {{ tool: "edit", args: {{ path: privatePath }}, output: privateBody }};+const inactive = capturePolicy(inactivePayload, "/no-marker");+check(inactive.disposition === "keep" && inactive.payload === inactivePayload && !inactive.protocol, "inactive-preserves-object");+const activeKeep = capturePolicy({{ tool: "bash", args: {{ command: privateBody }} }}, gatedCwd);+check(activeKeep.disposition === "keep" && activeKeep.protocol?.version === 1 && activeKeep.protocol.policy_state === "active", "active-keep-adds-protocol");+"#,+ fixture = fixture,+ policy = ts_capture_policy_v1(),+ );+ fs::write(&module, source).unwrap();+ let output = Command::new("node")+ .args([+ "--experimental-strip-types",+ module.to_str().unwrap(),+ temp.path().to_str().unwrap(),+ ])+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "Node runtime evidence failed\nstdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );+ let diagnostics = format!(+ "{}{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ for sentinel in [+ "PRIVATE_PATH_SENTINEL",+ "PRIVATE_PATTERN_SENTINEL",+ "PRIVATE_BODY_SENTINEL",+ ] {+ assert!(+ !diagnostics.contains(sentinel),+ "Node diagnostics leaked a private sentinel"+ );+ }+ }+#[test]fn claude_code_payload_has_all_events() {let root = PathBuf::from("/host/hooks/claude-code");@@ -1512,7 +1702,7 @@ mod tests {}#[test]- fn exec_form_is_narrow_to_claude_code_windows_native_nested() {+ fn windows_native_exec_form_is_claude_only_and_guarded() {fn handler_for(platform: HookCommandPlatform,agent: &str,@@ -1549,16 +1739,6 @@ mod tests {"claude-code",HookShape::Nested,),- (- HookCommandPlatform::WindowsNative,- "grok",- HookShape::Nested,- ),- (- HookCommandPlatform::WindowsNative,- "claude-code",- HookShape::Flat,- ),] {let handler = handler_for(platform, agent, shape);assert!(@@ -1567,6 +1747,37 @@ mod tests {);}+ let claude = handler_for(+ HookCommandPlatform::WindowsNative,+ "claude-code",+ HookShape::Nested,+ );+ assert!(+ claude.get("args").is_some(),+ "Claude must use exec form: {claude}"+ );++ for (agent, shape) in [+ ("cursor", HookShape::Flat),+ ("gemini-cli", HookShape::Flat),+ ("codex", HookShape::Nested),+ ("antigravity-cli", HookShape::Flat),+ ("grok", HookShape::Nested),+ ("devin", HookShape::Nested),+ ] {+ let handler = handler_for(HookCommandPlatform::WindowsNative, agent, shape);+ assert!(+ handler.get("args").is_none(),+ "{agent}/{shape:?} must retain command-string schema: {handler}"+ );+ let command = handler["command"].as_str().unwrap();+ assert!(+ command.contains("hook --event session-start")+ && command.contains(&format!("--agent {agent}")),+ "{agent}/{shape:?} must invoke the native hook command: {command}"+ );+ }+let setup_like = build_hook_payload_for_platform(&[("SessionStart", "session-start.sh")],Path::new(r"C:\hooks"),@@ -1584,7 +1795,7 @@ mod tests {setup_like.pointer("/hooks/SessionStart/0/hooks/0/args").is_none(),- "setup-agent style Claude Code payload must not inherit exec form: {setup_like}"+ "unapproved Claude render paths must retain command-string schema: {setup_like}");let antigravity = build_antigravity_payload_for_platform(@@ -1600,7 +1811,7 @@ mod tests {antigravity.pointer("/ai-memory/PreInvocation/0/args").is_none(),- "antigravity must not inherit exec form: {antigravity}"+ "Antigravity must retain command-string schema: {antigravity}");}diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex 2b21231a..7296b568 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -76,6 +76,9 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {let Some(agent_sub) = args.agent.script_hook_subdir() else {bail!("internal: generated integration should have returned before staging hooks")};+ eprintln!(+ "[ai-memory] setup-agent emits shell/PowerShell hook bundles for {agent_sub}; these remote/compatibility bundles do not enforce capture-policy capability v1. Install local native hooks instead when policy enforcement is required."+ );let source = resolve_source(args.source.as_deref(), agent_sub)?;let dest_dir = args.to.join(agent_sub);@@ -217,6 +220,12 @@ fn emit_extension_setup_hint(args: &SetupAgentArgs) -> Result<()> {other => bail!("internal: {other:?} is not a generated-integration agent"),};println!("# {label} uses a TypeScript extension/plugin, not extracted shell scripts.");+ println!(+ "# Capture-policy capability v1 requires a freshly generated integration; re-run --apply after upgrades."+ );+ println!(+ "# Legacy shell/PowerShell and remote-only paths are unsupported compatibility modes."+ );println!("# Install it directly instead:");println!("ai-memory install-hooks --agent {agent} --apply \\");if args.auth_token.is_some() {diff --git a/crates/ai-memory-hooks/Cargo.toml b/crates/ai-memory-hooks/Cargo.tomlindex a092f8ad..9b4092fd 100644--- a/crates/ai-memory-hooks/Cargo.toml+++ b/crates/ai-memory-hooks/Cargo.toml@@ -30,6 +30,8 @@ regex.workspace = true[dev-dependencies]tempfile.workspace = truegit2.workspace = true+ai-memory-llm.workspace = true+async-trait.workspace = true[lints]workspace = truediff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsnew file mode 100644index 00000000..570ad997--- /dev/null+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -0,0 +1,1007 @@+//! Pure, IO-free capture policy evaluation for native hooks and server defense.++use ai_memory_core::AgentKind;+use serde::{Deserialize, Deserializer, Serialize};+use serde_json::{Map, Value, json};++/// Maximum number of `ignore_paths` entries (entries, not bytes).+pub const MAX_IGNORE_PATTERNS: usize = 128;+/// Maximum Unicode scalar characters in one pattern.+pub const MAX_IGNORE_PATTERN_CHARS: usize = 1_024;+/// Marker readers must enforce this maximum byte read before parsing.+pub const MAX_MARKER_BYTES: usize = 64 * 1024;+/// Maximum Unicode scalar characters accepted in an extracted candidate path.+pub const MAX_CANDIDATE_PATH_CHARS: usize = 4_096;+/// Maximum direct path candidates accepted from one recognized file tool call.+pub const MAX_CAPTURE_CANDIDATES: usize = 32;+/// Maximum aggregate pattern-by-candidate scalar comparisons per inspection.+pub const MAX_MATCH_WORK: usize = 1_000_000;+const MAX_CALL_ID_CHARS: usize = 128;+const CAPTURE_PROTOCOL_VERSION: u8 = 1;++/// Minimal decoded `[capture]` marker configuration.+#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]+#[serde(deny_unknown_fields)]+pub struct CaptureConfig {+ /// Whole-path glob patterns to exclude.+ #[serde(default)]+ pub ignore_paths: Vec<String>,+}++/// Typed result of marker discovery and parsing, supplied by the IO-owning caller.+pub enum CaptureSource<'a> {+ /// No nearest marker exists.+ Absent,+ /// A complete marker parsed into the strict capture configuration.+ Parsed(&'a CaptureConfig),+ /// Discovery, bounded read, TOML parsing, or type validation failed.+ Invalid,+}++/// Local capture action.+#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "kebab-case")]+pub enum CaptureDisposition {+ /// Preserve the original event.+ Keep,+ /// Do not spool, queue, or transmit the event.+ Drop,+ /// Replace the event body with the strict metadata allowlist.+ MetadataOnly,+}++/// Resolution state of marker configuration.+#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "kebab-case")]+pub enum PolicyState {+ /// No marker or an explicitly empty list.+ Inactive,+ /// A complete valid pattern set is active.+ Active,+ /// Marker/configuration failed strict validation.+ Invalid,+}++/// Result of direct, schema-specific tool extraction.+#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "kebab-case")]+pub enum ExtractionState {+ /// Tool does not require path extraction.+ NotApplicable,+ /// Direct fields were extracted successfully.+ Extracted,+ /// A recognized file tool had absent, malformed, blank, or unusable fields.+ MissingOrMalformed,+ /// The agent payload did not use an explicitly supported adapter schema.+ #[default]+ UnsupportedSchema,+}++/// Canonical category used in the reserved protocol.+#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "kebab-case")]+pub enum ToolFamily {+ /// Recognized direct file operation.+ File,+ /// Recognized search/list operation.+ SearchList,+ /// Explicitly known non-file operation.+ NonFile,+ /// Unknown or unsupported tool.+ #[default]+ Unknown,+}++/// Strict, bounded reserved protocol body.+#[derive(Clone, Debug, Serialize, PartialEq, Eq)]+pub struct CaptureProtocol {+ version: u8,+ disposition: CaptureDisposition,+ policy_state: PolicyState,+ tool_family: ToolFamily,+ path_count: u16,+ extraction_state: ExtractionState,+}++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+struct WireProtocol {+ version: u8,+ disposition: CaptureDisposition,+ policy_state: PolicyState,+ tool_family: ToolFamily,+ path_count: u16,+ extraction_state: ExtractionState,+}++impl<'de> Deserialize<'de> for CaptureProtocol {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ let wire = WireProtocol::deserialize(deserializer)?;+ if wire.version != CAPTURE_PROTOCOL_VERSION {+ return Err(serde::de::Error::custom(+ "unsupported capture protocol version",+ ));+ }+ Ok(Self::new(+ wire.disposition,+ wire.policy_state,+ wire.tool_family,+ wire.path_count,+ wire.extraction_state,+ ))+ }+}++impl CaptureProtocol {+ fn new(+ disposition: CaptureDisposition,+ policy_state: PolicyState,+ tool_family: ToolFamily,+ path_count: u16,+ extraction_state: ExtractionState,+ ) -> Self {+ Self {+ version: CAPTURE_PROTOCOL_VERSION,+ disposition,+ policy_state,+ tool_family,+ path_count,+ extraction_state,+ }+ }+ /// Parses only the current protocol version and bounded field set.+ #[must_use]+ pub fn parse(value: &Value) -> Option<Self> {+ serde_json::from_value(value.clone()).ok()+ }+ /// Fixed wire protocol version.+ #[must_use]+ pub const fn version(&self) -> u8 {+ self.version+ }+ /// Chosen local action.+ #[must_use]+ pub const fn disposition(&self) -> CaptureDisposition {+ self.disposition+ }+ /// Resolved marker state.+ #[must_use]+ pub const fn policy_state(&self) -> PolicyState {+ self.policy_state+ }+ /// Canonical tool family.+ #[must_use]+ pub const fn tool_family(&self) -> ToolFamily {+ self.tool_family+ }+ /// Number of direct candidates, capped by the fixed `u16` wire type.+ #[must_use]+ pub const fn path_count(&self) -> u16 {+ self.path_count+ }+ /// Direct extraction result.+ #[must_use]+ pub const fn extraction_state(&self) -> ExtractionState {+ self.extraction_state+ }+}++/// Compiled policy plus its state. Construct with [`CapturePolicy::resolve`].+#[derive(Clone, Debug)]+pub struct CapturePolicy {+ state: PolicyState,+ patterns: Vec<CompiledPattern>,+}++#[derive(Clone, Debug)]+struct CompiledPattern {+ path: String,+ flavor: Flavor,+ directory_base: Option<String>,+}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Flavor {+ Posix,+ Windows,+}++/// Safe inspection result; it never retains raw arguments, paths, or arbitrary tool names.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CaptureDecision {+ protocol: CaptureProtocol,+ identity: CanonicalTool,+ call_id: Option<String>,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "kebab-case")]+enum CanonicalTool {+ File,+ SearchList,+ NonFile,+ Unknown,+}++impl CaptureDecision {+ /// Protocol clients send as `_ai_memory_capture` when the policy is active/invalid.+ #[must_use]+ pub const fn protocol(&self) -> &CaptureProtocol {+ &self.protocol+ }+}++impl CapturePolicy {+ /// Resolves a marker config atomically. Empty parsed configuration is inactive.+ /// `home_dir` is required only when at least one pattern starts with `~/`.+ #[must_use]+ pub fn resolve(source: CaptureSource<'_>, marker_dir: &str, home_dir: Option<&str>) -> Self {+ let config = match source {+ CaptureSource::Absent => return Self::inactive(),+ CaptureSource::Invalid => {+ return Self {+ state: PolicyState::Invalid,+ patterns: Vec::new(),+ };+ }+ CaptureSource::Parsed(config) => config,+ };+ if config.ignore_paths.is_empty() {+ return Self::inactive();+ }+ let compiled = compile(config, marker_dir, home_dir);+ match compiled {+ Ok(patterns) => Self {+ state: PolicyState::Active,+ patterns,+ },+ Err(()) => Self {+ state: PolicyState::Invalid,+ patterns: Vec::new(),+ },+ }+ }+ fn inactive() -> Self {+ Self {+ state: PolicyState::Inactive,+ patterns: Vec::new(),+ }+ }+ /// Evaluates every policy state using only direct fixture-backed schemas.+ #[must_use]+ pub fn inspect(&self, agent: AgentKind, raw: &Value, cwd: &str) -> CaptureDecision {+ let extracted = extract(agent, raw);+ let (disposition, extraction) = match self.state {+ PolicyState::Inactive => (CaptureDisposition::Keep, extracted.state),+ PolicyState::Invalid if extracted.family == ToolFamily::File => {+ (CaptureDisposition::MetadataOnly, extracted.state)+ }+ PolicyState::Invalid => (CaptureDisposition::Keep, extracted.state),+ PolicyState::Active => match extracted.family {+ ToolFamily::SearchList => {+ (CaptureDisposition::Drop, ExtractionState::NotApplicable)+ }+ ToolFamily::File => match extracted.paths.as_ref() {+ None => (+ CaptureDisposition::MetadataOnly,+ ExtractionState::MissingOrMalformed,+ ),+ Some(paths)+ if paths+ .iter()+ .any(|path| normalize_candidate(path, cwd).is_none()) =>+ {+ (+ CaptureDisposition::MetadataOnly,+ ExtractionState::MissingOrMalformed,+ )+ }+ Some(paths) => match self.match_paths(paths, cwd) {+ Ok(true) => (CaptureDisposition::Drop, ExtractionState::Extracted),+ Ok(false) => (CaptureDisposition::Keep, ExtractionState::Extracted),+ Err(()) => (+ CaptureDisposition::MetadataOnly,+ ExtractionState::MissingOrMalformed,+ ),+ },+ },+ _ => (CaptureDisposition::Keep, extracted.state),+ },+ };+ CaptureDecision {+ protocol: CaptureProtocol::new(+ disposition,+ self.state,+ extracted.family,+ extracted+ .paths+ .as_ref()+ .map_or(0, |p| p.len().min(u16::MAX as usize) as u16),+ extraction,+ ),+ identity: canonical(extracted.family),+ call_id: extracted.call_id,+ }+ }+ fn match_paths(&self, paths: &[String], cwd: &str) -> Result<bool, ()> {+ let candidates: Option<Vec<_>> = paths+ .iter()+ .map(|path| normalize_candidate(path, cwd))+ .collect();+ let candidates = candidates.ok_or(())?;+ let mut work = 0_usize;+ for candidate in candidates {+ for pattern in self+ .patterns+ .iter()+ .filter(|pattern| pattern.flavor == candidate.flavor)+ {+ work = work+ .checked_add(+ pattern+ .path+ .chars()+ .count()+ .saturating_mul(candidate.path.chars().count()),+ )+ .ok_or(())?;+ if work > MAX_MATCH_WORK {+ return Err(());+ }+ if glob_match(+ &pattern.path,+ &candidate.path,+ pattern.directory_base.as_deref(),+ pattern.flavor == Flavor::Windows,+ ) {+ return Ok(true);+ }+ }+ }+ Ok(false)+ }+}++/// Constructs a metadata-only replacement from scalar allowlisted envelope values and a decision.+#[must_use]+pub fn metadata_only_body(+ session_id: Option<&str>,+ cwd: Option<&str>,+ decision: &CaptureDecision,+) -> Value {+ let mut body = Map::new();+ if let Some(value) = session_id {+ body.insert("session_id".into(), Value::String(value.into()));+ }+ if let Some(value) = cwd {+ body.insert("cwd".into(), Value::String(value.into()));+ }+ body.insert("tool_family".into(), json!(decision.protocol.tool_family()));+ body.insert("tool_name".into(), json!(decision.identity));+ if let Some(value) = &decision.call_id {+ body.insert("tool_call_id".into(), Value::String(value.clone()));+ }+ body.insert("_ai_memory_capture".into(), json!(decision.protocol));+ Value::Object(body)+}++#[derive(Default)]+struct Extracted {+ family: ToolFamily,+ paths: Option<Vec<String>>,+ call_id: Option<String>,+ state: ExtractionState,+}++fn extract(agent: AgentKind, raw: &Value) -> Extracted {+ let Some(object) = raw.as_object() else {+ return Extracted::default();+ };+ let extracted = match agent {+ AgentKind::AntigravityCli => object+ .get("toolCall")+ .and_then(Value::as_object)+ .and_then(|call| Some((call.get("name")?.as_str()?, call.get("args")))),+ AgentKind::Grok => object+ .get("tool_name")+ .or_else(|| object.get("toolName"))+ .and_then(Value::as_str)+ .map(|name| {+ (+ name,+ object.get("tool_input").or_else(|| object.get("toolInput")),+ )+ }),+ AgentKind::Zero => object+ .get("toolName")+ .and_then(Value::as_str)+ .map(|name| (name, object.get("input"))),+ AgentKind::ClaudeCode+ | AgentKind::Codex+ | AgentKind::Cursor+ | AgentKind::GeminiCli+ | AgentKind::Devin => object+ .get("tool_name")+ .and_then(Value::as_str)+ .map(|name| (name, object.get("tool_input"))),+ AgentKind::OpenCode | AgentKind::Omp | AgentKind::Pi | AgentKind::OpenClaw => object+ .get("tool")+ .and_then(Value::as_str)+ .map(|name| (name, object.get("args"))),+ _ => None,+ };+ let Some((name, args)) = extracted else {+ return Extracted::default();+ };+ let family = family(name);+ let paths = (family == ToolFamily::File)+ .then(|| args.and_then(|value| extract_paths(name, value)))+ .flatten();+ let state = if family == ToolFamily::File && paths.is_none() {+ ExtractionState::MissingOrMalformed+ } else {+ ExtractionState::Extracted+ };+ let call_id = [+ "tool_use_id",+ "toolUseId",+ "tool_call_id",+ "toolCallId",+ "call_id",+ "callId",+ "callID",+ ]+ .iter()+ .find_map(|key| {+ object+ .get(*key)+ .and_then(Value::as_str)+ .filter(|id| valid_call_id(id))+ .map(str::to_owned)+ });+ Extracted {+ family,+ paths,+ call_id,+ state,+ }+}++fn family(name: &str) -> ToolFamily {+ match name.to_ascii_lowercase().as_str() {+ "read" | "write" | "edit" | "apply_patch" | "notebookedit" | "notebook_edit"+ | "create_file" | "delete_file" | "rename_file" | "move_file" | "multi_edit"+ | "multiedit" | "replace" | "replace_all" => ToolFamily::File,+ "search" | "grep" | "glob" | "find" | "list" | "ls" | "list_files" | "read_dir" => {+ ToolFamily::SearchList+ }+ "bash" | "shell" | "execute" | "run_command" | "web_search" => ToolFamily::NonFile,+ _ => ToolFamily::Unknown,+ }+}+fn canonical(family: ToolFamily) -> CanonicalTool {+ match family {+ ToolFamily::File => CanonicalTool::File,+ ToolFamily::SearchList => CanonicalTool::SearchList,+ ToolFamily::NonFile => CanonicalTool::NonFile,+ ToolFamily::Unknown => CanonicalTool::Unknown,+ }+}+fn valid_call_id(id: &str) -> bool {+ !id.is_empty()+ && id.chars().count() <= MAX_CALL_ID_CHARS+ && id+ .bytes()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.'))+}++fn extract_paths(name: &str, args: &Value) -> Option<Vec<String>> {+ let object = args.as_object()?;+ let mut paths = direct_paths(object).unwrap_or_default();+ if matches!(+ name.to_ascii_lowercase().as_str(),+ "multi_edit" | "multiedit" | "replace_all"+ ) {+ let entries = object+ .get("edits")+ .or_else(|| object.get("replacements"))?+ .as_array()?;+ if entries.is_empty() {+ return None;+ }+ if entries.len() > MAX_CAPTURE_CANDIDATES {+ return None;+ }+ for entry in entries {+ let paths_in_entry = direct_paths(entry.as_object()?)?;+ if paths.len().checked_add(paths_in_entry.len())? > MAX_CAPTURE_CANDIDATES {+ return None;+ }+ paths.extend(paths_in_entry);+ }+ }+ (!paths.is_empty()+ && paths.iter().all(|path| {+ !path.trim().is_empty() && path.chars().count() <= MAX_CANDIDATE_PATH_CHARS+ }))+ .then_some(paths)+}+fn direct_paths(object: &Map<String, Value>) -> Option<Vec<String>> {+ let mut paths = Vec::new();+ for key in [+ "file_path",+ "filePath",+ "path",+ "absolute_path",+ "AbsolutePath",+ "notebook_path",+ ] {+ if let Some(value) = object.get(key) {+ if paths.len() == MAX_CAPTURE_CANDIDATES {+ return None;+ }+ paths.push(value.as_str()?.to_owned());+ }+ }+ if let Some(values) = object.get("paths") {+ if values.as_array()?.len() > MAX_CAPTURE_CANDIDATES+ || paths.len().checked_add(values.as_array()?.len())? > MAX_CAPTURE_CANDIDATES+ {+ return None;+ }+ for value in values.as_array()? {+ paths.push(value.as_str()?.to_owned());+ }+ }+ (!paths.is_empty()).then_some(paths)+}++#[derive(Clone)]+struct Normalized {+ path: String,+ flavor: Flavor,+}+fn normalize_candidate(candidate: &str, cwd: &str) -> Option<Normalized> {+ if candidate.trim().is_empty()+ || candidate.chars().count() > MAX_CANDIDATE_PATH_CHARS+ || is_drive_relative(candidate)+ {+ return None;+ }+ let cwd = normalize_root(cwd).ok()?;+ let raw = if is_absolute(candidate) {+ candidate.to_owned()+ } else {+ join(&cwd, candidate)+ };+ let flavor = flavor_of(&raw);+ Some(Normalized {+ path: normalize_segments(&raw)?,+ flavor,+ })+}+fn compile(+ config: &CaptureConfig,+ marker_dir: &str,+ home_dir: Option<&str>,+) -> Result<Vec<CompiledPattern>, ()> {+ if config.ignore_paths.len() > MAX_IGNORE_PATTERNS {+ return Err(());+ }+ let marker = normalize_root(marker_dir).map_err(|_| ())?;+ let needs_home = config+ .ignore_paths+ .iter()+ .any(|pattern| pattern.starts_with("~/"));+ let home = if needs_home {+ Some(+ home_dir+ .and_then(|dir| normalize_root(dir).ok())+ .ok_or(())?,+ )+ } else {+ None+ };+ config+ .ignore_paths+ .iter()+ .map(|source| {+ validate_glob(source)?;+ let expanded = if let Some(rest) = source.strip_prefix("~/") {+ join(home.as_deref().ok_or(())?, rest)+ } else if is_absolute(source) {+ source.clone()+ } else {+ join(&marker, source)+ };+ let flavor = flavor_of(&expanded);+ let path = normalize_segments(&expanded).ok_or(())?;+ Ok(CompiledPattern {+ directory_base: path.strip_suffix("/**").map(|base| {+ if base.is_empty() {+ "/".into()+ } else {+ base.into()+ }+ }),+ path,+ flavor,+ })+ })+ .collect()+}+fn validate_glob(pattern: &str) -> Result<(), ()> {+ if pattern.trim().is_empty()+ || pattern.chars().count() > MAX_IGNORE_PATTERN_CHARS+ || pattern.contains(['!', '{', '}', '[', ']', '(', ')', '|', '^', '$', '%'])+ || pattern.contains("${")+ || pattern.contains("***")+ || pattern+ .replace('\\', "/")+ .split('/')+ .any(|segment| segment == "..")+ || (pattern.starts_with('~') && !pattern.starts_with("~/"))+ || is_drive_relative(pattern)+ {+ return Err(());+ }+ Ok(())+}+fn join(base: &str, child: &str) -> String {+ format!("{}/{}", base.trim_end_matches(['/', '\\']), child)+}+fn flavor_of(path: &str) -> Flavor {+ if path.starts_with("\\\\") || path.starts_with("//") || valid_drive_prefix(path) {+ Flavor::Windows+ } else {+ Flavor::Posix+ }+}+fn valid_drive_prefix(path: &str) -> bool {+ path.len() >= 2 && path.as_bytes()[0].is_ascii_alphabetic() && path.as_bytes()[1] == b':'+}+fn is_absolute(path: &str) -> bool {+ path.starts_with('/')+ || path.starts_with("\\\\")+ || (valid_drive_prefix(path)+ && path.len() >= 3+ && matches!(path.as_bytes()[2], b'/' | b'\\'))+}+fn is_drive_relative(path: &str) -> bool {+ path.len() >= 2+ && path.as_bytes()[1] == b':'+ && (!path.as_bytes()[0].is_ascii_alphabetic() || !is_absolute(path))+}+fn normalize_root(path: &str) -> Result<String, ()> {+ (is_absolute(path) && !is_drive_relative(path))+ .then(|| normalize_segments(path))+ .flatten()+ .ok_or(())+}+fn normalize_segments(path: &str) -> Option<String> {+ let path = path.replace('\\', "/");+ let (root, tail): (String, Vec<&str>) = if let Some(rest) = path.strip_prefix("//") {+ let mut parts = rest.split('/').filter(|p| !p.is_empty());+ let server = parts.next()?;+ let share = parts.next()?;+ (format!("//{server}/{share}"), parts.collect())+ } else if valid_drive_prefix(&path) && path.as_bytes().get(2) == Some(&b'/') {+ (+ format!("{}:/", path[..1].to_ascii_uppercase()),+ path[3..].split('/').collect(),+ )+ } else if let Some(rest) = path.strip_prefix('/') {+ ("/".into(), rest.split('/').collect())+ } else {+ return None;+ };+ let mut parts = Vec::new();+ for part in tail {+ if part.is_empty() || part == "." {+ continue;+ }+ if part == ".." {+ parts.pop();+ } else {+ parts.push(part);+ }+ }+ let mut output = root;+ if !parts.is_empty() {+ if !output.ends_with('/') {+ output.push('/');+ }+ output.push_str(&parts.join("/"));+ }+ Some(output)+}+fn glob_match(+ pattern: &str,+ candidate: &str,+ directory_base: Option<&str>,+ insensitive: bool,+) -> bool {+ let pattern: Vec<char> = pattern.chars().collect();+ let candidate: Vec<char> = candidate.chars().collect();+ if directory_base+ .is_some_and(|base| equal_chars(&base.chars().collect::<Vec<_>>(), &candidate, insensitive))+ {+ return true;+ }+ let mut previous = vec![false; pattern.len() + 1];+ previous[0] = true;+ for index in 1..=pattern.len() {+ previous[index] = match pattern[index - 1] {+ '*' if pattern.get(index) == Some(&'*') => false,+ '*' => previous[index - 1],+ _ => false,+ };+ }+ for character in candidate {+ let mut current = vec![false; pattern.len() + 1];+ for index in 1..=pattern.len() {+ current[index] = match pattern[index - 1] {+ '*' if pattern.get(index) == Some(&'*') => false,+ '*' if index >= 2 && pattern[index - 2] == '*' => {+ current[index - 2] || previous[index]+ }+ '*' => current[index - 1] || (character != '/' && previous[index]),+ '?' => character != '/' && previous[index - 1],+ expected => char_equal(expected, character, insensitive) && previous[index - 1],+ };+ }+ previous = current;+ }+ previous[pattern.len()]+}+fn equal_chars(left: &[char], right: &[char], insensitive: bool) -> bool {+ left.len() == right.len()+ && left+ .iter()+ .zip(right)+ .all(|(&a, &b)| char_equal(a, b, insensitive))+}+fn char_equal(left: char, right: char, insensitive: bool) -> bool {+ if insensitive && left.is_ascii() && right.is_ascii() {+ left.eq_ignore_ascii_case(&right)+ } else {+ left == right+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn fixture_vectors() {+ let fixture: Value =+ serde_json::from_str(include_str!("../tests/fixtures/capture-policy.json")).unwrap();+ let policy = CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec!["secret/**".into()],+ }),+ "/repo",+ None,+ );+ for vector in fixture["decisions"].as_array().unwrap() {+ let agent = AgentKind::from_wire(vector["agent"].as_str().unwrap());+ let decision = policy.inspect(agent, &vector["payload"], "/repo");+ let protocol = decision.protocol();+ assert_eq!(+ serde_json::to_value(protocol.disposition()).unwrap(),+ vector["disposition"]+ );+ assert_eq!(+ serde_json::to_value(protocol.tool_family()).unwrap(),+ vector["tool_family"]+ );+ assert_eq!(+ serde_json::to_value(protocol.extraction_state()).unwrap(),+ vector["extraction_state"]+ );+ assert_eq!(+ protocol.path_count(),+ vector["path_count"].as_u64().unwrap() as u16+ );+ }+ for vector in fixture["normalization"].as_array().unwrap() {+ let policy = CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec![vector["pattern"].as_str().unwrap().into()],+ }),+ "/repo",+ None,+ );+ assert_eq!(+ policy+ .match_paths(+ &[vector["candidate"].as_str().unwrap().into()],+ vector["cwd"].as_str().unwrap()+ )+ .unwrap(),+ vector["match"].as_bool().unwrap()+ );+ }+ assert!(CaptureProtocol::parse(&fixture["protocol"]["accept"]).is_some());+ assert!(CaptureProtocol::parse(&fixture["protocol"]["reject"]).is_none());+ }+ #[test]+ fn all_states_and_strict_protocol_are_reachable() {+ let file = json!({"tool_name":"Edit","tool_input":{}});+ assert_eq!(+ CapturePolicy::resolve(CaptureSource::Absent, "/repo", None)+ .inspect(AgentKind::Codex, &file, "/repo")+ .protocol()+ .policy_state(),+ PolicyState::Inactive+ );+ let invalid = CapturePolicy::resolve(CaptureSource::Invalid, "/repo", None).inspect(+ AgentKind::Codex,+ &file,+ "/repo",+ );+ assert_eq!(invalid.protocol().policy_state(), PolicyState::Invalid);+ assert_eq!(+ invalid.protocol().disposition(),+ CaptureDisposition::MetadataOnly+ );+ assert_eq!(+ CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec!["a/../b".into()]+ }),+ "/repo",+ None+ )+ .inspect(AgentKind::Codex, &file, "/repo")+ .protocol()+ .policy_state(),+ PolicyState::Invalid+ );+ assert_eq!(+ CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec!["x".into()]+ }),+ "/repo",+ None+ )+ .inspect(AgentKind::Other, &json!({}), "/repo")+ .protocol()+ .extraction_state(),+ ExtractionState::UnsupportedSchema+ );+ assert!(+ serde_json::from_value::<CaptureConfig>(json!({"ignore_paths": [], "mode": "keep"}))+ .is_err()+ );+ let value = serde_json::to_value(invalid.protocol()).unwrap();+ assert!(CaptureProtocol::parse(&value).is_some());+ let mut bad = value;+ bad.as_object_mut()+ .unwrap()+ .insert("paths".into(), json!(["x"]));+ assert!(CaptureProtocol::parse(&bad).is_none());+ }+ #[test]+ fn normalization_and_matcher_bounds() {+ let policy = CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec![+ r"C:\\Secret\\**".into(),+ r"\\server\\share\\x".into(),+ "unicode/?.txt".into(),+ ],+ }),+ "/repo",+ None,+ );+ assert!(policy.match_paths(&[r"c:/SECRET".into()], "C:/").unwrap());+ assert!(+ policy+ .match_paths(&[r"\\server\\share\\x".into()], "C:/")+ .unwrap()+ );+ assert!(+ policy+ .match_paths(&["unicode/é.txt".into()], "/repo")+ .unwrap()+ );+ assert!(policy.match_paths(&["C:bad".into()], "C:/").is_err());+ let raw = json!({"tool_name":"Edit","tool_input":{"path":"x".repeat(MAX_CANDIDATE_PATH_CHARS + 1)}});+ assert_eq!(+ policy+ .inspect(AgentKind::Codex, &raw, "/repo")+ .protocol()+ .disposition(),+ CaptureDisposition::MetadataOnly+ );+ let overflow = json!({"tool_name":"Edit","tool_input":{"paths":vec!["public"; MAX_CAPTURE_CANDIDATES + 1]}});+ assert_eq!(+ policy+ .inspect(AgentKind::Codex, &overflow, "/repo")+ .protocol()+ .disposition(),+ CaptureDisposition::MetadataOnly+ );+ let costly = CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec!["?".repeat(MAX_IGNORE_PATTERN_CHARS)],+ }),+ "/repo",+ None,+ );+ let costly_raw =+ json!({"tool_name":"Edit","tool_input":{"path":"x".repeat(MAX_CANDIDATE_PATH_CHARS)}});+ assert_eq!(+ costly+ .inspect(AgentKind::Codex, &costly_raw, "/repo")+ .protocol()+ .disposition(),+ CaptureDisposition::MetadataOnly+ );+ let chars = "?".repeat(MAX_IGNORE_PATTERN_CHARS);+ assert_eq!(CapturePolicy::resolve(CaptureSource::Parsed(&CaptureConfig { ignore_paths: vec![chars] }), "/repo", None).inspect(AgentKind::Codex, &json!({"tool_name":"Edit","tool_input":{"path":"x".repeat(MAX_IGNORE_PATTERN_CHARS)}}), "/repo").protocol().policy_state(), PolicyState::Active);+ assert_eq!(+ CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec!["?".repeat(MAX_IGNORE_PATTERN_CHARS + 1)]+ }),+ "/repo",+ None+ )+ .inspect(+ AgentKind::Codex,+ &json!({"tool_name":"Edit","tool_input":{"path":"x"}}),+ "/repo"+ )+ .protocol()+ .policy_state(),+ PolicyState::Invalid+ );+ }+ #[test]+ fn metadata_rewrite_strips_all_sentinels_and_has_exact_protocol_keys() {+ let policy = CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec!["secret/**".into()],+ }),+ "/repo",+ None,+ );+ let raw = json!({"tool_name":"Edit","tool_call_id":"safe-ID.1","tool_input":{"path":"secret/SENTINEL_PATH","args":"SENTINEL_ARGS"},"output":"SENTINEL_OUTPUT","error":"SENTINEL_ERROR","title":"SENTINEL_TITLE","result":"SENTINEL_RESULT","nested":{"raw":"SENTINEL_NESTED"}});+ let body = metadata_only_body(+ Some("s"),+ Some("/repo"),+ &policy.inspect(AgentKind::Codex, &raw, "/repo"),+ );+ let text = body.to_string();+ for sentinel in [+ "SENTINEL_PATH",+ "SENTINEL_ARGS",+ "SENTINEL_OUTPUT",+ "SENTINEL_ERROR",+ "SENTINEL_TITLE",+ "SENTINEL_RESULT",+ "SENTINEL_NESTED",+ ] {+ assert!(!text.contains(sentinel));+ }+ let keys: Vec<_> = body["_ai_memory_capture"]+ .as_object()+ .unwrap()+ .keys()+ .cloned()+ .collect();+ assert_eq!(+ keys,+ [+ "version",+ "disposition",+ "policy_state",+ "tool_family",+ "path_count",+ "extraction_state"+ ]+ );+ }+}diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex c5514309..69021b26 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -21,6 +21,7 @@//! This crate does not read process environment directly; server configuration//! is resolved once by `ai-memory-cli` and threaded in as typed state.+pub mod capture_policy;pub mod log;pub mod payload;pub mod router;@@ -29,6 +30,10 @@ pub mod synth;// Re-export the sanitizer types from core so callers that grew up// pointing at this crate's `sanitize` module keep working.pub use ai_memory_core::{SanitizeConfig, Sanitized, Sanitizer};+pub use capture_policy::{+ CaptureConfig, CaptureDecision, CaptureDisposition, CapturePolicy, CaptureProtocol,+ CaptureSource, ExtractionState, PolicyState, ToolFamily,+};pub use payload::{HookEnvelope, HookEvent};pub use router::{DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, DEFAULT_PROJECT_CACHE_MAX_ENTRIES, HookState,diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 95649cb4..0533caf0 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -31,6 +31,10 @@ use serde::{Deserialize, Serialize};use tracing::{debug, info, warn};use uuid::Uuid;+use crate::capture_policy::{+ CaptureConfig, CaptureDisposition, CapturePolicy, CaptureProtocol, CaptureSource, PolicyState,+ ToolFamily, metadata_only_body,+};use crate::log;use crate::payload::{HookEnvelope, HookEvent, HookQuery, ProjectStrategy, body_is_subagent, parse_agent,@@ -436,6 +440,9 @@ async fn handle_hook(Json(body): Json<serde_json::Value>,) -> impl IntoResponse {let env = HookEnvelope::from_query_and_body(query, body);+ let Some(env) = inspect_capture_envelope(env) else {+ return (StatusCode::ACCEPTED, "capture policy dropped");+ };// Accept-but-drop subagent captures (incl. the unmarked tail of tracked// subagent sessions) when the operator opts in. Returning 202 (not an error)// means the client treats the event as delivered and never retries/spools@@ -592,6 +599,13 @@ async fn handle_hook_batch(for (idx, item) in items.into_iter().enumerate() {let query = parse_hook_query(&item.url);let env = HookEnvelope::from_query_and_body(query, item.body);+ let Some(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.+ accepted_indices.push(idx);+ continue;+ };let actor_key = ActorKey {user: actor_user.clone(),session_id: env.session_id.clone(),@@ -640,6 +654,214 @@ async fn handle_hook_batch()}+/// Apply the client capture protocol before any admission or store work.+/// `None` is an acknowledged Drop; `Some` is either the legacy envelope or a+/// strict metadata-only replacement. This deliberately never logs protocol or+/// raw tool data: those fields can contain paths and captured content.+fn inspect_capture_envelope(env: HookEnvelope) -> Option<HookEnvelope> {+ let Some(raw_protocol) = env.raw.get("_ai_memory_capture") else {+ return Some(env);+ };+ let cwd = env.cwd.as_deref().unwrap_or("/");+ let direct = |state| capture_inspector(state, cwd).inspect(env.agent, &env.raw, cwd);++ let Some(protocol) = CaptureProtocol::parse(raw_protocol) else {+ // A new/malformed marker must not make a recognized file operation+ // less private. Mark the replacement invalid: an inactive/keep+ // protocol would falsely describe the server's privacy fallback.+ // Non-file legacy payloads retain their old behavior.+ let decision = direct(PolicyState::Invalid);+ if decision.protocol().tool_family() == ToolFamily::File {+ return Some(metadata_envelope(env, &decision, None));+ }+ return Some(env);+ };++ // Parsed Drops are terminal client-side policy decisions. They must stay+ // admission-free even when their other protocol fields are nonsensical.+ if protocol.disposition() == CaptureDisposition::Drop {+ return None;+ }++ if protocol.disposition() == CaptureDisposition::MetadataOnly {+ return metadata_only_protocol_envelope(env, &protocol);+ }++ let decision = direct(protocol.policy_state());+ let inspected = decision.protocol();+ if !protocol_matches_inspection(&protocol, inspected) {+ // A client protocol that contradicts direct inspection cannot be used+ // to retain a recognized file tool's raw arguments or response. The+ // invalid decision also gives the replacement a canonical, truthful+ // invalid/metadata-only protocol rather than echoing the bad claim.+ if protocol.tool_family() == ToolFamily::File || inspected.tool_family() == ToolFamily::File+ {+ let fallback = direct(PolicyState::Invalid);+ return Some(metadata_envelope(env, &fallback, None));+ }+ return match inspected.disposition() {+ CaptureDisposition::Drop => None,+ CaptureDisposition::MetadataOnly => Some(metadata_envelope(env, &decision, None)),+ CaptureDisposition::Keep => Some(env),+ };+ }++ Some(env)+}++/// Validate and rebuild a client-stripped metadata body without attempting to+/// recover its intentionally omitted tool arguments. Invalid stripped shapes+/// are dropped rather than risking retention of an unallowlisted field.+fn metadata_only_protocol_envelope(+ mut env: HookEnvelope,+ protocol: &CaptureProtocol,+) -> Option<HookEnvelope> {+ if !metadata_protocol_is_legal(protocol) {+ return None;+ }+ let object = env.raw.as_object()?;+ // Unknown fields are deliberately ignored below: the reconstructed body+ // contains only this allowlist, so a stale or malicious extra cannot leak.+ let valid_scalar = |key: &str, max: usize| {+ object.get(key).is_none_or(|value| {+ value+ .as_str()+ .is_some_and(|value| !value.is_empty() && value.len() <= max)+ })+ };+ if !valid_scalar("session_id", 512)+ || !valid_scalar("cwd", 4_096)+ || !object+ .get("tool_call_id")+ .is_none_or(valid_metadata_call_id)+ || object.get("tool_family") != Some(&serde_json::json!(protocol.tool_family()))+ || object.get("tool_name")+ != Some(&serde_json::json!(canonical_tool_name(+ protocol.tool_family()+ )))+ {+ return None;+ }++ let mut raw = serde_json::Map::new();+ for key in ["session_id", "cwd", "tool_call_id"] {+ if let Some(value) = object.get(key) {+ raw.insert(key.into(), value.clone());+ }+ }+ raw.insert(+ "tool_family".into(),+ serde_json::json!(protocol.tool_family()),+ );+ raw.insert(+ "tool_name".into(),+ serde_json::json!(canonical_tool_name(protocol.tool_family())),+ );+ raw.insert("_ai_memory_capture".into(), serde_json::json!(protocol));+ env.title_hint = Some(canonical_tool_name(protocol.tool_family()).into());+ env.body_excerpt = None;+ env.raw = serde_json::Value::Object(raw);+ Some(env)+}++const fn metadata_protocol_is_legal(protocol: &CaptureProtocol) -> bool {+ matches!(+ (protocol.policy_state(), protocol.tool_family()),+ (PolicyState::Active | PolicyState::Invalid, ToolFamily::File)+ )+}++fn valid_metadata_call_id(value: &serde_json::Value) -> bool {+ value.as_str().is_some_and(|id| {+ !id.is_empty()+ && id.len() <= 256+ && id+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))+ })+}++/// Whether a claimed protocol can be produced by the claimed policy state for+/// the directly inspected tool. Active, successfully-extracted file calls may+/// be either kept or dropped because the server intentionally does not receive+/// the client's private ignore patterns; every other disposition is fixed by+/// the shared decision table.+fn protocol_matches_inspection(protocol: &CaptureProtocol, inspected: &CaptureProtocol) -> bool {+ if protocol.policy_state() != inspected.policy_state()+ || protocol.tool_family() != inspected.tool_family()+ || protocol.extraction_state() != inspected.extraction_state()+ || protocol.path_count() != inspected.path_count()+ {+ return false;+ }++ match (+ protocol.policy_state(),+ protocol.tool_family(),+ inspected.disposition(),+ ) {+ (PolicyState::Active, ToolFamily::File, CaptureDisposition::Keep) => matches!(+ protocol.disposition(),+ CaptureDisposition::Keep | CaptureDisposition::Drop+ ),+ _ => protocol.disposition() == inspected.disposition(),+ }+}++/// Build a policy solely to use the shared, fixture-backed direct schema+/// inspection API. The active sentinel cannot match a normalized real path;+/// active extracted file calls can therefore be either Keep or Drop during+/// protocol validation.+fn capture_inspector(state: PolicyState, cwd: &str) -> CapturePolicy {+ const ACTIVE_SENTINEL: &str = "/__ai_memory_capture_server_inspection_never_match__";+ match state {+ PolicyState::Active => CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec![ACTIVE_SENTINEL.into()],+ }),+ cwd,+ None,+ ),+ PolicyState::Invalid => CapturePolicy::resolve(CaptureSource::Invalid, cwd, None),+ PolicyState::Inactive => CapturePolicy::resolve(CaptureSource::Absent, cwd, None),+ }+}++fn metadata_envelope(+ mut env: HookEnvelope,+ decision: &crate::capture_policy::CaptureDecision,+ protocol: Option<&CaptureProtocol>,+) -> HookEnvelope {+ let protocol = protocol.unwrap_or(decision.protocol());+ let mut raw = metadata_only_body(env.session_id.as_deref(), env.cwd.as_deref(), decision);+ if let Some(object) = raw.as_object_mut() {+ object.insert(+ "tool_family".into(),+ serde_json::json!(protocol.tool_family()),+ );+ object.insert(+ "tool_name".into(),+ serde_json::json!(canonical_tool_name(protocol.tool_family())),+ );+ object.insert("_ai_memory_capture".into(), serde_json::json!(protocol));+ }+ // These were extracted from the pre-replacement raw body. Clearing them is+ // essential: normal extraction must never retain a removed payload.+ env.title_hint = Some(canonical_tool_name(protocol.tool_family()).into());+ env.body_excerpt = None;+ env.raw = raw;+ env+}++const fn canonical_tool_name(family: ToolFamily) -> &'static str {+ match family {+ ToolFamily::File => "file",+ ToolFamily::SearchList => "search-list",+ ToolFamily::NonFile => "non-file",+ ToolFamily::Unknown => "unknown",+ }+}+/// Decide whether to accept-but-drop this event under `drop_subagent_captures`,/// maintaining the subagent-session set. Returns `true` to drop. Seeds the/// session on `SubagentStart` and on any marker-bearing event; keeps it through@@ -1834,9 +2056,11 @@ const fn importance_for(event: HookEvent) -> u8 {#[cfg(test)]mod tests {- use std::sync::Arc;+ use std::sync::{Arc, Mutex};+ use ai_memory_consolidate::{AutoImproveReviewConfig, run_auto_improve_review};use ai_memory_core::Sanitizer;+ use ai_memory_llm::{ChatRequest, ChatResponse, LlmProvider, LlmResult};use ai_memory_store::Store;use ai_memory_wiki::Wiki;use tempfile::TempDir;@@ -1844,6 +2068,36 @@ mod tests {use super::*;use crate::payload::HookQuery;+ struct RecordingLlm(Mutex<Option<ChatRequest>>);++ #[async_trait::async_trait]+ impl LlmProvider for RecordingLlm {+ fn name(&self) -> &'static str {+ "recording"+ }+ fn model(&self) -> &str {+ "recording-test"+ }+ async fn complete(&self, request: ChatRequest) -> LlmResult<ChatResponse> {+ *self.0.lock().unwrap() = Some(request);+ Ok(ChatResponse {+ text: "unused".into(),+ usage: None,+ model: self.model().into(),+ })+ }+ async fn complete_structured_raw(+ &self,+ request: ChatRequest,+ _schema: serde_json::Value,+ ) -> LlmResult<serde_json::Value> {+ *self.0.lock().unwrap() = Some(request);+ Ok(+ serde_json::json!({ "summary": "safe review", "proposals": [], "rejected_candidates": [] }),+ )+ }+ }+/// Build a minimal `HookState` backed by a real on-disk store.async fn make_state(tmp: &TempDir) -> HookState {let store = Store::open(tmp.path()).unwrap();@@ -5620,4 +5874,528 @@ mod tests {"PostCompaction checkpoint must not create a handoff");}++ fn capture_protocol(+ disposition: &str,+ policy_state: &str,+ family: &str,+ path_count: u16,+ extraction: &str,+ ) -> serde_json::Value {+ serde_json::json!({+ "version": 1,+ "disposition": disposition,+ "policy_state": policy_state,+ "tool_family": family,+ "path_count": path_count,+ "extraction_state": extraction,+ })+ }++ #[test]+ fn capture_protocol_legacy_payload_is_unchanged() {+ let raw = serde_json::json!({ "session_id": "legacy", "prompt": "keep me" });+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "user-prompt-submit".into(),+ ..Default::default()+ },+ raw.clone(),+ );+ assert_eq!(inspect_capture_envelope(env).unwrap().raw, raw);+ }++ #[test]+ fn capture_protocol_keep_file_mismatch_becomes_metadata_only() {+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": "mismatch",+ "tool_name": "Write",+ "tool_input": { "file_path": "/repo/real.txt" },+ "tool_response": "SENTINEL_SECRET",+ "_ai_memory_capture": capture_protocol("keep", "active", "file", 2, "extracted"),+ }),+ );+ let env = inspect_capture_envelope(env).unwrap();+ assert_eq!(env.title_hint.as_deref(), Some("file"));+ assert!(env.body_excerpt.is_none());+ assert!(!env.raw.to_string().contains("SENTINEL_SECRET"));+ assert_eq!(env.raw["tool_name"], "file");+ }++ #[test]+ fn capture_protocol_valid_keep_is_unchanged() {+ let raw = serde_json::json!({+ "session_id": "valid-keep", "tool_name": "Write",+ "tool_input": { "file_path": "/repo/real.txt" },+ "_ai_memory_capture": capture_protocol("keep", "active", "file", 1, "extracted"),+ });+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ raw.clone(),+ );+ assert_eq!(inspect_capture_envelope(env).unwrap().raw, raw);+ }++ #[test]+ fn capture_protocol_invalid_file_keep_becomes_canonical_metadata_only() {+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": "invalid-keep",+ "tool_name": "Write",+ "tool_input": { "file_path": "/repo/real.txt" },+ "tool_response": "SENTINEL_SECRET",+ "_ai_memory_capture": capture_protocol("keep", "invalid", "file", 1, "extracted"),+ }),+ );+ let env = inspect_capture_envelope(env).unwrap();+ assert_eq!(env.raw["_ai_memory_capture"]["policy_state"], "invalid");+ assert_eq!(+ env.raw["_ai_memory_capture"]["disposition"],+ "metadata-only"+ );+ assert_eq!(env.raw["_ai_memory_capture"]["tool_family"], "file");+ assert!(!env.raw.to_string().contains("SENTINEL_SECRET"));+ }++ #[test]+ fn capture_protocol_impossible_active_search_keep_is_dropped() {+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": "active-search-keep",+ "tool_name": "Glob",+ "tool_input": { "pattern": "**/*" },+ "_ai_memory_capture": capture_protocol("keep", "active", "search-list", 0, "not-applicable"),+ }),+ );+ assert!(inspect_capture_envelope(env).is_none());+ }++ #[test]+ fn capture_protocol_metadata_with_original_args_is_dropped() {+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": "active-file-metadata",+ "tool_name": "Write",+ "tool_input": { "file_path": "/repo/real.txt" },+ "tool_response": "SENTINEL_SECRET",+ "_ai_memory_capture": capture_protocol("metadata-only", "active", "file", 1, "extracted"),+ }),+ );+ assert!(inspect_capture_envelope(env).is_none());+ }++ #[test]+ fn capture_protocol_native_metadata_shape_is_rebuilt_without_body() {+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": "native-metadata", "cwd": "/repo",+ "tool_family": "file", "tool_name": "file", "tool_call_id": "safe-ID.1",+ "_ai_memory_capture": capture_protocol("metadata-only", "invalid", "file", 1, "extracted"),+ }),+ );+ let env = inspect_capture_envelope(env).unwrap();+ assert_eq!(env.raw["session_id"], "native-metadata");+ assert_eq!(env.raw["cwd"], "/repo");+ assert_eq!(env.raw["tool_call_id"], "safe-ID.1");+ assert!(env.body_excerpt.is_none());+ }++ #[test]+ fn capture_protocol_generated_metadata_shape_is_rebuilt() {+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": "generated-metadata", "cwd": "/generated",+ "tool_family": "file", "tool_name": "file",+ "_ai_memory_capture": capture_protocol("metadata-only", "active", "file", 0, "missing-or-malformed"),+ }),+ );+ let env = inspect_capture_envelope(env).unwrap();+ assert_eq!(env.raw["session_id"], "generated-metadata");+ assert_eq!(env.raw["cwd"], "/generated");+ assert!(env.body_excerpt.is_none());+ }++ #[test]+ fn capture_protocol_metadata_extra_is_stripped() {+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": "metadata-extra", "tool_family": "file", "tool_name": "file",+ "extra": "SENTINEL_SECRET",+ "_ai_memory_capture": capture_protocol("metadata-only", "invalid", "file", 0, "missing-or-malformed"),+ }),+ );+ let env = inspect_capture_envelope(env).unwrap();+ assert!(!env.raw.to_string().contains("SENTINEL_SECRET"));+ assert!(env.raw.get("extra").is_none());+ }++ #[tokio::test]+ async fn privacy_protocol_evidence_never_persists_protected_tool_sentinel() {+ const SENTINEL: &str = "PHASE3_PROTECTED_PATH_AND_CONTENT_7f6c";+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let session_id = "privacy-evidence";++ for (event, body) in [+ (+ "session-start",+ serde_json::json!({ "session_id": session_id, "cwd": "/repo" }),+ ),+ (+ "user-prompt-submit",+ serde_json::json!({ "session_id": session_id, "cwd": "/repo", "prompt": "safe observation" }),+ ),+ ] {+ process(+ &state,+ HookEnvelope::from_query_and_body(+ HookQuery {+ event: event.into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ body,+ ),+ None,+ )+ .await+ .unwrap();+ }++ // A parsed Drop with malicious original input is acknowledged before+ // admission; it never reaches process/store capacity.+ let dropped = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": session_id, "tool_name": "Write",+ "tool_input": { "file_path": SENTINEL }, "tool_response": SENTINEL,+ "_ai_memory_capture": capture_protocol("drop", "inactive", "unknown", 99, "extracted"),+ }),+ );+ assert!(inspect_capture_envelope(dropped).is_none());++ let metadata = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": session_id, "cwd": "/repo", "tool_family": "file", "tool_name": "file",+ "_ai_memory_capture": capture_protocol("metadata-only", "invalid", "file", 1, "extracted"),+ }),+ );+ let metadata = inspect_capture_envelope(metadata).expect("valid metadata is retained");+ assert!(+ metadata.body_excerpt.is_none(),+ "old envelope extraction sees no body"+ );+ process(&state, metadata, None).await.unwrap();++ process(+ &state,+ HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-end".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({ "session_id": session_id, "cwd": "/repo" }),+ ),+ None,+ )+ .await+ .unwrap();++ let sid = resolve_session_id(&HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-start".into(),+ ..Default::default()+ },+ serde_json::json!({ "session_id": session_id }),+ ))+ .unwrap();+ let (workspace_id, project_id) = state+ .reader+ .session_project_ids(sid)+ .await+ .unwrap()+ .unwrap();+ let observations = state.reader.observations_for_session(sid).await.unwrap();+ assert!(observations.iter().all(|observation| {+ observation.body.is_empty() || !observation.body.contains(SENTINEL)+ }));+ assert!(+ observations+ .iter()+ .any(|observation| observation.title == "file" && observation.body.is_empty())+ );+ assert!(+ state+ .reader+ .search_observations_for_project(workspace_id, project_id, SENTINEL.into(), 10)+ .await+ .unwrap()+ .is_empty()+ );+ let page = state+ .reader+ .page_body_by_ids(workspace_id, project_id, &format!("sessions/{sid}.md"))+ .await+ .unwrap()+ .unwrap();+ assert!(!page.body.contains(SENTINEL));+ let handoff = state+ .reader+ .latest_open_handoff(workspace_id, project_id, None)+ .await+ .unwrap()+ .unwrap();+ assert!(!handoff.summary.contains(SENTINEL));+ assert!(+ !state+ .wiki+ .recent_checkpoints(20)+ .unwrap()+ .iter()+ .any(|entry| entry.summary.contains(SENTINEL))+ );++ let llm: &'static RecordingLlm = Box::leak(Box::new(RecordingLlm(Mutex::new(None))));+ let llm_provider: &'static dyn LlmProvider = llm;+ let report = run_auto_improve_review(+ &state.reader,+ llm_provider,+ workspace_id,+ project_id,+ sid,+ AutoImproveReviewConfig {+ min_observations: 3,+ min_session_duration_secs: 0,+ ..Default::default()+ },+ )+ .await+ .unwrap();+ let request = llm+ .0+ .lock()+ .unwrap()+ .take()+ .expect("review called recording LLM");+ let request_text = format!("{:?}{:?}", request.system, request.messages);+ assert!(!request_text.contains(SENTINEL));+ let report_text = serde_json::to_string(&report).unwrap();+ assert!(!report_text.contains(SENTINEL));+ // Review is read-only: no pending sidecar or approved page is created.+ assert!(+ state+ .reader+ .page_body_by_ids(workspace_id, project_id, "_pending/auto-improve")+ .await+ .unwrap()+ .is_none()+ );+ }++ #[test]+ fn unknown_capture_protocol_version_protects_recognized_file_tool() {+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": "unknown-version",+ "tool_name": "Write",+ "tool_input": { "file_path": "/repo/real.txt" },+ "tool_response": "SENTINEL_SECRET",+ "_ai_memory_capture": { "version": 99 },+ }),+ );+ let env = inspect_capture_envelope(env).unwrap();+ assert_eq!(env.title_hint.as_deref(), Some("file"));+ assert!(env.body_excerpt.is_none());+ assert!(!env.raw.to_string().contains("SENTINEL_SECRET"));+ assert_eq!(env.raw["_ai_memory_capture"]["policy_state"], "invalid");+ assert_eq!(+ env.raw["_ai_memory_capture"]["disposition"],+ "metadata-only"+ );+ assert_eq!(env.raw["_ai_memory_capture"]["tool_family"], "file");+ }++ #[test]+ fn malformed_capture_protocol_protects_recognized_file_tool() {+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": "malformed-protocol",+ "tool_name": "Write",+ "tool_input": { "file_path": "/repo/real.txt" },+ "tool_response": "SENTINEL_SECRET",+ "_ai_memory_capture": { "version": 1, "disposition": "keep" },+ }),+ );+ let env = inspect_capture_envelope(env).unwrap();+ assert_eq!(env.raw["_ai_memory_capture"]["policy_state"], "invalid");+ assert_eq!(+ env.raw["_ai_memory_capture"]["disposition"],+ "metadata-only"+ );+ assert_eq!(env.raw["_ai_memory_capture"]["tool_family"], "file");+ assert!(!env.raw.to_string().contains("SENTINEL_SECRET"));+ }++ #[tokio::test]+ async fn capture_protocol_batch_mixes_keep_drop_and_metadata_without_spending_drop_capacity() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.ingest_semaphore = Arc::new(tokio::sync::Semaphore::new(1));+ let state = Arc::new(state);+ let response = handle_hook_batch(+ State(state.clone()),+ None,+ Json(vec![+ HookBatchItem {+ url: "http://h/hook?event=session-start&agent=claude-code".into(),+ body: serde_json::json!({ "session_id": "capture-mixed" }),+ },+ HookBatchItem {+ url: "http://h/hook?event=post-tool-use&agent=claude-code".into(),+ body: serde_json::json!({+ "session_id": "capture-mixed", "tool_name": "Read",+ "tool_input": { "file_path": "/repo/private.txt" },+ "_ai_memory_capture": capture_protocol("drop", "active", "file", 1, "extracted"),+ }),+ },+ HookBatchItem {+ url: "http://h/hook?event=post-tool-use&agent=claude-code".into(),+ body: serde_json::json!({+ "session_id": "capture-mixed", "tool_family": "file", "tool_name": "file",+ "_ai_memory_capture": capture_protocol("metadata-only", "invalid", "file", 1, "extracted"),+ }),+ },+ ]),+ )+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(ack["accepted"], 3);+ let sid = resolve_session_id(&HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-start".into(),+ ..Default::default()+ },+ serde_json::json!({ "session_id": "capture-mixed" }),+ ))+ .unwrap();+ let observations = state.reader.observations_for_session(sid).await.unwrap();+ assert_eq!(observations.len(), 2, "Drop must not be stored");+ let metadata = observations.last().unwrap();+ assert_eq!(metadata.title, "file");+ assert!(metadata.body.is_empty());+ assert!(+ observations+ .iter()+ .all(|o| !o.body.contains("SENTINEL_SECRET"))+ );+ }++ #[tokio::test]+ async fn parsed_impossible_drop_is_acked_without_ingest_capacity() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.ingest_semaphore = Arc::new(tokio::sync::Semaphore::new(0));+ let state = Arc::new(state);+ let response = handle_hook_batch(+ State(state.clone()),+ None,+ Json(vec![HookBatchItem {+ url: "http://h/hook?event=post-tool-use&agent=claude-code".into(),+ body: serde_json::json!({+ "session_id": "drop-without-capacity", "tool_name": "Write",+ "tool_input": { "file_path": "/repo/private.txt" },+ "_ai_memory_capture": capture_protocol("drop", "inactive", "unknown", 99, "extracted"),+ }),+ }]),+ )+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::OK);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(ack["accepted"], 1);+ let sid = resolve_session_id(&HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ ..Default::default()+ },+ serde_json::json!({ "session_id": "drop-without-capacity" }),+ ))+ .unwrap();+ assert!(+ state+ .reader+ .observations_for_session(sid)+ .await+ .unwrap()+ .is_empty()+ );+ }}diff --git a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json b/crates/ai-memory-hooks/tests/fixtures/capture-policy.jsonnew file mode 100644index 00000000..1ece4c14--- /dev/null+++ b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json@@ -0,0 +1,36 @@+{+ "note": "Cross-language expected capture-policy vectors. All sentinel strings are test-only.",+ "normalization": [+ {"pattern":"secret/**","candidate":"secret","cwd":"/repo","match":true},+ {"pattern":"secret/**","candidate":"a/../secret/file","cwd":"/repo","match":true},+ {"pattern":"/**","candidate":"/","cwd":"/repo","match":true},+ {"pattern":"C:/**","candidate":"C:/","cwd":"C:/","match":true},+ {"pattern":"\\\\server\\share\\**","candidate":"//SERVER/SHARE","cwd":"C:/","match":true},+ {"pattern":"C:\\Secret\\**","candidate":"c:/SECRET","cwd":"C:/","match":true},+ {"pattern":"\\\\server\\share\\x","candidate":"//SERVER/SHARE/X","cwd":"C:/","match":true},+ {"pattern":"unicode/?.txt","candidate":"unicode/é.txt","cwd":"/repo","match":true},+ {"pattern":"foo..bar","candidate":"foo..bar","cwd":"/repo","match":true}+ ],+ "decisions": [+ {"agent":"claude-code","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"codex","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"cursor","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"gemini-cli","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"devin","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"grok","payload":{"toolName":"Edit","toolInput":{"filePath":"secret/a"},"callID":"safe-1"},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"zero","payload":{"toolName":"Edit","input":{"path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"antigravity-cli","payload":{"toolCall":{"name":"Edit","args":{"path":"secret/a"}}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"open-code","payload":{"tool":"Edit","args":{"path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"omp","payload":{"tool":"Edit","args":{"path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"pi","payload":{"tool":"Edit","args":{"path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"openclaw","payload":{"tool":"Edit","args":{"path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},+ {"agent":"codex","payload":{"tool_name":"Edit","tool_input":null},"disposition":"metadata-only","tool_family":"file","extraction_state":"missing-or-malformed","path_count":0},+ {"agent":"codex","payload":{"tool_name":"Edit","tool_input":{"path":" "}},"disposition":"metadata-only","tool_family":"file","extraction_state":"missing-or-malformed","path_count":0},+ {"agent":"codex","payload":{"tool_name":"MultiEdit","tool_input":{"edits":[{"path":"public"},{"path":"secret/a"}]}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":2},+ {"agent":"codex","payload":{"tool_name":"Search","tool_input":{}},"disposition":"drop","tool_family":"search-list","extraction_state":"not-applicable","path_count":0},+ {"agent":"codex","payload":{"tool_name":"Bash","tool_input":{"command":"secret/a"}},"disposition":"keep","tool_family":"non-file","extraction_state":"extracted","path_count":0},+ {"agent":"codex","payload":{"tool_name":"FutureTool","tool_input":{"path":"secret/a"}},"disposition":"keep","tool_family":"unknown","extraction_state":"extracted","path_count":0},+ {"agent":"codex","payload":{"tool_name":"Edit","tool_input":{"nested":{"path":"secret/a"}}},"disposition":"metadata-only","tool_family":"file","extraction_state":"missing-or-malformed","path_count":0}+ ],+ "protocol": {"accept":{"version":1,"disposition":"drop","policy_state":"active","tool_family":"file","path_count":1,"extraction_state":"extracted"},"reject":{"version":1,"disposition":"drop","policy_state":"active","tool_family":"file","path_count":1,"extraction_state":"extracted","paths":["SENTINEL"]}}+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex a14bcbcf..92c48723 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -52,6 +52,10 @@ from hook paths.minute-based env vars.Agent hot paths never block on the network; saturated servers return HTTP429 instead of queueing unbounded work.+ For supported native commands and generated OpenCode/OMP/Pi/OpenClaw+ integrations, the nearest-marker capture policy runs first: a dropped+ recognized file-tool event never enters spool, queue, transport, logs, or+ storage. See [Capture exclusions](marker-file.md#capture-exclusions).2. Server's hook router sanitises the payload (the only path fromuntrusted text into the store), assigns an [`ObservationKind`], andenqueues a `WriteCmd` to the writer actor. `log.md` gets andiff --git a/docs/auto-improvement-loop.md b/docs/auto-improvement-loop.mdindex 87e1aaa8..793b9967 100644--- a/docs/auto-improvement-loop.md+++ b/docs/auto-improvement-loop.md@@ -174,7 +174,9 @@ The shipped feature is an audit-first learning reviewer:1. Scheduled auto-improvement is enabled when an LLM provider is configured and`[auto_improve.scheduler] enabled = true`. Manual runs do not affect thescheduler.-2. Reads a completed session, recent pages, and relevant existing wiki pages.+2. Reads stored observations/session pages, recent pages, and relevant existing+ wiki pages. Capture exclusions are upstream of storage: excluded content+ cannot be recovered by `include_raw_fallback` because it was never stored.3. Produces a structured proposal containing small page creates or updates.4. Stores the proposal in a pending-review queue with evidence and diffs.5. Applies approved proposals through `Wiki::apply_batch`, admission webhooks,@@ -261,6 +263,10 @@ Any implementation should preserve these invariants:14. Write a machine-readable audit row for every run and human-readable proposalsidecars whenever proposals exist.+Capture policy is a client-side storage boundary, not a filter performed by the+reviewer. Reviewers can only consume what was stored; see+[Capture exclusions](marker-file.md#capture-exclusions).+## Existing User Upgrade ContractDefault-available auto-improvement must not surprise existing installs:diff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex cecfaf00..1c90790e 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -114,6 +114,18 @@ Three capture surfaces, in priority order:3. **Manual MCP tool** (`memory_remember`) - only for ad-hoc explicit captures from the user ("remember this"). Not the primary path; not what the agent reaches for by default.+### Capture-policy boundary (#194)++The nearest `.ai-memory.toml` may use `[capture] ignore_paths` to exclude+recognized file-tool events before client spool or transport. This is a strict,+schema-specific lexical boundary, not a general content or DLP filter: private+patterns and candidates never leave the client, but shell/patch text, aliases,+and non-path-attributable bodies remain outside its scope. The authoritative+grammar, limits, supported integrations, and `--check-capture` affordance are+in [the marker-file reference](marker-file.md#capture-exclusions). It adds no+MCP tool and needs no DB migration; new-client/old-server is safe, while old+clients retain their previous capture behavior.+## 7. Memory model (temporal)Adopt agentmemory's tier model **but** keep the surface narrow:diff --git a/docs/install.md b/docs/install.mdindex 43d4271a..1dd39993 100644--- a/docs/install.md+++ b/docs/install.md@@ -368,6 +368,16 @@ then stages runnable copies under `~/.local/share/ai-memory/hooks/<agent>/` sothe agent can execute files owned by your user. Re-run `install-hooks --apply`after package upgrades to refresh those staged copies.+### Capture-policy capability and refresh++`[capture] ignore_paths` is enforced only by native `ai-memory hook` commands+and generated OpenCode/OMP/Pi/OpenClaw integrations. Local installers select+native commands where supported; legacy `.sh`/`.ps1` hooks and remote-only or+Docker script bundles do not enforce it. Re-run `install-hooks --agent <agent>+--apply` or refresh/reinstall generated plugins after upgrading; installer+capability output reflects the selected integration. See the canonical+[capture exclusions reference](marker-file.md#capture-exclusions).+Native `ai-memory hook --event ...` commands spool events locally. Session startdoes a short bounded cleanup drain before fetching a handoff; cancellation-proneboundary events (`stop`, `pre-compact`, and `session-end`) start a detached@@ -492,16 +502,14 @@ Claude Desktop is MCP-only today. Claude Code, Codex, Devin CLI, OpenCode,OMP, Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, and OpenClaw have lifecycle capture paths through`install-hooks`.-> **Two-step hook install pattern.** Claude Code, Codex, Cursor,-> Gemini CLI, Antigravity CLI, Grok Build CLI, and Devin CLI use shell/PowerShell hook scripts: (1) `docker cp` the-> bundled scripts to your home dir, (2) `docker run --rm install-hooks`-> to render the config snippet.-> On native Windows, Claude Code is the exception to the PowerShell default:-> it uses Claude exec form (`command` = real `ai-memory.exe`, `args` = argv-> tokens for `hook --event ...`) by default. Set-> `AI_MEMORY_HOOK_PLATFORM=windows-bash` before `install-hooks` to opt back into-> Git Bash `bash -c` commands for the `.sh` scripts, including for older Claude-> Code builds that do not support exec form.+> **Hook install pattern.** Local supported profiles default to host-native+> commands. Claude Code may use its supported Windows exec form (`command` =+> real `ai-memory.exe`, `args` = argv tokens for `hook --event ...`); other+> agents use native single command strings according to their hook schema.+> PowerShell/Git Bash script bundles are compatibility fallbacks and do not+> enforce capture-policy v1. Remote-only/Docker script installs still use the+> two-step path: (1) `docker cp` bundled scripts to your home dir, (2)+> `docker run --rm install-hooks` renders the config snippet.> OpenClaw, OpenCode, and OMP are different: they use generated> TypeScript plugin/extension files, so no shell-script extraction is> needed for those clients.diff --git a/docs/macos.md b/docs/macos.mdindex abaf2847..47cb8b24 100644--- a/docs/macos.md+++ b/docs/macos.md@@ -129,6 +129,12 @@ cleanup, and starts a detached session-end `hook-drain` helper; the whole-minutespool-timing overrides are shared with Windows and documented in[`docs/windows.md`](windows.md#tuning-the-spool-timings-high-latency-instances).+Native `posix-native` `ai-memory hook` commands enforce the nearest-marker+`[capture] ignore_paths` policy before spool or network delivery. The Docker+wrapper's `posix` shell-script path does not. Re-run `install-hooks --agent+<agent> --apply` after upgrading to refresh an existing native install; see+[Capture exclusions](marker-file.md#capture-exclusions).+## Troubleshooting on macOS- **`403 forbidden host` from Docker-wrapper CLI commands:** update the Dockerdiff --git a/docs/marker-file.md b/docs/marker-file.mdindex 4f084308..680f6cf9 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -120,6 +120,85 @@ always stored regardless. This is per-project on purpose: there is noserver-global switch, so opting one noisy project in never sheds subagentcaptures for the others on a shared instance.+## Capture exclusions++Use the exact per-repository shape `[capture]` plus `ignore_paths = [...]`+below to keep recognized file-tool activity under matching paths out of capture:++```toml+[capture]+ignore_paths = ["private/**", "~/personal-notes/**"]+```++The **nearest** `.ai-memory.toml` is authoritative; marker sections do not+merge. A missing `[capture]` section or `ignore_paths = []` is inactive and+preserves current behavior. `[capture]` accepts only `ignore_paths`: unknown+keys, invalid types/globs/roots, unreadable markers, or a marker over 64 KiB+invalidate the whole capture policy rather than partially applying it.++Patterns match an entire lexically normalized path, not a substring. Use only+`*`, `?`, and `**`; relative patterns are rooted at the marker directory and+`~/` expands to the home directory. Prefer forward slashes on every platform.+POSIX matching is case-sensitive; Windows drive/UNC matching is ASCII+case-insensitive. Bounds are 128 patterns, 1,024 characters per pattern, 32+direct candidates and 4,096 characters per candidate, and 1,000,000 bounded+pattern/candidate comparisons.++For fixture-proven direct file tools, ai-memory reads only explicit path fields+and documented direct arrays for multi-file calls. If any candidate matches, the+entire event is **dropped locally** before spool, queue, network, transport+logs, or server storage. With an active policy, recognized search/list tools are+dropped conservatively; missing or malformed recognized file candidates, an+unsupported recognized schema, or an invalid policy become **metadata-only**.+That form contains only bounded routing/tool/decision metadata, never paths,+patterns, arguments, output, errors, titles, or nested payload. Known non-file+and unknown tools retain current behavior. Excluding content before transport+matters because it cannot then reach observations/FTS, session pages, handoffs,+reviewer requests, proposals, or logs.++This is a lexical capture boundary, **not complete DLP**. It does not resolve+symlinks, junctions, bind mounts, or Windows 8.3 aliases. Shell commands and+free-form patches are not parsed; prompts, assistant text, notifications, and+quoted content are not path-attributable. Add each relevant visible alias+explicitly, and do not rely on this feature to detect every way private content+can be mentioned.++### Supported integrations and refresh++Capture policy v1 is enforced by native `ai-memory hook` commands (including+native POSIX/Windows hook commands) and generated OpenCode, OMP, Pi, and+OpenClaw integrations. Local installers default to native commands where that+path is supported. Legacy `.sh`/`.ps1` hooks and remote-only/Docker script+bundles do **not** enforce it. Reinstall hooks or refresh/reinstall generated+plugins after upgrading; existing hooks/plugins keep their prior behavior.+Installer capability output describes the selected integration.++New clients remain safe with old servers because stripping and dropping happen+on the client. Old clients talking to new servers retain old behavior and cannot+enforce a host-only marker policy; the server cannot warn about policy it never+saw. The policy adds no MCP tool and no database migration.++### Check a decision locally++`ai-memory hook --event ... --agent ... --check-capture` reads one JSON payload+from stdin and performs no spool, queue, drain, network, or handoff work. It+prints only bounded decision metadata (protocol version, policy state, tool+family, path count, disposition, and extraction state), never paths, patterns,+or payload content:++```bash+printf '%s\n' '{"session_id":"demo","cwd":"/example/workspace","tool_name":"Edit","tool_input":{"path":"docs/example.md"}}' \+ | ai-memory hook --event post-tool-use --agent claude-code \+ --server-url http://127.0.0.1:49374 --check-capture+```++The normal capture contract is intentionally narrow: `PostToolUse` stores the+tool-response excerpt, capped at 2,000 bytes. User-prompt stores its prompt+text, notification stores its message/text, and post-compaction stores its+summary; other event bodies are currently empty unless explicitly supported.+Capture exclusions are evaluated only where paths have a proven schema, so they+do not claim to filter those other bodies.+## Four canonical examples### Multi-clientdiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex fa9e220a..9b25c55a 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -20,17 +20,24 @@ This page documents how to register ai-memory as an MCP server withagent CLIs beyond the README quick start.Claude Code, OpenAI Codex, Devin CLI, Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, OpenClaw, OpenCode, and-OMP have automatic capture integrations (shell/PowerShell hooks for-Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Grok Build CLI, TypeScript plugin/extension-files for OpenClaw / OpenCode / OMP) and are covered in the-[main README](../README.md#quick-start). On native Windows, Claude Code uses-Git Bash `.sh` hooks rather than the PowerShell default used by other-script-hook agents. Grok and Zero capture lifecycle events, but both ignore+OMP have automatic capture integrations (host-native commands for supported+local profiles, plus generated TypeScript plugin/extension files for OpenClaw /+OpenCode / OMP) and are covered in the [main README](../README.md#quick-start).+Claude Code may use its supported Windows exec form; other agents use native+single command strings according to their hook schema. PowerShell/Git Bash+script bundles are compatibility fallbacks and do not enforce capture-policy+v1. Grok and Zero capture lifecycle events, but both ignoreSessionStart stdout, so ai-memory does not auto-inject handoffs for them.SessionStart handoff injection works only for clients that consume startup-hookstdout (or their equivalent context-injection result); Grok and Zero must call`memory_handoff_accept` when resuming.+Capture exclusions are separate from MCP registration. Native hook commands and+generated OpenCode/OMP/Pi/OpenClaw integrations enforce `[capture]+ignore_paths`; legacy shell/PowerShell and remote-only/Docker script bundles do+not. Reinstall/refresh an existing hook or plugin to gain it; see+[Capture exclusions](marker-file.md#capture-exclusions).+Claude Desktop and VS Code Copilot are **MCP-only** here: they exposelong-term memory to their LLMs via ai-memory's MCP tools(`memory_query`, `memory_recent`, `memory_handoff_accept`, etc.), butdiff --git a/docs/usage.md b/docs/usage.mdindex 4f070322..64ad3727 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -4,6 +4,15 @@ This page covers what happens after ai-memory is installed: handoffs,compaction recovery, proactive memory queries, the web UI, and themanaged routing snippet + Agent Skills package.+## Capture exclusions++To keep recognized file-tool events under private paths out of ai-memory before+they are spooled or sent, configure `[capture] ignore_paths` in the nearest+`.ai-memory.toml`. The canonical grammar, limitations, support matrix, refresh+requirements, and safe local `--check-capture` command are in+[the marker-file reference](marker-file.md#capture-exclusions). This is not a+general prompt/output DLP filter.+## Cross-agent handoffYou normally do not create handoffs by hand. With lifecycle hooksdiff --git a/docs/windows.md b/docs/windows.mdindex f5d1d447..788b8a59 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -16,14 +16,13 @@ launches Claude Code, Codex, Devin CLI, Cursor, Gemini CLI, or another agent.The difference matters because hook configs contain executable paths.WSL2 agents need Linux paths and POSIX `.sh` hooks. Native Windows-agents need Windows paths, but the hook runner is agent-specific:-Claude Code invokes its hooks with Claude's direct exec form-(`command: "…ai-memory.exe"`, `args: ["hook", "--event", …]`) with no shell — see [Native Hook-Command](#native-hook-command-claude-code-on-windows). Set-`AI_MEMORY_HOOK_PLATFORM=windows-bash` to fall back to the older-`bash -c` + `.sh` Git Bash commands. Other native Windows script-hook-agents, including Devin CLI, keep the current script-command defaults for-their harness.+agents need Windows paths, but the hook runner is agent-specific: local+supported profiles default to host-native commands. Claude Code may use+its supported direct exec form (`command: "…ai-memory.exe"`, `args: ["hook",+"--event", …]`) with no shell — see [Native Hook+Command](#native-hook-command-claude-code-on-windows). Other agents use native+single command strings matching their hook schema. PowerShell/Git Bash script+bundles are compatibility fallbacks and do not enforce capture-policy v1.## Scenario A: Everything Inside WSL2@@ -104,12 +103,11 @@ the CLI to render hook commands for the native Windows agent:- Config files are written through the mounted Windows home directory.- Hook scripts are staged under `$HOME\.local\share\ai-memory\hooks\`.-- Claude Code hook commands call the `ai-memory` binary directly with Claude's- exec form (`command` executable + `args` argv array), no shell — set- `AI_MEMORY_HOOK_PLATFORM=windows-bash` for the old `bash -c` + `.sh`- Git Bash path.-- Other native Windows script-hook agents, including Devin CLI, use their- generated script-command hook entries for the selected platform.+- Local supported profiles default to host-native commands. Claude Code may use+ its exec form (`command` executable + `args` argv array), while other agents+ use native single command strings matching their hook schema. PowerShell/Git+ Bash script bundles are compatibility fallbacks and do not enforce+ capture-policy v1.Use the matching `--client` / `--agent` values for other clients, forexample `codex`, `devin`, `cursor`, or `gemini-cli`.@@ -201,11 +199,19 @@ target\debug\ai-memory.exe install-mcp --client claude-code --applytarget\debug\ai-memory.exe install-hooks --agent claude-code --apply```-Native Windows builds render agent-specific lifecycle hooks. Claude Code-defaults to the native binary command (see below); other script-hook agents-use the PowerShell `.ps1` default. The hook bundle still ships matching `.sh`-and `.ps1` event scripts as a fallback, and tests enforce one-to-one-event/agent parity between them.+Native Windows builds render agent-specific host-native lifecycle commands.+Claude Code may use its supported binary exec form (see below); other agents+use native single command strings matching their hook schema. The bundled `.sh`+and `.ps1` event scripts are compatibility fallbacks and do not enforce+capture-policy v1; tests enforce one-to-one event/agent parity between them.++### Capture-policy support++Native `ai-memory.exe hook` commands enforce the nearest-marker `[capture]+ignore_paths` policy before spool or network delivery. The legacy `.ps1` and+`.sh` paths do not. After upgrading, rerun `install-hooks --agent <agent>+--apply` to refresh native hook entries; selected-install capability output says+whether enforcement is active. See [Capture exclusions](marker-file.md#capture-exclusions).## Native Hook Command (Claude Code on Windows)