Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(capture): keep monorepo globs whole and close more cross-checkout gaps
AkitaOnRails621f659b0825
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9ddd5750..30817733 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -48,14 +48,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0tool call made from another checkout or from an unmarked directory thatreaches one of its files, including through glob syntax in a directoryname, a search's path or file filter, or the files an `apply_patch` names.- Glob directories are followed through the directories on disk within fixed- bounds; past them, or for glob syntax that cannot be followed, the call is- metadata-only, and so is a file tool whose target cannot be read. A broken+ Glob directories outside the event's own checkout are followed through the+ directories on disk within fixed bounds of count and time; past them, or for+ glob syntax that cannot be followed, the call is metadata-only, and so is a+ file tool whose target cannot be read. A glob inside the event's own+ checkout is not walked, so ordinary monorepo commands over many packages+ (`cat packages/*/package.json`, `du -sh packages/*`) keep their output with+ or without a marker. A `..` after a `**`, a brace expansion, a zsh glob+ group, an ANSI-C escape, an indented `apply_patch` header and Hermes+ `search_files`' `file_glob` filter can no longer hide which checkout a call+ reaches. A brokenmarker makes a search metadata-only, as it does a file or shell call.Reading back a file a harness saved an earlier tool's output to(Claude Code's saved large results and background task output, OpenCode'sand Pi's truncated output files), or a glob that could match one, is- metadata-only under an active or invalid policy, like `BashOutput`. A `file:` URL's query or fragment is no longer+ metadata-only under an active or invalid policy, like `BashOutput`; an+ ordinary log glob (`tail -n 50 log/*.log`, `cat /tmp/*.log`) is not taken+ for one. A `file:` URL's query or fragment is no longerread as part of its path, a parameter default nested deeper than the matcherreads is metadata-only, and a backslash escape inside a default is read. Aquoted `~` (`git commit -m "fix ~approx"`) is no longer treated as a homediff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex 109694d2..f4916587 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -1311,9 +1311,11 @@ pub(crate) fn tool_location_routing_cwd(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.+/// syntax of one tool call's locations may cost, and how long: a hook has+/// about 200 ms in all.const MAX_GLOB_DIRECTORIES: usize = 256;-const MAX_GLOB_ENTRIES: usize = 65_536;+const MAX_GLOB_ENTRIES: usize = 32_768;+const MAX_GLOB_TIME: Duration = Duration::from_millis(50);/// 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,@@ -1325,13 +1327,16 @@ const MAX_GLOB_ENTRIES: usize = 65_536;/// 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 location with glob syntax-/// ([`glob_walk`]) is looked up from its literal root, and every directory+/// ([`glob_walk`]) is looked up from its literal root, and, when that root+/// lies outside the event's own checkout (its `.git` root), 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+/// symlink), and a `**` lists the whole subtree. A glob rooted inside the+/// event's own checkout is not walked, so a monorepo's `packages/*/x` costs+/// nothing; a checkout nested inside the event's own is not reached through+/// one. A call naming more locations, directories, entries or markers than+/// the bounds, a walk past its time budget, 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,@@ -1361,7 +1366,7 @@ pub(crate) fn foreign_capture_decision(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();+ let mut walk = GlobBudget::new(MAX_GLOB_TIME);for location in locations {let location = match glob_walk(&location) {GlobWalk::Literal => location,@@ -1417,17 +1422,41 @@ pub(crate) fn foreign_capture_decision(}/// What following one call's glob locations has cost so far.-#[derive(Default)]struct GlobBudget {directories: usize,entries: usize,+ /// Time spent since the walk started; injectable so a test can stand in+ /// for a slow filesystem.+ elapsed: Box<dyn FnMut() -> Duration>,+ limit: Duration,}impl GlobBudget {+ fn new(limit: Duration) -> Self {+ let started = std::time::Instant::now();+ Self::with_clock(limit, Box::new(move || started.elapsed()))+ }++ fn with_clock(limit: Duration, elapsed: Box<dyn FnMut() -> Duration>) -> Self {+ Self {+ directories: 0,+ entries: 0,+ elapsed,+ limit,+ }+ }++ /// Counts one more directory the glob reaches; `None` past the bound.+ fn reach(&mut self) -> Option<()> {+ self.directories += 1;+ (self.directories <= MAX_GLOB_DIRECTORIES).then_some(())+ }+/// 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.+ /// `root` itself excluded (its lookup is the caller's). Nothing when+ /// `root` lies inside the event's own `checkout`. `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,@@ -1435,6 +1464,9 @@ impl GlobBudget {checkout: Option<&Path>,) -> Option<Vec<PathBuf>> {let mut found = Vec::new();+ if checkout.is_some_and(|checkout| root.starts_with(checkout)) {+ return Some(found);+ }let mut current = vec![root.to_path_buf()];for step in steps {let mut next = Vec::new();@@ -1458,8 +1490,11 @@ impl GlobBudget {if checkout.is_some_and(|checkout| dir.starts_with(checkout)) {continue;}+ // Counted as listed: a deep tree must not cost a+ // full listing before the bound applies.let mut pending = self.child_directories(dir)?;while let Some(below) = pending.pop() {+ self.reach()?;pending.extend(self.child_directories(&below)?);next.push(below);}@@ -1467,9 +1502,8 @@ impl GlobBudget {}}for dir in &next {- self.directories += 1;- if self.directories > MAX_GLOB_DIRECTORIES {- return None;+ if !matches!(step, GlobStep::AnyDepth) {+ self.reach()?;}let marker = dir.join(ai_memory_core::repository_identity::MARKER_FILENAME);if marker.is_file() {@@ -1487,6 +1521,9 @@ impl GlobBudget {/// 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>> {+ if (self.elapsed)() > self.limit {+ return None;+ }let Ok(entries) = std::fs::read_dir(dir) else {return Some(Vec::new());};@@ -3618,6 +3655,313 @@ mod tests {}}+ /// Regression: a glob rooted inside the event's own checkout is not+ /// walked, so a monorepo with more matching directories than the walk's+ /// bounds keeps its ordinary commands whole, with or without a policy of+ /// its own (a search tool under an active policy is dropped by the search+ /// rule, not by the walk). The sibling-checkout attack still drops.+ #[tokio::test]+ async fn a_monorepo_glob_inside_the_own_checkout_is_not_walked() {+ let tmp = tempfile::tempdir().unwrap();+ let work = tmp.path().join("work");+ let mono = work.join("mono");+ let a = work.join("a");+ std::fs::create_dir_all(mono.join(".git")).unwrap();+ std::fs::create_dir_all(mono.join("log")).unwrap();+ for index in 0..300 {+ let package = mono.join("packages").join(format!("p{index}"));+ std::fs::create_dir_all(package.join("src")).unwrap();+ std::fs::write(package.join("package.json"), "{}").unwrap();+ std::fs::create_dir_all(mono.join("node_modules").join(format!("m{index}"))).unwrap();+ }+ const _: () = assert!(300 > MAX_GLOB_DIRECTORIES);+ std::fs::create_dir_all(&a).unwrap();+ std::fs::write(+ a.join(".ai-memory.toml"),+ "project = \"a\"\n[capture]\nignore_paths = [\"secrets.env\"]\n",+ )+ .unwrap();+ let event = |tool: &str, input: serde_json::Value| {+ serde_json::json!({+ "session_id": "monorepo",+ "cwd": mono,+ "tool_name": tool,+ "tool_input": input,+ "tool_response": {"stdout": "SENTINEL_MUST_NOT_BE_SPOOLED"}+ })+ };+ let bash = |command: &str| event("Bash", serde_json::json!({"command": command}));+ let shell = [+ "cat packages/*/package.json",+ "ls packages/*/src",+ "du -sh packages/*",+ "ls node_modules/*/package.json",+ "for f in packages/*/package.json; do echo $f; done",+ "tail -n 50 log/*.log",+ ];+ let searches = [+ event(+ "Glob",+ serde_json::json!({"pattern": "packages/*/package.json"}),+ ),+ event(+ "Grep",+ serde_json::json!({"pattern": "x", "path": "packages", "glob": "*/package.json"}),+ ),+ ];+ for policy in [None, Some("[capture]\nignore_paths = [\"private/**\"]\n")] {+ if let Some(text) = policy {+ std::fs::write(mono.join(".ai-memory.toml"), text).unwrap();+ }+ let label = if policy.is_some() { "active" } else { "none" };+ for (index, command) in shell.iter().enumerate() {+ let data_dir = tmp.path().join(format!("data-{label}-shell-{index}"));+ let entries = spool_one(&data_dir, "claude-code", None, &bash(command)).await;+ assert_eq!(entries.len(), 1, "{label}: {command}");+ assert!(+ entries[0].body.contains("SENTINEL_MUST_NOT_BE_SPOOLED"),+ "{label}: {command}: {}",+ entries[0].body+ );+ }+ for (index, raw) in searches.iter().enumerate() {+ let data_dir = tmp.path().join(format!("data-{label}-search-{index}"));+ let entries = spool_one(&data_dir, "claude-code", None, raw).await;+ if policy.is_some() {+ assert!(entries.is_empty(), "{label}: {raw}");+ } else {+ assert_eq!(entries.len(), 1, "{label}: {raw}");+ assert!(+ entries[0].body.contains("SENTINEL_MUST_NOT_BE_SPOOLED"),+ "{label}: {raw}: {}",+ entries[0].body+ );+ }+ }+ for (index, command) in ["cat ../*/secrets.env", "cat ../a/*.env"]+ .iter()+ .enumerate()+ {+ let data_dir = tmp.path().join(format!("data-{label}-attack-{index}"));+ let entries = spool_one(&data_dir, "claude-code", None, &bash(command)).await;+ assert!(+ entries+ .iter()+ .all(|entry| !entry.body.contains("SENTINEL_MUST_NOT_BE_SPOOLED")),+ "{label}: {command}: {entries:?}"+ );+ }+ }+ }++ /// A walk outside the event's own checkout stops, unprovable, past its+ /// directory bound (counted while a `**` lists, not after) or its time+ /// budget; under both it still finds a marker it reaches in time.+ #[test]+ fn a_glob_walk_outside_the_checkout_stops_at_its_bounds() {+ let tmp = tempfile::tempdir().unwrap();+ let wide = tmp.path().join("wide");+ for index in 0..=MAX_GLOB_DIRECTORIES {+ std::fs::create_dir_all(wide.join(format!("d{index}"))).unwrap();+ }+ let narrow = tmp.path().join("narrow");+ std::fs::create_dir_all(narrow.join("x").join("y")).unwrap();+ std::fs::write(narrow.join("x").join(".ai-memory.toml"), "").unwrap();+ let fast = || GlobBudget::with_clock(MAX_GLOB_TIME, Box::new(|| Duration::ZERO));+ assert_eq!(+ fast().markers_below(&wide, &[GlobStep::AnyDepth], None),+ None+ );+ // The bound stops a deep tree's listing early, not after all of it.+ let deep = tmp.path().join("deep");+ for outer in 0..64 {+ for inner in 0..64 {+ std::fs::create_dir_all(deep.join(format!("d{outer}/e{inner}"))).unwrap();+ }+ }+ let mut budget = fast();+ assert_eq!(+ budget.markers_below(&deep, &[GlobStep::AnyDepth], None),+ None+ );+ assert!(budget.entries < 1_024, "{}", budget.entries);+ assert_eq!(+ fast().markers_below(&narrow, &[GlobStep::AnyDepth], None),+ Some(vec![narrow.join("x").join(".ai-memory.toml")])+ );+ // Inside the event's own checkout nothing is walked at all.+ assert_eq!(+ fast().markers_below(&wide, &[GlobStep::AnyDepth], Some(tmp.path())),+ Some(Vec::new())+ );+ // A filesystem slower than the budget fails closed.+ let mut calls = 0;+ let mut slow = GlobBudget::with_clock(+ MAX_GLOB_TIME,+ Box::new(move || {+ calls += 1;+ MAX_GLOB_TIME * calls+ }),+ );+ assert_eq!(+ slow.markers_below(&narrow, &[GlobStep::AnyDepth], None),+ None+ );+ }++ /// Adversarial: syntax that builds a step out of the event's checkout+ /// reaches checkout A's policy: a `..` after a `**` (which can match no+ /// directory), a brace that builds `..`, a zsh glob group, an ANSI-C+ /// numeric escape, an indented patch header, and a Hermes `file_glob`.+ /// Controls: the same shapes that stay inside the checkout are kept.+ #[tokio::test]+ async fn constructed_parent_steps_answer_to_another_checkout() {+ let tmp = tempfile::tempdir().unwrap();+ let work = tmp.path().join("work");+ let a = work.join("a");+ let b = work.join("b");+ for dir in [&a, &b.join(".git"), &b.join("sub").join("x")] {+ 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();+ let event = |tool: &str, input: serde_json::Value| {+ serde_json::json!({+ "session_id": "constructed",+ "cwd": b,+ "tool_name": tool,+ "tool_input": input,+ "tool_response": {"stdout": "SENTINEL_MUST_NOT_BE_SPOOLED"}+ })+ };+ let bash = |command: &str| event("Bash", serde_json::json!({"command": command}));+ let attacks = [+ (+ "globstar parent",+ "claude-code",+ bash("cat ./**/../a/secrets.env"),+ ),+ (+ "globstar parent glob tool",+ "claude-code",+ event(+ "Glob",+ serde_json::json!({"pattern": "./**/../a/secrets.env"}),+ ),+ ),+ (+ "globstar parent grep filter",+ "claude-code",+ event(+ "Grep",+ serde_json::json!({"pattern": "KEY", "glob": "**/../a/secrets.env"}),+ ),+ ),+ ("brace dot", "claude-code", bash("cat .{.,x}/a/secrets.env")),+ (+ "brace empty",+ "claude-code",+ bash("cat {.,}./a/secrets.env"),+ ),+ (+ "brace twice",+ "claude-code",+ bash("cat .{.,.}/a/secrets.env"),+ ),+ (+ "brace sequence",+ "claude-code",+ bash("cat .{-..0}/a/secrets.env"),+ ),+ ("zsh group", "claude-code", bash("cat ../(a)/secrets.env")),+ (+ "zsh alternation",+ "claude-code",+ bash("cat ../(a|c)/secrets.env"),+ ),+ (+ "ansi-c hex",+ "claude-code",+ bash("cat ..$'\\x2f'a/secrets.env"),+ ),+ (+ "ansi-c octal",+ "claude-code",+ bash("cat $'\\056\\056'/a/secrets.env"),+ ),+ (+ "indented patch header",+ "codex",+ event(+ "apply_patch",+ serde_json::json!({"command": "*** Begin Patch\n*** Add File: sub/y.rs\n+y\n *** Update File: ../a/secrets.env\n+KEY\n*** End Patch"}),+ ),+ ),+ (+ "hermes file glob",+ "hermes",+ event(+ "search_files",+ serde_json::json!({"pattern": "KEY", "path": "..", "file_glob": "a/*.env"}),+ ),+ ),+ ];+ 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 = [+ (+ "own globstar parent",+ "claude-code",+ bash("cat sub/**/../README.md"),+ ),+ ("own brace", "claude-code", bash("cat {sub,lib}/README.md")),+ ("own sequence", "claude-code", bash("cat v{1..3}/README.md")),+ ("subshell", "claude-code", bash("(cd sub && ls)")),+ (+ "ansi-c own",+ "claude-code",+ bash("cat sub$'\\x2f'x/README.md"),+ ),+ (+ "indented own patch",+ "codex",+ event(+ "apply_patch",+ serde_json::json!({"command": "*** Begin Patch\n *** Add File: sub/x.rs\n+fn x() {}\n*** End Patch"}),+ ),+ ),+ (+ "hermes own file glob",+ "hermes",+ event(+ "search_files",+ serde_json::json!({"pattern": "KEY", "path": "sub", "file_glob": "x/*.rs"}),+ ),+ ),+ ];+ 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+ );+ }+ }+/// Under the default `basename` strategy the server files two/// subdirectories of one unmarked repository under two projects, so an/// import from one must not take the other's events. The same directorydiff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex b290f88a..888e54b8 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -245,7 +245,11 @@ 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;+const CAPTURE_MAX_GLOB_ENTRIES = 32768;+const CAPTURE_MAX_GLOB_MS = 50;+// Readings of one glob whose `..` follows a `**`, and words of one brace expansion; mirror `MAX_GLOBSTAR_READINGS` and `MAX_BRACE_ALTERNATIVES`.+const CAPTURE_MAX_GLOBSTAR_READINGS = 16;+const CAPTURE_MAX_BRACE_ALTERNATIVES = 64;// 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`.@@ -265,6 +269,8 @@ function captureTrimComment(line: string): string { let quote = ""; let escaped// root, and must collapse before flavor detection or it escapes every POSIX// `ignore_paths` pattern via a flavor mismatch (GHSA-vh98).function captureNormalize(path: string, windowsHost?: boolean): { path: string; windows: boolean } | undefined { const raw = windowsHost === false && path.startsWith("//") ? `/${path.replace(/^\/+/, "")}` : path; const p = raw.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 !== "/" }; }+// Every reading of a glob whose `..` steps back over a `**`, which matches no directory as well as many: the `..` then steps back from the segment before it, or the `**` stays. Undefined when the path is not usable, false past CAPTURE_MAX_GLOBSTAR_READINGS; mirrors `normalize_readings`.+function captureReadings(path: string, windowsHost?: boolean): { path: string; windows: boolean }[] | undefined | false { const raw = windowsHost === false && path.startsWith("//") ? `/${path.replace(/^\/+/, "")}` : path; const p = raw.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; let readings: string[][] = [[]]; for (const x of tail) { if (!x || x === ".") continue; const next: string[][] = []; const push = (parts: string[]) => { if (!next.some((other) => other.length === parts.length && other.every((part, i) => part === parts[i]))) next.push(parts); }; for (const parts of readings) { if (x !== "..") push([...parts, x]); else if (parts.length && parts[parts.length - 1].includes("**")) { push(parts.slice(0, -2)); push(parts); } else push(parts.slice(0, -1)); } if (next.length > CAPTURE_MAX_GLOBSTAR_READINGS) return false; readings = next; } return readings.map((out) => ({ 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; } }@@ -355,8 +361,9 @@ function captureShellCommand(args: Record<string, unknown> | undefined): string// shell knows, which makes the command unprovable. Each word carries whether a// `~` in it was outside quotes: a quoted tilde, or one in an argv element or a// quoted message, is literal, except under PowerShell, which reads `~` itself.-type CaptureSplit = { words: [string, boolean][]; opaque: boolean };-function captureShellSplit(command: string | string[], windows = false): CaptureSplit { const split: CaptureSplit = { words: [], opaque: false }; if (typeof command === "string") { split.opaque = captureUnevaluatedExpansion(command); captureNestedWords(captureMarkedWords(command), CAPTURE_MAX_SHELL_NESTING, split); const plain = windows ? captureWithoutWindowsEscapes(command) : undefined; if (plain !== undefined) captureNestedWords(captureMarkedWords(plain), CAPTURE_MAX_SHELL_NESTING, split); } else { split.opaque = command.some((item) => captureUnevaluatedExpansion(item)) || captureInlineCode(command); command.forEach((item, index) => { const script = captureShellScript(command, index); captureArgvItem(item, script, split); const plain = windows ? captureWithoutWindowsEscapes(item) : undefined; if (plain !== undefined) captureArgvItem(plain, script, split); }); } if (windows) for (const word of split.words) word[1] = true; if (split.words.some(([word, tilde]) => tilde && captureShellArguments(word).some(([argument]) => captureUnknownDirectory(argument)))) split.opaque = true; return split; }+// `expanded` holds the words of each script with such syntax as the shell expands them where that changes the directory a path names (a zsh glob group kept in its word, ANSI-C numeric escapes decoded), for the marker lookup only; mirrors `ShellWords::expanded`.+type CaptureSplit = { words: [string, boolean][]; opaque: boolean; expanded: [string, boolean][] };+function captureShellSplit(command: string | string[], windows = false): CaptureSplit { const split: CaptureSplit = { words: [], opaque: false, expanded: [] }; if (typeof command === "string") { split.opaque = captureUnevaluatedExpansion(command); if (split.opaque) split.expanded.push(...captureMarkedWords(command, true)); captureNestedWords(captureMarkedWords(command), CAPTURE_MAX_SHELL_NESTING, split); const plain = windows ? captureWithoutWindowsEscapes(command) : undefined; if (plain !== undefined) captureNestedWords(captureMarkedWords(plain), CAPTURE_MAX_SHELL_NESTING, split); } else { split.opaque = command.some((item) => captureUnevaluatedExpansion(item)) || captureInlineCode(command); for (const item of command) if (captureUnevaluatedExpansion(item)) split.expanded.push(...captureMarkedWords(item, true)); command.forEach((item, index) => { const script = captureShellScript(command, index); captureArgvItem(item, script, split); const plain = windows ? captureWithoutWindowsEscapes(item) : undefined; if (plain !== undefined) captureArgvItem(plain, script, split); }); } if (windows) for (const word of split.words) word[1] = true; if (split.words.some(([word, tilde]) => tilde && captureShellArguments(word).some(([argument]) => captureUnknownDirectory(argument)))) split.opaque = true; return split; }function captureArgvItem(item: string, script: boolean, split: CaptureSplit): void { const tokens = captureMarkedWords(item); if (tokens.length === 1 && tokens[0][0] === item) { capturePushWord(item, false, split); return; } if ([...item].length <= 256) split.words.push([item, false]); captureNestedWords(captureLiteralTildes(tokens, script), CAPTURE_MAX_SHELL_NESTING - 1, split); }// Only a script a shell runs expands a tilde; mirrors `literal_tildes`.function captureLiteralTildes(tokens: [string, boolean][], script: boolean): [string, boolean][] { return script ? tokens : tokens.map(([token]) => [token, false] as [string, boolean]); }@@ -364,7 +371,7 @@ function captureLiteralTildes(tokens: [string, boolean][], script: boolean): [stfunction captureWithoutWindowsEscapes(command: string): string | undefined { if (!/[`^]/.test(command)) return undefined; const chars = [...command]; let plain = ""; for (let i = 0; i < chars.length; i++) { if (chars[i] === "`" || chars[i] === "^") { i++; if (i < chars.length) plain += chars[i]; } else plain += chars[i]; } return plain; }function captureUnknownDirectory(argument: string): boolean { if (!argument.startsWith("~")) return false; const prefix = argument.slice(1).split(/[\/\\]/)[0]; return prefix !== "" && prefix !== "+"; }// Only a script a shell runs expands braces, classes and tildes; a quoted message or pattern does not.-function captureNestedWords(words: [string, boolean][], depth: number, split: CaptureSplit): void { const texts = words.map(([word]) => word); if (captureInlineCode(texts)) split.opaque = true; words.forEach(([word, tilde], index) => { capturePushWord(word, tilde, split); const tokens = captureMarkedWords(word); if (tokens.length === 1 && tokens[0][0] === word) return; if (depth === 0) { split.opaque = true; return; } const script = word.includes("$(") || word.includes("`") || captureShellScript(texts, index); if (script && captureUnevaluatedExpansion(word)) split.opaque = true; captureNestedWords(captureLiteralTildes(tokens, script), depth - 1, split); }); }+function captureNestedWords(words: [string, boolean][], depth: number, split: CaptureSplit): void { const texts = words.map(([word]) => word); if (captureInlineCode(texts)) split.opaque = true; words.forEach(([word, tilde], index) => { capturePushWord(word, tilde, split); const tokens = captureMarkedWords(word); if (tokens.length === 1 && tokens[0][0] === word) return; if (depth === 0) { split.opaque = true; return; } const script = word.includes("$(") || word.includes("`") || captureShellScript(texts, index); if (script && captureUnevaluatedExpansion(word)) { split.opaque = true; split.expanded.push(...captureMarkedWords(word, true)); } captureNestedWords(captureLiteralTildes(tokens, script), depth - 1, split); }); }// Also adds the POSIX reading of a word with `\o` escapes, which the shell reads as `o`, and the reading of each with every parameter default (`${X:-docs/x.md}`) replaced by its operand; a default nested deeper than the matcher reads makes the command unprovable.function capturePushWord(word: string, tilde: boolean, split: CaptureSplit): void { capturePushReading(word, tilde, split); if (!word.includes("\\")) return; const chars = [...word]; let plain = ""; for (let i = 0; i < chars.length; i++) { if (chars[i] === "\\") { i++; if (i < chars.length) plain += chars[i]; } else plain += chars[i]; } if (plain !== word) capturePushReading(plain, tilde, split); }function capturePushReading(word: string, tilde: boolean, split: CaptureSplit): void { split.words.push([word, tilde]); const operands = captureParameterOperands(word); if (operands === undefined) return; split.words.push([operands[0], tilde]); if (operands[1]) split.opaque = true; }@@ -377,8 +384,12 @@ function captureShellScript(words: string[], index: number): boolean { let flaggfunction captureShellValueOption(flag: string): boolean { return ["--rcfile","--init-file","--init-command","-C"].includes(flag) || (flag.length > 1 && (flag.startsWith("+") || (flag.startsWith("-") && !flag.startsWith("--"))) && /[oO]$/.test(flag)); }// Inline interpreter code (`python3 -c`, `node -e`, `ruby -e`, `perl -e`, `php -r`, `lua -e`, `Rscript -e`, `osascript -e`, `deno eval`) builds paths at run time; mirrors `runs_inline_code`.function captureInlineCode(words: string[]): boolean { return words.some((word, index) => { const name = captureCommandName(word); const versioned = (prefix: string) => name.startsWith(prefix) && /^[0-9.]*$/.test(name.slice(prefix.length)); if (name === "deno") return words[index + 1] === "eval"; const spec: [string, string[]] | undefined = versioned("python") || versioned("pypy") || name === "py" ? ["c", ["-W","-X","--check-hash-based-pycs"]] : versioned("perl") ? ["eE", ["-I","-M","-m"]] : versioned("ruby") ? ["e", ["-I","-r","-C","-E"]] : ["node","nodejs","bun"].includes(name) ? ["ep", ["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--input-type","--title","--env-file"]] : versioned("php") ? ["r", ["-d","-c","-z"]] : ["lua","luajit","rscript","osascript"].includes(name) ? ["e", ["-l"]] : undefined; if (!spec) return false; const [letters, values] = spec; for (let i = index + 1; i < words.length; i++) { const flag = words[i]; if (!flag.startsWith("-")) return false; if (["--eval","--print"].includes(flag) || flag.startsWith("--eval=") || flag.startsWith("--print=") || (!flag.startsWith("--") && [...flag.slice(1)].some((c) => letters.includes(c)))) return true; if (values.includes(flag)) i++; } return false; }); }-// Each word with whether it holds a `~` outside quotes and not after a backslash; mirrors `marked_shell_words`.-function captureMarkedWords(command: string): [string, boolean][] { const special = (c: string) => /\s/.test(c) || "|&;<>()`".includes(c); const chars = [...command]; const words: [string, boolean][] = []; let word = ""; let tilde = false; let inWord = false; let quote = ""; for (let i = 0; i < chars.length; i++) { const c = chars[i]; const next = chars[i + 1]; if (quote === "$") { if (c === "'") quote = ""; else if (c === "\\" && next !== undefined) { word += captureAnsiEscape(next) ?? c + next; i++; } else word += c; } else if (quote) { if (c === quote) quote = ""; else if (quote === '"' && c === "\\" && next === "\n") i++; else if (quote === '"' && c === "\\" && (next === '"' || next === "\\")) { word += next; i++; } else word += c; } else if (c === "'" || c === '"') { quote = c; inWord = true; } else if (c === "$" && (next === "'" || next === '"')) { quote = next === "'" ? "$" : '"'; i++; inWord = true; } else if (c === "\\" && next === "\n") { i++; } else if (c === "\\" && next !== undefined && (special(next) || next === "'" || next === '"' || next === "\\")) { word += next; i++; inWord = true; } else if (special(c)) { if (inWord) words.push([word, tilde]); word = ""; tilde = false; inWord = false; } else { if (c === "~" && !word.endsWith("\\")) tilde = true; word += c; inWord = true; } } if (inWord) words.push([word, tilde]); return words; }+// Each word with whether it holds a `~` outside quotes and not after a backslash; mirrors `marked_shell_words`. With `expand`, a zsh glob group stays in its word and ANSI-C numeric and control escapes are decoded; mirrors `shell_tokens`.+function captureMarkedWords(command: string, expand = false): [string, boolean][] { const special = (c: string) => /\s/.test(c) || "|&;<>()`".includes(c); const chars = [...command]; const words: [string, boolean][] = []; let word = ""; let tilde = false; let inWord = false; let quote = ""; for (let i = 0; i < chars.length; i++) { const c = chars[i]; const next = chars[i + 1]; if (quote === "$") { if (c === "'") quote = ""; else if (c === "\\" && next !== undefined) { const plain = captureAnsiEscape(next); const numeric = plain === undefined && expand ? captureAnsiNumeric(chars, i + 1) : undefined; if (plain !== undefined) { word += plain; i++; } else if (numeric) { word += numeric[0]; i = numeric[1]; } else { word += c + next; i++; } } else word += c; } else if (quote) { if (c === quote) quote = ""; else if (quote === '"' && c === "\\" && next === "\n") i++; else if (quote === '"' && c === "\\" && (next === '"' || next === "\\")) { word += next; i++; } else word += c; } else if (c === "'" || c === '"') { quote = c; inWord = true; } else if (c === "$" && (next === "'" || next === '"')) { quote = next === "'" ? "$" : '"'; i++; inWord = true; } else if (c === "\\" && next === "\n") { i++; } else if (c === "\\" && next !== undefined && (special(next) || next === "'" || next === '"' || next === "\\")) { word += next; i++; inWord = true; } else if (c === "(" && expand && (!inWord || !/[$=]$/.test(word)) && captureGlobGroup(chars, i, inWord) !== undefined) { const end = captureGlobGroup(chars, i, inWord)!; word += chars.slice(i, end + 1).join(""); i = end; inWord = true; } else if (special(c)) { if (inWord) words.push([word, tilde]); word = ""; tilde = false; inWord = false; } else { if (c === "~" && !word.endsWith("\\")) tilde = true; word += c; inWord = true; } } if (inWord) words.push([word, tilde]); return words; }+// The index of the `)` closing the zsh glob group `(` opens at `open`: inside a word, or at a word's start when a word character follows; undefined for a subshell or when whitespace, a quote, an escape or another operator comes first. Mirrors `glob_group`.+function captureGlobGroup(chars: string[], open: number, inWord: boolean): number | undefined { let depth = 0; for (let i = open; i < chars.length; i++) { const c = chars[i]; if (/\s/.test(c) || "'\"\\;&<>`".includes(c)) return undefined; if (c === "(") depth++; else if (c === ")" && --depth === 0) { const next = chars[i + 1]; return inWord || (next !== undefined && !/\s/.test(next) && !"|&;<>()`".includes(next)) ? i : undefined; } } return undefined; }+// A numeric or control ANSI-C escape whose letter or first digit is at `at` (`\xHH`, `\uHHHH`, `\UHHHHHHHH`, `\NNN`, `\cX`): the character and the index of its last source character, or undefined. Mirrors `ansi_c_numeric_escape`.+function captureAnsiNumeric(chars: string[], at: number): [string, number] | undefined { const escape = chars[at]; if (escape === "c") { const control = chars[at + 1]; return control !== undefined && control.charCodeAt(0) < 128 ? [String.fromCharCode(control.charCodeAt(0) & 0x1f), at + 1] : undefined; } const shape = escape === "x" ? [16, 2] : escape === "u" ? [16, 4] : escape === "U" ? [16, 8] : /^[0-7]$/.test(escape ?? "") ? [8, 2] : undefined; if (!shape) return undefined; const [radix, most] = shape; const digit = radix === 16 ? /^[0-9A-Fa-f]$/ : /^[0-7]$/; let value = radix === 8 ? Number(escape) : 0; let end = at; for (let n = 0; n < most && digit.test(chars[end + 1] ?? ""); n++) { end++; value = value * radix + parseInt(chars[end], radix); } if (radix === 16 && end === at) return undefined; return value <= 0x10ffff && !(value >= 0xd800 && value <= 0xdfff) ? [String.fromCodePoint(value), end] : undefined; }// `$'…'` escapes; numeric and control escapes stay as written. Mirrors `ansi_c_escape`.function captureAnsiEscape(escape: string): string | undefined { const decoded: Record<string, string> = { a: "\u0007", b: "\b", e: "\u001b", E: "\u001b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v", "\\": "\\", "'": "'", '"': '"', "?": "?" }; return Object.prototype.hasOwnProperty.call(decoded, escape) ? decoded[escape] : undefined; }// Whether an unquoted word holds syntax lexical matching does not evaluate: a brace expansion (`{a,b}`, `{1..3}`), a bracket class (`[ab]`, `[]a]`), a zsh glob group or extglob (`docs/(a|b)`, `(a|b)/x`), or an ANSI-C numeric/control escape; mirrors `has_unevaluated_expansion`.@@ -391,31 +402,36 @@ function captureGitObjectPath(word: string): string | undefined { if (word.start// Lexical only, like the native hook: nothing is expanded or executed, so// variables, command substitution, and `cd` state are not followed. A tool's// own `workdir` replaces the event cwd for relative arguments.-function captureMatchCommand(words: [string, boolean][], config: CaptureConfig, workdir?: string): { match: boolean | undefined; spool: boolean } { const budget = { work: 0 }; const home = homedir(); const base = captureBase(config, workdir); let spool = false; for (const [word, tilde] of words) for (const [argument, fromRoot] of captureShellArguments(word)) { const expanded = captureExpandTilde(argument, tilde, home, base); if ([...expanded].length > CAPTURE_MAX_PATH_CHARS) continue; const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(expanded); for (const root of fromRoot && !absolute && config.root ? [base, config.root] : [base]) { if (!absolute && !root) continue; const candidate = captureNormalize(absolute ? expanded : captureJoin(root, expanded), config.windowsHost); if (!candidate) continue; if (captureOutputSpool(candidate.path)) spool = true; const match = captureMatchCandidate(candidate, false, config, budget); if (match !== false) return { match, spool }; } } return { match: false, spool }; }+function captureMatchCommand(words: [string, boolean][], config: CaptureConfig, workdir?: string): { match: boolean | undefined; spool: boolean } { const budget = { work: 0 }; const home = homedir(); const base = captureBase(config, workdir); let spool = false; for (const [word, tilde] of words) for (const [argument, fromRoot] of captureShellArguments(word)) { const expanded = captureExpandTilde(argument, tilde, home, base); if ([...expanded].length > CAPTURE_MAX_PATH_CHARS) continue; const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(expanded); for (const root of fromRoot && !absolute && config.root ? [base, config.root] : [base]) { if (!absolute && !root) continue; const readings = captureReadings(absolute ? expanded : captureJoin(root, expanded), config.windowsHost); if (readings === false) return { match: undefined, spool }; if (!readings) continue; for (const candidate of readings) { if (captureOutputSpool(candidate.path)) spool = true; const match = captureMatchCandidate(candidate, false, config, budget); if (match !== false) return { match, spool }; } } } return { match: false, spool }; }// The directory a shell tool's relative arguments resolve from; mirrors `command_base`.function captureBase(config: CaptureConfig, workdir?: string): string { return workdir === undefined ? config.base : /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(workdir) ? workdir : config.base && captureJoin(config.base, workdir); }// A leading unquoted `~/` (PowerShell `~\`) is home and `~+` the working directory; mirrors `expand_tilde`.function captureExpandTilde(argument: string, tilde: boolean, home: string, base: string): string { return !tilde ? argument : /^~[\/\\]/.test(argument) ? captureJoin(home, argument.slice(2)) : argument === "~+" ? base : argument.startsWith("~+/") && base ? captureJoin(base, argument.slice(3)) : argument; }// A harness's saved copy of an earlier tool's output, read back like `BashOutput`: Claude Code `~/.claude/projects/<project>/<session>/tool-results/<id>.txt` and `<tmp>/claude-<uid>/<project>/<session>/tasks/<id>.output`, OpenCode `<data>/opencode/tool-output/tool_<id>`, Pi `<tmp>/pi-bash-<id>.log`. A glob segment fits a named one when the two share a match, and at least one fitting segment must spell literal text; mirrors `output_spool`.-function captureOutputSpool(path: string): boolean { const segments = path.split("/").filter(Boolean).map((segment) => segment.replace(/[A-Z]/g, (c) => c.toLowerCase())); const file = segments.pop(); if (file === undefined) return false; const fits = (segment: string, shape: string) => captureGlobsIntersect([...segment], [...shape]); const named = (...parts: string[]) => parts.some((part) => /[^*?]/.test(part)); const count = segments.length; let claudeResults = false; for (let i = 1; i < count && !claudeResults; i++) { const claude = segments[i - 1]; const projects = segments[i]; if (fits(claude, "*claude*") && fits(projects, "projects")) claudeResults = segments.slice(i + 1).some((results) => fits(results, "tool-results") && named(claude, projects, results)); } const parent = segments[count - 1]; const claudeTask = count > 0 && fits(parent, "tasks") && fits(file, "*.output") && segments.some((claude) => fits(claude, "claude*") && named(parent, file, claude)); const opencode = count >= 2 && fits(segments[count - 2], "opencode") && fits(parent, "tool-output") && named(segments[count - 2], parent); const pi = fits(file, "pi-bash-*.log") && named(file); return claudeResults || claudeTask || opencode || pi; }+function captureOutputSpool(path: string): boolean { const segments = path.split("/").filter(Boolean).map((segment) => segment.replace(/[A-Z]/g, (c) => c.toLowerCase())); const file = segments.pop(); if (file === undefined) return false; const fits = (segment: string, shape: string) => captureGlobsIntersect([...segment], [...shape]); const named = (...parts: [string, string][]) => parts.some(([part, word]) => captureSpells(part, word)); const count = segments.length; let claudeResults = false; for (let i = 1; i < count && !claudeResults; i++) { const claude = segments[i - 1]; const projects = segments[i]; if (fits(claude, "*claude*") && fits(projects, "projects")) claudeResults = segments.slice(i + 1).some((results) => fits(results, "tool-results") && named([claude, "claude"], [projects, "projects"], [results, "tool-results"])); } const parent = segments[count - 1]; const claudeTask = count > 0 && fits(parent, "tasks") && fits(file, "*.output") && segments.some((claude) => fits(claude, "claude*") && named([parent, "tasks"], [file, ".output"], [claude, "claude"])); const opencode = count >= 2 && fits(segments[count - 2], "opencode") && fits(parent, "tool-output") && named([segments[count - 2], "opencode"], [parent, "tool-output"]); const pi = fits(file, "pi-bash-*.log") && named([file, "pi-bash-"]); return claudeResults || claudeTask || opencode || pi; }+// Whether a one-segment glob spells part of `word` in literal text: a run between wildcards sharing three characters in a row with it; mirrors `spells`.+function captureSpells(segment: string, word: string): boolean { const needed = Math.min([...word].length, 3); return segment.split(/[*?]/).some((run) => { const chars = [...run]; for (let i = 0; i + needed <= chars.length; i++) if (word.includes(chars.slice(i, i + needed).join(""))) return true; return false; }); }// Whether two one-segment globs over `*` and `?` match a common string; mirrors `globs_intersect`.function captureGlobsIntersect(left: string[], right: string[]): boolean { const common = Array.from({ length: left.length + 1 }, () => new Array<boolean>(right.length + 1).fill(false)); common[left.length][right.length] = true; for (let i = left.length; i >= 0; i--) for (let j = right.length; j >= 0; j--) { if (i === left.length && j === right.length) continue; common[i][j] = left[i] === "*" ? common[i + 1][j] || (j < right.length && common[i][j + 1]) : right[j] === "*" ? common[i][j + 1] || (i < left.length && common[i + 1][j]) : i < left.length && j < right.length ? (left[i] === "?" || right[j] === "?" || left[i] === right[j]) && common[i + 1][j + 1] : false; } return common[0][0]; }// Gemini CLI `read_many_files` globs expand case-insensitively with `**`// recursing to any depth: a literal path matches like a file tool's, a glob// drops when it could expand into an ignored path, and glob syntax the matcher// cannot evaluate (classes, braces, extglobs, negation) fails closed.-function 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 captureMatchGlobs(paths: string[], config: CaptureConfig): boolean | undefined { const budget = { work: 0 }; for (const path of paths) { if (/[\[\]{}()!]/.test(path)) return undefined; const readings = captureReadings(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(path) ? path : captureJoin(config.base, path), config.windowsHost); if (!readings) return undefined; for (const candidate of readings) { const match = captureMatchCandidate(candidate, 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; 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; }+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","file_glob","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; }+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 trimmed = line.trimStart(); const header = ["*** Add File:","*** Update File:","*** Delete File:","*** Move to:"].find((h) => trimmed.startsWith(h)); if (!header) continue; const path = trimmed.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 (one a brace expansion builds included), 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; const leaves = (text: string) => text.split(/[{},()|@!+]/).some((piece) => piece === ".." || piece.startsWith("~")); const alternatives = segment.includes("{") ? captureBraceAlternatives(segment) : []; if (leaves(segment) || alternatives === undefined || alternatives.some((alternative) => /[\/\\]/.test(alternative) || leaves(alternative)) || 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 }; }+// Every word a brace expansion makes of `text` (a comma list or an integer or single-character sequence, nested and repeated); any other `{…}` stays. Undefined past CAPTURE_MAX_BRACE_ALTERNATIVES; mirrors `brace_alternatives`.+function captureBraceAlternatives(text: string): string[] | undefined { if (text.split("{").length - 1 > CAPTURE_MAX_BRACE_ALTERNATIVES) return undefined; const words: string[] = []; const sequence = (body: string): string[] | null | undefined => { const parts = body.split(".."); if (parts.length < 2 || parts.length > 3) return null; let step = 1; if (parts.length === 3) { if (!/^[+-]?\d+$/.test(parts[2])) return null; step = Math.max(Math.abs(Number(parts[2])), 1); } const integer = (part: string) => /^[+-]?\d+$/.test(part); let from: number; let to: number; let numeric: boolean; if (integer(parts[0]) && integer(parts[1])) { from = Number(parts[0]); to = Number(parts[1]); numeric = true; } else { const a = [...parts[0]]; const b = [...parts[1]]; if (a.length !== 1 || b.length !== 1) return null; from = a[0].codePointAt(0)!; to = b[0].codePointAt(0)!; numeric = false; } const count = Math.floor(Math.abs(to - from) / step) + 1; if (count > CAPTURE_MAX_BRACE_ALTERNATIVES) return undefined; const out: string[] = []; for (let i = 0, value = from; i < count; i++, value += from <= to ? step : -step) out.push(numeric ? String(value) : String.fromCodePoint(value)); return out; }; const expand = (chars: string[]): boolean => { for (let open = 0; open < chars.length; open++) { if (chars[open] !== "{") continue; let depth = 0; let close = -1; const commas: number[] = []; for (let i = open; i < chars.length; i++) { if (chars[i] === "{") depth++; else if (chars[i] === "}") { depth--; if (depth === 0) { close = i; break; } } else if (chars[i] === "," && depth === 1) commas.push(i); } if (close < 0) continue; let pieces: string[][]; if (!commas.length) { const words = sequence(chars.slice(open + 1, close).join("")); if (words === undefined) return false; if (words === null) continue; pieces = words.map((word) => [...word]); } else { pieces = []; let start = open + 1; for (const end of [...commas, close]) { pieces.push(chars.slice(start, end)); start = end + 1; } } for (const piece of pieces) if (!expand([...chars.slice(0, open), ...piece, ...chars.slice(close + 1)])) return false; return true; } if (words.length === CAPTURE_MAX_BRACE_ALTERNATIVES) return false; words.push(chars.join("")); return true; }; return expand([...text]) ? words : undefined; }+// The marker files of every directory `steps` reach below `root` (root excluded), never following a symlink; nothing when `root` lies inside `checkout`, and a "**" below it is not listed. Undefined past the directory or entry bounds (a "**" counts directories as it lists them) or the time budget; mirrors `GlobBudget::markers_below`.+type CaptureGlobBudget = { dirs: number; entries: number; deadline: number; now: () => number };+function captureMarkersBelow(root: string, steps: string[], checkout: string | undefined, budget: CaptureGlobBudget): string[] | undefined { const inside = (dir: string) => checkout !== undefined && dir.startsWith(checkout) && (dir.length === checkout.length || /[\\/]/.test(dir[checkout.length]) || /[\\/]$/.test(checkout)); if (inside(root)) return []; const children = (dir: string): string[] | undefined => { if (budget.now() > budget.deadline) return 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 (inside(dir)) continue; const pending = children(dir); if (!pending) return undefined; while (pending.length) { const below = pending.pop()!; if (++budget.dirs > CAPTURE_MAX_GLOB_DIRECTORIES) return undefined; 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 (step !== "**" && ++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@@ -435,10 +451,10 @@ 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.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"; }+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, config); if (match !== false) return match ? "drop" : "metadata-only"; return tool.paths.some((p) => { const readings = captureReadings(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p), config.windowsHost); return !!readings && readings.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 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)); }+// 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, when that root lies outside the event's own checkout, every directory it could pass through is checked for a marker of its own; a glob whose `..` follows a `**` is looked up in every reading. 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>(); let overflow = false; const add = (path: string, base: string): string[] | undefined => { const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(path); if (!absolute && !base) return undefined; const readings = captureReadings(absolute ? path : captureJoin(base, path), config.windowsHost); if (readings === false) { overflow = true; return undefined; } if (!readings) return undefined; return readings.map((candidate) => { 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 found = add(root, config.base); if (found === undefined) return invalid; roots.push(...found); } 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(); const split = captureShellSplit(tool.command, tool.powershell || config.windowsHost); for (const [word, tilde] of [...split.words, ...split.expanded]) for (const [argument] of captureShellArguments(word)) { const expanded = captureExpandTilde(argument, tilde, home, base); if (/[\/\\]/.test(expanded)) add(expanded, base); } } if (overflow || locations.size > CAPTURE_MAX_LOOKUP_LOCATIONS) return invalid; const directories = new Map<string, string | undefined>(); const markers: string[] = []; const checkout = captureCheckoutRoot(cwd); const budget: CaptureGlobBudget = { dirs: 0, entries: 0, deadline: Date.now() + CAPTURE_MAX_GLOB_MS, now: Date.now }; 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 !== "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 }; }@@ -2737,6 +2753,31 @@ writeFileSync(join(globA, ".ai-memory.toml"), '[capture]\nignore_paths = ["secrewriteFileSync(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 glob rooted inside the event's own checkout is not walked, so a monorepo with more matching directories than the walk's bounds keeps its commands; the sibling attack still drops. Mirrors `a_monorepo_glob_inside_the_own_checkout_is_not_walked`.+const mono = join(markerRoot, "mono-work", "mono"); const monoA = join(markerRoot, "mono-work", "a");+for (const dir of [join(mono, ".git"), join(mono, "log"), monoA]) mkdirSync(dir, {{ recursive: true }});+for (let i = 0; i < 300; i++) {{ mkdirSync(join(mono, "packages", `p${{i}}`, "src"), {{ recursive: true }}); writeFileSync(join(mono, "packages", `p${{i}}`, "package.json"), "{{}}"); mkdirSync(join(mono, "node_modules", `m${{i}}`), {{ recursive: true }}); }}+writeFileSync(join(monoA, ".ai-memory.toml"), '[capture]\nignore_paths = ["secrets.env"]\n'); markerFixtures.set(monoA, join(monoA, ".ai-memory.toml"));+for (const policy of [undefined, '[capture]\nignore_paths = ["private/**"]\n']) {{+ if (policy) {{ writeFileSync(join(mono, ".ai-memory.toml"), policy); markerFixtures.set(mono, join(mono, ".ai-memory.toml")); }}+ for (const command of ["cat packages/*/package.json", "ls packages/*/src", "du -sh packages/*", "ls node_modules/*/package.json", "for f in packages/*/package.json; do echo $f; done", "tail -n 50 log/*.log"]) check(capturePolicy(bash(command), mono).disposition === "keep", `monorepo-shell ${{!!policy}}: ${{command}}`);+ for (const payload of [{{ tool: "glob", args: {{ pattern: "packages/*/package.json" }} }}, {{ tool: "grep", args: {{ pattern: "x", path: "packages", glob: "*/package.json" }} }}]) check(capturePolicy(payload, mono).disposition === (policy ? "drop" : "keep"), `monorepo-search ${{!!policy}}: ${{JSON.stringify(payload)}}`);+ for (const command of ["cat ../*/secrets.env", "cat ../a/*.env"]) check(capturePolicy(bash(command), mono).disposition === "drop", `monorepo-sibling ${{!!policy}}: ${{command}}`);+}}+// A walk outside the checkout stops at its directory bound (counted as a "**" lists) and its time budget; mirrors `a_glob_walk_outside_the_checkout_stops_at_its_bounds`.+const budgetRoot = join(markerRoot, "budget"); mkdirSync(join(budgetRoot, "x", "y"), {{ recursive: true }}); writeFileSync(join(budgetRoot, "x", ".ai-memory.toml"), "");+const fastBudget = (): CaptureGlobBudget => ({{ dirs: 0, entries: 0, deadline: 50, now: () => 0 }});+check(captureMarkersBelow(budgetRoot, ["**"], undefined, fastBudget())?.length === 1, "walk-in-time");+check(captureMarkersBelow(budgetRoot, ["**"], budgetRoot, fastBudget())?.length === 0, "walk-inside-checkout");+check(captureMarkersBelow(budgetRoot, ["**"], undefined, {{ dirs: 0, entries: 0, deadline: 50, now: () => 51 }}) === undefined, "walk-past-time");+const deepRoot = join(markerRoot, "deep"); for (let o = 0; o < 64; o++) for (let i = 0; i < 64; i++) mkdirSync(join(deepRoot, `d${{o}}`, `e${{i}}`), {{ recursive: true }});+const deepBudget = fastBudget(); check(captureMarkersBelow(deepRoot, ["**"], undefined, deepBudget) === undefined && deepBudget.entries < 1024, "walk-stops-early");+// Syntax that builds a step out of the checkout reaches the other checkout's policy; mirrors `constructed_parent_steps_answer_to_another_checkout`.+const conWork = join(markerRoot, "con-work"); const conA = join(conWork, "a"); const conB = join(conWork, "b");+for (const dir of [conA, join(conB, ".git"), join(conB, "sub", "x")]) mkdirSync(dir, {{ recursive: true }});+writeFileSync(join(conA, ".ai-memory.toml"), '[capture]\nignore_paths = ["secrets.env"]\n'); markerFixtures.set(conA, join(conA, ".ai-memory.toml"));+for (const [payload, label] of [[bash("cat ./**/../a/secrets.env"), "con-globstar"], [{{ tool: "glob", args: {{ pattern: "./**/../a/secrets.env" }} }}, "con-globstar-tool"], [{{ tool: "grep", args: {{ pattern: "KEY", glob: "**/../a/secrets.env" }} }}, "con-globstar-filter"], [bash("cat .{{.,x}}/a/secrets.env"), "con-brace-dot"], [bash("cat {{.,}}./a/secrets.env"), "con-brace-empty"], [bash("cat .{{.,.}}/a/secrets.env"), "con-brace-twice"], [bash("cat .{{-..0}}/a/secrets.env"), "con-brace-sequence"], [bash("cat ../(a)/secrets.env"), "con-group"], [bash("cat ../(a|c)/secrets.env"), "con-group-alternation"], [bash("cat ..$'\\x2f'a/secrets.env"), "con-ansi-hex"], [bash("cat $'\\056\\056'/a/secrets.env"), "con-ansi-octal"], [{{ tool: "apply_patch", args: {{ patchText: "*** Begin Patch\n*** Add File: sub/y.rs\n+y\n *** Update File: ../a/secrets.env\n+KEY\n*** End Patch" }} }}, "con-indented-patch"], [{{ tool: "grep", args: {{ pattern: "KEY", path: "..", file_glob: "a/*.env" }} }}, "con-file-glob"]] as [Record<string, unknown>, string][]) {{ const result = capturePolicy({{ ...payload, output: privateBody }}, conB); check(result.disposition === "drop" || (result.disposition === "metadata-only" && !JSON.stringify(result.payload).includes(privateBody)), label); }}+for (const [payload, label] of [[bash("cat sub/**/../README.md"), "con-own-globstar"], [bash("cat {{sub,lib}}/README.md"), "con-own-brace"], [bash("cat v{{1..3}}/README.md"), "con-own-sequence"], [bash("(cd sub && ls)"), "con-subshell"], [bash("cat sub$'\\x2f'x/README.md"), "con-own-ansi"], [{{ tool: "apply_patch", args: {{ patchText: "*** Begin Patch\n *** Add File: sub/x.rs\n+fn x() {{}}\n*** End Patch" }} }}, "con-own-patch"], [{{ tool: "grep", args: {{ pattern: "KEY", path: "sub", file_glob: "x/*.rs" }} }}, "con-own-file-glob"]] as [Record<string, unknown>, string][]) check(capturePolicy(payload, conB).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)}}`);diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex fade0a00..8d37f673 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -652,8 +652,14 @@ impl CapturePolicy {// output is read back like `BashOutput`.Ok(false)if paths.iter().any(|path| {- normalize_candidate(path, cwd)- .is_some_and(|candidate| output_spool(&candidate.path))+ let readings = if extracted.globs {+ normalize_readings(path, cwd).ok().flatten()+ } else {+ normalize_candidate(path, cwd).map(|c| vec![c])+ };+ readings.is_some_and(|readings| {+ readings.iter().any(|c| output_spool(&c.path))+ })}) =>{(CaptureDisposition::MetadataOnly, ExtractionState::Extracted)@@ -757,12 +763,14 @@ impl CapturePolicy {.flatten();for base in std::iter::once(cwd).chain(root) {// Not a usable path (drive-relative, oversized, bad cwd).- let Some(candidate) = normalize_candidate(&expanded, base) else {+ let Some(readings) = normalize_readings(&expanded, base)? else {continue;};- spool |= output_spool(&candidate.path);- if self.match_pattern_candidate(&candidate, false, &mut work)? {- return Ok((true, spool));+ for candidate in readings {+ spool |= output_spool(&candidate.path);+ if self.match_pattern_candidate(&candidate, false, &mut work)? {+ return Ok((true, spool));+ }}}}@@ -792,9 +800,10 @@ impl CapturePolicy {if path.contains(['[', ']', '{', '}', '(', ')', '!']) {return Err(());}- let candidate = normalize_candidate(path, cwd).ok_or(())?;- if self.match_pattern_candidate(&candidate, true, &mut work)? {- return Ok(true);+ for candidate in normalize_readings(path, cwd)?.ok_or(())? {+ if self.match_pattern_candidate(&candidate, true, &mut work)? {+ return Ok(true);+ }}}Ok(false)@@ -1149,8 +1158,10 @@ fn reads_earlier_output(name: &str) -> bool {/// (`~/.claude/projects/*/*/tool-results/*`): each of its segments is read as/// a one-segment glob (`**` included) that fits a named directory or file/// when the two globs share a match. At least one segment that fits must-/// spell some literal text, so a bare `*` or `*/*` is never taken for a saved-/// output file on its own.+/// spell part of what makes its name distinctive (`claude`, `projects`,+/// `tool-results`, `tasks`, `.output`, `opencode`, `tool-output`, `pi-bash-`)+/// in literal text, so a bare `*` or `*/*`, or a `*.log` whose wildcard stands+/// where `pi-bash-` would be, is never taken for a saved output file.fn output_spool(path: &str) -> bool {let segments: Vec<Vec<char>> = path.split('/')@@ -1163,37 +1174,55 @@ fn output_spool(path: &str) -> bool {let fits = |segment: &[char], shape: &str| {globs_intersect(segment, &shape.chars().collect::<Vec<_>>())};- // A segment that is not only wildcards names something.- let named = |segments: &[&Vec<char>]| {- segments- .iter()- .any(|segment| segment.iter().any(|c| !matches!(c, '*' | '?')))+ let named = |segments: &[(&Vec<char>, &str)]| {+ segments.iter().any(|(segment, word)| spells(segment, word))};let count = directories.len();let claude_results = (1..count).any(|index| {let (claude, projects) = (&directories[index - 1], &directories[index]);fits(claude, "*claude*")&& fits(projects, "projects")- && directories[index + 1..]- .iter()- .any(|results| fits(results, "tool-results") && named(&[claude, projects, results]))+ && directories[index + 1..].iter().any(|results| {+ fits(results, "tool-results")+ && named(&[+ (claude, "claude"),+ (projects, "projects"),+ (results, "tool-results"),+ ])+ })});let claude_task = count > 0 && {let parent = &directories[count - 1];fits(parent, "tasks")&& fits(file, "*.output")- && directories- .iter()- .any(|claude| fits(claude, "claude*") && named(&[parent, file, claude]))+ && directories.iter().any(|claude| {+ fits(claude, "claude*")+ && named(&[(parent, "tasks"), (file, ".output"), (claude, "claude")])+ })};let opencode = count >= 2 && {let (data, output) = (&directories[count - 2], &directories[count - 1]);- fits(data, "opencode") && fits(output, "tool-output") && named(&[data, output])+ fits(data, "opencode")+ && fits(output, "tool-output")+ && named(&[(data, "opencode"), (output, "tool-output")])};- let pi = fits(file, "pi-bash-*.log") && named(&[file]);+ let pi = fits(file, "pi-bash-*.log") && named(&[(file, "pi-bash-")]);claude_results || claude_task || opencode || pi}+/// Whether a one-segment glob spells part of `word` in literal text: some+/// run of it between wildcards shares at least three characters in a row+/// with `word` (all of a shorter one). `tool-res*` and `pi-*` do; `*.log`,+/// `t*` and `*` do not.+fn spells(segment: &[char], word: &str) -> bool {+ let word: Vec<char> = word.chars().collect();+ let needed = word.len().min(3);+ segment.split(|c| matches!(c, '*' | '?')).any(|run| {+ run.windows(needed)+ .any(|piece| word.windows(needed).any(|w| w == piece))+ })+}+/// Whether two one-segment globs over `*` and `?` match a common string./// A literal is a glob without wildcards, so for one this is `glob_match`.fn globs_intersect(left: &[char], right: &[char]) -> bool {@@ -1416,9 +1445,13 @@ pub const MAX_LOOKUP_LOCATIONS: usize = 4_096;/// from, so a client applies the policy of each location's own marker as/// 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+/// nothing; their policy is the event's. A glob whose `..` follows a `**`+/// yields each of its readings (`normalize_readings`), and a shell script+/// with a zsh glob group or ANSI-C numeric escapes also yields its words as+/// the shell expands them (`ShellWords::expanded`). `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, a glob with+/// more than 16 readings, or more than/// [`MAX_LOOKUP_LOCATIONS`] distinct locations.pub fn capture_lookup_locations(agent: AgentKind,@@ -1442,6 +1475,8 @@ pub fn capture_lookup_locations(}Some(())};+ // Every reading of a glob whose `..` follows a `**` ([`normalize_readings`]).+ let readings = |path: &str, base: &str| normalize_readings(path, base).ok();match (extracted.family, extracted.command.as_ref()) {(ToolFamily::File, _) => {let paths = extracted@@ -1449,16 +1484,19 @@ pub fn capture_lookup_locations(.as_ref().or(extracted.patch_paths.as_ref())?;for path in paths {- push(Some(normalize_candidate(path, cwd)?))?;+ for candidate in readings(path, cwd)?? {+ push(Some(candidate))?;+ }}}(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))?;+ for root in readings(root, cwd)?? {+ roots.push(native_path(root.clone()));+ push(Some(root))?;+ }}if roots.is_empty() {roots.push(cwd.to_owned());@@ -1467,7 +1505,9 @@ pub fn capture_lookup_locations(// 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)?))?;+ for candidate in readings(pattern, root)?? {+ push(Some(candidate))?;+ }}}}@@ -1476,11 +1516,13 @@ pub fn capture_lookup_locations(push(normalize_candidate(&base, &base))?;let home = home.and_then(|dir| normalize_root(dir).ok());let split = command.split(extracted.powershell || flavor_of(cwd) == Flavor::Windows);- for (word, tilde) in &split.words {+ for (word, tilde) in split.words.iter().chain(&split.expanded) {for (argument, _) in shell_arguments(word) {let expanded = expand_tilde(argument, *tilde, home.as_deref(), &base);if expanded.contains(['/', '\\']) {- push(normalize_candidate(&expanded, &base))?;+ for candidate in readings(&expanded, &base)?.into_iter().flatten() {+ push(Some(candidate))?;+ }}}}@@ -1500,9 +1542,10 @@ struct SearchScope {/// 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).+/// (`glob`, `include`, `file_pattern`, Hermes `file_glob`, `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()),@@ -1537,10 +1580,11 @@ fn search_scope(name: &str, args: Option<&Value>) -> Option<SearchScope> {"glob","include","file_pattern",+ "file_glob","Includes",]} else {- &["glob", "include", "file_pattern", "Includes"]+ &["glob", "include", "file_pattern", "file_glob", "Includes"]};for key in pattern_keys {match object.get(*key) {@@ -1565,7 +1609,8 @@ fn search_scope(name: &str, args: Option<&Value>) -> Option<SearchScope> {/// 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.+/// field that holds it. Codex trims each line before it reads a header, so+/// leading whitespace does not hide one. `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;@@ -1586,7 +1631,7 @@ fn patch_paths(name: &str, args: &Value) -> Option<Vec<String>> {"*** Move to:",].iter()- .find_map(|header| line.strip_prefix(header)) else {+ .find_map(|header| line.trim_start().strip_prefix(header)) else {continue;};let path = path.trim();@@ -1618,7 +1663,8 @@ pub enum GlobWalk {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.+ /// or an alternative of `..` or `~…` inside one (also one a brace+ /// expansion builds), which leaves the root./// Nothing proves which markers govern it.Unprovable,}@@ -1686,10 +1732,19 @@ pub fn glob_walk(location: &str) -> GlobWalk {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('~'));+ // A brace or group alternative of `..` or `~…` leaves the root, and+ // so does one a brace expansion builds out of other pieces.+ let leaves_at = |text: &str| {+ text.split(['{', '}', ',', '(', ')', '|', '@', '!', '+'])+ .any(|piece| piece == ".." || piece.starts_with('~'))+ };+ let leaves = leaves_at(segment)+ || (segment.contains('{')+ && brace_alternatives(segment).is_none_or(|alternatives| {+ alternatives.iter().any(|alternative| {+ alternative.contains(['/', '\\']) || leaves_at(alternative)+ })+ }));if leaves || !balanced('{', '}') || !balanced('(', ')') {return GlobWalk::Unprovable;}@@ -1719,6 +1774,136 @@ pub fn glob_walk(location: &str) -> GlobWalk {}}+/// Upper bound on the words [`brace_alternatives`] expands one segment to,+/// and on the braces it reads.+const MAX_BRACE_ALTERNATIVES: usize = 64;++/// Every word a shell's brace expansion makes of `text`: a `{…}` holding a+/// top-level comma, or a sequence (`{1..3}`, `{a..e}`, `{x..y..n}` over+/// integers or single characters), gives one word per alternative, nested+/// and repeated braces included; any other `{…}` stays as written. `None`+/// past [`MAX_BRACE_ALTERNATIVES`].+fn brace_alternatives(text: &str) -> Option<Vec<String>> {+ if text.matches('{').count() > MAX_BRACE_ALTERNATIVES {+ return None;+ }+ let mut words = Vec::new();+ expand_braces(&text.chars().collect::<Vec<_>>(), &mut words)?;+ Some(words)+}++fn expand_braces(text: &[char], words: &mut Vec<String>) -> Option<()> {+ for open in (0..text.len()).filter(|&index| text[index] == '{') {+ let mut depth = 0_usize;+ let mut close = None;+ let mut commas = Vec::new();+ for (index, &c) in text.iter().enumerate().skip(open) {+ match c {+ '{' => depth += 1,+ '}' => {+ depth -= 1;+ if depth == 0 {+ close = Some(index);+ break;+ }+ }+ ',' if depth == 1 => commas.push(index),+ _ => {}+ }+ }+ let Some(close) = close else {+ continue;+ };+ let pieces: Vec<Vec<char>> = if commas.is_empty() {+ match brace_sequence(&text[open + 1..close])? {+ Some(pieces) => pieces,+ None => continue,+ }+ } else {+ let mut start = open + 1;+ let mut pieces = Vec::new();+ for end in commas.into_iter().chain(std::iter::once(close)) {+ pieces.push(text[start..end].to_vec());+ start = end + 1;+ }+ pieces+ };+ for piece in pieces {+ let mut word = text[..open].to_vec();+ word.extend(piece);+ word.extend_from_slice(&text[close + 1..]);+ expand_braces(&word, words)?;+ }+ return Some(());+ }+ if words.len() == MAX_BRACE_ALTERNATIVES {+ return None;+ }+ words.push(text.iter().collect());+ Some(())+}++/// The words of a brace sequence body (`1..3`, `a..e`, `x..y..n`):+/// `Some(None)` when the body is not one; `None` past+/// [`MAX_BRACE_ALTERNATIVES`] words.+fn brace_sequence(body: &[char]) -> Option<Option<Vec<Vec<char>>>> {+ let body: String = body.iter().collect();+ let parts: Vec<&str> = body.split("..").collect();+ if !(2..=3).contains(&parts.len()) {+ return Some(None);+ }+ let step = match parts.get(2) {+ Some(step) => match step.parse::<i64>() {+ Ok(step) => step.unsigned_abs().max(1),+ Err(_) => return Some(None),+ },+ None => 1,+ };+ let bounds = match (parts[0].parse::<i64>(), parts[1].parse::<i64>()) {+ (Ok(from), Ok(to)) => Some((from, to, true)),+ _ => {+ let single = |part: &str| {+ let mut chars = part.chars();+ chars.next().filter(|_| chars.next().is_none())+ };+ match (single(parts[0]), single(parts[1])) {+ (Some(from), Some(to)) => {+ Some((i64::from(u32::from(from)), i64::from(u32::from(to)), false))+ }+ _ => None,+ }+ }+ };+ let Some((from, to, numeric)) = bounds else {+ return Some(None);+ };+ let count = from.abs_diff(to) / step + 1;+ if count > MAX_BRACE_ALTERNATIVES as u64 {+ return None;+ }+ let mut words = Vec::new();+ let mut value = from;+ for _ in 0..count {+ let word = if numeric {+ value.to_string().chars().collect()+ } else {+ u32::try_from(value)+ .ok()+ .and_then(char::from_u32)+ .map(|c| vec![c])+ .unwrap_or_default()+ };+ words.push(word);+ let delta = i64::try_from(step).unwrap_or(1);+ value = if from <= to {+ value + delta+ } else {+ value - delta+ };+ }+ Some(Some(words))+}+/// 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 {@@ -1779,6 +1964,13 @@ enum ShellCommand<'a> {struct ShellWords {words: Vec<(String, bool)>,opaque: bool,+ /// The words of each script that holds such syntax, read as the shell+ /// expands them where that can change which directory a path names: a+ /// zsh glob group kept inside its word and an ANSI-C string with its+ /// numeric escapes decoded. Only the+ /// marker lookup reads them; the matcher already treats such a script+ /// as opaque.+ expanded: Vec<(String, bool)>,}impl ShellCommand<'_> {@@ -1807,6 +1999,9 @@ impl ShellCommand<'_> {match self {Self::Line(command) => {split.opaque = has_unevaluated_expansion(command);+ if split.opaque {+ split.expanded.extend(shell_tokens(command, true));+ }push_nested_words(&marked_shell_words(command), MAX_SHELL_NESTING, &mut split);if let Some(plain) = windows.then(|| without_windows_escapes(command)).flatten() {push_nested_words(&marked_shell_words(&plain), MAX_SHELL_NESTING, &mut split);@@ -1817,6 +2012,9 @@ impl ShellCommand<'_> {// over-approximation its words make.split.opaque = items.iter().any(|item| has_unevaluated_expansion(item))|| runs_inline_code(items);+ for item in items.iter().filter(|item| has_unevaluated_expansion(item)) {+ split.expanded.extend(shell_tokens(item, true));+ }for (index, item) in items.iter().enumerate() {// An element reaches the program as is, so only a script// a shell runs expands a tilde in it.@@ -1950,6 +2148,7 @@ fn push_nested_words(words: &[(String, bool)], depth: usize, split: &mut ShellWolet script = word.contains("$(") || word.contains('`') || is_shell_script(&texts, index);if script && has_unevaluated_expansion(word) {split.opaque = true;+ split.expanded.extend(shell_tokens(word, true));}push_nested_words(&literal_tildes(tokens, script), depth, split);}@@ -2314,6 +2513,13 @@ fn shell_words(command: &str) -> Vec<String> {/// [`shell_words`], each word with whether it holds a `~` outside quotes and/// not after a backslash, the only tilde a shell expands.fn marked_shell_words(command: &str) -> Vec<(String, bool)> {+ shell_tokens(command, false)+}++/// [`marked_shell_words`]; with `expand`, a zsh glob group stays inside its+/// word (`docs/(a|b)/x`, `(a|b)/x`) instead of splitting it as a subshell, and+/// the numeric and control escapes of an ANSI-C string are decoded.+fn shell_tokens(command: &str, expand: bool) -> Vec<(String, bool)> {let is_operator = |c: char| matches!(c, '|' | '&' | ';' | '<' | '>' | '(' | ')' | '`');let mut words = Vec::new();let mut word = String::new();@@ -2332,7 +2538,11 @@ fn marked_shell_words(command: &str) -> Vec<(String, bool)> {word.extend(chars.next());}(Some('$'), '\\') => match chars.next() {- Some(escape) => match ansi_c_escape(escape) {+ Some(escape) => match ansi_c_escape(escape).or_else(|| {+ expand+ .then(|| ansi_c_numeric_escape(escape, &mut chars))+ .flatten()+ }) {Some(decoded) => word.push(decoded),None => {word.push('\\');@@ -2362,6 +2572,15 @@ fn marked_shell_words(command: &str) -> Vec<(String, bool)> {word.extend(chars.next());in_word = true;}+ (None, '(')+ if expand+ && (!in_word || !word.ends_with(['$', '=']))+ && let Some((group, rest)) = glob_group(&chars, in_word) =>+ {+ word.push_str(&group);+ chars = rest;+ in_word = true;+ }(None, c) if c.is_whitespace() || is_operator(c) => {if in_word {words.push((std::mem::take(&mut word), tilde));@@ -2381,6 +2600,72 @@ fn marked_shell_words(command: &str) -> Vec<(String, bool)> {words}+/// The zsh glob group an unquoted `(` opens, `(` through its matching `)`,+/// and the characters after it: inside a word (`docs/(a|b)/x`), or at the start+/// of one when a word character follows the `)` (`(a|b)/x`). `None` for a+/// subshell, or when whitespace, a quote, an escape or another operator comes+/// first.+fn glob_group<'a>(+ after_open: &std::iter::Peekable<std::str::Chars<'a>>,+ in_word: bool,+) -> Option<(String, std::iter::Peekable<std::str::Chars<'a>>)> {+ let mut ahead = after_open.clone();+ let mut group = String::from("(");+ let mut depth = 1_usize;+ while depth > 0 {+ let c = ahead.next()?;+ if c.is_whitespace() || matches!(c, '\'' | '"' | '\\' | ';' | '&' | '<' | '>' | '`') {+ return None;+ }+ match c {+ '(' => depth += 1,+ ')' => depth -= 1,+ _ => {}+ }+ group.push(c);+ }+ let word_follows = ahead.peek().is_some_and(|next| {+ !next.is_whitespace() && !matches!(next, '|' | '&' | ';' | '<' | '>' | '(' | ')' | '`')+ });+ (in_word || word_follows).then_some((group, ahead))+}++/// The character a numeric or control ANSI-C escape stands for, reading its+/// digits from `rest`: `\xHH`, `\uHHHH`, `\UHHHHHHHH`, `\NNN` (octal) and+/// `\cX`. `None` when it spells no character.+fn ansi_c_numeric_escape(+ escape: char,+ rest: &mut std::iter::Peekable<std::str::Chars<'_>>,+) -> Option<char> {+ let (radix, mut value, most) = match escape {+ 'x' => (16, 0, 2),+ 'u' => (16, 0, 4),+ 'U' => (16, 0, 8),+ '0'..='7' => (8, escape.to_digit(8)?, 2),+ 'c' => {+ let control = rest.next_if(char::is_ascii)?;+ return Some(char::from(control as u8 & 0x1f));+ }+ _ => return None,+ };+ // Digits are consumed only when they spell a character.+ let mut ahead = rest.clone();+ let mut digits = 0;+ while digits < most {+ let Some(digit) = ahead.peek().and_then(|c| c.to_digit(radix)) else {+ break;+ };+ value = value * radix + digit;+ ahead.next();+ digits += 1;+ }+ let decoded = (radix == 8 || digits > 0)+ .then(|| char::from_u32(value))+ .flatten()?;+ *rest = ahead;+ Some(decoded)+}+/// The character an ANSI-C escape stands for, or `None` for a numeric or/// control escape (`\x64`, `\144`, `\u0064`, `\cA`) that is not decoded.fn ansi_c_escape(escape: char) -> Option<char> {@@ -2504,6 +2789,73 @@ struct Normalized {flavor: Flavor,}fn normalize_candidate(candidate: &str, cwd: &str) -> Option<Normalized> {+ let (raw, flavor) = candidate_raw(candidate, cwd)?;+ Some(Normalized {+ path: normalize_segments(&raw)?,+ flavor,+ })+}++/// Upper bound on the readings [`normalize_readings`] gives one glob.+const MAX_GLOBSTAR_READINGS: usize = 16;++/// [`normalize_candidate`] for a glob, whose `**` a shell (zsh, bash with+/// `globstar`) and a glob tool expand to no directory as well as to many. A+/// `..` after it then steps back from the directory before the `**` (or from+/// one it matched), which a lexical `..` that removes the `**` misses: every+/// such `..` gives two readings, the `**` matching nothing (the `..` steps+/// back from the segment before it) and the `**` matching at least one+/// directory (the `**` stays). `Ok(None)` when the candidate is not a usable+/// path; `Err` past [`MAX_GLOBSTAR_READINGS`], which proves nothing.+fn normalize_readings(candidate: &str, cwd: &str) -> Result<Option<Vec<Normalized>>, ()> {+ let Some((raw, flavor)) = candidate_raw(candidate, cwd) else {+ return Ok(None);+ };+ let Some((root, tail)) = split_root(&raw) else {+ return Ok(None);+ };+ let mut readings: Vec<Vec<&str>> = vec![Vec::new()];+ for part in tail {+ if part.is_empty() || part == "." {+ continue;+ }+ let mut next: Vec<Vec<&str>> = Vec::with_capacity(readings.len());+ for mut parts in readings {+ if part != ".." {+ parts.push(part);+ } else if parts.last().is_some_and(|last| last.contains("**")) {+ let mut none = parts.clone();+ none.pop();+ none.pop();+ if !next.contains(&none) {+ next.push(none);+ }+ } else {+ parts.pop();+ }+ if !next.contains(&parts) {+ next.push(parts);+ }+ }+ if next.len() > MAX_GLOBSTAR_READINGS {+ return Err(());+ }+ readings = next;+ }+ Ok(Some(+ readings+ .into_iter()+ .map(|parts| Normalized {+ path: join_segments(root.clone(), &parts),+ flavor,+ })+ .collect(),+ ))+}++/// A candidate joined to `cwd` when relative, with the flavor its matching+/// uses, before segment normalization.+fn candidate_raw(candidate: &str, cwd: &str) -> Option<(String, Flavor)> {if candidate.trim().is_empty()|| candidate.chars().count() > MAX_CANDIDATE_PATH_CHARS|| is_drive_relative(candidate)@@ -2530,10 +2882,7 @@ fn normalize_candidate(candidate: &str, cwd: &str) -> Option<Normalized> {raw};let flavor = flavor_of(&raw);- Some(Normalized {- path: normalize_segments(&raw)?,- flavor,- })+ Some((raw, flavor))}fn compile(config: &CaptureConfig,@@ -2687,21 +3036,7 @@ fn normalize_root(path: &str) -> Result<String, ()> {.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 {- let rest = path.strip_prefix('/')?;- ("/".into(), rest.split('/').collect())- };+ let (root, tail) = split_root(path)?;let mut parts = Vec::new();for part in tail {if part.is_empty() || part == "." {@@ -2713,14 +3048,40 @@ fn normalize_segments(path: &str) -> Option<String> {parts.push(part);}}- let mut output = root;+ Some(join_segments(root, &parts))+}+/// A path's root (`/`, `C:/`, `//server/share`, with either separator) and+/// the segments after it.+fn split_root(path: &str) -> Option<(String, Vec<&str>)> {+ fn tail(rest: &str) -> Vec<&str> {+ rest.split(['/', '\\']).collect()+ }+ let bytes = path.as_bytes();+ let separator = |index: usize| matches!(bytes.get(index), Some(b'/' | b'\\'));+ if separator(0) && separator(1) {+ let mut parts = path[2..].split(['/', '\\']).filter(|p| !p.is_empty());+ let server = parts.next()?;+ let share = parts.next()?;+ Some((format!("//{server}/{share}"), parts.collect()))+ } else if valid_drive_prefix(path) && separator(2) {+ Some((+ format!("{}:/", path[..1].to_ascii_uppercase()),+ tail(&path[3..]),+ ))+ } else if separator(0) {+ Some(("/".into(), tail(&path[1..])))+ } else {+ None+ }+}+fn join_segments(mut output: String, parts: &[&str]) -> String {if !parts.is_empty() {if !output.ends_with('/') {output.push('/');}output.push_str(&parts.join("/"));}- Some(output)+ output}fn glob_match(pattern: &str,@@ -4499,6 +4860,234 @@ mod tests {assert!(!glob_segment_matches("*.env", "src"));}+ /// Adversarial: a brace expansion can build a `..` or a separator out of+ /// pieces that are not one, which leaves+ /// the walk's root just like a literal `..` alternative. Controls: braces+ /// whose words stay below the root, sequences included, are walked.+ #[test]+ fn a_brace_that_builds_a_parent_step_cannot_be_walked() {+ for location in [+ "/work/b/.{.,x}/a/secrets.env",+ "/work/b/{.,}./a/secrets.env",+ "/work/b/.{.,.}/a/secrets.env",+ "/work/b/.{-..0}/a/secrets.env",+ "/work/b/{x,.{.,y}}/a/secrets.env",+ "/work/b/{a,{~,c}}/x",+ ] {+ assert_eq!(glob_walk(location), GlobWalk::Unprovable, "{location}");+ }+ for location in [+ "/work/{a,c}/x",+ "/work/b/.{git,hub}/x",+ "/work/b/v{1..3}/x",+ "/work/b/{a..c}.d/x",+ "/work/b/{.,x}/y",+ ] {+ assert!(+ matches!(glob_walk(location), GlobWalk::Walk { .. }),+ "{location}"+ );+ }+ assert_eq!(+ brace_alternatives(".{-..0}"),+ Some(vec![".-".into(), "..".into(), "./".into(), ".0".into()])+ );+ assert_eq!(+ brace_alternatives("a{1..5..2}{x,y}"),+ Some(+ ["a1x", "a1y", "a3x", "a3y", "a5x", "a5y"]+ .map(String::from)+ .to_vec()+ )+ );+ assert_eq!(brace_alternatives("{a}b{}"), Some(vec!["{a}b{}".into()]));+ assert_eq!(brace_alternatives("{1..1000}"), None);+ assert_eq!(brace_alternatives(&"{a,b}".repeat(7)), None);+ }++ /// Adversarial: a `**` matches no directory as well as many, so a `..`+ /// after it steps back from the directory before it (`sub/**/../x` reads+ /// `x`), which a lexical `..` that only removes the `**` misses. Both the+ /// event's own policy and the marker lookup read every such reading.+ /// Controls: a `**` without a later `..`, and a `..` that steps back+ /// over an ordinary segment, read as before.+ #[test]+ fn a_parent_step_after_a_globstar_is_read_both_ways() {+ let paths = |candidate: &str| {+ normalize_readings(candidate, "/repo")+ .unwrap()+ .unwrap()+ .into_iter()+ .map(|reading| reading.path)+ .collect::<Vec<_>>()+ };+ assert_eq!(+ paths("sub/**/../secrets.env"),+ ["/repo/secrets.env", "/repo/sub/**/secrets.env"]+ );+ assert_eq!(paths("./**/../../a/x"), ["/a/x", "/repo/**/a/x"]);+ assert_eq!(paths("src/**/*.rs"), ["/repo/src/**/*.rs"]);+ assert_eq!(paths("src/x/../y"), ["/repo/src/y"]);+ assert_eq!(+ normalize_readings(&"**/../".repeat(20), "/repo").map(|r| r.is_some()),+ Err(())+ );+ let policy = CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec!["docs/adr/**".into(), "secrets.env".into()],+ }),+ "/repo",+ None,+ );+ let read_many = |include: &[&str]| json!({"tool_name": "read_many_files", "tool_input": {"include": include}});+ let decide = |raw: &Value| {+ policy+ .inspect(AgentKind::GeminiCli, raw, "/repo")+ .protocol()+ .disposition()+ };+ assert_eq!(+ decide(&bash("cat sub/**/../secrets.env")),+ CaptureDisposition::Drop+ );+ assert_eq!(+ decide(&bash("cat src/**/../../repo/secrets.env")),+ CaptureDisposition::Drop+ );+ assert_eq!(+ decide(&read_many(&["src/**/../docs/adr"])),+ CaptureDisposition::Drop+ );+ assert_eq!(+ decide(&bash(&format!("cat {}x", "**/../".repeat(20)))),+ CaptureDisposition::Drop+ );+ assert_eq!(+ decide(&bash("cat sub/**/../README.md")),+ CaptureDisposition::Keep+ );+ assert_eq!(+ decide(&read_many(&["src/**/../lib"])),+ CaptureDisposition::Keep+ );+ let locations = |raw: &Value| {+ capture_lookup_locations(AgentKind::ClaudeCode, raw, "/work/b", None).unwrap()+ };+ for raw in [+ bash("cat ./**/../a/secrets.env"),+ json!({"tool_name": "Glob", "tool_input": {"pattern": "./**/../a/secrets.env"}}),+ json!({"tool_name": "Grep", "tool_input": {"pattern": "KEY", "glob": "**/../a/secrets.env"}}),+ ] {+ assert!(+ locations(&raw).contains(&"/work/a/secrets.env".to_owned()),+ "{raw}"+ );+ }+ }++ /// Adversarial: a zsh glob group splits into subshell tokens and an+ /// ANSI-C string keeps its numeric escapes, so neither spelled the other+ /// checkout's path for the marker lookup. The lookup reads the words as the shell expands them.+ /// Controls: a subshell, a command substitution and an array+ /// assignment add no such word.+ #[test]+ fn glob_groups_and_ansi_c_escapes_reach_the_marker_lookup() {+ let locations = |command: &str| {+ capture_lookup_locations(AgentKind::ClaudeCode, &bash(command), "/work/b", None)+ .unwrap()+ };+ for (command, location) in [+ ("cat ../(a)/secrets.env", "/work/(a)/secrets.env"),+ ("cat ../(a|c)/secrets.env", "/work/(a|c)/secrets.env"),+ ("cat (../a|x)/secrets.env", "/work/b/(../a|x)/secrets.env"),+ ("cat ..$'\\x2f'a/secrets.env", "/work/a/secrets.env"),+ ("cat $'\\056\\056/a'/secrets.env", "/work/a/secrets.env"),+ ("cat ..$'\\u002f'a/secrets.env", "/work/a/secrets.env"),+ (+ "bash -c \"cat ../(a)/secrets.env\"",+ "/work/(a)/secrets.env",+ ),+ ] {+ assert!(+ locations(command).contains(&location.to_owned()),+ "{command}: {:?}",+ locations(command)+ );+ }+ assert_eq!(+ glob_walk("/work/(a)/secrets.env"),+ GlobWalk::Walk {+ root: "/work".into(),+ steps: vec![GlobStep::Any, GlobStep::Named("secrets.env".into())],+ }+ );+ assert_eq!(+ glob_walk("/work/b/(../a|x)/secrets.env"),+ GlobWalk::Unprovable+ );+ for command in ["(cd .. && ls)", "echo $(pwd)/x", "x=(a b) && ls src/x"] {+ assert!(+ locations(command)+ .iter()+ .all(|location| !location.contains('(')),+ "{command}: {:?}",+ locations(command)+ );+ }+ }++ /// A saved-output rule needs its distinctive name spelled in literal text:+ /// `*.log` stands for `pi-bash-` with a wildcard and is an ordinary log+ /// glob, while `pi-*` and `tool-res*` spell enough of it to count.+ #[test]+ fn a_saved_output_glob_needs_its_distinctive_name_in_literal_text() {+ for path in [+ "/repo/log/*.log",+ "/tmp/*.log",+ "/tmp/p*.log",+ "/data/*/t*/tool_01",+ "/home/me/.c*/p*/x/s/t*/a.txt",+ ] {+ assert!(!output_spool(path), "{path}");+ }+ for path in [+ "/tmp/pi-*",+ "/tmp/*-bash-*.log",+ "/home/me/.claude/projects/x/s/tool-res*/a.txt",+ "/home/me/.c*/p*/x/s/*results/a.txt",+ "/data/*/tool-*/tool_01",+ "/tmp/c*/x/s/tasks/*",+ ] {+ assert!(output_spool(path), "{path}");+ }+ }++ /// Codex trims each patch line before it reads a header, so indentation+ /// does not hide a target from the marker lookup; Hermes `search_files`+ /// names its file filter `file_glob`.+ #[test]+ fn indented_patch_headers_and_hermes_file_globs_reach_the_marker_lookup() {+ let patch = json!({+ "tool_name": "apply_patch",+ "tool_input": {"command": "*** Begin Patch\n*** Add File: x.rs\n+x\n \t*** Update File: ../a/secrets.env\n+KEY\n*** End Patch"},+ });+ assert_eq!(+ capture_lookup_locations(AgentKind::Codex, &patch, "/work/b", None),+ Some(vec![+ "/work/b/x.rs".to_owned(),+ "/work/a/secrets.env".to_owned()+ ])+ );+ let search = json!({+ "tool_name": "search_files",+ "tool_input": {"pattern": "KEY", "path": "/work", "file_glob": "a/*.env"},+ });+ assert_eq!(+ capture_lookup_locations(AgentKind::Hermes, &search, "/work/b", None),+ Some(vec!["/work".to_owned(), "/work/a/*.env".to_owned()])+ );+ }+/// 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]diff --git a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json b/crates/ai-memory-hooks/tests/fixtures/capture-policy.jsonindex b40f5487..5d90d6a5 100644--- a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json+++ b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json@@ -115,6 +115,8 @@{"include":["Docs"],"disposition":"drop"},{"include":["src/../docs"],"disposition":"drop"},{"include":["src","docs"],"disposition":"drop"},+ {"include":["src/**/../docs/adr"],"disposition":"drop"},+ {"include":["src/**/../lib"],"disposition":"keep"},{"include":["src"],"disposition":"keep"},{"include":["README.md"],"disposition":"keep"},{"include":["docs/adrx"],"disposition":"keep"},@@ -341,6 +343,14 @@{"command":"cat /tmp/claude-1000/-repo/s1/*/b1.output","disposition":"metadata-only"},{"command":"cat /tmp/claude-1000/*/*/*/*.output","disposition":"metadata-only"},{"command":"tail -n 50 /tmp/pi-*","disposition":"metadata-only"},+ {"command":"tail -n 50 log/*.log","disposition":"keep"},+ {"command":"cat /tmp/*.log","disposition":"keep"},+ {"command":"cat /tmp/p*.log","disposition":"keep"},+ {"command":"cat /tmp/*-bash-*.log","disposition":"metadata-only"},+ {"command":"cat /home/me/.local/share/*/t*/tool_01","disposition":"keep"},+ {"command":"cat sub/**/../secrets.env","disposition":"drop"},+ {"command":"cat src/**/../../docs/adr/1.md","cwd":"sub","disposition":"drop"},+ {"command":"cat sub/**/../README.md","disposition":"keep"},{"command":"cat /home/me/.local/share/opencode/tool-*/tool_01","disposition":"metadata-only"},{"command":"cat ~/.claude/projects/*/*/tool-results/*","disposition":"metadata-only"},{"command":"ls src/*","disposition":"keep"},diff --git a/docs/marker-file.md b/docs/marker-file.mdindex 263f2d68..3a634ab7 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -517,7 +517,11 @@ OpenCode's truncated output (`<data>/opencode/tool-output/…`) and Pi's(`<tmp>/pi-bash-<id>.log`). A glob that could match such a file counts too(`cat ~/.claude/projects/*/*/tool-results/*`): each glob segment fits adirectory or file name it shares a match with, and at least one fitting segment-must spell literal text, so `ls src/*` is not read as one. Other unknown tools+must spell part of that name's distinctive text (`claude`, `projects`,+`tool-results`, `tasks`, `.output`, `opencode`, `tool-output`, `pi-bash-`)+literally, at least three characters in a row: `tool-res*` and `/tmp/pi-*`+count, while `ls src/*`, `tail -n 50 log/*.log` and `cat /tmp/*.log` (whose+wildcard stands where `pi-bash-` would be) are ordinary globs. Other unknown toolsretain current behavior. GitHub Copilot CLI's runtime `view`, `create` and`str_replace_editor` names are file tools read from their `path` argument.@@ -527,7 +531,8 @@ reaching any depth. ai-memory reads every entry and drops the whole call whenany one names an ignored path or could expand into one, matching case-insensitivelylike Gemini: `docs/adr/x.md`, `docs/*/x.md`, `docs/**` and `**/*.md` areall dropped under `docs/adr/**`, while `src/**/*.rs` and a root-level `*.md`-are not. Gemini reads an entry that names a directory recursively, and the+are not. A `..` after a `**` is read both ways, since `**` can match no+directory as well as many. Gemini reads an entry that names a directory recursively, and thematcher cannot tell a directory from a file, so an entry that could contain anignored path drops the call too: `docs`, `.` and `docs/` are dropped under`docs/adr/**`, while `src` and `README.md` are not. Its `exclude` list never@@ -578,7 +583,9 @@ repository root. Ifone matches a pattern, the whole event is **dropped**, exactly like a matchingfile read. An argument containing `*` or `?` also matches when its glob canreach a pattern's directory: `cat docs/*/0001.md` is dropped under-`docs/adr/**`, `cat *.md` at the repository root is not. A command that exceeds+`docs/adr/**`, `cat *.md` at the repository root is not. A `**` matches no+directory as well as many under zsh and bash's `globstar`, so a `..` after it+is read both ways. A command that exceedsthe match budget is dropped. A command that no argument matches outright is**metadata-only** when it uses syntax the matcher does not evaluate: anunquoted brace expansion (`docs/{adr,x}/1.md`, `{1..3}`), a bracket class@@ -609,12 +616,14 @@ decomposed accent like the composed letter, as its filesystem does; other POSIXhosts compare case-sensitively, and Windows paths always ignore ASCII case.A checkout's exclusions protect its files wherever a call is made from. For-every file-tool target (for `apply_patch`, the files its patch headers name),-every directory, file and path-like glob argument of a search/list tool (Grep,-Glob, LS, `grep_search`, `glob`, `list_directory`, `search_file_content` and-the other agents' equivalents; a grep `pattern` is a regular expression and is-not read), and every shell argument that spells a path (one with a separator,-after `~/` expansion) plus the tool's `workdir`, the native hook and the+every file-tool target (for `apply_patch`, the files its `*** Add File:`,+`*** Update File:`, `*** Delete File:` and `*** Move to:` headers name, read+after leading whitespace as Codex reads them), every directory, file and+path-like glob argument of a search/list tool (Grep, Glob, LS, `grep_search`,+`glob`, `list_directory`, `search_file_content`, Hermes `search_files` with its+`file_glob` filter, and the other agents' equivalents; a grep `pattern` is a+regular expression and is not read), and every shell argument that spells a+path (one with a separator, after `~/` expansion) plus the tool's `workdir`, the native hook and thegenerated integrations find the marker that governs that location, by thesame lexical walk as the event's own, and when it is another checkout's (or theevent's directory has none) apply that marker's policy as well: `cat@@ -627,23 +636,29 @@ call metadata-only. Each directory is looked up once; a call naming more thanso is a file tool whose target cannot be read or resolved.A location with glob syntax in a directory name (`cat ../*/secrets.env`, `cat-*/secrets.env` from a parent folder, `../{a,b}/x`, `../[ab]/x`) is looked up-from its literal leading directories, and every directory the glob could pass-through is checked for a marker of its own: a `*`/`?` segment lists the child-directories whose names it matches (ignoring ASCII case), a class, brace or-group segment lists every child, and a `**` lists the whole subtree unless it-starts inside the event's own checkout (the directory holding `.git`). Symlinks-are never followed. The walk reads at most 65,536 directory entries and visits-at most 256 directories per call; past either bound, or for glob syntax that-can leave its leading directories (a brace or group spanning a separator, a-`..` or `~` alternative), the call is metadata-only. An older server drops these metadata-only shell and output-reader+*/secrets.env` from a parent folder, `../{a,b}/x`, `../[ab]/x`)+is looked up from its literal leading directories. When those lie outside the+event's own checkout (the directory holding `.git`), every directory the glob+could pass through is checked for a marker of its own: a `*`/`?` segment lists+the child directories whose names it matches (ignoring ASCII case), a class,+brace or group segment lists every child, and a `**` lists the whole subtree+(not below the event's own checkout). A glob whose leading directories lie+inside the event's own checkout is not walked, so `cat packages/*/package.json`+in a monorepo costs nothing however many packages it has. Symlinks are never+followed. The walk reads at most 32,768 directory entries, visits at most 256+directories and runs at most 50 ms per call; past any bound the call is+metadata-only, and so is glob syntax that can leave its leading directories: a+brace or group spanning a separator, a `..` or `~` alternative, or a brace+expansion that builds one. A `..` after a `**` is looked up in both readings,+and a zsh glob group or an ANSI-C numeric escape is looked up as the shell+expands it. An older server drops these metadata-only shell and output-readerevents, so upgrade the server before the clients. Excluding content before transportmatters 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 resolvesymlinks, junctions, bind mounts, or Windows 8.3 aliases. Shell commands are-matched only lexically (above), and free-form patches are not parsed; prompts,+matched only lexically (above), and a patch is read only for its file headers; prompts,assistant text, notifications, and quoted content are not path-attributable.A copy of a file's content under another path is not linked back to it either.The harness output files listed above are read back metadata-only under a@@ -674,10 +689,11 @@ can be mentioned.- a bare word naming another checkout's directory (`grep -r x other`) is notlooked up for that checkout's marker, only arguments that spell a pathseparator are; a recursive search of a literal directory (a Grep whose- `path` is `..`) does not walk into the checkouts below it, a `**` that- starts inside the event's own checkout is not walked, so a checkout nested- inside it is reached only by a path or one-level glob that names it, and a- glob is not followed through a symlinked directory; a harness output file kept at a+ `path` is `..`) does not walk into the checkouts below it, a glob whose+ leading directories lie inside the event's own checkout is not walked, so a+ checkout nested inside it is reached only by a path that names it, and a+ glob is not followed through a symlinked directory; a parameter expansion+ next to glob syntax (`${X}/*/x`) is not walked; a harness output file kept at alocation other than the defaults listed above (a Claude Code configdirectory whose name lacks `claude`) is read as an ordinary file;- a value glued to a short flag is read after the flag's first letter only,diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 4ada7633..7da6ad60 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -66,7 +66,7 @@ means the boundary is not built yet.| 10e | Reconcile-tombstone of a disk-deleted page is opt-in, soft, scope-bound, and false-positive-guarded (invariant #16, #929 delete-half) | `ai-memory-wiki/src/watcher.rs` — off by default (`[maintenance] reconcile_tombstones_deleted_pages`); a page is tombstoned only after its file is observed missing on two consecutive passes (streak resets if the path's `PageId` changed), re-verified against the live filesystem immediately before acting, with reserved/indexed-but-unwalked paths (`bootstrap.md`, `_meta.md`, `_pending/`, `sessions/*.md`) excluded and a circuit breaker that skips a whole scope when `> max(3, 50%)` of its pages look missing or a non-partial walk finds nothing; `ai-memory-store/src/ops.rs` `soft_delete_for_reconcile_if_latest` is a soft tombstone (`is_latest=0` + `superseded_at`, decay's shape) through the single writer actor in one transaction — never a filesystem write — scoped to the page's own `(workspace_id, project_id)` | `watcher.rs` `reconcile_delete_disabled_by_default_never_tombstones_a_missing_page`, `reconcile_delete_cross_project_isolation` (project A's deletion never tombstones project B's same-path page), `reconcile_tombstone_refuses_a_stale_latest_id`, `reconcile_tombstone_refuses_when_the_file_still_exists`, `reconcile_tombstone_never_touches_the_filesystem`; `ops.rs` `reconcile_tombstone_resurrects_instead_of_orphaning_on_recreate` | STRONG || 10f | Session-time repair is scope-bound (no cross-project timestamp rewrite) | `ai-memory-store/src/ops.rs` `repair_session_times` — every candidate is read back and updated with `WHERE id=? AND workspace_id=? AND project_id=?`; a row outside that 3-tuple is reported `NotFound` and untouched, same code path as an id that does not exist at all; `ai-memory-mcp/src/admin.rs` `handle_repair_session_times` passes the caller's `(workspace, project)` straight through, never the candidate's own | `ops.rs` `repair_session_times_does_not_touch_a_session_of_another_project` (control: sibling session in-scope repaired in the same batch); `admin_repair_session_times.rs` `cross_project_session_is_not_found_and_untouched`; both bite-checked by dropping the `project_id` filter | STRONG || 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter; batch acknowledgements retain only processed indices and classify terminal drops without consuming capacity | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded`; `router.rs` `handle_hook_batch_skips_rate_limited_first_item_and_accepts_later_source`, `handle_hook_batch_reports_failed_index_after_rate_limited_skip`, `handle_hook_batch_drops_subagent_events_before_capacity_check` (each asserts result indices and includes an accepted control) | STRONG |-| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized, and every word that holds several words, such as a quoted `sh -c` script or a `"$(…)"` substitution, re-split to four levels by `ShellCommand::split`/`push_nested_words`, a deeper script metadata-only; ANSI-C strings decoded and a backslash before an ordinary letter dropped (`shell_words`, `push_word`); backslash-newline continuations joined (`shell_words`); a parameter default's operand, a value glued to a short flag and a `file:` URL's path read as candidates (`parameter_operands`, `shell_arguments`, `file_url_path`); PowerShell and cmd escape characters read out under the `PowerShell` tool or on a Windows host (`without_windows_escapes`); `~+` resolved to the cwd and a `~-`/`~N`/`~name` prefix metadata-only (`names_unknown_directory`); shell and interpreter options that take a value skipped while looking for a `-c` script or inline code (`takes_shell_value`, `runs_inline_code`, which also lists `lua`/`Rscript`/`osascript -e`, and `su -c`/`script -c` as script runners); paths compared without regard to case on a macOS host (`fold_case`, set by `resolve`; patterns and candidates composed to NFC and lowercased in full by `fold_path`, TS `captureFold`; client-only, the server's sentinel re-inspection never depends on it); a `file:` URL cut at its query or fragment before decoding (`file_url_path`); a parameter default nested past four levels metadata-only and a default read again after backslash removal (`parameter_operands`, `push_word_reading`); a tilde expanded or treated as an unknown directory only when the shell expands it, unquoted and in a script rather than a quoted message or argv element, every tilde under PowerShell (`marked_shell_words`, `literal_tildes`, `expand_tilde`); a file or shell read of a harness's saved tool output, or a glob that could match one, metadata-only under an active policy (`output_spool`: Claude Code `tool-results/` and `tasks/*.output`, OpenCode `tool-output/`, Pi `pi-bash-*.log`; glob segments fit a name they share a match with, `globs_intersect`, TS `captureGlobsIntersect`, and one fitting segment must spell literal text; the TS matcher applies it to `read_many_files` entries too); every other marker governing a file-tool target (an `apply_patch`'s header paths, `patch_paths`), a search/list tool's directory, file or path-like glob argument (`search_scope`; a grep `pattern` is not read) or a separator-bearing shell argument also inspects the call, found by the lexical marker walk from each location's nearest existing directory, bounded (4,096 locations, 256 directories, 16 markers, past which the call fails closed as under an invalid policy) and combined strictest-first (`capture_lookup_locations`, `CaptureDecision::stricter`, `hook.rs` `foreign_capture_decision`, also applied by `transcript_capture.rs` `decide_call`; TS `captureForeignConfigs`, `captureDecide`, `captureSearchScope`, `capturePatchPaths`); a location with glob syntax is looked up from its literal root and every directory the glob could pass through is checked for a marker (`glob_walk`, `hook.rs` `GlobBudget::markers_below`; TS `captureGlobWalk`, `captureMarkersBelow`, `captureCheckoutRoot`: a `*`/`?` segment lists the child directories it matches, a class/brace/group every child, a `**` the subtree unless it starts inside the event's `.git` checkout; symlinks never followed; 256 directories and 65,536 entries, past which, or for a brace/group spanning a separator or a `..`/`~` alternative, the call fails closed); a file tool whose targets cannot be read or resolved, and a search/list argument that is not a string, fail closed; the path of a git `REV:path` object name tried from the cwd and the marker directory (`git_object_path`); Antigravity `run_command` resolved from its `Cwd`); an invalid marker makes file, search/list and shell calls metadata-only; an active one makes a shell call metadata-only when a word uses unquoted brace expansion, a bracket class (a leading `]` included), a zsh glob group or extglob, or a numeric/control ANSI-C escape (`has_unevaluated_expansion`, also run on scripts given to `sh -c`, `eval` or a substitution), or when it runs inline interpreter code (`runs_inline_code`: `python -c`, `node -e`, `ruby -e`, `perl -e`, `php -r`, `deno eval`), and either makes tools that read back an earlier command's output metadata-only (`reads_earlier_output`: `BashOutput`, `TaskOutput`, `write_stdin`, `process`, `read_bash`/`write_bash` and PowerShell twins); the server admits a metadata-only shell or unknown-family body only under an active or invalid marker, with no paths and an `extracted` state (`router.rs` `metadata_protocol_is_legal`), and its own re-inspection strips an older client's keep for either; a Gemini `read_many_files` literal entry is also read as `entry/**` (`glob_matches_below`), and Copilot CLI's runtime `view`/`create`/`str_replace_editor` are file tools for that agent only (`agent_family`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`, `captureShellSplit`, `captureUnevaluatedExpansion`, `captureInlineCode`, `captureGitObjectPath`, `captureGlobBelow`, the `reader` flag). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected; `hook.rs` `--check-capture` preflight uses the same capture policy before any spool or spawn; transcript imports (`ai-memory backfill`, including the automatic first-boot run, and the `ai-memory run` ledger upload) apply the same decision table through `commands/transcript_capture.rs`: each recorded tool call is rebuilt in its agent's hook shape (`capture_policy.rs` `tool_call_payload`) and inspected by the checkout's policy, and by a reroute destination's policy too; a Drop removes the call and its result (paired by native id, else the strictest call of the turn when the result has no id; a result whose id matches no call, or with no call, follows the orphan rule: dropped under a policy, content-free without one), metadata-only posts the hook's metadata-only body with its protocol (backfill) or a withheld placeholder keeping only the family and a call id that passes the server's `valid_call_id` (ledger), and a shell call whose recorded arguments cannot be parsed drops; both imports also apply the hook's repository admission gate (`hook.rs` `checkout_admits_capture`: persisted capture mode, marker opt-in, readable routing marker — the same helpers the hook's own gate uses), so under allowlist mode an unmarked checkout imports nothing, prompts included: `backfill` stops before contacting the server and the run ledger finishes with no events; a tool the transcript names differently from the hook is rebuilt under the hook's name and fields (`capture_policy.rs` `hook_tool_call`: Codex `exec_command` `{cmd, workdir}` → `Bash` `{command, workdir}`); the Claude Code and Codex JSONL adapters label each event with its record's cwd (`transcript.rs` `stamp_record_cwd`, `RECORD_CWD_KEY`), from which the import resolves arguments, policy and reroutes, falling back to the session cwd, and which is removed before a ledger upload; a rerouted call, and an event whose record cwd lies outside the checkout, must pass that directory's admission gate, resolve to the same server-profile route as the checkout and to the same project scope (`transcript_capture.rs` `admits_elsewhere` → `hook.rs` `checkout_admits_capture` + `delivers_to_same_server`, which compares two `resolve_hook_route` results and never matches a refused selection, + `routes_to_same_project`, which compares the two `hook_scope` hint sets and, when they leave the project to the server, under `repo-root` the repository/marker anchor or the directory itself, under the default `basename` the directory itself or a destination inside the repository whose root is the source), else it drops with its result, since the import files every event under the importing project; compaction, checkpoint and annotation events answer to the same record-cwd checks; Claude Code `!` shell-mode output (a user message opening with a `<bash-stdout>`/`<bash-stderr>`/`<local-command-stdout>` block, whatever it holds) is dropped (`shell_mode_output`); the Claude Code adapter excludes harness-written background-task turns (`transcript.rs` `claude_task_notification`: `origin.kind` `task-notification` in any case, or a first text block opening with a `<task-notification` tag in any case, attributes allowed, after a byte-order mark, zero-width characters or whitespace) and records a compaction summary (`isCompactSummary` true, `"true"` or `1`, `truthy`) as a compaction event, which backfill does not post; a tool the matcher does not recognize (unknown family: MCP tools, Codex `view_image`, …) keeps only its family whatever the policy, as the live server stores for it (`EventCapture::Unrecognized`: backfill posts title `tool unknown` and body `tool_family: unknown`, the ledger a withheld placeholder), and so does a result with no call to inherit from (GHSA-gcpc-88hm-3xqr) | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec` and `PowerShell`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `claude_code_powershell_honors_ignored_paths_on_a_windows_host` (#1186: Windows-spelled and `-Param:value` paths drop, public-path and `git status` controls kept, invalid marker metadata-only), `gemini_cli_shell_and_read_many_files_honor_ignored_paths` (Gemini `run_shell_command` incl. `dir_path`/`directory`, and `read_many_files` globs via `match_globs`: excluded literal, mixed public+excluded, `docs/*`, recursive `**` and case-variant entries drop, an `exclude` list cannot rescue them, unsupported glob syntax and malformed lists are metadata-only, public entries kept, POSIX and Windows hosts) and `globstar_reaches_lets_double_star_span_any_depth`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell admitted for an unevaluated expansion, inactive refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`, `gemini_cli_shell_and_read_many_files_exclusions_drop_before_spool` (pre- and post-tool events with an excluded path are never spooled; public controls spool with their family); `capture_policy.rs` `read_many_files_directory_entries_cannot_reach_ignored_paths` (shared `read_many_files_directories` vectors: `docs`, `.`, `./`, `docs/`, case and `..` variants drop; `src`, `README.md`, `docs/adrx` kept), `output_reader_tools_are_metadata_only_only_under_a_policy` (active and invalid strip, inactive and an unrelated unknown tool keep), `copilot_cli_runtime_file_tools_are_scoped_to_copilot`, `unevaluated_shell_expansions_respect_quoting` (also leading-`]` classes, zsh groups and extglobs, ANSI-C numeric escapes; subshells, `$((…))`, `<(…)`, array assignments kept), the shell fixture's brace/class vectors (quoted, escaped, `${…}`, `{}`, `[ … ]`, `HEAD@{1}` controls kept); `quoted_scripts_in_string_commands_are_read_like_command_lines` (`sh -c`, `timeout … bash -c`, `"$(…)"`, `NAME="$(…)"`, backquotes, two nested shells and an inline-interpreter literal drop; `bash -c 'cargo test'` and `"$(git rev-parse HEAD)"` kept; four levels read, a fifth metadata-only), `inline_interpreter_code_is_metadata_only_under_an_active_policy` (inline code metadata-only, kept with no policy; modules, script files and `grep -e` unaffected), `git_object_names_are_path_candidates` (`HEAD:`, `:`, `:N:` and `@{n}` names drop, also from a subdirectory; drive letters, URLs, `NAME=a:b` and flags are not object names; a public object name kept), `ansi_c_strings_and_escaped_letters_are_read_like_the_shell`, `antigravity_run_command_resolves_arguments_from_its_cwd` (absolute and relative `Cwd` drop, a public `Cwd` kept, another agent's `Cwd` key ignored), `windows_escape_characters_are_read_on_a_windows_host` (caret and backquote spellings drop on a Windows host, public controls kept, a POSIX host reads both literally), `a_case_folding_host_matches_paths_without_regard_to_case` (file tool and shell drop with folding, keep without, public control kept; folding injected through `resolve_for_host` so it runs on every CI OS), the shell fixture's continuation, PowerShell/cmd escape, option-value, runner, interpreter, glued-flag, `file:` URL, tilde, parameter-default and `fold_case` vectors with their controls, the near-miss controls added to `common_commands_stay_kept_under_an_active_policy` (also quoted tildes, a `file:` URL with a query, a shallow nested default and a scratchpad log), the shell fixture's `file:` query/fragment, deep-default, escaped-default, quoted/argv/script tilde, PowerShell tilde, harness-output and Unicode `fold_case` vectors and the `decisions` harness-output vectors with their controls, `reading_a_harness_output_spool_is_metadata_only_under_a_policy` (active and invalid strip, inactive keeps, same-named files elsewhere kept, an ignored path still drops), `capture_lookup_locations_name_every_path_a_call_spells`, the Unicode rows of `a_case_folding_host_matches_paths_without_regard_to_case`, **`hook.rs` `another_checkouts_exclusions_hold_for_a_call_made_elsewhere`** (relative, absolute, glob and unmarked-Hermes shell calls naming another checkout's excluded file never spool; a broken foreign marker and too many foreign markers spool metadata-only; public, own-file and few-marker controls spool with content), **`hook.rs` `globs_searches_and_unreadable_targets_answer_to_another_checkout`** (sibling and parent-folder `*`, brace, bracket, `**` and separator-spanning-brace shell globs, a Grep path, a Glob pattern, a parent-folder Grep filter, a Gemini `search_file_content` directory, a Codex `apply_patch` header and a target-less Read never spool content; public-glob, own-glob, own-`**`, own-search, own-Glob-`**`, public-search and own-patch controls spool with content), `transcript_capture.rs` `globs_and_searches_reaching_another_checkout_honor_its_policy`, `capture_policy.rs` `glob_walk_follows_every_segment_a_glob_could_pass_through`, `an_invalid_policy_makes_a_search_metadata_only`, and the Node evidence test's `glob-*`, `search-*`, `patch-*` and `unreadable-target` checks with their controls and `transcript_capture.rs` `a_shell_command_naming_another_checkouts_file_honors_its_policy`, both failing with the foreign lookup disabled, and the Node evidence test's `cross-*` and `fold-unicode` checks, which fail with `captureForeignConfigs` disabled, and the shell fixture's quoted-script, git-object, ANSI-C, escaped-letter and inline-interpreter vectors with their controls (`cargo test`, `git status`/`log`, `pytest`, `python3 -m pytest`, `node build.js`, `npm run test`, a quoted commit message with braces); `router.rs` `capture_protocol_active_keep_of_unprovable_output_is_stripped`; `hook.rs` `excluded_content_cannot_reach_the_spool_through_unevaluated_tool_shapes` (directory entries and Copilot `view`/`create` never spool, readers and brace shells spool without content, public controls spool with it); `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 and Gemini `read_many_files`/`run_shell_command` vectors, plus unsupported-glob, empty-list and recursive-`**` checks, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job); `hook.rs` `check_capture_refuses_partial_scope_and_excluded_content` (ignored-path and partial-scope violations refused, complete public-path control passes), `check_capture_bounds_marker_hints_and_refuses_oversized_scope` (513-byte hints refused, 512-byte control passes; native routing preserved); **`backfill.rs` `backfill_never_posts_tool_content_the_capture_policy_excludes`** (planted Claude transcript: the excluded read's call and output never reach `/hook/batch`, a malformed read posts only the metadata-only body, public read control posted) and **`run.rs` `ledger_upload_drops_tool_content_the_capture_policy_excludes`** (excluded call and output absent from the finish request, public control present, cursor still advances), both failing with the guard removed; `transcript_capture.rs` `an_excluded_read_drops_its_call_and_result_by_id`, `id_less_results_take_the_strictest_call_of_their_turn`, `unrecoverable_arguments_and_orphan_results_fail_closed_under_a_policy`, `a_call_into_another_checkout_honors_its_policy`, `ledger_events_are_dropped_or_stripped_before_upload`, `without_a_policy_every_event_is_kept` (control); `capture_policy.rs` `tool_call_payload_reaches_the_live_decision_for_every_supported_agent`; **`backfill.rs` `allowlist_mode_backfills_nothing_from_an_unmarked_checkout`** (no request reaches the server; marked-checkout and denylist controls do), **`run.rs` `ledger_upload_under_allowlist_mode_carries_nothing_from_an_unmarked_checkout`** (finish carries no prompt or tool content; marked and denylist controls upload both), `transcript_capture.rs` `allowlist_mode_admits_nothing_from_an_unmarked_checkout`, all failing with the admission gate removed; **`backfill.rs` `backfill_inspects_codex_exec_command_as_the_hook_shell_call`** and **`run.rs` `ledger_upload_inspects_codex_exec_command_as_the_hook_shell_call`** (a planted Codex `exec_command` whose `workdir`-relative argument names an ignored file never posts its call or output; the same command from a public `workdir` does), `capture_policy.rs` `codex_transcript_exec_command_is_inspected_as_the_hook_bash_call` (absolute, relative and absent `workdir` and an argv `cmd` drop, public control kept, the `workdir` locates the call, another agent's `exec_command` stays unknown), all failing with `hook_tool_call` removed; **`backfill.rs` `backfill_resolves_each_call_from_its_record_cwd`** (`cat adr/x.md` recorded from `docs/` never posts; the same command from the root does) and `transcript.rs` `jsonl_events_carry_their_record_cwd` (Claude per line, Codex per turn context, a relative cwd ignored), failing with the record cwd ignored or unstamped; **`backfill.rs` `backfill_drops_reroutes_the_live_hook_would_not_deliver_here`** (under allowlist mode, reads rerouted to an unmarked git repository, to a marker selecting an unregistered profile, and to a marker selecting a registered profile while the source uses the install default are never posted; a read in a marked checkout with no server selection is the posted control), failing with either the admission check or the route comparison removed (each refused case checked on its own); `transcript_capture.rs` `a_record_cwd_answers_to_the_hook_admission_gate_there` (prompt, call and result recorded in an unmarked repository drop under allowlist; a subdirectory of the opted-in checkout is kept and its record cwd never reaches the ledger) and `claude_shell_mode_output_is_not_imported` (stdout, stderr, local-command and size-capped blocks drop; `<bash-input>`, a prompt quoting a tag, and another agent's message kept); **`backfill.rs` `backfill_posts_no_content_for_unrecognized_tools`** (a planted Codex MCP call's arguments and output never post, the call and output post as `tool unknown`; a recognized shell output is the posted control) and `transcript_capture.rs` `unrecognized_tools_keep_no_content_with_or_without_a_policy` (no policy and an active one; ledger content withheld; public read kept; a call-less result content-free), failing with the unknown-family rule removed, the backfill one also with its content-free body removed; **`backfill.rs` `backfill_keeps_reroutes_to_the_same_server_profile_only`** (a reroute into a checkout selecting the source's registered profile and project is posted; one selecting a different registered profile is not, nor one of another project on the same profile, nor a prompt recorded there), failing with the profile comparison forced either way and with the project comparison removed; `transcript_capture.rs` `a_record_cwd_in_another_project_is_dropped` and `a_reroute_into_another_project_is_dropped` (prompt, call and result recorded in, or a read reaching into, a checkout declaring another project drop; one declaring the same project is kept), failing with `routes_to_same_project` removed; `hook.rs` `subdirectories_of_one_repository_are_one_project_only_under_repo_root` (two subdirectories of an unmarked repository, and a subdirectory importing its root, are two projects; the same directory, the root importing a subdirectory and a `repo-root` marker agree), failing with the basename rule removed; **`backfill.rs` `backfill_posts_no_task_notification_or_compact_summary_as_a_prompt`** and `transcript.rs` `claude_adapter_keeps_task_notifications_and_compact_summaries_out_of_prompts` (a monitored command's notification, a background agent's report and an origin-tagged notice are excluded, also behind a byte-order mark and zero-width characters, in another case, with attributes, after a non-text block, or with an origin kind in another case; a compact summary, also flagged `"true"` or `1`, becomes a compaction event; the typed prompt, also one quoting the tag, and a look-alike tag are the controls), failing with either adapter rule removed or with the spelling rules reverted; `transcript_capture.rs` `boundary_events_answer_to_the_record_cwd_admission_gate` (compaction and annotation recorded in a refused directory drop; in the checkout kept), `a_result_whose_id_matches_no_call_is_an_orphan` (an unmatched id cannot borrow a public read's keep; the read's own result kept), `claude_shell_mode_output_is_not_imported` (a block holding a literal closing tag drops) and `unrecognized_tools_keep_no_content_with_or_without_a_policy` (ledger keeps no tool name and no invalid call id), each failing with its rule reverted | STRONG with listed residuals. Matching is lexical by design, so these stay open: shell variables (`$VAR`, `FILE=… sh -c 'cat $FILE'`) and the output of a command substitution, a `cd` inside the command, a script read from a file or a heredoc fed to an interpreter (read only for the words it spells out), git's repository root approximated by the marker directory, symlinks (paths are never resolved on disk), a recursive search of a parent directory (`grep -r x docs`, `rg x`) through a shell, a search tool rooted at a literal directory above another checkout (it is not walked) and a `**` starting inside the event's own checkout reaching a checkout nested there, a glob through a symlinked directory, a tool's own directory option (`git -C`), script runners and interpreters the matcher does not list (their words are still read, but expansion or inline code in them is not recognized), a value glued after the first letter of a short-flag cluster, non-ASCII percent-escapes in a `file:` URL, a bare word naming another checkout's directory (only separator-bearing arguments are looked up for another marker), harness output files outside the listed default locations, and tools the matcher does not list, which keep their current unknown-tool behavior. Transcript imports add: assistant prose quoting an excluded file is kept (as live prompt/assistant capture keeps it), harnesses whose hook schema the matcher does not read (Crush, Kimi Code) keep their tool events as live capture would, adapters that record no per-record cwd (Pi, OMP, OpenCode, Crush, Kimi Code, Command Code, Kiro, Grok) judge every event from the session cwd, a Codex ledger upload resumed from a mid-file cursor judges the events before the next turn context from the session cwd, and id-less adapters over-drop a whole turn's results when one call is excluded, and when the routing hints leave the project to the server, events from inside one repository count as the importing project even where the server has a separate project registered for a subdirectory (anywhere under `repo-root`; under `basename` only when the import runs from the repository root); a metadata-only import keeps an `event_id` (ledger) and `ingest_key` (backfill) derived from a SHA-256 of the original content plus session and record ids, left in place because those ids are the retry-dedupe keys and a content-free id would merge distinct events — it only confirms a guess of low-entropy content. Under allowlist mode a refused checkout's `ai-memory run` still records repository checkpoint metadata (HEAD, branch, a status hash and changed-path names, never file content), which the run also sends at launch. Re-splitting quoted words over-drops a quoted message naming an ignored path, and inline interpreter code is metadata-only under an active policy. Mitigation: allowlist capture mode (`install-hooks --capture-mode allowlist`) for sensitive projects. Bite checks: removing the nested re-split, the git object path or its marker-root base, Antigravity's `Cwd` key, the leading-`]` rule, either zsh-group rule, ANSI-C decoding or its numeric-escape rule, the `\o` reading, the inline-code rule, the nesting-depth rule, the nested-script scan, the line-continuation join, the Windows escape reading, the shell-option and interpreter-option value skips, the added runners and interpreters, the glued-flag value, the `file:` URL path, the `~+` resolution, the unknown-tilde rule, the parameter-default reading or case folding each fails the Rust tests, and each TypeScript counterpart fails the Node evidence test; so does reverting the `file:` URL cut, the deep-default rule, the escaped-default reading, the quoted-tilde rule, the harness-output rule or Unicode folding (the new fixture vectors fail against the previous matchers in both languages), and disabling the foreign-marker lookup fails the native, import and Node cross-checkout tests; reading every glob location as literal, skipping search/list locations, or skipping a file tool whose targets cannot be read each fails the native, import and Node glob/search/unreadable tests, removing `apply_patch` header reading fails the own-patch control, and reverting the saved-output glob rule fails the new fixture vectors in both languages |+| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized, and every word that holds several words, such as a quoted `sh -c` script or a `"$(…)"` substitution, re-split to four levels by `ShellCommand::split`/`push_nested_words`, a deeper script metadata-only; ANSI-C strings decoded and a backslash before an ordinary letter dropped (`shell_words`, `push_word`); backslash-newline continuations joined (`shell_words`); a parameter default's operand, a value glued to a short flag and a `file:` URL's path read as candidates (`parameter_operands`, `shell_arguments`, `file_url_path`); PowerShell and cmd escape characters read out under the `PowerShell` tool or on a Windows host (`without_windows_escapes`); `~+` resolved to the cwd and a `~-`/`~N`/`~name` prefix metadata-only (`names_unknown_directory`); shell and interpreter options that take a value skipped while looking for a `-c` script or inline code (`takes_shell_value`, `runs_inline_code`, which also lists `lua`/`Rscript`/`osascript -e`, and `su -c`/`script -c` as script runners); paths compared without regard to case on a macOS host (`fold_case`, set by `resolve`; patterns and candidates composed to NFC and lowercased in full by `fold_path`, TS `captureFold`; client-only, the server's sentinel re-inspection never depends on it); a `file:` URL cut at its query or fragment before decoding (`file_url_path`); a parameter default nested past four levels metadata-only and a default read again after backslash removal (`parameter_operands`, `push_word_reading`); a tilde expanded or treated as an unknown directory only when the shell expands it, unquoted and in a script rather than a quoted message or argv element, every tilde under PowerShell (`marked_shell_words`, `literal_tildes`, `expand_tilde`); a file or shell read of a harness's saved tool output, or a glob that could match one, metadata-only under an active policy (`output_spool`: Claude Code `tool-results/` and `tasks/*.output`, OpenCode `tool-output/`, Pi `pi-bash-*.log`; glob segments fit a name they share a match with, `globs_intersect`, TS `captureGlobsIntersect`, and one fitting segment must spell three characters in a row of that name's distinctive text literally, `spells`, TS `captureSpells`, so `*.log` is not read as `pi-bash-*.log`; the TS matcher applies it to `read_many_files` entries too); every other marker governing a file-tool target (an `apply_patch`'s header paths, read after leading whitespace, `patch_paths`), a search/list tool's directory, file or path-like glob argument (`search_scope`, Hermes `file_glob` included; a grep `pattern` is not read) or a separator-bearing shell argument also inspects the call, found by the lexical marker walk from each location's nearest existing directory, bounded (4,096 locations, 256 directories, 16 markers, past which the call fails closed as under an invalid policy) and combined strictest-first (`capture_lookup_locations`, `CaptureDecision::stricter`, `hook.rs` `foreign_capture_decision`, also applied by `transcript_capture.rs` `decide_call`; TS `captureForeignConfigs`, `captureDecide`, `captureSearchScope`, `capturePatchPaths`); a location with glob syntax is looked up from its literal root and, when that root lies outside the event's `.git` checkout, every directory the glob could pass through is checked for a marker (`glob_walk`, `hook.rs` `GlobBudget::markers_below`; TS `captureGlobWalk`, `captureMarkersBelow`, `captureCheckoutRoot`: a `*`/`?` segment lists the child directories it matches, a class/brace/group every child, a `**` the subtree, not below the event's checkout; a glob rooted inside the event's checkout is not walked; symlinks never followed; 256 directories, counted as a `**` lists, 32,768 entries and 50 ms, `MAX_GLOB_TIME`, TS `CAPTURE_MAX_GLOB_MS`, injectable clock, past which, or for a brace/group spanning a separator, a `..`/`~` alternative or one a bounded brace expansion builds, `brace_alternatives`, TS `captureBraceAlternatives`, the call fails closed); a `..` after a `**` is read both as the `**` matching no directory and as matching some, by the event's own matcher and the lookup (`normalize_readings`, TS `captureReadings`, at most 16 readings, past which the call fails closed); a zsh glob group kept in its word and ANSI-C numeric escapes decoded are fed to the lookup (`shell_tokens` with `expand`, `ShellWords::expanded`, `glob_group`, `ansi_c_numeric_escape`; TS `captureMarkedWords(…, true)`, `captureGlobGroup`, `captureAnsiNumeric`); a file tool whose targets cannot be read or resolved, and a search/list argument that is not a string, fail closed; the path of a git `REV:path` object name tried from the cwd and the marker directory (`git_object_path`); Antigravity `run_command` resolved from its `Cwd`); an invalid marker makes file, search/list and shell calls metadata-only; an active one makes a shell call metadata-only when a word uses unquoted brace expansion, a bracket class (a leading `]` included), a zsh glob group or extglob, or a numeric/control ANSI-C escape (`has_unevaluated_expansion`, also run on scripts given to `sh -c`, `eval` or a substitution), or when it runs inline interpreter code (`runs_inline_code`: `python -c`, `node -e`, `ruby -e`, `perl -e`, `php -r`, `deno eval`), and either makes tools that read back an earlier command's output metadata-only (`reads_earlier_output`: `BashOutput`, `TaskOutput`, `write_stdin`, `process`, `read_bash`/`write_bash` and PowerShell twins); the server admits a metadata-only shell or unknown-family body only under an active or invalid marker, with no paths and an `extracted` state (`router.rs` `metadata_protocol_is_legal`), and its own re-inspection strips an older client's keep for either; a Gemini `read_many_files` literal entry is also read as `entry/**` (`glob_matches_below`), and Copilot CLI's runtime `view`/`create`/`str_replace_editor` are file tools for that agent only (`agent_family`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`, `captureShellSplit`, `captureUnevaluatedExpansion`, `captureInlineCode`, `captureGitObjectPath`, `captureGlobBelow`, the `reader` flag). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected; `hook.rs` `--check-capture` preflight uses the same capture policy before any spool or spawn; transcript imports (`ai-memory backfill`, including the automatic first-boot run, and the `ai-memory run` ledger upload) apply the same decision table through `commands/transcript_capture.rs`: each recorded tool call is rebuilt in its agent's hook shape (`capture_policy.rs` `tool_call_payload`) and inspected by the checkout's policy, and by a reroute destination's policy too; a Drop removes the call and its result (paired by native id, else the strictest call of the turn when the result has no id; a result whose id matches no call, or with no call, follows the orphan rule: dropped under a policy, content-free without one), metadata-only posts the hook's metadata-only body with its protocol (backfill) or a withheld placeholder keeping only the family and a call id that passes the server's `valid_call_id` (ledger), and a shell call whose recorded arguments cannot be parsed drops; both imports also apply the hook's repository admission gate (`hook.rs` `checkout_admits_capture`: persisted capture mode, marker opt-in, readable routing marker — the same helpers the hook's own gate uses), so under allowlist mode an unmarked checkout imports nothing, prompts included: `backfill` stops before contacting the server and the run ledger finishes with no events; a tool the transcript names differently from the hook is rebuilt under the hook's name and fields (`capture_policy.rs` `hook_tool_call`: Codex `exec_command` `{cmd, workdir}` → `Bash` `{command, workdir}`); the Claude Code and Codex JSONL adapters label each event with its record's cwd (`transcript.rs` `stamp_record_cwd`, `RECORD_CWD_KEY`), from which the import resolves arguments, policy and reroutes, falling back to the session cwd, and which is removed before a ledger upload; a rerouted call, and an event whose record cwd lies outside the checkout, must pass that directory's admission gate, resolve to the same server-profile route as the checkout and to the same project scope (`transcript_capture.rs` `admits_elsewhere` → `hook.rs` `checkout_admits_capture` + `delivers_to_same_server`, which compares two `resolve_hook_route` results and never matches a refused selection, + `routes_to_same_project`, which compares the two `hook_scope` hint sets and, when they leave the project to the server, under `repo-root` the repository/marker anchor or the directory itself, under the default `basename` the directory itself or a destination inside the repository whose root is the source), else it drops with its result, since the import files every event under the importing project; compaction, checkpoint and annotation events answer to the same record-cwd checks; Claude Code `!` shell-mode output (a user message opening with a `<bash-stdout>`/`<bash-stderr>`/`<local-command-stdout>` block, whatever it holds) is dropped (`shell_mode_output`); the Claude Code adapter excludes harness-written background-task turns (`transcript.rs` `claude_task_notification`: `origin.kind` `task-notification` in any case, or a first text block opening with a `<task-notification` tag in any case, attributes allowed, after a byte-order mark, zero-width characters or whitespace) and records a compaction summary (`isCompactSummary` true, `"true"` or `1`, `truthy`) as a compaction event, which backfill does not post; a tool the matcher does not recognize (unknown family: MCP tools, Codex `view_image`, …) keeps only its family whatever the policy, as the live server stores for it (`EventCapture::Unrecognized`: backfill posts title `tool unknown` and body `tool_family: unknown`, the ledger a withheld placeholder), and so does a result with no call to inherit from (GHSA-gcpc-88hm-3xqr) | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec` and `PowerShell`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `claude_code_powershell_honors_ignored_paths_on_a_windows_host` (#1186: Windows-spelled and `-Param:value` paths drop, public-path and `git status` controls kept, invalid marker metadata-only), `gemini_cli_shell_and_read_many_files_honor_ignored_paths` (Gemini `run_shell_command` incl. `dir_path`/`directory`, and `read_many_files` globs via `match_globs`: excluded literal, mixed public+excluded, `docs/*`, recursive `**` and case-variant entries drop, an `exclude` list cannot rescue them, unsupported glob syntax and malformed lists are metadata-only, public entries kept, POSIX and Windows hosts) and `globstar_reaches_lets_double_star_span_any_depth`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell admitted for an unevaluated expansion, inactive refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`, `gemini_cli_shell_and_read_many_files_exclusions_drop_before_spool` (pre- and post-tool events with an excluded path are never spooled; public controls spool with their family); `capture_policy.rs` `read_many_files_directory_entries_cannot_reach_ignored_paths` (shared `read_many_files_directories` vectors: `docs`, `.`, `./`, `docs/`, case and `..` variants drop; `src`, `README.md`, `docs/adrx` kept), `output_reader_tools_are_metadata_only_only_under_a_policy` (active and invalid strip, inactive and an unrelated unknown tool keep), `copilot_cli_runtime_file_tools_are_scoped_to_copilot`, `unevaluated_shell_expansions_respect_quoting` (also leading-`]` classes, zsh groups and extglobs, ANSI-C numeric escapes; subshells, `$((…))`, `<(…)`, array assignments kept), the shell fixture's brace/class vectors (quoted, escaped, `${…}`, `{}`, `[ … ]`, `HEAD@{1}` controls kept); `quoted_scripts_in_string_commands_are_read_like_command_lines` (`sh -c`, `timeout … bash -c`, `"$(…)"`, `NAME="$(…)"`, backquotes, two nested shells and an inline-interpreter literal drop; `bash -c 'cargo test'` and `"$(git rev-parse HEAD)"` kept; four levels read, a fifth metadata-only), `inline_interpreter_code_is_metadata_only_under_an_active_policy` (inline code metadata-only, kept with no policy; modules, script files and `grep -e` unaffected), `git_object_names_are_path_candidates` (`HEAD:`, `:`, `:N:` and `@{n}` names drop, also from a subdirectory; drive letters, URLs, `NAME=a:b` and flags are not object names; a public object name kept), `ansi_c_strings_and_escaped_letters_are_read_like_the_shell`, `antigravity_run_command_resolves_arguments_from_its_cwd` (absolute and relative `Cwd` drop, a public `Cwd` kept, another agent's `Cwd` key ignored), `windows_escape_characters_are_read_on_a_windows_host` (caret and backquote spellings drop on a Windows host, public controls kept, a POSIX host reads both literally), `a_case_folding_host_matches_paths_without_regard_to_case` (file tool and shell drop with folding, keep without, public control kept; folding injected through `resolve_for_host` so it runs on every CI OS), the shell fixture's continuation, PowerShell/cmd escape, option-value, runner, interpreter, glued-flag, `file:` URL, tilde, parameter-default and `fold_case` vectors with their controls, the near-miss controls added to `common_commands_stay_kept_under_an_active_policy` (also quoted tildes, a `file:` URL with a query, a shallow nested default and a scratchpad log), the shell fixture's `file:` query/fragment, deep-default, escaped-default, quoted/argv/script tilde, PowerShell tilde, harness-output and Unicode `fold_case` vectors and the `decisions` harness-output vectors with their controls, `reading_a_harness_output_spool_is_metadata_only_under_a_policy` (active and invalid strip, inactive keeps, same-named files elsewhere kept, an ignored path still drops), `capture_lookup_locations_name_every_path_a_call_spells`, the Unicode rows of `a_case_folding_host_matches_paths_without_regard_to_case`, **`hook.rs` `another_checkouts_exclusions_hold_for_a_call_made_elsewhere`** (relative, absolute, glob and unmarked-Hermes shell calls naming another checkout's excluded file never spool; a broken foreign marker and too many foreign markers spool metadata-only; public, own-file and few-marker controls spool with content), **`hook.rs` `globs_searches_and_unreadable_targets_answer_to_another_checkout`** (sibling and parent-folder `*`, brace, bracket, `**` and separator-spanning-brace shell globs, a Grep path, a Glob pattern, a parent-folder Grep filter, a Gemini `search_file_content` directory, a Codex `apply_patch` header and a target-less Read never spool content; public-glob, own-glob, own-`**`, own-search, own-Glob-`**`, public-search and own-patch controls spool with content), `transcript_capture.rs` `globs_and_searches_reaching_another_checkout_honor_its_policy`, `capture_policy.rs` `glob_walk_follows_every_segment_a_glob_could_pass_through`, `an_invalid_policy_makes_a_search_metadata_only`, `a_brace_that_builds_a_parent_step_cannot_be_walked`, `a_parent_step_after_a_globstar_is_read_both_ways`, `glob_groups_and_ansi_c_escapes_reach_the_marker_lookup`, `a_saved_output_glob_needs_its_distinctive_name_in_literal_text`, `indented_patch_headers_and_hermes_file_globs_reach_the_marker_lookup` (each attack with its control), the shell fixture's `**`-then-`..` and `*.log` vectors and the `read_many_files_directories` `**`-then-`..` vectors, **`hook.rs` `constructed_parent_steps_answer_to_another_checkout`** (a `..` after a `**` through a shell, a Glob pattern and a Grep filter, four brace expansions that build a parent step, two zsh glob groups, hex and octal ANSI-C escapes, an indented `apply_patch` header next to an unindented one and a Hermes `file_glob` never spool content; the same shapes inside the checkout spool with it), **`hook.rs` `a_monorepo_glob_inside_the_own_checkout_is_not_walked`** (in a 300-package checkout, with and without a policy of its own, `packages/*` shell globs stay kept and the sibling `../*/secrets.env` and `../a/*.env` attacks still drop), `hook.rs` `a_glob_walk_outside_the_checkout_stops_at_its_bounds` (directory bound counted while a `**` lists, time budget through an injected clock, no walk inside the checkout), the Node evidence test's `monorepo-*`, `walk-*` and `con-*` checks, and the Node evidence test's `glob-*`, `search-*`, `patch-*` and `unreadable-target` checks with their controls and `transcript_capture.rs` `a_shell_command_naming_another_checkouts_file_honors_its_policy`, both failing with the foreign lookup disabled, and the Node evidence test's `cross-*` and `fold-unicode` checks, which fail with `captureForeignConfigs` disabled, and the shell fixture's quoted-script, git-object, ANSI-C, escaped-letter and inline-interpreter vectors with their controls (`cargo test`, `git status`/`log`, `pytest`, `python3 -m pytest`, `node build.js`, `npm run test`, a quoted commit message with braces); `router.rs` `capture_protocol_active_keep_of_unprovable_output_is_stripped`; `hook.rs` `excluded_content_cannot_reach_the_spool_through_unevaluated_tool_shapes` (directory entries and Copilot `view`/`create` never spool, readers and brace shells spool without content, public controls spool with it); `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 and Gemini `read_many_files`/`run_shell_command` vectors, plus unsupported-glob, empty-list and recursive-`**` checks, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job); `hook.rs` `check_capture_refuses_partial_scope_and_excluded_content` (ignored-path and partial-scope violations refused, complete public-path control passes), `check_capture_bounds_marker_hints_and_refuses_oversized_scope` (513-byte hints refused, 512-byte control passes; native routing preserved); **`backfill.rs` `backfill_never_posts_tool_content_the_capture_policy_excludes`** (planted Claude transcript: the excluded read's call and output never reach `/hook/batch`, a malformed read posts only the metadata-only body, public read control posted) and **`run.rs` `ledger_upload_drops_tool_content_the_capture_policy_excludes`** (excluded call and output absent from the finish request, public control present, cursor still advances), both failing with the guard removed; `transcript_capture.rs` `an_excluded_read_drops_its_call_and_result_by_id`, `id_less_results_take_the_strictest_call_of_their_turn`, `unrecoverable_arguments_and_orphan_results_fail_closed_under_a_policy`, `a_call_into_another_checkout_honors_its_policy`, `ledger_events_are_dropped_or_stripped_before_upload`, `without_a_policy_every_event_is_kept` (control); `capture_policy.rs` `tool_call_payload_reaches_the_live_decision_for_every_supported_agent`; **`backfill.rs` `allowlist_mode_backfills_nothing_from_an_unmarked_checkout`** (no request reaches the server; marked-checkout and denylist controls do), **`run.rs` `ledger_upload_under_allowlist_mode_carries_nothing_from_an_unmarked_checkout`** (finish carries no prompt or tool content; marked and denylist controls upload both), `transcript_capture.rs` `allowlist_mode_admits_nothing_from_an_unmarked_checkout`, all failing with the admission gate removed; **`backfill.rs` `backfill_inspects_codex_exec_command_as_the_hook_shell_call`** and **`run.rs` `ledger_upload_inspects_codex_exec_command_as_the_hook_shell_call`** (a planted Codex `exec_command` whose `workdir`-relative argument names an ignored file never posts its call or output; the same command from a public `workdir` does), `capture_policy.rs` `codex_transcript_exec_command_is_inspected_as_the_hook_bash_call` (absolute, relative and absent `workdir` and an argv `cmd` drop, public control kept, the `workdir` locates the call, another agent's `exec_command` stays unknown), all failing with `hook_tool_call` removed; **`backfill.rs` `backfill_resolves_each_call_from_its_record_cwd`** (`cat adr/x.md` recorded from `docs/` never posts; the same command from the root does) and `transcript.rs` `jsonl_events_carry_their_record_cwd` (Claude per line, Codex per turn context, a relative cwd ignored), failing with the record cwd ignored or unstamped; **`backfill.rs` `backfill_drops_reroutes_the_live_hook_would_not_deliver_here`** (under allowlist mode, reads rerouted to an unmarked git repository, to a marker selecting an unregistered profile, and to a marker selecting a registered profile while the source uses the install default are never posted; a read in a marked checkout with no server selection is the posted control), failing with either the admission check or the route comparison removed (each refused case checked on its own); `transcript_capture.rs` `a_record_cwd_answers_to_the_hook_admission_gate_there` (prompt, call and result recorded in an unmarked repository drop under allowlist; a subdirectory of the opted-in checkout is kept and its record cwd never reaches the ledger) and `claude_shell_mode_output_is_not_imported` (stdout, stderr, local-command and size-capped blocks drop; `<bash-input>`, a prompt quoting a tag, and another agent's message kept); **`backfill.rs` `backfill_posts_no_content_for_unrecognized_tools`** (a planted Codex MCP call's arguments and output never post, the call and output post as `tool unknown`; a recognized shell output is the posted control) and `transcript_capture.rs` `unrecognized_tools_keep_no_content_with_or_without_a_policy` (no policy and an active one; ledger content withheld; public read kept; a call-less result content-free), failing with the unknown-family rule removed, the backfill one also with its content-free body removed; **`backfill.rs` `backfill_keeps_reroutes_to_the_same_server_profile_only`** (a reroute into a checkout selecting the source's registered profile and project is posted; one selecting a different registered profile is not, nor one of another project on the same profile, nor a prompt recorded there), failing with the profile comparison forced either way and with the project comparison removed; `transcript_capture.rs` `a_record_cwd_in_another_project_is_dropped` and `a_reroute_into_another_project_is_dropped` (prompt, call and result recorded in, or a read reaching into, a checkout declaring another project drop; one declaring the same project is kept), failing with `routes_to_same_project` removed; `hook.rs` `subdirectories_of_one_repository_are_one_project_only_under_repo_root` (two subdirectories of an unmarked repository, and a subdirectory importing its root, are two projects; the same directory, the root importing a subdirectory and a `repo-root` marker agree), failing with the basename rule removed; **`backfill.rs` `backfill_posts_no_task_notification_or_compact_summary_as_a_prompt`** and `transcript.rs` `claude_adapter_keeps_task_notifications_and_compact_summaries_out_of_prompts` (a monitored command's notification, a background agent's report and an origin-tagged notice are excluded, also behind a byte-order mark and zero-width characters, in another case, with attributes, after a non-text block, or with an origin kind in another case; a compact summary, also flagged `"true"` or `1`, becomes a compaction event; the typed prompt, also one quoting the tag, and a look-alike tag are the controls), failing with either adapter rule removed or with the spelling rules reverted; `transcript_capture.rs` `boundary_events_answer_to_the_record_cwd_admission_gate` (compaction and annotation recorded in a refused directory drop; in the checkout kept), `a_result_whose_id_matches_no_call_is_an_orphan` (an unmatched id cannot borrow a public read's keep; the read's own result kept), `claude_shell_mode_output_is_not_imported` (a block holding a literal closing tag drops) and `unrecognized_tools_keep_no_content_with_or_without_a_policy` (ledger keeps no tool name and no invalid call id), each failing with its rule reverted | STRONG with listed residuals. Matching is lexical by design, so these stay open: shell variables (`$VAR`, `FILE=… sh -c 'cat $FILE'`) and the output of a command substitution, a `cd` inside the command, a script read from a file or a heredoc fed to an interpreter (read only for the words it spells out), git's repository root approximated by the marker directory, symlinks (paths are never resolved on disk), a recursive search of a parent directory (`grep -r x docs`, `rg x`) through a shell, a search tool rooted at a literal directory above another checkout (it is not walked) and a glob whose literal root lies inside the event's own checkout reaching a checkout nested there (it is not walked), a parameter expansion next to glob syntax (`${X}/*/x`, not walked), a glob through a symlinked directory, a tool's own directory option (`git -C`), script runners and interpreters the matcher does not list (their words are still read, but expansion or inline code in them is not recognized), a value glued after the first letter of a short-flag cluster, non-ASCII percent-escapes in a `file:` URL, a bare word naming another checkout's directory (only separator-bearing arguments are looked up for another marker), harness output files outside the listed default locations, and tools the matcher does not list, which keep their current unknown-tool behavior. Transcript imports add: assistant prose quoting an excluded file is kept (as live prompt/assistant capture keeps it), harnesses whose hook schema the matcher does not read (Crush, Kimi Code) keep their tool events as live capture would, adapters that record no per-record cwd (Pi, OMP, OpenCode, Crush, Kimi Code, Command Code, Kiro, Grok) judge every event from the session cwd, a Codex ledger upload resumed from a mid-file cursor judges the events before the next turn context from the session cwd, and id-less adapters over-drop a whole turn's results when one call is excluded, and when the routing hints leave the project to the server, events from inside one repository count as the importing project even where the server has a separate project registered for a subdirectory (anywhere under `repo-root`; under `basename` only when the import runs from the repository root); a metadata-only import keeps an `event_id` (ledger) and `ingest_key` (backfill) derived from a SHA-256 of the original content plus session and record ids, left in place because those ids are the retry-dedupe keys and a content-free id would merge distinct events — it only confirms a guess of low-entropy content. Under allowlist mode a refused checkout's `ai-memory run` still records repository checkpoint metadata (HEAD, branch, a status hash and changed-path names, never file content), which the run also sends at launch. Re-splitting quoted words over-drops a quoted message naming an ignored path, and inline interpreter code is metadata-only under an active policy. Mitigation: allowlist capture mode (`install-hooks --capture-mode allowlist`) for sensitive projects. Bite checks: removing the nested re-split, the git object path or its marker-root base, Antigravity's `Cwd` key, the leading-`]` rule, either zsh-group rule, ANSI-C decoding or its numeric-escape rule, the `\o` reading, the inline-code rule, the nesting-depth rule, the nested-script scan, the line-continuation join, the Windows escape reading, the shell-option and interpreter-option value skips, the added runners and interpreters, the glued-flag value, the `file:` URL path, the `~+` resolution, the unknown-tilde rule, the parameter-default reading or case folding each fails the Rust tests, and each TypeScript counterpart fails the Node evidence test; so does reverting the `file:` URL cut, the deep-default rule, the escaped-default reading, the quoted-tilde rule, the harness-output rule or Unicode folding (the new fixture vectors fail against the previous matchers in both languages), and disabling the foreign-marker lookup fails the native, import and Node cross-checkout tests; reading every glob location as literal, skipping search/list locations, or skipping a file tool whose targets cannot be read each fails the native, import and Node glob/search/unreadable tests, removing `apply_patch` header reading fails the own-patch control, and reverting the saved-output glob rule fails the new fixture vectors in both languages; walking globs rooted inside the event's checkout fails the monorepo tests, accepting any literal text for a saved-output glob fails the `*.log` vectors, removing the time budget or counting a `**`'s directories only after it lists fails the bounds tests, and removing the `**`-then-`..` readings, the brace-expansion check, the expanded lookup words, the patch-header trim or the `file_glob` key each fails the Rust tests and the Node evidence test || 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH || 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` || 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG |