Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(install-hooks): add Grok Build CLI as a supported agent
Djalma Júnior27e8d844cdc9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 29a826ab..ed2fb1a5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).## [Unreleased]+### Added+- `install-hooks --agent grok` (plus `setup-agent` / `uninstall` coverage) for+ the xAI **Grok Build CLI**. Grok's `~/.grok/hooks/ai-memory.json` shares Claude+ Code's JSON shape and seven-event vocabulary, so it reuses the claude-code hook+ scripts and emits the native `ai-memory hook --event … --agent grok` command.+ ai-memory entries merge into a dedicated `ai-memory.json`, leaving any+ third-party `~/.grok/hooks/*.json` untouched. NOTE: Grok ignores hook stdout on+ `SessionStart`, so capture works but handoff injection does not — recover a+ prior session's handoff via the MCP `memory_handoff_accept` tool. Adds+ `AgentKind::Grok` (`grok` wire tag).## [1.0.3] - 2026-06-13### Addeddiff --git a/README.md b/README.mdindex c9695a99..220fab9a 100644--- a/README.md+++ b/README.md@@ -31,6 +31,7 @@| Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. || OpenClaw | Supported | MCP config + native plugin lifecycle hooks. || 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`, native `--agent grok`, reuses claude-code scripts). Capture works; no handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. || VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). || LLM/auth providers | Supported | Anthropic, OpenAI, OpenAI OAuth/Codex, GitHub Copilot, Gemini, OpenAI-compatible endpoints, and generic OIDC device auth for native hooks. || Embedding providers | Supported | OpenAI, Voyage, and Google Gemini. |@@ -79,7 +80,7 @@ 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, OpenCode, Cursor, Claude Desktop (via `mcp-remote`),- Gemini CLI, Antigravity CLI, OpenClaw, Oh My Pi / OMP+ Gemini CLI, Antigravity CLI, Grok Build CLI, OpenClaw, Oh My Pi / OMP(`pi` / `omp` aliases), 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)diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 59ea15d3..bfa1e22c 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -714,6 +714,13 @@ pub enum AgentChoice {/// `~/.gemini/config/hooks.json`.#[value(alias = "antigravity", alias = "agy")]AntigravityCli,+ /// xAI Grok Build CLI — JSON-config hooks in+ /// `~/.grok/hooks/ai-memory.json`. Native `ai-memory hook --event`+ /// integration like Claude Code (reuses the claude-code hook+ /// scripts). NOTE: Grok ignores hook stdout on `SessionStart`, so+ /// capture works but handoff injection does not — recover the prior+ /// session's handoff via the MCP `memory_handoff_accept` tool.+ Grok,}/// MCP client to render configuration for. Includes both the@@ -1201,6 +1208,23 @@ mod tests {}}+ #[test]+ fn grok_hook_agent_parses() {+ let hook_cli = Cli::try_parse_from([+ "ai-memory",+ "install-hooks",+ "--agent",+ "grok",+ "--server-url",+ "http://example.test:49374",+ ])+ .unwrap_or_else(|e| panic!("failed to parse install-hooks --agent grok: {e}"));+ let Command::InstallHooks(hook_args) = hook_cli.command else {+ panic!("expected install-hooks command for grok");+ };+ assert!(matches!(hook_args.agent, AgentChoice::Grok));+ }+#[test]fn vscode_copilot_aliases_parse_to_same_variant() {for alias in ["vscode-copilot", "copilot", "github-copilot"] {diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 0e44e785..9c23917a 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -25,8 +25,9 @@ use crate::commands::install_mcp;use crate::commands::openclaw_plugin;use crate::commands::render_shared::{CURSOR_PROFILE, GEMINI_PROFILE, build_antigravity_payload_with_data_dir,- build_claude_code_payload_with_data_dir, build_profile_payload_for_agent,- hook_script_for_claude_code, hook_script_for_current_platform, ts_string_literal,+ build_claude_code_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,};use crate::config::{Config, DEFAULT_SERVER_URL};@@ -71,6 +72,15 @@ pub(crate) fn antigravity_hooks_path() -> anyhow::Result<std::path::PathBuf> {.join("hooks.json"))}+/// `~/.grok/hooks/ai-memory.json` — Grok Build CLI lifecycle hooks.+pub(crate) fn grok_hooks_path() -> anyhow::Result<std::path::PathBuf> {+ Ok(dirs::home_dir()+ .context("could not locate $HOME for ~/.grok/hooks/ai-memory.json")?+ .join(".grok")+ .join("hooks")+ .join("ai-memory.json"))+}+/// `~/.config/opencode/plugins/ai-memory.ts` — OpenCode's plugin file.pub(crate) fn opencode_plugin_path() -> anyhow::Result<std::path::PathBuf> {Ok(dirs::home_dir()@@ -156,6 +166,10 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {&args,)}+ AgentChoice::Grok => {+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;+ apply_to_grok_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)+ }AgentChoice::Openclaw => openclaw_plugin::apply(&server_url, auth, &args),};}@@ -182,6 +196,10 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;render_agent("antigravity-cli", &hooks_dir, &server_url, auth)}+ AgentChoice::Grok => {+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;+ render_grok(&hooks_dir, &server_url, auth, &config.data_dir)+ }AgentChoice::Openclaw => {openclaw_plugin::render(&server_url, auth);Ok(())@@ -302,6 +320,9 @@ fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {AgentChoice::Omp => Some(McpClient::Pi),AgentChoice::Openclaw => Some(McpClient::Openclaw),AgentChoice::AntigravityCli => Some(McpClient::AntigravityCli),+ // Grok manages its own MCP config under ~/.grok/; we don't+ // auto-infer a hook server URL from it.+ AgentChoice::Grok => None,}}@@ -488,6 +509,60 @@ fn apply_to_claude_code_settings(Ok(())}+/// Mutate `~/.grok/hooks/ai-memory.json` so Grok Build CLI fires the+/// ai-memory lifecycle hooks. Grok's hook config is structurally+/// identical to Claude Code's (`{"hooks":{"SessionStart":[{"hooks":+/// [{"type":"command","command":"..."}]}]}}`) and uses the same seven+/// CamelCase event names, so we reuse Claude Code's staged scripts and+/// only swap the emitted `--agent grok` tag. We merge into a dedicated+/// `ai-memory.json` (Grok discovers every `~/.grok/hooks/*.json`), so a+/// pre-existing third-party hook file is left untouched.+fn apply_to_grok_settings(+ 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 => grok_hooks_path()?,+ };+ let staged = stage_hook_scripts(hooks_dir, "grok")?;+ let command_dir = staged_command_dir(&staged, "grok");+ let payload =+ build_grok_payload_with_data_dir(&command_dir, server_url, auth_token, Some(data_dir));+ let our_hooks = payload+ .get("hooks")+ .and_then(|v| v.as_object())+ .context("internal: build_grok_payload didn't return a hooks object")?+ .clone();+ let outcome = apply_atomic(&path, |existing| {+ mutate_json(existing, |root| {+ let hooks = root+ .entry("hooks")+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))+ .as_object_mut()+ .context("`hooks` is present in ai-memory.json but not an object")?;+ for (event, value) in &our_hooks {+ overlay_event_hooks(hooks, event, value);+ }+ Ok(())+ })+ })?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ Ok(())+}+/// Mutate `~/.codex/hooks.json` (creating it if absent) so Codex's/// lifecycle hook runner fires the ai-memory scripts on every/// session/prompt/tool event.@@ -1643,6 +1718,9 @@ fn resolve_hooks_dir(explicit: Option<&Path>, agent: AgentChoice) -> Result<PathAgentChoice::Cursor => "cursor",AgentChoice::GeminiCli => "gemini-cli",AgentChoice::AntigravityCli => "antigravity-cli",+ // Grok reuses Claude Code's hook scripts (identical JSON shape ++ // event vocabulary); only the emitted `--agent grok` tag differs.+ AgentChoice::Grok => "claude-code",AgentChoice::OpenCode | AgentChoice::Omp | AgentChoice::Openclaw => {anyhow::bail!("{agent:?} uses a generated integration, not a hook script directory")}@@ -1738,6 +1816,46 @@ fn render_claude_code(Ok(())}+fn render_grok(+ hooks_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+) -> Result<()> {+ // Soft check (same rationale as render_claude_code): warn, don't bail,+ // so the docker host-path flow still works.+ for (_, script) in super::render_shared::CLAUDE_CODE_EVENTS {+ let script = hook_script_for_claude_code(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 payload =+ build_grok_payload_with_data_dir(hooks_dir, server_url, auth_token, Some(data_dir));+ let serialized =+ serde_json::to_string_pretty(&payload).context("serializing grok hook config")?;+ println!("# Grok Build CLI hook config — write to ~/.grok/hooks/ai-memory.json");+ 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 ~/.grok/hooks/ai-memory.json as sensitive (chmod 600).");+ }+ println!("# NOTE: Grok ignores hook stdout on SessionStart — capture works,");+ println!("# but handoff injection does not. Recover a prior session's");+ println!("# handoff via the MCP `memory_handoff_accept` tool.");+ println!();+ println!("{serialized}");+ Ok(())+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 7adf3019..2e1a2a40 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -131,6 +131,26 @@ pub(crate) fn build_claude_code_payload_with_data_dir()}+/// Grok Build CLI hook payload. Grok's `~/.grok/hooks/*.json` shares+/// Claude Code's JSON shape and seven-event vocabulary+/// (`CLAUDE_CODE_EVENTS`, `HookShape::Nested`), so we reuse both and+/// only swap the `--agent grok` tag in the emitted native command.+pub(crate) fn build_grok_payload_with_data_dir(+ emit_root: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: Option<&Path>,+) -> serde_json::Value {+ build_hook_payload_for_platform(+ &CLAUDE_CODE_EVENTS,+ emit_root,+ server_url,+ auth_token,+ HookShape::Nested,+ HookCommandContext::new(HookCommandPlatform::for_bash_runner(), "grok", data_dir),+ )+}+/// Different agents nest hook entries differently. Two shapes/// cover everyone we support:#[derive(Clone, Copy, Debug, PartialEq, Eq)]diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex 1206e156..843ee96a 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -70,6 +70,8 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {AgentChoice::Cursor => "cursor",AgentChoice::GeminiCli => "gemini-cli",AgentChoice::AntigravityCli => "antigravity-cli",+ // Grok reuses Claude Code's hook scripts (same shape + events).+ AgentChoice::Grok => "claude-code",AgentChoice::OpenCode => unreachable!("opencode handled above"),AgentChoice::Omp => unreachable!("omp handled above"),AgentChoice::Openclaw => unreachable!("openclaw handled above"),@@ -126,7 +128,7 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {.join(agent_sub);match args.agent {- AgentChoice::ClaudeCode => emit_claude_code(&emit_root, &args)?,+ AgentChoice::ClaudeCode | AgentChoice::Grok => emit_claude_code(&emit_root, &args)?,AgentChoice::Codex| AgentChoice::Cursor| AgentChoice::GeminiClidiff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex 6de89cc2..6dbf78d0 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -117,6 +117,9 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {install_hooks::codex_hooks_path()?,install_hooks::cursor_hooks_path()?,install_hooks::gemini_settings_path()?,+ // Grok's ~/.grok/hooks/ai-memory.json shares Claude Code's+ // JSON shape, so the same strip pass removes our entries.+ install_hooks::grok_hooks_path()?,];for path in hook_files {if !path.exists() {diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 14dbc99f..8388d480 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -191,6 +191,8 @@ pub enum AgentKind {AntigravityCli,/// Oh My Pi (`omp`) / Pi-compatible coding agent.Omp,+ /// xAI Grok Build CLI (`grok`).+ Grok,/// Anything else (manual capture, future agents).Other,}@@ -209,6 +211,7 @@ impl AgentKind {Self::OpenClaw => "openclaw",Self::AntigravityCli => "antigravity-cli",Self::Omp => "omp",+ Self::Grok => "grok",Self::Other => "other",}}@@ -228,6 +231,7 @@ impl AgentKind {"openclaw" | "open-claw" => Self::OpenClaw,"antigravity-cli" | "antigravity" | "agy" => Self::AntigravityCli,"omp" | "pi" | "oh-my-pi" => Self::Omp,+ "grok" => Self::Grok,_ => Self::Other,}}@@ -258,6 +262,20 @@ mod tests {assert!(PagePath::new("a/../b").is_err());}+ #[test]+ fn agent_kind_grok_round_trips() {+ assert_eq!(AgentKind::Grok.as_str(), "grok");+ assert_eq!(AgentKind::from_wire("grok"), AgentKind::Grok);+ // serde uses rename_all = "kebab-case" → "grok".+ assert_eq!(serde_json::to_string(&AgentKind::Grok).unwrap(), "\"grok\"");+ assert_eq!(+ serde_json::from_str::<AgentKind>("\"grok\"").unwrap(),+ AgentKind::Grok+ );+ // Unknown tags still degrade to Other.+ assert_eq!(AgentKind::from_wire("grok-2"), AgentKind::Other);+ }+#[test]fn page_path_rejects_backslashes_and_windows_prefixes() {assert!(PagePath::new(r"notes\secret.md").is_err());