Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge branch 'main' of https://github.com/akitaonrails/ai-memory into feat/kimi-code-support
Lucas Oliveira5316aaaaeed5
diff --cc CHANGELOG.mdindex ea432a7a,6b178f30..b51ba11a--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -8,18 -8,17 +8,29 @@@ and this project adheres to [Semantic V## [Unreleased]### Added+ - Tool lifecycle capture now records safe metadata summaries for the closed+ Claude Code, OpenCode, Pi, and Antigravity schemas: canonical family,+ validated agent-provided call ID where available, and a PostToolUse outcome.+ PreToolUse never stores tool inputs, commands, paths, or arbitrary tool+ names; PostToolUse keeps its bounded response/error excerpt. Stop and+ assistant-message capture remain disabled/deferred ([#190]).+ - Per-repository capture exclusions via `[capture] ignore_paths` in the nearest+ `.ai-memory.toml` ([#194]). Supported native hooks and generated+ OpenCode/OMP/Pi/OpenClaw integrations apply the policy before local spool or+ network delivery; `ai-memory hook --check-capture` safely reports a bounded+ local decision. This changes no MCP tools and needs no database migration.+- 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.- Grok Build CLI is now a first-class MCP client as well as a hook agent:`install-mcp --client grok` renders and `--apply` merges a native HTTPentry into `$GROK_HOME/config.toml` (default `~/.grok/config.toml`)diff --cc crates/ai-memory-cli/src/commands/install_hooks.rsindex 8cbe2004,50edfb70..644a7386--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@@ -26,10 -26,11 +26,11 @@@ use crate::commands::openclaw_pluginuse 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, kimi_code_hook_commands, ts_string_literal,- hook_script_for_current_platform, local_hook_policy_v1_supported, ts_capture_policy_v1,- ts_string_literal,++ hook_script_for_current_platform, kimi_code_hook_commands, local_hook_policy_v1_supported,++ ts_capture_policy_v1, ts_string_literal,};use crate::config::{Config, DEFAULT_SERVER_URL};diff --cc crates/ai-memory-cli/src/commands/render_shared.rsindex 2029273d,440baca1..f2a55c38--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@@ -587,55 -600,6 +621,56 @@@ fn build_hook_payloadbuild_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).++/// no `timeout` = 30s). Commands come from the shared `hook_command`++/// helper for the current platform: native `ai-memory hook --event …`++/// invocations by default, or the staged script bundle (`.sh` on++/// POSIX, `.ps1` on Windows) on the compatibility platforms.+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,diff --cc crates/ai-memory-store/migrations/V30__sessions_kimi_code_agent_kind.sqlindex 7b14f6d0,00000000..7b14f6d0mode 100644,000000..100644--- a/crates/ai-memory-store/migrations/V30__sessions_kimi_code_agent_kind.sql+++ b/crates/ai-memory-store/migrations/V30__sessions_kimi_code_agent_kind.sqldiff --cc crates/ai-memory-store/src/migrations.rsindex 5d5677a0,21703868..be471589--- a/crates/ai-memory-store/src/migrations.rs+++ b/crates/ai-memory-store/src/migrations.rs@@@ -96,7 -96,7 +96,7 @@@ mod testsfn schema_ahead_message_is_actionable() {let rendered = StoreError::DataSchemaAhead {applied: "V99 (future_feature)".to_string(),- supported: 28,- supported: 29,++ supported: 30,}.to_string();@@@ -109,6 -109,36 +109,36 @@@"{rendered}");assert!(rendered.contains("V99 (future_feature)"), "{rendered}");- assert!(rendered.contains("through V28"), "{rendered}");- assert!(rendered.contains("through V29"), "{rendered}");++ assert!(rendered.contains("through V30"), "{rendered}");+ }++ #[test]+ fn v28_to_v29_preserves_existing_rows() {+ let mut conn = Connection::open_in_memory().unwrap();+ run_to(&mut conn, 28).unwrap();+ let workspace_id = [7_u8; 16];+ conn.execute(+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, 'existing', 1)",+ params![workspace_id.as_slice()],+ )+ .unwrap();++ run(&mut conn).unwrap();+ let name: String = conn+ .query_row(+ "SELECT name FROM workspaces WHERE id = ?1",+ params![workspace_id.as_slice()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(name, "existing");+ let state_table: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'maintenance_scheduler_state'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(state_table, 1);}}diff --cc docs/install.mdindex 341a9f12,1dd39993..50c2d150--- a/docs/install.md+++ b/docs/install.md@@@ -489,19 -499,17 +499,17 @@@ Each agent CLI needs two thingsbecomes 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, 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:- > it uses Claude exec form (`command` = real `ai-memory.exe`, `args` = argv- > tokens for `hook --event ...`) by default. Set- > `AI_MEMORY_HOOK_PLATFORM=windows-bash` before `install-hooks` to opt back into- > Git Bash `bash -c` commands for the `.sh` scripts, including for older Claude- > Code builds that do not support exec form.+ > **Hook install pattern.** Local supported profiles default to host-native+ > commands. Claude Code may use its supported Windows exec form (`command` =+ > real `ai-memory.exe`, `args` = argv tokens for `hook --event ...`); other+ > agents use native single command strings according to their hook schema.+ > PowerShell/Git Bash script bundles are compatibility fallbacks and do not+ > enforce capture-policy v1. Remote-only/Docker script installs still use the+ > two-step path: (1) `docker cp` bundled scripts to your home dir, (2)+ > `docker run --rm install-hooks` renders the config snippet.> OpenClaw, OpenCode, and OMP are different: they use generated> TypeScript plugin/extension files, so no shell-script extraction is> needed for those clients.@@@ -568,34 -576,6 +576,37 @@@ from `DEVIN_PROJECT_DIR` or the hook promits it, and mints/reuses a per-host session id from hook state when necessary,so those events are still captured. A payload-provided value always wins.+### 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 —++provider/model settings the same file holds. Entries cover 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.++`Stop`, `SubagentStart`, `SubagentStop`, and `PreCompact` — and default to++native `ai-memory hook --event … --agent kimi-code` commands on local installs++(local spool plus batched delivery, capture-policy v1 enforced); the staged++script bundle under `~/.local/share/ai-memory/hooks/kimi-code/` is the++compatibility fallback (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 --cc docs/mcp-install.mdindex 177cd708,9b25c55a..1954a802--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@@ -19,13 -19,14 +19,14 @@@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, and- OMP have automatic capture integrations (shell/PowerShell hooks for- Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Grok Build CLI / Kimi Code, TypeScript plugin/extension- files for OpenClaw / OpenCode / OMP) and are covered in the- [main README](../README.md#quick-start). On native Windows, Claude Code uses- Git Bash `.sh` hooks rather than the PowerShell default used by other- script-hook agents. Grok and Zero capture lifecycle events, but both ignore+ OMP have automatic capture integrations (host-native commands for supported+ local profiles, plus generated TypeScript plugin/extension files for OpenClaw /+ OpenCode / OMP) and are covered in the [main README](../README.md#quick-start).+ Claude Code may use its supported Windows exec form; other agents use native+ single command strings according to their hook schema. PowerShell/Git Bash+ script bundles are compatibility fallbacks and do not enforce capture-policy+ v1. Grok and Zero capture lifecycle events, but both ignoreSessionStart stdout, so ai-memory does not auto-inject handoffs for them.SessionStart handoff injection works only for clients that consume startup-hookstdout (or their equivalent context-injection result); Grok and Zero must call@@@ -566,63 -573,6 +573,66 @@@ fill both instance 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.++`SubagentStop`, and `PreCompact` — with a Kimi Code-specific script bundle /++native `ai-memory hook --event … --agent kimi-code` commands (native is the++default for local installs; the staged scripts under++`~/.local/share/ai-memory/hooks/kimi-code/` are the compatibility fallback).++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.++ entries use a distinct command per event, so all 9 fire independently.+## OpenClaw**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported via a nativediff --cc docs/windows.mdindex 72c66151,788b8a59..5d21963f--- a/docs/windows.md+++ b/docs/windows.md@@@ -105,15 -103,14 +104,14 @@@ the CLI to render hook commands for th- Config files are written through the mounted Windows home directory.- Hook scripts are staged under `$HOME\.local\share\ai-memory\hooks\`.- - Claude Code hook commands call the `ai-memory` binary directly with Claude's- 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 and Kimi Code,- use their generated script-command hook entries for the selected platform.+ - Local supported profiles default to host-native commands. Claude Code may use+ its exec form (`command` executable + `args` argv array), while other agents+ use native single command strings matching their hook schema. PowerShell/Git+ Bash script bundles are compatibility fallbacks and do not enforce+ capture-policy v1.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`