Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat: add Cline and FreeBuff integrations
AkitaOnRails52cae6ea368e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 46b56f5d..8b06ce15 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,15 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]### Added+- Added first-party Cline CLI lifecycle and MCP support. `install-hooks+ --agent cline --apply` writes Cline's nine supported event files globally or+ per project, refuses user-owned and symlinked targets, and keeps embedded+ bearer credentials owner-only. `install-mcp --client cline --apply` writes+ Cline's nested transport schema and explicitly selects Streamable HTTP.+ Detached start hooks recover handoffs through MCP; yolo mode disables hooks.+ Also added `install-mcp --client freebuff --apply`, which registers the+ sessionless stdio bridge in `~/.agents/mcp.json` without starting another+ ai-memory server. (#1335)- Added `[ingest] drop_events` (env `AI_MEMORY_INGEST__DROP_EVENTS`), anopt-in list of hook event kinds the server drops before storing them, nextto the existing `drop_tool_use_id_prefixes` and `drop_tool_names`. A droppeddiff --git a/README.md b/README.mdindex c23fd6dc..f0045fde 100644--- a/README.md+++ b/README.md@@ -162,6 +162,8 @@ caveats is in [`docs/support-matrix.md`](docs/support-matrix.md).| VS Code Copilot | MCP-only || Zed | MCP-only || DeepSeek Harness (DSH) | Hooks + MCP |+| Cline CLI | Hooks + MCP |+| FreeBuff | MCP-only || Prime Agent | MCP-only || Hermes Agent | Supported || GrizzyBot | Supported |@@ -390,9 +392,10 @@ docker run -d --name ai-memory \# 3. Wire your agent CLI in two commands. The wrapper takes care of# mounts and each client's config-path detection. Re-run with# `--agent codex`, `--agent command-code`, `--agent devin`, `--agent opencode`, `--agent opencode2`, `--agent gemini-cli`,-# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli`, `--agent copilot-cli`, `--agent droid`, `--agent muse`, `--agent omp`,+# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli`, `--agent copilot-cli`, `--agent droid`, `--agent muse`, `--agent cline`, `--agent omp`,# `--agent oh-my-pi`, `--client cursor`,-# `--client gemini-cli`, `--client grok`, `--client kiro-cli`, etc.+# `--client gemini-cli`, `--client grok`, `--client kiro-cli`,+# `--client cline`, `--client freebuff`, etc.# for additional agents; full list in docs/install.md.ai-memory install-mcp --client claude-code --applyai-memory install-hooks --agent claude-code --applydiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 669ef88a..b1f49db3 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1750,14 +1750,15 @@ pub enum InstallSkillsScope {Global,}-/// Where `install-hooks` writes Claude Code's hook configuration.+/// Where `install-hooks` writes a hook configuration with user/project scope.#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]pub enum HookInstallScope {- /// The user-level settings file (`~/.claude/settings.json`, or- /// `$CLAUDE_CONFIG_DIR/settings.json`): hooks fire in every project.+ /// The user-level hook location: Claude Code's settings file or Cline+ /// CLI's `~/.cline/hooks` directory. Hooks fire in every project.Global,- /// This repository's gitignored `.claude/settings.local.json`: hooks fire- /// only for sessions started in this checkout.+ /// This repository's hook location: Claude Code's gitignored+ /// `.claude/settings.local.json` or Cline CLI's `.cline/hooks` directory.+ /// Hooks fire only for sessions started in this checkout.Project,}@@ -2490,6 +2491,11 @@ pub enum AgentChoice {/// `memory_handoff_accept` tool.#[value(alias = "deepseek-harness", alias = "deepseek_harness")]Dsh,+ /// Cline CLI — lifecycle files under `~/.cline/hooks`. Cline runs+ /// TaskStart/TaskResume detached by default, so capture works but automatic+ /// handoff injection does not; accept the handoff through MCP instead.+ #[value(alias = "cline-cli")]+ Cline,}impl AgentChoice {@@ -2526,6 +2532,7 @@ impl AgentChoice {Self::CodeBuddy => AgentKind::CodeBuddy,Self::IbmBob => AgentKind::IbmBob,Self::Dsh => AgentKind::Dsh,+ Self::Cline => AgentKind::Cline,}}@@ -2548,7 +2555,8 @@ impl AgentChoice {| Self::Droid| Self::Muse| Self::CodeBuddy- | Self::IbmBob => None,+ | Self::IbmBob+ | Self::Cline => None,_ => Some(self.kind().as_str()),}}@@ -2801,14 +2809,21 @@ pub enum McpClient {/// Pair with `install-hooks --agent muse` for lifecycle capture.#[value(alias = "muse-code", alias = "musecode")]Muse,- /// DeepSeek Harness (DSH) - MCP-only. DSH has no fixed JSON/TOML MCP+ /// DeepSeek Harness (DSH) MCP writer. DSH has no fixed JSON/TOML MCP/// config: the client is a Cordis plugin entry/// (@deepseek-ai/dsh-mcp-client) inside a profile's cordis.patch.yml./// This integration is print-only (--apply is refused); merge the- /// rendered insert list into the profile patch. No lifecycle capture is- /// claimed.+ /// rendered insert list into the profile patch. Lifecycle capture is+ /// installed separately with `install-hooks --agent dsh`.#[value(alias = "deepseek-harness", alias = "deepseek_harness")]Dsh,+ /// Cline CLI — `~/.cline/data/settings/cline_mcp_settings.json` (or+ /// `CLINE_MCP_SETTINGS_PATH`) with an explicit Streamable HTTP transport.+ #[value(alias = "cline-cli")]+ Cline,+ /// FreeBuff CLI — `~/.agents/mcp.json`; MCP-only through ai-memory's+ /// sessionless stdio-to-HTTP bridge.+ Freebuff,/// Prime Agent (PrimeIntellect-ai/prime-agent) - the `mcpServers` map of/// `$PRIME_AGENT_CODING_AGENT_DIR/settings.json` (default/// `~/.prime/agent/settings.json`) with `type: "http"` + `url`. A token is@@ -3228,18 +3243,16 @@ pub struct InstallHooksArgs {/// written next to the original before each modifying write.#[arg(long)]pub apply: bool,- /// Override the settings/plugin/extension file path for the selected agent.- /// For OpenClaw, this is the generated plugin package directory.+ /// Override the settings/plugin/extension path for the selected agent.+ /// For OpenClaw this is the generated plugin package directory; for Cline+ /// CLI it is the hook directory.#[arg(long)]pub config_file: Option<PathBuf>,- /// Where to write the hook configuration. `project` targets the- /// repository's `.claude/settings.local.json` (at the git root; in the- /// current directory outside a repository, on Windows, or when the- /// repository root is the home directory) so capture is opted in per- /// checkout instead of for every session; Claude Code reads it alongside- /// the user-level hooks.- /// Claude Code only; ignores `CLAUDE_CONFIG_DIR`. Cannot be combined- /// with `--config-file`, which names the target file directly.+ /// Where to write the hook configuration. For Claude Code, `project`+ /// targets the repository's `.claude/settings.local.json` (at the git+ /// root when available) and ignores `CLAUDE_CONFIG_DIR`. For Cline CLI,+ /// it targets `.cline/hooks` in the current checkout. Cannot be combined+ /// with `--config-file`, which names the target path directly.#[arg(long,value_enum,diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex c68e6117..75cb449c 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -298,6 +298,7 @@ fn payload_has_session_id(raw: &serde_json::Value) -> bool {"sessionID","session","conversationId",+ "taskId",].iter().any(|key| {diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex ee018218..39363a61 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -1021,6 +1021,9 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent, &config.data_dir)?;apply_to_dsh(&hooks_dir, &server_url, auth, &config.data_dir, &args)}+ AgentChoice::Cline => {+ apply_to_cline_hooks(&server_url, auth, &config.data_dir, &args, &capture_mode)+ }};}let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);@@ -1184,6 +1187,13 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent, &config.data_dir)?;render_dsh(&hooks_dir, &server_url, auth, &config.data_dir, strategy)}+ AgentChoice::Cline => render_cline_hooks(+ &server_url,+ auth,+ &config.data_dir,+ &args,+ &preview_capture_mode,+ ),}}@@ -1384,6 +1394,9 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {// data dir; it carries no baked strategy worth re-reading// (same reason Pool returns None).AgentChoice::Dsh => return None,+ // Cline hook files are generated independently and carry no+ // shared settings document from which to recover a strategy.+ AgentChoice::Cline => return None,}};std::fs::read_to_string(path).ok()@@ -1742,6 +1755,12 @@ fn infer_installed_mcp_config(&["mcpServers", "ai-memory"],"url",)),+ McpClient::Cline => Ok(infer_json_mcp_config(+ &content,+ &["mcpServers", "ai-memory", "transport"],+ "url",+ )),+ McpClient::Freebuff => Ok(None),}}@@ -1816,6 +1835,7 @@ pub(crate) fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {// from (install-mcp --client dsh is print-only), so pass explicit// --server-url / --auth-token instead.AgentChoice::Dsh => None,+ AgentChoice::Cline => Some(McpClient::Cline),}}@@ -1847,6 +1867,7 @@ pub(crate) fn hook_config_target_with(AgentChoice::Grok => grok_hooks_path_in(env("GROK_HOME")),AgentChoice::AntigravityCli => antigravity_hooks_path(),AgentChoice::CopilotCli => copilot_cli_hooks_path_in(env("COPILOT_HOME")),+ AgentChoice::Cline => cline_hooks_path_in(env("HOME")),other => anyhow::bail!("{} is not auto-wired by `ai-memory run`",other.kind().as_str()@@ -7768,6 +7789,209 @@ fn apply_to_pool(Ok(())}+pub(crate) const CLINE_HOOK_EVENTS: [(&str, &str); 9] = [+ ("TaskStart", "session-start"),+ ("TaskResume", "session-start"),+ ("UserPromptSubmit", "user-prompt"),+ ("PreToolUse", "pre-tool-use"),+ ("PostToolUse", "post-tool-use"),+ ("TaskComplete", "stop"),+ ("TaskCancel", "stop"),+ ("TaskError", "stop"),+ ("SessionShutdown", "session-end"),+];++pub(crate) fn cline_hooks_path_in(home: Option<std::ffi::OsString>) -> Result<PathBuf> {+ let home = home+ .filter(|value| !value.is_empty())+ .map(PathBuf::from)+ .or_else(home_dir)+ .context("could not locate $HOME for ~/.cline/hooks")?;+ Ok(home.join(".cline").join("hooks"))+}++fn cline_hooks_target(args: &InstallHooksArgs) -> Result<PathBuf> {+ if let Some(path) = &args.config_file {+ return Ok(path.clone());+ }+ match args.scope {+ HookInstallScope::Global => cline_hooks_path_in(std::env::var_os("HOME")),+ HookInstallScope::Project => Ok(std::env::current_dir()+ .context("could not resolve current dir for project Cline hooks")?+ .join(".cline")+ .join("hooks")),+ }+}++fn posix_single_quote(value: &str) -> String {+ format!("'{}'", value.replace('\'', "'\"'\"'"))+}++fn powershell_single_quote(value: &str) -> String {+ format!("'{}'", value.replace('\'', "''"))+}++fn cline_hook_argv(+ event: &str,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+ capture_mode: &str,+) -> Vec<String> {+ let mut argv = vec![+ "ai-memory".to_string(),+ "--data-dir".to_string(),+ data_dir.to_string_lossy().into_owned(),+ "hook".to_string(),+ "--event".to_string(),+ event.to_string(),+ "--agent".to_string(),+ "cline".to_string(),+ "--server-url".to_string(),+ server_url.to_string(),+ "--capture-mode".to_string(),+ capture_mode.to_string(),+ ];+ if let Some(token) = auth_token {+ argv.extend(["--auth-token".to_string(), token.to_string()]);+ }+ if let Some(strategy) = args.project_strategy.and_then(ProjectStrategyArg::baked) {+ argv.extend(["--project-strategy".to_string(), strategy.to_string()]);+ }+ argv+}++fn render_cline_hook_script(argv: &[String], windows: bool) -> String {+ if windows {+ let command = argv+ .iter()+ .map(|word| powershell_single_quote(word))+ .collect::<Vec<_>>()+ .join(" ");+ format!(+ "# Generated by ai-memory install-hooks --agent cline.\n\+ $ProgressPreference = 'SilentlyContinue'\n\+ & {command}\n\+ exit $LASTEXITCODE\n"+ )+ } else {+ let command = argv+ .iter()+ .map(|word| posix_single_quote(word))+ .collect::<Vec<_>>()+ .join(" ");+ format!(+ "#!/bin/sh\n# Generated by ai-memory install-hooks --agent cline.\nexec {command}\n"+ )+ }+}++fn render_cline_hooks(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+ capture_mode: &str,+) -> Result<()> {+ let target = cline_hooks_target(args)?;+ let extension = if cfg!(windows) { "ps1" } else { "sh" };+ println!("# Cline CLI hook files ({})", target.display());+ println!("# Restart Cline after installing. Cline's yolo mode disables hooks.");+ println!("# TaskStart/TaskResume run detached, so accept pending handoffs through MCP.");+ if auth_token.is_some() {+ println!(+ "# The applied files contain the bearer token and are owner-only; preview redacts it."+ );+ }+ for (name, event) in CLINE_HOOK_EVENTS {+ let preview_token = auth_token.map(|_| "<redacted>");+ let argv = cline_hook_argv(+ event,+ server_url,+ preview_token,+ data_dir,+ args,+ capture_mode,+ );+ println!(+ "\n# {}.{}\n{}",+ name,+ extension,+ render_cline_hook_script(&argv, cfg!(windows))+ );+ }+ Ok(())+}++fn apply_to_cline_hooks(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+ capture_mode: &str,+) -> Result<()> {+ let target = cline_hooks_target(args)?;+ fs::create_dir_all(&target)+ .with_context(|| format!("creating Cline hooks directory {}", target.display()))?;+ let extension = if cfg!(windows) { "ps1" } else { "sh" };+ let mut rendered = Vec::with_capacity(CLINE_HOOK_EVENTS.len());+ for (name, event) in CLINE_HOOK_EVENTS {+ let path = target.join(format!("{name}.{extension}"));+ if fs::symlink_metadata(&path).is_ok_and(|metadata| metadata.file_type().is_symlink()) {+ anyhow::bail!(+ "refusing to replace symlinked Cline hook {}",+ path.display()+ );+ }+ let argv = cline_hook_argv(event, server_url, auth_token, data_dir, args, capture_mode);+ let content = render_cline_hook_script(&argv, cfg!(windows));+ match fs::read_to_string(&path) {+ Ok(existing)+ if !existing.contains("Generated by ai-memory install-hooks --agent cline") =>+ {+ anyhow::bail!(+ "refusing to replace user-owned Cline hook {}; move it aside or combine it manually",+ path.display()+ );+ }+ Ok(_) => {}+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => {+ return Err(error).with_context(|| format!("reading {}", path.display()));+ }+ }+ rendered.push((name, path, content));+ }++ for (name, path, content) in rendered {+ let backup = PrivateBackup {+ dir: data_dir.join("backups").join("cline-hooks"),+ stem: format!("cline-{name}"),+ };+ let outcome = apply_atomic_with_backup(&path, Some(&backup), |existing| {+ if !existing.is_empty()+ && !existing.contains("Generated by ai-memory install-hooks --agent cline")+ {+ anyhow::bail!(+ "refusing to replace user-owned Cline hook {}; move it aside or combine it manually",+ path.display()+ );+ }+ Ok(content.clone())+ })?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(&path, fs::Permissions::from_mode(0o700))?;+ }+ eprintln!("✓ {} {}", outcome.verb(), path.display());+ }+ println!("Restart Cline so it reloads the hook directory.");+ println!("Cline yolo mode disables hooks; lifecycle capture is unavailable in that mode.");+ Ok(())+}+/// Print DSH's generated Claude Code `hooks.json` plus the Cordis patch/// fragment that points the official `@deepseek-ai/dsh-hooks-claude-code`/// bridge at it. DSH has no fixed agent config file, so merging the patch@@ -9103,6 +9327,112 @@ mod tests {}}+ #[test]+ fn cline_apply_writes_native_event_hooks_without_overwriting_user_files() {+ let tmp = tempfile::tempdir().unwrap();+ let target = tmp.path().join("cline-hooks");+ let data = tmp.path().join("data");+ let mut args = default_hook_args();+ args.agent = AgentChoice::Cline;+ args.config_file = Some(target.clone());+ args.project_strategy = Some(ProjectStrategyArg::RepoRoot);++ apply_to_cline_hooks(+ "https://memory.example",+ Some("tok'en"),+ &data,+ &args,+ "allowlist",+ )+ .unwrap();++ let extension = if cfg!(windows) { "ps1" } else { "sh" };+ for (name, event) in CLINE_HOOK_EVENTS {+ let path = target.join(format!("{name}.{extension}"));+ let content = fs::read_to_string(&path).unwrap();+ assert!(content.contains("--agent"));+ assert!(content.contains("cline"));+ assert!(content.contains(event));+ assert!(content.contains("https://memory.example"));+ assert!(content.contains("allowlist"));+ assert!(content.contains("repo-root"));+ assert!(content.contains("--auth-token"));+ assert!(!content.contains("<redacted>"));+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ assert_eq!(+ fs::metadata(path).unwrap().permissions().mode() & 0o777,+ 0o700+ );+ }+ }++ let first = target.join(format!("TaskStart.{extension}"));+ fs::remove_file(&first).unwrap();+ let owned = target.join(format!("TaskResume.{extension}"));+ fs::write(&owned, "user-owned hook\n").unwrap();+ let error = apply_to_cline_hooks("https://memory.example", None, &data, &args, "denylist")+ .unwrap_err();+ assert!(error.to_string().contains("refusing to replace user-owned"));+ assert_eq!(fs::read_to_string(owned).unwrap(), "user-owned hook\n");+ assert!(!first.exists(), "preflight must prevent a partial rewrite");+ }++ #[test]+ fn cline_script_quoting_is_shell_specific_and_literal() {+ let argv = vec!["ai-memory".to_string(), "a'b $HOME".to_string()];+ let sh = render_cline_hook_script(&argv, false);+ assert!(sh.contains("'a'\"'\"'b $HOME'"), "{sh}");+ let ps = render_cline_hook_script(&argv, true);+ assert!(ps.contains("'a''b $HOME'"), "{ps}");+ }++ #[cfg(unix)]+ #[test]+ fn cline_apply_refuses_a_symlinked_hook_without_touching_its_target() {+ use std::os::unix::fs::symlink;++ let tmp = tempfile::tempdir().unwrap();+ let target = tmp.path().join("cline-hooks");+ let data = tmp.path().join("data");+ fs::create_dir_all(&target).unwrap();+ let victim = tmp.path().join("victim");+ fs::write(&victim, "keep me\n").unwrap();+ symlink(&victim, target.join("TaskStart.sh")).unwrap();++ let mut args = default_hook_args();+ args.agent = AgentChoice::Cline;+ args.config_file = Some(target);+ let error = apply_to_cline_hooks(+ "https://memory.example",+ Some("secret"),+ &data,+ &args,+ "denylist",+ )+ .unwrap_err();++ assert!(error.to_string().contains("refusing to replace symlinked"));+ assert_eq!(fs::read_to_string(victim).unwrap(), "keep me\n");+ }++ #[test]+ fn cline_hook_target_follows_supplied_home() {+ let home = if cfg!(windows) {+ std::ffi::OsString::from(r"C:\Users\alice")+ } else {+ std::ffi::OsString::from("/home/alice")+ };+ assert_eq!(+ hook_config_target_with(AgentChoice::Cline, &|name| {+ (name == "HOME").then(|| home.clone())+ })+ .unwrap(),+ PathBuf::from(home).join(".cline").join("hooks")+ );+ }+// ── #issue project-strategy preservation on re-apply ─────────────#[test]diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 132bd40f..f9b0b57a 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -126,7 +126,9 @@ pub(crate) fn run_with_opencode_dialect(// install's config and token only through an explicit `--data-dir`, as// the Muse hooks do. Not from inside the Docker helper, whose data dir is// a container path the host-side bridge cannot open.- if args.client == McpClient::Muse && config.runtime_env.host_cwd().is_none() {+ if matches!(args.client, McpClient::Muse | McpClient::Freebuff)+ && config.runtime_env.host_cwd().is_none()+ {args.bridge_data_dir = Some(config.data_dir.clone());}if args.auth_token.is_none()@@ -166,6 +168,8 @@ pub(crate) fn run_with_opencode_dialect(McpClient::Muse => render_muse(&args)?,McpClient::Dsh => render_dsh(&args)?,McpClient::PrimeAgent => render_prime_agent(&args)?,+ McpClient::Cline => render_json_mcp_fragment(&args)?,+ McpClient::Freebuff => render_json_mcp_fragment(&args)?,};println!("{snippet}");Ok(())@@ -216,18 +220,29 @@ const BRIDGE_COMMAND: &str = "ai-memory";/// to it verbatim and the client is the one that needs the dialect.fn session_less_bridge_args(args: &InstallMcpArgs) -> Vec<String> {let base_url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL);- vec![+ let mut argv = vec!["mcp-bridge".to_owned(),"--no-session-id".to_owned(),"--server-url".to_owned(),flavored_url_for(args, base_url),- ]+ ];+ if let Some(data_dir) = &args.bridge_data_dir {+ argv.extend([+ "--data-dir".to_owned(),+ data_dir.to_string_lossy().into_owned(),+ ]);+ }+ argv}/// The upstream URL of an ai-memory bridge entry: `command: "ai-memory"` with/// `args`, or OpenCode's single `command` array, running `mcp-bridge` with a/// `--server-url`. `None` for any other entry.pub(crate) fn bridge_entry_url(entry: &serde_json::Value) -> Option<&str> {+ let entry = entry+ .get("transport")+ .filter(|transport| transport.is_object())+ .unwrap_or(entry);let argv: Vec<&str> = match entry.get("command")? {serde_json::Value::String(command) if command == BRIDGE_COMMAND => entry.get("args")?@@ -319,6 +334,11 @@ pub(crate) fn existing_entry_endpoint(if let Some(url) = ["url", "httpUrl", "serverUrl"].iter().find_map(|key| entry.get(*key).and_then(serde_json::Value::as_str))+ .or_else(|| {+ entry+ .pointer("/transport/url")+ .and_then(serde_json::Value::as_str)+ }).or_else(|| bridge_entry_url(entry)){return Ok(Some(url.to_owned()));@@ -361,6 +381,26 @@ fn stdio_bridge_entry(args: &InstallMcpArgs) -> Option<serde_json::Value> {McpClient::Cursor | McpClient::VsCodeCopilot | McpClient::Swival | McpClient::Zero => {typed("stdio")}+ McpClient::Cline => json!({+ "transport": {+ "type": "stdio",+ "command": BRIDGE_COMMAND,+ "args": bridge,+ },+ "disabled": false,+ "autoApprove": [],+ }),+ McpClient::Freebuff => {+ let env = args+ .auth_token+ .as_ref()+ .map_or_else(|| json!({}), |token| json!({"AI_MEMORY_AUTH_TOKEN": token}));+ json!({+ "command": BRIDGE_COMMAND,+ "args": bridge,+ "env": env,+ })+ }McpClient::Omp => json!({"type": "stdio","command": BRIDGE_COMMAND,@@ -511,7 +551,7 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>/// [`mcp_config_path`] with the relocation variables (`CLAUDE_CONFIG_DIR`,/// `CODEX_HOME`, `COPILOT_HOME`, `GROK_HOME`, `KIMI_CODE_HOME`, `KIRO_HOME`,-/// `PRIME_AGENT_CODING_AGENT_DIR`, and OMP's+/// `PRIME_AGENT_CODING_AGENT_DIR`, `CLINE_MCP_SETTINGS_PATH`, and OMP's/// `OMP_PROFILE`, `PI_PROFILE`, `PI_CODING_AGENT_DIR` and `PI_CONFIG_DIR`) read/// through `env`,/// so `ai-memory run --env` can point auto-wire at the same config home@@ -521,7 +561,13 @@ pub(crate) fn mcp_config_path_with(env: &dyn Fn(&str) -> Option<std::ffi::OsString>,) -> Result<PathBuf> {use crate::cli::McpClient;- let home = || home_dir().context("could not locate $HOME for config-file auto-detect");+ let home = || {+ env("HOME")+ .filter(|value| !value.is_empty())+ .map(PathBuf::from)+ .or_else(home_dir)+ .context("could not locate $HOME for config-file auto-detect")+ };Ok(match client {McpClient::ClaudeCode => claude_code_config_path_in(env("CLAUDE_CONFIG_DIR"))?,McpClient::Codex => codex_config_path_in(env("CODEX_HOME"))?,@@ -652,6 +698,11 @@ pub(crate) fn mcp_config_path_with(McpClient::PrimeAgent => {prime_agent_dir_in(env("PRIME_AGENT_CODING_AGENT_DIR"))?.join("settings.json")}+ McpClient::Cline => env("CLINE_MCP_SETTINGS_PATH")+ .filter(|path| !path.is_empty())+ .map(PathBuf::from)+ .unwrap_or(home()?.join(".cline/data/settings/cline_mcp_settings.json")),+ McpClient::Freebuff => home()?.join(".agents").join("mcp.json"),})}@@ -1059,6 +1110,7 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {| McpClient::Droid| McpClient::Swival| McpClient::PrimeAgent => Some(JsonMcpLocation::RootMcpServers),+ McpClient::Cline | McpClient::Freebuff => Some(JsonMcpLocation::RootMcpServers),McpClient::OpenCode => Some(JsonMcpLocation::RootMcp),// V2 nests servers under `mcp.servers` — the same shape OpenClaw,// Zero, and ZCode use.@@ -1077,7 +1129,12 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {fn build_json_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {validate_args(args)?;- if args.stdio_bridge+ // FreeBuff supports local stdio MCP servers, not remote HTTP entries.+ // Always bridge to the configured ai-memory HTTP server; starting another+ // `serve` process would contend for the data-dir lock. Keep this at the+ // typed builder boundary so auth-enable and other internal callers cannot+ // accidentally request an unsupported direct entry.+ if (args.stdio_bridge || args.client == McpClient::Freebuff)&& let Some(entry) = stdio_bridge_entry(args){return Ok(entry);@@ -1089,6 +1146,7 @@ fn build_json_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {McpClient::Zero => build_mcp_entry_zero(args),McpClient::Zcode => build_mcp_entry_zcode(args),McpClient::Muse => build_mcp_entry_muse(args),+ McpClient::Cline => build_mcp_entry_cline(args),McpClient::Codex | McpClient::Grok => {bail!("internal: Codex/Grok MCP config is TOML, not JSON")}@@ -1346,6 +1404,11 @@ fn entry_endpoint(entry: &serde_json::Value) -> Option<&str> {entry.get("url").and_then(serde_json::Value::as_str)+ .or_else(|| {+ entry+ .pointer("/transport/url")+ .and_then(serde_json::Value::as_str)+ }).or_else(|| bridge_entry_url(entry))}@@ -1702,6 +1765,9 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {entry.insert("bearerTokenEnvVar".into(), json!(PRIME_AGENT_TOKEN_ENV));}}+ McpClient::Cline | McpClient::Freebuff => {+ bail!("internal: client has a dedicated MCP entry builder")+ }_ => bail!("internal: build_mcp_entry called for unsupported client"),}Ok(serde_json::Value::Object(entry))@@ -1720,6 +1786,24 @@ fn build_mcp_entry_opencode(args: &InstallMcpArgs) -> Result<serde_json::Value>Ok(serde_json::Value::Object(entry))}+/// Cline's CLI writer uses a nested transport object. Keeping the explicit+/// `streamableHttp` discriminator is load-bearing: a bare `url` is parsed as+/// legacy SSE and sends GET requests to ai-memory's POST-only MCP endpoint.+fn build_mcp_entry_cline(args: &InstallMcpArgs) -> Result<serde_json::Value> {+ let base_url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL);+ let mut transport = serde_json::Map::new();+ transport.insert("type".into(), json!("streamableHttp"));+ transport.insert("url".into(), json!(flavored_url_for(args, base_url)));+ if let Some(bearer) = bearer_header_value(args.auth_token.as_deref()) {+ transport.insert("headers".into(), json!({"Authorization": bearer}));+ }+ Ok(json!({+ "transport": transport,+ "disabled": false,+ "autoApprove": [],+ }))+}+/// OpenCode 2.0 beta MCP entry: `type: "remote"` + `url` + optional/// `headers` under `mcp.servers`. V2 has no `enabled` field (servers/// connect unless `disabled: true`), and header-credentialed servers@@ -2617,6 +2701,62 @@ mod tests {}}+ #[test]+ fn cline_entry_explicitly_selects_streamable_http() {+ let entry = build_json_mcp_entry(&args_with_token(McpClient::Cline)).unwrap();+ assert_eq!(entry["transport"]["type"], "streamableHttp");+ assert_eq!(entry["transport"]["url"], "http://127.0.0.1:49374/mcp");+ assert_eq!(+ entry["transport"]["headers"]["Authorization"],+ "Bearer test-token-deadbeef"+ );+ assert_eq!(entry["disabled"], false);+ assert_eq!(entry["autoApprove"], json!([]));+ }++ #[test]+ fn freebuff_entry_uses_sessionless_bridge_not_a_second_server() {+ let mut args = args_for(McpClient::Freebuff);+ args.server_url = Some("https://memory.example/mcp".into());+ let entry = build_json_mcp_entry(&args).unwrap();+ assert_eq!(entry["command"], "ai-memory");+ assert_eq!(+ entry["args"],+ json!([+ "mcp-bridge",+ "--no-session-id",+ "--server-url",+ "https://memory.example/mcp"+ ])+ );+ assert_eq!(entry["env"], json!({}));+ assert!(+ !entry["args"]+ .as_array()+ .unwrap()+ .iter()+ .any(|arg| arg.as_str() == Some("serve"))+ );++ let mut authenticated = args_for(McpClient::Freebuff);+ authenticated.server_url = Some("https://memory.example/mcp".into());+ authenticated.auth_token = Some("explicit-token".into());+ authenticated.bridge_data_dir = Some(PathBuf::from("/srv/ai-memory"));+ let entry = build_json_mcp_entry(&authenticated).unwrap();+ assert_eq!(entry["env"]["AI_MEMORY_AUTH_TOKEN"], "explicit-token");+ assert_eq!(+ entry["args"],+ json!([+ "mcp-bridge",+ "--no-session-id",+ "--server-url",+ "https://memory.example/mcp",+ "--data-dir",+ "/srv/ai-memory"+ ])+ );+ }+/// Droid's `mcp.json` HTTP entry (#1240): the URL is literal (Droid/// never expands variables there), and a configured bearer becomes the/// `${AI_MEMORY_AUTH_TOKEN}` reference Droid expands in headers, never@@ -3428,6 +3568,25 @@ mod tests {"{client:?} must follow {var}");}++ let cline_file = root.join("cline-mcp.json");+ let env = |name: &str| {+ (name == "CLINE_MCP_SETTINGS_PATH").then(|| cline_file.clone().into_os_string())+ };+ assert_eq!(+ mcp_config_path_with(McpClient::Cline, &env).unwrap(),+ cline_file+ );++ let env = |name: &str| (name == "HOME").then(|| root.as_os_str().to_owned());+ assert_eq!(+ mcp_config_path_with(McpClient::Cline, &env).unwrap(),+ root.join(".cline/data/settings/cline_mcp_settings.json")+ );+ assert_eq!(+ mcp_config_path_with(McpClient::Freebuff, &env).unwrap(),+ root.join(".agents/mcp.json")+ );}#[test]@@ -3917,6 +4076,12 @@ mod tests {McpClient::Muse => render_muse(&args).unwrap(),McpClient::Dsh => render_dsh(&args).unwrap(),McpClient::PrimeAgent => render_prime_agent(&args).unwrap(),+ McpClient::Cline => render_json_mcp_fragment(&args).unwrap(),+ McpClient::Freebuff => {+ let mut args = args;+ args.stdio_bridge = true;+ render_json_mcp_fragment(&args).unwrap()+ }}}@@ -3948,6 +4113,7 @@ mod tests {McpClient::VsCodeCopilot,McpClient::Zed,McpClient::Dsh,+ McpClient::Cline,] {let out = render_with_token(client);// Every client embeds the token as `Authorization:@@ -3996,6 +4162,8 @@ mod tests {McpClient::Muse,McpClient::Dsh,McpClient::PrimeAgent,+ McpClient::Cline,+ McpClient::Freebuff,] {let out = render_for_test(client);assert!(@@ -4037,6 +4205,12 @@ mod tests {McpClient::Muse => render_muse(&args).unwrap(),McpClient::Dsh => render_dsh(&args).unwrap(),McpClient::PrimeAgent => render_prime_agent(&args).unwrap(),+ McpClient::Cline => render_json_mcp_fragment(&args).unwrap(),+ McpClient::Freebuff => {+ let mut args = args;+ args.stdio_bridge = true;+ render_json_mcp_fragment(&args).unwrap()+ }}}diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex cec6c68b..e2560c82 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -135,6 +135,11 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {emit_ibm_bob(&args)?;return Ok(());}+ if matches!(args.agent, AgentChoice::Cline) {+ bail!(+ "Cline discovers generated hook files in the host user's hook directory; run `ai-memory install-hooks --agent cline --apply` on that host"+ );+ }let Some(agent_sub) = args.agent.script_hook_subdir() else {bail!("internal: generated integration should have returned before staging hooks")};@@ -235,7 +240,8 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {| AgentChoice::Droid| AgentChoice::Muse| AgentChoice::CodeBuddy- | AgentChoice::IbmBob => {+ | AgentChoice::IbmBob+ | AgentChoice::Cline => {bail!("internal: generated integration should have returned before emitting staged hooks")diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex c2230eeb..7828268e 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -75,6 +75,7 @@ enum DeleteKind {OpenClawManifest,OpenClawEntrypoint,KiroCliV3Hooks,+ ClineHook,ManagedSkill,GrokHandoffRule,AutowireSentinel,@@ -91,6 +92,7 @@ impl DeleteKind {Self::OpenClawManifest => "OpenClaw plugin manifest",Self::OpenClawEntrypoint => "OpenClaw plugin entrypoint",Self::KiroCliV3Hooks => "Kiro CLI v3 hook file",+ Self::ClineHook => "Cline CLI hook file",Self::ManagedSkill => "managed Agent Skill",Self::GrokHandoffRule => "managed Grok first-turn handoff rule",Self::AutowireSentinel => "auto-wire sentinel",@@ -380,6 +382,22 @@ fn build_plan();}+ let mut cline_hook_dirs = vec![install_hooks::cline_hooks_path_in(env.var_os("HOME"))?];+ cline_hook_dirs.push(cwd.join(".cline").join("hooks"));+ cline_hook_dirs.sort();+ cline_hook_dirs.dedup();+ for dir in cline_hook_dirs {+ for (event, _) in install_hooks::CLINE_HOOK_EVENTS {+ for extension in ["sh", "ps1"] {+ push_generated_delete(+ &mut plan,+ dir.join(format!("{event}.{extension}")),+ DeleteKind::ClineHook,+ );+ }+ }+ }+let plugin = install_hooks::opencode_plugin_path()?;push_generated_delete(&mut plan, plugin, DeleteKind::OpenCodePlugin);@@ -448,6 +466,8 @@ fn build_plan(Swival,Muse,PrimeAgent,+ Cline,+ Freebuff,] {let paths = if matches!(client, ClaudeCode) {claude_config_paths(@@ -470,7 +490,8 @@ fn build_plan(} else if matches!(client, Muse) {vec![install_hooks::muse_settings_path(env)?]} else {- let Ok(path) = install_mcp::mcp_config_path(client) else {+ let Ok(path) = install_mcp::mcp_config_path_with(client, &|name| env.var_os(name))+ else {continue;};vec![path]@@ -679,6 +700,11 @@ fn apply_change({remove_dir_if_empty(parent)?;}+ if *kind == DeleteKind::ClineHook+ && let Some(parent) = path.parent()+ {+ remove_dir_if_empty(parent)?;+ }}PlannedChange::Rewrite { path, ops, .. } => {let outcome = apply_atomic_with_backup(path, private_backup, |existing| {@@ -1521,6 +1547,12 @@ fn generated_file_is_ours(path: &Path, kind: DeleteKind) -> bool {.all(install_hooks::is_ai_memory_kiro_v3_hook_entry)})}),+ DeleteKind::ClineHook => {+ content.contains("Generated by ai-memory install-hooks --agent cline")+ && content.contains("'ai-memory'")+ && content.contains("'hook'")+ && content.contains("'--agent' 'cline'")+ }DeleteKind::ManagedSkill => content.contains(MANAGED_MARKER),DeleteKind::GrokHandoffRule => content.contains(GROK_HANDOFF_RULE_MARKER),}@@ -1544,7 +1576,9 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {| McpClient::Droid| McpClient::Swival| McpClient::Devin- | McpClient::PrimeAgent => Some(&["mcpServers"]),+ | McpClient::PrimeAgent+ | McpClient::Cline+ | McpClient::Freebuff => Some(&["mcpServers"]),McpClient::OpenCode => Some(&["mcp"]),McpClient::OpenCode2 => Some(&["mcp", "servers"]),McpClient::Openclaw | McpClient::Zero | McpClient::Zcode => Some(&["mcp", "servers"]),@@ -1571,6 +1605,9 @@ fn mcp_entry_is_ours(key: &str, entry: &serde_json::Value, name: Option<&str>, ureturn true;}}+ if entry.pointer("/transport/url").and_then(|v| v.as_str()) == Some(url) {+ return true;+ }// Our stdio bridge, in any client's shape (`command` + `args`, or// OpenCode's single `command` array), aimed at this server.if install_mcp::bridge_entry_url(entry) == Some(url) {@@ -2630,6 +2667,25 @@ mod tests {assert!(generated_file_is_ours(&path, DeleteKind::OpenCodePlugin));}+ #[test]+ fn generated_cline_hook_detection_requires_the_full_signature() {+ let tmp = tempfile::tempdir().unwrap();+ let path = tmp.path().join("TaskStart.sh");+ std::fs::write(+ &path,+ "#!/bin/sh\n# Generated by ai-memory install-hooks --agent cline.\nexec 'other' 'hook' '--agent' 'cline'\n",+ )+ .unwrap();+ assert!(!generated_file_is_ours(&path, DeleteKind::ClineHook));++ std::fs::write(+ &path,+ "#!/bin/sh\n# Generated by ai-memory install-hooks --agent cline.\nexec 'ai-memory' 'hook' '--agent' 'cline'\n",+ )+ .unwrap();+ assert!(generated_file_is_ours(&path, DeleteKind::ClineHook));+ }+#[test]fn generated_openclaw_package_detection_requires_our_shape() {let tmp = tempfile::tempdir().unwrap();@@ -2934,6 +2990,15 @@ mod tests {"command": ["ai-memory", "mcp-bridge", "--no-session-id", "--server-url", url],"enabled": true,});+ let cline = serde_json::json!({+ "transport": {+ "type": "stdio",+ "command": "ai-memory",+ "args": ["mcp-bridge", "--no-session-id", "--server-url", url],+ },+ "disabled": false,+ "autoApprove": [],+ });assert!(mcp_entry_is_ours("ai-memory",&bridge(url),@@ -2946,6 +3011,12 @@ mod tests {Some("ai-memory"),url));+ assert!(mcp_entry_is_ours(+ "ai-memory",+ &cline,+ Some("ai-memory"),+ url+ ));assert!(!mcp_entry_is_ours("ai-memory",&bridge("https://team.example/mcp"),diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex f2c87c9c..e8928038 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -305,6 +305,9 @@ pub enum AgentKind {/// (`@deepseek-ai/dsh-hooks-claude-code`) fires Claude Code-shaped/// payloads for seven events (no `SessionEnd` or `PreCompact`).Dsh,+ /// Cline CLI, whose file hooks use `taskId` plus nested `tool_call` /+ /// `tool_result` payloads. Run-start hooks are detached by default.+ Cline,/// Anything else (manual capture, future agents).Other,}@@ -315,7 +318,7 @@ impl AgentKind {/// CHECK constraint accepts every kind (the Zero integration shipped/// with the enum variant but without the V26 migration and only a/// live test caught it). Extend together with the enum.- pub const ALL: [Self; 28] = [+ pub const ALL: [Self; 29] = [Self::ClaudeCode,Self::Codex,Self::OpenCode,@@ -343,6 +346,7 @@ impl AgentKind {Self::CodeBuddy,Self::IbmBob,Self::Dsh,+ Self::Cline,Self::Other,];@@ -377,6 +381,7 @@ impl AgentKind {Self::CodeBuddy => "codebuddy",Self::IbmBob => "ibm-bob",Self::Dsh => "dsh",+ Self::Cline => "cline",Self::Other => "other",}}@@ -414,6 +419,7 @@ impl AgentKind {"codebuddy" | "code-buddy" => Self::CodeBuddy,"ibm-bob" | "bob" => Self::IbmBob,"dsh" | "deepseek-harness" | "deepseek_harness" => Self::Dsh,+ "cline" | "cline-cli" => Self::Cline,_ => Self::Other,}}@@ -484,6 +490,9 @@ impl AgentKind {// DSH's bridge runs SessionStart detached, so its stdout// cannot be relied on to deliver a fetched handoff.| Self::Dsh+ // Cline CLI runs TaskStart/TaskResume detached by default,+ // so accepting a single-use handoff there would discard it.+ | Self::Cline| Self::Other)}@@ -1296,4 +1305,18 @@ mod portable_page_path_tests {assert_ne!(portable_page_key(a), portable_page_key(b));}}++ #[test]+ fn cline_wire_identity_fails_safe_for_detached_start_hooks() {+ assert_eq!(+ super::AgentKind::from_wire("cline"),+ super::AgentKind::Cline+ );+ assert_eq!(+ super::AgentKind::from_wire("cline-cli"),+ super::AgentKind::Cline+ );+ assert_eq!(super::AgentKind::Cline.as_str(), "cline");+ assert!(!super::AgentKind::Cline.session_start_injects_handoff());+ }}diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex c129b20c..2e443733 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -231,6 +231,16 @@ pub(crate) fn tool_payload_fields(agent: AgentKind, raw: &Value) -> Option<(&str// reaches a hook payload (verified against the 0.240.0 tool schemas,// #1240).AgentKind::Droid => (object.get("tool_name")?.as_str()?, None),+ AgentKind::Cline => {+ let tool = object+ .get("tool_call")+ .or_else(|| object.get("tool_result"))?+ .as_object()?;+ (+ tool.get("name")?.as_str()?,+ tool.get("id").and_then(Value::as_str),+ )+ }_ => return None,};Some((name, id))@@ -250,6 +260,11 @@ pub(crate) fn tool_observation_metadata(let has_args = !require_input|| match agent {AgentKind::AntigravityCli => object.get("toolCall")?.get("args").is_some(),+ AgentKind::Cline => object+ .get("tool_call")+ .and_then(Value::as_object)+ .and_then(|tool| tool.get("input"))+ .is_some(),_ => object.get(if matches!(@@ -292,6 +307,15 @@ pub(crate) fn tool_observation_outcome(agent: AgentKind, raw: &Value) -> ToolOutSome(false) => ToolOutcome::Success,None => ToolOutcome::Unknown,},+ AgentKind::Cline => match raw+ .get("tool_result")+ .and_then(Value::as_object)+ .and_then(|tool| tool.get("error"))+ {+ Some(Value::Null) | None => ToolOutcome::Success,+ Some(Value::String(error)) if error.is_empty() => ToolOutcome::Success,+ Some(_) => ToolOutcome::Error,+ },AgentKind::KiroCli => match raw.get("tool_response").and_then(|response| response.get("success"))@@ -1077,6 +1101,11 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted<'_> {.get("toolCall").and_then(Value::as_object).and_then(|call| Some((call.get("name")?.as_str()?, call.get("args")))),+ AgentKind::Cline => object+ .get("tool_call")+ .or_else(|| object.get("tool_result"))+ .and_then(Value::as_object)+ .and_then(|call| Some((call.get("name")?.as_str()?, call.get("input")))),AgentKind::Grok => object.get("tool_name").or_else(|| object.get("toolName"))@@ -5057,6 +5086,40 @@ mod tests {);}+ #[test]+ fn cline_nested_tool_payloads_are_closed_and_classified() {+ let pre = json!({+ "tool_call": {+ "id": "call-1",+ "name": "read_file",+ "input": {"path": "src/lib.rs"}+ }+ });+ assert_eq!(+ tool_payload_fields(AgentKind::Cline, &pre),+ Some(("read_file", Some("call-1")))+ );+ let metadata = tool_observation_metadata(AgentKind::Cline, &pre, true).unwrap();+ assert_eq!(metadata.tool_family, ToolFamily::File);+ assert_eq!(metadata.tool_call_id.as_deref(), Some("call-1"));++ let success = json!({+ "tool_result": {"id": "call-1", "name": "read_file", "output": "ok"}+ });+ let failure = json!({+ "tool_result": {"id": "call-1", "name": "read_file", "error": "denied"}+ });+ assert_eq!(+ tool_observation_outcome(AgentKind::Cline, &success),+ ToolOutcome::Success+ );+ assert_eq!(+ tool_observation_outcome(AgentKind::Cline, &failure),+ ToolOutcome::Error+ );+ assert_eq!(tool_payload_fields(AgentKind::Other, &pre), None);+ }+/// Meta Muse Code's tool calls, in the shapes captured offline from Muse/// Code 1.4.7 hooks: `tool_input.path` is relative as the model wrote it/// and resolves lexically against `cwd`. Each file tool naming an ignoreddiff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex e03c0246..78b263ed 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -555,6 +555,7 @@ pub fn hook_payload_context(raw: &serde_json::Value) -> HookPayloadContext {"sessionID","session","conversationId",+ "taskId",],).or_else(|| {@@ -573,7 +574,12 @@ pub fn hook_payload_context(raw: &serde_json::Value) -> HookPayloadContext {)});let cwd = extract_string(raw, &["cwd", "current_dir", "working_dir", "directory"])- .or_else(|| extract_first_string_array_item(raw, &["workspacePaths", "workspace_roots"]))+ .or_else(|| {+ extract_first_string_array_item(+ raw,+ &["workspacePaths", "workspace_roots", "workspaceRoots"],+ )+ }).or_else(|| {extract_string_path(raw,@@ -850,6 +856,7 @@ const fn closed_tool_agent(agent: AgentKind) -> bool {// forwards Claude Code's snake_case tool fields for PreToolUse /// PostToolUse.| AgentKind::Dsh+ | AgentKind::Cline)}@@ -943,6 +950,10 @@ fn safe_tool_body(.and_then(value_to_text).or_else(|| raw.pointer("/extra/error_message").and_then(value_to_text)).or_else(|| extract_content(raw, &["error"]))+ } else if agent == AgentKind::Cline {+ raw.pointer("/tool_result/output")+ .and_then(value_to_text)+ .or_else(|| raw.pointer("/tool_result/error").and_then(value_to_text))} else {extract_content(raw, &["tool_response", "tool_output", "output", "result"]).or_else(|| extract_content(raw, &["error"]))@@ -1093,7 +1104,12 @@ fn best_title_hint(event: HookEvent, raw: &serde_json::Value) -> Option<String>// Kimi Code sends `prompt` as content blocks// (`[{"type":"text","text":...}]`); `extract_content` flattens// them and returns identical values for plain-string agents.- extract_content(raw, &["prompt", "message", "text"]).and_then(first_line)+ extract_content(raw, &["prompt", "message", "text"])+ .or_else(|| {+ raw.pointer("/userPromptSubmit/prompt")+ .and_then(value_to_text)+ })+ .and_then(first_line)}HookEvent::PreToolUse | HookEvent::PostToolUse => {extract_string(raw, &["tool", "tool_name", "name"])@@ -1180,7 +1196,12 @@ fn value_to_text(value: &serde_json::Value) -> Option<String> {fn best_body_excerpt(event: HookEvent, raw: &serde_json::Value) -> Option<String> {match event {- HookEvent::UserPrompt => extract_content(raw, &["prompt", "message", "text"]),+ HookEvent::UserPrompt => {+ extract_content(raw, &["prompt", "message", "text"]).or_else(|| {+ raw.pointer("/userPromptSubmit/prompt")+ .and_then(value_to_text)+ })+ }HookEvent::PostToolUse => {let tool = extract_string(raw, &["tool", "tool_name", "name"]).or_else(|| extract_string_path(raw, &[&["toolCall", "name"]]))@@ -1414,6 +1435,27 @@ mod tests {assert!(!ProjectSource::Unspecified.yields_to_session());}+ #[test]+ fn cline_context_uses_task_id_and_first_workspace_root() {+ let raw = serde_json::json!({+ "taskId": "cline-task-1",+ "workspaceRoots": ["/work/project", "/work/other"],+ "userPromptSubmit": {"prompt": "continue the audit"}+ });+ let context = hook_payload_context(&raw);+ assert_eq!(context.session_id.as_deref(), Some("cline-task-1"));+ assert_eq!(context.cwd.as_deref(), Some("/work/project"));+ let envelope = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "user-prompt".into(),+ agent: Some("cline".into()),+ ..Default::default()+ },+ raw,+ );+ assert_eq!(envelope.body_excerpt.as_deref(), Some("continue the audit"));+ }+#[test]fn omitted_style_stays_legacy_host_path_while_new_clients_send_path() {let envelope = |identity_style: Option<&str>| {diff --git a/crates/ai-memory-store/migrations/V85__sessions_cline_agent_kind.sql b/crates/ai-memory-store/migrations/V85__sessions_cline_agent_kind.sqlnew file mode 100644index 00000000..4ce9f3ee--- /dev/null+++ b/crates/ai-memory-store/migrations/V85__sessions_cline_agent_kind.sql@@ -0,0 +1,72 @@+-- Expand sessions.agent_kind CHECK for Cline CLI while preserving V84's+-- schema, indexes, and scope-pairing triggers.+--+-- `Store::open` turns foreign keys off around the migration runner (a PRAGMA+-- inside refinery's transaction is ignored). With them on, `DROP TABLE+-- sessions` would delete every observation, ingest key, and other row that+-- references a session through ON DELETE CASCADE.++DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_session_pairing_ai;+DROP TRIGGER IF EXISTS session_consolidation_jobs_session_pairing_ai;++CREATE TABLE sessions_new (+ id BLOB PRIMARY KEY NOT NULL,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','cursor','gemini-cli','claude-desktop','openclaw','antigravity-cli','omp','pi','crush','grok','zero','devin','kimi-code','kiro-cli','command-code','hermes','pool','zcode','grizzybot','copilot-cli','droid','muse','codebuddy','ibm-bob','dsh','cline','other')),+ cwd TEXT,+ started_at INTEGER NOT NULL,+ ended_at INTEGER,+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL,+ ended_observation_count INTEGER NOT NULL DEFAULT 0 CHECK (ended_observation_count >= 0),+ actor_user TEXT+);++INSERT INTO sessions_new (+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,+ summary_page_id, ended_observation_count, actor_user+)+SELECT+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,+ summary_page_id, ended_observation_count, actor_user+FROM sessions;++DROP TABLE sessions;++ALTER TABLE sessions_new RENAME TO sessions;++CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);+CREATE INDEX idx_sessions_project ON sessions(project_id);+CREATE INDEX idx_sessions_started_at ON sessions(started_at DESC);+CREATE INDEX idx_sessions_scope_ended+ ON sessions(workspace_id, project_id, ended_at ASC)+ WHERE ended_at IS NOT NULL;+CREATE INDEX idx_sessions_open_owner+ ON sessions(workspace_id, project_id, agent_kind, actor_user)+ WHERE ended_at IS NULL;++CREATE TRIGGER sessions_ws_proj_pairing_ai+BEFORE INSERT ON sessions+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)+BEGIN+ SELECT RAISE(ABORT, 'sessions.workspace_id does not match the project''s workspace');+END;++CREATE TRIGGER auto_improve_scheduler_claims_session_pairing_ai+BEFORE INSERT ON auto_improve_scheduler_claims+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)+BEGIN+ SELECT RAISE(ABORT, 'auto_improve_scheduler_claims scope does not match the session scope');+END;++CREATE TRIGGER session_consolidation_jobs_session_pairing_ai+BEFORE INSERT ON session_consolidation_jobs+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)+BEGIN+ SELECT RAISE(ABORT, 'session_consolidation_jobs scope does not match the session scope');+END;diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rsindex ae25055e..8a055ee3 100644--- a/crates/ai-memory-store/src/api_credentials.rs+++ b/crates/ai-memory-store/src/api_credentials.rs@@ -433,7 +433,7 @@ mod tests {|row| row.get(0),).unwrap();- assert_eq!(version, 84, "update the pin when adding a migration");+ assert_eq!(version, 85, "update the pin when adding a migration");let cols: i64 = conn.query_row("SELECT COUNT(*) FROM pragma_table_info('users') \diff --git a/docs/competitive-parity.md b/docs/competitive-parity.mdindex 46721c4c..9c33a77e 100644--- a/docs/competitive-parity.md+++ b/docs/competitive-parity.md@@ -290,7 +290,7 @@ invariants), **ALREADY** (we have it and should say so).| Larger capture caps | Keep ours (2 KB / 16 KiB) | Privacy boundary (invariant 6); the decomposition showed the caps were not the cause (pages holding exactly the captured text scored 0.968) || PaaS deploy templates (Fly, Railway, Render, Coolify) | DECLINE for now (a demand-gated docs recipe at most) | Non-loopback already refuses to run without auth; a hosted path is not our product || Redis or other external store backends | DECLINE | Invariants 2 and 3 (single-writer SQLite; indexes in the same transaction) and markdown as truth |-| Harness long tail (Droid, Warp, Cline, Kilo, Goose, Qwen Code, Aider, …) | SHIPPED (3.0) as MCP recipes for six more clients (Warp, Cline, Kilo Code, Goose, Qwen Code, OpenHuman), plus first-class Droid; hooks only where the harness has a lifecycle API (Droid accepted, #1240) | Any MCP client reaches us over HTTP |+| Harness long tail (Droid, Warp, Cline, Kilo, Goose, Qwen Code, Aider, …) | SHIPPED as first-class Droid and Cline CLI support plus MCP recipes for Warp, Kilo Code, Goose, Qwen Code and OpenHuman; hooks only where the harness has a lifecycle API | Any MCP client reaches us over HTTP || Image / vision memory | DECLINE | Off-mission; the sanitizer boundary is text-only || Bidirectional bridge with a harness's own `MEMORY.md` | DECLINE (bidirectional); one-way import ADOPT | Two sources of truth contradict our routing rule against harness-local stores || Obsidian vault export | ALREADY | The wiki is already markdown in git; open `<data_dir>/wiki/<ws>/<project>` as a vault |diff --git a/docs/install.md b/docs/install.mdindex ae533a8c..db22acb8 100644--- a/docs/install.md+++ b/docs/install.md@@ -20,7 +20,7 @@ RPM, macOS menu bar app). This page covers everything else:- [macOS menu bar app](#macos-menu-bar-app)(self-contained `.app` + LaunchAgent)- [Configuring other agent CLIs](#configuring-other-agent-clis)- (Codex, Command Code, IBM Bob, Devin CLI, OpenCode, OpenCode 2, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, GitHub Copilot CLI, Factory Droid, Meta Muse Code, CodeBuddy Code, Hermes Agent, Zero, ZCode, Kimi Code, Kiro CLI, Pool, OpenClaw, VS Code Copilot, Zed, and MCP-only recipes for Warp, Cline, Kilo Code, Goose, Qwen Code and OpenHuman)+ (Codex, Command Code, IBM Bob, Devin CLI, OpenCode, OpenCode 2, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, GitHub Copilot CLI, Factory Droid, Meta Muse Code, CodeBuddy Code, Hermes Agent, Zero, ZCode, Kimi Code, Kiro CLI, Cline CLI, Pool, OpenClaw, FreeBuff, VS Code Copilot, Zed, and MCP-only recipes for Warp, Kilo Code, Goose, Qwen Code and OpenHuman)- [Installing hooks without docker](#installing-hooks-without-docker)(curl-based installer)- [Running ai-memory without docker](#running-ai-memory-without-docker)@@ -2326,6 +2326,37 @@ handoff injection at session start or the client's closest equivalent, exceptfor Zero's no-stdout SessionStart behavior. Grok delivers on the first`PostToolUse` instead (Antigravity CLI uses `PreInvocation`).+#### Cline CLI and FreeBuff++Cline CLI is a first-party hooks + MCP integration:++```bash+ai-memory install-mcp --client cline --apply+ai-memory install-hooks --agent cline --apply+```++The MCP writer reads `CLINE_MCP_SETTINGS_PATH` or defaults to+`~/.cline/data/settings/cline_mcp_settings.json`; it writes the nested+`transport` object and explicitly selects `streamableHttp` rather than Cline's+legacy SSE default. The hook writer targets the CLI's `~/.cline/hooks` files;+use `--scope project` for `.cline/hooks` in one checkout. Restart Cline after+installation. Yolo mode disables Cline hooks, and task-start hooks are+detached, so recover pending handoffs through MCP. The VS Code extension's+separate `~/Documents/Cline/Hooks` convention is not modified.++FreeBuff is MCP-only:++```bash+ai-memory install-mcp --client freebuff --apply+```++This merges a sessionless stdio bridge under `mcpServers` in+`~/.agents/mcp.json`. FreeBuff finds that file while walking from the current+directory to the home directory and already reads `AGENTS.md`. A file-backed+server bearer stays in ai-memory's data directory; an explicit `--auth-token`+is stored in the stdio entry's environment map. No lifecycle hooks or managed+workstream are claimed.+#### Clients without an `install-mcp` writerThe clients below can reach ai-memory over streamable HTTP, but `install-mcp`@@ -2350,8 +2381,8 @@ expands environment variables in its config, the example reads the tokenfrom `AI_MEMORY_AUTH_TOKEN`; export it in the shell that starts the client.Where the client documents no expansion, the example shows `<token>`, and thetoken has to be written into that file, so keep the file private. All of-these clients speak HTTP MCP natively; `ai-memory mcp-bridge` is a Claude-Code-only adapter and is not needed.+these clients speak HTTP MCP natively, so `ai-memory mcp-bridge` is not needed+for these hand-written recipes.##### Warp@@ -2379,34 +2410,6 @@ v0.2026.10.07.08.29.Sources: <https://docs.warp.dev/agents/capabilities/mcp>,<https://docs.warp.dev/agents/cli/configuration/>.-##### Cline--The Cline CLI reads `~/.cline/data/settings/cline_mcp_settings.json`-(override the path with `CLINE_MCP_SETTINGS_PATH`). In the VS Code extension,-open the **MCP Servers** icon, then **Configure > Configure MCP Servers**, and-edit the same `mcpServers` map. Set `type` to `streamableHttp`: without it,-Cline falls back to the legacy SSE transport.--```json-{- "mcpServers": {- "ai-memory": {- "type": "streamableHttp",- "url": "http://127.0.0.1:49374/mcp",- "headers": { "Authorization": "Bearer <token>" },- "disabled": false- }- }-}-```--Cline does not document environment-variable expansion in `headers`. Leave-out `headers` when the server has no bearer token; in that case the CLI can-write the entry with-`cline mcp add ai-memory http://127.0.0.1:49374/mcp --transport http`.-Documented for the Cline extension 4.1.23 and CLI 3.0.70.-Source: <https://docs.cline.bot/mcp/mcp-overview>.-##### Kilo CodeThe Kilo Code VS Code extension and the Kilo CLI share one config:diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex bc8c0468..42f9a8ec 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -3,7 +3,7 @@For a custom tool, start with the [programmatic memory guide](programmatic-memory.md).It shows direct MCP writes, queries and handoffs without a native hook adapter.-Warp, Cline, Kilo Code, Goose, Qwen Code and OpenHuman have no+Warp, Kilo Code, Goose, Qwen Code and OpenHuman have no`install-mcp` client; their hand-written recipes are in[`install.md`](install.md#clients-without-an-install-mcp-writer).@@ -177,11 +177,49 @@ metadata.> **One-shot tip:** every snippet below is also reachable from the> CLI:> ```bash-> ai-memory install-mcp --client gemini-cli # or cursor / claude-desktop / openclaw / omp / pi / antigravity-cli / grok / kimi-code / kiro-cli / command-code / swival / devin / zero / zcode / copilot-cli / vscode-copilot / zed / muse / dsh / prime-agent+> ai-memory install-mcp --client gemini-cli # or cursor / claude-desktop / openclaw / omp / pi / antigravity-cli / grok / kimi-code / kiro-cli / command-code / swival / devin / zero / zcode / copilot-cli / vscode-copilot / zed / muse / dsh / cline / freebuff / prime-agent> ```---+## Cline CLI++```bash+ai-memory install-mcp --client cline --apply+ai-memory install-hooks --agent cline --apply+```++The MCP writer targets+`${CLINE_MCP_SETTINGS_PATH:-~/.cline/data/settings/cline_mcp_settings.json}`+and writes Cline's nested `transport` schema with+`type: "streamableHttp"`; omitting that type makes Cline try legacy SSE. The+hook writer creates Cline CLI's supported event files under `~/.cline/hooks`.+Use `--scope project` for `.cline/hooks` in the current checkout. Existing+user-owned event files and symlinked targets are refused, and generated files+that carry a bearer token are owner-only.++Cline runs task-start hooks detached, so accept a pending handoff through MCP+(`memory_handoff_list`, then `memory_handoff_accept`). Restart Cline after+installing. Cline's yolo mode disables hooks. The VS Code extension has a+separate hook directory and is not changed by this CLI integration.++## FreeBuff++```bash+ai-memory install-mcp --client freebuff --apply+```++FreeBuff reads `mcpServers` from `.agents/mcp.json` while walking from the+current directory toward the home directory. The installer writes the home+file and registers a local `ai-memory mcp-bridge --no-session-id` stdio+process, which forwards to the configured server and reads a file-backed token+without copying it into FreeBuff's config. An explicit `--auth-token` is stored+in the stdio entry's `AI_MEMORY_AUTH_TOKEN` environment map, like a bearer+header in an HTTP-only client. FreeBuff has no lifecycle-hook or+managed-workstream integration; it already reads `AGENTS.md`.++---+## Claude Code**Status:** ✅ Native HTTP MCP supported. ✅ Optional session-aware stdiodiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 5243465e..5c7260b5 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -23,6 +23,7 @@ means the boundary is not built yet.| # | Boundary | Enforcing code | Adversarial test(s) | Coverage ||---|----------|----------------|---------------------|----------|| 0a | A generated DSH hook config cannot expose or redirect an embedded server bearer | `ai-memory-cli/src/commands/install_hooks.rs` `write_private_dsh_config` creates `hooks.json` owner-only before writing, resets a pre-existing file to `0600`, and refuses a final-component symlink | `install_hooks.rs` `apply_to_dsh_keeps_an_embedded_bearer_owner_only` (a world-readable predecessor becomes private before the new bearer is written; the bearer control is present), `apply_to_dsh_refuses_a_symlinked_hook_config` (an attempted redirect is refused and its target stays byte-identical) | STRONG on Unix; Windows protection remains the data directory ACL |+| 0b | Generated Cline CLI hook files cannot overwrite user hooks or redirect an embedded server bearer | `ai-memory-cli/src/commands/install_hooks.rs` `apply_to_cline_hooks` accepts only an absent or ai-memory-owned event file, refuses a final-component symlink, writes atomically, and sets each generated file to owner-only executable mode | `install_hooks.rs` `cline_apply_writes_native_event_hooks_without_overwriting_user_files` (all nine generated files are `0700`, a bearer is present, and a user-owned control remains byte-identical), `cline_apply_refuses_a_symlinked_hook_without_touching_its_target` (redirect refused, target byte-identical) | STRONG on Unix; Windows protection remains the user profile ACL || 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `sessions_for_scope_filtered` joins only consolidation jobs in the requested workspace and project; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit; `reader.rs` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project; `reader.rs` `observation_stream_votes` (`[retrieval] observation_stream`, on by default) filters both the matching observations and the `sessions/<id>.md` page they vote for to the queried workspace and project, and attaches a vote's observation excerpt and ids only when the caller's session-timeline owner filter admits the session (`sessions_hidden_from`; `HybridSearch::owner`, threaded from `memory_query`, `/web/search` and `/api/v1/search` through `OwnerFilter::for_actor_context`); the raw-observation fallback `search_observations_for_project_as` drops sessions that filter does not admit; `reader.rs` `page_versions` / `page_version_body` (web page history) read by `(workspace_id, project_id, path)` and take a caller's version id only inside that triple; `ai-memory-web` `routes/session.rs` takes a raw session id only through `session_summary_scoped` (row or observation in the project, owner filter) and `session_observations_scoped` | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `consolidation_summary_latest_generation_is_scope_and_owner_bound` (a foreign-scope job is absent; the own latest generation and owner controls pass), `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control), `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can); handoff receiver-session scope: see row 4, `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (cross-project and cross-workspace receivers refused); `multi_session.rs` `observation_stream_never_crosses_a_project_or_workspace` (a home observation cannot vote for a same-path session page in another project or workspace, and a foreign project's observation cannot lift a home page; control: home's own page receives the vote), fails with either the observation or the page scope filter removed; `multi_session.rs` `observation_excerpts_follow_the_session_owner_while_the_vote_stays_shared` (operator B, and an unattributed caller, querying words only A's owned session holds get A's shared session page with its own snippet, no excerpt, no observation ids and no raw hit; controls: A gets the excerpt, ids and raw hit, an unattributed session's excerpt reaches every viewer, and the unfiltered single-user path is unchanged), bite-checked against both the vote guard and the raw-fallback clause; `ai-memory-mcp` `server.rs` `memory_query_shows_observation_text_only_to_its_sessions_owner` and `ai-memory-web` `recall_trace.rs` `project_search_shows_observation_excerpts_only_to_the_sessions_owner` (the same through `memory_query`, `/web/search` and `/api/v1/search`; each fails when its surface passes `OwnerFilter::Any`); `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope` (a sibling project's or another workspace's version id, or a home id under another path, reads as `None`; control: both home versions); `ai-memory-web` `history_replay.rs` `history_refuses_foreign_project_workspace_and_version_ids` (another project's or workspace's path, and a foreign version id as `from` or `to`, answer 404 on `/web/w/…/h/*path` and `/api/v1/…/history/*path` without the foreign text; control: the home history lists only home's rows at a path a sibling also uses, and an explicit home pair diffs) and `session_timeline_refuses_foreign_session_ids` (a sibling project's or another workspace's session id and an unknown id → 404, another operator's owned session → 404; controls: the home session, and the owner reading theirs); bite: dropping the scope filter from `page_version_body` or the project filter from `page_versions`, or replacing the `session_summary_scoped` check or its owner filter, fails them | STRONG || 1b | Reserved `_global` scope union never leaks a foreign project (#930) | `ai-memory-mcp/src/server.rs` `memory_query` — the union runs for single-project queries (`scopes` empty) and searches **only** `lookup_global_scope`'s reserved `(workspace_id, project_id)`, never an arbitrary project; the double-search guard resolves the *queried* project (named or active) so it can't be tricked into skipping | `server.rs` `global_union_never_leaks_a_foreign_projects_pages` (a third real project's page must not surface via the union; reserved page must), `single_project_query_unions_global_scope_and_multi_scope_skips_it` | STRONG || 1c | Reserved `_global` scope is read-open, write-gated (GHSA-7qj3-7wqw-m5w6) | `ai-memory-store/src/project_authz.rs` `ProjectAuthz::authorize` (a write to `default/_global` needs root or a `write` grant in either access mode; creator ignored) fed by `resolve_project_authz`/`read_project_row` (`reserved_global`, grant read for the global scope regardless of mode); `ai-memory-mcp/src/server.rs` `memory_write_page` resolves `scope: "global"` through `write_target_ids_with_actor` like an explicit `default/_global` | `project_authz.rs` `the_global_scope_admits_writes_only_from_root_or_a_write_grant`; `server.rs` `a_user_without_a_global_grant_cannot_change_the_global_scope` (both spellings and delete refused for an ungranted user and for `_global`'s creator; page survives; reads stay open), `a_global_write_grant_admits_writes_and_the_union_stays_readable` (legitimate control: write grant admits both spellings, another user's restricted-project query still unions the page); bite-checked with the authz rule removed and with the raw `create_global_scope` path restored | STRONG |diff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex b6261598..b93e5587 100644--- a/docs/support-matrix.md+++ b/docs/support-matrix.md@@ -46,13 +46,14 @@| Meta Muse Code | Supported | MCP config (`install-mcp --client muse`, aliases `muse-code`, `musecode`) + lifecycle hooks (`install-hooks --agent muse`), both merged into `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json` around your own keys, servers and hooks. The writers add the mandatory `"schema_version": 1` when it is absent (without it every `muse` command fails at startup) and never rewrite an existing value. The MCP entry is a stdio `ai-memory mcp-bridge --agent muse` that forwards the `MUSE_SESSION_ID` Muse gives its stdio servers, so Muse is session-aware; it carries `"mode": "optional"` (Muse's default `required` aborts the run when a server cannot start) and the install's `--data-dir`, because Muse starts stdio servers and hooks with a cleared environment. It goes under `mcpServers`, or under the legacy `mcp_servers` when the file already uses it; Muse ignores every MCP server when both maps are present, so `--apply` refuses that file and `doctor` reports it. Hooks run the native `ai-memory hook --event … --agent muse` command (no script bundle) with an empty matcher and a 30-second timeout, and native commands enforce capture exclusions over Muse's `read_file`, `write_file`, `edit_file`, `apply_patch`, `search`, `bash`, `monitor`, `web_fetch` and memory tools; a relative `path` resolves lexically against `cwd`, and Muse's `tool_use_id` is kept as the call id. Eight events: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PreCompact`, `Stop`, `SessionEnd`; `SubagentStart`/`SubagentStop` are left out because Muse fires them every turn for its built-in reminder observers. The `SessionStart` hook delivers the prior session's handoff through `hookSpecificOutput.additionalContext`, and Muse's own `SessionEnd` closes the session. Verified offline against Muse Code 1.4.7: hook capture, exclusions, MCP session routing and handoff injection, run end to end in an isolated network namespace with a stand-in model provider. Skills need no extra step: Muse reads `~/.agents/skills` and `AGENTS.md`. `setup` detects Muse by its config or data directory. No managed workstream (`ai-memory run muse`) and no transcript backfill. See [`install.md`](install.md#meta-muse-code). || IBM Bob | Supported | Native Streamable HTTP MCP in `~/.bob/settings/mcp.json` plus five lifecycle hooks shared by Bob IDE and Bob Shell in `~/.bob/settings/settings.json`. `SessionStart` injects the prior handoff as plain context, and Claude-shaped tool events enforce capture exclusions. Bob exposes no true `SessionEnd`, so run `ai-memory finalize-session --agent ibm-bob` after the final turn. `ai-memory run ibm-bob` and transcript backfill are not claimed because Bob does not document a stable transcript-store contract. See [`mcp-install.md`](mcp-install.md#ibm-bob). || DeepSeek Harness (DSH) | Hooks + MCP | MCP: `install-mcp --client dsh` (aliases `deepseek-harness`, `deepseek_harness`) prints a Cordis patch fragment (a `- insert:` item for `@deepseek-ai/dsh-mcp-client`) to merge into `$DSH_HOME/profiles/<profile>/cordis.patch.yml`; DSH has no fixed MCP config file, so `--apply` is refused. Lifecycle hooks: `install-hooks --agent dsh` stages the `hooks/dsh` script bundle, generates a Claude Code `hooks.json` for DSH's official `@deepseek-ai/dsh-hooks-claude-code` bridge, and prints the bridge patch fragment — again merged by hand into `cordis.patch.yml` (the generated `hooks.json` itself is written to the data dir by `--apply`). The bridge delivers exactly seven Claude Code events (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`, `SubagentStart`, `SubagentStop`) — no `PreCompact` or `SessionEnd` — and runs `SessionStart` detached, so DSH sessions are stored as `agent=dsh`, pending handoffs are recovered via MCP `memory_handoff_list` then `memory_handoff_accept`, and finished sessions close with `ai-memory finalize-session --agent dsh`. No managed workstream. |+| Cline CLI | Hooks + MCP | `install-mcp --client cline --apply` merges Cline's required nested `transport` entry into `${CLINE_MCP_SETTINGS_PATH:-~/.cline/data/settings/cline_mcp_settings.json}` and explicitly selects Streamable HTTP (a bare URL selects legacy SSE). `install-hooks --agent cline --apply` writes the nine supported CLI event files to `~/.cline/hooks` (or project `.cline/hooks` with `--scope project`): task start/resume, prompt, pre/post tool, complete/cancel/error, and shutdown. The generated owner-only files refuse user-owned files and final-component symlinks. Cline starts task hooks detached, so pending handoffs are accepted through MCP; yolo mode disables hooks, and Cline must be restarted after installation. This installs Cline CLI hooks only; the VS Code extension uses a separate `~/Documents/Cline/Hooks` convention. No managed workstream. |+| FreeBuff | MCP-only | `install-mcp --client freebuff --apply` merges an `ai-memory mcp-bridge --no-session-id` stdio entry into `~/.agents/mcp.json`. FreeBuff discovers that file from the current directory, its parents, or the home directory and already reads `AGENTS.md`; it has no documented lifecycle-hook or managed-workstream surface. The bridge reaches the configured local or remote server without attempting to start a second server that would contend for the data-dir lock. || Prime Agent | MCP-only | `install-mcp --client prime-agent` merges an HTTP entry (`type: "http"` + `url`) into the `mcpServers` map of `$PRIME_AGENT_CODING_AGENT_DIR/settings.json` (default `~/.prime/agent/settings.json`), preserving other settings and servers; a project's `.prime/agent/settings.json` works through `--config-file`. A token is referenced as `"bearerTokenEnvVar": "AI_MEMORY_AUTH_TOKEN"`, never written: Prime Agent 0.10 counts a user HTTP server as connected and names it in the model's prompt only with that variable set or an OAuth grant. A credential-less entry is still callable through `mcp.call_tool("ai-memory", ...)` but is not listed. The model reaches MCP tools from its Python REPL (`await mcp.call_tool("ai-memory", "memory_query", {...})`), and Prime Agent sends no session id or cwd, so pass `workspace` and `project` on project-scoped calls. Lifecycle capture and managed workstreams are not claimed: Prime Agent 0.10 removed the TypeScript extensions its 0.9 releases had and has no hook surface. Verified against Prime Agent 0.10.0. || Hermes Agent | Supported | `install-hooks --agent hermes` (alias `hermes-agent`) prints a ready-to-paste `hooks:` block for `~/.hermes/config.yaml`. Hermes splits each configured `command` with `shlex.split` and runs it with no shell, passing the event JSON on stdin, so the entries invoke the native `ai-memory hook` command (exec form, like Zero and ZCode — no script bundle is staged); ai-memory never writes that YAML file, which is yours to edit and which Hermes itself gates behind its hook-acceptance prompt (`hooks_auto_accept`). Two tool events are wired, `pre_tool_call` → `pre-tool-use` and `post_tool_call` → `post-tool-use`; their `tool_name` / `tool_input` payload drives concrete session attribution, tool-family titles, and capture exclusions. Hermes reports its own process directory as `cwd`, so the native hook locates each event's `.ai-memory.toml` from the tool's absolute `workdir` (`terminal`) or `path` (file tools, `search_files`); a call with no absolute location stays with the process directory. Session lifecycle (recall, prompt capture, session-end, automatic handoff) is owned by the community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) memory provider, so no hook-driven `session-end` is installed and nothing is duplicated; review that plugin's compatibility matrix, install/uninstall scripts, and secret handling before enabling it. No first-party `install-mcp` client and no managed workstream are claimed yet, and because Hermes ignores session-start hook stdout a pending handoff is recovered through MCP (`memory_handoff_list` then `memory_handoff_accept`). || GrizzyBot | Supported | [GrizzyBot](https://github.com/Foscoe63/GrizzyBot), a native macOS agent app, ships its own ai-memory bridge: it posts lifecycle events to `/hook` with `agent=grizzybot` (alias `grizzy-bot`) and talks to `/mcp` directly, so there is nothing for `install-hooks` or `install-mcp` to write. Sessions are attributed to `grizzybot`, and its Claude Code-shaped tool payloads (`tool_name`/`tool_input`/`tool_use_id`) are stored as closed-schema tool families, never tool names or arguments. The bridge is maintained in the GrizzyBot repository; review it before pointing it at a shared server. No managed workstream. || Factory Droid | Supported | MCP config (`install-mcp --client droid`, alias `factory-droid` → `~/.factory/mcp.json`, root `mcpServers`, `type: "http"`) + lifecycle hooks (`install-hooks --agent droid` → `~/.factory/hooks.json`) (#1240). The URL is written literally because Droid expands `${VAR}` only in headers; a bearer becomes `Authorization: Bearer ${AI_MEMORY_AUTH_TOKEN}`, so export that variable where droid runs (a token-file install gets the same reference, never the token). Droid sends Claude Code-shaped hook payloads, so each entry runs the native `ai-memory hook --event … --agent droid` command (no script bundle) and native commands enforce capture exclusions over Droid's `Read`, `Create`, `Edit`, `ApplyPatch`, `LS`, `Grep`, `Glob` and `Execute` tools, verified against the Droid 0.240.0 tool schemas; Droid payloads carry no tool-call id. Seven events: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`, `SessionEnd`. The `SessionStart` hook delivers the prior session's handoff through `hookSpecificOutput.additionalContext`, and Droid's own `SessionEnd` closes the session, so no `finalize-session` step is needed. `--apply` merges around your own entries, and refuses to create `hooks.json` while `~/.factory/settings.json` keeps hooks under its `hooks` key, because Droid reads those only while `hooks.json` is absent. The issue reporter ran capture and recall end to end with this hook wiring on Droid 0.239.0; the handoff injection follows Droid's documented contract and has not been run end to end yet. No managed workstream (`ai-memory run droid`). See [`install.md`](install.md#factory-droid). || CodeBuddy Code | Hooks-only | Tencent CodeBuddy Code (`codebuddy`, alias `code-buddy`). Lifecycle-hook capture via `install-hooks --agent codebuddy --apply`: native `ai-memory hook` commands (no script bundle) merged into the `hooks` key of `~/.codebuddy/settings.json` around sibling settings and third-party hooks. Payloads are Claude Code-shaped (`session_id`, `cwd`, `tool_name`, `tool_input`, `tool_response`), so tool observations and capture exclusions use that parser. Seven events: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`, `SessionEnd`. `SessionStart` stdout (`hookSpecificOutput.additionalContext`) delivers the prior session's handoff; with nothing to deliver, `SessionStart` and `UserPromptSubmit` print nothing, because CodeBuddy appends that stdout to the session. An interactive `SessionStart` may arrive without `cwd`; the hook then uses the `CODEBUDDY_PROJECT_DIR` CodeBuddy exports, and when neither names a directory it captures the event but claims no handoff, which stays open for `memory_handoff_accept`. `setup` detects CodeBuddy when `~/.codebuddy` exists. No `install-mcp` client, no transcript backfill, no headless `codebuddy -p` session close and no managed workstream are claimed. Verified against CodeBuddy's hook documentation and the payloads reported on v2.164–v2.167 (#1299); not yet run end to end by the maintainers. See [`install.md`](install.md#codebuddy-code). || Warp | MCP-only (documented) | `url` + `headers` entry in `~/.warp/.mcp.json` or **Settings > Agents > MCP servers**; no documented env-var expansion in headers. No `install-mcp` client and no lifecycle hooks. Documented against Warp v0.2026.10.07.08.29, not yet verified end to end. See [`install.md`](install.md#warp). |-| Cline | MCP-only (documented) | `type: "streamableHttp"` entry under `mcpServers` (CLI: `~/.cline/data/settings/cline_mcp_settings.json`; extension: **MCP Servers > Configure**); without `type` Cline uses legacy SSE. No `install-mcp` client and no lifecycle hooks installed. Documented against Cline extension 4.1.23 / CLI 3.0.70, not yet verified end to end. See [`install.md`](install.md#cline). || Kilo Code | MCP-only (documented) | `type: "remote"` entry under `mcp` in `~/.config/kilo/kilo.jsonc` (shared by the VS Code extension and the CLI), with `"oauth": false` and the bearer header from `{env:AI_MEMORY_AUTH_TOKEN}`. No `install-mcp` client and no lifecycle hooks installed. Documented against Kilo Code 7.8.8, not yet verified end to end. See [`install.md`](install.md#kilo-code). || Goose | MCP-only (documented) | `type: streamable_http` extension (URL key `uri`) in `~/.config/goose/config.yaml`, added with `goose configure`; no documented env-var expansion in headers. No `install-mcp` client and no lifecycle hooks installed. Documented against Goose 1.54.0, not yet verified end to end. See [`install.md`](install.md#goose). || Qwen Code | MCP-only (documented) | `httpUrl` entry under `mcpServers` in `~/.qwen/settings.json`; the bearer header reads `${AI_MEMORY_AUTH_TOKEN}`, which Qwen Code expands. No `install-mcp` client and no lifecycle hooks installed. Documented against Qwen Code 0.25.1, not yet verified end to end. See [`install.md`](install.md#qwen-code). |