Skip to content

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

Rust

fix(auto-scope): prevent scoped fallback bleed

AkitaOnRails2a75394bbe96
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a689e4c5..931d1ad0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
upgraded servers (the antigravity/`V11` precedent).
### Fixed
+- Actor-scoped MCP tool calls no longer fall through to a user's or process's
+ latest hook-published project when the request carries a session id that does
+ not match hook activity. This prevents HTTP-remote shared servers from reading
+ or writing another same-user project when the MCP transport session id differs
+ from the hook session id ([#97]).
- `memory_handoff_begin` and `memory_handoff_accept` now accept an optional
`workspace` argument alongside `project`, resolving through the same
workspace+project path as `memory_write_page` (begin, create-if-missing) and
diff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rs
index 01a37efc..93f61714 100644
--- a/crates/ai-memory-core/src/active_project.rs
+++ b/crates/ai-memory-core/src/active_project.rs
@@ -29,18 +29,19 @@
//! the same operator (one person with several Claude Code / Codex windows
//! in different repos at once).
//! - `PerActor` keys by `(user, session_id)` when both coordinates are present
-//! and also keeps a user-only fallback slot. That isolates across operators
-//! even when a client cannot forward a per-session key, while preserving
-//! per-session isolation for clients/bridges that do forward one. Pairs with
-//! multi-user mode (rung 2): `user` comes from the `users` row that owns the
-//! bearer token.
+//! and also keeps a user-only slot for requests that truly have no session
+//! coordinate. That isolates across operators while preserving per-session
+//! isolation for clients/bridges that do forward one. Pairs with multi-user
+//! mode (rung 2): `user` comes from the `users` row that owns the bearer
+//! token.
//!
//! When the caller has no actor identity at all (anonymous request without a
//! session, or a code path the migration has not threaded yet), every mode
//! falls back to the single slot for backward compatibility. That is a legacy
-//! convenience, not isolation; session-aware clients should forward a session
-//! key, and shared authenticated installs should use `PerActor` so user-scoped
-//! fallback applies before the global slot. The single slot is also what the
+//! convenience, not isolation. If a request provides a usable actor coordinate
+//! and the keyed lookup misses, `get_for` returns `None` instead of falling
+//! through to another session's latest project; callers then use their baked
+//! default or an explicit workspace/project. The single slot is also what the
//! historical `set` / `get` / `clear` API touches, so existing callers compile
//! unchanged and admin ops like `move-project` still invalidate the pointer
//! correctly.
@@ -247,11 +248,9 @@ impl ActiveProject {
/// *and* the single slot is updated as well, so callers that have no
/// actor identity (anonymous probes, legacy code paths) still see the
/// latest project rather than an empty pointer.
- /// - In `PerActor`, a user-only fallback entry is also set when `user` is
- /// present. Real MCP clients often cannot attach the hook payload's
- /// session id to every tool call; the user-only slot still prevents an
- /// authenticated Alice request from falling through to Bob's latest
- /// project in the global slot.
+ /// - In `PerActor`, a user-only entry is also set when `user` is present.
+ /// Requests that carry that user but no session id can still resolve to
+ /// the user's latest project without falling through to the global slot.
pub fn set_for(&self, actor: &ActorKey, workspace_id: WorkspaceId, project_id: ProjectId) {
self.write_single(workspace_id, project_id);
if self.mode == ActiveProjectMode::Single || actor.is_empty() {
@@ -280,34 +279,27 @@ impl ActiveProject {
}
/// Read the currently active project for the given actor, if any has
- /// been published yet. Falls back to the single slot when:
+ /// been published yet. Falls back to the single slot only when:
/// - the mode is `Single`, or
- /// - the actor is empty (no identity coordinates), or
- /// - no per-actor entry matches (graceful degradation).
+ /// - the actor is empty, or has no coordinate usable by the selected mode.
+ ///
+ /// When a request provides a usable session/user coordinate and that keyed
+ /// entry is absent, return `None`. Falling through to the user/global latest
+ /// slot would route a remote MCP request with a mismatched session id into
+ /// whichever project published hook activity last.
#[must_use]
pub fn get_for(&self, actor: &ActorKey) -> Option<(WorkspaceId, ProjectId)> {
- if self.mode != ActiveProjectMode::Single && !actor.is_empty() {
- let scoped = self.scoped_key(actor);
- if !scoped.is_empty() {
- let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());
- if let Some(found) = guard.get(&scoped, Instant::now()) {
- return Some(found);
- }
- if self.mode == ActiveProjectMode::PerActor
- && scoped.user.is_some()
- && scoped.session_id.is_some()
- {
- let user_only = ActorKey {
- user: scoped.user.clone(),
- session_id: None,
- };
- if let Some(found) = guard.get(&user_only, Instant::now()) {
- return Some(found);
- }
- }
- }
+ if self.mode == ActiveProjectMode::Single || actor.is_empty() {
+ return self.read_single();
}
- self.read_single()
+
+ let scoped = self.scoped_key(actor);
+ if scoped.is_empty() {
+ return self.read_single();
+ }
+
+ let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());
+ guard.get(&scoped, Instant::now())
}
/// Project the actor's identity onto only the coordinates the current
@@ -363,10 +355,8 @@ impl ActiveProject {
guard.entries.clear();
}
- /// Test-only: look up only the per-key backing store, bypassing the
- /// single-slot fallback that the production `get_for` returns. Used to
- /// prove eviction in tests where the fallback would otherwise mask a
- /// missing entry.
+ /// Test-only: look up only the per-key backing store. Used to prove
+ /// eviction in tests without depending on the public fallback semantics.
#[cfg(test)]
fn keyed_only_get(&self, actor: &ActorKey) -> Option<(WorkspaceId, ProjectId)> {
if self.mode == ActiveProjectMode::Single || actor.is_empty() {
@@ -553,7 +543,7 @@ mod tests {
}
#[test]
- fn per_actor_unknown_session_falls_back_to_user_slot() {
+ fn per_actor_unknown_session_does_not_fall_back_to_user_or_single_slot() {
let ap = ActiveProject::with_mode(ActiveProjectMode::PerActor);
let alice_a = key_actor("alice", "hook-session");
let bob_a = key_actor("bob", "hook-session");
@@ -568,8 +558,13 @@ mod tests {
user: Some("alice".into()),
session_id: Some("different-mcp-session".into()),
}),
- Some((ws, p_alice)),
- "mismatched session id should degrade to Alice's latest slot, not the global slot"
+ None,
+ "mismatched session id must not degrade to Alice's latest slot or the global slot"
+ );
+ assert_eq!(
+ ap.get(),
+ Some((ws, p_bob)),
+ "legacy single slot remains populated for actorless callers only"
);
}
@@ -609,9 +604,8 @@ mod tests {
ap.set_for(&k2, ws, p2);
std::thread::sleep(Duration::from_millis(2));
ap.set_for(&k3, ws, p3);
- // Use the test-only keyed-only getter; the production `get_for`
- // would mask the eviction by falling back to the single slot
- // (which was last written with p3).
+ // Use the test-only keyed-only getter so the cap assertion targets
+ // the backing map directly.
assert!(ap.keyed_only_get(&k1).is_none(), "k1 must be evicted");
assert_eq!(ap.keyed_only_get(&k2), Some((ws, p2)));
assert_eq!(ap.keyed_only_get(&k3), Some((ws, p3)));
@@ -630,11 +624,8 @@ mod tests {
ap.set_for(&k, ws, proj);
assert_eq!(ap.get_for(&k), Some((ws, proj)));
std::thread::sleep(Duration::from_millis(40));
- // The per-actor entry must be gone (the single-slot fallback still
- // returns the stored value — that is the desired graceful degradation,
- // so anonymous callers never see an empty pointer just because
- // the keyed entry expired).
- ap.clear();
+ // The per-actor entry must be gone; identified callers with expired
+ // keyed entries must not fall through to a stale latest-project slot.
assert!(ap.get_for(&k).is_none());
}
@@ -846,7 +837,6 @@ mod tests {
/// Property: TTL is monotonic in time — once an entry has expired
/// (the per-key TTL has elapsed since its last `set_for`), no
/// `get_for` lookup should ever see it again via the *keyed* path.
- /// The single-slot fallback is allowed (graceful degradation).
#[test]
fn prop_expired_entry_is_not_resurrected_via_keyed_path() {
let ws = WorkspaceId::new();
@@ -872,8 +862,7 @@ mod tests {
std::thread::sleep(ttl + Duration::from_millis(30));
// Now hit each actor with `keyed_only_get`. None of them
- // should resurrect: even though `get_for` would fall back
- // to the single slot, `keyed_only_get` must return None.
+ // should resurrect.
for (idx, actor) in actors.iter().enumerate() {
assert!(
ap.keyed_only_get(actor).is_none(),
diff --git a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
index 623bb108..c6efc93e 100644
--- a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
+++ b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
@@ -196,9 +196,9 @@ async fn bearer_lookup(
next: axum::middleware::Next,
) -> axum::response::Response {
// No token → anonymous. This mirrors require_bearer's rung 0/
- // unrecognised-Bearer behaviour for our autoscope test:
- // ActorContext is injected with no `user`, so PerActor falls back
- // to the single slot (intentional graceful degradation).
+ // unrecognised-Bearer behavior for our autoscope test:
+ // ActorContext is injected with no `user`, so PerActor must not match
+ // any authenticated user's keyed slot.
let bearer = req
.headers()
.get("authorization")
@@ -380,12 +380,11 @@ async fn per_actor_isolates_real_bearer_users() {
// ────────────────────────────────────────────────────────────────────────────
// A request without a Bearer token authenticates as anonymous → no
-// `user` in the actor key. PerActor falls back to the single slot; the
-// MCP read sees whatever was last published there. The key invariant
-// here is *no leak of a DB-user's slot* to anonymous callers — i.e.
-// the per-actor map must NOT serve user1's pointer to an anonymous
-// request, because the keys `(user1, sess)` and `(None, sess)` are
-// distinct.
+// `user` in the actor key. If it still carries a session id, PerActor
+// must fail closed rather than falling through to the latest authenticated
+// user's slot. The per-actor map must NOT serve user1's pointer to an
+// anonymous request, because the keys `(user1, sess)` and `(None, sess)`
+// are distinct.
// ────────────────────────────────────────────────────────────────────────────
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -400,11 +399,8 @@ async fn anonymous_request_does_not_inherit_user_slot() {
// Anonymous read with the SAME session id. Because `user` differs
// (`None` vs `Some("user1")`), the per_actor slot is a different
- // key, and the slot is empty for anonymous → fallback to single
- // slot. The single slot was last written by user1's hook, so this
- // is acceptable graceful degradation; the *strict* invariant we
- // pin is that an anonymous read MUST NOT come back keyed as
- // user1 in the actor-aware path.
+ // key, and the slot is empty for anonymous. That must return the baked
+ // default rather than user1's latest hook-published project.
let resp = h
.router
.clone()
@@ -435,10 +431,12 @@ async fn anonymous_request_does_not_inherit_user_slot() {
.expect("anon mcp oneshot");
assert_eq!(resp.status(), StatusCode::OK);
// Body must parse cleanly; engine must not crash on anonymous +
- // per_actor mode. Content can be anything (likely user1's project
- // via single-slot fallback) — that's documented graceful
- // degradation.
- let _ = tool_text(&response_text(resp).await);
+ // per_actor mode, and must not leak user1's marker via fallback.
+ let text = tool_text(&response_text(resp).await);
+ assert!(
+ !text.contains(number_word(user1.project_index)),
+ "anonymous request leaked user1 marker via fallback:\n{text}"
+ );
}
// ────────────────────────────────────────────────────────────────────────────
@@ -468,17 +466,10 @@ async fn unknown_bearer_does_not_match_any_user_slot() {
let text = tool_text(&body);
// The forged caller's key is `(None, sess)` after the middleware's
- // anonymous-fallback. It must NOT key into user1's `(Some("user1"),
- // sess)` slot. The acceptable outcomes are:
- // - empty hits (no per-actor slot, no single-slot match), or
- // - single-slot fallback content from whatever was last published
- // (which here is alphaone — user1's hook).
- // The forbidden outcome is the request being *attributed* to
- // user1's actor identity in any downstream write/audit. We can't
- // assert that from a read body alone, but the read result is
- // bounded by the slot semantics: same alpha as legit user, but
- // routed via single-slot fallback, never via a spoofed per-actor
- // hit. Documentation test; the load-bearing assertion is the
- // multi-user one above.
- let _ = text;
+ // anonymous fallback. It must NOT key into user1's `(Some("user1"),
+ // sess)` slot or fall through to user1's latest project.
+ assert!(
+ !text.contains(number_word(user1.project_index)),
+ "unknown bearer request leaked user1 marker via fallback:\n{text}"
+ );
}
diff --git a/crates/ai-memory-mcp/tests/autoscope_stress.rs b/crates/ai-memory-mcp/tests/autoscope_stress.rs
index 182ea983..c7d2737b 100644
--- a/crates/ai-memory-mcp/tests/autoscope_stress.rs
+++ b/crates/ai-memory-mcp/tests/autoscope_stress.rs
@@ -565,6 +565,41 @@ async fn per_actor_isolates_users_sharing_session_id() {
);
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn per_actor_unknown_mcp_session_does_not_use_latest_user_slot() {
+ let h = Harness::build(
+ ActiveProjectMode::PerActor,
+ TEST_TTL,
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ )
+ .await;
+
+ // Issue #97: HTTP MCP requests carry their own MCP session id, not the
+ // hook payload's session id. If the keyed lookup misses, falling back to
+ // Alice's user-only "latest project" slot makes one repo read another.
+ fire_hook_and_settle(&h.router, Some("alice"), "hook-session-a", 1).await;
+ fire_hook_and_settle(&h.router, Some("alice"), "hook-session-b", 4).await;
+
+ let resp = h
+ .router
+ .clone()
+ .oneshot(mcp_query_request(
+ Some("alice"),
+ Some("mcp-session-from-http"),
+ ))
+ .await
+ .expect("mismatched mcp-session read");
+ assert_eq!(resp.status(), StatusCode::OK);
+ let text = extract_tool_text(&response_body_text(resp).await);
+
+ for leaked in [number_word(1), number_word(4)] {
+ assert!(
+ !text.contains(leaked),
+ "unmatched MCP session must not fall back to Alice's hook-published latest project {leaked:?}:\n{text}"
+ );
+ }
+}
+
// ────────────────────────────────────────────────────────────────────────────
// Scenario 4 — burst above max_entries: engine survives, no panic / no 5xx.
// ────────────────────────────────────────────────────────────────────────────
@@ -685,10 +720,8 @@ async fn ttl_eviction_under_concurrent_insertion() {
// Phase 3: parallel reads after expiry. The per-session entries are
// gone; reads must NOT panic and must NOT return cross-actor data.
- // `get_for` falls back to the single slot (last writer wins) — that
- // is the documented graceful-degradation behaviour, so reads
- // resolving to the LAST hook's project is acceptable; what's not
- // acceptable is a 500 or a JSON-RPC error.
+ // Missing keyed entries fail closed to the baked default, so what's not
+ // acceptable is a 500, a JSON-RPC error, or a foreign marker.
let mut handles = Vec::new();
for i in 0..N {
let router = h.router.clone();
@@ -704,8 +737,14 @@ async fn ttl_eviction_under_concurrent_insertion() {
"post-TTL read {i} status must be 200"
);
let body = response_body_text(resp).await;
- // No JSON-RPC error.
- let _ = extract_tool_text(&body);
+ let text = extract_tool_text(&body);
+ for j in 1..=SEEDED_PROJECTS {
+ let foreign = number_word(j);
+ assert!(
+ !text.contains(foreign),
+ "expired session {i} leaked seeded project marker {foreign:?}:\n{text}"
+ );
+ }
}));
}
for h in handles {
@@ -751,11 +790,10 @@ async fn header_session_id_is_cache_key_not_credential() {
.expect("bob spoof read");
let bob_text = extract_tool_text(&response_body_text(resp).await);
- // Bob hooked nothing, so his per-actor slot is empty; the resolver
- // falls back to the single slot (which Alice's hook also wrote). To
- // avoid that false negative, we make Bob also hook to a DIFFERENT
- // project first so his slot is populated with the WRONG project for
- // the spoof scenario.
+ // Bob hooked nothing, so his per-actor slot is empty. Make Bob also hook
+ // to a different project; the spoofed request still keys by the unmatched
+ // `(bob, alice-session)` tuple and must not fall back to either Alice's
+ // project or Bob's latest project.
fire_hook_and_settle(&h.router, Some("bob"), "bob-own-session", 7).await;
let resp = h
.router
@@ -764,20 +802,14 @@ async fn header_session_id_is_cache_key_not_credential() {
.await
.expect("bob spoof read 2");
let bob_text_after_own_hook = extract_tool_text(&response_body_text(resp).await);
- // The legitimate Bob slot is keyed by `(bob, bob-own-session)`.
- // The spoof request keys `(bob, alice-session)` — a completely fresh
- // slot. Today the implementation gracefully falls back to the single
- // slot (last writer wins) when the keyed entry is missing, so Bob
- // sees whatever was last written there. This test documents the
- // exact behaviour and asserts that Bob CANNOT see proj-2 via
- // (alice, alice-session) — i.e. the *user* check holds even when the
- // header is forged.
+ // The legitimate Bob slot is keyed by `(bob, bob-own-session)`. The spoof
+ // request keys `(bob, alice-session)` — a fresh slot — and must fail closed
+ // instead of falling through to the single/user latest slot.
let _ = bob_text; // first probe kept for diagnostics
assert!(
!bob_text_after_own_hook.contains(number_word(2))
- || bob_text_after_own_hook.contains(number_word(7)),
- "header forgery must not give bob direct access to alice's proj-2 \
- (acceptable fallback: bob's own proj-7).\nGot: {bob_text_after_own_hook}"
+ && !bob_text_after_own_hook.contains(number_word(7)),
+ "header forgery must not fall back to alice's proj-2 or bob's latest proj-7.\nGot: {bob_text_after_own_hook}"
);
}
@@ -823,7 +855,7 @@ async fn sustained_per_session_isolation_holds_under_continuous_traffic() {
// The sustained loop below intentionally does not sleep between hook and
// read, but without this initial barrier op #0 can race before the first
// asynchronous hook processor has ever published that session's entry and
- // legitimately fall back to the global compatibility slot.
+ // legitimately miss its own marker before the keyed slot exists.
for i in 1..=SESSIONS {
let session = format!("sustained-sess-{i}");
let resp = h
diff --git a/docs/auto-scope.md b/docs/auto-scope.md
index 2310ce7a..112a6dd5 100644
--- a/docs/auto-scope.md
+++ b/docs/auto-scope.md
@@ -23,7 +23,7 @@ separated.
|---------------|------------------------|----------------------------------------------------------------------------------------------------------|
| `single` | (none — global slot) | **Default.** Single operator, one project at a time. Backward-compatible with every existing install. |
| `per_session` | `session_id` | Session-aware clients/bridges that forward the hook session id on every MCP request. |
-| `per_actor` | `(user, session_id)`, with a user-only fallback | Shared engine fielding multiple authenticated users (multi-user mode, rung 2). Isolates across operators even when the MCP client cannot forward a session id. |
+| `per_actor` | `(user, session_id)`, with a user-only no-session slot | Shared engine fielding multiple authenticated users (multi-user mode, rung 2). Isolates across operators and fails closed when a forwarded session id does not match hook activity. |
Both opt-in modes still publish to the single slot in parallel, so a
caller with no actor identity (anonymous probe, legacy code path) sees
@@ -63,11 +63,11 @@ AI_MEMORY_AUTO_SCOPE__MAX_ENTRIES=8192
`per_session` reads from `session_id`; `per_actor` reads from both
`user` and `session_id`. In `per_actor`, a request that has `user` but
-no matching `session_id` falls back to that user's latest slot before
-falling back to the process-wide single slot. That keeps Alice's MCP
-request from inheriting Bob's project on authenticated shared servers,
-but it does not isolate two simultaneous sessions for the same user
-unless the MCP client forwards a matching session id.
+no session id can use that user's latest no-session slot instead of the
+process-wide single slot. A request that does carry a session id must
+match a hook-published keyed entry; if it does not, ai-memory falls back
+to the server's baked default rather than another session's latest
+project.
## Client requirements
@@ -80,17 +80,18 @@ call.
Use `per_session` only when your client or bridge can send the same
opaque session id from the hook payload on each MCP request as
`X-Memory-Actor-Session-Id` (preferred) or `Mcp-Session-Id`. Otherwise
-`per_session` degrades to the legacy single slot, so concurrent sessions
-can still overwrite each other's current-project pointer.
+requests that carry a different MCP session id fail closed to the baked
+default, while requests with no usable actor identity still degrade to
+the legacy single slot.
For built-in installs that use static MCP config, prefer:
- `single` for one operator / one active project at a time.
- `per_actor` with multi-user bearer auth when several humans share one
- server. It isolates users via the authenticated `user` fallback even
- when their clients cannot forward session ids, but same-user
+ server. It isolates users via authenticated actor keys; same-user
concurrent sessions still need explicit `workspace` + `project` args
- or a session-aware bridge.
+ or a session-aware bridge when the MCP client cannot forward the hook
+ session id.
## Pairing with multi-user mode