Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(agents): harden Grok configuration support

AkitaOnRails2e8af1d6b310
diff --git a/AGENTS.md b/AGENTS.md
index 8efcea09..7fa8fb5a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -36,7 +36,7 @@ install or refresh work.
If you're about to write a durable project rule ("always X", "never
Y", "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
+AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI, but if the project
says one file is canonical, use that file.
If the rule is a standing *user/team* preference that should apply to
@@ -53,7 +53,7 @@ latest binary's recommended copy:
- **From the agent** (no terminal needed): ask "refresh the ai-memory
routing 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
+ OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`), uses its Write / Edit tool
to replace or append the returned `markered_block` while preserving
non-ai-memory user content, then writes or updates each returned
`managed_skills` item under the selected skill root from `target_hints`
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 615b161c..fa435077 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,18 +10,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### 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
+ entry into `$GROK_HOME/config.toml` (default `~/.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
+ Managed routing skills can target `.grok/skills` / `$GROK_HOME/skills`
+ (default `~/.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
+- `install-hooks --agent devin` now infers the server URL and bearer token from
+ `~/.devin/config.json` when flags and environment settings are absent, keeping
+ hooks aligned with an existing Devin MCP registration.
+- Grok routing guidance now treats Grok Build CLI as an AGENTS-based client and
+ directs its managed skills to `.grok/skills` or `$GROK_HOME/skills` (default
+ `~/.grok/skills`). The MCP self-routing payload and installed prompt surface
+ now guard those targets;
+ Grok (like Zero) still resumes handoffs through `memory_handoff_accept`
+ because it ignores SessionStart stdout.
- One-shot client commands (`rename-project`, `status`, `write-page`, …) no
longer print the "cannot write log files … falling back" warning when the
log directory is unwritable — they still degrade to temp/stderr logging
diff --git a/README.md b/README.md
index 0fabb0be..18f1b218 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 | 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`. |
+| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.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_HOME/skills` (default `~/.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. |
@@ -120,7 +120,8 @@ priors are at the [bottom](#influences-and-prior-art).
classic. SessionStart hook in the next supported hook client prepends a
typed handoff with open questions, next steps, and a session summary. Grok
captures lifecycle events but ignores SessionStart stdout, so ask it to call
- `memory_handoff_accept` when resuming from a handoff.
+ `memory_handoff_accept` when resuming from a handoff. Zero has the same
+ no-stdout behavior and also must call `memory_handoff_accept`.
- **"What did we decide about X six weeks ago?"** Type
`memory_query X` from the agent (or `ai-memory search X` from a
terminal) - FTS5 over the wiki. Pages are LLM-consolidated, so
@@ -625,7 +626,7 @@ diagram, crate breakdown, schema notes, and invariants.
| [`docs/auto-scope.md`](docs/auto-scope.md) | `[auto_scope]` modes for shared servers: default single-slot routing, session-aware isolation, and multi-user `per_actor` behavior. |
| [`docs/macos.md`](docs/macos.md) | macOS install paths: native release binary (recommended), source build, the Docker wrapper, hook-platform notes, and current macOS limitations. |
| [`docs/windows.md`](docs/windows.md) | Windows install modes: full WSL2, native Windows with Docker Desktop, prebuilt native release zip, native source builds, and current hook/MCP harness caveats. |
-| [`docs/mcp-install.md`](docs/mcp-install.md) | Per-client MCP and lifecycle notes (Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, OpenClaw, OMP, VS Code Copilot) plus community bridge guidance. |
+| [`docs/mcp-install.md`](docs/mcp-install.md) | Per-client MCP and lifecycle notes, handoff-injection limits, and community bridge guidance. |
| [`docs/deploy.md`](docs/deploy.md) | Homelab deploy: bin/deploy, bearer-token auth, pointers to the TLS guide. |
| [`docs/users.md`](docs/users.md) | **Multi-user attribution (v0.8).** Four-rung auth ladder, `ai-memory user add/list/expire/revive/rotate-token` walkthrough, backward-compat migration for pre-v0.8 installs, token storage rationale. |
| [`docs/https-via-proxy.md`](docs/https-via-proxy.md) | **HTTPS via a reverse proxy.** When you need TLS (multi-user, non-loopback) and when you don't (loopback / stdio). Copy-paste docker compose templates for Caddy + Let's Encrypt, Caddy + internal CA (LAN-only), Cloudflare Tunnel (no open ports), and external cert files; plus native-Caddy + nginx recipes. The "thinking you're secure when you're not" failure modes explicitly called out. |
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 7d480dd3..4a60faa8 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -780,7 +780,7 @@ pub struct ReindexArgs {}
/// Agent CLI to install hooks/extensions for. For MCP-only clients
/// (Claude Desktop), use `install-mcp --client <name>` instead.
-#[derive(Debug, Clone, Copy, clap::ValueEnum)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum AgentChoice {
/// Anthropic Claude Code.
ClaudeCode,
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index cf0dc135..a89043a9 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -76,9 +76,7 @@ pub(crate) fn antigravity_hooks_path() -> anyhow::Result<std::path::PathBuf> {
/// `~/.grok/hooks/ai-memory.json` — Grok Build CLI lifecycle hooks.
pub(crate) fn grok_hooks_path() -> anyhow::Result<std::path::PathBuf> {
- Ok(home_dir()
- .context("could not locate $HOME for ~/.grok/hooks/ai-memory.json")?
- .join(".grok")
+ Ok(install_mcp::grok_home()?
.join("hooks")
.join("ai-memory.json"))
}
@@ -147,7 +145,7 @@ pub(crate) fn pi_extension_path() -> anyhow::Result<std::path::PathBuf> {
/// Returns an error if the hook script directory cannot be located.
pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {
let inferred = if args.server_url.is_none() {
- infer_installed_mcp_config(args.agent)
+ infer_installed_mcp_config(args.agent)?
} else {
None
};
@@ -360,40 +358,117 @@ fn apply_base_path_to_hook_url(url: &str, base_path: &str) -> String {
}
}
-fn infer_installed_mcp_config(agent: AgentChoice) -> Option<InferredMcpConfig> {
- let client = mcp_client_for_agent(agent)?;
- let path = install_mcp::mcp_config_path(client).ok()?;
- let content = fs::read_to_string(path).ok()?;
- match client {
- McpClient::ClaudeCode => {
- infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url")
+fn infer_installed_mcp_config(agent: AgentChoice) -> Result<Option<InferredMcpConfig>> {
+ if agent == AgentChoice::Grok {
+ let cwd = std::env::current_dir()
+ .context("could not resolve current dir for Grok project configuration")?;
+ let repo_root = ai_memory_consolidate::discover_repo_root(&cwd).ok();
+ if let Some(project_config) = find_grok_project_overlay(&cwd, repo_root.as_deref()) {
+ anyhow::bail!(
+ "Grok project configuration {} may override GROK_HOME; pass explicit --server-url and --auth-token rather than inferring MCP settings",
+ project_config.display()
+ );
}
+ }
+ let Some(client) = mcp_client_for_agent(agent) else {
+ return Ok(None);
+ };
+ let path = install_mcp::mcp_config_path(client)?;
+ let Ok(content) = fs::read_to_string(path) else {
+ return Ok(None);
+ };
+ match client {
+ McpClient::ClaudeCode => Ok(infer_json_mcp_config(
+ &content,
+ &["mcpServers", "ai-memory"],
+ "url",
+ )),
// 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 => {
- infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "httpUrl")
- }
- McpClient::Openclaw => {
- infer_json_mcp_config(&content, &["mcp", "servers", "ai-memory"], "url")
- }
- McpClient::Omp => infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url"),
- McpClient::Zero => infer_json_mcp_config(&content, &["mcp", "servers", "ai-memory"], "url"),
- McpClient::Pi => None,
- McpClient::AntigravityCli => {
- infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "serverUrl")
- }
- McpClient::Devin => infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url"),
- McpClient::ClaudeDesktop => None,
+ McpClient::Codex => Ok(infer_toml_mcp_config(&content)),
+ McpClient::Grok => infer_grok_mcp_config(&content),
+ McpClient::OpenCode => Ok(infer_json_mcp_config(
+ &content,
+ &["mcp", "ai-memory"],
+ "url",
+ )),
+ McpClient::Cursor => Ok(infer_json_mcp_config(
+ &content,
+ &["mcpServers", "ai-memory"],
+ "url",
+ )),
+ McpClient::GeminiCli => Ok(infer_json_mcp_config(
+ &content,
+ &["mcpServers", "ai-memory"],
+ "httpUrl",
+ )),
+ McpClient::Openclaw => Ok(infer_json_mcp_config(
+ &content,
+ &["mcp", "servers", "ai-memory"],
+ "url",
+ )),
+ McpClient::Omp => Ok(infer_json_mcp_config(
+ &content,
+ &["mcpServers", "ai-memory"],
+ "url",
+ )),
+ McpClient::Zero => Ok(infer_json_mcp_config(
+ &content,
+ &["mcp", "servers", "ai-memory"],
+ "url",
+ )),
+ McpClient::Pi => Ok(None),
+ McpClient::AntigravityCli => Ok(infer_json_mcp_config(
+ &content,
+ &["mcpServers", "ai-memory"],
+ "serverUrl",
+ )),
+ McpClient::Devin => Ok(infer_json_mcp_config(
+ &content,
+ &["mcpServers", "ai-memory"],
+ "url",
+ )),
+ McpClient::ClaudeDesktop => Ok(None),
// MCP-only client: no AgentChoice counterpart routes here.
// Reachable only if a future install_hooks flow targets VS
// Code Copilot directly.
- McpClient::VsCodeCopilot => {
- infer_json_mcp_config(&content, &["servers", "ai-memory"], "url")
+ McpClient::VsCodeCopilot => Ok(infer_json_mcp_config(
+ &content,
+ &["servers", "ai-memory"],
+ "url",
+ )),
+ }
+}
+
+/// Grok loads project settings from every directory between the repository
+/// root and CWD. Outside a repository, only the active directory is relevant.
+fn grok_project_overlay_paths(cwd: &Path, repo_root: Option<&Path>) -> Vec<PathBuf> {
+ let start = repo_root
+ .filter(|root| cwd.starts_with(root))
+ .unwrap_or(cwd);
+ let mut directories = Vec::new();
+ let mut current = cwd;
+ loop {
+ directories.push(current.to_path_buf());
+ if current == start {
+ break;
}
+ let Some(parent) = current.parent() else {
+ break;
+ };
+ current = parent;
}
+ directories.reverse();
+ directories
+ .into_iter()
+ .map(|directory| directory.join(".grok").join("config.toml"))
+ .collect()
+}
+
+fn find_grok_project_overlay(cwd: &Path, repo_root: Option<&Path>) -> Option<PathBuf> {
+ grok_project_overlay_paths(cwd, repo_root)
+ .into_iter()
+ .find(|path| path.exists())
}
fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {
@@ -470,6 +545,82 @@ fn infer_toml_mcp_config(content: &str) -> Option<InferredMcpConfig> {
})
}
+/// Infer Grok's TOML entry after resolving its supported `${VAR}` and
+/// `${VAR:-default}` placeholders. Refuse missing variables so generated hook
+/// commands never contain a literal placeholder.
+fn infer_grok_mcp_config(content: &str) -> Result<Option<InferredMcpConfig>> {
+ let doc: toml_edit::DocumentMut = match content.parse() {
+ Ok(doc) => doc,
+ Err(_) => return Ok(None),
+ };
+ let Some(server) = doc
+ .get("mcp_servers")
+ .and_then(|servers| servers.get("ai-memory"))
+ else {
+ return Ok(None);
+ };
+ let hook_server_url = server
+ .get("url")
+ .and_then(|value| value.as_str())
+ .map(expand_grok_placeholders)
+ .transpose()?
+ .as_deref()
+ .and_then(hook_server_url_from_mcp_url);
+ let auth_token = server
+ .get("headers")
+ .and_then(|headers| headers.get("Authorization"))
+ .and_then(|value| value.as_str())
+ .map(expand_grok_placeholders)
+ .transpose()?
+ .as_deref()
+ .and_then(bearer_token_from_header);
+ if hook_server_url.is_none() && auth_token.is_none() {
+ return Ok(None);
+ }
+ Ok(Some(InferredMcpConfig {
+ hook_server_url,
+ auth_token,
+ }))
+}
+
+fn expand_grok_placeholders(value: &str) -> Result<String> {
+ expand_grok_placeholders_with(value, |name| std::env::var(name).ok())
+}
+
+fn expand_grok_placeholders_with(
+ value: &str,
+ lookup: impl Fn(&str) -> Option<String>,
+) -> Result<String> {
+ let mut output = String::with_capacity(value.len());
+ let mut remaining = value;
+ while let Some(start) = remaining.find("${") {
+ output.push_str(&remaining[..start]);
+ let after_start = &remaining[start + 2..];
+ let end = after_start
+ .find('}')
+ .context("unterminated Grok ${...} placeholder")?;
+ let expression = &after_start[..end];
+ let (name, default) = expression
+ .split_once(":-")
+ .map_or((expression, None), |(name, default)| (name, Some(default)));
+ if name.is_empty()
+ || !name.chars().enumerate().all(|(index, ch)| {
+ ch == '_' || ch.is_ascii_alphanumeric() && (index > 0 || ch.is_ascii_alphabetic())
+ })
+ {
+ anyhow::bail!("invalid Grok environment placeholder `${{{expression}}}`");
+ }
+ let replacement = lookup(name)
+ .filter(|value| !value.is_empty())
+ .or_else(|| default.map(ToOwned::to_owned))
+ .with_context(|| format!("Grok MCP placeholder `${{{name}}}` is unset; pass explicit --server-url and --auth-token"))?;
+ output.push_str(&replacement);
+ remaining = &after_start[end + 1..];
+ }
+ output.push_str(remaining);
+ Ok(output)
+}
+
fn hook_server_url_from_mcp_url(url: &str) -> Option<String> {
let trimmed = url.trim().trim_end_matches('/');
if trimmed.is_empty() {
@@ -2580,12 +2731,19 @@ fn render_grok(
);
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");
+ let config_path = grok_hooks_path()?;
+ println!(
+ "# Grok Build CLI hook config — write to {}",
+ config_path.display()
+ );
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!(
+ "# Treat {} as sensitive (chmod 600).",
+ config_path.display()
+ );
}
println!("# NOTE: Grok ignores hook stdout on SessionStart — capture works,");
println!("# but handoff injection does not. Recover a prior session's");
@@ -4816,4 +4974,56 @@ model = "gpt-5"
"Devin session-start.sh must print {{}} only when no handoff is available"
);
}
+
+ #[test]
+ fn grok_placeholder_expansion_resolves_values_and_defaults() {
+ let expanded = expand_grok_placeholders_with("${HOST}/mcp ${TOKEN:-fallback}", |name| {
+ (name == "HOST").then(|| "https://memory.example".to_string())
+ })
+ .unwrap();
+ assert_eq!(expanded, "https://memory.example/mcp fallback");
+ }
+
+ #[test]
+ fn grok_placeholder_expansion_rejects_missing_variable() {
+ let err = expand_grok_placeholders_with("${MISSING}", |_| None).unwrap_err();
+ assert!(
+ err.to_string()
+ .contains("pass explicit --server-url and --auth-token")
+ );
+ }
+
+ #[test]
+ fn grok_project_overlays_cover_repo_root_through_cwd() {
+ let temp = tempfile::tempdir().unwrap();
+ let root = temp.path().join("repo");
+ let parent = root.join("nested");
+ let cwd = parent.join("leaf");
+ fs::create_dir_all(&cwd).unwrap();
+
+ for directory in [&root, &parent, &cwd] {
+ let overlay = directory.join(".grok/config.toml");
+ fs::create_dir_all(overlay.parent().unwrap()).unwrap();
+ fs::write(&overlay, "# override").unwrap();
+ assert_eq!(find_grok_project_overlay(&cwd, Some(&root)), Some(overlay));
+ fs::remove_file(directory.join(".grok/config.toml")).unwrap();
+ }
+ assert_eq!(find_grok_project_overlay(&cwd, Some(&root)), None);
+ }
+
+ #[test]
+ fn grok_project_overlay_outside_repo_checks_only_cwd() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("outside").join("leaf");
+ fs::create_dir_all(&cwd).unwrap();
+ let parent_overlay = cwd.parent().unwrap().join(".grok/config.toml");
+ fs::create_dir_all(parent_overlay.parent().unwrap()).unwrap();
+ fs::write(&parent_overlay, "# ignored").unwrap();
+ assert_eq!(find_grok_project_overlay(&cwd, None), None);
+
+ let cwd_overlay = cwd.join(".grok/config.toml");
+ fs::create_dir_all(cwd_overlay.parent().unwrap()).unwrap();
+ fs::write(&cwd_overlay, "# active").unwrap();
+ assert_eq!(find_grok_project_overlay(&cwd, None), Some(cwd_overlay));
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index 173cc149..f6a8112e 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -58,7 +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::Grok => render_grok(&args)?,
McpClient::OpenCode => render_opencode(&args)?,
McpClient::Cursor => render_cursor(&args)?,
McpClient::ClaudeDesktop => render_claude_desktop(&args)?,
@@ -120,10 +120,9 @@ 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"),
+ // Project scope is `.grok/config.toml` under cwd/repo; pass
+ // --config-file for that case rather than inventing a second default.
+ McpClient::Grok => grok_home()?.join("config.toml"),
McpClient::OpenCode => home()?
.join(".config")
.join("opencode")
@@ -182,6 +181,17 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>
})
}
+/// Resolve Grok Build CLI's user configuration root. Grok honours
+/// `GROK_HOME`; otherwise it uses `~/.grok`.
+pub(crate) fn grok_home() -> Result<PathBuf> {
+ if let Some(path) = std::env::var_os("GROK_HOME").filter(|path| !path.is_empty()) {
+ return Ok(PathBuf::from(path));
+ }
+ Ok(home_dir()
+ .context("could not locate $HOME for Grok configuration")?
+ .join(".grok"))
+}
+
/// Resolve the user-config file for this client. Honours
/// `--config-file` when provided, else uses the canonical default
/// per client.
@@ -452,23 +462,7 @@ fn codex_upsert_mcp_server(
doc: &mut toml_edit::DocumentMut,
args: &InstallMcpArgs,
) -> anyhow::Result<()> {
- use toml_edit::{Item, Table, Value, value};
-
- // Capture sibling entries from either inline-table or block-table
- // storage so we can rebuild in block form without dropping them.
- 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(),
- };
+ use toml_edit::{Item, Table, value};
// Build our `[mcp_servers.<name>]` as a block-style table.
//
@@ -522,17 +516,7 @@ fn codex_upsert_mcp_server(
server["http_headers"] = Item::Table(headers);
}
- // Replace `mcp_servers` wholesale with a fresh implicit parent
- // table. Implicit = render only the dotted `[mcp_servers.<name>]`
- // headers, never a bare `[mcp_servers]` header.
- 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));
+ upsert_toml_mcp_server(doc, &args.name, server);
Ok(())
}
@@ -550,21 +534,7 @@ 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(),
- };
+ use toml_edit::{Item, Table, value};
let mut server = Table::new();
server["url"] = value(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL));
@@ -575,15 +545,37 @@ fn grok_upsert_mcp_server(
server["headers"] = Item::Table(headers);
}
+ upsert_toml_mcp_server(doc, &args.name, server);
+ Ok(())
+}
+
+/// Replace one server while preserving siblings and canonicalising an inline
+/// `mcp_servers` map to block-form TOML tables.
+fn upsert_toml_mcp_server(doc: &mut toml_edit::DocumentMut, name: &str, server: toml_edit::Table) {
+ use toml_edit::{Item, Table, Value};
+
+ let preserved: Vec<(String, Item)> = match doc.get("mcp_servers") {
+ Some(Item::Table(table)) => table
+ .iter()
+ .filter(|(key, _)| *key != name)
+ .map(|(key, value)| (key.to_string(), value.clone()))
+ .collect(),
+ Some(Item::Value(Value::InlineTable(table))) => table
+ .iter()
+ .filter(|(key, _)| *key != name)
+ .map(|(key, value)| (key.to_string(), Item::Value(value.clone())))
+ .collect(),
+ _ => Vec::new(),
+ };
+
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));
+ parent.insert(name, Item::Table(server));
doc.insert("mcp_servers", Item::Table(parent));
- Ok(())
}
fn render_claude_code(args: &InstallMcpArgs) -> Result<String> {
@@ -651,12 +643,15 @@ fn render_codex(args: &InstallMcpArgs) -> String {
out
}
-fn render_grok(args: &InstallMcpArgs) -> String {
+fn render_grok(args: &InstallMcpArgs) -> Result<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 doc = toml_edit::DocumentMut::new();
+ grok_upsert_mcp_server(&mut doc, args)?;
+ let config_path = grok_home()?.join("config.toml");
let mut out = format!(
- "# Grok Build CLI — append to ~/.grok/config.toml\n\
+ "# Grok Build CLI — append to {config_path}\n\
#\n\
# Native HTTP transport. Pair with:\n\
# ai-memory install-hooks --agent grok --apply\n\
@@ -671,18 +666,14 @@ fn render_grok(args: &InstallMcpArgs) -> String {
enabled = true\n",
name = args.name,
url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL),
+ config_path = config_path.display(),
);
- 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
+ let config_start = out
+ .find("[mcp_servers.")
+ .context("internal: generated Grok TOML table missing")?;
+ out.truncate(config_start);
+ out.push_str(&doc.to_string());
+ Ok(out)
}
fn render_opencode(args: &InstallMcpArgs) -> Result<String> {
@@ -889,7 +880,7 @@ mod tests {
match args.client {
McpClient::ClaudeCode => render_claude_code(&args).unwrap(),
McpClient::Codex => render_codex(&args),
- McpClient::Grok => render_grok(&args),
+ McpClient::Grok => render_grok(&args).unwrap(),
McpClient::OpenCode => render_opencode(&args).unwrap(),
McpClient::Cursor => render_cursor(&args).unwrap(),
McpClient::ClaudeDesktop => render_claude_desktop(&args).unwrap(),
@@ -971,7 +962,7 @@ mod tests {
match args.client {
McpClient::ClaudeCode => render_claude_code(&args).unwrap(),
McpClient::Codex => render_codex(&args),
- McpClient::Grok => render_grok(&args),
+ McpClient::Grok => render_grok(&args).unwrap(),
McpClient::OpenCode => render_opencode(&args).unwrap(),
McpClient::Cursor => render_cursor(&args).unwrap(),
McpClient::ClaudeDesktop => render_claude_desktop(&args).unwrap(),
@@ -1094,7 +1085,15 @@ mod tests {
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"));
+ assert!(
+ grok.contains(
+ &grok_home()
+ .unwrap()
+ .join("config.toml")
+ .display()
+ .to_string()
+ )
+ );
// 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]"));
@@ -1418,4 +1417,26 @@ mod tests {
"second apply must produce identical bytes"
);
}
+
+ #[test]
+ fn grok_print_uses_apply_toml_builder_for_dotted_names_and_quotes() {
+ let mut args = args_with_token(McpClient::Grok);
+ args.name = "ai.memory".into();
+ args.server_url = Some("https://memory.example/mcp?note=\"quoted\"".into());
+
+ let printed = render_grok(&args).unwrap();
+ let mut applied = toml_edit::DocumentMut::new();
+ grok_upsert_mcp_server(&mut applied, &args).unwrap();
+ let expected = applied.to_string();
+
+ assert!(printed.ends_with(&expected), "print output:\n{printed}");
+ let parsed: toml_edit::DocumentMut = expected.parse().unwrap();
+ assert!(
+ parsed
+ .get("mcp_servers")
+ .unwrap()
+ .get("ai.memory")
+ .is_some()
+ );
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/install_skills.rs b/crates/ai-memory-cli/src/commands/install_skills.rs
index bf6d3e42..98337ab5 100644
--- a/crates/ai-memory-cli/src/commands/install_skills.rs
+++ b/crates/ai-memory-cli/src/commands/install_skills.rs
@@ -11,6 +11,7 @@ use anyhow::{Context, Result, bail};
use crate::cli::{InstallSkillsAgent, InstallSkillsArgs, InstallSkillsScope};
use crate::commands::apply_shared::{ApplyOutcome, apply_atomic};
+use crate::commands::install_mcp;
use crate::commands::path_util::home_dir;
use crate::config::Config;
@@ -83,11 +84,16 @@ fn resolve_target_roots_from_env(args: &InstallSkillsArgs) -> Result<Vec<TargetR
let cwd = std::env::current_dir().context("getting CWD for install-skills target")?;
let home = home_dir();
let appdata = std::env::var_os("APPDATA").map(PathBuf::from);
+ let grok_home = (args.scope == InstallSkillsScope::Global
+ && args.agent == InstallSkillsAgent::Grok)
+ .then(install_mcp::grok_home)
+ .transpose()?;
resolve_target_roots_for_platform(
args,
&cwd,
home.as_deref(),
appdata.as_deref(),
+ grok_home.as_deref(),
SkillHostPlatform::current(),
)
}
@@ -98,7 +104,7 @@ fn resolve_target_roots(
cwd: &Path,
home: Option<&Path>,
) -> Result<Vec<TargetRoot>> {
- resolve_target_roots_for_platform(args, cwd, home, None, SkillHostPlatform::Other)
+ resolve_target_roots_for_platform(args, cwd, home, None, None, SkillHostPlatform::Other)
}
fn resolve_target_roots_for_platform(
@@ -106,6 +112,7 @@ fn resolve_target_roots_for_platform(
cwd: &Path,
home: Option<&Path>,
appdata: Option<&Path>,
+ grok_home: Option<&Path>,
platform: SkillHostPlatform,
) -> Result<Vec<TargetRoot>> {
if let Some(target_dir) = &args.target_dir {
@@ -120,6 +127,7 @@ fn resolve_target_roots_for_platform(
cwd,
home,
appdata,
+ grok_home,
platform,
)?]
}
@@ -130,6 +138,7 @@ fn resolve_target_roots_for_platform(
cwd,
home,
appdata,
+ grok_home,
platform,
)?]
}
@@ -140,6 +149,7 @@ fn resolve_target_roots_for_platform(
cwd,
home,
appdata,
+ grok_home,
platform,
)?]
}
@@ -150,6 +160,7 @@ fn resolve_target_roots_for_platform(
cwd,
home,
appdata,
+ grok_home,
platform,
)?]
}
@@ -160,6 +171,7 @@ fn resolve_target_roots_for_platform(
cwd,
home,
appdata,
+ grok_home,
platform,
)?,
agent_root(
@@ -168,6 +180,7 @@ fn resolve_target_roots_for_platform(
cwd,
home,
appdata,
+ grok_home,
platform,
)?,
],
@@ -206,6 +219,7 @@ fn agent_root(
cwd: &Path,
home: Option<&Path>,
appdata: Option<&Path>,
+ grok_home: Option<&Path>,
platform: SkillHostPlatform,
) -> Result<PathBuf> {
if scope == InstallSkillsScope::Global
@@ -217,6 +231,13 @@ fn agent_root(
return Ok(appdata.join("devin").join(SKILLS_DIR));
}
+ if scope == InstallSkillsScope::Global
+ && kind == SkillRootKind::Grok
+ && let Some(grok_home) = grok_home
+ {
+ return Ok(grok_home.join(SKILLS_DIR));
+ }
+
let base = match scope {
InstallSkillsScope::Project => cwd,
InstallSkillsScope::Global => {
@@ -423,6 +444,7 @@ mod tests {
cwd,
Some(home),
Some(appdata),
+ None,
SkillHostPlatform::Windows,
)
.unwrap();
@@ -443,6 +465,7 @@ mod tests {
cwd,
Some(home),
None,
+ None,
SkillHostPlatform::Windows,
)
.unwrap_err();
@@ -450,6 +473,20 @@ mod tests {
assert!(err.to_string().contains("%APPDATA%"));
}
+ #[test]
+ fn global_grok_skill_root_uses_injected_grok_home_override() {
+ let roots = resolve_target_roots_for_platform(
+ &args(InstallSkillsScope::Global, InstallSkillsAgent::Grok),
+ Path::new("/repo"),
+ Some(Path::new("/home/alice")),
+ None,
+ Some(Path::new("/custom/grok")),
+ SkillHostPlatform::Other,
+ )
+ .unwrap();
+ assert_eq!(root_names(&roots), ["/custom/grok/skills"]);
+ }
+
#[test]
fn explicit_target_dir_overrides_scope_and_agent_roots() {
let cwd = Path::new("/repo");
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 2b136d36..2b21231a 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -35,6 +35,7 @@ use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use crate::cli::{AgentChoice, SetupAgentArgs};
+use crate::commands::install_mcp;
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,
@@ -261,19 +262,27 @@ fn emit_grok(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {
let payload = build_grok_payload(emit_root, &args.server_url, args.auth_token.as_deref());
let serialized =
serde_json::to_string_pretty(&payload).context("serializing Grok hook config")?;
- println!("# Grok Build CLI — write to ~/.grok/hooks/ai-memory.json");
+ let grok_home = install_mcp::grok_home()?;
+ let hooks_path = grok_home.join("hooks/ai-memory.json");
+ println!("# Grok Build CLI — write to {}", hooks_path.display());
println!("# Hook scripts (must be reachable from the host that runs Grok):");
println!("# {}", emit_root.display());
println!("# AI-memory server: {}", args.server_url);
if args.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!(
+ "# Treat {} as sensitive (chmod 600).",
+ hooks_path.display()
+ );
}
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!(
+ "# to register the MCP endpoint in {}.",
+ grok_home.join("config.toml").display()
+ );
println!();
println!("{serialized}");
Ok(())
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index 58b273e1..187c8e43 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -310,7 +310,13 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {
let cwd = std::env::current_dir().context("getting CWD for skill removal")?;
let home = home_dir();
let appdata = std::env::var_os("APPDATA").map(PathBuf::from);
- for root in skill_roots(&cwd, home.as_deref(), appdata.as_deref()) {
+ let grok_home = install_mcp::grok_home().ok();
+ for root in skill_roots(
+ &cwd,
+ home.as_deref(),
+ appdata.as_deref(),
+ grok_home.as_deref(),
+ ) {
for skill in MANAGED_SKILLS {
push_generated_delete(
&mut plan,
@@ -324,7 +330,12 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {
Ok(plan)
}
-fn skill_roots(cwd: &Path, home: Option<&Path>, appdata: Option<&Path>) -> Vec<PathBuf> {
+fn skill_roots(
+ cwd: &Path,
+ home: Option<&Path>,
+ appdata: Option<&Path>,
+ grok_home: Option<&Path>,
+) -> Vec<PathBuf> {
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));
@@ -334,7 +345,10 @@ fn skill_roots(cwd: &Path, home: Option<&Path>, appdata: Option<&Path>) -> Vec<P
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));
+ let grok_root = grok_home
+ .map(Path::to_path_buf)
+ .unwrap_or_else(|| home.join(GROK_SKILL_DIR));
+ push_unique_skill_root(&mut roots, grok_root.join(SKILLS_DIR));
}
// Windows global Devin installs live under %APPDATA%\devin\skills, not
// $HOME/.devin/skills — sweep it too or uninstall orphans those skills.
@@ -981,13 +995,13 @@ mod tests {
let home = Path::new("/home/alice");
let appdata = Path::new("C:/Users/Alice/AppData/Roaming");
- let roots = skill_roots(cwd, Some(home), Some(appdata));
+ let roots = skill_roots(cwd, Some(home), Some(appdata), None);
assert!(
roots.contains(&appdata.join("devin").join(SKILLS_DIR)),
"{roots:?}"
);
- let without = skill_roots(cwd, Some(home), None);
+ let without = skill_roots(cwd, Some(home), None, None);
assert_eq!(
without.len(),
8,
@@ -1003,6 +1017,21 @@ mod tests {
);
}
+ #[test]
+ fn skill_roots_use_injected_grok_home_override() {
+ let roots = skill_roots(
+ Path::new("/repo"),
+ Some(Path::new("/home/alice")),
+ None,
+ Some(Path::new("/custom/grok")),
+ );
+ assert!(
+ roots.contains(&PathBuf::from("/custom/grok/skills")),
+ "{roots:?}"
+ );
+ assert!(!roots.contains(&PathBuf::from("/home/alice/.grok/skills")));
+ }
+
#[test]
fn strip_instructions_round_trips_with_install_append() {
let original = "# Title\n";
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md
index 2755cbda..b6c288d5 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md
@@ -37,16 +37,19 @@ Project-local targets:
- `.claude/skills/<skill>/SKILL.md` for Claude-compatible installs.
- `.agents/skills/<skill>/SKILL.md` for cross-client installs.
+- `.grok/skills/<skill>/SKILL.md` for Grok Build CLI installs.
Global targets:
- `~/.claude/skills/<skill>/SKILL.md` for Claude-compatible installs.
- `~/.agents/skills/<skill>/SKILL.md` for cross-client installs.
+- `$GROK_HOME/skills/<skill>/SKILL.md` for Grok Build CLI installs (default:
+ `~/.grok/skills/<skill>/SKILL.md`).
Use platform-aware path joining. Do not build paths by string concatenation.
## Refresh guidance
-For an agent-side refresh, call the install-routing tool, choose the right instruction filename from its hints, write the markered block with the agent's file-edit tool, and write each managed skill file to the selected skill roots. Claude Code normally uses `CLAUDE.md` and `.claude/skills`; Codex, OpenCode, Cursor, Gemini CLI, and AGENTS-aware clients normally use `AGENTS.md` and `.agents/skills` unless the project says otherwise.
+For an agent-side refresh, call the install-routing tool. Its returned `target_hints` are authoritative for skill roots: choose the right instruction filename from `agent_filenames`, write the markered block with the agent's file-edit tool, and write each managed skill file below the selected hint using its `relative_path`. Claude Code normally uses `CLAUDE.md` and `.claude/skills`; Codex, OpenCode, Cursor, Gemini CLI, and AGENTS-aware clients normally use `AGENTS.md` and `.agents/skills`; Grok Build CLI uses `AGENTS.md` and `.grok/skills` unless the project says otherwise.
For a CLI refresh, prefer the canonical install command. The snippet and skills must be updated from the same core-owned assets so they do not drift.
diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rs
index ee344eb3..9acaf42c 100644
--- a/crates/ai-memory-core/src/routing_snippet.rs
+++ b/crates/ai-memory-core/src/routing_snippet.rs
@@ -64,7 +64,7 @@ install or refresh work.
If you're about to write a durable project rule ("always X", "never
Y", "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
+AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI / Grok Build CLI, but if the project
says one file is canonical, use that file.
If the rule is a standing *user/team* preference that should apply to
@@ -81,7 +81,7 @@ latest binary's recommended copy:
- **From the agent** (no terminal needed): ask "refresh the ai-memory
routing 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
+ OpenCode / Cursor / Gemini / Grok -> `AGENTS.md`), uses its Write / Edit tool
to replace or append the returned `markered_block` while preserving
non-ai-memory user content, then writes or updates each returned
`managed_skills` item under the selected skill root from `target_hints`
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 582fb733..d45d0a12 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -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`, `.grok/skills`, and Devin Windows global roots. Use when the user \
+ `.claude/skills`, `.agents/skills`, `.devin/skills`, `.grok/skills`, `$GROK_HOME/skills` (default `~/.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 -->` \
@@ -2471,7 +2471,7 @@ impl AiMemoryServer {
"windows": "%APPDATA%\\devin\\skills",
"non_windows": "~/.devin/skills"
},
- "grok": "~/.grok/skills"
+ "grok": "$GROK_HOME/skills (default: ~/.grok/skills)"
}
},
"overwrite_guidance": {
@@ -2484,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>, .grok/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>, $GROK_HOME/skills/<relative_path> (default ~/.grok/skills), 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."
]
});
@@ -3113,6 +3113,15 @@ mod tests {
);
}
}
+
+ #[test]
+ fn installed_prompt_surface_routes_grok_to_agents_md() {
+ let installed = installed_ai_memory_prompt_surface();
+ assert!(
+ installed.contains("Grok Build CLI") && installed.contains("Grok -> `AGENTS.md`"),
+ "installed snippet and managed skills must route Grok to AGENTS.md"
+ );
+ }
#[test]
fn prompts_separate_briefing_from_handoff_lifecycle() {
assert_detailed_prompt_surfaces(|label, prompt| {
@@ -3326,6 +3335,20 @@ mod tests {
expected.name
);
}
+ let routing_install_skill = managed_skills
+ .iter()
+ .find(|skill| skill["name"].as_str() == Some("ai-memory-routing-install"))
+ .expect("routing-install skill must be included in the install payload");
+ let routing_install_content = routing_install_skill["content"]
+ .as_str()
+ .expect("routing-install skill content must be text");
+ assert!(
+ routing_install_content.contains("target_hints")
+ && routing_install_content.contains(".grok/skills")
+ && routing_install_content.contains("$GROK_HOME/skills")
+ && routing_install_content.contains("~/.grok/skills"),
+ "routing-install skill must treat target_hints as authoritative and include Grok roots"
+ );
assert_eq!(
response["target_hints"]["project"]["claude_code"]
@@ -3377,7 +3400,7 @@ mod tests {
);
assert_eq!(
response["target_hints"]["global"]["grok"].as_str().unwrap(),
- "~/.grok/skills"
+ "$GROK_HOME/skills (default: ~/.grok/skills)"
);
assert_eq!(
response["agent_filenames"]["grok"].as_str().unwrap(),
@@ -3418,7 +3441,8 @@ mod tests {
desc.contains(".claude/skills")
&& desc.contains(".agents/skills")
&& desc.contains(".devin/skills")
- && desc.contains(".grok/skills"),
+ && desc.contains(".grok/skills")
+ && desc.contains("$GROK_HOME/skills"),
"tool description must name Claude, .agents, Devin, and Grok skill targets; got: {desc}"
);
assert!(
diff --git a/docs/install.md b/docs/install.md
index 65c36a71..8398ffce 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -563,9 +563,10 @@ differences:
The `SessionStart` hook injects pending handoffs through Devin's
`hookSpecificOutput.additionalContext`. Real Devin `SessionStart` and
-`PostToolUse` payloads may omit `session_id` and `cwd`; ai-memory derives stable
-session/cwd context from its hook state and process environment so those events
-are still captured.
+`PostToolUse` payloads may omit `session_id` and `cwd`; ai-memory now infers cwd
+from `DEVIN_PROJECT_DIR` or the hook process working directory when the payload
+omits 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.
### OpenCode
@@ -712,7 +713,9 @@ docker run --rm akitaonrails/ai-memory:latest \
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_HOME/config.toml` (default `~/.grok/config.toml`); its hooks live under
+`$GROK_HOME/hooks` (default `~/.grok/hooks`). `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` /
@@ -1125,7 +1128,7 @@ Default skill target roots:
| 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` |
+| `global` | `~/.claude/skills` | `~/.agents/skills` | Windows: `%APPDATA%\devin\skills`; non-Windows: `~/.devin/skills` | `$GROK_HOME/skills` (default `~/.grok/skills`) |
Each managed skill is written as `<root>/<skill-name>/SKILL.md`.
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index 661f275a..fa9e220a 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -27,6 +27,9 @@ files for OpenClaw / OpenCode / OMP) and are covered in the
Git Bash `.sh` hooks rather than the PowerShell default used by other
script-hook agents. Grok and Zero capture lifecycle events, but both ignore
SessionStart stdout, so ai-memory does not auto-inject handoffs for them.
+SessionStart handoff injection works only for clients that consume startup-hook
+stdout (or their equivalent context-injection result); Grok and Zero must call
+`memory_handoff_accept` when resuming.
Claude Desktop and VS Code Copilot are **MCP-only** here: they expose
long-term memory to their LLMs via ai-memory's MCP tools
@@ -37,7 +40,7 @@ endpoint. The trade-off:
| | What you get | What you don't get |
|---|---|---|
| **MCP only** | LLM can query the wiki, accept handoffs, run memory_consolidate, and run `memory_auto_improve` learning reviews | No automatic session-end summaries; no auto-handoff at session boundaries |
-| **MCP + hooks** | All of the above *plus* every prompt/tool-call captured automatically; handoffs surface at SessionStart with no human prompting | - |
+| **MCP + hooks** | All of the above *plus* every prompt/tool-call captured automatically; handoffs surface at SessionStart with no human prompting **only when the client consumes startup-hook output or an equivalent context-injection result** | Grok and Zero discard SessionStart stdout; ask them to call `memory_handoff_accept` when resuming. |
For MCP-only use, you can still cover the session-boundary gap by asking
the LLM to call `memory_handoff_begin` manually before quitting.
@@ -453,9 +456,11 @@ resumed session.
`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.
+**Config file:** `install-mcp --client grok --apply` writes the user config at
+`$GROK_HOME/config.toml` (default `~/.grok/config.toml`). To use a project or
+custom config file, pass its exact path with `--config-file`; the CLI does not
+infer a project config location. Provide the MCP URL and token explicitly for
+that lane, and remove a custom config entry manually when uninstalling.
```bash
ai-memory install-mcp --client grok --apply \
@@ -483,15 +488,17 @@ Authorization = "Bearer <token>"
`--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
+--apply` writes `$GROK_HOME/hooks/ai-memory.json` (default
+`~/.grok/hooks/ai-memory.json`; Grok discovers every
+`$GROK_HOME/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/skills` / `$GROK_HOME/skills` (default `~/.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
@@ -686,8 +693,9 @@ If the model sees the tools but does not call them proactively, refresh the
managed routing package. The `memory_install_self_routing` tool is read-only:
it returns the slim markered instruction block, marker strings, agent filename
hints, managed skill payloads (`name`, `description`, `relative_path`,
-`content`), project/global target hints for `.claude/skills` and
-`.agents/skills`, and overwrite guidance. Agents should use their own file
+`content`), and authoritative project/global target hints for `.claude/skills`,
+`.agents/skills`, `.grok/skills`, and `$GROK_HOME/skills` (default
+`~/.grok/skills`), plus overwrite guidance. Agents should use their own file
editing tools to write those artifacts while preserving unrelated user content.
If the model doesn't see any of those tools, the MCP registration
@@ -720,7 +728,7 @@ that *starts* the next one - to play nicely with ai-memory:
| Side | What's needed | Covered by |
|---|---|---|
| **Ending side** | The agent must create a handoff, either through a true session-end hook, the supported Codex manual finalizer, or by calling `memory_handoff_begin`. | Built-in automatically for Claude Code, Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, OpenClaw, OpenCode, and OMP. Codex has no reliable true session-end event, so run `ai-memory finalize-session` when you need the final summary/handoff/auto-improve eligibility. Antigravity CLI has no true session-end event in the current integration, so ask it to call `memory_handoff_begin` before quitting when you need a handoff. |
-| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / OpenClaw / OpenCode / OMP. Grok is explicitly excluded because it ignores SessionStart stdout; use (b). (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |
+| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / OpenClaw / OpenCode / OMP. It requires a client that consumes startup-hook stdout or an equivalent context-injection result. Grok and Zero are explicitly excluded because they discard SessionStart stdout; use (b). (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |
OpenCode uses its official `session.deleted` plugin event for true session-end
delivery. Its generated plugin also sends a deduped best-effort close for any
diff --git a/docs/usage.md b/docs/usage.md
index 61be7058..4f070322 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -100,7 +100,7 @@ and writes a timestamped backup before changing an existing instruction file.
`install-instructions --print` previews the instruction snippet only; use
`install-skills --print` to preview skill payloads. Skill flags mirror
`install-skills` with an `--skills-` prefix:
-`--skills-scope project|global`, `--skills-agent claude-code|agents|devin|both`,
+`--skills-scope project|global`, `--skills-agent claude-code|agents|devin|grok|both`,
`--skills-target-dir <dir>`, and `--skills-force`.
Auto-detect extends `CLAUDE.md` when it exists, `AGENTS.md` when it
@@ -108,7 +108,8 @@ exists, both when both exist, or creates `CLAUDE.md` when neither exists. Use
`--target AGENTS.md` for non-Claude-only projects. The skill target follows the
instruction target unless you override it: `CLAUDE.md` implies
`.claude/skills`, `AGENTS.md` implies `.agents/skills`, and both files imply
-both skill roots.
+both skill roots. For Grok Build CLI, select `--skills-agent grok` so skills
+install under its `.grok/skills` root.
To refresh only the managed Agent Skills:
@@ -124,13 +125,15 @@ ai-memory install-skills --target-dir .custom/skills --force
For Devin, project-local skills are installed under `.devin/skills`. Global
Devin installs use `%APPDATA%\devin\skills` on Windows and `~/.devin/skills`
on non-Windows systems. For Grok Build CLI, project-local skills go under
-`.grok/skills` and global under `~/.grok/skills`.
+`.grok/skills` and global under `$GROK_HOME/skills` (default
+`~/.grok/skills`).
Project-local skill roots are `.claude/skills` for Claude-compatible installs,
`.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; global Grok is `~/.grok/skills`. `--target-dir` points at an explicit skill root and bypasses scope/agent
+above; global Grok is `$GROK_HOME/skills` (default `~/.grok/skills`).
+`--target-dir` points at an explicit skill root and bypasses scope/agent
inference. `--print` previews target paths and `SKILL.md` contents. `--force`
allows replacement of unmanaged same-name skills; without it, user-authored
skills are preserved. Uninstall removes ai-memory-managed skills from the
@@ -289,7 +292,7 @@ docker exec ai-memory git -C /data/wiki log --oneline
Durable project rules belong in the agent's rules file, not only in the
wiki. For Claude Code that is `CLAUDE.md`; for Codex, Devin CLI, OpenCode,
-Cursor, and Gemini CLI it is usually `AGENTS.md`.
+Cursor, Gemini CLI, and Grok Build CLI it is usually `AGENTS.md`.
The consolidator classifies compiled observations as `decision`,
`fact`, `rule`, or `gotcha`. Rule-tagged pages are routed to