Skip to content

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

Rust

test(auto-scope): comprehensive concurrent + multi-user coverage

Djalma Júnior5825a48e48cc
diff --git a/Cargo.lock b/Cargo.lock
index 81e90e7c..ecd14044 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -174,6 +174,7 @@ version = "0.10.0"
dependencies = [
"ai-memory-consolidate",
"ai-memory-core",
+ "ai-memory-hooks",
"ai-memory-llm",
"ai-memory-store",
"ai-memory-wiki",
diff --git a/crates/ai-memory-cli/tests/autoscope_env.rs b/crates/ai-memory-cli/tests/autoscope_env.rs
new file mode 100644
index 00000000..a5c0a92d
--- /dev/null
+++ b/crates/ai-memory-cli/tests/autoscope_env.rs
@@ -0,0 +1,322 @@
+//! Subprocess smoke tests for `[auto_scope]` env-var configuration.
+//!
+//! These tests assert the wiring between figment's `AI_MEMORY_*` env-var
+//! parser and the `[auto_scope]` config block. The chart values.yaml will
+//! ship the same env vars (`AI_MEMORY_AUTO_SCOPE__MODE`, …), so a regression
+//! here would silently downgrade prod from `per_session`/`per_actor` to
+//! the legacy `single` slot — and we'd only catch it by smoke-running
+//! against a multi-actor scenario in prod.
+//!
+//! Each test spawns the `ai-memory` binary with one env-var combination,
+//! waits for the startup log line that records the resolved mode, and
+//! kills the child. Invalid values trip a clear-error exit, which is
+//! also asserted so figment's parse-failure path stays loud.
+
+use std::io::{BufRead, BufReader};
+use std::process::{Command, Stdio};
+use std::sync::mpsc;
+use std::time::{Duration, Instant};
+use tempfile::TempDir;
+
+fn bin() -> &'static str {
+ env!("CARGO_BIN_EXE_ai-memory")
+}
+
+/// Spawn the binary with the given env vars and stream stderr until either
+/// `needle` appears in a line or `timeout` elapses. Always kills the child
+/// before returning. Returns `(matched_line_or_none, all_stderr_captured)`.
+fn spawn_and_wait_for_log(
+ envs: &[(&str, &str)],
+ needle: &str,
+ timeout: Duration,
+) -> (Option<String>, String) {
+ let tmp = TempDir::new().expect("tempdir for serve");
+ // `--bind 127.0.0.1:0` asks the OS for any free port — we never
+ // actually want to talk to the listener, only to confirm the engine
+ // starts up far enough to log the `[auto_scope]` mode.
+ let mut cmd = Command::new(bin());
+ cmd.args([
+ "serve",
+ "--transport",
+ "http",
+ "--bind",
+ "127.0.0.1:0",
+ "--data-dir",
+ ])
+ .arg(tmp.path())
+ .env("AI_MEMORY_DATA_DIR", tmp.path())
+ // Force tracing to spit at least info-level so the
+ // "active-project isolation mode" line is rendered to stderr.
+ .env("RUST_LOG", "info")
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped());
+ for (k, v) in envs {
+ cmd.env(k, v);
+ }
+ let mut child = cmd.spawn().expect("spawn ai-memory serve");
+
+ // Pump stderr in a background thread so we can apply a wall-clock
+ // timeout on the *match*, not on the underlying read syscalls.
+ let stderr = child.stderr.take().expect("stderr piped");
+ let (tx, rx) = mpsc::channel::<String>();
+ let pump = std::thread::spawn(move || {
+ let mut all = String::new();
+ let reader = BufReader::new(stderr);
+ for line in reader.lines() {
+ let Ok(line) = line else { break };
+ all.push_str(&line);
+ all.push('\n');
+ if tx.send(line).is_err() {
+ break;
+ }
+ }
+ all
+ });
+
+ let deadline = Instant::now() + timeout;
+ let mut matched: Option<String> = None;
+ while Instant::now() < deadline {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ match rx.recv_timeout(remaining) {
+ Ok(line) => {
+ if line.contains(needle) {
+ matched = Some(line);
+ break;
+ }
+ }
+ Err(_) => break,
+ }
+ }
+
+ let _ = child.kill();
+ let _ = child.wait();
+ // Pump thread terminates once stderr closes (post-kill); collect what
+ // it captured.
+ let all_stderr = pump.join().unwrap_or_default();
+ (matched, all_stderr)
+}
+
+/// Spawn the binary and let it run to completion, capturing exit status
+/// + stderr. Used for the invalid-mode test where startup fails before
+/// reaching the log line we'd otherwise wait for.
+fn spawn_and_wait_for_exit(envs: &[(&str, &str)], timeout: Duration) -> (bool, String) {
+ let tmp = TempDir::new().expect("tempdir for serve");
+ let mut cmd = Command::new(bin());
+ cmd.args([
+ "serve",
+ "--transport",
+ "http",
+ "--bind",
+ "127.0.0.1:0",
+ "--data-dir",
+ ])
+ .arg(tmp.path())
+ .env("AI_MEMORY_DATA_DIR", tmp.path())
+ .env("RUST_LOG", "info")
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped());
+ for (k, v) in envs {
+ cmd.env(k, v);
+ }
+ let mut child = cmd.spawn().expect("spawn ai-memory serve");
+
+ // Poll for exit with a wall-clock cap. If the binary stays alive
+ // past the timeout, that's *also* a failure for "invalid value
+ // must fail fast" — kill it so the test doesn't hang and report
+ // false success.
+ let deadline = Instant::now() + timeout;
+ let exited_cleanly = loop {
+ match child.try_wait() {
+ Ok(Some(status)) => break status.success(),
+ Ok(None) => {
+ if Instant::now() >= deadline {
+ let _ = child.kill();
+ let _ = child.wait();
+ break true; // still running == didn't fail fast
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ Err(_) => break true,
+ }
+ };
+
+ let mut stderr_buf = String::new();
+ if let Some(mut s) = child.stderr.take() {
+ use std::io::Read;
+ let _ = s.read_to_string(&mut stderr_buf);
+ }
+ (exited_cleanly, stderr_buf)
+}
+
+const STARTUP_NEEDLE: &str = "active-project isolation mode";
+const STARTUP_TIMEOUT: Duration = Duration::from_secs(8);
+
+#[test]
+fn default_mode_is_single() {
+ let (line, all) = spawn_and_wait_for_log(&[], STARTUP_NEEDLE, STARTUP_TIMEOUT);
+ let line = line.unwrap_or_else(|| panic!("startup log line not found.\nstderr:\n{all}"));
+ assert!(
+ line.contains("Single"),
+ "default mode must log `Single`. Got: {line}\nfull stderr:\n{all}"
+ );
+}
+
+#[test]
+fn per_session_mode_via_env() {
+ let (line, all) = spawn_and_wait_for_log(
+ &[("AI_MEMORY_AUTO_SCOPE__MODE", "per_session")],
+ STARTUP_NEEDLE,
+ STARTUP_TIMEOUT,
+ );
+ let line = line.unwrap_or_else(|| {
+ panic!("startup log line not found for per_session.\nstderr:\n{all}")
+ });
+ assert!(
+ line.contains("PerSession"),
+ "expected `PerSession` in startup line, got: {line}\nfull stderr:\n{all}"
+ );
+}
+
+#[test]
+fn per_actor_mode_via_env() {
+ let (line, all) = spawn_and_wait_for_log(
+ &[("AI_MEMORY_AUTO_SCOPE__MODE", "per_actor")],
+ STARTUP_NEEDLE,
+ STARTUP_TIMEOUT,
+ );
+ let line = line.unwrap_or_else(|| {
+ panic!("startup log line not found for per_actor.\nstderr:\n{all}")
+ });
+ assert!(
+ line.contains("PerActor"),
+ "expected `PerActor` in startup line, got: {line}\nfull stderr:\n{all}"
+ );
+}
+
+#[test]
+fn ttl_and_max_entries_via_env() {
+ // Confirms the full struct round-trips through figment's `__`
+ // separator convention — not just `mode`. A typo in any of the
+ // three field-names downstream would surface here.
+ let (line, all) = spawn_and_wait_for_log(
+ &[
+ ("AI_MEMORY_AUTO_SCOPE__MODE", "per_session"),
+ ("AI_MEMORY_AUTO_SCOPE__SESSION_TTL_SECS", "120"),
+ ("AI_MEMORY_AUTO_SCOPE__MAX_ENTRIES", "64"),
+ ],
+ STARTUP_NEEDLE,
+ STARTUP_TIMEOUT,
+ );
+ let line = line.unwrap_or_else(|| panic!("startup log not found.\nstderr:\n{all}"));
+ assert!(
+ line.contains("PerSession") && line.contains("120") && line.contains("64"),
+ "all three fields must be reflected in the startup log.\nGot: {line}\nfull stderr:\n{all}"
+ );
+}
+
+#[test]
+fn invalid_mode_value_fails_fast() {
+ // figment + serde's `rename_all = "snake_case"` rejects unknown
+ // enum variants. The process must NOT keep running silently with a
+ // surprise fallback — that's exactly the silent-misconfig bug we
+ // want to catch in CI long before it reaches prod.
+ let (exited_ok, all) = spawn_and_wait_for_exit(
+ &[("AI_MEMORY_AUTO_SCOPE__MODE", "per_universe")],
+ Duration::from_secs(5),
+ );
+ assert!(
+ !exited_ok,
+ "invalid `mode` must NOT result in a successful startup.\nstderr:\n{all}"
+ );
+}
+
+// ─── Boundary-value cases for the numeric fields ──────────────────────
+//
+// figment coerces strings → integers and the `PerActorMap` constructor
+// gracefully clamps the degenerate-zero cases so an operator who copy-
+// pastes a placeholder doesn't get a server that immediately evicts
+// every entry (`ttl=0`) or refuses to store anything (`max_entries=0`).
+// These pin that behaviour so a future refactor either keeps the clamp
+// or makes the failure loud.
+
+#[test]
+fn max_entries_zero_clamps_and_starts() {
+ // `0` is a footgun — without clamping, every insertion would be
+ // immediately evicted and per_actor would silently degrade to the
+ // single slot. `PerActorMap::new` clamps to 1; the engine must
+ // still start.
+ let (line, all) = spawn_and_wait_for_log(
+ &[
+ ("AI_MEMORY_AUTO_SCOPE__MODE", "per_session"),
+ ("AI_MEMORY_AUTO_SCOPE__MAX_ENTRIES", "0"),
+ ],
+ STARTUP_NEEDLE,
+ STARTUP_TIMEOUT,
+ );
+ let line = line.unwrap_or_else(|| {
+ panic!("startup log line not found with max_entries=0.\nstderr:\n{all}")
+ });
+ // The startup log shows the configured value (0), not the
+ // post-clamp internal value — that's a separate observability
+ // concern. Asserting `PerSession` is enough proof that startup
+ // succeeded; the clamp itself is exercised by the unit tests on
+ // `PerActorMap::new`.
+ assert!(
+ line.contains("PerSession"),
+ "max_entries=0 should still start in per_session mode: {line}\nfull stderr:\n{all}"
+ );
+}
+
+#[test]
+fn session_ttl_zero_clamps_and_starts() {
+ // Same logic as max_entries=0: zero TTL = entries expire on
+ // insertion = per_actor silently degrades. `PerActorMap::new` falls
+ // back to DEFAULT_PER_KEY_TTL when ttl.is_zero(). Engine must
+ // still start.
+ let (line, all) = spawn_and_wait_for_log(
+ &[
+ ("AI_MEMORY_AUTO_SCOPE__MODE", "per_actor"),
+ ("AI_MEMORY_AUTO_SCOPE__SESSION_TTL_SECS", "0"),
+ ],
+ STARTUP_NEEDLE,
+ STARTUP_TIMEOUT,
+ );
+ let line = line.unwrap_or_else(|| {
+ panic!("startup log line not found with ttl=0.\nstderr:\n{all}")
+ });
+ assert!(
+ line.contains("PerActor"),
+ "session_ttl_secs=0 should still start in per_actor mode: {line}\nfull stderr:\n{all}"
+ );
+}
+
+#[test]
+fn empty_mode_string_fails_fast() {
+ // `""` is not a valid serde enum variant. Just like
+ // `per_universe`, this must abort startup — never quietly default
+ // to single.
+ let (exited_ok, all) = spawn_and_wait_for_exit(
+ &[("AI_MEMORY_AUTO_SCOPE__MODE", "")],
+ Duration::from_secs(5),
+ );
+ assert!(
+ !exited_ok,
+ "empty `mode` must NOT result in a successful startup.\nstderr:\n{all}"
+ );
+}
+
+#[test]
+fn pascalcase_mode_fails_fast() {
+ // The serde rename is `snake_case`. `PerSession` (the rust enum
+ // variant name) is NOT a valid wire value; the operator must use
+ // `per_session`. Pin this so a refactor doesn't quietly accept
+ // both forms (which would mask a future case-sensitivity bug).
+ let (exited_ok, all) = spawn_and_wait_for_exit(
+ &[("AI_MEMORY_AUTO_SCOPE__MODE", "PerSession")],
+ Duration::from_secs(5),
+ );
+ assert!(
+ !exited_ok,
+ "PascalCase `mode` must NOT result in a successful startup.\nstderr:\n{all}"
+ );
+}
diff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rs
index a1a5f6f2..a8c557d0 100644
--- a/crates/ai-memory-core/src/active_project.rs
+++ b/crates/ai-memory-core/src/active_project.rs
@@ -168,6 +168,16 @@ impl PerActorMap {
self.purge_expired(now);
self.entries.get(key).map(|(ws, proj, _)| (*ws, *proj))
}
+
+ /// Test-only: live row count in the backing HashMap. Counts all
+ /// rows, including ones whose TTL has elapsed (those are dropped
+ /// by `purge_expired` on the next read/write). The randomised cap
+ /// test uses this to verify `enforce_cap` keeps the storage bounded
+ /// at every step regardless of when expiry sweeps run.
+ #[cfg(test)]
+ fn raw_len(&self) -> usize {
+ self.entries.len()
+ }
}
/// Cheap, cloneable handle to the shared "currently active project" pointer.
@@ -333,6 +343,19 @@ impl ActiveProject {
let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());
guard.get(&scoped, Instant::now())
}
+
+ /// Test-only: live count of keyed entries in the per-actor backing
+ /// store, after any pending TTL expiry. Used by the randomised
+ /// invariant tests to pin `count <= max_entries` after every
+ /// operation. Counts both still-fresh and stale entries because
+ /// pre-expiry sweeping is a `get`-time concern; this helper
+ /// inspects raw storage so the cap test catches a cap violation
+ /// regardless of when expiry sweeps run.
+ #[cfg(test)]
+ fn keyed_entry_count_for_test(&self) -> usize {
+ let guard = self.per_actor.read().unwrap_or_else(|e| e.into_inner());
+ guard.raw_len()
+ }
}
#[cfg(test)]
@@ -536,4 +559,253 @@ mod tests {
ap.clear();
assert!(ap.get_for(&k).is_none());
}
+
+ // ────────────────────────────────────────────────────────────────────
+ // Randomised invariant tests.
+ //
+ // Each `prop_*` test runs a long sequence of operations driven by a
+ // tiny xorshift RNG with a fixed seed (printed on failure for
+ // repro). We assert universal invariants that must hold AFTER every
+ // operation — not just at one cherry-picked moment — so a bug in
+ // eviction order or TTL expiry that the fixed scenarios miss
+ // surfaces here.
+ //
+ // No external dep: workspace deliberately curates its dev-deps and
+ // adding `proptest` for one module is more cost than signal. The
+ // randomized fuzzing below covers the same ground for the
+ // invariants we care about; if a future regression motivates true
+ // shrinking, swap in proptest then.
+ // ────────────────────────────────────────────────────────────────────
+
+ /// Minimal xorshift64* — deterministic, ~4 cycles/step, no deps.
+ struct Rng(u64);
+ impl Rng {
+ fn new(seed: u64) -> Self {
+ // Avoid the all-zero degenerate state.
+ Self(if seed == 0 { 0x9e37_79b9_7f4a_7c15 } else { seed })
+ }
+ fn next(&mut self) -> u64 {
+ let mut x = self.0;
+ x ^= x << 13;
+ x ^= x >> 7;
+ x ^= x << 17;
+ self.0 = x;
+ x
+ }
+ fn pick<T: Copy>(&mut self, slice: &[T]) -> T {
+ slice[(self.next() as usize) % slice.len()]
+ }
+ }
+
+ /// One operation in the randomised harness.
+ #[derive(Debug, Clone, Copy)]
+ enum Op {
+ Set(usize), // set_for(actor_pool[idx], ws, fresh proj)
+ Get(usize), // get_for(actor_pool[idx])
+ ClearAll, // clear() — single + keyed
+ SetSingle, // set(ws, fresh proj) — legacy single-slot path
+ GetSingle, // get() — legacy single-slot path
+ }
+
+ fn run_seeded<F: FnMut(usize, &Op, &ActiveProject)>(
+ ap: &ActiveProject,
+ seed: u64,
+ steps: usize,
+ actor_pool_size: usize,
+ ws: WorkspaceId,
+ mut on_step: F,
+ ) {
+ let mut rng = Rng::new(seed);
+ let actors: Vec<ActorKey> = (0..actor_pool_size)
+ .map(|i| ActorKey {
+ user: Some(format!("user-{i}")),
+ session_id: Some(format!("sess-{i}")),
+ })
+ .collect();
+
+ let op_table = [Op::Set(0), Op::Get(0), Op::ClearAll, Op::SetSingle, Op::GetSingle];
+
+ for step in 0..steps {
+ let mut op = rng.pick(&op_table);
+ if let Op::Set(_) = op {
+ op = Op::Set((rng.next() as usize) % actor_pool_size);
+ } else if let Op::Get(_) = op {
+ op = Op::Get((rng.next() as usize) % actor_pool_size);
+ }
+
+ match op {
+ Op::Set(i) => {
+ let proj = ProjectId::new();
+ ap.set_for(&actors[i], ws, proj);
+ }
+ Op::Get(i) => {
+ let _ = ap.get_for(&actors[i]);
+ }
+ Op::ClearAll => ap.clear(),
+ Op::SetSingle => {
+ let proj = ProjectId::new();
+ ap.set(ws, proj);
+ }
+ Op::GetSingle => {
+ let _ = ap.get();
+ }
+ }
+
+ on_step(step, &op, ap);
+ }
+ }
+
+ /// Property: at every moment, the count of `keyed` entries must be
+ /// `<= max_entries`. The LRU evictor is the only thing keeping the
+ /// map bounded; a race that lets it grow past the cap would surface
+ /// here within a few thousand random ops.
+ #[test]
+ fn prop_keyed_entries_never_exceed_max() {
+ let ws = WorkspaceId::new();
+ for seed in [1, 42, 1337, 0xdead_beef, 0xfeed_face] {
+ let cap = 8;
+ let ap = ActiveProject::with_config(
+ ActiveProjectMode::PerActor,
+ DEFAULT_PER_KEY_TTL,
+ cap,
+ );
+ // Pool larger than cap so eviction is exercised continuously.
+ run_seeded(&ap, seed, 2_000, cap * 4, ws, |step, op, ap| {
+ let count = ap.keyed_entry_count_for_test();
+ assert!(
+ count <= cap,
+ "seed={seed:#x} step={step}: cap violated, count={count} > {cap} after {op:?}"
+ );
+ });
+ }
+ }
+
+ /// Property: an entry's projection through `set_for(k, _, p)` must
+ /// be observable by `keyed_only_get(k) == Some(_, p)` until either
+ /// (a) another `set_for(k, _, p')` overrides it, (b) eviction
+ /// kicks it out (only possible if cap was exceeded between writes),
+ /// or (c) the TTL passes.
+ ///
+ /// This is the "fresh write is durable" contract — the foundation
+ /// every read tool depends on.
+ #[test]
+ fn prop_fresh_write_round_trips_until_overwrite_or_evict() {
+ let ws = WorkspaceId::new();
+ for seed in [1, 99, 12_345, 0xc0ffee_u64] {
+ let cap = 16;
+ let pool_size = cap * 2;
+ let ap = ActiveProject::with_config(
+ ActiveProjectMode::PerActor,
+ Duration::from_secs(60), // long TTL — eviction stays cap-driven
+ cap,
+ );
+ let mut rng = Rng::new(seed);
+ let actors: Vec<ActorKey> = (0..pool_size)
+ .map(|i| ActorKey {
+ user: Some(format!("user-{i}")),
+ session_id: Some(format!("sess-{i}")),
+ })
+ .collect();
+
+ // Walk: each step picks an actor, writes a fresh project id,
+ // immediately reads back, asserts the read sees THAT id.
+ // Whether other actors' entries were evicted is fine; the
+ // write we JUST did MUST be readable.
+ for step in 0..1_000 {
+ let i = (rng.next() as usize) % pool_size;
+ let proj = ProjectId::new();
+ ap.set_for(&actors[i], ws, proj);
+ let got = ap.keyed_only_get(&actors[i]);
+ assert_eq!(
+ got,
+ Some((ws, proj)),
+ "seed={seed:#x} step={step}: fresh write for actor {i} not readable; got {got:?}"
+ );
+ }
+ }
+ }
+
+ /// Property: `clear()` must wipe BOTH the single slot and every
+ /// keyed entry. Operators rely on this for tests / admin-driven
+ /// reset; a partial clear would leak stale routing.
+ #[test]
+ fn prop_clear_wipes_all_slots() {
+ let ws = WorkspaceId::new();
+ for seed in [1_u64, 7, 314_159, 271_828, 161_803] {
+ let ap = ActiveProject::with_config(
+ ActiveProjectMode::PerActor,
+ DEFAULT_PER_KEY_TTL,
+ 64,
+ );
+ run_seeded(&ap, seed, 500, 8, ws, |_step, _op, _ap| {});
+ // After arbitrary ops, clear and assert emptiness from every
+ // angle. Use a fresh actor key not seen in the run.
+ ap.clear();
+ assert!(ap.get().is_none(), "seed={seed:#x}: single slot not cleared");
+ assert!(
+ ap.keyed_only_get(&ActorKey {
+ user: Some("post-clear-probe".into()),
+ session_id: Some("post-clear".into()),
+ })
+ .is_none(),
+ "seed={seed:#x}: keyed lookup after clear must be None"
+ );
+ assert_eq!(
+ ap.keyed_entry_count_for_test(),
+ 0,
+ "seed={seed:#x}: keyed_entry_count after clear must be 0"
+ );
+ }
+ }
+
+ /// 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();
+ for seed in [1_u64, 11, 222, 3_333] {
+ let ttl = Duration::from_millis(40);
+ let ap = ActiveProject::with_config(ActiveProjectMode::PerActor, ttl, 32);
+ let mut rng = Rng::new(seed);
+ let actors: Vec<ActorKey> = (0..8)
+ .map(|i| ActorKey {
+ user: Some(format!("u-{i}")),
+ session_id: Some(format!("s-{i}")),
+ })
+ .collect();
+
+ // Pre-populate every actor; record the write time relative
+ // to the run start.
+ for actor in &actors {
+ ap.set_for(actor, ws, ProjectId::new());
+ }
+
+ // Wait for TTL plus a margin so every pre-populated entry
+ // is logically expired.
+ 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.
+ for (idx, actor) in actors.iter().enumerate() {
+ assert!(
+ ap.keyed_only_get(actor).is_none(),
+ "seed={seed:#x} idx={idx}: expired keyed entry resurrected"
+ );
+ }
+
+ // Cross-check that fresh writes still work after expiry —
+ // the map shouldn't go into an unrecoverable state.
+ let i = (rng.next() as usize) % actors.len();
+ let proj = ProjectId::new();
+ ap.set_for(&actors[i], ws, proj);
+ assert_eq!(
+ ap.keyed_only_get(&actors[i]),
+ Some((ws, proj)),
+ "seed={seed:#x}: fresh post-expiry write must round-trip"
+ );
+ }
+ }
}
diff --git a/crates/ai-memory-mcp/Cargo.toml b/crates/ai-memory-mcp/Cargo.toml
index 933a5e88..b9e8baa6 100644
--- a/crates/ai-memory-mcp/Cargo.toml
+++ b/crates/ai-memory-mcp/Cargo.toml
@@ -34,6 +34,7 @@ jiff.workspace = true
[dev-dependencies]
ai-memory-core.workspace = true
+ai-memory-hooks.workspace = true
ai-memory-store.workspace = true
ai-memory-wiki.workspace = true
flate2.workspace = true
diff --git a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
new file mode 100644
index 00000000..623bb108
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
@@ -0,0 +1,484 @@
+//! End-to-end test for `auto_scope.mode = per_actor` with the **production
+//! auth chain**: real `users` table rows, hashed bearer tokens, and a
+//! middleware that mirrors `ai_memory_cli::auth::require_bearer`'s Bearer
+//! → hash → DB-lookup → `ActorContext.user = user.username` path.
+//!
+//! Why a replica and not the real one: `ai-memory-cli` is a binary-only
+//! crate (no `lib.rs`), so its `auth` module isn't reachable from an
+//! integration test in another crate. The slice that matters for
+//! `auto_scope` is the (Bearer header → ActorContext.user) wiring, which
+//! is short enough to replicate verbatim. Cookie / Basic-auth paths are
+//! covered elsewhere and have no bearing on actor-key derivation.
+//!
+//! If `require_bearer` adds a new ActorContext field that affects the
+//! per-actor key, the replica below must mirror it. The
+//! `users.username -> ActorContext.user` invariant is the load-bearing
+//! one: an autoscope regression that fed `user.id` (UUID) instead of
+//! `user.username` into the actor key would split the per-actor map
+//! across rungs, which is exactly what this test pins.
+
+use ai_memory_core::{ActiveProject, ActiveProjectMode, ActorContext, NewUser, Tier};
+use ai_memory_hooks::{
+ DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore, hook_router,
+};
+use ai_memory_mcp::AiMemoryServer;
+use ai_memory_store::{Store, TokenPepper, generate_token, hash_token};
+use ai_memory_wiki::Wiki;
+use axum::Router;
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
+use serde_json::json;
+use std::sync::Arc;
+use std::time::Duration;
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+struct SeededUser {
+ /// Kept for debugging panics and future assertions on the
+ /// `ActorContext.user` path; the tests below probe by token, but
+ /// retaining the username avoids re-deriving it from the index.
+ #[allow(dead_code)]
+ username: String,
+ token: String,
+ project_index: usize,
+}
+
+struct MultiUserHarness {
+ router: Router,
+ _store: Store,
+ _tmp: TempDir,
+ users: Vec<SeededUser>,
+}
+
+impl MultiUserHarness {
+ /// Build a server with multi-user auth enabled, seed N users (each
+ /// owning a distinct seeded project), and assemble the production-
+ /// shaped Router (Bearer middleware → /mcp + /hook).
+ async fn build(num_users: usize) -> Self {
+ let tmp = TempDir::new().expect("tempdir");
+ let store = Store::open(tmp.path()).expect("store");
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .expect("ws");
+ let baked = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .expect("baked");
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).expect("wiki");
+
+ // Seed N users with hashed tokens + their own project + marker page.
+ let pepper = TokenPepper::new("test-pepper-multiuser-1234567890abcdef");
+ let mut users = Vec::with_capacity(num_users);
+ for i in 1..=num_users {
+ let username = format!("user{i}");
+ let raw_token = generate_token().expect("gen token");
+ let hash = hash_token(&raw_token, &pepper);
+ store
+ .writer
+ .create_user(
+ NewUser {
+ username: username.clone(),
+ name: Some(format!("User {i}")),
+ email: Some(format!("user{i}@example.com")),
+ },
+ hash,
+ )
+ .await
+ .expect("create user");
+
+ // Each user "owns" a uniquely-named project + marker page; the
+ // FTS5 tokenizer treats `_` as a TOKEN character, so the body
+ // uses space-separated alphabetic words to stay searchable.
+ let proj = store
+ .writer
+ .get_or_create_project(ws, format!("user{i}-proj"), None)
+ .await
+ .expect("seed proj");
+ store
+ .writer
+ .upsert_page(ai_memory_core::NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: ai_memory_core::PagePath::new("marker.md").expect("path"),
+ title: format!("Marker for user {i}"),
+ body: format!("multistream {tag}", tag = number_word(i)),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ author_id: None,
+ })
+ .await
+ .expect("seed page");
+
+ users.push(SeededUser {
+ username,
+ token: raw_token,
+ project_index: i,
+ });
+ }
+
+ let active_project = ActiveProject::with_config(
+ ActiveProjectMode::PerActor,
+ Duration::from_secs(60),
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ );
+
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, baked)
+ .with_wiki(wiki.clone())
+ .with_active_project(active_project.clone());
+
+ let mcp_service = StreamableHttpService::new(
+ move || Ok(server.clone()),
+ LocalSessionManager::default().into(),
+ StreamableHttpServerConfig::default()
+ .with_stateful_mode(false)
+ .with_json_response(true),
+ );
+
+ let project_cache: ai_memory_hooks::ProjectCache =
+ Arc::new(tokio::sync::Mutex::new(ProjectCacheStore::default()));
+ let hooks = hook_router(HookState {
+ workspace_id: ws,
+ project_id: baked,
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki: wiki.clone(),
+ consolidator: None,
+ sanitizer: ai_memory_core::Sanitizer::default(),
+ project_cache,
+ active_project: active_project.clone(),
+ ingest_semaphore: Arc::new(tokio::sync::Semaphore::new(
+ DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,
+ )),
+ consolidate_on_session_end: false,
+ });
+
+ // Production-equivalent Bearer middleware. Pepper + reader are
+ // shared via a small Arc state. The implementation mirrors the
+ // Bearer-only branch of `ai_memory_cli::auth::require_bearer`:
+ // valid token → ActorContext { user: Some(username), name, email }.
+ let auth_state = Arc::new(BearerAuthState {
+ pepper,
+ reader: store.reader.clone(),
+ });
+ let router = Router::new()
+ .nest_service("/mcp", mcp_service)
+ .merge(hooks)
+ .layer(axum::middleware::from_fn_with_state(
+ auth_state,
+ bearer_lookup,
+ ));
+
+ MultiUserHarness {
+ router,
+ _store: store,
+ _tmp: tmp,
+ users,
+ }
+ }
+}
+
+#[derive(Clone)]
+struct BearerAuthState {
+ pepper: TokenPepper,
+ reader: ai_memory_store::ReaderPool,
+}
+
+async fn bearer_lookup(
+ axum::extract::State(state): axum::extract::State<Arc<BearerAuthState>>,
+ mut req: Request<Body>,
+ 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).
+ let bearer = req
+ .headers()
+ .get("authorization")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|s| s.strip_prefix("Bearer "))
+ .map(str::trim)
+ .filter(|s| !s.is_empty());
+
+ if let Some(token) = bearer {
+ let hash = hash_token(token, &state.pepper);
+ match state.reader.find_active_user_by_token_hash(hash).await {
+ Ok(Some(user)) => {
+ // Mirror require_bearer:
+ // ActorContext.user = user.username
+ // ActorContext.name = user.name
+ // ActorContext.email = user.email
+ req.extensions_mut().insert(ActorContext {
+ user: Some(user.username.clone()),
+ name: user.name.clone(),
+ email: user.email.clone(),
+ ..ActorContext::default()
+ });
+ req.extensions_mut().insert(user.id);
+ }
+ _ => {
+ req.extensions_mut().insert(ActorContext::anonymous());
+ }
+ }
+ } else {
+ req.extensions_mut().insert(ActorContext::anonymous());
+ }
+ next.run(req).await
+}
+
+fn number_word(i: usize) -> &'static str {
+ match i {
+ 1 => "alphaone",
+ 2 => "alphatwo",
+ 3 => "alphathree",
+ 4 => "alphafour",
+ _ => panic!("number_word: 1..=4 only"),
+ }
+}
+
+fn hook_request(token: &str, session_id: &str, project_name: &str) -> Request<Body> {
+ let body = json!({
+ "event": "session-start",
+ "session_id": session_id,
+ "cwd": format!("/tmp/aim-test/{project_name}"),
+ });
+ Request::builder()
+ .method("POST")
+ .uri(format!(
+ "/hook?event=session-start&agent=claude-code&project={project_name}"
+ ))
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {token}"))
+ .body(Body::from(body.to_string()))
+ .expect("hook req")
+}
+
+fn mcp_query_request(token: &str, session_id: &str) -> Request<Body> {
+ let body = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": {
+ "name": "memory_query",
+ "arguments": { "query": "multistream", "limit": 20 }
+ }
+ });
+ Request::builder()
+ .method("POST")
+ .uri("/mcp")
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ .header("accept", "application/json, text/event-stream")
+ .header("authorization", format!("Bearer {token}"))
+ .header("x-memory-actor-session-id", session_id)
+ .body(Body::from(body.to_string()))
+ .expect("mcp req")
+}
+
+async fn response_text(resp: axum::response::Response) -> String {
+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)
+ .await
+ .expect("body bytes");
+ String::from_utf8(bytes.to_vec()).expect("utf8")
+}
+
+fn tool_text(body: &str) -> String {
+ let v: serde_json::Value =
+ serde_json::from_str(body).unwrap_or_else(|e| panic!("non-JSON: {body}\nerr: {e}"));
+ if let Some(err) = v.get("error") {
+ panic!("JSON-RPC error: {err}\nfull: {body}");
+ }
+ v.pointer("/result/content")
+ .and_then(|c| c.as_array())
+ .unwrap_or_else(|| panic!("missing result.content: {body}"))
+ .iter()
+ .filter_map(|i| i.get("text").and_then(|t| t.as_str()))
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+async fn fire_hook_and_settle(router: &Router, token: &str, session_id: &str, proj: &str) {
+ let resp = router
+ .clone()
+ .oneshot(hook_request(token, session_id, proj))
+ .await
+ .expect("hook oneshot");
+ assert_eq!(resp.status(), StatusCode::ACCEPTED, "hook must accept");
+ let _ = response_text(resp).await;
+ for _ in 0..20 {
+ tokio::task::yield_now().await;
+ }
+ tokio::time::sleep(Duration::from_millis(15)).await;
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Each user, authenticated by their real Bearer token, hooks their own
+// project; concurrent reads must resolve into their OWN slot, never any
+// sibling user's, even though they all share the same `session_id` value.
+// ────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn per_actor_isolates_real_bearer_users() {
+ let h = MultiUserHarness::build(3).await;
+
+ // Intentionally shared session id across all users: the per_actor map
+ // must key by `(user, session)`, so even with collisions on the
+ // session-id half, the user-half from the auth middleware partitions
+ // them correctly. If a regression dropped `user` from the actor key,
+ // ALL three users would collapse into one slot and the assertion
+ // below would fail.
+ let shared_sess = "shared-session-across-users";
+ for u in &h.users {
+ let proj = format!("user{}-proj", u.project_index);
+ fire_hook_and_settle(&h.router, &u.token, shared_sess, &proj).await;
+ }
+
+ // Concurrent reads, one per user, with the shared session id.
+ let mut handles = Vec::new();
+ for u in &h.users {
+ let router = h.router.clone();
+ let token = u.token.clone();
+ let i = u.project_index;
+ handles.push(tokio::spawn(async move {
+ let resp = router
+ .oneshot(mcp_query_request(&token, shared_sess))
+ .await
+ .expect("mcp oneshot");
+ assert_eq!(resp.status(), StatusCode::OK, "user{i} read status");
+ let body = response_text(resp).await;
+ (i, tool_text(&body))
+ }));
+ }
+
+ for hd in handles {
+ let (i, text) = hd.await.expect("join");
+ let own = number_word(i);
+ assert!(
+ text.contains(own),
+ "user{i} did NOT see its own marker. Expected {own:?}:\n{text}"
+ );
+ for j in 1..=3 {
+ if j == i {
+ continue;
+ }
+ let foreign = number_word(j);
+ assert!(
+ !text.contains(foreign),
+ "user{i} leaked into user{j}'s project. Saw {foreign:?}:\n{text}"
+ );
+ }
+ }
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// 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.
+// ────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn anonymous_request_does_not_inherit_user_slot() {
+ let h = MultiUserHarness::build(2).await;
+ let sess = "anon-vs-user1";
+
+ let user1 = &h.users[0]; // owns user1-proj (alphaone marker)
+
+ // user1 publishes their per_actor slot.
+ fire_hook_and_settle(&h.router, &user1.token, sess, "user1-proj").await;
+
+ // 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.
+ let resp = h
+ .router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/mcp")
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ .header("accept", "application/json, text/event-stream")
+ .header("x-memory-actor-session-id", sess)
+ // NO authorization header.
+ .body(Body::from(
+ json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": {
+ "name": "memory_query",
+ "arguments": { "query": "multistream", "limit": 20 }
+ }
+ })
+ .to_string(),
+ ))
+ .expect("anon mcp req"),
+ )
+ .await
+ .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);
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// A request with an unknown Bearer (typo, revoked token) must also fall
+// through to anonymous, not get spoofed into another user's slot. This
+// pins the rung-2 lookup-miss path.
+// ────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn unknown_bearer_does_not_match_any_user_slot() {
+ let h = MultiUserHarness::build(2).await;
+ let sess = "unknown-bearer-probe";
+ let user1 = &h.users[0];
+
+ fire_hook_and_settle(&h.router, &user1.token, sess, "user1-proj").await;
+
+ // Forged Bearer of the right shape but unknown to the users table.
+ let forged = "deadbeef".repeat(8);
+ let resp = h
+ .router
+ .clone()
+ .oneshot(mcp_query_request(&forged, sess))
+ .await
+ .expect("forged mcp oneshot");
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = response_text(resp).await;
+ 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;
+}
diff --git a/crates/ai-memory-mcp/tests/autoscope_stress.rs b/crates/ai-memory-mcp/tests/autoscope_stress.rs
new file mode 100644
index 00000000..5b0571c6
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/autoscope_stress.rs
@@ -0,0 +1,1081 @@
+//! Multi-actor concurrency stress tests for the per-session / per-actor
+//! [`ActiveProject`] isolation modes.
+//!
+//! Unit tests in `ai_memory_core::active_project` cover the map's
+//! single-threaded contract. These tests exercise the *production wiring*
+//! — `/hook` → `process_envelope` → `set_for(actor)` interleaved with
+//! `/mcp tools/call` → `actor_key_from_parts` → `get_for(actor)` — under
+//! genuine `tokio::spawn` concurrency, so a race in the mutex, the LRU
+//! eviction order, or the actor-key extraction surfaces here rather than
+//! in prod.
+//!
+//! The router is assembled in-process (axum `Router` + tower
+//! `ServiceExt::oneshot`), the auth middleware is replaced by a fake that
+//! injects `ActorContext` from `x-test-actor-user` / `x-test-actor-session-id`
+//! request headers — exactly the field the production middleware fills.
+//! Session id is also accepted via the production `x-memory-actor-session-id`
+//! header on /mcp so the "header is cache key, not credential" scenario can
+//! exercise the same fallback the real server walks.
+
+use ai_memory_core::{ActiveProject, ActiveProjectMode, ActorContext};
+use ai_memory_hooks::{
+ DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore, hook_router,
+};
+use ai_memory_mcp::AiMemoryServer;
+use ai_memory_store::Store;
+use ai_memory_wiki::Wiki;
+use axum::Router;
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
+use serde_json::json;
+use std::sync::Arc;
+use std::time::Duration;
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+/// All scenarios share a server with this many seeded projects, each with a
+/// `marker.md` page whose body uniquely identifies the project. Reads after a
+/// hook event must find the marker for the project the hook published — not
+/// any other.
+const SEEDED_PROJECTS: usize = 8;
+
+/// English number words, indexed from 1 — used as space-separated FTS5
+/// tokens so we can both find any marker via the shared `markerstream`
+/// word and tell which project a given hit came from. Indexed 1..=8.
+fn number_word(i: usize) -> &'static str {
+ match i {
+ 1 => "alphaone",
+ 2 => "alphatwo",
+ 3 => "alphathree",
+ 4 => "alphafour",
+ 5 => "alphafive",
+ 6 => "alphasix",
+ 7 => "alphaseven",
+ 8 => "alphaeight",
+ _ => panic!("number_word: only 1..=8 supported, got {i}"),
+ }
+}
+
+/// Per-actor map config used by most scenarios — large enough not to evict
+/// under normal concurrency, small enough that the burst test can overflow it.
+const TEST_TTL: Duration = Duration::from_secs(60);
+
+struct Harness {
+ router: Router,
+ active_project: ActiveProject,
+ _store: Store,
+ _wiki: Wiki,
+ _tmp: TempDir,
+}
+
+impl Harness {
+ /// Build a complete in-process server: store + wiki + N seeded projects
+ /// + MCP service + hook router + actor-injecting fake-auth middleware.
+ async fn build(mode: ActiveProjectMode, ttl: Duration, max_entries: usize) -> Self {
+ let tmp = TempDir::new().expect("tempdir");
+ let store = Store::open(tmp.path()).expect("store");
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .expect("ws");
+ // Baked default project; hook events that set their own cwd take
+ // precedence via the per-actor map.
+ let baked_proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .expect("baked proj");
+
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).expect("wiki");
+
+ // Seed N distinct projects, each with a unique marker page so MCP
+ // reads can verify they resolved into the right active_project.
+ //
+ // The FTS5 tokenizer is `unicode61 ... tokenchars '/_-'`, so
+ // `_` is part of a token (NOT a separator). A body like
+ // "PROJ_1_BODY" tokenizes as a single token and a `PROJ` query
+ // misses it. Use space-separated words instead: a shared word
+ // "markerstream" that every marker carries, plus a per-project
+ // unique english-number word so we can both find any marker and
+ // tell which project it came from.
+ for i in 1..=SEEDED_PROJECTS {
+ let proj = store
+ .writer
+ .get_or_create_project(ws, format!("proj-{i}"), None)
+ .await
+ .expect("seed proj");
+ store
+ .writer
+ .upsert_page(ai_memory_core::NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: ai_memory_core::PagePath::new("marker.md").expect("path"),
+ title: format!("Marker {i}"),
+ body: format!("markerstream {tag}", tag = number_word(i)),
+ tier: ai_memory_core::Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ author_id: None,
+ })
+ .await
+ .expect("seed page");
+ }
+
+ let active_project = ActiveProject::with_config(mode, ttl, max_entries);
+
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, baked_proj)
+ .with_wiki(wiki.clone())
+ .with_active_project(active_project.clone());
+
+ let mcp_service = StreamableHttpService::new(
+ move || Ok(server.clone()),
+ LocalSessionManager::default().into(),
+ StreamableHttpServerConfig::default()
+ .with_stateful_mode(false)
+ .with_json_response(true),
+ );
+
+ let project_cache: ai_memory_hooks::ProjectCache =
+ Arc::new(tokio::sync::Mutex::new(ProjectCacheStore::default()));
+ let hooks = hook_router(HookState {
+ workspace_id: ws,
+ project_id: baked_proj,
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki: wiki.clone(),
+ consolidator: None,
+ sanitizer: ai_memory_core::Sanitizer::default(),
+ project_cache,
+ active_project: active_project.clone(),
+ ingest_semaphore: Arc::new(tokio::sync::Semaphore::new(
+ DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,
+ )),
+ consolidate_on_session_end: false,
+ });
+
+ let router = Router::new()
+ .nest_service("/mcp", mcp_service)
+ .merge(hooks)
+ // Fake auth: read test headers, inject ActorContext exactly the
+ // way the production auth middleware (rung 1 / rung 2) does.
+ // This is the seam under test — the engine's per-actor map keys
+ // off the *extension*, never the raw header value, for `user`.
+ .layer(axum::middleware::from_fn(inject_actor_from_test_headers));
+
+ Self {
+ router,
+ active_project,
+ _store: store,
+ _wiki: wiki,
+ _tmp: tmp,
+ }
+ }
+}
+
+/// Test-only middleware that mimics production auth: read `x-test-actor-user`
+/// and `x-test-actor-session-id`, inject them as an [`ActorContext`] extension.
+async fn inject_actor_from_test_headers(
+ mut req: Request<Body>,
+ next: axum::middleware::Next,
+) -> axum::response::Response {
+ let user = req
+ .headers()
+ .get("x-test-actor-user")
+ .and_then(|v| v.to_str().ok())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ let session_id = req
+ .headers()
+ .get("x-test-actor-session-id")
+ .and_then(|v| v.to_str().ok())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ if user.is_some() || session_id.is_some() {
+ req.extensions_mut().insert(ActorContext {
+ user,
+ session_id,
+ ..ActorContext::default()
+ });
+ }
+ next.run(req).await
+}
+
+/// Build a `POST /hook` request publishing `cwd → proj-{i}` for the given
+/// `session_id` (and optional `user` for per-actor mode). The body
+/// `session_id` field is what the engine actually keys the map by — we mirror
+/// it in the header so the MCP read in the same actor's lane lines up.
+fn hook_request(user: Option<&str>, session_id: &str, project_index: usize) -> Request<Body> {
+ let body = json!({
+ "event": "session-start",
+ "session_id": session_id,
+ "cwd": format!("/tmp/aim-test/proj-{project_index}"),
+ });
+ let mut builder = Request::builder()
+ .method("POST")
+ .uri("/hook?event=session-start&agent=claude-code&project=proj-{i}".replace(
+ "{i}",
+ &project_index.to_string(),
+ ))
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ .header("x-test-actor-session-id", session_id);
+ if let Some(u) = user {
+ builder = builder.header("x-test-actor-user", u);
+ }
+ builder.body(Body::from(body.to_string())).expect("hook req")
+}
+
+/// Build a `POST /mcp` tools/call request for `memory_query` matching the
+/// shared `markerstream` token every seeded marker carries. The
+/// assertion downstream is on WHICH marker (and therefore which
+/// project's unique `alpha*` word) the per-actor scope resolves to.
+fn mcp_query_request(user: Option<&str>, session_id: Option<&str>) -> Request<Body> {
+ let body = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": {
+ "name": "memory_query",
+ "arguments": { "query": "markerstream", "limit": 20 }
+ }
+ });
+ build_mcp_request(body.to_string(), user, session_id)
+}
+
+/// Build a `POST /mcp` tools/call request for `memory_write_page`. The page
+/// path is unique per call so concurrent writes don't collide on the same
+/// row; the per-actor map decides which *project* the write lands in.
+fn mcp_write_request(
+ user: Option<&str>,
+ session_id: Option<&str>,
+ page_path: &str,
+ body_text: &str,
+) -> Request<Body> {
+ let body = json!({
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": {
+ "name": "memory_write_page",
+ "arguments": {
+ "path": page_path,
+ "body": format!("# Title\n\n{body_text}"),
+ }
+ }
+ });
+ build_mcp_request(body.to_string(), user, session_id)
+}
+
+fn build_mcp_request(
+ body: String,
+ user: Option<&str>,
+ session_id: Option<&str>,
+) -> Request<Body> {
+ let mut builder = Request::builder()
+ .method("POST")
+ .uri("/mcp")
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ .header("accept", "application/json, text/event-stream");
+ if let Some(u) = user {
+ builder = builder.header("x-test-actor-user", u);
+ }
+ if let Some(s) = session_id {
+ // Send BOTH the test-only header (which the fake middleware lifts
+ // into the ActorContext extension) AND the production
+ // `x-memory-actor-session-id` header (which the MCP server reads
+ // directly from raw headers as the rung-4 fallback). Setting both
+ // mirrors what an authenticated browser session would look like
+ // and avoids depending on which one the server prefers.
+ builder = builder
+ .header("x-test-actor-session-id", s)
+ .header("x-memory-actor-session-id", s);
+ }
+ builder.body(Body::from(body)).expect("mcp req")
+}
+
+async fn response_body_text(resp: axum::response::Response) -> String {
+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)
+ .await
+ .expect("body bytes");
+ String::from_utf8(bytes.to_vec()).expect("utf8 body")
+}
+
+/// Parse a JSON-RPC tools/call response and return the joined text of all
+/// `content[]` text items. Panics with the raw body on protocol errors so
+/// failures are debuggable.
+fn extract_tool_text(body: &str) -> String {
+ let v: serde_json::Value = serde_json::from_str(body)
+ .unwrap_or_else(|e| panic!("non-JSON response: {body}\nerr: {e}"));
+ if let Some(err) = v.get("error") {
+ panic!("JSON-RPC error: {err}\nfull: {body}");
+ }
+ let content = v
+ .pointer("/result/content")
+ .and_then(|c| c.as_array())
+ .unwrap_or_else(|| panic!("missing result.content: {body}"));
+ content
+ .iter()
+ .filter_map(|item| item.get("text").and_then(|t| t.as_str()))
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+/// Fire a hook synchronously and wait for the `/hook` 202 ACCEPTED + a
+/// brief settle so the spawned `process_envelope` task lands its write to
+/// the active-project map before the caller continues. This matches the
+/// production "hooks are fire-and-forget" contract — tests need an explicit
+/// barrier because they assert on what the map looks like immediately after.
+async fn fire_hook_and_settle(
+ router: &Router,
+ user: Option<&str>,
+ session_id: &str,
+ project_index: usize,
+) {
+ let resp = router
+ .clone()
+ .oneshot(hook_request(user, session_id, project_index))
+ .await
+ .expect("hook oneshot");
+ assert_eq!(resp.status(), StatusCode::ACCEPTED, "hook must accept");
+ // Drain the response body before settling so the connection releases.
+ let _ = response_body_text(resp).await;
+ // `process_envelope` is `tokio::spawn`-ed; give it a generous window
+ // to land the active_project write on a loaded machine. Empirically a
+ // single yield is enough; we go higher for headroom in CI.
+ for _ in 0..20 {
+ tokio::task::yield_now().await;
+ }
+ tokio::time::sleep(Duration::from_millis(15)).await;
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Scenario 1 — per_session isolates concurrent reads after one hook each.
+// ────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn per_session_isolates_concurrent_reads_after_hook() {
+ let h = Harness::build(
+ ActiveProjectMode::PerSession,
+ TEST_TTL,
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ )
+ .await;
+
+ // Each session i sets its active project to proj-i via one hook event.
+ for i in 1..=SEEDED_PROJECTS {
+ fire_hook_and_settle(&h.router, None, &format!("sess-{i}"), i).await;
+ }
+
+ // Now fan out: each session does M parallel reads. Every read must
+ // resolve to its own project's marker, not some neighbour's.
+ const READS_PER_SESSION: usize = 20;
+ let mut handles = Vec::new();
+ for i in 1..=SEEDED_PROJECTS {
+ for _ in 0..READS_PER_SESSION {
+ let router = h.router.clone();
+ let session = format!("sess-{i}");
+ handles.push(tokio::spawn(async move {
+ let resp = router
+ .oneshot(mcp_query_request(None, Some(&session)))
+ .await
+ .expect("mcp oneshot");
+ assert_eq!(resp.status(), StatusCode::OK, "session {i} read status");
+ let body = response_body_text(resp).await;
+ let text = extract_tool_text(&body);
+ (i, text)
+ }));
+ }
+ }
+
+ for h in handles {
+ let (i, text) = h.await.expect("join");
+ let own = number_word(i);
+ assert!(
+ text.contains(own),
+ "session {i} did NOT see its own marker. Expected {own:?} in result text:\n{text}"
+ );
+ // Every other project's marker must be ABSENT — that's the
+ // isolation guarantee. Reads must not bleed across sessions.
+ for j in 1..=SEEDED_PROJECTS {
+ if j == i {
+ continue;
+ }
+ let foreign = number_word(j);
+ assert!(
+ !text.contains(foreign),
+ "session {i} leaked into sibling proj-{j}.\n saw: {foreign:?}\n in: {text}"
+ );
+ }
+ }
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Scenario 2 — per_session isolates concurrent writes.
+// ────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn per_session_isolates_concurrent_writes() {
+ let h = Harness::build(
+ ActiveProjectMode::PerSession,
+ TEST_TTL,
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ )
+ .await;
+
+ for i in 1..=SEEDED_PROJECTS {
+ fire_hook_and_settle(&h.router, None, &format!("sess-{i}"), i).await;
+ }
+
+ // Each session writes a uniquely-named page concurrently.
+ let mut write_handles = Vec::new();
+ for i in 1..=SEEDED_PROJECTS {
+ let router = h.router.clone();
+ let session = format!("sess-{i}");
+ let page_path = format!("writes/from-sess-{i}.md");
+ // Underscore-free body word so the FTS5 tokenizer (which treats
+ // `_` as a TOKEN character, not a separator) keeps the marker
+ // searchable. Each session gets a unique english-number-tagged
+ // word so the round-trip read can distinguish own vs leaked.
+ let body = format!("writefromsess{tag}", tag = number_word(i));
+ write_handles.push(tokio::spawn(async move {
+ let resp = router
+ .oneshot(mcp_write_request(None, Some(&session), &page_path, &body))
+ .await
+ .expect("mcp write oneshot");
+ assert_eq!(resp.status(), StatusCode::OK, "write {i} status");
+ let body = response_body_text(resp).await;
+ // Ensure the call did NOT error; we don't need to parse the
+ // detailed result here — the round-trip read below is the
+ // real assertion.
+ let _ = extract_tool_text(&body);
+ i
+ }));
+ }
+ for w in write_handles {
+ w.await.expect("write join");
+ }
+
+ // Round-trip: each session reads back its own page. Because the per-
+ // session active_project still points at proj-i, memory_query for
+ // "WRITE_FROM_SESS_" must find ONLY the row that landed in proj-i.
+ let mut read_handles = Vec::new();
+ for i in 1..=SEEDED_PROJECTS {
+ let router = h.router.clone();
+ let session = format!("sess-{i}");
+ read_handles.push(tokio::spawn(async move {
+ let body_q = json!({
+ "jsonrpc": "2.0",
+ "id": 3,
+ "method": "tools/call",
+ "params": {
+ "name": "memory_query",
+ "arguments": { "query": "writefromsess*", "limit": 20 }
+ }
+ });
+ let resp = router
+ .oneshot(build_mcp_request(body_q.to_string(), None, Some(&session)))
+ .await
+ .expect("mcp read oneshot");
+ let body = response_body_text(resp).await;
+ (i, extract_tool_text(&body))
+ }));
+ }
+
+ for r in read_handles {
+ let (i, text) = r.await.expect("read join");
+ let own = format!("writefromsess{tag}", tag = number_word(i));
+ assert!(
+ text.contains(&own),
+ "sess-{i} write did not round-trip in its own scope:\n{text}"
+ );
+ // Strict isolation: no other session's payload should leak. The
+ // per-session map keeps each write in its own project_id, so a
+ // memory_query scoped by the same session cannot see siblings.
+ for j in 1..=SEEDED_PROJECTS {
+ if j == i {
+ continue;
+ }
+ let foreign = format!("writefromsess{tag}", tag = number_word(j));
+ assert!(
+ !text.contains(&foreign),
+ "sess-{i} read leaked write from sess-{j}:\n{text}"
+ );
+ }
+ }
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Scenario 3 — per_actor: users sharing a session_id are still isolated.
+// ────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn per_actor_isolates_users_sharing_session_id() {
+ let h = Harness::build(
+ ActiveProjectMode::PerActor,
+ TEST_TTL,
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ )
+ .await;
+
+ // Alice and Bob send hooks with the SAME `session_id` but DIFFERENT
+ // users. In `per_actor` mode they must land in distinct map slots
+ // because the key is `(user, session_id)`, not `session_id` alone.
+ let shared_sess = "shared-session-x";
+ fire_hook_and_settle(&h.router, Some("alice"), shared_sess, 1).await;
+ fire_hook_and_settle(&h.router, Some("bob"), shared_sess, 5).await;
+
+ // Alice reads — must see proj-1's marker, never proj-5's.
+ let resp = h
+ .router
+ .clone()
+ .oneshot(mcp_query_request(Some("alice"), Some(shared_sess)))
+ .await
+ .expect("alice read");
+ let alice_text = extract_tool_text(&response_body_text(resp).await);
+ assert!(
+ alice_text.contains(number_word(1)),
+ "alice did not see her own proj-1 marker:\n{alice_text}"
+ );
+ assert!(
+ !alice_text.contains(number_word(5)),
+ "alice leaked into bob's proj-5:\n{alice_text}"
+ );
+
+ // Bob reads — must see proj-5's marker, never proj-1's.
+ let resp = h
+ .router
+ .clone()
+ .oneshot(mcp_query_request(Some("bob"), Some(shared_sess)))
+ .await
+ .expect("bob read");
+ let bob_text = extract_tool_text(&response_body_text(resp).await);
+ assert!(
+ bob_text.contains(number_word(5)),
+ "bob did not see his own proj-5 marker:\n{bob_text}"
+ );
+ assert!(
+ !bob_text.contains(number_word(1)),
+ "bob leaked into alice's proj-1:\n{bob_text}"
+ );
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Scenario 4 — burst above max_entries: engine survives, no panic / no 5xx.
+// ────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn burst_above_max_entries_does_not_corrupt() {
+ // max_entries deliberately tiny so the burst is sure to exceed it.
+ let h = Harness::build(ActiveProjectMode::PerSession, TEST_TTL, 8).await;
+
+ const BURST_SIZE: usize = 64;
+
+ // Fan out: BURST_SIZE distinct sessions all hooking in parallel. The
+ // map can hold only 8, so the LRU eviction path is under contention.
+ let mut hook_handles = Vec::new();
+ for i in 0..BURST_SIZE {
+ let router = h.router.clone();
+ let sess = format!("burst-{i}");
+ // Cycle through the seeded projects so every hook resolves a real
+ // (workspace, project) pair — the eviction code shouldn't care
+ // about WHICH ids, just that inserting under contention doesn't
+ // tear the map.
+ let proj_idx = (i % SEEDED_PROJECTS) + 1;
+ hook_handles.push(tokio::spawn(async move {
+ let resp = router
+ .oneshot(hook_request(None, &sess, proj_idx))
+ .await
+ .expect("burst hook oneshot");
+ assert_eq!(
+ resp.status(),
+ StatusCode::ACCEPTED,
+ "burst hook {i} must accept under load"
+ );
+ }));
+ }
+ for h in hook_handles {
+ h.await.expect("burst hook join");
+ }
+
+ // Settle: every spawned process_envelope must drain.
+ for _ in 0..50 {
+ tokio::task::yield_now().await;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+
+ // Now BURST_SIZE parallel reads. Every read must return a JSON-RPC
+ // 200 — no panic, no 500. The CONTENT may be any of the projects
+ // we hooked (LRU may have evicted), but the *server* must never
+ // tear.
+ let mut read_handles = Vec::new();
+ for i in 0..BURST_SIZE {
+ let router = h.router.clone();
+ let sess = format!("burst-{i}");
+ read_handles.push(tokio::spawn(async move {
+ let resp = router
+ .oneshot(mcp_query_request(None, Some(&sess)))
+ .await
+ .expect("burst read oneshot");
+ assert_eq!(
+ resp.status(),
+ StatusCode::OK,
+ "burst read {i} status must be 200"
+ );
+ let body = response_body_text(resp).await;
+ // Any JSON-RPC response that is NOT an error is acceptable;
+ // we just need to confirm the server didn't crash mid-burst.
+ let v: serde_json::Value = serde_json::from_str(&body)
+ .unwrap_or_else(|e| panic!("non-JSON burst read {i}: {body}\nerr: {e}"));
+ assert!(
+ v.get("error").is_none(),
+ "burst read {i} produced JSON-RPC error: {body}"
+ );
+ }));
+ }
+ for h in read_handles {
+ h.await.expect("burst read join");
+ }
+
+ // Invariant check on the map itself: the LRU cap must be enforced
+ // even after the burst. We can't easily count entries from outside
+ // (no public accessor), but we can verify the single-slot fallback
+ // still resolves — that's the graceful-degradation contract.
+ assert!(
+ h.active_project.get().is_some(),
+ "after a burst, the single-slot fallback must still be populated"
+ );
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Scenario 5 — TTL eviction under concurrent insertion (no zombie reads).
+// ────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn ttl_eviction_under_concurrent_insertion() {
+ // Short TTL so the test runs in seconds; large max so eviction is
+ // strictly TTL-driven, not capacity-driven.
+ let h = Harness::build(
+ ActiveProjectMode::PerSession,
+ Duration::from_millis(150),
+ 4096,
+ )
+ .await;
+
+ // Phase 1: insert N distinct sessions, read them back immediately —
+ // each must see its own project.
+ const N: usize = 12;
+ for i in 0..N {
+ fire_hook_and_settle(&h.router, None, &format!("ttl-{i}"), (i % SEEDED_PROJECTS) + 1).await;
+ }
+
+ // Phase 2: wait past the TTL.
+ tokio::time::sleep(Duration::from_millis(250)).await;
+
+ // 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.
+ let mut handles = Vec::new();
+ for i in 0..N {
+ let router = h.router.clone();
+ let sess = format!("ttl-{i}");
+ handles.push(tokio::spawn(async move {
+ let resp = router
+ .oneshot(mcp_query_request(None, Some(&sess)))
+ .await
+ .expect("ttl read oneshot");
+ assert_eq!(
+ resp.status(),
+ StatusCode::OK,
+ "post-TTL read {i} status must be 200"
+ );
+ let body = response_body_text(resp).await;
+ // No JSON-RPC error.
+ let _ = extract_tool_text(&body);
+ }));
+ }
+ for h in handles {
+ h.await.expect("ttl read join");
+ }
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Scenario 6 — header session_id is a cache key, NOT a credential.
+// ────────────────────────────────────────────────────────────────────────────
+//
+// In per_actor mode, the *user* component of the actor key is read ONLY from
+// the auth middleware's [`ActorContext`] extension — never from a client-
+// supplied header. So if Bob sends the `x-memory-actor-session-id` header
+// with Alice's session id, the engine still keys by `(Bob, alice-session)`
+// — a fresh slot, not Alice's slot. This is the documented trust boundary;
+// pin it explicitly so a refactor can't quietly downgrade `user` to the
+// header path.
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn header_session_id_is_cache_key_not_credential() {
+ let h = Harness::build(
+ ActiveProjectMode::PerActor,
+ TEST_TTL,
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ )
+ .await;
+
+ // Alice publishes her active project (proj-2) via hook.
+ fire_hook_and_settle(&h.router, Some("alice"), "alice-session", 2).await;
+
+ // Bob attempts to escalate: he sends an MCP read with Alice's session
+ // id in the header. The MIDDLEWARE-injected `user` (from his own
+ // `x-test-actor-user`) is "bob"; the *session_id* is Alice's. Per-
+ // actor key becomes `(bob, alice-session)` — distinct from
+ // `(alice, alice-session)`, so Bob's read must NOT resolve into
+ // proj-2.
+ let resp = h
+ .router
+ .clone()
+ .oneshot(mcp_query_request(Some("bob"), Some("alice-session")))
+ .await
+ .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.
+ fire_hook_and_settle(&h.router, Some("bob"), "bob-own-session", 7).await;
+ let resp = h
+ .router
+ .clone()
+ .oneshot(mcp_query_request(Some("bob"), Some("alice-session")))
+ .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.
+ 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}"
+ );
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Scenario 7 — sustained-rate stress.
+//
+// One-shot bursts (scenarios 1–6) prove the map handles a *spike* of
+// concurrent ops; this scenario proves it handles a *sustained flow*
+// over time without:
+// - latency creeping up (lock contention growing unboundedly),
+// - cross-actor reads slipping through under steady-state churn,
+// - dropped /hook 202s under continuous load.
+//
+// Duration is short enough for CI (~5s) but long enough to dwarf the
+// per-op latency, so a flapping invariant would surface here even with
+// only thousands of cycles. Crank `STRESS_DURATION_SECS` env var to
+// repro a flake locally over a longer window.
+// ────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn sustained_per_session_isolation_holds_under_continuous_traffic() {
+ let h = Harness::build(
+ ActiveProjectMode::PerSession,
+ TEST_TTL,
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ )
+ .await;
+
+ // 4 distinct sessions; each one owns its own seeded project. Every
+ // iteration in the loop re-hooks (set active project) and then
+ // reads, asserting the read returns the OWN marker and NEVER a
+ // sibling's. The hook+read pair is the smallest cycle that touches
+ // every code path in the per-session map: set_for, purge_expired,
+ // enforce_cap, get_for.
+ const SESSIONS: usize = 4;
+ let duration_secs: u64 = std::env::var("STRESS_DURATION_SECS")
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(5);
+ let duration = Duration::from_secs(duration_secs);
+
+ // One driver task per session, all running concurrently. Each
+ // returns its op count + the first cross-actor leak it observed
+ // (None means clean).
+ let mut drivers = Vec::new();
+ for i in 1..=SESSIONS {
+ let router = h.router.clone();
+ let session = format!("sustained-sess-{i}");
+ let deadline = std::time::Instant::now() + duration;
+ drivers.push(tokio::spawn(async move {
+ let mut ops = 0_u64;
+ let mut first_leak: Option<String> = None;
+ while std::time::Instant::now() < deadline {
+ // 1. Hook to pin active project = proj-i for this session.
+ let resp = router
+ .clone()
+ .oneshot(hook_request(None, &session, i))
+ .await
+ .expect("sustained hook oneshot");
+ if resp.status() != StatusCode::ACCEPTED {
+ return (ops, Some(format!("hook returned {}", resp.status())));
+ }
+ let _ = response_body_text(resp).await;
+
+ // 2. Read; assert own marker present, no sibling marker.
+ // Skip a hard barrier sleep between hook and read —
+ // the spawned process_envelope is short, and any
+ // lag just shows up as a temporary cross-actor read
+ // (which IS what we want to catch).
+ tokio::task::yield_now().await;
+ let resp = router
+ .clone()
+ .oneshot(mcp_query_request(None, Some(&session)))
+ .await
+ .expect("sustained read oneshot");
+ if resp.status() != StatusCode::OK {
+ return (ops, Some(format!("read returned {}", resp.status())));
+ }
+ let text = extract_tool_text(&response_body_text(resp).await);
+ let own = number_word(i);
+
+ // OWN marker may take a hook cycle to surface (the hook
+ // is spawned async); ABSENCE of own is acceptable ONLY
+ // if no foreign marker is present either. Foreign marker
+ // present is a HARD leak.
+ for j in 1..=SESSIONS {
+ if j == i {
+ continue;
+ }
+ let foreign = number_word(j);
+ if text.contains(foreign) && first_leak.is_none() {
+ first_leak = Some(format!(
+ "sess-{i} saw sess-{j}'s marker {foreign:?} (own={own}) on op #{ops}:\n{text}"
+ ));
+ break;
+ }
+ }
+ ops += 1;
+ }
+ (ops, first_leak)
+ }));
+ }
+
+ let mut total_ops = 0_u64;
+ let mut leaks = Vec::new();
+ for d in drivers {
+ let (ops, leak) = d.await.expect("driver join");
+ total_ops += ops;
+ if let Some(msg) = leak {
+ leaks.push(msg);
+ }
+ }
+
+ assert!(
+ leaks.is_empty(),
+ "sustained-rate stress observed {} cross-actor leak(s):\n{}",
+ leaks.len(),
+ leaks.join("\n---\n")
+ );
+
+ // Lower bound on completed ops — a generous floor that would only
+ // fail if the engine seized up entirely under load. The real signal
+ // is the leak assertion; this is just a "did we actually exercise
+ // anything" check so a future regression making each op take 5s
+ // doesn't pass a no-op test.
+ let min_ops = (SESSIONS as u64) * 50;
+ assert!(
+ total_ops >= min_ops,
+ "sustained-rate stress completed only {total_ops} ops across {SESSIONS} \
+ sessions in {duration_secs}s (expected >= {min_ops}). \
+ Either the harness is broken or perf regressed catastrophically."
+ );
+ println!("sustained stress: {total_ops} ops in {duration_secs}s ({SESSIONS} sessions)");
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Scenario 8 — real agent payload shapes (Claude / OpenCode / Codex).
+//
+// `HookEnvelope::from_query_and_body` extracts `session_id` and `cwd`
+// from a list of well-known keys. The autoscope per-session map keys
+// on the *raw extracted session_id*, so each agent's wire shape must
+// reach the same map slot when the session id value matches — even if
+// it lives at a different JSON path.
+//
+// The tests below send hand-crafted payloads in the shape each agent
+// CLI actually emits (per `payload.rs::from_query_and_body`'s key
+// list), then assert that a per-session MCP read keyed by the *same
+// session_id value* finds the project the hook published. A
+// regression in either the extractor OR the per-session resolution
+// would break exactly one of these.
+// ────────────────────────────────────────────────────────────────────────────
+
+fn hook_with_raw_body(body: serde_json::Value, project_index: usize, session_id: &str) -> Request<Body> {
+ // Same `project` query arg as the rest of the suite so the hook
+ // resolves directly to the seeded `proj-{i}` row regardless of how
+ // the agent shape encodes cwd.
+ let uri = format!(
+ "/hook?event=session-start&agent=claude-code&project=proj-{project_index}"
+ );
+ Request::builder()
+ .method("POST")
+ .uri(uri)
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ // The MCP read side will need the same session id we want the
+ // hook to extract; mirror it on the header too so the read's
+ // `actor_key_from_parts` lines up with the hook's body extract.
+ .header("x-test-actor-session-id", session_id)
+ .body(Body::from(body.to_string()))
+ .expect("agent-shape hook req")
+}
+
+async fn fire_raw_hook_and_settle(router: &Router, body: serde_json::Value, project_index: usize, session_id: &str) {
+ let resp = router
+ .clone()
+ .oneshot(hook_with_raw_body(body, project_index, session_id))
+ .await
+ .expect("agent-shape hook oneshot");
+ assert_eq!(
+ resp.status(),
+ StatusCode::ACCEPTED,
+ "agent-shape hook must accept"
+ );
+ let _ = response_body_text(resp).await;
+ for _ in 0..20 {
+ tokio::task::yield_now().await;
+ }
+ tokio::time::sleep(Duration::from_millis(15)).await;
+}
+
+async fn read_session_marker(router: &Router, session_id: &str) -> String {
+ let resp = router
+ .clone()
+ .oneshot(mcp_query_request(None, Some(session_id)))
+ .await
+ .expect("agent-shape mcp oneshot");
+ assert_eq!(resp.status(), StatusCode::OK);
+ extract_tool_text(&response_body_text(resp).await)
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn claude_code_payload_shape_routes_per_session() {
+ let h = Harness::build(
+ ActiveProjectMode::PerSession,
+ TEST_TTL,
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ )
+ .await;
+ // Claude Code's session-start hook (per `from_query_and_body`'s key
+ // list): top-level `session_id`, top-level `cwd`,
+ // `hook_event_name` discriminator.
+ let body = json!({
+ "hook_event_name": "SessionStart",
+ "session_id": "claude-sess-A",
+ "cwd": "/tmp/aim-test/proj-3",
+ "tools": ["Read", "Write"],
+ "version": "1.0.0",
+ });
+ fire_raw_hook_and_settle(&h.router, body, 3, "claude-sess-A").await;
+ let text = read_session_marker(&h.router, "claude-sess-A").await;
+ assert!(
+ text.contains(number_word(3)),
+ "Claude Code shape did not route to proj-3:\n{text}"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn opencode_payload_shape_routes_per_session() {
+ let h = Harness::build(
+ ActiveProjectMode::PerSession,
+ TEST_TTL,
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ )
+ .await;
+ // OpenCode's SDK on `session.idle` / `tool.execute.*` events uses
+ // `sessionID` (capital ID) nested under `properties` for some
+ // events, and at the top level for others. The extractor accepts
+ // BOTH; this test pins the top-level form. The nested form is
+ // covered by the next test.
+ let body = json!({
+ "sessionID": "oc-sess-B",
+ "cwd": "/tmp/aim-test/proj-6",
+ "event": "session-start",
+ });
+ fire_raw_hook_and_settle(&h.router, body, 6, "oc-sess-B").await;
+ let text = read_session_marker(&h.router, "oc-sess-B").await;
+ assert!(
+ text.contains(number_word(6)),
+ "OpenCode top-level sessionID shape did not route to proj-6:\n{text}"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn opencode_nested_properties_shape_routes_per_session() {
+ let h = Harness::build(
+ ActiveProjectMode::PerSession,
+ TEST_TTL,
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ )
+ .await;
+ // OpenCode `tool.execute.before` and friends wrap the session id
+ // (and the directory hint) inside a `properties.info` block. The
+ // extractor's nested path list covers this; if the key list ever
+ // changes upstream, this test will be the warning shot.
+ let body = json!({
+ "type": "tool.execute.before",
+ "properties": {
+ "sessionID": "oc-nested-C",
+ "info": {
+ "directory": "/tmp/aim-test/proj-2",
+ "id": "ignored-tool-id"
+ }
+ }
+ });
+ fire_raw_hook_and_settle(&h.router, body, 2, "oc-nested-C").await;
+ let text = read_session_marker(&h.router, "oc-nested-C").await;
+ assert!(
+ text.contains(number_word(2)),
+ "OpenCode nested properties shape did not route to proj-2:\n{text}"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn codex_payload_shape_routes_per_session() {
+ let h = Harness::build(
+ ActiveProjectMode::PerSession,
+ TEST_TTL,
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ )
+ .await;
+ // Codex CLI: camelCase `sessionId`, `cwd` at top level. Differs
+ // from Claude (snake_case) and OpenCode (capital ID) by one
+ // letter each; the extractor must accept all three case variants
+ // because the same engine serves all the agents.
+ let body = json!({
+ "sessionId": "codex-sess-D",
+ "cwd": "/tmp/aim-test/proj-4",
+ "model": "gpt-4",
+ });
+ fire_raw_hook_and_settle(&h.router, body, 4, "codex-sess-D").await;
+ let text = read_session_marker(&h.router, "codex-sess-D").await;
+ assert!(
+ text.contains(number_word(4)),
+ "Codex sessionId shape did not route to proj-4:\n{text}"
+ );
+}