Skip to content

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

Rust

M22: install-mcp / install-hooks / install-instructions --apply

AkitaOnRailsd6dad1aee092
diff --git a/Cargo.lock b/Cargo.lock
index c8cfe96f..5d96e6c3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -47,6 +47,7 @@ dependencies = [
"figment",
"flate2",
"getrandom 0.3.4",
+ "jiff",
"rmcp",
"secrecy",
"serde",
@@ -57,6 +58,7 @@ dependencies = [
"tempfile",
"tokio",
"tokio-util",
+ "toml_edit",
"tower",
"tracing",
"tracing-appender",
diff --git a/Cargo.toml b/Cargo.toml
index e175909e..9f6d1eb0 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -57,6 +57,10 @@ uuid = { version = "1", features = ["v4", "v5", "v7", "serde"] }
figment = { version = "0.10", features = ["toml", "env"] }
clap = { version = "4", features = ["derive", "env"] }
dirs = "5"
+# Format-preserving TOML editor for install-mcp --apply against
+# Codex's config.toml. Plain `toml` round-trips destroy comments;
+# `toml_edit` doesn't.
+toml_edit = "0.22"
# Secrets + constant-time / RNG primitives for bearer-token auth.
secrecy = { version = "0.10", features = ["serde"] }
diff --git a/README.md b/README.md
index bd39f5b1..b85c4ca3 100644
--- a/README.md
+++ b/README.md
@@ -50,22 +50,32 @@ docker run -d --name ai-memory \
# OpenCode, Cursor, Claude Desktop, Gemini CLI, OpenClaw, see
# docs/install.md.
-# 3a. Register the MCP endpoint
-claude mcp add --transport http ai-memory http://localhost:49374/mcp \
- --header "Authorization: Bearer $TOKEN"
+# 3a. Register the MCP endpoint (auto-edits ~/.claude/settings.json)
+docker run --rm -v "$HOME:/host" akitaonrails/ai-memory:latest \
+ install-mcp --client claude-code --apply \
+ --config-file /host/.claude/settings.json \
+ --server-url "http://localhost:49374/mcp" \
+ --auth-token "$TOKEN"
# 3b. Extract the bundled hook scripts to your home dir
docker cp ai-memory:/usr/local/share/ai-memory/hooks ~/.ai-memory/
-# 3c. Render the settings.json snippet, then merge the printed JSON
-# into ~/.claude/settings.json (chmod 600 the file)
-docker run --rm akitaonrails/ai-memory:latest \
- install-hooks --agent claude-code \
- --hooks-dir ~/.ai-memory/hooks \
+# 3c. Wire the hooks into ~/.claude/settings.json (also auto-edits)
+docker run --rm -v "$HOME:/host" akitaonrails/ai-memory:latest \
+ install-hooks --agent claude-code --apply \
+ --hooks-dir /host/.ai-memory/hooks \
+ --config-file /host/.claude/settings.json \
--server-url "http://localhost:49374" \
--auth-token "$TOKEN"
```
+Both `install-mcp` and `install-hooks` accept `--apply` to **mutate
+the agent's config file in place** (idempotent — re-runs replace
+ai-memory's entry, preserving every other server / hook the user has
+configured; a timestamped `.bak-<ts>` is written next to the file
+before each modifying write). Drop `--apply` to keep the legacy
+print-the-JSON behaviour.
+
That's it. Start a Claude Code session as usual — every prompt and
tool call now lands in ai-memory, and the next session you open in
this project will see a handoff with where you left off.
@@ -178,24 +188,21 @@ the whole UX. You copy what's useful, ignore what isn't.
Lifecycle hooks handle *capture* and *handoff resume* without you
typing anything. Proactive *querying* still depends on the agent
-thinking to call `memory_query`. The tool descriptions nudge in that
-direction; for projects where memory matters, drop this in your
-`CLAUDE.md` / agent system prompt:
-
-```markdown
-## Long-term memory
-
-This project uses ai-memory. The SessionStart hook auto-fetches any
-pending handoff. Beyond that, proactively use:
-
-- `memory_query` — before proposing architecture, when the user
- references prior work you don't recognise, or when investigating a
- bug that might have a known root cause.
-- `memory_recent` — at session start to scan the last few pages.
-- `memory_handoff_begin` — optional; only if you want extra context
- beyond what the SessionEnd hook captures by default.
+thinking to call `memory_query`. For projects where memory matters,
+one command installs the recommended snippet into your `CLAUDE.md`:
+
+```bash
+docker run --rm -v "$PWD:/host" akitaonrails/ai-memory:latest \
+ install-instructions --target /host/CLAUDE.md
```
+The block is wrapped in `<!-- ai-memory:start -->` /
+`<!-- ai-memory:end -->` markers so re-running picks up an updated
+snippet without duplicating. Use `--target /host/AGENTS.md` for
+non-Claude agents, or any other path for project-rules files
+(`.cursor/rules`, `.windsurfrules`, etc.). Append `--print` to
+preview without writing.
+
## LLM provider — recommended defaults
You can run ai-memory entirely without an LLM (FTS5 search +
diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.toml
index e5b59c2d..127cbb06 100644
--- a/crates/ai-memory-cli/Cargo.toml
+++ b/crates/ai-memory-cli/Cargo.toml
@@ -32,8 +32,10 @@ flate2.workspace = true
rmcp.workspace = true
serde.workspace = true
serde_json.workspace = true
+toml_edit.workspace = true
sysinfo.workspace = true
tar.workspace = true
+jiff.workspace = true
tokio.workspace = true
tokio-util.workspace = true
tracing.workspace = true
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 3f3a10ff..75dab78b 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -74,6 +74,30 @@ pub enum Command {
/// project that's been around for a while. Requires
/// AI_MEMORY_LLM_PROVIDER configured on the server.
Bootstrap(BootstrapArgs),
+ /// Install the ai-memory usage snippet into the project's
+ /// CLAUDE.md / AGENTS.md (or any markdown file you specify).
+ /// Idempotent — bracketed by `<!-- ai-memory:start -->` /
+ /// `<!-- ai-memory:end -->` markers so re-running replaces the
+ /// block in place without duplicating.
+ InstallInstructions(InstallInstructionsArgs),
+}
+
+/// Arguments for `install-instructions`.
+#[derive(Debug, Args)]
+pub struct InstallInstructionsArgs {
+ /// Markdown file to write into. Defaults to `$PWD/CLAUDE.md`.
+ /// Use `--target AGENTS.md` for non-Claude agents, or any other
+ /// path for project-rules files (`.cursor/rules`,
+ /// `.windsurfrules`, etc.).
+ #[arg(long, default_value = "CLAUDE.md")]
+ pub target: PathBuf,
+ /// Print the snippet to stdout instead of mutating the file.
+ /// The default IS mutation here (the print form is also
+ /// available without this command — copy the block from the
+ /// README). Pass `--print` to preview what would land in
+ /// the file.
+ #[arg(long)]
+ pub print: bool,
}
/// Arguments for `bootstrap`.
@@ -380,6 +404,19 @@ pub struct InstallHooksArgs {
/// is set there. Generate one with `ai-memory generate-auth-token`.
#[arg(long, env = "AI_MEMORY_AUTH_TOKEN", hide_env_values = true)]
pub auth_token: Option<String>,
+ /// **Mutate** ~/.claude/settings.json in place instead of just
+ /// printing the snippet. Idempotent — replaces the seven hook
+ /// entries (SessionStart, UserPromptSubmit, …) and preserves
+ /// any other hook config the user has. Only supported for
+ /// `--agent claude-code` today; Codex / OpenCode hook config
+ /// formats are still in flux upstream, so they keep the print
+ /// path. A timestamped backup is written next to the original.
+ #[arg(long)]
+ pub apply: bool,
+ /// Override the settings.json path (auto-detected as
+ /// `~/.claude/settings.json`).
+ #[arg(long)]
+ pub config_file: Option<PathBuf>,
}
/// Arguments for `install-mcp`.
@@ -400,6 +437,17 @@ pub struct InstallMcpArgs {
/// requires it. Picked up from `AI_MEMORY_AUTH_TOKEN` if unset.
#[arg(long, env = "AI_MEMORY_AUTH_TOKEN", hide_env_values = true)]
pub auth_token: Option<String>,
+ /// **Mutate** the client's config file in place instead of just
+ /// printing the snippet. Idempotent: replaces any existing entry
+ /// named `<name>` (default `ai-memory`); preserves every other
+ /// MCP server the user has configured. A timestamped backup is
+ /// written next to the original before each modifying write.
+ #[arg(long)]
+ pub apply: bool,
+ /// Override the config-file path. Auto-detected per client when
+ /// absent (e.g. `~/.claude/settings.json` for Claude Code).
+ #[arg(long)]
+ pub config_file: Option<PathBuf>,
}
/// Transport for the MCP server.
diff --git a/crates/ai-memory-cli/src/commands/apply_shared.rs b/crates/ai-memory-cli/src/commands/apply_shared.rs
new file mode 100644
index 00000000..c5e42408
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/apply_shared.rs
@@ -0,0 +1,319 @@
+//! Filesystem-mutation primitives shared by the `--apply` modes on
+//! `install-mcp`, `install-hooks`, `setup-agent`, and the new
+//! `install-instructions`.
+//!
+//! Every write goes through [`apply_atomic`], which:
+//!
+//! 1. Reads the existing file (or empty string if absent).
+//! 2. Runs the caller-supplied mutator to compute the new content.
+//! 3. If the new content equals the old, returns `NoOp` — never
+//! touches the disk on a redundant call.
+//! 4. Otherwise copies the existing file to `<path>.bak-<unix-ts>`
+//! so the user has a recovery path.
+//! 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.
+
+use std::fs;
+use std::io::Write as _;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result};
+use jiff::Timestamp;
+
+/// What the mutation did to the target file. Surfaced to the user
+/// so they can tell a meaningful change from a redundant re-run.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ApplyOutcome {
+ /// File didn't exist; we created it.
+ Created,
+ /// File existed; our mutation changed it. A backup at
+ /// `<path>.bak-<ts>` records the prior content.
+ Updated,
+ /// File existed and our mutation produced the same content.
+ /// No write happened. No backup written.
+ NoOp,
+}
+
+impl ApplyOutcome {
+ /// Short verb for the CLI report line.
+ #[must_use]
+ pub const fn verb(self) -> &'static str {
+ match self {
+ Self::Created => "created",
+ Self::Updated => "updated",
+ Self::NoOp => "no-op",
+ }
+ }
+}
+
+/// Apply an idempotent mutation to `path`.
+///
+/// `mutator` receives the existing file content (`""` if absent) and
+/// returns the desired new content. The atomicity, backup, and
+/// no-op detection happen here.
+///
+/// # Errors
+/// Propagates IO + mutator failures.
+pub fn apply_atomic<F>(path: &Path, mutator: F) -> Result<ApplyOutcome>
+where
+ F: FnOnce(&str) -> Result<String>,
+{
+ let existed = path.exists();
+ let original = if existed {
+ fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?
+ } else {
+ String::new()
+ };
+
+ let new_content = mutator(&original)?;
+
+ if existed && new_content == original {
+ return Ok(ApplyOutcome::NoOp);
+ }
+
+ if let Some(parent) = path.parent()
+ && !parent.as_os_str().is_empty()
+ {
+ fs::create_dir_all(parent)
+ .with_context(|| format!("ensuring parent directory {}", parent.display()))?;
+ }
+
+ if existed {
+ let backup = backup_path_for(path);
+ fs::copy(path, &backup)
+ .with_context(|| format!("backing up {} → {}", path.display(), backup.display()))?;
+ }
+
+ write_atomic(path, &new_content)?;
+ Ok(if existed {
+ ApplyOutcome::Updated
+ } else {
+ ApplyOutcome::Created
+ })
+}
+
+fn backup_path_for(path: &Path) -> PathBuf {
+ let stamp = Timestamp::now().as_second();
+ let mut bak = path.as_os_str().to_owned();
+ bak.push(format!(".bak-{stamp}"));
+ PathBuf::from(bak)
+}
+
+/// Tempfile + rename atomic write. Sibling tempfile so the rename
+/// is on the same filesystem (avoids cross-mount EXDEV).
+fn write_atomic(path: &Path, content: &str) -> Result<()> {
+ let parent = path.parent().filter(|p| !p.as_os_str().is_empty());
+ let mut tmp = match parent {
+ Some(p) => tempfile::Builder::new()
+ .prefix(".ai-memory-apply-tmp.")
+ .tempfile_in(p),
+ None => tempfile::Builder::new()
+ .prefix(".ai-memory-apply-tmp.")
+ .tempfile(),
+ }
+ .with_context(|| format!("creating tempfile next to {}", path.display()))?;
+ tmp.write_all(content.as_bytes())
+ .context("writing tempfile content")?;
+ tmp.as_file().sync_data().context("fsync tempfile")?;
+ tmp.persist(path)
+ .with_context(|| format!("renaming tempfile into place at {}", path.display()))?;
+ Ok(())
+}
+
+// --------------------------------------------------------------------
+// JSON mutation helpers
+// --------------------------------------------------------------------
+
+/// Parse `original` as JSON (or yield an empty object if blank),
+/// hand the mutable object to `mutator`, and return the
+/// pretty-printed result with a trailing newline.
+///
+/// Errors out with a clear "this file isn't JSON" message rather
+/// than silently overwriting; the user gets a chance to investigate.
+///
+/// # Errors
+/// Returns an error if the input is non-empty and not parseable as
+/// a JSON object.
+pub fn mutate_json<F>(original: &str, mutator: F) -> Result<String>
+where
+ F: FnOnce(&mut serde_json::Map<String, serde_json::Value>) -> Result<()>,
+{
+ let mut root: serde_json::Map<String, serde_json::Value> = if original.trim().is_empty() {
+ serde_json::Map::new()
+ } else {
+ let parsed: serde_json::Value = serde_json::from_str(original).with_context(|| {
+ "existing file isn't valid JSON; refusing to overwrite. Inspect by hand, \
+ rename it, or delete it before re-running --apply."
+ })?;
+ match parsed {
+ serde_json::Value::Object(m) => m,
+ _ => {
+ anyhow::bail!(
+ "existing file is JSON but not an object at the root \
+ (top-level array / string / number). Refusing to overwrite."
+ );
+ }
+ }
+ };
+ mutator(&mut root)?;
+ let mut out = serde_json::to_string_pretty(&serde_json::Value::Object(root))
+ .context("serialising merged JSON")?;
+ if !out.ends_with('\n') {
+ out.push('\n');
+ }
+ Ok(out)
+}
+
+/// Read-mutate-write for TOML files via `toml_edit` (preserves
+/// comments + formatting from the original).
+///
+/// `mutator` receives the parsed `DocumentMut` and can use the full
+/// `toml_edit` API to make changes. Returns the rendered TOML.
+///
+/// # Errors
+/// Returns an error if the input is non-empty and not parseable.
+pub fn mutate_toml<F>(original: &str, mutator: F) -> Result<String>
+where
+ F: FnOnce(&mut toml_edit::DocumentMut) -> Result<()>,
+{
+ let mut doc: toml_edit::DocumentMut = if original.trim().is_empty() {
+ toml_edit::DocumentMut::new()
+ } else {
+ original.parse().with_context(|| {
+ "existing file isn't valid TOML; refusing to overwrite. Inspect by hand, \
+ rename it, or delete it before re-running --apply."
+ })?
+ };
+ mutator(&mut doc)?;
+ Ok(doc.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+
+ #[test]
+ fn apply_to_missing_file_creates() {
+ let tmp = TempDir::new().unwrap();
+ let p = tmp.path().join("nested/dir/foo.json");
+ let outcome = apply_atomic(&p, |_| Ok("hello\n".into())).unwrap();
+ assert_eq!(outcome, ApplyOutcome::Created);
+ assert_eq!(fs::read_to_string(&p).unwrap(), "hello\n");
+ }
+
+ #[test]
+ fn apply_to_unchanged_file_is_noop_and_no_backup() {
+ let tmp = TempDir::new().unwrap();
+ let p = tmp.path().join("foo.json");
+ fs::write(&p, "same\n").unwrap();
+ let outcome = apply_atomic(&p, |_| Ok("same\n".into())).unwrap();
+ assert_eq!(outcome, ApplyOutcome::NoOp);
+ // No .bak-<ts> file should appear.
+ let backups: Vec<_> = fs::read_dir(tmp.path())
+ .unwrap()
+ .flatten()
+ .filter(|e| e.file_name().to_string_lossy().contains(".bak-"))
+ .collect();
+ assert!(backups.is_empty(), "no-op must not create a backup");
+ }
+
+ #[test]
+ fn apply_to_changed_file_backs_up_then_writes() {
+ let tmp = TempDir::new().unwrap();
+ let p = tmp.path().join("foo.json");
+ fs::write(&p, "old\n").unwrap();
+ let outcome = apply_atomic(&p, |_| Ok("new\n".into())).unwrap();
+ assert_eq!(outcome, ApplyOutcome::Updated);
+ assert_eq!(fs::read_to_string(&p).unwrap(), "new\n");
+ let backups: Vec<_> = fs::read_dir(tmp.path())
+ .unwrap()
+ .flatten()
+ .filter(|e| e.file_name().to_string_lossy().contains(".bak-"))
+ .collect();
+ assert_eq!(backups.len(), 1, "exactly one backup file expected");
+ let bak_content = fs::read_to_string(backups[0].path()).unwrap();
+ assert_eq!(bak_content, "old\n");
+ }
+
+ #[test]
+ fn json_mutator_preserves_user_keys() {
+ let original = r#"{"unrelated":"keep me","mcpServers":{"foo":{"url":"http://foo"}}}"#;
+ let out = mutate_json(original, |m| {
+ let servers = m
+ .entry("mcpServers")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .unwrap();
+ servers.insert(
+ "ai-memory".into(),
+ serde_json::json!({"url": "http://homelab:49374/mcp"}),
+ );
+ Ok(())
+ })
+ .unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
+ // Unrelated key survives.
+ assert_eq!(parsed["unrelated"], "keep me");
+ // Sibling MCP server survives.
+ assert_eq!(parsed["mcpServers"]["foo"]["url"], "http://foo");
+ // Ours is added.
+ assert_eq!(
+ parsed["mcpServers"]["ai-memory"]["url"],
+ "http://homelab:49374/mcp"
+ );
+ }
+
+ #[test]
+ fn json_mutator_rejects_non_object_root() {
+ let err = mutate_json("[1,2,3]", |_| Ok(())).unwrap_err();
+ assert!(format!("{err:?}").contains("not an object"));
+ }
+
+ #[test]
+ fn json_mutator_rejects_invalid_json() {
+ let err = mutate_json("{not valid", |_| Ok(())).unwrap_err();
+ assert!(format!("{err:?}").contains("isn't valid JSON"));
+ }
+
+ #[test]
+ fn toml_mutator_preserves_comments_and_other_tables() {
+ let original = "# top comment kept\n\
+ [other]\n\
+ keep = \"this\"\n";
+ let out = mutate_toml(original, |doc| {
+ doc["mcp_servers"]["ai-memory"]["url"] = toml_edit::value("http://homelab:49374/mcp");
+ Ok(())
+ })
+ .unwrap();
+ assert!(out.contains("# top comment kept"));
+ assert!(out.contains("[other]"));
+ assert!(out.contains("keep = \"this\""));
+ assert!(out.contains("ai-memory"));
+ assert!(out.contains("http://homelab:49374/mcp"));
+ }
+
+ #[test]
+ fn idempotent_double_apply_second_is_noop() {
+ // The realistic flow: user runs --apply twice in a row,
+ // second call should be a clean no-op.
+ let tmp = TempDir::new().unwrap();
+ let p = tmp.path().join("settings.json");
+
+ let mutator = |s: &str| {
+ mutate_json(s, |m| {
+ m.insert("foo".into(), serde_json::json!("bar"));
+ Ok(())
+ })
+ };
+ let first = apply_atomic(&p, mutator).unwrap();
+ assert_eq!(first, ApplyOutcome::Created);
+ let second = apply_atomic(&p, mutator).unwrap();
+ assert_eq!(second, ApplyOutcome::NoOp);
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index f4389e86..ba42cedd 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -9,9 +9,10 @@
use std::path::{Path, PathBuf};
-use anyhow::{Context, Result};
+use anyhow::{Context, Result, bail};
use crate::cli::{AgentChoice, InstallHooksArgs};
+use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json};
use crate::commands::render_shared::build_claude_code_payload;
use crate::config::Config;
@@ -22,6 +23,16 @@ use crate::config::Config;
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();
+ if args.apply {
+ if !matches!(args.agent, AgentChoice::ClaudeCode) {
+ bail!(
+ "--apply currently only supports --agent claude-code. Codex / OpenCode \
+ hook config formats are still evolving upstream; print the snippet \
+ (drop --apply) and merge by hand."
+ );
+ }
+ return apply_to_claude_code_settings(&hooks_dir, &args.server_url, auth, &args);
+ }
match args.agent {
AgentChoice::ClaudeCode => render_claude_code(&hooks_dir, &args.server_url, auth),
AgentChoice::Codex => render_agent("codex", &hooks_dir, &args.server_url, auth),
@@ -29,6 +40,58 @@ pub fn run(_config: &Config, args: InstallHooksArgs) -> Result<()> {
}
}
+/// 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.
+fn apply_to_claude_code_settings(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let path = match &args.config_file {
+ Some(p) => p.clone(),
+ None => dirs::home_dir()
+ .context("could not locate $HOME for ~/.claude/settings.json")?
+ .join(".claude")
+ .join("settings.json"),
+ };
+ let payload = build_claude_code_payload(hooks_dir, server_url, auth_token);
+ let our_hooks = payload
+ .get("hooks")
+ .and_then(|v| v.as_object())
+ .context("internal: build_claude_code_payload didn't return a hooks object")?
+ .clone();
+ let outcome = apply_atomic(&path, |existing| {
+ mutate_json(existing, |root| {
+ // Get-or-create the top-level `hooks` table, then OVERLAY
+ // our seven event keys onto the user's table. Anything
+ // they had under a non-overlapping event name (e.g. a
+ // hand-written "Notification" hook) survives.
+ let hooks = root
+ .entry("hooks")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .context("`hooks` is present in settings.json but not an object")?;
+ for (event, value) in &our_hooks {
+ hooks.insert(event.clone(), value.clone());
+ }
+ 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(())
+}
+
fn render_agent(
label: &str,
hooks_dir: &Path,
diff --git a/crates/ai-memory-cli/src/commands/install_instructions.rs b/crates/ai-memory-cli/src/commands/install_instructions.rs
new file mode 100644
index 00000000..36bd99e1
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs
@@ -0,0 +1,179 @@
+//! `ai-memory install-instructions` — drop the proactive-use snippet
+//! into a project's `CLAUDE.md` / `AGENTS.md` / other rules file.
+//!
+//! ## Why this exists
+//!
+//! Lifecycle hooks handle *capture* and *handoff surfacing*
+//! automatically. What they can't do is make the agent *proactively
+//! call* `memory_query` / `memory_recent` when it should — that
+//! decision lives in the model's system prompt, fed turn-by-turn by
+//! the project's CLAUDE.md / AGENTS.md.
+//!
+//! This subcommand drops a small, opinionated snippet into that
+//! file. Idempotent via HTML-comment markers so re-running picks up
+//! whatever the snippet evolves into without duplicating the block.
+
+use anyhow::Result;
+
+use crate::cli::InstallInstructionsArgs;
+use crate::commands::apply_shared::{ApplyOutcome, apply_atomic};
+use crate::config::Config;
+
+/// Marker that opens our managed section. Don't change the wording —
+/// the closing marker, the install-instructions tooling, and any
+/// future "ai-memory uninstall-instructions" all key off this exact
+/// string.
+const MARKER_START: &str = "<!-- ai-memory:start -->";
+const MARKER_END: &str = "<!-- ai-memory:end -->";
+
+/// The canonical snippet body. Lives in code so `install-instructions`
+/// always writes the current recommended copy.
+const SNIPPET_BODY: &str = r#"
+## Long-term memory
+
+This project uses [ai-memory](https://github.com/akitaonrails/ai-memory)
+for cross-session continuity. Lifecycle hooks automatically capture
+every prompt + tool call, and the SessionStart hook surfaces any
+pending cross-agent handoff into the next session's prompt — neither
+needs your prompting.
+
+Beyond that, **proactively use the MCP tools** when the conversation
+calls for it:
+
+- `memory_query` — before proposing architecture, when the user
+ references prior work you don't recognise, or when investigating a
+ bug that might have a known root cause.
+- `memory_recent` — at session start to scan the last few pages of
+ context (complements the auto-injected handoff).
+- `memory_handoff_begin` — optional; only if you want to capture
+ extra context beyond what the SessionEnd hook captures by default.
+
+If you're about to write a durable project rule ("always X", "never
+Y"), this file is where it belongs — ai-memory's lint pass will
+suggest the same.
+"#;
+
+/// Run the `install-instructions` subcommand.
+///
+/// # Errors
+/// Returns an error if the target path can't be written or if the
+/// existing file isn't valid UTF-8.
+pub fn run(_config: &Config, args: InstallInstructionsArgs) -> Result<()> {
+ let block = format!("{MARKER_START}\n{}\n{MARKER_END}\n", SNIPPET_BODY.trim());
+
+ if args.print {
+ // Print mode: show the block + the target path, no mutation.
+ println!("# Would write into: {}\n", args.target.display());
+ println!("{block}");
+ return Ok(());
+ }
+
+ let outcome = apply_atomic(&args.target, |existing| {
+ Ok(merge_instructions_block(existing, &block))
+ })?;
+ println!(
+ "✓ {} {} ({})",
+ outcome.verb(),
+ args.target.display(),
+ match outcome {
+ ApplyOutcome::Created => "new file",
+ ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::NoOp => "already up to date",
+ }
+ );
+ Ok(())
+}
+
+/// Idempotent merge: when the markers exist, replace everything
+/// between them (inclusive) with `block`. When they don't, append
+/// `block` to the end of the file with a single blank-line
+/// separator. The user's other content is never touched.
+fn merge_instructions_block(existing: &str, block: &str) -> String {
+ if let Some(start_idx) = existing.find(MARKER_START)
+ && let Some(end_idx_rel) = existing[start_idx..].find(MARKER_END)
+ {
+ let end_idx = start_idx + end_idx_rel + MARKER_END.len();
+ // Consume a trailing newline after the end marker if present
+ // so we don't accumulate blank lines on every re-run.
+ let after_end = if existing.as_bytes().get(end_idx).copied() == Some(b'\n') {
+ end_idx + 1
+ } else {
+ end_idx
+ };
+ let mut out = String::with_capacity(existing.len() + block.len());
+ out.push_str(&existing[..start_idx]);
+ out.push_str(block);
+ out.push_str(&existing[after_end..]);
+ return out;
+ }
+ // No prior block — append. If the file already ends with a
+ // newline, separate with one blank line; otherwise add the
+ // newline + a blank line.
+ let mut out = existing.to_string();
+ if !out.is_empty() && !out.ends_with('\n') {
+ out.push('\n');
+ }
+ if !out.is_empty() {
+ out.push('\n');
+ }
+ out.push_str(block);
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn merge_appends_to_empty_file() {
+ let out = merge_instructions_block("", "BLOCK\n");
+ assert_eq!(out, "BLOCK\n");
+ }
+
+ #[test]
+ fn merge_appends_when_no_markers_present() {
+ let original = "# My project\n\nSome notes.\n";
+ let out = merge_instructions_block(original, "BLOCK\n");
+ assert!(out.starts_with("# My project"));
+ assert!(out.ends_with("BLOCK\n"));
+ // One blank line between user content and our block.
+ assert!(out.contains("Some notes.\n\nBLOCK\n"));
+ }
+
+ /// Real-world contract: the caller passes a marker-wrapped
+ /// block (that's what `run()` builds). The merge replaces the
+ /// prior bracketed section in place.
+ #[test]
+ fn merge_replaces_existing_block() {
+ let original =
+ format!("# My project\n\n{MARKER_START}\nOLD\n{MARKER_END}\n\nMore notes.\n");
+ let new_block = format!("{MARKER_START}\nNEW BLOCK\n{MARKER_END}\n");
+ let out = merge_instructions_block(&original, &new_block);
+ assert!(out.contains("# My project"));
+ assert!(out.contains("NEW BLOCK"));
+ // Old content gone.
+ assert!(!out.contains("OLD"));
+ // User content after the block is preserved.
+ assert!(out.contains("More notes."));
+ // No duplicate markers.
+ assert_eq!(out.matches(MARKER_START).count(), 1);
+ assert_eq!(out.matches(MARKER_END).count(), 1);
+ }
+
+ #[test]
+ fn merge_idempotent_double_run() {
+ let block = format!("{MARKER_START}\nBLOCK\n{MARKER_END}\n");
+ let first = merge_instructions_block("# Title\n", &block);
+ let second = merge_instructions_block(&first, &block);
+ assert_eq!(first, second, "second merge must be a no-op");
+ }
+
+ /// Defensive: existing file ends without trailing newline. We
+ /// should still produce well-formed output.
+ #[test]
+ fn merge_tolerates_missing_trailing_newline() {
+ let out = merge_instructions_block("# Title", "BLOCK\n");
+ assert!(out.starts_with("# Title\n"));
+ assert!(out.ends_with("BLOCK\n"));
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index 6ccb6f20..13605dce 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -15,10 +15,13 @@
//! author's stated position), we print an explanation + pointers
//! instead of fabricating a config.
-use anyhow::Result;
+use std::path::PathBuf;
+
+use anyhow::{Context, Result, bail};
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::config::Config;
@@ -28,6 +31,15 @@ use crate::config::Config;
/// Returns an error if JSON serialisation fails (should never happen
/// for our handcrafted values).
pub fn run(_config: &Config, args: InstallMcpArgs) -> Result<()> {
+ if args.apply {
+ if matches!(args.client, McpClient::Pi) {
+ bail!(
+ "--apply is not supported for `pi` — pi has no MCP config to mutate. \
+ Run without --apply to print the non-support explanation."
+ );
+ }
+ return apply_to_config_file(&args);
+ }
let snippet = match args.client {
McpClient::ClaudeCode => render_claude_code(&args)?,
McpClient::Codex => render_codex(&args),
@@ -42,6 +54,193 @@ pub fn run(_config: &Config, args: InstallMcpArgs) -> Result<()> {
Ok(())
}
+/// Resolve the user-config file for this client. Honours
+/// `--config-file` when provided, else uses the canonical default
+/// per client.
+fn resolve_config_file(args: &InstallMcpArgs) -> Result<PathBuf> {
+ if let Some(p) = &args.config_file {
+ return Ok(p.clone());
+ }
+ let home = dirs::home_dir().context("could not locate $HOME for config-file auto-detect")?;
+ Ok(match args.client {
+ McpClient::ClaudeCode => home.join(".claude").join("settings.json"),
+ McpClient::Codex => home.join(".codex").join("config.toml"),
+ McpClient::OpenCode => home.join(".config").join("opencode").join("opencode.json"),
+ McpClient::Cursor => home.join(".cursor").join("mcp.json"),
+ McpClient::ClaudeDesktop => {
+ #[cfg(target_os = "macos")]
+ {
+ home.join("Library")
+ .join("Application Support")
+ .join("Claude")
+ .join("claude_desktop_config.json")
+ }
+ #[cfg(target_os = "windows")]
+ {
+ // %APPDATA% is roughly ~/AppData/Roaming.
+ home.join("AppData")
+ .join("Roaming")
+ .join("Claude")
+ .join("claude_desktop_config.json")
+ }
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
+ {
+ bail!(
+ "Claude Desktop is not officially distributed for this OS. \
+ Pass --config-file explicitly if you know where it lives."
+ );
+ }
+ }
+ McpClient::GeminiCli => home.join(".gemini").join("settings.json"),
+ McpClient::Openclaw => home.join(".openclaw").join("config.json"),
+ McpClient::Pi => bail!("pi has no MCP config file (MCP not supported)"),
+ })
+}
+
+/// Mutate the resolved client config file in place. Idempotent —
+/// re-runs that produce the same content are reported as no-op.
+fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {
+ let path = resolve_config_file(args)?;
+ let outcome = match args.client {
+ McpClient::ClaudeCode
+ | McpClient::ClaudeDesktop
+ | McpClient::Cursor
+ | McpClient::GeminiCli => apply_atomic(&path, |existing| {
+ mutate_json(existing, |root| {
+ let entry = build_mcp_entry(args)?;
+ let servers = root
+ .entry("mcpServers")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .context("`mcpServers` is present but not an object")?;
+ servers.insert(args.name.clone(), entry);
+ Ok(())
+ })
+ })?,
+ McpClient::OpenCode => apply_atomic(&path, |existing| {
+ mutate_json(existing, |root| {
+ let entry = build_mcp_entry_opencode(args)?;
+ let mcp = root
+ .entry("mcp")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .context("`mcp` is present but not an object")?;
+ mcp.insert(args.name.clone(), entry);
+ Ok(())
+ })
+ })?,
+ McpClient::Openclaw => apply_atomic(&path, |existing| {
+ mutate_json(existing, |root| {
+ let entry = build_mcp_entry_openclaw(args)?;
+ let mcp = root
+ .entry("mcp")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .context("`mcp` is present but not an object")?;
+ let servers = mcp
+ .entry("servers")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .context("`mcp.servers` is present but not an object")?;
+ servers.insert(args.name.clone(), entry);
+ Ok(())
+ })
+ })?,
+ McpClient::Codex => apply_atomic(&path, |existing| {
+ mutate_toml(existing, |doc| {
+ // `[mcp_servers.<name>]` table.
+ let bearer = bearer_header_value_shared(args.auth_token.as_deref());
+ let key = format!("mcp_servers.{}", args.name);
+ let _ = key; // (used in the comment above; toml_edit indexes via [] chain)
+ doc["mcp_servers"][&args.name]["url"] = toml_edit::value(args.server_url.clone());
+ if let Some(b) = bearer {
+ doc["mcp_servers"][&args.name]["headers"]["Authorization"] =
+ toml_edit::value(b);
+ }
+ Ok(())
+ })
+ })?,
+ McpClient::Pi => unreachable!("pi guarded above"),
+ };
+ 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(())
+}
+
+/// JSON entry shape used by Claude Code, Claude Desktop, Cursor, and
+/// 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 mut entry = serde_json::Map::new();
+ match args.client {
+ McpClient::ClaudeCode => {
+ 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}));
+ }
+ }
+ McpClient::ClaudeDesktop => {
+ // Stdio shim via mcp-remote — Claude Desktop's JSON
+ // doesn't accept HTTP transport directly.
+ let mut cmd_args = vec![json!("-y"), json!("mcp-remote"), json!(args.server_url)];
+ if let Some(b) = &bearer {
+ cmd_args.push(json!("--header"));
+ cmd_args.push(json!(format!("Authorization: {b}")));
+ }
+ entry.insert("command".into(), json!("npx"));
+ entry.insert("args".into(), serde_json::Value::Array(cmd_args));
+ }
+ McpClient::Cursor => {
+ entry.insert("url".into(), json!(args.server_url));
+ if let Some(b) = &bearer {
+ entry.insert("headers".into(), json!({"Authorization": b}));
+ }
+ }
+ McpClient::GeminiCli => {
+ entry.insert("httpUrl".into(), json!(args.server_url));
+ entry.insert("timeout".into(), json!(5000));
+ if let Some(b) = &bearer {
+ entry.insert("headers".into(), json!({"Authorization": b}));
+ }
+ }
+ _ => bail!("internal: build_mcp_entry called for unsupported client"),
+ }
+ Ok(serde_json::Value::Object(entry))
+}
+
+fn build_mcp_entry_opencode(args: &InstallMcpArgs) -> Result<serde_json::Value> {
+ let bearer = bearer_header_value_shared(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));
+ entry.insert("enabled".into(), json!(true));
+ if let Some(b) = bearer {
+ entry.insert("headers".into(), json!({"Authorization": b}));
+ }
+ Ok(serde_json::Value::Object(entry))
+}
+
+fn build_mcp_entry_openclaw(args: &InstallMcpArgs) -> Result<serde_json::Value> {
+ let bearer = bearer_header_value_shared(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"));
+ if let Some(b) = bearer {
+ entry.insert("headers".into(), json!({"Authorization": b}));
+ }
+ 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
@@ -251,6 +450,8 @@ mod tests {
server_url: "http://127.0.0.1:49374/mcp".into(),
name: "ai-memory".into(),
auth_token: None,
+ apply: false,
+ config_file: None,
}
}
@@ -260,6 +461,8 @@ mod tests {
server_url: "http://127.0.0.1:49374/mcp".into(),
name: "ai-memory".into(),
auth_token: Some("test-token-deadbeef".into()),
+ apply: false,
+ config_file: None,
}
}
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index c1d91ab9..a3d7cd80 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -1,5 +1,6 @@
//! Subcommand implementations.
+pub mod apply_shared;
pub mod backup;
pub mod bootstrap;
pub mod commit;
@@ -8,6 +9,7 @@ pub mod forget_sweep;
pub mod generate_auth_token;
pub mod init;
pub mod install_hooks;
+pub mod install_instructions;
pub mod install_mcp;
pub mod lint;
pub mod llm_test;
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 971f32e8..f0b5575d 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -57,5 +57,6 @@ async fn main() -> Result<()> {
Command::GenerateAuthToken(args) => commands::generate_auth_token::run(&config, args),
Command::SetupAgent(args) => commands::setup_agent::run(&config, args),
Command::Bootstrap(args) => commands::bootstrap::run(&config, args).await,
+ Command::InstallInstructions(args) => commands::install_instructions::run(&config, args),
}
}