Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(capture): read Windows spellings, bound the spool check, align TS reader

AkitaOnRails3d7161414aa8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6c8f84bb..af3bf110 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -76,6 +76,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
reads is metadata-only, and a backslash escape inside a default is read. A
quoted `~` (`git commit -m "fix ~approx"`) is no longer treated as a home
or user directory, so such commands are kept again.
+ In a Windows session, Git Bash, MSYS2 and Cygwin spellings (`/c/...`,
+ `/cygdrive/c/...`), a rooted path without a drive, the `\\?\`, `\\.\` and
+ `\\localhost\C$` prefixes, an alternate data stream suffix and trailing dots
+ or spaces are read as the file they open, so they no longer slip past a
+ pattern. Hermes `execute_code` is metadata-only under an active policy, like
+ `python3 -c`, and a shell command longer than 1 MiB is metadata-only instead
+ of being split. The generated TypeScript integrations now read a dotted
+ `capture.ignore_paths` key and quoted `[capture]` headers, reject the shapes
+ the native hook rejects (an inline `capture = { ... }` table among them),
+ recognize the same file tools (`read_file`, `patch`, `fs_read`, ...), and stop
+ reading a directory at the walk's entry bound. Checking a path of thousands
+ of wildcard segments for a saved output file no longer takes seconds.
This applies to the native hook, the server, and the
generated TypeScript integrations. (GHSA-gcpc-88hm-3xqr)
- Fixed `ai-memory backfill`, including the automatic first-boot import, and
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index c8ac1542..e70163a7 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -1290,6 +1290,47 @@ mod tests {
assert!(read_capture_config(&marker).is_err());
}
+ /// Every TOML spelling of `[capture]` the native parser honours, and the
+ /// ones it rejects, from the shared fixture the generated TypeScript
+ /// reader's Node runtime evidence runs too: a dotted top-level key or a
+ /// quoted table name must not escape either reader, and a shape toml_edit
+ /// rejects (an inline table, `[[capture]]`) fails closed in both.
+ #[test]
+ fn capture_section_spellings_match_toml_semantics() {
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../ai-memory-hooks/tests/fixtures/capture-policy.json"
+ ))
+ .unwrap();
+ let spellings = &fixture["marker_spellings"];
+ let texts = |kind: &str| {
+ spellings[kind]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|text| text.as_str().unwrap().to_owned())
+ .collect::<Vec<_>>()
+ };
+ let tmp = tempfile::TempDir::new().unwrap();
+ let marker = tmp.path().join(".ai-memory.toml");
+ let read = |text: &str| {
+ std::fs::write(&marker, text).unwrap();
+ read_capture_config(&marker).map(|config| config.ignore_paths)
+ };
+ for honoured in texts("honoured") {
+ assert_eq!(
+ read(&honoured),
+ Ok(vec!["secret/**".to_owned()]),
+ "{honoured}"
+ );
+ }
+ for rejected in texts("rejected") {
+ assert!(read(&rejected).is_err(), "{rejected}");
+ }
+ for unrelated in texts("unrelated") {
+ assert_eq!(read(&unrelated), Ok(Vec::new()), "{unrelated}");
+ }
+ }
+
#[test]
fn canonical_context_matches_supported_routing_shapes() {
let agy =
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 95c0a8a1..30395c2a 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -4611,13 +4611,13 @@ fn add_hook_spooling(source: String) -> Result<String> {
"async function drainHookQueue(): Promise<void> {\n if (hookDraining) return;\n requestSpoolDrain();",
1,
);
- let import_anchor = "import { closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync } from \"node:fs\";";
+ let import_anchor = "import { closeSync, existsSync, opendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync } from \"node:fs\";";
if out.matches(import_anchor).count() != 1 {
anyhow::bail!("TS integration template drifted: node:fs import anchor not unique");
}
out = out.replacen(
import_anchor,
- "import { closeSync, existsSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";",
+ "import { closeSync, existsSync, mkdirSync, opendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";",
1,
);
Ok(out)
@@ -4644,7 +4644,7 @@ fn build_opencode_plugin(
import type {{ Plugin }} from "@opencode-ai/plugin";
import {{ execFileSync }} from "node:child_process";
-import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync }} from "node:fs";
+import {{ closeSync, existsSync, opendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync }} from "node:fs";
import {{ basename, dirname, join, resolve, sep }} from "node:path";
import {{ homedir }} from "node:os";
@@ -5392,7 +5392,7 @@ fn build_omp_extension(
// re-run.
import {{ execFileSync }} from "node:child_process";
-import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync }} from "node:fs";
+import {{ closeSync, existsSync, opendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync }} from "node:fs";
import {{ basename, dirname, join, resolve, sep }} from "node:path";
import {{ homedir }} from "node:os";
diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
index 6b621c87..ebf07e13 100644
--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
@@ -239,7 +239,7 @@ fn build_plugin(
import {{ definePluginEntry }} from "openclaw/plugin-sdk/plugin-entry";
import {{ execFileSync }} from "node:child_process";
-import {{ closeSync, existsSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync }} from "node:fs";
+import {{ closeSync, existsSync, mkdirSync, opendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync }} from "node:fs";
import {{ basename, dirname, join, resolve, sep }} from "node:path";
import {{ homedir }} from "node:os";
@@ -684,7 +684,7 @@ mod tests {
.unwrap()
.0;
let source = format!(
- "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst routeCwd={1};const direct=homeRoute(readHomeRouteText(join(homedir(),\".ai-memory.toml\")),routeCwd,\"github.com/acme/api\");const url=new URL(\"http://h/hook\");const ok=applyMarkerParams(url,routeCwd);process.stdout.write((direct?.project??\"none\")+\":\"+String(ok)+url.search);",
+ "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, opendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst routeCwd={1};const direct=homeRoute(readHomeRouteText(join(homedir(),\".ai-memory.toml\")),routeCwd,\"github.com/acme/api\");const url=new URL(\"http://h/hook\");const ok=applyMarkerParams(url,routeCwd);process.stdout.write((direct?.project??\"none\")+\":\"+String(ok)+url.search);",
helpers,
serde_json::to_string(&repo.to_string_lossy()).unwrap()
);
@@ -818,7 +818,7 @@ mod tests {
.0;
let module = tmp.path().join("openclaw-all-routes.ts");
let source = format!(
- "import {{ execFileSync as realExecFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction execFileSync(command:string,args:string[],options?:any):string{{return realExecFileSync(command,args,options) as string;}}\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst cases={} as any[];for(const c of cases){{const file=join(homedir(),\".ai-memory.toml\");writeFileSync(file,c.text);const url=new URL(\"http://h/hook\");let applied=false;let helper=\"none\";try{{const route=homeRoute(readHomeRouteText(file),c.cwd,c.identity);helper=route?route.workspace+\"/\"+route.project:\"none\";}}catch{{helper=\"invalid\";}}try{{applied=applyMarkerParams(url,c.cwd);}}catch{{applied=false;}}process.stdout.write(JSON.stringify({{name:c.name,applied,helper,params:Object.fromEntries(url.searchParams)}})+\"\\n\");}}",
+ "import {{ execFileSync as realExecFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, opendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction execFileSync(command:string,args:string[],options?:any):string{{return realExecFileSync(command,args,options) as string;}}\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst cases={} as any[];for(const c of cases){{const file=join(homedir(),\".ai-memory.toml\");writeFileSync(file,c.text);const url=new URL(\"http://h/hook\");let applied=false;let helper=\"none\";try{{const route=homeRoute(readHomeRouteText(file),c.cwd,c.identity);helper=route?route.workspace+\"/\"+route.project:\"none\";}}catch{{helper=\"invalid\";}}try{{applied=applyMarkerParams(url,c.cwd);}}catch{{applied=false;}}process.stdout.write(JSON.stringify({{name:c.name,applied,helper,params:Object.fromEntries(url.searchParams)}})+\"\\n\");}}",
helpers,
serde_json::to_string(&cases).unwrap()
);
@@ -960,7 +960,7 @@ mod tests {
.unwrap()
.0;
let source = format!(
- "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, unlinkSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst repoCwd={};const marker={};const homeMarker={};const run=(body:string)=>{{writeFileSync(marker,body);const url=new URL(\"http://h/hook\");applyMarkerParams(url,repoCwd);return Object.fromEntries(url.searchParams);}};const noMarkerUrl=new URL(\"http://h/hook\");applyMarkerParams(noMarkerUrl,repoCwd);const noMarker=Object.fromEntries(noMarkerUrl.searchParams);const plain=run('project=\"api\"\\n');const aliases=run('project=\"api\"\\naliases=[\"old-api\"]\\n');unlinkSync(marker);writeFileSync(homeMarker,'[routes.identity.\"github.com/acme/api\"]\\nroute_workspace=\"oss\"\\nroute_project=\"api\"\\n');const routedUrl=new URL(\"http://h/hook\");applyMarkerParams(routedUrl,repoCwd);process.stdout.write(JSON.stringify({{noMarker,plain,aliases,routed:Object.fromEntries(routedUrl.searchParams)}}));",
+ "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, opendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, unlinkSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst repoCwd={};const marker={};const homeMarker={};const run=(body:string)=>{{writeFileSync(marker,body);const url=new URL(\"http://h/hook\");applyMarkerParams(url,repoCwd);return Object.fromEntries(url.searchParams);}};const noMarkerUrl=new URL(\"http://h/hook\");applyMarkerParams(noMarkerUrl,repoCwd);const noMarker=Object.fromEntries(noMarkerUrl.searchParams);const plain=run('project=\"api\"\\n');const aliases=run('project=\"api\"\\naliases=[\"old-api\"]\\n');unlinkSync(marker);writeFileSync(homeMarker,'[routes.identity.\"github.com/acme/api\"]\\nroute_workspace=\"oss\"\\nroute_project=\"api\"\\n');const routedUrl=new URL(\"http://h/hook\");applyMarkerParams(routedUrl,repoCwd);process.stdout.write(JSON.stringify({{noMarker,plain,aliases,routed:Object.fromEntries(routedUrl.searchParams)}}));",
helpers,
serde_json::to_string(&repo.to_string_lossy()).unwrap(),
serde_json::to_string(&marker.to_string_lossy()).unwrap(),
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index b5f960d1..0d4b65eb 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -21,6 +21,7 @@
use std::borrow::Cow;
use std::path::{Path, PathBuf};
+use ai_memory_hooks::capture_policy;
use base64::Engine as _;
use serde_json::{Value, json};
@@ -240,6 +241,13 @@ const CAPTURE_MAX_CANDIDATES = 32;
const CAPTURE_MAX_WORK = 1000000;
const CAPTURE_MAX_SHELL_NESTING = 4;
const CAPTURE_MAX_CALL_ID_CHARS = 128;
+// Generated from `capture_policy.rs` (`FILE_TOOL_NAMES` and its siblings, `MAX_SHELL_COMMAND_CHARS`) so the two front doors cannot drift; never edit them here.
+const CAPTURE_FILE_TOOLS: string[] = __AI_MEMORY_FILE_TOOLS__;
+const CAPTURE_SEARCH_TOOLS: string[] = __AI_MEMORY_SEARCH_TOOLS__;
+const CAPTURE_NON_FILE_TOOLS: string[] = __AI_MEMORY_NON_FILE_TOOLS__;
+const CAPTURE_INLINE_CODE_TOOLS: string[] = __AI_MEMORY_INLINE_CODE_TOOLS__;
+const CAPTURE_OUTPUT_READER_TOOLS: string[] = __AI_MEMORY_OUTPUT_READER_TOOLS__;
+const CAPTURE_MAX_COMMAND_CHARS = __AI_MEMORY_MAX_COMMAND_CHARS__;
// 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_MARKERS = 16;
@@ -262,7 +270,7 @@ type CaptureProtocol = { version: 1; disposition: CaptureDisposition; policy_sta
type CaptureConfig = { state: "inactive" | "active" | "invalid"; patterns: { path: string; windows: boolean; directory?: string; prefix: string }[]; base: string; windowsHost: boolean; root?: string };
function readFileSync(path: string, encoding?: "utf8"): any { if (encoding) return readMarkerText(path, encoding); const fd = openSync(path, "r"); try { const bytes = Buffer.allocUnsafe(CAPTURE_MARKER_MAX_BYTES + 1); const count = readSync(fd, bytes, 0, bytes.length, 0); if (count > CAPTURE_MARKER_MAX_BYTES) throw new Error("marker too large"); const result = bytes.subarray(0, count); new TextDecoder("utf-8", { fatal: true }).decode(result); return result; } finally { closeSync(fd); } }
-function captureTrimComment(line: string): string { let quote = ""; let escaped = false; for (let i = 0; i < line.length; i++) { const c = line[i]; if (escaped) { escaped = false; continue; } if (c === "\\" && quote === '"') { escaped = true; continue; } if ((c === '"' || c === "'") && (!quote || quote === c)) quote = quote ? "" : c; else if (c === "#" && !quote) { line = line.slice(0, i); break; } } if (line.trimStart().startsWith("[") && !/^\s*\[[^\]]+\]\s*$/.test(line)) throw new Error("invalid table header"); if (quote) throw new Error("unterminated string"); return line; }
+function captureTrimComment(line: string): string { let quote = ""; let escaped = false; for (let i = 0; i < line.length; i++) { const c = line[i]; if (escaped) { escaped = false; continue; } if (c === "\\" && quote === '"') { escaped = true; continue; } if ((c === '"' || c === "'") && (!quote || quote === c)) quote = quote ? "" : c; else if (c === "#" && !quote) { line = line.slice(0, i); break; } } if (quote) throw new Error("unterminated string"); return line; }
// `windowsHost` is omitted for self-determining callers (the cwd/marker base,
// and ignore_paths patterns, which are allowed an explicit UNC/drive form
// regardless of host). It is passed explicitly, from the already-resolved
@@ -280,48 +288,75 @@ function captureClassGlob(pattern: string[], text: string[]): boolean { if (!pat
// 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}`; }
+// Under a Windows host, the absolute path Windows opens for `path` from `base`, `/`-separated with its `.` and `..` still in place: the `\\?\`, `\\.\` and `\??\` prefixes and the local administrative share (`\\localhost\C$`) name the drive or share (any other device is no path), Git Bash/MSYS2/Cygwin `/c/x` and `/cygdrive/c/x` are `C:/x`, any other rooted path is on the base's drive or share, and each segment loses an alternate data stream suffix and its trailing dots and spaces. Undefined when it is not usable; mirrors `windows_spelling`.
+function captureWindowsSpelling(path: string, base: string): string | undefined { if (/^[\x00-\x7f]:/.test(path) && !/^[A-Za-z]:[\\/]/.test(path)) return undefined; const b = captureNormalize(base)?.path ?? ""; let p = path.replace(/\\/g, "/"); if (/^(?:\/\/[?.]\/|\/\?\?\/)/.test(p)) { const rest = p.slice(4); if (/^unc\//i.test(rest)) p = `//${rest.slice(4)}`; else if (/^[A-Za-z]:/.test(rest)) p = rest; else return undefined; } if (/^[A-Za-z]:$/.test(p)) p += "/"; if (p.startsWith("//")) { const [server = "", share = "", ...rest] = p.slice(2).split("/"); if ((/^localhost$/i.test(server) || server === "127.0.0.1") && /^[A-Za-z]\$$/.test(share)) p = `${share[0]}:/${rest.join("/")}`; } else if (p.startsWith("/")) { const forward = path.startsWith("/"); const [first, ...after] = p.slice(1).split("/"); if (forward && /^[A-Za-z]$/.test(first)) p = `${first.toUpperCase()}:/${after.join("/")}`; else if (forward && first.toLowerCase() === "cygdrive" && /^[A-Za-z]$/.test(after[0] ?? "")) p = `${after[0].toUpperCase()}:/${after.slice(1).join("/")}`; else { const root = /^[A-Za-z]:/.test(b) ? b.slice(0, 2) : /^\/\/[^/]+\/[^/]+/.exec(b)?.[0]; if (root === undefined) return undefined; p = root + p; } } else if (!/^[A-Za-z]:\//.test(p)) { if (!b) return undefined; p = `${b.replace(/\/+$/, "")}/${p}`; } 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 return undefined; const parts = tail.map(captureWindowsSegment).filter((x): x is string => x !== undefined); return root + (parts.length ? (root.endsWith("/") ? "" : "/") + parts.join("/") : ""); }
+// One segment as Windows reads it; undefined when nothing is left. Mirrors `windows_segment`.
+function captureWindowsSegment(segment: string): string | undefined { const name = segment.split(":")[0]; const unspaced = name.replace(/ +$/, ""); if (unspaced === "." || unspaced === "..") return unspaced; return name.replace(/[. ]+$/, "") || undefined; }
+// The path a candidate names from `base`, read as Windows reads it on a Windows host.
+function captureResolve(path: string, base: string, windowsHost: boolean): string | undefined { if (windowsHost) return captureWindowsSpelling(path, base); return /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(path) ? path : captureJoin(base, path); }
+// Longer than CAPTURE_MAX_COMMAND_CHARS characters summed over its argv elements; mirrors `ShellCommand::oversized`.
+function captureCommandOversized(command: string | string[]): boolean { let total = 0; for (const item of typeof command === "string" ? [command] : command) for (const _c of item) if (++total > CAPTURE_MAX_COMMAND_CHARS) return true; return false; }
+// A TOML key (`a`, `"a"`, `'a'`, dotted `a . "b"`) at the start of `text`: its parts and the index past it and any blanks, or undefined. Enough of the key grammar to see every spelling of `capture`.
+function captureTomlKey(text: string): { parts: string[]; end: number } | undefined { const parts: string[] = []; let i = 0; for (;;) { while (text[i] === " " || text[i] === "\t") i++; if (text[i] === '"') { let j = i + 1; while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1; if (j >= text.length) return undefined; const decoded = captureParseArray(`[${text.slice(i, j + 1)}]`); if (!decoded) return undefined; parts.push(decoded[0]); i = j + 1; } else if (text[i] === "'") { const j = text.indexOf("'", i + 1); if (j < 0) return undefined; parts.push(text.slice(i + 1, j)); i = j + 1; } else { const bare = /^[A-Za-z0-9_-]+/.exec(text.slice(i)); if (!bare) return undefined; parts.push(bare[0]); i += bare[0].length; } while (text[i] === " " || text[i] === "\t") i++; if (text[i] !== ".") return { parts, end: i }; i++; } }
function captureValidGlob(p: string): boolean { return !!p && [...p].length <= CAPTURE_MAX_PATTERN_CHARS && !/[!{}\[\]()|^$%]/.test(p) && !p.includes("${") && !p.includes("***") && !p.replace(/\\/g, "/").split("/").includes("..") && (!p.startsWith("~") || p.startsWith("~/")) && !/^[^A-Za-z]?:/.test(p) && !/^[A-Za-z]:[^/\\]/.test(p); }
function captureParseArray(value: string): string[] | undefined { let i = 0; const out: string[] = []; const ws = () => { while (/\s/.test(value[i] ?? "")) i++; }; const basic = { b: "\b", t: "\t", n: "\n", f: "\f", r: "\r", '"': '"', "\\": "\\" } as Record<string, string>; ws(); if (value[i++] !== "[") return undefined; for (;;) { ws(); if (value[i] === "]") { i++; ws(); return i === value.length ? out : undefined; } const quote = value[i++]; if (quote !== '"' && quote !== "'") return undefined; let s = ""; for (;;) { if (i >= value.length) return undefined; const c = value[i++]; if (c === quote) break; if (c === "\\" && quote === '"') { const e = value[i++]; if (e in basic) s += basic[e]; else if (e === "u" || e === "U") { const count = e === "u" ? 4 : 8; const hex = value.slice(i, i + count); if (!new RegExp(`^[0-9A-Fa-f]{${count}}$`).test(hex)) return undefined; const n = Number.parseInt(hex, 16); if (n > 0x10ffff || (n >= 0xd800 && n <= 0xdfff)) return undefined; s += String.fromCodePoint(n); i += count; } else return undefined; } else if (c === "\n" || c === "\r") return undefined; else s += c; } out.push(s); ws(); if (value[i] === ",") { i++; continue; } if (value[i] === "]") continue; return undefined; } }
function captureHostWindows(path: string): boolean { return path.startsWith("\\\\") || path.startsWith("//") || /^[A-Za-z]:/.test(path); }
function captureConfig(cwd: string | undefined): CaptureConfig { return captureConfigAt(findMarker(cwd), cwd); }
// The policy one marker declares, for an event reported from `cwd`.
function captureConfigAt(marker: string | undefined, cwd: string | undefined): CaptureConfig {
- const candidateBase = captureNormalize(cwd ? resolve(cwd) : "")?.path ?? "";
// Host flavor comes from the cwd STRING itself, never from `resolve(cwd)`:
// `resolve` re-roots a drive/UNC-shaped cwd through the real OS's own path
// module, which only agrees on the OS that actually owns that path. The
// cwd the hook reports is already absolute and already names its own host,
- // exactly like the native hook's pure-string `flavor_of(cwd)`.
+ // exactly like the native hook's pure-string `flavor_of(cwd)`; a Windows
+ // cwd is normalized lexically for the same reason.
const windowsHost = captureHostWindows(cwd ?? "");
+ const candidateBase = (windowsHost ? captureNormalize(cwd ?? "") : captureNormalize(cwd ? resolve(cwd) : ""))?.path ?? "";
if (!marker) return { state: "inactive", patterns: [], base: candidateBase, windowsHost };
try {
const bytes = readFileSync(marker);
const markerBase = captureNormalize(dirname(marker))?.path ?? candidateBase;
if (bytes.byteLength > CAPTURE_MARKER_MAX_BYTES) return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
- let section = "";
+ // Every TOML spelling of the capture table the native parser honours
+ // (`[capture]`, `[ "capture" ]`, a top-level dotted `capture.ignore_paths`)
+ // is read; any other shape of a `capture` key (an inline table,
+ // `[[capture]]`, `[capture.x]`, a second definition) is invalid, as
+ // `read_capture_config` finds it.
+ let section: "top" | "capture" | "other" = "top";
let value = "";
let collecting = false;
let seen = false;
+ let defined = false;
for (const raw of bytes.toString("utf8").split(/\r?\n/)) {
const line = captureTrimComment(raw).trim();
if (!line) continue;
- const table = /^\[([^\]]+)\]$/.exec(line);
- if (table) {
- if (collecting) return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
- section = table[1];
- continue;
- }
- if (section !== "capture") continue;
- if (!seen) {
- const kv = /^([A-Za-z0-9_-]+)\s*=\s*(.*)$/.exec(line);
- if (!kv || kv[1] !== "ignore_paths") return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
- seen = true;
- value = kv[2];
- collecting = !value.includes("]");
- } else if (collecting) {
+ if (collecting) {
value += ` ${line}`;
collecting = !value.includes("]");
- } else return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
+ continue;
+ }
+ if (line.startsWith("[")) {
+ const array = line.startsWith("[[");
+ const close = array ? "]]" : "]";
+ const inner = line.slice(array ? 2 : 1, line.length - close.length);
+ const header = line.endsWith(close) ? captureTomlKey(inner) : undefined;
+ if (!header || header.end !== inner.length) return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
+ if (header.parts[0] !== "capture") { section = "other"; continue; }
+ if (array || header.parts.length !== 1 || defined) return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
+ section = "capture";
+ defined = true;
+ continue;
+ }
+ if (section === "other") continue;
+ const key = captureTomlKey(line);
+ const kv = key && line[key.end] === "=" ? key : undefined;
+ if (section === "top" && kv?.parts[0] !== "capture") continue;
+ const path = kv ? (section === "top" ? kv.parts.slice(1) : kv.parts) : [];
+ if (!kv || seen || path.length !== 1 || path[0] !== "ignore_paths") return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
+ seen = true;
+ defined = true;
+ value = line.slice(kv.end + 1).trim();
+ collecting = !value.includes("]");
}
if (collecting) return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
if (!seen) return { state: "inactive", patterns: [], base: candidateBase, windowsHost };
@@ -410,13 +445,13 @@ function captureGitObjectPath(word: string): string | undefined { if (word.start
// Lexical only, like the native hook: nothing is expanded or executed, so
// variables, command substitution, and `cd` state are not followed. A tool's
// own `workdir` replaces the event cwd for relative arguments.
-function captureMatchCommand(words: [string, boolean][], config: CaptureConfig, workdir?: string): { match: boolean | undefined; spool: boolean } { const budget = { work: 0 }; const home = homedir(); const base = captureBase(config, workdir); let spool = false; for (const [word, tilde] of words) for (const [argument, fromRoot] of captureShellArguments(word)) { const expanded = captureExpandTilde(argument, tilde, home, base); if ([...expanded].length > CAPTURE_MAX_PATH_CHARS) continue; const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(expanded); for (const root of fromRoot && !absolute && config.root ? [base, config.root] : [base]) { if (!absolute && !root) continue; const readings = captureReadings(absolute ? expanded : captureJoin(root, expanded), config.windowsHost); if (readings === false) return { match: undefined, spool }; if (!readings) continue; for (const candidate of readings) { if (captureOutputSpool(candidate.path)) spool = true; const match = captureMatchCandidate(candidate, false, config, budget); if (match !== false) return { match, spool }; } } } return { match: false, spool }; }
+function captureMatchCommand(words: [string, boolean][], config: CaptureConfig, workdir?: string): { match: boolean | undefined; spool: boolean } { const budget = { work: 0 }; const home = homedir(); const base = captureBase(config, workdir); let spool = false; for (const [word, tilde] of words) for (const [argument, fromRoot] of captureShellArguments(word)) { const expanded = captureExpandTilde(argument, tilde, home, base); if ([...expanded].length > CAPTURE_MAX_PATH_CHARS) continue; const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(expanded); for (const root of fromRoot && !absolute && config.root ? [base, config.root] : [base]) { if (!absolute && !root) continue; const resolved = captureResolve(expanded, root, config.windowsHost); const readings = resolved === undefined ? undefined : captureReadings(resolved, config.windowsHost); if (readings === false) return { match: undefined, spool }; if (!readings) continue; for (const candidate of readings) { const spooled = captureOutputSpool(candidate.path, budget); if (spooled === undefined) return { match: undefined, spool }; if (spooled) spool = true; const match = captureMatchCandidate(candidate, false, config, budget); if (match !== false) return { match, spool }; } } } return { match: false, spool }; }
// The directory a shell tool's relative arguments resolve from; mirrors `command_base`.
-function captureBase(config: CaptureConfig, workdir?: string): string { return workdir === undefined ? config.base : /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(workdir) ? workdir : config.base && captureJoin(config.base, workdir); }
+function captureBase(config: CaptureConfig, workdir?: string): string { const spelled = workdir !== undefined && config.windowsHost && config.base ? captureWindowsSpelling(workdir, config.base) : undefined; if (spelled !== undefined) return spelled; return workdir === undefined ? config.base : /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(workdir) ? workdir : config.base && captureJoin(config.base, workdir); }
// A leading unquoted `~/` (PowerShell `~\`) is home and `~+` the working directory; mirrors `expand_tilde`.
function captureExpandTilde(argument: string, tilde: boolean, home: string, base: string): string { return !tilde ? argument : /^~[\/\\]/.test(argument) ? captureJoin(home, argument.slice(2)) : argument === "~+" ? base : argument.startsWith("~+/") && base ? captureJoin(base, argument.slice(3)) : argument; }
-// A harness's saved copy of an earlier tool's output, read back like `BashOutput`: Claude Code `~/.claude/projects/<project>/<session>/tool-results/<id>.txt` and `<tmp>/claude-<uid>/<project>/<session>/tasks/<id>.output`, OpenCode `<data>/opencode/tool-output/tool_<id>`, Pi `<tmp>/pi-bash-<id>.log`. A glob segment fits a named one when the two share a match, and at least one fitting segment must spell literal text; mirrors `output_spool`.
-function captureOutputSpool(path: string): boolean { const segments = path.split("/").filter(Boolean).map((segment) => segment.replace(/[A-Z]/g, (c) => c.toLowerCase())); const file = segments.pop(); if (file === undefined) return false; const fits = (segment: string, shape: string) => captureGlobsIntersect([...segment], [...shape]); const named = (...parts: [string, string][]) => parts.some(([part, word]) => captureSpells(part, word)); const count = segments.length; let claudeResults = false; for (let i = 1; i < count && !claudeResults; i++) { const claude = segments[i - 1]; const projects = segments[i]; if (fits(claude, "*claude*") && fits(projects, "projects")) claudeResults = segments.slice(i + 1).some((results) => fits(results, "tool-results") && named([claude, "claude"], [projects, "projects"], [results, "tool-results"])); } const parent = segments[count - 1]; const claudeTask = count > 0 && fits(parent, "tasks") && fits(file, "*.output") && segments.some((claude) => fits(claude, "claude*") && named([parent, "tasks"], [file, ".output"], [claude, "claude"])); const opencode = count >= 2 && fits(segments[count - 2], "opencode") && fits(parent, "tool-output") && named([segments[count - 2], "opencode"], [parent, "tool-output"]); const pi = fits(file, "pi-bash-*.log") && named([file, "pi-bash-"]); return claudeResults || claudeTask || opencode || pi; }
+// A harness's saved copy of an earlier tool's output, read back like `BashOutput`: Claude Code `~/.claude/projects/<project>/<session>/tool-results/<id>.txt` and `<tmp>/claude-<uid>/<project>/<session>/tasks/<id>.output`, OpenCode `<data>/opencode/tool-output/tool_<id>`, Pi `<tmp>/pi-bash-<id>.log`. A glob segment fits a named one when the two share a match, and at least one fitting segment must spell literal text. Each segment is fitted to each shape once and the work is charged to `budget`; undefined past CAPTURE_MAX_WORK. Mirrors `output_spool`.
+function captureOutputSpool(path: string, budget: { work: number }): boolean | undefined { const segments = path.split("/").filter(Boolean).map((segment) => [...segment.replace(/[A-Z]/g, (c) => c.toLowerCase())]); const file = segments.pop(); if (file === undefined) return false; const fits = (segment: string[], shape: string): boolean | undefined => { budget.work += (segment.length + 1) * ([...shape].length + 1); return budget.work > CAPTURE_MAX_WORK ? undefined : captureGlobsIntersect(segment, [...shape]); }; const spells = (segment: string[], word: string) => captureSpells(segment.join(""), word); const count = segments.length; let after: [boolean, boolean][] | undefined; let claudeResults = false; for (let index = 1; index < count; index++) { const claude = segments[index - 1]; const projects = segments[index]; const c = fits(claude, "*claude*"); if (c === undefined) return undefined; if (!c) continue; const p = fits(projects, "projects"); if (p === undefined) return undefined; if (!p) continue; if (!after) { after = new Array<[boolean, boolean]>(count); let seen: [boolean, boolean] = [false, false]; for (let at = count - 1; at >= 0; at--) { after[at] = seen; const results = fits(segments[at], "tool-results"); if (results === undefined) return undefined; if (results) seen = [true, seen[1] || spells(segments[at], "tool-results")]; } } const [fitting, spelled] = after[index]; if (spelled || (fitting && (spells(claude, "claude") || spells(projects, "projects")))) { claudeResults = true; break; } } let claudeTask = false; if (count > 0) { const parent = segments[count - 1]; const tasks = fits(parent, "tasks"); if (tasks === undefined) return undefined; if (tasks) { const output = fits(file, "*.output"); if (output === undefined) return undefined; if (output) { const named = spells(parent, "tasks") || spells(file, ".output"); for (const claude of segments) { const c = fits(claude, "claude*"); if (c === undefined) return undefined; if (c && (named || spells(claude, "claude"))) { claudeTask = true; break; } } } } } let opencode = false; if (count >= 2) { const data = fits(segments[count - 2], "opencode"); if (data === undefined) return undefined; if (data) { const output = fits(segments[count - 1], "tool-output"); if (output === undefined) return undefined; opencode = output && (spells(segments[count - 2], "opencode") || spells(segments[count - 1], "tool-output")); } } const pi = fits(file, "pi-bash-*.log"); if (pi === undefined) return undefined; return claudeResults || claudeTask || opencode || (pi && spells(file, "pi-bash-")); }
// Whether a one-segment glob spells part of `word` in literal text: a run between wildcards sharing three characters in a row with it; mirrors `spells`.
function captureSpells(segment: string, word: string): boolean { const needed = Math.min([...word].length, 3); return segment.split(/[*?]/).some((run) => { const chars = [...run]; for (let i = 0; i + needed <= chars.length; i++) if (word.includes(chars.slice(i, i + needed).join(""))) return true; return false; }); }
// Whether two one-segment globs over `*` and `?` match a common string; mirrors `globs_intersect`.
@@ -425,10 +460,10 @@ function captureGlobsIntersect(left: string[], right: string[]): boolean { const
// recursing to any depth: a literal path matches like a file tool's, a glob
// drops when it could expand into an ignored path, and glob syntax the matcher
// cannot evaluate (classes, braces, extglobs, negation) fails closed.
-function captureMatchGlobs(paths: string[], config: CaptureConfig): boolean | undefined { const budget = { work: 0 }; for (const path of paths) { if (/[\[\]{}()!]/.test(path)) return undefined; const readings = captureReadings(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(path) ? path : captureJoin(config.base, path), config.windowsHost); if (!readings) return undefined; for (const candidate of readings) { const match = captureMatchCandidate(candidate, true, config, budget); if (match !== false) return match; } } return false; }
+function captureMatchGlobs(paths: string[], config: CaptureConfig): boolean | undefined { const budget = { work: 0 }; for (const path of paths) { if (/[\[\]{}()!]/.test(path)) return undefined; const resolved = captureResolve(path, config.base, config.windowsHost); const readings = resolved === undefined ? undefined : captureReadings(resolved, config.windowsHost); if (!readings) return undefined; for (const candidate of readings) { const match = captureMatchCandidate(candidate, true, config, budget); if (match !== false) return match; } } return false; }
function captureMatchCandidate(raw: { path: string; windows: boolean }, toolGlob: boolean, config: CaptureConfig, budget: { work: number }): boolean | undefined { const candidate = { path: captureFold(raw.path), windows: raw.windows }; const glob = /[*?]/.test(candidate.path); const directory = toolGlob && !glob; for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; const insensitive = toolGlob || pattern.windows || captureFoldCase; const under = captureStartsWith(candidate.path, pattern.prefix, insensitive); if (!under && !glob && !directory) continue; if (under) { const directory = pattern.directory ? captureGlob(pattern.directory, candidate.path, insensitive, budget) : false; if (directory !== false) return directory; const match = captureGlob(pattern.path, candidate.path, insensitive, budget); if (match !== false) return match; } if (glob) { const reaches = captureGlobstarReaches(candidate.path, pattern.prefix, insensitive, budget); if (reaches !== false) return reaches; } if (directory) { const below = captureGlobBelow(pattern.path, candidate.path, insensitive, budget); if (below !== false) return below; } } return false; }
function captureGlobstarReaches(glob: string, prefix: string, insensitive: boolean, budget: { work: number }): boolean | undefined { const star = glob.indexOf("**"); if (star < 0) return captureGlobReaches(glob, prefix, insensitive, budget); const slash = glob.lastIndexOf("/", star); const head = slash < 0 ? "" : glob.slice(0, slash); const depth = head.split("/").filter(Boolean).length; let seen = 0; let offset = 0; for (const part of prefix.split("/")) { if (seen === depth) break; offset += part.length; if (part) seen++; if (seen < depth) offset++; } if (seen < depth) return captureGlobReaches(glob, prefix, insensitive, budget); return captureGlob(head, prefix.slice(0, offset), insensitive, budget); }
-function captureTool(payload: Record<string, unknown>): { family: CaptureProtocol["tool_family"]; paths?: string[]; extraction: CaptureProtocol["extraction_state"]; callID?: string; command?: string | string[]; shell?: boolean; powershell?: boolean; workdir?: string; globs?: boolean; reader?: boolean; search?: { roots: string[]; patterns: string[] }; patch?: string[] } { const name = typeof payload.tool === "string" ? payload.tool.toLowerCase() : ""; const args = payload.args as Record<string, unknown> | undefined; const call = ["tool_use_id","toolUseId","tool_call_id","toolCallId","call_id","callId","callID"].map((k) => payload[k]).find((v): v is string => typeof v === "string" && /^[A-Za-z0-9_.-]{1,128}$/.test(v)); if (["search","grep","glob","find","list","ls","list_files","read_dir","list_dir","grep_search","search_files","find_by_name","list_directory","search_file_content"].includes(name)) return { family: "search-list", extraction: "not-applicable", callID: call, search: captureSearchScope(name, args) }; if (["bash","shell","shell_command","exec","execute","run_command","web_search","search_web","manage_task","manage_subagents","terminal","execute_bash","execute_cmd","powershell","run_shell_command"].includes(name)) { const workdir = ["workdir","dir_path","directory"].map((k) => args?.[k]).find((v) => v !== undefined); return { family: "non-file", extraction: "extracted", callID: call, command: captureShellCommand(args), shell: name !== "web_search", powershell: name === "powershell", workdir: typeof workdir === "string" && workdir.trim() ? workdir : undefined }; } if (!["read","write","edit","apply_patch","notebookedit","notebook_edit","create_file","delete_file","rename_file","move_file","multi_edit","multiedit","replace","replace_all","read_many_files"].includes(name)) return { family: "unknown", extraction: "extracted", callID: call, reader: ["bashoutput","taskoutput","write_stdin","process","read_bash","write_bash","read_powershell","write_powershell"].includes(name) }; const direct = (o: any): string[] | undefined => { if (!o || typeof o !== "object") return undefined; const r: string[] = []; for (const k of ["file_path","filePath","path","absolute_path","AbsolutePath","notebook_path","TargetFile"]) if (k in o) { if (typeof o[k] !== "string") return undefined; r.push(o[k]); } if ("paths" in o) { if (!Array.isArray(o.paths) || o.paths.some((x: unknown) => typeof x !== "string")) return undefined; r.push(...o.paths); } return r.length && r.length <= CAPTURE_MAX_CANDIDATES ? r : undefined; }; let paths = direct(args); if (["multi_edit","multiedit","replace_all"].includes(name)) { const entries = args?.edits ?? args?.replacements; if (!Array.isArray(entries) || !entries.length || entries.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else { paths = paths ?? []; for (const entry of entries) { const more = direct(entry); if (!more || paths.length + more.length > CAPTURE_MAX_CANDIDATES) { paths = undefined; break; } paths.push(...more); } } } if (name === "read_many_files" && args && "include" in args) { const include = args.include; if (!Array.isArray(include) || include.some((x: unknown) => typeof x !== "string") || (paths?.length ?? 0) + include.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else paths = [...(paths ?? []), ...(include as string[])]; } if (!paths || !paths.length || paths.some((p) => !p.trim() || [...p].length > CAPTURE_MAX_PATH_CHARS)) return { family: "file", extraction: "missing-or-malformed", callID: call, patch: capturePatchPaths(name, payload.args) }; return { family: "file", paths, extraction: "extracted", callID: call, globs: name === "read_many_files" }; }
+function captureTool(payload: Record<string, unknown>): { family: CaptureProtocol["tool_family"]; paths?: string[]; extraction: CaptureProtocol["extraction_state"]; callID?: string; command?: string | string[]; shell?: boolean; powershell?: boolean; inline?: boolean; workdir?: string; globs?: boolean; reader?: boolean; search?: { roots: string[]; patterns: string[] }; patch?: string[] } { const name = typeof payload.tool === "string" ? payload.tool.toLowerCase() : ""; const args = payload.args as Record<string, unknown> | undefined; const call = ["tool_use_id","toolUseId","tool_call_id","toolCallId","call_id","callId","callID"].map((k) => payload[k]).find((v): v is string => typeof v === "string" && /^[A-Za-z0-9_.-]{1,128}$/.test(v)); if (CAPTURE_SEARCH_TOOLS.includes(name)) return { family: "search-list", extraction: "not-applicable", callID: call, search: captureSearchScope(name, args) }; if (CAPTURE_NON_FILE_TOOLS.includes(name)) { const workdir = ["workdir","dir_path","directory"].map((k) => args?.[k]).find((v) => v !== undefined); return { family: "non-file", extraction: "extracted", callID: call, command: captureShellCommand(args), shell: name !== "web_search", powershell: name === "powershell", inline: CAPTURE_INLINE_CODE_TOOLS.includes(name), workdir: typeof workdir === "string" && workdir.trim() ? workdir : undefined }; } if (!CAPTURE_FILE_TOOLS.includes(name)) return { family: "unknown", extraction: "extracted", callID: call, reader: CAPTURE_OUTPUT_READER_TOOLS.includes(name) }; const direct = (o: any): string[] | undefined => { if (!o || typeof o !== "object") return undefined; const r: string[] = []; for (const k of ["file_path","filePath","path","absolute_path","AbsolutePath","notebook_path","TargetFile"]) if (k in o) { if (typeof o[k] !== "string") return undefined; r.push(o[k]); } if ("paths" in o) { if (!Array.isArray(o.paths) || o.paths.some((x: unknown) => typeof x !== "string")) return undefined; r.push(...o.paths); } return r.length && r.length <= CAPTURE_MAX_CANDIDATES ? r : undefined; }; let paths = direct(args); if (["multi_edit","multiedit","replace_all"].includes(name)) { const entries = args?.edits ?? args?.replacements; if (!Array.isArray(entries) || !entries.length || entries.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else { paths = paths ?? []; for (const entry of entries) { const more = direct(entry); if (!more || paths.length + more.length > CAPTURE_MAX_CANDIDATES) { paths = undefined; break; } paths.push(...more); } } } if (name === "read_many_files" && args && "include" in args) { const include = args.include; if (!Array.isArray(include) || include.some((x: unknown) => typeof x !== "string") || (paths?.length ?? 0) + include.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else paths = [...(paths ?? []), ...(include as string[])]; } if ((name === "read" || name === "fs_read") && args && "operations" in args) { const entries = args.operations; if (!Array.isArray(entries) || !entries.length || entries.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else { paths = paths ?? []; for (const entry of entries) { const more = direct(entry); if (!more || paths.length + more.length > CAPTURE_MAX_CANDIDATES) { paths = undefined; break; } paths.push(...more); } } } if (!paths || !paths.length || paths.some((p) => !p.trim() || [...p].length > CAPTURE_MAX_PATH_CHARS)) return { family: "file", extraction: "missing-or-malformed", callID: call, patch: capturePatchPaths(name, payload.args) }; return { family: "file", paths, extraction: "extracted", callID: call, globs: name === "read_many_files" }; }
// Where a search/list tool reads, for the cross-checkout lookup: its directory and file arguments, a glob tool's `pattern`, and a content search's file filters (a grep `pattern` is a regular expression). Undefined when one is not a string; mirrors `search_scope`.
function captureSearchScope(name: string, args: unknown): { roots: string[]; patterns: string[] } | undefined { if (args === undefined || args === null) return { roots: [], patterns: [] }; if (typeof args !== "object" || Array.isArray(args)) return undefined; const o = args as Record<string, unknown>; const roots: string[] = []; const patterns: string[] = []; for (const k of ["file_path","filePath","path","absolute_path","AbsolutePath","notebook_path","TargetFile","dir_path","directory","DirectoryPath","SearchDirectory","SearchPath"]) if (k in o) { if (typeof o[k] !== "string") return undefined; roots.push(o[k] as string); } if ("paths" in o) { if (!Array.isArray(o.paths) || o.paths.some((x: unknown) => typeof x !== "string")) return undefined; roots.push(...(o.paths as string[])); } for (const k of [...(["glob","find","find_by_name"].includes(name) ? ["pattern","Pattern"] : []), "glob","include","file_pattern","file_glob","Includes"]) { if (!(k in o)) continue; const v = o[k]; if (typeof v === "string") patterns.push(v); else if (Array.isArray(v) && v.every((x) => typeof x === "string")) patterns.push(...(v as string[])); else return undefined; } return roots.length + patterns.length <= CAPTURE_MAX_CANDIDATES && [...roots, ...patterns].every((p) => p.trim() && [...p].length <= CAPTURE_MAX_PATH_CHARS) ? { roots, patterns } : undefined; }
// The files an `apply_patch` patch names in its Add/Update/Delete File and Move to headers, for the cross-checkout lookup only; mirrors `patch_paths`.
@@ -441,9 +476,9 @@ function captureBraceAlternatives(text: string): string[] | undefined { if (text
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`.
+// 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. Each directory is read one entry at a time, so a huge one costs no more than the entry bound. 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; }
+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 handle: { readSync(): { name: string; isDirectory(): boolean } | null; closeSync(): void }; try { handle = opendirSync(dir); } catch (_e) { return []; } const out: string[] = []; try { for (let entry = handle.readSync(); entry; entry = handle.readSync()) { if (++budget.entries > CAPTURE_MAX_GLOB_ENTRIES) return undefined; if (entry.isDirectory()) out.push(join(dir, entry.name)); } } catch (_e) { /* the rest of an unreadable directory lists nothing */ } finally { handle.closeSync(); } 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.
@@ -480,13 +515,42 @@ function captureOwnedExternally(): boolean { const owner = typeof process === "u
function captureServerRouted(cwd: string | undefined): boolean { let dir = resolve(cwd ?? process.cwd()); const home = homedir(); let boundary: string | undefined; for (let probe = dir; ; probe = dirname(probe)) { if (probe === home) { boundary = home; break; } if (probe === dirname(probe)) break; } for (;;) { try { if (/^\s*server\s*=/m.test(readFileSync(join(dir, ".ai-memory.toml"), "utf8"))) return true; } catch (e) { if (!["ENOENT", "ENOTDIR", "EISDIR"].includes((e as { code?: string })?.code ?? "")) return true; } if (dir === boundary || dir === dirname(dir)) return false; dir = dirname(dir); } }
type CaptureTool = ReturnType<typeof captureTool>;
// One policy's disposition for one call, shared by the event's own marker and every other marker it reaches.
-function captureDecide(tool: CaptureTool, config: CaptureConfig): CaptureDisposition { if (config.state === "invalid" && (tool.family === "file" || tool.family === "search-list" || tool.shell || tool.reader)) return "metadata-only"; if (config.state !== "active") return "keep"; if (tool.reader) return "metadata-only"; if (tool.family === "search-list") return "drop"; if (tool.family === "file") { if (!tool.paths) return "metadata-only"; const parsed = tool.paths.map((p) => captureNormalize(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p), config.windowsHost)); if (parsed.some((p) => !p)) return "metadata-only"; const candidates = parsed as { path: string; windows: boolean }[]; if (tool.globs) { const match = captureMatchGlobs(tool.paths, 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"; }
+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) => { const resolved = captureResolve(p, config.base, config.windowsHost); return resolved === undefined ? undefined : captureNormalize(resolved, config.windowsHost); }); if (parsed.some((p) => !p)) return "metadata-only"; const candidates = parsed as { path: string; windows: boolean }[]; const spoolBudget = { work: 0 }; if (tool.globs) { const match = captureMatchGlobs(tool.paths, config); if (match !== false) return match ? "drop" : "metadata-only"; for (const p of tool.paths) { const resolved = captureResolve(p, config.base, config.windowsHost); const readings = resolved === undefined ? undefined : captureReadings(resolved, config.windowsHost); if (!readings) continue; for (const candidate of readings) if (captureOutputSpool(candidate.path, spoolBudget) !== false) return "metadata-only"; } return "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"; } } for (const candidate of candidates) if (captureOutputSpool(candidate.path, spoolBudget) !== false) return "metadata-only"; return "keep"; } if (tool.family === "non-file" && (tool.inline || (tool.command !== undefined && captureCommandOversized(tool.command)))) return "metadata-only"; 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 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 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 resolved = captureResolve(path, base, config.windowsHost); if (resolved === undefined) return undefined; const readings = captureReadings(resolved, 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) { if (captureCommandOversized(tool.command)) return invalid; 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)
+ let names = |names: &[&str]| {
+ let quoted: Vec<String> = names.iter().map(|name| ts_string_literal(name)).collect();
+ format!("[{}]", quoted.join(", "))
+ };
+ TEMPLATE
+ .replace("__AI_MEMORY_CAPTURE_MODE__", capture_mode)
+ .replace(
+ "__AI_MEMORY_FILE_TOOLS__",
+ &names(capture_policy::FILE_TOOL_NAMES),
+ )
+ .replace(
+ "__AI_MEMORY_SEARCH_TOOLS__",
+ &names(capture_policy::SEARCH_LIST_TOOL_NAMES),
+ )
+ .replace(
+ "__AI_MEMORY_NON_FILE_TOOLS__",
+ &names(capture_policy::NON_FILE_TOOL_NAMES),
+ )
+ .replace(
+ "__AI_MEMORY_INLINE_CODE_TOOLS__",
+ &names(capture_policy::INLINE_CODE_TOOL_NAMES),
+ )
+ .replace(
+ "__AI_MEMORY_OUTPUT_READER_TOOLS__",
+ &names(capture_policy::OUTPUT_READER_TOOL_NAMES),
+ )
+ .replace(
+ "__AI_MEMORY_MAX_COMMAND_CHARS__",
+ &capture_policy::MAX_SHELL_COMMAND_CHARS.to_string(),
+ )
}
/// Build the Claude Code `settings.json` fragment that wires the
@@ -2647,10 +2711,13 @@ mod tests {
let fixture = include_str!("../../../ai-memory-hooks/tests/fixtures/capture-policy.json");
let fixture = serde_json::to_string(fixture).unwrap();
let source = format!(
- r#"import {{ closeSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync }} from "node:fs";
+ r#"import {{ closeSync, mkdirSync, opendirSync as realOpendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync }} from "node:fs";
import {{ basename, dirname, join, resolve }} from "node:path";
import {{ homedir }} from "node:os";
+// Counts the entries the policy's directory walk reads.
+let opendirReads = 0;
+function opendirSync(path: string) {{ const dir = realOpendirSync(path); return {{ readSync() {{ opendirReads++; return dir.readSync(); }}, closeSync() {{ dir.closeSync(); }} }}; }}
const fixtureText = {fixture};
const markerRoot = process.argv[2]!;
const markerFixtures = new Map<string, string>();
@@ -2880,6 +2947,42 @@ const inactive = capturePolicy(inactivePayload, "/no-marker");
check(inactive.disposition === "keep" && inactive.payload === inactivePayload && !inactive.protocol, "inactive-preserves-object");
const activeKeep = capturePolicy({{ tool: "bash", args: {{ command: privateBody }} }}, gatedCwd);
check(activeKeep.disposition === "keep" && activeKeep.protocol?.version === 1 && activeKeep.protocol.policy_state === "active", "active-keep-adds-protocol");
+// Windows spellings of an ignored file, and the POSIX sessions they must not touch (shared vectors; mirrors `windows_spelling_fixture_vectors`).
+for (const section of [fixture.windows, fixture.windows_posix_controls]) {{
+ markerFixtures.set(section.cwd, markerFixtures.get(marker(`[capture]\nignore_paths = ${{JSON.stringify(section.ignore_paths)}}\n`))!);
+ for (const vector of section.files) {{ const result = capturePolicy({{ tool: "edit", args: {{ path: vector.path }} }}, section.cwd); check(result.disposition === vector.disposition && result.protocol?.tool_family === "file", `windows-file ${{section.cwd}} ${{JSON.stringify(vector)}}: ${{result.disposition}}`); }}
+ for (const vector of section.shell ?? []) {{ const result = capturePolicy(vector.payload ?? bash(vector.command), section.cwd); check(result.disposition === vector.disposition, `windows-shell ${{JSON.stringify(vector)}}: ${{result.disposition}}`); }}
+}}
+// Every TOML spelling of the capture table the native parser honours, and the ones it rejects (shared vectors; mirrors `capture_section_spellings_match_toml_semantics`).
+for (const text of fixture.marker_spellings.honoured) check(capturePolicy({{ tool: "edit", args: {{ path: "secret/x" }} }}, marker(text)).disposition === "drop", `marker-honoured ${{JSON.stringify(text)}}`);
+for (const text of fixture.marker_spellings.rejected) {{ const result = capturePolicy({{ tool: "edit", args: {{ path: "public/x" }} }}, marker(text)); check(result.disposition === "metadata-only" && result.protocol?.policy_state === "invalid", `marker-rejected ${{JSON.stringify(text)}}`); }}
+for (const text of fixture.marker_spellings.unrelated) check(capturePolicy({{ tool: "edit", args: {{ path: "secret/x" }} }}, marker(text)).disposition === "keep", `marker-unrelated ${{JSON.stringify(text)}}`);
+// The tool names each family covers come from the native constants (shared vectors; mirrors `tool_family_fixture_vectors`).
+for (const vector of fixture.tool_families) check(captureTool({{ tool: vector.name, args: {{}} }}).family === vector.family, `tool-family ${{vector.name}}`);
+// The harness-spool check is linear in the path and charged to the match budget; mirrors `output_spool_work_is_linear_and_budgeted`.
+const spoolPath = `/tmp/${{"*/".repeat(2040)}}x`; const spoolWork = {{ work: 0 }};
+check(captureOutputSpool(spoolPath, spoolWork) === false && spoolWork.work <= 64 * spoolPath.length, `spool-linear ${{spoolWork.work}}`);
+check(captureOutputSpool("/home/u/.claude/projects/p/s/tool-results/a.txt", {{ work: 0 }}) === true, "spool-still-found");
+check(captureOutputSpool(spoolPath, {{ work: CAPTURE_MAX_WORK }}) === undefined, "spool-past-budget-unproven");
+const spoolRoot = marker('[capture]\nignore_paths = ["/s"]\n');
+const spoolPaths = Array.from({{ length: 32 }}, (_, i) => `/tmp/${{i}}/${{"*/".repeat(2000)}}x`);
+check(capturePolicy({{ tool: "read", args: {{ paths: spoolPaths }} }}, spoolRoot).disposition === "metadata-only", "spool-budget-fails-closed");
+check(capturePolicy({{ tool: "read", args: {{ paths: spoolPaths.slice(0, 1) }} }}, spoolRoot).disposition === "keep", "spool-one-path-keep");
+// A command longer than the matcher splits is unprovable; mirrors `an_oversized_shell_command_is_unprovable`.
+const atLimit = `cat public.md${{" ".repeat(CAPTURE_MAX_COMMAND_CHARS - 13)}}`;
+check(capturePolicy(bash(atLimit), shellRoot).disposition === "keep", "command-at-limit-keep");
+check(capturePolicy(bash(`${{atLimit}} `), shellRoot).disposition === "metadata-only", "command-oversized-metadata-only");
+check(capturePolicy({{ tool: "shell", args: {{ command: ["bash", "-lc", atLimit] }} }}, shellRoot).disposition === "metadata-only", "argv-oversized-metadata-only");
+check(capturePolicy(bash(`${{atLimit}} `), "/no-marker").disposition === "metadata-only", "command-oversized-lookup-unprovable");
+// Inline program source (Hermes `execute_code`) is metadata-only under a policy, like `python3 -c`.
+const inlineCode = {{ tool: "execute_code", args: {{ code: "print(open('secret/a.txt').read())" }}, output: privateBody }};
+check(capturePolicy(inlineCode, "/no-marker").disposition === "keep", "inline-code-inactive-keep");
+const inlineResult = capturePolicy(inlineCode, marker(active));
+check(inlineResult.disposition === "metadata-only" && inlineResult.protocol?.tool_family === "non-file" && !JSON.stringify(inlineResult.payload).includes(privateBody), "inline-code-metadata-only");
+// A directory walk reads one entry at a time and stops at the entry bound instead of listing the whole directory first.
+const wide = join(markerRoot, "wide"); for (let i = 0; i < 100; i++) mkdirSync(join(wide, `d${{i}}`), {{ recursive: true }});
+opendirReads = 0;
+check(captureMarkersBelow(wide, ["*"], undefined, {{ dirs: 0, entries: CAPTURE_MAX_GLOB_ENTRIES - 5, deadline: 50, now: () => 0 }}) === undefined && opendirReads > 0 && opendirReads <= 6, `walk-reads-to-the-entry-bound ${{opendirReads}}`);
// #992: only the native hook routes `server` profiles; these integrations
// must drop rather than deliver a routed repository to the install default,
// including under a nested marker that does not repeat the key.
@@ -2939,7 +3042,7 @@ check(capturePolicy(bash("echo hi"), routedChild).disposition === "drop", "serve
// `config.state`, or this second case would be wrongly dropped.
let allowlist_module = temp.path().join("capture-policy-allowlist-evidence.ts");
let allowlist_source = format!(
- r#"import {{ closeSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync }} from "node:fs";
+ r#"import {{ closeSync, mkdirSync, opendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync }} from "node:fs";
import {{ basename, dirname, join, resolve }} from "node:path";
import {{ homedir }} from "node:os";
@@ -2998,7 +3101,7 @@ check(markedButEmpty.disposition === "keep", "allowlist-marker-present-empty-cap
// evidence, so they stay on disk for inspection after the run.
let temp = tempfile::tempdir().unwrap().keep();
eprintln!("capture-owner gate modules retained at {}", temp.display());
- const HARNESS: &str = r#"import { closeSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync } from "node:fs";
+ const HARNESS: &str = r#"import { closeSync, mkdirSync, opendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
import { homedir } from "node:os";
diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rs
index 4297ef96..758aac9c 100644
--- a/crates/ai-memory-hooks/src/capture_policy.rs
+++ b/crates/ai-memory-hooks/src/capture_policy.rs
@@ -646,22 +646,28 @@ impl CapturePolicy {
} else {
self.match_paths(paths, cwd)
};
+ // A harness's saved copy of an earlier tool's output
+ // is read back like `BashOutput`; past the budget
+ // that check proves nothing either.
+ let spooled = || -> Result<bool, ()> {
+ let mut work = 0_usize;
+ for path in paths {
+ let readings = if extracted.globs {
+ normalize_readings(path, cwd).ok().flatten()
+ } else {
+ normalize_candidate(path, cwd).map(|c| vec![c])
+ };
+ for candidate in readings.into_iter().flatten() {
+ if output_spool(&candidate.path, &mut work)? {
+ return Ok(true);
+ }
+ }
+ }
+ Ok(false)
+ };
match matched {
Ok(true) => (CaptureDisposition::Drop, ExtractionState::Extracted),
- // A harness's saved copy of an earlier tool's
- // output is read back like `BashOutput`.
- Ok(false)
- if paths.iter().any(|path| {
- let readings = if extracted.globs {
- normalize_readings(path, cwd).ok().flatten()
- } else {
- normalize_candidate(path, cwd).map(|c| vec![c])
- };
- readings.is_some_and(|readings| {
- readings.iter().any(|c| output_spool(&c.path))
- })
- }) =>
- {
+ Ok(false) if spooled().unwrap_or(true) => {
(CaptureDisposition::MetadataOnly, ExtractionState::Extracted)
}
Ok(false) => (CaptureDisposition::Keep, ExtractionState::Extracted),
@@ -672,6 +678,18 @@ impl CapturePolicy {
}
}
},
+ // Program source builds its paths at run time, like
+ // `python3 -c`, and a command longer than the matcher splits
+ // is not read at all; neither proves a miss.
+ ToolFamily::NonFile
+ if extracted.inline_code
+ || extracted
+ .command
+ .as_ref()
+ .is_some_and(ShellCommand::oversized) =>
+ {
+ (CaptureDisposition::MetadataOnly, extracted.state)
+ }
// A shell command has no path field, but its arguments can
// still name an ignored file whose content lands in the
// output (`cat docs/adr/*.md`). An exhausted match budget
@@ -767,7 +785,7 @@ impl CapturePolicy {
continue;
};
for candidate in readings {
- spool |= output_spool(&candidate.path);
+ spool |= output_spool(&candidate.path, &mut work)?;
if self.match_pattern_candidate(&candidate, false, &mut work)? {
return Ok((true, spool));
}
@@ -980,6 +998,8 @@ struct Extracted<'a> {
output_reader: bool,
/// Claude Code's `PowerShell` tool.
powershell: bool,
+ /// A non-file tool whose input is program source ([`INLINE_CODE_TOOL_NAMES`]).
+ inline_code: bool,
call_id: Option<String>,
state: ExtractionState,
}
@@ -1105,6 +1125,8 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted<'_> {
globs: name.eq_ignore_ascii_case("read_many_files"),
output_reader: reads_earlier_output(name),
powershell: name.eq_ignore_ascii_case("powershell"),
+ inline_code: family == ToolFamily::NonFile
+ && INLINE_CODE_TOOL_NAMES.contains(&name.to_ascii_lowercase().as_str()),
call_id,
state,
}
@@ -1126,23 +1148,11 @@ fn agent_family(agent: AgentKind, name: &str) -> ToolFamily {
family(name)
}
-/// Tools that return output of a command started by an earlier call: Claude
-/// Code `BashOutput`/`TaskOutput`, Codex `write_stdin`, Hermes and OpenClaw
-/// `process`, Copilot CLI `read_bash`/`write_bash` and their PowerShell twins.
-/// That command's own event may have been dropped, so its output must not
-/// come back through these.
+/// Whether a tool returns output of a command started by an earlier call
+/// ([`OUTPUT_READER_TOOL_NAMES`]). That command's own event may have been
+/// dropped, so its output must not come back through these.
fn reads_earlier_output(name: &str) -> bool {
- matches!(
- name.to_ascii_lowercase().as_str(),
- "bashoutput"
- | "taskoutput"
- | "write_stdin"
- | "process"
- | "read_bash"
- | "write_bash"
- | "read_powershell"
- | "write_powershell"
- )
+ OUTPUT_READER_TOOL_NAMES.contains(&name.to_ascii_lowercase().as_str())
}
/// Whether a normalized path is a file a harness saved a tool's output to and
@@ -1162,52 +1172,84 @@ fn reads_earlier_output(name: &str) -> bool {
/// `tool-results`, `tasks`, `.output`, `opencode`, `tool-output`, `pi-bash-`)
/// in literal text, so a bare `*` or `*/*`, or a `*.log` whose wildcard stands
/// where `pi-bash-` would be, is never taken for a saved output file.
-fn output_spool(path: &str) -> bool {
+///
+/// Each segment is fitted against each shape at most once, so the work is
+/// linear in the path; it is charged to the caller's match budget (`work`,
+/// up to [`MAX_MATCH_WORK`]), and past it nothing is proven (`Err`).
+fn output_spool(path: &str, work: &mut usize) -> Result<bool, ()> {
let segments: Vec<Vec<char>> = path
.split('/')
.filter(|segment| !segment.is_empty())
.map(|segment| segment.to_ascii_lowercase().chars().collect())
.collect();
let Some((file, directories)) = segments.split_last() else {
- return false;
+ return Ok(false);
};
- let fits = |segment: &[char], shape: &str| {
- globs_intersect(segment, &shape.chars().collect::<Vec<_>>())
+ let mut charge = |segment: &[char], shape: &str| -> Result<(), ()> {
+ *work = work
+ .checked_add((segment.len() + 1).saturating_mul(shape.chars().count() + 1))
+ .ok_or(())?;
+ if *work > MAX_MATCH_WORK {
+ Err(())
+ } else {
+ Ok(())
+ }
};
- let named = |segments: &[(&Vec<char>, &str)]| {
- segments.iter().any(|(segment, word)| spells(segment, word))
+ let mut fits = |segment: &[char], shape: &str| -> Result<bool, ()> {
+ charge(segment, shape)?;
+ Ok(globs_intersect(segment, &shape.chars().collect::<Vec<_>>()))
};
let count = directories.len();
- let claude_results = (1..count).any(|index| {
+ // `<..claude..>/projects/../tool-results/..`: whether some directory past
+ // `index` fits `tool-results`, and whether one that fits also spells it,
+ // each computed once for every `index` (`after[index]`).
+ let mut after: Option<Vec<(bool, bool)>> = None;
+ let mut claude_results = false;
+ for index in 1..count {
let (claude, projects) = (&directories[index - 1], &directories[index]);
- fits(claude, "*claude*")
- && fits(projects, "projects")
- && directories[index + 1..].iter().any(|results| {
- fits(results, "tool-results")
- && named(&[
- (claude, "claude"),
- (projects, "projects"),
- (results, "tool-results"),
- ])
- })
- });
+ if !fits(claude, "*claude*")? || !fits(projects, "projects")? {
+ continue;
+ }
+ if after.is_none() {
+ let mut suffix = vec![(false, false); count];
+ let mut seen = (false, false);
+ for at in (0..count).rev() {
+ suffix[at] = seen;
+ let results = &directories[at];
+ if fits(results, "tool-results")? {
+ seen = (true, seen.1 || spells(results, "tool-results"));
+ }
+ }
+ after = Some(suffix);
+ }
+ let (fitting, spelled) = after.as_ref().map_or((false, false), |after| after[index]);
+ if spelled || (fitting && (spells(claude, "claude") || spells(projects, "projects"))) {
+ claude_results = true;
+ break;
+ }
+ }
let claude_task = count > 0 && {
let parent = &directories[count - 1];
- fits(parent, "tasks")
- && fits(file, "*.output")
- && directories.iter().any(|claude| {
- fits(claude, "claude*")
- && named(&[(parent, "tasks"), (file, ".output"), (claude, "claude")])
- })
+ fits(parent, "tasks")? && fits(file, "*.output")? && {
+ let named = spells(parent, "tasks") || spells(file, ".output");
+ let mut found = false;
+ for claude in directories {
+ if fits(claude, "claude*")? && (named || spells(claude, "claude")) {
+ found = true;
+ break;
+ }
+ }
+ found
+ }
};
let opencode = count >= 2 && {
let (data, output) = (&directories[count - 2], &directories[count - 1]);
- fits(data, "opencode")
- && fits(output, "tool-output")
- && named(&[(data, "opencode"), (output, "tool-output")])
+ fits(data, "opencode")?
+ && fits(output, "tool-output")?
+ && (spells(data, "opencode") || spells(output, "tool-output"))
};
- let pi = fits(file, "pi-bash-*.log") && named(&[(file, "pi-bash-")]);
- claude_results || claude_task || opencode || pi
+ let pi = fits(file, "pi-bash-*.log")? && spells(file, "pi-bash-");
+ Ok(claude_results || claude_task || opencode || pi)
}
/// Whether a one-segment glob spells part of `word` in literal text: some
@@ -1248,53 +1290,120 @@ fn globs_intersect(left: &[char], right: &[char]) -> bool {
common[0][0]
}
+/// Tool names (compared ASCII-lowercased) whose calls name the files they
+/// read or write. The generated TypeScript integrations embed this list, so
+/// the two front doors cannot drift apart. Gemini CLI's `read_many_files`
+/// reads every file its `include` globs expand to.
+pub const FILE_TOOL_NAMES: &[&str] = &[
+ "read",
+ "write",
+ "edit",
+ "apply_patch",
+ "notebookedit",
+ "notebook_edit",
+ "create_file",
+ "delete_file",
+ "remove",
+ "rename_file",
+ "move_file",
+ "multi_edit",
+ "multiedit",
+ "replace",
+ "replace_all",
+ "view_file",
+ "replace_file_content",
+ "multi_replace_file_content",
+ "write_to_file",
+ "fs_read",
+ "fs_write",
+ "read_file",
+ "write_file",
+ "edit_file",
+ "patch",
+ "read_many_files",
+];
+
+/// Search and list tools, whose output under an active policy is dropped.
+/// Includes Gemini CLI's directory listing and the pre-rename name of its
+/// `grep_search` that it still accepts as an alias.
+pub const SEARCH_LIST_TOOL_NAMES: &[&str] = &[
+ "search",
+ "grep",
+ "glob",
+ "find",
+ "list",
+ "ls",
+ "list_files",
+ "read_dir",
+ "list_dir",
+ "grep_search",
+ "search_files",
+ "find_by_name",
+ "list_directory",
+ "search_file_content",
+];
+
+/// Tools that name no workspace file path of their own: shells (Claude Code's
+/// `PowerShell` beside `Bash` with the same `tool_input.command` field, #1186;
+/// Gemini CLI's `run_shell_command`, `{command, dir_path?}`) and the Hermes
+/// Agent tools that execute code, drive a browser, or fetch the web
+/// (agent/shell_hooks.py envelope; names from the model_tools registry,
+/// live-captured 2026-10-07). They are non-file rather than unknown because
+/// family `unknown` drops the tool output from observation bodies.
+pub const NON_FILE_TOOL_NAMES: &[&str] = &[
+ "bash",
+ "shell",
+ "shell_command",
+ "exec",
+ "execute",
+ "run_command",
+ "web_search",
+ "search_web",
+ "manage_task",
+ "manage_subagents",
+ "terminal",
+ "execute_bash",
+ "execute_cmd",
+ "powershell",
+ "run_shell_command",
+ "execute_code",
+ "browser_exec",
+ "browser_navigate",
+ "web_extract",
+ "web_fetch",
+ "delegate_task",
+];
+
+/// Non-file tools whose input is program source (Hermes `execute_code`,
+/// `{"code": "..."}`): like `python3 -c`, it builds paths at run time, so
+/// nothing lexical proves it read no ignored file.
+pub const INLINE_CODE_TOOL_NAMES: &[&str] = &["execute_code"];
+
+/// Tools that return output of a command started by an earlier call: Claude
+/// Code `BashOutput`/`TaskOutput`, Codex `write_stdin`, Hermes and OpenClaw
+/// `process`, Copilot CLI `read_bash`/`write_bash` and their PowerShell twins.
+pub const OUTPUT_READER_TOOL_NAMES: &[&str] = &[
+ "bashoutput",
+ "taskoutput",
+ "write_stdin",
+ "process",
+ "read_bash",
+ "write_bash",
+ "read_powershell",
+ "write_powershell",
+];
+
fn family(name: &str) -> ToolFamily {
- match name.to_ascii_lowercase().as_str() {
- "read"
- | "write"
- | "edit"
- | "apply_patch"
- | "notebookedit"
- | "notebook_edit"
- | "create_file"
- | "delete_file"
- | "remove"
- | "rename_file"
- | "move_file"
- | "multi_edit"
- | "multiedit"
- | "replace"
- | "replace_all"
- | "view_file"
- | "replace_file_content"
- | "multi_replace_file_content"
- | "write_to_file"
- | "fs_read"
- | "fs_write" => ToolFamily::File,
- "read_file" | "write_file" | "edit_file" | "patch" => ToolFamily::File,
- // Gemini CLI reads every file its `include` globs expand to.
- "read_many_files" => ToolFamily::File,
- "search" | "grep" | "glob" | "find" | "list" | "ls" | "list_files" | "read_dir"
- | "list_dir" | "grep_search" | "search_files" | "find_by_name" => ToolFamily::SearchList,
- // Gemini CLI's directory listing, and the pre-rename name of its
- // `grep_search` that it still accepts as an alias.
- "list_directory" | "search_file_content" => ToolFamily::SearchList,
- "bash" | "shell" | "shell_command" | "exec" | "execute" | "run_command" | "web_search"
- | "search_web" | "manage_task" | "manage_subagents" | "terminal" | "execute_bash"
- | "execute_cmd" => ToolFamily::NonFile,
- // Claude Code on Windows exposes `PowerShell` beside `Bash`, with the
- // same `tool_input.command` field (#1186).
- "powershell" => ToolFamily::NonFile,
- // Gemini CLI's shell tool, `{command, dir_path?}`.
- "run_shell_command" => ToolFamily::NonFile,
- // Hermes Agent tool surface (agent/shell_hooks.py envelope; tool
- // names from model_tools registry, live-captured 2026-10-07). These
- // execute code, drive a browser, or fetch the web — none touch
- // workspace file paths, so they are non-file rather than unknown:
- // family `unknown` drops the tool output from observation bodies.
- "execute_code" | "browser_exec" | "browser_navigate" | "web_extract" | "web_fetch"
- | "delegate_task" => ToolFamily::NonFile,
- _ => ToolFamily::Unknown,
+ let name = name.to_ascii_lowercase();
+ let name = name.as_str();
+ if FILE_TOOL_NAMES.contains(&name) {
+ ToolFamily::File
+ } else if SEARCH_LIST_TOOL_NAMES.contains(&name) {
+ ToolFamily::SearchList
+ } else if NON_FILE_TOOL_NAMES.contains(&name) {
+ ToolFamily::NonFile
+ } else {
+ ToolFamily::Unknown
}
}
fn canonical(family: ToolFamily) -> CanonicalTool {
@@ -1512,6 +1621,9 @@ pub fn capture_lookup_locations(
}
}
(ToolFamily::NonFile, Some(command)) => {
+ if command.oversized() {
+ return None;
+ }
let base = command_base(extracted.workdir.as_deref(), cwd);
push(normalize_candidate(&base, &base))?;
let home = home.and_then(|dir| normalize_root(dir).ok());
@@ -2001,6 +2113,16 @@ fn brace_overflow_could_leave(segment: &str) -> bool {
/// 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 {
+ // A Windows shell's own spellings of its directory (`/c/x`, `\\?\C:\x`)
+ // must not turn the base, and every argument resolved from it, POSIX.
+ if let Some(dir) = workdir
+ && let Ok(root) = normalize_root(cwd)
+ && flavor_of(&root) == Flavor::Windows
+ && !is_drive_relative(dir)
+ && let Some(base) = windows_spelling(dir, &root)
+ {
+ return base;
+ }
match workdir {
Some(dir) if is_absolute(dir) => dir.to_owned(),
// `join` would turn an unusable cwd into `/dir`.
@@ -2067,7 +2189,34 @@ struct ShellWords {
expanded: Vec<(String, bool)>,
}
+/// Longest shell command, in characters summed over its argv elements, the
+/// matcher splits. Splitting, matching and the marker-lookup scan are linear
+/// in the command (tens of milliseconds per MiB in a release build), but the
+/// hook reads an unbounded payload and only the glob walk is timed, so a
+/// longer command is unprovable: metadata-only under an active policy, and
+/// no marker lookup (the invalid-policy decision, metadata-only for a shell).
+pub const MAX_SHELL_COMMAND_CHARS: usize = 1024 * 1024;
+
impl ShellCommand<'_> {
+ /// Longer than [`MAX_SHELL_COMMAND_CHARS`].
+ fn oversized(&self) -> bool {
+ let over = |text: &str| {
+ // Bytes bound characters from above, so most commands are cleared
+ // without counting.
+ text.len() > MAX_SHELL_COMMAND_CHARS && text.chars().count() > MAX_SHELL_COMMAND_CHARS
+ };
+ match self {
+ Self::Line(command) => over(command),
+ Self::Argv(items) => {
+ let mut total = 0_usize;
+ items.iter().any(|item| {
+ total = total.saturating_add(item.chars().count());
+ total > MAX_SHELL_COMMAND_CHARS
+ })
+ }
+ }
+ }
+
#[cfg(test)]
fn words(&self) -> Vec<String> {
self.split(false)
@@ -3180,6 +3329,9 @@ fn candidate_raw(candidate: &str, cwd: &str) -> Option<(String, Flavor)> {
return None;
}
let cwd = normalize_root(cwd).ok()?;
+ if flavor_of(&cwd) == Flavor::Windows {
+ return Some((windows_spelling(candidate, &cwd)?, Flavor::Windows));
+ }
// Flavor must come from the host (the cwd), never from the candidate
// string alone: on a POSIX host a leading `//` is an ordinary doubled
// separator, not a UNC root, but `flavor_of` cannot tell the two apart
@@ -3201,6 +3353,88 @@ fn candidate_raw(candidate: &str, cwd: &str) -> Option<(String, Flavor)> {
let flavor = flavor_of(&raw);
Some((raw, flavor))
}
+/// The absolute path Windows opens for `candidate` from the normalized
+/// Windows `cwd`, spelled with `/`, its `.` and `..` segments still in place.
+/// Every spelling of one file comes out the same, because an ignore pattern
+/// names only one of them:
+///
+/// - the Win32 device and NT prefixes `\\?\`, `\\.\` and `\??\` before a
+/// drive or `UNC\server\share`, and the administrative share of the local
+/// machine (`\\localhost\C$`, `\\127.0.0.1\C$`), name the drive or share
+/// itself; any other device (a volume GUID, a pipe) is no usable path;
+/// - Git Bash, MSYS2 and Cygwin spell `C:\x` as `/c/x` and `/cygdrive/c/x`;
+/// - any other rooted path (`/x`, `\x`) is on the cwd's drive or share;
+/// - Windows drops an alternate data stream suffix (`name:stream`,
+/// `name::$DATA`, the file's own content) and the trailing dots and spaces
+/// of every segment (`private.md.`, `secrets. `).
+///
+/// A native tool reads `/c/x` as `C:\c\x`; only the MSYS reading is kept, so
+/// a pattern under a one-letter top-level directory misses that spelling.
+fn windows_spelling(candidate: &str, cwd: &str) -> Option<String> {
+ let one_letter =
+ |segment: &str| segment.len() == 1 && segment.as_bytes()[0].is_ascii_alphabetic();
+ let mut path = candidate.replace('\\', "/");
+ if let Some(rest) = ["//?/", "//./", "/??/"]
+ .iter()
+ .find_map(|prefix| path.strip_prefix(prefix))
+ {
+ path = if let Some(unc) = rest
+ .get(..4)
+ .filter(|unc| unc.eq_ignore_ascii_case("unc/"))
+ .and_then(|_| rest.get(4..))
+ {
+ format!("//{unc}")
+ } else if valid_drive_prefix(rest) {
+ rest.to_owned()
+ } else {
+ return None;
+ };
+ }
+ if valid_drive_prefix(&path) && path.len() == 2 {
+ path.push('/');
+ }
+ if let Some(rest) = path.strip_prefix("//") {
+ let mut parts = rest.splitn(3, '/');
+ let (server, share) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
+ if (server.eq_ignore_ascii_case("localhost") || server == "127.0.0.1")
+ && share.len() == 2
+ && share.as_bytes()[0].is_ascii_alphabetic()
+ && share.as_bytes()[1] == b'$'
+ {
+ path = format!("{}:/{}", &share[..1], parts.next().unwrap_or(""));
+ }
+ } else if let Some(rest) = path.strip_prefix('/') {
+ let forward = candidate.starts_with('/');
+ let (first, after) = rest.split_once('/').unwrap_or((rest, ""));
+ let cygdrive = after.split_once('/').unwrap_or((after, ""));
+ path = if forward && one_letter(first) {
+ format!("{}:/{after}", first.to_ascii_uppercase())
+ } else if forward && first.eq_ignore_ascii_case("cygdrive") && one_letter(cygdrive.0) {
+ format!("{}:/{}", cygdrive.0.to_ascii_uppercase(), cygdrive.1)
+ } else {
+ let (root, _) = split_root(cwd)?;
+ format!("{}{path}", root.trim_end_matches('/'))
+ };
+ } else if !is_absolute(&path) {
+ path = join(cwd, &path);
+ }
+ let (root, tail) = split_root(&path)?;
+ let parts: Vec<&str> = tail.into_iter().filter_map(windows_segment).collect();
+ Some(join_segments(root, &parts))
+}
+
+/// One segment as Windows reads it ([`windows_spelling`]); `None` when nothing
+/// is left of it.
+fn windows_segment(segment: &str) -> Option<&str> {
+ let name = segment.split(':').next().unwrap_or(segment);
+ let unspaced = name.trim_end_matches(' ');
+ if unspaced == "." || unspaced == ".." {
+ return Some(unspaced);
+ }
+ let name = name.trim_end_matches(['.', ' ']);
+ (!name.is_empty()).then_some(name)
+}
+
fn compile(
config: &CaptureConfig,
marker_dir: &str,
@@ -4508,6 +4742,201 @@ mod tests {
/// The drop/keep tables live in the shared fixture so the generated
/// TypeScript matcher runs the very same vectors (#961).
+ /// The shared Windows-spelling vectors. Adversarial: every Git Bash,
+ /// MSYS2, Cygwin, rooted, device, administrative-share, trailing
+ /// dot/space and alternate-data-stream spelling of an ignored file in a
+ /// Windows session drops, file tool or shell. Controls: the same names on
+ /// another drive or share, a longer name, and a POSIX session (where a
+ /// trailing dot, a colon or `/c/...` is part of the name) keep.
+ #[test]
+ fn windows_spelling_fixture_vectors() {
+ let fixture: Value =
+ serde_json::from_str(include_str!("../tests/fixtures/capture-policy.json")).unwrap();
+ for name in ["windows", "windows_posix_controls"] {
+ let section = &fixture[name];
+ let cwd = section["cwd"].as_str().unwrap();
+ let config = CaptureConfig {
+ ignore_paths: section["ignore_paths"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|pattern| pattern.as_str().unwrap().to_owned())
+ .collect(),
+ };
+ let policy =
+ CapturePolicy::resolve_for_host(CaptureSource::Parsed(&config), cwd, None, false);
+ let shell = section["shell"].as_array().cloned().unwrap_or_default();
+ let files = section["files"].as_array().unwrap().iter().map(|vector| {
+ (
+ json!({"tool": "edit", "args": {"path": vector["path"]}}),
+ vector,
+ )
+ });
+ let commands = shell.iter().map(|vector| {
+ let payload = vector.get("payload").cloned().unwrap_or_else(
+ || json!({"tool": "bash", "args": {"command": vector["command"]}}),
+ );
+ (payload, vector)
+ });
+ for (payload, vector) in files.chain(commands) {
+ let decision = policy.inspect(AgentKind::OpenCode, &payload, cwd);
+ assert_eq!(
+ serde_json::to_value(decision.protocol().disposition()).unwrap(),
+ vector["disposition"],
+ "{name}: {vector}"
+ );
+ }
+ }
+ }
+
+ /// Native and generated TypeScript classify every tool name alike; the
+ /// TypeScript lists are generated from these constants.
+ #[test]
+ fn tool_family_fixture_vectors() {
+ let fixture: Value =
+ serde_json::from_str(include_str!("../tests/fixtures/capture-policy.json")).unwrap();
+ for vector in fixture["tool_families"].as_array().unwrap() {
+ let name = vector["name"].as_str().unwrap();
+ assert_eq!(
+ serde_json::to_value(family(name)).unwrap(),
+ vector["family"],
+ "{name}"
+ );
+ }
+ }
+
+ /// Adversarial: a path of thousands of `*` segments used to cost a
+ /// quadratic number of allocating glob intersections outside any budget
+ /// (~400 ms for one, 14 s for 32). The check is linear, charged to the
+ /// match budget, and a call past the budget fails closed. Controls: a
+ /// real spool path is still found, and one long path or 32 short ones
+ /// keep.
+ #[test]
+ fn output_spool_work_is_linear_and_budgeted() {
+ let path = format!("/tmp/{}x", "*/".repeat(2040));
+ let mut work = 0;
+ assert_eq!(output_spool(&path, &mut work), Ok(false));
+ assert!(
+ work <= 64 * path.len(),
+ "spool work {work} for {} chars",
+ path.len()
+ );
+ assert_eq!(
+ output_spool("/home/u/.claude/projects/p/s/tool-results/a.txt", &mut 0),
+ Ok(true)
+ );
+ assert_eq!(output_spool(&path, &mut MAX_MATCH_WORK.clone()), Err(()));
+ // A two-character pattern keeps the path match itself under budget
+ // (natively and in the generated TypeScript), so only the spool check
+ // can run out.
+ let policy = CapturePolicy::resolve(
+ CaptureSource::Parsed(&CaptureConfig {
+ ignore_paths: vec!["/s".into()],
+ }),
+ "/repo",
+ None,
+ );
+ let read = |paths: &[String]| {
+ policy
+ .inspect(
+ AgentKind::ClaudeCode,
+ &json!({"tool_name": "Read", "tool_input": {"paths": paths}}),
+ "/repo",
+ )
+ .protocol()
+ .disposition()
+ };
+ let long: Vec<String> = (0..32)
+ .map(|i| format!("/tmp/{i}/{}x", "*/".repeat(2000)))
+ .collect();
+ assert_eq!(read(&long), CaptureDisposition::MetadataOnly);
+ assert_eq!(read(&long[..1]), CaptureDisposition::Keep);
+ let short: Vec<String> = (0..32).map(|i| format!("/tmp/{i}/x")).collect();
+ assert_eq!(read(&short), CaptureDisposition::Keep);
+ }
+
+ /// A command longer than [`MAX_SHELL_COMMAND_CHARS`] is not split: it is
+ /// metadata-only under a policy and its marker lookup is unprovable.
+ /// Controls: one character shorter keeps and is looked up, and without a
+ /// policy nothing changes.
+ #[test]
+ fn an_oversized_shell_command_is_unprovable() {
+ let policy = CapturePolicy::resolve(
+ CaptureSource::Parsed(&CaptureConfig {
+ ignore_paths: vec!["secret/**".into()],
+ }),
+ "/repo",
+ None,
+ );
+ let at_limit = format!("cat public.md{}", " ".repeat(MAX_SHELL_COMMAND_CHARS - 13));
+ let over = format!("{at_limit} ");
+ let bash = |command: &str| json!({"tool_name": "Bash", "tool_input": {"command": command}});
+ let decide = |policy: &CapturePolicy, raw: &Value| {
+ policy
+ .inspect(AgentKind::ClaudeCode, raw, "/repo")
+ .protocol()
+ .disposition()
+ };
+ assert_eq!(decide(&policy, &bash(&at_limit)), CaptureDisposition::Keep);
+ assert_eq!(
+ decide(&policy, &bash(&over)),
+ CaptureDisposition::MetadataOnly
+ );
+ let argv =
+ json!({"tool_name": "shell", "tool_input": {"command": ["bash", "-lc", at_limit]}});
+ assert_eq!(
+ policy
+ .inspect(AgentKind::Codex, &argv, "/repo")
+ .protocol()
+ .disposition(),
+ CaptureDisposition::MetadataOnly
+ );
+ assert_eq!(
+ decide(&CapturePolicy::inactive(), &bash(&over)),
+ CaptureDisposition::Keep
+ );
+ assert!(
+ capture_lookup_locations(AgentKind::ClaudeCode, &bash(&over), "/repo", None).is_none()
+ );
+ assert!(
+ capture_lookup_locations(AgentKind::ClaudeCode, &bash(&at_limit), "/repo", None)
+ .is_some()
+ );
+ }
+
+ /// Hermes `execute_code` runs program source, which names its paths at
+ /// run time: metadata-only under an active or broken policy, untouched
+ /// without one. Control: a browser tool keeps.
+ #[test]
+ fn inline_code_tools_are_unprovable_under_a_policy() {
+ let raw = json!({"tool_name": "execute_code", "tool_input": {"code": "print(open('secret/a.txt').read())"}});
+ let active = CapturePolicy::resolve(
+ CaptureSource::Parsed(&CaptureConfig {
+ ignore_paths: vec!["secret/**".into()],
+ }),
+ "/repo",
+ None,
+ );
+ let invalid = CapturePolicy::resolve(CaptureSource::Invalid, "/repo", None);
+ for (policy, expected) in [
+ (&active, CaptureDisposition::MetadataOnly),
+ (&invalid, CaptureDisposition::MetadataOnly),
+ (&CapturePolicy::inactive(), CaptureDisposition::Keep),
+ ] {
+ let decision = policy.inspect(AgentKind::Hermes, &raw, "/repo");
+ assert_eq!(decision.protocol().disposition(), expected);
+ assert_eq!(decision.protocol().tool_family(), ToolFamily::NonFile);
+ }
+ let browse = json!({"tool_name": "browser_navigate", "tool_input": {"url": "https://example.com/secret/a"}});
+ assert_eq!(
+ active
+ .inspect(AgentKind::Hermes, &browse, "/repo")
+ .protocol()
+ .disposition(),
+ CaptureDisposition::Keep
+ );
+ }
+
#[test]
fn shell_fixture_vectors() {
let fixture: Value =
@@ -5547,7 +5976,7 @@ mod tests {
"/data/*/t*/tool_01",
"/home/me/.c*/p*/x/s/t*/a.txt",
] {
- assert!(!output_spool(path), "{path}");
+ assert_eq!(output_spool(path, &mut 0), Ok(false), "{path}");
}
for path in [
"/tmp/pi-*",
@@ -5557,7 +5986,7 @@ mod tests {
"/data/*/tool-*/tool_01",
"/tmp/c*/x/s/tasks/*",
] {
- assert!(output_spool(path), "{path}");
+ assert_eq!(output_spool(path, &mut 0), Ok(true), "{path}");
}
}
diff --git a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
index 99918e77..377ce1e2 100644
--- a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
+++ b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
@@ -102,7 +102,14 @@
{"agent":"copilot-cli","payload":{"tool_name":"write_powershell","tool_input":{"shellId":"s1","input":"x"}},"disposition":"metadata-only","tool_family":"unknown","extraction_state":"extracted","path_count":0},
{"agent":"openclaw","payload":{"tool":"process","args":{"action":"log","sessionId":"p1"}},"disposition":"metadata-only","tool_family":"unknown","extraction_state":"extracted","path_count":0},
{"agent":"open-code","payload":{"tool":"process","args":{"action":"log"}},"disposition":"metadata-only","tool_family":"unknown","extraction_state":"extracted","path_count":0},
- {"agent":"openclaw","payload":{"tool":"future_tool","args":{"action":"log"}},"disposition":"keep","tool_family":"unknown","extraction_state":"extracted","path_count":0}
+ {"agent":"openclaw","payload":{"tool":"future_tool","args":{"action":"log"}},"disposition":"keep","tool_family":"unknown","extraction_state":"extracted","path_count":0},
+ {"agent":"open-code","payload":{"tool":"execute_code","args":{"code":"print(open('secret/a.txt').read())"}},"disposition":"metadata-only","tool_family":"non-file","extraction_state":"extracted","path_count":0},
+ {"agent":"hermes","payload":{"tool_name":"execute_code","tool_input":{"code":"print(open('secret/a.txt').read())"}},"disposition":"metadata-only","tool_family":"non-file","extraction_state":"extracted","path_count":0},
+ {"agent":"open-code","payload":{"tool":"browser_navigate","args":{"url":"https://example.com/secret/a"}},"disposition":"keep","tool_family":"non-file","extraction_state":"extracted","path_count":0},
+ {"agent":"open-code","payload":{"tool":"fs_read","args":{"operations":[{"path":"public/a"},{"path":"secret/a"}]}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":2},
+ {"agent":"open-code","payload":{"tool":"read_file","args":{"path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},
+ {"agent":"open-code","payload":{"tool":"patch","args":{"path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},
+ {"agent":"open-code","payload":{"tool":"write_to_file","args":{"TargetFile":"public/a"}},"disposition":"keep","tool_family":"file","extraction_state":"extracted","path_count":1}
],
"read_many_files_directories": {
"note": "Gemini CLI reads a directory entry as `entry/**`; both matchers run these as `read_many_files` `include` lists from the marker directory.",
@@ -385,5 +392,9 @@
{"command":"jq .[] package.json","disposition":"keep"}
]
},
- "protocol": {"accept":{"version":1,"disposition":"drop","policy_state":"active","tool_family":"file","path_count":1,"extraction_state":"extracted"},"reject":{"version":1,"disposition":"drop","policy_state":"active","tool_family":"file","path_count":1,"extraction_state":"extracted","paths":["SENTINEL"]}}
+ "protocol": {"accept":{"version":1,"disposition":"drop","policy_state":"active","tool_family":"file","path_count":1,"extraction_state":"extracted"},"reject":{"version":1,"disposition":"drop","policy_state":"active","tool_family":"file","path_count":1,"extraction_state":"extracted","paths":["SENTINEL"]}},
+ "windows": {"note": "A Windows session (cwd C:\\repo) reads Git Bash/MSYS/Cygwin, rooted, device, administrative-share, trailing dot/space and alternate-data-stream spellings as the file they open; both matchers run `files` as an `edit` path and `shell` as a `bash` call.", "cwd": "C:\\repo", "ignore_paths": ["C:/repo/secrets/**", "C:/repo/private.md"], "files": [{"path": "/c/repo/secrets/a", "disposition": "drop"}, {"path": "/C/repo/secrets/a", "disposition": "drop"}, {"path": "/cygdrive/c/repo/secrets/a", "disposition": "drop"}, {"path": "/repo/secrets/a", "disposition": "drop"}, {"path": "\\repo\\secrets\\a", "disposition": "drop"}, {"path": "secrets.\\a", "disposition": "drop"}, {"path": "secrets \\a", "disposition": "drop"}, {"path": "C:\\repo\\secrets. .\\a", "disposition": "drop"}, {"path": "private.md.", "disposition": "drop"}, {"path": "private.md ", "disposition": "drop"}, {"path": "private.md...", "disposition": "drop"}, {"path": "private.md::$DATA", "disposition": "drop"}, {"path": "private.md:stream", "disposition": "drop"}, {"path": "PRIVATE.MD", "disposition": "drop"}, {"path": "\\\\?\\C:\\repo\\private.md", "disposition": "drop"}, {"path": "\\\\.\\C:\\repo\\private.md", "disposition": "drop"}, {"path": "\\??\\C:\\repo\\private.md", "disposition": "drop"}, {"path": "\\\\localhost\\C$\\repo\\private.md", "disposition": "drop"}, {"path": "\\\\127.0.0.1\\c$\\repo\\private.md", "disposition": "drop"}, {"path": "\\\\?\\UNC\\localhost\\C$\\repo\\private.md", "disposition": "drop"}, {"path": "/c/repo/public.md", "disposition": "keep"}, {"path": "/d/repo/secrets/a", "disposition": "keep"}, {"path": "/cygdrive/d/repo/secrets/a", "disposition": "keep"}, {"path": "/repo/public/a", "disposition": "keep"}, {"path": "private.md.bak", "disposition": "keep"}, {"path": "public.md:private.md", "disposition": "keep"}, {"path": "\\\\localhost\\D$\\repo\\private.md", "disposition": "keep"}, {"path": "\\\\server\\C$\\repo\\private.md", "disposition": "keep"}, {"path": "\\\\.\\pipe\\private.md", "disposition": "metadata-only"}], "shell": [{"command": "cat /c/repo/secrets/a", "disposition": "drop"}, {"command": "cat /C/repo/secrets/a", "disposition": "drop"}, {"command": "cat /cygdrive/c/repo/secrets/a", "disposition": "drop"}, {"command": "cat /repo/secrets/a", "disposition": "drop"}, {"command": "type \\repo\\secrets\\a", "disposition": "drop"}, {"command": "cat secrets./a", "disposition": "drop"}, {"command": "cat 'private.md.'", "disposition": "drop"}, {"command": "cat 'private.md '", "disposition": "drop"}, {"command": "cat 'private.md::$DATA'", "disposition": "drop"}, {"command": "more < private.md:stream", "disposition": "drop"}, {"command": "type '\\\\?\\C:\\repo\\private.md'", "disposition": "drop"}, {"command": "type '\\\\localhost\\C$\\repo\\private.md'", "disposition": "drop"}, {"payload": {"tool": "bash", "args": {"command": "cat secrets/a", "workdir": "/c/repo"}}, "disposition": "drop"}, {"command": "cat /c/repo/public.md", "disposition": "keep"}, {"command": "cat /d/repo/secrets/a", "disposition": "keep"}, {"command": "cat 'private.md.bak'", "disposition": "keep"}, {"payload": {"tool": "bash", "args": {"command": "cat secrets/a", "workdir": "/c/other"}}, "disposition": "keep"}]},
+ "windows_posix_controls": {"note": "The Windows readings never apply to a POSIX session: there a trailing dot, a colon or a one-letter top-level directory is part of the name.", "cwd": "/repo", "ignore_paths": ["/repo/secrets/**", "/repo/private.md", "/c/repo/drive/**"], "files": [{"path": "/repo/secrets/a", "disposition": "drop"}, {"path": "/c/repo/drive/a", "disposition": "drop"}, {"path": "/c/repo/secrets/a", "disposition": "keep"}, {"path": "secrets./a", "disposition": "keep"}, {"path": "private.md.", "disposition": "keep"}, {"path": "private.md:stream", "disposition": "keep"}, {"path": "/cygdrive/c/repo/drive/a", "disposition": "keep"}]},
+ "marker_spellings": {"note": "Every TOML spelling of the capture table the native parser (toml_edit) honours, and the ones it rejects; the TypeScript reader must agree. Each declares `secret/**`.", "honoured": ["capture.ignore_paths = [\"secret/**\"]\n", "capture . \"ignore_paths\" = [\"secret/**\"]\n[other]\nx = 1\n", "[ capture ]\nignore_paths = [\"secret/**\"]\n", "[\"capture\"]\nignore_paths = [\"secret/**\"]\n", "['capture']\n'ignore_paths' = [\"secret/**\"]\n", "[\"\\u0063apture\"]\nignore_paths = [\"secret/**\"]\n", "[[tools]]\nname = \"x\"\n[capture]\nignore_paths = [\"secret/**\"]\n"], "rejected": ["capture = { ignore_paths = [\"secret/**\"] }\n", "[[capture]]\nignore_paths = [\"secret/**\"]\n", "[capture.extra]\nx = 1\n", "capture = 1\n", "[capture]\nignore_paths = [\"secret/**\"]\n[capture]\n", "capture.ignore_paths = [\"secret/**\"]\n[capture]\n"], "unrelated": ["[tool]\ncapture.ignore_paths = [\"secret/**\"]\n", "x = 1\n"]},
+ "tool_families": [{"name": "read", "family": "file"}, {"name": "write", "family": "file"}, {"name": "edit", "family": "file"}, {"name": "apply_patch", "family": "file"}, {"name": "notebookedit", "family": "file"}, {"name": "notebook_edit", "family": "file"}, {"name": "create_file", "family": "file"}, {"name": "delete_file", "family": "file"}, {"name": "remove", "family": "file"}, {"name": "rename_file", "family": "file"}, {"name": "move_file", "family": "file"}, {"name": "multi_edit", "family": "file"}, {"name": "multiedit", "family": "file"}, {"name": "replace", "family": "file"}, {"name": "replace_all", "family": "file"}, {"name": "view_file", "family": "file"}, {"name": "replace_file_content", "family": "file"}, {"name": "multi_replace_file_content", "family": "file"}, {"name": "write_to_file", "family": "file"}, {"name": "fs_read", "family": "file"}, {"name": "fs_write", "family": "file"}, {"name": "read_file", "family": "file"}, {"name": "write_file", "family": "file"}, {"name": "edit_file", "family": "file"}, {"name": "patch", "family": "file"}, {"name": "read_many_files", "family": "file"}, {"name": "search", "family": "search-list"}, {"name": "grep", "family": "search-list"}, {"name": "glob", "family": "search-list"}, {"name": "find", "family": "search-list"}, {"name": "list", "family": "search-list"}, {"name": "ls", "family": "search-list"}, {"name": "list_files", "family": "search-list"}, {"name": "read_dir", "family": "search-list"}, {"name": "list_dir", "family": "search-list"}, {"name": "grep_search", "family": "search-list"}, {"name": "search_files", "family": "search-list"}, {"name": "find_by_name", "family": "search-list"}, {"name": "list_directory", "family": "search-list"}, {"name": "search_file_content", "family": "search-list"}, {"name": "bash", "family": "non-file"}, {"name": "shell", "family": "non-file"}, {"name": "shell_command", "family": "non-file"}, {"name": "exec", "family": "non-file"}, {"name": "execute", "family": "non-file"}, {"name": "run_command", "family": "non-file"}, {"name": "web_search", "family": "non-file"}, {"name": "search_web", "family": "non-file"}, {"name": "manage_task", "family": "non-file"}, {"name": "manage_subagents", "family": "non-file"}, {"name": "terminal", "family": "non-file"}, {"name": "execute_bash", "family": "non-file"}, {"name": "execute_cmd", "family": "non-file"}, {"name": "powershell", "family": "non-file"}, {"name": "run_shell_command", "family": "non-file"}, {"name": "execute_code", "family": "non-file"}, {"name": "browser_exec", "family": "non-file"}, {"name": "browser_navigate", "family": "non-file"}, {"name": "web_extract", "family": "non-file"}, {"name": "web_fetch", "family": "non-file"}, {"name": "delegate_task", "family": "non-file"}, {"name": "bashoutput", "family": "unknown"}, {"name": "taskoutput", "family": "unknown"}, {"name": "write_stdin", "family": "unknown"}, {"name": "process", "family": "unknown"}, {"name": "read_bash", "family": "unknown"}, {"name": "write_bash", "family": "unknown"}, {"name": "read_powershell", "family": "unknown"}, {"name": "write_powershell", "family": "unknown"}, {"name": "todowrite", "family": "unknown"}, {"name": "mcp__x__read", "family": "unknown"}, {"name": "view", "family": "unknown"}, {"name": "Read_File", "family": "file"}, {"name": "Execute_Code", "family": "non-file"}]
}
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 97b53550..6753ef1f 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -484,7 +484,12 @@ The **nearest** `.ai-memory.toml` is authoritative; marker sections do not
merge. A missing `[capture]` section or `ignore_paths = []` is inactive and
preserves current behavior. `[capture]` accepts only `ignore_paths`: unknown
keys, invalid types/globs/roots, unreadable markers, or a marker over 64 KiB
-invalidate the whole capture policy rather than partially applying it.
+invalidate the whole capture policy rather than partially applying it. Any
+TOML spelling of the table works (`[ capture ]`, `["capture"]`, or a top-level
+dotted `capture.ignore_paths = [...]`), and the shapes TOML does not make a
+plain table (an inline `capture = { ignore_paths = [...] }`, `[[capture]]`, a
+`[capture.x]` subtable, a second `[capture]`) are invalid. The native hook and
+the generated TypeScript integrations reach the same decision for each.
Patterns match an entire lexically normalized path, not a substring. Use only
`*`, `?`, and `**`; relative patterns are rooted at the marker directory,
@@ -495,6 +500,12 @@ case-insensitive. Bounds are 128 patterns, 1,024 characters per pattern, 32
direct candidates and 4,096 characters per candidate, and 1,000,000 bounded
pattern/candidate comparisons.
+A `**/` matches one or more directories, never zero, unlike `.gitignore`:
+`**/.env` matches `sub/.env` but not the `.env` at the marker directory, and
+`docs/**/x.md` does not match `docs/x.md`. List both forms when you mean both
+(`[".env", "**/.env"]`). A trailing `/**` does match the directory itself
+(`secrets/**` covers `secrets`).
+
For fixture-proven direct file tools, ai-memory reads only explicit path fields
and documented direct arrays for multi-file calls. If any candidate matches, the
entire event is **dropped locally** before spool, queue, network, transport
@@ -606,8 +617,14 @@ also after options that take a value, as in `python3 -W ignore -c`) is
**metadata-only** under an active policy
unless one of its words names an ignored path outright, which drops it:
code can build a path at run time (`'docs/' + name`), so no lexical match can
-rule one out. Running a script file or a module (`python3 -m pytest`,
-`node build.js`) is unaffected. Variables, command substitution, `cd` state, and
+rule one out. Hermes Agent's `execute_code` tool, which runs program source
+it is given, is metadata-only under an active policy for the same reason.
+Running a script file or a module (`python3 -m pytest`,
+`node build.js`) is unaffected. A shell command longer than 1 MiB (1,048,576
+characters, summed over the elements of an argument vector) is not read at
+all: it is metadata-only under an active policy, and its marker lookup
+(below) counts as unprovable, which makes it metadata-only even in a
+directory without a marker. Variables, command substitution, `cd` state, and
commands that name no path at all (`rg TODO`, `git diff`) are not followed, so
their output is still captured. An invalid policy makes a shell command
**metadata-only**, like a file tool, because a broken marker cannot prove its
@@ -618,6 +635,19 @@ generated integrations match file-tool and shell paths without regard to case
decomposed accent like the composed letter, as its filesystem does; other POSIX
hosts compare case-sensitively, and Windows paths always ignore ASCII case.
+In a Windows session (the event's `cwd` is a drive or UNC path), a file-tool
+path, shell argument or `workdir` is read as the file Windows opens, so other
+spellings of an ignored file match its pattern too: Git Bash, MSYS2 and Cygwin
+`/c/Users/me/repo/x` and `/cygdrive/c/...` are `C:\Users\me\repo\x`; a rooted
+path without a drive (`/repo/x`, `\repo\x`) is on the `cwd`'s drive; the
+`\\?\`, `\\.\` and `\??\` prefixes and the local administrative share
+(`\\localhost\C$\...`, `\\127.0.0.1\C$\...`) name the drive itself; an
+alternate data stream suffix (`private.md::$DATA`, `private.md:stream`) and the
+trailing dots and spaces of each segment (`private.md.`, `secrets. \x`) are
+dropped. Any other device path (`\\.\pipe\x`) makes a file tool
+metadata-only. None of this applies to a POSIX session, where `/c/x`, a
+trailing dot or a colon is part of the name.
+
A checkout's exclusions protect its files wherever a call is made from. For
every file-tool target (for `apply_patch`, the files its `*** Add File:`,
`*** Update File:`, `*** Delete File:` and `*** Move to:` headers name, read
@@ -733,6 +763,13 @@ can be mentioned.
- 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-escapes
are not decoded;
+- in a Windows session `/c/x` is read only as Git Bash reads it
+ (`C:\x`), so a native tool's reading of it (`C:\c\x`, under a one-letter
+ top-level directory) is not matched;
+- the generated TypeScript integrations check the `[capture]` table as
+ strictly as the native hook but do not validate the rest of the marker's
+ TOML, so a syntax error elsewhere in the file invalidates the policy only in
+ the native hook;
- tools the matcher does not list keep their current behavior.
For a project whose content must never be captured, use allowlist capture mode
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index f27d0058..e321de5f 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`, 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 |
+| 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 ; in a Windows session every candidate, shell argument and `workdir` is read as the file Windows opens before matching (`windows_spelling`, `windows_segment`, `command_base`; TS `captureWindowsSpelling`/`captureResolve`/`captureBase`): Git Bash/MSYS2/Cygwin `/c/…` and `/cygdrive/c/…`, a drive-less rooted path on the cwd's drive, the `\\?\`/`\\.\`/`\??\` and `UNC` prefixes, the local administrative share (`\\localhost\C$`), and per-segment alternate-data-stream suffixes and trailing dots/spaces, any other device path unusable (metadata-only for a file tool); the harness-spool check is linear in the path and charged to the match budget, past it fail-closed (`output_spool`, TS `captureOutputSpool`); a shell command over `MAX_SHELL_COMMAND_CHARS` (1 MiB) is metadata-only and its marker lookup unprovable (`ShellCommand::oversized`, TS `captureCommandOversized`); Hermes `execute_code` is metadata-only under an active policy (`INLINE_CODE_TOOL_NAMES`); the TS file/search/non-file/inline-code/output-reader tool lists and the command limit are generated from the native constants (`FILE_TOOL_NAMES` and siblings, spliced by `ts_capture_policy_v1`), and the TS marker reader honours every TOML spelling of the capture table toml_edit does (dotted `capture.ignore_paths`, quoted or spaced `[capture]` headers) and fails closed on the shapes it rejects (inline table, `[[capture]]`, `[capture.x]`, a second definition) (`captureTomlKey` and the `captureConfigAt` section loop); the TS glob walk reads a directory one entry at a time with `opendirSync`, stopping at the entry bound (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; `windows_spelling_fixture_vectors` (shared `capture-policy.json` `windows` drop vectors for every spelling above, file tool and shell, with other-drive, other-share, longer-name and pipe controls, and `windows_posix_controls` proving a POSIX session keeps `/c/…`, trailing-dot and colon names), `tool_family_fixture_vectors` (shared `tool_families`, every native name per family), new `decisions` vectors (`execute_code` metadata-only, `read_file`/`patch`/`fs_read` operations drop, `write_to_file`/`browser_navigate` keep), `output_spool_work_is_linear_and_budgeted` (a 2,040-wildcard-segment path stays under a linear work bound; 32 such paths fail closed; one long or 32 short paths keep), `an_oversized_shell_command_is_unprovable` (one character over the limit is metadata-only and unlooked-up, at the limit keeps, argv summed, inactive untouched), `inline_code_tools_are_unprovable_under_a_policy`, `hook_capture::capture_section_spellings_match_toml_semantics` (shared `marker_spellings`), and the Node evidence test running all of these vectors against the generated TypeScript plus its entry-bound read count for the directory walk; each fails with its rule reverted (Windows reading off, spool memo dropped or budget failing open, length check off, inline-code rule off, a name dropped from the list, TS dotted key or inline-table rule reverted, TS walk back on `readdirSync`) | 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; in a Windows session `/c/x` is read only as Git Bash reads it, so a native tool's `C:\c\x` reading is not matched, and the TS marker reader does not validate TOML outside the capture table (a syntax error elsewhere invalidates the policy only natively); a `**/` matches one or more directories, never zero (documented in `marker-file.md`) |
| 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 |