Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(agents): add Kimi Code as a first-class supported agent
Lucas Oliveira34c487739113
diff --git a/AGENTS.md b/AGENTS.mdindex 8efcea09..5dbe8081 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -36,8 +36,8 @@ install or refresh work.If you're about to write a durable project rule ("always X", "neverY", "all PRs must ..."), write it in the project's canonical agent instruction file.Many projects use CLAUDE.md for Claude Code and-AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI, but if the project-says one file is canonical, use that file.+AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Kimi Code,+but if the project says one file is canonical, use that file.If the rule is a standing *user/team* preference that should apply toevery project (tech choices, code style, personal conventions), save it@@ -53,8 +53,8 @@ latest binary's recommended copy:- **From the agent** (no terminal needed): ask "refresh the ai-memoryrouting in this project". The agent calls `memory_install_self_routing`,picks the right filename for itself (Claude Code -> `CLAUDE.md`; Codex /- OpenCode / Cursor / Gemini -> `AGENTS.md`), uses its Write / Edit tool- to replace or append the returned `markered_block` while preserving+ OpenCode / Cursor / Gemini / Kimi Code -> `AGENTS.md`), uses its Write /+ Edit tool to replace or append the returned `markered_block` while preservingnon-ai-memory user content, then writes or updates each returned`managed_skills` item under the selected skill root from `target_hints`using its `relative_path`.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a12da340..f58b0bd2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Kimi Code CLI is now a supported MCP + lifecycle-hook integration+ (`--client kimi-code` / `--agent kimi-code`, alias `kimi`). `install-mcp`+ merges an `mcpServers` entry into `~/.kimi-code/mcp.json` with a plain `url`+ (Kimi Code treats `url` with no `transport` field as streamable HTTP) plus+ optional bearer `headers`. `install-hooks` merges `[[hooks]]` entries into+ `~/.kimi-code/config.toml`, preserving the provider/model settings the same+ file holds, and covers 9 events: `SessionStart`, `SessionEnd`,+ `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`, `SubagentStart`,+ `SubagentStop`, and `PreCompact`. Both paths honor `$KIMI_CODE_HOME`.+ Handoff injection happens at `SessionStart` through hook stdout, which Kimi+ Code appends to the model context; `setup-agent` and `uninstall` handle the+ new agent like the other first-class integrations.+### Changed- One-shot client commands (`rename-project`, `status`, `write-page`, …) nolonger print the "cannot write log files … falling back" warning when thediff --git a/README.md b/README.mdindex 66f48483..ee9c84d6 100644--- a/README.md+++ b/README.md@@ -35,6 +35,7 @@| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). || Grok Build CLI | Hooks | Lifecycle hooks via `install-hooks --agent grok` (`~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle, native `--agent grok`). Capture works; no handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. || Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. |+| Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 9 events including subagent start/stop); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `SessionStart` stdout. || VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). || Hermes Agent | Community | A community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is available. It is not part of ai-memory's first-party install surface; review its compatibility matrix, install/uninstall scripts, and secret handling before using it. || LLM/auth providers | Supported | Anthropic, OpenAI, OpenAI OAuth/Codex, GitHub Copilot, Gemini, OpenCode Zen/Go, OpenAI-compatible endpoints, and generic OIDC device auth for native hooks. |@@ -92,9 +93,9 @@ priors are at the [bottom](#influences-and-prior-art).mode. Mounted on the same axum server as MCP.- **Multi-agent + multi-machine ready.** Supported clients: ClaudeCode, Codex, Devin CLI, OpenCode, Cursor, Claude Desktop (via `mcp-remote`),- Gemini CLI, Antigravity CLI, Grok Build CLI, OpenClaw, Oh My Pi / OMP- (`omp` / `oh-my-pi`), Pi via generated bridge extension, and VS Code GitHub- Copilot agent mode+ Gemini CLI, Antigravity CLI, Grok Build CLI, Kimi Code, OpenClaw, Oh My Pi+ / OMP (`omp` / `oh-my-pi`), Pi via generated bridge extension, and VS Code+ GitHub Copilot agent mode(MCP-only, workspace `.vscode/mcp.json`).Server runs local (loopback) OR on a homelab box (LAN/VPN/cloud)with bearer-token auth. Shared servers can opt into@@ -270,7 +271,7 @@ docker run -d --name ai-memory \# 3. Wire your agent CLI in two commands. The wrapper takes care of# mounts + auto-detecting ~/.claude/settings.json. Re-run with# `--agent codex`, `--agent devin`, `--agent opencode`, `--agent gemini-cli`,-# `--agent omp`, `--agent oh-my-pi`, `--client cursor`,+# `--agent kimi-code`, `--agent omp`, `--agent oh-my-pi`, `--client cursor`,# `--client gemini-cli`, etc.# for additional agents; full list in docs/install.md.ai-memory install-mcp --client claude-code --apply@@ -342,7 +343,7 @@ one matching entry.markered snippet and managed Agent Skills from the same binary-owned assets.For Codex, Devin CLI, OpenCode, OMP, Cursor, Claude Desktop, Gemini CLI,-Antigravity CLI, Grok Build CLI, OpenClaw, VS Code Copilot,+Antigravity CLI, Grok Build CLI, Kimi Code, OpenClaw, VS Code Copilot,curl-based hook installs, source builds,CLI env vars, and the full subcommand reference, see [`docs/install.md`](docs/install.md).diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex c803e9ea..8429d472 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -833,6 +833,9 @@ pub enum AgentChoice {/// hook scripts. Devin consumes the handoff via/// `hookSpecificOutput.additionalContext` on `SessionStart`.Devin,+ /// Kimi Code CLI (Moonshot AI).+ #[value(alias = "kimi")]+ KimiCode,}impl AgentChoice {@@ -857,6 +860,7 @@ impl AgentChoice {Self::Grok => AgentKind::Grok,Self::Zero => AgentKind::Zero,Self::Devin => AgentKind::Devin,+ Self::KimiCode => AgentKind::KimiCode,}}@@ -933,6 +937,9 @@ pub enum McpClient {Zero,/// Devin CLI — `~/.devin/config.json`.Devin,+ /// Kimi Code CLI (Moonshot AI).+ #[value(alias = "kimi")]+ KimiCode,/// VS Code GitHub Copilot (agent mode) — per-workspace/// `.vscode/mcp.json`. Copilot's agent mode reads MCP servers/// from VS Code's own MCP framework (top-level `servers` key),diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 19706017..9244a48e 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -20,16 +20,16 @@ use std::path::{Path, PathBuf};use anyhow::{Context, Result};use crate::cli::{AgentChoice, InstallHooksArgs, McpClient};-use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json};+use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json, mutate_toml};use crate::commands::install_mcp;use crate::commands::openclaw_plugin;use crate::commands::path_util::home_dir;use crate::commands::render_shared::{ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, CURSOR_PROFILE,- GEMINI_PROFILE, build_antigravity_payload_with_data_dir,+ GEMINI_PROFILE, KIMI_CODE_EVENTS, build_antigravity_payload_with_data_dir,build_claude_code_payload_with_data_dir, build_devin_payload_with_data_dir,build_grok_payload_with_data_dir, build_profile_payload_for_agent, hook_script_for_claude_code,- hook_script_for_current_platform, ts_string_literal,+ hook_script_for_current_platform, kimi_code_hook_commands, ts_string_literal,};use crate::config::{Config, DEFAULT_SERVER_URL};@@ -141,6 +141,29 @@ pub(crate) fn pi_extension_path() -> anyhow::Result<std::path::PathBuf> {.join("ai-memory.ts"))}+/// `$KIMI_CODE_HOME/config.toml` when set, else `~/.kimi-code/config.toml`.+/// Kimi Code keeps hooks as `[[hooks]]` entries inside the same+/// config.toml that stores the user's providers/model, so the apply+/// path merges TOML-aware instead of rewriting the file.+pub(crate) fn kimi_code_config_path() -> anyhow::Result<std::path::PathBuf> {+ kimi_code_config_path_in(std::env::var_os("KIMI_CODE_HOME"))+}++/// The env value comes in as a parameter so tests can exercise both+/// branches without mutating process env (mirrors+/// `install_mcp::kimi_code_home`).+fn kimi_code_config_path_in(+ env_override: Option<std::ffi::OsString>,+) -> anyhow::Result<std::path::PathBuf> {+ if let Some(dir) = env_override.filter(|value| !value.is_empty()) {+ return Ok(PathBuf::from(dir).join("config.toml"));+ }+ Ok(home_dir()+ .context("could not locate $HOME for ~/.kimi-code/config.toml")?+ .join(".kimi-code")+ .join("config.toml"))+}+/// Run the `install-hooks` subcommand.////// # Errors@@ -217,6 +240,10 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {apply_to_devin_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)}AgentChoice::Openclaw => openclaw_plugin::apply(&server_url, auth, &args),+ AgentChoice::KimiCode => {+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;+ apply_to_kimi_code_config(&hooks_dir, &server_url, auth, &config.data_dir, &args)+ }};}let strategy = args.project_strategy.baked();@@ -285,6 +312,10 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {openclaw_plugin::render(&server_url, auth, strategy);Ok(())}+ AgentChoice::KimiCode => {+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;+ render_kimi_code(&hooks_dir, &server_url, auth, &config.data_dir, strategy)+ }}}@@ -384,6 +415,7 @@ fn infer_installed_mcp_config(agent: AgentChoice) -> Option<InferredMcpConfig> {infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "serverUrl")}McpClient::Devin => infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url"),+ McpClient::KimiCode => infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url"),McpClient::ClaudeDesktop => None,// MCP-only client: no AgentChoice counterpart routes here.// Reachable only if a future install_hooks flow targets VS@@ -405,6 +437,7 @@ fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {AgentChoice::Openclaw => Some(McpClient::Openclaw),AgentChoice::AntigravityCli => Some(McpClient::AntigravityCli),AgentChoice::Zero => Some(McpClient::Zero),+ AgentChoice::KimiCode => Some(McpClient::KimiCode),// Grok and Devin manage their own MCP config under ~/.grok/ and ~/.devin/;// we don't auto-infer a hook server URL from it.AgentChoice::Pi | AgentChoice::Grok | AgentChoice::Devin => None,@@ -1114,6 +1147,121 @@ fn merge_antigravity_hooks(})}+/// Mutate Kimi Code's `config.toml` (`$KIMI_CODE_HOME/config.toml` when+/// the var is set, else `~/.kimi-code/config.toml`) so Kimi Code fires+/// the ai-memory scripts on its lifecycle events.+///+/// Kimi Code stores hooks as `[[hooks]]` array-of-tables entries inside+/// the SAME config.toml that carries the user's providers and model,+/// and any unknown key on a hook entry makes the whole config fail to+/// load. The merge is therefore TOML-aware via `toml_edit` (the rest of+/// the document is preserved as parsed) and each entry carries exactly+/// `event` + `command` — `matcher` omitted (Kimi Code matches+/// everything) and `timeout` omitted (30s default).+fn apply_to_kimi_code_config(+ hooks_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+) -> Result<()> {+ let path = match &args.config_file {+ Some(p) => p.clone(),+ None => kimi_code_config_path()?,+ };+ let staged = stage_hook_scripts(hooks_dir, "kimi-code")?;+ let command_dir = staged_command_dir(&staged, "kimi-code");+ let strategy = args.project_strategy.baked();+ let outcome = merge_kimi_code_hooks(+ &command_dir,+ server_url,+ auth_token,+ data_dir,+ strategy,+ &path,+ )?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ Ok(())+}++fn merge_kimi_code_hooks(+ staged: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+ config_path: &Path,+) -> Result<ApplyOutcome> {+ let commands = kimi_code_hook_commands(+ staged,+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ apply_atomic(config_path, |existing| {+ mutate_toml(existing, |doc| upsert_kimi_code_hooks(doc, &commands))+ })+}++/// Insert or refresh ai-memory's `[[hooks]]` entries: drop any prior+/// entry whose command references our staged scripts (so re-runs update+/// in place instead of duplicating), append the fresh set, and leave+/// every third-party `[[hooks]]` entry — and every other table in+/// config.toml — untouched.+fn upsert_kimi_code_hooks(+ doc: &mut toml_edit::DocumentMut,+ commands: &[(&str, String)],+) -> Result<()> {+ use toml_edit::{ArrayOfTables, Item, Table, value};++ if doc.get("hooks").is_none() {+ doc.insert("hooks", Item::ArrayOfTables(ArrayOfTables::new()));+ }+ let hooks = doc+ .get_mut("hooks")+ .and_then(Item::as_array_of_tables_mut)+ .context("`hooks` is present in config.toml but not an array of tables")?;++ let stale: Vec<usize> = hooks+ .iter()+ .enumerate()+ .filter_map(|(i, entry)| is_ai_memory_toml_hook_entry(entry).then_some(i))+ .collect();+ for i in stale.into_iter().rev() {+ hooks.remove(i);+ }+ for (event, command) in commands {+ let mut entry = Table::new();+ entry["event"] = value(*event);+ entry["command"] = value(command);+ hooks.push(entry);+ }+ Ok(())+}++/// True if a `[[hooks]]` table belongs to ai-memory — i.e. its command+/// references our staged script path or the inlined `AI_MEMORY_*` env+/// vars. Broad matching is intentional (mirrors the shell-form branch+/// of `is_ai_memory_hook_entry`): old installs may identify us by the+/// script path or by the env prefix alone.+fn is_ai_memory_toml_hook_entry(entry: &toml_edit::Table) -> bool {+ let Some(command) = entry.get("command").and_then(|c| c.as_str()) else {+ return false;+ };+ let lower = command.to_ascii_lowercase();+ lower.contains("ai-memory") || lower.contains("ai_memory")+}+/// Generate an OpenCode plugin at `~/.config/opencode/plugins/ai-memory.ts`.////// OpenCode's integration surface is a TypeScript plugin, not a JSON@@ -2746,6 +2894,56 @@ fn render_devin(Ok(())}+/// Print Kimi Code's `[[hooks]]` TOML fragment to stdout (dry-run+/// counterpart of [`apply_to_kimi_code_config`]). Rendered through the+/// same upsert path the apply mode uses, so the printout is byte-for-+/// byte what `--apply` would append to config.toml.+fn render_kimi_code(+ hooks_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+) -> Result<()> {+ // Soft check (same rationale as render_claude_code): warn, don't bail,+ // so the docker host-path flow still works.+ for (_, script) in KIMI_CODE_EVENTS {+ let script = hook_script_for_current_platform(script);+ let abs = hooks_dir.join(script.as_ref());+ if !abs.exists() {+ eprintln!(+ "# warning: {} not present on this filesystem. \+ If this command is running inside docker against a \+ host path, you can ignore this; otherwise extract \+ the scripts first with `ai-memory setup-agent`.",+ abs.display()+ );+ }+ }+ let commands = kimi_code_hook_commands(+ hooks_dir,+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ let mut doc = toml_edit::DocumentMut::new();+ upsert_kimi_code_hooks(&mut doc, &commands)?;+ println!("# Kimi Code hook config — merge into $KIMI_CODE_HOME/config.toml");+ println!("# (~/.kimi-code/config.toml when KIMI_CODE_HOME is unset), or re-run");+ println!("# with --apply to merge it in place, preserving providers/model and");+ println!("# any third-party [[hooks]] entries already in the file.");+ println!("# Hook scripts: {}", hooks_dir.display());+ println!("# AI-memory server URL: {server_url}");+ if auth_token.is_some() {+ println!("# Auth: AI_MEMORY_AUTH_TOKEN embedded in each hook command below.");+ println!("# Treat config.toml as sensitive (chmod 600).");+ }+ println!();+ print!("{doc}");+ Ok(())+}+#[cfg(test)]mod tests {use super::*;@@ -3382,6 +3580,7 @@ model = "gpt-5""devin","opencode","antigravity-cli",+ "kimi-code",] {let dir = hooks_root.join(agent_dir);let mut sh = BTreeMap::new();@@ -4462,6 +4661,233 @@ model = "gpt-5"assert_eq!(second, ApplyOutcome::NoOp, "second apply must be a no-op");}+ // ----------------------------------------------------------------+ // Kimi Code tests+ // ----------------------------------------------------------------++ const KIMI_CODE_STUB_SCRIPTS: [&str; 9] = [+ "session-start.sh",+ "user-prompt-submit.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "pre-compact.sh",+ "stop.sh",+ "session-end.sh",+ "subagent-start.sh",+ "subagent-stop.sh",+ ];++ fn kimi_code_hooks_in(config_path: &Path) -> Vec<(String, String)> {+ let doc: toml_edit::DocumentMut = fs::read_to_string(config_path)+ .unwrap()+ .parse()+ .expect("config.toml must stay valid TOML");+ doc.get("hooks")+ .and_then(toml_edit::Item::as_array_of_tables)+ .expect("`hooks` must be an array of tables")+ .iter()+ .map(|entry| {+ let event = entry+ .get("event")+ .and_then(|v| v.as_str())+ .unwrap_or_default()+ .to_string();+ let command = entry+ .get("command")+ .and_then(|v| v.as_str())+ .unwrap_or_default()+ .to_string();+ (event, command)+ })+ .collect()+ }++ #[test]+ fn kimi_code_apply_writes_all_events_into_fresh_config() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(hooks_tmp.path(), &KIMI_CODE_STUB_SCRIPTS);++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("config.toml");++ let outcome = merge_kimi_code_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &config_path,+ )+ .unwrap();+ assert_eq!(outcome, ApplyOutcome::Created);++ let entries = kimi_code_hooks_in(&config_path);+ assert_eq!(entries.len(), KIMI_CODE_EVENTS.len());+ for (i, (event, script)) in KIMI_CODE_EVENTS.iter().enumerate() {+ assert_eq!(entries[i].0, *event, "entry order follows KIMI_CODE_EVENTS");+ let stem = script.strip_suffix(".sh").unwrap();+ assert!(+ entries[i].1.contains(stem),+ "{event}: command must reference the staged script: {}",+ entries[i].1+ );+ }+ // Only the allowed keys are written — Kimi Code rejects unknown+ // fields by failing the whole config load.+ let doc: toml_edit::DocumentMut =+ fs::read_to_string(&config_path).unwrap().parse().unwrap();+ for entry in doc+ .get("hooks")+ .and_then(toml_edit::Item::as_array_of_tables)+ .unwrap()+ {+ let keys: Vec<&str> = entry.iter().map(|(k, _)| k).collect();+ assert_eq!(keys, ["event", "command"], "only event + command allowed");+ }+ }++ #[test]+ fn kimi_code_apply_preserves_providers_and_third_party_hooks() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(hooks_tmp.path(), &KIMI_CODE_STUB_SCRIPTS);++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("config.toml");+ fs::write(+ &config_path,+ r#"# Kimi Code user config+model = "kimi-k2"++[providers.moonshot]+api_key = "sk-secret"+base_url = "https://api.moonshot.cn/v1"++[[hooks]]+event = "SessionStart"+command = "echo third-party"++[[hooks]]+event = "SessionStart"+command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/session-start.sh"+"#,+ )+ .unwrap();++ merge_kimi_code_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &config_path,+ )+ .unwrap();++ let content = fs::read_to_string(&config_path).unwrap();+ assert!(+ content.contains("# Kimi Code user config"),+ "comments survive"+ );+ assert!(+ content.contains(r#"api_key = "sk-secret""#),+ "providers table survives"+ );++ let doc: toml_edit::DocumentMut = content.parse().unwrap();+ assert_eq!(+ doc.get("model").and_then(|v| v.as_str()),+ Some("kimi-k2"),+ "model setting survives"+ );+ assert_eq!(+ doc.get("providers")+ .and_then(|p| p.get("moonshot"))+ .and_then(|m| m.get("base_url"))+ .and_then(|v| v.as_str()),+ Some("https://api.moonshot.cn/v1"),+ "providers.moonshot survives"+ );++ let entries = kimi_code_hooks_in(&config_path);+ // Third-party entry + our 9: the stale ai-memory entry must be+ // replaced, not duplicated.+ assert_eq!(entries.len(), 1 + KIMI_CODE_EVENTS.len());+ let ours: Vec<&(String, String)> = entries+ .iter()+ .filter(|(_, command)| {+ let lower = command.to_ascii_lowercase();+ lower.contains("ai-memory") || lower.contains("ai_memory")+ })+ .collect();+ assert_eq!(ours.len(), KIMI_CODE_EVENTS.len(), "no duplicated entries");+ assert!(+ entries+ .iter()+ .any(|(_, command)| command == "echo third-party"),+ "third-party hook survives: {entries:?}"+ );+ assert!(+ !entries.iter().any(|(_, command)| command.contains("/old/")),+ "stale ai-memory entry must be replaced: {entries:?}"+ );+ }++ #[test]+ fn kimi_code_apply_is_idempotent() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(hooks_tmp.path(), &KIMI_CODE_STUB_SCRIPTS);++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("config.toml");++ let first = merge_kimi_code_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &config_path,+ )+ .unwrap();+ assert_ne!(+ first,+ ApplyOutcome::NoOp,+ "first apply should not be a no-op"+ );++ let second = merge_kimi_code_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &config_path,+ )+ .unwrap();+ assert_eq!(second, ApplyOutcome::NoOp, "second apply must be a no-op");+ }++ #[test]+ fn kimi_code_config_path_honours_kimi_code_home() {+ let custom = if cfg!(windows) {+ r"C:\custom\kimi"+ } else {+ "/custom/kimi"+ };+ let path = kimi_code_config_path_in(Some(std::ffi::OsString::from(custom))).unwrap();+ assert_eq!(path, Path::new(custom).join("config.toml"));++ // Empty override and unset var both fall back to ~/.kimi-code.+ for env in [None, Some(std::ffi::OsString::new())] {+ let path = kimi_code_config_path_in(env).unwrap();+ assert!(+ path.ends_with(Path::new(".kimi-code").join("config.toml")),+ "default must be ~/.kimi-code/config.toml, got {}",+ path.display()+ );+ }+ }+// ----------------------------------------------------------------// Devin tests// ----------------------------------------------------------------diff --git a/crates/ai-memory-cli/src/commands/install_instructions.rs b/crates/ai-memory-cli/src/commands/install_instructions.rsindex e3ee47aa..9ac6f509 100644--- a/crates/ai-memory-cli/src/commands/install_instructions.rs+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs@@ -96,12 +96,14 @@ pub fn run(_config: &Config, args: InstallInstructionsArgs) -> Result<()> {/// 3. Only `CLAUDE.md` exists → write to it./// 4. Only `AGENTS.md` exists → write to it./// 5. Neither exists → default to `CLAUDE.md` AND print a hint about-/// `--target AGENTS.md` for Codex / OpenCode / Cursor / Gemini.+/// `--target AGENTS.md` for Codex / OpenCode / Cursor / Gemini /+/// Kimi Code.////// The auto-pick exists because Claude Code uses CLAUDE.md while-/// every other supported agent (Codex, OpenCode, Cursor, Gemini CLI)-/// converged on AGENTS.md. The heuristic "extend whatever's already-/// there" matches the user's intent better than a hard-coded default.+/// every other supported agent (Codex, OpenCode, Cursor, Gemini CLI,+/// Kimi Code) converged on AGENTS.md. The heuristic "extend whatever's+/// already there" matches the user's intent better than a hard-coded+/// default.fn resolve_targets(explicit: Option<&std::path::PathBuf>) -> Result<Vec<std::path::PathBuf>> {if let Some(p) = explicit {return Ok(vec![p.clone()]);@@ -119,7 +121,8 @@ fn resolve_targets(explicit: Option<&std::path::PathBuf>) -> Result<Vec<std::pateprintln!("note: neither CLAUDE.md nor AGENTS.md exists in {}; \creating CLAUDE.md. If you use Codex / OpenCode / \- Cursor / Gemini CLI / Antigravity CLI, re-run with `--target AGENTS.md`.",+ Cursor / Gemini CLI / Antigravity CLI / Kimi Code, \+ re-run with `--target AGENTS.md`.",cwd.display());Ok(vec![claude_md])diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex da1cd119..b9ca4813 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -68,6 +68,7 @@ pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {McpClient::AntigravityCli => render_antigravity_cli(&args)?,McpClient::Zero => render_zero(&args)?,McpClient::Devin => render_devin(&args)?,+ McpClient::KimiCode => render_kimi_code(&args)?,McpClient::VsCodeCopilot => render_vscode_copilot(&args)?,};println!("{snippet}");@@ -165,6 +166,10 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>// non-default XDG setups (same policy as OpenCode above).McpClient::Zero => home()?.join(".config").join("zero").join("config.json"),McpClient::Devin => home()?.join(".devin").join("config.json"),+ // Kimi Code keeps its data dir at $KIMI_CODE_HOME when set,+ // falling back to ~/.kimi-code; MCP servers live in mcp.json at+ // that root.+ McpClient::KimiCode => kimi_code_home(std::env::var_os("KIMI_CODE_HOME"))?.join("mcp.json"),// VS Code MCP is workspace-scoped by default: `.vscode/mcp.json`// at the current workspace root. The user-profile alternative// lives under VS Code's profile-specific data dir; use VS@@ -177,6 +182,18 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>})}+/// Kimi Code's data dir: `$KIMI_CODE_HOME` when set (non-empty), else+/// `~/.kimi-code`. The env value comes in as a parameter so tests can+/// exercise both branches without mutating process env.+fn kimi_code_home(env_override: Option<std::ffi::OsString>) -> Result<PathBuf> {+ if let Some(dir) = env_override.filter(|value| !value.is_empty()) {+ return Ok(PathBuf::from(dir));+ }+ Ok(home_dir()+ .context("could not locate $HOME for config-file auto-detect")?+ .join(".kimi-code"))+}+/// Resolve the user-config file for this client. Honours/// `--config-file` when provided, else uses the canonical default/// per client.@@ -223,7 +240,8 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {| McpClient::GeminiCli| McpClient::Omp| McpClient::AntigravityCli- | McpClient::Devin => Some(JsonMcpLocation::RootMcpServers),+ | McpClient::Devin+ | McpClient::KimiCode => Some(JsonMcpLocation::RootMcpServers),McpClient::OpenCode => Some(JsonMcpLocation::RootMcp),// Zero's config.json nests servers under `mcp.servers`, the same// shape OpenClaw uses.@@ -374,6 +392,15 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {entry.insert("headers".into(), json!({"Authorization": b}));}}+ McpClient::KimiCode => {+ // Kimi Code treats an entry with `url` and no `transport`+ // field as streamable-HTTP; `transport` is only for legacy+ // SSE endpoints.+ entry.insert("url".into(), json!(server_url));+ if let Some(b) = &bearer {+ entry.insert("headers".into(), json!({"Authorization": b}));+ }+ }McpClient::VsCodeCopilot => {// VS Code MCP framework schema: `type: "http"` + `url`,// headers map for auth. Verified against@@ -737,6 +764,18 @@ fn render_devin(args: &InstallMcpArgs) -> Result<String> {))}+fn render_kimi_code(args: &InstallMcpArgs) -> Result<String> {+ Ok(format!(+ "# Kimi Code — merge into ~/.kimi-code/mcp.json\n\+ # ($KIMI_CODE_HOME/mcp.json when KIMI_CODE_HOME is set):\n\+ #\n\+ # An entry with `url` and no `transport` field is a streamable-HTTP\n\+ # server; `transport` is only needed for legacy SSE endpoints.\n\+ {snippet}\n",+ snippet = render_json_mcp_fragment(args)?,+ ))+}+fn render_vscode_copilot(args: &InstallMcpArgs) -> Result<String> {Ok(format!("# VS Code GitHub Copilot (agent mode) — write to one of:\n\@@ -805,6 +844,7 @@ mod tests {McpClient::AntigravityCli => render_antigravity_cli(&args).unwrap(),McpClient::Zero => render_zero(&args).unwrap(),McpClient::Devin => render_devin(&args).unwrap(),+ McpClient::KimiCode => render_kimi_code(&args).unwrap(),McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),}}@@ -825,6 +865,7 @@ mod tests {McpClient::AntigravityCli,McpClient::Zero,McpClient::Devin,+ McpClient::KimiCode,McpClient::VsCodeCopilot,] {let out = render_with_token(client);@@ -859,6 +900,7 @@ mod tests {McpClient::AntigravityCli,McpClient::Zero,McpClient::Devin,+ McpClient::KimiCode,McpClient::VsCodeCopilot,] {let out = render_for_test(client);@@ -884,6 +926,7 @@ mod tests {McpClient::AntigravityCli => render_antigravity_cli(&args).unwrap(),McpClient::Zero => render_zero(&args).unwrap(),McpClient::Devin => render_devin(&args).unwrap(),+ McpClient::KimiCode => render_kimi_code(&args).unwrap(),McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),}}@@ -1008,6 +1051,18 @@ mod tests {let devin_with_token = render_with_token(McpClient::Devin);assert!(devin_with_token.contains("\"headers\""));assert!(devin_with_token.contains("\"Authorization\": \"Bearer test-token-deadbeef\""));+ // Kimi Code: `url` with NO `transport` field means streamable-HTTP+ // (`transport` is legacy-SSE-only there), and the URL key is plain+ // `url` — not Gemini's `httpUrl` or Antigravity's `serverUrl`.+ let kimi = render_for_test(McpClient::KimiCode);+ assert!(kimi.contains("\"mcpServers\""));+ assert!(kimi.contains("\"url\""));+ assert!(!kimi.contains("\"transport\""));+ assert!(!kimi.contains("\"httpUrl\""));+ assert!(!kimi.contains("\"serverUrl\""));+ let kimi_with_token = render_with_token(McpClient::KimiCode);+ assert!(kimi_with_token.contains("\"headers\""));+ assert!(kimi_with_token.contains("\"Authorization\": \"Bearer test-token-deadbeef\""));// VS Code Copilot must use the `servers` top-level key — the// `mcpServers` form is silently ignored by VS Code's MCP// framework. Regression guard against a future copy-paste@@ -1018,6 +1073,22 @@ mod tests {assert!(vsc.contains("\"type\": \"http\""));}+ /// Kimi Code resolves its mcp.json under $KIMI_CODE_HOME when the env+ /// var is set (non-empty), else under ~/.kimi-code. Tested through the+ /// helper's parameter so no process-env mutation (unsafe in edition+ /// 2024, and racy under parallel tests) is needed.+ #[test]+ fn kimi_code_home_honours_env_override() {+ assert_eq!(+ kimi_code_home(Some("/tmp/custom-kimi-home".into())).unwrap(),+ PathBuf::from("/tmp/custom-kimi-home")+ );+ let default = home_dir().unwrap().join(".kimi-code");+ // An empty override falls back to the default home-based dir.+ assert_eq!(kimi_code_home(Some("".into())).unwrap(), default);+ assert_eq!(kimi_code_home(None).unwrap(), default);+ }+#[test]fn pi_apply_fails_closed_without_writing_even_with_config_override() {let tmp = tempfile::TempDir::new().unwrap();diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 06b5dc6a..1203c3ee 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -47,6 +47,27 @@ pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 9] = [("SubagentStop", "subagent-stop.sh"),];+/// Kimi Code lifecycle events ai-memory hooks. Same 9-event vocabulary+/// as Claude Code (`CLAUDE_CODE_EVENTS`), but Kimi Code wires hooks as+/// `[[hooks]]` entries in `$KIMI_CODE_HOME/config.toml` (TOML) instead of+/// a JSON settings file, so its payload comes from+/// [`kimi_code_hook_commands`] rather than the JSON hook shapes.+///+/// Adding a hook event means updating this list AND adding the matching+/// `.sh` and `.ps1` files under `hooks/kimi-code/`. The install-hooks+/// parity test fails if the bundle drifts.+pub(crate) const KIMI_CODE_EVENTS: [(&str, &str); 9] = [+ ("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"),+ ("SubagentStart", "subagent-start.sh"),+ ("SubagentStop", "subagent-stop.sh"),+];+/// Devin lifecycle events ai-memory hooks. Each pair is/// `(event-name-in-Devin-settings, POSIX hook-script-filename)`.///@@ -566,6 +587,55 @@ fn build_hook_payload(build_hook_payload_for_platform(events, emit_root, server_url, auth_token, shape, context)}+/// Build the `(event, command)` pairs behind Kimi Code's `[[hooks]]`+/// TOML entries. Kimi Code hook entries accept only `event` / `matcher`+/// / `command` / `timeout` — any other key makes the whole config.toml+/// fail to load — so callers emit exactly `event` + `command` and leave+/// the rest at Kimi Code's defaults (no `matcher` = match everything;+/// no `timeout` = 30s). Commands point at the staged script bundle via+/// the same `hook_command` mounting the other script-based agents use+/// (`.sh` on POSIX, `.ps1` on Windows).+pub(crate) fn kimi_code_hook_commands(+ emit_root: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> Vec<(&'static str, String)> {+ kimi_code_hook_commands_for_platform(+ emit_root,+ server_url,+ auth_token,+ HookCommandPlatform::current(),+ data_dir,+ project_strategy,+ )+}++fn kimi_code_hook_commands_for_platform(+ emit_root: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ platform: HookCommandPlatform,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> Vec<(&'static str, String)> {+ KIMI_CODE_EVENTS+ .iter()+ .map(|(event, script)| {+ let script = script_for_platform(script, platform);+ let abs = emit_root.join(script.as_ref());+ let command = hook_command(+ &abs,+ server_url,+ auth_token,+ HookCommandContext::new(platform, "kimi-code", data_dir, project_strategy),+ );+ (*event, command)+ })+ .collect()+}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum HookCommandPlatform {Posix,@@ -1758,6 +1828,54 @@ mod tests {}}+ #[test]+ fn kimi_code_commands_cover_all_events_with_script_paths() {+ let root = PathBuf::from("/host/hooks/kimi-code");+ let commands = kimi_code_hook_commands_for_platform(+ &root,+ "http://localhost:49374",+ Some("tok"),+ HookCommandPlatform::Posix,+ None,+ None,+ );+ assert_eq!(commands.len(), KIMI_CODE_EVENTS.len());+ let events: Vec<&str> = commands.iter().map(|(event, _)| *event).collect();+ for (event, script) in KIMI_CODE_EVENTS {+ assert!(events.contains(&event), "missing Kimi Code event {event}");+ let (_, cmd) = commands.iter().find(|(e, _)| *e == event).unwrap();+ assert!(+ cmd.contains(&format!("/host/hooks/kimi-code/{script}")),+ "{event}: command must point at the staged script: {cmd}"+ );+ }+ let (_, session_start) = &commands[0];+ assert!(+ session_start.contains("AI_MEMORY_HOOK_URL=http://localhost:49374"),+ "{session_start}"+ );+ assert!(+ session_start.contains("AI_MEMORY_AUTH_TOKEN=tok"),+ "{session_start}"+ );+ }++ #[test]+ fn kimi_code_commands_windows_use_ps1_scripts() {+ let root = PathBuf::from(r"C:\hooks\kimi-code");+ let commands = kimi_code_hook_commands_for_platform(+ &root,+ "http://h:49374",+ None,+ HookCommandPlatform::Windows,+ None,+ None,+ );+ let (_, cmd) = &commands[0];+ assert!(cmd.contains("session-start.ps1"), "{cmd}");+ assert!(!cmd.contains("session-start.sh"), "{cmd}");+ }+#[test]fn to_git_bash_path_converts_drive_letter_and_backslashes() {assert_eq!(diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex e64b949b..32f22137 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -36,9 +36,9 @@ use anyhow::{Context, Result, bail};use crate::cli::{AgentChoice, SetupAgentArgs};use crate::commands::render_shared::{- ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, CURSOR_PROFILE,- GEMINI_PROFILE, build_claude_code_payload, build_devin_payload, build_grok_payload,- hook_script_for_current_platform,+ ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CLAUDE_CODE_EVENTS, CODEX_PROFILE,+ CURSOR_PROFILE, GEMINI_PROFILE, build_claude_code_payload, build_devin_payload,+ build_grok_payload, hook_script_for_current_platform,};use crate::config::{Config, DEFAULT_SERVER_URL};@@ -141,6 +141,11 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {&args,&[&ANTIGRAVITY_TOOL_EVENTS, &ANTIGRAVITY_LIFECYCLE_EVENTS],),+ // Kimi Code's nine hook events mirror Claude Code's vocabulary+ // exactly; its `[[hooks]]` TOML merge into config.toml (shared+ // with user provider/model settings) is owned by install-hooks+ // apply-mode, so print-mode stays a conservative script listing.+ AgentChoice::KimiCode => emit_other(&emit_root, agent_sub, &args, &[&CLAUDE_CODE_EVENTS]),AgentChoice::OpenCode| AgentChoice::Pi| AgentChoice::Omp@@ -605,4 +610,36 @@ mod tests {"Gemini has no subagent hook events; setup-agent must not print nonexistent scripts");}++ #[test]+ fn kimi_code_manual_script_paths_cover_claude_code_event_set() {+ // Kimi Code's hook vocabulary (SessionStart, SessionEnd,+ // UserPromptSubmit, PreToolUse, PostToolUse, Stop, SubagentStart,+ // SubagentStop, PreCompact) mirrors Claude Code's nine events.+ let root = Path::new("/hooks/kimi-code");+ let paths = event_script_paths(root, &[&CLAUDE_CODE_EVENTS]);+ let rendered = paths+ .iter()+ .map(|path| path.to_string_lossy())+ .collect::<Vec<_>>()+ .join("\n");++ for script in [+ "session-start",+ "session-end",+ "user-prompt-submit",+ "pre-tool-use",+ "post-tool-use",+ "pre-compact",+ "stop",+ "subagent-start",+ "subagent-stop",+ ] {+ assert!(+ rendered.contains(script),+ "Kimi Code setup-agent must list {script}; got:\n{rendered}"+ );+ }+ assert_eq!(paths.len(), 9);+ }}diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex 760a963f..c54a867c 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -39,6 +39,8 @@ enum RewriteOp {/// Zero hooks.json — `hooks` array entries whose `id` carries the/// `ai-memory-` prefix.ZeroHooksJson,+ /// Kimi Code `[[hooks]]` rules inside config.toml.+ KimiCodeHooksToml,/// MCP JSON config for one client shape.McpJson(McpClient),/// Codex TOML MCP config.@@ -215,6 +217,19 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {);}+ let kimi_code = install_hooks::kimi_code_config_path()?;+ if kimi_code.exists() {+ let content = std::fs::read_to_string(&kimi_code)+ .with_context(|| format!("reading {}", kimi_code.display()))?;+ let removal = strip_kimi_code_hooks(&content)?;+ push_rewrite(+ &mut plan,+ kimi_code,+ removal.removed_events,+ RewriteOp::KimiCodeHooksToml,+ );+ }+let plugin = install_hooks::opencode_plugin_path()?;push_generated_delete(&mut plan, plugin, DeleteKind::OpenCodePlugin);@@ -258,6 +273,7 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {Zero,VsCodeCopilot,Devin,+ KimiCode,] {let Ok(path) = install_mcp::mcp_config_path(client) else {continue;@@ -407,6 +423,7 @@ fn apply_change(change: &PlannedChange, name: Option<&str>, url: &str) -> anyhowstrip_antigravity_hooks(&out)?.new_content}RewriteOp::ZeroHooksJson => strip_zero_hooks(&out)?.new_content,+ RewriteOp::KimiCodeHooksToml => strip_kimi_code_hooks(&out)?.new_content,RewriteOp::McpJson(client) => strip_mcp_json(&out, client, name, url)?.0,RewriteOp::McpToml => strip_mcp_toml(&out, name, url)?.0,};@@ -764,6 +781,48 @@ fn strip_antigravity_hooks(content: &str) -> Result<HookRemoval> {})}+/// Remove ai-memory's `[[hooks]]` rules from Kimi Code's config.toml. The+/// same file holds the user's providers/model settings and any third-party+/// rules, so ownership is proven by the hook command signature alone and+/// everything else round-trips untouched.+fn strip_kimi_code_hooks(content: &str) -> Result<HookRemoval> {+ let mut removed_events = Vec::new();+ let new_content = mutate_toml(content, |doc| {+ let Some(hooks) = doc+ .get_mut("hooks")+ .and_then(toml_edit::Item::as_array_of_tables_mut)+ else {+ return Ok(());+ };+ for index in (0..hooks.len()).rev() {+ let Some(table) = hooks.get_mut(index) else {+ continue;+ };+ let ours = table+ .get("command")+ .and_then(toml_edit::Item::as_str)+ .is_some_and(hook_command_is_ours);+ if !ours {+ continue;+ }+ let event = table+ .get("event")+ .and_then(toml_edit::Item::as_str)+ .unwrap_or("unknown")+ .to_string();+ removed_events.push(format!("kimi-code.{event}"));+ hooks.remove(index);+ }+ Ok(())+ })?;+ // Index-descending removal collects events in reverse document order.+ removed_events.reverse();+ Ok(HookRemoval {+ new_content,+ removed_events,+ })+}+fn generated_file_is_ours(path: &Path, kind: DeleteKind) -> bool {let Ok(content) = std::fs::read_to_string(path) else {return false;@@ -831,6 +890,7 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {| McpClient::GeminiCli| McpClient::Omp| McpClient::AntigravityCli+ | McpClient::KimiCode| McpClient::Devin => Some(&["mcpServers"]),McpClient::OpenCode => Some(&["mcp"]),McpClient::Openclaw | McpClient::Zero => Some(&["mcp", "servers"]),@@ -1614,4 +1674,93 @@ mod tests {strip_mcp_toml(content, Some("ai-memory"), "http://127.0.0.1:49374/mcp").unwrap();assert!(removed.is_empty());}++ #[test]+ fn strip_kimi_code_hooks_removes_only_ours_preserving_config() {+ let content = r#"model = "kimi-k2"++[providers.kimi]+api_key = "sk-user-key"++[[hooks]]+event = "SessionStart"+command = "AI_MEMORY_HOOK_URL=http://h /x/session-start.sh"++[[hooks]]+event = "SessionStart"+matcher = "*"+command = "/usr/bin/user-session-start"+timeout = 10++[[hooks]]+event = "Stop"+command = "'/usr/local/bin/ai-memory' hook --event stop --agent kimi-code --server-url http://h:49374"+"#;+ let out = strip_kimi_code_hooks(content).unwrap();+ assert_eq!(+ out.removed_events,+ vec![+ "kimi-code.SessionStart".to_string(),+ "kimi-code.Stop".to_string()+ ]+ );+ let doc: toml_edit::DocumentMut = out.new_content.parse().unwrap();+ assert_eq!(doc.get("model").and_then(|m| m.as_str()), Some("kimi-k2"));+ assert_eq!(+ doc.get("providers")+ .and_then(|p| p.get("kimi"))+ .and_then(|k| k.get("api_key"))+ .and_then(|k| k.as_str()),+ Some("sk-user-key")+ );+ let hooks = doc+ .get("hooks")+ .and_then(toml_edit::Item::as_array_of_tables)+ .expect("third-party hooks must survive");+ assert_eq!(hooks.len(), 1, "only ai-memory rules removed");+ let kept = hooks.get(0).unwrap();+ assert_eq!(+ kept.get("command").and_then(|c| c.as_str()),+ Some("/usr/bin/user-session-start")+ );+ assert_eq!(kept.get("matcher").and_then(|m| m.as_str()), Some("*"));+ assert_eq!(kept.get("timeout").and_then(|t| t.as_integer()), Some(10));+ }++ #[test]+ fn strip_kimi_code_hooks_all_ours_leaves_no_hooks_section() {+ let content = "[providers.kimi]\napi_key = \"sk-user-key\"\n\n[[hooks]]\nevent = \"Stop\"\ncommand = \"AI_MEMORY_HOOK_URL=x /a/stop.sh\"\n";+ let out = strip_kimi_code_hooks(content).unwrap();+ assert_eq!(out.removed_events, vec!["kimi-code.Stop".to_string()]);+ assert!(+ !out.new_content.contains("hooks"),+ "emptied [[hooks]] array must serialize to nothing: {}",+ out.new_content+ );+ assert!(out.new_content.contains("[providers.kimi]"));+ }++ #[test]+ fn strip_kimi_code_hooks_no_hooks_key_is_noop() {+ let content = "model = \"kimi-k2\"\n";+ let out = strip_kimi_code_hooks(content).unwrap();+ assert!(out.removed_events.is_empty());+ assert_eq!(out.new_content, content);+ }++ #[test]+ fn strip_mcp_kimi_code_root_servers() {+ let content = r#"{"mcpServers":{"ai-memory":{"url":"http://127.0.0.1:49374/mcp","headers":{"X-Token":"t"}},"other":{"url":"http://x"}}}"#;+ let (out, removed) = strip_mcp_json(+ content,+ McpClient::KimiCode,+ Some("ai-memory"),+ "http://127.0.0.1:49374/mcp",+ )+ .unwrap();+ assert_eq!(removed, vec!["ai-memory".to_string()]);+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert!(v["mcpServers"].get("ai-memory").is_none());+ assert!(v["mcpServers"].get("other").is_some());+ }}diff --git a/crates/ai-memory-cli/tests/removal.rs b/crates/ai-memory-cli/tests/removal.rsindex 093fa1a8..3ad3c234 100644--- a/crates/ai-memory-cli/tests/removal.rs+++ b/crates/ai-memory-cli/tests/removal.rs@@ -34,7 +34,10 @@ fn command_with_home(home: &Path) -> Command {.env("APPDATA", app_data).env("LOCALAPPDATA", local_app_data).env("AI_MEMORY_HOME", home)- .env("AI_MEMORY_DATA_DIR", home.join(".ai-memory-data"));+ .env("AI_MEMORY_DATA_DIR", home.join(".ai-memory-data"))+ // A host-level KIMI_CODE_HOME would pull uninstall's kimi-code+ // config sweep out of the sandbox; tests opt back in explicitly.+ .env_remove("KIMI_CODE_HOME");command}@@ -912,3 +915,116 @@ fn uninstall_mcp_removes_devin_only() {"third-party MCP server must survive");}++#[test]+fn uninstall_kimi_code_hooks_preserves_user_entries() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let kimi = home.path().join(".kimi-code");+ std::fs::create_dir_all(&kimi).unwrap();+ let config = kimi.join("config.toml");+ std::fs::write(+ &config,+ r#"model = "kimi-k2"++[providers.kimi]+base_url = "https://api.moonshot.cn/v1"+api_key = "sk-user-key"++[[hooks]]+event = "SessionStart"+command = "AI_MEMORY_HOOK_URL=http://h /x/session-start.sh"++[[hooks]]+event = "SessionStart"+matcher = "*"+command = "/usr/bin/user-session-start"+timeout = 10++[[hooks]]+event = "Stop"+command = "'/usr/local/bin/ai-memory' hook --event stop --agent kimi-code --server-url http://h:49374"+"#,+ )+ .unwrap();++ let status = command_with_home(home.path())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ let after = std::fs::read_to_string(&config).unwrap();+ let doc: toml_edit::DocumentMut = after.parse().unwrap();+ assert_eq!(doc.get("model").and_then(|m| m.as_str()), Some("kimi-k2"));+ assert_eq!(+ doc.get("providers")+ .and_then(|p| p.get("kimi"))+ .and_then(|k| k.get("api_key"))+ .and_then(|k| k.as_str()),+ Some("sk-user-key"),+ "[providers] table must survive"+ );+ let hooks = doc+ .get("hooks")+ .and_then(toml_edit::Item::as_array_of_tables)+ .expect("third-party [[hooks]] entries must survive");+ assert_eq!(hooks.len(), 1, "only ai-memory rules removed");+ assert_eq!(+ hooks+ .get(0)+ .and_then(|t| t.get("command"))+ .and_then(|c| c.as_str()),+ Some("/usr/bin/user-session-start")+ );+ assert!(+ !after.contains("AI_MEMORY_HOOK_URL") && !after.contains("--agent kimi-code"),+ "no ai-memory hook command may remain: {after}"+ );+}++#[test]+fn uninstall_mcp_custom_url_removes_kimi_code_only_by_endpoint() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ // KIMI_CODE_HOME moves the whole data dir; point it away from HOME to+ // prove uninstall honours the override.+ let kimi = home.path().join("custom-kimi-home");+ std::fs::create_dir_all(&kimi).unwrap();+ let mcp = kimi.join("mcp.json");+ std::fs::write(+ &mcp,+ r#"{+ "mcpServers": {+ "ai-memory": {"url":"http://example.invalid/mcp"},+ "custom-memory": {"url":"http://lan:49374/mcp"},+ "other": {"url":"http://other/mcp","headers":{"Authorization":"Bearer t"}}+ }+ }"#,+ )+ .unwrap();++ let status = command_with_home(home.path())+ .args([+ "uninstall",+ "--apply",+ "--only",+ "mcp",+ "--mcp-url",+ "http://lan:49374/mcp",+ "--yes",+ ])+ .env("KIMI_CODE_HOME", &kimi)+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ let after: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&mcp).unwrap()).unwrap();+ assert!(after["mcpServers"].get("custom-memory").is_none());+ assert!(+ after["mcpServers"].get("ai-memory").is_some(),+ "same name with a different endpoint must survive"+ );+ assert!(after["mcpServers"].get("other").is_some());+}diff --git a/crates/ai-memory-cli/tests/routing_instructions.rs b/crates/ai-memory-cli/tests/routing_instructions.rsindex 82fca471..5e94e16d 100644--- a/crates/ai-memory-cli/tests/routing_instructions.rs+++ b/crates/ai-memory-cli/tests/routing_instructions.rs@@ -367,6 +367,43 @@ fn devin_install_instructions_targets_agents_md() {assert!(!project.path().join("CLAUDE.md").exists());}+#[test]+fn kimi_code_install_instructions_targets_agents_md() {+ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();++ // Kimi Code's canonical instruction file is AGENTS.md; create it+ // first so it gets picked up instead of defaulting to CLAUDE.md.+ fs::write(project.path().join("AGENTS.md"), "# Project\n").unwrap();++ let output = run_ai_memory(+ project.path(),+ home.path(),+ &["install-instructions", "--no-skills"],+ );+ assert_success(output);++ let agents_md = fs::read_to_string(project.path().join("AGENTS.md")).unwrap();+ assert!(agents_md.contains(MARKER_START));+ assert!(agents_md.contains("Use the installed ai-memory Agent Skills"));+ assert!(!project.path().join("CLAUDE.md").exists());++ // With neither file present, the fallback hint must point Kimi Code+ // users at `--target AGENTS.md`.+ let empty = tempfile::tempdir().unwrap();+ let output = run_ai_memory(+ empty.path(),+ home.path(),+ &["install-instructions", "--no-skills"],+ );+ assert!(output.status.success());+ let stderr = String::from_utf8(output.stderr).unwrap();+ assert!(+ stderr.contains("Kimi Code"),+ "fallback hint must mention Kimi Code; got:\n{stderr}"+ );+}+#[test]fn devin_install_instructions_writes_project_devin_skills() {let project = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 14638b47..274694bd 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -202,6 +202,8 @@ pub enum AgentKind {Zero,/// Devin CLI (Cognition).Devin,+ /// Kimi Code CLI (Moonshot AI).+ KimiCode,/// Anything else (manual capture, future agents).Other,}@@ -212,7 +214,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; 14] = [+ pub const ALL: [Self; 15] = [Self::ClaudeCode,Self::Codex,Self::OpenCode,@@ -226,6 +228,7 @@ impl AgentKind {Self::Grok,Self::Zero,Self::Devin,+ Self::KimiCode,Self::Other,];@@ -246,6 +249,7 @@ impl AgentKind {Self::Grok => "grok",Self::Zero => "zero",Self::Devin => "devin",+ Self::KimiCode => "kimi-code",Self::Other => "other",}}@@ -269,6 +273,7 @@ impl AgentKind {"grok" => Self::Grok,"zero" => Self::Zero,"devin" => Self::Devin,+ "kimi-code" | "kimi" => Self::KimiCode,_ => Self::Other,}}@@ -359,6 +364,26 @@ mod tests {assert!(AgentKind::Devin.session_start_injects_handoff());}+ #[test]+ fn agent_kind_kimi_code_round_trips() {+ assert_eq!(AgentKind::KimiCode.as_str(), "kimi-code");+ assert_eq!(AgentKind::from_wire("kimi-code"), AgentKind::KimiCode);+ assert_eq!(AgentKind::from_wire("kimi"), AgentKind::KimiCode);+ // serde uses rename_all = "kebab-case" → "kimi-code".+ assert_eq!(+ serde_json::to_string(&AgentKind::KimiCode).unwrap(),+ "\"kimi-code\""+ );+ assert_eq!(+ serde_json::from_str::<AgentKind>("\"kimi-code\"").unwrap(),+ AgentKind::KimiCode+ );+ // Unknown tags still degrade to Other.+ assert_eq!(AgentKind::from_wire("kimi-2"), AgentKind::Other);+ // Kimi Code can inject the session-start handoff (consumes additionalContext).+ assert!(AgentKind::KimiCode.session_start_injects_handoff());+ }+#[test]fn page_path_rejects_backslashes_and_windows_prefixes() {assert!(PagePath::new(r"notes\secret.md").is_err());diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rsindex ee344eb3..56c73008 100644--- a/crates/ai-memory-core/src/routing_snippet.rs+++ b/crates/ai-memory-core/src/routing_snippet.rs@@ -64,8 +64,8 @@ install or refresh work.If you're about to write a durable project rule ("always X", "neverY", "all PRs must ..."), write it in the project's canonical agent instruction file.Many projects use CLAUDE.md for Claude Code and-AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI, but if the project-says one file is canonical, use that file.+AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Kimi Code,+but if the project says one file is canonical, use that file.If the rule is a standing *user/team* preference that should apply toevery project (tech choices, code style, personal conventions), save it@@ -81,8 +81,8 @@ latest binary's recommended copy:- **From the agent** (no terminal needed): ask "refresh the ai-memoryrouting in this project". The agent calls `memory_install_self_routing`,picks the right filename for itself (Claude Code -> `CLAUDE.md`; Codex /- OpenCode / Cursor / Gemini -> `AGENTS.md`), uses its Write / Edit tool- to replace or append the returned `markered_block` while preserving+ OpenCode / Cursor / Gemini / Kimi Code -> `AGENTS.md`), uses its Write /+ Edit tool to replace or append the returned `markered_block` while preservingnon-ai-memory user content, then writes or updates each returned`managed_skills` item under the selected skill root from `target_hints`using its `relative_path`.diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex ce6ad144..5cb0bb30 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -2453,6 +2453,7 @@ impl AiMemoryServer {"antigravity_cli": "AGENTS.md","zero": "AGENTS.md","devin": "AGENTS.md",+ "kimi_code": "AGENTS.md","default": "AGENTS.md"},"managed_skills": managed_skills,@@ -3286,6 +3287,10 @@ mod tests {response["agent_filenames"]["devin"].as_str().unwrap(),"AGENTS.md");+ assert_eq!(+ response["agent_filenames"]["kimi_code"].as_str().unwrap(),+ "AGENTS.md"+ );// Proposed symmetrically alongside the devin assertion above:// upstream added "zero" to this same payload (issue #156) without a// matching assertion. Not validated against a live Zero agent indiff --git a/crates/ai-memory-store/migrations/V29__sessions_kimi_code_agent_kind.sql b/crates/ai-memory-store/migrations/V29__sessions_kimi_code_agent_kind.sqlnew file mode 100644index 00000000..7b14f6d0--- /dev/null+++ b/crates/ai-memory-store/migrations/V29__sessions_kimi_code_agent_kind.sql@@ -0,0 +1,63 @@+-- Expand sessions.agent_kind CHECK for Kimi Code CLI (Moonshot AI).+--+-- V09/V11/V20/V25/V26/V28 intentionally enumerated every supported agent.+-- Adding a concrete AgentKind must update the persisted CHECK too, or+-- Kimi Code hook events fail at begin_session on upgraded databases (the+-- hook router would WARN and drop the session, silently breaking Kimi Code+-- capture server-side). V28 (the Devin CLI) landed first, so this+-- migration's CHECK list carries 'devin' forward in addition to adding+-- 'kimi-code' — dropping it here would silently break Devin the same way+-- omitting 'kimi-code' would break us.++PRAGMA foreign_keys = OFF;++DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_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','grok','zero','devin','kimi-code','other')),+ cwd TEXT,+ started_at INTEGER NOT NULL,+ ended_at INTEGER,+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL+);++INSERT INTO sessions_new SELECT * 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;++-- Recreate the V18 pairing-enforcement trigger: dropping the old `sessions`+-- table above also dropped its triggers. Every sessions-table rebuild after+-- V18 must reinstate it or the (workspace_id, project_id) pairing invariant+-- silently stops being enforced on inserts.+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;++-- Recreate the V22 claim/session pairing trigger, which references `sessions`+-- and must be dropped before the table rebuild above.+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;++PRAGMA foreign_keys = ON;diff --git a/docs/install.md b/docs/install.mdindex ba25bd8a..3eb036d1 100644--- a/docs/install.md+++ b/docs/install.md@@ -9,7 +9,7 @@ path (docker + Claude Code). This page covers everything else:- [Arch Linux native packages (AUR)](#arch-linux-native-packages-aur)(systemd system service or user service)- [Configuring other agent CLIs](#configuring-other-agent-clis)- (Codex, Devin CLI, OpenCode, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, OpenClaw, VS Code Copilot)+ (Codex, Devin CLI, OpenCode, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, VS Code Copilot)- [Installing hooks without docker](#installing-hooks-without-docker)(curl-based installer)- [Running ai-memory without docker](#running-ai-memory-without-docker)@@ -489,11 +489,11 @@ Each agent CLI needs two things:becomes manual.Claude Desktop is MCP-only today. Claude Code, Codex, Devin CLI, OpenCode,-OMP, Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, and OpenClaw have lifecycle capture paths through+OMP, Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Kimi Code, and OpenClaw have lifecycle capture paths through`install-hooks`.> **Two-step hook install pattern.** Claude Code, Codex, Cursor,-> Gemini CLI, Antigravity CLI, Grok Build CLI, and Devin CLI use shell/PowerShell hook scripts: (1) `docker cp` the+> Gemini CLI, Antigravity CLI, Grok Build CLI, Kimi Code, and Devin CLI use shell/PowerShell hook scripts: (1) `docker cp` the> bundled scripts to your home dir, (2) `docker run --rm install-hooks`> to render the config snippet.> On native Windows, Claude Code is the exception to the PowerShell default:@@ -567,6 +567,34 @@ The `SessionStart` hook injects pending handoffs through Devin'ssession/cwd context from its hook state and process environment so those eventsare still captured.+### Kimi Code++Kimi Code keeps MCP servers in `~/.kimi-code/mcp.json` and lifecycle hooks in+`~/.kimi-code/config.toml`; both move together when `$KIMI_CODE_HOME` is set.+The CLI also accepts `--agent kimi` as an alias.++```bash+ai-memory install-mcp --client kimi-code --apply \+ --server-url "http://homelab:49374/mcp" \+ --auth-token "$TOKEN"++ai-memory install-hooks --agent kimi-code --apply \+ --server-url "http://homelab:49374" \+ --auth-token "$TOKEN"+```++`install-hooks` merges `[[hooks]]` entries into `config.toml`, preserving the+provider/model settings the same file holds, and stages the hook scripts under+`~/.local/share/ai-memory/hooks/kimi-code/`. Capture covers 9 events —+`SessionStart`, `SessionEnd`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,+`Stop`, `SubagentStart`, `SubagentStop`, and `PreCompact` — as fire-and-forget+POSTs to `/hook`. A pending handoff is injected at `SessionStart` through the+hook's stdout, which Kimi Code appends to the model context.++Kimi Code hook entries accept only `event`, `matcher`, `command`, and+`timeout`; extra fields make the whole `config.toml` fail to load, so prefer+`install-hooks --apply` over hand edits.+### OpenCode```bashdiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex d1772736..4c0aad11 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -19,9 +19,9 @@This page documents how to register ai-memory as an MCP server withagent CLIs beyond the README quick start.-Claude Code, OpenAI Codex, Devin CLI, Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, OpenClaw, OpenCode, and+Claude Code, OpenAI Codex, Devin CLI, Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, OpenCode, andOMP have automatic capture integrations (shell/PowerShell hooks for-Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Grok Build CLI, TypeScript plugin/extension+Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Grok Build CLI / Kimi Code, TypeScript plugin/extensionfiles for OpenClaw / OpenCode / OMP) and are covered in the[main README](../README.md#quick-start). On native Windows, Claude Code usesGit Bash `.sh` hooks rather than the PowerShell default used by other@@ -509,6 +509,63 @@ fill both in:stance as the single-slot `/handoff` fallback). A payload that does carryits own `session_id` always wins over both.+## Kimi Code++**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported via+`ai-memory install-hooks --agent kimi-code --apply`.++**Config file (MCP):** `~/.kimi-code/mcp.json`+(`$KIMI_CODE_HOME/mcp.json` when `KIMI_CODE_HOME` is set).++Kimi Code treats any `mcpServers` entry with a `url` field and no+`transport` field as a streamable-HTTP server, so the entry needs no+transport key:++```bash+ai-memory install-mcp --client kimi-code --apply \+ --server-url "http://homelab:49374/mcp" --auth-token "$TOKEN"+```++which merges:++```json+{+ "mcpServers": {+ "ai-memory": {+ "url": "http://homelab:49374/mcp",+ "headers": { "Authorization": "Bearer <token>" }+ }+ }+}+```++**Config file (hooks):** `~/.kimi-code/config.toml` (same `$KIMI_CODE_HOME`+base). Kimi Code stores hooks as `[[hooks]]` array entries in the same TOML+file that holds its provider/model settings; `install-hooks` merges+ai-memory's entries and preserves everything else:++```bash+ai-memory install-hooks --agent kimi-code --apply \+ --server-url "http://homelab:49374" --auth-token "$TOKEN"+```++The installed entries cover 9 events — `SessionStart`, `SessionEnd`,+`UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`, `SubagentStart`,+`SubagentStop`, and `PreCompact` — and call the staged scripts under+`~/.local/share/ai-memory/hooks/kimi-code/`. Capture is fire-and-forget; a+pending handoff is injected at `SessionStart` via the hook's stdout (Kimi+Code appends stdout to context on exit 0), the same pattern as Gemini CLI.++**Gotchas:**+- Do not add a `transport` field for HTTP servers: `url` alone means+ streamable HTTP; `transport: "sse"` selects the legacy SSE transport.+- Hook entries accept only `event`, `matcher`, `command`, and `timeout`+ (seconds, 1-600, default 30). Any extra field makes Kimi Code fail to load+ the entire `config.toml`, so prefer `install-hooks --apply` over hand+ edits.+- Kimi Code runs rules with an identical `command` only once; ai-memory's+ entries use one script per event, so all 9 fire independently.+## OpenClaw**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported via a nativediff --git a/docs/usage.md b/docs/usage.mdindex 87ac2a38..aedb4cd2 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -194,6 +194,9 @@ Client cleanup hints:`.devin/skills` for stale MCP, hook, or routing-skill entries.- Gemini CLI and Antigravity CLI: check `settings.json` or equivalent hook/MCPconfig files.+- Kimi Code: check `~/.kimi-code/mcp.json` and the `[[hooks]]` entries in+ `~/.kimi-code/config.toml` (both under `$KIMI_CODE_HOME` when set) for stale+ MCP or hook entries.- OpenCode, OpenClaw, and OMP: check MCP config and plugin/extension directories;move old memory plugins to a disabled/quarantine directory before deleting.- VS Code Copilot and Claude Desktop: these are usually MCP-only, so confirm@@ -287,7 +290,7 @@ docker exec ai-memory git -C /data/wiki log --onelineDurable project rules belong in the agent's rules file, not only in thewiki. For Claude Code that is `CLAUDE.md`; for Codex, Devin CLI, OpenCode,-Cursor, and Gemini CLI it is usually `AGENTS.md`.+Cursor, Kimi Code, and Gemini CLI it is usually `AGENTS.md`.The consolidator classifies compiled observations as `decision`,`fact`, `rule`, or `gotcha`. Rule-tagged pages are routed todiff --git a/docs/windows.md b/docs/windows.mdindex f5d1d447..72c66151 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -6,7 +6,8 @@ agent CLI actually runs.## Rule Of ThumbRun `install-mcp` and `install-hooks` from the same environment that-launches Claude Code, Codex, Devin CLI, Cursor, Gemini CLI, or another agent.+launches Claude Code, Codex, Devin CLI, Cursor, Gemini CLI, Kimi Code, or+another agent.- If the agent runs inside WSL2, install ai-memory inside WSL2.- If the agent runs as a native Windows process, install ai-memory from@@ -22,8 +23,8 @@ Claude Code invokes its hooks with Claude's direct exec formCommand](#native-hook-command-claude-code-on-windows). Set`AI_MEMORY_HOOK_PLATFORM=windows-bash` to fall back to the older`bash -c` + `.sh` Git Bash commands. Other native Windows script-hook-agents, including Devin CLI, keep the current script-command defaults for-their harness.+agents, including Devin CLI and Kimi Code, keep the current script-command+defaults for their harness.## Scenario A: Everything Inside WSL2@@ -108,11 +109,11 @@ the CLI to render hook commands for the native Windows agent:exec form (`command` executable + `args` argv array), no shell — set`AI_MEMORY_HOOK_PLATFORM=windows-bash` for the old `bash -c` + `.sh`Git Bash path.-- Other native Windows script-hook agents, including Devin CLI, use their- generated script-command hook entries for the selected platform.+- Other native Windows script-hook agents, including Devin CLI and Kimi Code,+ use their generated script-command hook entries for the selected platform.Use the matching `--client` / `--agent` values for other clients, for-example `codex`, `devin`, `cursor`, or `gemini-cli`.+example `codex`, `devin`, `kimi-code`, `cursor`, or `gemini-cli`.For Devin, `install-mcp --client devin --apply` writes MCP config to`%USERPROFILE%\.devin\config.json`. `install-hooks --agent devin --apply`@@ -298,7 +299,8 @@ Windows agent builds.Claude Code invokes hooks as a direct binary call (no shell) by default;`AI_MEMORY_HOOK_PLATFORM=windows-bash` restores the Git Bash `bash -c`path. WSL2 Claude Code uses normal WSL `.sh` paths.-- Codex, Devin CLI, OpenCode, Cursor, Gemini CLI, Grok Build CLI, and OpenClaw may each choose different+- Codex, Devin CLI, OpenCode, Cursor, Gemini CLI, Grok Build CLI, Kimi Code,+ and OpenClaw may each choose differentWindows config locations or shell execution behavior. ai-memory usesthe current best-known defaults, but they need validation on realinstallations.diff --git a/hooks/_lib.sh b/hooks/_lib.shindex d5f425ba..b16129a6 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -2,7 +2,8 @@# Sourced by per-agent lifecycle hook scripts. POSIX shell only —# no bash-isms, no non-standard deps (no jq, no toml crate). Keep changes# byte-trivial because every supported agent (claude-code, codex,-# cursor, gemini-cli, antigravity-cli, opencode, omp) sources this same file.+# cursor, gemini-cli, kimi-code, antigravity-cli, opencode, omp) sources+# this same file.# Walk up from "$1" toward $HOME (or /) looking for `.ai-memory.toml`.# Prints the absolute path of the first marker found, or nothing.diff --git a/hooks/kimi-code/post-tool-use.ps1 b/hooks/kimi-code/post-tool-use.ps1new file mode 100644index 00000000..ab2b21ce--- /dev/null+++ b/hooks/kimi-code/post-tool-use.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "post-tool-use" -Agent "kimi-code"+exit 0diff --git a/hooks/kimi-code/post-tool-use.sh b/hooks/kimi-code/post-tool-use.shnew file mode 100755index 00000000..762d057b--- /dev/null+++ b/hooks/kimi-code/post-tool-use.sh@@ -0,0 +1,15 @@+#!/bin/sh+# kimi-code post-tool-use hook.+# Forwards the event JSON to the ai-memory server, fire-and-forget.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=post-tool-use&agent=kimi-code${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/hooks/kimi-code/pre-compact.ps1 b/hooks/kimi-code/pre-compact.ps1new file mode 100644index 00000000..8d717799--- /dev/null+++ b/hooks/kimi-code/pre-compact.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "pre-compact" -Agent "kimi-code"+exit 0diff --git a/hooks/kimi-code/pre-compact.sh b/hooks/kimi-code/pre-compact.shnew file mode 100755index 00000000..a9858c26--- /dev/null+++ b/hooks/kimi-code/pre-compact.sh@@ -0,0 +1,15 @@+#!/bin/sh+# kimi-code pre-compact hook.+# Forwards the event JSON to the ai-memory server, fire-and-forget.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=pre-compact&agent=kimi-code${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/hooks/kimi-code/pre-tool-use.ps1 b/hooks/kimi-code/pre-tool-use.ps1new file mode 100644index 00000000..f8a8c685--- /dev/null+++ b/hooks/kimi-code/pre-tool-use.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "kimi-code"+exit 0diff --git a/hooks/kimi-code/pre-tool-use.sh b/hooks/kimi-code/pre-tool-use.shnew file mode 100755index 00000000..ad00d4e2--- /dev/null+++ b/hooks/kimi-code/pre-tool-use.sh@@ -0,0 +1,15 @@+#!/bin/sh+# kimi-code pre-tool-use hook.+# Forwards the event JSON to the ai-memory server, fire-and-forget.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=pre-tool-use&agent=kimi-code${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/hooks/kimi-code/session-end.ps1 b/hooks/kimi-code/session-end.ps1new file mode 100644index 00000000..2f4cf482--- /dev/null+++ b/hooks/kimi-code/session-end.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "session-end" -Agent "kimi-code"+exit 0diff --git a/hooks/kimi-code/session-end.sh b/hooks/kimi-code/session-end.shnew file mode 100755index 00000000..dc654715--- /dev/null+++ b/hooks/kimi-code/session-end.sh@@ -0,0 +1,15 @@+#!/bin/sh+# kimi-code session-end hook.+# Forwards the event JSON to the ai-memory server, fire-and-forget.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=session-end&agent=kimi-code${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/hooks/kimi-code/session-start.ps1 b/hooks/kimi-code/session-start.ps1new file mode 100644index 00000000..279a83b8--- /dev/null+++ b/hooks/kimi-code/session-start.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "session-start" -Agent "kimi-code" -FetchHandoff+exit 0diff --git a/hooks/kimi-code/session-start.sh b/hooks/kimi-code/session-start.shnew file mode 100755index 00000000..838251d7--- /dev/null+++ b/hooks/kimi-code/session-start.sh@@ -0,0 +1,21 @@+#!/bin/sh+# kimi-code SessionStart hook.+# 1. Forwards the event JSON to the ai-memory server (fire-and-forget).+# 2. Synchronously fetches any pending cross-agent handoff and prints+# it to stdout — kimi-code appends exit-0 hook stdout to the agent's+# context, so the resuming agent sees prior context with no human+# in the loop.+#+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=session-start&agent=kimi-code${QS}" >/dev/null 2>&1 || true+ai_memory_get_handoff "$SERVER/handoff?agent=kimi-code${QS}" 2>/dev/null || true+exit 0diff --git a/hooks/kimi-code/stop.ps1 b/hooks/kimi-code/stop.ps1new file mode 100644index 00000000..3eec8298--- /dev/null+++ b/hooks/kimi-code/stop.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "stop" -Agent "kimi-code"+exit 0diff --git a/hooks/kimi-code/stop.sh b/hooks/kimi-code/stop.shnew file mode 100755index 00000000..2be6cb73--- /dev/null+++ b/hooks/kimi-code/stop.sh@@ -0,0 +1,15 @@+#!/bin/sh+# kimi-code stop hook.+# Forwards the event JSON to the ai-memory server, fire-and-forget.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=stop&agent=kimi-code${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/hooks/kimi-code/subagent-start.ps1 b/hooks/kimi-code/subagent-start.ps1new file mode 100644index 00000000..2aa5099d--- /dev/null+++ b/hooks/kimi-code/subagent-start.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "subagent-start" -Agent "kimi-code"+exit 0diff --git a/hooks/kimi-code/subagent-start.sh b/hooks/kimi-code/subagent-start.shnew file mode 100755index 00000000..1c3cccba--- /dev/null+++ b/hooks/kimi-code/subagent-start.sh@@ -0,0 +1,16 @@+#!/bin/sh+# kimi-code subagent-start hook — forwards the event so the server can seed+# the subagent's session id for drop_subagent_captures (so the whole nested+# session, incl. the unmarked tail, is dropped). Mirrors stop.sh.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=subagent-start&agent=kimi-code${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/hooks/kimi-code/subagent-stop.ps1 b/hooks/kimi-code/subagent-stop.ps1new file mode 100644index 00000000..fa848796--- /dev/null+++ b/hooks/kimi-code/subagent-stop.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "subagent-stop" -Agent "kimi-code"+exit 0diff --git a/hooks/kimi-code/subagent-stop.sh b/hooks/kimi-code/subagent-stop.shnew file mode 100755index 00000000..7aa88d73--- /dev/null+++ b/hooks/kimi-code/subagent-stop.sh@@ -0,0 +1,15 @@+#!/bin/sh+# kimi-code subagent-stop hook — forwards the event so the server can forget+# the subagent's session id (drop_subagent_captures). Mirrors stop.sh.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=subagent-stop&agent=kimi-code${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/hooks/kimi-code/user-prompt-submit.ps1 b/hooks/kimi-code/user-prompt-submit.ps1new file mode 100644index 00000000..57379652--- /dev/null+++ b/hooks/kimi-code/user-prompt-submit.ps1@@ -0,0 +1,3 @@+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "user-prompt" -Agent "kimi-code"+exit 0diff --git a/hooks/kimi-code/user-prompt-submit.sh b/hooks/kimi-code/user-prompt-submit.shnew file mode 100755index 00000000..e439dc62--- /dev/null+++ b/hooks/kimi-code/user-prompt-submit.sh@@ -0,0 +1,15 @@+#!/bin/sh+# kimi-code user-prompt hook.+# Forwards the event JSON to the ai-memory server, fire-and-forget.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=user-prompt&agent=kimi-code${QS}" >/dev/null 2>&1 || true+exit 0diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.shindex 7f2a7d3e..1316e1bf 100755--- a/scripts/install-hooks.sh+++ b/scripts/install-hooks.sh@@ -10,7 +10,7 @@# | bash -s -- --agent claude-code## Options:-# --agent <claude-code|codex|cursor|gemini-cli|antigravity-cli|grok|opencode|openclaw|omp|oh-my-pi|pi>+# --agent <claude-code|codex|cursor|gemini-cli|kimi-code|antigravity-cli|grok|opencode|openclaw|omp|oh-my-pi|pi># which agent (default: claude-code;# generated-plugin agents print hints)# --to <dir> install root (default: $HOME/.ai-memory/hooks)@@ -46,9 +46,9 @@ while [[ $# -gt 0 ]]; dodonecase "$AGENT" in- claude-code|codex|cursor|gemini-cli|antigravity-cli|grok|opencode|openclaw|omp|pi|oh-my-pi) ;;+ claude-code|codex|cursor|gemini-cli|kimi-code|antigravity-cli|grok|opencode|openclaw|omp|pi|oh-my-pi) ;;*)- echo "unsupported agent: $AGENT (expected claude-code | codex | cursor | gemini-cli | antigravity-cli | grok | opencode | openclaw | omp | pi | oh-my-pi)" >&2+ echo "unsupported agent: $AGENT (expected claude-code | codex | cursor | gemini-cli | kimi-code | antigravity-cli | grok | opencode | openclaw | omp | pi | oh-my-pi)" >&2exit 64 ;;esac@@ -91,6 +91,12 @@ SCRIPTS=("session-end")+# kimi-code mirrors the claude-code bundle, which also captures the+# subagent lifecycle events.+if [[ "$AGENT" == "kimi-code" ]]; then+ SCRIPTS+=("subagent-start" "subagent-stop")+fi+DEST="$TO/$AGENT"mkdir -p "$DEST"