Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(mcp): add memory_handoff_list so no-stdout agents can inspect before claiming
viniciusdsandradea2bc64da8cd4
diff --git a/AGENTS.md b/AGENTS.mdindex 16ae60de..ead62bb1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -489,7 +489,7 @@ Additional boundary rules:- **MCP tool surface changes** require updating `MEMORY_INSTRUCTIONS`,`ai_memory_core::SNIPPET_BODY`, README/docs tool references, and theregression tests asserting every tool appears in both prompt surfaces.- The tool count is currently 18 (see `docs/ARCHITECTURE.md`).+ The tool count is currently 19 (see `docs/ARCHITECTURE.md`).- **Semantic versioning:** patch = fixes; minor = additive (new CLIsubcommands, MCP tools, config keys, a new agent harness or LLMprovider); major = breaking (on-disk format without migration, removeddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex d88c7516..8b1e543a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- `memory_handoff_list` lets no-stdout and MCP-only clients inspect open+ project handoffs without claiming or expiring them, then+ `memory_handoff_accept` can claim that exact `handoff_id` once. Grok,+ Zero, and other clients that discard SessionStart stdout no longer have+ to recover a baton by blindly accepting the latest row. Listing is+ owner-filtered like accept (own plus shared; root-only `any_owner`);+ it is not a second claim path, and Grok SessionStart still does not+ fetch `/handoff`.+### Fixed- OKF-conformed event ledgers are skipped by the indexer again, so a migratedstore stops growing without bound. The reserved-file check treated anydiff --git a/crates/ai-memory-core/src/routing_skills.rs b/crates/ai-memory-core/src/routing_skills.rsindex f501f7d5..0cfe9347 100644--- a/crates/ai-memory-core/src/routing_skills.rs+++ b/crates/ai-memory-core/src/routing_skills.rs@@ -97,6 +97,7 @@ mod tests {("memory_handoff_accept", "ai-memory-handoff"),("memory_handoff_begin", "ai-memory-handoff"),("memory_handoff_cancel", "ai-memory-handoff"),+ ("memory_handoff_list", "ai-memory-handoff"),("memory_write_page", "ai-memory-durable-pages"),("memory_delete_page", "ai-memory-durable-pages"),("memory_consolidate", "ai-memory-learning-maintenance"),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.mdindex 44285900..2522006f 100644--- 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@@ -10,15 +10,16 @@ Use this skill for single-use cross-session handoffs. Handoffs are for the next## 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_list` is the read-only inspect path: it returns open handoffs without claiming or expiring them. Use it when no SessionStart handoff block is in context (Grok, Zero, and other no-stdout / MCP-only clients), when the user asks what is pending, or when you need an exact id.+- `memory_handoff_accept` consumes one open handoff. Prefer listing first when no prepended block is visible, then pass the listed `handoff_id` to claim that exact row. Omitting `handoff_id` claims the latest eligible open handoff. Use this 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.+- `memory_handoff_cancel` expires a mistaken pending handoff by exact handoff id from begin or list.## Single-use handoff behaviorThe 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 with the client-aware project scope below.+If no pending handoff block is visible, inspect with `memory_handoff_list` first. Listing does not claim or expire anything. When the user asks where we left off, claim one listed row with `memory_handoff_accept` and that `handoff_id`, using the client-aware project scope below. Do not treat list as a second accept path.## Creating a handoff@@ -30,7 +31,7 @@ On a shared server, a handoff belongs to the operator who created it. Set `share## 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.+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 or list tool. Cancellation is idempotent from the user's point of view, but it should still target only the known handoff.Accept and cancel normally act only on the caller's own plus shared handoffs. `any_owner: true` is a root-only recovery action over another operator's context; use it only on an explicit user request.diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 298d8ca7..454b0444 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -39,6 +39,8 @@ const HANDOFF_FILE_MAX_CHARS: usize = 512;const HANDOFF_TEXT_LIST_MAX_CHARS: usize = 6_000;const HANDOFF_FILE_LIST_MAX_CHARS: usize = 4_096;const HANDOFF_LIST_MAX_ITEMS: usize = 20;+const OPEN_HANDOFFS_DEFAULT_LIMIT: u32 = 50;+const OPEN_HANDOFFS_MAX_LIMIT: u32 = 200;fn default_auto_improve_review_config() -> AutoImproveReviewConfig {AutoImproveReviewConfig {@@ -211,14 +213,28 @@ developer, user, and canonical project instructions.\n\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_list` — READ-ONLY list of OPEN handoffs in the \+ resolved project. It does not claim or expire anything. Use it when \+ no SessionStart handoff block is in context (Grok, Zero, and other \+ no-stdout / MCP-only clients), when the user asks what is pending, \+ or when you need an exact id for accept or cancel. Then claim one \+ row with memory_handoff_accept passing that `handoff_id`. Follow \+ the client-aware project-scope rule above. On shared servers the \+ default is your own plus deliberately shared handoffs; \+ `any_owner=true` is root-only recovery and requires an explicit \+ user request.\n\- `memory_handoff_accept` — when the user asks 'where did we leave \off'. The SessionStart hook auto-fetches + consumes the handoff \before you see your first prompt; if a block starting with \'📥 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). Follow \- the client-aware project-scope rule above; session-aware clients add \- explicit scope when the user names a sibling workspace/project. On shared servers the default is your \+ this tool (it'll return null because handoffs are single-use). \+ When no prepended block is visible, inspect with memory_handoff_list \+ first, then pass the listed `handoff_id` to claim that exact row; \+ omitting `handoff_id` still claims the latest eligible open handoff. \+ Follow the client-aware project-scope rule above; session-aware \+ clients add explicit scope when the user names a sibling \+ workspace/project. On shared servers the default is your \own plus deliberately shared handoffs; `any_owner=true` is root-only \recovery and requires an explicit user request.\n\- `memory_handoff_begin` — ONLY when the user is wrapping up / ending \@@ -1022,6 +1038,33 @@ struct HandoffAcceptArgs {/// may omit both for the current project; static MCP clients must pass both.#[serde(default)]workspace: Option<String>,+ /// Exact open handoff id returned by `memory_handoff_list` or+ /// `memory_handoff_begin`. When set, this call claims that row rather than+ /// the latest eligible open handoff. Omit to keep the latest-open behavior.+ #[serde(default)]+ handoff_id: Option<String>,+}++#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]+struct HandoffListArgs {+ /// Also list handoffs that belong to OTHER operators. Off by default:+ /// on a shared server you only see your own plus the ones published to the+ /// whole project. Root-only recovery; requires an explicit user request.+ #[serde(default)]+ any_owner: Option<bool>,+ /// Maximum open handoffs to return (clamped to 1..=200, default 50).+ #[serde(default)]+ limit: Option<u32>,+ /// Project to list within. Session-aware clients may omit it for the+ /// current project. Static MCP clients must pass it together with+ /// `workspace` for every project-scoped call.+ #[serde(default)]+ project: Option<String>,+ /// Workspace to list within, together with `project`. Session-aware+ /// clients may omit both for the current project; static MCP clients must+ /// pass both.+ #[serde(default)]+ workspace: Option<String>,}#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]@@ -3517,9 +3560,68 @@ impl AiMemoryServer {ok_json(&serde_json::json!({ "handoff_id": id.to_string() }))}+ /// List open handoffs without claiming them.+ #[tool(description = "List OPEN cross-agent handoffs for this project \+ WITHOUT claiming or expiring them. \+ \+ READ-ONLY: every returned row stays `open`. Use this when no \+ SessionStart handoff block is in context (Grok, Zero, and other \+ no-stdout / MCP-only clients), when the user asks what is pending, \+ or when you need an exact id for memory_handoff_accept or \+ memory_handoff_cancel. After inspecting, claim one row with \+ memory_handoff_accept passing that `handoff_id` — handoffs remain \+ SINGLE-USE. This is not a briefing or status tool. \+ \+ Follow the client-aware project-scope instructions: static clients \+ pass `workspace` + `project` together for every project-scoped call. \+ On shared servers the default is your own plus deliberately shared \+ handoffs; `any_owner=true` is root-only recovery and requires an \+ explicit user request. \+ \+ Returns `{ \"handoffs\": [ ... ] }` with inspectable summary, \+ open_questions, next_steps, files_touched, and identity fields.")]+ async fn memory_handoff_list(+ &self,+ Parameters(args): Parameters<HandoffListArgs>,+ OptionalParts(parts): OptionalParts,+ ) -> Result<CallToolResult, McpError> {+ let aps_actor = Self::actor_key_from_parts(Some(&parts));+ let (ws, proj) = self+ .effective_ids_for_read_args_with_actor(+ args.workspace.as_deref(),+ args.project.as_deref(),+ &aps_actor,+ )+ .await?;+ let actor_user = crate::actor::actor_from_parts(&parts)+ .identity_key()+ .map(|key| key.storage_key());+ let owner_filter = if args.any_owner.unwrap_or(false) {+ self.require_admin_capability(&parts).await?;+ ai_memory_core::OwnerFilter::Any+ } else {+ match actor_user {+ Some(key) => ai_memory_core::OwnerFilter::User(key),+ None => ai_memory_core::OwnerFilter::Unattributed,+ }+ };+ let limit = usize::try_from(+ args.limit+ .unwrap_or(OPEN_HANDOFFS_DEFAULT_LIMIT)+ .clamp(1, OPEN_HANDOFFS_MAX_LIMIT),+ )+ .unwrap_or(OPEN_HANDOFFS_DEFAULT_LIMIT as usize);+ let handoffs = self+ .reader+ .list_handoffs(ws, proj, Some(HandoffState::Open), owner_filter, limit)+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ ok_json(&serde_json::json!({ "handoffs": handoffs }))+ }+/// Fetch the latest open handoff for this project (optionally filtered/// by cwd) and mark it accepted.- #[tool(description = "Fetch the latest OPEN cross-agent handoff and \+ #[tool(description = "Fetch an OPEN cross-agent handoff and \mark it accepted. \\IMPORTANT: handoffs are SINGLE-USE. The SessionStart hook \@@ -3534,8 +3636,11 @@ impl AiMemoryServer {first, and answer the user from there. Call this tool only when \you BOTH don't see a prepended block AND the user explicitly asks \for a handoff (e.g. a hook script ran with no stdout capture). \+ Prefer memory_handoff_list first in that case, then pass the listed \+ `handoff_id` here to claim that exact row. Omitting `handoff_id` \+ claims the latest eligible open handoff. \\- Returns the same JSON shape memory_handoff_begin accepted.")]+ Returns the handoff body only when THIS call wins the claim.")]async fn memory_handoff_accept(&self,Parameters(args): Parameters<HandoffAcceptArgs>,@@ -3566,11 +3671,25 @@ impl AiMemoryServer {}};let receiving_cwd = args.cwd;- let handoff = self- .reader- .latest_open_handoff(ws, proj, receiving_cwd.clone(), owner_filter.clone())- .await- .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ let requested_id = args+ .handoff_id+ .as_deref()+ .map(str::trim)+ .filter(|id| !id.is_empty());+ let handoff = if let Some(id) = requested_id {+ let handoff_id = HandoffId::from_str(id)+ .map_err(|e| McpError::internal_error(format!("invalid handoff_id: {e}"), None))?;+ self.reader+ .handoff_by_id_in_scope(ws, proj, handoff_id, owner_filter.clone())+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?+ .filter(|h| h.lifecycle.state == HandoffState::Open)+ } else {+ self.reader+ .latest_open_handoff(ws, proj, receiving_cwd.clone(), owner_filter.clone())+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?+ };match handoff {None => ok_json(&serde_json::json!({ "handoff": null })),Some(h) => {@@ -3619,7 +3738,8 @@ 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 \+ exact `handoff_id` returned from `memory_handoff_begin` or \+ `memory_handoff_list`. 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 \@@ -5046,6 +5166,7 @@ mod tests {"memory_handoff_accept","memory_handoff_begin","memory_handoff_cancel",+ "memory_handoff_list","memory_consolidate","memory_auto_improve","memory_write_page",@@ -5067,6 +5188,7 @@ mod tests {"memory_handoff_accept","memory_handoff_begin","memory_handoff_cancel",+ "memory_handoff_list","memory_consolidate","memory_auto_improve","memory_write_page",@@ -5323,6 +5445,14 @@ mod tests {&& lower.contains("briefing"),"{label} must make handoff-begin session-end only and reject status/briefing use");+ assert!(+ prompt.contains("memory_handoff_list")+ && lower.contains("read-only")+ && (lower.contains("does not claim")+ || lower.contains("without claiming")+ || lower.contains("not claim")),+ "{label} must expose inspect-without-claim list as read-only"+ );assert!(prompt.contains("memory_handoff_cancel") && prompt.contains("handoff_id"),"{label} must expose exact-id cleanup for mistaken handoffs"@@ -9987,6 +10117,7 @@ mod tests {project: None,workspace: None,any_owner: None,+ handoff_id: None,}),OptionalParts(test_parts_default()),)@@ -10009,6 +10140,7 @@ mod tests {project: None,workspace: None,any_owner: None,+ handoff_id: None,}),OptionalParts(test_parts_default()),)@@ -10053,6 +10185,7 @@ mod tests {project: None,workspace: None,any_owner: None,+ handoff_id: None,}),OptionalParts(test_parts_default()),)@@ -10130,6 +10263,7 @@ mod tests {project: None,workspace: None,any_owner: None,+ handoff_id: None,}),OptionalParts(test_parts_default()),)@@ -10176,6 +10310,7 @@ mod tests {project: None,workspace: None,any_owner: None,+ handoff_id: None,}),OptionalParts(test_parts_default()),)@@ -10238,6 +10373,7 @@ mod tests {project: None,workspace: None,any_owner: None,+ handoff_id: None,}),OptionalParts(test_parts_default()),)@@ -10262,6 +10398,7 @@ mod tests {project: Some("sibling-app".into()),workspace: Some("djalmajr".into()),any_owner: None,+ handoff_id: None,}),OptionalParts(test_parts_default()),)@@ -10279,6 +10416,352 @@ mod tests {);}+ fn tool_json(result: &CallToolResult) -> serde_json::Value {+ let text = result+ .content+ .first()+ .and_then(|c| c.as_text())+ .map(|t| t.text.as_str())+ .expect("tool text");+ serde_json::from_str(text).unwrap_or_else(|e| panic!("tool text not JSON ({e}): {text}"))+ }++ #[tokio::test]+ async fn memory_handoff_list_does_not_claim_then_accept_same_id() {+ let (_tmp, store, server, ws, proj) = setup_server().await;+ let begin = server+ .memory_handoff_begin(+ Parameters(HandoffBeginArgs {+ summary: "inspect-without-claim baton".into(),+ open_questions: vec!["still open?".into()],+ next_steps: vec!["claim by id".into()],+ files_touched: vec!["crates/ai-memory-mcp/src/server.rs".into()],+ cwd: None,+ project: None,+ workspace: None,+ shared: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ let handoff_id = tool_json(&begin)["handoff_id"]+ .as_str()+ .expect("begin returns handoff_id")+ .to_string();++ let listed = server+ .memory_handoff_list(+ Parameters(HandoffListArgs {+ any_owner: None,+ limit: None,+ project: None,+ workspace: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ let listed_json = tool_json(&listed);+ let rows = listed_json["handoffs"].as_array().expect("handoffs array");+ assert_eq!(rows.len(), 1, "expected one open handoff: {listed_json}");+ assert_eq!(rows[0]["id"].as_str(), Some(handoff_id.as_str()));+ assert_eq!(+ rows[0]["summary"].as_str(),+ Some("inspect-without-claim baton")+ );+ assert_eq!(rows[0]["open_questions"][0].as_str(), Some("still open?"));+ assert_eq!(rows[0]["state"].as_str(), Some("open"));++ let stored = store+ .reader+ .handoff_by_id(HandoffId::from_str(&handoff_id).unwrap())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(+ stored.lifecycle.state,+ HandoffState::Open,+ "list must not claim the inspected row"+ );+ assert_eq!(stored.scope.workspace_id, ws);+ assert_eq!(stored.scope.project_id, proj);++ let claimed = server+ .memory_handoff_accept(+ Parameters(HandoffAcceptArgs {+ cwd: None,+ project: None,+ workspace: None,+ any_owner: None,+ handoff_id: Some(handoff_id.clone()),+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ let claimed_json = tool_json(&claimed);+ assert_eq!(+ claimed_json["handoff"]["summary"].as_str(),+ Some("inspect-without-claim baton"),+ "first claim of the inspected id must return the body: {claimed_json}"+ );+ let stored = store+ .reader+ .handoff_by_id(HandoffId::from_str(&handoff_id).unwrap())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(stored.lifecycle.state, HandoffState::Accepted);++ let again = server+ .memory_handoff_accept(+ Parameters(HandoffAcceptArgs {+ cwd: None,+ project: None,+ workspace: None,+ any_owner: None,+ handoff_id: Some(handoff_id),+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ let again_json = tool_json(&again);+ assert!(+ again_json["handoff"].is_null(),+ "second claim of the same id must return no body: {again_json}"+ );+ }++ #[tokio::test]+ async fn memory_handoff_accept_by_id_leaves_sibling_open() {+ let (_tmp, store, server, _ws, _pj) = setup_server().await;+ let first = server+ .memory_handoff_begin(+ Parameters(HandoffBeginArgs {+ summary: "first pending baton".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ cwd: None,+ project: None,+ workspace: None,+ shared: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ let second = server+ .memory_handoff_begin(+ Parameters(HandoffBeginArgs {+ summary: "sibling pending baton".into(),+ open_questions: vec![],+ next_steps: vec![],+ files_touched: vec![],+ cwd: None,+ project: None,+ workspace: None,+ shared: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ let first_id = tool_json(&first)["handoff_id"]+ .as_str()+ .unwrap()+ .to_string();+ let sibling_id = tool_json(&second)["handoff_id"]+ .as_str()+ .unwrap()+ .to_string();++ let listed = tool_json(+ &server+ .memory_handoff_list(+ Parameters(HandoffListArgs {+ any_owner: None,+ limit: None,+ project: None,+ workspace: None,+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap(),+ );+ assert_eq!(+ listed["handoffs"].as_array().map(Vec::len),+ Some(2),+ "both rows must stay open after list: {listed}"+ );++ let claimed = tool_json(+ &server+ .memory_handoff_accept(+ Parameters(HandoffAcceptArgs {+ cwd: None,+ project: None,+ workspace: None,+ any_owner: None,+ handoff_id: Some(first_id.clone()),+ }),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap(),+ );+ assert_eq!(+ claimed["handoff"]["summary"].as_str(),+ Some("first pending baton")+ );++ let first_row = store+ .reader+ .handoff_by_id(HandoffId::from_str(&first_id).unwrap())+ .await+ .unwrap()+ .unwrap();+ let sibling_row = store+ .reader+ .handoff_by_id(HandoffId::from_str(&sibling_id).unwrap())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(first_row.lifecycle.state, HandoffState::Accepted);+ assert_eq!(+ sibling_row.lifecycle.state,+ HandoffState::Open,+ "claiming one inspected id must leave the sibling open"+ );+ }++ #[tokio::test]+ async fn memory_handoff_list_hides_private_baton_but_pages_stay_shared() {+ let (tmp, store, server, ws, proj) = setup_server().await;+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let bob_owner = ai_memory_core::IdentityKey::User("bob".into()).storage_key();+ let bob_handoff = store+ .writer+ .insert_handoff(NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_session_id: None,+ from_agent: AgentKind::Codex,+ to_agent: None,+ cwd: None,+ summary: "Bob's private prompt-derived context".into(),+ open_questions: vec!["private question".into()],+ next_steps: vec!["private next step".into()],+ files_touched: vec![],+ owner_user: Some(bob_owner),+ })+ .await+ .unwrap();+ let bob_user_id = store+ .writer+ .create_human_user(+ NewUser {+ username: "bob".into(),+ name: Some("Bob".into()),+ email: Some("[email protected]".into()),+ },+ ai_memory_core::UserRole::User,+ None,+ false,+ )+ .await+ .unwrap();+ store+ .writer+ .upsert_page(NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("notes/bob-authored.md").unwrap(),+ title: "Bob authored".into(),+ body: "shared wiki knowledge from Bob".into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({"title": "Bob authored"}),+ pinned: false,+ links: Vec::new(),+ author_id: Some(bob_user_id),+ expires_at: None,+ entities: Vec::new(),+ })+ .await+ .unwrap();+ let server = server.with_wiki(wiki);++ let mut alice_parts = test_parts_default();+ alice_parts.extensions.insert(AuthLevel::User);+ alice_parts.extensions.insert(ActorContext {+ user: Some("alice".into()),+ ..ActorContext::default()+ });+ let listed = tool_json(+ &server+ .memory_handoff_list(+ Parameters(HandoffListArgs {+ any_owner: None,+ limit: None,+ project: None,+ workspace: None,+ }),+ OptionalParts(alice_parts.clone()),+ )+ .await+ .unwrap(),+ );+ let rows = listed["handoffs"].as_array().expect("handoffs array");+ assert!(+ rows.is_empty(),+ "Alice must not inspect Bob's private baton: {listed}"+ );+ let stored = store+ .reader+ .handoff_by_id(bob_handoff)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(stored.lifecycle.state, HandoffState::Open);++ let page = tool_json(+ &server+ .memory_read_page(+ Parameters(ReadPageArgs {+ query: None,+ path: Some("notes/bob-authored.md".into()),+ project: None,+ workspace: None,+ }),+ OptionalParts(alice_parts),+ )+ .await+ .unwrap(),+ );+ assert!(+ page["body"]+ .as_str()+ .is_some_and(|body| body.contains("shared wiki knowledge from Bob")),+ "page reads must stay unfiltered by author: {page}"+ );+ }++ #[test]+ fn grok_session_start_hook_does_not_fetch_handoff() {+ let src = include_str!("../../../hooks/grok/session-start.sh");+ assert!(+ src.contains("Do NOT fetch /handoff"),+ "Grok SessionStart must keep the capture-only refusal"+ );+ assert!(+ !src.contains("/handoff?"),+ "Grok SessionStart must not fetch the claiming /handoff endpoint"+ );+ }+#[tokio::test]async fn handoff_cancel_expires_open_handoff_and_clears_briefing_count() {let (_tmp, store, server, _ws, _pj) = setup_server().await;@@ -10373,6 +10856,7 @@ mod tests {project: None,workspace: None,any_owner: None,+ handoff_id: None,}),OptionalParts(test_parts_default()),)@@ -11176,6 +11660,7 @@ mod tests {project: None,workspace: None,any_owner: None,+ handoff_id: None,}),OptionalParts(test_parts_default()),)diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 124fb98a..0c9be48f 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -363,7 +363,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 (18 tools)+## MCP tool surface (19 tools)| Tool | Hint | Purpose ||---|---|---|@@ -375,10 +375,11 @@ invariants below.| `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. || `memory_explore` | read-only | LLM prose digest over the briefing snapshot, degrading to JSON without a provider. || `memory_handoff_begin` | destructive | Open an owner-scoped handoff for the next agent; `shared=true` deliberately publishes it to the project. Optional `workspace` + `project` targets a named sibling workspace/project. |-| `memory_handoff_accept` | destructive | Fetch + ack the latest own/shared handoff (automatic handoffs are cwd-matched). Root-only `any_owner=true` recovers across operators. Optional `workspace` + `project` targets a named sibling workspace/project. |+| `memory_handoff_list` | read-only | List open own/shared handoffs with inspectable body and identity fields; does not claim or expire. Root-only `any_owner=true` recovers across operators. Optional `workspace` + `project` targets a named sibling workspace/project. |+| `memory_handoff_accept` | destructive | Fetch + ack an open own/shared handoff. Pass `handoff_id` from `memory_handoff_list` to claim that exact row; omitting it still claims the latest eligible open handoff (automatic handoffs are cwd-matched). Root-only `any_owner=true` recovers across operators. Optional `workspace` + `project` targets a named sibling workspace/project. || `memory_handoff_cancel` | destructive | Mark an exact visible open handoff id expired when it was created by mistake; root-only `any_owner=true` recovers across operators. |-`memory_handoff_cancel` needs an exact id. `ai-memory handoffs` lists the open+`memory_handoff_list` is the inspect-without-claim path for clients that cannot inject SessionStart stdout. `memory_handoff_cancel` needs an exact id. `ai-memory handoffs` lists the openhandoffs for a project, oldest first, with their ids — read-only, andcontent-free (identity, provenance and age, never the summary body). Automaticexpiry deliberately spares manual and sibling-directory handoffs, so adiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 5ea64025..b3d55ce0 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -1232,6 +1232,7 @@ 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_handoff_cancel,+ memory_handoff_list,memory_consolidate, memory_auto_improve, memory_write_page,memory_read_page, memory_read_session_observations,memory_delete_page, memory_feedback,@@ -1278,7 +1279,7 @@ that *starts* the next one - to play nicely with ai-memory:| Side | What's needed | Covered by ||---|---|---|| **Ending side** | The agent must create a handoff through a true session-end hook, the manual finalizer, or `memory_handoff_begin`. | Built-in automatically for Claude Code, Codex (native `SessionEnd`, Codex CLI 0.145.0+), Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, OpenCode, OpenCode 2 beta, and OMP. Antigravity CLI, both Kiro CLI engines, and Command Code have no reliable true session-end event; run `ai-memory finalize-session` with the corresponding `--agent` after the final turn (also the fallback on Codex older than 0.145.0). MCP-only clients such as Swival must call `memory_handoff_begin` explicitly. |-| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Kimi Code / both Kiro CLI engines / Command Code / OpenClaw / OpenCode / OpenCode 2 beta / OMP. It requires a client that consumes startup-hook stdout or an equivalent context-injection result. Grok and Zero discard SessionStart stdout; Swival is MCP-only. Use (b) for those clients. (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |+| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model inspects with `memory_handoff_list` then claims with `memory_handoff_accept` (`handoff_id` from the list). | (a) is built-in for Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Kimi Code / both Kiro CLI engines / Command Code / OpenClaw / OpenCode / OpenCode 2 beta / OMP. It requires a client that consumes startup-hook stdout or an equivalent context-injection result. Grok and Zero discard SessionStart stdout; Swival is MCP-only. Use (b) for those clients. (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |OpenCode uses its official `session.deleted` plugin event for true session-enddelivery. The OpenCode 2 beta plugin subscribes to the same event name on thediff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex e20a15f1..917f45cd 100644--- a/docs/support-matrix.md+++ b/docs/support-matrix.md@@ -25,13 +25,13 @@| Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. || OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. || Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). Only `PreInvocation` with `invocationNum = 0` maps to SessionStart; later model calls cannot consume a next-session handoff. No automatic true session-end hook, so run `ai-memory finalize-session --agent antigravity-cli` after the final turn when you need a summary, handoff, and opt-in SessionEnd consolidation. `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; conversation text is not decoded, so the ledger for this harness comes from hook capture. |-| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no hook handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). |+| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no hook handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). || Swival CLI | MCP-only | `install-mcp --client swival --apply` merges a native HTTP entry into the project-root `.swival/mcp.json`, preserving sibling servers. Lifecycle and managed-workstream support are not claimed because Swival's callback contract does not expose a stable session identifier. |-| Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. |+| Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. || ZCode | Supported | `install-mcp --client zcode --apply` merges a native HTTP entry (strict schema: `type`/`url`/`headers` only) into the `mcp.servers` map of `~/.zcode/cli/config.json`, preserving sibling servers. ZCode (z.ai, `zcode`, alias `zai`). Lifecycle-hook capture via `install-hooks --agent zcode --apply`: exec-form native commands (`type: "process"`, no shell) merged into the root `hooks` block of `~/.zcode/cli/config.json` around any third-party hooks; native commands enforce capture exclusions. Six documented triggers (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`); `PostToolUseFailure` fires instead of `PostToolUse` when a tool throws and lands on the same capture channel with the error preserved. `PermissionRequest` is deliberately not installed — its hook chain races the interactive permission client, so passive capture of that event is unreliable by design. No true session-end — `Stop` is a per-turn boundary, so run `ai-memory finalize-session --agent zcode` after the final turn. Unlike Pool and Zero, `SessionStart` stdout injection works (`hookSpecificOutput.additionalContext`, verified live against the embedded engine v0.16.5), so the prior session's handoff is delivered automatically. No first-party `install-mcp` client and no managed workstream are claimed yet. || Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including subagent start/stop and `PostToolUseFailure` for tool-failure capture); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `UserPromptSubmit` stdout (Kimi Code discards `SessionStart` hook stdout); `ai-memory run kimi` adds managed workstream resume. || Kiro CLI | Supported | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges v2 hooks into existing agent configs; the explicit `--agent kiro-cli-v3` target writes the incompatible standalone v3 registration. Both preserve unrelated entries, honor `$KIRO_HOME`, enforce capture exclusions, and inject pending handoffs at session start. Kiro has no true SessionEnd hook; use `ai-memory finalize-session --agent kiro-cli`, with `--session-id <uuid>` for concurrent sessions. `ai-memory run kiro` manages v2; add `--v3`, `--mode`, or `--agent-engine v3` for version-safe v3 resume. |-| Pool | Hooks-only | Poolside Agent CLI (`pool`). Lifecycle-hook capture via `install-hooks --agent pool` (alias `poolside`): Pool reads project-scoped hooks from the repo-root `.poolside/settings.yaml`, so ai-memory stages the scripts and prints a ready-to-paste `hooks:` snippet rather than writing project-local files; native commands enforce capture exclusions. Five Claude-shaped events (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`) and no true session-end — `Stop` is a turn boundary, so run `ai-memory finalize-session --agent pool` after the final turn. `SessionStart` stdout injection is not demonstrated, so capture works but handoff injection does not — recover handoffs via MCP `memory_handoff_accept`. No first-party `install-mcp` client and no managed workstream (`ai-memory run pool`) are claimed: Pool's native session-store contract is not demonstrated (see [`docs/managed-harness-contributions.md`](docs/managed-harness-contributions.md)). Verified against Poolside CLI v1.0.16. |+| Pool | Hooks-only | Poolside Agent CLI (`pool`). Lifecycle-hook capture via `install-hooks --agent pool` (alias `poolside`): Pool reads project-scoped hooks from the repo-root `.poolside/settings.yaml`, so ai-memory stages the scripts and prints a ready-to-paste `hooks:` snippet rather than writing project-local files; native commands enforce capture exclusions. Five Claude-shaped events (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`) and no true session-end — `Stop` is a turn boundary, so run `ai-memory finalize-session --agent pool` after the final turn. `SessionStart` stdout injection is not demonstrated, so capture works but handoff injection does not — recover handoffs via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. No first-party `install-mcp` client and no managed workstream (`ai-memory run pool`) are claimed: Pool's native session-store contract is not demonstrated (see [`docs/managed-harness-contributions.md`](docs/managed-harness-contributions.md)). Verified against Poolside CLI v1.0.16. || VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). || Zed | MCP-only | Native remote MCP under `context_servers` in Zed's user `settings.json`; no lifecycle hooks or managed-workstream support. || Hermes Agent | Community | Core hook ingestion recognizes `agent=hermes` and Hermes' documented shell-hook `tool_name` / `tool_input` payload for concrete session attribution, tool-family titles, and capture exclusions. A community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is available, but no first-party installer is shipped; review its compatibility matrix, install/uninstall scripts, and secret handling before using it. Hermes ignores session-start hook stdout, so recover handoffs through MCP. |diff --git a/docs/usage.md b/docs/usage.mdindex 5ef245cc..f83ea9b9 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -38,7 +38,9 @@ $ codex # in the same directory, laterIf an agent has MCP but no lifecycle hook surface, ask it to call`memory_handoff_begin` before quitting. The next hooked agent can still-consume that handoff automatically.+consume that handoff automatically. No-stdout clients (Grok, Zero) should+call `memory_handoff_list` on resume, then `memory_handoff_accept` with+the listed `handoff_id`; listing does not claim the row.On a server that distinguishes operators, handoffs belong to their creator bydefault: the next session for that operator sees their own plus deliberately@@ -87,7 +89,7 @@ at the managed ai-memory Agent Skills that carry detailed tool routing.| "Have we discussed X?" / "search memory for Y" | `memory_query` | FTS5 + entity/graph/vector RRF over compiled wiki pages, followed by bounded source-authority ranking and raw-observation fallback on a page miss. || 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. |+| "Where did we leave off?" | Existing handoff block, or `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id` if no block exists | Inspects pending handoffs without claiming, then claims the chosen id once. || "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. A project can keep advisory preferences in `_prompts/consolidation.md`; `instructions` overrides them for one call. Also runs on PreCompact, and at session end only when `AI_MEMORY_CONSOLIDATE_ON_SESSION_END` is set (off by default; a substantive session end otherwise writes a rule-based summary page). Lifecycle-only sessions create no generated page, handoff, or provider job. Opt-in SessionEnd provider work is durably queued outside the hook response, retried with backoff, and recovered after server restart. Resumed sessions re-end only when their persisted observation generation advances, so duplicate delivery and clock skew cannot loop consolidation. |diff --git a/docs/users.md b/docs/users.mdindex 6e8ea7b1..e4c21a7e 100644--- a/docs/users.md+++ b/docs/users.md@@ -190,7 +190,7 @@ to — and consumed by — the next session to start, whoever it belongs to.the same rule that decides the auth tier, so the proxy path gets realper-operator isolation rather than one shared bucket.- `memory_handoff_begin` takes `shared: true` to publish a baton deliberately.-- `memory_handoff_accept` / `memory_handoff_cancel` take `any_owner: true` to+- `memory_handoff_list` / `memory_handoff_accept` / `memory_handoff_cancel` take `any_owner: true` toact on somebody else's baton; that opt-out requires admin authority inmulti-user mode.- `ai-memory finalize-session --all-owners` does the same for sessions, and