Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(capture): close round-9 gaps in cross-checkout policy lookup
AkitaOnRailsf91a16b5b976
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 20863362..a484dd38 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -54,11 +54,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0file tool whose target cannot be read. A glob inside the event's owncheckout 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 dot glob that older bash- expands to the parent directory, 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 broken+ or without a marker, and neither are a large brace expansion that cannot+ leave it (`touch test/file{1..200}.txt`) or the checkout's own subtree under+ a `**` that starts above it. Each directory's marker is looked up once, so+ many paths in a deep tree stay within the hook's time budget, and a+ dotfiles `.git` in the home directory no longer counts as every project's+ own checkout. A `..` after a `**`, a dot glob that older bash+ expands to the parent directory (POSIX classes and extglobs included), a+ brace expansion, a zsh glob group, an ANSI-C escape (also inside a+ double-quoted `bash -c` or `eval` script), 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'sdiff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex af6011b4..41e8d0b8 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -1306,9 +1306,8 @@ pub(crate) fn tool_location_routing_cwd(source_keeps.then(|| dir.to_string_lossy().into_owned())}-/// How many distinct directories, and markers other than the event's own, one-/// tool call may make [`foreign_capture_decision`] look up.-const MAX_FOREIGN_DIRECTORIES: usize = 256;+/// How many markers other than the event's own one tool call may make+/// [`foreign_capture_decision`] apply.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, and how long: a hook has@@ -1316,6 +1315,12 @@ const MAX_FOREIGN_MARKERS: usize = 16;const MAX_GLOB_DIRECTORIES: usize = 256;const MAX_GLOB_ENTRIES: usize = 32_768;const MAX_GLOB_TIME: Duration = Duration::from_millis(50);+/// How many filesystem probes looking up the markers of one call's locations+/// may cost; each directory's marker is found once ([`MarkerMemo`]), so only+/// a tree built to be deep and wide reaches it.+///+/// [`MarkerMemo`]: crate::marker::MarkerMemo+const MAX_LOOKUP_PROBES: usize = 16_384;/// 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,@@ -1326,23 +1331,53 @@ const MAX_GLOB_TIME: Duration = Duration::from_millis(50);////// 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, 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+/// with each directory's answer remembered for every lookup that passes it+/// ([`MarkerMemo`]), so a deep tree costs one probe per directory. A location+/// with glob syntax ([`glob_walk`]) is looked up from its literal root first,+/// and, when that root lies outside the event's own checkout, 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. 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.+/// symlink), and a `**` lists the whole subtree except the own checkout's. 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. The own checkout is the nearest `.git` root of+/// the cwd unless that is the filesystem root or lies at or above the home+/// directory ([`own_checkout`]).+///+/// The walk and the lookups share one budget of time, directories, entries+/// and probes. Locations outside the own checkout come first: there a call+/// naming more locations or markers than the bounds, a walk or lookup past+/// the 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. Inside the own checkout the own policy governs, so running out of+/// budget there ends the lookup without failing closed.+///+/// [`MarkerMemo`]: crate::marker::MarkerMemopub(crate) fn foreign_capture_decision(agent: AgentKind,raw: &serde_json::Value,inspection_cwd: &str,own_marker: Option<&Path>,+) -> Option<CaptureDecision> {+ foreign_decision_within(+ agent,+ raw,+ inspection_cwd,+ own_marker,+ home_dir().as_deref(),+ || GlobBudget::new(MAX_GLOB_TIME),+ )+}++/// [`foreign_capture_decision`] with the home directory and the budget given;+/// the budget is made once the event's own lookups are done.+fn foreign_decision_within(+ agent: AgentKind,+ raw: &serde_json::Value,+ inspection_cwd: &str,+ own_marker: Option<&Path>,+ home: Option<&Path>,+ budget: impl FnOnce() -> GlobBudget,) -> Option<CaptureDecision> {let unprovable = || {Some(@@ -1353,65 +1388,93 @@ pub(crate) fn foreign_capture_decision(),)};- let home = home_dir();- let Some(locations) = capture_lookup_locations(- agent,- raw,- inspection_cwd,- home.as_deref().and_then(Path::to_str),- ) else {+ let Some(locations) =+ capture_lookup_locations(agent, raw, inspection_cwd, home.and_then(Path::to_str))+ else {return unprovable();};- let mut directories: std::collections::HashMap<PathBuf, Option<PathBuf>> =- std::collections::HashMap::new();let mut markers: Vec<PathBuf> = Vec::new();- let checkout = crate::marker::checkout_root(Path::new(inspection_cwd));- let mut walk = GlobBudget::new(MAX_GLOB_TIME);- for location in locations {- let location = match glob_walk(&location) {- GlobWalk::Literal => location,- GlobWalk::Unprovable => return unprovable(),- GlobWalk::Walk { root, steps } => {- let Some(found) = walk.markers_below(Path::new(&root), &steps, checkout.as_deref())- else {- return unprovable();- };- for marker in found {- if Some(marker.as_path()) == own_marker || markers.contains(&marker) {- continue;- }- if markers.len() == MAX_FOREIGN_MARKERS {- return unprovable();- }- markers.push(marker);- }- root+ let mut memo = crate::marker::MarkerMemo::with_home(home);+ // The event's own lookups already paid for these, outside the budget; a+ // location below the cwd then stops at it.+ let cwd = Path::new(inspection_cwd);+ let checkout = memo+ .checkout_root(cwd, &mut || Some(()))+ .flatten()+ .filter(|root| own_checkout(root, home));+ memo.remember(cwd, own_marker);+ if cwd.is_dir() {+ memo.note_directory(cwd);+ }+ let mut walk = budget();+ // Locations outside the own checkout first: there another checkout's+ // policy may apply, so running out of budget there is unprovable, and a+ // long list inside the checkout must not spend it first. Inside it the+ // own policy governs, as for a glob rooted there; a marker nested in it+ // is found while the budget lasts, the shallowest locations first.+ let (outside, mut inside): (Vec<String>, Vec<String>) =+ locations.into_iter().partition(|location| {+ checkout+ .as_deref()+ .is_none_or(|checkout| !Path::new(location).starts_with(checkout))+ });+ inside.sort_by_key(|location| Path::new(location).components().count());+ let inside_from = outside.len();+ for (index, location) in outside.into_iter().chain(inside).enumerate() {+ // Past a bound, a location inside the own checkout ends the lookup;+ // one outside it is unprovable.+ let exhausted = || {+ if index >= inside_from {+ None+ } else {+ Some(unprovable())}};- let Some(dir) = existing_target_dir(Path::new(&location)) else {- continue;+ let (lookup, steps) = match glob_walk(&location) {+ GlobWalk::Literal => (location, None),+ GlobWalk::Unprovable => return unprovable(),+ GlobWalk::Walk { root, steps } => (root, Some(steps)),};- let marker = match directories.get(&dir) {- Some(marker) => marker.clone(),- None => {- if directories.len() == MAX_FOREIGN_DIRECTORIES {- return unprovable();- }- let marker = crate::marker::find_marker(&dir.to_string_lossy());- directories.insert(dir, marker.clone());+ // The literal root's marker first: a few probes, before a directory+ // listing that may spend the rest of the time budget on its own.+ let Some(dir) = memo.existing_dir(Path::new(&lookup), &mut || walk.probe()) else {+ match exhausted() {+ Some(decision) => return decision,+ None => break,+ }+ };+ let marker = match dir {+ Some(dir) => {+ let Some(marker) = memo.find_marker(&dir, &mut || walk.probe()) else {+ match exhausted() {+ Some(decision) => return decision,+ None => break,+ }+ };marker}+ None => None,};- let Some(marker) = marker else {- continue;+ let below = match steps {+ Some(steps) => {+ let Some(found) =+ walk.markers_below(Path::new(&lookup), &steps, checkout.as_deref())+ else {+ return unprovable();+ };+ found+ }+ None => Vec::new(),};- if Some(marker.as_path()) == own_marker || markers.contains(&marker) {- continue;- }- if markers.len() == MAX_FOREIGN_MARKERS {- return unprovable();+ for marker in marker.into_iter().chain(below) {+ if Some(marker.as_path()) == own_marker || markers.contains(&marker) {+ continue;+ }+ if markers.len() == MAX_FOREIGN_MARKERS {+ return unprovable();+ }+ markers.push(marker);}- markers.push(marker);}markers.iter()@@ -1421,10 +1484,22 @@ pub(crate) fn foreign_capture_decision(.reduce(CaptureDecision::stricter)}-/// What following one call's glob locations has cost so far.+/// Whether a checkout root counts as the event's own for the rules that a+/// glob rooted inside it is not walked and that its locations come last:+/// not the filesystem root, and not at or above the home directory (a+/// dotfiles repository in `$HOME` would otherwise make every other checkout+/// under it "own"). It still counts as a checkout for marker lookups.+fn own_checkout(root: &Path, home: Option<&Path>) -> bool {+ let home = home.map(crate::marker::absolute_normalized);+ root.parent().is_some() && !home.is_some_and(|home| home.starts_with(root))+}++/// What following one call's glob locations and looking up their markers+/// has cost so far.struct GlobBudget {directories: usize,entries: usize,+ probes: usize,/// Time spent since the walk started; injectable so a test can stand in/// for a slow filesystem.elapsed: Box<dyn FnMut() -> Duration>,@@ -1441,11 +1516,19 @@ impl GlobBudget {Self {directories: 0,entries: 0,+ probes: 0,elapsed,limit,}}+ /// Counts one more filesystem probe of the marker lookup; `None` past+ /// [`MAX_LOOKUP_PROBES`] or the time budget the walk shares.+ fn probe(&mut self) -> Option<()> {+ self.probes += 1;+ (self.probes <= MAX_LOOKUP_PROBES && (self.elapsed)() <= self.limit).then_some(())+ }+/// Counts one more directory the glob reaches; `None` past the bound.fn reach(&mut self) -> Option<()> {self.directories += 1;@@ -1454,7 +1537,8 @@ impl GlobBudget {/// The marker files of every directory `steps` can reach below `root`,/// `root` itself excluded (its lookup is the caller's). Nothing when- /// `root` lies inside the event's own `checkout`. `None` past the bounds.+ /// `root` lies inside the event's own `checkout`, and a `**` lists+ /// nothing inside it. `None` past the bounds./// A step that reaches no directory ends the walk: the glob then matches/// nothing there.fn markers_below(@@ -1491,11 +1575,22 @@ impl GlobBudget {continue;}// Counted as listed: a deep tree must not cost a- // full listing before the bound applies.- let mut pending = self.child_directories(dir)?;+ // full listing before the bound applies. The own+ // checkout's subtree is skipped, as a glob rooted+ // in it is.+ let outside = |path: &PathBuf| {+ checkout.is_none_or(|checkout| !path.starts_with(checkout))+ };+ let mut pending: Vec<PathBuf> = self+ .child_directories(dir)?+ .into_iter()+ .filter(outside)+ .collect();while let Some(below) = pending.pop() {self.reach()?;- pending.extend(self.child_directories(&below)?);+ pending.extend(+ self.child_directories(&below)?.into_iter().filter(outside),+ );next.push(below);}}@@ -3809,6 +3904,223 @@ mod tests {);}+ /// The payload of a Bash call made from `cwd`.+ fn bash_call(cwd: &Path, command: &str) -> serde_json::Value {+ serde_json::json!({+ "session_id": "lookup",+ "cwd": cwd,+ "tool_name": "Bash",+ "tool_input": {"command": command},+ "tool_response": {"stdout": "x"}+ })+ }++ /// The disposition [`foreign_decision_within`] gives a call, `None` when no+ /// other marker governs it.+ fn foreign_disposition(+ cwd: &Path,+ command: &str,+ own_marker: Option<&Path>,+ home: Option<&Path>,+ budget: impl FnOnce() -> GlobBudget,+ ) -> Option<CaptureDisposition> {+ let raw = bash_call(cwd, command);+ foreign_decision_within(+ AgentKind::ClaudeCode,+ &raw,+ &lexical_capture_cwd(&cwd.to_string_lossy()),+ own_marker,+ home,+ budget,+ )+ .map(|decision| decision.protocol().disposition())+ }++ /// Regression (the docs promised it; v2.6.3 kept the call): a `**` that+ /// starts above the event's checkout skips the checkout's own subtree, so+ /// a checkout with more directories than the walk's bound keeps+ /// `ls ../**/README.md`. Adversarial: the sibling checkout's policy still+ /// drops `cat ../**/secrets.env`.+ #[test]+ fn a_globstar_above_the_checkout_skips_the_own_subtree() {+ let tmp = tempfile::tempdir().unwrap();+ let work = tmp.path().join("work");+ let own = work.join("own");+ let a = work.join("a");+ std::fs::create_dir_all(own.join(".git")).unwrap();+ for index in 0..300 {+ std::fs::create_dir_all(own.join(format!("d{index}"))).unwrap();+ }+ const _: () = assert!(300 > MAX_GLOB_DIRECTORIES);+ std::fs::create_dir_all(&a).unwrap();+ let fast = || GlobBudget::with_clock(MAX_GLOB_TIME, Box::new(|| Duration::ZERO));+ assert_eq!(+ fast().markers_below(&work, &[GlobStep::AnyDepth], Some(&own)),+ Some(Vec::new())+ );+ assert_eq!(+ fast().markers_below(&work, &[GlobStep::AnyDepth], None),+ None,+ "without the skip the own subtree exceeds the bound"+ );+ assert_eq!(+ foreign_disposition(&own, "ls ../**/README.md", None, None, fast),+ None+ );+ std::fs::write(+ a.join(".ai-memory.toml"),+ "[capture]\nignore_paths = [\"secrets.env\"]\n",+ )+ .unwrap();+ assert_eq!(+ foreign_disposition(&own, "cat ../**/secrets.env", None, None, fast),+ Some(CaptureDisposition::Drop)+ );+ }++ /// Regression (v2.6.3 answered in milliseconds): many paths inside a deep+ /// tree look each directory's marker up once, not once per path and+ /// level, and the lookup shares the walk's budget. Running out of it+ /// inside the own checkout keeps the call (the own policy governs there);+ /// outside it the call is unprovable. Adversarial: a location outside+ /// the checkout is looked up first, so a long list inside it cannot spend+ /// the budget before another checkout's policy is found, and inside it a+ /// shallow nested marker is found before a deep list.+ #[test]+ fn marker_lookups_in_a_deep_tree_cost_one_probe_per_directory() {+ let tmp = tempfile::tempdir().unwrap();+ let work = tmp.path().join("work");+ let own = work.join("own");+ let a = work.join("a");+ let depth = 300;+ let deep = (0..depth).fold(own.clone(), |dir, _| dir.join("d"));+ std::fs::create_dir_all(&deep).unwrap();+ std::fs::create_dir_all(own.join(".git")).unwrap();+ std::fs::create_dir_all(&a).unwrap();+ std::fs::write(+ a.join(".ai-memory.toml"),+ "[capture]\nignore_paths = [\"secrets.env\"]\n",+ )+ .unwrap();+ let spread: Vec<String> = (1..=depth)+ .map(|level| format!("{}f", "d/".repeat(level)))+ .collect();+ let inside = format!("cat {}", spread.join(" "));+ // A clock that counts its readings: one per probe or listing.+ let counted = |readings: std::rc::Rc<std::cell::Cell<usize>>, expire_after: usize| {+ move || {+ GlobBudget::with_clock(+ MAX_GLOB_TIME,+ Box::new(move || {+ readings.set(readings.get() + 1);+ if readings.get() > expire_after {+ MAX_GLOB_TIME * 2+ } else {+ Duration::ZERO+ }+ }),+ )+ }+ };+ let readings = std::rc::Rc::new(std::cell::Cell::new(0));+ assert_eq!(+ foreign_disposition(+ &own,+ &inside,+ None,+ None,+ counted(readings.clone(), usize::MAX)+ ),+ None+ );+ assert!(+ readings.get() < 5 * depth,+ "{} probes for {depth} levels",+ readings.get()+ );+ // Out of budget inside the own checkout: kept.+ let readings = std::rc::Rc::new(std::cell::Cell::new(0));+ assert_eq!(+ foreign_disposition(&own, &inside, None, None, counted(readings, 10)),+ None+ );+ // Out of budget outside it: unprovable.+ let outside = (0..depth).fold(work.join("elsewhere"), |dir, _| dir.join("d"));+ std::fs::create_dir_all(&outside).unwrap();+ let readings = std::rc::Rc::new(std::cell::Cell::new(0));+ assert_eq!(+ foreign_disposition(+ &own,+ &format!("cat {}/f", outside.display()),+ None,+ None,+ counted(readings, 10)+ ),+ Some(CaptureDisposition::MetadataOnly)+ );+ // The other checkout's location comes first, whatever the order.+ let attack = format!("{inside} ../a/secrets.env");+ let readings = std::rc::Rc::new(std::cell::Cell::new(0));+ assert_eq!(+ foreign_disposition(&own, &attack, None, None, counted(readings, 10)),+ Some(CaptureDisposition::Drop)+ );+ // Inside the checkout the shallowest locations come first, so a+ // marker nested near the top is found before a deep list spends the+ // budget.+ std::fs::create_dir_all(own.join("vendor")).unwrap();+ std::fs::write(+ own.join("vendor").join(".ai-memory.toml"),+ "[capture]\nignore_paths = [\"secrets.env\"]\n",+ )+ .unwrap();+ let nested = format!("{inside} vendor/secrets.env");+ let readings = std::rc::Rc::new(std::cell::Cell::new(0));+ assert_eq!(+ foreign_disposition(&own, &nested, None, None, counted(readings, 10)),+ Some(CaptureDisposition::Drop)+ );+ }++ /// Adversarial: a `.git` at the home directory (a dotfiles repository)+ /// does not make every checkout under home the event's own, so a glob+ /// from `~/Projects` into a sibling checkout is still walked and that+ /// checkout's policy drops the call. Control: a harmless glob is kept.+ #[test]+ fn a_dotfiles_checkout_at_home_is_not_the_own_checkout() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path().join("home");+ let projects = home.join("Projects");+ let a = projects.join("a");+ std::fs::create_dir_all(home.join(".git")).unwrap();+ std::fs::create_dir_all(projects.join("b")).unwrap();+ std::fs::create_dir_all(&a).unwrap();+ std::fs::write(+ a.join(".ai-memory.toml"),+ "[capture]\nignore_paths = [\"secrets.env\"]\n",+ )+ .unwrap();+ let fast = || GlobBudget::with_clock(MAX_GLOB_TIME, Box::new(|| Duration::ZERO));+ for command in [+ "cat */secrets.env".to_owned(),+ format!("cat {}/*/secrets.env", projects.display()),+ ] {+ assert_eq!(+ foreign_disposition(&projects, &command, None, Some(&home), fast),+ Some(CaptureDisposition::Drop),+ "{command}"+ );+ }+ assert_eq!(+ foreign_disposition(&projects, "cat */README.md", None, Some(&home), fast),+ Some(CaptureDisposition::Keep)+ );+ assert!(!own_checkout(&home, Some(&home)));+ assert!(!own_checkout(tmp.path(), Some(&home)));+ assert!(!own_checkout(Path::new("/"), None));+ assert!(own_checkout(&a, Some(&home)));+ }+/// 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@@ -3914,6 +4226,47 @@ mod tests {serde_json::json!({"pattern": "KEY", "path": "..", "file_glob": "a/*.env"}),),),+ (+ "ansi-c in a double-quoted script",+ "claude-code",+ bash("bash -c \"cat \\$'\\\\x2e\\\\x2e'/a/secrets.env\""),+ ),+ (+ "ansi-c in a double-quoted eval",+ "claude-code",+ bash("eval \"cat \\$'\\\\x2e\\\\x2e'/a/secrets.env\""),+ ),+ (+ "posix class dot glob",+ "claude-code",+ bash("cat .[[:punct:]]/a/secrets.env"),+ ),+ ("extglob at", "claude-code", bash("cat .@(.)/a/secrets.env")),+ (+ "extglob optional",+ "claude-code",+ bash("cat .?(.)/a/secrets.env"),+ ),+ (+ "extglob star",+ "claude-code",+ bash("cat .*(.)/a/secrets.env"),+ ),+ (+ "extglob plus",+ "claude-code",+ bash("cat .+(.)/a/secrets.env"),+ ),+ (+ "brace dot glob",+ "claude-code",+ bash("cat .{*,x}/a/secrets.env"),+ ),+ (+ "oversized brace sequence",+ "claude-code",+ bash("cat .{-..~}/a/secrets.env"),+ ),];for (name, agent, raw) in attacks {let data_dir = tmp.path().join(format!("data-{}", name.replace(' ', "-")));@@ -3958,6 +4311,39 @@ mod tests {serde_json::json!({"pattern": "KEY", "path": "sub", "file_glob": "x/*.rs"}),),),+ (+ "double-quoted script",+ "claude-code",+ bash("bash -c \"echo \\$HOME && cat ../a/README.md\""),+ ),+ ("posix class own", "claude-code", bash("ls .[[:alpha:]]*")),+ (+ "posix class own directory",+ "claude-code",+ bash("cat .[[:alpha:]]x/README.md"),+ ),+ // Regression (v2.6.3 kept these): an expansion too large to list+ // that cannot leave the checkout.+ (+ "oversized brace",+ "claude-code",+ bash("touch test/file{1..200}.txt"),+ ),+ (+ "oversized directory brace",+ "claude-code",+ bash("mkdir -p build/{1..100}/out"),+ ),+ (+ "oversized dotted brace",+ "claude-code",+ bash("rm -f logs/app.{1..99}.log"),+ ),+ (+ "oversized product",+ "claude-code",+ bash("cat data/{a..h}{1..9}.csv"),+ ),];for (name, agent, raw) in controls {let data_dir = tmp.path().join(format!("data-{}", name.replace(' ', "-")));diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex d53aff5a..b5f960d1 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -242,11 +242,13 @@ const CAPTURE_MAX_SHELL_NESTING = 4;const CAPTURE_MAX_CALL_ID_CHARS = 128;// Bounds on the other markers one call may make the policy read; mirror `capture_lookup_locations` and `foreign_capture_decision`.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 = 32768;const CAPTURE_MAX_GLOB_MS = 50;+const CAPTURE_MAX_LOOKUP_PROBES = 16384;+// The clock the walk and lookup budget reads; a test stands in a slow filesystem with it.+let captureNow: () => number = Date.now;// 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;@@ -270,11 +272,13 @@ function captureTrimComment(line: string): string { let quote = ""; let escaped// `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; a directory segment an older bash can expand to `..` is read as `..` too. 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[][] = [[]]; let overflow = false; const segments = tail.filter((x) => x && x !== "."); segments.forEach((x, index) => { const parent = index + 1 < segments.length && x !== ".." && captureCouldNameParent(x); 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 (parent) push(parts.slice(0, -1)); 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) overflow = true; readings = next; }); if (overflow) return false; return readings.map((out) => ({ path: root + (out.length ? (root.endsWith("/") ? "" : "/") + out.join("/") : ""), windows: root !== "/" })); }-// Whether a glob segment can match `..` where a leading-dot pattern matches the `.` and `..` entries (bash before 5.2): `.` then `*`, `?` or a class admitting `.`; mirrors `could_name_parent`.-function captureCouldNameParent(segment: string): boolean { if (!segment.startsWith(".")) return false; const rest = [...segment.slice(1)]; return /[*?\[]/.test(segment.slice(1)) && captureClassGlob(rest, ["."]); }-// A one-segment glob over `*`, `?` and `[…]` classes (`!`/`^` negates, ranges, a leading `]` is a member) matched against `text`; a `[` without a closing `]` is literal. Mirrors `class_glob_matches`.-function captureClassGlob(pattern: string[], text: string[]): boolean { if (!pattern.length) return !text.length; const head = pattern[0]; if (head === "*") { for (let skip = 0; skip <= text.length; skip++) if (captureClassGlob(pattern.slice(1), text.slice(skip))) return true; return false; } if (head === "?") return text.length > 0 && captureClassGlob(pattern.slice(1), text.slice(1)); if (head === "[") { const negated = pattern[1] === "!" || pattern[1] === "^"; const start = negated ? 2 : 1; let close = -1; for (let i = start + 1; i < pattern.length; i++) if (pattern[i] === "]") { close = i; break; } if (close < 0) return text[0] === "[" && captureClassGlob(pattern.slice(1), text.slice(1)); if (!text.length) return false; const c = text[0]; const members = pattern.slice(start, close); let found = false; for (let i = 0; i < members.length;) { if (i + 2 < members.length && members[i + 1] === "-") { found ||= members[i] <= c && c <= members[i + 2]; i += 3; } else { found ||= members[i] === c; i += 1; } } return found !== negated && captureClassGlob(pattern.slice(close + 1), text.slice(1)); } return text[0] === head && captureClassGlob(pattern.slice(1), text.slice(1)); }+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[][] = [[]]; let overflow = false; const segments = tail.filter((x) => x && x !== "."); segments.forEach((x, index) => { const parent = index + 1 < segments.length && x !== ".." && captureCouldNameParent(x); if (!parent && x !== "..") { for (const parts of readings) parts.push(x); return; } 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 (parent) push(parts.slice(0, -1)); 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) overflow = true; readings = next; }); if (overflow) return false; return readings.map((out) => ({ path: root + (out.length ? (root.endsWith("/") ? "" : "/") + out.join("/") : ""), windows: root !== "/" })); }+// Whether a glob segment can match `..` where a leading-dot pattern matches the `.` and `..` entries (bash before 5.2): `.` then `*`, `?`, a class admitting `.` (`[[:punct:]]` too) or an extglob group with an alternative matching `.` (`.@(.)`, `.!(x)`); mirrors `could_name_parent`.+function captureCouldNameParent(segment: string): boolean { if (!segment.startsWith(".")) return false; const rest = [...segment.slice(1)]; return /[*?\[(]/.test(segment.slice(1)) && captureClassGlob(rest, ["."]); }+// A one-segment glob over `*`, `?`, `[…]` classes (`!`/`^` negates, ranges, a leading `]` is a member, `[:name:]`, `[=c=]`, `[.c.]`) and extglob groups (`@(…)`, `?(…)`, `*(…)`, `+(…)`, `!(…)`) matched against a short `text`; an unclosed `[` or `(` is literal. Mirrors `class_glob_matches`.+function captureClassGlob(pattern: string[], text: string[]): boolean { if (!pattern.length) return !text.length; const head = pattern[0]; if ("@?*+!".includes(head) && pattern[1] === "(") { let depth = 0; let close = -1; for (let i = 1; i < pattern.length; i++) { if (pattern[i] === "(") depth++; else if (pattern[i] === ")" && --depth === 0) { close = i; break; } } if (close >= 0) { const alternatives: string[][] = []; let start = 2; depth = 0; for (let i = 2; i < close; i++) { if (pattern[i] === "(") depth++; else if (pattern[i] === ")") depth = Math.max(depth - 1, 0); else if (pattern[i] === "|" && depth === 0) { alternatives.push(pattern.slice(start, i)); start = i + 1; } } alternatives.push(pattern.slice(start, close)); const once = (t: string[]) => alternatives.some((alternative) => captureClassGlob(alternative, t)); const repeated = (t: string[]): boolean => { for (let split = 1; split <= t.length; split++) if (once(t.slice(0, split)) && (split === t.length || repeated(t.slice(split)))) return true; return false; }; const group = (t: string[]) => head === "@" ? once(t) : head === "?" ? !t.length || once(t) : head === "*" ? !t.length || repeated(t) : head === "+" ? repeated(t) : !once(t); for (let split = 0; split <= text.length; split++) if (group(text.slice(0, split)) && captureClassGlob(pattern.slice(close + 1), text.slice(split))) return true; return false; } } if (head === "*") { for (let skip = 0; skip <= text.length; skip++) if (captureClassGlob(pattern.slice(1), text.slice(skip))) return true; return false; } if (head === "?") return text.length > 0 && captureClassGlob(pattern.slice(1), text.slice(1)); if (head === "[") { const negated = pattern[1] === "!" || pattern[1] === "^"; const start = negated ? 2 : 1; const members: ((c: string) => boolean)[] = []; let i = start; if (pattern[i] === "]") { members.push((c) => c === "]"); i++; } let closed = false; while (i < pattern.length) { const c = pattern[i]; if (c === "]") { closed = true; break; } if (c === "[" && (pattern[i + 1] === ":" || pattern[i + 1] === "=" || pattern[i + 1] === ".")) { const kind = pattern[i + 1]; let end = -1; for (let at = i + 2; at + 1 < pattern.length; at++) if (pattern[at] === kind && pattern[at + 1] === "]") { end = at; break; } if (end >= 0) { const name = pattern.slice(i + 2, end).join(""); members.push(kind === ":" ? (x) => captureNamedClass(name, x) : (x) => [...name].length !== 1 || name === x); i = end + 2; continue; } members.push((x) => x === "["); i++; continue; } if (pattern[i + 1] === "-" && pattern[i + 2] !== undefined && pattern[i + 2] !== "]") { const low = c; const high = pattern[i + 2]; members.push((x) => low <= x && x <= high); i += 3; continue; } members.push((x) => x === c); i++; } if (!closed) return text[0] === "[" && captureClassGlob(pattern.slice(1), text.slice(1)); if (!text.length) return false; const found = members.some((member) => member(text[0])); return found !== negated && captureClassGlob(pattern.slice(i + 1), text.slice(1)); } return text[0] === head && captureClassGlob(pattern.slice(1), text.slice(1)); }+// Whether the POSIX class `[:name:]` admits `c`; an unknown class may admit anything. Mirrors `ClassMember::admits`.+function captureNamedClass(name: string, c: string): boolean { const code = c.codePointAt(0)!; const ascii = code < 128; switch (name) { case "alnum": return /[\p{L}\p{N}]/u.test(c); case "alpha": return /\p{L}/u.test(c); case "blank": return c === " " || c === "\t"; case "cntrl": return /\p{Cc}/u.test(c); case "digit": return /[0-9]/.test(c); case "lower": return /\p{Ll}/u.test(c); case "space": return /\s/.test(c); case "upper": return /\p{Lu}/u.test(c); case "word": return /[\p{L}\p{N}_]/u.test(c); case "xdigit": return /[0-9A-Fa-f]/.test(c); case "punct": return ascii && /[!-\/:-@\[-`{-~]/.test(c); case "graph": return code > 32 && code < 127; case "print": return code >= 32 && code < 127; case "ascii": return ascii; default: return true; } }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; } }@@ -382,14 +386,14 @@ function capturePushReading(word: string, tilde: boolean, split: CaptureSplit):// Mirrors `parameter_operands`: `${NAME:-w}`, `${NAME:=w}`, `${NAME:+w}` (or without `:`) become `w`, nested down to CAPTURE_MAX_SHELL_NESTING levels; the flag is set when one is nested deeper still.function captureParameterOperands(word: string): [string, boolean] | undefined { let current = captureReplaceOperands(word); if (current === undefined) return undefined; for (let i = 1; i < CAPTURE_MAX_SHELL_NESTING; i++) { const next = captureReplaceOperands(current); if (next === undefined) return [current, false]; current = next; } return [current, captureReplaceOperands(current) !== undefined]; }function captureReplaceOperands(word: string): string | undefined { let output = ""; let rest = word; let changed = false; for (;;) { const start = rest.indexOf("${"); if (start < 0) break; output += rest.slice(0, start); const body = rest.slice(start + 2); const name = (/^[A-Za-z0-9_]*/.exec(body) ?? [""])[0].length; const after = body.slice(name); const operator = /^:[-=+]/.test(after) ? 2 : /^[-=+]/.test(after) ? 1 : 0; const operand = after.slice(operator); let depth = 0; let end = -1; for (let i = 0; i < operand.length; i++) { const c = operand[i]; if (c === "{") depth++; else if (c === "}") { if (depth === 0) { end = i; break; } depth--; } } if (end >= 0 && name > 0 && operator > 0) { output += operand.slice(0, end); changed = true; rest = operand.slice(end + 1); } else { output += "${"; rest = body; } } output += rest; return changed ? output : undefined; }-function captureCommandName(word: string): string { const name = (word.split(/[\/\\]/).pop() ?? word).replace(/[A-Z]/g, (c) => c.toLowerCase()); return name.endsWith(".exe") ? name.slice(0, -4) : name; }+function captureCommandName(word: string): string { const name = word.slice(Math.max(word.lastIndexOf("/"), word.lastIndexOf("\\")) + 1).replace(/[A-Z]/g, (c) => c.toLowerCase()); return name.endsWith(".exe") ? name.slice(0, -4) : name; }// Skips options and their values (`bash -o pipefail -c`); mirrors `is_shell_script`/`takes_shell_value`.function captureShellScript(words: string[], index: number): boolean { let flagged = false; for (let i = index - 1; i >= 0; i--) { const word = words[i]; if (word.startsWith("-")) { flagged ||= !word.startsWith("--") && word.slice(1).includes("c"); continue; } if (word.length > 1 && word.startsWith("+")) continue; if (i > 0 && captureShellValueOption(words[i - 1])) continue; const name = captureCommandName(word); return (flagged && ["sh","bash","zsh","dash","ksh","mksh","ash","yash","fish","su","script"].includes(name)) || (i + 1 === index && name === "eval"); } return false; }function 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`. 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; }+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 === "\\" || 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`.@@ -430,14 +434,35 @@ function captureSearchScope(name: string, args: unknown): { roots: string[]; pat// 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 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 }; }+function captureGlobWalk(location: string): { root: string; steps: string[] } | null | undefined { if (location.includes("${") || !/[*?\[{(]/.test(location)) 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 (let index = first; index < segments.length; index++) { const segment = segments[index]; 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 ? captureBraceOverflowLeaves(segment) : alternatives.some((alternative) => /[\/\\]/.test(alternative) || leaves(alternative) || (index < segments.length - 1 && captureCouldNameParent(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; } }+// The bounds of a brace sequence body (`1..3`, `a..e`, `x..y..n`): first and last value and whether they are integers (else code points); undefined when it is not one. Mirrors `brace_sequence_bounds`.+function captureBraceSequenceBounds(body: string): [number, number, boolean] | undefined { const parts = body.split(".."); if (parts.length < 2 || parts.length > 3) return undefined; if (parts.length === 3 && !/^[+-]?\d+$/.test(parts[2])) return undefined; const integer = (part: string) => /^[+-]?\d+$/.test(part); if (integer(parts[0]) && integer(parts[1])) return [Number(parts[0]), Number(parts[1]), true]; const a = [...parts[0]]; const b = [...parts[1]]; if (a.length !== 1 || b.length !== 1) return undefined; return [a[0].codePointAt(0)!, b[0].codePointAt(0)!, false]; }+// Whether a segment whose brace expansion is too large to list could still build a word that leaves the root (a separator, `~`, a group, `..` or a dot-glob an older bash expands to it): integer and letter sequences cannot, nor a `.` where every word also holds another literal character; a character sequence over a range with `.`, a separator, `~` or a group character can. Mirrors `brace_overflow_could_leave`.+function captureBraceOverflowLeaves(segment: string): boolean { if (/[\/\\~()|]/.test(segment)) return true; const chars = [...segment]; const close: (number | undefined)[] = []; const comma: boolean[] = []; const open: number[] = []; chars.forEach((c, index) => { if (c === "{") open.push(index); else if (c === "}") { const start = open.pop(); if (start !== undefined) close[start] = index; } else if (c === "," && open.length) comma[open[open.length - 1]] = true; }); const glob = ".*?[]"; let dot = false; let anchor = false; const ends: number[] = []; for (let index = 0; index < chars.length;) { const c = chars[index]; if (ends.length && ends[ends.length - 1] === index) { ends.pop(); index++; continue; } const end = c === "{" ? close[index] : undefined; if (end !== undefined) { if (comma[index]) { ends.push(end); index++; continue; } const bounds = captureBraceSequenceBounds(chars.slice(index + 1, end).join("")); if (bounds) { const [from, to, numeric] = bounds; const holds = (set: string) => [...set].some((x) => { const code = x.codePointAt(0)!; return Math.min(from, to) <= code && code <= Math.max(from, to); }); if (!numeric && holds("./\\~()|")) return true; if (!ends.length && (numeric || !holds(glob))) anchor = true; index = end + 1; continue; } } if (c === "," && ends.length) { index++; continue; } if (c === ".") dot = true; if (!ends.length && !glob.includes(c)) anchor = true; index++; } return dot && !anchor; }+// The marker files of every directory `steps` reach below `root` (root excluded), never following a symlink; nothing when `root` lies inside `checkout`, and a "**" lists nothing inside it. 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; probes?: 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 listed = children(dir); if (!listed) return undefined; const pending = listed.filter((child) => !inside(child)); 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.filter((child) => !inside(child))); 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; }+// Whether a checkout root counts as the event's own for the no-walk rule and the lookup order: not the filesystem root, and not at or above the home directory (a dotfiles repository); mirrors `own_checkout`.+function captureOwnCheckout(root: string): boolean { const home = homedir(); const above = !!home && (resolve(home) === root || resolve(home).startsWith(join(root, "x").slice(0, -1))); return dirname(root) !== root && !above; }+// A missing path answers without an exception, which a deep tree's many misses would pay for.+function captureExists(path: string): boolean { try { return statSync(path, { throwIfNoEntry: false }) !== undefined; } catch (_e) { return false; } }+// `name` inside the resolved directory `dir`, without `join`'s normalizing pass over a long path.+const captureSep = join("a", "b").charAt(1);+function captureChild(dir: string, name: string): string { return dir.endsWith(captureSep) ? dir + name : dir + captureSep + name; }+// Counts one filesystem probe of the marker lookup against the walk's budget; false past CAPTURE_MAX_LOOKUP_PROBES or the deadline. Mirrors `GlobBudget::probe`.+function captureProbe(budget: CaptureGlobBudget): boolean { budget.probes = (budget.probes ?? 0) + 1; return budget.probes <= CAPTURE_MAX_LOOKUP_PROBES && budget.now() <= budget.deadline; }+// `findMarker` for the many directories one call names: every directory a lookup passes keeps its answer and its checkout root, so a deep tree costs one probe per directory; each probe is counted. Null when there is none, undefined past the budget. Mirrors `MarkerMemo`.+type CaptureMarkerMemo = { governing: Map<string, string | null>; checkouts: Map<string, string | null>; known?: Set<string> };+// Records that `dir` exists, and with it every ancestor; mirrors `MarkerMemo::note_directory`.+function captureMemoNote(dir: string, memo: CaptureMarkerMemo): void { memo.known ??= new Set(); for (let current = resolve(dir); !memo.known.has(current); current = dirname(current)) { memo.known.add(current); if (dirname(current) === current) break; } }+function captureMemoCheckout(dir: string, memo: CaptureMarkerMemo, budget: CaptureGlobBudget): string | null | undefined { const chain: string[] = []; let current = dir; let found: string | null; for (;;) { const known = memo.checkouts.get(current); if (known !== undefined) { found = known; break; } if (dirname(current) === current) { found = null; break; } if (!captureProbe(budget)) return undefined; chain.push(current); if (captureExists(captureChild(current, ".git"))) { found = current; break; } current = dirname(current); } for (const d of chain) memo.checkouts.set(d, found); return found; }+// Records the marker an earlier `findMarker` found from `dir` for every directory that walk passed: up to the marker's directory, or to its boundary when it found none (home inside it, else the checkout root, else `dir` alone). Mirrors `MarkerMemo::remember`.+function captureMemoRemember(dir: string, marker: string | undefined, memo: CaptureMarkerMemo): void { const home = homedir(); const start = resolve(dir); const within = (d: string, stop: string) => d === stop || d.startsWith(join(stop, "x").slice(0, -1)); let stop: string | null; if (marker) stop = dirname(marker); else if (!home) stop = null; else if (within(start, home)) stop = home; else stop = memo.checkouts.get(start) ?? start; if (stop !== null && !within(start, stop)) stop = start; for (let current = start; ; current = dirname(current)) { memo.governing.set(current, marker ?? null); if (current === stop || dirname(current) === current) break; } }+function captureMemoMarker(start: string, memo: CaptureMarkerMemo, budget: CaptureGlobBudget): string | null | undefined { const home = homedir(); const homePrefix = home ? join(home, "x").slice(0, -1) : ""; const chain: string[] = []; let current = resolve(start); let found: string | null; for (;;) { const known = memo.governing.get(current); if (known !== undefined) { found = known; break; } if (dirname(current) === current) { found = null; break; } if (!captureProbe(budget)) return undefined; chain.push(current); const marker = captureChild(current, ".ai-memory.toml"); if (captureExists(marker)) { found = marker; break; } let boundary = false; if (home && (current === home || current.startsWith(homePrefix))) boundary = current === home; else if (home) { if (memo.checkouts.get(dirname(current)) === null) boundary = true; else { const root = captureMemoCheckout(current, memo, budget); if (root === undefined) return undefined; boundary = root === null || root === current; } } if (boundary) { found = null; break; } current = dirname(current); } for (const d of chain) memo.governing.set(d, found); return found; }+// The nearest existing directory at or above `path`, probing only what is not known already: null when there is none, undefined past the budget; mirrors `MarkerMemo::existing_dir`.+function captureExistingDirWithin(path: string, memo: CaptureMarkerMemo, budget: CaptureGlobBudget): string | null | undefined { let probe = path; for (;;) { if (memo.known?.has(probe)) return probe; if (!captureProbe(budget)) return undefined; try { if (statSync(probe, { throwIfNoEntry: false })?.isDirectory()) { captureMemoNote(probe, memo); return probe; } } catch (_e) { /* not there yet */ } const parent = dirname(probe); if (parent === probe || parent === ".") return null; probe = parent; } }// An external lifecycle owner (`AI_MEMORY_CAPTURE_OWNER`, any value that is// non-empty after trimming) takes over capture for this process: the gate runs// before the capture-policy marker scan, so no disposition work, no marker read@@ -457,10 +482,8 @@ 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, 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, 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; } }+// 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 and remembered for every lookup that passes it; a glob location is looked up from its literal root (before the walk, whose one listing may spend the time budget) 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. Locations outside the own checkout come first: there unreadable targets, glob syntax the walk cannot follow, and anything past the bounds are unprovable, while running out of budget inside the own checkout ends the lookup. 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 markers: string[] = []; const memo: CaptureMarkerMemo = { governing: new Map(), checkouts: new Map() }; let checkout: string | undefined; if (cwd) { const root = captureMemoCheckout(resolve(cwd), memo, { dirs: 0, entries: 0, deadline: Infinity, now: Date.now, probes: -Infinity }); checkout = root && captureOwnCheckout(root) ? root : undefined; captureMemoRemember(cwd, own, memo); if (statSync(resolve(cwd), { throwIfNoEntry: false })?.isDirectory()) captureMemoNote(cwd, memo); } const budget: CaptureGlobBudget = { dirs: 0, entries: 0, deadline: captureNow() + CAPTURE_MAX_GLOB_MS, now: captureNow, probes: 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; }; const insideOwn = (location: string) => checkout !== undefined && (location === checkout || location.startsWith(join(checkout, "x").slice(0, -1))); const ordered = [...locations].filter((location) => !insideOwn(location)); const insideFrom = ordered.length; ordered.push(...[...locations].filter(insideOwn).sort((a, b) => a.split(/[\\/]/).length - b.split(/[\\/]/).length)); for (let index = 0; index < ordered.length; index++) { const location = ordered[index]; const walk = captureGlobWalk(location); if (walk === undefined) return invalid; const lookup = walk ? walk.root : location; const dir = captureExistingDirWithin(lookup, memo, budget); if (dir === undefined) { if (index >= insideFrom) break; return invalid; } const marker = dir === null ? null : captureMemoMarker(dir, memo, budget); if (marker === undefined) { if (index >= insideFrom) break; return invalid; } if (!remember(marker ?? undefined)) return invalid; 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; } } return markers.map((marker) => captureConfigAt(marker, cwd)); }function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { if (captureOwnedExternally()) return { disposition: "drop", payload }; if (captureServerRouted(cwd)) return { disposition: "drop", payload }; const markerPresent = !!findMarker(cwd); if (CAPTURE_MODE === "allowlist" && !markerPresent) return { disposition: "drop", payload }; const own = findMarker(cwd); let config = captureConfigAt(own, cwd); const tool = captureTool(payload); let disposition = captureDecide(tool, config); if (disposition !== "drop" && tool.family !== "unknown") for (const other of captureForeignConfigs(tool, config, cwd, own)) { const decided = captureDecide(tool, other); if (captureRank[decided] > captureRank[disposition]) { disposition = decided; config = other; } } if (config.state === "inactive") return { disposition, payload }; const protocol: CaptureProtocol = { version: CAPTURE_POLICY_V1, disposition, policy_state: config.state, tool_family: tool.family, path_count: tool.paths?.length ?? 0, extraction_state: tool.extraction }; if (disposition === "metadata-only") { const session = payload.sessionID ?? payload.sessionId ?? payload.session_id; const routing = typeof payload.cwd === "string" ? payload.cwd : cwd; return { disposition, protocol, payload: { ...(typeof session === "string" ? { session_id: session } : {}), ...(typeof routing === "string" ? { cwd: routing } : {}), tool_family: tool.family, tool_name: tool.family, ...(tool.callID ? { tool_call_id: tool.callID } : {}), _ai_memory_capture: protocol } }; } if (disposition === "keep") return { disposition, protocol, payload: { ...payload, _ai_memory_capture: protocol } }; return { disposition, protocol, payload }; }"##;TEMPLATE.replace("__AI_MEMORY_CAPTURE_MODE__", capture_mode)@@ -2782,6 +2805,27 @@ for (const dir of [conA, join(conB, ".git"), join(conB, "sub", "x")]) mkdirSync(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"], [bash("cat .*/a/secrets.env"), "con-dot-star"], [bash("cat ./.?/a/secrets.env"), "con-dot-question"], [{{ 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("ls .*"), "con-dot-list"], [bash("cat .config/x"), "con-dot-directory"], [bash("cat .github/*.yml"), "con-dot-glob"], [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);+// Double-quoted scripts, POSIX classes, extglobs, brace-built dot-globs and oversized expansions that could leave reach checkout A's policy; an oversized expansion that cannot leave is kept (v2.6.3 kept it). Mirrors the additions to `constructed_parent_steps_answer_to_another_checkout`.+for (const [command, label] of [["bash -c \"cat \\$'\\\\x2e\\\\x2e'/a/secrets.env\"", "con-dq-ansi"], ["eval \"cat \\$'\\\\x2e\\\\x2e'/a/secrets.env\"", "con-dq-eval"], ["cat .[[:punct:]]/a/secrets.env", "con-posix-class"], ["cat .@(.)/a/secrets.env", "con-extglob-at"], ["cat .?(.)/a/secrets.env", "con-extglob-optional"], ["cat .*(.)/a/secrets.env", "con-extglob-star"], ["cat .+(.)/a/secrets.env", "con-extglob-plus"], ["cat .{{*,x}}/a/secrets.env", "con-brace-dot-glob"], ["cat .{{-..~}}/a/secrets.env", "con-oversized-leaves"]]) check(capturePolicy(bash(command), conB).disposition !== "keep", label);+for (const [command, label] of [["bash -c \"echo \\$HOME && cat ../a/README.md\"", "con-dq-own"], ["ls .[[:alpha:]]*", "con-posix-own"], ["cat .[[:alpha:]]x/README.md", "con-posix-own-directory"], ["touch test/file{{1..200}}.txt", "con-oversized"], ["mkdir -p build/{{1..100}}/out", "con-oversized-directory"], ["rm -f logs/app.{{1..99}}.log", "con-oversized-dotted"], ["cat data/{{a..h}}{{1..9}}.csv", "con-oversized-product"]]) check(capturePolicy(bash(command), conB).disposition === "keep", label);+// A "**" above the checkout skips the own subtree; mirrors `a_globstar_above_the_checkout_skips_the_own_subtree`.+check(captureMarkersBelow(join(markerRoot, "mono-work"), ["**"], mono, fastBudget())?.includes(join(monoA, ".ai-memory.toml")) === true, "globstar-skips-own-subtree");+check(captureMarkersBelow(join(markerRoot, "mono-work"), ["**"], undefined, fastBudget()) === undefined, "globstar-own-subtree-exceeds-bound");+// Deep trees look each directory up once and share the budget; the other checkout's location comes first. Mirrors `marker_lookups_in_a_deep_tree_cost_one_probe_per_directory`.+const deepLevels = 300; let deepDir = conB; const deepWords: string[] = []; for (let level = 1; level <= deepLevels; level++) {{ deepDir = join(deepDir, "d"); deepWords.push("d/".repeat(level) + "f"); }} mkdirSync(deepDir, {{ recursive: true }});+check(capturePolicy(bash(`cat ${{deepWords.join(" ")}}`), conB).disposition === "keep", "deep-inside-kept");+// A clock that advances one millisecond per reading runs out within the deep list: inside the own checkout that keeps the call, and the other checkout's location is looked up first.+let readings = 0; captureNow = () => {{ readings++; return 0; }};+try {{ check(capturePolicy(bash(`cat ${{deepWords.join(" ")}}`), conB).disposition === "keep" && readings < 5 * deepLevels, `deep-one-probe-per-directory ${{readings}}`); }} finally {{ captureNow = Date.now; }}+let ticks = 0; captureNow = () => ticks++;+try {{ check(capturePolicy(bash(`cat ${{deepWords.join(" ")}}`), conB).disposition === "keep", "deep-out-of-budget-inside-kept"); check(capturePolicy(bash(`cat ${{deepWords.join(" ")}} ../a/secrets.env`), conB).disposition === "drop", "deep-attack-first"); mkdirSync(join(conB, "vendor"), {{ recursive: true }}); writeFileSync(join(conB, "vendor", ".ai-memory.toml"), '[capture]\nignore_paths = ["secrets.env"]\n'); ticks = 0; check(capturePolicy(bash(`cat ${{deepWords.join(" ")}} vendor/secrets.env`), conB).disposition === "drop", "deep-nested-shallow-first"); check(capturePolicy(bash(`cat ${{join(markerRoot, "elsewhere", "d".repeat(1), ...deepWords.slice(0, 120).map(() => "d"))}}/f`), conB).disposition === "metadata-only", "deep-out-of-budget-outside-unprovable"); }} finally {{ captureNow = Date.now; }}+const deepMemo: CaptureMarkerMemo = {{ governing: new Map(), checkouts: new Map() }}; const deepBudget2: CaptureGlobBudget = {{ dirs: 0, entries: 0, deadline: 50, now: () => 0, probes: 0 }}; let lookupDir = deepDir; for (let level = 0; level < deepLevels; level++, lookupDir = dirname(lookupDir)) check(captureMemoMarker(lookupDir, deepMemo, deepBudget2) === null, "deep-memo-answer");+check((deepBudget2.probes ?? 0) < 3 * deepLevels, `deep-memo-probes ${{deepBudget2.probes}}`);+check(captureMemoMarker(deepDir, {{ governing: new Map(), checkouts: new Map() }}, {{ dirs: 0, entries: 0, deadline: 50, now: () => 51, probes: 0 }}) === undefined, "deep-memo-past-budget");+// A `.git` at home does not make every checkout under it the own one; mirrors `a_dotfiles_checkout_at_home_is_not_the_own_checkout`.+const realHome = process.env.HOME; const dotHome = join(markerRoot, "dot-home"); const dotProjects = join(dotHome, "Projects"); for (const dir of [join(dotHome, ".git"), join(dotProjects, "a"), join(dotProjects, "b")]) mkdirSync(dir, {{ recursive: true }}); writeFileSync(join(dotProjects, "a", ".ai-memory.toml"), '[capture]\nignore_paths = ["secrets.env"]\n');+process.env.HOME = dotHome;+try {{ check(capturePolicy(bash("cat */secrets.env"), dotProjects).disposition === "drop", "dotfiles-home-glob"); check(capturePolicy(bash(`cat ${{dotProjects}}/*/secrets.env`), dotProjects).disposition === "drop", "dotfiles-home-absolute"); check(!captureOwnCheckout(dotHome), "dotfiles-home-not-own"); }} finally {{ process.env.HOME = realHome; }}// 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-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rsindex e8024f45..67853d87 100644--- a/crates/ai-memory-cli/src/marker.rs+++ b/crates/ai-memory-cli/src/marker.rs@@ -1024,6 +1024,187 @@ fn find_marker_matching<T>(}}+/// [`find_marker`] for the many directories one event names: every directory+/// a lookup passes through keeps its answer (and its [`checkout_root`]), so a+/// deep tree costs one probe per directory rather than one walk per lookup.+/// Each filesystem probe first calls the caller's `spend`; when that refuses,+/// the lookup stops with `None`.+pub(crate) struct MarkerMemo {+ home: Option<PathBuf>,+ governing: std::collections::HashMap<PathBuf, Option<PathBuf>>,+ checkouts: std::collections::HashMap<PathBuf, Option<PathBuf>>,+ /// Directories known to exist: one a probe found, and every ancestor of+ /// it.+ directories: std::collections::HashSet<PathBuf>,+}++impl MarkerMemo {+ pub(crate) fn with_home(home: Option<&Path>) -> Self {+ Self {+ home: home.map(absolute_normalized),+ governing: std::collections::HashMap::new(),+ checkouts: std::collections::HashMap::new(),+ directories: std::collections::HashSet::new(),+ }+ }++ /// Records that `dir` exists, and with it every ancestor.+ pub(crate) fn note_directory(&mut self, dir: &Path) {+ for ancestor in absolute_normalized(dir).ancestors() {+ if !self.directories.insert(ancestor.to_path_buf()) {+ break;+ }+ }+ }++ /// The nearest existing directory at or above `path` (an existing path's+ /// parent when it is not a directory), probing only what is not known+ /// already; `path` is taken as given, never joined to the process's own+ /// directory; `Some(None)` when there is none, `None` when `spend` refuses+ /// a probe first.+ pub(crate) fn existing_dir(+ &mut self,+ path: &Path,+ spend: &mut dyn FnMut() -> Option<()>,+ ) -> Option<Option<PathBuf>> {+ let mut candidate = path;+ loop {+ if self.directories.contains(candidate) {+ return Some(Some(candidate.to_path_buf()));+ }+ spend()?;+ if candidate.is_dir() {+ self.note_directory(candidate);+ return Some(Some(candidate.to_path_buf()));+ }+ match candidate.parent() {+ Some(parent) => candidate = parent,+ None => return Some(None),+ }+ }+ }++ /// The marker [`find_marker`] finds from `dir`; `None` when `spend`+ /// refuses a probe first.+ pub(crate) fn find_marker(+ &mut self,+ dir: &Path,+ spend: &mut dyn FnMut() -> Option<()>,+ ) -> Option<Option<PathBuf>> {+ let mut current = absolute_normalized(dir);+ let mut chain = Vec::new();+ let found = loop {+ if let Some(known) = self.governing.get(¤t) {+ break known.clone();+ }+ spend()?;+ let candidate = current.join(MARKER_FILENAME);+ if candidate.is_file() {+ chain.push(current);+ break Some(candidate);+ }+ // The same boundary as `find_marker_matching`: `$HOME` for a+ // directory inside it, else the nearest `.git` root (the+ // directory itself outside any checkout), else the filesystem+ // root when home is unknown.+ let boundary = match self.home.as_deref() {+ Some(home) if current.starts_with(home) => current == home,+ // Below a directory known to lie in no checkout, this one is+ // a checkout root or in none: a boundary either way.+ Some(_) => {+ current+ .parent()+ .is_some_and(|parent| matches!(self.checkouts.get(parent), Some(None)))+ || self+ .checkout_root(¤t, spend)?+ .is_none_or(|root| root == current)+ }+ None => false,+ };+ let parent = current.parent().map(Path::to_path_buf);+ chain.push(current);+ match parent {+ Some(parent)+ if !boundary+ && Some(parent.as_path()) != chain.last().map(PathBuf::as_path) =>+ {+ current = parent;+ }+ _ => break None,+ }+ };+ for dir in chain {+ self.governing.insert(dir, found.clone());+ }+ Some(found)+ }++ /// Records the marker an earlier [`find_marker`] found from `dir`, for+ /// `dir` and every directory that walk passed: up to the marker's own+ /// directory, or to the walk's boundary when it found none. Call it after+ /// [`Self::checkout_root`] of `dir`, which that boundary may need.+ pub(crate) fn remember(&mut self, dir: &Path, marker: Option<&Path>) {+ let start = absolute_normalized(dir);+ let stop = match marker {+ Some(marker) => marker.parent().map(absolute_normalized),+ None => match self.home.as_deref() {+ Some(home) if start.starts_with(home) => Some(home.to_path_buf()),+ Some(_) => self.checkouts.get(&start).cloned().flatten(),+ None => None,+ },+ };+ // Outside a checkout (or for a marker not above `dir`) the walk+ // checked `dir` alone.+ let stop = match (marker, &stop) {+ (_, Some(stop)) if start.starts_with(stop) => Some(stop.clone()),+ (None, None) if self.home.is_none() => None,+ _ => Some(start.clone()),+ };+ let mut current = Some(start.as_path());+ while let Some(dir) = current {+ self.governing+ .insert(dir.to_path_buf(), marker.map(Path::to_path_buf));+ if Some(dir) == stop.as_deref() {+ break;+ }+ current = dir.parent();+ }+ }++ /// [`checkout_root`] of `dir`, remembered for every directory passed.+ pub(crate) fn checkout_root(+ &mut self,+ dir: &Path,+ spend: &mut dyn FnMut() -> Option<()>,+ ) -> Option<Option<PathBuf>> {+ let mut current = absolute_normalized(dir);+ let mut chain = Vec::new();+ let found = loop {+ if let Some(known) = self.checkouts.get(¤t) {+ break known.clone();+ }+ spend()?;+ if current.join(".git").exists() {+ let root = current.clone();+ chain.push(current);+ break Some(root);+ }+ let parent = current.parent().map(Path::to_path_buf);+ chain.push(current);+ match parent {+ Some(parent) if Some(parent.as_path()) != chain.last().map(PathBuf::as_path) => {+ current = parent;+ }+ _ => break None,+ }+ };+ for dir in chain {+ self.checkouts.insert(dir, found.clone());+ }+ Some(found)+ }+}+/// Whether a marker's raw text declares anything beyond a `[capture]`/// section: any root-level scope key (`workspace`/`project`//// `project_strategy`), or any of the other settings@@ -1322,6 +1503,93 @@ mod tests {);}+ /// The memoized lookup answers exactly as `find_marker` does from every+ /// directory, inside home and outside it, in and out of a checkout, with+ /// and without a home; each directory costs one probe of each kind at+ /// most, however many lookups pass it, and directories an earlier walk+ /// already covered (`remember`) cost none.+ #[test]+ fn marker_memo_answers_like_find_marker_once_per_directory() {+ let tmp = TempDir::new().unwrap();+ let root = tmp.path().canonicalize().unwrap();+ let home = root.join("home");+ let dirs = [+ home.join("p").join("q").join("r"),+ home.join("s").join("t"),+ root.join("out").join("repo").join("u").join("v"),+ root.join("out").join("repo").join("w").join("z"),+ root.join("out").join("norepo").join("x").join("y"),+ ];+ for dir in &dirs {+ fs::create_dir_all(dir).unwrap();+ }+ fs::create_dir_all(root.join("out").join("repo").join(".git")).unwrap();+ for marked in [+ home.join("p"),+ root.join("out").join("repo"),+ root.join("out").join("repo").join("w"),+ root.join("out").join("norepo").join("x"),+ ] {+ write_marker(&marked, "workspace = \"w\"\n");+ }+ let every: Vec<PathBuf> = dirs+ .iter()+ .flat_map(|dir| dir.ancestors().take_while(|a| a.starts_with(&root)))+ .map(Path::to_path_buf)+ .collect();+ for home in [Some(home.as_path()), None] {+ let mut memo = MarkerMemo::with_home(home);+ let mut probes = 0;+ for dir in &every {+ let found = memo.find_marker(dir, &mut || {+ probes += 1;+ Some(())+ });+ assert_eq!(+ found,+ Some(find_marker_with_home(dir.to_str().unwrap(), home)),+ "{dir:?} with home {home:?}"+ );+ }+ let levels = every+ .iter()+ .map(|dir| dir.components().count())+ .sum::<usize>();+ assert!(+ probes <= 2 * every.len() + 2 * root.components().count(),+ "{probes}"+ );+ assert!(probes < levels, "{probes} probes, {levels} levels");+ // A refused probe stops the lookup.+ let mut fresh = MarkerMemo::with_home(home);+ assert_eq!(fresh.find_marker(&dirs[0], &mut || None), None);+ // What an earlier walk found costs nothing to look up again.+ for dir in &dirs {+ let mut seeded = MarkerMemo::with_home(home);+ if home.is_none() || !dir.starts_with(home.unwrap()) {+ seeded.checkout_root(dir, &mut || Some(()));+ }+ let found = find_marker_with_home(dir.to_str().unwrap(), home);+ seeded.remember(dir, found.as_deref());+ for ancestor in dir.ancestors().take_while(|a| a.starts_with(&root)) {+ let mut spent = false;+ let answer = seeded.find_marker(ancestor, &mut || {+ spent = true;+ Some(())+ });+ assert_eq!(+ answer,+ Some(find_marker_with_home(ancestor.to_str().unwrap(), home)),+ "{ancestor:?} below {dir:?} with home {home:?}"+ );+ if ancestor == dir.as_path() {+ assert!(!spent, "{dir:?}");+ }+ }+ }+ }+ }+#[test]fn find_marker_returns_none_without_one() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex 57501725..4297ef96 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -1664,8 +1664,8 @@ pub enum GlobWalk {},/// Syntax a walk cannot follow: a brace or group that spans a separator,/// or an alternative of `..` or `~…` inside one (also one a brace- /// expansion builds), which leaves the root.- /// Nothing proves which markers govern it.+ /// expansion builds, or a directory alternative older bash expands to+ /// `..`), which leaves the root. Nothing proves which markers govern it.Unprovable,}@@ -1697,10 +1697,10 @@ pub fn glob_segment_matches(segment: &str, name: &str) -> bool {pub fn glob_walk(location: &str) -> GlobWalk {// A parameter expansion's braces are not a brace expansion; the shell// split also reads the word with each default in its place.- if location.contains("${") {+ let syntax = |segment: &str| segment.contains(['*', '?', '[', '{', '(']);+ if location.contains("${") || !syntax(location) {return GlobWalk::Literal;}- let syntax = |segment: &str| segment.contains(['*', '?', '[', '{', '(']);let flavor = flavor_of(location);let Ok(normalized) = normalize_root(location) else {return GlobWalk::Literal;@@ -1724,7 +1724,8 @@ pub fn glob_walk(location: &str) -> GlobWalk {return GlobWalk::Literal;};let mut steps = Vec::new();- for segment in &segments[first..] {+ let last = segments.len() - 1;+ for (index, segment) in segments.iter().enumerate().skip(first) {if !syntax(segment) {steps.push(GlobStep::Named((*segment).to_owned()));continue;@@ -1733,18 +1734,24 @@ pub fn glob_walk(location: &str) -> GlobWalk {segment.matches(open).count() == segment.matches(close).count()};// A brace or group alternative of `..` or `~…` leaves the root, and- // so does one a brace expansion builds out of other pieces.+ // so does one a brace expansion builds out of other pieces, or a+ // directory alternative it builds that an older bash expands to `..`+ // (`.{*,x}/`). An expansion too large to list leaves only when its+ // pieces could build such a word.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)- })- }));+ && match brace_alternatives(segment) {+ Some(alternatives) => alternatives.iter().any(|alternative| {+ alternative.contains(['/', '\\'])+ || leaves_at(alternative)+ || (index < last && could_name_parent(alternative))+ }),+ None => brace_overflow_could_leave(segment),+ });if leaves || !balanced('{', '}') || !balanced('(', ')') {return GlobWalk::Unprovable;}@@ -1843,38 +1850,41 @@ fn expand_braces(text: &[char], words: &mut Vec<String>) -> Option<()> {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();+/// The bounds of a brace sequence body (`1..3`, `a..e`, `x..y..n`): the+/// first and last value, whether they are integers (else code points of+/// single characters), and the step. `None` when the body is not one.+fn brace_sequence_bounds(body: &str) -> Option<(i64, i64, bool, u64)> {let parts: Vec<&str> = body.split("..").collect();if !(2..=3).contains(&parts.len()) {- return Some(None);+ return None;}let step = match parts.get(2) {- Some(step) => match step.parse::<i64>() {- Ok(step) => step.unsigned_abs().max(1),- Err(_) => return Some(None),- },+ Some(step) => step.parse::<i64>().ok()?.unsigned_abs().max(1),None => 1,};- let bounds = match (parts[0].parse::<i64>(), parts[1].parse::<i64>()) {- (Ok(from), Ok(to)) => Some((from, to, true)),+ match (parts[0].parse::<i64>(), parts[1].parse::<i64>()) {+ (Ok(from), Ok(to)) => Some((from, to, true, step)),_ => {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 (from, to) = (single(parts[0])?, single(parts[1])?);+ Some((+ i64::from(u32::from(from)),+ i64::from(u32::from(to)),+ false,+ step,+ ))}- };- let Some((from, to, numeric)) = bounds else {+ }+}++/// The words of a brace sequence body: `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 Some((from, to, numeric, step)) = brace_sequence_bounds(&body) else {return Some(None);};let count = from.abs_diff(to) / step + 1;@@ -1904,6 +1914,90 @@ fn brace_sequence(body: &[char]) -> Option<Option<Vec<Vec<char>>>> {Some(Some(words))}+/// Whether a segment whose brace expansion has more words than+/// [`brace_alternatives`] lists could still build one that leaves the root:+/// one holding a separator, `~` or a group, or one that is `..` or a dot-glob+/// an older bash expands to it. Integer and letter sequences+/// (`file{1..200}.txt`, `{a..h}{1..9}`) build none of these, and neither does+/// a segment with a `.` only where every word also holds another literal+/// character (`app.{1..99}.log`). A character sequence over a range holding+/// `.`, a separator, `~` or a group character leaves.+fn brace_overflow_could_leave(segment: &str) -> bool {+ const LEAVING: [char; 7] = ['.', '/', '\\', '~', '(', ')', '|'];+ // Characters a glob can match a `.` with: never a word's anchor.+ const GLOB: [char; 5] = ['.', '*', '?', '[', ']'];+ if segment.contains(['/', '\\', '~', '(', ')', '|']) {+ return true;+ }+ let chars: Vec<char> = segment.chars().collect();+ // Pair each `{` with its `}` and note the ones holding a comma of their+ // own, in one pass.+ let mut close = vec![None; chars.len()];+ let mut comma = vec![false; chars.len()];+ let mut open = Vec::new();+ for (index, &c) in chars.iter().enumerate() {+ match c {+ '{' => open.push(index),+ '}' => {+ if let Some(start) = open.pop() {+ close[start] = Some(index);+ }+ }+ ',' => {+ if let Some(&start) = open.last() {+ comma[start] = true;+ }+ }+ _ => {}+ }+ }+ // `dot`: a word can hold a `.`; `anchor`: every word holds a literal+ // character no glob reads as `.`, so no word is `..` or matches it.+ let (mut dot, mut anchor) = (false, false);+ // The closing indexes of the comma braces the scan is inside.+ let mut ends: Vec<usize> = Vec::new();+ let mut index = 0;+ while index < chars.len() {+ let c = chars[index];+ if ends.last() == Some(&index) {+ ends.pop();+ index += 1;+ continue;+ }+ if c == '{'+ && let Some(end) = close[index]+ {+ if comma[index] {+ ends.push(end);+ index += 1;+ continue;+ }+ let body: String = chars[index + 1..end].iter().collect();+ if let Some((from, to, numeric, _)) = brace_sequence_bounds(&body) {+ let range = from.min(to)..=from.max(to);+ let holds = |set: &[char]| {+ set.iter()+ .any(|&c| range.contains(&i64::from(u32::from(c))))+ };+ if !numeric && holds(&LEAVING) {+ return true;+ }+ anchor |= ends.is_empty() && (numeric || !holds(&GLOB));+ index = end + 1;+ continue;+ }+ }+ if c == ',' && !ends.is_empty() {+ index += 1;+ continue;+ }+ dot |= c == '.';+ anchor |= ends.is_empty() && !GLOB.contains(&c);+ index += 1;+ }+ dot && !anchor+}+/// 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 {@@ -2534,7 +2628,10 @@ fn shell_tokens(command: &str, expand: bool) -> Vec<(String, bool)> {(Some('"') | None, '\\') if chars.peek() == Some(&'\n') => {chars.next();}- (Some('"'), '\\') if matches!(chars.peek(), Some('"' | '\\')) => {+ // Inside double quotes a backslash escapes `"`, `\`, `$` and a+ // backquote, so a script a shell re-reads (`bash -c "cat \$'…'"`)+ // sees the `$` itself.+ (Some('"'), '\\') if matches!(chars.peek(), Some('"' | '\\' | '$' | '`')) => {word.extend(chars.next());}(Some('$'), '\\') => match chars.next() {@@ -2874,55 +2971,201 @@ fn keep<'a>(readings: &mut Vec<Vec<&'a str>>, parts: Vec<&'a str>) {/// Whether a glob segment can match `..` in a shell that, like bash before/// 5.2, lets a pattern with a leading `.` match the `.` and `..` entries-/// (`.*`, `.?`, a class after the dot that admits `.`). zsh and newer bash-/// never do; reading the segment as `..` as well only adds a reading.+/// (`.*`, `.?`, a class after the dot that admits `.`, `[[:punct:]]` among+/// them, or an extglob group with an alternative that matches `.`, as in+/// `.@(.)` or `.!(x)`). zsh and newer bash never do; reading the segment as+/// `..` as well only adds a reading.fn could_name_parent(segment: &str) -> bool {let Some(rest) = segment.strip_prefix('.') else {return false;};- rest.contains(['*', '?', '[']) && class_glob_matches(&rest.chars().collect::<Vec<_>>(), &['.'])+ rest.contains(['*', '?', '[', '('])+ && class_glob_matches(&rest.chars().collect::<Vec<_>>(), &['.'])}-/// A one-segment glob over `*`, `?` and `[…]` classes (`!` or `^` negates,-/// `a-z` ranges, a leading `]` is a member) matched against `text`. A `[`-/// without a closing `]` is literal.+/// A one-segment glob over `*`, `?`, `[…]` classes (`!` or `^` negates,+/// `a-z` ranges, a leading `]` is a member, `[:name:]`, `[=c=]` and `[.c.]`+/// inside) and extglob groups (`@(…)`, `?(…)`, `*(…)`, `+(…)`, `!(…)`, `|`+/// between alternatives) matched against `text`. A `[` without a closing `]`+/// is literal, and so is a `(` without its `)`. Meant for short texts: a+/// group tries every split of the text.fn class_glob_matches(pattern: &[char], text: &[char]) -> bool {+ if let [kind @ ('@' | '?' | '*' | '+' | '!'), '(', ..] = pattern+ && let Some(close) = group_close(pattern, 1)+ {+ let alternatives = group_alternatives(&pattern[2..close]);+ let rest = &pattern[close + 1..];+ return (0..=text.len()).any(|split| {+ extglob_group_matches(*kind, &alternatives, &text[..split])+ && class_glob_matches(rest, &text[split..])+ });+ }match pattern.first() {None => text.is_empty(),Some('*') => (0..=text.len()).any(|skip| class_glob_matches(&pattern[1..], &text[skip..])),Some('?') => !text.is_empty() && class_glob_matches(&pattern[1..], &text[1..]),Some('[') => {- let negated = matches!(pattern.get(1), Some('!' | '^'));- let start = if negated { 2 } else { 1 };- // A `]` right after the opening (and negation) is a member.- let close = pattern- .iter()- .enumerate()- .skip(start + 1)- .find(|(_, c)| **c == ']')- .map(|(index, _)| index);- let Some(close) = close else {+ let Some((close, members)) = bracket_class(pattern) else {return text.first() == Some(&'[') && class_glob_matches(&pattern[1..], &text[1..]);};let Some(&c) = text.first() else {return false;};- let members = &pattern[start..close];- let mut index = 0;- let mut found = false;- while index < members.len() {- if index + 2 < members.len() && members[index + 1] == '-' {- found |= (members[index]..=members[index + 2]).contains(&c);- index += 3;+ members(c) && class_glob_matches(&pattern[close + 1..], &text[1..])+ }+ Some(&literal) => {+ text.first() == Some(&literal) && class_glob_matches(&pattern[1..], &text[1..])+ }+ }+}++/// The index of the `)` closing the group whose `(` is at `open`.+fn group_close(pattern: &[char], open: usize) -> Option<usize> {+ let mut depth = 0_usize;+ for (index, &c) in pattern.iter().enumerate().skip(open) {+ match c {+ '(' => depth += 1,+ ')' => {+ depth -= 1;+ if depth == 0 {+ return Some(index);+ }+ }+ _ => {}+ }+ }+ None+}++/// The `|`-separated alternatives of a group body, nested groups kept whole.+fn group_alternatives(body: &[char]) -> Vec<&[char]> {+ let mut alternatives = Vec::new();+ let (mut depth, mut start) = (0_usize, 0);+ for (index, &c) in body.iter().enumerate() {+ match c {+ '(' => depth += 1,+ ')' => depth = depth.saturating_sub(1),+ '|' if depth == 0 => {+ alternatives.push(&body[start..index]);+ start = index + 1;+ }+ _ => {}+ }+ }+ alternatives.push(&body[start..]);+ alternatives+}++/// Whether the extglob group `kind(alternatives)` matches all of `text`.+fn extglob_group_matches(kind: char, alternatives: &[&[char]], text: &[char]) -> bool {+ let once = |text: &[char]| {+ alternatives+ .iter()+ .any(|alternative| class_glob_matches(alternative, text))+ };+ // One or more alternatives in a row (`+`), or none as well (`*`).+ fn repeated(once: &dyn Fn(&[char]) -> bool, text: &[char]) -> bool {+ (1..=text.len()).any(|split| {+ once(&text[..split]) && (split == text.len() || repeated(once, &text[split..]))+ })+ }+ match kind {+ '@' => once(text),+ '?' => text.is_empty() || once(text),+ '*' => text.is_empty() || repeated(&once, text),+ '+' => repeated(&once, text),+ _ => !once(text),+ }+}++/// The `]` closing the bracket class that opens `pattern`, and whether the+/// class admits a character. `None` when no `]` closes it.+fn bracket_class(pattern: &[char]) -> Option<(usize, impl Fn(char) -> bool + '_)> {+ let negated = matches!(pattern.get(1), Some('!' | '^'));+ let start = if negated { 2 } else { 1 };+ // A `]` right after the opening (and negation) is a member.+ let mut index = start + usize::from(pattern.get(start) == Some(&']'));+ let mut members: Vec<ClassMember> = Vec::new();+ if index > start {+ members.push(ClassMember::Char(']'));+ }+ loop {+ match pattern.get(index)? {+ ']' => break,+ '[' if matches!(pattern.get(index + 1), Some(':' | '=' | '.')) => {+ let kind = pattern[index + 1];+ let end = (index + 2..pattern.len().saturating_sub(1))+ .find(|&at| pattern[at] == kind && pattern[at + 1] == ']');+ if let Some(end) = end {+ let name: String = pattern[index + 2..end].iter().collect();+ members.push(if kind == ':' {+ ClassMember::Named(name)+ } else {+ ClassMember::Symbol(name)+ });+ index = end + 2;} else {- found |= members[index] == c;+ members.push(ClassMember::Char('['));index += 1;}}- found != negated && class_glob_matches(&pattern[close + 1..], &text[1..])+ &low if pattern.get(index + 1) == Some(&'-')+ && pattern.get(index + 2).is_some_and(|&high| high != ']') =>+ {+ members.push(ClassMember::Range(low, pattern[index + 2]));+ index += 3;+ }+ &c => {+ members.push(ClassMember::Char(c));+ index += 1;+ }}- Some(&literal) => {- text.first() == Some(&literal) && class_glob_matches(&pattern[1..], &text[1..])+ }+ let admits = move |c: char| members.iter().any(|member| member.admits(c)) != negated;+ Some((index, admits))+}++/// One member of a bracket class.+enum ClassMember {+ Char(char),+ Range(char, char),+ /// `[:name:]`.+ Named(String),+ /// `[=c=]` or `[.c.]`.+ Symbol(String),+}++impl ClassMember {+ fn admits(&self, c: char) -> bool {+ match self {+ Self::Char(member) => *member == c,+ Self::Range(low, high) => (*low..=*high).contains(&c),+ Self::Named(name) => match name.as_str() {+ "alnum" => c.is_alphanumeric(),+ "alpha" => c.is_alphabetic(),+ "blank" => c == ' ' || c == '\t',+ "cntrl" => c.is_control(),+ "digit" => c.is_ascii_digit(),+ "lower" => c.is_lowercase(),+ "space" => c.is_whitespace(),+ "upper" => c.is_uppercase(),+ "word" => c.is_alphanumeric() || c == '_',+ "xdigit" => c.is_ascii_hexdigit(),+ "punct" => c.is_ascii_punctuation(),+ "graph" => c.is_ascii_graphic(),+ "print" => c.is_ascii_graphic() || c == ' ',+ "ascii" => c.is_ascii(),+ // A class this reading does not know may admit anything.+ _ => true,+ },+ // A single character, or a named collating element that may be it.+ Self::Symbol(symbol) => {+ let mut chars = symbol.chars();+ match (chars.next(), chars.next()) {+ (Some(only), None) => only == c,+ _ => true,+ }+ }}}}@@ -4979,6 +5222,69 @@ mod tests {assert_eq!(brace_alternatives(&"{a,b}".repeat(7)), None);}+ /// Regression (v2.6.3 kept these): a brace expansion with more words than+ /// [`brace_alternatives`] lists is walked like any glob, so inside the+ /// own checkout it costs nothing; only one whose pieces could build a+ /// separator, `~`, a group, `..` or a dot-glob that names the parent+ /// cannot be. Adversarial: such oversized braces stay unprovable. A+ /// directory alternative an older bash expands to `..` (`.{*,x}/`) is+ /// unprovable at any size.+ #[test]+ fn an_oversized_brace_expansion_is_walked_unless_its_pieces_could_leave() {+ for location in [+ "/work/b/test/file{1..200}.txt",+ "/work/b/build/{1..100}/out",+ "/work/b/logs/app.{1..99}.log",+ "/work/b/data/{a..h}{1..9}.csv",+ "/work/b/{A..Z}{a..z}/x",+ "/work/b/x{1..9}{1..9}.{a,b,c}/y",+ "/work/b/.{1..100}/y",+ "/work/b/.cache{1..100}/y",+ "/work/b/v{001..100}/y",+ "/work/b/{-100..100}/y",+ ] {+ assert!(+ matches!(glob_walk(location), GlobWalk::Walk { .. }),+ "{location}"+ );+ }+ for location in [+ "/work/b/.{-..~}/a/secrets.env",+ "/work/b/.{!..z}/a/x",+ "/work/b/.{.,a}{,}{,}{,}{,}{,}{,}/a/x",+ "/work/b/{.,}{.,}{,}{,}{,}{,}{,}/a/x",+ "/work/b/.{,a,b}{,c}{,d}{,e}{,f}{,g}*/a/x",+ "/work/b/{1..100}~/x",+ ] {+ assert_eq!(glob_walk(location), GlobWalk::Unprovable, "{location}");+ }+ for location in [+ "/work/b/.{*,x}/a/x",+ "/work/b/.{?,x}/a/x",+ "/work/b/x/.{[.],y}/z",+ ] {+ assert_eq!(glob_walk(location), GlobWalk::Unprovable, "{location}");+ }+ // A final segment names files, which never step out.+ assert!(matches!(glob_walk("/work/b/.{*,x}"), GlobWalk::Walk { .. }));+ for segment in [+ "file{1..200}.txt",+ "app.{1..99}.log",+ "{a..h}{1..9}.csv",+ "{x,y}{1..99}",+ ] {+ assert!(!brace_overflow_could_leave(segment), "{segment}");+ }+ for segment in [+ ".{-..~}",+ "{,.}{.,}{,}{,}{,}{,}{,}",+ ".{,a}{,b}{,c}{,d}{,e}{,f}{,g}*",+ "{0..z}",+ ] {+ assert!(brace_overflow_could_leave(segment), "{segment}");+ }+ }+/// 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@@ -5066,11 +5372,53 @@ mod tests {/// cannot match `..` read as before.#[test]fn a_dot_glob_directory_that_can_match_the_parent_is_read_as_it() {- for segment in [".*", ".?", ".[.]", ".[!x]", ".[^x]", ".[--0]", ".**"] {+ for segment in [+ ".*",+ ".?",+ ".[.]",+ ".[!x]",+ ".[^x]",+ ".[--0]",+ ".**",+ ".[[:punct:]]",+ ".[[:print:]]",+ ".[[:graph:]]",+ ".[[:ascii:]]",+ ".[![:alpha:]]",+ ".[^[:space:]]",+ ".[[=.=]]",+ ".[[.period.]]",+ ".[[:nope:]]",+ ".@(.)",+ ".?(.)",+ ".*(.)",+ ".+(.)",+ ".!(x)",+ ".@(x|.)",+ ".@(?)",+ ".+(@(.))",+ ] {assert!(could_name_parent(segment), "{segment}");}for segment in [- ".g*", ".[!.]", ".[x]", "*", "?", "..", ".", ".config", ".?x",+ ".g*",+ ".[!.]",+ ".[x]",+ "*",+ "?",+ "..",+ ".",+ ".config",+ ".?x",+ ".[[:alpha:]]",+ ".[[:digit:]]",+ ".[![:punct:]]",+ ".[[=x=]]",+ ".@(x)",+ ".+(x|y)",+ ".!(.)",+ ".@(.)x",+ "x@(.)",] {assert!(!could_name_parent(segment), "{segment}");}@@ -5094,13 +5442,27 @@ mod tests {capture_lookup_locations(AgentKind::ClaudeCode, &bash(command), "/work/b", None).unwrap()};- for command in ["cat .*/a/secrets.env", "cat ./.?/a/secrets.env"] {+ for command in [+ "cat .*/a/secrets.env",+ "cat ./.?/a/secrets.env",+ "cat .[[:punct:]]/a/secrets.env",+ "cat .@(.)/a/secrets.env",+ "cat .?(.)/a/secrets.env",+ "cat .*(.)/a/secrets.env",+ "cat .+(.)/a/secrets.env",+ ] {assert!(locations(command).contains(&"/work/a/secrets.env".to_owned()),"{command}");}- for command in ["ls .*", "cat .config/x", "cat .github/*.yml"] {+ for command in [+ "ls .*",+ "cat .config/x",+ "cat .github/*.yml",+ "cat .[[:alpha:]]*/x",+ "ls .[[:alnum:]]*",+ ] {assert!(locations(command).iter().all(|l| l.starts_with("/work/b")),"{command}"@@ -5130,6 +5492,20 @@ mod tests {"bash -c \"cat ../(a)/secrets.env\"","/work/(a)/secrets.env",),+ // A double-quoted script loses the backslash before `$`, so the+ // shell it runs reads an ANSI-C string.+ (+ "bash -c \"cat \\$'\\\\x2e\\\\x2e'/a/secrets.env\"",+ "/work/a/secrets.env",+ ),+ (+ "eval \"cat \\$'\\\\x2e\\\\x2e'/a/secrets.env\"",+ "/work/a/secrets.env",+ ),+ (+ "sh -c \"bash -c \\\"cat \\\\\\$'\\\\x2e\\\\x2e'/a/secrets.env\\\"\"",+ "/work/a/secrets.env",+ ),] {assert!(locations(command).contains(&location.to_owned()),diff --git a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json b/crates/ai-memory-hooks/tests/fixtures/capture-policy.jsonindex 0c454320..99918e77 100644--- a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json+++ b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json@@ -247,6 +247,11 @@{"command":"cat $'docs/adr/1.md'","disposition":"drop"},{"command":"cat $\"docs/adr/1.md\"","disposition":"drop"},{"command":"cat $'docs/\\x61dr/1.md'","disposition":"metadata-only"},+ {"command":"bash -c \"cat \\$'docs/\\\\x61dr/1.md'\"","disposition":"metadata-only"},+ {"command":"eval \"cat \\$'docs/\\\\x61dr/1.md'\"","disposition":"metadata-only"},+ {"command":"bash -c \"cat \\$'docs/adr/1.md'\"","disposition":"drop"},+ {"command":"bash -c \"cat \\$'src/main.rs'\"","disposition":"keep"},+ {"command":"bash -c \"echo \\$HOME \\`date\\`\"","disposition":"keep"},{"command":"cat d\\ocs/adr/1.md","disposition":"drop"},{"command":"cat docs/ad\\r/1.md","disposition":"drop"},{"command":"(cd src && cargo test)","disposition":"keep"},diff --git a/docs/marker-file.md b/docs/marker-file.mdindex df057fca..97b53550 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -634,9 +634,17 @@ event's directory has none) apply that marker's policy as well: `catcheckout, or a Hermes terminal call from an unmarked directory, is dropped when`other` ignores `secrets.env` (a search reaching a checkout with an activepolicy is dropped, as in its own checkout), and a broken marker there makes the-call metadata-only. Each directory is looked up once; a call naming more than-4,096 path locations, 256 directories or 16 other markers is metadata-only, and-so is a file tool whose target cannot be read or resolved.+call metadata-only. Each directory is looked up once, and what one lookup+learns about a directory serves every other location below it, so many paths+in a deep tree cost one check per directory. A call naming more than 4,096+path locations or 16 other markers is metadata-only, and so is a file tool+whose target cannot be read or resolved. The lookups share the glob walk's+budget below (50 ms, and at most 16,384 file checks); a glob's leading+directories are looked up before the walk below them. Locations outside the+event's own checkout are looked up first, and running out of budget there makes+the call metadata-only; inside the own checkout the event's own policy already+applies, so running out there ends the lookup and the call keeps its+disposition.A location with glob syntax in a directory name (`cat ../*/secrets.env`, `cat*/secrets.env` from a parent folder, `../{a,b}/x`, `../[ab]/x`)@@ -645,17 +653,28 @@ event's own checkout (the directory holding `.git`), every directory the globcould pass through is checked for a marker of its own: a `*`/`?` segment liststhe 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+except the event's own checkout, so `ls ../**/README.md` does not list the+checkout it runs in. A glob whose leading directories lieinside 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 `**`, and a dot-glob directory-segment that older bash can expand to `..`, are 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-reader+in a monorepo costs nothing however many packages it has. A `.git` at or above+your home directory (a dotfiles repository) or at the filesystem root does not+make that directory the own checkout for these rules, so `cat */secrets.env`+from `~/Projects` is still checked against the checkouts it reaches. 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, a brace+expansion that builds one, or a brace-built directory name that older bash+expands to `..` (`.{*,x}/`). A brace expansion too large to list (more than 64+words) counts as leaving only when its pieces could build such a word; integer+and letter sequences cannot, so `touch test/file{1..200}.txt` and `cat+data/{a..h}{1..9}.csv` are walked like any other glob. A `..` after a `**`,+and a dot-glob directory segment that older bash can expand to `..` (`.*`,+`.?`, a class such as `.[[:punct:]]`, or an extglob such as `.@(.)` or+`.+(.)`), are looked up in both readings, and a zsh glob group or an ANSI-C+numeric escape is looked up as the shell expands it, also inside a+double-quoted script (`bash -c "cat \$'…'"`, `eval "…"`), whose backslash+before `$` the outer shell removes. 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.@@ -700,6 +719,17 @@ can be mentioned.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 saved-output glob counts only when it spells three characters of the+ output file's distinctive name in a row, so a glob with no such literal run+ (`/tmp/p?-b*`) is read as an ordinary glob; requiring the literal text is+ what keeps `cat /tmp/*.log` and `tail log/*.log` ordinary;+- the own checkout is decided after the command ran, so a command that creates+ a `.git` (`touch .git; cat */x`) makes its directory the own checkout and its+ globs are not walked; a `.git` at or above the home directory never counts,+ but one in any other directory does;+- a marker nested inside the own checkout is found only while the lookup+ budget lasts (the shallowest paths are looked up first); past it the+ event's own policy governs the remaining paths;- a value glued to a short flag is read after the flag's first letter only,not after a cluster (`-rf…`), and a `file:` URL's non-ASCII percent-escapesare not decoded;diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 51a7bf3a..16055fbe 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 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), and so is a directory segment that bash before 5.2 can expand to `..` (`could_name_parent`, `class_glob_matches`; TS `captureCouldNameParent`, `captureClassGlob`), read as `..` too; 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`, `a_dot_glob_directory_that_can_match_the_parent_is_read_as_it` (each attack with its control), the shell fixture's dot-glob directory vectors and their controls, the shell fixture's `**`-then-`..` and `*.log` vectors and the `read_many_files_directories` `**`-then-`..` vectors, **`hook.rs` `constructed_parent_steps_answer_to_another_checkout`** (a `..` after a `**` through a shell, a Glob pattern and a Grep filter, four brace expansions that build a parent step, two zsh glob groups, hex and octal ANSI-C escapes, two dot-glob directory segments, 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, the `file_glob` key or the dot-glob parent reading each fails the Rust tests and the Node evidence test |+| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized, and every word that holds several words, such as a quoted `sh -c` script or a `"$(…)"` substitution, re-split to four levels by `ShellCommand::split`/`push_nested_words`, a deeper script metadata-only; ANSI-C strings decoded and a backslash before an ordinary letter dropped (`shell_words`, `push_word`); backslash-newline continuations joined (`shell_words`); a parameter default's operand, a value glued to a short flag and a `file:` URL's path read as candidates (`parameter_operands`, `shell_arguments`, `file_url_path`); PowerShell and cmd escape characters read out under the `PowerShell` tool or on a Windows host (`without_windows_escapes`); `~+` resolved to the cwd and a `~-`/`~N`/`~name` prefix metadata-only (`names_unknown_directory`); shell and interpreter options that take a value skipped while looking for a `-c` script or inline code (`takes_shell_value`, `runs_inline_code`, which also lists `lua`/`Rscript`/`osascript -e`, and `su -c`/`script -c` as script runners); paths compared without regard to case on a macOS host (`fold_case`, set by `resolve`; patterns and candidates composed to NFC and lowercased in full by `fold_path`, TS `captureFold`; client-only, the server's sentinel re-inspection never depends on it); a `file:` URL cut at its query or fragment before decoding (`file_url_path`); a parameter default nested past four levels metadata-only and a default read again after backslash removal (`parameter_operands`, `push_word_reading`); a tilde expanded or treated as an unknown directory only when the shell expands it, unquoted and in a script rather than a quoted message or argv element, every tilde under PowerShell (`marked_shell_words`, `literal_tildes`, `expand_tilde`); a file or shell read of a harness's saved tool output, or a glob that could match one, metadata-only under an active policy (`output_spool`: Claude Code `tool-results/` and `tasks/*.output`, OpenCode `tool-output/`, Pi `pi-bash-*.log`; glob segments fit a name they share a match with, `globs_intersect`, TS `captureGlobsIntersect`, and one fitting segment must spell three characters in a row of that name's distinctive text literally, `spells`, TS `captureSpells`, so `*.log` is not read as `pi-bash-*.log`, a trade-off that leaves a glob with no such literal run, `/tmp/p?-b*`, outside the rule; the TS matcher applies it to `read_many_files` entries too); every other marker governing a file-tool target (an `apply_patch`'s header paths, read after leading whitespace, `patch_paths`), a search/list tool's directory, file or path-like glob argument (`search_scope`, Hermes `file_glob` included; a grep `pattern` is not read) or a separator-bearing shell argument also inspects the call, found by the lexical marker walk from each location's nearest existing directory, each directory's answer remembered for every lookup that passes it (`marker.rs` `MarkerMemo`, TS `captureMemoMarker`, seeded with the event's own walk, `remember`, TS `captureMemoRemember`), bounded (4,096 locations, 16 markers, and 16,384 probes sharing the glob walk's 50 ms, `MAX_LOOKUP_PROBES`, TS `CAPTURE_MAX_LOOKUP_PROBES`; locations outside the own checkout are looked up first, a glob's literal root before the walk below it (whose single listing can spend the time budget on a large directory), and past a bound fail closed as under an invalid policy, while running out inside the own checkout, whose locations are looked up shallowest first, ends the lookup, its own policy governing there) and combined strictest-first (`capture_lookup_locations`, `CaptureDecision::stricter`, `hook.rs` `foreign_capture_decision`, also applied by `transcript_capture.rs` `decide_call`; TS `captureForeignConfigs`, `captureDecide`, `captureSearchScope`, `capturePatchPaths`); a location with glob syntax is looked up from its literal root and, when that root lies outside the event's `.git` checkout, every directory the glob could pass through is checked for a marker (`glob_walk`, `hook.rs` `GlobBudget::markers_below`; TS `captureGlobWalk`, `captureMarkersBelow`, `captureOwnCheckout`: a `*`/`?` segment lists the child directories it matches, a class/brace/group every child, a `**` the subtree except the event's checkout's; a glob rooted inside the event's checkout is not walked; a checkout root at or above the home directory, or the filesystem root, is never the own checkout for these rules (`own_checkout`), so a dotfiles `~/.git` does not stop the walk from `~/Projects`; symlinks never followed; 256 directories, counted as a `**` lists, 32,768 entries and 50 ms, `MAX_GLOB_TIME`, TS `CAPTURE_MAX_GLOB_MS`, injectable clock, past which, or for a brace/group spanning a separator, a `..`/`~` alternative or one a bounded brace expansion builds, `brace_alternatives`, TS `captureBraceAlternatives`, a directory alternative bash before 5.2 expands to `..` (`.{*,x}/`), or an expansion too large to list whose pieces could build one of these (`brace_overflow_could_leave`, TS `captureBraceOverflowLeaves`: integer and letter sequences cannot, so `file{1..200}.txt` is walked like any glob), the call fails closed); a `..` after a `**` is read both as the `**` matching no directory and as matching some, by the event's own matcher and the lookup (`normalize_readings`, TS `captureReadings`, at most 16 readings, past which the call fails closed), and so is a directory segment that bash before 5.2 can expand to `..` (`could_name_parent`, `class_glob_matches` with POSIX classes such as `[[:punct:]]` and extglob groups such as `@(.)`, `?(.)`, `*(.)`, `+(.)`, `!(x)`; TS `captureCouldNameParent`, `captureClassGlob`, `captureNamedClass`), read as `..` too; inside double quotes a backslash before `$` or a backquote is dropped, so a quoted script (`bash -c "…"`, `eval "…"`) re-split for its words reads an ANSI-C string as the shell it runs does (`shell_tokens`, TS `captureMarkedWords`); a zsh glob group kept in its word and ANSI-C numeric escapes decoded are fed to the lookup (`shell_tokens` with `expand`, `ShellWords::expanded`, `glob_group`, `ansi_c_numeric_escape`; TS `captureMarkedWords(…, true)`, `captureGlobGroup`, `captureAnsiNumeric`); a file tool whose targets cannot be read or resolved, and a search/list argument that is not a string, fail closed; the path of a git `REV:path` object name tried from the cwd and the marker directory (`git_object_path`); Antigravity `run_command` resolved from its `Cwd`); an invalid marker makes file, search/list and shell calls metadata-only; an active one makes a shell call metadata-only when a word uses unquoted brace expansion, a bracket class (a leading `]` included), a zsh glob group or extglob, or a numeric/control ANSI-C escape (`has_unevaluated_expansion`, also run on scripts given to `sh -c`, `eval` or a substitution), or when it runs inline interpreter code (`runs_inline_code`: `python -c`, `node -e`, `ruby -e`, `perl -e`, `php -r`, `deno eval`), and either makes tools that read back an earlier command's output metadata-only (`reads_earlier_output`: `BashOutput`, `TaskOutput`, `write_stdin`, `process`, `read_bash`/`write_bash` and PowerShell twins); the server admits a metadata-only shell or unknown-family body only under an active or invalid marker, with no paths and an `extracted` state (`router.rs` `metadata_protocol_is_legal`), and its own re-inspection strips an older client's keep for either; a Gemini `read_many_files` literal entry is also read as `entry/**` (`glob_matches_below`), and Copilot CLI's runtime `view`/`create`/`str_replace_editor` are file tools for that agent only (`agent_family`); 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`, `a_dot_glob_directory_that_can_match_the_parent_is_read_as_it` (POSIX classes and extglob groups included), `an_oversized_brace_expansion_is_walked_unless_its_pieces_could_leave` (each attack with its control), the shell fixture's double-quoted `bash -c`/`eval` ANSI-C vectors and their controls, `marker.rs` `marker_memo_answers_like_find_marker_once_per_directory`, **`hook.rs` `a_globstar_above_the_checkout_skips_the_own_subtree`** (regression: `ls ../**/README.md` from a 300-directory checkout with no policy is not metadata-only; the sibling `cat ../**/secrets.env` drops), **`hook.rs` `marker_lookups_in_a_deep_tree_cost_one_probe_per_directory`** (regression: 300 paths in a 300-level tree cost fewer than five probes per level; out of budget inside the checkout kept, outside it metadata-only, the sibling checkout's location looked up before a long list inside the checkout, and a shallow nested marker before a deep list), **`hook.rs` `a_dotfiles_checkout_at_home_is_not_the_own_checkout`** (with `~/.git`, `cat */secrets.env` from `~/Projects` drops; a harmless glob kept), the shell fixture's dot-glob directory vectors and their controls, the shell fixture's `**`-then-`..` and `*.log` vectors and the `read_many_files_directories` `**`-then-`..` vectors, **`hook.rs` `constructed_parent_steps_answer_to_another_checkout`** (a `..` after a `**` through a shell, a Glob pattern and a Grep filter, four brace expansions that build a parent step, two zsh glob groups, hex and octal ANSI-C escapes, two dot-glob directory segments, a POSIX-class and four extglob dot-glob segments, a brace-built dot-glob, an oversized brace sequence over `.`, ANSI-C strings in a double-quoted `bash -c` and `eval`, an indented `apply_patch` header next to an unindented one and a Hermes `file_glob` never spool content; the same shapes inside the checkout spool with it, and so do four brace expansions too large to list that cannot leave it, which v2.6.3 kept), **`hook.rs` `a_monorepo_glob_inside_the_own_checkout_is_not_walked`** (in a 300-package checkout, with and without a policy of its own, `packages/*` shell globs stay kept and the sibling `../*/secrets.env` and `../a/*.env` attacks still drop), `hook.rs` `a_glob_walk_outside_the_checkout_stops_at_its_bounds` (directory bound counted while a `**` lists, time budget through an injected clock, no walk inside the checkout), the Node evidence test's `monorepo-*`, `walk-*`, `con-*`, `globstar-*`, `deep-*` and `dotfiles-*` checks, and the Node evidence test's `glob-*`, `search-*`, `patch-*` and `unreadable-target` checks with their controls and `transcript_capture.rs` `a_shell_command_naming_another_checkouts_file_honors_its_policy`, both failing with the foreign lookup disabled, and the Node evidence test's `cross-*` and `fold-unicode` checks, which fail with `captureForeignConfigs` disabled, and the shell fixture's quoted-script, git-object, ANSI-C, escaped-letter and inline-interpreter vectors with their controls (`cargo test`, `git status`/`log`, `pytest`, `python3 -m pytest`, `node build.js`, `npm run test`, a quoted commit message with braces); `router.rs` `capture_protocol_active_keep_of_unprovable_output_is_stripped`; `hook.rs` `excluded_content_cannot_reach_the_spool_through_unevaluated_tool_shapes` (directory entries and Copilot `view`/`create` never spool, readers and brace shells spool without content, public controls spool with it); `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 marker nested inside the own checkout below what the lookup budget reaches, a `.git` the same command creates (`touch .git; cat */x`: the hook reads the tree after the command ran, so that directory counts as the own checkout; a `.git` at or above the home directory never does), a parameter expansion next to glob syntax (`${X}/*/x`, not walked), a glob through a symlinked directory, a tool's own directory option (`git -C`), script runners and interpreters the matcher does not list (their words are still read, but expansion or inline code in them is not recognized), a value glued after the first letter of a short-flag cluster, non-ASCII percent-escapes in a `file:` URL, a bare word naming another checkout's directory (only separator-bearing arguments are looked up for another marker), harness output files outside the listed default locations, and tools the matcher does not list, which keep their current unknown-tool behavior. Transcript imports add: assistant prose quoting an excluded file is kept (as live prompt/assistant capture keeps it), harnesses whose hook schema the matcher does not read (Crush, Kimi Code) keep their tool events as live capture would, adapters that record no per-record cwd (Pi, OMP, OpenCode, Crush, Kimi Code, Command Code, Kiro, Grok) judge every event from the session cwd, a Codex ledger upload resumed from a mid-file cursor judges the events before the next turn context from the session cwd, and id-less adapters over-drop a whole turn's results when one call is excluded, and when the routing hints leave the project to the server, events from inside one repository count as the importing project even where the server has a separate project registered for a subdirectory (anywhere under `repo-root`; under `basename` only when the import runs from the repository root); a metadata-only import keeps an `event_id` (ledger) and `ingest_key` (backfill) derived from a SHA-256 of the original content plus session and record ids, left in place because those ids are the retry-dedupe keys and a content-free id would merge distinct events — it only confirms a guess of low-entropy content. Under allowlist mode a refused checkout's `ai-memory run` still records repository checkpoint metadata (HEAD, branch, a status hash and changed-path names, never file content), which the run also sends at launch. Re-splitting quoted words over-drops a quoted message naming an ignored path, and inline interpreter code is metadata-only under an active policy. Mitigation: allowlist capture mode (`install-hooks --capture-mode allowlist`) for sensitive projects. Bite checks: removing the nested re-split, the git object path or its marker-root base, Antigravity's `Cwd` key, the leading-`]` rule, either zsh-group rule, ANSI-C decoding or its numeric-escape rule, the `\o` reading, the inline-code rule, the nesting-depth rule, the nested-script scan, the line-continuation join, the Windows escape reading, the shell-option and interpreter-option value skips, the added runners and interpreters, the glued-flag value, the `file:` URL path, the `~+` resolution, the unknown-tilde rule, the parameter-default reading or case folding each fails the Rust tests, and each TypeScript counterpart fails the Node evidence test; so does reverting the `file:` URL cut, the deep-default rule, the escaped-default reading, the quoted-tilde rule, the harness-output rule or Unicode folding (the new fixture vectors fail against the previous matchers in both languages), and disabling the foreign-marker lookup fails the native, import and Node cross-checkout tests; reading every glob location as literal, skipping search/list locations, or skipping a file tool whose targets cannot be read each fails the native, import and Node glob/search/unreadable tests, removing `apply_patch` header reading fails the own-patch control, and reverting the saved-output glob rule fails the new fixture vectors in both languages; walking globs rooted inside the event's checkout fails the monorepo tests, accepting any literal text for a saved-output glob fails the `*.log` vectors, removing the time budget or counting a `**`'s directories only after it lists fails the bounds tests, and removing the `**`-then-`..` readings, the brace-expansion check, the expanded lookup words, the patch-header trim, the `file_glob` key or the dot-glob parent reading each fails the Rust tests and the Node evidence test; treating every oversized brace expansion as leaving, dropping the brace-built dot-glob check, listing the own checkout's subtree under a `**`, looking up locations in their given order (outside before inside, then shallowest first), dropping the per-directory memo, counting a checkout at home as the own one, keeping the backslash before `$` in double quotes, or dropping the POSIX-class or extglob reading each fails its Rust test and the Node evidence test || 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 |