Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
refactor: clean up install integrations
AkitaOnRailsad1922ffc371
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bd62ee70..48855cae 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -44,6 +44,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0being parsed as column operators.- Gemini 2.5 Flash requests disable default dynamic thinking so hidden thoughttokens do not consume `maxOutputTokens` and truncate strict JSON responses.+- `install-mcp --client claude-code` now prints the direct-edit JSON path as+ `~/.claude.json`, matching the `--apply` path and `claude mcp add` behavior.## [0.1.3] - 2026-05-24diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 4173e86a..d80932c8 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -15,17 +15,16 @@//! and produces no backup.use std::fs;-use std::io::ErrorKind;use std::path::{Path, PathBuf};-use std::process::Command;use anyhow::{Context, Result};use crate::cli::{AgentChoice, InstallHooksArgs};use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json};+use crate::commands::openclaw_plugin;use crate::commands::render_shared::{CURSOR_PROFILE, GEMINI_PROFILE, build_claude_code_payload, build_codex_payload,- build_profile_payload, hook_script_for_current_platform,+ build_profile_payload, hook_script_for_current_platform, ts_string_literal,};use crate::config::Config;@@ -59,7 +58,7 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;apply_to_gemini_settings(&hooks_dir, &args.server_url, auth, &args)}- AgentChoice::Openclaw => apply_to_openclaw_plugin(&args.server_url, auth, &args),+ AgentChoice::Openclaw => openclaw_plugin::apply(&args.server_url, auth, &args),};}match args.agent {@@ -81,7 +80,10 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;render_agent("gemini-cli", &hooks_dir, &args.server_url, auth)}- AgentChoice::Openclaw => render_openclaw_plugin(&args.server_url, auth),+ AgentChoice::Openclaw => {+ openclaw_plugin::render(&args.server_url, auth);+ Ok(())+ }}}@@ -886,373 +888,6 @@ export default function AiMemoryExtension(api: any): void {{)}-const OPENCLAW_PLUGIN_ID: &str = "ai-memory";--fn apply_to_openclaw_plugin(- server_url: &str,- auth_token: Option<&str>,- args: &InstallHooksArgs,-) -> Result<()> {- let plugin_dir = resolve_openclaw_plugin_dir(args)?;- let outcomes = write_openclaw_plugin_package(&plugin_dir, server_url, auth_token)?;- for (path, outcome) in &outcomes {- println!(- "✓ {} {} ({})",- outcome.verb(),- path.display(),- match outcome {- ApplyOutcome::Created => "new file",- ApplyOutcome::Updated => "backup written next to it",- ApplyOutcome::NoOp => "already up to date",- }- );- }-- match install_openclaw_plugin(&plugin_dir)? {- OpenClawInstallStatus::Installed => {- println!();- println!("OpenClaw plugin installed from {}.", plugin_dir.display());- println!(- "If your OpenClaw gateway did not auto-restart, run `openclaw gateway restart`."- );- println!("Verify with `openclaw plugins inspect ai-memory --runtime --json`.");- }- OpenClawInstallStatus::CliMissing => {- println!();- println!("OpenClaw CLI not found on PATH; plugin package was written only.");- println!("Install it with:");- println!(- " openclaw plugins install --link {} --force",- plugin_dir.display()- );- println!(" openclaw gateway restart");- println!(" openclaw plugins inspect ai-memory --runtime --json");- }- }- Ok(())-}--fn render_openclaw_plugin(server_url: &str, auth_token: Option<&str>) -> Result<()> {- println!("# OpenClaw native plugin package");- println!("# Re-run with `--apply` to write the package and call:");- println!("# openclaw plugins install --link <package-dir> --force");- println!("# OpenClaw loads plugin code at gateway startup; restart if your");- println!("# managed gateway does not auto-restart after install.");- println!();- println!("## package.json");- println!("{}", openclaw_package_json());- println!("## openclaw.plugin.json");- println!("{}", openclaw_manifest_json());- println!("## index.ts");- println!("{}", build_openclaw_plugin(server_url, auth_token));- Ok(())-}--fn resolve_openclaw_plugin_dir(args: &InstallHooksArgs) -> Result<PathBuf> {- if let Some(path) = &args.config_file {- return Ok(path.clone());- }- Ok(dirs::data_local_dir()- .context("could not locate the user data-local directory")?- .join("ai-memory")- .join("openclaw-plugin"))-}--fn write_openclaw_plugin_package(- plugin_dir: &Path,- server_url: &str,- auth_token: Option<&str>,-) -> Result<Vec<(PathBuf, ApplyOutcome)>> {- let files = [- ("package.json", openclaw_package_json()),- ("openclaw.plugin.json", openclaw_manifest_json()),- ("index.ts", build_openclaw_plugin(server_url, auth_token)),- ];- let mut outcomes = Vec::with_capacity(files.len());- for (name, body) in files {- let path = plugin_dir.join(name);- let outcome = apply_atomic(&path, move |_existing| Ok(body.clone()))?;- outcomes.push((path, outcome));- }- Ok(outcomes)-}--enum OpenClawInstallStatus {- Installed,- CliMissing,-}--fn install_openclaw_plugin(plugin_dir: &Path) -> Result<OpenClawInstallStatus> {- let output = match Command::new("openclaw")- .args(["plugins", "install", "--link"])- .arg(plugin_dir)- .arg("--force")- .output()- {- Ok(output) => output,- Err(e) if e.kind() == ErrorKind::NotFound => return Ok(OpenClawInstallStatus::CliMissing),- Err(e) => return Err(e).context("running openclaw plugins install"),- };- if !output.status.success() {- anyhow::bail!(- "openclaw plugins install failed with status {}\nstdout:\n{}\nstderr:\n{}",- output.status,- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr)- );- }-- let enable = Command::new("openclaw")- .args(["plugins", "enable", OPENCLAW_PLUGIN_ID])- .output()- .context("running openclaw plugins enable")?;- if !enable.status.success() {- eprintln!(- "# warning: `openclaw plugins enable ai-memory` exited with {}\n# stdout:\n{}\n# stderr:\n{}",- enable.status,- String::from_utf8_lossy(&enable.stdout),- String::from_utf8_lossy(&enable.stderr)- );- }-- Ok(OpenClawInstallStatus::Installed)-}--fn openclaw_package_json() -> String {- serde_json::to_string_pretty(&serde_json::json!({- "name": "@ai-memory/openclaw-plugin",- "version": env!("CARGO_PKG_VERSION"),- "private": true,- "type": "module",- "openclaw": {- "extensions": ["./index.ts"]- }- }))- .expect("OpenClaw package metadata serializes")- + "\n"-}--fn openclaw_manifest_json() -> String {- serde_json::to_string_pretty(&serde_json::json!({- "id": OPENCLAW_PLUGIN_ID,- "name": "ai-memory",- "description": "Capture OpenClaw session lifecycle, tool use, compaction, and handoffs into ai-memory.",- "activation": {- "onCapabilities": ["hook"]- },- "configSchema": {- "type": "object",- "additionalProperties": false,- "properties": {}- }- }))- .expect("OpenClaw manifest serializes")- + "\n"-}--fn build_openclaw_plugin(server_url: &str, auth_token: Option<&str>) -> String {- let token_line = auth_token- .map(|t| format!("const TOKEN: string | null = {};\n", ts_string_literal(t)))- .unwrap_or_else(|| "const TOKEN: string | null = null;\n".to_string());- format!(- r#"// Auto-generated by `ai-memory install-hooks --agent openclaw --apply`.-// Edit by re-running the command, not by hand. install-hooks owns-// this local OpenClaw plugin package.--import {{ definePluginEntry }} from "openclaw/plugin-sdk/plugin-entry";--const SERVER = {server_literal}.replace(/\/+$/, "");-const AGENT = "openclaw";-{token_line}--function timeoutSignal(ms: number): AbortSignal | undefined {{- if (typeof AbortSignal === "undefined") return undefined;- const factory = (AbortSignal as unknown as {{ timeout?: (ms: number) => AbortSignal }}).timeout;- return factory ? factory(ms) : undefined;-}}--function authHeaders(): Record<string, string> {{- return TOKEN ? {{ Authorization: `Bearer ${{TOKEN}}` }} : {{}};-}}--function textFrom(value: unknown): string {{- if (value === null || value === undefined) return "";- if (typeof value === "string") return value;- if (Array.isArray(value)) return value.map(textFrom).filter(Boolean).join("\n\n").trim();- const obj = value as any;- if (typeof obj.text === "string") return obj.text;- if (typeof obj.content === "string") return obj.content;- if (typeof obj.prompt === "string") return obj.prompt;- try {{- return JSON.stringify(value);- }} catch (_e) {{- return String(value);- }}-}}--function sessionID(event: any, ctx: any): string | undefined {{- const value = ctx?.sessionId ?? ctx?.sessionID ?? ctx?.sessionKey ?? event?.sessionId ?? event?.sessionID ?? event?.sessionKey;- return typeof value === "string" && value.length > 0 ? value : undefined;-}}--function cwd(event: any, ctx: any): string | undefined {{- const value = ctx?.workspaceDir ?? ctx?.cwd ?? event?.cwd ?? event?.workspaceDir;- return typeof value === "string" && value.length > 0 ? value : undefined;-}}--function payload(event: any, ctx: any, extra: Record<string, unknown> = {{}}): Record<string, unknown> {{- return {{- sessionID: sessionID(event, ctx),- cwd: cwd(event, ctx),- agentID: ctx?.agentId,- runID: ctx?.runId ?? event?.runId,- jobID: ctx?.jobId,- ...extra,- }};-}}--const startedSessions = new Set<string>();-const handoffChecked = new Set<string>();-const preCompactLast = new Map<string, number>();--function rememberSession(event: any, ctx: any): void {{- const id = sessionID(event, ctx);- if (!id || startedSessions.has(id)) return;- startedSessions.add(id);- postHook("session-start", payload(event, ctx, {{ reason: event?.reason }}));-}}--function postPreCompact(event: any, ctx: any): void {{- rememberSession(event, ctx);- const key = sessionID(event, ctx) || "unknown";- const now = Date.now();- const last = preCompactLast.get(key) ?? 0;- if (now - last < 1000) return;- preCompactLast.set(key, now);- postHook("pre-compact", payload(event, ctx, {{ reason: event?.reason }}));-}}--function postHook(eventName: string, body: Record<string, unknown>): void {{- const url = new URL(`${{SERVER}}/hook`);- url.searchParams.set("event", eventName);- url.searchParams.set("agent", AGENT);- try {{- void fetch(url, {{- method: "POST",- headers: {{ "Content-Type": "application/json", ...authHeaders() }},- body: JSON.stringify(body),- signal: timeoutSignal(500),- }}).catch(() => undefined);- }} catch (_e) {{- // Fire-and-forget. Hooks must never block OpenClaw.- }}-}}--async function fetchHandoff(event: any, ctx: any): Promise<string | undefined> {{- const currentCwd = cwd(event, ctx);- if (!currentCwd) return undefined;- const url = new URL(`${{SERVER}}/handoff`);- url.searchParams.set("agent", AGENT);- url.searchParams.set("cwd", currentCwd);- try {{- const response = await fetch(url, {{- headers: authHeaders(),- signal: timeoutSignal(1000),- }});- const text = (await response.text()).trim();- return text.length > 0 ? text : undefined;- }} catch (_e) {{- return undefined;- }}-}}--export default definePluginEntry({{- id: "ai-memory",- name: "ai-memory",- description: "Capture OpenClaw lifecycle events into ai-memory.",- register(api) {{- api.on("session_start", (event: any, ctx: any) => {{- rememberSession(event, ctx);- }});-- api.on("session_end", (event: any, ctx: any) => {{- rememberSession(event, ctx);- postHook("session-end", payload(event, ctx, {{ reason: event?.reason }}));- }});-- api.on("before_prompt_build", async (event: any, ctx: any) => {{- rememberSession(event, ctx);- postHook("user-prompt", payload(event, ctx, {{- prompt: textFrom(event?.prompt ?? event?.userPrompt ?? event?.message ?? event?.messages?.at?.(-1)),- }}));-- const id = sessionID(event, ctx);- if (!id || handoffChecked.has(id)) return;- handoffChecked.add(id);- const handoff = await fetchHandoff(event, ctx);- return handoff ? {{ prependContext: handoff }} : undefined;- }});-- api.on("before_tool_call", (event: any, ctx: any) => {{- rememberSession(event, ctx);- postHook("pre-tool-use", payload(event, ctx, {{- tool: event?.toolName,- toolKind: event?.toolKind,- callID: event?.toolCallId,- args: event?.params,- }}));- }});-- api.on("after_tool_call", (event: any, ctx: any) => {{- rememberSession(event, ctx);- postHook("post-tool-use", payload(event, ctx, {{- tool: event?.toolName,- toolKind: event?.toolKind,- callID: event?.toolCallId,- args: event?.params,- output: textFrom(event?.result ?? event?.output ?? event?.content),- error: event?.error,- durationMs: event?.durationMs,- }}));- }});-- api.on("before_compaction", (event: any, ctx: any) => {{- postPreCompact(event, ctx);- }});-- api.on("agent_end", (event: any, ctx: any) => {{- rememberSession(event, ctx);- postHook("stop", payload(event, ctx, {{ success: event?.success }}));- }});- }},-}});-"#,- server_literal = ts_string_literal(server_url),- token_line = token_line,- )-}--/// Emit a TypeScript string literal containing `s`. Escapes-/// backslashes, double quotes, and newlines. Sufficient for the-/// URL + auth-token + path strings we embed; the generated file is-/// not user-edited.-fn ts_string_literal(s: &str) -> String {- let mut out = String::with_capacity(s.len() + 2);- out.push('"');- for ch in s.chars() {- match ch {- '\\' => out.push_str("\\\\"),- '"' => out.push_str("\\\""),- '\n' => out.push_str("\\n"),- '\r' => out.push_str("\\r"),- '\t' => out.push_str("\\t"),- c => out.push(c),- }- }- out.push('"');- out-}-fn render_agent(label: &str,hooks_dir: &Path,@@ -1419,12 +1054,9 @@ fn resolve_hooks_dir(explicit: Option<&Path>, agent: AgentChoice) -> Result<PathAgentChoice::Codex => "codex",AgentChoice::Cursor => "cursor",AgentChoice::GeminiCli => "gemini-cli",- AgentChoice::OpenCode => "opencode",- // OMP/OpenClaw use generated TypeScript integrations → no script dir- // needed. Return a sentinel that's never touched; the caller's apply- // path short-circuits before any filesystem use.- AgentChoice::Omp => return Ok(PathBuf::from("/dev/null")),- AgentChoice::Openclaw => return Ok(PathBuf::from("/dev/null")),+ AgentChoice::OpenCode | AgentChoice::Omp | AgentChoice::Openclaw => {+ anyhow::bail!("{agent:?} uses a generated integration, not a hook script directory")+ }};if let Some(p) = explicit {let path = p.join(sub);@@ -1715,54 +1347,6 @@ mod tests {);}- // ----------------------------------------------------------------- // OpenClaw tests- // ------------------------------------------------------------------ #[test]- fn openclaw_plugin_package_has_manifest_and_hook_entrypoint() {- let package = openclaw_package_json();- let manifest = openclaw_manifest_json();- let plugin = build_openclaw_plugin("http://127.0.0.1:49374", Some("tok"));-- assert!(package.contains(r#""extensions""#));- assert!(package.contains(r#""./index.ts""#));- assert!(manifest.contains(r#""id": "ai-memory""#));- assert!(manifest.contains(r#""onCapabilities""#));- assert!(manifest.contains(r#""hook""#));- assert!(plugin.contains("definePluginEntry"));- assert!(plugin.contains("api.on(\"session_start\""));- assert!(plugin.contains("api.on(\"session_end\""));- assert!(plugin.contains("api.on(\"before_prompt_build\""));- assert!(plugin.contains("api.on(\"before_tool_call\""));- assert!(plugin.contains("api.on(\"after_tool_call\""));- assert!(plugin.contains("api.on(\"before_compaction\""));- assert!(plugin.contains("api.on(\"agent_end\""));- assert!(plugin.contains("postHook(\"session-start\""));- assert!(plugin.contains("postHook(\"user-prompt\""));- assert!(plugin.contains("fetchHandoff"));- assert!(plugin.contains("prependContext: handoff"));- assert!(plugin.contains("Bearer ${TOKEN}"));- assert!(plugin.contains("tok"));- }-- #[test]- fn openclaw_plugin_package_writes_all_required_files() {- let tmp = TempDir::new().unwrap();- let outcomes =- write_openclaw_plugin_package(tmp.path(), "http://127.0.0.1:49374", None).unwrap();-- assert_eq!(outcomes.len(), 3);- assert!(tmp.path().join("package.json").is_file());- assert!(tmp.path().join("openclaw.plugin.json").is_file());- assert!(tmp.path().join("index.ts").is_file());- assert!(- fs::read_to_string(tmp.path().join("index.ts"))- .unwrap()- .contains("const TOKEN: string | null = null;")- );- }-#[cfg(unix)]#[test]fn curl_installer_accepts_generated_integration_agents() {diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 88db8bac..1d8eb9e9 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -24,6 +24,15 @@ use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json, mutuse crate::commands::render_shared::bearer_header_value;use crate::config::Config;+const GEMINI_MCP_TIMEOUT_MS: u64 = 5000;++#[derive(Clone, Copy)]+enum JsonMcpLocation {+ RootMcpServers,+ RootMcp,+ NestedMcpServers,+}+/// Run the `install-mcp` subcommand.////// # Errors@@ -107,54 +116,12 @@ fn resolve_config_file(args: &InstallMcpArgs) -> Result<PathBuf> {fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {let path = resolve_config_file(args)?;let outcome = match args.client {- McpClient::ClaudeCode- | McpClient::ClaudeDesktop- | McpClient::Cursor- | McpClient::GeminiCli- | McpClient::Pi => apply_atomic(&path, |existing| {- mutate_json(existing, |root| {- let entry = build_mcp_entry(args)?;- let servers = root- .entry("mcpServers")- .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))- .as_object_mut()- .context("`mcpServers` is present but not an object")?;- servers.insert(args.name.clone(), entry);- Ok(())- })- })?,- McpClient::OpenCode => apply_atomic(&path, |existing| {- mutate_json(existing, |root| {- let entry = build_mcp_entry_opencode(args)?;- let mcp = root- .entry("mcp")- .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))- .as_object_mut()- .context("`mcp` is present but not an object")?;- mcp.insert(args.name.clone(), entry);- Ok(())- })- })?,- McpClient::Openclaw => apply_atomic(&path, |existing| {- mutate_json(existing, |root| {- let entry = build_mcp_entry_openclaw(args)?;- let mcp = root- .entry("mcp")- .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))- .as_object_mut()- .context("`mcp` is present but not an object")?;- let servers = mcp- .entry("servers")- .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))- .as_object_mut()- .context("`mcp.servers` is present but not an object")?;- servers.insert(args.name.clone(), entry);- Ok(())- })- })?,McpClient::Codex => apply_atomic(&path, |existing| {mutate_toml(existing, |doc| codex_upsert_mcp_server(doc, args))})?,+ _ => apply_atomic(&path, |existing| {+ mutate_json(existing, |root| upsert_json_mcp_entry(root, args))+ })?,};println!("✓ {} {} ({})",@@ -169,6 +136,84 @@ fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {Ok(())}+fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {+ match client {+ McpClient::ClaudeCode+ | McpClient::ClaudeDesktop+ | McpClient::Cursor+ | McpClient::GeminiCli+ | McpClient::Pi => Some(JsonMcpLocation::RootMcpServers),+ McpClient::OpenCode => Some(JsonMcpLocation::RootMcp),+ McpClient::Openclaw => Some(JsonMcpLocation::NestedMcpServers),+ McpClient::Codex => None,+ }+}++fn build_json_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {+ match args.client {+ McpClient::OpenCode => build_mcp_entry_opencode(args),+ McpClient::Openclaw => build_mcp_entry_openclaw(args),+ McpClient::Codex => bail!("internal: Codex MCP config is TOML, not JSON"),+ _ => build_mcp_entry(args),+ }+}++fn upsert_json_mcp_entry(+ root: &mut serde_json::Map<String, serde_json::Value>,+ args: &InstallMcpArgs,+) -> Result<()> {+ let entry = build_json_mcp_entry(args)?;+ match json_mcp_location(args.client).context("internal: unsupported JSON MCP client")? {+ JsonMcpLocation::RootMcpServers => {+ let servers = root+ .entry("mcpServers")+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))+ .as_object_mut()+ .context("`mcpServers` is present but not an object")?;+ servers.insert(args.name.clone(), entry);+ }+ JsonMcpLocation::RootMcp => {+ let mcp = root+ .entry("mcp")+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))+ .as_object_mut()+ .context("`mcp` is present but not an object")?;+ mcp.insert(args.name.clone(), entry);+ }+ JsonMcpLocation::NestedMcpServers => {+ let mcp = root+ .entry("mcp")+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))+ .as_object_mut()+ .context("`mcp` is present but not an object")?;+ let servers = mcp+ .entry("servers")+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))+ .as_object_mut()+ .context("`mcp.servers` is present but not an object")?;+ servers.insert(args.name.clone(), entry);+ }+ }+ Ok(())+}++fn render_json_mcp_fragment(args: &InstallMcpArgs) -> Result<String> {+ let entry = build_json_mcp_entry(args)?;+ let fragment =+ match json_mcp_location(args.client).context("internal: unsupported JSON MCP client")? {+ JsonMcpLocation::RootMcpServers => json!({+ "mcpServers": { args.name.as_str(): entry }+ }),+ JsonMcpLocation::RootMcp => json!({+ "mcp": { args.name.as_str(): entry }+ }),+ JsonMcpLocation::NestedMcpServers => json!({+ "mcp": { "servers": { args.name.as_str(): entry } }+ }),+ };+ Ok(serde_json::to_string_pretty(&fragment)?)+}+/// JSON entry shape used by Claude Code, Claude Desktop, Cursor, and/// Gemini CLI — they all accept `mcpServers.<name>` with `url` or/// `httpUrl` plus optional `headers`. Returns the per-client variant.@@ -203,7 +248,7 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {}McpClient::GeminiCli => {entry.insert("httpUrl".into(), json!(args.server_url));- entry.insert("timeout".into(), json!(5000));+ entry.insert("timeout".into(), json!(GEMINI_MCP_TIMEOUT_MS));if let Some(b) = &bearer {entry.insert("headers".into(), json!({"Authorization": b}));}@@ -355,23 +400,14 @@ fn render_claude_code(args: &InstallMcpArgs) -> Result<String> {url = args.server_url,)};- let mut entry = serde_json::Map::new();- entry.insert("type".into(), json!("http"));- entry.insert("url".into(), json!(args.server_url));- if let Some(b) = &bearer {- entry.insert("headers".into(), json!({"Authorization": b}));- }- let snippet = serde_json::to_string_pretty(&json!({- "mcpServers": { args.name.as_str(): entry }- }))?;+ let snippet = render_json_mcp_fragment(args)?;Ok(format!("# Claude Code — register the MCP server\n\#\n\# Recommended (one-shot CLI):\n\{cli_line}\n\#\n\- # Equivalent JSON if you'd rather edit settings directly\n\- # (~/.claude/settings.json):\n\+ # Equivalent JSON if you'd rather edit ~/.claude.json directly:\n\{snippet}\n"))}@@ -414,28 +450,14 @@ fn render_codex(args: &InstallMcpArgs) -> String {}fn render_opencode(args: &InstallMcpArgs) -> Result<String> {- let mut entry = serde_json::Map::new();- entry.insert("type".into(), json!("remote"));- entry.insert("url".into(), json!(args.server_url));- entry.insert("enabled".into(), json!(true));- if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {- entry.insert("headers".into(), json!({"Authorization": b}));- }Ok(format!("# OpenCode — add to ~/.config/opencode/opencode.json under \"mcp\":\n\{snippet}\n",- snippet = serde_json::to_string_pretty(&json!({- "mcp": { args.name.as_str(): entry }- }))?,+ snippet = render_json_mcp_fragment(args)?,))}fn render_cursor(args: &InstallMcpArgs) -> Result<String> {- let mut entry = serde_json::Map::new();- entry.insert("url".into(), json!(args.server_url));- if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {- entry.insert("headers".into(), json!({"Authorization": b}));- }Ok(format!("# Cursor — write to one of:\n\# - ~/.cursor/mcp.json (global, all projects)\n\@@ -446,9 +468,7 @@ fn render_cursor(args: &InstallMcpArgs) -> Result<String> {# adding a new entry; live reload landed in recent builds but\n\# is still flaky.\n\{snippet}\n",- snippet = serde_json::to_string_pretty(&json!({- "mcpServers": { args.name.as_str(): entry }- }))?,+ snippet = render_json_mcp_fragment(args)?,))}@@ -457,16 +477,6 @@ fn render_claude_desktop(args: &InstallMcpArgs) -> Result<String> {// through Claude Desktop's stdio-only config. Put the Bearer value// in env so Windows subprocess parsing never has to split a value// containing a space.- let bearer = bearer_header_value(args.auth_token.as_deref());- let mut cmd_args = vec![json!("-y"), json!("mcp-remote"), json!(args.server_url)];- let mut server = serde_json::Map::new();- if let Some(b) = &bearer {- cmd_args.push(json!("--header"));- cmd_args.push(json!("Authorization:${AI_MEMORY_AUTH_HEADER}"));- server.insert("env".into(), json!({"AI_MEMORY_AUTH_HEADER": b}));- }- server.insert("command".into(), json!("npx"));- server.insert("args".into(), serde_json::Value::Array(cmd_args));Ok(format!("# Claude Desktop — write to claude_desktop_config.json:\n\# - macOS: ~/Library/Application Support/Claude/claude_desktop_config.json\n\@@ -480,58 +490,33 @@ fn render_claude_desktop(args: &InstallMcpArgs) -> Result<String> {# After editing, fully quit + relaunch Claude Desktop; \"Check for\n\# Updates\" is not enough.\n\{snippet}\n",- snippet = serde_json::to_string_pretty(&json!({- "mcpServers": { args.name.as_str(): server }- }))?,+ snippet = render_json_mcp_fragment(args)?,))}fn render_gemini_cli(args: &InstallMcpArgs) -> Result<String> {- let mut entry = serde_json::Map::new();- entry.insert("httpUrl".into(), json!(args.server_url));- entry.insert("timeout".into(), json!(5000));- if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {- entry.insert("headers".into(), json!({"Authorization": b}));- }Ok(format!("# Gemini CLI — merge into ~/.gemini/settings.json:\n\#\n\# Gemini CLI uses `httpUrl` (not `url`) for streamable-HTTP\n\# endpoints. The `timeout` is in milliseconds.\n\{snippet}\n",- snippet = serde_json::to_string_pretty(&json!({- "mcpServers": { args.name.as_str(): entry }- }))?,+ snippet = render_json_mcp_fragment(args)?,))}fn render_openclaw(args: &InstallMcpArgs) -> Result<String> {- let mut entry = serde_json::Map::new();- entry.insert("url".into(), json!(args.server_url));- entry.insert("transport".into(), json!("streamable-http"));- if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {- entry.insert("headers".into(), json!({"Authorization": b}));- }Ok(format!("# OpenClaw — merge into ~/.openclaw/config.json:\n\#\n\# OpenClaw distinguishes transports explicitly. Use\n\# \"transport\": \"streamable-http\" for ai-memory's HTTP endpoint.\n\{snippet}\n",- snippet = serde_json::to_string_pretty(&json!({- "mcp": { "servers": { args.name.as_str(): entry } }- }))?,+ snippet = render_json_mcp_fragment(args)?,))}fn render_pi(args: &InstallMcpArgs) -> Result<String> {- let mut entry = serde_json::Map::new();- entry.insert("type".into(), json!("http"));- entry.insert("url".into(), json!(args.server_url));- entry.insert("enabled".into(), json!(true));- if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {- entry.insert("headers".into(), json!({"Authorization": b}));- }Ok(format!("# Oh My Pi / OMP — merge into ~/.omp/agent/mcp.json:\n\#\n\@@ -539,9 +524,7 @@ fn render_pi(args: &InstallMcpArgs) -> Result<String> {# `.omp` config directories; `pi` is accepted here as the compatible\n\# client name. Restart `omp` after changing MCP config.\n\{snippet}\n",- snippet = serde_json::to_string_pretty(&json!({- "mcpServers": { args.name.as_str(): entry }- }))?,+ snippet = render_json_mcp_fragment(args)?,))}diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 08447fc0..e16a3afe 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -17,6 +17,7 @@ pub mod install_instructions;pub mod install_mcp;pub mod lint;pub mod llm_test;+pub mod openclaw_plugin;pub mod purge_project;pub mod rename_project;pub mod render_shared;diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rsnew file mode 100644index 00000000..dec4174e--- /dev/null+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs@@ -0,0 +1,416 @@+//! Generated OpenClaw lifecycle plugin support.++use std::io::ErrorKind;+use std::path::{Path, PathBuf};+use std::process::Command;++use anyhow::{Context, Result};++use crate::cli::InstallHooksArgs;+use crate::commands::apply_shared::{ApplyOutcome, apply_atomic};+use crate::commands::render_shared::ts_string_literal;++const PLUGIN_ID: &str = "ai-memory";+const PACKAGE_NAME: &str = "@ai-memory/openclaw-plugin";+const PACKAGE_JSON: &str = "package.json";+const MANIFEST_JSON: &str = "openclaw.plugin.json";+const ENTRYPOINT_TS: &str = "index.ts";+const OPENCLAW_BIN: &str = "openclaw";++/// Write and install the generated OpenClaw plugin package.+pub(crate) fn apply(+ server_url: &str,+ auth_token: Option<&str>,+ args: &InstallHooksArgs,+) -> Result<()> {+ let plugin_dir = resolve_plugin_dir(args)?;+ let outcomes = write_package(&plugin_dir, server_url, auth_token)?;+ for (path, outcome) in &outcomes {+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ outcome_detail(*outcome)+ );+ }++ match install_plugin(&plugin_dir)? {+ InstallStatus::Installed => {+ println!();+ println!("OpenClaw plugin installed from {}.", plugin_dir.display());+ println!(+ "If your OpenClaw gateway did not auto-restart, run `openclaw gateway restart`."+ );+ println!("Verify with `openclaw plugins inspect ai-memory --runtime --json`.");+ }+ InstallStatus::CliMissing => {+ println!();+ println!("OpenClaw CLI not found on PATH; plugin package was written only.");+ println!("Install it with:");+ println!(+ " openclaw plugins install --link {} --force",+ plugin_dir.display()+ );+ println!(" openclaw gateway restart");+ println!(" openclaw plugins inspect ai-memory --runtime --json");+ }+ }+ Ok(())+}++/// Print the generated package for manual installation.+pub(crate) fn render(server_url: &str, auth_token: Option<&str>) {+ println!("# OpenClaw native plugin package");+ println!("# Re-run with `--apply` to write the package and call:");+ println!("# openclaw plugins install --link <package-dir> --force");+ println!("# OpenClaw loads plugin code at gateway startup; restart if your");+ println!("# managed gateway does not auto-restart after install.");+ println!();+ println!("## {PACKAGE_JSON}");+ println!("{}", package_json());+ println!("## {MANIFEST_JSON}");+ println!("{}", manifest_json());+ println!("## {ENTRYPOINT_TS}");+ println!("{}", build_plugin(server_url, auth_token));+}++fn outcome_detail(outcome: ApplyOutcome) -> &'static str {+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+}++fn resolve_plugin_dir(args: &InstallHooksArgs) -> Result<PathBuf> {+ if let Some(path) = &args.config_file {+ return Ok(path.clone());+ }+ Ok(dirs::data_local_dir()+ .context("could not locate the user data-local directory")?+ .join("ai-memory")+ .join("openclaw-plugin"))+}++fn write_package(+ plugin_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+) -> Result<Vec<(PathBuf, ApplyOutcome)>> {+ let files = [+ (PACKAGE_JSON, package_json()),+ (MANIFEST_JSON, manifest_json()),+ (ENTRYPOINT_TS, build_plugin(server_url, auth_token)),+ ];+ let mut outcomes = Vec::with_capacity(files.len());+ for (name, body) in files {+ let path = plugin_dir.join(name);+ let outcome = apply_atomic(&path, move |_existing| Ok(body.clone()))?;+ outcomes.push((path, outcome));+ }+ Ok(outcomes)+}++enum InstallStatus {+ Installed,+ CliMissing,+}++fn install_plugin(plugin_dir: &Path) -> Result<InstallStatus> {+ let output = match Command::new(OPENCLAW_BIN)+ .args(["plugins", "install", "--link"])+ .arg(plugin_dir)+ .arg("--force")+ .output()+ {+ Ok(output) => output,+ Err(e) if e.kind() == ErrorKind::NotFound => return Ok(InstallStatus::CliMissing),+ Err(e) => return Err(e).context("running openclaw plugins install"),+ };+ if !output.status.success() {+ anyhow::bail!(+ "openclaw plugins install failed with status {}\nstdout:\n{}\nstderr:\n{}",+ output.status,+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ }++ let enable = Command::new(OPENCLAW_BIN)+ .args(["plugins", "enable", PLUGIN_ID])+ .output()+ .context("running openclaw plugins enable")?;+ if !enable.status.success() {+ eprintln!(+ "# warning: `openclaw plugins enable ai-memory` exited with {}\n# stdout:\n{}\n# stderr:\n{}",+ enable.status,+ String::from_utf8_lossy(&enable.stdout),+ String::from_utf8_lossy(&enable.stderr)+ );+ }++ Ok(InstallStatus::Installed)+}++fn package_json() -> String {+ serde_json::to_string_pretty(&serde_json::json!({+ "name": PACKAGE_NAME,+ "version": env!("CARGO_PKG_VERSION"),+ "private": true,+ "type": "module",+ "openclaw": {+ "extensions": [format!("./{ENTRYPOINT_TS}")]+ }+ }))+ .expect("OpenClaw package metadata serializes")+ + "\n"+}++fn manifest_json() -> String {+ serde_json::to_string_pretty(&serde_json::json!({+ "id": PLUGIN_ID,+ "name": "ai-memory",+ "description": "Capture OpenClaw session lifecycle, tool use, compaction, and handoffs into ai-memory.",+ "activation": {+ "onCapabilities": ["hook"]+ },+ "configSchema": {+ "type": "object",+ "additionalProperties": false,+ "properties": {}+ }+ }))+ .expect("OpenClaw manifest serializes")+ + "\n"+}++fn build_plugin(server_url: &str, auth_token: Option<&str>) -> String {+ let token_line = auth_token+ .map(|t| format!("const TOKEN: string | null = {};\n", ts_string_literal(t)))+ .unwrap_or_else(|| "const TOKEN: string | null = null;\n".to_string());+ format!(+ r#"// Auto-generated by `ai-memory install-hooks --agent openclaw --apply`.+// Edit by re-running the command, not by hand. install-hooks owns+// this local OpenClaw plugin package.++import {{ definePluginEntry }} from "openclaw/plugin-sdk/plugin-entry";++const SERVER = {server_literal}.replace(/\/+$/, "");+const AGENT = "openclaw";+{token_line}++function timeoutSignal(ms: number): AbortSignal | undefined {{+ if (typeof AbortSignal === "undefined") return undefined;+ const factory = (AbortSignal as unknown as {{ timeout?: (ms: number) => AbortSignal }}).timeout;+ return factory ? factory(ms) : undefined;+}}++function authHeaders(): Record<string, string> {{+ return TOKEN ? {{ Authorization: `Bearer ${{TOKEN}}` }} : {{}};+}}++function textFrom(value: unknown): string {{+ if (value === null || value === undefined) return "";+ if (typeof value === "string") return value;+ if (Array.isArray(value)) return value.map(textFrom).filter(Boolean).join("\n\n").trim();+ const obj = value as any;+ if (typeof obj.text === "string") return obj.text;+ if (typeof obj.content === "string") return obj.content;+ if (typeof obj.prompt === "string") return obj.prompt;+ try {{+ return JSON.stringify(value);+ }} catch (_e) {{+ return String(value);+ }}+}}++function sessionID(event: any, ctx: any): string | undefined {{+ const value = ctx?.sessionId ?? ctx?.sessionID ?? ctx?.sessionKey ?? event?.sessionId ?? event?.sessionID ?? event?.sessionKey;+ return typeof value === "string" && value.length > 0 ? value : undefined;+}}++function cwd(event: any, ctx: any): string | undefined {{+ const value = ctx?.workspaceDir ?? ctx?.cwd ?? event?.cwd ?? event?.workspaceDir;+ return typeof value === "string" && value.length > 0 ? value : undefined;+}}++function payload(event: any, ctx: any, extra: Record<string, unknown> = {{}}): Record<string, unknown> {{+ return {{+ sessionID: sessionID(event, ctx),+ cwd: cwd(event, ctx),+ agentID: ctx?.agentId,+ runID: ctx?.runId ?? event?.runId,+ jobID: ctx?.jobId,+ ...extra,+ }};+}}++const startedSessions = new Set<string>();+const handoffChecked = new Set<string>();+const preCompactLast = new Map<string, number>();++function rememberSession(event: any, ctx: any): void {{+ const id = sessionID(event, ctx);+ if (!id || startedSessions.has(id)) return;+ startedSessions.add(id);+ postHook("session-start", payload(event, ctx, {{ reason: event?.reason }}));+}}++function postPreCompact(event: any, ctx: any): void {{+ rememberSession(event, ctx);+ const key = sessionID(event, ctx) || "unknown";+ const now = Date.now();+ const last = preCompactLast.get(key) ?? 0;+ if (now - last < 1000) return;+ preCompactLast.set(key, now);+ postHook("pre-compact", payload(event, ctx, {{ reason: event?.reason }}));+}}++function postHook(eventName: string, body: Record<string, unknown>): void {{+ const url = new URL(`${{SERVER}}/hook`);+ url.searchParams.set("event", eventName);+ url.searchParams.set("agent", AGENT);+ try {{+ void fetch(url, {{+ method: "POST",+ headers: {{ "Content-Type": "application/json", ...authHeaders() }},+ body: JSON.stringify(body),+ signal: timeoutSignal(500),+ }}).catch(() => undefined);+ }} catch (_e) {{+ // Fire-and-forget. Hooks must never block OpenClaw.+ }}+}}++async function fetchHandoff(event: any, ctx: any): Promise<string | undefined> {{+ const currentCwd = cwd(event, ctx);+ if (!currentCwd) return undefined;+ const url = new URL(`${{SERVER}}/handoff`);+ url.searchParams.set("agent", AGENT);+ url.searchParams.set("cwd", currentCwd);+ try {{+ const response = await fetch(url, {{+ headers: authHeaders(),+ signal: timeoutSignal(1000),+ }});+ const text = (await response.text()).trim();+ return text.length > 0 ? text : undefined;+ }} catch (_e) {{+ return undefined;+ }}+}}++export default definePluginEntry({{+ id: "ai-memory",+ name: "ai-memory",+ description: "Capture OpenClaw lifecycle events into ai-memory.",+ register(api) {{+ api.on("session_start", (event: any, ctx: any) => {{+ rememberSession(event, ctx);+ }});++ api.on("session_end", (event: any, ctx: any) => {{+ rememberSession(event, ctx);+ postHook("session-end", payload(event, ctx, {{ reason: event?.reason }}));+ }});++ api.on("before_prompt_build", async (event: any, ctx: any) => {{+ rememberSession(event, ctx);+ postHook("user-prompt", payload(event, ctx, {{+ prompt: textFrom(event?.prompt ?? event?.userPrompt ?? event?.message ?? event?.messages?.at?.(-1)),+ }}));++ const id = sessionID(event, ctx);+ if (!id || handoffChecked.has(id)) return;+ handoffChecked.add(id);+ const handoff = await fetchHandoff(event, ctx);+ return handoff ? {{ prependContext: handoff }} : undefined;+ }});++ api.on("before_tool_call", (event: any, ctx: any) => {{+ rememberSession(event, ctx);+ postHook("pre-tool-use", payload(event, ctx, {{+ tool: event?.toolName,+ toolKind: event?.toolKind,+ callID: event?.toolCallId,+ args: event?.params,+ }}));+ }});++ api.on("after_tool_call", (event: any, ctx: any) => {{+ rememberSession(event, ctx);+ postHook("post-tool-use", payload(event, ctx, {{+ tool: event?.toolName,+ toolKind: event?.toolKind,+ callID: event?.toolCallId,+ args: event?.params,+ output: textFrom(event?.result ?? event?.output ?? event?.content),+ error: event?.error,+ durationMs: event?.durationMs,+ }}));+ }});++ api.on("before_compaction", (event: any, ctx: any) => {{+ postPreCompact(event, ctx);+ }});++ api.on("agent_end", (event: any, ctx: any) => {{+ rememberSession(event, ctx);+ postHook("stop", payload(event, ctx, {{ success: event?.success }}));+ }});+ }},+}});+"#,+ server_literal = ts_string_literal(server_url),+ token_line = token_line,+ )+}++#[cfg(test)]+mod tests {+ use super::*;+ use tempfile::TempDir;++ #[test]+ fn package_has_manifest_and_hook_entrypoint() {+ let package = package_json();+ let manifest = manifest_json();+ let plugin = build_plugin("http://127.0.0.1:49374", Some("tok"));++ assert!(package.contains(r#""extensions""#));+ assert!(package.contains(r#""./index.ts""#));+ assert!(manifest.contains(r#""id": "ai-memory""#));+ assert!(manifest.contains(r#""onCapabilities""#));+ assert!(manifest.contains(r#""hook""#));+ assert!(plugin.contains("definePluginEntry"));+ assert!(plugin.contains("api.on(\"session_start\""));+ assert!(plugin.contains("api.on(\"session_end\""));+ assert!(plugin.contains("api.on(\"before_prompt_build\""));+ assert!(plugin.contains("api.on(\"before_tool_call\""));+ assert!(plugin.contains("api.on(\"after_tool_call\""));+ assert!(plugin.contains("api.on(\"before_compaction\""));+ assert!(plugin.contains("api.on(\"agent_end\""));+ assert!(plugin.contains("postHook(\"session-start\""));+ assert!(plugin.contains("postHook(\"user-prompt\""));+ assert!(plugin.contains("fetchHandoff"));+ assert!(plugin.contains("prependContext: handoff"));+ assert!(plugin.contains("Bearer ${TOKEN}"));+ assert!(plugin.contains("tok"));+ }++ #[test]+ fn package_writes_all_required_files() {+ let tmp = TempDir::new().unwrap();+ let outcomes = write_package(tmp.path(), "http://127.0.0.1:49374", None).unwrap();++ assert_eq!(outcomes.len(), 3);+ assert!(tmp.path().join(PACKAGE_JSON).is_file());+ assert!(tmp.path().join(MANIFEST_JSON).is_file());+ assert!(tmp.path().join(ENTRYPOINT_TS).is_file());+ assert!(+ std::fs::read_to_string(tmp.path().join(ENTRYPOINT_TS))+ .unwrap()+ .contains("const TOKEN: string | null = null;")+ );+ }+}diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 1a899e5a..03048d12 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -52,6 +52,28 @@ pub(crate) fn bearer_header_value(token: Option<&str>) -> Option<String> {token.map(|t| format!("Bearer {t}"))}+/// Emit a TypeScript string literal containing `s`. Escapes+/// backslashes, double quotes, and common control characters. This is+/// sufficient for URL, auth-token, and path strings embedded into+/// generated TypeScript integrations.+#[must_use]+pub(crate) fn ts_string_literal(s: &str) -> String {+ let mut out = String::with_capacity(s.len() + 2);+ out.push('"');+ for ch in s.chars() {+ match ch {+ '\\' => out.push_str("\\\\"),+ '"' => out.push_str("\\\""),+ '\n' => out.push_str("\\n"),+ '\r' => out.push_str("\\r"),+ '\t' => out.push_str("\\t"),+ c => out.push(c),+ }+ }+ out.push('"');+ out+}+/// Build the Claude Code `settings.json` fragment that wires the/// seven hooks. Used by both:/// - `install-hooks --agent claude-code` (script paths arediff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 4233f1b9..09426643 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -110,6 +110,14 @@ impl PagePath {"leading slash: {raw}")));}+ if raw.len() >= 3 {+ let bytes = raw.as_bytes();+ if bytes[1] == b':' && bytes[2] == b'/' && bytes[0].is_ascii_alphabetic() {+ return Err(MemoryError::InvalidPagePath(format!(+ "windows drive prefix in {raw}"+ )));+ }+ }if raw.contains('\\') {return Err(MemoryError::InvalidPagePath(format!("backslash separator in {raw}"@@ -200,6 +208,24 @@ impl AgentKind {Self::Other => "other",}}++ /// Parse a known wire string or common alias. Unknown values map+ /// to [`AgentKind::Other`], which keeps hook ingestion tolerant of+ /// typos or future agents.+ #[must_use]+ pub fn from_wire(s: &str) -> Self {+ match s {+ "claude-code" | "claude_code" | "claude" => Self::ClaudeCode,+ "codex" => Self::Codex,+ "open-code" | "opencode" => Self::OpenCode,+ "cursor" => Self::Cursor,+ "gemini-cli" | "gemini" => Self::GeminiCli,+ "claude-desktop" | "claude_desktop" => Self::ClaudeDesktop,+ "openclaw" | "open-claw" => Self::OpenClaw,+ "omp" | "pi" | "oh-my-pi" => Self::Omp,+ _ => Self::Other,+ }+ }}#[cfg(test)]@@ -231,6 +257,7 @@ mod tests {fn page_path_rejects_backslashes_and_windows_prefixes() {assert!(PagePath::new(r"notes\secret.md").is_err());assert!(PagePath::new(r"C:\Users\me\secret.md").is_err());+ assert!(PagePath::new("C:/Users/me/secret.md").is_err());}#[test]diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 56bd21f9..aa5ce249 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -105,17 +105,7 @@ impl HookEvent {/// [`AgentKind::Other`].#[must_use]pub fn parse_agent(s: &str) -> AgentKind {- match s {- "claude-code" | "claude_code" | "claude" => AgentKind::ClaudeCode,- "codex" => AgentKind::Codex,- "open-code" | "opencode" => AgentKind::OpenCode,- "cursor" => AgentKind::Cursor,- "gemini-cli" | "gemini" => AgentKind::GeminiCli,- "claude-desktop" | "claude_desktop" => AgentKind::ClaudeDesktop,- "openclaw" | "open-claw" => AgentKind::OpenClaw,- "omp" | "pi" | "oh-my-pi" => AgentKind::Omp,- _ => AgentKind::Other,- }+ AgentKind::from_wire(s)}impl HookEnvelope {diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex a2c27a79..9833eb7a 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -329,7 +329,7 @@ fn refresh_incoming_links_for_path(/// Idempotent: a second call with the same id leaves the row untouched.pub fn begin_session(conn: &mut Connection, session: &NewSession) -> StoreResult<()> {let now = Timestamp::now().as_microsecond();- let agent = agent_kind_as_str(session.agent_kind);+ let agent = session.agent_kind.as_str();let cwd: Option<String> = session.cwd.as_ref()@@ -506,8 +506,8 @@ pub fn insert_handoff(conn: &mut Connection, h: &NewHandoff) -> StoreResult<Handlet files = serde_json::to_string(&h.files_touched)?;let from_session: Option<&[u8]> = h.from_session_id.as_ref().map(|s| &s.as_bytes()[..]);let cwd: Option<String> = h.cwd.as_ref().map(|p| p.to_string_lossy().into_owned());- let from_agent = agent_kind_as_str(h.from_agent);- let to_agent = h.to_agent.map(agent_kind_as_str);+ let from_agent = h.from_agent.as_str();+ let to_agent = h.to_agent.map(AgentKind::as_str);conn.execute("INSERT INTO handoffs \(id, workspace_id, project_id, from_session_id, from_agent, to_agent, cwd, summary, \@@ -539,7 +539,7 @@ pub fn accept_handoff(accepting_session: Option<&SessionId>,) -> StoreResult<()> {let now = Timestamp::now().as_microsecond();- let agent = agent_kind_as_str(accepting_agent);+ let agent = accepting_agent.as_str();let session: Option<&[u8]> = accepting_session.map(|s| &s.as_bytes()[..]);conn.execute("UPDATE handoffs SET state = 'accepted', accepted_by = ?1, accepted_at = ?2, \@@ -550,20 +550,6 @@ pub fn accept_handoff(Ok(())}-fn agent_kind_as_str(kind: AgentKind) -> &'static str {- match kind {- AgentKind::ClaudeCode => "claude-code",- AgentKind::Codex => "codex",- AgentKind::OpenCode => "open-code",- AgentKind::Cursor => "cursor",- AgentKind::GeminiCli => "gemini-cli",- AgentKind::ClaudeDesktop => "claude-desktop",- AgentKind::OpenClaw => "openclaw",- AgentKind::Omp => "omp",- AgentKind::Other => "other",- }-}-fn observation_kind_as_str(kind: ObservationKind) -> &'static str {kind.as_str()}diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 6835ee59..81887830 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -1991,17 +1991,7 @@ fn materialise_handoff(}fn parse_agent(s: &str) -> AgentKind {- match s {- "claude-code" => AgentKind::ClaudeCode,- "codex" => AgentKind::Codex,- "open-code" => AgentKind::OpenCode,- "cursor" => AgentKind::Cursor,- "gemini-cli" => AgentKind::GeminiCli,- "claude-desktop" => AgentKind::ClaudeDesktop,- "openclaw" => AgentKind::OpenClaw,- "omp" => AgentKind::Omp,- _ => AgentKind::Other,- }+ AgentKind::from_wire(s)}fn count(conn: &Connection, sql: &str) -> StoreResult<u64> {