Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(hooks): register CodeBuddy Code as a first-party agent
Gabriel Alencar34399d9af3e9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 53f77b46..59b3e9a2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,23 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]+### Added+- Added first-party CodeBuddy Code (Tencent) support. `codebuddy` is an+ `AgentKind` (migration V81), so hook events are attributed to it and a+ Claude Code-shaped tool payload (`tool_name`, `tool_input`, `tool_response`)+ is stored as a closed tool observation instead of an empty `other` capture.+ `install-hooks --agent codebuddy` (alias `code-buddy`) merges native+ `ai-memory hook --event … --agent codebuddy` commands for seven events+ (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,+ `PreCompact`, `Stop`, `SessionEnd`) into the `hooks` key of+ `~/.codebuddy/settings.json`, keeps sibling settings and your own hooks,+ and changes nothing on a re-run. There is no script bundle. The+ `SessionStart` hook delivers the pending handoff through+ `hookSpecificOutput.additionalContext`. `setup` wires CodeBuddy when+ `~/.codebuddy` exists, `setup-agent --agent codebuddy` prints the hook+ block, and `uninstall` removes the entries. Transcript backfill and+ headless `codebuddy -p` session close are not part of this change. (#1299)+### Fixed- Fixed the thin-client commands ignoring a custom `bind`, which could writeinto the wrong store. `server_url` defaulted to `http://127.0.0.1:49374`diff --git a/README.md b/README.mdindex ca9b0c18..baa5b122 100644--- a/README.md+++ b/README.md@@ -144,6 +144,7 @@ caveats is in [`docs/support-matrix.md`](docs/support-matrix.md).| GitHub Copilot CLI | Supported || Factory Droid | Supported || Meta Muse Code | Supported |+| CodeBuddy Code | Hooks-only || VS Code Copilot | MCP-only || Zed | MCP-only || DeepSeek Harness (DSH) | MCP-only |diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 2834f73a..75b8a4d7 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -2432,6 +2432,13 @@ pub enum AgentChoice {/// Muse's own `SessionEnd` closes the session.#[value(alias = "muse-code", alias = "musecode")]Muse,+ /// Tencent CodeBuddy Code (`codebuddy`) — lifecycle hooks merged into the+ /// `hooks` key of `~/.codebuddy/settings.json`. CodeBuddy sends Claude+ /// Code-shaped hook payloads on stdin, so each entry runs ai-memory's+ /// native `hook` command directly; there is no script bundle. SessionStart+ /// stdout (`hookSpecificOutput.additionalContext`) carries the handoff.+ #[value(name = "codebuddy", alias = "code-buddy")]+ CodeBuddy,}impl AgentChoice {@@ -2465,6 +2472,7 @@ impl AgentChoice {Self::CopilotCli => AgentKind::CopilotCli,Self::Droid => AgentKind::Droid,Self::Muse => AgentKind::Muse,+ Self::CodeBuddy => AgentKind::CodeBuddy,}}@@ -2485,7 +2493,8 @@ impl AgentChoice {| Self::Zcode| Self::Hermes| Self::Droid- | Self::Muse => None,+ | Self::Muse+ | Self::CodeBuddy => None,_ => Some(self.kind().as_str()),}}@@ -4574,6 +4583,20 @@ mod tests {}}+ #[test]+ fn codebuddy_install_hooks_parses_with_the_kebab_alias() {+ for alias in ["codebuddy", "code-buddy"] {+ let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", alias])+ .unwrap_or_else(|error| panic!("{alias}: {error}"));+ let Command::InstallHooks(args) = hooks.command else {+ panic!("expected install-hooks");+ };+ assert_eq!(args.agent, AgentChoice::CodeBuddy);+ assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::CodeBuddy);+ assert_eq!(args.agent.script_hook_subdir(), None);+ }+ }+#[test]fn muse_install_hooks_install_mcp_and_mcp_bridge_parse_with_their_aliases() {for alias in ["muse", "muse-code", "musecode"] {diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex c8aea8de..251f42ad 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -439,6 +439,15 @@ pub(crate) fn muse_settings_path(install_mcp::muse_settings_path_in(env.var_os("XDG_CONFIG_HOME"), home_dir())}+/// `~/.codebuddy/settings.json` — Tencent CodeBuddy Code's user settings.+/// The root `hooks` block is Claude Code's nested shape (#1299).+pub(crate) fn codebuddy_settings_path() -> anyhow::Result<std::path::PathBuf> {+ Ok(home_dir()+ .context("could not locate $HOME for ~/.codebuddy/settings.json")?+ .join(".codebuddy")+ .join("settings.json"))+}+/// `~/.config/zero/hooks.json` — Zero's user-level lifecycle hook config/// (issue #156). Zero resolves it under `$XDG_CONFIG_HOME` falling back to/// `~/.config`; like the OpenCode plugin path below we target the default@@ -982,6 +991,13 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(.context("internal: the Muse settings path is resolved before apply")?;apply_to_muse_settings(&path, &server_url, auth, &config.data_dir, &args)}+ AgentChoice::CodeBuddy => {+ let path = match &args.config_file {+ Some(path) => path.clone(),+ None => codebuddy_settings_path()?,+ };+ apply_to_codebuddy_settings(&path, &server_url, auth, &config.data_dir, &args)+ }};}let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);@@ -1138,6 +1154,7 @@ pub(crate) fn run_with_opencode_dialect_and_mcp_path(}AgentChoice::Droid => render_droid(&server_url, auth, &config.data_dir, strategy),AgentChoice::Muse => render_muse(&server_url, auth, &config.data_dir, strategy),+ AgentChoice::CodeBuddy => render_codebuddy(&server_url, auth, &config.data_dir, strategy),}}@@ -1332,6 +1349,7 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {AgentChoice::Droid => droid_hooks_path().ok()?,// `run` resolves it into `args.config_file` before any caller.AgentChoice::Muse => return None,+ AgentChoice::CodeBuddy => codebuddy_settings_path().ok()?,}};std::fs::read_to_string(path).ok()@@ -1759,6 +1777,8 @@ pub(crate) fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {AgentChoice::CopilotCli => Some(McpClient::CopilotCli),AgentChoice::Droid => Some(McpClient::Droid),AgentChoice::Muse => Some(McpClient::Muse),+ // No first-party CodeBuddy MCP installer in this change.+ AgentChoice::CodeBuddy => None,}}@@ -7104,6 +7124,91 @@ fn render_droid(Ok(())}+/// Merge ai-memory's entries into the `hooks` key of CodeBuddy's+/// `settings.json`, keeping every other key and every other hook,+/// idempotently.+fn apply_to_codebuddy_settings(+ path: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+) -> Result<()> {+ let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);+ let payload = super::render_shared::build_codebuddy_hooks_payload(+ server_url,+ auth_token,+ Some(data_dir),+ strategy,+ );+ let our_hooks = payload+ .get("hooks")+ .and_then(serde_json::Value::as_object)+ .context("internal: build_codebuddy_hooks_payload didn't return a hooks object")?;+ let outcome = apply_atomic(path, |existing| {+ mutate_json(existing, |root| {+ let hooks = root+ .entry("hooks")+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))+ .as_object_mut()+ .context("`hooks` is present in the CodeBuddy settings.json but not an object")?;+ for (event, value) in our_hooks {+ overlay_event_hooks(hooks, event, value);+ }+ Ok(())+ })+ })?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ print!("{CODEBUDDY_INSTALL_NOTES}");+ Ok(())+}++const CODEBUDDY_INSTALL_NOTES: &str = "\+# NOTE: CodeBuddy appends SessionStart stdout (`hookSpecificOutput.additionalContext`)+# to the session, so the prior session's handoff is delivered automatically.+# NOTE: start a new codebuddy session for it to load the new hooks.+";++/// Print the `hooks` block for `~/.codebuddy/settings.json` (dry-run+/// counterpart of [`apply_to_codebuddy_settings`]).+fn render_codebuddy(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+) -> Result<()> {+ let payload = super::render_shared::build_codebuddy_hooks_payload(+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ let serialized = serde_json::to_string_pretty(&payload["hooks"])+ .context("serializing codebuddy hook config")?;+ println!("# CodeBuddy Code hook config — merge under the `hooks` key of");+ println!("# ~/.codebuddy/settings.json, or re-run with --apply to merge it in");+ println!("# place.");+ println!("# AI-memory server URL: {server_url}");+ if auth_token.is_some() {+ println!("# Auth: this printed snippet embeds the token in each hook command —");+ println!("# treat settings.json as sensitive (chmod 600). `--apply` stores it");+ println!("# under the data dir instead.");+ }+ print!("{CODEBUDDY_INSTALL_NOTES}");+ println!();+ println!("{serialized}");+ Ok(())+}+/// Merge ai-memory's entries into the `hooks` key of Muse's `settings.json`,/// keeping `schema_version`, every unknown key and every other hook in it,/// idempotently, with a backup next to the file on change. Muse fails every@@ -8079,6 +8184,75 @@ mod tests {}}+ /// `install-hooks --agent codebuddy --apply` merges native `--agent+ /// codebuddy` commands under the `hooks` key of `settings.json`, keeps+ /// sibling keys and third-party hooks, and a re-apply changes nothing.+ #[test]+ fn codebuddy_apply_merges_native_hooks_under_the_settings_hooks_key() {+ let home = TempDir::new().unwrap();+ let data = TempDir::new().unwrap();+ let settings = home.path().join("settings.json");+ fs::write(+ &settings,+ serde_json::json!({+ "model": "deepseek-v4.1-flash",+ "hooks": {+ "PreToolUse": [{+ "matcher": "Bash",+ "hooks": [{"type": "command", "command": "/usr/local/bin/guard.sh"}]+ }]+ }+ })+ .to_string(),+ )+ .unwrap();+ let args = InstallHooksArgs {+ agent: AgentChoice::CodeBuddy,+ config_file: Some(settings.clone()),+ ..default_hook_args()+ };++ apply_to_codebuddy_settings(&settings, "http://memory:49374", None, data.path(), &args)+ .unwrap();+ let first = fs::read_to_string(&settings).unwrap();+ apply_to_codebuddy_settings(&settings, "http://memory:49374", None, data.path(), &args)+ .unwrap();+ assert_eq!(+ first,+ fs::read_to_string(&settings).unwrap(),+ "re-apply is a no-op"+ );++ let root: serde_json::Value = serde_json::from_str(&first).unwrap();+ assert_eq!(root["model"], "deepseek-v4.1-flash");+ for (event, script) in super::super::render_shared::CODEBUDDY_EVENTS {+ let entries = root["hooks"][event].as_array().unwrap();+ let ours: Vec<_> = entries+ .iter()+ .filter(|entry| is_ai_memory_hook_entry(entry))+ .collect();+ assert_eq!(ours.len(), 1, "{event}: exactly one ai-memory entry");+ assert_eq!(ours[0]["matcher"], "", "{event}");+ let command = ours[0]["hooks"][0]["command"].as_str().unwrap();+ let stem = script.trim_end_matches(".sh");+ assert!(+ command.contains(&format!(+ " hook --event {stem} --agent codebuddy --server-url "+ )),+ "{event}: {command}"+ );+ assert!(+ !command.contains(".sh"),+ "{event}: no script bundle: {command}"+ );+ }+ assert!(root["hooks"].get("SubagentStart").is_none());+ assert!(root["hooks"].get("PostToolUseFailure").is_none());+ let pre = root["hooks"]["PreToolUse"].as_array().unwrap();+ assert_eq!(pre.len(), 2);+ assert_eq!(pre[0]["hooks"][0]["command"], "/usr/local/bin/guard.sh");+ }+/// `install-hooks --agent droid --apply` merges native `--agent droid`/// commands into `hooks.json` (the bare event map), keeps every/// third-party entry, and a re-apply changes nothing (#1240).diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex dfaafc38..9a82f0b1 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -146,6 +146,25 @@ pub(crate) const MUSE_EVENTS: [(&str, &str); 8] = [("SessionEnd", "session-end.sh"),];+/// Tencent CodeBuddy Code lifecycle events ai-memory hooks (#1299). Each pair+/// is `(event-name-in-~/.codebuddy/settings.json, native hook-event script+/// stem)`; CodeBuddy has no script bundle, so the `.sh` name only carries the+/// event token the native command is rendered with.+///+/// The reporter's mapping on v2.164–v2.167: Claude Code's vocabulary minus+/// the subagent events. `PostToolUseFailure` is not in that mapping.+/// `SessionEnd` is wired for the interactive exit; headless `codebuddy -p`+/// is a separate follow-up.+pub(crate) const CODEBUDDY_EVENTS: [(&str, &str); 7] = [+ ("SessionStart", "session-start.sh"),+ ("UserPromptSubmit", "user-prompt-submit.sh"),+ ("PreToolUse", "pre-tool-use.sh"),+ ("PostToolUse", "post-tool-use.sh"),+ ("PreCompact", "pre-compact.sh"),+ ("Stop", "stop.sh"),+ ("SessionEnd", "session-end.sh"),+];+/// Seconds Muse waits for one ai-memory hook. Muse reads `timeout` in/// seconds, like the Claude Code plugins it loads. The capture POST is/// fire-and-forget; `SessionStart` also fetches a handoff.@@ -1139,6 +1158,34 @@ pub(crate) fn build_muse_hooks_payload(payload}+/// `{"hooks": <event map>}` for Tencent CodeBuddy Code (#1299). The `hooks`+/// key of `~/.codebuddy/settings.json` holds Claude Code's nested shape+/// (`"Event": [{"matcher": "", "hooks": [{"type": "command", "command": …}]}]`).+/// CodeBuddy runs each `command` with the Claude Code-shaped event JSON on+/// stdin, so every entry invokes the native `ai-memory hook` command; there+/// is no script bundle, whatever `AI_MEMORY_HOOK_PLATFORM` asks for. An empty+/// matcher fires on every tool and every SessionStart source.+pub(crate) fn build_codebuddy_hooks_payload(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> Value {+ build_hook_payload_for_platform(+ &CODEBUDDY_EVENTS,+ Path::new(""),+ server_url,+ auth_token,+ HookShape::Nested,+ HookCommandContext::new(+ HookCommandPlatform::native(),+ "codebuddy",+ data_dir,+ project_strategy,+ ),+ )+}+/// Pool (Poolside Agent CLI) `.poolside/settings.yaml` `hooks:` block for/// install-hooks' print path. Pool's hook config is a project-scoped YAML/// file at the repo root — there is no user-global hook file for ai-memorydiff --git a/crates/ai-memory-cli/src/commands/setup.rs b/crates/ai-memory-cli/src/commands/setup.rsindex d9bf6ce1..3fdd3fc7 100644--- a/crates/ai-memory-cli/src/commands/setup.rs+++ b/crates/ai-memory-cli/src/commands/setup.rs@@ -163,6 +163,9 @@ pub async fn run(config: &Config, args: SetupArgs, config_path: Option<&Path>) -if muse_detected(&home, &env) {found.push(AgentChoice::Muse);}+ if codebuddy_detected(&home) {+ found.push(AgentChoice::CodeBuddy);+ }found} else {dedup(args.agents.iter().copied())@@ -271,6 +274,13 @@ fn muse_detected(home: &Path, env: &dyn Fn(&str) -> Option<OsString>) -> bool {|| xdg("XDG_DATA_HOME", &[".local", "share"]).is_dir()}+/// Whether CodeBuddy Code has been used on this machine: `~/.codebuddy`+/// exists. CodeBuddy has no native-session adapter, so setup finds it by+/// that directory rather than by [`detect_agents`].+fn codebuddy_detected(home: &Path) -> bool {+ home.join(".codebuddy").is_dir()+}+/// The binary path the service unit runs. A package manager's versioned/// location (a Homebrew `Cellar/<formula>/<version>` or a `/nix/store` path)/// disappears on the next upgrade or `brew cleanup` / garbage collection, so a@@ -739,6 +749,19 @@ mod tests {assert_eq!(AgentPlan::new(AgentChoice::Muse).mcp, Some(McpClient::Muse));}+ #[test]+ fn codebuddy_is_detected_only_when_its_home_directory_exists() {+ let home = tempfile::tempdir().unwrap();+ assert!(!codebuddy_detected(home.path()));+ std::fs::create_dir_all(home.path().join(".codebuddy")).unwrap();+ assert!(codebuddy_detected(home.path()));+ assert_eq!(+ skills_for(AgentChoice::CodeBuddy),+ InstallSkillsAgent::Agents+ );+ assert_eq!(AgentPlan::new(AgentChoice::CodeBuddy).mcp, None);+ }+/// A versioned Homebrew binary is recorded through the `opt/<formula>`/// link that survives `brew upgrade` and `brew cleanup`, falling back to/// the `<prefix>/bin` link; a link to some other binary never wins.diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex 9e4d5fbc..92851d7a 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -125,6 +125,11 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {emit_muse(&args)?;return Ok(());}+ // CodeBuddy too: ~/.codebuddy/settings.json runs the native `hook` command.+ if matches!(args.agent, AgentChoice::CodeBuddy) {+ emit_codebuddy(&args)?;+ return Ok(());+ }let Some(agent_sub) = args.agent.script_hook_subdir() else {bail!("internal: generated integration should have returned before staging hooks")};@@ -222,7 +227,8 @@ pub fn run(config: &Config, mut args: SetupAgentArgs) -> Result<()> {| AgentChoice::Zcode| AgentChoice::Hermes| AgentChoice::Droid- | AgentChoice::Muse => {+ | AgentChoice::Muse+ | AgentChoice::CodeBuddy => {bail!("internal: generated integration should have returned before emitting staged hooks")@@ -372,6 +378,30 @@ fn emit_muse(args: &SetupAgentArgs) -> Result<()> {Ok(())}+/// Print the `hooks` block for `~/.codebuddy/settings.json`. No scripts are+/// staged: each entry runs the ai-memory binary's native `hook` command with+/// CodeBuddy's event JSON on stdin.+fn emit_codebuddy(args: &SetupAgentArgs) -> Result<()> {+ let payload = crate::commands::render_shared::build_codebuddy_hooks_payload(+ &args.server_url,+ args.auth_token.as_deref(),+ None,+ None,+ );+ let serialized = serde_json::to_string_pretty(&payload["hooks"])+ .context("serializing CodeBuddy hook config")?;+ println!("# CodeBuddy Code — merge under the `hooks` key of");+ println!("# ~/.codebuddy/settings.json. The `command` must be an ai-memory");+ println!("# binary reachable on the host that runs CodeBuddy; prefer");+ println!("# `ai-memory install-hooks --agent codebuddy --apply` from that host.");+ if args.auth_token.is_some() {+ println!("# Treat settings.json as sensitive (chmod 600).");+ }+ println!();+ println!("{serialized}");+ Ok(())+}+fn normalise_hook_server_url(url: &str) -> String {url.trim().trim_end_matches('/').to_string()}diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex dad55be9..8ae920bc 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -272,6 +272,10 @@ fn build_plan(install_hooks::muse_settings_path(env)?,HookConfigShape::NestedHooksKey,),+ (+ install_hooks::codebuddy_settings_path()?,+ HookConfigShape::NestedHooksKey,+ ),]);for (path, shape) in hook_files {if !path.exists() {diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 354450ac..d304463c 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -291,6 +291,12 @@ pub enum AgentKind {/// Meta Muse Code (`muse`), whose hooks send Claude Code-shaped payloads/// with Muse's own tool names.Muse,+ /// Tencent CodeBuddy Code (`codebuddy`). Hooks are Claude Code-shaped+ /// (PascalCase events; `session_id`, `cwd`, `tool_name` and `tool_input`+ /// on stdin). `SessionStart` stdout's `hookSpecificOutput.additionalContext`+ /// is appended to the session (#1299).+ #[serde(rename = "codebuddy", alias = "code-buddy")]+ CodeBuddy,/// Anything else (manual capture, future agents).Other,}@@ -301,7 +307,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; 25] = [+ pub const ALL: [Self; 26] = [Self::ClaudeCode,Self::Codex,Self::OpenCode,@@ -326,6 +332,7 @@ impl AgentKind {Self::Grizzybot,Self::Droid,Self::Muse,+ Self::CodeBuddy,Self::Other,];@@ -357,6 +364,7 @@ impl AgentKind {Self::Grizzybot => "grizzybot",Self::Droid => "droid",Self::Muse => "muse",+ Self::CodeBuddy => "codebuddy",Self::Other => "other",}}@@ -391,6 +399,7 @@ impl AgentKind {"grizzybot" | "grizzy-bot" => Self::Grizzybot,"droid" | "factory-droid" | "factory_droid" => Self::Droid,"muse" | "muse-code" | "musecode" => Self::Muse,+ "codebuddy" | "code-buddy" => Self::CodeBuddy,_ => Self::Other,}}@@ -443,6 +452,11 @@ impl AgentKind {/// Meta Muse Code injects a `SessionStart` stdout's/// `hookSpecificOutput.additionalContext` as developer context (verified/// offline against Muse Code 1.4.7), so it takes the same envelope.+ ///+ /// CodeBuddy Code appends that same envelope to the session (reported+ /// against v2.164.0–v2.167.0, #1299), so the native hook fetches the+ /// handoff for it. The fetch stays the built-in SessionStart path; a+ /// separate `GET /handoff` client is not part of the installer.#[must_use]pub fn session_start_injects_handoff(self) -> bool {!matches!(@@ -736,6 +750,34 @@ mod tests {assert!(!AgentKind::Muse.reuses_session_id_after_end());}+ #[test]+ fn agent_kind_codebuddy_round_trips_and_injects_session_start_handoff() {+ assert_eq!(AgentKind::CodeBuddy.as_str(), "codebuddy");+ for alias in ["codebuddy", "code-buddy"] {+ assert_eq!(AgentKind::from_wire(alias), AgentKind::CodeBuddy, "{alias}");+ }+ assert_eq!(+ serde_json::to_string(&AgentKind::CodeBuddy).unwrap(),+ "\"codebuddy\""+ );+ assert_eq!(+ serde_json::from_str::<AgentKind>("\"codebuddy\"").unwrap(),+ AgentKind::CodeBuddy+ );+ assert_eq!(+ serde_json::from_str::<AgentKind>("\"code-buddy\"").unwrap(),+ AgentKind::CodeBuddy+ );+ assert_eq!(AgentKind::from_wire("codebuddy-2"), AgentKind::Other);+ assert_eq!(AgentKind::from_wire("tencent"), AgentKind::Other);+ // CodeBuddy appends SessionStart's hookSpecificOutput.additionalContext+ // (#1299), so the built-in fetch is the delivery path.+ assert!(AgentKind::CodeBuddy.session_start_injects_handoff());+ assert!(!AgentKind::CodeBuddy.user_prompt_injects_handoff());+ assert!(!AgentKind::CodeBuddy.post_tool_injects_handoff());+ assert!(!AgentKind::CodeBuddy.reuses_session_id_after_end());+ }+#[test]fn agent_kind_grizzybot_round_trips() {assert_eq!(AgentKind::Grizzybot.as_str(), "grizzybot");diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex adfa094b..7302ecf8 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -181,6 +181,7 @@ pub(crate) fn tool_payload_fields(agent: AgentKind, raw: &Value) -> Option<(&str// `tool_name`/`tool_input`/`tool_use_id` (captured live, Cursor 3.24.9).// Meta Muse Code sends the same three fields, `tool_use_id` being the// provider's call id (`call_…`, captured offline on Muse Code 1.4.7).+ // CodeBuddy Code sends the same Claude Code fields (#1299).AgentKind::ClaudeCode| AgentKind::CommandCode| AgentKind::Codex@@ -189,7 +190,8 @@ pub(crate) fn tool_payload_fields(agent: AgentKind, raw: &Value) -> Option<(&str| AgentKind::Grizzybot| AgentKind::Zcode| AgentKind::CopilotCli- | AgentKind::Muse => (+ | AgentKind::Muse+ | AgentKind::CodeBuddy => (object.get("tool_name")?.as_str()?,object.get("tool_use_id").and_then(Value::as_str),),@@ -261,6 +263,7 @@ pub(crate) fn tool_observation_metadata(| AgentKind::Grizzybot| AgentKind::Droid| AgentKind::Muse+ | AgentKind::CodeBuddy) {"tool_input"} else {@@ -1103,7 +1106,10 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted<'_> {// Factory Droid's hooks send the same Claude Code shape (#1240).| AgentKind::Droid// Meta Muse Code too, with its own tool names (Muse Code 1.4.7).- | AgentKind::Muse => object+ // CodeBuddy Code uses Claude Code's names and the same two fields+ // (#1299), so `[capture] ignore_paths` classifies them as Claude's.+ | AgentKind::Muse+ | AgentKind::CodeBuddy => object.get("tool_name").and_then(Value::as_str).map(|name| (name, object.get("tool_input"))),@@ -4587,6 +4593,7 @@ mod tests {AgentKind::CopilotCli,AgentKind::Droid,AgentKind::Muse,+ AgentKind::CodeBuddy,AgentKind::OpenCode,AgentKind::Omp,AgentKind::Pi,diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex d82dff96..6bf6f39e 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -833,6 +833,10 @@ const fn closed_tool_agent(agent: AgentKind) -> bool {| AgentKind::Grizzybot| AgentKind::Droid| AgentKind::Muse+ // CodeBuddy Code sends Claude Code's snake_case tool fields+ // (#1299). Unknown values stay `Other` and keep the capture-only+ // path.+ | AgentKind::CodeBuddy)}@@ -2180,6 +2184,8 @@ mod tests {assert_eq!(parse_agent("hermes-agent"), AgentKind::Hermes);assert_eq!(parse_agent("pool"), AgentKind::Pool);assert_eq!(parse_agent("poolside"), AgentKind::Pool);+ assert_eq!(parse_agent("codebuddy"), AgentKind::CodeBuddy);+ assert_eq!(parse_agent("code-buddy"), AgentKind::CodeBuddy);// Anything else is `Other`. Critical for the hook router:// a typo in the query string must not crash, it just gets// attributed to the catch-all bucket.@@ -2241,6 +2247,54 @@ mod tests {assert!(unknown.title_hint.is_none());}+ /// CodeBuddy posts Claude Code's tool payload. The same body under+ /// `agent=codebuddy` is a closed tool observation; under an unknown+ /// agent it stays capture-only (`title` empty, no tool family).+ #[test]+ fn codebuddy_post_tool_use_uses_the_claude_shaped_parser() {+ let raw = serde_json::json!({+ "hook_event_name": "PostToolUse",+ "session_id": "11111111-2222-3333-4444-555555555555",+ "cwd": "/repo",+ "tool_name": "Read",+ "tool_use_id": "toolu_codebuddy",+ "tool_input": {"file_path": "src/lib.rs"},+ "tool_response": "file contents"+ });+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("codebuddy".into()),+ ..Default::default()+ },+ raw.clone(),+ );+ assert_eq!(env.agent, AgentKind::CodeBuddy);+ assert_eq!(+ env.session_id.as_deref(),+ Some("11111111-2222-3333-4444-555555555555")+ );+ assert_eq!(env.cwd.as_deref(), Some("/repo"));+ assert_eq!(env.title_hint.as_deref(), Some("tool file"));+ let body = env.body_excerpt.expect("structured tool body");+ assert!(body.starts_with("tool_family: file\n"), "{body}");+ assert!(body.contains("outcome: unknown"), "{body}");+ assert!(body.contains("tool_call_id: toolu_codebuddy"), "{body}");+ assert!(body.contains("\n---\nfile contents"), "{body}");++ let unknown = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("codebuddy-2".into()),+ ..Default::default()+ },+ raw,+ );+ assert_eq!(unknown.agent, AgentKind::Other);+ assert!(unknown.title_hint.is_none());+ assert!(unknown.body_excerpt.is_none());+ }+/// Hermes 3.x puts the tool result inside `extra.result` and mirrors the/// call status in `extra.status` (`ok` | `error`). The extractor must read/// both from the documented `extra` object: output lands in the bodydiff --git a/crates/ai-memory-store/migrations/V81__sessions_codebuddy_agent_kind.sql b/crates/ai-memory-store/migrations/V81__sessions_codebuddy_agent_kind.sqlnew file mode 100644index 00000000..d20ac639--- /dev/null+++ b/crates/ai-memory-store/migrations/V81__sessions_codebuddy_agent_kind.sql@@ -0,0 +1,74 @@+-- Expand sessions.agent_kind CHECK for Tencent CodeBuddy Code.+--+-- Keep the complete V80 schema, indexes, and scope-pairing triggers while+-- adding the `codebuddy` wire value.+--+-- `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','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/migrations.rs b/crates/ai-memory-store/src/migrations.rsindex 4fea0e81..24b2bfb6 100644--- a/crates/ai-memory-store/src/migrations.rs+++ b/crates/ai-memory-store/src/migrations.rs@@ -1282,6 +1282,128 @@ mod tests {}}+ /// V81 rebuilds `sessions` again, for CodeBuddy Code: rows, the ingest+ /// keys and observations that reference them, and the scope-pairing+ /// triggers all survive, and a `codebuddy` session is accepted afterwards.+ #[test]+ fn v80_to_v81_preserves_sessions_ingest_keys_and_observations_and_accepts_codebuddy() {+ let mut conn = Connection::open_in_memory().unwrap();+ run_to(&mut conn, 80).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ let workspace_id = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();+ let project_id =+ crate::ops::get_or_create_project(&mut conn, &workspace_id, "project", None).unwrap();+ let existing = SessionId::new();+ conn.execute(+ "INSERT INTO sessions \+ (id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at, \+ ended_observation_count, actor_user) \+ VALUES (?1, ?2, ?3, 'muse', '/repo', 1, 2, 7, 'user:alice')",+ params![+ existing.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ ],+ )+ .unwrap();+ // V80 cannot store a CodeBuddy session yet.+ assert!(+ conn.execute(+ "INSERT INTO sessions \+ (id, workspace_id, project_id, agent_kind, started_at) \+ VALUES (?1, ?2, ?3, 'codebuddy', 1)",+ params![+ SessionId::new().as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ ],+ )+ .is_err(),+ "the V80 CHECK must reject codebuddy"+ );+ conn.execute(+ "INSERT INTO ingest_keys (project_id, key, seen_at, session_id, agent_kind) \+ VALUES (?1, 'k1', 1, ?2, 'muse')",+ params![project_id.as_bytes(), existing.as_bytes()],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO observations \+ (id, session_id, workspace_id, project_id, kind, title, body, created_at) \+ VALUES (?1, ?2, ?3, ?4, 'prompt', 'kept', 'kept body', 1)",+ params![+ uuid::Uuid::new_v4().as_bytes(),+ existing.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ ],+ )+ .unwrap();++ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();+ run(&mut conn).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();++ let preserved: (String, String, i64, Option<String>) = conn+ .query_row(+ "SELECT agent_kind, cwd, ended_observation_count, actor_user \+ FROM sessions WHERE id = ?1",+ params![existing.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),+ )+ .unwrap();+ assert_eq!(+ preserved,+ ("muse".into(), "/repo".into(), 7, Some("user:alice".into()))+ );+ let observations: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM observations WHERE session_id = ?1",+ params![existing.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(observations, 1, "the session's observations survive");+ for table in ["ingest_keys", "observations"] {+ let dangling: i64 = conn+ .query_row(+ &format!("SELECT COUNT(*) FROM pragma_foreign_key_check('{table}')"),+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(dangling, 0, "{table} must still reference sessions");+ }++ crate::ops::begin_session(+ &mut conn,+ &NewSession {+ occurred_at: None,+ id: SessionId::new(),+ workspace_id,+ project_id,+ agent_kind: AgentKind::CodeBuddy,+ cwd: Some("/repo".into()),+ actor_user: Some("user:alice".into()),+ },+ )+ .unwrap();++ for name in [+ "idx_sessions_open_owner",+ "sessions_ws_proj_pairing_ai",+ "auto_improve_scheduler_claims_session_pairing_ai",+ "session_consolidation_jobs_session_pairing_ai",+ ] {+ let kind = if name.starts_with("idx_") {+ "index"+ } else {+ "trigger"+ };+ assert_eq!(schema_object_count(&conn, kind, name), 1, "missing {name}");+ }+ }+/// V62 was reshaped in place (#776) from an in-migration backfill to/// DDL-only + a boot-path backfill, changing its checksum. A store that/// applied the ORIGINAL V62 recorded the old checksum; `run` must stilldiff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex 5da4f7a9..bd17aa95 100644--- a/docs/support-matrix.md+++ b/docs/support-matrix.md@@ -49,6 +49,7 @@| 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. `setup` detects CodeBuddy when `~/.codebuddy` exists. No `install-mcp` client, no transcript backfill, and no managed workstream are claimed. Reported against CodeBuddy v2.164–v2.167 (#1299). || 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). |