Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
mcp+install-instructions: full conversational tool routing
AkitaOnRails2f64dc8b271f
diff --git a/CLAUDE.md.bak-1779496975 b/CLAUDE.md.bak-1779496975new file mode 100644index 00000000..fc233d0f--- /dev/null+++ b/CLAUDE.md.bak-1779496975@@ -0,0 +1,147 @@+# CLAUDE.md — ai-memory project directives++> Read this every session before touching code. The long-form research and+> design specs live under [`docs/`](docs/); this file is the operating rules.++## What this project is++A self-contained Rust binary providing long-term memory for AI coding agents+(Claude Code, OpenAI Codex, OpenCode) over the Model Context Protocol.+Storage = markdown-in-git wiki (source of truth) + SQLite (derived index).+Capture = automatic via agent lifecycle hooks, never manual `write_note`.+Consolidation = Karpathy "LLM Wiki" pattern with versioned supersession.++Read [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) first for the+operational summary. Read [`docs/design-decisions.md`](docs/design-decisions.md)+for the full v1 spec. Read [`docs/research-karpathy-llm-wiki.md`](docs/research-karpathy-llm-wiki.md)+for what "Karpathy-faithful" means in practice.++## Stack (do not deviate without updating `docs/design-decisions.md` §4)++- **Runtime:** Rust 1.95 (pinned in `rust-toolchain.toml`), edition 2024,+ resolver 3, async via `tokio`.+- **MCP:** `rmcp` (official `modelcontextprotocol/rust-sdk`).+- **Store:** `rusqlite` + `refinery` migrations, FTS5 in v1, `sqlite-vec` in+ v0.2. **One file**, one writer actor, one read pool.+- **Wiki:** markdown on disk, `notify-debouncer-full` watcher with heartbeat+ + reconciliation, `git2` for versioning.+- **HTTP:** `axum` for hook ingress + MCP HTTP/SSE.+- **LLM:** typed clients per provider (Anthropic, OpenAI, OpenAI-compat) via+ `reqwest`. **Never** a generic gateway like LiteLLM (cognee #2840 lesson).+- **Config:** `figment`, one read at startup, passed by `&Arc<Config>`.+- **Logging:** `tracing` with module filters; never let the appender's own+ module log at INFO+ (agentmemory #519 lesson).++## Repository layout++```+crates/+ ai-memory-core/ # domain types, errors. NO IO.+ ai-memory-store/ # SQLite, single-writer actor, migrations.+ ai-memory-wiki/ # markdown read/write, watcher, git.+ ai-memory-mcp/ # rmcp transport + tool router.+ ai-memory-hooks/ # hook payload schemas + HTTP ingress.+ ai-memory-llm/ # LlmProvider trait + 3 impls.+ ai-memory-consolidate/ # Karpathy ingest/query/lint pipeline.+ ai-memory-cli/ # `ai-memory` binary entry point.+hooks/ # vendored hook scripts per agent.+docker/ # Dockerfile + compose.+docs/ # research + design (DO NOT delete).+tests/ # workspace integration tests.+```++## Workflow rules++1. **Milestone by milestone.** Do not start M(n+1) until every "Done when"+ bullet in M(n) passes. See [`docs/design-decisions.md`](docs/design-decisions.md)+ for the milestone list. No mixing.+2. **No dead code, no half-built features.** If a feature is not finished,+ it does not land. If you must stub something, document it as `M(n) TODO`+ in the relevant module's doc-comment with the milestone number.+3. **Tests before claiming done.** Every milestone requires:+ - `cargo fmt --all -- --check` (no diffs)+ - `cargo clippy --workspace --all-targets -- -D warnings` (no warnings)+ - `cargo test --workspace` (all green)+ - Manual exercise of the new feature against a real agent CLI when applicable.+4. **Document the why in code, not the what.** No comments restating the line+ above; only comments explaining a constraint, an incident, or a non-obvious+ invariant.+5. **Add a unit test before the implementation, not after.** Especially for+ parsers, ID derivation, and any retention/decay math.+6. **Don't refactor outside the milestone.** Touch only what the current+ milestone requires; resist scope creep.++## Cross-cutting invariants (carved in, never violated)++These come straight from issue-tracker research on agentmemory, basic-memory+and cognee — every one of them is in `docs/design-decisions.md` §14 with+issue citations. **Treat any code review that violates one of these as a+blocking issue:**++1. One config-read path. No `std::env::var` outside `Config::load()`.+2. Single-writer SQLite actor. All writes through one `mpsc` channel.+3. Indexes commit in the same transaction as the data. No+ background-task-indexing-after-return.+4. Typed `(WorkspaceId, ProjectId, PagePath)` identity in every layer.+5. Hooks are fire-and-forget. Sub-second timeouts. Return 202 immediately.+6. Privacy strip is a typed boundary (`RawHookPayload → Sanitized<Observation>`).+7. JSON-schema structured outputs only. No XML, no `instructor`-style wrapping.+8. `{provider, model, dim}` stored next to every embedding. Refuse on mismatch.+9. Live-process check (`sysinfo`) before any destructive op.+10. Atomic file writes (tmp + rename + fsync). Watcher ignores own writes.+11. Default data dir is an absolute canonical platform path.+ Logged loudly on startup.+12. No global singletons / `lazy_static` configs.+13. Zero-LLM default path. LLM features opt-in via env.+14. Tracing subscribers explicitly filter their own module.++## Mistakes documented in the research — do NOT repeat++- [`docs/issues-agentmemory.md`](docs/issues-agentmemory.md): install/ops+ landmines (iii-engine sidecar, distroless volumes, cwd-relative paths).+- [`docs/issues-basic-memory.md`](docs/issues-basic-memory.md): file watcher+ pain, manual-capture friction, multi-workspace retrofit.+- [`docs/issues-cognee.md`](docs/issues-cognee.md): LiteLLM/instructor wire+ drift, multi-store sync bugs, dependency landmines.++When in doubt about a design decision, search those files for the keyword.++## Quick commands++```bash+# Build everything.+cargo build --workspace++# Lint + format + test (run before every commit).+cargo fmt --all -- --check+cargo clippy --workspace --all-targets -- -D warnings+cargo test --workspace++# Auto-format.+cargo fmt --all++# Exercise the binary.+./target/debug/ai-memory --version+./target/debug/ai-memory init+AI_MEMORY_DATA_DIR=/tmp/x ./target/debug/ai-memory init+./target/debug/ai-memory status --json++# CI parity (requires cargo-deny + cargo-audit installed).+cargo install cargo-deny cargo-audit+cargo deny check+cargo audit+```++## What this project is NOT (v1 non-goals)++See [`docs/design-decisions.md`](docs/design-decisions.md) §13 for the full+list. Highlights: no multi-tenant auth, no web UI, no Postgres backend in v1,+no alternative vector backends, no remote sync (use `git remote` on the wiki+dir), no multimodal.++## Plan & status++The current execution plan is at+[`/home/akitaonrails/.claude/plans/cuddly-moseying-karp.md`](/home/akitaonrails/.claude/plans/cuddly-moseying-karp.md)+(local to the maintainer's `~/.claude/`).+Live progress is tracked via the TaskList tool inside Claude Code sessions.diff --git a/crates/ai-memory-cli/src/commands/install_instructions.rs b/crates/ai-memory-cli/src/commands/install_instructions.rsindex 36bd99e1..8b243088 100644--- a/crates/ai-memory-cli/src/commands/install_instructions.rs+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs@@ -29,28 +29,56 @@ 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+## Long-term memory (ai-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.+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?" / first turn of a new session | `memory_handoff_accept` |+| "save context for the next session" / wrapping up | `memory_handoff_begin` |+| "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 hereIf 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.+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."#;/// Run the `install-instructions` subcommand.diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex fd21b871..c5aa1d6d 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -16,13 +16,48 @@ use rmcp::model::{use rmcp::{ErrorData as McpError, ServerHandler, schemars, tool, tool_handler, tool_router};use serde::{Deserialize, Serialize};-/// Instructions surfaced to clients via `ServerInfo`. Short and-/// agent-readable — Claude Code / Codex will see this in their session-/// preamble.-pub const MEMORY_INSTRUCTIONS: &str = "Long-term memory for coding agents. Use \-memory_query for free-text search, memory_recent to peek at recently-changed \-pages, and memory_status for counts. All tools are read-only; writes happen \-automatically via hooks and the watcher.";+/// Instructions surfaced to clients via `ServerInfo`. Sent on every+/// MCP handshake so Claude Code / Codex / OpenCode see this in their+/// session preamble. Maps conversational triggers to tool names so+/// the agent can route natural-language requests without the user+/// having to know the tool name or schema.+pub const MEMORY_INSTRUCTIONS: &str = "\+Long-term memory for the current project. Lifecycle hooks already \+capture every prompt + tool call automatically — you do NOT need to \+write anything by hand. Use these tools when the conversation calls \+for them:\n\+\n\+- `memory_query` — when the user references prior work you don't \+ recognise, or asks 'have we done / discussed X', or you're about \+ to propose architecture (always check first).\n\+- `memory_recent` — at session start, or when the user asks 'what's \+ been going on lately'. Returns the N most-recent pages.\n\+- `memory_status` — when the user asks 'is ai-memory healthy' or \+ 'how big is the knowledge base'. Returns lifetime counts.\n\+- `memory_briefing` — when the user wants a STRUCTURED snapshot \+ (counts + 7d/30d activity + rules + recent pages, JSON, no LLM \+ call). Use over memory_status when more detail is wanted.\n\+- `memory_explore` — when the user wants a PROSE digest. \+ Calibrates verbosity to time since last activity: 'fresh' → one \+ line, 'stale' (>30d) → full catchup. Accepts an optional `focus` \+ arg. Use over memory_briefing when the user asks open-ended \+ questions like 'catch me up' or 'what's important right now'.\n\+- `memory_handoff_accept` — when the user asks 'where did we leave \+ off'. The SessionStart hook also auto-fetches this.\n\+- `memory_handoff_begin` — when the user is wrapping up and you \+ want to ensure the next agent has context (the SessionEnd hook \+ also auto-captures this).\n\+- `memory_consolidate` — when the user asks to compile session \+ observations into wiki pages (usually automatic at session end).\n\+- `memory_lint` — when the user asks to audit the wiki for stale \+ pages, contradictions, or rule suggestions.\n\+- `memory_forget_sweep` — when the user wants to prune old / cold \+ pages (idempotent, supports dry-run).\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.";/// MCP server backed by the ai-memory store.#[derive(Clone)]