Skip to content

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

Rust

fix(security): derive capture-exclusion path flavor from the host (GHSA-vh98)

AkitaOnRails85ddc1f45001
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 439e4426..68e32390 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Security
+- Fixed GHSA-vh98: a capture-exclusion candidate or shell argument spelled
+ with a leading `//` (e.g. `//repo/secret/token.txt`) self-classified as a
+ Windows UNC path regardless of the actual host, so it matched zero POSIX
+ `ignore_paths` patterns (a flavor mismatch) and was captured instead of
+ dropped. Path flavor for an untrusted candidate is now derived from the
+ host (the cwd) rather than the candidate string alone, both in the native
+ hook (`ai-memory-hooks` `capture_policy.rs`) and the generated
+ OpenCode/OMP/Pi/OpenClaw TypeScript integrations
+ (`ai-memory-cli` `render_shared.rs`); a genuine Windows/UNC host's UNC
+ candidates are unaffected.
+
## [2.5.0] - 2026-09-30
### Added
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 67aeb6ee..81fe726e 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -219,21 +219,35 @@ 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 };
+type CaptureConfig = { state: "inactive" | "active" | "invalid"; patterns: { path: string; windows: boolean; directory?: string; prefix: string }[]; base: string; windowsHost: boolean };
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 captureNormalize(path: string): { path: string; windows: boolean } | undefined { const p = path.replace(/\\/g, "/"); let root: string; let tail: string[]; if (p.startsWith("//")) { const x = p.slice(2).split("/").filter(Boolean); if (x.length < 2) return undefined; root = `//${x.shift()}/${x.shift()}`; tail = x; } else if (/^[A-Za-z]:\//.test(p)) { root = `${p[0].toUpperCase()}:/`; tail = p.slice(3).split("/"); } else if (p.startsWith("/")) { root = "/"; tail = p.slice(1).split("/"); } else return undefined; const out: string[] = []; for (const x of tail) { if (!x || x === ".") continue; if (x === "..") out.pop(); else out.push(x); } return { path: root + (out.length ? (root.endsWith("/") ? "" : "/") + out.join("/") : ""), windows: root !== "/" }; }
+// `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
+// host base, only when normalizing an untrusted tool-argument candidate: on a
+// POSIX host a leading `//` there is an ordinary doubled separator, not a UNC
+// root, and must collapse before flavor detection or it escapes every POSIX
+// `ignore_paths` pattern via a flavor mismatch (GHSA-vh98).
+function captureNormalize(path: string, windowsHost?: boolean): { path: string; windows: boolean } | undefined { const raw = windowsHost === false && path.startsWith("//") ? `/${path.replace(/^\/+/, "")}` : path; const p = raw.replace(/\\/g, "/"); let root: string; let tail: string[]; if (p.startsWith("//")) { const x = p.slice(2).split("/").filter(Boolean); if (x.length < 2) return undefined; root = `//${x.shift()}/${x.shift()}`; tail = x; } else if (/^[A-Za-z]:\//.test(p)) { root = `${p[0].toUpperCase()}:/`; tail = p.slice(3).split("/"); } else if (p.startsWith("/")) { root = "/"; tail = p.slice(1).split("/"); } else return undefined; const out: string[] = []; for (const x of tail) { if (!x || x === ".") continue; if (x === "..") out.pop(); else out.push(x); } return { path: root + (out.length ? (root.endsWith("/") ? "" : "/") + out.join("/") : ""), windows: root !== "/" }; }
function captureJoin(base: string, child: string): string { if (/^[^A-Za-z]?:|^[A-Za-z]:[^/\\]/.test(child)) return child; return `${base.replace(/[\\/]+$/, "")}/${child}`; }
function captureValidGlob(p: string): boolean { return !!p && [...p].length <= CAPTURE_MAX_PATTERN_CHARS && !/[!{}\[\]()|^$%]/.test(p) && !p.includes("${") && !p.includes("***") && !p.replace(/\\/g, "/").split("/").includes("..") && (!p.startsWith("~") || p.startsWith("~/")) && !/^[^A-Za-z]?:/.test(p) && !/^[A-Za-z]:[^/\\]/.test(p); }
function captureParseArray(value: string): string[] | undefined { let i = 0; const out: string[] = []; const ws = () => { while (/\s/.test(value[i] ?? "")) i++; }; const basic = { b: "\b", t: "\t", n: "\n", f: "\f", r: "\r", '"': '"', "\\": "\\" } as Record<string, string>; ws(); if (value[i++] !== "[") return undefined; for (;;) { ws(); if (value[i] === "]") { i++; ws(); return i === value.length ? out : undefined; } const quote = value[i++]; if (quote !== '"' && quote !== "'") return undefined; let s = ""; for (;;) { if (i >= value.length) return undefined; const c = value[i++]; if (c === quote) break; if (c === "\\" && quote === '"') { const e = value[i++]; if (e in basic) s += basic[e]; else if (e === "u" || e === "U") { const count = e === "u" ? 4 : 8; const hex = value.slice(i, i + count); if (!new RegExp(`^[0-9A-Fa-f]{${count}}$`).test(hex)) return undefined; const n = Number.parseInt(hex, 16); if (n > 0x10ffff || (n >= 0xd800 && n <= 0xdfff)) return undefined; s += String.fromCodePoint(n); i += count; } else return undefined; } else if (c === "\n" || c === "\r") return undefined; else s += c; } out.push(s); ws(); if (value[i] === ",") { i++; continue; } if (value[i] === "]") continue; return undefined; } }
+function captureHostWindows(path: string): boolean { return path.startsWith("\\\\") || path.startsWith("//") || /^[A-Za-z]:/.test(path); }
function captureConfig(cwd: string | undefined): CaptureConfig {
const marker = findMarker(cwd);
const candidateBase = captureNormalize(cwd ? resolve(cwd) : "")?.path ?? "";
- if (!marker) return { state: "inactive", patterns: [], base: candidateBase };
+ // 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)`.
+ const windowsHost = captureHostWindows(cwd ?? "");
+ 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 };
+ if (bytes.byteLength > CAPTURE_MARKER_MAX_BYTES) return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
let section = "";
let value = "";
let collecting = false;
@@ -243,26 +257,26 @@ function captureConfig(cwd: string | undefined): CaptureConfig {
if (!line) continue;
const table = /^\[([^\]]+)\]$/.exec(line);
if (table) {
- if (collecting) return { state: "invalid", patterns: [], base: candidateBase };
+ 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 };
+ if (!kv || kv[1] !== "ignore_paths") return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
seen = true;
value = kv[2];
collecting = !value.includes("]");
} else if (collecting) {
value += ` ${line}`;
collecting = !value.includes("]");
- } else return { state: "invalid", patterns: [], base: candidateBase };
+ } else return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
}
- if (collecting) return { state: "invalid", patterns: [], base: candidateBase };
- if (!seen) return { state: "inactive", patterns: [], base: candidateBase };
+ if (collecting) return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
+ if (!seen) return { state: "inactive", patterns: [], base: candidateBase, windowsHost };
const strings = captureParseArray(value);
- if (!strings || strings.length > CAPTURE_MAX_PATTERNS) return { state: "invalid", patterns: [], base: candidateBase };
+ if (!strings || strings.length > CAPTURE_MAX_PATTERNS) return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
const home = homedir();
const patterns = strings.map((source) => {
if (!captureValidGlob(source)) return undefined;
@@ -275,12 +289,12 @@ function captureConfig(cwd: string | undefined): CaptureConfig {
if (!normalized) return undefined;
return { path: normalized.path, windows: normalized.windows, directory: normalized.path.endsWith("/**") ? (normalized.path.slice(0, -3) || "/") : undefined, prefix: captureLiteralPrefix(normalized.path) };
});
- if (patterns.some((p) => !p)) return { state: "invalid", patterns: [], base: candidateBase };
+ if (patterns.some((p) => !p)) return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
return patterns.length
- ? { state: "active", patterns: patterns as CaptureConfig["patterns"], base: candidateBase }
- : { state: "inactive", patterns: [], base: candidateBase };
+ ? { state: "active", patterns: patterns as CaptureConfig["patterns"], base: candidateBase, windowsHost }
+ : { state: "inactive", patterns: [], base: candidateBase, windowsHost };
} catch (_e) {
- return { state: "invalid", patterns: [], base: candidateBase };
+ return { state: "invalid", patterns: [], base: candidateBase, windowsHost };
}
}
function captureGlob(pattern: string, candidate: string, insensitive: boolean, budget: { work: number }): boolean | undefined { const p = [...pattern]; const c = [...candidate]; const previous = new Array<boolean>(p.length + 1).fill(false); previous[0] = true; for (let j = 1; j <= p.length; j++) previous[j] = p[j - 1] === "*" && p[j] !== "*" && previous[j - 1]; for (const ch of c) { const current = new Array<boolean>(p.length + 1).fill(false); for (let j = 1; j <= p.length; j++) { if (++budget.work > CAPTURE_MAX_WORK) return undefined; const x = p[j - 1]; current[j] = x === "*" && p[j] === "*" ? false : x === "*" && j >= 2 && p[j - 2] === "*" ? current[j - 2] || previous[j] : x === "*" ? current[j - 1] || (ch !== "/" && previous[j]) : x === "?" ? ch !== "/" && previous[j - 1] : captureCharEq(x, ch, insensitive) && previous[j - 1]; } for (let j = 0; j <= p.length; j++) previous[j] = current[j]; } return previous[p.length]; }
@@ -299,7 +313,7 @@ function captureShellArguments(word: string): string[] { const out = word.starts
// 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)); if (!candidate) continue; const glob = /[*?]/.test(candidate.path); for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; const under = captureStartsWith(candidate.path, pattern.prefix, pattern.windows); if (!under && !glob) continue; if (under) { const directory = pattern.directory ? captureGlob(pattern.directory, candidate.path, pattern.windows, budget) : false; if (directory !== false) return directory; const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match !== false) return match; } if (glob) { const reaches = captureGlobReaches(candidate.path, pattern.prefix, pattern.windows, budget); if (reaches !== false) return reaches; } } } return false; }
+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 glob = /[*?]/.test(candidate.path); for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; const under = captureStartsWith(candidate.path, pattern.prefix, pattern.windows); if (!under && !glob) continue; if (under) { const directory = pattern.directory ? captureGlob(pattern.directory, candidate.path, pattern.windows, budget) : false; if (directory !== false) return directory; const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match !== false) return match; } if (glob) { const reaches = captureGlobReaches(candidate.path, pattern.prefix, pattern.windows, budget); if (reaches !== false) return reaches; } } } return false; }
function captureTool(payload: Record<string, unknown>): { family: CaptureProtocol["tool_family"]; paths?: string[]; extraction: CaptureProtocol["extraction_state"]; callID?: string; command?: string | string[]; shell?: boolean; workdir?: 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"].includes(name)) return { family: "search-list", extraction: "not-applicable", callID: call }; if (["bash","shell","shell_command","exec","execute","run_command","web_search","search_web","manage_task","manage_subagents","terminal","execute_bash","execute_cmd"].includes(name)) return { family: "non-file", extraction: "extracted", callID: call, command: captureShellCommand(args), shell: name !== "web_search", workdir: typeof args?.workdir === "string" && args.workdir.trim() ? args.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"].includes(name)) return { family: "unknown", extraction: "extracted", callID: call }; 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 (!paths || paths.some((p) => !p.trim() || [...p].length > CAPTURE_MAX_PATH_CHARS)) return { family: "file", extraction: "missing-or-malformed", callID: call }; return { family: "file", paths, extraction: "extracted", callID: call }; }
// An external lifecycle owner (`AI_MEMORY_CAPTURE_OWNER`, any value that is
// non-empty after trimming) takes over capture for this process: the gate runs
@@ -316,7 +330,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)) 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))); if (candidates.some((p) => !p)) disposition = "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 && captureMatchCommand(tool.command, config, tool.workdir) !== false) disposition = "drop"; 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)) 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 { 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 && captureMatchCommand(tool.command, config, tool.workdir) !== false) disposition = "drop"; 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)
}
@@ -2311,7 +2325,17 @@ for (const vector of fixture.decisions.filter((v: any) => ["open-code", "omp", "
}}
for (const vector of fixture.normalization) {{
const cwd = marker(`[capture]\nignore_paths = [${{JSON.stringify(vector.pattern)}}]\n`);
- expectDecision({{ tool: "edit", args: {{ path: vector.candidate }} }}, cwd, vector.match ? "drop" : "keep", "file", "extracted", 1, "fixture-normalization");
+ // Every normalization vector here uses an absolute pattern+candidate pair
+ // (so neither ever needs the real marker directory as a join base); the
+ // fixture's own `cwd` is what decides host flavor. A Windows-shaped `cwd`
+ // (e.g. "C:/") can't be a real directory on this (POSIX) test runner —
+ // `resolve("C:/")` would mangle it through the real OS path module — so
+ // alias the already-written marker file under the fixture's literal `cwd`
+ // string and pass that string straight through, exactly like the native
+ // test honors `vector["cwd"]` verbatim.
+ const hostCwd: string = /^(?:\\\\|\/\/|[A-Za-z]:)/.test(vector.cwd) ? vector.cwd : cwd;
+ if (hostCwd !== cwd) markerFixtures.set(hostCwd, markerFixtures.get(cwd)!);
+ expectDecision({{ tool: "edit", args: {{ path: vector.candidate }} }}, hostCwd, vector.match ? "drop" : "keep", "file", "extracted", 1, "fixture-normalization");
}}
expectDecision({{ tool: "edit", args: {{ path: "private/item" }} }}, marker('[capture]\nignore_paths = ["private/**"]\n'), "drop", "file", "extracted", 1, "marker-relative");
// Shell parity with the native hook's lexical command matching (#948): the
@@ -2345,7 +2369,8 @@ expectDecision({{ tool: "edit", args: {{ path: "private/item" }} }}, nestedCwd,
expectDecision({{ tool: "edit", args: {{ path: `${{homedir()}}/home-private/item` }} }}, marker('[capture]\nignore_paths = ["~/home-private/**"]\n'), "drop", "file", "extracted", 1, "home-expansion");
expectDecision({{ tool: "edit", args: {{ path: "case/item" }} }}, marker('[capture]\nignore_paths = ["Case/**"]\n'), "keep", "file", "extracted", 1, "posix-case");
expectDecision({{ tool: "edit", args: {{ path: "c:/SECRET/item" }} }}, marker('[capture]\nignore_paths = ["C:/secret/**"]\n'), "drop", "file", "extracted", 1, "windows-drive-case");
-expectDecision({{ tool: "edit", args: {{ path: "//SERVER/SHARE/item" }} }}, marker(`[capture]\nignore_paths = ['${{String.raw`\\server\share/**`}}']\n`), "drop", "file", "extracted", 1, "windows-unc-case");
+const uncCwd = "C:/"; markerFixtures.set(uncCwd, markerFixtures.get(marker(`[capture]\nignore_paths = ['${{String.raw`\\server\share/**`}}']\n`))!);
+expectDecision({{ tool: "edit", args: {{ path: "//SERVER/SHARE/item" }} }}, uncCwd, "drop", "file", "extracted", 1, "windows-unc-case");
expectDecision({{ tool: "edit", args: {{ path: "x" }} }}, marker('[capture'), "metadata-only", "file", "extracted", 1, "malformed-table");
const malformedQuoteCwd = marker('[capture]\nignore_paths = ["private/**');
expectDecision({{ tool: "edit", args: {{ path: privatePath }} }}, malformedQuoteCwd, "metadata-only", "file", "extracted", 1, "malformed-unterminated-quote");
diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rs
index 87dcc46a..766f2fc3 100644
--- a/crates/ai-memory-hooks/src/capture_policy.rs
+++ b/crates/ai-memory-hooks/src/capture_policy.rs
@@ -1014,11 +1014,24 @@ fn normalize_candidate(candidate: &str, cwd: &str) -> Option<Normalized> {
return None;
}
let cwd = normalize_root(cwd).ok()?;
+ // 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
+ // from the string in isolation. Collapsing it first keeps a POSIX
+ // candidate POSIX-flavored so it still matches a POSIX `ignore_paths`
+ // pattern instead of silently escaping every pattern via a flavor
+ // mismatch (GHSA-vh98). A genuine Windows/UNC host is unaffected: the
+ // collapse only runs when the cwd itself is not windows-flavored.
let raw = if is_absolute(candidate) {
candidate.to_owned()
} else {
join(&cwd, candidate)
};
+ let raw = if flavor_of(&cwd) == Flavor::Posix && raw.starts_with("//") {
+ format!("/{}", raw.trim_start_matches('/'))
+ } else {
+ raw
+ };
let flavor = flavor_of(&raw);
Some(Normalized {
path: normalize_segments(&raw)?,
@@ -1326,6 +1339,69 @@ mod tests {
assert!(CaptureProtocol::parse(&fixture["protocol"]["accept"]).is_some());
assert!(CaptureProtocol::parse(&fixture["protocol"]["reject"]).is_none());
}
+ /// Adversarial regression for GHSA-vh98 / security-boundaries.md row
+ /// 11b: a POSIX-host candidate spelled with a leading `//` used to be
+ /// classified `Flavor::Windows` purely from the string, so it matched
+ /// zero POSIX `ignore_paths` patterns (flavor mismatch in `match_paths`'
+ /// filter) and was captured instead of dropped. `flavor_of` cannot tell
+ /// a doubled POSIX separator from a UNC root by itself; only the host
+ /// (the cwd) can. This attempts the violation, proves a plain-looking
+ /// control still drops normally, and proves a genuine Windows-hosted UNC
+ /// candidate still matches (so the fix didn't just blanket-collapse
+ /// every `//`).
+ #[test]
+ fn a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch() {
+ let policy = CapturePolicy::resolve(
+ CaptureSource::Parsed(&CaptureConfig {
+ ignore_paths: vec!["secret/**".into()],
+ }),
+ "/repo",
+ None,
+ );
+ // The violation attempt: on the unfixed code this normalized to a
+ // Windows-flavored candidate and matched no POSIX pattern, so it
+ // came back `Keep` (captured) instead of `Drop`.
+ let attack =
+ json!({"tool_name":"Edit","tool_input":{"file_path":"//repo/secret/token.txt"}});
+ assert_eq!(
+ policy
+ .inspect(AgentKind::ClaudeCode, &attack, "/repo")
+ .protocol()
+ .disposition(),
+ CaptureDisposition::Drop,
+ "a leading `//` must not escape a POSIX host's ignore_paths"
+ );
+ // Legitimate control: an ordinary single-slash candidate under the
+ // same pattern must keep being dropped.
+ let control =
+ json!({"tool_name":"Edit","tool_input":{"file_path":"/repo/secret/token.txt"}});
+ assert_eq!(
+ policy
+ .inspect(AgentKind::ClaudeCode, &control, "/repo")
+ .protocol()
+ .disposition(),
+ CaptureDisposition::Drop
+ );
+ // Windows-UNC control: a genuine UNC candidate on a Windows host
+ // must still match a UNC pattern — the fix is host-derived, not an
+ // unconditional `//` -> `/` collapse.
+ let windows_policy = CapturePolicy::resolve(
+ CaptureSource::Parsed(&CaptureConfig {
+ ignore_paths: vec!["\\\\server\\share\\**".into()],
+ }),
+ "C:/",
+ None,
+ );
+ let unc = json!({"tool_name":"Edit","tool_input":{"file_path":"//SERVER/SHARE/token.txt"}});
+ assert_eq!(
+ windows_policy
+ .inspect(AgentKind::ClaudeCode, &unc, "C:/")
+ .protocol()
+ .disposition(),
+ CaptureDisposition::Drop,
+ "a genuine UNC candidate on a Windows host must still match"
+ );
+ }
#[test]
fn all_states_and_strict_protocol_are_reachable() {
let file = json!({"tool_name":"Edit","tool_input":{}});
diff --git a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
index 2ae01b48..76d07428 100644
--- a/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
+++ b/crates/ai-memory-hooks/tests/fixtures/capture-policy.json
@@ -11,7 +11,9 @@
{"pattern":"unicode/?.txt","candidate":"unicode/é.txt","cwd":"/repo","match":true},
{"pattern":"foo..bar","candidate":"foo..bar","cwd":"/repo","match":true},
{"pattern":"docs/a?r/**","candidate":"docs/adr","cwd":"/repo","match":true},
- {"pattern":"docs/a?r/**","candidate":"docs/adrx","cwd":"/repo","match":false}
+ {"pattern":"docs/a?r/**","candidate":"docs/adrx","cwd":"/repo","match":false},
+ {"pattern":"/repo/secret/**","candidate":"//repo/secret/token.txt","cwd":"/repo","match":true},
+ {"pattern":"/repo/secret/**","candidate":"//repo/secret","cwd":"/repo","match":true}
],
"decisions": [
{"agent":"claude-code","payload":{"tool_name":"Edit","tool_input":{"file_path":"secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1},
@@ -43,7 +45,8 @@
{"agent":"codex","payload":{"tool_name":"Search","tool_input":{}},"disposition":"drop","tool_family":"search-list","extraction_state":"not-applicable","path_count":0},
{"agent":"codex","payload":{"tool_name":"Bash","tool_input":{"command":"secret/a"}},"disposition":"drop","tool_family":"non-file","extraction_state":"extracted","path_count":0},
{"agent":"codex","payload":{"tool_name":"FutureTool","tool_input":{"path":"secret/a"}},"disposition":"keep","tool_family":"unknown","extraction_state":"extracted","path_count":0},
- {"agent":"codex","payload":{"tool_name":"Edit","tool_input":{"nested":{"path":"secret/a"}}},"disposition":"metadata-only","tool_family":"file","extraction_state":"missing-or-malformed","path_count":0}
+ {"agent":"codex","payload":{"tool_name":"Edit","tool_input":{"nested":{"path":"secret/a"}}},"disposition":"metadata-only","tool_family":"file","extraction_state":"missing-or-malformed","path_count":0},
+ {"agent":"claude-code","payload":{"tool_name":"Edit","tool_input":{"file_path":"//repo/secret/a"}},"disposition":"drop","tool_family":"file","extraction_state":"extracted","path_count":1}
],
"shell": {
"note": "Shell-tool vectors run by both matchers. `{root}` is the marker directory, `cwd` is relative to it, and `command` is shorthand for a `bash` payload.",
@@ -52,6 +55,7 @@
{"command":"cat docs/adr/0001.md","disposition":"drop"},
{"command":"cat ./docs/adr/0001.md","disposition":"drop"},
{"command":"cat {root}/docs/adr/0001.md","disposition":"drop"},
+ {"command":"cat /{root}/docs/adr/x.md","disposition":"drop"},
{"command":"cat ../docs/adr/0001.md","cwd":"sub","disposition":"drop"},
{"command":"cat docs/adr/*.md","disposition":"drop"},
{"command":"cat docs/*/0001.md","disposition":"drop"},
diff --git a/crates/ai-memory-web/tests/suite/routes.rs b/crates/ai-memory-web/tests/suite/routes.rs
index 7f250400..ccc8c010 100644
--- a/crates/ai-memory-web/tests/suite/routes.rs
+++ b/crates/ai-memory-web/tests/suite/routes.rs
@@ -3431,6 +3431,129 @@ async fn web_reads_honour_grants_in_a_restricted_project() {
}
}
+/// Pins a documented, by-design boundary (see `docs/users.md`): under a
+/// trusted-proxy deployment, a proxied non-root end-user is authenticated as
+/// [`ai_memory_core::AuthLevel::User`] with an [`ai_memory_core::ActorContext`]
+/// (`auth.rs::authenticate_token`'s proxy branch), but — unlike a database
+/// user — is never stamped with an [`ai_memory_core::AuthorizedViewer`],
+/// because grants are keyed on `UserId` and a proxied identity has none.
+/// `viewer_from_parts` reads a missing `AuthorizedViewer` as "no per-project
+/// check applies" (same as root, or an install with no database users), so
+/// the per-project authorization gate is a pass-through for this actor: a
+/// `restricted` project is readable with no grant at all. This is NOT an
+/// endorsement of a gap to close — the proxy is the authorization boundary in
+/// this deployment shape — it is a pin so a future change to this behavior is
+/// an intentional decision, not a silent regression.
+///
+/// This mirrors `web_reads_honour_grants_in_a_restricted_project`'s harness:
+/// that test's own `viewer: None` case already exercises the same code path
+/// (a missing `AuthorizedViewer`), but doesn't carry the extensions a real
+/// trusted-proxy request would, so it doesn't document *why* that is safe
+/// here. The real middleware (`authenticate_token`) is not reachable from
+/// this router-only harness, so this stamps the same extensions it would
+/// have stamped, by hand.
+#[tokio::test]
+async fn a_trusted_proxy_user_is_not_subject_to_restricted_without_a_db_identity() {
+ use ai_memory_core::{ActorContext, AuthLevel};
+
+ let (_tmp, store, wiki) = setup().await;
+ store
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let client = store
+ .writer
+ .get_or_create_project(ws, "alice-client-work", None)
+ .await
+ .unwrap();
+ wiki.write_page(wiki_req(
+ ws,
+ client,
+ "secrets/rates.md",
+ "# Rates\n\nDay rate is confidential.",
+ ))
+ .await
+ .unwrap();
+ // A real database user, with no grant, is correctly refused — the
+ // control proving the project really is restricted.
+ let carol = store
+ .writer
+ .create_human_user(
+ ai_memory_core::NewUser {
+ username: "carol".into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ let api = api_router(store.reader.clone(), wiki.clone());
+ let web = router(store.reader.clone(), wiki.clone());
+ let routes = [
+ (
+ api.clone(),
+ "/workspaces/default/projects/alice-client-work/pages/secrets/rates.md",
+ ),
+ (
+ web.clone(),
+ "/w/default/alice-client-work/p/secrets/rates.md",
+ ),
+ ];
+
+ // Control: carol as a *database* user (AuthorizedViewer stamped, no
+ // grant) is refused on both surfaces.
+ for (app, uri) in &routes {
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(*uri)
+ .extension(ai_memory_core::AuthorizedViewer(carol))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::FORBIDDEN, "{uri}");
+ }
+
+ // The pinned case: the same project, read by a request carrying the
+ // extensions a trusted-proxy non-root user actually gets (`ActorContext`
+ // + `AuthLevel::User`) and nothing else — no `AuthorizedViewer`. Today
+ // this is admitted.
+ for (app, uri) in &routes {
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(*uri)
+ .extension(ActorContext {
+ user: Some("carol-proxied".into()),
+ ..ActorContext::default()
+ })
+ .extension(AuthLevel::User)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ resp.status(),
+ StatusCode::OK,
+ "{uri}: trusted-proxy user without a DB identity must be admitted today (pinned boundary)"
+ );
+ }
+}
+
/// #708, second half on the web: bob can no longer read or search alice's
/// repositories, but every listing, the graph, the workspace overview and a
/// page's link panel still told him they existed and roughly what was in
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index a842ed85..bcd3b858 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -51,7 +51,7 @@ boundary not yet built.
| 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 | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded` | 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, and the server admits a metadata-only shell body only under an invalid marker (`router.rs` `metadata_protocol_is_legal`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`) | `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`, `workdir`, glob directories, Windows paths), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors); `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 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`; `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job) | 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, and the server admits a metadata-only shell body only under an invalid marker (`router.rs` `metadata_protocol_is_legal`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`). 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 | `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`, `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`, `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 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`; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 vectors, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job) | STRONG |
| 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 | `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) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |
| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG |
diff --git a/docs/users.md b/docs/users.md
index 728236e2..4e712e66 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -153,6 +153,17 @@ root_subject = "<root-subject>"
exact match with `root_issuer` plus `root_subject`.
- Origin health checks or maintenance calls that need root should use the root
bearer, not the proxy bearer. Raw actor headers on the root rung are ignored.
+- **A proxied non-root end-user is not subject to per-project `restricted`
+ grants.** The proxy branch authenticates the request as `AuthLevel::User`
+ with an `ActorContext`, but — unlike a database user — never maps it to a
+ database `UserId`/`AuthorizedViewer`: grants are keyed on `UserId`, and a
+ proxied identity has none to key on. A missing `AuthorizedViewer` reads as
+ "no per-project check applies" (the same as root, or an install with no
+ database users at all), so a `restricted` project is readable by any
+ proxied user with no grant. This is by design, not a gap: in a trusted-proxy
+ deployment the proxy itself is the authorization boundary. If you need
+ per-project `restricted` enforcement for individual end users, issue them
+ database-user tokens (see above) instead of relying on the proxy headers.
## Identity keys