Skip to content

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

Rust

fix(capture): read nested shell words and fail closed on more syntax

AkitaOnRails2ab50cd77758
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc040f45..6c6734bf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,7 +29,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`write_bash`) and shell commands using brace expansion or a bracket class
are now metadata-only, since the matcher cannot prove they miss an ignored
path; upgrade the server before the clients, because an older server drops
- those events. This applies to the native hook, the server, and the
+ those events. A script quoted inside a string-form shell command (an
+ `sh -c` argument, a command substitution in double quotes) is now read like
+ the rest of the command line, the path in a git object name (`REV:path`) is
+ checked, Antigravity's `run_command` resolves its arguments from its `Cwd`,
+ and ANSI-C strings and backslash-escaped letters are read the way the shell
+ reads them. Inline interpreter code (`python3 -c`, `node -e` and similar)
+ and further glob syntax the matcher does not evaluate (zsh glob groups,
+ extglobs, encoded escapes) are now metadata-only under an active policy.
+ This applies to the native hook, the server, and the
generated TypeScript integrations. (GHSA-gcpc-88hm-3xqr)
- Fixed a web page open in the operator's browser being able to act on an
unauthenticated server (the loopback default, no token), such as claiming a
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index b446df01..4a1697f4 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -238,12 +238,13 @@ const CAPTURE_MAX_PATTERN_CHARS = 1024;
const CAPTURE_MAX_PATH_CHARS = 4096;
const CAPTURE_MAX_CANDIDATES = 32;
const CAPTURE_MAX_WORK = 1000000;
+const CAPTURE_MAX_SHELL_NESTING = 4;
const CAPTURE_MAX_CALL_ID_CHARS = 128;
type CaptureDisposition = "keep" | "drop" | "metadata-only";
type CaptureProtocol = { version: 1; disposition: CaptureDisposition; policy_state: "inactive" | "active" | "invalid"; tool_family: "file" | "search-list" | "non-file" | "unknown"; path_count: number; extraction_state: "not-applicable" | "extracted" | "missing-or-malformed" | "unsupported-schema" };
-type CaptureConfig = { state: "inactive" | "active" | "invalid"; patterns: { path: string; windows: boolean; directory?: string; prefix: string }[]; base: string; windowsHost: boolean };
+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; }
// `windowsHost` is omitted for self-determining callers (the cwd/marker base,
@@ -315,7 +316,7 @@ function captureConfig(cwd: string | undefined): CaptureConfig {
});
if (patterns.some((p) => !p)) return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
return patterns.length
- ? { state: "active", patterns: patterns as CaptureConfig["patterns"], base: candidateBase, windowsHost }
+ ? { state: "active", patterns: patterns as CaptureConfig["patterns"], base: candidateBase, windowsHost, root: markerBase }
: { state: "inactive", patterns: [], base: candidateBase, windowsHost };
} catch (_e) {
return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
@@ -333,16 +334,31 @@ function captureGlobReaches(glob: string, prefix: string, insensitive: boolean,
// (`bash -lc "<script>"`); joining elements would re-split paths with spaces.
// Elements over 256 chars are scripts, so only their tokens count.
function captureShellCommand(args: Record<string, unknown> | undefined): string | string[] | undefined { if (!args || typeof args !== "object" || Array.isArray(args)) return undefined; const value = "command" in args ? args.command : ("cmd" in args ? args.cmd : args.CommandLine); if (typeof value === "string") return value; if (Array.isArray(value) && value.every((x) => typeof x === "string")) return value as string[]; return undefined; }
-// Split only when a policy is active: this runs for every tool event.
-function captureShellWordList(command: string | string[]): string[] { if (typeof command === "string") return captureShellWords(command); return command.flatMap((item) => { const tokens = captureShellWords(item); return tokens.length === 1 && tokens[0] === item || [...item].length > 256 ? tokens : [item, ...tokens]; }); }
-function captureShellWords(command: string): string[] { const special = (c: string) => /\s/.test(c) || "|&;<>()".includes(c); const chars = [...command]; const words: string[] = []; let word = ""; let inWord = false; let quote = ""; for (let i = 0; i < chars.length; i++) { const c = chars[i]; const next = chars[i + 1]; if (quote) { if (c === quote) quote = ""; else if (quote === '"' && c === "\\" && (next === '"' || next === "\\")) { word += next; i++; } else word += c; } else if (c === "'" || c === '"') { quote = c; inWord = true; } else if (c === "\\" && next !== undefined && (special(next) || next === "'" || next === '"' || next === "\\")) { word += next; i++; inWord = true; } else if (special(c)) { if (inWord) words.push(word); word = ""; inWord = false; } else { word += c; inWord = true; } } if (inWord) words.push(word); return words; }
-// Whether an unquoted word holds a brace expansion (`{a,b}`, `{1..3}`) or a bracket class (`[ab]`), which lexical matching does not evaluate; mirrors `has_unevaluated_expansion`.
-function captureUnevaluatedExpansion(command: string | string[]): boolean { if (typeof command !== "string") return command.some((item) => captureUnevaluatedExpansion(item)); const chars = [...command]; let quote = ""; let previous = ""; let parameter = false; let brace: boolean | undefined; let klass: number | undefined; for (let i = 0; i < chars.length; i++) { const c = chars[i]; if (quote) { if (c === quote) quote = ""; else if (quote === '"' && c === "\\") i++; if (klass !== undefined) klass++; previous = ""; continue; } if (c === "'" || c === '"') quote = c; else if (c === "\\") { i++; if (klass !== undefined) klass++; previous = ""; continue; } else if (/\s/.test(c) || "|&;<>()".includes(c)) { parameter = false; brace = undefined; klass = undefined; } else if (c === "{" && previous === "$") parameter = true; else if (c === "}" && parameter) parameter = false; else if (parameter) { /* parameter expansion */ } else if (c === "{") brace = false; else if (c === "," && brace !== undefined) brace = true; else if (c === "." && brace !== undefined && previous === ".") brace = true; else if (c === "}" && brace !== undefined) { if (brace) return true; brace = undefined; } else if (c === "[" && klass === undefined) klass = 0; else if (c === "]" && klass !== undefined) { if (klass > 0) return true; klass = undefined; } else if (klass !== undefined) klass++; previous = c; } return false; }
-function captureShellArguments(word: string): string[] { const flag = word.startsWith("-"); const out = flag ? [] : [word]; const eq = word.indexOf("="); const colon = flag && eq < 0 ? word.indexOf(":") : -1; if (eq >= 0) out.push(word.slice(eq + 1)); else if (colon >= 0) out.push(word.slice(colon + 1)); return out.filter((argument) => argument.trim() !== ""); }
+// Split only when a policy is active: this runs for every tool event. Every
+// word, and again every word inside a word that holds more than one
+// (`bash -c 'cat x'`, `"$(cat x)"`), down to CAPTURE_MAX_SHELL_NESTING levels;
+// a script nested deeper is opaque. Mirrors `ShellCommand::split`.
+function captureShellSplit(command: string | string[]): { words: string[]; opaque: boolean } { const split = { words: [] as string[], opaque: false }; if (typeof command === "string") { split.opaque = captureUnevaluatedExpansion(command); captureNestedWords(captureShellWords(command), CAPTURE_MAX_SHELL_NESTING, split); return split; } split.opaque = command.some((item) => captureUnevaluatedExpansion(item)) || captureInlineCode(command); for (const item of command) { const tokens = captureShellWords(item); if (tokens.length === 1 && tokens[0] === item) { capturePushWord(item, split); continue; } if ([...item].length <= 256) split.words.push(item); captureNestedWords(tokens, CAPTURE_MAX_SHELL_NESTING - 1, split); } return split; }
+// Only a script a shell runs expands braces and classes; a quoted message or pattern does not.
+function captureNestedWords(words: string[], depth: number, split: { words: string[]; opaque: boolean }): void { if (captureInlineCode(words)) split.opaque = true; words.forEach((word, index) => { capturePushWord(word, split); const tokens = captureShellWords(word); if (tokens.length === 1 && tokens[0] === word) return; if (depth === 0) { split.opaque = true; return; } if ((word.includes("$(") || word.includes("`") || captureShellScript(words, index)) && captureUnevaluatedExpansion(word)) split.opaque = true; captureNestedWords(tokens, depth - 1, split); }); }
+// Also adds the POSIX reading of a word with `\o` escapes, which the shell reads as `o`.
+function capturePushWord(word: string, split: { words: string[] }): void { split.words.push(word); if (!word.includes("\\")) return; const chars = [...word]; let plain = ""; for (let i = 0; i < chars.length; i++) { if (chars[i] === "\\") { i++; if (i < chars.length) plain += chars[i]; } else plain += chars[i]; } if (plain !== word) split.words.push(plain); }
+function captureCommandName(word: string): string { const name = (word.split(/[\/\\]/).pop() ?? word).replace(/[A-Z]/g, (c) => c.toLowerCase()); return name.endsWith(".exe") ? name.slice(0, -4) : name; }
+function captureShellScript(words: string[], index: number): boolean { let flagged = false; for (let i = index - 1; i >= 0; i--) { const word = words[i]; if (word.startsWith("-")) { flagged ||= !word.startsWith("--") && word.slice(1).includes("c"); continue; } const name = captureCommandName(word); return (flagged && ["sh","bash","zsh","dash","ksh","mksh","ash","yash","fish"].includes(name)) || (i + 1 === index && name === "eval"); } return false; }
+// Inline interpreter code (`python3 -c`, `node -e`, `ruby -e`, `perl -e`, `php -r`, `deno eval`) builds paths at run time; mirrors `runs_inline_code`.
+function captureInlineCode(words: string[]): boolean { return words.some((word, index) => { const name = captureCommandName(word); const versioned = (prefix: string) => name.startsWith(prefix) && /^[0-9.]*$/.test(name.slice(prefix.length)); if (name === "deno") return words[index + 1] === "eval"; const letters = versioned("python") || versioned("pypy") || name === "py" ? "c" : versioned("perl") ? "eE" : versioned("ruby") ? "e" : ["node","nodejs","bun"].includes(name) ? "ep" : versioned("php") ? "r" : undefined; if (!letters) return false; for (const flag of words.slice(index + 1)) { if (!flag.startsWith("-")) break; if (["--eval","--print"].includes(flag) || flag.startsWith("--eval=") || flag.startsWith("--print=") || (!flag.startsWith("--") && [...flag.slice(1)].some((c) => letters.includes(c)))) return true; } return false; }); }
+function captureShellWords(command: string): string[] { const special = (c: string) => /\s/.test(c) || "|&;<>()`".includes(c); const chars = [...command]; const words: string[] = []; let word = ""; let inWord = false; let quote = ""; for (let i = 0; i < chars.length; i++) { const c = chars[i]; const next = chars[i + 1]; if (quote === "$") { if (c === "'") quote = ""; else if (c === "\\" && next !== undefined) { word += captureAnsiEscape(next) ?? c + next; i++; } else word += c; } else if (quote) { if (c === quote) quote = ""; else if (quote === '"' && c === "\\" && (next === '"' || next === "\\")) { word += next; i++; } else word += c; } else if (c === "'" || c === '"') { quote = c; inWord = true; } else if (c === "$" && (next === "'" || next === '"')) { quote = next === "'" ? "$" : '"'; i++; inWord = true; } else if (c === "\\" && next !== undefined && (special(next) || next === "'" || next === '"' || next === "\\")) { word += next; i++; inWord = true; } else if (special(c)) { if (inWord) words.push(word); word = ""; inWord = false; } else { word += c; inWord = true; } } if (inWord) words.push(word); return words; }
+// `$'…'` escapes; numeric and control escapes stay as written. Mirrors `ansi_c_escape`.
+function captureAnsiEscape(escape: string): string | undefined { const decoded: Record<string, string> = { a: "\u0007", b: "\b", e: "\u001b", E: "\u001b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v", "\\": "\\", "'": "'", '"': '"', "?": "?" }; return Object.prototype.hasOwnProperty.call(decoded, escape) ? decoded[escape] : undefined; }
+// Whether an unquoted word holds syntax lexical matching does not evaluate: a brace expansion (`{a,b}`, `{1..3}`), a bracket class (`[ab]`, `[]a]`), a zsh glob group or extglob (`docs/(a|b)`, `(a|b)/x`), or an ANSI-C numeric/control escape; mirrors `has_unevaluated_expansion`.
+function captureUnevaluatedExpansion(command: string): boolean { const operator = (c: string) => "|&;<>()`".includes(c); const isWord = (c: string | undefined) => c !== undefined && !/\s/.test(c) && !operator(c); const chars = [...command]; let quote = ""; let previous = ""; let inWord = false; let parameter = false; let brace: boolean | undefined; let klass: number | undefined; const groups: boolean[] = []; for (let i = 0; i < chars.length; i++) { const c = chars[i]; if (quote) { if (((quote === "$" || quote === "'") && c === "'") || (quote === '"' && c === '"')) quote = ""; else if (quote === "$" && c === "\\") { const escape = chars[++i]; if (escape !== undefined && /^[xuUc0-7]$/.test(escape)) return true; } else if (quote === '"' && c === "\\") i++; if (klass !== undefined) klass++; previous = ""; inWord = true; continue; } if (c === "'" && previous === "$") quote = "$"; else if (c === "'" || c === '"') quote = c; else if (c === "\\") { i++; if (klass !== undefined) klass++; previous = ""; inWord = true; continue; } else if (c === "(") { if (inWord && previous !== "$" && previous !== "=") return true; groups.push(!inWord && previous !== "<" && previous !== ">"); parameter = false; brace = undefined; klass = undefined; inWord = false; } else if (c === ")") { if (groups.pop() === true && isWord(chars[i + 1])) return true; parameter = false; brace = undefined; klass = undefined; inWord = false; } else if (c === "|" && groups[groups.length - 1] === true && inWord && isWord(chars[i + 1])) return true; else if (/\s/.test(c) || operator(c)) { parameter = false; brace = undefined; klass = undefined; inWord = false; } else if (c === "{" && previous === "$") parameter = true; else if (c === "}" && parameter) parameter = false; else if (parameter) { /* parameter expansion */ } else if (c === "{") brace = false; else if (c === "," && brace !== undefined) brace = true; else if (c === "." && brace !== undefined && previous === ".") brace = true; else if (c === "}" && brace !== undefined) { if (brace) return true; brace = undefined; } else if (c === "[" && klass === undefined) klass = 0; else if (c === "]" && klass === 0) klass = 1; else if (c === "]" && klass !== undefined) return true; else if (klass !== undefined) klass++; if (!/\s/.test(c) && !operator(c)) inWord = true; previous = c; } return false; }
+// Also the path of a git `REV:path` object name, flagged because git resolves it from the repository root; mirrors `shell_arguments`.
+function captureShellArguments(word: string): [string, boolean][] { const flag = word.startsWith("-"); const out: [string, boolean][] = flag ? [] : [[word, false]]; const eq = word.indexOf("="); const colon = flag && eq < 0 ? word.indexOf(":") : -1; if (eq >= 0) out.push([word.slice(eq + 1), false]); else if (colon >= 0) out.push([word.slice(colon + 1), false]); const object = captureGitObjectPath(word); if (object !== undefined) out.push([object, true]); return out.filter(([argument]) => argument.trim() !== ""); }
+function captureGitObjectPath(word: string): string | undefined { if (word.startsWith("-")) return undefined; const colon = word.indexOf(":"); if (colon < 0) return undefined; const revision = word.slice(0, colon); let path = word.slice(colon + 1); if (!revision && /^[0-3]:/.test(path)) path = path.slice(2); return !/^[A-Za-z]$/.test(revision) && /^[A-Za-z0-9._\/~^@{}-]*$/.test(revision) && !path.startsWith("//") ? path : undefined; }
// 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(command: string | string[], config: CaptureConfig, workdir?: string): boolean | undefined { const budget = { work: 0 }; const home = homedir(); const base = workdir === undefined ? config.base : /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(workdir) ? workdir : config.base && captureJoin(config.base, workdir); for (const word of captureShellWordList(command)) for (const argument of captureShellArguments(word)) { const expanded = argument.startsWith("~/") ? captureJoin(home, argument.slice(2)) : argument; if ([...expanded].length > CAPTURE_MAX_PATH_CHARS) continue; const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(expanded); if (!absolute && !base) continue; const candidate = captureNormalize(absolute ? expanded : captureJoin(base, expanded), config.windowsHost); if (!candidate) continue; const match = captureMatchCandidate(candidate, false, config, budget); if (match !== false) return match; } return false; }
+function captureMatchCommand(words: string[], config: CaptureConfig, workdir?: string): boolean | undefined { const budget = { work: 0 }; const home = homedir(); const base = workdir === undefined ? config.base : /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(workdir) ? workdir : config.base && captureJoin(config.base, workdir); for (const word of words) for (const [argument, fromRoot] of captureShellArguments(word)) { const expanded = argument.startsWith("~/") ? captureJoin(home, argument.slice(2)) : argument; if ([...expanded].length > CAPTURE_MAX_PATH_CHARS) continue; const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(expanded); for (const root of fromRoot && !absolute && config.root ? [base, config.root] : [base]) { if (!absolute && !root) continue; const candidate = captureNormalize(absolute ? expanded : captureJoin(root, expanded), config.windowsHost); if (!candidate) continue; const match = captureMatchCandidate(candidate, false, config, budget); if (match !== false) return match; } } return false; }
// Gemini CLI `read_many_files` globs expand case-insensitively with `**`
// recursing to any depth: a literal path matches like a file tool's, a glob
// drops when it could expand into an ignored path, and glob syntax the matcher
@@ -366,7 +382,7 @@ function captureOwnedExternally(): boolean { const owner = typeof process === "u
// home the walk stops at home, outside it continues past the checkout root to an
// organisation-level marker; an unreadable marker counts as a selection.
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); } }
-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 config = captureConfig(cwd); const tool = captureTool(payload); let disposition: CaptureDisposition = "keep"; if (config.state === "invalid" && (tool.family === "file" || tool.shell || tool.reader)) disposition = "metadata-only"; else if (config.state === "active" && tool.reader) disposition = "metadata-only"; else if (config.state === "active" && tool.family === "search-list") disposition = "drop"; else if (config.state === "active" && tool.family === "file") { if (!tool.paths) disposition = "metadata-only"; else { const candidates = tool.paths.map((p) => captureNormalize(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p), config.windowsHost)); if (candidates.some((p) => !p)) disposition = "metadata-only"; else if (tool.globs) { const match = captureMatchGlobs(tool.paths, candidates as { path: string; windows: boolean }[], config); if (match !== false) disposition = match ? "drop" : "metadata-only"; } else { const budget = { work: 0 }; captureMatch: for (const candidate of candidates as { path: string; windows: boolean }[]) for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; if (pattern.directory && captureGlob(pattern.directory, candidate.path, pattern.windows, budget)) { disposition = "drop"; break captureMatch; } const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match === undefined) { disposition = "metadata-only"; break; } if (match) { disposition = "drop"; break captureMatch; } } } } } else if (config.state === "active" && tool.family === "non-file" && tool.command !== undefined) { if (captureMatchCommand(tool.command, config, tool.workdir) !== false) disposition = "drop"; else if (captureUnevaluatedExpansion(tool.command)) disposition = "metadata-only"; } if (config.state === "inactive") return { disposition, payload }; const protocol: CaptureProtocol = { version: CAPTURE_POLICY_V1, disposition, policy_state: config.state, tool_family: tool.family, path_count: tool.paths?.length ?? 0, extraction_state: tool.extraction }; if (disposition === "metadata-only") { const session = payload.sessionID ?? payload.sessionId ?? payload.session_id; const routing = typeof payload.cwd === "string" ? payload.cwd : cwd; return { disposition, protocol, payload: { ...(typeof session === "string" ? { session_id: session } : {}), ...(typeof routing === "string" ? { cwd: routing } : {}), tool_family: tool.family, tool_name: tool.family, ...(tool.callID ? { tool_call_id: tool.callID } : {}), _ai_memory_capture: protocol } }; } if (disposition === "keep") return { disposition, protocol, payload: { ...payload, _ai_memory_capture: protocol } }; return { disposition, protocol, payload }; }
+function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { if (captureOwnedExternally()) return { disposition: "drop", payload }; if (captureServerRouted(cwd)) return { disposition: "drop", payload }; const markerPresent = !!findMarker(cwd); if (CAPTURE_MODE === "allowlist" && !markerPresent) return { disposition: "drop", payload }; const config = captureConfig(cwd); const tool = captureTool(payload); let disposition: CaptureDisposition = "keep"; if (config.state === "invalid" && (tool.family === "file" || tool.shell || tool.reader)) disposition = "metadata-only"; else if (config.state === "active" && tool.reader) disposition = "metadata-only"; else if (config.state === "active" && tool.family === "search-list") disposition = "drop"; else if (config.state === "active" && tool.family === "file") { if (!tool.paths) disposition = "metadata-only"; else { const candidates = tool.paths.map((p) => captureNormalize(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p), config.windowsHost)); if (candidates.some((p) => !p)) disposition = "metadata-only"; else if (tool.globs) { const match = captureMatchGlobs(tool.paths, candidates as { path: string; windows: boolean }[], config); if (match !== false) disposition = match ? "drop" : "metadata-only"; } else { const budget = { work: 0 }; captureMatch: for (const candidate of candidates as { path: string; windows: boolean }[]) for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; if (pattern.directory && captureGlob(pattern.directory, candidate.path, pattern.windows, budget)) { disposition = "drop"; break captureMatch; } const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match === undefined) { disposition = "metadata-only"; break; } if (match) { disposition = "drop"; break captureMatch; } } } } } else if (config.state === "active" && tool.family === "non-file" && tool.command !== undefined) { const split = captureShellSplit(tool.command); if (captureMatchCommand(split.words, config, tool.workdir) !== false) disposition = "drop"; else if (split.opaque) disposition = "metadata-only"; } 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)
}
diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rs
index 4410f849..e2f3d234 100644
--- a/crates/ai-memory-hooks/src/capture_policy.rs
+++ b/crates/ai-memory-hooks/src/capture_policy.rs
@@ -435,6 +435,9 @@ pub struct CapturePolicy {
state: PolicyState,
patterns: Vec<CompiledPattern>,
home: Option<String>,
+ /// The marker directory, where git resolves a `REV:path` object name
+ /// when the repository root holds the marker.
+ root: Option<String>,
}
#[derive(Clone, Debug)]
@@ -512,6 +515,7 @@ impl CapturePolicy {
state: PolicyState::Invalid,
patterns: Vec::new(),
home: None,
+ root: None,
};
}
CaptureSource::Parsed(config) => config,
@@ -525,11 +529,13 @@ impl CapturePolicy {
state: PolicyState::Active,
patterns,
home: home_dir.and_then(|dir| normalize_root(dir).ok()),
+ root: normalize_root(marker_dir).ok(),
},
Err(_) => Self {
state: PolicyState::Invalid,
patterns: Vec::new(),
home: None,
+ root: None,
},
}
}
@@ -538,6 +544,7 @@ impl CapturePolicy {
state: PolicyState::Inactive,
patterns: Vec::new(),
home: None,
+ root: None,
}
}
/// Evaluates every policy state using only direct fixture-backed schemas.
@@ -609,12 +616,14 @@ impl CapturePolicy {
Some(dir) if is_absolute(cwd) => join(cwd, dir),
_ => cwd.to_owned(),
};
- self.match_command(&command.words(), &base)
- .map(|matched| (matched, command.has_unevaluated_expansion()))
+ let split = command.split();
+ self.match_command(&split.words, &base)
+ .map(|matched| (matched, split.opaque))
}) {
Some(Ok((true, _)) | Err(())) => (CaptureDisposition::Drop, extracted.state),
- // Brace expansion and bracket classes are not evaluated,
- // so such a word proves nothing either way.
+ // Syntax the matcher does not evaluate (brace expansion,
+ // bracket classes, zsh groups, encoded escapes) and inline
+ // interpreter code prove nothing either way.
Some(Ok((false, true))) => (CaptureDisposition::MetadataOnly, extracted.state),
Some(Ok((false, false))) | None => (CaptureDisposition::Keep, extracted.state),
},
@@ -673,17 +682,24 @@ impl CapturePolicy {
fn match_command(&self, words: &[String], cwd: &str) -> Result<bool, ()> {
let mut work = 0_usize;
for word in words {
- for argument in shell_arguments(word) {
+ for (argument, from_root) in shell_arguments(word) {
let expanded = match (argument.strip_prefix("~/"), self.home.as_deref()) {
(Some(rest), Some(home)) => join(home, rest),
_ => argument.to_owned(),
};
- // Not a usable path (drive-relative, oversized, bad cwd).
- let Some(candidate) = normalize_candidate(&expanded, cwd) else {
- continue;
- };
- if self.match_pattern_candidate(&candidate, false, &mut work)? {
- return Ok(true);
+ // Git reads `REV:path` from the repository root, which only
+ // the marker directory approximates; try the cwd as well.
+ let root = (from_root && !is_absolute(&expanded))
+ .then_some(self.root.as_deref())
+ .flatten();
+ for base in std::iter::once(cwd).chain(root) {
+ // Not a usable path (drive-relative, oversized, bad cwd).
+ let Some(candidate) = normalize_candidate(&expanded, base) else {
+ continue;
+ };
+ if self.match_pattern_candidate(&candidate, false, &mut work)? {
+ return Ok(true);
+ }
}
}
}
@@ -879,16 +895,19 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted<'_> {
.flatten();
// OpenCode `bash`, OpenClaw `exec` and Codex `shell` run in `workdir`
// when given, Gemini CLI `run_shell_command` in `dir_path` (`directory`
- // before it was renamed), so relative arguments resolve from there.
+ // before it was renamed), and Antigravity `run_command` in `Cwd`, so
+ // relative arguments resolve from there.
let shell = family == ToolFamily::NonFile && !name.eq_ignore_ascii_case("web_search");
+ let workdir_keys: &[&str] = if agent == AgentKind::AntigravityCli {
+ &["Cwd"]
+ } else {
+ &["workdir", "dir_path", "directory"]
+ };
let workdir = command
.as_ref()
.and_then(|_| {
let args = args?;
- ["workdir", "dir_path", "directory"]
- .iter()
- .find_map(|key| args.get(*key))?
- .as_str()
+ workdir_keys.iter().find_map(|key| args.get(*key))?.as_str()
})
.filter(|dir| !dir.trim().is_empty())
.map(str::to_owned);
@@ -1174,77 +1193,251 @@ enum ShellCommand<'a> {
Argv(Vec<&'a str>),
}
+/// A shell tool's words, plus whether any of them holds syntax the lexical
+/// matcher does not evaluate, which makes a miss unprovable.
+#[derive(Default)]
+struct ShellWords {
+ words: Vec<String>,
+ opaque: bool,
+}
+
impl ShellCommand<'_> {
+ #[cfg(test)]
+ fn words(&self) -> Vec<String> {
+ self.split().words
+ }
+
+ /// Every word, and again every word inside a word that holds more than
+ /// one (`bash -c 'cat x'`, `"$(cat x)"`), down to [`MAX_SHELL_NESTING`]
+ /// levels. A script nested deeper is opaque.
+ ///
/// An argument vector (Codex exec) keeps each element as one word
/// (`private notes/x.md`) and also tokenizes it, so a `bash -lc "<script>"`
/// element is read like any script. Joining the elements instead would
/// re-split paths with spaces and let one stray quote swallow the rest.
- fn words(&self) -> Vec<String> {
+ fn split(&self) -> ShellWords {
+ let mut split = ShellWords::default();
match self {
- Self::Line(command) => shell_words(command),
+ Self::Line(command) => {
+ split.opaque = has_unevaluated_expansion(command);
+ push_nested_words(&shell_words(command), MAX_SHELL_NESTING, &mut split);
+ }
Self::Argv(items) => {
- let mut words = Vec::new();
+ // Each element is scanned as a script too, the same
+ // over-approximation its words make.
+ split.opaque = items.iter().any(|item| has_unevaluated_expansion(item))
+ || runs_inline_code(items);
for item in items {
let tokens = shell_words(item);
+ if tokens.len() == 1 && tokens[0] == *item {
+ push_word(item, &mut split);
+ continue;
+ }
// Kept whole, a long script would exhaust the match budget.
- if (tokens.len() != 1 || tokens[0] != *item)
- && item.chars().count() <= MAX_ARGV_PATH_CHARS
- {
- words.push((*item).to_owned());
+ if item.chars().count() <= MAX_ARGV_PATH_CHARS {
+ split.words.push((*item).to_owned());
}
- words.extend(tokens);
+ push_nested_words(&tokens, MAX_SHELL_NESTING - 1, &mut split);
}
- words
}
}
+ split
}
+}
- /// Whether any word uses brace expansion or a bracket class, which the
- /// lexical matcher does not evaluate. Each argv element is scanned as a
- /// script too, the same over-approximation [`Self::words`] makes.
- fn has_unevaluated_expansion(&self) -> bool {
- match self {
- Self::Line(command) => has_unevaluated_expansion(command),
- Self::Argv(items) => items.iter().any(|item| has_unevaluated_expansion(item)),
+/// How many quoting levels a script inside a word is re-split.
+const MAX_SHELL_NESTING: usize = 4;
+
+fn push_nested_words(words: &[String], depth: usize, split: &mut ShellWords) {
+ if runs_inline_code(words) {
+ split.opaque = true;
+ }
+ for (index, word) in words.iter().enumerate() {
+ push_word(word, split);
+ let tokens = shell_words(word);
+ if tokens.len() == 1 && tokens[0] == *word {
+ continue;
}
+ let Some(depth) = depth.checked_sub(1) else {
+ split.opaque = true;
+ continue;
+ };
+ // Only a script a shell runs expands its braces and classes; a
+ // quoted message or pattern (`git log --format='%h {a,b}'`) does not.
+ if (word.contains("$(") || word.contains('`') || is_shell_script(words, index))
+ && has_unevaluated_expansion(word)
+ {
+ split.opaque = true;
+ }
+ push_nested_words(&tokens, depth, split);
}
}
-/// Whether an unquoted word of `command` holds a brace expansion (`{a,b}`,
-/// `{1..3}`) or a bracket class (`[ab]`). Quoted or escaped braces and
-/// brackets are literal, `${…}` is a parameter expansion, and `{}` or a
-/// lone `[` (`find -exec … {}`, `[ -f x ]`) expands nothing.
+/// Adds a word, and its POSIX reading when it differs: outside quotes a
+/// shell drops the backslash of `\o`, but [`shell_words`] keeps it so a
+/// Windows path keeps its separators.
+fn push_word(word: &str, split: &mut ShellWords) {
+ split.words.push(word.to_owned());
+ if word.contains('\\') {
+ let mut plain = String::with_capacity(word.len());
+ let mut chars = word.chars();
+ while let Some(c) = chars.next() {
+ if c == '\\' {
+ plain.extend(chars.next());
+ } else {
+ plain.push(c);
+ }
+ }
+ if plain != word {
+ split.words.push(plain);
+ }
+ }
+}
+
+/// A command word's program name: its last path segment, lowercased,
+/// without `.exe`.
+fn command_name(word: &str) -> String {
+ let name = word.rsplit(['/', '\\']).next().unwrap_or(word);
+ let name = name.to_ascii_lowercase();
+ if let Some(stem) = name.strip_suffix(".exe") {
+ return stem.to_owned();
+ }
+ name
+}
+
+/// Whether `words[index]` is a script a shell runs: the argument after
+/// `sh -c` (any flag cluster with `c`, as in `bash -lc`) or after `eval`.
+fn is_shell_script<S: AsRef<str>>(words: &[S], index: usize) -> bool {
+ let mut script_flag = false;
+ for previous in (0..index).rev() {
+ let word = words[previous].as_ref();
+ if let Some(flag) = word.strip_prefix('-') {
+ script_flag |= !flag.starts_with('-') && flag.contains('c');
+ continue;
+ }
+ let name = command_name(word);
+ return (script_flag
+ && matches!(
+ name.as_str(),
+ "sh" | "bash" | "zsh" | "dash" | "ksh" | "mksh" | "ash" | "yash" | "fish"
+ ))
+ || (previous + 1 == index && name == "eval");
+ }
+ false
+}
+
+/// Whether the words run inline interpreter code (`python3 -c`, `node -e`,
+/// `ruby -e`, `perl -e`, `php -r`, `deno eval`). Code builds paths at run
+/// time (`'docs/' + name`), so no lexical match can rule an ignored path out.
+fn runs_inline_code<S: AsRef<str>>(words: &[S]) -> bool {
+ (0..words.len()).any(|index| {
+ let name = command_name(words[index].as_ref());
+ let versioned = |prefix: &str| {
+ name.strip_prefix(prefix)
+ .is_some_and(|rest| rest.chars().all(|c| c.is_ascii_digit() || c == '.'))
+ };
+ let letters: &[char] = if versioned("python") || versioned("pypy") || name == "py" {
+ &['c']
+ } else if versioned("perl") {
+ &['e', 'E']
+ } else if versioned("ruby") {
+ &['e']
+ } else if matches!(name.as_str(), "node" | "nodejs" | "bun") {
+ &['e', 'p']
+ } else if versioned("php") {
+ &['r']
+ } else if name == "deno" {
+ return words
+ .get(index + 1)
+ .is_some_and(|next| next.as_ref() == "eval");
+ } else {
+ return false;
+ };
+ words[index + 1..]
+ .iter()
+ .map(AsRef::as_ref)
+ .take_while(|word| word.starts_with('-'))
+ .any(|flag| {
+ matches!(flag, "--eval" | "--print")
+ || flag.starts_with("--eval=")
+ || flag.starts_with("--print=")
+ || (!flag.starts_with("--") && flag[1..].contains(letters))
+ })
+ })
+}
+
+/// Whether an unquoted word of `command` holds syntax the lexical matcher
+/// does not evaluate: a brace expansion (`{a,b}`, `{1..3}`), a bracket class
+/// (`[ab]`, `[]a]`), a zsh glob group or extglob (`docs/(a|b)`, `(a|b)/x`,
+/// `@(x)`), or an ANSI-C string with a numeric or control escape
+/// (`$'\x64'`). Quoted or escaped braces and brackets are literal, `${…}` is
+/// a parameter expansion, `$(…)`, `<(…)` and a standalone `( … )` subshell
+/// are not globs, and `{}` or a lone `[` (`find -exec … {}`, `[ -f x ]`)
+/// expands nothing.
fn has_unevaluated_expansion(command: &str) -> bool {
- let is_operator = |c: char| matches!(c, '|' | '&' | ';' | '<' | '>' | '(' | ')');
+ let is_operator = |c: char| matches!(c, '|' | '&' | ';' | '<' | '>' | '(' | ')' | '`');
+ let is_word = |c: Option<&char>| c.is_some_and(|c| !c.is_whitespace() && !is_operator(*c));
let mut quote = None;
let mut previous = None;
+ let mut in_word = false;
let mut parameter = false;
let mut brace = None::<bool>;
let mut class = None::<usize>;
- let mut chars = command.chars();
+ // One entry per open unquoted `(`: whether it starts a word, where zsh
+ // reads a following glob (`(a|b)/x`) instead of a subshell.
+ let mut groups = Vec::new();
+ let mut chars = command.chars().peekable();
while let Some(c) = chars.next() {
if let Some(open) = quote {
- if c == open {
- quote = None;
- } else if open == '"' && c == '\\' {
- chars.next();
+ match (open, c) {
+ ('$' | '\'', '\'') | ('"', '"') => quote = None,
+ // The guard consumes the escaped character either way.
+ ('$', '\\')
+ if chars.next().is_some_and(|escape| {
+ matches!(escape, 'x' | 'u' | 'U' | 'c' | '0'..='7')
+ }) =>
+ {
+ return true;
+ }
+ ('"', '\\') => {
+ chars.next();
+ }
+ _ => {}
}
class = class.map(|len| len + 1);
previous = None;
+ in_word = true;
continue;
}
match c {
+ // `$'…'` is an ANSI-C string, tracked as its own quote.
+ '\'' if previous == Some('$') => quote = Some('$'),
'\'' | '"' => quote = Some(c),
'\\' => {
chars.next();
class = class.map(|len| len + 1);
previous = None;
+ in_word = true;
continue;
}
+ '(' => {
+ if in_word && !matches!(previous, Some('$' | '=')) {
+ return true;
+ }
+ groups.push(!in_word && !matches!(previous, Some('<' | '>')));
+ (parameter, brace, class, in_word) = (false, None, None, false);
+ }
+ ')' => {
+ if groups.pop() == Some(true) && is_word(chars.peek()) {
+ return true;
+ }
+ (parameter, brace, class, in_word) = (false, None, None, false);
+ }
+ '|' if groups.last() == Some(&true) && in_word && is_word(chars.peek()) => {
+ return true;
+ }
c if c.is_whitespace() || is_operator(c) => {
- parameter = false;
- brace = None;
- class = None;
+ (parameter, brace, class, in_word) = (false, None, None, false);
}
'{' if previous == Some('$') => parameter = true,
'}' if parameter => parameter = false,
@@ -1259,14 +1452,14 @@ fn has_unevaluated_expansion(command: &str) -> bool {
brace = None;
}
'[' if class.is_none() => class = Some(0),
- ']' if class.is_some() => {
- if class > Some(0) {
- return true;
- }
- class = None;
- }
+ // A `]` first in a class is a member (`[]a]`), not its end.
+ ']' if class == Some(0) => class = Some(1),
+ ']' if class.is_some() => return true,
_ => class = class.map(|len| len + 1),
}
+ if !c.is_whitespace() && !is_operator(c) {
+ in_word = true;
+ }
previous = Some(c);
}
false
@@ -1291,9 +1484,12 @@ fn shell_command(args: &Value) -> Option<ShellCommand<'_>> {
/// Splits a command line into words the way a POSIX shell would before
/// expansion: quotes group, and whitespace and control/redirection operators
/// separate. A backslash escapes only a character the shell treats specially,
-/// so Windows paths (`docs\adr\x.md`) keep their separators.
+/// so Windows paths (`docs\adr\x.md`) keep their separators. A backquote
+/// opens or closes a command substitution, so it separates too. An ANSI-C
+/// string (`$'…'`) has its escapes decoded; numeric and control escapes stay
+/// as written, and [`has_unevaluated_expansion`] reports them.
fn shell_words(command: &str) -> Vec<String> {
- let is_operator = |c: char| matches!(c, '|' | '&' | ';' | '<' | '>' | '(' | ')');
+ let is_operator = |c: char| matches!(c, '|' | '&' | ';' | '<' | '>' | '(' | ')' | '`');
let mut words = Vec::new();
let mut word = String::new();
let mut in_word = false;
@@ -1301,15 +1497,33 @@ fn shell_words(command: &str) -> Vec<String> {
let mut chars = command.chars().peekable();
while let Some(c) = chars.next() {
match (quote, c) {
- (Some('\''), '\'') | (Some('"'), '"') => quote = None,
+ (Some('\'' | '$'), '\'') | (Some('"'), '"') => quote = None,
(Some('"'), '\\') if matches!(chars.peek(), Some('"' | '\\')) => {
word.extend(chars.next());
}
+ (Some('$'), '\\') => match chars.next() {
+ Some(escape) => match ansi_c_escape(escape) {
+ Some(decoded) => word.push(decoded),
+ None => {
+ word.push('\\');
+ word.push(escape);
+ }
+ },
+ None => word.push('\\'),
+ },
(Some(_), _) => word.push(c),
(None, '\'' | '"') => {
quote = Some(c);
in_word = true;
}
+ // `$'…'` (ANSI-C) and `$"…"` (locale) strings drop the `$`.
+ (None, '$') if matches!(chars.peek(), Some('\'' | '"')) => {
+ quote = match chars.next() {
+ Some('\'') => Some('$'),
+ _ => Some('"'),
+ };
+ in_word = true;
+ }
(None, '\\')
if chars.peek().is_some_and(|next| {
next.is_whitespace() || is_operator(*next) || matches!(next, '\'' | '"' | '\\')
@@ -1336,20 +1550,65 @@ fn shell_words(command: &str) -> Vec<String> {
words
}
+/// The character an ANSI-C escape stands for, or `None` for a numeric or
+/// control escape (`\x64`, `\144`, `\u0064`, `\cA`) that is not decoded.
+fn ansi_c_escape(escape: char) -> Option<char> {
+ Some(match escape {
+ 'a' => '\u{7}',
+ 'b' => '\u{8}',
+ 'e' | 'E' => '\u{1b}',
+ 'f' => '\u{c}',
+ 'n' => '\n',
+ 'r' => '\r',
+ 't' => '\t',
+ 'v' => '\u{b}',
+ '\\' | '\'' | '"' | '?' => escape,
+ _ => return None,
+ })
+}
+
/// Path-like values carried by one shell word: the word itself unless it is
/// a flag, plus the value of a `--flag=value`, `NAME=value`, or PowerShell
-/// `-Param:value` word.
-fn shell_arguments(word: &str) -> impl Iterator<Item = &str> {
+/// `-Param:value` word, plus the path of a git `REV:path` object name. The
+/// flag is set for that last one, which git resolves from the repository
+/// root.
+fn shell_arguments(word: &str) -> impl Iterator<Item = (&str, bool)> {
let flag = word.starts_with('-');
- let whole = (!flag).then_some(word);
+ let whole = (!flag).then_some((word, false));
let value = word
.split_once('=')
.or_else(|| flag.then(|| word.split_once(':')).flatten())
- .map(|(_, value)| value);
+ .map(|(_, value)| (value, false));
+ let object = git_object_path(word).map(|path| (path, true));
whole
.into_iter()
.chain(value)
- .filter(|argument| !argument.trim().is_empty())
+ .chain(object)
+ .filter(|(argument, _)| !argument.trim().is_empty())
+}
+
+/// The path of a git object name such as `HEAD:docs/x.md`, `v1.2~3:x`,
+/// `:docs/x.md` (the index) or `:2:x` (a merge stage). A drive letter
+/// (`C:\x`), a URL (`https://…`) and anything whose left side is not
+/// revision-shaped (`host:path`, `NAME=a:b`) are not object names here.
+fn git_object_path(word: &str) -> Option<&str> {
+ if word.starts_with('-') {
+ return None;
+ }
+ let (revision, path) = word.split_once(':')?;
+ let path = if revision.is_empty() {
+ path.strip_prefix(['0', '1', '2', '3'])
+ .and_then(|rest| rest.strip_prefix(':'))
+ .unwrap_or(path)
+ } else {
+ path
+ };
+ let drive = revision.len() == 1 && revision.as_bytes()[0].is_ascii_alphabetic();
+ let revision_shaped = revision.chars().all(|c| {
+ c.is_ascii_alphanumeric()
+ || matches!(c, '.' | '_' | '-' | '/' | '~' | '^' | '@' | '{' | '}')
+ });
+ (!drive && revision_shaped && !path.starts_with("//")).then_some(path)
}
#[derive(Clone)]
@@ -3054,6 +3313,28 @@ mod tests {
("git diff HEAD@{1}..HEAD", false),
("echo a, b} {c", false),
("cat [] x", false),
+ // A leading `]` is a class member; the class still closes.
+ ("cat docs/ad[]r]/1.md", true),
+ ("cat docs/ad[!]x]/1.md", true),
+ ("jq .[] x.json", false),
+ // zsh glob groups and extglobs, but not subshells or substitutions.
+ ("cat docs/(adr|x)/1.md", true),
+ ("cat (docs|x)/adr/1.md", true),
+ ("cat (docs)/adr/1.md", true),
+ ("cat (docs/adr/1.md|x)", true),
+ ("cat docs/@(adr)/1.md", true),
+ ("(cd src && cargo test)", false),
+ ("(cd src && cargo test) | tee log", false),
+ ("echo $((1+2)) $(date) x=$(pwd)/y", false),
+ ("diff <(ls src) <(ls tests)", false),
+ ("arr=(a b)", false),
+ ("cat '(adr|x)'", false),
+ // ANSI-C strings: numeric and control escapes are not decoded.
+ ("cat $'docs/\\x61dr/1.md'", true),
+ ("cat $'docs/\\141dr/1.md'", true),
+ ("cat $'docs/\\u0061dr'", true),
+ ("cat $'it\\'s {a,b}'", false),
+ ("cat $'a\\tb'", false),
] {
assert_eq!(has_unevaluated_expansion(command), expected, "{command}");
}
@@ -3324,9 +3605,10 @@ mod tests {
panic!("a string command is kept as a line");
};
assert!(std::ptr::eq(borrowed, line["command"].as_str().unwrap()));
+ // A quoted word holding several words is read like a command line.
assert_eq!(
ShellCommand::Line(borrowed).words(),
- ["cat", "private notes/x.md", "head"]
+ ["cat", "private notes/x.md", "private", "notes/x.md", "head"]
);
let argv = json!({"cmd": ["cat", "private notes/x.md"]});
@@ -3348,4 +3630,280 @@ mod tests {
assert!(shell_command(&args).is_none(), "{args}");
}
}
+ /// A string-form command used to keep any quoted script whole, so
+ /// `bash -c 'cat <ignored>'` or `"$(cat <ignored>)"` was kept while the
+ /// argv form dropped. Nested words are now read like a command line, to a
+ /// bounded depth; deeper nesting fails closed.
+ #[test]
+ fn quoted_scripts_in_string_commands_are_read_like_command_lines() {
+ let policy = shell_policy();
+ let decide = |command: &str| {
+ policy
+ .inspect(AgentKind::ClaudeCode, &bash(command), "/repo")
+ .protocol()
+ .disposition()
+ };
+ for command in [
+ "bash -c 'cat docs/adr/1.md'",
+ "timeout 5 bash -c \"head docs/adr/1.md\"",
+ "echo \"$(cat docs/adr/1.md)\"",
+ "FOO=\"$(cat docs/adr/1.md)\"",
+ "echo \"`cat docs/adr/1.md`\"",
+ "bash -c \"sh -c 'cat docs/adr/1.md'\"",
+ "python3 -c \"print(open('docs/adr/1.md').read())\"",
+ ] {
+ assert_eq!(decide(command), CaptureDisposition::Drop, "{command}");
+ }
+ for command in ["bash -c 'cargo test'", "echo \"$(git rev-parse HEAD)\""] {
+ assert_eq!(decide(command), CaptureDisposition::Keep, "{command}");
+ }
+ // Five quoting levels: the innermost script is not read, so the
+ // command proves nothing.
+ let mut script = "cat docs/adr/1.md".to_owned();
+ for _ in 0..MAX_SHELL_NESTING {
+ script = format!("bash -c {}", shell_quote(&script));
+ }
+ assert_eq!(decide(&script), CaptureDisposition::Drop, "four levels");
+ let deeper = format!(
+ "bash -c {}",
+ shell_quote(&script.replace("docs/adr", "src"))
+ );
+ assert_eq!(
+ decide(&deeper),
+ CaptureDisposition::MetadataOnly,
+ "five levels"
+ );
+ }
+
+ fn shell_quote(text: &str) -> String {
+ format!("'{}'", text.replace('\'', "'\\''"))
+ }
+
+ /// Inline interpreter code can name a path no lexical match sees, so a
+ /// command running it is metadata-only unless a literal names an ignored
+ /// path outright. Running a script file or a module is unaffected.
+ #[test]
+ fn inline_interpreter_code_is_metadata_only_under_an_active_policy() {
+ for (words, inline) in [
+ (&["python3", "-c", "x"][..], true),
+ (&["/usr/bin/python3.12", "-I", "-c", "x"], true),
+ (&["python", "-Ic", "x"], true),
+ (&["node", "-e", "x"], true),
+ (&["node", "--eval=x"], true),
+ (&["bun", "-p", "x"], true),
+ (&["ruby", "-e", "x"], true),
+ (&["perl", "-ne", "x"], true),
+ (&["php", "-r", "x"], true),
+ (&["deno", "eval", "x"], true),
+ (&["python3", "-m", "pytest", "-c", "x"], false),
+ (&["python3", "script.py"], false),
+ (&["node", "scripts/build.js"], false),
+ (&["ruby", "-Eutf-8", "x.rb"], false),
+ (&["grep", "-e", "x"], false),
+ ] {
+ assert_eq!(runs_inline_code(words), inline, "{words:?}");
+ }
+ let policy = shell_policy();
+ let argv =
+ json!({"tool_name": "shell", "tool_input": {"command": ["python3", "-c", "print(1)"]}});
+ assert_eq!(
+ policy
+ .inspect(AgentKind::Codex, &argv, "/repo")
+ .protocol()
+ .disposition(),
+ CaptureDisposition::MetadataOnly
+ );
+ let inactive = CapturePolicy::resolve(CaptureSource::Absent, "/repo", None);
+ assert_eq!(
+ inactive
+ .inspect(AgentKind::Codex, &argv, "/repo")
+ .protocol()
+ .disposition(),
+ CaptureDisposition::Keep
+ );
+ }
+
+ /// `git show REV:path` names a file the way `cat path` does, resolved
+ /// from the repository root; drive letters, URLs and host names are not
+ /// object names.
+ #[test]
+ fn git_object_names_are_path_candidates() {
+ assert_eq!(git_object_path("HEAD:docs/x.md"), Some("docs/x.md"));
+ assert_eq!(git_object_path(":docs/x.md"), Some("docs/x.md"));
+ assert_eq!(git_object_path(":2:docs/x.md"), Some("docs/x.md"));
+ assert_eq!(git_object_path("HEAD@{1}:x"), Some("x"));
+ assert_eq!(git_object_path(r"C:\docs\x.md"), None);
+ assert_eq!(git_object_path("C:/docs/x.md"), None);
+ assert_eq!(git_object_path("https://h/docs/x.md"), None);
+ assert_eq!(git_object_path("NAME=a:b"), None);
+ assert_eq!(git_object_path("--format=%h:%s"), None);
+ let policy = shell_policy();
+ for (command, cwd, expected) in [
+ (
+ "git show HEAD:docs/adr/1.md",
+ "/repo",
+ CaptureDisposition::Drop,
+ ),
+ (
+ "git show HEAD:docs/adr/1.md",
+ "/repo/src",
+ CaptureDisposition::Drop,
+ ),
+ (
+ "git show :./adr/1.md",
+ "/repo/docs",
+ CaptureDisposition::Drop,
+ ),
+ (
+ "git show HEAD:src/main.rs",
+ "/repo",
+ CaptureDisposition::Keep,
+ ),
+ ] {
+ assert_eq!(
+ policy
+ .inspect(AgentKind::ClaudeCode, &bash(command), cwd)
+ .protocol()
+ .disposition(),
+ expected,
+ "{command} in {cwd}"
+ );
+ }
+ // A Windows host keeps its drive paths out of object-name parsing.
+ let windows = CapturePolicy::resolve(
+ CaptureSource::Parsed(&CaptureConfig {
+ ignore_paths: vec!["docs/adr/**".into()],
+ }),
+ r"C:\repo",
+ None,
+ );
+ for (command, expected) in [
+ (r"type C:\repo\src\x.md", CaptureDisposition::Keep),
+ ("git show HEAD:docs/adr/1.md", CaptureDisposition::Drop),
+ ] {
+ assert_eq!(
+ windows
+ .inspect(AgentKind::ClaudeCode, &bash(command), r"C:\repo")
+ .protocol()
+ .disposition(),
+ expected,
+ "{command}"
+ );
+ }
+ }
+
+ /// `$'…'` is decoded like the shell does, and `\o` outside quotes is
+ /// `o`, so neither spelling hides an ignored path.
+ #[test]
+ fn ansi_c_strings_and_escaped_letters_are_read_like_the_shell() {
+ assert_eq!(
+ shell_words(r"cat $'docs/adr/1.md' $'a\tb' $'it\'s' $'\x61' $loc"),
+ ["cat", "docs/adr/1.md", "a\tb", "it's", r"\x61", "$loc"]
+ );
+ assert_eq!(shell_words("echo `cat x`y"), ["echo", "cat", "x", "y"]);
+ let policy = shell_policy();
+ for (command, expected) in [
+ ("cat $'docs/adr/1.md'", CaptureDisposition::Drop),
+ ("cat $\"docs/adr/1.md\"", CaptureDisposition::Drop),
+ (r"cat d\ocs/adr/1.md", CaptureDisposition::Drop),
+ (r"cat docs/a\dr/1.\md", CaptureDisposition::Drop),
+ (r"cat $'docs/\x61dr/1.md'", CaptureDisposition::MetadataOnly),
+ ("cat $'src/main.rs'", CaptureDisposition::Keep),
+ (r"cat s\rc/main.rs", CaptureDisposition::Keep),
+ ] {
+ assert_eq!(
+ policy
+ .inspect(AgentKind::ClaudeCode, &bash(command), "/repo")
+ .protocol()
+ .disposition(),
+ expected,
+ "{command}"
+ );
+ }
+ }
+
+ /// Antigravity's `run_command` runs in its `Cwd` argument, so a relative
+ /// argument resolves from there; another agent's `Cwd` key means nothing.
+ #[test]
+ fn antigravity_run_command_resolves_arguments_from_its_cwd() {
+ let policy = shell_policy();
+ let run = |command: &str, cwd: &str| json!({"toolCall": {"name": "run_command", "args": {"CommandLine": command, "Cwd": cwd}}});
+ for (raw, expected) in [
+ (run("cat 1.md", "/repo/docs/adr"), CaptureDisposition::Drop),
+ (run("cat adr/1.md", "docs"), CaptureDisposition::Drop),
+ (run("cat 1.md", "/repo/src"), CaptureDisposition::Keep),
+ (run("cat docs/adr/1.md", "/repo"), CaptureDisposition::Drop),
+ ] {
+ assert_eq!(
+ policy
+ .inspect(AgentKind::AntigravityCli, &raw, "/repo")
+ .protocol()
+ .disposition(),
+ expected,
+ "{raw}"
+ );
+ }
+ let other = json!({"tool_name": "Bash", "tool_input": {"command": "cat 1.md", "Cwd": "/repo/docs/adr"}});
+ assert_eq!(
+ policy
+ .inspect(AgentKind::ClaudeCode, &other, "/repo")
+ .protocol()
+ .disposition(),
+ CaptureDisposition::Keep
+ );
+ assert_eq!(
+ absolute_tool_location_paths(
+ AgentKind::AntigravityCli,
+ &run("ls", "/other/repo"),
+ "/repo"
+ ),
+ Some(vec!["/other/repo".to_owned()])
+ );
+ }
+ /// Reading nested words and the new fail-closed syntax must not strip
+ /// everyday commands that name no ignored path.
+ #[test]
+ fn common_commands_stay_kept_under_an_active_policy() {
+ let policy = shell_policy();
+ for command in [
+ "cargo test",
+ "cargo test -p ai-memory-hooks -- --nocapture",
+ "cargo clippy --workspace --all-targets -- -D warnings",
+ "git status",
+ "git log --oneline -10",
+ "git log --format='%h %s' -5",
+ "git log --pretty=format:\"%h {a,b}\" -- src/",
+ "git diff",
+ "git diff --stat HEAD~1",
+ "git diff HEAD~1 -- src/",
+ "git show HEAD --stat",
+ "git show HEAD:src/main.rs",
+ "git commit -m \"fix: handle {a,b} and [x] in the parser\"",
+ "ls",
+ "ls -la src",
+ "npm test",
+ "npm run build -- --watch",
+ "npx jest src/app.test.ts",
+ "pytest -k \"not slow\" -x tests/",
+ "python3 -m pytest -q",
+ "python3 scripts/gen.py --out build/",
+ "node scripts/build.js",
+ "rg TODO src",
+ "rg \"(foo|bar)baz\" src",
+ "grep -rn \"fn main\\(\" src",
+ "echo \"$(git rev-parse HEAD)\"",
+ "(cd src && cargo test)",
+ "docker compose up -d",
+ "curl -s http://localhost:8080/health",
+ ] {
+ assert_eq!(
+ policy
+ .inspect(AgentKind::ClaudeCode, &bash(command), "/repo")
+ .protocol()
+ .disposition(),
+ CaptureDisposition::Keep,
+ "{command}"
+ );
+ }
+ }
}
diff --git a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
index 9235c77d..6f6418cf 100644
--- a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
+++ b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
@@ -144,7 +144,8 @@
{"command":"cat *.md","disposition":"keep"},
{"command":"git add .","disposition":"keep"},
{"command":"cargo test -p ai-memory-hooks","disposition":"keep"},
- {"command":"echo 'docs/adr is ignored'x","disposition":"keep"},
+ {"command":"echo 'docs/adr is ignored'x","disposition":"drop"},
+ {"command":"echo 'see docs/adrx'","disposition":"keep"},
{"command":"cat notes/today.md","disposition":"keep"},
{"command":"","disposition":"keep"},
{"command":"cat C:/Public/x.md","disposition":"keep"},
@@ -189,7 +190,55 @@
{"command":"echo ${HOME} ${arr[0]}","disposition":"keep"},
{"command":"[ -f src/main.rs ] && [[ -d src ]]","disposition":"keep"},
{"command":"git diff HEAD@{1}..HEAD","disposition":"keep"},
- {"command":"ls src/*.rs","disposition":"keep"}
+ {"command":"ls src/*.rs","disposition":"keep"},
+ {"command":"bash -c 'cat docs/adr/1.md'","disposition":"drop"},
+ {"command":"sh -c \"cat docs/adr/1.md\"","disposition":"drop"},
+ {"command":"timeout 5 bash -c \"head docs/adr/1.md\"","disposition":"drop"},
+ {"command":"echo \"$(cat docs/adr/1.md)\"","disposition":"drop"},
+ {"command":"FOO=\"$(cat docs/adr/1.md)\"","disposition":"drop"},
+ {"command":"echo \"`cat docs/adr/1.md`\"","disposition":"drop"},
+ {"command":"bash -c \"sh -c 'cat docs/adr/1.md'\"","disposition":"drop"},
+ {"command":"bash -c 'cat docs/{adr,x}/1.md'","disposition":"metadata-only"},
+ {"command":"echo \"$(cat docs/ad[r]/1.md)\"","disposition":"metadata-only"},
+ {"command":"python3 -c \"print(open('docs/adr/1.md').read())\"","disposition":"drop"},
+ {"command":"ruby -e 'puts File.read(\"docs/adr/1.md\")'","disposition":"drop"},
+ {"command":"python3 -c \"import os; print(open(os.path.join('docs','adr','1.md')).read())\"","disposition":"metadata-only"},
+ {"command":"node -e \"require('fs').readFileSync('docs/' + 'adr/1.md')\"","disposition":"metadata-only"},
+ {"command":"perl -e 'print 1'","disposition":"metadata-only"},
+ {"command":"bash -c 'cargo test'","disposition":"keep"},
+ {"command":"sh -c \"git status && git log --oneline -5\"","disposition":"keep"},
+ {"command":"python3 -m pytest -q tests/","disposition":"keep"},
+ {"command":"pytest -k \"not slow\" tests/","disposition":"keep"},
+ {"command":"node scripts/build.js","disposition":"keep"},
+ {"command":"npm run test -- --watch","disposition":"keep"},
+ {"command":"git commit -m \"fix {a,b} parsing\"","disposition":"keep"},
+ {"command":"echo \"$(git rev-parse HEAD)\"","disposition":"keep"},
+ {"command":"git show HEAD:docs/adr/1.md","disposition":"drop"},
+ {"command":"git show :docs/adr/1.md","disposition":"drop"},
+ {"command":"git show :0:docs/adr/1.md","disposition":"drop"},
+ {"command":"git cat-file -p main~2:docs/adr/1.md","disposition":"drop"},
+ {"command":"git show HEAD:docs/adr/1.md","cwd":"sub","disposition":"drop"},
+ {"command":"git diff HEAD~1:docs/adr/1.md src/main.rs","disposition":"drop"},
+ {"command":"git show HEAD:src/main.rs","disposition":"keep"},
+ {"command":"git show HEAD:docs/adrx.md","disposition":"keep"},
+ {"command":"curl -s https://example.com/docs/adr/1.md","disposition":"keep"},
+ {"command":"docker run -p 8080:80 img","disposition":"keep"},
+ {"command":"cat docs/ad[]r]/1.md","disposition":"metadata-only"},
+ {"command":"cat docs/(adr|x)/1.md","disposition":"metadata-only"},
+ {"command":"cat (docs|x)/adr/1.md","disposition":"metadata-only"},
+ {"command":"cat (docs)/adr/1.md","disposition":"metadata-only"},
+ {"command":"cat (docs/adr/1.md|x)","disposition":"drop"},
+ {"command":"cat (README.md|x)","disposition":"metadata-only"},
+ {"command":"cat $'docs/adr/1.md'","disposition":"drop"},
+ {"command":"cat $\"docs/adr/1.md\"","disposition":"drop"},
+ {"command":"cat $'docs/\\x61dr/1.md'","disposition":"metadata-only"},
+ {"command":"cat d\\ocs/adr/1.md","disposition":"drop"},
+ {"command":"cat docs/ad\\r/1.md","disposition":"drop"},
+ {"command":"(cd src && cargo test)","disposition":"keep"},
+ {"command":"echo $((1+2))","disposition":"keep"},
+ {"command":"diff <(ls src) <(ls tests)","disposition":"keep"},
+ {"command":"cat $'src/main.rs'","disposition":"keep"},
+ {"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"]}}
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 7827125d..8236ac61 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -461,6 +461,17 @@ out of capture:
ignore_paths = ["private/**", "~/personal-notes/**"]
```
+> **`ignore_paths` is a best-effort filter for shell commands and unknown
+> tools.** File tools are matched on their explicit path fields, but a shell
+> command is only read lexically and a tool the matcher does not list is not
+> read at all. The [gaps listed below](#capture-exclusion-residuals) stay
+> open: shell variables (`$VAR`), a `cd` inside a command, symlinks, a
+> recursive search of a parent directory, unknown tools, and scripts that a
+> command reads from a file or a heredoc. For a sensitive project, use
+> **allowlist capture mode** (`install-hooks --capture-mode allowlist`, above)
+> and leave that repository without a marker. That mode is the strict
+> guarantee: nothing from an unmarked repository is captured at all.
+
A repository that keeps its decision records in the tree (an ADR directory,
a [Keep the Why](https://github.com/oliver-zehentleitner/keep-the-why)
`context/` tree) belongs here too: `ignore_paths = ["docs/adr/**"]` or
@@ -521,19 +532,40 @@ Codex shell calls, including its `exec_command` path, reach hooks as `Bash`
with the command in `tool_input.command`.
A command given as an argument vector keeps each element as one word (a path
with spaces stays whole, up to 256 characters) and also splits each element on
-its own, so a `bash -lc "<script>"` script is read like any command line. Each
+its own. Any word that holds more than one word is split again the same way,
+whether it is an argument vector element, a quoted script (`bash -c '…'`,
+`sh -c "…"`), or a command substitution inside double quotes (`"$(…)"` or
+backquotes), so a script is read like any command line, up to four quoting
+levels; a script nested deeper is **metadata-only**. A quoted message that
+mentions an ignored path (`git commit -m "…docs/adr/…"`) therefore drops the
+event too. An ANSI-C string (`$'…'`) is decoded and a backslash before an
+ordinary letter is dropped, as the shell does. Each
argument that is not a flag, plus the value of a `--flag=value`, `NAME=value`,
or PowerShell `-Param:value` word, is resolved like a file-tool path: from the tool's own
-`workdir` argument (Gemini CLI's `dir_path`) when it has one, otherwise from the event's `cwd`. If
+`workdir` argument (Gemini CLI's `dir_path`, Antigravity's `Cwd`) when it has one, otherwise from the event's `cwd`.
+The path in a git object name (`HEAD:docs/x.md`, `:docs/x.md`) is resolved
+from both the `cwd` and the marker directory, because git reads it from the
+repository root. If
one matches a pattern, the whole event is **dropped**, exactly like a matching
file read. An argument containing `*` or `?` also matches when its glob can
reach a pattern's directory: `cat docs/*/0001.md` is dropped under
`docs/adr/**`, `cat *.md` at the repository root is not. A command that exceeds
-the match budget is dropped. A command with an unquoted brace expansion
-(`docs/{adr,x}/1.md`, `{1..3}`) or bracket class (`docs/ad[r]/1.md`) that no
-argument matches outright is **metadata-only**, because those are not
-evaluated; quoted or escaped braces and brackets, `${…}`, `{}` and `[ -f x ]`
-are unaffected. Variables, command substitution, `cd` state, and
+the match budget is dropped. A command that no argument matches outright is
+**metadata-only** when it uses syntax the matcher does not evaluate: an
+unquoted brace expansion (`docs/{adr,x}/1.md`, `{1..3}`), a bracket class
+(`docs/ad[r]/1.md`, including one that starts with `]`), a zsh glob group or
+extglob (`docs/(a|b)/1.md`, `@(…)`), or a numeric or control escape in an
+ANSI-C string. The same holds for those inside a script run by `sh -c`,
+`eval` or a command substitution, but not inside a quoted message or pattern
+(`git log --format='%h {a,b}'`). Quoted or escaped braces and brackets,
+`${…}`, `{}`, `[ -f x ]`, `$(…)`, `<(…)` and a `( … )` subshell are
+unaffected; a word glued to a parenthesis (`f()`, `(a|b)x`) also counts as a
+glob group. Inline interpreter code (`python3 -c`, `node -e`, `ruby -e`,
+`perl -e`, `php -r`, `deno eval`) 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
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
@@ -556,13 +588,19 @@ re-reads too (for every file, not only the ignored ones). Add each relevant visi
explicitly, and do not rely on this feature to detect every way private content
can be mentioned.
-These gaps are inherent to lexical matching and stay open:
+<a id="capture-exclusion-residuals"></a>These gaps are inherent to lexical matching and stay open:
-- shell variables (`$VAR`) and command substitution are not expanded;
+- shell variables (`$VAR`) are not expanded, and a command substitution's
+ output is not known (its own words are read);
- a `cd` inside a command is not followed (the tool's own `workdir` is);
- symlinks are not resolved, by design;
- a recursive search of a parent directory through a shell (`grep -r x docs`,
`rg x`) names no ignored path, so its output is kept;
+- a script read from a file (`bash run.sh`, `python3 tool.py`) is not read,
+ and a heredoc fed to an interpreter (`python3 - <<EOF`) is read only for the
+ words it spells out;
+- git resolves `REV:path` from the repository root, which is approximated by
+ the marker directory and the `cwd`;
- 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 44012b0a..c10b9185 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); an invalid marker makes file and shell calls metadata-only; an active one makes a shell call metadata-only when a word uses unquoted brace expansion or a bracket class (`has_unevaluated_expansion`), 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`, `captureUnevaluatedExpansion`, `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 | `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`, the shell fixture's brace/class vectors (quoted, escaped, `${…}`, `{}`, `[ … ]`, `HEAD@{1}` controls kept); `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) | STRONG with listed residuals. Matching is lexical by design, so these stay open: shell variables (`$VAR`, `FILE=… sh -c 'cat $FILE'`) and command substitution, a `cd` inside the command, symlinks (paths are never resolved on disk), a recursive search of a parent directory (`grep -r x docs`, `rg x`) through a shell, and tools the matcher does not list, which keep their current unknown-tool behavior. Mitigation: allowlist capture mode (`install-hooks --capture-mode allowlist`) for sensitive projects |
+| 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`); 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 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 | `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), 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) | 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, and tools the matcher does not list, which keep their current unknown-tool behavior. 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 or the nested-script scan each fails the Rust tests, and each TypeScript counterpart fails the Node evidence test |
| 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH |
| 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |
| 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG |