Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(capture): follow globs, searches and patch targets into other checkouts
AkitaOnRailsa3cfbd6c544e
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex 4399b16f..2c07355b 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -20,8 +20,9 @@ use std::time::Duration;use ai_memory_core::{AgentKind, ManagedRunId, SessionId};use ai_memory_hooks::capture_policy::metadata_only_body;use ai_memory_hooks::{- CaptureDecision, CaptureDisposition, CaptureMode, CapturePolicy, CaptureSource, HookEvent,- PolicyState, absolute_tool_location_paths, capture_lookup_locations, repository_admits_capture,+ CaptureDecision, CaptureDisposition, CaptureMode, CapturePolicy, CaptureSource, GlobStep,+ GlobWalk, HookEvent, PolicyState, absolute_tool_location_paths, capture_lookup_locations,+ glob_segment_matches, glob_walk, repository_admits_capture,};use ai_memory_llm::OidcToken;@@ -852,6 +853,8 @@ wherewrite_success_response(stdout, agent_kind, hook_event)?;return Ok(());}+ // Read before a metadata-only rewrite drops the payload's own fields.+ let subagent_payload = payload_is_subagent(&json);if let Some(decision) = decision {match decision.protocol().disposition() {CaptureDisposition::Drop => {@@ -1145,7 +1148,7 @@ wherecanonical_session_id.as_deref(),policy_cwd.as_deref(),);- if !shown.is_file() && !payload_is_subagent(&json) {+ if !shown.is_file() && !subagent_payload {let client = build_client();let bearer = hook_spool::resolve_bearer(&client, &dd, effective_token).await;let native_session_qs = canonical_session_id@@ -1307,6 +1310,10 @@ pub(crate) fn tool_location_routing_cwd(/// tool call may make [`foreign_capture_decision`] look up.const MAX_FOREIGN_DIRECTORIES: usize = 256;const MAX_FOREIGN_MARKERS: usize = 16;+/// How many directories, and directory entries read, following the glob+/// syntax of one tool call's locations may cost.+const MAX_GLOB_DIRECTORIES: usize = 256;+const MAX_GLOB_ENTRIES: usize = 65_536;/// The stricter decision of every other marker that governs a location the/// tool call names: a file-tool target, or a path a shell argument spells,@@ -1317,8 +1324,14 @@ const MAX_FOREIGN_MARKERS: usize = 16;////// Markers are found by the same lexical walk as the event's (no/// canonicalization), from the nearest existing directory of each location,-/// with each directory looked up once. A call naming more locations,-/// directories or markers than the bounds is unprovable and gets the+/// with each directory looked up once. A location with glob syntax+/// ([`glob_walk`]) is looked up from its literal root, and every directory+/// the glob could pass through below the root is checked for a marker of its+/// own: each glob segment lists the child directories (never following a+/// symlink), and a `**` lists the whole subtree unless it starts inside the+/// event's own checkout (its `.git` root). A call naming more locations,+/// directories, entries or markers than the bounds, glob syntax the walk+/// cannot follow, or locations that cannot be read is unprovable and gets the/// fail-closed decision of an invalid policy.pub(crate) fn foreign_capture_decision(agent: AgentKind,@@ -1347,7 +1360,29 @@ pub(crate) fn foreign_capture_decision(let mut directories: std::collections::HashMap<PathBuf, Option<PathBuf>> =std::collections::HashMap::new();let mut markers: Vec<PathBuf> = Vec::new();+ let checkout = crate::marker::checkout_root(Path::new(inspection_cwd));+ let mut walk = GlobBudget::default();for location in locations {+ let location = match glob_walk(&location) {+ GlobWalk::Literal => location,+ GlobWalk::Unprovable => return unprovable(),+ GlobWalk::Walk { root, steps } => {+ let Some(found) = walk.markers_below(Path::new(&root), &steps, checkout.as_deref())+ else {+ return unprovable();+ };+ for marker in found {+ if Some(marker.as_path()) == own_marker || markers.contains(&marker) {+ continue;+ }+ if markers.len() == MAX_FOREIGN_MARKERS {+ return unprovable();+ }+ markers.push(marker);+ }+ root+ }+ };let Some(dir) = existing_target_dir(Path::new(&location)) else {continue;};@@ -1381,6 +1416,95 @@ pub(crate) fn foreign_capture_decision(.reduce(CaptureDecision::stricter)}+/// What following one call's glob locations has cost so far.+#[derive(Default)]+struct GlobBudget {+ directories: usize,+ entries: usize,+}++impl GlobBudget {+ /// The marker files of every directory `steps` can reach below `root`,+ /// `root` itself excluded (its lookup is the caller's). `None` past the+ /// bounds. A step that reaches no directory ends the walk: the glob then+ /// matches nothing there.+ fn markers_below(+ &mut self,+ root: &Path,+ steps: &[GlobStep],+ checkout: Option<&Path>,+ ) -> Option<Vec<PathBuf>> {+ let mut found = Vec::new();+ let mut current = vec![root.to_path_buf()];+ for step in steps {+ let mut next = Vec::new();+ for dir in ¤t {+ match step {+ GlobStep::Named(name) => {+ let child = dir.join(name);+ if child.is_dir() {+ next.push(child);+ }+ }+ GlobStep::Matching(segment) => {+ next.extend(self.child_directories(dir)?.into_iter().filter(|child| {+ child.file_name().is_some_and(|name| {+ glob_segment_matches(segment, &name.to_string_lossy())+ })+ }))+ }+ GlobStep::Any => next.extend(self.child_directories(dir)?),+ GlobStep::AnyDepth => {+ if checkout.is_some_and(|checkout| dir.starts_with(checkout)) {+ continue;+ }+ let mut pending = self.child_directories(dir)?;+ while let Some(below) = pending.pop() {+ pending.extend(self.child_directories(&below)?);+ next.push(below);+ }+ }+ }+ }+ for dir in &next {+ self.directories += 1;+ if self.directories > MAX_GLOB_DIRECTORIES {+ return None;+ }+ let marker = dir.join(ai_memory_core::repository_identity::MARKER_FILENAME);+ if marker.is_file() {+ found.push(marker);+ }+ }+ if next.is_empty() {+ break;+ }+ current = next;+ }+ Some(found)+ }++ /// The child directories of `dir`, symlinks left out. An unreadable+ /// directory has none the glob could match either.+ fn child_directories(&mut self, dir: &Path) -> Option<Vec<PathBuf>> {+ let Ok(entries) = std::fs::read_dir(dir) else {+ return Some(Vec::new());+ };+ let mut children = Vec::new();+ for entry in entries {+ self.entries += 1;+ if self.entries > MAX_GLOB_ENTRIES {+ return None;+ }+ let Ok(entry) = entry else { continue };+ if entry.file_type().is_ok_and(|kind| kind.is_dir()) {+ children.push(entry.path());+ }+ }+ Some(children)+ }+}+/// Where one event is delivered (#992).#[derive(Debug)]enum HookRoute {@@ -3311,6 +3435,169 @@ mod tests {}}+ /// Adversarial: checkout A's `ignore_paths` also hold for a call from a+ /// sibling checkout or an unmarked parent that reaches A through glob+ /// syntax in a directory segment, through a search/list tool's path or+ /// glob, or through an `apply_patch` header; glob syntax the lookup+ /// cannot follow, and a file tool whose target cannot be read, fail+ /// closed. Controls: public files, the event's own files and searches,+ /// and ordinary globs are still captured whole.+ #[tokio::test]+ async fn globs_searches_and_unreadable_targets_answer_to_another_checkout() {+ let tmp = tempfile::tempdir().unwrap();+ let parent = tmp.path().join("work");+ let a = parent.join("a");+ let b = parent.join("b");+ for dir in [&a, &b, &b.join("src")] {+ std::fs::create_dir_all(dir).unwrap();+ }+ std::fs::write(+ a.join(".ai-memory.toml"),+ "project = \"a\"\n[capture]\nignore_paths = [\"secrets.env\"]\n",+ )+ .unwrap();+ std::fs::write(b.join(".ai-memory.toml"), "project = \"b\"\n").unwrap();+ let event = |agent_cwd: &Path, tool: &str, input: serde_json::Value| {+ serde_json::json!({+ "session_id": "cross-glob",+ "cwd": agent_cwd,+ "tool_name": tool,+ "tool_input": input,+ "tool_response": {"stdout": "SENTINEL_MUST_NOT_BE_SPOOLED"}+ })+ };+ let bash = |agent_cwd: &Path, command: &str| {+ event(agent_cwd, "Bash", serde_json::json!({"command": command}))+ };+ let attacks = [+ (+ "sibling star",+ "claude-code",+ bash(&b, "cat ../*/secrets.env"),+ ),+ (+ "parent star",+ "claude-code",+ bash(&parent, "cat */secrets.env"),+ ),+ ("brace", "claude-code", bash(&b, "cat ../{a,c}/secrets.env")),+ ("bracket", "claude-code", bash(&b, "cat ../[a]/secrets.env")),+ ("globstar", "claude-code", bash(&b, "cat ../**/secrets.env")),+ (+ "spanning brace",+ "claude-code",+ bash(&b, "cat ../{a/x,c}/secrets.env"),+ ),+ (+ "grep path",+ "claude-code",+ event(+ &b,+ "Grep",+ serde_json::json!({"pattern": "KEY", "path": "../a/secrets.env", "output_mode": "content"}),+ ),+ ),+ (+ "glob pattern",+ "claude-code",+ event(&b, "Glob", serde_json::json!({"pattern": "../a/*.env"})),+ ),+ (+ "grep filter from the parent",+ "claude-code",+ event(+ &parent,+ "Grep",+ serde_json::json!({"pattern": "KEY", "glob": "*/secrets.env"}),+ ),+ ),+ (+ "gemini search",+ "gemini-cli",+ event(+ &b,+ "search_file_content",+ serde_json::json!({"pattern": "KEY", "dir_path": "../a"}),+ ),+ ),+ (+ "patch header",+ "codex",+ event(+ &b,+ "apply_patch",+ serde_json::json!({"command": "*** Begin Patch\n*** Update File: ../a/secrets.env\n+KEY\n*** End Patch"}),+ ),+ ),+ (+ "unreadable target",+ "claude-code",+ event(&parent, "Read", serde_json::json!({})),+ ),+ ];+ for (name, agent, raw) in attacks {+ let data_dir = tmp.path().join(format!("data-{}", name.replace(' ', "-")));+ let entries = spool_one(&data_dir, agent, None, &raw).await;+ assert!(+ entries+ .iter()+ .all(|entry| !entry.body.contains("SENTINEL_MUST_NOT_BE_SPOOLED")),+ "{name}: {entries:?}"+ );+ }+ let controls = [+ ("public glob", "claude-code", bash(&b, "cat ../*/public.md")),+ ("own glob", "claude-code", bash(&b, "ls src/*")),+ (+ "own globstar",+ "claude-code",+ bash(&b, "cat src/**/main.rs"),+ ),+ (+ "own grep",+ "claude-code",+ event(+ &b,+ "Grep",+ serde_json::json!({"pattern": "KEY", "path": "src"}),+ ),+ ),+ (+ "own glob tool",+ "claude-code",+ event(&b, "Glob", serde_json::json!({"pattern": "**/*.rs"})),+ ),+ (+ "public grep",+ "claude-code",+ event(+ &parent,+ "Grep",+ serde_json::json!({"pattern": "KEY", "path": "b"}),+ ),+ ),+ (+ "own patch",+ "codex",+ event(+ &b,+ "apply_patch",+ serde_json::json!({"command": "*** Begin Patch\n*** Add File: src/x.rs\n+fn x() {}\n*** End Patch"}),+ ),+ ),+ ];+ for (name, agent, raw) in controls {+ let data_dir = tmp.path().join(format!("data-{}", name.replace(' ', "-")));+ let entries = spool_one(&data_dir, agent, None, &raw).await;+ assert_eq!(entries.len(), 1, "{name}");+ assert!(+ entries[0].body.contains("SENTINEL_MUST_NOT_BE_SPOOLED"),+ "{name}: {}",+ entries[0].body+ );+ }+ }+#[tokio::test]async fn shell_command_reading_an_ignored_path_is_dropped_before_spool() {for (command, spooled) in [("cat ./secret/*.md | head", 0), ("cat public/readme.md", 1)] {diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex e76a209b..95c0a8a1 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -4611,7 +4611,7 @@ fn add_hook_spooling(source: String) -> Result<String> {"async function drainHookQueue(): Promise<void> {\n if (hookDraining) return;\n requestSpoolDrain();",1,);- let import_anchor = "import { closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync } from \"node:fs\";";+ let import_anchor = "import { closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync } from \"node:fs\";";if out.matches(import_anchor).count() != 1 {anyhow::bail!("TS integration template drifted: node:fs import anchor not unique");}@@ -4644,7 +4644,7 @@ fn build_opencode_plugin(import type {{ Plugin }} from "@opencode-ai/plugin";import {{ execFileSync }} from "node:child_process";-import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync }} from "node:fs";+import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync }} from "node:fs";import {{ basename, dirname, join, resolve, sep }} from "node:path";import {{ homedir }} from "node:os";@@ -5392,7 +5392,7 @@ fn build_omp_extension(// re-run.import {{ execFileSync }} from "node:child_process";-import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync }} from "node:fs";+import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync }} from "node:fs";import {{ basename, dirname, join, resolve, sep }} from "node:path";import {{ homedir }} from "node:os";diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rsindex 9a993487..6b621c87 100644--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs@@ -684,7 +684,7 @@ mod tests {.unwrap().0;let source = format!(- "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst routeCwd={1};const direct=homeRoute(readHomeRouteText(join(homedir(),\".ai-memory.toml\")),routeCwd,\"github.com/acme/api\");const url=new URL(\"http://h/hook\");const ok=applyMarkerParams(url,routeCwd);process.stdout.write((direct?.project??\"none\")+\":\"+String(ok)+url.search);",+ "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst routeCwd={1};const direct=homeRoute(readHomeRouteText(join(homedir(),\".ai-memory.toml\")),routeCwd,\"github.com/acme/api\");const url=new URL(\"http://h/hook\");const ok=applyMarkerParams(url,routeCwd);process.stdout.write((direct?.project??\"none\")+\":\"+String(ok)+url.search);",helpers,serde_json::to_string(&repo.to_string_lossy()).unwrap());@@ -818,7 +818,7 @@ mod tests {.0;let module = tmp.path().join("openclaw-all-routes.ts");let source = format!(- "import {{ execFileSync as realExecFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction execFileSync(command:string,args:string[],options?:any):string{{return realExecFileSync(command,args,options) as string;}}\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst cases={} as any[];for(const c of cases){{const file=join(homedir(),\".ai-memory.toml\");writeFileSync(file,c.text);const url=new URL(\"http://h/hook\");let applied=false;let helper=\"none\";try{{const route=homeRoute(readHomeRouteText(file),c.cwd,c.identity);helper=route?route.workspace+\"/\"+route.project:\"none\";}}catch{{helper=\"invalid\";}}try{{applied=applyMarkerParams(url,c.cwd);}}catch{{applied=false;}}process.stdout.write(JSON.stringify({{name:c.name,applied,helper,params:Object.fromEntries(url.searchParams)}})+\"\\n\");}}",+ "import {{ execFileSync as realExecFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction execFileSync(command:string,args:string[],options?:any):string{{return realExecFileSync(command,args,options) as string;}}\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst cases={} as any[];for(const c of cases){{const file=join(homedir(),\".ai-memory.toml\");writeFileSync(file,c.text);const url=new URL(\"http://h/hook\");let applied=false;let helper=\"none\";try{{const route=homeRoute(readHomeRouteText(file),c.cwd,c.identity);helper=route?route.workspace+\"/\"+route.project:\"none\";}}catch{{helper=\"invalid\";}}try{{applied=applyMarkerParams(url,c.cwd);}}catch{{applied=false;}}process.stdout.write(JSON.stringify({{name:c.name,applied,helper,params:Object.fromEntries(url.searchParams)}})+\"\\n\");}}",helpers,serde_json::to_string(&cases).unwrap());@@ -960,7 +960,7 @@ mod tests {.unwrap().0;let source = format!(- "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync, unlinkSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst repoCwd={};const marker={};const homeMarker={};const run=(body:string)=>{{writeFileSync(marker,body);const url=new URL(\"http://h/hook\");applyMarkerParams(url,repoCwd);return Object.fromEntries(url.searchParams);}};const noMarkerUrl=new URL(\"http://h/hook\");applyMarkerParams(noMarkerUrl,repoCwd);const noMarker=Object.fromEntries(noMarkerUrl.searchParams);const plain=run('project=\"api\"\\n');const aliases=run('project=\"api\"\\naliases=[\"old-api\"]\\n');unlinkSync(marker);writeFileSync(homeMarker,'[routes.identity.\"github.com/acme/api\"]\\nroute_workspace=\"oss\"\\nroute_project=\"api\"\\n');const routedUrl=new URL(\"http://h/hook\");applyMarkerParams(routedUrl,repoCwd);process.stdout.write(JSON.stringify({{noMarker,plain,aliases,routed:Object.fromEntries(routedUrl.searchParams)}}));",+ "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, unlinkSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst repoCwd={};const marker={};const homeMarker={};const run=(body:string)=>{{writeFileSync(marker,body);const url=new URL(\"http://h/hook\");applyMarkerParams(url,repoCwd);return Object.fromEntries(url.searchParams);}};const noMarkerUrl=new URL(\"http://h/hook\");applyMarkerParams(noMarkerUrl,repoCwd);const noMarker=Object.fromEntries(noMarkerUrl.searchParams);const plain=run('project=\"api\"\\n');const aliases=run('project=\"api\"\\naliases=[\"old-api\"]\\n');unlinkSync(marker);writeFileSync(homeMarker,'[routes.identity.\"github.com/acme/api\"]\\nroute_workspace=\"oss\"\\nroute_project=\"api\"\\n');const routedUrl=new URL(\"http://h/hook\");applyMarkerParams(routedUrl,repoCwd);process.stdout.write(JSON.stringify({{noMarker,plain,aliases,routed:Object.fromEntries(routedUrl.searchParams)}}));",helpers,serde_json::to_string(&repo.to_string_lossy()).unwrap(),serde_json::to_string(&marker.to_string_lossy()).unwrap(),diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex f259e32d..b290f88a 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -244,6 +244,8 @@ const CAPTURE_MAX_CALL_ID_CHARS = 128;const CAPTURE_MAX_LOOKUP_LOCATIONS = 4096;const CAPTURE_MAX_FOREIGN_DIRECTORIES = 256;const CAPTURE_MAX_FOREIGN_MARKERS = 16;+const CAPTURE_MAX_GLOB_DIRECTORIES = 256;+const CAPTURE_MAX_GLOB_ENTRIES = 65536;// macOS's default filesystem ignores case and Unicode composition, so `NOTES/X.md` reads `notes/x.md`; mirrors `fold_case`.let captureFoldCase = typeof process !== "undefined" && process.platform === "darwin";// A path as a case-folding host compares it: NFC, then the full lowercase mapping; mirrors `fold_path`.@@ -405,7 +407,17 @@ function captureGlobsIntersect(left: string[], right: string[]): boolean { constfunction captureMatchGlobs(paths: string[], candidates: { path: string; windows: boolean }[], config: CaptureConfig): boolean | undefined { const budget = { work: 0 }; for (let i = 0; i < paths.length; i++) { if (/[\[\]{}()!]/.test(paths[i])) return undefined; const match = captureMatchCandidate(candidates[i], true, config, budget); if (match !== false) return match; } return false; }function captureMatchCandidate(raw: { path: string; windows: boolean }, toolGlob: boolean, config: CaptureConfig, budget: { work: number }): boolean | undefined { const candidate = { path: captureFold(raw.path), windows: raw.windows }; const glob = /[*?]/.test(candidate.path); const directory = toolGlob && !glob; for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; const insensitive = toolGlob || pattern.windows || captureFoldCase; const under = captureStartsWith(candidate.path, pattern.prefix, insensitive); if (!under && !glob && !directory) continue; if (under) { const directory = pattern.directory ? captureGlob(pattern.directory, candidate.path, insensitive, budget) : false; if (directory !== false) return directory; const match = captureGlob(pattern.path, candidate.path, insensitive, budget); if (match !== false) return match; } if (glob) { const reaches = captureGlobstarReaches(candidate.path, pattern.prefix, insensitive, budget); if (reaches !== false) return reaches; } if (directory) { const below = captureGlobBelow(pattern.path, candidate.path, insensitive, budget); if (below !== false) return below; } } return false; }function captureGlobstarReaches(glob: string, prefix: string, insensitive: boolean, budget: { work: number }): boolean | undefined { const star = glob.indexOf("**"); if (star < 0) return captureGlobReaches(glob, prefix, insensitive, budget); const slash = glob.lastIndexOf("/", star); const head = slash < 0 ? "" : glob.slice(0, slash); const depth = head.split("/").filter(Boolean).length; let seen = 0; let offset = 0; for (const part of prefix.split("/")) { if (seen === depth) break; offset += part.length; if (part) seen++; if (seen < depth) offset++; } if (seen < depth) return captureGlobReaches(glob, prefix, insensitive, budget); return captureGlob(head, prefix.slice(0, offset), insensitive, budget); }-function captureTool(payload: Record<string, unknown>): { family: CaptureProtocol["tool_family"]; paths?: string[]; extraction: CaptureProtocol["extraction_state"]; callID?: string; command?: string | string[]; shell?: boolean; powershell?: boolean; workdir?: string; globs?: boolean; reader?: boolean } { 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","list_dir","grep_search","search_files","find_by_name","list_directory","search_file_content"].includes(name)) return { family: "search-list", extraction: "not-applicable", callID: call }; if (["bash","shell","shell_command","exec","execute","run_command","web_search","search_web","manage_task","manage_subagents","terminal","execute_bash","execute_cmd","powershell","run_shell_command"].includes(name)) { const workdir = ["workdir","dir_path","directory"].map((k) => args?.[k]).find((v) => v !== undefined); return { family: "non-file", extraction: "extracted", callID: call, command: captureShellCommand(args), shell: name !== "web_search", powershell: name === "powershell", workdir: typeof workdir === "string" && workdir.trim() ? workdir : undefined }; } if (!["read","write","edit","apply_patch","notebookedit","notebook_edit","create_file","delete_file","rename_file","move_file","multi_edit","multiedit","replace","replace_all","read_many_files"].includes(name)) return { family: "unknown", extraction: "extracted", callID: call, reader: ["bashoutput","taskoutput","write_stdin","process","read_bash","write_bash","read_powershell","write_powershell"].includes(name) }; 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","TargetFile"]) 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 (name === "read_many_files" && args && "include" in args) { const include = args.include; if (!Array.isArray(include) || include.some((x: unknown) => typeof x !== "string") || (paths?.length ?? 0) + include.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else paths = [...(paths ?? []), ...(include as string[])]; } if (!paths || !paths.length || 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, globs: name === "read_many_files" }; }+function captureTool(payload: Record<string, unknown>): { family: CaptureProtocol["tool_family"]; paths?: string[]; extraction: CaptureProtocol["extraction_state"]; callID?: string; command?: string | string[]; shell?: boolean; powershell?: boolean; workdir?: string; globs?: boolean; reader?: boolean; search?: { roots: string[]; patterns: string[] }; patch?: 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","list_dir","grep_search","search_files","find_by_name","list_directory","search_file_content"].includes(name)) return { family: "search-list", extraction: "not-applicable", callID: call, search: captureSearchScope(name, args) }; if (["bash","shell","shell_command","exec","execute","run_command","web_search","search_web","manage_task","manage_subagents","terminal","execute_bash","execute_cmd","powershell","run_shell_command"].includes(name)) { const workdir = ["workdir","dir_path","directory"].map((k) => args?.[k]).find((v) => v !== undefined); return { family: "non-file", extraction: "extracted", callID: call, command: captureShellCommand(args), shell: name !== "web_search", powershell: name === "powershell", workdir: typeof workdir === "string" && workdir.trim() ? workdir : undefined }; } if (!["read","write","edit","apply_patch","notebookedit","notebook_edit","create_file","delete_file","rename_file","move_file","multi_edit","multiedit","replace","replace_all","read_many_files"].includes(name)) return { family: "unknown", extraction: "extracted", callID: call, reader: ["bashoutput","taskoutput","write_stdin","process","read_bash","write_bash","read_powershell","write_powershell"].includes(name) }; 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","TargetFile"]) 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 (name === "read_many_files" && args && "include" in args) { const include = args.include; if (!Array.isArray(include) || include.some((x: unknown) => typeof x !== "string") || (paths?.length ?? 0) + include.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else paths = [...(paths ?? []), ...(include as string[])]; } if (!paths || !paths.length || paths.some((p) => !p.trim() || [...p].length > CAPTURE_MAX_PATH_CHARS)) return { family: "file", extraction: "missing-or-malformed", callID: call, patch: capturePatchPaths(name, payload.args) }; return { family: "file", paths, extraction: "extracted", callID: call, globs: name === "read_many_files" }; }+// Where a search/list tool reads, for the cross-checkout lookup: its directory and file arguments, a glob tool's `pattern`, and a content search's file filters (a grep `pattern` is a regular expression). Undefined when one is not a string; mirrors `search_scope`.+function captureSearchScope(name: string, args: unknown): { roots: string[]; patterns: string[] } | undefined { if (args === undefined || args === null) return { roots: [], patterns: [] }; if (typeof args !== "object" || Array.isArray(args)) return undefined; const o = args as Record<string, unknown>; const roots: string[] = []; const patterns: string[] = []; for (const k of ["file_path","filePath","path","absolute_path","AbsolutePath","notebook_path","TargetFile","dir_path","directory","DirectoryPath","SearchDirectory","SearchPath"]) if (k in o) { if (typeof o[k] !== "string") return undefined; roots.push(o[k] as string); } if ("paths" in o) { if (!Array.isArray(o.paths) || o.paths.some((x: unknown) => typeof x !== "string")) return undefined; roots.push(...(o.paths as string[])); } for (const k of [...(["glob","find","find_by_name"].includes(name) ? ["pattern","Pattern"] : []), "glob","include","file_pattern","Includes"]) { if (!(k in o)) continue; const v = o[k]; if (typeof v === "string") patterns.push(v); else if (Array.isArray(v) && v.every((x) => typeof x === "string")) patterns.push(...(v as string[])); else return undefined; } return roots.length + patterns.length <= CAPTURE_MAX_CANDIDATES && [...roots, ...patterns].every((p) => p.trim() && [...p].length <= CAPTURE_MAX_PATH_CHARS) ? { roots, patterns } : undefined; }+// The files an `apply_patch` patch names in its Add/Update/Delete File and Move to headers, for the cross-checkout lookup only; mirrors `patch_paths`.+function capturePatchPaths(name: string, args: unknown): string[] | undefined { if (name !== "apply_patch" && name !== "patch") return undefined; const o = args as Record<string, unknown> | undefined; const text = typeof args === "string" ? args : o && typeof o === "object" ? ["command","patch","patchText","input"].map((k) => o[k]).find((v): v is string => typeof v === "string") : undefined; if (text === undefined) return undefined; const paths: string[] = []; for (const line of text.split(/\r?\n/)) { const header = ["*** Add File:","*** Update File:","*** Delete File:","*** Move to:"].find((h) => line.startsWith(h)); if (!header) continue; const path = line.slice(header.length).trim(); if (!path || [...path].length > CAPTURE_MAX_PATH_CHARS || paths.length === CAPTURE_MAX_CANDIDATES) return undefined; paths.push(path); } return paths.length ? paths : undefined; }+// How to follow a lookup location with glob syntax: null when it has none (a parameter expansion's braces are not syntax; the shell split also reads each default in its place), undefined when a brace or group spans a separator or an alternative of `..` or `~…` leaves the root, else its literal root and one step per remaining segment ("*" any child directory, "?<glob>" a child the `*`/`?` glob names without regard to ASCII case, "**" any depth, ending the walk; anything else that child); mirrors `glob_walk`.+function captureGlobWalk(location: string): { root: string; steps: string[] } | null | undefined { if (location.includes("${")) return null; const parsed = captureNormalize(location); if (!parsed) return null; const p = parsed.path; let root: string; let tail: string; if (p.startsWith("//")) { const parts = p.slice(2).split("/"); root = `//${parts[0]}/${parts[1]}`; tail = parts.slice(2).join("/"); } else if (/^[A-Za-z]:\//.test(p)) { root = p.slice(0, 3); tail = p.slice(3); } else { root = "/"; tail = p.slice(1); } const segments = tail.split("/").filter(Boolean); const syntax = (segment: string) => /[*?\[{(]/.test(segment); const first = segments.findIndex(syntax); if (first < 0) return null; const steps: string[] = []; for (const segment of segments.slice(first)) { if (!syntax(segment)) { steps.push(segment); continue; } const count = (c: string) => segment.split(c).length - 1; if (segment.split(/[{},()|@!+]/).some((piece) => piece === ".." || piece.startsWith("~")) || count("{") !== count("}") || count("(") !== count(")")) return undefined; if (segment.includes("**")) { steps.push("**"); break; } steps.push(/[\[{(]/.test(segment) ? "*" : `?${segment}`); } for (const segment of segments.slice(0, first)) root += `${root.endsWith("/") ? "" : "/"}${segment}`; return { root: parsed.windows ? root.replace(/\//g, "\\") : root, steps }; }+// The marker files of every directory `steps` reach below `root` (root excluded), never following a symlink; a "**" below `checkout` is not listed. Undefined past the bounds; mirrors `GlobBudget::markers_below`.+function captureMarkersBelow(root: string, steps: string[], checkout: string | undefined, budget: { dirs: number; entries: number }): string[] | undefined { const children = (dir: string): string[] | undefined => { let entries: { name: string; isDirectory(): boolean }[]; try { entries = readdirSync(dir, { withFileTypes: true }); } catch (_e) { return []; } const out: string[] = []; for (const entry of entries) { if (++budget.entries > CAPTURE_MAX_GLOB_ENTRIES) return undefined; if (entry.isDirectory()) out.push(join(dir, entry.name)); } return out; }; const found: string[] = []; let current = [root]; for (const step of steps) { const next: string[] = []; for (const dir of current) { if (step === "*" || step.startsWith("?")) { const more = children(dir); if (!more) return undefined; next.push(...(step === "*" ? more : more.filter((child) => captureGlob(step.slice(1), basename(child), true, { work: 0 }) !== false))); } else if (step === "**") { if (checkout !== undefined && dir.startsWith(checkout) && (dir.length === checkout.length || /[\\/]/.test(dir[checkout.length]) || /[\\/]$/.test(checkout))) continue; const pending = children(dir); if (!pending) return undefined; while (pending.length) { const below = pending.pop()!; const more = children(below); if (!more) return undefined; pending.push(...more); next.push(below); } } else { const child = join(dir, step); try { if (statSync(child).isDirectory()) next.push(child); } catch (_e) { /* the glob matches nothing there */ } } } for (const dir of next) { if (++budget.dirs > CAPTURE_MAX_GLOB_DIRECTORIES) return undefined; const marker = join(dir, ".ai-memory.toml"); try { if (statSync(marker).isFile()) found.push(marker); } catch (_e) { /* no marker here */ } } if (!next.length) break; current = next; } return found; }+// The event's own checkout: the nearest directory at or above `cwd` holding `.git`; mirrors `checkout_root`.+function captureCheckoutRoot(cwd: string | undefined): string | undefined { if (!cwd) return undefined; for (let dir = resolve(cwd); ; dir = dirname(dir)) { try { statSync(join(dir, ".git")); return dir; } catch (_e) { /* keep walking */ } if (dirname(dir) === dir) return undefined; } }// An external lifecycle owner (`AI_MEMORY_CAPTURE_OWNER`, any value that is// non-empty after trimming) takes over capture for this process: the gate runs// before the capture-policy marker scan, so no disposition work, no marker read@@ -423,13 +435,13 @@ function captureOwnedExternally(): boolean { const owner = typeof process === "ufunction captureServerRouted(cwd: string | undefined): boolean { let dir = resolve(cwd ?? process.cwd()); const home = homedir(); let boundary: string | undefined; for (let probe = dir; ; probe = dirname(probe)) { if (probe === home) { boundary = home; break; } if (probe === dirname(probe)) break; } for (;;) { try { if (/^\s*server\s*=/m.test(readFileSync(join(dir, ".ai-memory.toml"), "utf8"))) return true; } catch (e) { if (!["ENOENT", "ENOTDIR", "EISDIR"].includes((e as { code?: string })?.code ?? "")) return true; } if (dir === boundary || dir === dirname(dir)) return false; dir = dirname(dir); } }type CaptureTool = ReturnType<typeof captureTool>;// One policy's disposition for one call, shared by the event's own marker and every other marker it reaches.-function captureDecide(tool: CaptureTool, config: CaptureConfig): CaptureDisposition { if (config.state === "invalid" && (tool.family === "file" || tool.shell || tool.reader)) return "metadata-only"; if (config.state !== "active") return "keep"; if (tool.reader) return "metadata-only"; if (tool.family === "search-list") return "drop"; if (tool.family === "file") { if (!tool.paths) return "metadata-only"; const parsed = tool.paths.map((p) => captureNormalize(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p), config.windowsHost)); if (parsed.some((p) => !p)) return "metadata-only"; const candidates = parsed as { path: string; windows: boolean }[]; if (tool.globs) { const match = captureMatchGlobs(tool.paths, candidates, config); if (match !== false) return match ? "drop" : "metadata-only"; return candidates.some((candidate) => captureOutputSpool(candidate.path)) ? "metadata-only" : "keep"; } const budget = { work: 0 }; for (const raw of candidates) { const candidate = { path: captureFold(raw.path), windows: raw.windows }; for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; if (pattern.directory && captureGlob(pattern.directory, candidate.path, pattern.windows || captureFoldCase, budget)) return "drop"; const match = captureGlob(pattern.path, candidate.path, pattern.windows || captureFoldCase, budget); if (match === undefined) return "metadata-only"; if (match) return "drop"; } } return candidates.some((candidate) => captureOutputSpool(candidate.path)) ? "metadata-only" : "keep"; } if (tool.family === "non-file" && tool.command !== undefined) { const split = captureShellSplit(tool.command, tool.powershell || config.windowsHost); const matched = captureMatchCommand(split.words, config, tool.workdir); if (matched.match !== false) return "drop"; if (split.opaque || matched.spool) return "metadata-only"; } return "keep"; }+function captureDecide(tool: CaptureTool, config: CaptureConfig): CaptureDisposition { if (config.state === "invalid" && (tool.family === "file" || tool.family === "search-list" || tool.shell || tool.reader)) return "metadata-only"; if (config.state !== "active") return "keep"; if (tool.reader) return "metadata-only"; if (tool.family === "search-list") return "drop"; if (tool.family === "file") { if (!tool.paths) return "metadata-only"; const parsed = tool.paths.map((p) => captureNormalize(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p), config.windowsHost)); if (parsed.some((p) => !p)) return "metadata-only"; const candidates = parsed as { path: string; windows: boolean }[]; if (tool.globs) { const match = captureMatchGlobs(tool.paths, candidates, config); if (match !== false) return match ? "drop" : "metadata-only"; return candidates.some((candidate) => captureOutputSpool(candidate.path)) ? "metadata-only" : "keep"; } const budget = { work: 0 }; for (const raw of candidates) { const candidate = { path: captureFold(raw.path), windows: raw.windows }; for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; if (pattern.directory && captureGlob(pattern.directory, candidate.path, pattern.windows || captureFoldCase, budget)) return "drop"; const match = captureGlob(pattern.path, candidate.path, pattern.windows || captureFoldCase, budget); if (match === undefined) return "metadata-only"; if (match) return "drop"; } } return candidates.some((candidate) => captureOutputSpool(candidate.path)) ? "metadata-only" : "keep"; } if (tool.family === "non-file" && tool.command !== undefined) { const split = captureShellSplit(tool.command, tool.powershell || config.windowsHost); const matched = captureMatchCommand(split.words, config, tool.workdir); if (matched.match !== false) return "drop"; if (split.opaque || matched.spool) return "metadata-only"; } return "keep"; }const captureRank: Record<CaptureDisposition, number> = { keep: 0, "metadata-only": 1, drop: 2 };-// Every other marker governing a path the call names (a file-tool target, or a shell argument with a separator resolved from its workdir, plus that directory) inspects it too, so a checkout's `ignore_paths` hold for a call made from elsewhere. Lexical; each directory is looked up once, and past the bounds the call is unprovable. Mirrors `capture_lookup_locations` and `foreign_capture_decision`.-function captureForeignConfigs(tool: CaptureTool, config: CaptureConfig, cwd: string | undefined, own: string | undefined): CaptureConfig[] { const invalid: CaptureConfig[] = [{ state: "invalid", patterns: [], base: config.base, windowsHost: config.windowsHost }]; const locations = new Set<string>(); const add = (path: string, base: string) => { const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(path); if (!absolute && !base) return; const candidate = captureNormalize(absolute ? path : captureJoin(base, path), config.windowsHost); if (candidate) locations.add(candidate.windows ? candidate.path.replace(/\//g, "\\") : candidate.path); }; if (tool.family === "file") for (const path of tool.paths ?? []) add(path, config.base); else if (tool.family === "non-file" && tool.command !== undefined) { const base = captureBase(config, tool.workdir); if (base) add(base, base); const home = homedir(); for (const [word, tilde] of captureShellSplit(tool.command, tool.powershell || config.windowsHost).words) for (const [argument] of captureShellArguments(word)) { const expanded = captureExpandTilde(argument, tilde, home, base); if (/[\/\\]/.test(expanded)) add(expanded, base); } } if (locations.size > CAPTURE_MAX_LOOKUP_LOCATIONS) return invalid; const directories = new Map<string, string | undefined>(); const markers: string[] = []; for (const location of locations) { const dir = captureExistingDir(location); if (dir === undefined) continue; let marker: string | undefined; if (directories.has(dir)) marker = directories.get(dir); else { if (directories.size === CAPTURE_MAX_FOREIGN_DIRECTORIES) return invalid; marker = findMarker(dir); directories.set(dir, marker); } if (!marker || marker === own || markers.includes(marker)) continue; if (markers.length === CAPTURE_MAX_FOREIGN_MARKERS) return invalid; markers.push(marker); } return markers.map((marker) => captureConfigAt(marker, cwd)); }+// Every other marker governing a path the call names (a file-tool target or the files an `apply_patch` names, a search/list directory, file or path-like glob argument, or a shell argument with a separator resolved from its workdir, plus that directory) inspects it too, so a checkout's `ignore_paths` hold for a call made from elsewhere. Lexical; each directory is looked up once; a glob location is looked up from its literal root and every directory it could pass through is checked for a marker of its own. Unreadable targets, glob syntax the walk cannot follow, and anything past the bounds are unprovable. Mirrors `capture_lookup_locations` and `foreign_capture_decision`.+function captureForeignConfigs(tool: CaptureTool, config: CaptureConfig, cwd: string | undefined, own: string | undefined): CaptureConfig[] { const invalid: CaptureConfig[] = [{ state: "invalid", patterns: [], base: config.base, windowsHost: config.windowsHost }]; const locations = new Set<string>(); const add = (path: string, base: string): string | undefined => { const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(path); if (!absolute && !base) return undefined; const candidate = captureNormalize(absolute ? path : captureJoin(base, path), config.windowsHost); if (!candidate) return undefined; const location = candidate.windows ? candidate.path.replace(/\//g, "\\") : candidate.path; locations.add(location); return location; }; if (tool.family === "file") { const paths = tool.paths ?? tool.patch; if (!paths) return invalid; for (const path of paths) if (add(path, config.base) === undefined) return invalid; } else if (tool.family === "search-list") { if (!tool.search) return invalid; const roots: string[] = []; for (const root of tool.search.roots) { const location = add(root, config.base); if (location === undefined) return invalid; roots.push(location); } if (!roots.length) roots.push(config.base); for (const pattern of tool.search.patterns.filter((p) => /[\/\\]/.test(p))) for (const root of roots) if (add(pattern, root) === undefined) return invalid; } else if (tool.family === "non-file" && tool.command !== undefined) { const base = captureBase(config, tool.workdir); if (base) add(base, base); const home = homedir(); for (const [word, tilde] of captureShellSplit(tool.command, tool.powershell || config.windowsHost).words) for (const [argument] of captureShellArguments(word)) { const expanded = captureExpandTilde(argument, tilde, home, base); if (/[\/\\]/.test(expanded)) add(expanded, base); } } if (locations.size > CAPTURE_MAX_LOOKUP_LOCATIONS) return invalid; const directories = new Map<string, string | undefined>(); const markers: string[] = []; const checkout = captureCheckoutRoot(cwd); const budget = { dirs: 0, entries: 0 }; const remember = (marker: string | undefined): boolean => { if (!marker || marker === own || markers.includes(marker)) return true; if (markers.length === CAPTURE_MAX_FOREIGN_MARKERS) return false; markers.push(marker); return true; }; for (const location of locations) { const walk = captureGlobWalk(location); if (walk === undefined) return invalid; let lookup = location; if (walk) { const found = captureMarkersBelow(walk.root, walk.steps, checkout, budget); if (!found) return invalid; for (const marker of found) if (!remember(marker)) return invalid; lookup = walk.root; } const dir = captureExistingDir(lookup); if (dir === undefined) continue; let marker: string | undefined; if (directories.has(dir)) marker = directories.get(dir); else { if (directories.size === CAPTURE_MAX_FOREIGN_DIRECTORIES) return invalid; marker = findMarker(dir); directories.set(dir, marker); } if (!remember(marker)) return invalid; } return markers.map((marker) => captureConfigAt(marker, cwd)); }// The nearest existing directory at or above `path`; mirrors `existing_target_dir`.function captureExistingDir(path: string): string | undefined { let probe = path; for (;;) { try { if (statSync(probe).isDirectory()) return probe; } catch (_e) { /* not there yet */ } const parent = dirname(probe); if (parent === probe || parent === ".") return undefined; probe = parent; } }-function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { if (captureOwnedExternally()) return { disposition: "drop", payload }; if (captureServerRouted(cwd)) return { disposition: "drop", payload }; const markerPresent = !!findMarker(cwd); if (CAPTURE_MODE === "allowlist" && !markerPresent) return { disposition: "drop", payload }; const own = findMarker(cwd); let config = captureConfigAt(own, cwd); const tool = captureTool(payload); let disposition = captureDecide(tool, config); if (disposition !== "drop" && tool.family !== "search-list" && tool.family !== "unknown") for (const other of captureForeignConfigs(tool, config, cwd, own)) { const decided = captureDecide(tool, other); if (captureRank[decided] > captureRank[disposition]) { disposition = decided; config = other; } } 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 }; }+function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { if (captureOwnedExternally()) return { disposition: "drop", payload }; if (captureServerRouted(cwd)) return { disposition: "drop", payload }; const markerPresent = !!findMarker(cwd); if (CAPTURE_MODE === "allowlist" && !markerPresent) return { disposition: "drop", payload }; const own = findMarker(cwd); let config = captureConfigAt(own, cwd); const tool = captureTool(payload); let disposition = captureDecide(tool, config); if (disposition !== "drop" && tool.family !== "unknown") for (const other of captureForeignConfigs(tool, config, cwd, own)) { const decided = captureDecide(tool, other); if (captureRank[decided] > captureRank[disposition]) { disposition = decided; config = other; } } 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 }; }"##;TEMPLATE.replace("__AI_MEMORY_CAPTURE_MODE__", capture_mode)}@@ -2592,8 +2604,8 @@ mod tests {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, mkdirSync, openSync, readFileSync as readMarkerText, readSync, statSync, writeFileSync }} from "node:fs";-import {{ dirname, join, resolve }} from "node:path";+ r#"import {{ closeSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync }} from "node:fs";+import {{ basename, dirname, join, resolve }} from "node:path";import {{ homedir }} from "node:os";const fixtureText = {fixture};@@ -2629,7 +2641,7 @@ function expectDecision(payload: Record<string, unknown>, cwd: string, dispositiconst 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}}`);+ expectDecision(vector.payload, cwd, vector.disposition, vector.tool_family, vector.extraction_state, vector.path_count, `fixture-${{vector.agent}} ${{JSON.stringify(vector.payload)}}`);}}for (const vector of fixture.normalization) {{const cwd = marker(`[capture]\nignore_paths = [${{JSON.stringify(vector.pattern)}}]\n`);@@ -2718,6 +2730,13 @@ check(crossBrokenResult.disposition === "metadata-only" && crossBrokenResult.prolet crossMany = "cat"; for (let i = 0; i <= CAPTURE_MAX_FOREIGN_MARKERS; i++) {{ const dir = join(markerRoot, `cross-m${{i}}`); mkdirSync(dir, {{ recursive: true }}); writeFileSync(join(dir, ".ai-memory.toml"), 'project = "m"\n'); markerFixtures.set(dir, join(dir, ".ai-memory.toml")); crossMany += ` ../cross-m${{i}}/x.md`; }}check(capturePolicy(bash(crossMany), crossB).disposition === "metadata-only", "cross-too-many-markers");for (const [payload, cwd, label] of [[bash("cat ../cross-a/public.md README.md"), crossB, "cross-shell-public"], [{{ tool: "read", args: {{ path: "../cross-a/public.md" }} }}, crossB, "cross-file-public"], [bash("cat secrets.env"), crossB, "cross-own-file"], [bash("cat ../cross-m0/x.md ../cross-m1/x.md"), crossB, "cross-few-markers"]] as [Record<string, unknown>, string, string][]) check(capturePolicy(payload, cwd).disposition === "keep", label);+// Globs in directory segments, search/list tools, patch headers and unreadable targets reach another checkout's policy; mirrors `globs_searches_and_unreadable_targets_answer_to_another_checkout`.+const globParent = join(markerRoot, "glob-parent"); const globA = join(globParent, "a"); const globB = join(globParent, "b");+for (const dir of [globA, join(globB, "src")]) mkdirSync(dir, {{ recursive: true }});+writeFileSync(join(globA, ".ai-memory.toml"), '[capture]\nignore_paths = ["secrets.env"]\n'); markerFixtures.set(globA, join(globA, ".ai-memory.toml"));+writeFileSync(join(globB, ".ai-memory.toml"), 'project = "b"\n'); markerFixtures.set(globB, join(globB, ".ai-memory.toml"));+for (const [payload, cwd, label] of [[bash("cat ../*/secrets.env"), globB, "glob-sibling"], [bash("cat */secrets.env"), globParent, "glob-parent"], [bash("cat ../{{a,c}}/secrets.env"), globB, "glob-brace"], [bash("cat ../[a]/secrets.env"), globB, "glob-bracket"], [bash("cat ../**/secrets.env"), globB, "glob-globstar"], [bash("cat ../{{a/x,c}}/secrets.env"), globB, "glob-spanning"], [{{ tool: "grep", args: {{ pattern: "KEY", path: "../a/secrets.env" }} }}, globB, "search-path"], [{{ tool: "glob", args: {{ pattern: "../a/*.env" }} }}, globB, "search-pattern"], [{{ tool: "grep", args: {{ pattern: "KEY", include: "*/secrets.env" }} }}, globParent, "search-filter"], [{{ tool: "apply_patch", args: {{ patchText: "*** Begin Patch\n*** Update File: ../a/secrets.env\n*** End Patch" }} }}, globB, "patch-header"], [{{ tool: "read", args: {{}} }}, globParent, "unreadable-target"]] as [Record<string, unknown>, string, string][]) {{ const result = capturePolicy({{ ...payload, output: privateBody }}, cwd); check(result.disposition === "drop" || (result.disposition === "metadata-only" && !JSON.stringify(result.payload).includes(privateBody)), label); }}+for (const [payload, cwd, label] of [[bash("cat ../*/public.md"), globB, "glob-public"], [bash("ls src/*"), globB, "glob-own"], [{{ tool: "grep", args: {{ pattern: "KEY", path: "src" }} }}, globB, "search-own"], [{{ tool: "glob", args: {{ pattern: "**/*.ts" }} }}, globB, "search-own-globstar"], [{{ tool: "grep", args: {{ pattern: "KEY", path: "b" }} }}, globParent, "search-public"], [{{ tool: "apply_patch", args: {{ patchText: "*** Begin Patch\n*** Add File: src/x.ts\n*** End Patch" }} }}, globB, "patch-own"]] as [Record<string, unknown>, string, string][]) check(capturePolicy(payload, cwd).disposition === "keep", label);// A macOS host folds case beyond ASCII and composes Unicode; mirrors `a_case_folding_host_matches_paths_without_regard_to_case`.captureFoldCase = true;for (const path of ["\u00e9crits/x.md", "\u00c9CRITS/x.md", "E\u0301crits/x.md"]) expectDecision({{ tool: "edit", args: {{ path }} }}, marker('[capture]\nignore_paths = ["\u00c9crits/**"]\n'), "drop", "file", "extracted", 1, `fold-unicode ${{JSON.stringify(path)}}`);@@ -2831,8 +2850,8 @@ check(capturePolicy(bash("echo hi"), routedChild).disposition === "drop", "serve// `config.state`, or this second case would be wrongly dropped.let allowlist_module = temp.path().join("capture-policy-allowlist-evidence.ts");let allowlist_source = format!(- r#"import {{ closeSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, statSync, writeFileSync }} from "node:fs";-import {{ dirname, join, resolve }} from "node:path";+ r#"import {{ closeSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync }} from "node:fs";+import {{ basename, dirname, join, resolve }} from "node:path";import {{ homedir }} from "node:os";const markerRoot = process.argv[2]!;@@ -2890,8 +2909,8 @@ check(markedButEmpty.disposition === "keep", "allowlist-marker-present-empty-cap// evidence, so they stay on disk for inspection after the run.let temp = tempfile::tempdir().unwrap().keep();eprintln!("capture-owner gate modules retained at {}", temp.display());- const HARNESS: &str = r#"import { closeSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, statSync, writeFileSync } from "node:fs";-import { dirname, join, resolve } from "node:path";+ const HARNESS: &str = r#"import { closeSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync } from "node:fs";+import { basename, dirname, join, resolve } from "node:path";import { homedir } from "node:os";const markerRoot = process.argv[2]!;diff --git a/crates/ai-memory-cli/src/commands/transcript_capture.rs b/crates/ai-memory-cli/src/commands/transcript_capture.rsindex 357686ac..c7dbb66d 100644--- a/crates/ai-memory-cli/src/commands/transcript_capture.rs+++ b/crates/ai-memory-cli/src/commands/transcript_capture.rs@@ -645,6 +645,55 @@ mod tests {);}+ /// A search, a directory glob or an `apply_patch` recorded here that+ /// reaches a sibling checkout's excluded file answers to that checkout's+ /// policy on import too, as in the live hook. The same tools kept to this+ /// checkout are imported whole.+ #[test]+ fn globs_and_searches_reaching_another_checkout_honor_its_policy() {+ let parent = tempfile::tempdir().unwrap();+ let (a, b) = (parent.path().join("a"), parent.path().join("b"));+ for dir in [&a, &b] {+ std::fs::create_dir_all(dir).unwrap();+ }+ std::fs::write(+ a.join(".ai-memory.toml"),+ "[capture]\nignore_paths = [\"secrets.env\"]\n",+ )+ .unwrap();+ let capture = TranscriptCapture::for_checkout(parent.path(), &b);+ let call = |tool: &str, input: Value, id: &str| {+ event(+ WorkstreamEventKind::ToolCall,+ "assistant",+ &format!("{tool}: {input}"),+ json!({"tool": tool, "tool_use_id": id}),+ )+ };+ let events = [+ call(+ "Grep",+ json!({"pattern": "KEY", "path": "../a/secrets.env"}),+ "a",+ ),+ result("secret", Some("a")),+ call("Bash", json!({"command": "cat ../*/secrets.env"}), "b"),+ result("secret", Some("b")),+ call("Glob", json!({"pattern": "../a/*.env"}), "c"),+ result("secret", Some("c")),+ call("Grep", json!({"pattern": "KEY", "path": "src"}), "d"),+ result("own", Some("d")),+ call("Bash", json!({"command": "ls src/*"}), "e"),+ result("own", Some("e")),+ ];+ assert_eq!(+ kinds(&capture.decide(&events)),+ [+ "drop", "drop", "drop", "drop", "drop", "drop", "keep", "keep", "keep", "keep"+ ]+ );+ }+/// Under allowlist capture mode the live hook emits nothing — prompts/// included — from a checkout without a marker; an import drops every/// event there. A marked checkout and the default denylist mode keep them.diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rsindex 66991975..e8024f45 100644--- a/crates/ai-memory-cli/src/marker.rs+++ b/crates/ai-memory-cli/src/marker.rs@@ -1194,7 +1194,7 @@ fn lexically_normalize(path: &Path) -> PathBuf {stack.into_iter().collect()}-fn checkout_root(start: &Path) -> Option<PathBuf> {+pub(crate) fn checkout_root(start: &Path) -> Option<PathBuf> {let mut dir = start;loop {if dir.join(".git").exists() {diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex 95f03353..fade0a00 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -603,11 +603,12 @@ impl CapturePolicy {let extracted = extract(agent, raw);let (disposition, extraction) = match self.state {PolicyState::Inactive => (CaptureDisposition::Keep, extracted.state),- // A broken marker cannot prove a shell command's arguments miss- // every ignored path, so it fails closed like a file tool, readable- // or not.+ // A broken marker cannot prove a shell command's arguments, or a+ // search's matches, miss every ignored path, so it fails closed+ // like a file tool, readable or not.PolicyState::Invalidif extracted.family == ToolFamily::File+ || extracted.family == ToolFamily::SearchList|| extracted.shell|| extracted.output_reader =>{@@ -955,6 +956,15 @@ struct Extracted<'a> {/// locate where the tool ran; capture policy drops search output under an/// active marker regardless of it.search_paths: Option<Vec<String>>,+ /// Every place a search/list tool reads from, for the cross-checkout+ /// lookup: its directory and file arguments (`roots`) and the glob+ /// arguments that select below them (`patterns`). `None` when one of+ /// them is not a string, so the lookup cannot be made.+ search_scope: Option<SearchScope>,+ /// The files an `apply_patch` call's patch text names, for the+ /// cross-checkout lookup only; the call's own decision does not read+ /// them.+ patch_paths: Option<Vec<String>>,/// The paths are globs (Gemini CLI `read_many_files`), not literal files.globs: bool,/// The tool reads back output of an earlier command (`BashOutput`).@@ -1028,6 +1038,12 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted<'_> {let search_paths = (family == ToolFamily::SearchList).then(|| args.and_then(|value| direct_paths(value.as_object()?))).flatten();+ let search_scope = (family == ToolFamily::SearchList)+ .then(|| search_scope(name, args))+ .flatten();+ let patch_paths = (family == ToolFamily::File && paths.is_none())+ .then(|| args.and_then(|value| patch_paths(name, value)))+ .flatten();// OpenCode `bash`, OpenClaw `exec` and Codex `shell` run in `workdir`// when given, Gemini CLI `run_shell_command` in `dir_path` (`directory`// before it was renamed), and Antigravity `run_command` in `Cwd`, so@@ -1075,6 +1091,8 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted<'_> {shell,workdir,search_paths,+ search_scope,+ patch_paths,globs: name.eq_ignore_ascii_case("read_many_files"),output_reader: reads_earlier_output(name),powershell: name.eq_ignore_ascii_case("powershell"),@@ -1386,18 +1404,22 @@ fn native_path(candidate: Normalized) -> String {/// tool call.pub const MAX_LOOKUP_LOCATIONS: usize = 4_096;-/// The absolute locations a recognized file or shell tool call names, in-/// their own separator style, for a hook client to find the marker that-/// governs each: every file-tool target, and every shell argument that names-/// a path (one with a separator, after `~/` expansion) resolved from the-/// tool's `workdir` or the `cwd`, plus that directory itself.+/// The absolute locations a recognized file, search/list or shell tool call+/// names, in their own separator style, for a hook client to find the marker+/// that governs each: every file-tool target (for `apply_patch`, the files its+/// patch names), every directory, file and path-like glob argument of a+/// search/list tool, and every shell argument that names a path (one with a+/// separator, after `~/` expansion) resolved from the tool's `workdir` or the+/// `cwd`, plus that directory itself.////// A checkout's `ignore_paths` protect its files wherever the call is made/// from, so a client applies the policy of each location's own marker as-/// well as the event's (`cat ../other-checkout/secret.env`). Search/list and-/// unknown tools yield nothing; their policy is the event's. `None` when the-/// call names more than [`MAX_LOOKUP_LOCATIONS`] distinct locations, since-/// nothing then proves which markers govern it.+/// well as the event's (`cat ../other-checkout/secret.env`). A location may+/// hold glob syntax; [`glob_walk`] says how to follow it. Unknown tools yield+/// nothing; their policy is the event's. `None` when nothing proves which+/// markers govern the call: a file tool whose targets cannot be read or+/// resolved, a search/list argument that is not a string, or more than+/// [`MAX_LOOKUP_LOCATIONS`] distinct locations.pub fn capture_lookup_locations(agent: AgentKind,raw: &Value,@@ -1422,8 +1444,31 @@ pub fn capture_lookup_locations(};match (extracted.family, extracted.command.as_ref()) {(ToolFamily::File, _) => {- for path in extracted.paths.iter().flatten() {- push(normalize_candidate(path, cwd))?;+ let paths = extracted+ .paths+ .as_ref()+ .or(extracted.patch_paths.as_ref())?;+ for path in paths {+ push(Some(normalize_candidate(path, cwd)?))?;+ }+ }+ (ToolFamily::SearchList, _) => {+ let scope = extracted.search_scope.as_ref()?;+ let mut roots = Vec::new();+ for root in &scope.roots {+ let root = normalize_candidate(root, cwd)?;+ roots.push(native_path(root.clone()));+ push(Some(root))?;+ }+ if roots.is_empty() {+ roots.push(cwd.to_owned());+ }+ // A glob argument without a separator only selects names below+ // its root, which the root's own lookup already covers.+ for pattern in scope.patterns.iter().filter(|p| p.contains(['/', '\\'])) {+ for root in &roots {+ push(Some(normalize_candidate(pattern, root)?))?;+ }}}(ToolFamily::NonFile, Some(command)) => {@@ -1445,6 +1490,235 @@ pub fn capture_lookup_locations(Some(locations)}+/// Where a search/list tool reads: see [`Extracted::search_scope`].+#[derive(Default)]+struct SearchScope {+ roots: Vec<String>,+ patterns: Vec<String>,+}++/// A search/list tool's directory and file arguments, and its glob+/// arguments: a glob tool's `pattern` (Claude Code `Glob`, Gemini CLI `glob`,+/// Antigravity `find_by_name`), and the file filters of a content search+/// (`glob`, `include`, `file_pattern`, `Includes`). A grep `pattern` is a+/// regular expression, not a path, and is left out. `None` when one of them+/// is present but not a string (or, for a filter, a list of strings).+fn search_scope(name: &str, args: Option<&Value>) -> Option<SearchScope> {+ let object = match args {+ None | Some(Value::Null) => return Some(SearchScope::default()),+ Some(value) => value.as_object()?,+ };+ let mut scope = SearchScope::default();+ if object+ .keys()+ .any(|key| DIRECT_PATH_KEYS.contains(&key.as_str()) || key == "paths")+ {+ scope.roots = direct_paths(object)?;+ }+ for key in [+ "dir_path",+ "directory",+ "DirectoryPath",+ "SearchDirectory",+ "SearchPath",+ ] {+ if let Some(value) = object.get(key) {+ scope.roots.push(value.as_str()?.to_owned());+ }+ }+ let glob_tool = matches!(+ name.to_ascii_lowercase().as_str(),+ "glob" | "find" | "find_by_name"+ );+ let pattern_keys: &[&str] = if glob_tool {+ &[+ "pattern",+ "Pattern",+ "glob",+ "include",+ "file_pattern",+ "Includes",+ ]+ } else {+ &["glob", "include", "file_pattern", "Includes"]+ };+ for key in pattern_keys {+ match object.get(*key) {+ None => {}+ Some(Value::String(pattern)) => scope.patterns.push(pattern.clone()),+ Some(Value::Array(patterns)) => {+ for pattern in patterns {+ scope.patterns.push(pattern.as_str()?.to_owned());+ }+ }+ Some(_) => return None,+ }+ }+ let total = scope.roots.len().checked_add(scope.patterns.len())?;+ (total <= MAX_CAPTURE_CANDIDATES+ && scope.roots.iter().chain(&scope.patterns).all(|path| {+ !path.trim().is_empty() && path.chars().count() <= MAX_CANDIDATE_PATH_CHARS+ }))+ .then_some(scope)+}++/// The files an `apply_patch` patch names in its `*** Add File:`,+/// `*** Update File:`, `*** Delete File:` and `*** Move to:` headers, from+/// the patch text itself or the `command`, `patch`, `patchText` or `input`+/// field that holds it. `None` when no header names a file.+fn patch_paths(name: &str, args: &Value) -> Option<Vec<String>> {+ if !matches!(name.to_ascii_lowercase().as_str(), "apply_patch" | "patch") {+ return None;+ }+ let text = match args {+ Value::String(text) => text.as_str(),+ Value::Object(object) => ["command", "patch", "patchText", "input"]+ .iter()+ .find_map(|key| object.get(*key)?.as_str())?,+ _ => return None,+ };+ let mut paths = Vec::new();+ for line in text.lines() {+ let Some(path) = [+ "*** Add File:",+ "*** Update File:",+ "*** Delete File:",+ "*** Move to:",+ ]+ .iter()+ .find_map(|header| line.strip_prefix(header)) else {+ continue;+ };+ let path = path.trim();+ if path.is_empty() || path.chars().count() > MAX_CANDIDATE_PATH_CHARS {+ return None;+ }+ if paths.len() == MAX_CAPTURE_CANDIDATES {+ return None;+ }+ paths.push(path.to_owned());+ }+ (!paths.is_empty()).then_some(paths)+}++/// How a hook client reaches every directory a [`capture_lookup_locations`]+/// location could name when it holds glob syntax (`*`, `?`, a `[` class, a+/// `{` brace, a `(` group).+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum GlobWalk {+ /// No glob syntax: look the location up as a path.+ Literal,+ /// Look `root` (the leading segments without glob syntax, in the+ /// location's own separator style) up as a path, then follow `steps`+ /// through the directories below it.+ Walk {+ /// The deepest directory the glob cannot leave.+ root: String,+ /// One step per remaining segment; [`GlobStep::AnyDepth`] ends it.+ steps: Vec<GlobStep>,+ },+ /// Syntax a walk cannot follow: a brace or group that spans a separator,+ /// or an alternative of `..` or `~…` inside one, which leaves the root.+ /// Nothing proves which markers govern it.+ Unprovable,+}++/// One segment of a [`GlobWalk::Walk`].+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum GlobStep {+ /// A segment without glob syntax: that child directory.+ Named(String),+ /// A segment whose only glob syntax is `*` and `?`: every child directory+ /// whose name it matches, compared without regard to ASCII case.+ Matching(String),+ /// A segment with a class, brace or group: every child directory.+ Any,+ /// A `**` segment: every directory at any depth below.+ AnyDepth,+}++/// Whether a directory entry named `name` is one [`GlobStep::Matching`]+/// reaches.+#[must_use]+pub fn glob_segment_matches(segment: &str, name: &str) -> bool {+ glob_match(segment, name, None, true)+}++/// How to follow a lookup location that may hold glob syntax. A segment with+/// syntax the matcher does not evaluate is read as matching any name, which+/// only ever adds directories.+#[must_use]+pub fn glob_walk(location: &str) -> GlobWalk {+ // A parameter expansion's braces are not a brace expansion; the shell+ // split also reads the word with each default in its place.+ if location.contains("${") {+ return GlobWalk::Literal;+ }+ let syntax = |segment: &str| segment.contains(['*', '?', '[', '{', '(']);+ let flavor = flavor_of(location);+ let Ok(normalized) = normalize_root(location) else {+ return GlobWalk::Literal;+ };+ // The root itself (`/`, `C:/`, `//server/share`) is never a glob.+ let (root, tail) = if let Some(rest) = normalized.strip_prefix("//") {+ let mut parts = rest.splitn(3, '/');+ let server = parts.next().unwrap_or_default();+ let share = parts.next().unwrap_or_default();+ (+ format!("//{server}/{share}"),+ parts.next().unwrap_or_default().to_owned(),+ )+ } else if valid_drive_prefix(&normalized) {+ (normalized[..3].to_owned(), normalized[3..].to_owned())+ } else {+ ("/".to_owned(), normalized[1..].to_owned())+ };+ let segments: Vec<&str> = tail.split('/').filter(|part| !part.is_empty()).collect();+ let Some(first) = segments.iter().position(|segment| syntax(segment)) else {+ return GlobWalk::Literal;+ };+ let mut steps = Vec::new();+ for segment in &segments[first..] {+ if !syntax(segment) {+ steps.push(GlobStep::Named((*segment).to_owned()));+ continue;+ }+ let balanced = |open: char, close: char| {+ segment.matches(open).count() == segment.matches(close).count()+ };+ // A brace or group alternative of `..` or `~…` leaves the root.+ let leaves = segment+ .split(['{', '}', ',', '(', ')', '|', '@', '!', '+'])+ .any(|piece| piece == ".." || piece.starts_with('~'));+ if leaves || !balanced('{', '}') || !balanced('(', ')') {+ return GlobWalk::Unprovable;+ }+ if segment.contains("**") {+ steps.push(GlobStep::AnyDepth);+ break;+ }+ steps.push(if segment.contains(['[', '{', '(']) {+ GlobStep::Any+ } else {+ GlobStep::Matching((*segment).to_owned())+ });+ }+ let mut root_path = root;+ for segment in &segments[..first] {+ if !root_path.ends_with('/') {+ root_path.push('/');+ }+ root_path.push_str(segment);+ }+ GlobWalk::Walk {+ root: native_path(Normalized {+ path: root_path,+ flavor,+ }),+ steps,+ }+}+/// The directory a shell tool's relative arguments resolve from: its own/// `workdir` (absolute, or relative to the `cwd`), else the `cwd`.fn command_base(workdir: Option<&str>, cwd: &str) -> String {@@ -1456,17 +1730,20 @@ fn command_base(workdir: Option<&str>, cwd: &str) -> String {}}+/// The single-path fields of the file and search/list tool schemas.+const DIRECT_PATH_KEYS: [&str; 7] = [+ "file_path",+ "filePath",+ "path",+ "absolute_path",+ "AbsolutePath",+ "notebook_path",+ "TargetFile",+];+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",- "TargetFile",- ] {+ for key in DIRECT_PATH_KEYS {if let Some(value) = object.get(key) {if paths.len() == MAX_CAPTURE_CANDIDATES {return None;@@ -4117,13 +4394,54 @@ mod tests {),Some(vec!["C:\\a\\x.md".to_owned()]));- // Search/list and unknown tools stay with the event's own policy.+ // A search/list tool names its root and the path-like globs below it;+ // a grep pattern is a regular expression and names nothing.+ assert_eq!(+ locations(+ &json!({"tool_name": "Grep", "tool_input": {"path": "../a", "pattern": "x/y", "glob": "*.env"}})+ ),+ Some(vec!["/work/a".to_owned()])+ );+ assert_eq!(+ locations(&json!({"tool_name": "Glob", "tool_input": {"pattern": "../a/*.env"}})),+ Some(vec!["/work/a/*.env".to_owned()])+ );+ assert_eq!(+ locations(+ &json!({"tool_name": "grep_search", "tool_input": {"dir_path": "/work/a", "include": ["src/*.rs", "*.md"]}})+ ),+ Some(vec!["/work/a".to_owned(), "/work/a/src/*.rs".to_owned()])+ );+ assert_eq!(+ locations(&json!({"tool_name": "Grep", "tool_input": {"pattern": "x"}})),+ Some(Vec::new())+ );+ // An argument that is not a string, a file tool without readable+ // targets, and a target that cannot be resolved prove nothing.for raw in [- json!({"tool_name": "Grep", "tool_input": {"path": "../a"}}),- json!({"tool_name": "FutureTool", "tool_input": {"path": "../a/x"}}),+ json!({"tool_name": "Grep", "tool_input": {"path": 7}}),+ json!({"tool_name": "Glob", "tool_input": {"pattern": 7}}),+ json!({"tool_name": "Read", "tool_input": {}}),+ json!({"tool_name": "Read", "tool_input": {"file_path": "C:x"}}),+ json!({"tool_name": "apply_patch", "tool_input": {"command": "no headers"}}),] {- assert_eq!(locations(&raw), Some(Vec::new()));+ assert_eq!(locations(&raw), None, "{raw}");}+ // An `apply_patch` names the files its headers name.+ assert_eq!(+ locations(+ &json!({"tool_name": "apply_patch", "tool_input": {"command": "*** Begin Patch\n*** Update File: ../a/secrets.env\n*** Move to: c.md\n*** End Patch"}})+ ),+ Some(vec![+ "/work/a/secrets.env".to_owned(),+ "/work/b/c.md".to_owned()+ ])+ );+ // Unknown tools stay with the event's own policy.+ assert_eq!(+ locations(&json!({"tool_name": "FutureTool", "tool_input": {"path": "../a/x"}})),+ Some(Vec::new())+ );let many = (0..=MAX_LOOKUP_LOCATIONS).map(|index| format!("d{index}/x")).collect::<Vec<_>>()@@ -4131,6 +4449,87 @@ mod tests {assert_eq!(locations(&bash(&format!("cat {many}"))), None);}+ /// A glob location is followed from its literal root; syntax that can+ /// leave the root (a brace spanning a separator, a `..` or `~`+ /// alternative) cannot be followed.+ #[test]+ fn glob_walk_follows_every_segment_a_glob_could_pass_through() {+ assert_eq!(glob_walk("/work/a/secrets.env"), GlobWalk::Literal);+ assert_eq!(glob_walk("/work/x/${HOME:-a}/*"), GlobWalk::Literal);+ assert_eq!(+ glob_walk("/work/*/secrets.env"),+ GlobWalk::Walk {+ root: "/work".into(),+ steps: vec![+ GlobStep::Matching("*".into()),+ GlobStep::Named("secrets.env".into())+ ],+ }+ );+ assert_eq!(+ glob_walk("/work/{a,b}/[xy]/**/z/*"),+ GlobWalk::Walk {+ root: "/work".into(),+ steps: vec![GlobStep::Any, GlobStep::Any, GlobStep::AnyDepth],+ }+ );+ assert_eq!(+ glob_walk("C:\\work\\a?\\x"),+ GlobWalk::Walk {+ root: "C:\\work".into(),+ steps: vec![GlobStep::Matching("a?".into()), GlobStep::Named("x".into())],+ }+ );+ for location in [+ "/work/{a/x,b}/secrets.env",+ "/work/b/{..,c}/secrets.env",+ "/work/b/{~,c}/x",+ "/work/b/@(..|c)/x",+ "/work/b/(a/x)/y",+ ] {+ assert_eq!(glob_walk(location), GlobWalk::Unprovable, "{location}");+ }+ // A brace sequence and a backup-file glob stay walkable.+ assert!(matches!(+ glob_walk("/work/b/ad{1..3}/x"),+ GlobWalk::Walk { .. }+ ));+ assert!(matches!(glob_walk("/work/b/src/*~"), GlobWalk::Walk { .. }));+ assert!(glob_segment_matches("SEC*", "secrets"));+ assert!(!glob_segment_matches("*.env", "src"));+ }++ /// A broken marker fails a search/list tool closed, as it does a file or+ /// shell tool: nothing proves its matches miss every ignored path.+ #[test]+ fn an_invalid_policy_makes_a_search_metadata_only() {+ let policy = CapturePolicy::resolve(CaptureSource::Invalid, "/repo", None);+ for raw in [+ json!({"tool_name": "Grep", "tool_input": {"pattern": "x"}}),+ json!({"tool_name": "Glob", "tool_input": {"pattern": "*.rs"}}),+ ] {+ assert_eq!(+ policy+ .inspect(AgentKind::ClaudeCode, &raw, "/repo")+ .protocol()+ .disposition(),+ CaptureDisposition::MetadataOnly+ );+ }+ let inactive = CapturePolicy::resolve(CaptureSource::Absent, "/repo", None);+ assert_eq!(+ inactive+ .inspect(+ AgentKind::ClaudeCode,+ &json!({"tool_name": "Grep", "tool_input": {"pattern": "x"}}),+ "/repo"+ )+ .protocol()+ .disposition(),+ CaptureDisposition::Keep+ );+ }+/// Copilot CLI's runtime `view`/`create` names are file tools for that/// agent only; another agent's same-named tool stays unknown.#[test]diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex 0525eb4c..729c2b03 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -46,9 +46,9 @@ pub use assistant_capture::{};pub use capture_policy::{CaptureConfig, CaptureDecision, CaptureDisposition, CaptureMode, CapturePolicy,- CaptureProtocol, CaptureSource, ExtractionState, PolicyState, ToolFamily,+ CaptureProtocol, CaptureSource, ExtractionState, GlobStep, GlobWalk, PolicyState, ToolFamily,absolute_tool_location_paths, capture_lookup_locations, describe_invalid_capture_config,- repository_admits_capture, tool_call_payload, valid_call_id,+ glob_segment_matches, glob_walk, repository_admits_capture, tool_call_payload, valid_call_id,};pub use payload::{HookEnvelope, HookEvent, NOTIFICATION_EXCERPT_MAX_BYTES, POST_COMPACTION_EXCERPT_MAX_BYTES,diff --git a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json b/crates/ai-memory-hooks/tests/fixtures/capture-policy.jsonindex 2666e673..b40f5487 100644--- a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json+++ b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json@@ -48,7 +48,7 @@{"agent":"gemini-cli","payload":{"tool_name":"read_many_files","tool_input":{"include":["/home/me/.claude/*/-repo/s1/tool-results/*"]}},"disposition":"metadata-only","tool_family":"file","extraction_state":"extracted","path_count":1},{"agent":"open-code","payload":{"tool":"read_many_files","args":{"include":["/home/me/.claude/*/-repo/s1/tool-results/*"]}},"disposition":"metadata-only","tool_family":"file","extraction_state":"extracted","path_count":1},{"agent":"open-code","payload":{"tool":"read_many_files","args":{"include":["/tmp/pi-*"]}},"disposition":"metadata-only","tool_family":"file","extraction_state":"extracted","path_count":1},- {"agent":"open-code","payload":{"tool":"read_many_files","args":{"include":["src/*/*.rs","/tmp/*.txt"]}},"disposition":"keep","tool_family":"file","extraction_state":"extracted","path_count":2},+ {"agent":"open-code","payload":{"tool":"read_many_files","args":{"include":["src/*/*.rs","notes/*.txt"]}},"disposition":"keep","tool_family":"file","extraction_state":"extracted","path_count":2},{"agent":"openclaw","payload":{"tool":"exec","args":{"command":"wc -l <secret/a"}},"disposition":"drop","tool_family":"non-file","extraction_state":"extracted","path_count":0},{"agent":"open-code","payload":{"tool":"bash","args":{"command":"cat public/a *.md"}},"disposition":"keep","tool_family":"non-file","extraction_state":"extracted","path_count":0},{"agent":"openclaw","payload":{"tool":"exec","args":{"command":"git diff"}},"disposition":"keep","tool_family":"non-file","extraction_state":"extracted","path_count":0},@@ -346,7 +346,7 @@{"command":"ls src/*","disposition":"keep"},{"command":"cat src/*/*","disposition":"keep"},{"command":"grep -n main src/*","disposition":"keep"},- {"command":"cat /tmp/*/notes.txt","disposition":"keep"},+ {"command":"cat /scratch-absent/*/notes.txt","disposition":"keep"},{"command":"cat /tmp/claude-1000/-repo/s1/scratchpad/*.txt","disposition":"keep"},{"command":"cat /home/me/.claude/projects/-repo/*.jsonl","disposition":"keep"},{"command":"cat DOCS/ADR/1.md","fold_case":true,"disposition":"drop"},