Skip to content

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

Rust

test(mcp,cli): end-to-end use-case tests for cross-project agent messaging

AkitaOnRails4e10f0a22872
diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rs
index 4d2c4c05..f4338ab0 100644
--- a/crates/ai-memory-cli/tests/suite/main.rs
+++ b/crates/ai-memory-cli/tests/suite/main.rs
@@ -12,6 +12,7 @@ mod doctor_e2e;
mod hook_drain;
mod hook_payload;
mod marker_scope;
+mod message_e2e;
mod packaging;
mod removal;
mod repo_layout;
diff --git a/crates/ai-memory-cli/tests/suite/message_e2e.rs b/crates/ai-memory-cli/tests/suite/message_e2e.rs
new file mode 100644
index 00000000..2c1b6c4c
--- /dev/null
+++ b/crates/ai-memory-cli/tests/suite/message_e2e.rs
@@ -0,0 +1,415 @@
+//! Use-case end-to-end test for `ai-memory message` (cross-project inbox/queue).
+//!
+//! Cross-project messaging lets an agent in project A drop a self-contained
+//! request into project B's inbox without pulling B's context into A's session;
+//! a session in B later pops it exactly once. The store layer is pinned in
+//! `ai-memory-store`'s `agent_messages.rs` and the MCP tools in
+//! `ai-memory-mcp`'s `agent_messages_tools.rs`. The UNTESTED half is the whole
+//! CLI surface (`crates/ai-memory-cli/src/commands/message.rs` had zero tests):
+//! does the shipped `ai-memory message send|list|pop|cancel`, driven exactly as
+//! an operator would against a real spawned server, actually round-trip a
+//! message across the isolation boundary and enforce claim-once + recipient-only
+//! visibility + sender-only cancel?
+//!
+//! This drives that flow against a live `ai-memory serve`:
+//!
+//! 1. **Send + recipient-only visibility.** A→B send shows up in B's inbox and
+//! A's outbox, and in neither A's inbox nor an unrelated project's inbox.
+//! 2. **Pop claims exactly once.** B pops it (body fenced as untrusted input,
+//! with the security notice); a second pop finds nothing.
+//! 3. **Sender cancel.** A second A→B send, retracted from A by id, leaves B's
+//! inbox empty — the recipient never sees it.
+//!
+//! The recipient project must already exist for a send to be accepted (the
+//! server resolves both scopes with a no-create lookup), so the test first makes
+//! both projects real by firing a `session-start` hook for each — the "an agent
+//! must have run there at least once" precondition from `docs/agent-messaging.md`.
+
+/// Spawns a server and several subprocesses: seconds, not milliseconds, so this
+/// lives in the slow tier (`cargo tf` / CI), not the everyday loop.
+mod slow {
+ use std::net::TcpListener;
+ use std::path::Path;
+ use std::process::{Child, Command, Stdio};
+ use std::time::{Duration, Instant};
+
+ use serde_json::{Value, json};
+
+ const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");
+ const WORKSPACE: &str = "message-e2e-ws";
+ /// The sender project (the baked "current project" of the spawned server).
+ const SENDER: &str = "message-e2e-a";
+ /// The recipient project the sender addresses.
+ const RECIPIENT: &str = "message-e2e-b";
+ /// A third, uninvolved project — it must never see A→B mail.
+ const BYSTANDER: &str = "message-e2e-c";
+
+ /// Start from a clean, hermetic environment: drop every ambient
+ /// `AI_MEMORY_*` var (a developer box or this project's own MCP config may
+ /// export `AI_MEMORY_AUTH_TOKEN`, `AI_MEMORY_SERVER_URL`, scope names, …)
+ /// so the child sees only what this test sets. Without this the spawned
+ /// server would inherit an auth token and reject the test's own requests.
+ fn hermetic(program: &str) -> Command {
+ let mut cmd = Command::new(program);
+ for (key, _) in std::env::vars_os() {
+ if key.to_string_lossy().starts_with("AI_MEMORY_") {
+ cmd.env_remove(key);
+ }
+ }
+ cmd
+ }
+
+ /// Kill the spawned server when the test ends, pass or fail.
+ struct ServerGuard(Child);
+ impl Drop for ServerGuard {
+ fn drop(&mut self) {
+ let _ = self.0.kill();
+ let _ = self.0.wait();
+ }
+ }
+
+ /// A free loopback port. The brief unbind→rebind race is acceptable for a
+ /// slow-tier test and is the same approach the shell smoke test uses.
+ fn free_port() -> u16 {
+ TcpListener::bind("127.0.0.1:0")
+ .expect("bind ephemeral port")
+ .local_addr()
+ .expect("local addr")
+ .port()
+ }
+
+ /// Sum the server's per-agent session counts for a scope. A 404 (the
+ /// no-create scope lookup for a project that has never been written to)
+ /// counts as zero — the pre-existence state.
+ async fn session_count(client: &reqwest::Client, base: &str, project: &str) -> u64 {
+ let resp = client
+ .get(format!("{base}/admin/sessions/by-agent"))
+ .query(&[("workspace", WORKSPACE), ("project", project)])
+ .send()
+ .await
+ .expect("by-agent request");
+ if !resp.status().is_success() {
+ return 0;
+ }
+ let body: Value = resp.json().await.expect("by-agent json");
+ body["by_agent"]
+ .as_array()
+ .map(|agents| {
+ agents
+ .iter()
+ .filter_map(|a| a["sessions"].as_u64())
+ .sum::<u64>()
+ })
+ .unwrap_or(0)
+ }
+
+ /// Fire one `session-start` hook for `project`, then wait until the server
+ /// has committed it — which both creates the project scope (so a later send
+ /// can resolve it with the no-create lookup) and is the docs' "an agent ran
+ /// here at least once" precondition.
+ async fn ensure_project(client: &reqwest::Client, base: &str, project: &str, nth: u8) {
+ // A unique session id per project: a shared id would make the later
+ // hooks look like a cross-project session collision and be dropped,
+ // leaving those projects uncreated.
+ let session_id = format!("00000000-0000-4000-8000-0000000000{nth:02x}");
+ let resp = client
+ .post(format!("{base}/hook"))
+ .query(&[
+ ("event", "session-start"),
+ ("agent", "claude-code"),
+ ("workspace", WORKSPACE),
+ ("project", project),
+ ])
+ .header("content-type", "application/json")
+ .body(
+ json!({
+ "event": "session-start",
+ "session_id": session_id,
+ "cwd": format!("/tmp/message-e2e/{project}"),
+ })
+ .to_string(),
+ )
+ .send()
+ .await
+ .expect("hook request");
+ assert!(
+ resp.status().is_success() || resp.status().as_u16() == 202,
+ "hook must be accepted for {project}: {}",
+ resp.status()
+ );
+ let deadline = Instant::now() + Duration::from_secs(10);
+ loop {
+ if session_count(client, base, project).await >= 1 {
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "project {project} was never created by its session-start hook"
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ /// Run a subcommand of the built binary to completion, returning its stdout.
+ /// The scope/server/home environment is shared with the spawned server so
+ /// the client talks to the same store the way a real install does.
+ fn run_cli(args: &[&str], data_dir: &Path, home: &Path, base: &str) -> String {
+ let out = hermetic(BIN)
+ .args(args)
+ .env("AI_MEMORY_DATA_DIR", data_dir)
+ .env("AI_MEMORY_HOME", home)
+ .env("AI_MEMORY_SERVER_URL", base)
+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")
+ .env("RUST_LOG", "off")
+ .output()
+ .unwrap_or_else(|e| panic!("spawn `{}`: {e}", args.join(" ")));
+ assert!(
+ out.status.success(),
+ "`{}` failed: {}\nstdout: {}\nstderr: {}",
+ args.join(" "),
+ out.status,
+ String::from_utf8_lossy(&out.stdout),
+ String::from_utf8_lossy(&out.stderr),
+ );
+ String::from_utf8(out.stdout).expect("stdout utf8")
+ }
+
+ /// `ai-memory message send` A→B with `--json`, returning the new message id.
+ fn send(data_dir: &Path, home: &Path, base: &str, subject: &str, body: &str) -> String {
+ let out = run_cli(
+ &[
+ "message",
+ "send",
+ "--from-workspace",
+ WORKSPACE,
+ "--from-project",
+ SENDER,
+ "--to-workspace",
+ WORKSPACE,
+ "--to-project",
+ RECIPIENT,
+ "--subject",
+ subject,
+ "--json",
+ body,
+ ],
+ data_dir,
+ home,
+ base,
+ );
+ let report: Value = serde_json::from_str(&out).expect("send --json report");
+ report["message_id"]
+ .as_str()
+ .unwrap_or_else(|| panic!("send returned no message_id: {report}"))
+ .to_string()
+ }
+
+ /// `ai-memory message list` for `project` with `--json`, returning the array.
+ fn list(data_dir: &Path, home: &Path, base: &str, project: &str, outbox: bool) -> Vec<Value> {
+ let mut args = vec![
+ "message",
+ "list",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ project,
+ "--json",
+ ];
+ if outbox {
+ args.push("--outbox");
+ }
+ let out = run_cli(&args, data_dir, home, base);
+ serde_json::from_str(&out).expect("list --json array")
+ }
+
+ #[tokio::test]
+ async fn message_round_trips_across_projects_with_claim_once_and_cancel() {
+ let data_dir = tempfile::tempdir().expect("data dir");
+ let home = tempfile::tempdir().expect("home");
+
+ // Start the real server (loopback, no auth, hermetic: no embedder, no
+ // wiki watcher — a machine-global inotify instance concurrent server
+ // children can exhaust, #745).
+ let port = free_port();
+ let base = format!("http://127.0.0.1:{port}");
+ let server = ServerGuard(
+ hermetic(BIN)
+ .args([
+ "serve",
+ "--transport",
+ "http",
+ "--bind",
+ &format!("127.0.0.1:{port}"),
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ SENDER,
+ "--no-watcher",
+ ])
+ .env("AI_MEMORY_DATA_DIR", data_dir.path())
+ .env("AI_MEMORY_HOME", home.path())
+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")
+ .env("RUST_LOG", "off")
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .expect("spawn serve"),
+ );
+
+ let client = reqwest::Client::new();
+
+ // Wait for the server to accept connections.
+ let deadline = Instant::now() + Duration::from_secs(30);
+ loop {
+ if client
+ .get(format!("{base}/mcp"))
+ .timeout(Duration::from_secs(2))
+ .send()
+ .await
+ .is_ok()
+ {
+ break;
+ }
+ assert!(Instant::now() < deadline, "server never became reachable");
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ }
+
+ // A send is rejected unless the recipient project already exists, so make
+ // all three projects real by "running an agent" in each once.
+ for (nth, project) in [SENDER, RECIPIENT, BYSTANDER].into_iter().enumerate() {
+ ensure_project(&client, &base, project, nth as u8 + 1).await;
+ }
+
+ // Phase 1 — send A→B, then check where it is visible.
+ let body = "Add a /v1/export endpoint that streams NDJSON. Keep the auth middleware.";
+ let id = send(data_dir.path(), home.path(), &base, "export endpoint", body);
+
+ let inbox_b = list(data_dir.path(), home.path(), &base, RECIPIENT, false);
+ assert_eq!(
+ inbox_b.len(),
+ 1,
+ "B's inbox must show exactly the sent message: {inbox_b:?}"
+ );
+ assert_eq!(inbox_b[0]["id"].as_str(), Some(id.as_str()));
+ assert_eq!(inbox_b[0]["body"].as_str(), Some(body));
+ assert_eq!(inbox_b[0]["subject"].as_str(), Some("export endpoint"));
+ assert_eq!(inbox_b[0]["state"].as_str(), Some("pending"));
+
+ // Recipient-only visibility: not in A's inbox, not in the bystander's.
+ assert!(
+ list(data_dir.path(), home.path(), &base, SENDER, false).is_empty(),
+ "the sender must not see its outbound mail in its own inbox"
+ );
+ assert!(
+ list(data_dir.path(), home.path(), &base, BYSTANDER, false).is_empty(),
+ "an unrelated project must not see mail addressed to B"
+ );
+
+ // The sender sees it in its OUTBOX (what it can still cancel).
+ let outbox_a = list(data_dir.path(), home.path(), &base, SENDER, true);
+ assert_eq!(
+ outbox_a.len(),
+ 1,
+ "A's outbox must show the message it sent"
+ );
+ assert_eq!(outbox_a[0]["id"].as_str(), Some(id.as_str()));
+
+ // Phase 2 — B pops it exactly once. The human rendering fences the body
+ // as untrusted cross-project input and prints the security notice.
+ let popped_human = run_cli(
+ &[
+ "message",
+ "pop",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ RECIPIENT,
+ ],
+ data_dir.path(),
+ home.path(),
+ &base,
+ );
+ assert!(
+ popped_human.contains(&id),
+ "pop must name the popped message id: {popped_human}"
+ );
+ assert!(
+ popped_human.contains(body),
+ "pop must print the message body: {popped_human}"
+ );
+ assert!(
+ popped_human.contains("untrusted cross-project input"),
+ "pop must fence the body as untrusted input: {popped_human}"
+ );
+
+ // Claim-once: the inbox is now empty and a second pop returns nothing.
+ assert!(
+ list(data_dir.path(), home.path(), &base, RECIPIENT, false).is_empty(),
+ "the inbox must be empty once the message is claimed"
+ );
+ let second_pop = run_cli(
+ &[
+ "message",
+ "pop",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ RECIPIENT,
+ "--json",
+ ],
+ data_dir.path(),
+ home.path(),
+ &base,
+ );
+ let second: Value = serde_json::from_str(&second_pop).expect("second pop --json");
+ assert_eq!(
+ second["message"],
+ Value::Null,
+ "a claimed message must not be poppable again: {second}"
+ );
+
+ // Phase 3 — sender cancel. A second send, retracted from A by id, must
+ // never reach B.
+ let id2 = send(
+ data_dir.path(),
+ home.path(),
+ &base,
+ "never mind",
+ "cancel me",
+ );
+ assert_eq!(
+ list(data_dir.path(), home.path(), &base, RECIPIENT, false).len(),
+ 1,
+ "the second message must be pending in B before cancel"
+ );
+ let cancel = run_cli(
+ &[
+ "message",
+ "cancel",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ SENDER,
+ "--id",
+ &id2,
+ "--json",
+ ],
+ data_dir.path(),
+ home.path(),
+ &base,
+ );
+ let cancel: Value = serde_json::from_str(&cancel).expect("cancel --json");
+ assert_eq!(
+ cancel["cancelled"].as_u64(),
+ Some(1),
+ "the sender must cancel exactly its one pending message: {cancel}"
+ );
+ assert!(
+ list(data_dir.path(), home.path(), &base, RECIPIENT, false).is_empty(),
+ "a cancelled message must never reach the recipient inbox"
+ );
+
+ drop(server);
+ }
+}
diff --git a/crates/ai-memory-mcp/tests/suite/agent_messages_tools.rs b/crates/ai-memory-mcp/tests/suite/agent_messages_tools.rs
new file mode 100644
index 00000000..76119fce
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/suite/agent_messages_tools.rs
@@ -0,0 +1,330 @@
+//! The user-facing MCP surface for cross-project agent messaging (V64).
+//!
+//! The store layer is pinned in `ai-memory-store`'s `agent_messages.rs`; what is
+//! untested there is the four tools an agent actually calls —
+//! `memory_message_send`, `memory_message_list`, `memory_message_pop`, and
+//! `memory_message_cancel` — driven through the real `tools/call` JSON-RPC path
+//! and asserted on the user-visible JSON they return. These are the surfaces
+//! `docs/agent-messaging.md` documents, so the behaviours pinned here are the
+//! ones a Kimi-in-A → Claude-in-B round trip depends on: a message crosses the
+//! per-project isolation boundary on purpose, so it is visible only in the
+//! recipient's inbox and the sender's outbox; it pops exactly once; and the
+//! sender can retract it while the recipient cannot cancel someone else's send.
+//!
+//! The harness mounts the production `AiMemoryServer` over the same
+//! Streamable-HTTP transport `handoff_identity.rs` uses, with no auth layer
+//! (the local/stdio shape), and drives every scope explicitly the way a static
+//! MCP client does — so `to_*`/`from_*`/`workspace`+`project` are the exact
+//! arguments an agent sends.
+
+use ai_memory_mcp::AiMemoryServer;
+use ai_memory_store::Store;
+use ai_memory_wiki::Wiki;
+use axum::Router;
+use axum::body::Body;
+use axum::http::Request;
+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
+use serde_json::{Value, json};
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+const WS: &str = "default";
+const A: &str = "project-a";
+const B: &str = "project-b";
+const C: &str = "project-c";
+
+struct Harness {
+ router: Router,
+ _tmp: TempDir,
+}
+
+fn mount(server: AiMemoryServer) -> Router {
+ let service = StreamableHttpService::new(
+ move || Ok(server.clone()),
+ LocalSessionManager::default().into(),
+ StreamableHttpServerConfig::default()
+ .with_stateful_mode(false)
+ .with_json_response(true),
+ );
+ Router::new().nest_service("/mcp", service)
+}
+
+/// A server over a temp store/wiki with three sibling projects in one
+/// workspace: `project-a` (the baked "current project"), `project-b`, and
+/// `project-c`. All three must already exist, because sends and reads resolve
+/// scope through the no-create lookup.
+async fn harness() -> Harness {
+ let tmp = TempDir::new().expect("tempdir");
+ let store = Store::open(tmp.path()).expect("store");
+ let ws = store.writer.get_or_create_workspace(WS).await.expect("ws");
+ let baked = store
+ .writer
+ .get_or_create_project(ws, A.to_string(), None)
+ .await
+ .expect("project-a");
+ for name in [B, C] {
+ store
+ .writer
+ .get_or_create_project(ws, name.to_string(), None)
+ .await
+ .expect("sibling project");
+ }
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).expect("wiki");
+ let server =
+ AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, baked).with_wiki(wiki);
+ Harness {
+ router: mount(server),
+ _tmp: tmp,
+ }
+}
+
+/// Drive one real `tools/call` and return the parsed tool JSON payload.
+async fn call(router: &Router, name: &str, arguments: Value) -> Value {
+ let body = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": { "name": name, "arguments": arguments },
+ });
+ let req = Request::builder()
+ .method("POST")
+ .uri("/mcp")
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ .header("accept", "application/json, text/event-stream")
+ .body(Body::from(body.to_string()))
+ .expect("mcp req");
+ let resp = router.clone().oneshot(req).await.expect("oneshot");
+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)
+ .await
+ .expect("body");
+ let text = String::from_utf8(bytes.to_vec()).expect("utf8");
+ let v: Value = serde_json::from_str(&text).unwrap_or_else(|e| panic!("non-JSON: {text}: {e}"));
+ if let Some(err) = v.get("error") {
+ panic!("JSON-RPC error: {err}\nfull: {text}");
+ }
+ let joined = v
+ .pointer("/result/content")
+ .and_then(|c| c.as_array())
+ .unwrap_or_else(|| panic!("missing result.content: {text}"))
+ .iter()
+ .filter_map(|i| i.get("text").and_then(|t| t.as_str()))
+ .collect::<Vec<_>>()
+ .join("\n");
+ serde_json::from_str(&joined).unwrap_or_else(|e| panic!("tool text not JSON: {joined}: {e}"))
+}
+
+/// `memory_message_send` from `project-a` to `project-b`, returning the new id.
+async fn send(router: &Router, subject: &str, body: &str) -> String {
+ let sent = call(
+ router,
+ "memory_message_send",
+ json!({
+ "from_workspace": WS,
+ "from_project": A,
+ "to_workspace": WS,
+ "to_project": B,
+ "subject": subject,
+ "body": body,
+ }),
+ )
+ .await;
+ sent.get("message_id")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| panic!("send returned no message_id: {sent}"))
+ .to_string()
+}
+
+/// The messages array from a `memory_message_list` for `workspace/project`.
+async fn list(router: &Router, project: &str, mailbox: &str) -> Vec<Value> {
+ let listed = call(
+ router,
+ "memory_message_list",
+ json!({ "workspace": WS, "project": project, "box": mailbox }),
+ )
+ .await;
+ listed
+ .get("messages")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("list returned no messages array: {listed}"))
+ .clone()
+}
+
+/// The full end-to-end round trip through the tools: A sends to B, only B's
+/// inbox (and A's outbox) shows it, B pops it exactly once, and a second pop
+/// finds nothing.
+#[tokio::test]
+async fn send_list_pop_delivers_to_recipient_exactly_once() {
+ let h = harness().await;
+ let body = "Add a /v1/export endpoint that streams NDJSON.";
+ let id = send(&h.router, "export endpoint", body).await;
+
+ // B's inbox shows exactly the one message, with the sent content and id.
+ let inbox = list(&h.router, B, "inbox").await;
+ assert_eq!(
+ inbox.len(),
+ 1,
+ "B's inbox must show exactly the sent message"
+ );
+ assert_eq!(inbox[0]["id"].as_str(), Some(id.as_str()));
+ assert_eq!(inbox[0]["body"].as_str(), Some(body));
+ assert_eq!(inbox[0]["subject"].as_str(), Some("export endpoint"));
+ assert_eq!(inbox[0]["state"].as_str(), Some("pending"));
+
+ // Recipient-only visibility: neither the sender's inbox nor an unrelated
+ // third project sees mail addressed to B.
+ assert!(
+ list(&h.router, A, "inbox").await.is_empty(),
+ "the sender must not see its own outbound mail in its inbox"
+ );
+ assert!(
+ list(&h.router, C, "inbox").await.is_empty(),
+ "an unrelated project must not see mail addressed to B"
+ );
+
+ // The sender does see it in its OUTBOX (it is what A can still cancel).
+ let outbox = list(&h.router, A, "outbox").await;
+ assert_eq!(outbox.len(), 1, "A's outbox must show the message it sent");
+ assert_eq!(outbox[0]["id"].as_str(), Some(id.as_str()));
+
+ // B pops it exactly once: the body comes back fenced with a security notice.
+ let popped = call(
+ &h.router,
+ "memory_message_pop",
+ json!({ "workspace": WS, "project": B }),
+ )
+ .await;
+ assert_eq!(popped["message"]["id"].as_str(), Some(id.as_str()));
+ assert_eq!(popped["message"]["body"].as_str(), Some(body));
+ assert_eq!(
+ popped["message"]["state"].as_str(),
+ Some("claimed"),
+ "a popped message is marked claimed: {popped}"
+ );
+ assert!(
+ popped["security_notice"].as_str().is_some(),
+ "pop must carry the untrusted-input security notice: {popped}"
+ );
+
+ // Claim-once: the inbox is empty and a second pop returns nothing.
+ assert!(
+ list(&h.router, B, "inbox").await.is_empty(),
+ "the inbox must be empty once the message is claimed"
+ );
+ let again = call(
+ &h.router,
+ "memory_message_pop",
+ json!({ "workspace": WS, "project": B }),
+ )
+ .await;
+ assert_eq!(
+ again["message"],
+ Value::Null,
+ "a claimed message must not be poppable again: {again}"
+ );
+}
+
+/// A non-recipient project cannot pop mail addressed to B: its own inbox pop
+/// returns nothing and B's message stays pending and claimable.
+#[tokio::test]
+async fn a_non_recipient_cannot_pop_the_recipients_mail() {
+ let h = harness().await;
+ let id = send(&h.router, "for B only", "for B only").await;
+
+ // C pops from its own (empty) inbox — it cannot reach B's mail.
+ let c_pop = call(
+ &h.router,
+ "memory_message_pop",
+ json!({ "workspace": WS, "project": C }),
+ )
+ .await;
+ assert_eq!(
+ c_pop["message"],
+ Value::Null,
+ "C must not be able to pop mail addressed to B: {c_pop}"
+ );
+
+ // B's message is untouched and still deliverable to B.
+ let b_pop = call(
+ &h.router,
+ "memory_message_pop",
+ json!({ "workspace": WS, "project": B }),
+ )
+ .await;
+ assert_eq!(b_pop["message"]["id"].as_str(), Some(id.as_str()));
+}
+
+/// The sender retracts a pending message through `memory_message_cancel`; once
+/// cancelled the recipient can no longer pop it.
+#[tokio::test]
+async fn sender_can_cancel_a_pending_message() {
+ let h = harness().await;
+ let id = send(&h.router, "never mind", "never mind soon").await;
+
+ let cancelled = call(
+ &h.router,
+ "memory_message_cancel",
+ json!({ "workspace": WS, "project": A, "message_id": id }),
+ )
+ .await;
+ assert_eq!(
+ cancelled["cancelled"].as_u64(),
+ Some(1),
+ "the sender must cancel exactly its one pending message: {cancelled}"
+ );
+
+ assert!(
+ list(&h.router, B, "inbox").await.is_empty(),
+ "a cancelled message must leave the recipient inbox"
+ );
+ let popped = call(
+ &h.router,
+ "memory_message_pop",
+ json!({ "workspace": WS, "project": B }),
+ )
+ .await;
+ assert_eq!(
+ popped["message"],
+ Value::Null,
+ "a cancelled message must not be deliverable: {popped}"
+ );
+}
+
+/// Cancel is scoped to the SENDER coordinate: the recipient calling cancel from
+/// its own project clears nothing and the message it received survives — the
+/// tool-surface mirror of the store's `recipient_cannot_cancel_the_senders_outbox`.
+#[tokio::test]
+async fn recipient_cannot_cancel_the_senders_message() {
+ let h = harness().await;
+ let id = send(&h.router, "do the work", "do the work").await;
+
+ // B cancels scoped to its own project: it has no outbox mail, so nothing
+ // is cancelled and A's message to B survives.
+ let cancelled = call(
+ &h.router,
+ "memory_message_cancel",
+ json!({ "workspace": WS, "project": B }),
+ )
+ .await;
+ assert_eq!(
+ cancelled["cancelled"].as_u64(),
+ Some(0),
+ "the recipient cancelling its own outbox must touch nothing: {cancelled}"
+ );
+
+ // The message is still there and still poppable by B.
+ let inbox = list(&h.router, B, "inbox").await;
+ assert_eq!(
+ inbox.len(),
+ 1,
+ "A's message must survive B's cancel attempt"
+ );
+ let popped = call(
+ &h.router,
+ "memory_message_pop",
+ json!({ "workspace": WS, "project": B }),
+ )
+ .await;
+ assert_eq!(popped["message"]["id"].as_str(), Some(id.as_str()));
+}
diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rs
index 421af735..61b4866e 100644
--- a/crates/ai-memory-mcp/tests/suite/mod.rs
+++ b/crates/ai-memory-mcp/tests/suite/mod.rs
@@ -16,6 +16,7 @@ mod admin_read_page;
mod admin_rename;
mod admin_status_search;
mod admin_write_page;
+mod agent_messages_tools;
mod autoscope_multiuser;
mod handoff_admission;
mod handoff_identity;