Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
mcp: add memory_install_self_routing tool + auto-pick CLAUDE.md/AGENTS.md
AkitaOnRails82bc6a168fd5
diff --git a/README.md b/README.mdindex 2d289802..026c71ff 100644--- a/README.md+++ b/README.md@@ -459,23 +459,66 @@ the agent sees a suggestion:ai-memory never edits your `CLAUDE.md` itself — the suggestion isthe whole UX. You copy what's useful, ignore what isn't.+### When the agent reaches for memory++Hooks handle *capture* (every prompt + tool call + session boundary)+and *handoff resume* (SessionStart auto-fetches pending handoffs)+without you typing anything. **Proactive querying** — the agent+reaching into the wiki on its own — depends on the agent knowing+*when* to call which tool. Concrete patterns once the routing+snippet is installed (see "Nudge the agent" below):++| You say… | Agent calls… | Effect |+|---|---|---|+| "Have we discussed X?" / "search memory for Y" | `memory_query` | FTS5 over consolidated wiki pages; returns ranked snippets with `<mark>`-highlighted hits. |+| (before proposing architecture) implicit | `memory_query` | The routing snippet tells the agent to check prior decisions / gotchas before proposing anything, so you don't get contradicted-by-its-own-history suggestions. |+| "Catch me up" / "I've been away" | `memory_explore` | Prose digest. Verbosity auto-scales to time-since-last-activity: < 1 h → one line, > 30 days → full catchup. |+| "Where did we leave off?" | (handoff already prepended) | SessionStart hook already prepended the handoff before your first prompt; the agent just reads from that block. |+| "Save context for the next session" | `memory_handoff_begin` | Writes a terse handoff with `open_questions` + `next_steps` for whichever agent opens this project next. |+| "Consolidate this session" | `memory_consolidate` | Manual trigger of what session-end normally does automatically (compile observations into wiki pages). |+| "Audit the wiki" / "any contradictions?" | `memory_lint` | Runs the stale-page / contradiction / rule-suggestion pass. |+| "How big is the wiki?" / "stats?" | `memory_status`, `memory_briefing` | Counts + recent activity windows. |++The mapping is in the [routing snippet](#nudge-the-agent-to-use-memory-proactively)+the next section installs.+### Nudge the agent to *use* memory proactively-Lifecycle hooks handle *capture* and *handoff resume* without you-typing anything. Proactive *querying* still depends on the agent-thinking to call `memory_query`. For projects where memory matters,-one command installs the recommended snippet into your `CLAUDE.md`:+The capture side works automatically. For the *query* side, the+agent needs a routing table in the project's rules file+(`CLAUDE.md` for Claude Code; `AGENTS.md` for Codex / OpenCode /+Cursor / Gemini CLI). Two ways to install it — pick whichever's+easier in the moment:++**From the agent** (no terminal needed):++> "Install ai-memory routing into this project."++The agent calls the `memory_install_self_routing` MCP tool, gets+back the canonical snippet + a per-agent filename map, then uses+its own Write/Edit tool to land the block in the right rules file+(Claude Code → CLAUDE.md, everyone else → AGENTS.md). Idempotent:+the block is wrapped in `<!-- ai-memory:start -->` /+`<!-- ai-memory:end -->` markers so the agent replaces in place on+re-runs.++**From the terminal**:```bash-ai-memory install-instructions --target ./CLAUDE.md+ai-memory install-instructions # auto-detects CLAUDE.md vs AGENTS.md+ai-memory install-instructions --target AGENTS.md # force a specific file+ai-memory install-instructions --print # preview without writing```-The block is wrapped in `<!-- ai-memory:start -->` /-`<!-- ai-memory:end -->` markers so re-running picks up an updated-snippet without duplicating. Use `--target ./AGENTS.md` for-non-Claude agents, or any other path for project-rules files-(`.cursor/rules`, `.windsurfrules`, etc.). Append `--print` to-preview without writing.+The CLI's auto-detect: if `$PWD/CLAUDE.md` exists, extend that;+if `$PWD/AGENTS.md` exists, extend that; if both exist, write to+both (multi-agent project — keep both files in sync); if neither+exists, create `CLAUDE.md` and print a hint about `--target+AGENTS.md` for non-Claude agents.++Both paths produce the same block. Both replace existing markered+blocks in place rather than duplicating, so you can re-run safely+whenever the snippet evolves (e.g. when a new MCP tool ships).## LLM provider — recommended defaultsdiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex e8963226..11147eb9 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -139,12 +139,15 @@ pub struct RenameProjectArgs {/// 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,+ /// Markdown file to write into. When omitted, the command picks+ /// whichever of `CLAUDE.md` or `AGENTS.md` already exists in+ /// $PWD; if both exist it writes to both; if neither exists it+ /// creates `CLAUDE.md` (Claude Code's convention) and prints a+ /// hint that Codex / OpenCode / Cursor / Gemini users likely+ /// want `--target AGENTS.md` instead. Pass `--target` explicitly+ /// to override the auto-detection.+ #[arg(long)]+ pub target: Option<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 thediff --git a/crates/ai-memory-cli/src/commands/install_instructions.rs b/crates/ai-memory-cli/src/commands/install_instructions.rsindex dd1521db..86e48611 100644--- a/crates/ai-memory-cli/src/commands/install_instructions.rs+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs@@ -13,74 +13,16 @@//! file. Idempotent via HTML-comment markers so re-running picks up//! whatever the snippet evolves into without duplicating the block.-use anyhow::Result;+use anyhow::{Context, 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 (ai-memory)--This project uses [ai-memory](https://github.com/akitaonrails/ai-memory)-for cross-session continuity. **Lifecycle hooks already capture every-prompt + 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.--### When to reach for each tool--The user can express any of the intents below in plain English —-match the intent to the tool. They do not need to name the tool.--| User says / situation | Tool |-|---|---|-| "have we discussed X?" / "search memory for Y" / before proposing architecture | `memory_query` |-| "what's been going on" / "show recent activity" (light) | `memory_recent` |-| "is ai-memory healthy?" / "how big is the wiki?" | `memory_status` |-| "give me the stats" / structured snapshot for the agent to consume | `memory_briefing` |-| "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) |-| "consolidate this session" / "compile what we learned" (usually automatic) | `memory_consolidate` |-| "audit the wiki" / "find contradictions" / "what rules should we add?" | `memory_lint` |-| "prune old pages" / "memory cleanup" | `memory_forget_sweep` |--`memory_explore` is the right default for the "I want to know what's-going on" use case — it returns a prose digest whose verbosity-scales automatically to how long it's been since the last activity-(< 1 h → one line; > 30 days → full catchup).--### When you write a project rule, write it here--If you're about to write a durable project rule ("always X", "never-Y", "all PRs must …"), this file (CLAUDE.md / AGENTS.md) is where-the rule belongs. ai-memory's lint pass surfaces the same hint-automatically when a `kind: rule` page lands in `_rules/`.--### Refreshing this snippet--This block is maintained by ai-memory. To re-sync it with the-latest binary's recommended copy (e.g. when new tools ship), run:--```-ai-memory install-instructions-```--It's idempotent: re-runs replace the block bracketed by-`<!-- ai-memory:start -->` / `<!-- ai-memory:end -->` markers-without disturbing the rest of the file.-"#;+// Markers + the snippet body live in `ai_memory_core::routing_snippet`+// so the `memory_install_self_routing` MCP tool can return the same+// block this subcommand writes. Single source of truth.+use ai_memory_core::{MARKER_END, MARKER_START, full_block};/// Run the `install-instructions` subcommand.///@@ -88,31 +30,76 @@ without disturbing the rest of the file./// 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());+ let block = full_block();+ let targets = resolve_targets(args.target.as_ref())?;if args.print {- // Print mode: show the block + the target path, no mutation.- println!("# Would write into: {}\n", args.target.display());- println!("{block}");+ for t in &targets {+ println!("# Would write into: {}\n", t.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",- }- );+ for target in &targets {+ let outcome = apply_atomic(target, |existing| {+ Ok(merge_instructions_block(existing, &block))+ })?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ target.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ }Ok(())}+/// Decide which file(s) the snippet should land in.+///+/// Precedence:+/// 1. `--target` passed explicitly → use exactly that path (one file).+/// 2. Both `CLAUDE.md` and `AGENTS.md` exist in `$PWD` → write to both+/// (a project that's set up for multiple agent CLIs deserves the+/// snippet in each convention).+/// 3. Only `CLAUDE.md` exists → write to it.+/// 4. Only `AGENTS.md` exists → write to it.+/// 5. Neither exists → default to `CLAUDE.md` AND print a hint about+/// `--target AGENTS.md` for Codex / OpenCode / Cursor / Gemini.+///+/// The auto-pick exists because Claude Code uses CLAUDE.md while+/// every other supported agent (Codex, OpenCode, Cursor, Gemini CLI)+/// converged on AGENTS.md. The heuristic "extend whatever's already+/// there" matches the user's intent better than a hard-coded default.+fn resolve_targets(explicit: Option<&std::path::PathBuf>) -> Result<Vec<std::path::PathBuf>> {+ if let Some(p) = explicit {+ return Ok(vec![p.clone()]);+ }+ let cwd = std::env::current_dir().context("getting CWD for install-instructions target")?;+ let claude_md = cwd.join("CLAUDE.md");+ let agents_md = cwd.join("AGENTS.md");+ let has_claude = claude_md.exists();+ let has_agents = agents_md.exists();+ match (has_claude, has_agents) {+ (true, true) => Ok(vec![claude_md, agents_md]),+ (true, false) => Ok(vec![claude_md]),+ (false, true) => Ok(vec![agents_md]),+ (false, false) => {+ eprintln!(+ "note: neither CLAUDE.md nor AGENTS.md exists in {}; \+ creating CLAUDE.md. If you use Codex / OpenCode / \+ Cursor / Gemini CLI, re-run with `--target AGENTS.md`.",+ cwd.display()+ );+ Ok(vec![claude_md])+ }+ }+}+/// 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-linediff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 95e42109..160a5115 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -10,6 +10,7 @@ pub mod handoff;pub mod ids;pub mod observation;pub mod page;+pub mod routing_snippet;pub mod sanitize;pub use error::{MemoryError, MemoryResult};@@ -19,4 +20,5 @@ pub use ids::{};pub use observation::{NewObservation, NewSession, Observation, ObservationKind};pub use page::{NewPage, Page, Tier};+pub use routing_snippet::{MARKER_END, MARKER_START, SNIPPET_BODY, full_block};pub use sanitize::{SanitizeConfig, Sanitized, Sanitizer};diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rsnew file mode 100644index 00000000..cce05736--- /dev/null+++ b/crates/ai-memory-core/src/routing_snippet.rs@@ -0,0 +1,98 @@+//! Canonical CLAUDE.md / AGENTS.md routing snippet.+//!+//! The agent only proactively calls `memory_query` / `memory_recent` / etc.+//! when the project's CLAUDE.md tells it WHEN to. This module owns the+//! markdown block that defines that "intent → tool" routing table.+//!+//! Two callers consume it:+//!+//! - `ai-memory-cli`'s `install-instructions` subcommand — writes the+//! block into `./CLAUDE.md` directly from the host.+//! - `ai-memory-mcp`'s `memory_install_self_routing` MCP tool — returns+//! the block to the agent, which then uses its own Write/Edit tool+//! to land it in the target file (the MCP server can't reach the+//! agent's host filesystem).+//!+//! Keeping the snippet in one constant means "what gets written" stays+//! consistent across both paths; updating it once propagates.++/// HTML-comment marker that opens the managed section. Anything that+/// edits a CLAUDE.md must key off this exact string — install /+/// uninstall / refresh all locate the block by these markers.+pub const MARKER_START: &str = "<!-- ai-memory:start -->";++/// HTML-comment marker that closes the managed section.+pub const MARKER_END: &str = "<!-- ai-memory:end -->";++/// The canonical snippet body. Trimmed of leading/trailing whitespace+/// by callers; wrap with `MARKER_START` + `MARKER_END` before writing.+pub const SNIPPET_BODY: &str = r#"+## Long-term memory (ai-memory)++This project uses [ai-memory](https://github.com/akitaonrails/ai-memory)+for cross-session continuity. **Lifecycle hooks already capture every+prompt + 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.++### When to reach for each tool++The user can express any of the intents below in plain English —+match the intent to the tool. They do not need to name the tool.++| User says / situation | Tool |+|---|---|+| "have we discussed X?" / "search memory for Y" / before proposing architecture | `memory_query` |+| "what's been going on" / "show recent activity" (light) | `memory_recent` |+| "is ai-memory healthy?" / "how big is the wiki?" | `memory_status` |+| "give me the stats" / structured snapshot for the agent to consume | `memory_briefing` |+| "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) |+| "consolidate this session" / "compile what we learned" (usually automatic) | `memory_consolidate` |+| "audit the wiki" / "find contradictions" / "what rules should we add?" | `memory_lint` |+| "prune old pages" / "memory cleanup" | `memory_forget_sweep` |++`memory_explore` is the right default for the "I want to know what's+going on" use case — it returns a prose digest whose verbosity+scales automatically to how long it's been since the last activity+(< 1 h → one line; > 30 days → full catchup).++### When you write a project rule, write it here++If you're about to write a durable project rule ("always X", "never+Y", "all PRs must …"), this rules file (CLAUDE.md for Claude Code;+AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI; whichever+convention your agent uses) is where it belongs. ai-memory's lint+pass surfaces the same hint automatically when a `kind: rule` page+lands in `_rules/`.++### Refreshing this snippet++This block is maintained by ai-memory. Two ways to refresh it with+the latest binary's recommended copy:++- **From the agent** (no terminal needed): ask "refresh the ai-memory+ routing in this project" — the agent calls+ `memory_install_self_routing`, picks the right filename for itself+ (Claude Code → `CLAUDE.md`; Codex / OpenCode / Cursor / Gemini →+ `AGENTS.md`), and uses its Write / Edit tool to land the block.+- **From the CLI**: `ai-memory install-instructions` (defaults to+ `CLAUDE.md`; pass `--target AGENTS.md` for non-Claude agents).++Both are idempotent: re-runs replace the block bracketed by+`<!-- ai-memory:start -->` / `<!-- ai-memory:end -->` markers+without disturbing the rest of the file.+"#;++/// Build the full markered block that should land in CLAUDE.md /+/// AGENTS.md, including the `<!-- ai-memory:start -->` / `<!-- ai-+/// memory:end -->` wrappers and a trailing newline.+///+/// Both the CLI's `install-instructions` and the MCP tool+/// `memory_install_self_routing` emit this exact string.+#[must_use]+pub fn full_block() -> String {+ format!("{MARKER_START}\n{}\n{MARKER_END}\n", SNIPPET_BODY.trim())+}diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex e8b702ec..90ee1850 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -58,11 +58,17 @@ for them:\n\pages, contradictions, or rule suggestions.\n\- `memory_forget_sweep` — when the user wants to prune old / cold \pages (idempotent, supports dry-run).\n\+- `memory_install_self_routing` — when the user asks to 'install \+ ai-memory routing into this project' or 'add ai-memory to \+ CLAUDE.md / AGENTS.md'. Returns the canonical routing snippet + \+ filename hints; you then use your own Write/Edit tool to land it \+ in the right rules file (Claude Code → CLAUDE.md, Codex / \+ OpenCode / Cursor / Gemini → AGENTS.md).\n\\n\-To configure ai-memory's CLAUDE.md guidance for this project, run \-`ai-memory install-instructions` from the CLI — that updates this \-text in your project's CLAUDE.md / AGENTS.md so the model has the \-same routing table in its system prompt.";+The routing snippet this very text comes from can also be installed \+into the project's CLAUDE.md / AGENTS.md so the guidance survives \+across sessions. From the agent: ask 'install ai-memory routing'. \+From the terminal: `ai-memory install-instructions`.";/// MCP server backed by the ai-memory store.#[derive(Clone)]@@ -643,6 +649,48 @@ impl AiMemoryServer {"briefing": snapshot,}))}++ /// Return the canonical CLAUDE.md / AGENTS.md routing block so the+ /// agent can land it via its own Write/Edit tool. No server-side+ /// state changes — the server can't reach the agent's host+ /// filesystem.+ #[tool(description = "Returns the canonical ai-memory routing snippet \+ (the markdown block that tells the agent WHEN to call \+ memory_query / memory_recent / memory_handoff_accept / etc.) \+ plus filename hints per agent. Use when the user asks 'install \+ ai-memory routing in this project' or 'add ai-memory to \+ CLAUDE.md'. After calling, use your Write/Edit tool to: (a) \+ pick the right rules file for yourself — Claude Code → \+ CLAUDE.md, Codex / OpenCode / Cursor / Gemini CLI → AGENTS.md \+ (or check `agent_filenames` in the response); (b) if the file \+ already has a block bracketed by `<!-- ai-memory:start -->` / \+ `<!-- ai-memory:end -->`, replace that block in place; \+ otherwise append `markered_block` to the file with one blank \+ line of separation. The block IS idempotent — re-runs replace \+ in place. This tool is the source of truth for the snippet; \+ do NOT improvise the routing table from memory.")]+ async fn memory_install_self_routing(&self) -> Result<CallToolResult, McpError> {+ let response = serde_json::json!({+ "markered_block": ai_memory_core::full_block(),+ "marker_start": ai_memory_core::MARKER_START,+ "marker_end": ai_memory_core::MARKER_END,+ "agent_filenames": {+ "claude_code": "CLAUDE.md",+ "codex": "AGENTS.md",+ "opencode": "AGENTS.md",+ "cursor": "AGENTS.md",+ "gemini_cli": "AGENTS.md",+ "default": "AGENTS.md"+ },+ "notes": [+ "Pick the filename matching your own agent identity.",+ "If the target file already contains <!-- ai-memory:start --> / <!-- ai-memory:end -->, replace ONLY that block in place; preserve every other line.",+ "If the file doesn't exist, create it with just the markered_block (plus a trailing newline).",+ "If the file exists but has no ai-memory markers, append the markered_block with one blank line of separation from existing content."+ ]+ });+ ok_json(&response)+ }}#[tool_handler]