Skip to content

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

Rust

feat(integrations): generated TS plugins fail closed on a server profile (#992)

Talysson de Oliveira Cassiano5ed1d29ea56e
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 6b69b6cc..9503b32c 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -3537,6 +3537,7 @@ pub(crate) const TS_FIND_SETTINGS_MARKER: &str = r#"function declaresSettings(te
for (const key of ["workspace", "project", "project_strategy", "drop_subagent_captures", "identity"]) {
if (tomlKey(text, key) !== undefined) return true;
}
+ if (/^\s*server\s*=/m.test(text)) return true;
for (const key of ["default_global", "inject_on_session_start", "max_chars"]) {
if (tomlFlag(text, key) !== undefined) return true;
}
@@ -4136,6 +4137,7 @@ function postHook(event: string, payload: Record<string, unknown>): void {{
}}
async function fetchHandoff(cwd: string, id: string | undefined): Promise<string | undefined> {{
+ if (captureServerRouted(cwd)) return undefined;
const url = new URL(`${{SERVER}}/handoff`);
url.searchParams.set("agent", AGENT);
url.searchParams.set("cwd", cwd);
@@ -4875,6 +4877,7 @@ function postHook(event: string, payload: Record<string, unknown>): void {{
}}
async function fetchHandoff(cwd: string, id: string | undefined): Promise<string | undefined> {{
+ if (captureServerRouted(cwd)) return undefined;
const url = new URL(`${{SERVER}}/handoff`);
url.searchParams.set("agent", AGENT);
url.searchParams.set("cwd", cwd);
@@ -9973,6 +9976,49 @@ model = "gpt-5"
assert!(extension.contains(CAPTURE_ADMIT_GATE_TS), "{extension}");
}
+ /// #992: the generated integrations do not route `server` profiles, so
+ /// every one must drop a routed repository's events and skip its handoff
+ /// fetch — both before anything reaches the install-default `SERVER`.
+ #[test]
+ fn generated_integrations_fail_closed_on_a_server_profile_marker() {
+ let plugins = [
+ (
+ "opencode",
+ build_opencode_plugin("http://127.0.0.1:49374", None, None, "denylist"),
+ ),
+ (
+ "opencode2",
+ build_opencode2_plugin("http://127.0.0.1:49374", None, None, "denylist", false)
+ .unwrap(),
+ ),
+ (
+ "omp",
+ build_omp_extension("http://127.0.0.1:49374", None, None, "denylist"),
+ ),
+ (
+ "pi",
+ build_pi_extension("http://127.0.0.1:49374", None, None, "denylist"),
+ ),
+ ];
+ for (agent, plugin) in plugins {
+ assert!(
+ plugin.contains(
+ "if (captureServerRouted(cwd)) return { disposition: \"drop\", payload };"
+ ),
+ "{agent}: capture must drop a server-routed repository"
+ );
+ let handoff = plugin
+ .split_once("async function fetchHandoff(")
+ .unwrap_or_else(|| panic!("{agent}: no fetchHandoff"))
+ .1;
+ let guard = handoff
+ .find("if (captureServerRouted(")
+ .unwrap_or_else(|| panic!("{agent}: handoff fetch must be gated"));
+ let request = handoff.find("/handoff`").unwrap();
+ assert!(guard < request, "{agent}: gate must precede the request");
+ }
+ }
+
#[test]
fn pi_extension_denylist_bakes_inert_gate() {
let extension = build_pi_extension("http://127.0.0.1:49374", Some("tok"), None, "denylist");
diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
index e9475c47..ae4e32de 100644
--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
@@ -500,6 +500,7 @@ function postPreCompact(event: any, ctx: any): void {{
async function fetchHandoff(event: any, ctx: any): Promise<string | undefined> {{
const currentCwd = cwd(event, ctx);
if (!currentCwd) return undefined;
+ if (captureServerRouted(currentCwd)) return undefined;
const url = new URL(`${{SERVER}}/handoff`);
url.searchParams.set("agent", AGENT);
applyMarkerParams(url, currentCwd);
@@ -758,6 +759,24 @@ mod tests {
);
}
+ /// #992: OpenClaw posts to `SERVER` directly and does not route `server`
+ /// profiles, so a routed repository must emit nothing and fetch no handoff.
+ #[test]
+ fn openclaw_plugin_fails_closed_on_a_server_profile_marker() {
+ let plugin = build_plugin("http://127.0.0.1:49374", None, None, "denylist");
+ assert!(
+ plugin.contains(
+ "if (captureServerRouted(cwd)) return { disposition: \"drop\", payload };"
+ ),
+ "{plugin}"
+ );
+ let handoff = plugin.split_once("async function fetchHandoff(").unwrap().1;
+ let guard = handoff
+ .find("if (captureServerRouted(currentCwd)) return undefined;")
+ .expect("handoff fetch must be gated");
+ assert!(guard < handoff.find("/handoff`").unwrap());
+ }
+
#[test]
fn openclaw_plugin_denylist_bakes_inert_gate() {
let plugin = build_plugin("http://127.0.0.1:49374", Some("tok"), None, "denylist");
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 05a4d9ef..67aeb6ee 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -309,7 +309,14 @@ function captureTool(payload: Record<string, unknown>): { family: CaptureProtoco
// earlier in postHook), and context delivery (`fetchHandoff`) is a separate
// path that stays live.
function captureOwnedExternally(): boolean { const owner = typeof process === "undefined" ? undefined : process.env?.AI_MEMORY_CAPTURE_OWNER; return typeof owner === "string" && owner.trim() !== ""; }
-function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { if (captureOwnedExternally()) 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 }; }
+// Server profiles (`server = "<name>"`, #992) are routed only by the native
+// hook. Any marker up the tree that selects one makes this integration emit
+// nothing rather than deliver that repository's capture to the install default.
+// Mirrors the native walk: no payload cwd falls back to the process cwd; inside
+// 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 }; }
"##;
TEMPLATE.replace("__AI_MEMORY_CAPTURE_MODE__", capture_mode)
}
@@ -2377,6 +2384,20 @@ const inactive = capturePolicy(inactivePayload, "/no-marker");
check(inactive.disposition === "keep" && inactive.payload === inactivePayload && !inactive.protocol, "inactive-preserves-object");
const activeKeep = capturePolicy({{ tool: "bash", args: {{ command: privateBody }} }}, gatedCwd);
check(activeKeep.disposition === "keep" && activeKeep.protocol?.version === 1 && activeKeep.protocol.policy_state === "active", "active-keep-adds-protocol");
+// #992: only the native hook routes `server` profiles; these integrations
+// must drop rather than deliver a routed repository to the install default,
+// including under a nested marker that does not repeat the key.
+check(capturePolicy(bash("echo hi"), marker('server = "team-b"\n')).disposition === "drop", "server-routed-drops");
+check(capturePolicy(bash("echo hi"), marker("server = team-b\n")).disposition === "drop", "server-routed-bare-drops");
+check(capturePolicy(bash("echo hi"), marker('servers = "x"\n')).disposition === "keep", "servers-key-is-not-server");
+const routedRoot = join(markerRoot, "routed-repo");
+const routedChild = join(routedRoot, "child");
+mkdirSync(join(routedRoot, ".git"), {{ recursive: true }});
+mkdirSync(routedChild, {{ recursive: true }});
+writeFileSync(join(routedRoot, ".ai-memory.toml"), 'server = "team-b"\n');
+writeFileSync(join(routedChild, ".ai-memory.toml"), 'workspace = "child"\n');
+markerFixtures.set(routedChild, join(routedChild, ".ai-memory.toml"));
+check(capturePolicy(bash("echo hi"), routedChild).disposition === "drop", "server-routed-inherited-drops");
"#,
fixture = fixture,
policy = ts_capture_policy_v1("denylist"),