Skip to content

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

Rust

Add managed ai-memory routing skills

Thiago Silva649b7e5fff5d
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 52bcbd07..8d98d595 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -12,6 +12,7 @@ pub mod handoff;
pub mod ids;
pub mod observation;
pub mod page;
+pub mod routing_skills;
pub mod routing_snippet;
pub mod sanitize;
pub mod user;
diff --git a/crates/ai-memory-core/src/routing_skills.rs b/crates/ai-memory-core/src/routing_skills.rs
new file mode 100644
index 00000000..af971ecf
--- /dev/null
+++ b/crates/ai-memory-core/src/routing_skills.rs
@@ -0,0 +1,203 @@
+//! Canonical managed ai-memory Agent Skill assets.
+//!
+//! The installer-facing crates consume these definitions so every path that
+//! writes ai-memory routing skills uses the same metadata and `SKILL.md` bytes.
+
+/// Stable ownership marker embedded in every managed ai-memory skill file.
+pub const MANAGED_MARKER: &str = "<!-- ai-memory-managed: routing-skill -->";
+
+const RETRIEVAL_DESCRIPTION: &str = "Use when the user asks to search memory, catch up, inspect recent activity, read wiki pages, get ai-memory stats, query prior decisions, or apply remembered rules before design or debugging.";
+const HANDOFF_DESCRIPTION: &str = "Use when the user asks where we left off, whether there is a pending handoff, to save context for the next session, to end or wrap up a session, or to discard a mistaken handoff.";
+const DURABLE_PAGES_DESCRIPTION: &str = "Use when the user explicitly asks to remember something permanently, save a durable project note, add an annotation, create a wiki page, delete a memory page, or record a project rule.";
+const LEARNING_MAINTENANCE_DESCRIPTION: &str = "Use when the user asks to consolidate memory, review what was learned, propose durable lessons, audit the wiki, find contradictions, prune old memory, or run auto-improvement maintenance.";
+const ROUTING_INSTALL_DESCRIPTION: &str = "Use when the user asks to install, refresh, update, repair, or remove ai-memory routing instructions or Agent Skills in CLAUDE.md, AGENTS.md, .claude/skills, or .agents/skills.";
+
+/// One ai-memory-managed Agent Skill file bundled by the core crate.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct ManagedSkill {
+ /// Skill directory name and frontmatter `name` value.
+ pub name: &'static str,
+ /// Trigger-rich frontmatter `description` value.
+ pub description: &'static str,
+ /// File path relative to an agent skill root.
+ pub relative_path: &'static str,
+ /// Complete `SKILL.md` contents.
+ pub content: &'static str,
+}
+
+/// Canonical managed ai-memory routing skills.
+pub const MANAGED_SKILLS: &[ManagedSkill] = &[
+ ManagedSkill {
+ name: "ai-memory-retrieval",
+ description: RETRIEVAL_DESCRIPTION,
+ relative_path: "ai-memory-retrieval/SKILL.md",
+ content: include_str!("routing_skills/ai-memory-retrieval/SKILL.md"),
+ },
+ ManagedSkill {
+ name: "ai-memory-handoff",
+ description: HANDOFF_DESCRIPTION,
+ relative_path: "ai-memory-handoff/SKILL.md",
+ content: include_str!("routing_skills/ai-memory-handoff/SKILL.md"),
+ },
+ ManagedSkill {
+ name: "ai-memory-durable-pages",
+ description: DURABLE_PAGES_DESCRIPTION,
+ relative_path: "ai-memory-durable-pages/SKILL.md",
+ content: include_str!("routing_skills/ai-memory-durable-pages/SKILL.md"),
+ },
+ ManagedSkill {
+ name: "ai-memory-learning-maintenance",
+ description: LEARNING_MAINTENANCE_DESCRIPTION,
+ relative_path: "ai-memory-learning-maintenance/SKILL.md",
+ content: include_str!("routing_skills/ai-memory-learning-maintenance/SKILL.md"),
+ },
+ ManagedSkill {
+ name: "ai-memory-routing-install",
+ description: ROUTING_INSTALL_DESCRIPTION,
+ relative_path: "ai-memory-routing-install/SKILL.md",
+ content: include_str!("routing_skills/ai-memory-routing-install/SKILL.md"),
+ },
+];
+
+#[cfg(test)]
+mod tests {
+ use std::collections::BTreeMap;
+
+ use super::{MANAGED_MARKER, MANAGED_SKILLS, ManagedSkill};
+
+ const EXPECTED_SKILLS: &[&str] = &[
+ "ai-memory-retrieval",
+ "ai-memory-handoff",
+ "ai-memory-durable-pages",
+ "ai-memory-learning-maintenance",
+ "ai-memory-routing-install",
+ ];
+
+ const EXPECTED_TOOL_CLUSTERS: &[(&str, &str)] = &[
+ ("memory_query", "ai-memory-retrieval"),
+ ("memory_recent", "ai-memory-retrieval"),
+ ("memory_read_page", "ai-memory-retrieval"),
+ ("memory_status", "ai-memory-retrieval"),
+ ("memory_briefing", "ai-memory-retrieval"),
+ ("memory_explore", "ai-memory-retrieval"),
+ ("memory_handoff_accept", "ai-memory-handoff"),
+ ("memory_handoff_begin", "ai-memory-handoff"),
+ ("memory_handoff_cancel", "ai-memory-handoff"),
+ ("memory_write_page", "ai-memory-durable-pages"),
+ ("memory_delete_page", "ai-memory-durable-pages"),
+ ("memory_consolidate", "ai-memory-learning-maintenance"),
+ ("memory_auto_improve", "ai-memory-learning-maintenance"),
+ ("memory_lint", "ai-memory-learning-maintenance"),
+ ("memory_forget_sweep", "ai-memory-learning-maintenance"),
+ ("memory_install_self_routing", "ai-memory-routing-install"),
+ ];
+
+ #[derive(Debug)]
+ struct Frontmatter<'a> {
+ name: &'a str,
+ description: &'a str,
+ }
+
+ #[test]
+ fn exposes_exact_managed_skill_set() {
+ let names: Vec<_> = MANAGED_SKILLS.iter().map(|skill| skill.name).collect();
+ assert_eq!(names, EXPECTED_SKILLS);
+ }
+
+ #[test]
+ fn skill_frontmatter_is_valid_and_matches_metadata() {
+ for skill in MANAGED_SKILLS {
+ let frontmatter = parse_frontmatter(skill);
+ assert_eq!(frontmatter.name, skill.name);
+ assert_eq!(frontmatter.description, skill.description);
+ assert_eq!(frontmatter.name, directory_name(skill));
+ assert!(!frontmatter.description.trim().is_empty());
+ assert!(
+ frontmatter.description.chars().count() <= 1024,
+ "{} description is over the Agent Skills limit",
+ skill.name
+ );
+ }
+ }
+
+ #[test]
+ fn every_skill_has_managed_marker() {
+ assert!(!MANAGED_MARKER.is_empty());
+ for skill in MANAGED_SKILLS {
+ assert!(
+ skill.content.contains(MANAGED_MARKER),
+ "{} is missing the managed ownership marker",
+ skill.name
+ );
+ }
+ }
+
+ #[test]
+ fn relative_paths_are_skill_markdown_files() {
+ for skill in MANAGED_SKILLS {
+ let expected_suffix = format!("{}/SKILL.md", skill.name);
+ assert_eq!(skill.relative_path, expected_suffix);
+ }
+ }
+
+ #[test]
+ fn every_routing_tool_appears_only_in_its_intended_cluster() {
+ let expected_by_tool: BTreeMap<_, _> = EXPECTED_TOOL_CLUSTERS.iter().copied().collect();
+ assert_eq!(expected_by_tool.len(), EXPECTED_TOOL_CLUSTERS.len());
+
+ for (tool, expected_skill) in expected_by_tool {
+ let containing_skills: Vec<_> = MANAGED_SKILLS
+ .iter()
+ .filter(|skill| skill.content.contains(tool))
+ .map(|skill| skill.name)
+ .collect();
+
+ assert_eq!(
+ containing_skills,
+ vec![expected_skill],
+ "{tool} should appear in exactly one intended skill"
+ );
+ }
+ }
+
+ fn parse_frontmatter(skill: &ManagedSkill) -> Frontmatter<'_> {
+ let mut lines = skill.content.lines();
+ assert_eq!(
+ lines.next(),
+ Some("---"),
+ "{} must start with frontmatter",
+ skill.name
+ );
+
+ let mut name = None;
+ let mut description = None;
+ let mut closed = false;
+ for line in lines.by_ref() {
+ if line == "---" {
+ closed = true;
+ break;
+ }
+
+ if let Some(value) = line.strip_prefix("name: ") {
+ name = Some(value.trim());
+ } else if let Some(value) = line.strip_prefix("description: ") {
+ description = Some(value.trim());
+ }
+ }
+ assert!(closed, "{} must close frontmatter", skill.name);
+
+ Frontmatter {
+ name: name.unwrap_or_else(|| panic!("{} is missing frontmatter name", skill.name)),
+ description: description
+ .unwrap_or_else(|| panic!("{} is missing frontmatter description", skill.name)),
+ }
+ }
+
+ fn directory_name(skill: &ManagedSkill) -> &str {
+ skill
+ .relative_path
+ .split('/')
+ .next()
+ .unwrap_or_else(|| panic!("{} has an empty relative path", skill.name))
+ }
+}
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md
new file mode 100644
index 00000000..a1ae60d6
--- /dev/null
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md
@@ -0,0 +1,32 @@
+---
+name: ai-memory-durable-pages
+description: Use when the user explicitly asks to remember something permanently, save a durable project note, add an annotation, create a wiki page, delete a memory page, or record a project rule.
+---
+<!-- ai-memory-managed: routing-skill -->
+
+# ai-memory durable pages
+
+Use this skill only for deliberate durable wiki mutations. Routine session capture is automatic, and permanent notes require an explicit user request.
+
+## Tools in this cluster
+
+- `memory_write_page` writes a durable wiki page for permanent project knowledge.
+- `memory_delete_page` removes a durable wiki page by exact path.
+
+## Writing durable memory
+
+Write a page only when the user explicitly asks to remember something permanently, save a note, add an annotation, or record project knowledge. Do not use durable pages for transient progress, normal status updates, or next-session context.
+
+Put the page title as a `# H1` on the first line of the body and omit the separate title argument. ai-memory derives the title from that H1. Keep the content concise and fact-like, with enough context that a future agent can apply it without rereading the whole session.
+
+## Project rules belong in instructions first
+
+If the user asks to create a durable project rule such as always do X or never do Y, update the project's canonical agent instruction file when the repository says one exists. Use a durable page only when the user explicitly wants the rule in the wiki too, or when no canonical instruction file applies.
+
+## Deleting durable memory
+
+Delete only by exact path. If the user gives a vague title or topic, first resolve it to the page path using read-only lookup. Preserve sibling projects unless the user explicitly names them.
+
+## Scope default
+
+Default to the current project. Pass workspace and project together only when the user explicitly names a different project. Never pass scope arguments for phrases like this project, here, we, or our work.
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md
new file mode 100644
index 00000000..707e0036
--- /dev/null
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md
@@ -0,0 +1,35 @@
+---
+name: ai-memory-handoff
+description: Use when the user asks where we left off, whether there is a pending handoff, to save context for the next session, to end or wrap up a session, or to discard a mistaken handoff.
+---
+<!-- ai-memory-managed: routing-skill -->
+
+# ai-memory handoff
+
+Use this skill for single-use cross-session handoffs. Handoffs are for the next agent, not durable project documentation.
+
+## Tools in this cluster
+
+- `memory_handoff_accept` consumes the pending handoff when the user asks where we left off and no already-fetched handoff block is visible.
+- `memory_handoff_begin` creates a terse next-session handoff only when the user is wrapping up, ending the session, or explicitly asks to save context for the next session.
+- `memory_handoff_cancel` expires a mistaken pending handoff by exact handoff id.
+
+## Single-use handoff behavior
+
+The SessionStart hook usually fetches and consumes any pending handoff before the agent sees its first prompt. If the current context already contains a pending handoff block, answer from that block directly. Do not call the accept tool again to find it in another project, because handoffs are single-use and the tool will normally return null after SessionStart consumed it.
+
+If no pending handoff block is visible and the user asks where we left off, then use the accept tool. Keep the default current-project scope unless the user explicitly names a sibling workspace and project.
+
+## Creating a handoff
+
+Create a handoff only at session end or when the user explicitly asks to save context for the next session. Do not use handoffs for status checks, briefings, project notes, or permanent memory. Keep the summary to two or three concise sentences, and put details in open questions and next steps bullets.
+
+Lifecycle hooks already capture routine prompts and tool calls, so do not manually write a handoff just to record normal progress.
+
+## Canceling a handoff
+
+Cancel only when the user asks to discard a handoff or you created one by mistake. Use the exact handoff id returned by the begin tool. Cancellation is idempotent from the user's point of view, but it should still target only the known handoff.
+
+## Scope default
+
+Default to the current project. Pass workspace and project together only when the user names a different project. Never pass scope arguments just because the user says this project, here, we, or our work.
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md
new file mode 100644
index 00000000..44f10380
--- /dev/null
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md
@@ -0,0 +1,38 @@
+---
+name: ai-memory-learning-maintenance
+description: Use when the user asks to consolidate memory, review what was learned, propose durable lessons, audit the wiki, find contradictions, prune old memory, or run auto-improvement maintenance.
+---
+<!-- ai-memory-managed: routing-skill -->
+
+# ai-memory learning and maintenance
+
+Use this skill for compilation, learning review, wiki linting, and cleanup of ai-memory's durable knowledge base.
+
+## Tools in this cluster
+
+- `memory_consolidate` compiles raw session observations into topical wiki pages on demand.
+- `memory_auto_improve` reviews a completed session for durable lessons and project-rule proposals.
+- `memory_lint` audits the wiki for contradictions, stale guidance, and candidate rule placement.
+- `memory_forget_sweep` prunes or proposes removal of old pages when the user asks for memory cleanup.
+
+## Consolidation and learning review
+
+The server may already run consolidation on PreCompact and at session end when configured. Use on-demand consolidation only when the user asks to compile or consolidate what happened.
+
+Use the auto-improvement tool when the user asks what durable lessons should be proposed from a completed session, or during an explicit wrap-up learning review. It reads the latest completed session by default when no session id is provided.
+
+## Approval path
+
+Scheduled and manual learning reviews apply or stage validated edits through the auto-improvement approval path. Admins can disable scheduling, or require proposal approval so pending writes remain staged until approved. Do not imply a proposal was applied unless the tool result says it was applied.
+
+## Dry-run and destructive caution
+
+Prefer read-only linting or proposal mode before destructive cleanup. When a maintenance tool exposes dry-run behavior, use it first unless the user explicitly requested immediate deletion. If no dry run exists for a destructive action, report what would be removed and ask before proceeding.
+
+## What not to learn
+
+Generic ai-memory routing guidance, Agent Skill installation details, and temporary prompt-packaging instructions are not durable project knowledge. Do not turn them into wiki pages or project rules unless the user explicitly asks to remember a project-specific decision.
+
+## Scope default
+
+Default to the current project. Pass workspace and project together only when the user explicitly names a different project.
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
new file mode 100644
index 00000000..814827ba
--- /dev/null
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
@@ -0,0 +1,51 @@
+---
+name: ai-memory-retrieval
+description: Use when the user asks to search memory, catch up, inspect recent activity, read wiki pages, get ai-memory stats, query prior decisions, or apply remembered rules before design or debugging.
+---
+<!-- ai-memory-managed: routing-skill -->
+
+# ai-memory retrieval
+
+Use this skill for read-only ai-memory lookups, catch-up, and applying remembered project knowledge before you design, debug, or edit.
+
+## Tools in this cluster
+
+- `memory_query` searches the current project's wiki for prior decisions, gotchas, procedures, rules, and session notes.
+- `memory_recent` lists the most recently updated pages when the user wants a light activity check.
+- `memory_read_page` fetches a full page body after a search hit or direct path lookup.
+- `memory_status` reports whether ai-memory is healthy and how large the knowledge base is.
+- `memory_briefing` returns a structured read-only snapshot for agent consumption.
+- `memory_explore` returns a prose digest when the user asks for an open-ended catch-up.
+
+## Scope default
+
+Default to the current project. The tools auto-scope from the working directory, so omit project, workspace, and cwd arguments unless the user explicitly names a different project. Phrases like this project, here, we, our work, and where did we leave off mean the current project.
+
+## Choose the smallest useful lookup
+
+- Use the search tool when the user asks whether something was discussed, before proposing architecture, or before non-trivial coding in a subsystem with possible prior decisions.
+- Use the recent-pages tool for a quick what changed lately view.
+- Use the status tool only for health and size questions.
+- Use the structured briefing when code needs counts, windows, pending-handoff counts, current rules, or recent pages as JSON-like data.
+- Use the prose exploration tool for broad catch-up questions like what is important right now or I have been away.
+
+## Broaden on miss
+
+If a current-project search is empty or thin, do not conclude the knowledge was never recorded. It may live in a sibling project such as infra, ops, or a related app.
+
+- If the user named the sibling project or you know the likely sibling, search explicit scopes.
+- If you do not know where it lives, search globally across every project.
+- Do not combine global search with explicit scopes or project and workspace arguments.
+
+## Snippets are not full pages
+
+Search returns snippets, not complete bodies. An empty-looking or short snippet does not prove the page is empty because the match can be outside the snippet window. Fetch the full page when the path or title looks relevant, especially for rules, procedures, decisions, and gotchas.
+
+## Apply retrieved guidance
+
+Treat matching pages under `_rules/`, `gotchas/`, `procedures/`, and `decisions/` as operating constraints.
+
+- Apply rules as current project policy.
+- Check gotchas before editing the same subsystem.
+- Follow procedures as checklists for releases, PR review, deploys, migrations, and other repeatable workflows.
+- Treat decisions as prior architecture unless the user asks to revisit them.
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md
new file mode 100644
index 00000000..bbb119e9
--- /dev/null
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md
@@ -0,0 +1,52 @@
+---
+name: ai-memory-routing-install
+description: Use when the user asks to install, refresh, update, repair, or remove ai-memory routing instructions or Agent Skills in CLAUDE.md, AGENTS.md, .claude/skills, or .agents/skills.
+---
+<!-- ai-memory-managed: routing-skill -->
+
+# ai-memory routing install
+
+Use this skill when the user wants ai-memory's agent-facing routing instructions or managed Agent Skills installed, refreshed, repaired, or removed.
+
+## Tools in this cluster
+
+- `memory_install_self_routing` returns the canonical markered instruction block, marker strings, filename hints, notes, and managed skill payloads for agents that cannot let the MCP server write the host filesystem directly.
+
+## Managed instruction marker
+
+The always-loaded instruction block is owned by ai-memory only between these markers.
+
+- Start marker: `<!-- ai-memory:start -->`
+- End marker: `<!-- ai-memory:end -->`
+
+Refresh must replace the first complete marker-bounded block in place, preserving unrelated content before and after it. If no complete block exists, append the canonical block with one blank line of separation. Never edit unrelated instructions while refreshing ai-memory routing.
+
+## Managed skill marker
+
+Every ai-memory-managed `SKILL.md` file contains this ownership marker.
+
+`<!-- ai-memory-managed: routing-skill -->`
+
+Installers and uninstallers should overwrite or remove same-name skill files only when that marker is present, unless the user supplied an explicit force option. If a same-name skill lacks the marker, skip it with an actionable message so user-authored skills are preserved.
+
+## Skill install targets
+
+Managed skills are ordinary Agent Skills. Their relative file path is `<skill>/SKILL.md`, and the installer prepends the selected skill root.
+
+Project-local targets:
+
+- `.claude/skills/<skill>/SKILL.md` for Claude-compatible installs.
+- `.agents/skills/<skill>/SKILL.md` for cross-client installs.
+
+Global targets:
+
+- `~/.claude/skills/<skill>/SKILL.md` for Claude-compatible installs.
+- `~/.agents/skills/<skill>/SKILL.md` for cross-client installs.
+
+Use platform-aware path joining. Do not build paths by string concatenation.
+
+## Refresh guidance
+
+For an agent-side refresh, call the install-routing tool, choose the right instruction filename from its hints, write the markered block with the agent's file-edit tool, and write each managed skill file to the selected skill roots. Claude Code normally uses `CLAUDE.md` and `.claude/skills`; Codex, OpenCode, Cursor, Gemini CLI, and AGENTS-aware clients normally use `AGENTS.md` and `.agents/skills` unless the project says otherwise.
+
+For a CLI refresh, prefer the canonical install command. The snippet and skills must be updated from the same core-owned assets so they do not drift.