Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
cleanup pass on install/mcp/hooks code
AkitaOnRails1a1dd99e3772
diff --git a/crates/ai-memory-cli/src/commands/apply_shared.rs b/crates/ai-memory-cli/src/commands/apply_shared.rsindex f3f6ac6e..b5bb74e0 100644--- a/crates/ai-memory-cli/src/commands/apply_shared.rs+++ b/crates/ai-memory-cli/src/commands/apply_shared.rs@@ -13,10 +13,9 @@//! 5. Writes the new content to a sibling tempfile, fsyncs, then//! renames over the original (POSIX atomic).//!-//! All three M22 file-mutating subcommands (install-mcp --apply,-//! install-hooks --apply, install-instructions) route through this-//! function. The mutator decides the format (JSON / TOML / markdown)-//! and the idempotency rule; the I/O atomics live here.+//! Every `--apply` mode (install-mcp, install-hooks, install-instructions, …)+//! routes through this function. The mutator decides the format (JSON /+//! TOML / markdown) and the idempotency rule; the I/O atomics live here.use std::fs;use std::io::Write as _;diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex a083c4ba..fd79ffb4 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -1,11 +1,18 @@-//! `ai-memory install-hooks` — print the suggested lifecycle-hook-//! configuration for the chosen agent CLI.+//! `ai-memory install-hooks` — install lifecycle-hook configuration for+//! the chosen agent CLI.//!-//! In M3 this is *non-destructive*: we render the JSON snippet the user-//! should merge into their agent CLI's settings file, plus the absolute-//! paths to the vendored shell scripts. We intentionally do not mutate-//! `~/.claude/settings.json` automatically — agent CLI hook formats are-//! still in flux and bad merges are very user-visible.+//! Two modes:+//!+//! - **Default (print):** renders the JSON/TOML/TypeScript snippet the+//! user should merge into their agent CLI's settings file, plus the+//! absolute paths to the vendored shell scripts. Nothing is written to+//! disk.+//!+//! - **`--apply` (recommended):** performs an atomic in-place merge into+//! the target config file. A timestamped backup (`.bak-<unix-ts>`) is+//! written next to the file before any mutation. Re-runs are+//! idempotent — a second `--apply` with unchanged content is a no-op+//! and produces no backup.use std::fs;use std::path::{Path, PathBuf};@@ -24,9 +31,13 @@ use crate::config::Config;////// # Errors/// Returns an error if the hook script directory cannot be located.-pub fn run(_config: &Config, args: InstallHooksArgs) -> Result<()> {+pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- let auth = args.auth_token.as_deref();+ let auth_token_owned = args+ .auth_token+ .clone()+ .or_else(|| config.auth.bearer_token.clone());+ let auth = auth_token_owned.as_deref();if args.apply {return match args.agent {AgentChoice::ClaudeCode => {@@ -164,16 +175,47 @@ fn apply_to_codex_settings(.join("hooks.json"),};let staged = stage_hook_scripts(hooks_dir, "codex")?;+ let outcome = merge_codex_hooks(&staged, server_url, auth_token, &path)?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ // First-time trust reminder. Codex's TUI flags new/changed+ // hooks on startup; users must explicitly trust them before+ // they fire.+ if !matches!(outcome, ApplyOutcome::NoOp) {+ println!();+ println!("Codex requires explicit trust for new hooks. Next time you start `codex`:");+ println!(" → the TUI will surface 'Hooks need review' for each new event");+ println!(" → choose 'Trust all and continue' (or trust individually)");+ println!("To bypass the prompt for automated installs, start with");+ println!("`codex --dangerously-bypass-hook-trust` (review hook scripts first).");+ }+ Ok(())+}++fn merge_codex_hooks(+ staged: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ config_path: &Path,+) -> Result<ApplyOutcome> {// Build the Codex-flavoured payload. The JSON shape is identical// to Claude Code's matcher + nested hooks form — only the event// list differs (no `SessionEnd`, which Codex doesn't recognise).- let payload = build_codex_payload(&staged, server_url, auth_token);+ let payload = build_codex_payload(staged, server_url, auth_token);let our_hooks = payload.get("hooks").and_then(|v| v.as_object()).context("internal: payload builder didn't return a hooks object")?.clone();- let outcome = apply_atomic(&path, |existing| {+ apply_atomic(config_path, |existing| {mutate_json(existing, |root| {let hooks = root.entry("hooks")@@ -191,29 +233,7 @@ fn apply_to_codex_settings(}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",- }- );- // First-time trust reminder. Codex's TUI flags new/changed- // hooks on startup; users must explicitly trust them before- // they fire.- if !matches!(outcome, ApplyOutcome::NoOp) {- println!();- println!("Codex requires explicit trust for new hooks. Next time you start `codex`:");- println!(" → the TUI will surface 'Hooks need review' for each new event");- println!(" → choose 'Trust all and continue' (or trust individually)");- println!("To bypass the prompt for automated installs, start with");- println!("`codex --dangerously-bypass-hook-trust` (review hook scripts first).");- }- Ok(())+ })}/// Mutate `~/.cursor/hooks.json` (creating it if absent) so Cursor's@@ -249,13 +269,33 @@ fn apply_to_cursor_settings(.join("hooks.json"),};let staged = stage_hook_scripts(hooks_dir, "cursor")?;- let payload = build_profile_payload(&CURSOR_PROFILE, &staged, server_url, auth_token);+ let outcome = merge_cursor_hooks(&staged, server_url, auth_token, &path)?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ Ok(())+}++fn merge_cursor_hooks(+ staged: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ config_path: &Path,+) -> Result<ApplyOutcome> {+ let payload = build_profile_payload(&CURSOR_PROFILE, staged, server_url, auth_token);let our_hooks = payload.get("hooks").and_then(|v| v.as_object()).context("internal: payload builder didn't return a hooks object")?.clone();- let outcome = apply_atomic(&path, |existing| {+ apply_atomic(config_path, |existing| {mutate_json(existing, |root| {// Cursor requires "version": 1 at the top level.// Overwrite unconditionally — the schema is versioned@@ -272,18 +312,7 @@ fn apply_to_cursor_settings(}Ok(())})- })?;- println!(- "✓ {} {} ({})",- outcome.verb(),- path.display(),- match outcome {- ApplyOutcome::Created => "new file",- ApplyOutcome::Updated => "backup written next to it",- ApplyOutcome::NoOp => "already up to date",- }- );- Ok(())+ })}/// Mutate `~/.gemini/settings.json` so Gemini CLI fires the ai-memory@@ -315,13 +344,33 @@ fn apply_to_gemini_settings(.join("settings.json"),};let staged = stage_hook_scripts(hooks_dir, "gemini-cli")?;- let payload = build_profile_payload(&GEMINI_PROFILE, &staged, server_url, auth_token);+ let outcome = merge_gemini_hooks(&staged, server_url, auth_token, &path)?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ Ok(())+}++fn merge_gemini_hooks(+ staged: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ config_path: &Path,+) -> Result<ApplyOutcome> {+ let payload = build_profile_payload(&GEMINI_PROFILE, staged, server_url, auth_token);let our_hooks = payload.get("hooks").and_then(|v| v.as_object()).context("internal: payload builder didn't return a hooks object")?.clone();- let outcome = apply_atomic(&path, |existing| {+ apply_atomic(config_path, |existing| {mutate_json(existing, |root| {// Gemini's settings.json mixes MCP servers, hooks, and// other config under one document. Get-or-create the@@ -336,18 +385,7 @@ fn apply_to_gemini_settings(}Ok(())})- })?;- println!(- "✓ {} {} ({})",- outcome.verb(),- path.display(),- match outcome {- ApplyOutcome::Created => "new file",- ApplyOutcome::Updated => "backup written next to it",- ApplyOutcome::NoOp => "already up to date",- }- );- Ok(())+ })}/// Generate an OpenCode plugin at `~/.config/opencode/plugins/ai-memory.ts`.@@ -386,12 +424,7 @@ fn apply_to_opencode_plugin(.join("ai-memory.ts"),};let staged = stage_hook_scripts(hooks_dir, "opencode")?;- let script = |name: &str| {- staged- .join(name)- .to_string_lossy()- .into_owned()- };+ let script = |name: &str| staged.join(name).to_string_lossy().into_owned();let token_line = auth_token.map(|t| format!("const TOKEN = {};\n", ts_string_literal(t))).unwrap_or_else(|| "const TOKEN = null;\n".to_string());@@ -593,10 +626,7 @@ fn stage_hook_scripts(source_dir: &Path, agent_label: &str) -> Result<PathBuf> {copied += 1;}- eprintln!(- "✓ staged {copied} hook script(s) → {}",- dest_root.display()- );+ eprintln!("✓ staged {copied} hook script(s) → {}", dest_root.display());Ok(dest_root)}@@ -683,3 +713,264 @@ fn render_claude_code(hooks_dir: &Path, server_url: &str, auth_token: Option<&stprintln!("{serialized}");Ok(())}++#[cfg(test)]+mod tests {+ use super::*;+ use std::fs;+ use tempfile::TempDir;++ fn stub_scripts(dir: &Path, names: &[&str]) {+ for name in names {+ let p = dir.join(name);+ fs::write(&p, "#!/bin/sh\n").unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mut perms = fs::metadata(&p).unwrap().permissions();+ perms.set_mode(0o755);+ fs::set_permissions(&p, perms).unwrap();+ }+ }+ }++ // ----------------------------------------------------------------+ // Cursor tests+ // ----------------------------------------------------------------++ #[test]+ fn cursor_preserves_existing_user_hooks_and_adds_ours() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(+ hooks_tmp.path(),+ &[+ "session-start.sh",+ "session-end.sh",+ "user-prompt-submit.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "pre-compact.sh",+ "stop.sh",+ ],+ );++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("hooks.json");+ // Pre-existing settings with a user hook under a different event.+ fs::write(+ &config_path,+ r#"{"version":1,"hooks":{"userHook":"something"}}"#,+ )+ .unwrap();++ merge_cursor_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ &config_path,+ )+ .unwrap();++ let parsed: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ // User's hook survives.+ assert_eq!(parsed["hooks"]["userHook"], "something");+ // Our hooks are present.+ assert!(+ parsed["hooks"]["sessionStart"].is_array(),+ "sessionStart hook should be present"+ );+ assert!(+ parsed["hooks"]["preToolUse"].is_array(),+ "preToolUse hook should be present"+ );+ assert_eq!(+ parsed["version"], 1,+ "version: 1 must be set at the top level"+ );+ }++ #[test]+ fn cursor_apply_is_idempotent() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(+ hooks_tmp.path(),+ &[+ "session-start.sh",+ "session-end.sh",+ "user-prompt-submit.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "pre-compact.sh",+ "stop.sh",+ ],+ );++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("hooks.json");++ let first = merge_cursor_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ &config_path,+ )+ .unwrap();+ assert_ne!(+ first,+ ApplyOutcome::NoOp,+ "first apply should not be a no-op"+ );++ let second = merge_cursor_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ &config_path,+ )+ .unwrap();+ assert_eq!(second, ApplyOutcome::NoOp, "second apply must be a no-op");+ }++ // ----------------------------------------------------------------+ // Codex tests+ // ----------------------------------------------------------------++ #[test]+ fn codex_preserves_unrelated_keys_and_adds_hooks() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(+ hooks_tmp.path(),+ &[+ "session-start.sh",+ "user-prompt-submit.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "pre-compact.sh",+ "stop.sh",+ ],+ );++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("hooks.json");+ // Pre-existing settings with an unrelated key.+ fs::write(&config_path, r#"{"theme":"dark"}"#).unwrap();++ merge_codex_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ &config_path,+ )+ .unwrap();++ let parsed: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ // Unrelated key survives.+ assert_eq!(parsed["theme"], "dark");+ // Our hooks are present.+ assert!(+ parsed["hooks"]["SessionStart"].is_array(),+ "SessionStart hook should be present"+ );+ }++ #[test]+ fn codex_removes_stale_session_end_key() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(+ hooks_tmp.path(),+ &[+ "session-start.sh",+ "user-prompt-submit.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "pre-compact.sh",+ "stop.sh",+ ],+ );++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("hooks.json");+ // Simulate a file with a stale SessionEnd entry from a previous+ // install that mistakenly included the Claude-Code-only event.+ fs::write(+ &config_path,+ r#"{"hooks":{"SessionEnd":[{"matcher":"","hooks":[{"type":"command","command":"stale.sh"}]}]}}"#,+ )+ .unwrap();++ merge_codex_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ &config_path,+ )+ .unwrap();++ let parsed: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ // SessionEnd must be gone.+ assert!(+ parsed["hooks"].get("SessionEnd").is_none(),+ "stale SessionEnd must be removed; got: {:?}",+ parsed["hooks"]+ );+ // Our hooks are present.+ assert!(parsed["hooks"]["SessionStart"].is_array());+ }++ // ----------------------------------------------------------------+ // Gemini tests+ // ----------------------------------------------------------------++ #[test]+ fn gemini_preserves_mcp_servers_and_adds_hooks() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(+ hooks_tmp.path(),+ &[+ "session-start.sh",+ "session-end.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "pre-compact.sh",+ ],+ );++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("settings.json");+ // Pre-existing settings with an mcpServers entry.+ fs::write(&config_path, r#"{"mcpServers":{"foo":{}}}"#).unwrap();++ merge_gemini_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ &config_path,+ )+ .unwrap();++ let parsed: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ // The pre-existing mcpServers.foo survives.+ assert!(+ parsed["mcpServers"]["foo"].is_object(),+ "mcpServers.foo must survive"+ );+ // Our hooks are present with Gemini-specific event names.+ assert!(+ parsed["hooks"]["SessionStart"].is_array(),+ "SessionStart hook should be present"+ );+ assert!(+ parsed["hooks"]["BeforeTool"].is_array(),+ "BeforeTool hook should be present"+ );+ // Claude-Code-only events must NOT appear.+ assert!(+ parsed["hooks"].get("PreToolUse").is_none(),+ "PreToolUse must not appear in Gemini config"+ );+ }+}diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 18d5fcd9..20246fc2 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -22,7 +22,7 @@ use serde_json::json;use crate::cli::{InstallMcpArgs, McpClient};use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json, mutate_toml};-use crate::commands::render_shared::bearer_header_value as bearer_header_value_shared;+use crate::commands::render_shared::bearer_header_value;use crate::config::Config;/// Run the `install-mcp` subcommand.@@ -30,7 +30,11 @@ use crate::config::Config;/// # Errors/// Returns an error if JSON serialisation fails (should never happen/// for our handcrafted values).-pub fn run(_config: &Config, args: InstallMcpArgs) -> Result<()> {+pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {+ let args = InstallMcpArgs {+ auth_token: args.auth_token.or_else(|| config.auth.bearer_token.clone()),+ ..args+ };if args.apply {if matches!(args.client, McpClient::Pi) {bail!(@@ -176,7 +180,7 @@ fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {/// Gemini CLI — they all accept `mcpServers.<name>` with `url` or/// `httpUrl` plus optional `headers`. Returns the per-client variant.fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {- let bearer = bearer_header_value_shared(args.auth_token.as_deref());+ let bearer = bearer_header_value(args.auth_token.as_deref());let mut entry = serde_json::Map::new();match args.client {McpClient::ClaudeCode => {@@ -216,7 +220,7 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {}fn build_mcp_entry_opencode(args: &InstallMcpArgs) -> Result<serde_json::Value> {- let bearer = bearer_header_value_shared(args.auth_token.as_deref());+ let bearer = bearer_header_value(args.auth_token.as_deref());let mut entry = serde_json::Map::new();entry.insert("type".into(), json!("remote"));entry.insert("url".into(), json!(args.server_url));@@ -228,7 +232,7 @@ fn build_mcp_entry_opencode(args: &InstallMcpArgs) -> Result<serde_json::Value>}fn build_mcp_entry_openclaw(args: &InstallMcpArgs) -> Result<serde_json::Value> {- let bearer = bearer_header_value_shared(args.auth_token.as_deref());+ let bearer = bearer_header_value(args.auth_token.as_deref());let mut entry = serde_json::Map::new();entry.insert("url".into(), json!(args.server_url));entry.insert("transport".into(), json!("streamable-http"));@@ -238,14 +242,6 @@ fn build_mcp_entry_openclaw(args: &InstallMcpArgs) -> Result<serde_json::Value>Ok(serde_json::Value::Object(entry))}-/// Thin shim so the renderers can call `bearer_header_value(args)`-/// without spelling out `args.auth_token.as_deref()` every time.-/// Delegates to the shared `render_shared::bearer_header_value` which-/// takes a raw `Option<&str>` so other commands can call it too.-fn bearer_header_value(args: &InstallMcpArgs) -> Option<String> {- bearer_header_value_shared(args.auth_token.as_deref())-}-/// Insert / replace `[mcp_servers.<name>]` in a Codex `config.toml`.////// Codex parses both forms (block-style `[mcp_servers.foo]` and the@@ -321,7 +317,7 @@ fn codex_upsert_mcp_server(// override per-tool — see Codex's `[mcp_servers.X.tools]`// map.server["default_tools_approval_mode"] = value("approve");- if let Some(b) = bearer_header_value_shared(args.auth_token.as_deref()) {+ if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {let mut headers = Table::new();headers["Authorization"] = value(b);server["http_headers"] = Item::Table(headers);@@ -342,7 +338,7 @@ fn codex_upsert_mcp_server(}fn render_claude_code(args: &InstallMcpArgs) -> Result<String> {- let bearer = bearer_header_value(args);+ let bearer = bearer_header_value(args.auth_token.as_deref());let cli_line = if let Some(b) = &bearer {format!("claude mcp add --transport http {name} {url} \\\n --header \"Authorization: {b}\"",@@ -401,7 +397,7 @@ fn render_codex(args: &InstallMcpArgs) -> String {name = args.name,url = args.server_url,);- if let Some(b) = bearer_header_value(args) {+ if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {out.push_str(&format!("\n[mcp_servers.{name}.http_headers]\n\Authorization = \"{b}\"\n\@@ -420,7 +416,7 @@ fn render_opencode(args: &InstallMcpArgs) -> Result<String> {entry.insert("type".into(), json!("remote"));entry.insert("url".into(), json!(args.server_url));entry.insert("enabled".into(), json!(true));- if let Some(b) = bearer_header_value(args) {+ if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {entry.insert("headers".into(), json!({"Authorization": b}));}Ok(format!(@@ -435,7 +431,7 @@ fn render_opencode(args: &InstallMcpArgs) -> Result<String> {fn render_cursor(args: &InstallMcpArgs) -> Result<String> {let mut entry = serde_json::Map::new();entry.insert("url".into(), json!(args.server_url));- if let Some(b) = bearer_header_value(args) {+ if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {entry.insert("headers".into(), json!({"Authorization": b}));}Ok(format!(@@ -458,7 +454,7 @@ fn render_claude_desktop(args: &InstallMcpArgs) -> Result<String> {// mcp-remote's --header flag is how we plumb the Authorization// through Claude Desktop's stdio-only config.let mut cmd_args = vec![json!("-y"), json!("mcp-remote"), json!(args.server_url)];- if let Some(b) = bearer_header_value(args) {+ if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {cmd_args.push(json!("--header"));cmd_args.push(json!(format!("Authorization: {b}")));}@@ -490,7 +486,7 @@ fn render_gemini_cli(args: &InstallMcpArgs) -> Result<String> {let mut entry = serde_json::Map::new();entry.insert("httpUrl".into(), json!(args.server_url));entry.insert("timeout".into(), json!(5000));- if let Some(b) = bearer_header_value(args) {+ if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {entry.insert("headers".into(), json!({"Authorization": b}));}Ok(format!(@@ -509,7 +505,7 @@ fn render_openclaw(args: &InstallMcpArgs) -> Result<String> {let mut entry = serde_json::Map::new();entry.insert("url".into(), json!(args.server_url));entry.insert("transport".into(), json!("streamable-http"));- if let Some(b) = bearer_header_value(args) {+ if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {entry.insert("headers".into(), json!({"Authorization": b}));}Ok(format!(diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 15f87447..d2dd9c41 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -24,7 +24,7 @@ use serde_json::json;/// `(event-name-in-Claude-Code-settings, hook-script-filename)`.////// Adding a hook event means updating this list AND adding the-/// matching `hooks/{claude-code,codex,opencode}/<filename>` script —+/// matching `hooks/{claude-code,codex,cursor,gemini-cli,opencode}/<filename>` script —/// the e2e test + the generator in `bin/regen-hooks` (if added) both/// key off this constant.pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 7] = [@@ -74,7 +74,13 @@ pub(crate) fn build_claude_code_payload(server_url: &str,auth_token: Option<&str>,) -> serde_json::Value {- build_hook_payload(&CLAUDE_CODE_EVENTS, emit_root, server_url, auth_token)+ build_hook_payload(+ &CLAUDE_CODE_EVENTS,+ emit_root,+ server_url,+ auth_token,+ HookShape::Nested,+ )}/// Different agents nest hook entries differently. Two shapes@@ -155,16 +161,6 @@ pub(crate) const GEMINI_EVENTS: [(&str, &str); 5] = [/// Per-agent profile constants. Add a new agent by adding one of/// these + a script-dir name + a config-file path resolver — the/// payload-build path picks up the rest from `shape`.-// Defined for completeness alongside the other profiles; the Claude-// Code apply path still goes through `build_claude_code_payload`-// (kept stable for the existing setup-agent emitter). Marked-// `allow(dead_code)` so cargo doesn't complain — anyone adding a-// new caller can switch to `build_profile_payload(&CLAUDE_CODE_PROFILE, …)`.-#[allow(dead_code)]-pub(crate) const CLAUDE_CODE_PROFILE: HookProfile = HookProfile {- events: &CLAUDE_CODE_EVENTS,- shape: HookShape::Nested,-};pub(crate) const CODEX_PROFILE: HookProfile = HookProfile {events: &CODEX_EVENTS,shape: HookShape::Nested,@@ -198,7 +194,13 @@ pub(crate) fn build_profile_payload(server_url: &str,auth_token: Option<&str>,) -> serde_json::Value {- build_hook_payload_inner(profile.events, profile.shape, emit_root, server_url, auth_token)+ build_hook_payload(+ profile.events,+ emit_root,+ server_url,+ auth_token,+ profile.shape,+ )}fn build_hook_payload(@@ -206,16 +208,7 @@ fn build_hook_payload(emit_root: &Path,server_url: &str,auth_token: Option<&str>,-) -> serde_json::Value {- build_hook_payload_inner(events, HookShape::Nested, emit_root, server_url, auth_token)-}--fn build_hook_payload_inner(- events: &[(&str, &str)],shape: HookShape,- emit_root: &Path,- server_url: &str,- auth_token: Option<&str>,) -> serde_json::Value {let mut hooks_block = serde_json::Map::new();for (event, script) in events {@@ -344,8 +337,12 @@ mod tests {// Flat shape: no inner `hooks: [...]` array; each event// maps to an array of {type, command, matcher} entries.let root = PathBuf::from("/host/hooks/cursor");- let v =- build_profile_payload(&CURSOR_PROFILE, &root, "http://localhost:49374", Some("tok"));+ let v = build_profile_payload(+ &CURSOR_PROFILE,+ &root,+ "http://localhost:49374",+ Some("tok"),+ );let session_start = v.pointer("/hooks/sessionStart/0").and_then(|e| e.as_object())@@ -390,8 +387,12 @@ mod tests {// names (BeforeTool / AfterTool / PreCompress; no// UserPromptSubmit, no Stop).let root = PathBuf::from("/host/hooks/gemini-cli");- let v =- build_profile_payload(&GEMINI_PROFILE, &root, "http://localhost:49374", Some("tok"));+ let v = build_profile_payload(+ &GEMINI_PROFILE,+ &root,+ "http://localhost:49374",+ Some("tok"),+ );let session_start = v.pointer("/hooks/SessionStart/0").and_then(|e| e.as_object())@@ -412,10 +413,25 @@ mod tests {.and_then(|h| h.as_object()).map(|o| o.keys().map(String::as_str).collect()).unwrap_or_default();- for expected in ["SessionStart", "SessionEnd", "BeforeTool", "AfterTool", "PreCompress"] {- assert!(events.contains(&expected), "missing Gemini event {expected}");+ for expected in [+ "SessionStart",+ "SessionEnd",+ "BeforeTool",+ "AfterTool",+ "PreCompress",+ ] {+ assert!(+ events.contains(&expected),+ "missing Gemini event {expected}"+ );}- for unexpected in ["PreToolUse", "PostToolUse", "UserPromptSubmit", "Stop", "PreCompact"] {+ for unexpected in [+ "PreToolUse",+ "PostToolUse",+ "UserPromptSubmit",+ "Stop",+ "PreCompact",+ ] {assert!(!events.contains(&unexpected),"Gemini should NOT have CC-only event {unexpected}; got {events:?}"diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex 5140db0c..cdb61022 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -44,7 +44,11 @@ use crate::config::Config;/// Returns an error if the source bundle can't be located, the/// destination directory can't be created, any script copy fails,/// or the JSON config can't be serialised.-pub fn run(_config: &Config, args: SetupAgentArgs) -> Result<()> {+pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {+ let args = SetupAgentArgs {+ auth_token: args.auth_token.or_else(|| config.auth.bearer_token.clone()),+ ..args+ };let agent_sub = match args.agent {AgentChoice::ClaudeCode => "claude-code",AgentChoice::Codex => "codex",@@ -111,7 +115,10 @@ pub fn run(_config: &Config, args: SetupAgentArgs) -> Result<()> {match args.agent {AgentChoice::ClaudeCode => emit_claude_code(&emit_root, &args)?,- AgentChoice::Codex | AgentChoice::Cursor | AgentChoice::GeminiCli | AgentChoice::OpenCode => {+ AgentChoice::Codex+ | AgentChoice::Cursor+ | AgentChoice::GeminiCli+ | AgentChoice::OpenCode => {emit_other(&emit_root, agent_sub, &args);}AgentChoice::Openclaw => {diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex c0b5e4f1..76036a62 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -464,6 +464,3 @@ const fn importance_for(event: HookEvent) -> u8 {HookEvent::Notification | HookEvent::Other => 3,}}--#[allow(dead_code)]-fn _agent_kind_marker(_k: AgentKind) {}