Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(agents): first-class Grok MCP install and skill roots
Fernando95ee1c71e989
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a12da340..615b161c 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+- 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 HTTP+ entry into `~/.grok/config.toml` (`[mcp_servers.ai-memory]` with+ `url` / `enabled` / `[mcp_servers.ai-memory.headers]` — not Codex's+ `http_headers` key). `install-hooks --agent grok` reuses that entry to+ infer server URL and bearer token; `uninstall` strips the MCP table;+ `setup-agent --agent grok` prints the companion `install-mcp` tip.+ Managed routing skills can target `.grok/skills` / `~/.grok/skills` via+ `install-skills --agent grok` and `memory_install_self_routing`+ `target_hints`. Lifecycle capture was already present; handoff injection+ remains unavailable because Grok ignores SessionStart stdout — recover+ via MCP `memory_handoff_accept`.+### 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..0fabb0be 100644--- a/README.md+++ b/README.md@@ -33,7 +33,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`, Grok-specific hook bundle, native `--agent grok`). Capture works; no handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. |+| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. Skills root: `.grok/skills` / `~/.grok/skills`. || 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`. || 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. |@@ -270,11 +270,14 @@ 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`,-# `--client gemini-cli`, etc.+# `--agent grok`, `--agent omp`, `--agent oh-my-pi`, `--client cursor`,+# `--client gemini-cli`, `--client grok`, etc.# for additional agents; full list in docs/install.md.ai-memory install-mcp --client claude-code --applyai-memory install-hooks --agent claude-code --apply+# Grok Build CLI example:+# ai-memory install-mcp --client grok --apply+# ai-memory install-hooks --agent grok --apply```On Linux/macOS, that's it. Start a Claude Code session as usual - everydiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex c803e9ea..7d480dd3 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -72,7 +72,8 @@ pub enum Command {HookDrain(HookDrainArgs),/// Print MCP server registration snippets for any supported client/// (Claude Code, Codex, OpenCode, Cursor, Claude Desktop, Gemini- /// CLI, OpenClaw, OMP, Pi). See docs/mcp-install.md for the full guide.+ /// CLI, OpenClaw, OMP, Pi, Grok, Zero, Devin, Antigravity CLI, VS Code+ /// Copilot). See docs/mcp-install.md for the full guide.InstallMcp(InstallMcpArgs),/// Stage + commit the wiki tree under git.Commit(CommitArgs),@@ -483,6 +484,8 @@ pub enum InstallSkillsAgent {Agents,/// Devin's `.devin/skills` directory.Devin,+ /// Grok Build CLI's `.grok/skills` directory.+ Grok,/// Install into both Claude Code and `.agents` skill directories.Both,}@@ -933,6 +936,12 @@ pub enum McpClient {Zero,/// Devin CLI — `~/.devin/config.json`.Devin,+ /// xAI Grok Build CLI — `~/.grok/config.toml` under+ /// `[mcp_servers.<name>]` with native HTTP `url` + `headers`.+ /// Pair with `install-hooks --agent grok` for lifecycle capture.+ /// Grok ignores SessionStart stdout, so handoffs are recovered via+ /// MCP `memory_handoff_accept` rather than hook injection.+ Grok,/// 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),@@ -1755,6 +1764,23 @@ mod tests {assert!(matches!(hook_args.agent, AgentChoice::Grok));}+ #[test]+ fn grok_mcp_client_parses() {+ let mcp_cli = Cli::try_parse_from([+ "ai-memory",+ "install-mcp",+ "--client",+ "grok",+ "--server-url",+ "http://example.test:49374",+ ])+ .unwrap_or_else(|e| panic!("failed to parse install-mcp --client grok: {e}"));+ let Command::InstallMcp(mcp_args) = mcp_cli.command else {+ panic!("expected install-mcp command for grok");+ };+ assert!(matches!(mcp_args.client, McpClient::Grok));+ }+#[test]fn devin_hook_agent_parses() {let hook_cli = Cli::try_parse_from([diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 19706017..cf0dc135 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -368,7 +368,9 @@ fn infer_installed_mcp_config(agent: AgentChoice) -> Option<InferredMcpConfig> {McpClient::ClaudeCode => {infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url")}- McpClient::Codex => infer_codex_mcp_config(&content),+ // Codex uses `http_headers`; Grok uses `headers`. The shared TOML+ // inferencer accepts both.+ McpClient::Codex | McpClient::Grok => infer_toml_mcp_config(&content),McpClient::OpenCode => infer_json_mcp_config(&content, &["mcp", "ai-memory"], "url"),McpClient::Cursor => infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url"),McpClient::GeminiCli => {@@ -405,9 +407,11 @@ fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {AgentChoice::Openclaw => Some(McpClient::Openclaw),AgentChoice::AntigravityCli => Some(McpClient::AntigravityCli),AgentChoice::Zero => Some(McpClient::Zero),- // 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,+ AgentChoice::Grok => Some(McpClient::Grok),+ AgentChoice::Devin => Some(McpClient::Devin),+ // Pi bridges MCP through its generated extension, not a native+ // mcp.json the installer can scrape.+ AgentChoice::Pi => None,}}@@ -436,12 +440,14 @@ fn infer_json_mcp_config(})}-fn infer_codex_mcp_config(content: &str) -> Option<InferredMcpConfig> {+/// Infer hook server URL + bearer from a TOML `[mcp_servers.ai-memory]`+/// entry (Codex `http_headers` or Grok `headers`).+fn infer_toml_mcp_config(content: &str) -> Option<InferredMcpConfig> {let doc: toml_edit::DocumentMut = content.parse().ok()?;// `toml_edit::Item`'s `Index` impl panics on missing keys, so this// walks the table chain with `.get()` instead. A user with// `[mcp_servers.context7]` but no `[mcp_servers.ai-memory]` is a- // perfectly valid hooks-only Codex setup (issue #53) — return None+ // perfectly valid hooks-only Codex/Grok setup (issue #53) — return None// rather than abort the whole install with a stack trace.let server = doc.get("mcp_servers")?.get("ai-memory")?;@@ -3289,7 +3295,7 @@ mod tests {#[test]fn codex_mcp_inference_accepts_block_form_config() {- let inferred = infer_codex_mcp_config(+ let inferred = infer_toml_mcp_config(r#"[mcp_servers.ai-memory]url = "http://homelab:49374/mcp"@@ -3306,6 +3312,26 @@ Authorization = "Bearer secret-token"assert_eq!(inferred.auth_token.as_deref(), Some("secret-token"));}+ #[test]+ fn grok_mcp_inference_accepts_headers_key() {+ let inferred = infer_toml_mcp_config(+ r#"[mcp_servers.ai-memory]+url = "http://homelab:49374/mcp"+enabled = true++[mcp_servers.ai-memory.headers]+Authorization = "Bearer secret-token"+"#,+ )+ .unwrap();++ assert_eq!(+ inferred.hook_server_url.as_deref(),+ Some("http://homelab:49374")+ );+ assert_eq!(inferred.auth_token.as_deref(), Some("secret-token"));+ }+/// Regression for issue #53 — `install-hooks --agent codex` used to/// panic with "index not found" when `~/.codex/config.toml` had an/// `[mcp_servers]` table populated with *other* servers (context7,@@ -3314,7 +3340,7 @@ Authorization = "Bearer secret-token"/// server — must return None, not abort the whole install.#[test]fn codex_mcp_inference_returns_none_when_ai_memory_entry_missing() {- let inferred = infer_codex_mcp_config(+ let inferred = infer_toml_mcp_config(r#"[mcp_servers.context7]url = "http://localhost:9000/mcp"@@ -3334,7 +3360,7 @@ args = ["node-repl"]/// None rather than panic on the first index.#[test]fn codex_mcp_inference_returns_none_when_no_mcp_servers_table() {- let inferred = infer_codex_mcp_config(+ let inferred = infer_toml_mcp_config(r#"# fresh codex configmodel = "gpt-5""#,@@ -3345,7 +3371,7 @@ model = "gpt-5"/// And the empty-file edge case the parser still accepts.#[test]fn codex_mcp_inference_returns_none_for_empty_doc() {- assert!(infer_codex_mcp_config("").is_none());+ assert!(infer_toml_mcp_config("").is_none());}/// An ai-memory entry that exists but ships neither a `url` nor an@@ -3354,7 +3380,7 @@ model = "gpt-5"/// present but unhelpful" — both yield None, neither panics.#[test]fn codex_mcp_inference_returns_none_for_bare_ai_memory_entry() {- let inferred = infer_codex_mcp_config(+ let inferred = infer_toml_mcp_config(r#"[mcp_servers.ai-memory]# intentionally empty — no url, no headers."#,diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex da1cd119..173cc149 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -58,6 +58,7 @@ pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {let snippet = match args.client {McpClient::ClaudeCode => render_claude_code(&args)?,McpClient::Codex => render_codex(&args),+ McpClient::Grok => render_grok(&args),McpClient::OpenCode => render_opencode(&args)?,McpClient::Cursor => render_cursor(&args)?,McpClient::ClaudeDesktop => render_claude_desktop(&args)?,@@ -119,6 +120,10 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>// in `claude mcp list`.)McpClient::ClaudeCode => home()?.join(".claude.json"),McpClient::Codex => home()?.join(".codex").join("config.toml"),+ // Grok discovers MCP under ~/.grok/config.toml (user scope). Project+ // scope is `.grok/config.toml` under cwd/repo; pass --config-file for+ // that case rather than inventing a second default.+ McpClient::Grok => home()?.join(".grok").join("config.toml"),McpClient::OpenCode => home()?.join(".config").join("opencode")@@ -198,6 +203,9 @@ fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {McpClient::Codex => apply_atomic(&path, |existing| {mutate_toml(existing, |doc| codex_upsert_mcp_server(doc, args))})?,+ McpClient::Grok => apply_atomic(&path, |existing| {+ mutate_toml(existing, |doc| grok_upsert_mcp_server(doc, args))+ })?,_ => apply_atomic(&path, |existing| {mutate_json(existing, |root| upsert_json_mcp_entry(root, args))})?,@@ -229,7 +237,7 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {// shape OpenClaw uses.McpClient::Openclaw | McpClient::Zero => Some(JsonMcpLocation::NestedMcpServers),McpClient::VsCodeCopilot => Some(JsonMcpLocation::RootServers),- McpClient::Codex | McpClient::Pi => None,+ McpClient::Codex | McpClient::Grok | McpClient::Pi => None,}}@@ -238,7 +246,9 @@ fn build_json_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {McpClient::OpenCode => build_mcp_entry_opencode(args),McpClient::Openclaw => build_mcp_entry_openclaw(args),McpClient::Zero => build_mcp_entry_zero(args),- McpClient::Codex => bail!("internal: Codex MCP config is TOML, not JSON"),+ McpClient::Codex | McpClient::Grok => {+ bail!("internal: Codex/Grok MCP config is TOML, not JSON")+ }_ => build_mcp_entry(args),}}@@ -526,6 +536,56 @@ fn codex_upsert_mcp_server(Ok(())}+/// Insert / replace `[mcp_servers.<name>]` in a Grok `config.toml`.+///+/// Grok's schema (user-guide § MCP Servers) uses:+/// - `url` for native HTTP/SSE+/// - optional `enabled = true`+/// - `[mcp_servers.<name>.headers]` for static headers (NOT Codex's+/// `http_headers` key — wrong key is silently ignored by Grok)+///+/// Sibling servers are preserved; storage is canonicalised to block form+/// even when the file currently holds an inline `mcp_servers` table.+fn grok_upsert_mcp_server(+ doc: &mut toml_edit::DocumentMut,+ args: &InstallMcpArgs,+) -> anyhow::Result<()> {+ use toml_edit::{Item, Table, Value, value};++ let preserved: Vec<(String, Item)> = match doc.get("mcp_servers") {+ Some(Item::Table(t)) => t+ .iter()+ .filter(|(k, _)| *k != args.name.as_str())+ .map(|(k, v)| (k.to_string(), v.clone()))+ .collect(),+ Some(Item::Value(Value::InlineTable(it))) => it+ .iter()+ .filter(|(k, _)| *k != args.name.as_str())+ .map(|(k, v)| (k.to_string(), Item::Value(v.clone())))+ .collect(),+ _ => Vec::new(),+ };++ let mut server = Table::new();+ server["url"] = value(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL));+ server["enabled"] = value(true);+ if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {+ let mut headers = Table::new();+ headers["Authorization"] = value(b);+ server["headers"] = Item::Table(headers);+ }++ let mut parent = Table::new();+ parent.set_implicit(true);+ for (k, v) in preserved {+ parent.insert(&k, v);+ }+ parent.insert(&args.name, Item::Table(server));++ doc.insert("mcp_servers", Item::Table(parent));+ Ok(())+}+fn render_claude_code(args: &InstallMcpArgs) -> Result<String> {let bearer = bearer_header_value(args.auth_token.as_deref());let cli_line = if let Some(b) = &bearer {@@ -591,6 +651,40 @@ fn render_codex(args: &InstallMcpArgs) -> String {out}+fn render_grok(args: &InstallMcpArgs) -> String {+ // Grok Build CLI uses TOML under ~/.grok/config.toml. Schema differs+ // from Codex: static auth lives under `.headers` (not `http_headers`),+ // and `enabled = true` is the documented toggle.+ let mut out = format!(+ "# Grok Build CLI — append to ~/.grok/config.toml\n\+ #\n\+ # Native HTTP transport. Pair with:\n\+ # ai-memory install-hooks --agent grok --apply\n\+ # for lifecycle capture. Grok ignores SessionStart stdout, so\n\+ # handoffs are recovered via MCP memory_handoff_accept.\n\+ #\n\+ # CLI alternative:\n\+ # grok mcp add --transport http {name} {url}\n\+ #\n\+ [mcp_servers.{name}]\n\+ url = \"{url}\"\n\+ enabled = true\n",+ name = args.name,+ url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL),+ );+ if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {+ out.push_str(&format!(+ "\n[mcp_servers.{name}.headers]\n\+ Authorization = \"{b}\"\n\+ # Prefer env expansion to avoid embedding the token:\n\+ # Authorization = \"Bearer ${{AI_MEMORY_AUTH_TOKEN}}\"\n",+ name = args.name,+ b = b,+ ));+ }+ out+}+fn render_opencode(args: &InstallMcpArgs) -> Result<String> {Ok(format!("# OpenCode — add to ~/.config/opencode/opencode.json under \"mcp\":\n\@@ -795,6 +889,7 @@ mod tests {match args.client {McpClient::ClaudeCode => render_claude_code(&args).unwrap(),McpClient::Codex => render_codex(&args),+ McpClient::Grok => render_grok(&args),McpClient::OpenCode => render_opencode(&args).unwrap(),McpClient::Cursor => render_cursor(&args).unwrap(),McpClient::ClaudeDesktop => render_claude_desktop(&args).unwrap(),@@ -816,6 +911,7 @@ mod tests {for client in [McpClient::ClaudeCode,McpClient::Codex,+ McpClient::Grok,McpClient::OpenCode,McpClient::Cursor,McpClient::ClaudeDesktop,@@ -850,6 +946,7 @@ mod tests {for client in [McpClient::ClaudeCode,McpClient::Codex,+ McpClient::Grok,McpClient::OpenCode,McpClient::Cursor,McpClient::ClaudeDesktop,@@ -874,6 +971,7 @@ mod tests {match args.client {McpClient::ClaudeCode => render_claude_code(&args).unwrap(),McpClient::Codex => render_codex(&args),+ McpClient::Grok => render_grok(&args),McpClient::OpenCode => render_opencode(&args).unwrap(),McpClient::Cursor => render_cursor(&args).unwrap(),McpClient::ClaudeDesktop => render_claude_desktop(&args).unwrap(),@@ -993,6 +1091,14 @@ mod tests {assert!(render_for_test(McpClient::ClaudeDesktop).contains("mcp-remote"));assert!(render_for_test(McpClient::Openclaw).contains("\"streamable-http\""));assert!(render_for_test(McpClient::Codex).contains("[mcp_servers.ai-memory]"));+ let grok = render_for_test(McpClient::Grok);+ assert!(grok.contains("[mcp_servers.ai-memory]"));+ assert!(grok.contains("enabled = true"));+ assert!(grok.contains("~/.grok/config.toml"));+ // Grok uses `headers`, never Codex's `http_headers`.+ let grok_token = render_with_token(McpClient::Grok);+ assert!(grok_token.contains("[mcp_servers.ai-memory.headers]"));+ assert!(!grok_token.contains("http_headers"));assert!(render_for_test(McpClient::Omp).contains("~/.omp/agent/mcp.json"));let pi = render_pi(&args_for(McpClient::Pi)).unwrap();assert!(pi.contains("Pi has no native mcp.json"));@@ -1148,6 +1254,73 @@ mod tests {assert!(out.contains("[mcp_servers.ai-memory]"));}+ #[test]+ fn grok_apply_writes_block_form_with_headers_not_http_headers() {+ let args = args_with_token(McpClient::Grok);+ let mut doc: toml_edit::DocumentMut = "".parse().unwrap();+ grok_upsert_mcp_server(&mut doc, &args).unwrap();+ let out = doc.to_string();+ assert!(+ out.contains("[mcp_servers.ai-memory]"),+ "expected block-form table header, got:\n{out}"+ );+ assert!(+ out.contains("enabled = true"),+ "expected enabled = true, got:\n{out}"+ );+ assert!(+ out.contains("[mcp_servers.ai-memory.headers]"),+ "expected `[mcp_servers.X.headers]` sub-table, got:\n{out}"+ );+ assert!(+ out.contains("Authorization = \"Bearer test-token-deadbeef\""),+ "expected Authorization header, got:\n{out}"+ );+ assert!(+ !out.contains("http_headers"),+ "Codex's http_headers key must not be emitted for Grok; got:\n{out}"+ );+ assert!(+ !out.contains("mcp_servers = {"),+ "found inline-table form (regression):\n{out}"+ );+ }++ #[test]+ fn grok_apply_preserves_sibling_mcp_servers_and_is_idempotent() {+ let args = args_with_token(McpClient::Grok);+ let original = "[mcp_servers.other-server]\n\+ url = \"http://other\"\n\+ enabled = true\n";+ let mut doc: toml_edit::DocumentMut = original.parse().unwrap();+ grok_upsert_mcp_server(&mut doc, &args).unwrap();+ let first = doc.to_string();+ assert!(first.contains("[mcp_servers.other-server]"));+ assert!(first.contains("http://other"));+ assert!(first.contains("[mcp_servers.ai-memory]"));+ assert!(first.contains("[mcp_servers.ai-memory.headers]"));++ let mut doc2: toml_edit::DocumentMut = first.parse().unwrap();+ grok_upsert_mcp_server(&mut doc2, &args).unwrap();+ assert_eq!(first, doc2.to_string());+ }++ #[test]+ fn grok_mcp_client_parses() {+ let cli = crate::cli::Cli::parse_from([+ "ai-memory",+ "install-mcp",+ "--client",+ "grok",+ "--server-url",+ "http://example.test:49374",+ ]);+ let crate::cli::Command::InstallMcp(args) = cli.command else {+ panic!("expected install-mcp");+ };+ assert!(matches!(args.client, McpClient::Grok));+ }+#[test]fn devin_mcp_client_parses() {let cli = crate::cli::Cli::parse_from([diff --git a/crates/ai-memory-cli/src/commands/install_skills.rs b/crates/ai-memory-cli/src/commands/install_skills.rsindex 8083f416..bf6d3e42 100644--- a/crates/ai-memory-cli/src/commands/install_skills.rs+++ b/crates/ai-memory-cli/src/commands/install_skills.rs@@ -4,8 +4,8 @@ use std::fs;use std::path::{Path, PathBuf};use ai_memory_core::routing_skills::{- AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, DEVIN_SKILL_DIR, MANAGED_MARKER, MANAGED_SKILLS,- ManagedSkill, SKILLS_DIR,+ AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, DEVIN_SKILL_DIR, GROK_SKILL_DIR, MANAGED_MARKER,+ MANAGED_SKILLS, ManagedSkill, SKILLS_DIR,};use anyhow::{Context, Result, bail};@@ -143,6 +143,16 @@ fn resolve_target_roots_for_platform(platform,)?]}+ InstallSkillsAgent::Grok => {+ vec![agent_root(+ args.scope,+ SkillRootKind::Grok,+ cwd,+ home,+ appdata,+ platform,+ )?]+ }InstallSkillsAgent::Both => vec![agent_root(args.scope,@@ -187,6 +197,7 @@ enum SkillRootKind {Claude,Agents,Devin,+ Grok,}fn agent_root(@@ -216,6 +227,7 @@ fn agent_root(SkillRootKind::Claude => CLAUDE_SKILL_DIR,SkillRootKind::Agents => AGENTS_SKILL_DIR,SkillRootKind::Devin => DEVIN_SKILL_DIR,+ SkillRootKind::Grok => GROK_SKILL_DIR,};Ok(base.join(agent_dir).join(SKILLS_DIR))}@@ -353,6 +365,14 @@ mod tests {.unwrap();assert_eq!(root_names(&project_devin), ["/repo/.devin/skills"]);+ let project_grok = resolve_target_roots(+ &args(InstallSkillsScope::Project, InstallSkillsAgent::Grok),+ cwd,+ Some(home),+ )+ .unwrap();+ assert_eq!(root_names(&project_grok), ["/repo/.grok/skills"]);+let project_both = resolve_target_roots(&args(InstallSkillsScope::Project, InstallSkillsAgent::Both),cwd,@@ -382,6 +402,14 @@ mod tests {).unwrap();assert_eq!(root_names(&global_devin), ["/home/alice/.devin/skills"]);++ let global_grok = resolve_target_roots(+ &args(InstallSkillsScope::Global, InstallSkillsAgent::Grok),+ cwd,+ Some(home),+ )+ .unwrap();+ assert_eq!(root_names(&global_grok), ["/home/alice/.grok/skills"]);}#[test]diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex e64b949b..2b136d36 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -272,6 +272,8 @@ fn emit_grok(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {println!("# NOTE: Grok ignores SessionStart stdout, so this config captures");println!("# lifecycle events but does not inject handoffs automatically.");println!("# Recover handoffs via the MCP memory_handoff_accept tool.");+ println!("# Tip: also run `ai-memory install-mcp --client grok --auth-token <…>`");+ println!("# to register the MCP endpoint in ~/.grok/config.toml.");println!();println!("{serialized}");Ok(())diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex 760a963f..58b273e1 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -15,7 +15,8 @@ use crate::commands::path_util::home_dir;use crate::commands::{data_purge, install_hooks, install_mcp, openclaw_plugin};use crate::config::Config;use ai_memory_core::routing_skills::{- AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, DEVIN_SKILL_DIR, MANAGED_MARKER, MANAGED_SKILLS, SKILLS_DIR,+ AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, DEVIN_SKILL_DIR, GROK_SKILL_DIR, MANAGED_MARKER,+ MANAGED_SKILLS, SKILLS_DIR,};use ai_memory_core::{MARKER_END, MARKER_START, find_marker_line};use anyhow::{Context, Result};@@ -248,6 +249,7 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {for client in [ClaudeCode,Codex,+ Grok,OpenCode,Cursor,ClaudeDesktop,@@ -267,12 +269,12 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {}let content = std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;- let (_new, removed) = if matches!(client, Codex) {+ let (_new, removed) = if matches!(client, Codex | Grok) {strip_mcp_toml(&content, name, url)?} else {strip_mcp_json(&content, client, name, url)?};- let op = if matches!(client, Codex) {+ let op = if matches!(client, Codex | Grok) {RewriteOp::McpToml} else {RewriteOp::McpJson(client)@@ -323,14 +325,16 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {}fn skill_roots(cwd: &Path, home: Option<&Path>, appdata: Option<&Path>) -> Vec<PathBuf> {- let mut roots = Vec::with_capacity(7);+ let mut roots = Vec::with_capacity(9);push_unique_skill_root(&mut roots, cwd.join(CLAUDE_SKILL_DIR).join(SKILLS_DIR));push_unique_skill_root(&mut roots, cwd.join(AGENTS_SKILL_DIR).join(SKILLS_DIR));push_unique_skill_root(&mut roots, cwd.join(DEVIN_SKILL_DIR).join(SKILLS_DIR));+ push_unique_skill_root(&mut roots, cwd.join(GROK_SKILL_DIR).join(SKILLS_DIR));if let Some(home) = home {push_unique_skill_root(&mut roots, home.join(CLAUDE_SKILL_DIR).join(SKILLS_DIR));push_unique_skill_root(&mut roots, home.join(AGENTS_SKILL_DIR).join(SKILLS_DIR));push_unique_skill_root(&mut roots, home.join(DEVIN_SKILL_DIR).join(SKILLS_DIR));+ push_unique_skill_root(&mut roots, home.join(GROK_SKILL_DIR).join(SKILLS_DIR));}// Windows global Devin installs live under %APPDATA%\devin\skills, not// $HOME/.devin/skills — sweep it too or uninstall orphans those skills.@@ -835,7 +839,7 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {McpClient::OpenCode => Some(&["mcp"]),McpClient::Openclaw | McpClient::Zero => Some(&["mcp", "servers"]),McpClient::VsCodeCopilot => Some(&["servers"]),- McpClient::Codex | McpClient::Pi => None,+ McpClient::Codex | McpClient::Grok | McpClient::Pi => None,}}@@ -984,7 +988,19 @@ mod tests {);let without = skill_roots(cwd, Some(home), None);- assert_eq!(without.len(), 6, "no phantom root when APPDATA is unset");+ assert_eq!(+ without.len(),+ 8,+ "no phantom root when APPDATA is unset (claude/agents/devin/grok × project+global)"+ );+ assert!(+ without.contains(&cwd.join(GROK_SKILL_DIR).join(SKILLS_DIR)),+ "{without:?}"+ );+ assert!(+ without.contains(&home.join(GROK_SKILL_DIR).join(SKILLS_DIR)),+ "{without:?}"+ );}#[test]diff --git a/crates/ai-memory-core/src/routing_skills.rs b/crates/ai-memory-core/src/routing_skills.rsindex 4e99ed84..f679a584 100644--- a/crates/ai-memory-core/src/routing_skills.rs+++ b/crates/ai-memory-core/src/routing_skills.rs@@ -12,6 +12,8 @@ pub const CLAUDE_SKILL_DIR: &str = ".claude";pub const AGENTS_SKILL_DIR: &str = ".agents";/// Devin-compatible Agent Skill directory below a project or home root.pub const DEVIN_SKILL_DIR: &str = ".devin";+/// Grok Build CLI Agent Skill directory below a project or home root.+pub const GROK_SKILL_DIR: &str = ".grok";/// Leaf directory that contains individual Agent Skill directories.pub const SKILLS_DIR: &str = "skills";diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex ce6ad144..582fb733 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -253,7 +253,7 @@ should be proposed from a completed session, or at explicit wrap-up \CLAUDE.md / AGENTS.md'. Returns the managed routing package: the \slim markered snippet (`markered_block`), filename hints, \`managed_skills` payloads, `target_hints` for `.claude/skills`, \- `.agents/skills`, `.devin/skills`, and Devin's Windows global \+ `.agents/skills`, `.devin/skills`, `.grok/skills`, and Devin's Windows global \`%APPDATA%\\devin\\skills` root, and overwrite guidance. Use your own Write/Edit \tool to replace only the ai-memory marker block in the rules file, \then write each managed skill under the selected skill root. Only \@@ -2415,7 +2415,7 @@ impl AiMemoryServer {`markered_block` for the slim CLAUDE.md / AGENTS.md snippet, \`agent_filenames` for rules-file targets, `managed_skills` for \Agent Skill files, and `target_hints` for project/global \- `.claude/skills`, `.agents/skills`, `.devin/skills`, and Devin Windows global roots. Use when the user \+ `.claude/skills`, `.agents/skills`, `.devin/skills`, `.grok/skills`, and Devin Windows global roots. Use when the user \asks to install or refresh ai-memory routing in this project. \After calling, use your Write/Edit tool to preserve non-ai-memory \user content: replace only an existing `<!-- ai-memory:start -->` \@@ -2453,6 +2453,7 @@ impl AiMemoryServer {"antigravity_cli": "AGENTS.md","zero": "AGENTS.md","devin": "AGENTS.md",+ "grok": "AGENTS.md","default": "AGENTS.md"},"managed_skills": managed_skills,@@ -2460,7 +2461,8 @@ impl AiMemoryServer {"project": {"claude_code": ".claude/skills","agents": ".agents/skills",- "devin": ".devin/skills"+ "devin": ".devin/skills",+ "grok": ".grok/skills"},"global": {"claude_code": "~/.claude/skills",@@ -2468,7 +2470,8 @@ impl AiMemoryServer {"devin": {"windows": "%APPDATA%\\devin\\skills","non_windows": "~/.devin/skills"- }+ },+ "grok": "~/.grok/skills"}},"overwrite_guidance": {@@ -2481,7 +2484,7 @@ impl AiMemoryServer {"If the target file already contains <!-- ai-memory:start --> / <!-- ai-memory:end --> delimiters alone on their own lines, replace ONLY that line-delimited block in place; ignore inline mentions and preserve every other line.","If the file doesn't exist, create it with just the markered_block (plus a trailing newline).","If the file exists but has no ai-memory markers, append the markered_block with one blank line of separation from existing content.",- "Install each managed_skills item under the selected skill root from target_hints using its relative_path, for example .claude/skills/<relative_path>, .agents/skills/<relative_path>, .devin/skills/<relative_path>, or %APPDATA%\\devin\\skills\\<relative_path> on Windows global Devin installs.",+ "Install each managed_skills item under the selected skill root from target_hints using its relative_path, for example .claude/skills/<relative_path>, .agents/skills/<relative_path>, .devin/skills/<relative_path>, .grok/skills/<relative_path>, or %APPDATA%\\devin\\skills\\<relative_path> on Windows global Devin installs.","Existing skill files containing the managed marker <!-- ai-memory-managed: routing-skill --> may be replaced; unmanaged same-name skills must not be overwritten unless the human explicitly forces replacement."]});@@ -3342,6 +3345,12 @@ mod tests {.unwrap(),".devin/skills");+ assert_eq!(+ response["target_hints"]["project"]["grok"]+ .as_str()+ .unwrap(),+ ".grok/skills"+ );assert_eq!(response["target_hints"]["global"]["claude_code"].as_str()@@ -3366,6 +3375,14 @@ mod tests {.unwrap(),"~/.devin/skills");+ assert_eq!(+ response["target_hints"]["global"]["grok"].as_str().unwrap(),+ "~/.grok/skills"+ );+ assert_eq!(+ response["agent_filenames"]["grok"].as_str().unwrap(),+ "AGENTS.md"+ );let notes = response["notes"].as_array()@@ -3400,8 +3417,9 @@ mod tests {assert!(desc.contains(".claude/skills")&& desc.contains(".agents/skills")- && desc.contains(".devin/skills"),- "tool description must name Claude, .agents, and Devin skill targets; got: {desc}"+ && desc.contains(".devin/skills")+ && desc.contains(".grok/skills"),+ "tool description must name Claude, .agents, Devin, and Grok skill targets; got: {desc}");assert!(desc.contains("preserve non-ai-memory user content"),diff --git a/docs/install.md b/docs/install.mdindex ba25bd8a..65c36a71 100644--- a/docs/install.md+++ b/docs/install.md@@ -689,6 +689,10 @@ docker run --rm akitaonrails/ai-memory:latest \install-hooks --agent antigravity-cli --auth-token "$TOKEN" \--server-url "http://homelab:49374"+docker run --rm akitaonrails/ai-memory:latest \+ install-mcp --client grok --auth-token "$TOKEN" \+ --server-url "http://homelab:49374/mcp"+docker run --rm akitaonrails/ai-memory:latest \install-hooks --agent grok --auth-token "$TOKEN" \--server-url "http://homelab:49374"@@ -706,16 +710,16 @@ docker run --rm akitaonrails/ai-memory:latest \--server-url "http://homelab:49374/mcp"```-Cursor, Gemini CLI, Antigravity CLI, and OpenClaw support both `install-mcp` and-`install-hooks`. Grok Build CLI is hook-only in ai-memory's installer today:-`install-hooks --agent grok` captures lifecycle events, but Grok ignores-`SessionStart` stdout, so handoffs must be accepted through MCP with+Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, and OpenClaw support both+`install-mcp` and `install-hooks`. Grok's `install-mcp --client grok` writes+`~/.grok/config.toml`; `install-hooks --agent grok` captures lifecycle events.+Grok ignores `SessionStart` stdout, so handoffs must be accepted through MCP with`memory_handoff_accept` when resuming. Claude Desktop and VS Code Copilot are MCP-only here,so you'll need to nudge the model to call `memory_query` /`memory_handoff_accept` itself.For clients with `install-hooks` support, the capture path handleshandoff injection at session start or the client's closest equivalent, except-for Grok's no-stdout SessionStart behavior (Antigravity CLI uses `PreInvocation`).+for Grok's (and Zero's) no-stdout SessionStart behavior (Antigravity CLI uses `PreInvocation`).---@@ -1090,7 +1094,7 @@ without that marker are preserved unless you explicitly force replacement.|---|---|| `--no-skills` | Refresh only the markered instruction block. || `--skills-scope <scope>` | Choose project-local or user-global skill roots. Values: `project`, `global`. Defaults to `project`. |-| `--skills-agent <agent>` | Choose `.claude/skills`, `.agents/skills`, `.devin/skills`, or both Claude/Agents roots. Values: `claude-code`, `agents`, `devin`, `both`. By default, `CLAUDE.md` targets imply `claude-code`, `AGENTS.md` targets imply `agents`, and both instruction files imply `both`. |+| `--skills-agent <agent>` | Choose `.claude/skills`, `.agents/skills`, `.devin/skills`, `.grok/skills`, or both Claude/Agents roots. Values: `claude-code`, `agents`, `devin`, `grok`, `both`. By default, `CLAUDE.md` targets imply `claude-code`, `AGENTS.md` targets imply `agents`, and both instruction files imply `both`. || `--skills-target-dir <dir>` | Write managed skill directories below an explicit root instead of inferring from scope and agent. || `--skills-force` | Replace unmanaged same-name skills during `install-instructions`; without it, they are left untouched and the command exits with an actionable error. |@@ -1101,6 +1105,7 @@ Agent Skill files need a refresh:ai-memory install-skillsai-memory install-skills --scope global --agent agentsai-memory install-skills --scope global --agent devin+ai-memory install-skills --scope global --agent grokai-memory install-skills --agent both --printai-memory install-skills --target-dir .custom/skills --force```@@ -1110,17 +1115,17 @@ ai-memory install-skills --target-dir .custom/skills --force| Flag | Meaning ||---|---|| `--scope <scope>` | Install into this project or the current user's global skill roots. Values: `project`, `global`. Defaults to `project`. |-| `--agent <agent>` | Install into Claude Code's skill root, the cross-agent skill root, Devin's skill root, or both Claude/Agents roots. Values: `claude-code`, `agents`, `devin`, `both`. Defaults to `claude-code`. |+| `--agent <agent>` | Install into Claude Code's skill root, the cross-agent skill root, Devin's skill root, Grok's skill root, or both Claude/Agents roots. Values: `claude-code`, `agents`, `devin`, `grok`, `both`. Defaults to `claude-code`. || `--target-dir <dir>` | Write managed skill directories below an explicit root; `--scope` and `--agent` are ignored. || `--print` | Print target paths and `SKILL.md` contents without writing files. || `--force` | Replace unmanaged same-name skills; without it, user-authored same-name skills are preserved. |Default skill target roots:-| Scope | `--agent claude-code` | `--agent agents` | `--agent devin` |-|---|---|---|---|-| `project` | `.claude/skills` | `.agents/skills` | `.devin/skills` |-| `global` | `~/.claude/skills` | `~/.agents/skills` | Windows: `%APPDATA%\devin\skills`; non-Windows: `~/.devin/skills` |+| Scope | `--agent claude-code` | `--agent agents` | `--agent devin` | `--agent grok` |+|---|---|---|---|---|+| `project` | `.claude/skills` | `.agents/skills` | `.devin/skills` | `.grok/skills` |+| `global` | `~/.claude/skills` | `~/.agents/skills` | Windows: `%APPDATA%\devin\skills`; non-Windows: `~/.devin/skills` | `~/.grok/skills` |Each managed skill is written as `<root>/<skill-name>/SKILL.md`.diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex d1772736..661f275a 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -101,7 +101,7 @@ metadata.> **One-shot tip:** every snippet below is also reachable from the> CLI:> ```bash-> ai-memory install-mcp --client gemini-cli # or cursor / claude-desktop / openclaw / omp / pi / antigravity-cli / vscode-copilot+> ai-memory install-mcp --client gemini-cli # or cursor / claude-desktop / openclaw / omp / pi / antigravity-cli / grok / vscode-copilot> ```---@@ -447,6 +447,56 @@ capture and session-end handoff *creation* work, but handoff *injection*does not — ask Zero to call `memory_handoff_accept` at the start of aresumed session.+## Grok Build CLI++**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported via+`ai-memory install-hooks --agent grok --apply`. ❌ No automatic handoff+injection (Grok ignores SessionStart stdout — same policy as Zero).++**Config file:** `~/.grok/config.toml` (user scope). Project scope is+`<repo>/.grok/config.toml`; pass `--config-file` if you want the+installer to write there.++```bash+ai-memory install-mcp --client grok --apply \+ --server-url "http://homelab:49374/mcp" --auth-token "$TOKEN"+```++which merges:++```toml+[mcp_servers.ai-memory]+url = "http://homelab:49374/mcp"+enabled = true++[mcp_servers.ai-memory.headers]+Authorization = "Bearer <token>"+```++**Schema notes (do not confuse with Codex):**+- Grok uses `[mcp_servers.<name>.headers]`; Codex uses `http_headers`.+- `enabled = true` is the documented per-server toggle.+- String fields support `${VAR}` expansion, so you can write+ `Authorization = "Bearer ${AI_MEMORY_AUTH_TOKEN}"` instead of embedding+ the token.+- CLI alternative: `grok mcp add --transport http ai-memory <url>` (plus+ `--header` for bearer auth).++Lifecycle capture is separate: `ai-memory install-hooks --agent grok+--apply` writes `~/.grok/hooks/ai-memory.json` (Grok discovers every+`~/.grok/hooks/*.json`, so third-party hook files stay untouched). Events+mirror Claude Code's vocabulary (`SessionStart`, `UserPromptSubmit`,+`PreToolUse`, `PostToolUse`, `PreCompact`, `Stop`, `SessionEnd`,+`SubagentStart`, `SubagentStop`) with a Grok-specific script bundle /+native `ai-memory hook --event … --agent grok` commands. Session-end+handoff *creation* works; handoff *injection* does not — ask Grok to+call `memory_handoff_accept` (or install the managed routing skills under+`.grok/skills` / `~/.grok/skills`) at the start of a resumed session.++Grok can also load MCP from Claude Code / Cursor compat sources when those+compat flags are enabled, but first-party `install-mcp --client grok` is+the supported path for uninstall isolation and hooks URL inference.+## Devin CLIDevin manages MCP servers in `~/.devin/config.json` under `mcpServers`:diff --git a/docs/usage.md b/docs/usage.mdindex 87ac2a38..61be7058 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -116,19 +116,21 @@ To refresh only the managed Agent Skills:ai-memory install-skillsai-memory install-skills --scope global --agent agentsai-memory install-skills --scope global --agent devin+ai-memory install-skills --scope global --agent grokai-memory install-skills --agent both --printai-memory install-skills --target-dir .custom/skills --force```For Devin, project-local skills are installed under `.devin/skills`. GlobalDevin installs use `%APPDATA%\devin\skills` on Windows and `~/.devin/skills`-on non-Windows systems.+on non-Windows systems. For Grok Build CLI, project-local skills go under+`.grok/skills` and global under `~/.grok/skills`.Project-local skill roots are `.claude/skills` for Claude-compatible installs,-`.agents/skills` for cross-client installs, and `.devin/skills` for Devin-installs. Global Claude/Agents roots are `~/.claude/skills` and+`.agents/skills` for cross-client installs, `.devin/skills` for Devin, and+`.grok/skills` for Grok. Global Claude/Agents roots are `~/.claude/skills` and`~/.agents/skills`; global Devin roots are platform-specific as described-above. `--target-dir` points at an explicit skill root and bypasses scope/agent+above; global Grok is `~/.grok/skills`. `--target-dir` points at an explicit skill root and bypasses scope/agentinference. `--print` previews target paths and `SKILL.md` contents. `--force`allows replacement of unmanaged same-name skills; without it, user-authoredskills are preserved. Uninstall removes ai-memory-managed skills from the