Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(agents): support Zero (Gitlawb/zero) as agent + MCP client
AkitaOnRails14aed477c1d0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4aca375f..e5097131 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Zero (Gitlawb/zero) is now a supported agent/client ([#156]).+ `install-mcp --client zero` merges a native HTTP + bearer entry into+ Zero's `~/.config/zero/config.json` (`mcp.servers` map), and+ `install-hooks --agent zero --apply` merges exec-form lifecycle hooks+ (the native `ai-memory hook` command with an args array — JSON payload+ on stdin, no shell) into `~/.config/zero/hooks.json`, preserving+ third-party hooks in the same file by id prefix. All six Zero events+ are covered: `sessionStart`/`sessionEnd`, `beforeTool`/`afterTool`,+ and `specialistStart`/`specialistStop` (mapped to ai-memory's subagent+ events). Zero discards `sessionStart` hook stdout, so capture and+ handoff creation work but handoff injection does not — recover+ handoffs via the MCP `memory_handoff_accept` tool, same policy as+ Grok. `uninstall` strips the hook entries and the MCP registration;+ `setup-agent --agent zero` prints the config for docker-host flows.+ Support tracks Zero's current formats — it is a fast-moving young+ project and upstream churn will be fixed as reported.+## [1.9.1] - 2026-07-08### Fixeddiff --git a/README.md b/README.mdindex fde922ca..be9d0c3d 100644--- a/README.md+++ b/README.md@@ -33,6 +33,7 @@| 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`. |+| 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). || LLM/auth providers | Supported | Anthropic, OpenAI, OpenAI OAuth/Codex, GitHub Copilot, Gemini, OpenCode Zen/Go, OpenAI-compatible endpoints, and generic OIDC device auth for native hooks. || Embedding providers | Supported | OpenAI, Voyage, and Google Gemini. |diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 54ee491b..fc6cdf5b 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -818,6 +818,13 @@ pub enum AgentChoice {/// capture works but handoff injection does not — recover the prior/// session's handoff via the MCP `memory_handoff_accept` tool.Grok,+ /// Zero coding agent (Gitlawb/zero) — JSON-config lifecycle hooks in+ /// `$XDG_CONFIG_HOME/zero/hooks.json` (exec-form `command` + `args`,+ /// so ai-memory's native `hook` command runs with no shell). NOTE:+ /// Zero discards `sessionStart` hook stdout, so capture works but+ /// handoff injection does not — recover the prior session's handoff+ /// via the MCP `memory_handoff_accept` tool.+ Zero,}impl AgentChoice {@@ -840,17 +847,19 @@ impl AgentChoice {Self::Openclaw => AgentKind::OpenClaw,Self::AntigravityCli => AgentKind::AntigravityCli,Self::Grok => AgentKind::Grok,+ Self::Zero => AgentKind::Zero,}}/// `hooks/<subdir>` bundle name for agents that install script hooks./// `None` for agents wired through a generated integration (plugin /- /// extension) instead of a script directory. The subdir equals the- /// kind's wire string for every script agent.+ /// extension / exec-form native commands) instead of a script+ /// directory. The subdir equals the kind's wire string for every+ /// script agent.#[must_use]pub const fn script_hook_subdir(self) -> Option<&'static str> {match self {- Self::OpenCode | Self::Pi | Self::Omp | Self::Openclaw => None,+ Self::OpenCode | Self::Pi | Self::Omp | Self::Openclaw | Self::Zero => None,_ => Some(self.kind().as_str()),}}@@ -910,6 +919,9 @@ pub enum McpClient {/// Google Antigravity CLI (`agy`) — `~/.gemini/antigravity-cli/mcp_config.json`.#[value(alias = "antigravity", alias = "agy")]AntigravityCli,+ /// Zero coding agent (Gitlawb/zero) — `~/.config/zero/config.json`,+ /// `mcp.servers` map with native HTTP transport + bearer headers.+ Zero,/// VS Code GitHub Copilot (agent mode) — per-workspace/// `.vscode/mcp.json`. Copilot's agent mode reads MCP servers/// from VS Code's own MCP framework (top-level `servers` key),diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex daa53a09..9d63140f 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -83,6 +83,18 @@ pub(crate) fn grok_hooks_path() -> anyhow::Result<std::path::PathBuf> {.join("ai-memory.json"))}+/// `~/.config/zero/hooks.json` — Zero's user-level lifecycle hook config+/// (issue #156). Zero resolves it under `$XDG_CONFIG_HOME` falling back to+/// `~/.config`; like the OpenCode plugin path below we target the default+/// location and `--config-file` covers non-default XDG setups.+pub(crate) fn zero_hooks_path() -> anyhow::Result<std::path::PathBuf> {+ Ok(home_dir()+ .context("could not locate $HOME for ~/.config/zero/hooks.json")?+ .join(".config")+ .join("zero")+ .join("hooks.json"))+}+/// `~/.config/opencode/plugins/ai-memory.ts` — OpenCode's plugin file.pub(crate) fn opencode_plugin_path() -> anyhow::Result<std::path::PathBuf> {Ok(home_dir()@@ -183,6 +195,7 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;apply_to_grok_settings(&hooks_dir, &server_url, auth, &config.data_dir, &args)}+ AgentChoice::Zero => apply_to_zero_hooks(&server_url, auth, &config.data_dir, &args),AgentChoice::Openclaw => openclaw_plugin::apply(&server_url, auth, &args),};}@@ -243,6 +256,7 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;render_grok(&hooks_dir, &server_url, auth, &config.data_dir, strategy)}+ AgentChoice::Zero => render_zero(&server_url, auth, &config.data_dir, strategy),AgentChoice::Openclaw => {openclaw_plugin::render(&server_url, auth, strategy);Ok(())@@ -340,6 +354,7 @@ fn infer_installed_mcp_config(agent: AgentChoice) -> Option<InferredMcpConfig> {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")@@ -364,6 +379,7 @@ fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {AgentChoice::Omp => Some(McpClient::Omp),AgentChoice::Openclaw => Some(McpClient::Openclaw),AgentChoice::AntigravityCli => Some(McpClient::AntigravityCli),+ AgentChoice::Zero => Some(McpClient::Zero),// Grok manages its own MCP config under ~/.grok/; we don't// auto-infer a hook server URL from it.AgentChoice::Pi | AgentChoice::Grok => None,@@ -2450,6 +2466,113 @@ fn render_grok(Ok(())}+/// Merge ai-memory's lifecycle hooks into Zero's user-level+/// `~/.config/zero/hooks.json` (issue #156). Zero executes hook entries+/// directly (`command` + `args`, JSON payload on stdin) — no scripts to+/// stage, no shell. Only entries whose `id` carries the `ai-memory-`+/// prefix are replaced, so third-party hooks in the same file survive+/// re-installs and version upgrades. The file-level `enabled` flag is+/// preserved when the file already exists (a user who disabled hooks+/// globally keeps that choice — we warn instead of overriding).+fn apply_to_zero_hooks(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+) -> Result<()> {+ let path = match &args.config_file {+ Some(p) => p.clone(),+ None => zero_hooks_path()?,+ };+ let strategy = args.project_strategy.baked();+ let payload = super::render_shared::build_zero_hooks_config(+ server_url,+ auth_token,+ Some(data_dir),+ strategy,+ );+ let our_hooks = payload+ .get("hooks")+ .and_then(|v| v.as_array())+ .context("internal: build_zero_hooks_config didn't return a hooks array")?+ .clone();+ let mut hooks_disabled = false;+ let outcome = apply_atomic(&path, |existing| {+ mutate_json(existing, |root| {+ hooks_disabled = root.get("enabled").and_then(|v| v.as_bool()) == Some(false);+ if !root.contains_key("enabled") {+ root.insert("enabled".into(), serde_json::Value::Bool(true));+ }+ let hooks = root+ .entry("hooks")+ .or_insert_with(|| serde_json::Value::Array(Vec::new()))+ .as_array_mut()+ .context("`hooks` is present in hooks.json but not an array")?;+ hooks.retain(|hook| {+ !hook+ .get("id")+ .and_then(|v| v.as_str())+ .is_some_and(|id| id.starts_with("ai-memory-"))+ });+ hooks.extend(our_hooks.iter().cloned());+ Ok(())+ })+ })?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ if hooks_disabled {+ eprintln!(+ "# warning: this hooks.json sets \"enabled\": false at the top level, \+ so Zero will not run ANY hooks (including ai-memory's) until you \+ re-enable them."+ );+ }+ println!("# NOTE: Zero discards sessionStart hook stdout — capture works, but");+ println!("# handoff injection does not. Recover a prior session's handoff");+ println!("# via the MCP `memory_handoff_accept` tool.");+ Ok(())+}++/// Print Zero's hooks.json to stdout (dry-run counterpart of+/// [`apply_to_zero_hooks`]).+fn render_zero(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+) -> Result<()> {+ let payload = super::render_shared::build_zero_hooks_config(+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ let serialized =+ serde_json::to_string_pretty(&payload).context("serializing zero hook config")?;+ println!("# Zero hook config — merge into ~/.config/zero/hooks.json");+ println!("# ($XDG_CONFIG_HOME/zero/hooks.json on non-default XDG setups), or");+ println!("# re-run with --apply to merge it in place, preserving other hooks.");+ println!("# AI-memory server URL: {server_url}");+ if auth_token.is_some() {+ println!("# Auth: token embedded in each hook's args below.");+ println!("# Treat hooks.json as sensitive (chmod 600).");+ }+ println!("# NOTE: Zero discards sessionStart hook stdout — capture works, but");+ println!("# handoff injection does not. Recover a prior session's handoff");+ println!("# via the MCP `memory_handoff_accept` tool.");+ println!();+ println!("{serialized}");+ Ok(())+}+#[cfg(test)]mod tests {use super::*;@@ -2827,6 +2950,109 @@ mod tests {assert_eq!(resolved, tmp.path().join("grok"));}+ // Issue #156: Zero hook install writes exec-form entries into Zero's+ // hooks.json shape and merges around third-party hooks by id prefix.+ #[test]+ fn zero_hooks_config_covers_all_events_in_exec_form() {+ let payload = super::super::render_shared::build_zero_hooks_config(+ "http://127.0.0.1:49374",+ Some("tok-test"),+ Some(Path::new("/data")),+ Some("repo-root"),+ );+ assert_eq!(payload["enabled"], serde_json::json!(true));+ let hooks = payload["hooks"].as_array().unwrap();+ assert_eq!(hooks.len(), 6, "one entry per Zero lifecycle event");+ let events: Vec<&str> = hooks.iter().map(|h| h["event"].as_str().unwrap()).collect();+ for zero_event in [+ "sessionStart",+ "sessionEnd",+ "beforeTool",+ "afterTool",+ "specialistStart",+ "specialistStop",+ ] {+ assert!(events.contains(&zero_event), "missing {zero_event}");+ }+ for hook in hooks {+ let id = hook["id"].as_str().unwrap();+ assert!(id.starts_with("ai-memory-"), "ownership prefix: {id}");+ assert!(hook["enabled"].as_bool().unwrap());+ let args: Vec<&str> = hook["args"]+ .as_array()+ .unwrap()+ .iter()+ .map(|a| a.as_str().unwrap())+ .collect();+ // Exec form: the native hook subcommand with agent + auth ++ // strategy — never a shell string.+ assert!(args.contains(&"hook"), "{args:?}");+ assert!(+ args.contains(&"--agent") && args.contains(&"zero"),+ "{args:?}"+ );+ assert!(args.contains(&"--auth-token") && args.contains(&"tok-test"));+ assert!(args.contains(&"--project-strategy") && args.contains(&"repo-root"));+ assert!(args.contains(&"--data-dir") && args.contains(&"/data"));+ }+ }++ #[test]+ fn zero_apply_merges_around_third_party_hooks_and_preserves_disabled_flag() {+ let tmp = TempDir::new().unwrap();+ let path = tmp.path().join("hooks.json");+ fs::write(+ &path,+ r#"{"enabled": false, "hooks": [+ {"id": "my-custom-hook", "event": "beforeTool",+ "command": "/usr/bin/true", "args": [], "enabled": true},+ {"id": "ai-memory-session-start", "event": "sessionStart",+ "command": "/old/ai-memory", "args": [], "enabled": true}+ ]}"#,+ )+ .unwrap();+ let args = InstallHooksArgs {+ agent: AgentChoice::Zero,+ config_file: Some(path.clone()),+ ..default_hook_args()+ };++ apply_to_zero_hooks("http://127.0.0.1:49374", None, Path::new("/data"), &args).unwrap();++ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();+ assert_eq!(+ root["enabled"],+ serde_json::json!(false),+ "a user-disabled hooks file must stay disabled (we warn instead)"+ );+ let hooks = root["hooks"].as_array().unwrap();+ assert!(+ hooks+ .iter()+ .any(|h| h["id"] == serde_json::json!("my-custom-hook")),+ "third-party hooks must survive the merge"+ );+ let ours: Vec<&serde_json::Value> = hooks+ .iter()+ .filter(|h| {+ h["id"]+ .as_str()+ .is_some_and(|id| id.starts_with("ai-memory-"))+ })+ .collect();+ assert_eq!(+ ours.len(),+ 6,+ "stale ai-memory entries replaced, not duplicated"+ );+ assert!(+ ours.iter()+ .all(|h| h["command"] != serde_json::json!("/old/ai-memory")),+ "the stale command path must be replaced"+ );+ }+#[test]fn opencode_mcp_inference_supplies_hook_origin_and_token() {let inferred = infer_json_mcp_config(diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 08da1cf3..7430bb69 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -66,6 +66,7 @@ pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {McpClient::Pi => render_pi(&args)?,McpClient::Omp => render_omp(&args)?,McpClient::AntigravityCli => render_antigravity_cli(&args)?,+ McpClient::Zero => render_zero(&args)?,McpClient::VsCodeCopilot => render_vscode_copilot(&args)?,};println!("{snippet}");@@ -152,6 +153,10 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>.join(".gemini").join("antigravity-cli").join("mcp_config.json"),+ // Zero resolves its user config under $XDG_CONFIG_HOME falling back+ // to ~/.config; we target the default and --config-file covers+ // non-default XDG setups (same policy as OpenCode above).+ McpClient::Zero => home()?.join(".config").join("zero").join("config.json"),// VS Code MCP is workspace-scoped by default: `.vscode/mcp.json`// at the current workspace root. The user-profile alternative// lives under VS Code's profile-specific data dir; use VS@@ -211,7 +216,9 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {| McpClient::Omp| McpClient::AntigravityCli => Some(JsonMcpLocation::RootMcpServers),McpClient::OpenCode => Some(JsonMcpLocation::RootMcp),- McpClient::Openclaw => Some(JsonMcpLocation::NestedMcpServers),+ // Zero's config.json nests servers under `mcp.servers`, the same+ // shape OpenClaw uses.+ McpClient::Openclaw | McpClient::Zero => Some(JsonMcpLocation::NestedMcpServers),McpClient::VsCodeCopilot => Some(JsonMcpLocation::RootServers),McpClient::Codex | McpClient::Pi => None,}@@ -221,6 +228,7 @@ fn build_json_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {match args.client {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"),_ => build_mcp_entry(args),}@@ -387,6 +395,20 @@ fn build_mcp_entry_openclaw(args: &InstallMcpArgs) -> Result<serde_json::Value>Ok(serde_json::Value::Object(entry))}+/// Zero (Gitlawb/zero) MCP entry: native HTTP transport with optional+/// bearer headers — `internal/config/types.go`'s `MCPServerConfig` accepts+/// `type: "http"` + `url` + a `headers` map (issue #156).+fn build_mcp_entry_zero(args: &InstallMcpArgs) -> Result<serde_json::Value> {+ let bearer = bearer_header_value(args.auth_token.as_deref());+ let mut entry = serde_json::Map::new();+ entry.insert("type".into(), json!("http"));+ entry.insert("url".into(), json!(args.server_url));+ if let Some(b) = bearer {+ entry.insert("headers".into(), json!({"Authorization": b}));+ }+ Ok(serde_json::Value::Object(entry))+}+/// Insert / replace `[mcp_servers.<name>]` in a Codex `config.toml`.////// Codex parses both forms (block-style `[mcp_servers.foo]` and the@@ -614,6 +636,16 @@ fn render_openclaw(args: &InstallMcpArgs) -> Result<String> {))}+fn render_zero(args: &InstallMcpArgs) -> Result<String> {+ Ok(format!(+ "# Zero (Gitlawb/zero) — merge into ~/.config/zero/config.json\n\+ # ($XDG_CONFIG_HOME/zero/config.json on non-default XDG setups),\n\+ # or run `zero mcp add` / re-run this command with --apply.\n\+ {snippet}\n",+ snippet = render_json_mcp_fragment(args)?,+ ))+}+fn render_pi(args: &InstallMcpArgs) -> Result<String> {Ok(pi_mcp_render_guidance(args))}@@ -736,6 +768,7 @@ mod tests {McpClient::Pi => render_pi(&args).unwrap(),McpClient::Omp => render_omp(&args).unwrap(),McpClient::AntigravityCli => render_antigravity_cli(&args).unwrap(),+ McpClient::Zero => render_zero(&args).unwrap(),McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),}}@@ -754,6 +787,7 @@ mod tests {McpClient::Openclaw,McpClient::Omp,McpClient::AntigravityCli,+ McpClient::Zero,McpClient::VsCodeCopilot,] {let out = render_with_token(client);@@ -786,6 +820,7 @@ mod tests {McpClient::Openclaw,McpClient::Omp,McpClient::AntigravityCli,+ McpClient::Zero,McpClient::VsCodeCopilot,] {let out = render_for_test(client);@@ -809,6 +844,7 @@ mod tests {McpClient::Pi => render_pi(&args).unwrap(),McpClient::Omp => render_omp(&args).unwrap(),McpClient::AntigravityCli => render_antigravity_cli(&args).unwrap(),+ McpClient::Zero => render_zero(&args).unwrap(),McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),}}diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 6f5e36d1..08f8468e 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -169,6 +169,75 @@ pub(crate) fn build_grok_payload()}+/// Zero's hook events → ai-memory event names (issue #156). Zero has no+/// user-prompt or pre-compact equivalents; its `specialistStart`/`Stop`+/// map onto the subagent events the router already tracks for Claude Code.+pub(crate) const ZERO_EVENTS: [(&str, &str); 6] = [+ ("sessionStart", "session-start"),+ ("sessionEnd", "session-end"),+ ("beforeTool", "pre-tool-use"),+ ("afterTool", "post-tool-use"),+ ("specialistStart", "subagent-start"),+ ("specialistStop", "subagent-stop"),+];++/// Zero hooks.json config (issue #156): `{"enabled": true, "hooks": [..]}`+/// with one entry per lifecycle event. Zero executes `command` + `args`+/// directly (exec form, JSON payload on the hook's stdin) — no shell is+/// spawned, and our native `ai-memory hook` command reads exactly that+/// stdin shape, so Zero gets the local spool + OIDC fallback with zero+/// glue scripts. Entry ids carry the `ai-memory-` prefix so apply/uninstall+/// can merge around third-party hooks in the same file.+pub(crate) fn build_zero_hooks_config(+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> serde_json::Value {+ let exe = std::env::current_exe()+ .map(|p| p.to_string_lossy().into_owned())+ .unwrap_or_else(|_| "ai-memory".to_string());+ let hooks: Vec<serde_json::Value> = ZERO_EVENTS+ .iter()+ .map(|(zero_event, our_event)| {+ let mut args: Vec<String> = Vec::new();+ if let Some(dir) = data_dir {+ args.push("--data-dir".into());+ args.push(dir.to_string_lossy().into_owned());+ }+ args.extend(+ [+ "hook",+ "--event",+ our_event,+ "--agent",+ "zero",+ "--server-url",+ server_url,+ ]+ .map(String::from),+ );+ if let Some(token) = auth_token {+ args.push("--auth-token".into());+ args.push(token.to_string());+ }+ if let Some(strategy) = project_strategy {+ args.push("--project-strategy".into());+ args.push(strategy.to_string());+ }+ serde_json::json!({+ "id": format!("ai-memory-{our_event}"),+ "name": format!("ai-memory {our_event}"),+ "event": zero_event,+ "command": exe,+ "args": args,+ "enabled": true,+ })+ })+ .collect();+ serde_json::json!({ "enabled": true, "hooks": hooks })+}+/// Grok Build CLI hook payload for apply/render paths. Native commands are the/// default; explicit script fallback still points at the Grok script bundle.pub(crate) fn build_grok_payload_with_data_dir(diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex 3507d169..7998816e 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -66,6 +66,12 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {emit_extension_setup_hint(&args)?;return Ok(());}+ // Zero runs ai-memory's native `hook` command directly (exec form,+ // no scripts to stage) — setup-agent just prints the hooks.json.+ if matches!(args.agent, AgentChoice::Zero) {+ emit_zero(&args)?;+ return Ok(());+ }let Some(agent_sub) = args.agent.script_hook_subdir() else {bail!("internal: generated integration should have returned before staging hooks")};@@ -134,7 +140,11 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {&args,&[&ANTIGRAVITY_TOOL_EVENTS, &ANTIGRAVITY_LIFECYCLE_EVENTS],),- AgentChoice::OpenCode | AgentChoice::Pi | AgentChoice::Omp | AgentChoice::Openclaw => {+ AgentChoice::OpenCode+ | AgentChoice::Pi+ | AgentChoice::Omp+ | AgentChoice::Openclaw+ | AgentChoice::Zero => {bail!("internal: generated integration should have returned before emitting staged hooks")@@ -143,6 +153,35 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {Ok(())}+/// Print Zero's hooks.json (issue #156). No scripts are staged: Zero+/// executes the ai-memory binary directly with the JSON payload on stdin,+/// so the only artifact is the config itself. The binary must be reachable+/// on the host that runs Zero — for docker-wrapper setups install the+/// native binary or point `command` at the wrapper.+fn emit_zero(args: &SetupAgentArgs) -> Result<()> {+ let payload = crate::commands::render_shared::build_zero_hooks_config(+ &args.server_url,+ args.auth_token.as_deref(),+ None,+ None,+ );+ let serialized =+ serde_json::to_string_pretty(&payload).context("serializing Zero hook config")?;+ println!("# Zero (Gitlawb/zero) — merge into ~/.config/zero/hooks.json");+ println!("# The `command` must be an ai-memory binary reachable on the host");+ println!("# that runs Zero; prefer `ai-memory install-hooks --agent zero --apply`");+ println!("# from that host so the path is resolved for you.");+ if args.auth_token.is_some() {+ println!("# Treat hooks.json as sensitive (chmod 600).");+ }+ println!("# NOTE: Zero discards sessionStart stdout, so this config captures");+ println!("# but does not inject handoffs; recover them via the MCP");+ println!("# `memory_handoff_accept` tool.");+ println!();+ println!("{serialized}");+ Ok(())+}+fn normalise_hook_server_url(url: &str) -> String {url.trim().trim_end_matches('/').to_string()}diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex f2efd558..256c9574 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -31,6 +31,9 @@ enum RewriteOp {HooksJson,/// Antigravity CLI named hook group under top-level `ai-memory`.AntigravityHooksJson,+ /// Zero hooks.json — `hooks` array entries whose `id` carries the+ /// `ai-memory-` prefix.+ ZeroHooksJson,/// MCP JSON config for one client shape.McpJson(McpClient),/// Codex TOML MCP config.@@ -157,6 +160,19 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {);}+ let zero = install_hooks::zero_hooks_path()?;+ if zero.exists() {+ let content = std::fs::read_to_string(&zero)+ .with_context(|| format!("reading {}", zero.display()))?;+ let removal = strip_zero_hooks(&content)?;+ push_rewrite(+ &mut plan,+ zero,+ removal.removed_events,+ RewriteOp::ZeroHooksJson,+ );+ }+let plugin = install_hooks::opencode_plugin_path()?;push_generated_delete(&mut plan, plugin, DeleteKind::OpenCodePlugin);@@ -197,6 +213,7 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {Openclaw,Omp,AntigravityCli,+ Zero,VsCodeCopilot,] {let Ok(path) = install_mcp::mcp_config_path(client) else {@@ -333,6 +350,7 @@ fn apply_change(change: &PlannedChange, name: Option<&str>, url: &str) -> anyhowRewriteOp::AntigravityHooksJson => {strip_antigravity_hooks(&out)?.new_content}+ RewriteOp::ZeroHooksJson => strip_zero_hooks(&out)?.new_content,RewriteOp::McpJson(client) => strip_mcp_json(&out, client, name, url)?.0,RewriteOp::McpToml => strip_mcp_toml(&out, name, url)?.0,};@@ -582,6 +600,35 @@ fn strip_ai_memory_hooks(content: &str) -> Result<HookRemoval> {})}+/// Remove ai-memory's entries from Zero's hooks.json `hooks` array. Zero+/// hook entries are objects with an `id`; install writes ours with the+/// `ai-memory-` prefix (issue #156), so the prefix IS the ownership+/// signature — third-party hooks in the same file keep their ids and+/// survive untouched. The top-level `enabled` flag is left alone.+fn strip_zero_hooks(content: &str) -> Result<HookRemoval> {+ let mut removed_events = Vec::new();+ let new_content = mutate_json(content, |root| {+ let Some(hooks) = root.get_mut("hooks").and_then(|v| v.as_array_mut()) else {+ return Ok(());+ };+ hooks.retain(|hook| {+ let ours = hook+ .get("id")+ .and_then(|v| v.as_str())+ .is_some_and(|id| id.starts_with("ai-memory-"));+ if ours && let Some(id) = hook.get("id").and_then(|v| v.as_str()) {+ removed_events.push(id.to_string());+ }+ !ours+ });+ Ok(())+ })?;+ Ok(HookRemoval {+ new_content,+ removed_events,+ })+}+/// Remove ai-memory's named Antigravity CLI hook group entries. The group/// name alone is not enough to prove ownership; every removed entry must still/// carry ai-memory's hook command signature.@@ -688,7 +735,7 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {| McpClient::Omp| McpClient::AntigravityCli => Some(&["mcpServers"]),McpClient::OpenCode => Some(&["mcp"]),- McpClient::Openclaw => Some(&["mcp", "servers"]),+ McpClient::Openclaw | McpClient::Zero => Some(&["mcp", "servers"]),McpClient::VsCodeCopilot => Some(&["servers"]),McpClient::Codex | McpClient::Pi => None,}@@ -1034,6 +1081,34 @@ mod tests {assert!(out.removed_events.is_empty());}+ // Issue #156: uninstall removes only ai-memory's entries from Zero's+ // hooks.json, keyed by the id prefix, and leaves everything else alone.+ #[test]+ fn strip_zero_hooks_removes_only_prefixed_ids() {+ let content = r#"{"enabled": true, "hooks": [+ {"id": "my-custom-hook", "event": "beforeTool",+ "command": "/usr/bin/true", "args": [], "enabled": true},+ {"id": "ai-memory-session-start", "event": "sessionStart",+ "command": "/usr/local/bin/ai-memory", "args": ["hook"], "enabled": true},+ {"id": "ai-memory-post-tool-use", "event": "afterTool",+ "command": "/usr/local/bin/ai-memory", "args": ["hook"], "enabled": true}+ ]}"#;+ let removal = strip_zero_hooks(content).unwrap();+ assert_eq!(+ removal.removed_events,+ vec!["ai-memory-session-start", "ai-memory-post-tool-use"]+ );+ let root: serde_json::Value = serde_json::from_str(&removal.new_content).unwrap();+ let hooks = root["hooks"].as_array().unwrap();+ assert_eq!(hooks.len(), 1);+ assert_eq!(hooks[0]["id"], serde_json::json!("my-custom-hook"));+ assert_eq!(+ root["enabled"],+ serde_json::json!(true),+ "the top-level enabled flag is not ours to touch"+ );+ }+#[test]fn strip_antigravity_hooks_removes_only_signed_entries() {let content = r#"{diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 80db8a6f..e6f98e62 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -198,6 +198,8 @@ pub enum AgentKind {Pi,/// xAI Grok Build CLI (`grok`).Grok,+ /// Zero coding agent (Gitlawb/zero).+ Zero,/// Anything else (manual capture, future agents).Other,}@@ -218,6 +220,7 @@ impl AgentKind {Self::Omp => "omp",Self::Pi => "pi",Self::Grok => "grok",+ Self::Zero => "zero",Self::Other => "other",}}@@ -239,6 +242,7 @@ impl AgentKind {"pi" => Self::Pi,"omp" | "oh-my-pi" => Self::Omp,"grok" => Self::Grok,+ "zero" => Self::Zero,_ => Self::Other,}}@@ -248,7 +252,9 @@ impl AgentKind {/// `true` (Claude Code reads `hookSpecificOutput.additionalContext`).////// Grok ignores hook stdout on `SessionStart` (per Grok's hooks docs:- /// "For events like SessionStart or PostToolUse, stdout is ignored"), so+ /// "For events like SessionStart or PostToolUse, stdout is ignored"), and+ /// Zero's agent loop discards the sessionStart dispatch result entirely+ /// (`internal/agent/loop.go` ignores `Dispatch`'s return there), so/// the native hook must NOT fetch the handoff for it: the fetch is/// **destructive** (the server marks the handoff accepted) and the result/// would be discarded — silently losing the handoff. For such agents the@@ -258,7 +264,7 @@ impl AgentKind {/// should fail safe.#[must_use]pub fn session_start_injects_handoff(self) -> bool {- !matches!(self, Self::Grok | Self::Other)+ !matches!(self, Self::Grok | Self::Zero | Self::Other)}}@@ -302,6 +308,7 @@ mod tests {// Grok cannot inject the session-start handoff (ignores hook stdout);// every other agent can.assert!(!AgentKind::Grok.session_start_injects_handoff());+ assert!(!AgentKind::Zero.session_start_injects_handoff());assert!(AgentKind::ClaudeCode.session_start_injects_handoff());assert!(AgentKind::Codex.session_start_injects_handoff());assert!(!AgentKind::Other.session_start_injects_handoff());diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 7b2444e4..f78b93e5 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -2316,6 +2316,7 @@ impl AiMemoryServer {"cursor": "AGENTS.md","gemini_cli": "AGENTS.md","antigravity_cli": "AGENTS.md",+ "zero": "AGENTS.md","default": "AGENTS.md"},"managed_skills": managed_skills,diff --git a/docs/install.md b/docs/install.mdindex 3aa77907..aed35e2c 100644--- a/docs/install.md+++ b/docs/install.md@@ -9,7 +9,7 @@ path (docker + Claude Code). This page covers everything else:- [Arch Linux native packages (AUR)](#arch-linux-native-packages-aur)(systemd system service or user service)- [Configuring other agent CLIs](#configuring-other-agent-clis)- (Codex, OpenCode, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, OpenClaw, VS Code Copilot)+ (Codex, OpenCode, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, OpenClaw, VS Code Copilot)- [Installing hooks without docker](#installing-hooks-without-docker)(curl-based installer)- [Running ai-memory without docker](#running-ai-memory-without-docker)@@ -613,7 +613,7 @@ files owned by the user running the command. Prefer it as thedefault; reach for `setup-agent` only when your docker setup isknown not to remap UIDs.-### Cursor, Gemini CLI, Claude Desktop, OpenClaw, Antigravity CLI, Grok Build CLI, VS Code Copilot+### Cursor, Gemini CLI, Claude Desktop, OpenClaw, Antigravity CLI, Grok Build CLI, Zero, VS Code CopilotSee [**`docs/mcp-install.md`**](mcp-install.md) for the per-client MCPconfig file path and snippet, or one-shot it via:diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 3c14e21f..6cb1cacc 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -19,14 +19,14 @@This page documents how to register ai-memory as an MCP server withagent CLIs beyond the README quick start.-Claude Code, OpenAI Codex, Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, OpenClaw, OpenCode, and+Claude Code, OpenAI Codex, Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, OpenClaw, OpenCode, andOMP have automatic capture integrations (shell/PowerShell hooks forClaude Code / Codex / Cursor / Gemini CLI / Antigravity CLI / Grok Build CLI, TypeScript plugin/extensionfiles for OpenClaw / OpenCode / OMP) and are covered in the[main README](../README.md#quick-start). On native Windows, Claude Code usesGit Bash `.sh` hooks rather than the PowerShell default used by other-script-hook agents. Grok captures lifecycle events, but it ignores-SessionStart stdout, so ai-memory does not auto-inject handoffs for Grok.+script-hook agents. Grok and Zero capture lifecycle events, but both ignore+SessionStart stdout, so ai-memory does not auto-inject handoffs for them.Claude Desktop and VS Code Copilot are **MCP-only** here: they exposelong-term memory to their LLMs via ai-memory's MCP tools@@ -393,6 +393,43 @@ The rendered hooks config looks like:---+## Zero (Gitlawb/zero)++Zero manages MCP servers in `~/.config/zero/config.json`+(`$XDG_CONFIG_HOME/zero/config.json` on non-default XDG setups) under an+`mcp.servers` map, with native HTTP transport + bearer headers:++```bash+ai-memory install-mcp --client zero --apply \+ --server-url "http://homelab:49374/mcp" --auth-token "$TOKEN"+```++which merges:++```json+{+ "mcp": {+ "servers": {+ "ai-memory": {+ "type": "http",+ "url": "http://homelab:49374/mcp",+ "headers": { "Authorization": "Bearer <token>" }+ }+ }+ }+}+```++Lifecycle capture is separate and script-free: `ai-memory install-hooks+--agent zero --apply` merges exec-form entries (the native `ai-memory hook`+command + args, JSON payload on stdin — no shell) into+`~/.config/zero/hooks.json`, covering `sessionStart`/`sessionEnd`/+`beforeTool`/`afterTool` plus `specialistStart`/`specialistStop` (mapped to+ai-memory's subagent events). Zero discards `sessionStart` hook stdout, so+capture and session-end handoff *creation* work, but handoff *injection*+does not — ask Zero to call `memory_handoff_accept` at the start of a+resumed session.+## OpenClaw**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported via a native@@ -553,7 +590,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, Cursor, Gemini CLI, Grok Build CLI, 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. |+| **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, 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 / 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). |OpenCode uses its official `session.deleted` plugin event for true session-end