Skip to content

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

Rust

fix(messages): diagnose an empty inbox read under an inferred scope (#854)

AkitaOnRails4b6341b1831f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 188df552..cc5e182d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixed
+- `memory_message_pop` and `memory_message_list` no longer return a silent
+ empty result when the inbox scope was *inferred* rather than named. A caller
+ with no explicit `workspace`/`project` and no forwarded hook-session id
+ resolves the shared active-project slot (whichever project published last),
+ so two same-operator agents can have a no-scope pop land on a different inbox
+ than the on-start notice / `memory_briefing` counted — "you have mail"
+ followed by an empty fetch, with no way to tell it was the wrong inbox. An
+ empty read from an inferred scope now reports the `resolved_scope`
+ (workspace + project), the `scope_source`, and a hint to re-run with explicit
+ scope; an explicitly-scoped or session-bound empty read is unchanged. No
+ message is lost — the mis-scoped pop consumes nothing. (#854)
- `companions/ai-memory-macos/build.sh` no longer fails on machines whose
active developer directory is Command Line Tools only: SwiftUI `@State`
needs the `SwiftUIMacros` plugin shipped with full Xcode, so the script
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 3b812f8b..d5ad993d 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -1960,6 +1960,44 @@ impl AiMemoryServer {
)
}
+ /// Diagnostic fields for an EMPTY inbox read whose scope was *inferred*
+ /// (not named by the caller, not bound to the caller's hook session).
+ ///
+ /// An inferred scope can be the wrong inbox: two same-operator agents with
+ /// no session id share one active-project slot, so a no-scope
+ /// `memory_message_pop` / `memory_message_list` can resolve a *different*
+ /// project than the on-start notice / `memory_briefing` counted — the exact
+ /// dead-end where "you have mail" is followed by an empty fetch. Naming the
+ /// resolved scope and how it was inferred turns that silent empty into an
+ /// actionable "re-run with explicit workspace + project". Merged into the
+ /// response only when the read came back empty AND the scope was inferred.
+ async fn inferred_scope_hint(
+ &self,
+ ws: ai_memory_core::WorkspaceId,
+ proj: ai_memory_core::ProjectId,
+ source: ai_memory_store::ScopeSource,
+ ) -> serde_json::Map<String, serde_json::Value> {
+ let (ws_name, proj_name) = self.scope_names(ws, proj).await;
+ let hint = format!(
+ "This inbox ({ws_name}/{proj_name}) was resolved by {source} scope, not \
+ named explicitly, so it may not be the inbox you meant. A SessionStart \
+ notice or memory_briefing count is for the project it named; if you \
+ expected mail here, re-run with explicit workspace and project.",
+ source = source.as_str(),
+ );
+ let mut fields = serde_json::Map::new();
+ fields.insert(
+ "resolved_scope".to_owned(),
+ serde_json::json!({ "workspace": ws_name, "project": proj_name }),
+ );
+ fields.insert(
+ "scope_source".to_owned(),
+ serde_json::Value::String(source.as_str().to_owned()),
+ );
+ fields.insert("hint".to_owned(), serde_json::Value::String(hint));
+ fields
+ }
+
async fn embed_query(&self, query: &str) -> Option<Vec<f32>> {
let Some(embedder) = &self.embedder else {
return None;
@@ -4524,8 +4562,8 @@ impl AiMemoryServer {
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(
+ let ((ws, proj), scope_source) = self
+ .traced_ids_for_read_args(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
@@ -4552,7 +4590,19 @@ impl AiMemoryServer {
.list_messages(ws, proj, mailbox, limit)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
- ok_json(&serde_json::json!({ "messages": messages }))
+ let mut obj = serde_json::Map::new();
+ // An empty inbox listing under an inferred scope is the same ambiguity
+ // as an empty pop: the caller may be looking at the wrong project.
+ // Only the inbox side can be mis-resolved this way (the outbox is the
+ // caller's own sent mail).
+ if messages.is_empty()
+ && matches!(mailbox, ai_memory_core::MessageBox::Inbox)
+ && scope_source.is_inferred()
+ {
+ obj.extend(self.inferred_scope_hint(ws, proj, scope_source).await);
+ }
+ obj.insert("messages".to_owned(), serde_json::json!(messages));
+ ok_json(&serde_json::Value::Object(obj))
}
/// Pop (claim exactly once) the next inbox message.
@@ -4575,8 +4625,8 @@ impl AiMemoryServer {
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(
+ let ((ws, proj), scope_source) = self
+ .traced_ids_for_read_args(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
@@ -4610,7 +4660,20 @@ impl AiMemoryServer {
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
match popped {
- None => ok_json(&serde_json::json!({ "message": null })),
+ None => {
+ // A no-scope pop that resolves the shared active-project slot
+ // can land on a different (empty) inbox than the on-start
+ // notice counted — a silent dead-end. When the scope was
+ // inferred, say which inbox was checked and how, so the caller
+ // can re-pop with explicit workspace + project (#847-adjacent
+ // messaging scope divergence).
+ let mut obj = serde_json::Map::new();
+ obj.insert("message".to_owned(), serde_json::Value::Null);
+ if scope_source.is_inferred() {
+ obj.extend(self.inferred_scope_hint(ws, proj, scope_source).await);
+ }
+ ok_json(&serde_json::Value::Object(obj))
+ }
Some(message) => {
self.notify_operation_observers(admission.as_ref());
// Fence the body as untrusted cross-project input, and surface
diff --git a/crates/ai-memory-mcp/tests/suite/agent_messages_briefing.rs b/crates/ai-memory-mcp/tests/suite/agent_messages_briefing.rs
index 85d1a985..8c17c2ed 100644
--- a/crates/ai-memory-mcp/tests/suite/agent_messages_briefing.rs
+++ b/crates/ai-memory-mcp/tests/suite/agent_messages_briefing.rs
@@ -204,3 +204,132 @@ async fn briefing_pending_message_count_tracks_the_recipient_inbox() {
"popping one message must drop the briefed pending_message_count to 2",
);
}
+
+/// Regression for the field-reported dead-end (cross-project mail on the
+/// homeserver): the on-start notice / `memory_briefing` counts one project's
+/// inbox, but a *no-scope* `memory_message_pop` resolves the shared
+/// active-project slot to a DIFFERENT project whose inbox is empty, and used to
+/// return a bare `{"message": null}` — "you have mail" followed by an empty
+/// fetch, with no way to tell they were looking at the wrong inbox.
+///
+/// The mail must stay put (the mis-scoped pop consumes nothing), the empty
+/// result must NAME the inbox it actually resolved and how it was inferred, and
+/// an explicit-scope pop must still deliver.
+#[tokio::test]
+async fn no_scope_pop_that_misses_the_mail_is_diagnosed_not_a_silent_null() {
+ let h = harness().await;
+
+ // Mail lands in project-b's inbox; the notice/briefing for B reports it.
+ send_to_b(&h.router, "export", "please add the /v1/export endpoint").await;
+ assert_eq!(pending_count(&h.router, B).await, 1);
+
+ // A no-scope pop resolves the baked "current project" (project-a), whose
+ // inbox is empty. It must not be a bare null: it names the resolved scope
+ // and flags that the scope was inferred, not stated.
+ let missed = call(&h.router, "memory_message_pop", json!({})).await;
+ assert!(
+ missed["message"].is_null(),
+ "the wrong (inferred) inbox has no mail: {missed}",
+ );
+ assert_eq!(
+ missed["resolved_scope"]["project"].as_str(),
+ Some(A),
+ "an empty inferred-scope pop must name the inbox it resolved: {missed}",
+ );
+ let src = missed["scope_source"].as_str().unwrap_or_default();
+ assert!(
+ !src.is_empty() && src != "explicit" && src != "session",
+ "the miss must report an inferred (non-explicit, non-session) scope source, got {src:?}: {missed}",
+ );
+ assert!(
+ missed["hint"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("explicit"),
+ "the hint must steer the caller to re-run with explicit scope: {missed}",
+ );
+
+ // The mis-scoped pop consumed nothing: B still has its message.
+ assert_eq!(
+ pending_count(&h.router, B).await,
+ 1,
+ "a pop that resolved the wrong inbox must not consume B's mail",
+ );
+
+ // Popping with explicit scope delivers it.
+ let got = call(
+ &h.router,
+ "memory_message_pop",
+ json!({ "workspace": WS, "project": B }),
+ )
+ .await;
+ assert_eq!(
+ got["message"]["body"], "please add the /v1/export endpoint",
+ "an explicit-scope pop of B delivers the message: {got}",
+ );
+ assert!(
+ got.get("hint").is_none(),
+ "a successful pop carries no scope hint: {got}",
+ );
+ assert_eq!(pending_count(&h.router, B).await, 0);
+
+ // An EXPLICIT pop of an empty inbox is unambiguous — no hint.
+ let empty_explicit = call(
+ &h.router,
+ "memory_message_pop",
+ json!({ "workspace": WS, "project": C }),
+ )
+ .await;
+ assert!(empty_explicit["message"].is_null());
+ assert!(
+ empty_explicit.get("hint").is_none(),
+ "an explicitly-scoped empty pop is not ambiguous and must not add a hint: {empty_explicit}",
+ );
+}
+
+/// The same divergence via `memory_message_list`: a no-scope inbox listing that
+/// resolves the wrong (empty) project names the inferred scope instead of
+/// silently returning `{"messages": []}`, while an explicit listing of B shows
+/// the mail with no hint.
+#[tokio::test]
+async fn no_scope_inbox_list_that_misses_the_mail_names_the_inferred_scope() {
+ let h = harness().await;
+ send_to_b(&h.router, "export", "please add the /v1/export endpoint").await;
+
+ // No-scope inbox list resolves project-a (empty) -> hint, not a silent [].
+ let missed = call(&h.router, "memory_message_list", json!({ "box": "inbox" })).await;
+ assert_eq!(
+ missed["messages"].as_array().map(Vec::len),
+ Some(0),
+ "the inferred (wrong) inbox is empty: {missed}",
+ );
+ assert_eq!(
+ missed["resolved_scope"]["project"].as_str(),
+ Some(A),
+ "an empty inferred-scope list must name the inbox it resolved: {missed}",
+ );
+ assert!(
+ missed["hint"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("explicit"),
+ "the list hint must steer the caller to explicit scope: {missed}",
+ );
+
+ // Explicit inbox list of B shows the mail and carries no hint.
+ let seen = call(
+ &h.router,
+ "memory_message_list",
+ json!({ "box": "inbox", "workspace": WS, "project": B }),
+ )
+ .await;
+ assert_eq!(
+ seen["messages"].as_array().map(Vec::len),
+ Some(1),
+ "explicit list of B shows its mail: {seen}",
+ );
+ assert!(
+ seen.get("hint").is_none(),
+ "a non-empty explicit list carries no scope hint: {seen}",
+ );
+}
diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rs
index abbed5c9..255687de 100644
--- a/crates/ai-memory-store/src/scope.rs
+++ b/crates/ai-memory-store/src/scope.rs
@@ -113,6 +113,23 @@ impl ScopeSource {
ScopeSource::StartupSeed | ScopeSource::DefaultAfterMismatch
)
}
+
+ /// True when the scope was inferred from a pointer or default rather than
+ /// stated by the caller ([`ScopeSource::Explicit`]) or bound to the
+ /// caller's own hook session ([`ScopeSource::Session`]).
+ ///
+ /// Broader than [`Self::is_fallback`] on purpose: it also covers
+ /// [`ScopeSource::SharedSlot`] (whichever project published last). Two
+ /// same-operator agents with no session id share that one slot, so a
+ /// no-scope read can resolve to a *different* project than the caller
+ /// meant — the empty-pop dead-end where the on-start inbox notice counted
+ /// one project's mail but a later no-scope `memory_message_pop` resolved
+ /// another project's (empty) inbox and returned nothing. A surface that
+ /// answers from an inferred scope should say so when the answer is empty.
+ #[must_use]
+ pub fn is_inferred(self) -> bool {
+ !matches!(self, ScopeSource::Explicit | ScopeSource::Session)
+ }
}
impl fmt::Display for ScopeSource {