Skip to content

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

Rust

fix(auto-scope): document and guard session fallback

AkitaOnRails0257331df446
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fae96ffd..91ea8730 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,8 +14,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
pointer by `session_id` to isolate concurrent agent runs of the same
operator; opt-in `per_actor` keys by `(user, session_id)` to isolate
across operators as well, pairing with multi-user mode where `user`
- comes from the `users` row that owns the bearer token. Per-key entries
- carry an insertion timestamp and are TTL-evicted (default 1 hour) and
+ comes from the `users` row that owns the bearer token. `per_actor`
+ also keeps a user-only fallback slot so authenticated MCP requests
+ from clients that cannot forward a session id do not inherit another
+ user's latest project; same-user session isolation still requires a
+ client/bridge that sends `X-Memory-Actor-Session-Id` or
+ `Mcp-Session-Id` on MCP tool calls. Per-key entries carry an insertion
+ timestamp and are TTL-evicted (default 1 hour) and
capped (default 4096) so adversarial / runaway clients cannot grow the
map without bound. Both opt-in modes still publish to the single slot
in parallel, so any caller without actor context falls back gracefully
diff --git a/README.md b/README.md
index 352a6e95..d5132b5f 100644
--- a/README.md
+++ b/README.md
@@ -81,7 +81,9 @@ priors are at the [bottom](#influences-and-prior-art).
Gemini CLI, Antigravity CLI, OpenClaw, and Oh My Pi / OMP
(`pi` / `omp` aliases).
Server runs local (loopback) OR on a homelab box (LAN/VPN/cloud)
- with bearer-token auth.
+ with bearer-token auth. Shared servers can opt into
+ [`[auto_scope]` modes](docs/auto-scope.md) for per-user or
+ session-aware current-project routing.
- **Thin-client CLI.** `ai-memory status`, `bootstrap`, `purge-project`,
`rename-project`, `move-project`, `lint`, `embed`, `forget-sweep`, `backup` are
all HTTP clients of the running server - never touch SQLite or
@@ -492,6 +494,7 @@ diagram, crate breakdown, schema notes, and invariants.
| [`docs/install.md`](docs/install.md) | **Installation cookbook.** Every agent CLI, every alternative (curl, source build, no-docker, no-auth), and the server-on-a-different-machine (homelab/LAN) walkthrough. Read after the Quick start if your setup doesn't match the happy path. |
| [`docs/usage.md`](docs/usage.md) | Handoffs, proactive memory queries, routing snippet, web UI, raw-wiki inspection, and rules-vs-facts workflow. |
| [`docs/marker-file.md`](docs/marker-file.md) | `.ai-memory.toml` workspace/project routing for multi-client trees, mono-repos, worktrees, and work/personal separation. |
+| [`docs/auto-scope.md`](docs/auto-scope.md) | `[auto_scope]` modes for shared servers: default single-slot routing, session-aware isolation, and multi-user `per_actor` behavior. |
| [`docs/windows.md`](docs/windows.md) | Windows install modes: full WSL2, native Windows with Docker Desktop, native source builds, and current hook/MCP harness caveats. |
| [`docs/mcp-install.md`](docs/mcp-install.md) | Per-client MCP and lifecycle notes (Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, OpenClaw, OMP). |
| [`docs/deploy.md`](docs/deploy.md) | Homelab deploy: bin/deploy, bearer-token auth, pointers to the TLS guide. |
diff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rs
index 27ed0c35..01a37efc 100644
--- a/crates/ai-memory-core/src/active_project.rs
+++ b/crates/ai-memory-core/src/active_project.rs
@@ -28,17 +28,22 @@
//! - `PerSession` keys by `session_id` — isolates concurrent agent runs of
//! the same operator (one person with several Claude Code / Codex windows
//! in different repos at once).
-//! - `PerActor` keys by `(user, session_id)` — isolates across operators as
-//! well as across sessions, for corporate installs with multiple authed
-//! users sharing one engine. Pairs with multi-user mode (rung 2): `user`
-//! comes from the `users` row that owns the bearer token.
+//! - `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.
//!
//! 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 — never a silent error, never a wrong-actor
-//! lookup. 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.
+//! 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
+//! historical `set` / `get` / `clear` API touches, so existing callers compile
+//! unchanged and admin ops like `move-project` still invalidate the pointer
+//! correctly.
//!
//! ## Memory bound
//!
@@ -242,6 +247,11 @@ 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.
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() {
@@ -252,6 +262,20 @@ impl ActiveProject {
return;
}
let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());
+ if self.mode == ActiveProjectMode::PerActor
+ && actor.user.is_some()
+ && actor.session_id.is_some()
+ {
+ guard.insert(
+ ActorKey {
+ user: actor.user.clone(),
+ session_id: None,
+ },
+ workspace_id,
+ project_id,
+ Instant::now(),
+ );
+ }
guard.insert(scoped, workspace_id, project_id, Instant::now());
}
@@ -269,6 +293,18 @@ impl ActiveProject {
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);
+ }
+ }
}
}
self.read_single()
@@ -495,6 +531,48 @@ mod tests {
assert_eq!(ap.get_for(&bob_a), Some((ws, p3)));
}
+ #[test]
+ fn per_actor_user_only_lookup_stays_with_that_user() {
+ let ap = ActiveProject::with_mode(ActiveProjectMode::PerActor);
+ let alice_a = key_actor("alice", "sA");
+ let bob_a = key_actor("bob", "sA");
+ let ws = WorkspaceId::new();
+ let p_alice = ProjectId::new();
+ let p_bob = ProjectId::new();
+ ap.set_for(&alice_a, ws, p_alice);
+ ap.set_for(&bob_a, ws, p_bob);
+
+ assert_eq!(
+ ap.get_for(&ActorKey {
+ user: Some("alice".into()),
+ session_id: None,
+ }),
+ Some((ws, p_alice)),
+ "missing session id must not fall through to Bob's global slot"
+ );
+ }
+
+ #[test]
+ fn per_actor_unknown_session_falls_back_to_user_slot() {
+ let ap = ActiveProject::with_mode(ActiveProjectMode::PerActor);
+ let alice_a = key_actor("alice", "hook-session");
+ let bob_a = key_actor("bob", "hook-session");
+ let ws = WorkspaceId::new();
+ let p_alice = ProjectId::new();
+ let p_bob = ProjectId::new();
+ ap.set_for(&alice_a, ws, p_alice);
+ ap.set_for(&bob_a, ws, p_bob);
+
+ assert_eq!(
+ ap.get_for(&ActorKey {
+ 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"
+ );
+ }
+
#[test]
fn per_actor_falls_back_to_single_when_actor_is_empty() {
let ap = ActiveProject::with_mode(ActiveProjectMode::PerActor);
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index e7ffc5f7..ebbbe361 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -546,10 +546,11 @@ impl AiMemoryServer {
/// security-critical.
/// - `session_id` comes from the same `ActorContext` when the auth
/// middleware filled it; if not, falls back to the rung-4
- /// `X-Memory-Actor-Session-Id` request header. The session id is
- /// just a cache key for the active-project map — getting it wrong
- /// only routes the lookup to a different (or absent) slot, with no
- /// auth-bypass risk, so trusting the header here is safe.
+ /// `X-Memory-Actor-Session-Id` request header, then to the standard
+ /// MCP `Mcp-Session-Id` header. The session id is just a cache key
+ /// for the active-project map — getting it wrong only routes the
+ /// lookup to a different (or absent) slot, with no auth-bypass risk,
+ /// so trusting the header here is safe.
///
/// Returns the empty [`ActorKey`] when neither source has anything to
/// offer; that's the graceful-degradation signal for callers to fall
@@ -562,15 +563,19 @@ impl AiMemoryServer {
};
let ctx = parts.extensions.get::<ai_memory_core::ActorContext>();
let user = ctx.and_then(|c| c.user.clone());
- let session_id = ctx.and_then(|c| c.session_id.clone()).or_else(|| {
+ let header_session = |name: &str| {
parts
.headers
- .get("x-memory-actor-session-id")
+ .get(name)
.and_then(|v| v.to_str().ok())
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
- });
+ };
+ let session_id = ctx
+ .and_then(|c| c.session_id.clone())
+ .or_else(|| header_session("x-memory-actor-session-id"))
+ .or_else(|| header_session("mcp-session-id"));
ai_memory_core::ActorKey { user, session_id }
}
@@ -1922,6 +1927,57 @@ mod tests {
(tmp, store, server, ws, proj)
}
+ #[test]
+ fn actor_key_uses_memory_session_header() {
+ let mut parts = test_parts_default();
+ parts.headers.insert(
+ "x-memory-actor-session-id",
+ axum::http::HeaderValue::from_static("hook-session"),
+ );
+
+ let actor = AiMemoryServer::actor_key_from_parts(Some(&parts));
+
+ assert_eq!(actor.user, None);
+ assert_eq!(actor.session_id.as_deref(), Some("hook-session"));
+ }
+
+ #[test]
+ fn actor_key_accepts_standard_mcp_session_header() {
+ let mut parts = test_parts_default();
+ parts.headers.insert(
+ "mcp-session-id",
+ axum::http::HeaderValue::from_static("mcp-session"),
+ );
+
+ let actor = AiMemoryServer::actor_key_from_parts(Some(&parts));
+
+ assert_eq!(actor.user, None);
+ assert_eq!(actor.session_id.as_deref(), Some("mcp-session"));
+ }
+
+ #[test]
+ fn actor_key_prefers_middleware_context_over_headers() {
+ let mut parts = test_parts_default();
+ parts.headers.insert(
+ "x-memory-actor-session-id",
+ axum::http::HeaderValue::from_static("header-session"),
+ );
+ parts.headers.insert(
+ "mcp-session-id",
+ axum::http::HeaderValue::from_static("mcp-session"),
+ );
+ parts.extensions.insert(ai_memory_core::ActorContext {
+ user: Some("alice".into()),
+ session_id: Some("context-session".into()),
+ ..ai_memory_core::ActorContext::default()
+ });
+
+ let actor = AiMemoryServer::actor_key_from_parts(Some(&parts));
+
+ assert_eq!(actor.user.as_deref(), Some("alice"));
+ assert_eq!(actor.session_id.as_deref(), Some("context-session"));
+ }
+
#[tokio::test]
async fn server_constructs_with_tool_router() {
let (_tmp, _store, _server, _ws, _pj) = setup_server().await;
diff --git a/docs/auto-scope.md b/docs/auto-scope.md
index 68b652f9..2310ce7a 100644
--- a/docs/auto-scope.md
+++ b/docs/auto-scope.md
@@ -22,13 +22,15 @@ separated.
| `mode` | Key | When to use |
|---------------|------------------------|----------------------------------------------------------------------------------------------------------|
| `single` | (none — global slot) | **Default.** Single operator, one project at a time. Backward-compatible with every existing install. |
-| `per_session` | `session_id` | Single operator running concurrent agent runs in different repos (e.g. several Claude Code / Codex windows open). |
-| `per_actor` | `(user, session_id)` | Shared engine fielding multiple authenticated users (multi-user mode, rung 2). Isolates across operators too. |
+| `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. |
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
-the most recent project rather than an empty pointer — graceful
-degradation, never a silent error.
+the most recent project rather than an empty pointer. That preserves
+legacy behavior, but it is not per-session isolation; use explicit
+`workspace` + `project` arguments when a client cannot send actor
+identity and concurrent runs matter.
## Configuration
@@ -55,11 +57,40 @@ AI_MEMORY_AUTO_SCOPE__MAX_ENTRIES=8192
| Hook payload (`/hook?event=…&agent=…`) | `session_id`, `agent` |
| Auth middleware (rung 1 root with `root_username`) | `user` ← root_username |
| Auth middleware (rung 2 DB user) | `user` ← `users.username` |
+| MCP request header `X-Memory-Actor-Session-Id` | `session_id` for tool calls |
+| MCP request header `Mcp-Session-Id` | fallback `session_id` for tool calls |
| Anonymous / no token | empty actor → single slot |
`per_session` reads from `session_id`; `per_actor` reads from both
-`user` and `session_id`. When either is missing, the lookup falls back
-through the chain ending at the single slot.
+`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.
+
+## Client requirements
+
+Lifecycle hooks already include the agent-run session id in their
+payloads. MCP tool calls are separate HTTP requests, and most built-in
+MCP client config files can only declare static URL/auth headers. Static
+configs cannot inject the current agent-run session id into every tool
+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.
+
+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
+ concurrent sessions still need explicit `workspace` + `project` args
+ or a session-aware bridge.
## Pairing with multi-user mode
@@ -68,11 +99,14 @@ through the chain ending at the single slot.
`users.token_hash` row, so the auth middleware tags every request with
the right `user`. With `[auto_scope] mode = "per_actor"`, two
authenticated users running concurrent agent sessions through the same
-engine no longer overwrite each other's "current project" pointer.
+engine no longer overwrite each other's "current project" pointer for
+MCP calls; if their clients also forward session ids, concurrent
+sessions by the same user are isolated too.
Single-user installs can use `per_session` alone (no `token_pepper`,
-no `users` row) when one operator wants to run multiple agent windows
-in parallel.
+no `users` row) only when the client/bridge forwards the session id on
+MCP calls. With the stock static MCP configs, use explicit
+`workspace` + `project` arguments for concurrent windows.
## Memory footprint