Skip to content

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

Rust

feat(auto-scope): per-session and per-actor ActiveProject isolation modes

Djalma Júnior060182ca38aa
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 18446533..117714f8 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -126,7 +126,21 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
// answers for the project the agent is actually in, not the static
// `--project` (issue #2). In stdio mode no hook router is built, so
// this stays empty and the baked-in default is used.
- let active_project = ActiveProject::new();
+ // Construct ActiveProject with the configured `[auto_scope]` mode +
+ // TTL/cap. `single` (default) preserves the legacy behaviour; the
+ // opt-in modes (`per_session`, `per_actor`) keyed-isolate concurrent
+ // sessions / operators on shared installs.
+ let active_project = ActiveProject::with_config(
+ config.auto_scope.mode,
+ std::time::Duration::from_secs(config.auto_scope.session_ttl_secs),
+ config.auto_scope.max_entries,
+ );
+ tracing::info!(
+ mode = ?config.auto_scope.mode,
+ session_ttl_secs = config.auto_scope.session_ttl_secs,
+ max_entries = config.auto_scope.max_entries,
+ "active-project isolation mode"
+ );
let mut server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
.with_wiki(wiki.clone())
.with_decay_params(config.decay)
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 8e2cf616..4c3f7dc4 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -101,6 +101,12 @@ pub struct Config {
/// `AI_MEMORY_AUTH_TOKEN` env var or `[auth].bearer_token` in
/// config.toml.
pub auth: AuthSettings,
+ /// `[auto_scope]` — opt-in isolation of the hook-published "current
+ /// project" pointer used by MCP tools that omit `workspace`/`project`.
+ /// Default `single` mode preserves the legacy global slot; `per_session`
+ /// and `per_actor` are for shared installs. See [`AutoScopeSettings`]
+ /// and [`ai_memory_core::ActiveProjectMode`].
+ pub auto_scope: AutoScopeSettings,
/// `Host`-header allowlist for the HTTP server. Requests whose
/// `Host` header doesn't match this list are rejected before they
/// reach MCP, hook, admin, or web routes (DNS-rebinding defence).
@@ -274,6 +280,39 @@ pub struct AuthSettings {
pub token_pepper: Option<String>,
}
+/// `[auto_scope]` — controls how the hook-published "currently active
+/// project" pointer is shared across concurrent callers. The legacy default
+/// is `single` (process-wide slot, last-write-wins). Opt-in modes isolate
+/// concurrent agent runs and/or operators.
+///
+/// Set under `[auto_scope]` in `config.toml` or via the
+/// `AI_MEMORY_AUTO_SCOPE__MODE`, `AI_MEMORY_AUTO_SCOPE__SESSION_TTL_SECS`,
+/// and `AI_MEMORY_AUTO_SCOPE__MAX_ENTRIES` env vars.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(default)]
+pub struct AutoScopeSettings {
+ /// `single` (default), `per_session`, or `per_actor`. See
+ /// [`ai_memory_core::ActiveProjectMode`] for full semantics.
+ pub mode: ai_memory_core::ActiveProjectMode,
+ /// TTL (seconds) for per-key entries in `per_session`/`per_actor`
+ /// modes. Default is 1 hour. Set to 0 to fall back to the default.
+ pub session_ttl_secs: u64,
+ /// Hard upper bound on the per-key map size, evicting the oldest
+ /// insertions first. Default 4096; lower for very small installs,
+ /// raise for shared engines with many concurrent agents.
+ pub max_entries: usize,
+}
+
+impl Default for AutoScopeSettings {
+ fn default() -> Self {
+ Self {
+ mode: ai_memory_core::ActiveProjectMode::default(),
+ session_ttl_secs: ai_memory_core::DEFAULT_PER_KEY_TTL.as_secs(),
+ max_entries: ai_memory_core::DEFAULT_MAX_ENTRIES,
+ }
+ }
+}
+
impl Default for Config {
fn default() -> Self {
Self {
@@ -294,6 +333,7 @@ impl Default for Config {
maintenance: MaintenanceSettings::default(),
sanitize: ai_memory_core::SanitizeConfig::default(),
auth: AuthSettings::default(),
+ auto_scope: AutoScopeSettings::default(),
allowed_hosts: vec!["localhost".into(), "127.0.0.1".into(), "::1".into()],
cors_allow_origins: Vec::new(),
admission_webhooks: Vec::new(),
diff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rs
index 4bd24906..a1a5f6f2 100644
--- a/crates/ai-memory-core/src/active_project.rs
+++ b/crates/ai-memory-core/src/active_project.rs
@@ -15,60 +15,323 @@
//! defaults to `scratch` and made the read tools return empty memory even
//! when the hooks were correctly populating a real project).
//!
-//! The pointer reflects the most recently resolved cwd-based project. For the
-//! common single-user, one-project-at-a-time workflow this is exactly right.
-//! For the rarer case of one shared server fielding several projects
-//! concurrently, the MCP tools also accept an explicit `project` argument that
-//! takes precedence over this pointer.
+//! ## Isolation modes
//!
-//! The lock is held only for the microseconds it takes to copy a small tuple;
-//! callers never `.await` while holding it, so a plain `std::sync::RwLock` is
-//! the right primitive (no async lock needed).
+//! The default `Single` mode keeps the historical behaviour — one process-
+//! wide slot, last-write-wins. That is right for a single operator running
+//! one project at a time, but collapses parallel sessions on shared installs:
+//! a hook firing from `~/repo-A` overwrites the slot a concurrent
+//! `memory_query` (with no explicit project) in `~/repo-B` was about to read.
+//!
+//! Opt-in modes keep a per-key map alongside the single slot:
+//!
+//! - `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.
+//!
+//! 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.
+//!
+//! ## Memory bound
+//!
+//! Per-key entries carry an [`Instant`] insertion timestamp and are evicted
+//! on read or write once they exceed the configured TTL (default 1 hour).
+//! A hard `max_entries` cap (default 4096) drops the oldest entries when
+//! exceeded, so an adversarial / runaway client cannot grow the map without
+//! bound. Both knobs are exposed via the CLI's `[auto_scope]` config block.
+//!
+//! ## Locking
+//!
+//! Locks are held only for the microseconds it takes to copy a small tuple
+//! or do a single hash lookup; callers never `.await` while holding them, so
+//! plain `std::sync::RwLock` is the right primitive (no async lock needed).
+use std::collections::HashMap;
use std::sync::{Arc, RwLock};
+use std::time::{Duration, Instant};
+
+use serde::{Deserialize, Serialize};
use crate::ids::{ProjectId, WorkspaceId};
-/// Cheap, cloneable handle to the shared "currently active project" slot.
+/// Default TTL for per-key entries in the opt-in isolation modes.
+pub const DEFAULT_PER_KEY_TTL: Duration = Duration::from_secs(60 * 60);
+/// Default upper bound on per-key entries, to keep memory finite on shared
+/// installs where many short-lived sessions may come and go.
+pub const DEFAULT_MAX_ENTRIES: usize = 4096;
+
+/// Selects how the hook router and the MCP tools share the "currently active
+/// project" pointer. `Single` is the legacy behaviour and remains the default
+/// — the other modes are opt-in via the CLI's `[auto_scope]` config block.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ActiveProjectMode {
+ /// Process-wide slot, last-write-wins. Backward-compatible default.
+ #[default]
+ Single,
+ /// Keyed by `session_id`. Isolates concurrent agent runs of the same
+ /// operator from each other.
+ PerSession,
+ /// Keyed by `(user, session_id)`. Isolates across operators as well,
+ /// for installs with multi-user mode enabled.
+ PerActor,
+}
+
+/// Composite identity used to key per-actor entries.
///
-/// Clones share the same underlying slot. Starts empty; the hook router
+/// - `PerSession` mode populates only `session_id`.
+/// - `PerActor` mode populates both (`user` is the username row from
+/// `users`, or the configured `root_username` for rung 1 callers).
+///
+/// An [`ActorKey`] with both fields `None` is treated the same as "no actor"
+/// — the request falls back to the single slot. That keeps anonymous /
+/// pre-identity callers working without a special branch at every call site.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
+pub struct ActorKey {
+ /// Stable username when the request was authenticated as a known user
+ /// (rung 1 root with `root_username`, or rung 2 DB user). `None` for
+ /// anonymous calls.
+ pub user: Option<String>,
+ /// Per-agent-run session identifier published by the lifecycle hooks
+ /// (Claude Code, Codex, OpenCode, …). `None` when the call site has no
+ /// session context (e.g. an ad-hoc MCP probe with no hook history).
+ pub session_id: Option<String>,
+}
+
+impl ActorKey {
+ /// `true` when neither identity coordinate is present — used to short-
+ /// circuit the per-key map and fall back to the single slot.
+ #[must_use]
+ pub fn is_empty(&self) -> bool {
+ self.user.is_none() && self.session_id.is_none()
+ }
+}
+
+#[derive(Debug)]
+struct PerActorMap {
+ entries: HashMap<ActorKey, (WorkspaceId, ProjectId, Instant)>,
+ ttl: Duration,
+ max_entries: usize,
+}
+
+impl PerActorMap {
+ fn new(ttl: Duration, max_entries: usize) -> Self {
+ Self {
+ entries: HashMap::new(),
+ ttl: if ttl.is_zero() {
+ DEFAULT_PER_KEY_TTL
+ } else {
+ ttl
+ },
+ max_entries: max_entries.max(1),
+ }
+ }
+
+ /// Drop expired entries. Run on every read + write so a stale key never
+ /// surfaces to a tool handler and the cap below sees an accurate size.
+ fn purge_expired(&mut self, now: Instant) {
+ self.entries
+ .retain(|_, (_, _, inserted)| now.saturating_duration_since(*inserted) < self.ttl);
+ }
+
+ /// Cap the map at `max_entries`, dropping the oldest insertions first.
+ /// O(n log n) when over the cap; called only at insertion time, so the
+ /// amortised cost is well below the hash insertion itself.
+ fn enforce_cap(&mut self) {
+ if self.entries.len() <= self.max_entries {
+ return;
+ }
+ let excess = self.entries.len() - self.max_entries;
+ let mut by_age: Vec<(ActorKey, Instant)> =
+ self.entries.iter().map(|(k, v)| (k.clone(), v.2)).collect();
+ by_age.sort_by_key(|(_, inserted)| *inserted);
+ for (k, _) in by_age.into_iter().take(excess) {
+ self.entries.remove(&k);
+ }
+ }
+
+ fn insert(&mut self, key: ActorKey, ws: WorkspaceId, proj: ProjectId, now: Instant) {
+ self.purge_expired(now);
+ self.entries.insert(key, (ws, proj, now));
+ self.enforce_cap();
+ }
+
+ fn get(&mut self, key: &ActorKey, now: Instant) -> Option<(WorkspaceId, ProjectId)> {
+ self.purge_expired(now);
+ self.entries.get(key).map(|(ws, proj, _)| (*ws, *proj))
+ }
+}
+
+/// Cheap, cloneable handle to the shared "currently active project" pointer.
+///
+/// Clones share the same underlying state. Starts empty; the hook router
/// fills it as events arrive.
-#[derive(Clone, Default)]
+#[derive(Clone)]
pub struct ActiveProject {
- inner: Arc<RwLock<Option<(WorkspaceId, ProjectId)>>>,
+ mode: ActiveProjectMode,
+ single: Arc<RwLock<Option<(WorkspaceId, ProjectId)>>>,
+ per_actor: Arc<RwLock<PerActorMap>>,
+}
+
+impl Default for ActiveProject {
+ fn default() -> Self {
+ Self::with_config(
+ ActiveProjectMode::Single,
+ DEFAULT_PER_KEY_TTL,
+ DEFAULT_MAX_ENTRIES,
+ )
+ }
}
impl ActiveProject {
- /// Create an empty pointer (no project resolved yet).
+ /// Create an empty `Single`-mode pointer — the legacy default.
#[must_use]
pub fn new() -> Self {
Self::default()
}
+ /// Create an empty pointer in the given mode, using the default TTL +
+ /// cap for the per-key backing map.
+ #[must_use]
+ pub fn with_mode(mode: ActiveProjectMode) -> Self {
+ Self::with_config(mode, DEFAULT_PER_KEY_TTL, DEFAULT_MAX_ENTRIES)
+ }
+
+ /// Full-fidelity constructor used by the CLI's `serve` wiring and by
+ /// unit tests that need to exercise eviction.
+ #[must_use]
+ pub fn with_config(mode: ActiveProjectMode, ttl: Duration, max_entries: usize) -> Self {
+ Self {
+ mode,
+ single: Arc::new(RwLock::new(None)),
+ per_actor: Arc::new(RwLock::new(PerActorMap::new(ttl, max_entries))),
+ }
+ }
+
+ /// The mode this handle was built with. Mostly useful for tests and for
+ /// observability (the `serve` startup log records it once).
+ #[must_use]
+ pub fn mode(&self) -> ActiveProjectMode {
+ self.mode
+ }
+
/// Publish the project the agent is currently active in. Called by the
/// hook router after it resolves an event's `cwd` to a real project.
+ ///
+ /// The actor's identity steers which slot is updated:
+ /// - In `Single` mode (the default), the process-wide slot is overwritten.
+ /// - In `PerSession` / `PerActor`, the entry keyed by the actor is set
+ /// *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.
+ 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() {
+ return;
+ }
+ let scoped = self.scoped_key(actor);
+ if scoped.is_empty() {
+ return;
+ }
+ let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());
+ guard.insert(scoped, workspace_id, project_id, Instant::now());
+ }
+
+ /// Read the currently active project for the given actor, if any has
+ /// been published yet. Falls back to the single slot when:
+ /// - the mode is `Single`, or
+ /// - the actor is empty (no identity coordinates), or
+ /// - no per-actor entry matches (graceful degradation).
+ #[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);
+ }
+ }
+ }
+ self.read_single()
+ }
+
+ /// Project the actor's identity onto only the coordinates the current
+ /// mode uses: `PerSession` keeps `session_id`, `PerActor` keeps both.
+ fn scoped_key(&self, actor: &ActorKey) -> ActorKey {
+ match self.mode {
+ ActiveProjectMode::Single => ActorKey {
+ user: None,
+ session_id: None,
+ },
+ ActiveProjectMode::PerSession => ActorKey {
+ user: None,
+ session_id: actor.session_id.clone(),
+ },
+ ActiveProjectMode::PerActor => actor.clone(),
+ }
+ }
+
+ fn write_single(&self, ws: WorkspaceId, proj: ProjectId) {
+ let mut guard = self.single.write().unwrap_or_else(|e| e.into_inner());
+ *guard = Some((ws, proj));
+ }
+
+ fn read_single(&self) -> Option<(WorkspaceId, ProjectId)> {
+ let guard = self.single.read().unwrap_or_else(|e| e.into_inner());
+ *guard
+ }
+
+ /// Legacy single-slot setter — used by tests and by call sites that
+ /// have no actor context yet. Touches the single slot only; the per-key
+ /// map is untouched.
pub fn set(&self, workspace_id: WorkspaceId, project_id: ProjectId) {
- // A poisoned lock means a writer panicked mid-update. The slot holds
- // only a Copy tuple, so there's no torn state to recover — recover the
- // guard and overwrite rather than propagating the panic into a hook
- // handler that must stay fire-and-forget.
- let mut guard = self.inner.write().unwrap_or_else(|e| e.into_inner());
- *guard = Some((workspace_id, project_id));
+ self.write_single(workspace_id, project_id);
}
- /// Read the currently active project, if any has been published yet.
+ /// Legacy single-slot getter — same contract as [`Self::set`].
#[must_use]
pub fn get(&self) -> Option<(WorkspaceId, ProjectId)> {
- let guard = self.inner.read().unwrap_or_else(|e| e.into_inner());
- *guard
+ self.read_single()
}
/// Forget the active project. Called after an admin operation invalidates
- /// the published pointer (e.g. a `move-project` whose copy-purge path gives
- /// the project a NEW id, so the old pointer no longer resolves).
+ /// the published pointer (e.g. a `move-project` whose copy-purge path
+ /// gives the project a NEW id, so the old pointer no longer resolves).
+ /// Clears both the single slot AND the per-key map, since the project
+ /// id is gone for every caller.
pub fn clear(&self) {
- let mut guard = self.inner.write().unwrap_or_else(|e| e.into_inner());
- *guard = None;
+ {
+ let mut guard = self.single.write().unwrap_or_else(|e| e.into_inner());
+ *guard = None;
+ }
+ let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());
+ 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.
+ #[cfg(test)]
+ fn keyed_only_get(&self, actor: &ActorKey) -> Option<(WorkspaceId, ProjectId)> {
+ if self.mode == ActiveProjectMode::Single || actor.is_empty() {
+ return None;
+ }
+ let scoped = self.scoped_key(actor);
+ if scoped.is_empty() {
+ return None;
+ }
+ let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());
+ guard.get(&scoped, Instant::now())
}
}
@@ -76,13 +339,34 @@ impl ActiveProject {
mod tests {
use super::*;
+ fn key_session(s: &str) -> ActorKey {
+ ActorKey {
+ user: None,
+ session_id: Some(s.to_string()),
+ }
+ }
+
+ fn key_actor(user: &str, session: &str) -> ActorKey {
+ ActorKey {
+ user: Some(user.to_string()),
+ session_id: Some(session.to_string()),
+ }
+ }
+
+ fn empty_actor() -> ActorKey {
+ ActorKey {
+ user: None,
+ session_id: None,
+ }
+ }
+
#[test]
fn starts_empty() {
assert!(ActiveProject::new().get().is_none());
}
#[test]
- fn set_then_get_round_trips() {
+ fn set_then_get_round_trips_legacy_api() {
let ap = ActiveProject::new();
let ws = WorkspaceId::new();
let proj = ProjectId::new();
@@ -91,7 +375,7 @@ mod tests {
}
#[test]
- fn set_overwrites_previous() {
+ fn set_overwrites_previous_legacy_api() {
let ap = ActiveProject::new();
ap.set(WorkspaceId::new(), ProjectId::new());
let ws2 = WorkspaceId::new();
@@ -109,4 +393,147 @@ mod tests {
a.set(ws, proj);
assert_eq!(b.get(), Some((ws, proj)), "clone must see the same slot");
}
+
+ #[test]
+ fn clear_drops_single_and_per_actor() {
+ let ap = ActiveProject::with_mode(ActiveProjectMode::PerActor);
+ let alice = key_actor("alice", "sA");
+ let ws = WorkspaceId::new();
+ let proj = ProjectId::new();
+ ap.set_for(&alice, ws, proj);
+ assert_eq!(ap.get_for(&alice), Some((ws, proj)));
+
+ ap.clear();
+ assert!(ap.get_for(&alice).is_none(), "per-actor entry must be gone");
+ assert!(ap.get().is_none(), "single slot must be gone");
+ }
+
+ #[test]
+ fn single_mode_ignores_actor_coordinates() {
+ let ap = ActiveProject::new();
+ let alice = key_actor("alice", "sA");
+ let bob = key_actor("bob", "sB");
+ let ws = WorkspaceId::new();
+ let p_alice = ProjectId::new();
+ let p_bob = ProjectId::new();
+ ap.set_for(&alice, ws, p_alice);
+ ap.set_for(&bob, ws, p_bob);
+ // Both reads see the last write; that's the legacy contract.
+ assert_eq!(ap.get_for(&alice), Some((ws, p_bob)));
+ assert_eq!(ap.get_for(&bob), Some((ws, p_bob)));
+ assert_eq!(ap.get(), Some((ws, p_bob)));
+ }
+
+ #[test]
+ fn per_session_isolates_by_session_id() {
+ let ap = ActiveProject::with_mode(ActiveProjectMode::PerSession);
+ let sess_a = key_session("sA");
+ let sess_b = key_session("sB");
+ let ws = WorkspaceId::new();
+ let p_a = ProjectId::new();
+ let p_b = ProjectId::new();
+ ap.set_for(&sess_a, ws, p_a);
+ ap.set_for(&sess_b, ws, p_b);
+ assert_eq!(ap.get_for(&sess_a), Some((ws, p_a)));
+ assert_eq!(ap.get_for(&sess_b), Some((ws, p_b)));
+ }
+
+ #[test]
+ fn per_session_ignores_user_field() {
+ let ap = ActiveProject::with_mode(ActiveProjectMode::PerSession);
+ let ws = WorkspaceId::new();
+ let p = ProjectId::new();
+ let alice = key_actor("alice", "shared-session");
+ let bob = key_actor("bob", "shared-session");
+ ap.set_for(&alice, ws, p);
+ let p_bob = ProjectId::new();
+ ap.set_for(&bob, ws, p_bob);
+ // Same session_id, different users → still collapses to one entry
+ // (intentional: per_session is the right mode for single-operator,
+ // multi-cwd installs; per_actor is the mode for multi-operator).
+ assert_eq!(ap.get_for(&alice), Some((ws, p_bob)));
+ }
+
+ #[test]
+ fn per_actor_isolates_by_user_and_session() {
+ let ap = ActiveProject::with_mode(ActiveProjectMode::PerActor);
+ let alice_a = key_actor("alice", "sA");
+ let alice_b = key_actor("alice", "sB");
+ let bob_a = key_actor("bob", "sA");
+ let ws = WorkspaceId::new();
+ let p1 = ProjectId::new();
+ let p2 = ProjectId::new();
+ let p3 = ProjectId::new();
+ ap.set_for(&alice_a, ws, p1);
+ ap.set_for(&alice_b, ws, p2);
+ ap.set_for(&bob_a, ws, p3);
+ assert_eq!(ap.get_for(&alice_a), Some((ws, p1)));
+ assert_eq!(ap.get_for(&alice_b), Some((ws, p2)));
+ assert_eq!(ap.get_for(&bob_a), Some((ws, p3)));
+ }
+
+ #[test]
+ fn per_actor_falls_back_to_single_when_actor_is_empty() {
+ let ap = ActiveProject::with_mode(ActiveProjectMode::PerActor);
+ let ws = WorkspaceId::new();
+ let proj = ProjectId::new();
+ ap.set(ws, proj);
+ assert_eq!(ap.get_for(&empty_actor()), Some((ws, proj)));
+ }
+
+ #[test]
+ fn per_actor_set_also_updates_single_slot() {
+ // Legacy callers (anonymous probes, code paths the migration has not
+ // touched yet) keep seeing a fresh pointer via `get()`.
+ let ap = ActiveProject::with_mode(ActiveProjectMode::PerActor);
+ let alice = key_actor("alice", "sA");
+ let ws = WorkspaceId::new();
+ let proj = ProjectId::new();
+ ap.set_for(&alice, ws, proj);
+ assert_eq!(ap.get(), Some((ws, proj)));
+ }
+
+ #[test]
+ fn per_actor_max_entries_evicts_oldest() {
+ let ap = ActiveProject::with_config(ActiveProjectMode::PerActor, DEFAULT_PER_KEY_TTL, 2);
+ let ws = WorkspaceId::new();
+ let p1 = ProjectId::new();
+ let p2 = ProjectId::new();
+ let p3 = ProjectId::new();
+ let k1 = key_session("s1");
+ let k2 = key_session("s2");
+ let k3 = key_session("s3");
+ ap.set_for(&k1, ws, p1);
+ std::thread::sleep(Duration::from_millis(2));
+ 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).
+ 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)));
+ }
+
+ #[test]
+ fn per_actor_ttl_expires_entries() {
+ let ap = ActiveProject::with_config(
+ ActiveProjectMode::PerActor,
+ Duration::from_millis(20),
+ DEFAULT_MAX_ENTRIES,
+ );
+ let k = key_session("s");
+ let ws = WorkspaceId::new();
+ let proj = ProjectId::new();
+ 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();
+ assert!(ap.get_for(&k).is_none());
+ }
}
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 35d8b97b..03b6ae77 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -22,7 +22,9 @@ pub const DEFAULT_WORKSPACE_NAME: &str = "default";
/// Defensive project fallback used only when no cwd/project is available.
pub const DEFAULT_PROJECT_NAME: &str = "scratch";
-pub use active_project::ActiveProject;
+pub use active_project::{
+ ActiveProject, ActiveProjectMode, ActorKey, DEFAULT_MAX_ENTRIES, DEFAULT_PER_KEY_TTL,
+};
pub use actor::{ActorContext, AuthLevel};
pub use error::{MemoryError, MemoryResult};
pub use handoff::{Handoff, HandoffState, NewHandoff};
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 865587b8..99633341 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -192,16 +192,25 @@ pub fn hook_router(state: HookState) -> Router {
async fn handle_hook(
State(state): State<Arc<HookState>>,
Query(query): Query<HookQuery>,
+ actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
Json(body): Json<serde_json::Value>,
) -> impl IntoResponse {
let env = HookEnvelope::from_query_and_body(query, body);
+ // The auth middleware in front of `/hook` injects the request's
+ // [`ActorContext`] (rung 1 root, rung 2 DB user, or anonymous). We
+ // capture its `user` field NOW — before the spawn drops the request
+ // extensions — so `process()` can key the `ActiveProject` map by the
+ // authenticated identity when `[auto_scope] mode = per_actor` is on.
+ let actor_user = actor_ext
+ .map(|axum::Extension(ctx)| ctx.user)
+ .unwrap_or_default();
let Ok(permit) = state.ingest_semaphore.clone().try_acquire_owned() else {
warn!("hook ingest saturated; dropping event with 429");
return (StatusCode::TOO_MANY_REQUESTS, "hook queue full");
};
tokio::spawn(async move {
let _permit = permit;
- process_envelope(state, env).await;
+ process_envelope(state, env, actor_user).await;
});
(StatusCode::ACCEPTED, "queued")
}
@@ -240,8 +249,12 @@ pub struct HandoffQuery {
async fn handle_handoff(
State(state): State<Arc<HookState>>,
Query(query): Query<HandoffQuery>,
+ actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
) -> impl IntoResponse {
- match fetch_and_accept_handoff(&state, query).await {
+ let actor_user = actor_ext
+ .map(|axum::Extension(ctx)| ctx.user)
+ .unwrap_or_default();
+ match fetch_and_accept_handoff(&state, query, actor_user).await {
Ok(Some(markdown)) => (StatusCode::OK, markdown),
Ok(None) => (StatusCode::OK, String::new()),
Err(e) => {
@@ -254,14 +267,23 @@ async fn handle_handoff(
async fn fetch_and_accept_handoff(
state: &HookState,
query: HandoffQuery,
+ actor_user: Option<String>,
) -> anyhow::Result<Option<String>> {
let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);
+ // `/handoff` has no session_id in the request — `per_session` mode
+ // therefore falls back to the single slot (graceful degradation),
+ // while `per_actor` keys by `user` alone.
+ let actor_key = ai_memory_core::ActorKey {
+ user: actor_user,
+ session_id: None,
+ };
let (ws, proj) = resolve_project_ids(
state,
query.cwd.as_deref(),
query.workspace.as_deref(),
query.project.as_deref(),
ProjectStrategy::parse(query.project_strategy.as_deref()),
+ &actor_key,
)
.await?;
let handoff = state
@@ -374,6 +396,7 @@ async fn resolve_project_ids(
workspace_override: Option<&str>,
project_override: Option<&str>,
project_strategy: ProjectStrategy,
+ actor: &ai_memory_core::ActorKey,
) -> anyhow::Result<(WorkspaceId, ProjectId)> {
let cwd_norm = cwd.filter(|s| !s.is_empty()).map(str::to_string);
@@ -395,8 +418,10 @@ async fn resolve_project_ids(
if let Some(ids) = cache.get(&cache_key) {
// Republish on every hit: a cache hit still means the agent
// is active in this project *now*, which is exactly what the
- // MCP read tools need as their default.
- state.active_project.set(ids.0, ids.1);
+ // MCP read tools need as their default. Keyed by the actor so
+ // opt-in isolation modes (`per_session`/`per_actor`) keep
+ // concurrent callers separated.
+ state.active_project.set_for(actor, ids.0, ids.1);
return Ok(ids);
}
}
@@ -412,7 +437,7 @@ async fn resolve_project_ids(
None => {
state
.active_project
- .set(state.workspace_id, state.project_id);
+ .set_for(actor, state.workspace_id, state.project_id);
return Ok((state.workspace_id, state.project_id));
}
},
@@ -425,7 +450,7 @@ async fn resolve_project_ids(
// message.
state
.active_project
- .set(state.workspace_id, state.project_id);
+ .set_for(actor, state.workspace_id, state.project_id);
return Ok((state.workspace_id, state.project_id));
}
};
@@ -466,24 +491,37 @@ async fn resolve_project_ids(
.map_err(|e| anyhow::anyhow!("get_or_create_project: {e}"))?;
let ids = (ws, proj);
state.project_cache.lock().await.insert(cache_key, ids);
- state.active_project.set(ws, proj);
+ state.active_project.set_for(actor, ws, proj);
Ok(ids)
}
-async fn process_envelope(state: Arc<HookState>, env: HookEnvelope) {
- if let Err(e) = process(&state, env).await {
+async fn process_envelope(state: Arc<HookState>, env: HookEnvelope, actor_user: Option<String>) {
+ if let Err(e) = process(&state, env, actor_user).await {
warn!(error = %e, "hook processing failed");
}
}
-async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {
+async fn process(
+ state: &HookState,
+ env: HookEnvelope,
+ actor_user: Option<String>,
+) -> anyhow::Result<()> {
let session_id = resolve_session_id(&env)?;
+ // Build the actor key used to scope the in-process `ActiveProject`
+ // pointer. `user` is whatever the auth middleware extracted from this
+ // request; `session_id` comes from the envelope. Empty actor (anonymous
+ // + no session) is allowed — `set_for` falls back to the single slot.
+ let actor_key = ai_memory_core::ActorKey {
+ user: actor_user.clone(),
+ session_id: Some(session_id.to_string()),
+ };
let (mut ws, mut proj) = resolve_project_ids(
state,
env.cwd.as_deref(),
env.workspace_override.as_deref(),
env.project_override.as_deref(),
env.project_strategy,
+ &actor_key,
)
.await?;
@@ -519,6 +557,7 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {
env.workspace_override.as_deref(),
env.project_override.as_deref(),
env.project_strategy,
+ &actor_key,
)
.await?;
ws = refreshed.0;
@@ -895,6 +934,7 @@ mod tests {
None,
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -905,6 +945,7 @@ mod tests {
None,
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -935,6 +976,7 @@ mod tests {
agent: Some("claude-code".into()),
..Default::default()
}),
+ None,
Json(serde_json::json!({})),
)
.await
@@ -949,17 +991,30 @@ mod tests {
let tmp = TempDir::new().unwrap();
let state = make_state(&tmp).await;
- let (ws, proj) = resolve_project_ids(&state, None, None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (ws, proj) = resolve_project_ids(
+ &state,
+ None,
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
assert_eq!(ws, state.workspace_id);
assert_eq!(proj, state.project_id);
// Likewise for an empty string.
- let (ws2, proj2) =
- resolve_project_ids(&state, Some(""), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (ws2, proj2) = resolve_project_ids(
+ &state,
+ Some(""),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
assert_eq!(ws2, state.workspace_id);
assert_eq!(proj2, state.project_id);
@@ -974,10 +1029,16 @@ mod tests {
let tmp = TempDir::new().unwrap();
let state = make_state(&tmp).await;
- let (ws, proj) =
- resolve_project_ids(&state, Some("/"), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (ws, proj) = resolve_project_ids(
+ &state,
+ Some("/"),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
assert_eq!(ws, state.workspace_id);
assert_eq!(proj, state.project_id);
assert_eq!(state.active_project.get(), Some((ws, proj)));
@@ -1010,10 +1071,16 @@ mod tests {
let cwd = "/home/user/cached-project";
// First call — populates the cache.
- let (_, proj_first) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (_, proj_first) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
// Inspect the cache: should have exactly one entry.
{
@@ -1032,10 +1099,16 @@ mod tests {
}
// Second call — must return the same IDs from the cache.
- let (_, proj_second) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (_, proj_second) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
assert_eq!(proj_first, proj_second, "cache must return identical IDs");
// Cache must still have exactly one entry (no duplicate insert).
@@ -1086,11 +1159,17 @@ mod tests {
},
serde_json::json!({ "sessionID": "heal-sess-1" }),
);
- process(&state, env1).await.unwrap();
- let (ws, proj) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ process(&state, env1, None).await.unwrap();
+ let (ws, proj) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
// 2) Purge the project — the DB row is gone but the cache still
// points at it (exactly the purge-on-live-server scenario).
@@ -1120,15 +1199,21 @@ mod tests {
},
serde_json::json!({ "sessionID": "heal-sess-2" }),
);
- process(&state, env2)
+ process(&state, env2, None)
.await
.expect("self-heal: stale cached project must be recreated, not FK-fail");
// 4) The project was recreated (fresh id) and the event landed.
- let (_, proj_new) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (_, proj_new) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
assert_ne!(
proj_new, proj,
"purged project must be replaced by a fresh one"
@@ -1159,11 +1244,17 @@ mod tests {
},
serde_json::json!({ "sessionID": "move-sess-1" }),
);
- process(&state, env1).await.unwrap();
- let (ws, proj) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ process(&state, env1, None).await.unwrap();
+ let (ws, proj) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
// 2) Move the project to another workspace (re-stamp workspace_id, same
// project_id) — the cache still points at (default_ws, proj), now a
@@ -1200,7 +1291,7 @@ mod tests {
},
serde_json::json!({ "sessionID": "move-sess-2" }),
);
- process(&state, env2)
+ process(&state, env2, None)
.await
.expect("self-heal: stale cross-workspace pair must re-resolve, not write split-brain");
@@ -1215,10 +1306,16 @@ mod tests {
Some(proj),
"moved project keeps its id in the destination workspace"
);
- let (ws_new, proj_new) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (ws_new, proj_new) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
assert_eq!(ws_new, ws, "re-resolved back into the default workspace");
assert_ne!(
proj_new, proj,
@@ -1247,11 +1344,17 @@ mod tests {
},
serde_json::json!({ "sessionID": "heal-repo-root-1" }),
);
- process(&state, env1).await.unwrap();
- let (ws, proj) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::RepoRoot)
- .await
- .unwrap();
+ process(&state, env1, None).await.unwrap();
+ let (ws, proj) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::RepoRoot,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
state
.writer
@@ -1269,14 +1372,20 @@ mod tests {
},
serde_json::json!({ "sessionID": "heal-repo-root-2" }),
);
- process(&state, env2)
+ process(&state, env2, None)
.await
.expect("repo-root cache slot must be evicted and recreated");
- let (_, proj_new) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::RepoRoot)
- .await
- .unwrap();
+ let (_, proj_new) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::RepoRoot,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
assert_ne!(proj_new, proj);
}
@@ -1300,7 +1409,7 @@ mod tests {
}),
);
- process(&state, env).await.unwrap();
+ process(&state, env, None).await.unwrap();
// The observation must be in the project derived from the cwd,
// not in the server-default `scratch` project.
@@ -1310,6 +1419,7 @@ mod tests {
None,
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1340,7 +1450,7 @@ mod tests {
},
serde_json::json!({ "session_id": sid }),
);
- process(&state, env).await.unwrap();
+ process(&state, env, None).await.unwrap();
}
let pages = state
@@ -1375,7 +1485,7 @@ mod tests {
}),
);
- process(&state, env).await.unwrap();
+ process(&state, env, None).await.unwrap();
let counts = state.reader.status_counts().await.unwrap();
assert_eq!(counts.sessions, 1);
@@ -1403,7 +1513,7 @@ mod tests {
);
let session_id = resolve_session_id(&env).unwrap();
- process(&state, env).await.unwrap();
+ process(&state, env, None).await.unwrap();
let observations = state
.reader
@@ -1445,7 +1555,7 @@ mod tests {
);
let session_id = resolve_session_id(&env).unwrap();
- process(&state, env).await.unwrap();
+ process(&state, env, None).await.unwrap();
let observations = state
.reader
@@ -1484,6 +1594,7 @@ mod tests {
None,
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1493,6 +1604,7 @@ mod tests {
Some("movvia"),
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1515,6 +1627,7 @@ mod tests {
Some("acme"),
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1544,6 +1657,7 @@ mod tests {
project: None,
project_strategy: None,
},
+ None,
)
.await
.unwrap();
@@ -1560,10 +1674,16 @@ mod tests {
let state = make_state(&tmp).await;
let cwd = "/home/u/plain-repo";
- let (ws, proj) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (ws, proj) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
state
.writer
.insert_handoff(NewHandoff {
@@ -1590,6 +1710,7 @@ mod tests {
project: None,
project_strategy: None,
},
+ None,
)
.await
.unwrap();
@@ -1615,6 +1736,7 @@ mod tests {
None,
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1624,6 +1746,7 @@ mod tests {
None,
Some("pe-portais"),
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1648,6 +1771,7 @@ mod tests {
Some("acme"),
Some("api"),
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1657,6 +1781,7 @@ mod tests {
Some("acme"),
Some("api"),
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1675,16 +1800,23 @@ mod tests {
let state = make_state(&tmp).await;
let cwd = "/home/u/poison-test";
- let (ws_default, _) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (ws_default, _) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
let (ws_movvia, _) = resolve_project_ids(
&state,
Some(cwd),
Some("movvia"),
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1716,6 +1848,7 @@ mod tests {
Some("acme"),
Some("api"),
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1751,23 +1884,36 @@ mod tests {
std::fs::create_dir_all(&app_dir).unwrap();
let app_cwd = app_dir.to_str().unwrap();
- let (_, proj_basename) =
- resolve_project_ids(&state, Some(app_cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (_, proj_basename) = resolve_project_ids(
+ &state,
+ Some(app_cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
let (_, proj_explicit_app) = resolve_project_ids(
&state,
Some(main_dir.to_str().unwrap()),
None,
Some("app"),
ProjectStrategy::RepoRoot,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
+ let (_, proj_repo_root) = resolve_project_ids(
+ &state,
+ Some(app_cwd),
+ None,
+ None,
+ ProjectStrategy::RepoRoot,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
- let (_, proj_repo_root) =
- resolve_project_ids(&state, Some(app_cwd), None, None, ProjectStrategy::RepoRoot)
- .await
- .unwrap();
assert_eq!(
proj_basename, proj_explicit_app,
@@ -1790,16 +1936,23 @@ mod tests {
std::fs::create_dir_all(&app_dir).unwrap();
let app_cwd = app_dir.to_str().unwrap();
- let (_, proj_repo_root) =
- resolve_project_ids(&state, Some(app_cwd), None, None, ProjectStrategy::RepoRoot)
- .await
- .unwrap();
+ let (_, proj_repo_root) = resolve_project_ids(
+ &state,
+ Some(app_cwd),
+ None,
+ None,
+ ProjectStrategy::RepoRoot,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
let (_, proj_override_repo_root) = resolve_project_ids(
&state,
Some(app_cwd),
None,
Some("manual"),
ProjectStrategy::RepoRoot,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1809,6 +1962,7 @@ mod tests {
None,
Some("manual"),
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1831,14 +1985,26 @@ mod tests {
std::fs::create_dir_all(&app_dir).unwrap();
let app_cwd = app_dir.to_str().unwrap();
- let (_, proj_basename) =
- resolve_project_ids(&state, Some(app_cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
- let (_, proj_repo_root) =
- resolve_project_ids(&state, Some(app_cwd), None, None, ProjectStrategy::RepoRoot)
- .await
- .unwrap();
+ let (_, proj_basename) = resolve_project_ids(
+ &state,
+ Some(app_cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
+ let (_, proj_repo_root) = resolve_project_ids(
+ &state,
+ Some(app_cwd),
+ None,
+ None,
+ ProjectStrategy::RepoRoot,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
assert_ne!(proj_basename, proj_repo_root);
let cache = state.project_cache.lock().await;
@@ -1881,13 +2047,20 @@ mod tests {
None,
None,
ProjectStrategy::RepoRoot,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
+ let (ws_wt, proj_wt) = resolve_project_ids(
+ &state,
+ Some(wt_cwd),
+ None,
+ None,
+ ProjectStrategy::RepoRoot,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
- let (ws_wt, proj_wt) =
- resolve_project_ids(&state, Some(wt_cwd), None, None, ProjectStrategy::RepoRoot)
- .await
- .unwrap();
assert_eq!(ws_main, ws_wt, "same workspace");
assert_eq!(
@@ -1895,10 +2068,16 @@ mod tests {
"worktree must resolve to same project as main repo"
);
- let (_, proj_wt_basename) =
- resolve_project_ids(&state, Some(wt_cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (_, proj_wt_basename) = resolve_project_ids(
+ &state,
+ Some(wt_cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
assert_ne!(
proj_main, proj_wt_basename,
"default strategy must not collapse worktrees into the main repo project"
@@ -1917,10 +2096,16 @@ mod tests {
std::fs::create_dir_all(&plain_dir).unwrap();
let cwd = plain_dir.to_str().unwrap();
- let (_, proj) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (_, proj) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
// Must NOT be the server-default scratch project.
assert_ne!(proj, state.project_id);
@@ -1935,6 +2120,7 @@ mod tests {
None,
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1952,10 +2138,16 @@ mod tests {
git2::Repository::init_bare(&bare_dir).unwrap();
let cwd = bare_dir.to_str().unwrap();
- let (_, proj) =
- resolve_project_ids(&state, Some(cwd), None, None, ProjectStrategy::Basename)
- .await
- .unwrap();
+ let (_, proj) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
// Must NOT be the server-default scratch project — basename should work.
assert_ne!(proj, state.project_id);
@@ -1970,6 +2162,7 @@ mod tests {
None,
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -1992,6 +2185,7 @@ mod tests {
None,
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
@@ -2002,6 +2196,7 @@ mod tests {
None,
None,
ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
)
.await
.unwrap();
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index b41a0a08..9d320722 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -537,16 +537,66 @@ impl AiMemoryServer {
self
}
+ /// Build the [`ActorKey`] for a tool call from the request's stored
+ /// extensions. When the auth middleware has attached an
+ /// [`ai_memory_core::ActorContext`] (rung 1 root, rung 2 DB user), its
+ /// `user` field is used; the `session_id` comes from the same
+ /// extension when the agent's MCP client forwards it, otherwise stays
+ /// `None` and the per-actor lookup gracefully degrades to the single
+ /// slot under `[auto_scope] mode = single` (the default).
+ ///
+ /// Threading parts into every read tool is mechanical but wide; the
+ /// helper is kept here so a follow-up commit can opt each tool in
+ /// without re-doing the design — the wrapper [`Self::effective_ids`] /
+ /// [`Self::effective_ids_for_read_args`] keep working unchanged while
+ /// the migration is in progress.
+ #[allow(dead_code)]
+ fn actor_key_from_parts(
+ parts: Option<&axum::http::request::Parts>,
+ ) -> ai_memory_core::ActorKey {
+ let Some(parts) = parts else {
+ return ai_memory_core::ActorKey::default();
+ };
+ let ctx = parts.extensions.get::<ai_memory_core::ActorContext>();
+ match ctx {
+ None => ai_memory_core::ActorKey::default(),
+ Some(ctx) => ai_memory_core::ActorKey {
+ user: ctx.user.clone(),
+ session_id: ctx.session_id.clone(),
+ },
+ }
+ }
+
/// Resolve which `(workspace_id, project_id)` a read tool should
/// query. Precedence (matches the documented resolution chain):
/// 1. an explicit `project` name argument in the active workspace
- /// when hooks have published one,
+ /// when hooks have published one (for THIS actor),
/// 2. that same explicit `project` in the server's baked workspace,
/// 3. the hook-published [`ActiveProject`] (the cwd the agent is
- /// currently working in),
+ /// currently working in, keyed by `actor` in opt-in isolation
+ /// modes),
/// 4. the server's baked-in `--project` default.
+ ///
+ /// `actor` is built by [`Self::actor_key_from_parts`]; pass
+ /// `ActorKey::default()` when the call site has no request context.
+ /// Empty actor → fall back to the single slot (legacy behaviour).
+ /// Backward-compatible wrapper for call sites that have not yet
+ /// threaded a request `Parts` extension. Behaves like the historical
+ /// `effective_ids` — i.e. consults the single slot only — which is
+ /// what every tool gets under the default `[auto_scope] mode = single`.
+ /// Opt-in modes (`per_session` / `per_actor`) gain proper isolation as
+ /// each tool gets migrated to [`Self::effective_ids_with_actor`].
async fn effective_ids(&self, explicit_project: Option<&str>) -> (WorkspaceId, ProjectId) {
- let active = self.active_project.get();
+ self.effective_ids_with_actor(explicit_project, &ai_memory_core::ActorKey::default())
+ .await
+ }
+
+ async fn effective_ids_with_actor(
+ &self,
+ explicit_project: Option<&str>,
+ actor: &ai_memory_core::ActorKey,
+ ) -> (WorkspaceId, ProjectId) {
+ let active = self.active_project.get_for(actor);
if let Some(name) = explicit_project.map(str::trim).filter(|s| !s.is_empty()) {
if let Some((active_ws, _)) = active
&& let Ok(Some(pid)) = self.reader.find_project(active_ws, name.to_string()).await
@@ -565,10 +615,25 @@ impl AiMemoryServer {
active.unwrap_or((self.workspace_id, self.project_id))
}
+ /// Backward-compatible wrapper paired with [`Self::effective_ids`].
async fn effective_ids_for_read_args(
&self,
explicit_workspace: Option<&str>,
explicit_project: Option<&str>,
+ ) -> Result<(WorkspaceId, ProjectId), McpError> {
+ self.effective_ids_for_read_args_with_actor(
+ explicit_workspace,
+ explicit_project,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ }
+
+ async fn effective_ids_for_read_args_with_actor(
+ &self,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+ actor: &ai_memory_core::ActorKey,
) -> Result<(WorkspaceId, ProjectId), McpError> {
match (
trimmed_opt(explicit_workspace),
@@ -579,7 +644,7 @@ impl AiMemoryServer {
"workspace and project must be provided together",
None,
)),
- (None, project) => Ok(self.effective_ids(project).await),
+ (None, project) => Ok(self.effective_ids_with_actor(project, actor).await),
}
}