Skip to content

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

Rust

Slim ai-memory routing snippet

Thiago Silvadd19d6ed93f6
diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rs
index e3e8e47a..e830fb9f 100644
--- a/crates/ai-memory-core/src/routing_snippet.rs
+++ b/crates/ai-memory-core/src/routing_snippet.rs
@@ -1,8 +1,8 @@
//! 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.
+//! This module owns the slim always-loaded base guidance that points agents at
+//! the ai-memory MCP server and, when installed, the detailed ai-memory Agent
+//! Skills.
//!
//! Two callers consume it:
//!
@@ -32,135 +32,52 @@ pub const SNIPPET_BODY: &str = r#"
This project uses [ai-memory](https://github.com/akitaonrails/ai-memory)
for cross-session continuity.
-**Default to the current project — always.** Every ai-memory tool
+**Default to the current project - always.** Every ai-memory tool
auto-scopes to the project resolved from your session's working
-directory. **Do NOT pass `project`, `workspace`, or `cwd` arguments unless the user
-explicitly references a *different* project by name** (e.g. "what did we
-decide in the `other-app` project?"). Phrases like "this project",
-"here", "we", "our work", "where did we leave off" all mean the *current*
-project — call the tool with no scoping args. If the user asks about a
-handoff and the SessionStart auto-fetched block is already in your
-context, just answer from it; do not re-call the tool to "find it again"
-in another project.
+directory. **Do NOT pass `project`, `workspace`, or `cwd` arguments unless
+the user explicitly references a *different* project by name** (e.g. "what
+did we decide in the `other-app` project?"). Phrases like "this project",
+"here", "we", "our work", and "where did we leave off" all mean the
+*current* project, so call tools with no scoping args.
-**Lifecycle hooks already capture every prompt + tool call
-automatically.** You never need to manually write routine notes; the
-SessionStart hook auto-fetches pending handoffs, and on session end
-ai-memory writes a session-summary page and a handoff.
-LLM consolidation (compiling observations into topical wiki pages) runs
-on PreCompact, on demand via `memory_consolidate`, and at session end
-only when the server sets `AI_MEMORY_CONSOLIDATE_ON_SESSION_END`. Only
-write a durable wiki page when the user explicitly asks to remember or
-annotate something permanently.
+**Lifecycle hooks already capture every prompt and tool call
+automatically.** Do not manually write routine notes. Only write durable
+memory when the user explicitly asks to remember or annotate something
+permanently.
-### When to reach for each tool
+### Use the installed ai-memory Agent Skills
-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` (current project; `scopes` for named siblings; `global=true` to search every project) |
-| "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` (read-only; never creates handoffs) |
-| "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; pass `workspace` + `project` together only for a named sibling workspace/project) |
-| "save context for the next session" / wrapping up / ending this session | `memory_handoff_begin` (session-end only; do **not** use for status/briefing; single-use handoff; terse summary; put detail in `open_questions` + `next_steps` bullets; pass `workspace` + `project` together only for a named sibling workspace/project) |
-| "discard that handoff" / "I created a handoff by mistake" | `memory_handoff_cancel` (requires exact `handoff_id` from `memory_handoff_begin`; marks it expired before the next session sees it) |
-| "consolidate this session" / "compile what we learned" (also runs on PreCompact; at session end only if `AI_MEMORY_CONSOLIDATE_ON_SESSION_END` is set) | `memory_consolidate` |
-| "what did we learn from this session?" / "what memory should we add?" / explicit wrap-up learning review | `memory_auto_improve` (manual learning review for a completed session; omit `session_id` for latest completed session; the server also schedules background review for newly completed sessions in every project when configured) |
-| "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; put the title as a `# H1` on the first line of `body` and omit the `title` arg — ai-memory derives it from the H1) |
-| "read the page about X" / "show me the full content of Y" / "open the page on Z" | `memory_read_page` (full body; pass a query to search or `path` for a direct lookup; pass `workspace` + `project` together only for a named sibling workspace/project) |
-| "delete the page X" / "remove that note" | `memory_delete_page` (by exact `path`; idempotent; pass `workspace` + `project` together only for a named sibling workspace/project) |
-| "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 the current project comes up empty — broaden the search
-
-`memory_query` searches only the **current** project by default. If a
-search comes back empty or thin, the knowledge may live in a **sibling
-project** — shared `infra`, `ops`, or a related app. Don't conclude
-"we never recorded it" after a single project misses; broaden instead:
-
-- **Know which projects to check?** Re-run with explicit `scopes`, e.g.
- `scopes: [{ "workspace": "default", "project": "infra" }]`.
-- **Don't know where it lives?** Pass `global=true` to search every
- project in every workspace at once. Each hit is annotated with its
- workspace + project so you can tell where it came from. `global=true`
- cannot be combined with `scopes`/`project`/`workspace`.
-
-`memory_query` returns **snippets, not full page bodies** — an empty or
-short snippet does **not** mean the page is empty (a large page can
-match outside the snippet window). To read the whole page, use
-`memory_read_page` (by `path`, or pass a `query` to fetch the top hit's
-full body; add `workspace` + `project` together only when the user names
-a sibling workspace/project).
-
-### Use Retrieved Memory As Operating Guidance
-
-When `memory_query` or `memory_recent` returns `_rules/`, `gotchas/`,
-`procedures/`, or `decisions/` pages that match the current task, treat
-them as actionable context, not trivia:
-
-- Read full pages with `memory_read_page` when the snippet looks relevant.
-- Apply `_rules/` as constraints.
-- Check `gotchas/` as preflight warnings before editing the same subsystem.
-- Follow `procedures/` as checklists for releases, PR reviews, deploys,
- migrations, and other repeatable workflows.
-- Use `decisions/` as prior architecture unless the user explicitly asks
- to revisit them.
-
-Before non-trivial coding, debugging, deployment, release, auth, scope,
-migration, PR-review, or data-preservation work, search memory for the
-subsystem and task type first. If the first query is thin, broaden or
-query specific error/subsystem terms before designing a fix.
-
-### Learning Review
-
-The server schedules background auto-improvement for newly completed sessions in
-every project when an LLM provider is configured. `memory_auto_improve` is the manual version:
-use it when the user asks what durable lessons this session suggests, or at
-explicit wrap-up when reviewing proposed memory would be useful. Scheduled and
-manual runs apply or stage validated edits through the auto-improvement approval
-path. Admins can turn off scheduling with `[auto_improve.scheduler] enabled =
-false`, or opt into manual proposal approval with `[auto_improve]
-require_approval = true`, in which case scheduled and manual proposals stay in
-pending-writes until approved.
+Detailed tool-routing guidance lives in the installed ai-memory Agent
+Skills. When a task matches an installed ai-memory Agent Skill, load and
+follow that skill before calling ai-memory tools. The skills cover memory
+retrieval, handoffs, durable pages, learning maintenance, and routing
+install or refresh work.
### 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 …"), write it in the project's canonical agent
-instruction file. Many projects use CLAUDE.md for Claude Code and
-AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI, but if the
-project says one file is canonical, use that file. ai-memory's lint
-pass surfaces the same hint automatically when a `kind: rule` page
-lands in `_rules/`.
+Y", "all PRs must ..."), write it in the project's canonical agent instruction file.
+Many projects use CLAUDE.md for Claude Code and
+AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI, but if the project
+says one file is canonical, use that file.
### Refreshing this snippet
-This block is maintained by ai-memory. Two ways to refresh it with
-the latest binary's recommended copy:
+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.
+ 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 or
- projects that use `AGENTS.md` as the canonical instruction file).
+ `CLAUDE.md`; pass `--target AGENTS.md` for non-Claude agents or projects
+ that use `AGENTS.md` as the canonical instruction file).
Both are idempotent: re-runs replace the block bracketed by
-`<!-- ai-memory:start -->` / `<!-- ai-memory:end -->` markers
-without disturbing the rest of the file.
+`<!-- 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 /
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 962afa22..feb70683 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -2412,6 +2412,65 @@ mod tests {
(tmp, store, server, ws, proj)
}
+ fn installed_ai_memory_prompt_surface() -> String {
+ let mut prompt = String::from(ai_memory_core::SNIPPET_BODY);
+ for skill in ai_memory_core::routing_skills::MANAGED_SKILLS {
+ prompt.push_str("\n\n");
+ prompt.push_str(skill.content);
+ }
+ prompt
+ }
+
+ fn combined_ai_memory_prompt_surface() -> String {
+ let mut prompt = String::from(MEMORY_INSTRUCTIONS);
+ prompt.push_str("\n\n");
+ prompt.push_str(&installed_ai_memory_prompt_surface());
+ prompt
+ }
+
+ fn assert_detailed_prompt_surfaces(mut assert_prompt: impl FnMut(&str, &str)) {
+ assert_prompt("MCP handshake instructions", MEMORY_INSTRUCTIONS);
+ let combined = combined_ai_memory_prompt_surface();
+ assert_prompt("combined MCP, snippet, and managed skill prompts", &combined);
+ }
+
+ const MCP_TOOL_NAMES: &[&str] = &[
+ "memory_query",
+ "memory_recent",
+ "memory_status",
+ "memory_briefing",
+ "memory_explore",
+ "memory_handoff_accept",
+ "memory_handoff_begin",
+ "memory_handoff_cancel",
+ "memory_consolidate",
+ "memory_auto_improve",
+ "memory_write_page",
+ "memory_read_page",
+ "memory_delete_page",
+ "memory_lint",
+ "memory_forget_sweep",
+ "memory_install_self_routing",
+ ];
+
+ const DETAILED_ROUTING_TOOL_NAMES: &[&str] = &[
+ "memory_query",
+ "memory_recent",
+ "memory_status",
+ "memory_briefing",
+ "memory_explore",
+ "memory_handoff_accept",
+ "memory_handoff_begin",
+ "memory_handoff_cancel",
+ "memory_consolidate",
+ "memory_auto_improve",
+ "memory_write_page",
+ "memory_read_page",
+ "memory_delete_page",
+ "memory_lint",
+ "memory_forget_sweep",
+ ];
+
#[test]
fn actor_key_uses_memory_session_header() {
let mut parts = test_parts_default();
@@ -2470,44 +2529,80 @@ mod tests {
#[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_handoff_cancel",
- "memory_consolidate",
- "memory_auto_improve",
- "memory_write_page",
- "memory_read_page",
- "memory_delete_page",
- "memory_lint",
- "memory_forget_sweep",
- "memory_install_self_routing",
- ];
- let routing = ai_memory_core::full_block();
- for tool in tools {
+ for tool in MCP_TOOL_NAMES {
assert!(
MEMORY_INSTRUCTIONS.contains(tool),
"MCP handshake instructions omit {tool}"
);
+ }
+
+ let installed = installed_ai_memory_prompt_surface();
+ for tool in MCP_TOOL_NAMES {
assert!(
- routing.contains(tool),
- "routing snippet omit {tool}; update ai_memory_core::SNIPPET_BODY"
+ installed.contains(tool),
+ "installed snippet and managed skills omit {tool}"
);
}
}
+ #[test]
+ fn snippet_keeps_always_loaded_invariants() {
+ let snippet = ai_memory_core::SNIPPET_BODY;
+ assert!(snippet.contains("Long-term memory (ai-memory)"));
+ assert!(snippet.contains("Default to the current project"));
+ assert!(
+ snippet.contains("Do NOT pass `project`, `workspace`, or `cwd`"),
+ "snippet must preserve current-project scope defaulting"
+ );
+ assert!(
+ snippet.contains("Lifecycle hooks already capture"),
+ "snippet must keep automatic lifecycle capture guidance"
+ );
+ assert!(
+ snippet.contains("durable")
+ && snippet.contains("explicitly asks")
+ && (snippet.contains("permanent") || snippet.contains("permanently")),
+ "snippet must say durable writes require an explicit user request"
+ );
+ assert!(
+ snippet.contains("Agent Skills") && snippet.contains("installed"),
+ "snippet must route detailed guidance through installed Agent Skills"
+ );
+ assert!(
+ snippet.contains("canonical agent instruction file"),
+ "snippet must keep canonical project-rule placement guidance"
+ );
+ assert!(
+ snippet.contains("memory_install_self_routing")
+ && snippet.contains("ai-memory install-instructions"),
+ "snippet must preserve refresh/install guidance"
+ );
+ assert!(
+ snippet.contains(ai_memory_core::MARKER_START)
+ && snippet.contains(ai_memory_core::MARKER_END),
+ "snippet must preserve marker replacement guidance"
+ );
+ }
+
+ #[test]
+ fn snippet_omits_detailed_tool_routing_table() {
+ let snippet = ai_memory_core::SNIPPET_BODY;
+ assert!(!snippet.contains("### When to reach for each tool"));
+ assert!(!snippet.contains("| User says / situation | Tool |"));
+ for tool in DETAILED_ROUTING_TOOL_NAMES {
+ assert!(
+ !snippet.contains(tool),
+ "slim snippet must leave detailed {tool} routing to managed skills"
+ );
+ }
+ }
#[test]
fn prompts_separate_briefing_from_handoff_lifecycle() {
- for prompt in [MEMORY_INSTRUCTIONS, ai_memory_core::SNIPPET_BODY] {
+ assert_detailed_prompt_surfaces(|label, prompt| {
let lower = prompt.to_ascii_lowercase();
assert!(
prompt.contains("memory_briefing") && lower.contains("read-only"),
- "briefing guidance must say it is read-only"
+ "{label} must say briefing is read-only"
);
assert!(
prompt.contains("memory_handoff_begin")
@@ -2516,15 +2611,14 @@ mod tests {
&& (lower.contains("do not use") || lower.contains("do **not** use"))
&& lower.contains("status")
&& lower.contains("briefing"),
- "handoff-begin guidance must be session-end only and reject status/briefing use"
+ "{label} must make handoff-begin session-end only and reject status/briefing use"
);
assert!(
prompt.contains("memory_handoff_cancel") && prompt.contains("handoff_id"),
- "cancel guidance must expose exact-id cleanup for mistaken handoffs"
+ "{label} must expose exact-id cleanup for mistaken handoffs"
);
- }
+ });
}
-
#[test]
fn prompts_teach_cross_project_search_strategy() {
// Regression: a single-project miss must not read as "never recorded".
@@ -2534,22 +2628,22 @@ mod tests {
// legacy "no global mode" phrasing that briefly shipped in #56.
// (Learned the hard way when cluster-access info lived in a sibling
// `infra` project.)
- for prompt in [MEMORY_INSTRUCTIONS, ai_memory_core::SNIPPET_BODY] {
+ assert_detailed_prompt_surfaces(|label, prompt| {
assert!(
prompt.contains("scopes"),
- "prompt must teach broadening via `scopes`"
+ "{label} must teach broadening via `scopes`"
);
assert!(
prompt.contains("global=true") || prompt.contains("global = true"),
- "prompt must also teach broadening via `global=true`"
+ "{label} must also teach broadening via `global=true`"
);
assert!(
prompt.contains("sibling") || prompt.contains("SIBLING"),
- "prompt must mention knowledge can live in a sibling project"
+ "{label} must mention knowledge can live in a sibling project"
);
assert!(
prompt.contains("snippet") || prompt.contains("SNIPPET"),
- "prompt must warn that query returns snippets, not full bodies"
+ "{label} must warn that query returns snippets, not full bodies"
);
// Guard against the contradiction: standalone prose must not say
// a global mode doesn't exist when the bullet/table-row above it
@@ -2563,72 +2657,70 @@ mod tests {
for phrase in no_global_phrases {
assert!(
!prompt.contains(phrase),
- "prompt must not contain the contradictory phrase {phrase:?}"
+ "{label} must not contain the contradictory phrase {phrase:?}"
);
}
- }
+ });
}
+
#[test]
fn prompts_route_permanent_annotations_to_write_page_not_handoff() {
- for prompt in [MEMORY_INSTRUCTIONS, ai_memory_core::SNIPPET_BODY] {
+ assert_detailed_prompt_surfaces(|label, prompt| {
assert!(
prompt.contains("permanent") || prompt.contains("permanently"),
- "prompt must mention permanent memory use cases"
+ "{label} must mention permanent memory use cases"
);
assert!(
prompt.contains("memory_write_page"),
- "prompt must expose memory_write_page"
+ "{label} must expose memory_write_page"
);
assert!(
prompt.contains("do NOT use") || prompt.contains("do **not** use"),
- "prompt must explicitly disallow handoffs for permanent notes"
+ "{label} must explicitly disallow handoffs for permanent notes"
);
- }
+ });
}
-
#[test]
fn prompts_treat_retrieved_memory_as_actionable_guidance() {
- for prompt in [MEMORY_INSTRUCTIONS, ai_memory_core::SNIPPET_BODY] {
+ assert_detailed_prompt_surfaces(|label, prompt| {
let lower = prompt.to_ascii_lowercase();
assert!(
prompt.contains("_rules/")
&& prompt.contains("gotchas/")
&& prompt.contains("procedures/")
&& prompt.contains("decisions/"),
- "prompt must name actionable page families"
+ "{label} must name actionable page families"
);
assert!(
lower.contains("constraints")
&& lower.contains("preflight")
&& lower.contains("checklists"),
- "prompt must teach how to use rules/gotchas/procedures"
+ "{label} must teach how to use rules/gotchas/procedures"
);
assert!(
lower.contains("before non-trivial")
&& lower.contains("auth")
&& lower.contains("migration"),
- "prompt must make proactive retrieval the default for risky work"
+ "{label} must make proactive retrieval the default for risky work"
);
- }
+ });
}
-
#[tokio::test]
async fn prompts_expose_auto_improve_as_auto_approval_with_manual_opt_in() {
- for prompt in [MEMORY_INSTRUCTIONS, ai_memory_core::SNIPPET_BODY] {
+ assert_detailed_prompt_surfaces(|label, prompt| {
let lower = prompt.to_ascii_lowercase();
assert!(prompt.contains("memory_auto_improve"));
assert!(
lower.contains("applies validated")
|| (lower.contains("approval") && lower.contains("path")),
- "prompt must state auto-improve applies through the approval path"
+ "{label} must state auto-improve applies through the approval path"
);
assert!(
lower.contains("require_approval") && lower.contains("pending-writes"),
- "prompt must describe the manual review opt-in"
+ "{label} must describe the manual review opt-in"
);
- }
-
+ });
let (_tmp, _store, server, _ws, _pj) = setup_server().await;
let tools = server.tool_router.list_all();
let auto_improve = tools
@@ -2645,23 +2737,23 @@ mod tests {
#[test]
fn prompts_teach_cross_workspace_handoff_scope() {
- for prompt in [MEMORY_INSTRUCTIONS, ai_memory_core::SNIPPET_BODY] {
+ assert_detailed_prompt_surfaces(|label, prompt| {
assert!(
prompt.contains("memory_handoff_begin") && prompt.contains("memory_handoff_accept"),
- "prompt must include handoff lifecycle tools"
+ "{label} must include handoff lifecycle tools"
);
assert!(
prompt.contains("workspace") && prompt.contains("project"),
- "handoff prompt guidance must mention workspace+project scoping"
+ "{label} handoff guidance must mention workspace+project scoping"
);
assert!(
prompt.contains("sibling")
&& (prompt.contains("workspace/project")
|| prompt.contains("workspace + project")
|| prompt.contains("workspace` + `project")),
- "handoff prompt guidance must restrict explicit workspace scope to named siblings"
+ "{label} handoff guidance must restrict explicit workspace scope to named siblings"
);
- }
+ });
}
/// All three prompt surfaces must steer agents toward the H1-in-body
@@ -2670,22 +2762,22 @@ mod tests {
/// fails to escape quotes (issue #67); routing every "remember this"
/// call through the H1 path avoids the footgun entirely.
///
- /// The three surfaces — `MEMORY_INSTRUCTIONS`, the routing snippet
- /// (`SNIPPET_BODY`), and the per-tool `#[tool(description=...)]`
- /// string surfaced via `tools/list` — are independent and must be
- /// kept aligned per the CLAUDE.md "MCP tool surface changes" rule.
+ /// The three surfaces - `MEMORY_INSTRUCTIONS`, the installed routing
+ /// surface (`SNIPPET_BODY` plus managed skills), and the per-tool
+ /// `#[tool(description=...)]` string surfaced via `tools/list` - are
+ /// independent and must stay aligned.
#[tokio::test]
async fn prompts_steer_write_page_toward_h1_title_convention() {
- for prompt in [MEMORY_INSTRUCTIONS, ai_memory_core::SNIPPET_BODY] {
+ assert_detailed_prompt_surfaces(|label, prompt| {
assert!(
prompt.contains("H1"),
- "prompt must mention the H1 title convention for memory_write_page"
+ "{label} must mention the H1 title convention for memory_write_page"
);
assert!(
prompt.contains("omit") || prompt.contains("Omit"),
- "prompt must tell the agent to omit the `title` argument"
+ "{label} must tell the agent to omit the `title` argument"
);
- }
+ });
// The third surface: the rmcp tool description sent to clients
// via `tools/list`. Spell-checked against the same keywords so
// that a future edit cannot silently drop the guidance from the