Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(handoff): add cancel guardrails
AkitaOnRailsd399af6f2d5a
diff --git a/AGENTS.md b/AGENTS.mdindex 0719c899..501c7f77 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -19,11 +19,12 @@ match the intent to the tool. They do not need to name the 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` |+| "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) |-| "save context for the next session" / wrapping up | `memory_handoff_begin` (single-use handoff; terse summary; put detail in `open_questions` + `next_steps` bullets) |+| "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) |+| "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" (usually automatic) | `memory_consolidate` || "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) || "audit the wiki" / "find contradictions" / "what rules should we add?" | `memory_lint` |diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2b32eba7..01e82f15 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,8 +16,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0subcommand, a thin client of `/admin/delete-page`. Mirrors thewrite-page/read-page CLI shape so terminal users get a completedelete-single-page surface for the first time.+- New `memory_handoff_cancel` MCP tool marks an exact open handoff id expired,+ giving agents a safe way to discard a mistakenly-created pending handoff+ before the next session consumes stale context.### Fixed+- MCP tool descriptions and routing snippets now draw a sharper boundary+ between read-only `memory_briefing` and session-ending+ `memory_handoff_begin`, reducing accidental dangling handoffs when an agent+ was only asked for project status.- Custom `--web-ui-dir` SPAs mounted at a non-root `--web-slug` now serve theinjected shell at the trailing-slash root too (for example `/web/`), matching`/web` and deep client routes instead of returning a refresh-only 404.diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rsindex d3dd8100..573e9426 100644--- a/crates/ai-memory-core/src/routing_snippet.rs+++ b/crates/ai-memory-core/src/routing_snippet.rs@@ -63,11 +63,12 @@ match the intent to the tool. They do not need to name the 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` |+| "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) |-| "save context for the next session" / wrapping up | `memory_handoff_begin` (single-use handoff; terse summary; put detail in `open_questions` + `next_steps` bullets) |+| "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) |+| "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` || "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) |diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 0c3f04d8..b41a0a08 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -6,7 +6,8 @@ use std::sync::Arc;use ai_memory_consolidate::{Consolidator, run_lint, run_sweep};use ai_memory_core::{- ActiveProject, AgentKind, NewHandoff, PageId, PagePath, ProjectId, SessionId, Tier, WorkspaceId,+ ActiveProject, AgentKind, HandoffId, HandoffState, NewHandoff, PageId, PagePath, ProjectId,+ SessionId, Tier, WorkspaceId,};use ai_memory_llm::{Embedder, LlmProvider};use ai_memory_store::{DecayParams, PageHit, ReaderPool, WriterHandle};@@ -57,7 +58,8 @@ the conversation calls for them:\n\'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\+ call). READ-ONLY: it never creates handoffs or mutates state. 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` \@@ -69,10 +71,16 @@ the conversation calls for them:\n\'📥 ai-memory: pending handoff' is anywhere in your context, \THAT is the handoff — answer from it directly, don't re-call \this tool (it'll return null because handoffs are single-use).\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). Keep the summary terse (2-3 sentences); \- put detail in open_questions + next_steps bullets.\n\+- `memory_handoff_begin` — ONLY when the user is wrapping up / ending \+ the current session and you want to ensure the next agent has context \+ (the SessionEnd hook also auto-captures this). DO NOT use this to \+ summarize work mid-session, check project status, or answer a request \+ for a briefing. Keep the summary terse (2-3 sentences); put detail \+ in open_questions + next_steps bullets.\n\+- `memory_handoff_cancel` — when you realize you mistakenly called \+ `memory_handoff_begin`, or the user explicitly asks to discard a \+ pending handoff. Requires the exact `handoff_id` from the begin call \+ and marks it expired so the next session will not consume it.\n\- `memory_consolidate` — when the user asks to compile session \observations into wiki pages. Also runs on PreCompact, and at \session end only when AI_MEMORY_CONSOLIDATE_ON_SESSION_END is set.\n\@@ -343,6 +351,21 @@ struct HandoffAcceptArgs {project: Option<String>,}+#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]+struct HandoffCancelArgs {+ /// Exact handoff id returned by `memory_handoff_begin`. Required so this+ /// tool only discards a handoff the agent can identify.+ handoff_id: String,+ /// Project to cancel within. Omit to target the current project. **Omit+ /// unless the user explicitly names a different project.**+ #[serde(default)]+ project: Option<String>,+ /// Workspace to cancel within, together with `project`. Omit for the+ /// current/default workspace resolution chain.+ #[serde(default)]+ workspace: Option<String>,+}+#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]struct BriefingArgs {/// How many recently-updated pages to include (default 10, max 100).@@ -1265,7 +1288,10 @@ impl AiMemoryServer {/// Create a handoff snapshot for the next agent CLI.#[tool(description = "Record a cross-agent handoff snapshot for the \NEXT agent that opens this project (e.g. Codex picking up after \- Claude Code). The next session's SessionStart hook automatically \+ Claude Code). Use this ONLY when ending/wrapping up the current \+ session or when the user explicitly says to save context for the next \+ session. DO NOT use this to check project status, get a briefing, or \+ summarize work mid-session. The next session's SessionStart hook automatically \consumes the handoff and prepends its content to the agent's \context — no manual fetch needed. \\@@ -1348,6 +1374,55 @@ impl AiMemoryServer {}}+ /// Cancel a mistaken open handoff by exact id.+ #[tool(description = "Cancel/discard a mistakenly-created OPEN handoff by \+ exact `handoff_id` returned from `memory_handoff_begin`. Use this ONLY \+ when you realize you called `memory_handoff_begin` by mistake or the \+ user explicitly asks to discard a pending handoff. This is a cleanup \+ tool, not a status/briefing tool. It marks the handoff expired so the \+ next SessionStart hook will not consume it. Omit project/workspace \+ unless the user names a different project; when provided, workspace \+ and project must be supplied together.")]+ async fn memory_handoff_cancel(+ &self,+ Parameters(args): Parameters<HandoffCancelArgs>,+ ) -> Result<CallToolResult, McpError> {+ let handoff_id = HandoffId::from_str(&args.handoff_id)+ .map_err(|e| McpError::internal_error(format!("invalid handoff_id: {e}"), None))?;+ let (ws, proj) = self+ .effective_ids_for_read_args(args.workspace.as_deref(), args.project.as_deref())+ .await?;+ let handoff = self+ .reader+ .handoff_by_id(handoff_id)+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?+ .ok_or_else(|| McpError::internal_error("handoff not found", None))?;+ if handoff.workspace_id != ws || handoff.project_id != proj {+ return Err(McpError::internal_error(+ "handoff does not belong to the resolved project",+ None,+ ));+ }+ if handoff.state != HandoffState::Open {+ return ok_json(&serde_json::json!({+ "handoff_id": handoff_id.to_string(),+ "cancelled": false,+ "state": handoff.state.as_str(),+ }));+ }+ let cancelled = self+ .writer+ .cancel_handoff(handoff_id)+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ ok_json(&serde_json::json!({+ "handoff_id": handoff_id.to_string(),+ "cancelled": cancelled,+ "state": if cancelled { "expired" } else { "open" },+ }))+ }+/// Report aggregate counts (pages, sessions, observations).#[tool(description = "Report aggregate memory counts and runtime status \(pages latest, pages all versions, sessions, observations). \@@ -1375,7 +1450,8 @@ impl AiMemoryServer {WITHOUT any LLM call: lifetime counts, 7-day and 30-day activity \windows, last-observation timestamp, pending handoff count, \current `_rules/` pages, and recent-page list. Cheap, fast, \- deterministic. Use this when you want a programmatic view of \+ deterministic, and READ-ONLY: it never creates handoffs or mutates \+ project state. Use this when you want a programmatic view of \project state; use `memory_explore` if you want an LLM-composed \prose summary on top of the same data.")]async fn memory_briefing(@@ -1711,6 +1787,7 @@ mod tests {"memory_explore","memory_handoff_accept","memory_handoff_begin",+ "memory_handoff_cancel","memory_consolidate","memory_write_page","memory_read_page",@@ -1732,6 +1809,30 @@ mod tests {}}+ #[test]+ fn prompts_separate_briefing_from_handoff_lifecycle() {+ for prompt in [MEMORY_INSTRUCTIONS, ai_memory_core::SNIPPET_BODY] {+ let lower = prompt.to_ascii_lowercase();+ assert!(+ prompt.contains("memory_briefing") && lower.contains("read-only"),+ "briefing guidance must say it is read-only"+ );+ assert!(+ prompt.contains("memory_handoff_begin")+ && (lower.contains("session-end")+ || (lower.contains("ending") && lower.contains("session")))+ && (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"+ );+ assert!(+ prompt.contains("memory_handoff_cancel") && prompt.contains("handoff_id"),+ "cancel guidance 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".@@ -3093,6 +3194,102 @@ mod tests {assert!(again_text.contains("\"handoff\": null"));}+ #[tokio::test]+ async fn handoff_cancel_expires_open_handoff_and_clears_briefing_count() {+ let (_tmp, store, server, _ws, _pj) = setup_server().await;+ let begin = server+ .memory_handoff_begin(Parameters(HandoffBeginArgs {+ summary: "accidental status summary".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ cwd: Some("/tmp/aim".into()),+ project: None,+ }))+ .await+ .unwrap();+ let begin_text = begin+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ let begin_json: serde_json::Value = serde_json::from_str(&begin_text).unwrap();+ let handoff_id = begin_json["handoff_id"].as_str().unwrap().to_string();++ let before = server+ .memory_briefing(Parameters(BriefingArgs {+ recent_pages_limit: Some(5),+ project: None,+ workspace: None,+ }))+ .await+ .unwrap();+ let before_text = before+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(before_text.contains("\"pending_handoff_count\": 1"));++ let cancel = server+ .memory_handoff_cancel(Parameters(HandoffCancelArgs {+ handoff_id: handoff_id.clone(),+ project: None,+ workspace: None,+ }))+ .await+ .unwrap();+ let cancel_text = cancel+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(cancel_text.contains("\"cancelled\": true"));+ assert!(cancel_text.contains("\"state\": \"expired\""));++ let after = server+ .memory_briefing(Parameters(BriefingArgs {+ recent_pages_limit: Some(5),+ project: None,+ workspace: None,+ }))+ .await+ .unwrap();+ let after_text = after+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(after_text.contains("\"pending_handoff_count\": 0"));++ let accept = server+ .memory_handoff_accept(Parameters(HandoffAcceptArgs {+ cwd: Some("/tmp/aim".into()),+ project: None,+ }))+ .await+ .unwrap();+ let accept_text = accept+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.clone())+ .unwrap();+ assert!(accept_text.contains("\"handoff\": null"));++ let stored = store+ .reader+ .handoff_by_id(HandoffId::from_str(&handoff_id).unwrap())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(stored.state, HandoffState::Expired);+ }+// ----------------------------------------------------------------// Error / mis-configured paths — caught at the tool boundary so the// agent sees a clean McpError instead of a panic.diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 3554759f..9087d55e 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -799,6 +799,15 @@ pub fn accept_handoff(Ok(())}+/// Mark an open handoff expired so it will no longer be consumed.+pub fn cancel_handoff(conn: &mut Connection, handoff_id: &HandoffId) -> StoreResult<bool> {+ let changed = conn.execute(+ "UPDATE handoffs SET state = 'expired' WHERE id = ?1 AND state = 'open'",+ params![handoff_id.as_bytes()],+ )?;+ Ok(changed > 0)+}+fn observation_kind_as_str(kind: ObservationKind) -> &'static str {kind.as_str()}@@ -1578,6 +1587,39 @@ mod tests {assert!(second.is_ok(), "double-accept must not error");}+ #[test]+ fn cancel_handoff_transitions_open_to_expired() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let new = NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_session_id: None,+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ cwd: None,+ summary: "accidental handoff".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ };+ let id = insert_handoff(&mut conn, &new).unwrap();++ assert!(cancel_handoff(&mut conn, &id).unwrap());+ let state: String = conn+ .query_row(+ "SELECT state FROM handoffs WHERE id = ?1",+ params![&id.as_bytes()[..]],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(state, "expired");++ assert!(+ !cancel_handoff(&mut conn, &id).unwrap(),+ "double-cancel should be a no-op"+ );+ }+/// Supported hook agents persist concrete agent_kind values. V01's CHECK/// omitted agents added after launch; regression for hook-router WARNs.#[test]diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 8abde6d8..8989b3ce 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -75,6 +75,10 @@ pub(crate) enum WriteCmd {accepting_session: Option<SessionId>,reply: oneshot::Sender<StoreResult<()>>,},+ CancelHandoff {+ handoff_id: HandoffId,+ reply: oneshot::Sender<StoreResult<bool>>,+ },/// Retro-fit sessions + observations to per-cwd projects and graveyard/// mash-up pages. Executed in one transaction for atomicity.Reorg {@@ -338,6 +342,23 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Mark an open handoff expired so it will no longer be consumed.+ ///+ /// Returns `true` when an open handoff was changed, `false` when the id was+ /// already accepted/expired or missing.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.+ pub async fn cancel_handoff(&self, handoff_id: HandoffId) -> StoreResult<bool> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::CancelHandoff {+ handoff_id,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Store (or replace) the embedding for one page (M9).////// # Errors@@ -816,6 +837,10 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {);send_or_warn(reply, result, "accept_handoff");}+ WriteCmd::CancelHandoff { handoff_id, reply } => {+ let result = ops::cancel_handoff(&mut conn, &handoff_id);+ send_or_warn(reply, result, "cancel_handoff");+ }WriteCmd::Reorg { plan, reply } => {let result = ops::reorg_sessions(&mut conn, &plan);send_or_warn(reply, result, "reorg_sessions");diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex a6c8fe09..31c9dbad 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -229,7 +229,7 @@ Each crate has a single responsibility and exposes a typed API. Nocircular deps. Inter-crate boundaries enforce the cross-cuttinginvariants below.-## MCP tool surface (14 tools)+## MCP tool surface (15 tools)| Tool | Hint | Purpose ||---|---|---|@@ -241,6 +241,7 @@ invariants below.| `memory_explore` | read-only | LLM prose digest over the briefing snapshot, degrading to JSON without a provider. || `memory_handoff_begin` | destructive | Open a handoff for the next agent. || `memory_handoff_accept` | destructive | Fetch + ack the latest open handoff (auto-cwd-matched). |+| `memory_handoff_cancel` | destructive | Mark an exact open handoff id expired when it was created by mistake. || `memory_consolidate` | destructive | LLM-driven page rewrite. `multi_page=true` for atomic fan-out. || `memory_write_page` | destructive | Write durable wiki knowledge when the user explicitly asks to remember/annotate something permanent. || `memory_delete_page` | destructive | Delete a single page by exact `path`. Fires the admission chain (op=delete); idempotent. |@@ -249,7 +250,8 @@ invariants below.| `memory_install_self_routing` | read-only | Return the canonical routing snippet for CLAUDE.md / AGENTS.md. |`memory_briefing`, `memory_explore`, `memory_write_page`,-`memory_install_self_routing`, `memory_read_page`, and `memory_delete_page`+`memory_install_self_routing`, `memory_read_page`, `memory_delete_page`, and+`memory_handoff_cancel`post-date the original "narrow on purpose" cut (§10 of`design-decisions.md`): briefing/explore separate the structured vs.prose halves of "what's going on", `memory_write_page` covers explicit@@ -259,8 +261,9 @@ must re-write its own routing rules into a project's `CLAUDE.md` /`AGENTS.md`, `memory_read_page` complements `memory_query` for the"I need the full page, not a snippet" case (e.g. opening a decision pageend-to-end), and `memory_delete_page` is the exact-path destructive pair-needed by admission-aware mirrors. The narrow-surface discipline still holds-— every new tool has to earn its slot — but the v1 count is 14, not 10.+needed by admission-aware mirrors. `memory_handoff_cancel` is the safety valve+for mistaken handoff creation. The narrow-surface discipline still holds —+every new tool has to earn its slot — but the v1 count is 15, not 10.MCP parameter aliases are intentionally sparse: `memory_query.query` accepts`q|search`, and limit fields accept `n` / `top_k` where shipped. Project anddiff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex a554bf34..8708a0f0 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -148,13 +148,13 @@ struct Handoff {}```-MCP tools `memory_handoff_begin` (writes a handoff page tagged `state=open`) and `memory_handoff_accept` (acknowledges, returns the handoff content, marks `accepted_by`). The user can stop Claude Code, start Codex, and Codex's session-start hook fetches the latest open handoff for the cwd.+MCP tools `memory_handoff_begin` (writes a handoff row tagged `state=open`), `memory_handoff_accept` (acknowledges, returns the handoff content, marks `accepted_by`), and `memory_handoff_cancel` (marks an exact open handoff id expired when it was created by mistake). The user can stop Claude Code, start Codex, and Codex's session-start hook fetches the latest open handoff for the cwd.agentmemory has this informally (`/handoff` skill); we make it explicit from day one because every research report flagged cross-agent as the v0.1 weak spot.## 10. MCP tool surface - narrow on purpose-basic-memory has ~25 tools, agentmemory has 53. Both have user confusion as a result. v1 ships 11 tools:+basic-memory has ~25 tools, agentmemory has 53. Both have user confusion as a result. The current v1 surface is still deliberately narrow:| Tool | Purpose | Annotation ||---|---|---|@@ -165,8 +165,11 @@ basic-memory has ~25 tools, agentmemory has 53. Both have user confusion as a re| `memory_explore` | LLM-composed prose digest over `memory_briefing`; degrades to JSON without a provider | read-only || `memory_handoff_begin` | Mark session boundary, write handoff | destructive || `memory_handoff_accept` | Fetch + ack the latest open handoff | destructive |+| `memory_handoff_cancel` | Mark an exact mistakenly-created open handoff expired | destructive || `memory_consolidate` | LLM-driven page rewrite (`multi_page=true` for atomic fan-out) | destructive || `memory_write_page` | Write durable wiki knowledge on explicit user request | destructive |+| `memory_read_page` | Read a full page body by exact path or top search hit | read-only |+| `memory_delete_page` | Delete a single exact-path page with admission hooks | destructive || `memory_forget_sweep` | Retention sweep (M8); soft-delete below cold threshold; `dry_run=true` previews | destructive || `memory_lint` | Rule-based + optional LLM contradiction findings → `wiki/_lint/<date>.md` | destructive || `memory_install_self_routing` | Returns the canonical CLAUDE.md / AGENTS.md routing block + per-agent filename hints | read-only |diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex a1a8cf3d..2ed748f7 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -401,8 +401,8 @@ You: List the MCP tools you can call. Use one of them to checkModel (any client): I can call: memory_query, memory_recent,memory_status, memory_briefing, memory_explore,- memory_handoff_accept, memory_handoff_begin, memory_consolidate,- memory_write_page, memory_read_page, memory_delete_page,+ memory_handoff_accept, memory_handoff_begin, memory_handoff_cancel,+ memory_consolidate, memory_write_page, memory_read_page, memory_delete_page,memory_lint, memory_forget_sweep, memory_install_self_routing.memory_status reports: 0 pages, 0 observations, 0 sessions.```diff --git a/docs/usage.md b/docs/usage.mdindex 4812388a..6e1487ef 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -25,6 +25,11 @@ If an agent has MCP but no lifecycle hook surface, ask it to call`memory_handoff_begin` before quitting. The next hooked agent can stillconsume that handoff automatically.+If an agent creates a handoff by mistake, cancel it immediately with+`memory_handoff_cancel` and the `handoff_id` returned by+`memory_handoff_begin`. Cancelling marks the handoff expired, so the next+session-start hook will not consume stale context.+## Compaction recoveryWhen Claude Code or Codex compact their working context, the@@ -46,12 +51,13 @@ the wiki without you naming tools explicitly.| Before proposing architecture | `memory_query` | Checks prior decisions and gotchas before suggesting designs. || "Catch me up" / "I've been away" | `memory_explore` | Prose digest whose verbosity scales with time since last activity. || "Where did we leave off?" | Existing handoff block, or `memory_handoff_accept` if no block exists | Resumes from the latest pending handoff. |-| "Save context for the next session" | `memory_handoff_begin` | Writes a terse handoff with open questions and next steps. |+| "Save context for the next session" | `memory_handoff_begin` | Writes a terse session-end handoff with open questions and next steps. Do not use for status or briefing requests. |+| "Discard that handoff" / "I created a handoff by mistake" | `memory_handoff_cancel` | Marks an exact open handoff id expired before the next session can consume it. || "Consolidate this session" | `memory_consolidate` | Manually runs LLM consolidation. Also runs on PreCompact, and at session end only when `AI_MEMORY_CONSOLIDATE_ON_SESSION_END` is set (off by default; session end otherwise writes a rule-based summary page). || "Remember this permanently" / "add an annotation" | `memory_write_page` | Writes durable wiki knowledge; not a single-use handoff. || "Delete this page" / "remove the note about X" | `memory_delete_page` | Removes a page by exact path. Pass `workspace` + `project` together when the page lives in a sibling workspace, so a project name shared between workspaces never silently routes the delete to the wrong slot. || "Audit the wiki" / "any contradictions?" | `memory_lint` | Runs stale-page, contradiction, and rule-suggestion checks. |-| "How big is the wiki?" / "stats?" | `memory_status`, `memory_briefing` | Counts and recent activity windows. |+| "How big is the wiki?" / "stats?" | `memory_status`, `memory_briefing` | Counts and recent activity windows; `memory_briefing` is read-only. |## Install the routing snippet