Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(scope): make multi-session and multi-user work without configuration (#562)
Fabio Akitaabf4d41d90f6
diff --git a/AGENTS.md b/AGENTS.mdindex fe8a8d5b..a6824358 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -291,6 +291,36 @@ prior-art bug (see `docs/ARCHITECTURE.md` and `docs/issues-*.md`):15. **Tracing subscribers explicitly filter their own module** — nofeedback loops.+16. **Multi-session and multi-user access to one project is a core+ capability.** One operator running several harnesses at once, and+ several operators sharing one server, must both work — and knowledge+ written by either must be readable by the other in the same project.+ Concretely:+ - **Pages are shared, batons are owned.** `pages.author_id` exists for+ attribution and must never become a read filter; `OwnerFilter` applies+ to handoffs and stays there. A change that scopes page reads by+ operator silently stops a team collaborating while every single-user+ test still passes.+ - **A divergent concurrent write supersedes, never destroys.** Two+ harnesses editing one path produce a supersession chain; the loser+ stays reachable. "Last write wins" must not come to mean "the other+ version is gone".+ - **A handoff is claimed exactly once**, by two independent `state =+ 'open'` guards (the metadata lookup and the claim `UPDATE`). Keep both;+ they are defence in depth, not duplication.+ - **The active-project pointer is keyed by the caller's coordinate**+ (`ActiveProjectMode::PerActor` by default), so parallel harnesses and+ separate operators cannot overwrite each other's notion of "current+ project" — which unscoped *writes* also resolve through.++ Unit tests do not cover this: they exercise one session at a time, which+ is the exact shape that cannot see a collaboration or concurrency defect.+ `crates/ai-memory-store/tests/multi_session.rs` and the pointer tests in+ `ai-memory-core::active_project` are the guards. Any change to scope+ resolution, page supersession, session identity, handoff acceptance, the+ writer actor, or owner filters must be argued against this invariant+ explicitly rather than assumed safe.+Additional boundary rules:- **Scope resolution:** new MCP/admin/web routes must usediff --git a/CHANGELOG.md b/CHANGELOG.mdindex 70137419..8f810742 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -114,6 +114,68 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`status` only advises compaction once the backlog is worth the stall (≥20% ofthe file *and* ≥64 MiB); the raw numbers are always reported.+### Changed++- **The `[auto_scope]` default changed from `single` to `per_actor`.** The+ "currently active project" pointer is now keyed by the caller's identity and+ session, so two harnesses in one project — or two operators on one server —+ no longer overwrite each other's notion of the current project. Unscoped MCP+ calls resolve through that pointer, and so do unscoped **writes**, so under+ the old default a `memory_write_page` from one session could land in whatever+ project another session had most recently published.++ **Upgrade impact is narrow, and there is an escape hatch.** A single harness+ with hooks, a static MCP client sending only a bearer, a client forwarding no+ identity at all, and an MCP-only install with no lifecycle hooks all resolve+ to the same project they did before — the last case because nothing is ever+ keyed there, so the shared slot still applies. The one deliberate change: a+ client forwarding a session id that matches no published hook activity no+ longer inherits the shared slot, because that is precisely what routed a+ request into whichever project published last. It now resolves to the+ server's configured default.++ Set `mode = "single"` under `[auto_scope]`, or+ `AI_MEMORY_AUTO_SCOPE__MODE=single`, for the old behaviour exactly. The+ effective mode is logged at startup. `docs/auto-scope.md` carries a+ per-setup upgrade table.++- Multi-session and multi-user access to one project is now a documented+ cross-cutting invariant (`AGENTS.md` #16) with integration-level guards:+ `crates/ai-memory-store/tests/multi_session.rs` plus pointer tests in+ `ai-memory-core::active_project`. They pin the properties a team depends on —+ pages shared while handoffs stay owned, a concurrent write superseding rather+ than destroying, an identical rewrite staying idempotent, and a second accept+ being unable to steal a claimed handoff. Unit tests could not cover this:+ they exercise one session at a time, which is the shape that cannot see a+ collaboration or concurrency defect.++ `crates/ai-memory-consolidate/tests/multi_machine.rs` additionally pins the+ same-project-two-machines case: identity derives from the checkout's name,+ never its absolute path, so a copy at a different path on another machine+ is the same project and reads what the first wrote.++ Writer capacity is now measured rather than assumed:+ `crates/ai-memory-store/tests/writer_throughput.rs` reports ~700 writes/second+ at saturation (~32 concurrent writers, flat to 128), with single-writer+ latency dominated by `fsync` rather than CPU. A companion test asserts that a+ burst larger than the 1024-deep queue applies backpressure and loses nothing.+ `docs/deploy.md` carries the table and the capacity reading.++ `docs/users.md` and `docs/deploy.md` gain the team-facing guidance they were+ missing entirely, including that two servers must never share one data+ directory.++- `/admin/*` and `/api/v1/*` accept a human web session or a machine Bearer.+ Custom SPA HTML at `/web` is public static; the builtin wiki browser stays+ authenticated. Human auth is additive during 1.x: until a human password or+ completed bootstrap exists, deprecated GET-only HTTP Basic and+ `ai_memory_auth` cookie authentication continue to work. The transition to+ human auth disables both legacy browser credentials immediately. (#533)+- Preserved `ai-memory user add|expire|revive|rotate-token` and their admin+ endpoints as deprecated 1.x compatibility paths backed by the reserved+ `legacy-user-token` API credential. New automation should use+ `api-key add|rotate|revoke`. (#533)+### Fixed- A failed or skipped embed now leaves a durable record. `page_embeddings`stores only successes, and its upsert rewrites `created_at`, so a global@@ -328,18 +390,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.01.x `user add|expire|revive|rotate-token` shims and may be removed only whenthose shims are removed in 2.0. (#533)-### Changed-- `/admin/*` and `/api/v1/*` accept a human web session or a machine Bearer.- Custom SPA HTML at `/web` is public static; the builtin wiki browser stays- authenticated. Human auth is additive during 1.x: until a human password or- completed bootstrap exists, deprecated GET-only HTTP Basic and- `ai_memory_auth` cookie authentication continue to work. The transition to- human auth disables both legacy browser credentials immediately. (#533)-- Preserved `ai-memory user add|expire|revive|rotate-token` and their admin- endpoints as deprecated 1.x compatibility paths backed by the reserved- `legacy-user-token` API credential. New automation should use- `api-key add|rotate|revoke`. (#533)-## [1.38.0] - 2026-08-30### Addeddiff --git a/crates/ai-memory-cli/templates/config.default.toml b/crates/ai-memory-cli/templates/config.default.tomlindex d44dce59..96629f63 100644--- a/crates/ai-memory-cli/templates/config.default.toml+++ b/crates/ai-memory-cli/templates/config.default.toml@@ -217,6 +217,21 @@ min_session_age_secs = 600[routing]mid_session = "follow-cwd"+# How the "currently active project" pointer is keyed. Unscoped MCP calls —+# the normal case, since the tools default to the current project — resolve+# through it, and so do unscoped writes.+#+# per_actor (default) keyed by identity + session. Two harnesses, or two+# operators, keep separate pointers. Falls back to the shared+# slot for a caller with no coordinate and for installs with no+# lifecycle hooks.+# per_session keyed by session id only.+# single one process-wide slot, last write wins. The pre-v1.39+# behaviour; correct only for one harness at a time.+#+# [auto_scope]+# mode = "per_actor"+# NOTE: `[auth]` must remain the LAST section in this template.# `ai-memory init` appends further `[auth]` keys (token_pepper, root_username,# ...) as bare keys to the end of the rendered file, so any section addeddiff --git a/crates/ai-memory-cli/tests/autoscope_env.rs b/crates/ai-memory-cli/tests/autoscope_env.rsindex 23e27da6..d6a932d1 100644--- a/crates/ai-memory-cli/tests/autoscope_env.rs+++ b/crates/ai-memory-cli/tests/autoscope_env.rs@@ -151,13 +151,35 @@ fn spawn_and_wait_for_exit(envs: &[(&str, &str)], timeout: Duration) -> (bool, Sconst STARTUP_NEEDLE: &str = "active-project isolation mode";const STARTUP_TIMEOUT: Duration = Duration::from_secs(8);+/// The shipped default keys the active-project pointer by whatever coordinate+/// the caller has, so two harnesses in one project — or two operators on one+/// server — do not overwrite each other's pointer.+///+/// `Single` is still selectable, but it is no longer what an install gets for+/// free: a process-wide last-write-wins slot is only correct for exactly one+/// harness at a time, and nothing about a fresh install says that is the case.#[test]-fn default_mode_is_single() {+fn default_mode_is_per_actor() {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("PerActor"),+ "default mode must log `PerActor`. Got: {line}\nfull stderr:\n{all}"+ );+}++/// …and `Single` must remain reachable for anyone who wants the old slot.+#[test]+fn single_mode_is_still_selectable_via_env() {+ let (line, all) = spawn_and_wait_for_log(+ &[("AI_MEMORY_AUTO_SCOPE__MODE", "single")],+ 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}"+ "explicit single must log `Single`. Got: {line}\nfull stderr:\n{all}");}diff --git a/crates/ai-memory-consolidate/tests/multi_machine.rs b/crates/ai-memory-consolidate/tests/multi_machine.rsnew file mode 100644index 00000000..beea1d44--- /dev/null+++ b/crates/ai-memory-consolidate/tests/multi_machine.rs@@ -0,0 +1,101 @@+//! One operator, one project, two machines.+//!+//! Project identity is derived from the checkout's *name*, never its absolute+//! path, which is what makes the same project portable between machines. This+//! lives in `ai-memory-consolidate` because that crate owns the name+//! derivation and also depends on the store, so the property can be asserted+//! end to end rather than in two halves that never meet.+//!+//! See `AGENTS.md` invariant 16.++use ai_memory_consolidate::{ProjectNameStrategy, derive_project_name};+use ai_memory_core::{NewPage, PagePath, ProjectId, Tier, WorkspaceId};+use ai_memory_store::Store;++fn page(ws: WorkspaceId, proj: ProjectId, path: &str, title: &str, body: &str) -> NewPage {+ NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ title: title.into(),+ body: body.into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ }+}++/// The scenario the maintainer named first: one operator, the same project,+/// two machines.+///+/// Project identity is derived from the checkout's *name*, never its absolute+/// path — so `/home/alice/work/proj-b` on one machine and+/// `/Users/alice/src/proj-b` on another resolve to one project row, and each+/// machine reads what the other wrote.+///+/// This is what makes the capability portable, and it is a property of name+/// derivation rather than of any storage code, so it is asserted end to end:+/// resolve both paths, then prove the second machine reads the first's page.+#[tokio::test]+async fn the_same_checkout_on_two_machines_resolves_to_one_project() {+ let machine_one = std::path::Path::new("/home/alice/work/proj-b");+ let machine_two = std::path::Path::new("/Users/alice/src/proj-b");++ let (name_one, _) = derive_project_name(machine_one, ProjectNameStrategy::Basename)+ .expect("a real checkout path resolves to a name");+ let (name_two, _) = derive_project_name(machine_two, ProjectNameStrategy::Basename)+ .expect("a real checkout path resolves to a name");+ assert_eq!(+ name_one, name_two,+ "the same project checked out at different absolute paths must derive \+ the same project name, or the two machines silently diverge"+ );++ // …and that name lands both machines in one project row, sharing knowledge.+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();++ let proj_one = store+ .writer+ .get_or_create_project(ws, name_one, None)+ .await+ .unwrap();+ let proj_two = store+ .writer+ .get_or_create_project(ws, name_two, None)+ .await+ .unwrap();+ assert_eq!(+ proj_one, proj_two,+ "both machines must land in the same project row"+ );++ store+ .writer+ .upsert_page(page(+ ws,+ proj_one,+ "notes/from-machine-one.md",+ "From machine one",+ "written on the laptop",+ ))+ .await+ .unwrap();++ let seen_from_machine_two = store+ .reader+ .page_body_by_ids(ws, proj_two, "notes/from-machine-one.md")+ .await+ .unwrap()+ .expect("machine two must see machine one's page");+ assert!(seen_from_machine_two.body.contains("written on the laptop"));+}diff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rsindex 97f0e0e6..f53eb9c7 100644--- a/crates/ai-memory-core/src/active_project.rs+++ b/crates/ai-memory-core/src/active_project.rs@@ -63,6 +63,7 @@//! plain `std::sync::RwLock` is the right primitive (no async lock needed).use std::collections::HashMap;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, RwLock};use std::time::{Duration, Instant};@@ -77,19 +78,27 @@ pub const DEFAULT_PER_KEY_TTL: Duration = Duration::from_secs(60 * 60);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.+/// project" pointer.+///+/// `PerActor` is the default: it keys the pointer by whatever coordinate the+/// caller actually has, so parallel harnesses and multiple operators stay+/// separated without configuration. A caller carrying no coordinate at all+/// still reads the shared slot, which is what keeps a single-harness install+/// behaving exactly as it always has.+///+/// `Single` remains available for installs that want the historical+/// process-wide slot explicitly.#[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]+ /// Process-wide slot, last-write-wins. The historical behaviour, now opt-in.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.+ /// Keyed by `(user, session_id)`, with an identity-only slot alongside.+ /// Isolates parallel harnesses and separate operators. The default.+ #[default]PerActor,}@@ -318,12 +327,23 @@ pub struct ActiveProject {/// byte-for-byte unchanged.single_default_global: Arc<RwLock<bool>>,per_actor: Arc<RwLock<PerActorMap>>,+ /// Whether any keyed entry has ever been published on this process.+ ///+ /// Distinguishes "this install has no lifecycle hooks, so nothing was ever+ /// keyed" from "hooks are running and this key simply does not match".+ /// The first deserves the shared fallback — there is no better information+ /// anywhere — while the second is a mismatch that must fail closed rather+ /// than answer for whichever project published last.+ ///+ /// Never reset: an install that once had hook activity is not hookless+ /// again just because entries aged out of the TTL map.+ ever_keyed: Arc<AtomicBool>,}impl Default for ActiveProject {fn default() -> Self {Self::with_config(- ActiveProjectMode::Single,+ ActiveProjectMode::default(),DEFAULT_PER_KEY_TTL,DEFAULT_MAX_ENTRIES,)@@ -331,7 +351,11 @@ impl Default for ActiveProject {}impl ActiveProject {- /// Create an empty `Single`-mode pointer — the legacy default.+ /// Create an empty pointer in the shipped default mode+ /// ([`ActiveProjectMode::PerActor`]).+ ///+ /// Was `Single` before v1.39. Call [`Self::with_mode`] explicitly for the+ /// historical process-wide slot.#[must_use]pub fn new() -> Self {Self::default()@@ -353,6 +377,7 @@ impl ActiveProject {single: Arc::new(RwLock::new(None)),single_default_global: Arc::new(RwLock::new(false)),per_actor: Arc::new(RwLock::new(PerActorMap::new(ttl, max_entries))),+ ever_keyed: Arc::new(AtomicBool::new(false)),}}@@ -392,6 +417,7 @@ impl ActiveProject {return;}let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());+ self.ever_keyed.store(true, Ordering::Relaxed);if self.mode == ActiveProjectMode::PerActor&& actor.user.is_some()&& actor.session_id.is_some()@@ -468,8 +494,39 @@ impl ActiveProject {return self.read_single();}+ let now = Instant::now();let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());- guard.get(&scoped, Instant::now())+ if let Some(found) = guard.get(&scoped, now) {+ return Some(found);+ }++ // A keyed miss means one of two very different things.+ //+ // If this identity has published before — or anything on this process+ // has — then hooks are running and this coordinate simply does not+ // match one. That is a mismatch, and answering from the shared slot+ // would route the request into whichever project published last,+ // possibly another operator's. Fail closed and let the caller fall+ // back to its configured default.+ //+ // If nothing has *ever* been keyed, this install has no lifecycle+ // hooks feeding the pointer at all (MCP-only). There is no better+ // information anywhere, and the shared slot is exactly what such an+ // install has always used, so keep answering from it.+ if self.mode == ActiveProjectMode::PerActor && actor.user.is_some() {+ let identity_only = ActorKey {+ user: actor.user.clone(),+ session_id: None,+ };+ if guard.get(&identity_only, now).is_some() {+ return None;+ }+ }+ drop(guard);+ if self.ever_keyed.load(Ordering::Relaxed) {+ return None;+ }+ self.read_single()}/// Whether the actor opted this session into `default_global` recall (via@@ -673,6 +730,138 @@ mod tests {}}+ fn per_actor() -> ActiveProject {+ ActiveProject::with_config(+ ActiveProjectMode::PerActor,+ DEFAULT_PER_KEY_TTL,+ DEFAULT_MAX_ENTRIES,+ )+ }++ fn ids(_n: u8) -> (WorkspaceId, ProjectId) {+ (WorkspaceId::new(), ProjectId::new())+ }++ /// The scenario the default must not break: one operator, one harness, and+ /// an MCP-only install with no lifecycle hooks feeding the pointer.+ ///+ /// Nothing is ever keyed, so a request carrying a session id has no keyed+ /// entry to match. That is not a mismatch — there is no better information+ /// anywhere — so it must keep reading the shared slot, exactly as it did+ /// before `PerActor` became the default.+ #[test]+ fn a_hookless_install_still_reads_the_shared_slot() {+ let ap = per_actor();+ let (ws, proj) = ids(1);+ ap.set(ws, proj);++ assert_eq!(+ ap.get_for(&key_actor("alice", "session-never-published")),+ Some((ws, proj)),+ "with no keyed activity anywhere, the shared slot is the only answer"+ );+ }++ /// Once hooks *are* publishing, a session id that matches nothing is a+ /// mismatch rather than a hookless install. Answering from the shared slot+ /// would hand back whichever project published last — on a shared server,+ /// somebody else's. Fail closed instead.+ #[test]+ fn a_session_mismatch_fails_closed_once_anything_has_been_keyed() {+ let ap = per_actor();+ let (ws_a, proj_a) = ids(1);+ ap.set_for(&key_actor("alice", "s-alice"), ws_a, proj_a, false);++ assert_eq!(+ ap.get_for(&key_actor("alice", "some-other-session")),+ None,+ "alice has published, so an unmatched session of hers is a mismatch"+ );+ assert_eq!(+ ap.get_for(&key_actor("carol", "s-carol")),+ None,+ "and another operator must not inherit alice's pointer"+ );+ }++ /// Scenario: one user, two harnesses open in the same project at once.+ /// Each must keep its own pointer; neither may overwrite the other.+ #[test]+ fn parallel_harnesses_of_one_user_keep_separate_pointers() {+ let ap = per_actor();+ let (ws_1, proj_1) = ids(1);+ let (ws_2, proj_2) = ids(2);++ ap.set_for(&key_actor("alice", "harness-a"), ws_1, proj_1, false);+ ap.set_for(&key_actor("alice", "harness-b"), ws_2, proj_2, false);++ assert_eq!(+ ap.get_for(&key_actor("alice", "harness-a")),+ Some((ws_1, proj_1))+ );+ assert_eq!(+ ap.get_for(&key_actor("alice", "harness-b")),+ Some((ws_2, proj_2)),+ "the second harness must not have clobbered the first"+ );+ }++ /// Scenario: two operators on one server. Neither may read the other's+ /// pointer, in either direction.+ #[test]+ fn two_operators_never_read_each_others_pointer() {+ let ap = per_actor();+ let (ws_a, proj_a) = ids(1);+ let (ws_c, proj_c) = ids(2);++ ap.set_for(&key_actor("alice", "s-a"), ws_a, proj_a, false);+ ap.set_for(&key_actor("carol", "s-c"), ws_c, proj_c, false);++ assert_eq!(ap.get_for(&key_actor("alice", "s-a")), Some((ws_a, proj_a)));+ assert_eq!(ap.get_for(&key_actor("carol", "s-c")), Some((ws_c, proj_c)));+ }++ /// The commonest authenticated upgrade path: lifecycle hooks publish with+ /// both a user and a session, while a *static* MCP client (no session-aware+ /// bridge) sends only its bearer.+ ///+ /// That client keys to the identity-only slot, which `set_for` publishes+ /// alongside the session slot precisely so this works. Without it, every+ /// static MCP client on an authenticated install would fail closed after+ /// the default changed — which would be a broken upgrade, not a safer one.+ #[test]+ fn a_static_mcp_client_reads_the_identity_only_slot() {+ let ap = per_actor();+ let (ws, proj) = ids(1);+ ap.set_for(&key_actor("alice", "hook-session"), ws, proj, false);++ let static_client = ActorKey {+ user: Some("alice".to_string()),+ session_id: None,+ };+ assert_eq!(+ ap.get_for(&static_client),+ Some((ws, proj)),+ "a bearer with no session must still resolve to that user's project"+ );+ }++ /// A caller with no coordinate at all — an anonymous probe, or a client+ /// that cannot forward identity — still reads the shared slot. This is what+ /// keeps the single-harness install unchanged under the new default.+ #[test]+ fn an_actorless_caller_still_reads_the_shared_slot_after_keying() {+ let ap = per_actor();+ let (ws_a, proj_a) = ids(1);+ ap.set_for(&key_actor("alice", "s-a"), ws_a, proj_a, false);++ assert_eq!(+ ap.get_for(&empty_actor()),+ Some((ws_a, proj_a)),+ "an empty actor has no coordinate to mismatch on"+ );+ }+#[test]fn starts_empty() {assert!(ActiveProject::new().get().is_none());@@ -791,7 +980,9 @@ mod tests {#[test]fn single_mode_ignores_actor_coordinates() {- let ap = ActiveProject::new();+ // Explicit: `Single` is opt-in since v1.39, so this pins the mode+ // rather than relying on whatever the default happens to be.+ let ap = ActiveProject::with_mode(ActiveProjectMode::Single);let alice = key_actor("alice", "sA");let bob = key_actor("bob", "sB");let ws = WorkspaceId::new();diff --git a/crates/ai-memory-store/tests/multi_session.rs b/crates/ai-memory-store/tests/multi_session.rsnew file mode 100644index 00000000..fcf7a391--- /dev/null+++ b/crates/ai-memory-store/tests/multi_session.rs@@ -0,0 +1,359 @@+//! Integration tests for the multi-session and multi-user scenarios.+//!+//! These are the guarantees a team and a parallel-harness workflow depend on,+//! and they are deliberately at integration level: the unit tests around them+//! exercise one session at a time, which is exactly the shape that cannot see+//! a collaboration or concurrency defect.+//!+//! Two halves, and they pull in opposite directions:+//!+//! * **Shared** — knowledge written by one operator must be readable by+//! another in the same project. Pages carry an `author_id` for attribution,+//! and it must never become a filter.+//! * **Owned** — a handoff is a baton. Exactly one session may take it, and a+//! second attempt must not be able to steal it.+//!+//! Anything that makes pages owner-filtered, or handoffs stealable, breaks a+//! core capability rather than a detail.++use ai_memory_core::{+ ActorContext, AgentKind, HandoffAcceptance, IdentityKey, NewHandoff, NewPage, NewSession,+ OwnerFilter, PagePath, ProjectId, SessionId, Tier, WorkspaceId, owner_stamp,+};+use ai_memory_store::Store;++fn operator(name: &str) -> String {+ IdentityKey::User(name.into()).storage_key()+}++async fn scope(store: &Store) -> (WorkspaceId, ProjectId) {+ let ws = store+ .writer+ .get_or_create_workspace("acme".to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "shared-app".to_string(), None)+ .await+ .unwrap();+ (ws, proj)+}++/// Open a real session row. `accept_handoff` requires the receiver to exist —+/// a guard worth keeping, so the tests satisfy it rather than route around it.+async fn open_session(+ store: &Store,+ ws: WorkspaceId,+ proj: ProjectId,+ agent_kind: AgentKind,+) -> SessionId {+ let id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id,+ workspace_id: ws,+ project_id: proj,+ agent_kind,+ cwd: Some("/repo".into()),+ actor_user: None,+ })+ .await+ .unwrap();+ id+}++fn page(ws: WorkspaceId, proj: ProjectId, path: &str, title: &str, body: &str) -> NewPage {+ NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ title: title.into(),+ body: body.into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ }+}++/// The collaboration guarantee, and the reason a team can use one server:+/// what Alice writes, Carol reads.+///+/// `pages.author_id` exists for attribution and must never become a read+/// filter. If it ever does, this fails — and a team silently stops sharing+/// knowledge while every single-user test still passes.+#[tokio::test]+async fn one_operators_page_is_readable_by_another_in_the_same_project() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;++ store+ .writer+ .upsert_page(page(+ ws,+ proj,+ "decisions/0001.md",+ "Chose SQLite",+ "We picked SQLite for the derived index.",+ ))+ .await+ .unwrap();++ // Carol's read of the same project: no owner coordinate involved.+ let hits = store+ .reader+ .search_pages("SQLite".to_string(), 10)+ .await+ .unwrap();++ assert!(+ hits.iter().any(|h| h.path.as_str() == "decisions/0001.md"),+ "a page written in this project must be visible to any operator \+ reading it; got {:?}",+ hits.iter().map(|h| h.path.as_str()).collect::<Vec<_>>()+ );++ // …and readable in full, not just rankable.+ let body = store+ .reader+ .page_body_by_ids(ws, proj, "decisions/0001.md")+ .await+ .unwrap()+ .expect("the page resolves by path for any reader");+ assert!(body.body.contains("We picked SQLite"));+}++/// Two harnesses editing the same page keep both versions.+///+/// The latest write wins the `is_latest` flag — there is no merge, and none is+/// claimed — but the superseded version stays reachable through the chain.+/// "Last write wins" must never mean "the other version is gone".+#[tokio::test]+async fn concurrent_writes_to_one_path_supersede_rather_than_destroy() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;++ let first = store+ .writer+ .upsert_page(page(ws, proj, "notes/shared.md", "Shared", "alice's text"))+ .await+ .unwrap();+ let second = store+ .writer+ .upsert_page(page(ws, proj, "notes/shared.md", "Shared", "carol's text"))+ .await+ .unwrap();++ assert_ne!(first, second, "a divergent write creates a new version");++ let latest = store+ .reader+ .page_body_by_ids(ws, proj, "notes/shared.md")+ .await+ .unwrap()+ .expect("the path still resolves");+ assert!(+ latest.body.contains("carol's text"),+ "the later write is the latest version"+ );++ let latest_id = store+ .reader+ .latest_page_id_by_ids(ws, proj, "notes/shared.md".to_string())+ .await+ .unwrap()+ .expect("a latest version exists");+ assert_eq!(latest_id, second, "the later write holds is_latest");++ // The overwritten version is still a row, reachable by its own id.+ let earlier_survives = store+ .reader+ .with_conn(move |conn| {+ let body: String = conn.query_row(+ "SELECT body FROM pages WHERE id = ?1",+ rusqlite::params![&first.as_bytes()[..]],+ |r| r.get(0),+ )?;+ Ok(body)+ })+ .await+ .unwrap();+ assert!(+ earlier_survives.contains("alice's text"),+ "the overwritten version must survive in the supersession chain, \+ not be destroyed"+ );+}++/// Re-writing identical content must not churn a new version.+///+/// Two harnesses syncing the same file would otherwise manufacture a version+/// per pass and bloat the chain with nothing to show for it.+#[tokio::test]+async fn an_identical_rewrite_is_idempotent() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;++ let first = store+ .writer+ .upsert_page(page(ws, proj, "notes/same.md", "Same", "identical body"))+ .await+ .unwrap();+ let again = store+ .writer+ .upsert_page(page(ws, proj, "notes/same.md", "Same", "identical body"))+ .await+ .unwrap();++ assert_eq!(+ first, again,+ "identical content must return the same version, not create one"+ );+}++/// A handoff is a baton: exactly one session takes it.+///+/// The pre-existing unit test asserted only that a second accept does not+/// *error*, which would still pass if the second accept overwrote+/// `accepted_by`. This asserts the property that actually matters — the first+/// accepter keeps it.+#[tokio::test]+async fn a_second_accept_cannot_steal_an_accepted_handoff() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;++ let id = store+ .writer+ .insert_handoff(NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ from_session_id: None,+ summary: "pick this up".into(),+ next_steps: Vec::new(),+ open_questions: Vec::new(),+ files_touched: Vec::new(),+ cwd: None,+ owner_user: None,+ })+ .await+ .unwrap();++ let accept = |agent: AgentKind, session: SessionId| HandoffAcceptance {+ handoff_id: id,+ workspace_id: ws,+ project_id: proj,+ accepting_agent: agent,+ accepting_session: Some(session),+ accepting_user: None,+ owner_filter: OwnerFilter::Any,+ receiving_cwd: None,+ };++ let winner = open_session(&store, ws, proj, AgentKind::Codex).await;+ let loser = open_session(&store, ws, proj, AgentKind::ClaudeCode).await;++ let first = store+ .writer+ .accept_handoff(accept(AgentKind::Codex, winner))+ .await+ .unwrap();+ assert!(first, "the first accept claims the baton");++ let second = store+ .writer+ .accept_handoff(accept(AgentKind::ClaudeCode, loser))+ .await+ .unwrap();+ assert!(+ !second,+ "a second accept must report that it claimed nothing"+ );++ let handoff_bytes = id.as_bytes().to_vec();+ let (accepted_by, accepted_session): (Option<String>, Option<Vec<u8>>) = store+ .reader+ .with_conn(move |conn| {+ Ok(conn.query_row(+ "SELECT accepted_by, accepted_by_session FROM handoffs WHERE id = ?1",+ rusqlite::params![handoff_bytes],+ |r| Ok((r.get(0)?, r.get(1)?)),+ )?)+ })+ .await+ .unwrap();++ assert_eq!(+ accepted_by.as_deref(),+ Some("codex"),+ "the original accepter must still own the handoff"+ );+ assert_eq!(+ accepted_session.as_deref(),+ Some(&winner.as_bytes()[..]),+ "and the winning session must not have been overwritten by the loser"+ );+}++/// Ownership still applies to batons even though pages are shared: the two+/// halves of the model must not collapse into each other.+#[tokio::test]+async fn an_owned_handoff_stays_with_its_owner_while_pages_stay_shared() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;++ let id = store+ .writer+ .insert_handoff(NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ from_session_id: None,+ summary: "alice's baton".into(),+ next_steps: Vec::new(),+ open_questions: Vec::new(),+ files_touched: Vec::new(),+ cwd: None,+ owner_user: owner_stamp(Some(&IdentityKey::User("alice".into())), true),+ })+ .await+ .unwrap();++ let carol = OwnerFilter::for_actor_context(&ActorContext {+ user: Some("carol".into()),+ ..ActorContext::default()+ });++ let stolen = store+ .writer+ .accept_handoff(HandoffAcceptance {+ handoff_id: id,+ workspace_id: ws,+ project_id: proj,+ accepting_agent: AgentKind::Codex,+ accepting_session: Some(open_session(&store, ws, proj, AgentKind::Codex).await),+ accepting_user: Some(operator("carol")),+ owner_filter: carol,+ receiving_cwd: None,+ })+ .await+ .unwrap();++ assert!(+ !stolen,+ "carol must not be able to accept a baton owned by {}",+ operator("alice")+ );+}diff --git a/crates/ai-memory-store/tests/writer_throughput.rs b/crates/ai-memory-store/tests/writer_throughput.rsnew file mode 100644index 00000000..b3a2d4c5--- /dev/null+++ b/crates/ai-memory-store/tests/writer_throughput.rs@@ -0,0 +1,148 @@+//! How much load the single writer actor absorbs before it becomes the+//! bottleneck — measured, not estimated.+//!+//! All writes funnel through one actor over a bounded `mpsc` channel, which is+//! the right design for SQLite but does make one question worth answering with+//! a number: at what point does a shared server stop keeping up?+//!+//! Run it on demand; it is `#[ignore]`d so a throughput measurement never+//! becomes a flaky CI gate on a loaded runner:+//!+//! ```text+//! cargo test -p ai-memory-store --test writer_throughput -- --ignored --nocapture+//! ```++use std::time::Instant;++use ai_memory_core::{+ AgentKind, NewObservation, NewSession, ObservationKind, ProjectId, Sanitized, Sanitizer,+ SessionId, WorkspaceId,+};+use ai_memory_store::Store;++async fn scope(store: &Store) -> (WorkspaceId, ProjectId, SessionId) {+ let ws = store+ .writer+ .get_or_create_workspace("bench".to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "load".to_string(), None)+ .await+ .unwrap();+ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Codex,+ cwd: None,+ actor_user: None,+ })+ .await+ .unwrap();+ (ws, proj, session_id)+}++fn observation(+ ws: WorkspaceId,+ proj: ProjectId,+ session_id: SessionId,+ n: usize,+) -> Sanitized<NewObservation> {+ Sanitized::new(+ NewObservation {+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::PostToolUse,+ extension: None,+ source_event: None,+ title: format!("tool call {n}"),+ body: "ran a command and captured a bounded excerpt of its output".into(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ )+}++/// Sustained throughput of the hot path — the write every tool call performs.+///+/// Reported as observations/second plus the implied budget in concurrent+/// agents, taking one tool call per agent-second as a deliberately pessimistic+/// stand-in for an actively working harness.+#[tokio::test(flavor = "multi_thread")]+#[ignore = "throughput measurement; run explicitly"]+async fn writer_throughput_under_concurrent_load() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj, session_id) = scope(&store).await;++ for writers in [1usize, 8, 32, 128] {+ const PER_WRITER: usize = 200;+ let total = writers * PER_WRITER;++ let started = Instant::now();+ let mut tasks = Vec::with_capacity(writers);+ for _ in 0..writers {+ let writer = store.writer.clone();+ tasks.push(tokio::spawn(async move {+ for n in 0..PER_WRITER {+ writer+ .insert_observation(observation(ws, proj, session_id, n))+ .await+ .unwrap();+ }+ }));+ }+ for t in tasks {+ t.await.unwrap();+ }+ let elapsed = started.elapsed();++ let per_sec = total as f64 / elapsed.as_secs_f64();+ let mean_ms = elapsed.as_secs_f64() * 1000.0 / total as f64;+ println!(+ "writers={writers:>4} writes={total:>6} {elapsed:>10.2?} \+ {per_sec:>9.0}/s mean {mean_ms:>6.3}ms \+ ≈{per_sec:>7.0} concurrent agents at 1 tool-call/s"+ );+ }+}++/// The queue is bounded at 1024 with `send().await`, so a burst larger than the+/// queue applies backpressure rather than dropping work or growing without+/// limit. This asserts the property that matters operationally: every write in+/// an over-queue burst lands.+#[tokio::test(flavor = "multi_thread")]+async fn a_burst_larger_than_the_queue_applies_backpressure_and_loses_nothing() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj, session_id) = scope(&store).await;++ // Deliberately more than the 1024-deep channel.+ const BURST: usize = 1500;+ let mut tasks = Vec::with_capacity(BURST);+ for n in 0..BURST {+ let writer = store.writer.clone();+ tasks.push(tokio::spawn(async move {+ writer+ .insert_observation(observation(ws, proj, session_id, n))+ .await+ .unwrap()+ }));+ }+ for t in tasks {+ t.await.unwrap();+ }++ let status = store.reader.derived_index_status().await.unwrap();+ assert_eq!(+ status.observations_rows, BURST as u64,+ "every write in a burst larger than the queue must land: backpressure, \+ never a silent drop"+ );+}diff --git a/docs/auto-scope.md b/docs/auto-scope.mdindex af743621..02b43c5a 100644--- a/docs/auto-scope.md+++ b/docs/auto-scope.md@@ -10,23 +10,27 @@ land in their resolved project, but do not advance shared fallback slots: adelayed post-tool, stop, or session-end tail from an older process must notredirect a newer session's unscoped reads.-By default that pointer is a single process-wide slot — right for one-operator running one project at a time, but it collapses parallel-sessions on shared installs: a hook firing from `~/repo-A` overwrites-the slot that a concurrent `memory_query` (with no explicit project)-in `~/repo-B` was about to read.+Since v1.39 that pointer is **keyed by the caller's own coordinate** by+default (`per_actor`), so two harnesses in one project — or two operators on+one server — cannot overwrite each other's notion of "current project".-The `[auto_scope]` config block selects opt-in isolation modes that-key the pointer by request identity so concurrent callers stay-separated.+Before v1.39 the default was a single process-wide slot (`single`). That is+right for exactly one harness at a time and collapses as soon as there are+two: a hook firing from `~/repo-A` overwrites the slot that a concurrent+`memory_query` (with no explicit project) in `~/repo-B` was about to read.+Because unscoped **writes** resolve through the same pointer, that could also+land a `memory_write_page` in the wrong project.++The `[auto_scope]` config block still selects the mode explicitly, including+`single` for anyone who wants the historical slot back.## Modes| `mode` | Key | When to use ||---------------|------------------------|----------------------------------------------------------------------------------------------------------|-| `single` | (none — global slot) | **Default.** Single operator, one project at a time. Backward-compatible with every existing install. |+| `single` | (none — global slot) | The pre-v1.39 behaviour. One operator, one harness at a time; last write wins. Opt in only if you want it. || `per_session` | `session_id` | Session-aware clients/bridges that forward the hook session id on every MCP request. |-| `per_actor` | `(qualified identity, session_id)`, with an identity-only no-session slot | Shared engine fielding multiple authenticated users or trusted-proxy identities. Isolates across operators and fails closed when a forwarded session id does not match hook activity. |+| `per_actor` | `(qualified identity, session_id)`, with an identity-only no-session slot | **Default.** Isolates parallel harnesses and separate operators. Falls back to the shared slot for a caller with no coordinate, and for an install where nothing has ever been keyed (no lifecycle hooks); fails closed on a genuine session mismatch. |Both opt-in modes still publish foreground activity to the single slot inparallel, so a caller with no actor identity (anonymous probe, legacy code@@ -196,3 +200,34 @@ even on a corporate engine fielding hundreds of concurrent sessions.The TTL ensures stale entries (closed Claude Code windows, droppedhook clients) age out within an hour; the cap drops the oldestinsertions first if the TTL window is somehow exceeded.+++## Upgrading to v1.39++The default changed from `single` to `per_actor`. For most installs nothing+observable changes:++| your setup | before | after |+|---|---|---|+| one harness, hooks installed | shared slot | keyed slot for that session — same project |+| static MCP client (bearer, no session id) | shared slot | that operator's identity-only slot — same project |+| client that forwards no identity at all | shared slot | shared slot, unchanged |+| **MCP-only install, no lifecycle hooks** | shared slot | shared slot — nothing is ever keyed, so the fallback applies |+| two harnesses / two operators | one slot, last write wins | one slot each |++The single behavioural change is deliberate: a client that forwards a session+id which does **not** match any published hook activity no longer inherits the+shared slot. Answering it from there is what routed a request into whichever+project published last — on a shared server, potentially another operator's.+Such a caller now resolves to the server's configured default instead.++To restore the old behaviour exactly:++```toml+[auto_scope]+mode = "single"+```++or `AI_MEMORY_AUTO_SCOPE__MODE=single`. The effective mode is logged at+startup (`active-project isolation mode mode=…`), which is the quickest way+to confirm what a running server is using.diff --git a/docs/deploy.md b/docs/deploy.mdindex 104b5336..d440d047 100644--- a/docs/deploy.md+++ b/docs/deploy.md@@ -210,6 +210,72 @@ scp "$SERVER:$DEPLOY_DIR/data/snapshot-$(date +%F).tar.gz" ./backups/The `ai-memory backup` command uses SQLite's online backup API sowrites during the snapshot are coherent.+## Sharing one server between people or harnesses++A deployed server is the supported way to share a project — between teammates,+or between several harnesses you run yourself. Two things are worth knowing+before you hand out the URL.++**One server per data directory.** Point two `ai-memory serve` processes at the+same `data/` (a synced folder, an NFS mount, two containers on one volume) and+they will each run their own writer and their own git handle on the wiki. SQLite+survives it; the wiki and the in-process state do not. Run one server and let+everyone connect to it — which is also what makes the shared-knowledge model+work.++**Check the isolation mode.** Unscoped MCP calls resolve "current project"+through a pointer that, since v1.39, is keyed per caller. The startup line says+which mode is live:++```+active-project isolation mode mode=PerActor …+```++`PerActor` is the default and the one you want on a shared server. `Single` is+a single process-wide slot — fine for one harness, but concurrent sessions then+share it, and unscoped **writes** resolve through it too. See+[auto-scope.md](auto-scope.md) and [users.md](users.md#running-for-a-team).++### How much load one server absorbs++Every write goes through a single writer actor — the right design for SQLite,+and the obvious question it raises is when that becomes the ceiling. Measured+rather than estimated, with+`cargo test -p ai-memory-store --test writer_throughput -- --ignored --nocapture`:++| concurrent writers | throughput | mean latency |+|---|---|---|+| 1 | 42/s | 23.9 ms |+| 8 | 295/s | 3.4 ms |+| 32 | 698/s | 1.43 ms |+| 128 | 700/s | 1.43 ms |++Read it in two parts.++**The ceiling is ~700 writes/second**, reached around 32 concurrent writers and+flat from there — 128 writers produce the same throughput at the same latency.+Past saturation the server applies backpressure instead of degrading: the queue+is bounded at 1024 with an awaiting send, so a burst larger than the queue slows+its producers down and still lands every write. Nothing is dropped, and nothing+grows without limit.++**Single-writer latency is dominated by `fsync`, not CPU.** One observation per+commit costs about one disk sync; concurrency lets SQLite coalesce WAL commits,+which is why throughput rises 17× while per-write latency *falls*.++For capacity planning: an actively working agent emits on the order of one+lifecycle write per tool call. Even at a pessimistic one tool call per second+per agent, ~700/s is several hundred concurrently active agents — far beyond a+team, and beyond most shared installs. The writer is not the thing that will+break first.++Two caveats before you lean on the numbers. They were taken on a fast local+disk; because the cost is `fsync`, a network filesystem or a slow volume will+be materially lower, which is another reason to keep the data dir on local+storage. And they measure the store, not the HTTP front door — an install that+saturates this is far more likely to be limited by the agent side than by+SQLite.+## Reclaiming disk spaceSQLite does not return deleted space to the filesystem. Deleted rows leavediff --git a/docs/users.md b/docs/users.mdindex 663582aa..6e8ea7b1 100644--- a/docs/users.md+++ b/docs/users.md@@ -521,6 +521,37 @@ Until you re-run `install-hooks`, the hooks still hold the old token and thereis nothing newer to retry with — those events stay queued and age out on thenormal retry budget rather than blocking the rest of the spool (#493).+## Running for a team++Everything above concerns *who* a request is, which is the identity half. The+other half is *which project* it lands in, and it matters most once more than+one person shares a server.++**Knowledge is shared; batons are owned.** A page written in a project is+readable by every operator in that project — `pages.author_id` records who+wrote it and is never a read filter. That is the point of a shared server: what+one person learns, the next person retrieves. Handoffs are the opposite: a+handoff carries an owner, and only that operator receives it.++**Concurrent edits supersede rather than collide.** Two people editing the same+page produce a version chain, not a conflict; the later write becomes latest and+the earlier one stays reachable. There is no merge, and none is claimed — but+nothing is destroyed either.++**Isolation of the "current project" pointer is automatic** since v1.39. Unscoped+calls (the normal case — the MCP tools default to the current project) resolve+through a pointer keyed by the caller's identity and session, so two operators,+or one operator with two harnesses, do not overwrite each other. Confirm what a+server is running with the startup line:++```+active-project isolation mode mode=PerActor session_ttl_secs=3600 max_entries=4096+```++If that says `Single` on a shared server, unscoped reads **and writes** from+concurrent sessions share one last-write-wins slot. See+[auto-scope.md](auto-scope.md).+## Backward compatibilityIf you're upgrading a machine-bearer-only install: