Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(install): align hooks with remote server config
AkitaOnRails0a11e13a785f
diff --git a/AGENTS.md b/AGENTS.mdindex d49dc7a9..450ae80f 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -4,8 +4,10 @@This project uses [ai-memory](https://github.com/akitaonrails/ai-memory)for cross-session continuity. **Lifecycle hooks already capture everyprompt + tool call automatically.** You never need to manually write-notes; the SessionStart hook auto-fetches pending handoffs and the-SessionEnd hook auto-consolidates. Just *use* the read tools.+routine notes; the SessionStart hook auto-fetches pending handoffs and+the SessionEnd hook auto-consolidates. Only write a durable wiki page+when the user explicitly asks to remember or annotate something+permanently.### When to reach for each tool@@ -21,8 +23,9 @@ match the intent to the tool. They do not need to name the tool.| "catch me up" / "I've been away" / "what's important right now?" / open-ended exploration | `memory_explore` || "where did we leave off?" — and you see a `📥 ai-memory: pending handoff` block in your context | already done — answer from that block; do NOT re-call `memory_handoff_accept` || "where did we leave off?" — and no such block is visible | `memory_handoff_accept` (rare; the SessionStart hook usually got there first) |-| "save context for the next session" / wrapping up | `memory_handoff_begin` (terse summary; put detail in `open_questions` + `next_steps` bullets) |+| "save context for the next session" / wrapping up | `memory_handoff_begin` (single-use handoff; terse summary; put detail in `open_questions` + `next_steps` bullets) || "consolidate this session" / "compile what we learned" (usually automatic) | `memory_consolidate` |+| "remember this permanently" / "save a note" / "add an annotation" / durable project knowledge | `memory_write_page` (write a wiki page; do **not** use handoff for permanent notes) || "audit the wiki" / "find contradictions" / "what rules should we add?" | `memory_lint` || "prune old pages" / "memory cleanup" | `memory_forget_sweep` |@@ -63,6 +66,9 @@ without disturbing the rest of the file.- When a change affects user-visible behavior, installation, supportedplatforms, supported agents, providers, or deployment, update`CHANGELOG.md` and the README/docs support references in the same commit.+- When the MCP tool surface changes, update `MEMORY_INSTRUCTIONS`,+ `ai_memory_core::SNIPPET_BODY`, README/docs tool references, and regression+ tests that assert every tool appears in both prompt surfaces.## Rust Engineering Rulesdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4d23e9d8..2aa7a526 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,7 +6,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).## [Unreleased]+### Added+- `memory_write_page` MCP tool for explicit durable annotations, so agents can+ write permanent wiki knowledge without abusing single-use handoffs.+### Fixed+- `install-mcp`, `install-hooks`, and `setup-agent` now honor configured+ `AI_MEMORY_SERVER_URL` defaults; `install-hooks` also reuses an existing+ ai-memory MCP entry when present, preventing remote MCP setups from+ regenerating loopback-only lifecycle hooks during installs/upgrades.- Filesystem watcher now reindexes a project when backends report only aparent-directory event, improving external editor capture on macOS/FSEvents.- OpenAI strict structured-output schema normalization now strips generateddiff --git a/CLAUDE.md b/CLAUDE.mdindex 2db466c6..5a186687 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -68,7 +68,11 @@ tests/ # workspace integration tests.invariant.5. **Add a unit test before the implementation, not after.** Especially forparsers, ID derivation, and any retention/decay math.-6. **Don't refactor outside the milestone.** Touch only what the current+6. **MCP tool surface changes must update every prompt surface.** When adding,+ removing, or renaming an MCP tool, update `MEMORY_INSTRUCTIONS`,+ `ai_memory_core::SNIPPET_BODY`, README/docs tool references, and regression+ tests that assert every tool appears in both prompt surfaces.+7. **Don't refactor outside the milestone.** Touch only what the currentmilestone requires; resist scope creep.## Cross-cutting invariants (carved in, never violated)@@ -230,8 +234,10 @@ Live progress is tracked via the TaskList tool inside Claude Code sessions.This project uses [ai-memory](https://github.com/akitaonrails/ai-memory)for cross-session continuity. **Lifecycle hooks already capture everyprompt + tool call automatically.** You never need to manually write-notes; the SessionStart hook auto-fetches pending handoffs and the-SessionEnd hook auto-consolidates. Just *use* the read tools.+routine notes; the SessionStart hook auto-fetches pending handoffs and+the SessionEnd hook auto-consolidates. Only write a durable wiki page+when the user explicitly asks to remember or annotate something+permanently.### When to reach for each tool@@ -247,8 +253,9 @@ match the intent to the tool. They do not need to name the tool.| "catch me up" / "I've been away" / "what's important right now?" / open-ended exploration | `memory_explore` || "where did we leave off?" — and you see a `📥 ai-memory: pending handoff` block in your context | already done — answer from that block; do NOT re-call `memory_handoff_accept` || "where did we leave off?" — and no such block is visible | `memory_handoff_accept` (rare; the SessionStart hook usually got there first) |-| "save context for the next session" / wrapping up | `memory_handoff_begin` (terse summary; put detail in `open_questions` + `next_steps` bullets) |+| "save context for the next session" / wrapping up | `memory_handoff_begin` (single-use handoff; terse summary; put detail in `open_questions` + `next_steps` bullets) || "consolidate this session" / "compile what we learned" (usually automatic) | `memory_consolidate` |+| "remember this permanently" / "save a note" / "add an annotation" / durable project knowledge | `memory_write_page` (write a wiki page; do **not** use handoff for permanent notes) || "audit the wiki" / "find contradictions" / "what rules should we add?" | `memory_lint` || "prune old pages" / "memory cleanup" | `memory_forget_sweep` |diff --git a/README.md b/README.mdindex 7cc334bc..860db046 100644--- a/README.md+++ b/README.md@@ -167,15 +167,18 @@ On Linux/macOS, that's it. Start a Claude Code session as usual - everyprompt and tool call now lands in ai-memory, and the next session youopen in this project will see a handoff with where you left off.-The `install-mcp` / `install-hooks` commands default to-`http://127.0.0.1:49374` (matching the server above) and no bearer-token. Both are idempotent - re-runs replace ai-memory's entry,-preserve every other server / hook you have configured, and write a-timestamped `.bak-<ts>` next to the file before each modifying-write. The hook scripts are staged into-`~/.local/share/ai-memory/hooks/<agent>/` automatically; re-running-overwrites them so future image updates ship updated hooks. Drop-`--apply` to print the snippet instead of mutating.+The `install-mcp` / `install-hooks` commands use+`AI_MEMORY_SERVER_URL` / `AI_MEMORY_AUTH_TOKEN` when set; otherwise+they default to `http://127.0.0.1:49374` (matching the server above)+and no bearer token. If hooks are installed after an ai-memory MCP+entry already exists, `install-hooks` reuses that endpoint so a remote+MCP setup cannot silently regenerate loopback-only hooks. Both commands+are idempotent - re-runs replace ai-memory's entry, preserve every+other server / hook you have configured, and write a timestamped+`.bak-<ts>` next to the file before each modifying write. The hook+scripts are staged into `~/.local/share/ai-memory/hooks/<agent>/`+automatically; re-running overwrites them so future image updates ship+updated hooks. Drop `--apply` to print the snippet instead of mutating.The Docker wrapper also bridges thin-client commands such as`ai-memory status` and `ai-memory bootstrap` back to the host's@@ -196,8 +199,10 @@ use `--mcp-url` if you installed MCP with a custom endpoint, and- **Docker compose:** `docker compose -f docker/docker-compose.yml up -d`is supported; agent setup is the same as step 3 above.- **Remote server:** set `AI_MEMORY_SERVER_URL=http://<server-ip>:49374`- on the client and pass matching `--server-url` flags when installing- MCP/hooks. Any non-loopback server should use bearer auth.+ and `AI_MEMORY_AUTH_TOKEN=<token>` on the client before installing+ MCP/hooks. Explicit `--server-url` flags still work, but are no longer+ required when the env vars are set. Any non-loopback server should use+ bearer auth.- **Upgrades:** run `ai-memory upgrade` to refresh the wrapper, image,and staged hook scripts. Redeploy remote servers separately.diff --git a/bin/ai-memory b/bin/ai-memoryindex a0614a96..75af9837 100755--- a/bin/ai-memory+++ b/bin/ai-memory@@ -126,6 +126,7 @@ cmd_upgrade() {# the seven hook keys we own get replaced; everything else# (other hooks the user wired up) survives untouched.echo " ai-memory install-hooks --agent ${agent} --apply"+ echo " (uses AI_MEMORY_SERVER_URL/AI_MEMORY_AUTH_TOKEN or the existing ai-memory MCP entry when present)"AI_MEMORY_NO_VERSION_CHECK=1 \"$0" install-hooks --agent "${agent}" --apply \|| echo " (skipped — re-run with the same --server-url / --auth-token used originally)"diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 2d3884a5..67dc752f 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -287,7 +287,8 @@ pub struct SetupAgentArgs {/// --to /host/hooks --host-prefix $HOME/.ai-memory/hooks#[arg(long)]pub host_prefix: Option<PathBuf>,- /// MCP / hook ingress URL the agent should POST to.+ /// MCP / hook ingress URL the agent should POST to. Defaults to the+ /// configured `server_url` / AI_MEMORY_SERVER_URL when set, else loopback.#[arg(long, default_value_t = crate::config::DEFAULT_SERVER_URL.to_string())]pub server_url: String,/// Bearer token embedded into each hook's env block. When omitted,@@ -552,7 +553,10 @@ pub struct InstallHooksArgs {/// Ignored for generated TypeScript integrations (OpenCode, OMP, OpenClaw).#[arg(long)]pub hooks_dir: Option<PathBuf>,- /// Server URL the hooks will POST to.+ /// Server URL the hooks will POST to. Defaults to the configured+ /// `server_url` / AI_MEMORY_SERVER_URL when set, else loopback. If neither+ /// is configured, apply-mode also reuses an existing ai-memory MCP entry+ /// for the same agent when one is present.#[arg(long, default_value_t = crate::config::DEFAULT_SERVER_URL.to_string())]pub server_url: String,/// Bearer token to embed in the hook config's `env` block. When@@ -580,7 +584,9 @@ pub struct InstallMcpArgs {/// Which MCP client to render configuration for.#[arg(long, value_enum, default_value_t = McpClient::ClaudeCode)]pub client: McpClient,- /// MCP HTTP endpoint URL the client should connect to.+ /// MCP HTTP endpoint URL the client should connect to. Defaults to the+ /// configured `server_url` / AI_MEMORY_SERVER_URL plus `/mcp` when set,+ /// else loopback.#[arg(long, default_value_t = crate::config::DEFAULT_MCP_URL.to_string())]pub server_url: String,/// Friendly name the client should show for this server entry.diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex c7452759..39bb87c3 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -19,15 +19,16 @@ use std::path::{Path, PathBuf};use anyhow::{Context, Result};-use crate::cli::{AgentChoice, InstallHooksArgs};+use crate::cli::{AgentChoice, InstallHooksArgs, McpClient};use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json};+use crate::commands::install_mcp;use crate::commands::openclaw_plugin;use crate::commands::render_shared::{CURSOR_PROFILE, GEMINI_PROFILE, build_antigravity_payload, build_claude_code_payload,build_codex_payload, build_profile_payload, hook_script_for_current_platform,ts_string_literal,};-use crate::config::Config;+use crate::config::{Config, DEFAULT_SERVER_URL};/// `~/.claude/settings.json` — Claude Code hooks live under `hooks`.pub(crate) fn claude_settings_path() -> anyhow::Result<std::path::PathBuf> {@@ -95,68 +96,201 @@ pub(crate) fn omp_extension_path() -> anyhow::Result<std::path::PathBuf> {/// # Errors/// 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 == DEFAULT_SERVER_URL {+ infer_installed_mcp_config(args.agent)+ } else {+ None+ };+ let server_url = effective_hook_server_url(config, &args, inferred.as_ref());let auth_token_owned = args.auth_token.clone()- .or_else(|| config.auth.bearer_token.clone());+ .or_else(|| config.auth.bearer_token.clone())+ .or_else(|| inferred.as_ref().and_then(|mcp| mcp.auth_token.clone()));let auth = auth_token_owned.as_deref();if args.apply {return match args.agent {- AgentChoice::OpenCode => apply_to_opencode_plugin(&args.server_url, auth, &args),- AgentChoice::Omp => apply_to_omp_extension(&args.server_url, auth, &args),+ AgentChoice::OpenCode => apply_to_opencode_plugin(&server_url, auth, &args),+ AgentChoice::Omp => apply_to_omp_extension(&server_url, auth, &args),AgentChoice::ClaudeCode => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- apply_to_claude_code_settings(&hooks_dir, &args.server_url, auth, &args)+ apply_to_claude_code_settings(&hooks_dir, &server_url, auth, &args)}AgentChoice::Codex => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- apply_to_codex_settings(&hooks_dir, &args.server_url, auth, &args)+ apply_to_codex_settings(&hooks_dir, &server_url, auth, &args)}AgentChoice::Cursor => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- apply_to_cursor_settings(&hooks_dir, &args.server_url, auth, &args)+ apply_to_cursor_settings(&hooks_dir, &server_url, auth, &args)}AgentChoice::GeminiCli => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- apply_to_gemini_settings(&hooks_dir, &args.server_url, auth, &args)+ apply_to_gemini_settings(&hooks_dir, &server_url, auth, &args)}AgentChoice::AntigravityCli => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- apply_to_antigravity_settings(&hooks_dir, &args.server_url, auth, &args)+ apply_to_antigravity_settings(&hooks_dir, &server_url, auth, &args)}- AgentChoice::Openclaw => openclaw_plugin::apply(&args.server_url, auth, &args),+ AgentChoice::Openclaw => openclaw_plugin::apply(&server_url, auth, &args),};}match args.agent {- AgentChoice::OpenCode => render_opencode_plugin(&args.server_url, auth),- AgentChoice::Omp => render_omp_extension(&args.server_url, auth),+ AgentChoice::OpenCode => render_opencode_plugin(&server_url, auth),+ AgentChoice::Omp => render_omp_extension(&server_url, auth),AgentChoice::ClaudeCode => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- render_claude_code(&hooks_dir, &args.server_url, auth)+ render_claude_code(&hooks_dir, &server_url, auth)}AgentChoice::Codex => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- render_agent("codex", &hooks_dir, &args.server_url, auth)+ render_agent("codex", &hooks_dir, &server_url, auth)}AgentChoice::Cursor => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- render_agent("cursor", &hooks_dir, &args.server_url, auth)+ render_agent("cursor", &hooks_dir, &server_url, auth)}AgentChoice::GeminiCli => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- render_agent("gemini-cli", &hooks_dir, &args.server_url, auth)+ render_agent("gemini-cli", &hooks_dir, &server_url, auth)}AgentChoice::AntigravityCli => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- render_agent("antigravity-cli", &hooks_dir, &args.server_url, auth)+ render_agent("antigravity-cli", &hooks_dir, &server_url, auth)}AgentChoice::Openclaw => {- openclaw_plugin::render(&args.server_url, auth);+ openclaw_plugin::render(&server_url, auth);Ok(())}}}+#[derive(Debug, Clone, Default)]+struct InferredMcpConfig {+ hook_server_url: Option<String>,+ auth_token: Option<String>,+}++fn effective_hook_server_url(+ config: &Config,+ args: &InstallHooksArgs,+ inferred: Option<&InferredMcpConfig>,+) -> String {+ if args.server_url != DEFAULT_SERVER_URL {+ return normalise_hook_server_url(&args.server_url);+ }+ if config.server_url_configured() {+ return normalise_hook_server_url(&config.server_url);+ }+ if let Some(url) = inferred.and_then(|mcp| mcp.hook_server_url.clone()) {+ return normalise_hook_server_url(&url);+ }+ args.server_url.clone()+}++fn normalise_hook_server_url(url: &str) -> String {+ url.trim().trim_end_matches('/').to_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")+ }+ McpClient::Codex => infer_codex_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::Pi => infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "url"),+ McpClient::AntigravityCli => {+ infer_json_mcp_config(&content, &["mcpServers", "ai-memory"], "serverUrl")+ }+ McpClient::ClaudeDesktop => None,+ }+}++fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {+ match agent {+ AgentChoice::ClaudeCode => Some(McpClient::ClaudeCode),+ AgentChoice::Codex => Some(McpClient::Codex),+ AgentChoice::Cursor => Some(McpClient::Cursor),+ AgentChoice::GeminiCli => Some(McpClient::GeminiCli),+ AgentChoice::OpenCode => Some(McpClient::OpenCode),+ AgentChoice::Omp => Some(McpClient::Pi),+ AgentChoice::Openclaw => Some(McpClient::Openclaw),+ AgentChoice::AntigravityCli => Some(McpClient::AntigravityCli),+ }+}++fn infer_json_mcp_config(+ content: &str,+ entry_path: &[&str],+ url_key: &str,+) -> Option<InferredMcpConfig> {+ let root: serde_json::Value = serde_json::from_str(content).ok()?;+ let mut entry = &root;+ for key in entry_path {+ entry = entry.get(*key)?;+ }+ let hook_server_url = entry+ .get(url_key)+ .and_then(|v| v.as_str())+ .and_then(hook_server_url_from_mcp_url);+ let auth_token = entry+ .get("headers")+ .and_then(|headers| headers.get("Authorization"))+ .and_then(|v| v.as_str())+ .and_then(bearer_token_from_header);+ Some(InferredMcpConfig {+ hook_server_url,+ auth_token,+ })+}++fn infer_codex_mcp_config(content: &str) -> Option<InferredMcpConfig> {+ let doc: toml_edit::DocumentMut = content.parse().ok()?;+ let server = &doc["mcp_servers"]["ai-memory"];+ let hook_server_url = server["url"]+ .as_str()+ .and_then(hook_server_url_from_mcp_url);+ let auth_token = server["http_headers"]["Authorization"]+ .as_str()+ .or_else(|| server["headers"]["Authorization"].as_str())+ .and_then(bearer_token_from_header);+ if hook_server_url.is_none() && auth_token.is_none() {+ return None;+ }+ Some(InferredMcpConfig {+ hook_server_url,+ auth_token,+ })+}++fn hook_server_url_from_mcp_url(url: &str) -> Option<String> {+ let trimmed = url.trim().trim_end_matches('/');+ if trimmed.is_empty() {+ return None;+ }+ Some(trimmed.strip_suffix("/mcp").unwrap_or(trimmed).to_string())+}++fn bearer_token_from_header(header: &str) -> Option<String> {+ header+ .trim()+ .strip_prefix("Bearer ")+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(ToOwned::to_owned)+}+/// Mutate `~/.claude/settings.json` in place: replace the seven hook/// entries ai-memory cares about; preserve every other hook the user/// has wired up to other tools.@@ -1385,6 +1519,104 @@ mod tests {}}+ fn default_hook_args() -> InstallHooksArgs {+ InstallHooksArgs {+ agent: AgentChoice::OpenCode,+ hooks_dir: None,+ server_url: DEFAULT_SERVER_URL.into(),+ auth_token: None,+ apply: true,+ config_file: None,+ }+ }++ #[test]+ fn hook_server_url_defaults_to_configured_server_url() {+ let config = Config {+ server_url: "http://192.168.0.90:49374/".into(),+ ..Config::default()+ };+ let args = default_hook_args();++ assert_eq!(+ effective_hook_server_url(&config, &args, None),+ "http://192.168.0.90:49374"+ );+ }++ #[test]+ fn hook_server_url_explicit_flag_wins_over_config() {+ let config = Config {+ server_url: "http://homelab:49374".into(),+ ..Config::default()+ };+ let mut args = default_hook_args();+ args.server_url = "http://explicit:49374/".into();++ assert_eq!(+ effective_hook_server_url(&config, &args, None),+ "http://explicit:49374"+ );+ }++ #[test]+ fn hook_server_url_falls_back_to_existing_mcp_entry() {+ let config = Config::default();+ let args = default_hook_args();+ let inferred = InferredMcpConfig {+ hook_server_url: Some("http://homelab:49374".into()),+ auth_token: Some("tok".into()),+ };++ assert_eq!(+ effective_hook_server_url(&config, &args, Some(&inferred)),+ "http://homelab:49374"+ );+ }++ #[test]+ fn opencode_mcp_inference_supplies_hook_origin_and_token() {+ let inferred = infer_json_mcp_config(+ r#"{+ "mcp": {+ "ai-memory": {+ "type": "remote",+ "url": "http://homelab:49374/mcp",+ "headers": { "Authorization": "Bearer secret-token" }+ }+ }+ }"#,+ &["mcp", "ai-memory"],+ "url",+ )+ .unwrap();++ assert_eq!(+ inferred.hook_server_url.as_deref(),+ Some("http://homelab:49374")+ );+ assert_eq!(inferred.auth_token.as_deref(), Some("secret-token"));+ }++ #[test]+ fn codex_mcp_inference_accepts_block_form_config() {+ let inferred = infer_codex_mcp_config(+ r#"[mcp_servers.ai-memory]+url = "http://homelab:49374/mcp"++[mcp_servers.ai-memory.http_headers]+Authorization = "Bearer secret-token"+"#,+ )+ .unwrap();++ assert_eq!(+ inferred.hook_server_url.as_deref(),+ Some("http://homelab:49374")+ );+ assert_eq!(inferred.auth_token.as_deref(), Some("secret-token"));+ }+#[test]fn bundled_posix_and_powershell_hooks_stay_in_parity() {let hooks_root = Path::new(env!("CARGO_MANIFEST_DIR"))diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex b19a5b6c..bd2c66a8 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;-use crate::config::Config;+use crate::config::{Config, DEFAULT_MCP_URL};const GEMINI_MCP_TIMEOUT_MS: u64 = 5000;@@ -39,7 +39,9 @@ enum JsonMcpLocation {/// Returns an error if JSON serialisation fails (should never happen/// for our handcrafted values).pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {+ let server_url = effective_mcp_server_url(config, &args);let args = InstallMcpArgs {+ server_url,auth_token: args.auth_token.or_else(|| config.auth.bearer_token.clone()),..args};@@ -61,6 +63,25 @@ pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {Ok(())}+fn effective_mcp_server_url(config: &Config, args: &InstallMcpArgs) -> String {+ if args.server_url != DEFAULT_MCP_URL {+ return args.server_url.clone();+ }+ if config.server_url_configured() {+ return mcp_server_url_from_base(&config.server_url);+ }+ args.server_url.clone()+}++fn mcp_server_url_from_base(server_url: &str) -> String {+ let trimmed = server_url.trim().trim_end_matches('/');+ if trimmed.ends_with("/mcp") {+ trimmed.to_string()+ } else {+ format!("{trimmed}/mcp")+ }+}+/// Default MCP config-file path for a client (ignores any/// `--config-file` override). Shared by install and uninstall.///@@ -673,6 +694,49 @@ mod tests {}}+ #[test]+ fn mcp_server_url_defaults_to_configured_server_url() {+ let config = Config {+ server_url: "http://192.168.0.90:49374/".into(),+ ..Config::default()+ };+ let args = args_for(McpClient::OpenCode);++ assert_eq!(+ effective_mcp_server_url(&config, &args),+ "http://192.168.0.90:49374/mcp"+ );+ }++ #[test]+ fn mcp_server_url_does_not_duplicate_mcp_suffix() {+ let config = Config {+ server_url: "http://192.168.0.90:49374/mcp".into(),+ ..Config::default()+ };+ let args = args_for(McpClient::OpenCode);++ assert_eq!(+ effective_mcp_server_url(&config, &args),+ "http://192.168.0.90:49374/mcp"+ );+ }++ #[test]+ fn mcp_server_url_explicit_flag_wins_over_config() {+ let config = Config {+ server_url: "http://homelab:49374".into(),+ ..Config::default()+ };+ let mut args = args_for(McpClient::OpenCode);+ args.server_url = "http://explicit:49374/mcp".into();++ assert_eq!(+ effective_mcp_server_url(&config, &args),+ "http://explicit:49374/mcp"+ );+ }+/// Specific shape checks — each client has a distinguishing key/// in its JSON snippet. This catches accidental cross-pollination/// between renderers (e.g. Gemini's `httpUrl` showing up underdiff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex d16cac81..4f184b74 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -38,7 +38,7 @@ use crate::cli::{AgentChoice, SetupAgentArgs};use crate::commands::render_shared::{CLAUDE_CODE_EVENTS, build_claude_code_payload, hook_script_for_current_platform,};-use crate::config::Config;+use crate::config::{Config, DEFAULT_SERVER_URL};/// Run the `setup-agent` subcommand.///@@ -47,7 +47,13 @@ use crate::config::Config;/// 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<()> {+ let server_url = if args.server_url == DEFAULT_SERVER_URL && config.server_url_configured() {+ normalise_hook_server_url(&config.server_url)+ } else {+ normalise_hook_server_url(&args.server_url)+ };let args = SetupAgentArgs {+ server_url,auth_token: args.auth_token.or_else(|| config.auth.bearer_token.clone()),..args};@@ -136,6 +142,10 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {Ok(())}+fn normalise_hook_server_url(url: &str) -> String {+ url.trim().trim_end_matches('/').to_string()+}+fn emit_extension_setup_hint(args: &SetupAgentArgs) {let (label, agent, restart_note, mcp_client) = match args.agent {AgentChoice::OpenCode => (diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rsindex cce05736..1a32919d 100644--- a/crates/ai-memory-core/src/routing_snippet.rs+++ b/crates/ai-memory-core/src/routing_snippet.rs@@ -32,8 +32,10 @@ pub const SNIPPET_BODY: &str = r#"This project uses [ai-memory](https://github.com/akitaonrails/ai-memory)for cross-session continuity. **Lifecycle hooks already capture everyprompt + tool call automatically.** You never need to manually write-notes; the SessionStart hook auto-fetches pending handoffs and the-SessionEnd hook auto-consolidates. Just *use* the read tools.+routine notes; the SessionStart hook auto-fetches pending handoffs and+the SessionEnd hook auto-consolidates. Only write a durable wiki page+when the user explicitly asks to remember or annotate something+permanently.### When to reach for each tool@@ -49,8 +51,9 @@ match the intent to the tool. They do not need to name the tool.| "catch me up" / "I've been away" / "what's important right now?" / open-ended exploration | `memory_explore` || "where did we leave off?" — and you see a `📥 ai-memory: pending handoff` block in your context | already done — answer from that block; do NOT re-call `memory_handoff_accept` || "where did we leave off?" — and no such block is visible | `memory_handoff_accept` (rare; the SessionStart hook usually got there first) |-| "save context for the next session" / wrapping up | `memory_handoff_begin` (terse summary; put detail in `open_questions` + `next_steps` bullets) |+| "save context for the next session" / wrapping up | `memory_handoff_begin` (single-use handoff; terse summary; put detail in `open_questions` + `next_steps` bullets) || "consolidate this session" / "compile what we learned" (usually automatic) | `memory_consolidate` |+| "remember this permanently" / "save a note" / "add an annotation" / durable project knowledge | `memory_write_page` (write a wiki page; do **not** use handoff for permanent notes) || "audit the wiki" / "find contradictions" / "what rules should we add?" | `memory_lint` || "prune old pages" / "memory cleanup" | `memory_forget_sweep` |diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex a1e1efda..0ab6cc66 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -5,11 +5,11 @@ use std::sync::Arc;use ai_memory_consolidate::{Consolidator, run_lint, run_sweep};use ai_memory_core::{- ActiveProject, AgentKind, NewHandoff, PageId, ProjectId, SessionId, WorkspaceId,+ ActiveProject, AgentKind, NewHandoff, PageId, PagePath, ProjectId, SessionId, Tier, WorkspaceId,};use ai_memory_llm::{Embedder, LlmProvider};use ai_memory_store::{DecayParams, ReaderPool, WriterHandle};-use ai_memory_wiki::Wiki;+use ai_memory_wiki::{Wiki, WritePageRequest};use rmcp::handler::server::router::tool::ToolRouter;use rmcp::handler::server::wrapper::Parameters;use rmcp::model::{@@ -26,8 +26,10 @@ use serde::{Deserialize, Serialize};pub const MEMORY_INSTRUCTIONS: &str = "\Long-term memory for the current project. Lifecycle hooks already \capture every prompt + tool call automatically — you do NOT need to \-write anything by hand. Use these tools when the conversation calls \-for them:\n\+write routine notes by hand. When the user explicitly asks to remember \+a permanent annotation/fact/rule, write a durable wiki page; do not use \+a handoff for that. Use these tools when the conversation calls for \+them:\n\\n\- `memory_query` — when the user references prior work you don't \recognise, or asks 'have we done / discussed X', or you're about \@@ -56,6 +58,9 @@ for them:\n\put detail in open_questions + next_steps bullets.\n\- `memory_consolidate` — when the user asks to compile session \observations into wiki pages (usually automatic at session end).\n\+- `memory_write_page` — when the user explicitly asks to remember, \+ save, or annotate durable project knowledge. This writes a wiki page; \+ do NOT use `memory_handoff_begin` for permanent annotations.\n\- `memory_lint` — when the user asks to audit the wiki for stale \pages, contradictions, or rule suggestions.\n\- `memory_forget_sweep` — when the user wants to prune old / cold \@@ -258,6 +263,30 @@ struct ExploreArgs {project: Option<String>,}+#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]+struct WritePageArgs {+ /// Relative wiki path to write, for example `notes/santander-2025.md`.+ path: String,+ /// Markdown body. Pass the durable fact/note content, not a handoff summary.+ body: String,+ /// Optional page title; otherwise derived from the first H1 or path stem.+ #[serde(default)]+ title: Option<String>,+ /// Tier (`working`, `episodic`, `semantic`, `procedural`). Default semantic.+ #[serde(default)]+ tier: Option<String>,+ /// Tags to attach to the page.+ #[serde(default)]+ tags: Vec<String>,+ /// Pin the page so the decay sweep skips it.+ #[serde(default)]+ pinned: bool,+ /// Project to write into. Omit to target the project you're currently+ /// working in (resolved from recent hook activity).+ #[serde(default)]+ project: Option<String>,+}+#[tool_router]impl AiMemoryServer {/// Construct a server backed by the given reader/writer + 3-tuple@@ -586,6 +615,78 @@ impl AiMemoryServer {}}+ /// Write or update a durable wiki page.+ #[tool(description = "Write or update a durable wiki page for the \+ current project. Use this when the user explicitly asks to \+ remember, save, pin, annotate, or make permanent a fact/rule/note. \+ This is for long-lived project knowledge; do NOT use \+ memory_handoff_begin for permanent annotations. Choose a stable \+ relative path such as `notes/<topic>.md`, `concepts/<topic>.md`, \+ `decisions/<topic>.md`, or `_rules/<topic>.md`. `tier` defaults \+ to `semantic`; set `pinned=true` for facts that should never decay.")]+ async fn memory_write_page(+ &self,+ Parameters(args): Parameters<WritePageArgs>,+ ) -> Result<CallToolResult, McpError> {+ let Some(wiki) = self.wiki.as_ref() else {+ return Err(McpError::internal_error(+ "memory_write_page requires the server to be built with a wiki handle",+ None,+ ));+ };+ let tier_name = args.tier.as_deref().unwrap_or("semantic");+ let tier: Tier = tier_name+ .parse()+ .map_err(|_| McpError::internal_error(format!("unknown tier '{tier_name}'"), None))?;+ let path = PagePath::new(args.path.clone())+ .map_err(|e| McpError::internal_error(format!("invalid path: {e}"), None))?;+ let (ws, proj) = self.effective_ids(args.project.as_deref()).await;++ let mut fm = serde_json::Map::new();+ if let Some(title) = &args.title {+ fm.insert("title".into(), serde_json::Value::String(title.clone()));+ }+ if !args.tags.is_empty() {+ fm.insert(+ "tags".into(),+ serde_json::Value::Array(+ args.tags+ .iter()+ .cloned()+ .map(serde_json::Value::String)+ .collect(),+ ),+ );+ }+ if args.pinned {+ fm.insert("pinned".into(), serde_json::Value::Bool(true));+ }+ let frontmatter = if fm.is_empty() {+ serde_json::Value::Null+ } else {+ serde_json::Value::Object(fm)+ };++ let page_id = wiki+ .write_page(WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: path.clone(),+ frontmatter,+ body: args.body,+ tier,+ pinned: args.pinned,+ title: args.title,+ })+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;++ ok_json(&serde_json::json!({+ "page_id": page_id.to_string(),+ "path": path.to_string()+ }))+ }+/// Create a handoff snapshot for the next agent CLI.#[tool(description = "Record a cross-agent handoff snapshot for the \NEXT agent that opens this project (e.g. Codex picking up after \@@ -1009,6 +1110,53 @@ mod tests {let (_tmp, _store, _server, _ws, _pj) = setup_server().await;}+ #[test]+ fn prompts_cover_every_mcp_tool() {+ let tools = [+ "memory_query",+ "memory_recent",+ "memory_status",+ "memory_briefing",+ "memory_explore",+ "memory_handoff_accept",+ "memory_handoff_begin",+ "memory_consolidate",+ "memory_write_page",+ "memory_lint",+ "memory_forget_sweep",+ "memory_install_self_routing",+ ];+ let routing = ai_memory_core::full_block();+ for tool in tools {+ assert!(+ MEMORY_INSTRUCTIONS.contains(tool),+ "MCP handshake instructions omit {tool}"+ );+ assert!(+ routing.contains(tool),+ "routing snippet omit {tool}; update ai_memory_core::SNIPPET_BODY"+ );+ }+ }++ #[test]+ fn prompts_route_permanent_annotations_to_write_page_not_handoff() {+ for prompt in [MEMORY_INSTRUCTIONS, ai_memory_core::SNIPPET_BODY] {+ assert!(+ prompt.contains("permanent") || prompt.contains("permanently"),+ "prompt must mention permanent memory use cases"+ );+ assert!(+ prompt.contains("memory_write_page"),+ "prompt must expose memory_write_page"+ );+ assert!(+ prompt.contains("do NOT use") || prompt.contains("do **not** use"),+ "prompt must explicitly disallow handoffs for permanent notes"+ );+ }+ }+/// Read tools resolve the project in the order: explicit `project`/// arg → hook-published active project → baked-in default (issue #2).#[tokio::test]@@ -1259,6 +1407,63 @@ mod tests {assert!(text.contains("foo.md"), "expected hit; got {text}");}+ #[tokio::test]+ async fn memory_write_page_writes_durable_page() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)+ .with_wiki(wiki);++ let result = server+ .memory_write_page(Parameters(WritePageArgs {+ path: "notes/santander-2025.md".into(),+ body: "# Santander 2025\n\nDurable tax annotation.".into(),+ title: Some("Santander 2025".into()),+ tier: Some("semantic".into()),+ tags: vec!["finance".into()],+ pinned: true,+ project: None,+ }))+ .await+ .unwrap();+ let text = result+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(text.contains("notes/santander-2025.md"), "got {text}");++ let recent = server+ .memory_recent(Parameters(RecentArgs {+ limit: Some(5),+ project: None,+ }))+ .await+ .unwrap();+ let recent_text = recent+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(+ recent_text.contains("notes/santander-2025.md"),+ "write-page result must be visible to read tools; got {recent_text}"+ );+ }+/// `memory_handoff_begin` must resolve the same project as/// `memory_briefing` when hooks publish `ActiveProject` (issue #2).#[tokio::test]diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 2006f4ce..06b7a4e2 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -196,7 +196,7 @@ Each crate has a single responsibility and exposes a typed API. Nocircular deps. Inter-crate boundaries enforce the cross-cuttinginvariants below.-## MCP tool surface (11 tools)+## MCP tool surface (12 tools)| Tool | Hint | Purpose ||---|---|---|@@ -208,18 +208,21 @@ invariants below.| `memory_handoff_begin` | destructive | Open a handoff for the next agent. || `memory_handoff_accept` | destructive | Fetch + ack the latest open handoff (auto-cwd-matched). || `memory_consolidate` | destructive | LLM-driven page rewrite. `multi_page=true` for atomic fan-out. |+| `memory_write_page` | destructive | Write durable wiki knowledge when the user explicitly asks to remember/annotate something permanent. || `memory_forget_sweep` | destructive | M8 retention pass. `dry_run=true` for preview. || `memory_lint` | destructive | Rule-based + LLM contradiction findings → `wiki/_lint/`. || `memory_install_self_routing` | read-only | Return the canonical routing snippet for CLAUDE.md / AGENTS.md. |-`memory_briefing`, `memory_explore` and `memory_install_self_routing`+`memory_briefing`, `memory_explore`, `memory_write_page`, and+`memory_install_self_routing`post-date the original "narrow on purpose" cut (§10 of`design-decisions.md`): briefing/explore separate the structured vs.-prose halves of "what's going on", and `memory_install_self_routing`-exists for the meta case where the agent must re-write its own routing-rules into a project's `CLAUDE.md` / `AGENTS.md`. The narrow-surface-discipline still holds — every new tool has to earn its slot — but the-v1 count is 11, not 10.+prose halves of "what's going on", `memory_write_page` covers explicit+durable annotations without abusing single-use handoffs, and+`memory_install_self_routing` exists for the meta case where the agent+must re-write its own routing rules into a project's `CLAUDE.md` /+`AGENTS.md`. The narrow-surface discipline still holds — every new tool+has to earn its slot — but the v1 count is 12, not 10.MCP parameter aliases are intentionally sparse: `memory_query.query` accepts`q|search`, and limit fields accept `n` / `top_k` where shipped. Project anddiff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex 5fa5ec29..85b5fdfd 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -166,6 +166,7 @@ basic-memory has ~25 tools, agentmemory has 53. Both have user confusion as a re| `memory_handoff_begin` | Mark session boundary, write handoff | destructive || `memory_handoff_accept` | Fetch + ack the latest open handoff | destructive || `memory_consolidate` | LLM-driven page rewrite (`multi_page=true` for atomic fan-out) | destructive |+| `memory_write_page` | Write durable wiki knowledge on explicit user request | destructive || `memory_forget_sweep` | Retention sweep (M8); soft-delete below cold threshold; `dry_run=true` previews | destructive || `memory_lint` | Rule-based + optional LLM contradiction findings → `wiki/_lint/<date>.md` | destructive || `memory_install_self_routing` | Returns the canonical CLAUDE.md / AGENTS.md routing block + per-agent filename hints | read-only |diff --git a/docs/install.md b/docs/install.mdindex 49395bfa..12cc53be 100644--- a/docs/install.md+++ b/docs/install.md@@ -56,14 +56,14 @@ required for any non-loopback bind.export AI_MEMORY_SERVER_URL="http://<server-ip>:49374"export AI_MEMORY_AUTH_TOKEN="$TOKEN"-ai-memory install-mcp --client claude-code --apply \- --server-url "http://<server-ip>:49374/mcp"-ai-memory install-hooks --agent claude-code --apply \- --server-url "http://<server-ip>:49374"+ai-memory install-mcp --client claude-code --apply+ai-memory install-hooks --agent claude-code --apply```The CLI commands (`bootstrap`, `status`, `search`, `lint`, etc.) inherit the-two env vars automatically.+two env vars automatically. So do `install-mcp`, `install-hooks`, and+`setup-agent`: with `AI_MEMORY_SERVER_URL` set, `install-mcp` derives the+`/mcp` endpoint and `install-hooks` uses the bare server origin.---@@ -88,14 +88,18 @@ export AI_MEMORY_SERVER_URL="http://192.168.0.90:49374"export AI_MEMORY_AUTH_TOKEN="<token>"```-Explicit `--server-url` and `--auth-token` flags on `install-mcp` and-`install-hooks` override the environment. That is useful when you are-generating config for a client that talks to a different server than-your default CLI target.+Explicit `--server-url` and `--auth-token` flags on `install-mcp`,+`install-hooks`, and `setup-agent` override the environment. That is+useful when you are generating config for a client that talks to a+different server than your default CLI target.++If you run `install-mcp --apply` first and later run `install-hooks --apply`+without env vars or flags, hooks reuse the existing ai-memory MCP entry for+that agent when possible. This keeps remote MCP config and lifecycle capture+pointed at the same server instead of falling back to loopback.-`init`, `serve`, `install-*`, `generate-auth-token`, and `setup-agent`-do not need these env vars because they either set up local files or-start the server itself.+`init`, `serve`, and `generate-auth-token` do not need these env vars because+they either create local files or start the server itself.---diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex e7f3fe5e..05d202b9 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -400,7 +400,8 @@ You: List the MCP tools you can call. Use one of them to checkModel (any client): I can call: memory_query, memory_recent,memory_status, memory_briefing, memory_explore,memory_handoff_accept, memory_handoff_begin, memory_consolidate,- memory_lint, memory_forget_sweep, memory_install_self_routing.+ memory_write_page, memory_lint, memory_forget_sweep,+ memory_install_self_routing.memory_status reports: 0 pages, 0 observations, 0 sessions.```diff --git a/docs/usage.md b/docs/usage.mdindex 895cb9ff..3b100a58 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -48,6 +48,7 @@ the wiki without you naming tools explicitly.| "Where did we leave off?" | Existing handoff block, or `memory_handoff_accept` if no block exists | Resumes from the latest pending handoff. || "Save context for the next session" | `memory_handoff_begin` | Writes a terse handoff with open questions and next steps. || "Consolidate this session" | `memory_consolidate` | Manually runs what session-end normally runs automatically. |+| "Remember this permanently" / "add an annotation" | `memory_write_page` | Writes durable wiki knowledge; not a single-use handoff. || "Audit the wiki" / "any contradictions?" | `memory_lint` | Runs stale-page, contradiction, and rule-suggestion checks. || "How big is the wiki?" / "stats?" | `memory_status`, `memory_briefing` | Counts and recent activity windows. |