Skip to content

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

Rust

fix(scope): refuse an unscoped write whose active-project pointer misses

Abhishek Sharma0f812e5d5c62
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa2a7355..94bc75bb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -73,6 +73,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
out with `embedding_provider = "none"`; configured providers are
never overridden. Measured on LongMemEval-S: overall hit@5 rises
from 0.617 (FTS-only) to 0.779 with local embeddings.
+- An unscoped `memory_write_page` / `memory_handoff_begin` from a caller whose
+ active-project pointer does not resolve is now refused instead of written to
+ the server's default project. The page such a write produced was real,
+ attributed and searchable, and in a project nobody goes looking in. The error
+ names both remedies — pass explicit `workspace`/`project`, or install the
+ lifecycle hooks so the pointer is populated. Reads are unchanged: a read
+ answering from the default is a wrong answer the caller can see, a write is a
+ misfile they cannot. Callers with no identity coordinate at all
+ (anonymous/legacy) keep resolving through the shared slot, and an install with
+ no pointer information anywhere still resolves to the configured default
+ ([#564]).
- The wiki's on-disk format is now natively the Open Knowledge Format
(OKF) v0.2: every page write fills the spec's `type`, `generated`,
`sources` and `stale_after` keys (ai-memory's own fields ride along as
diff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rs
index f53eb9c7..a8812ac5 100644
--- a/crates/ai-memory-core/src/active_project.rs
+++ b/crates/ai-memory-core/src/active_project.rs
@@ -175,6 +175,33 @@ pub struct ActorKey {
pub session_id: Option<String>,
}
+/// Outcome of resolving the active-project pointer for one actor.
+///
+/// Distinguishes the two cases [`ActiveProject::get_for`] returns `None` for,
+/// which callers that *write* need to tell apart.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ActiveProjectLookup {
+ /// The pointer resolved to a concrete workspace/project.
+ Resolved(WorkspaceId, ProjectId),
+ /// The actor carries a coordinate, this install's pointer is live, and
+ /// nothing matched it. Answering from the shared slot or the server default
+ /// would route the call somewhere the caller did not mean.
+ Mismatch,
+ /// No pointer information exists anywhere for this caller — an anonymous or
+ /// legacy call site, or an install with no lifecycle hooks feeding the
+ /// pointer. The configured default is the best and only answer.
+ Unset,
+}
+
+impl ActiveProjectLookup {
+ fn from_single(slot: Option<(WorkspaceId, ProjectId)>) -> Self {
+ match slot {
+ Some((workspace_id, project_id)) => Self::Resolved(workspace_id, project_id),
+ None => Self::Unset,
+ }
+ }
+}
+
impl ActorKey {
/// `true` when neither identity coordinate is present — used to short-
/// circuit the per-key map and fall back to the single slot.
@@ -485,19 +512,37 @@ impl ActiveProject {
/// whichever project published hook activity last.
#[must_use]
pub fn get_for(&self, actor: &ActorKey) -> Option<(WorkspaceId, ProjectId)> {
+ match self.lookup_for(actor) {
+ ActiveProjectLookup::Resolved(workspace_id, project_id) => {
+ Some((workspace_id, project_id))
+ }
+ ActiveProjectLookup::Mismatch | ActiveProjectLookup::Unset => None,
+ }
+ }
+
+ /// Same resolution as [`Self::get_for`], but says *why* it failed.
+ ///
+ /// `get_for` collapses two very different outcomes into `None`, which is fine
+ /// for a read (both mean "use your configured default") and wrong for a write.
+ /// A [`ActiveProjectLookup::Mismatch`] is a caller that carries a coordinate on
+ /// an install whose pointer is live — writing it to the default silently misfiles
+ /// a real page. [`ActiveProjectLookup::Unset`] is an install with no pointer
+ /// information at all, which has always used the default and must keep doing so.
+ #[must_use]
+ pub fn lookup_for(&self, actor: &ActorKey) -> ActiveProjectLookup {
if self.mode == ActiveProjectMode::Single || actor.is_empty() {
- return self.read_single();
+ return ActiveProjectLookup::from_single(self.read_single());
}
let scoped = self.scoped_key(actor);
if scoped.is_empty() {
- return self.read_single();
+ return ActiveProjectLookup::from_single(self.read_single());
}
let now = Instant::now();
let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());
- if let Some(found) = guard.get(&scoped, now) {
- return Some(found);
+ if let Some((workspace_id, project_id)) = guard.get(&scoped, now) {
+ return ActiveProjectLookup::Resolved(workspace_id, project_id);
}
// A keyed miss means one of two very different things.
@@ -519,14 +564,14 @@ impl ActiveProject {
session_id: None,
};
if guard.get(&identity_only, now).is_some() {
- return None;
+ return ActiveProjectLookup::Mismatch;
}
}
drop(guard);
if self.ever_keyed.load(Ordering::Relaxed) {
- return None;
+ return ActiveProjectLookup::Mismatch;
}
- self.read_single()
+ ActiveProjectLookup::from_single(self.read_single())
}
/// Whether the actor opted this session into `default_global` recall (via
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 0d87814a..40fde265 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -41,8 +41,8 @@ pub const DEFAULT_PROJECT_NAME: &str = "scratch";
pub const GLOBAL_SCOPE_PROJECT: &str = "_global";
pub use active_project::{
- ActiveProject, ActiveProjectMode, ActorKey, DEFAULT_MAX_ENTRIES, DEFAULT_PER_KEY_TTL,
- MidSessionRouting,
+ ActiveProject, ActiveProjectLookup, ActiveProjectMode, ActorKey, DEFAULT_MAX_ENTRIES,
+ DEFAULT_PER_KEY_TTL, MidSessionRouting,
};
pub use actor::{
ActorContext, AuthLevel, AuthzError, Capability, IdentityKey, OwnerFilter,
diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rs
index 8359052b..db096672 100644
--- a/crates/ai-memory-store/src/scope.rs
+++ b/crates/ai-memory-store/src/scope.rs
@@ -9,7 +9,7 @@
use std::collections::HashSet;
use std::fmt;
-use ai_memory_core::{ActiveProject, ActorKey, ProjectId, WorkspaceId};
+use ai_memory_core::{ActiveProject, ActiveProjectLookup, ActorKey, ProjectId, WorkspaceId};
use crate::error::StoreError;
use crate::{ReaderPool, WriterHandle};
@@ -17,6 +17,12 @@ use crate::{ReaderPool, WriterHandle};
/// Canonical error for partial explicit scope arguments.
pub const WORKSPACE_PROJECT_PAIR_REQUIRED: &str = "workspace and project must be provided together";
+/// Message for [`ScopeResolutionError::AmbiguousUnscopedWrite`]. Names both fixes,
+/// because the caller cannot tell from the failure alone which one applies to them.
+pub const AMBIGUOUS_UNSCOPED_WRITE: &str = "cannot resolve a target for this write: the active-project pointer does not match this \
+ caller. Pass an explicit workspace and project, or install the lifecycle hooks so the \
+ pointer is populated";
+
/// Human-readable workspace/project pair supplied by an API caller.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ScopeName {
@@ -88,6 +94,9 @@ pub enum ScopeResolutionError {
/// Project name supplied by the caller.
project: String,
},
+ /// An unscoped write from a caller whose active-project pointer did not
+ /// resolve. Writing it to the server default would silently misfile it.
+ AmbiguousUnscopedWrite,
/// A write-create policy was requested without a writer handle.
WriterRequired,
/// Underlying store failure.
@@ -105,6 +114,7 @@ impl ScopeResolutionError {
| ScopeResolutionError::ScopeWorkspaceEmpty
| ScopeResolutionError::ScopeProjectEmpty
| ScopeResolutionError::TooManyScopes { .. }
+ | ScopeResolutionError::AmbiguousUnscopedWrite
)
}
@@ -130,6 +140,7 @@ impl fmt::Display for ScopeResolutionError {
f.write_str("scope workspace cannot be empty")
}
ScopeResolutionError::ScopeProjectEmpty => f.write_str("scope project cannot be empty"),
+ ScopeResolutionError::AmbiguousUnscopedWrite => f.write_str(AMBIGUOUS_UNSCOPED_WRITE),
ScopeResolutionError::TooManyScopes { max, .. } => {
write!(f, "at most {max} scopes are allowed")
}
@@ -425,9 +436,23 @@ impl<'a> ScopeResolver<'a> {
if trimmed_opt(explicit_workspace).is_some() {
return Err(ScopeResolutionError::WorkspaceProjectPairRequired);
}
- let active = self.active_project.and_then(|a| a.get_for(actor));
- let (workspace_id, project_id) =
- active.unwrap_or((self.default_workspace_id, self.default_project_id));
+ // #564: a caller carrying a coordinate that resolves to nothing is not
+ // asking for the server default — it is a mismatch, and the page it
+ // writes would be real, attributed, searchable, and in a project nobody
+ // looks in. Refuse and name the two fixes. Callers with no coordinate at
+ // all (anonymous/legacy) keep resolving through the default as before.
+ let (workspace_id, project_id) = match self.active_project.map(|a| a.lookup_for(actor))
+ {
+ Some(ActiveProjectLookup::Resolved(workspace_id, project_id)) => {
+ (workspace_id, project_id)
+ }
+ Some(ActiveProjectLookup::Mismatch) => {
+ return Err(ScopeResolutionError::AmbiguousUnscopedWrite);
+ }
+ Some(ActiveProjectLookup::Unset) | None => {
+ (self.default_workspace_id, self.default_project_id)
+ }
+ };
return Ok(ResolvedScope {
workspace_id,
project_id,
@@ -956,4 +981,165 @@ mod tests {
}
);
}
+
+ /// Build a store with a `default/scratch` fallback plus an `ActiveProject`.
+ async fn scoped_fixture(
+ tmp: &tempfile::TempDir,
+ ) -> (Store, WorkspaceId, ProjectId, WorkspaceId, ProjectId) {
+ let store = Store::open(tmp.path()).unwrap();
+ let default_ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let default_proj = store
+ .writer
+ .get_or_create_project(default_ws, "scratch", None)
+ .await
+ .unwrap();
+ let team_ws = store.writer.get_or_create_workspace("team").await.unwrap();
+ let team_proj = store
+ .writer
+ .get_or_create_project(team_ws, "real-work", None)
+ .await
+ .unwrap();
+ (store, default_ws, default_proj, team_ws, team_proj)
+ }
+
+ #[tokio::test]
+ async fn unscoped_write_with_unresolvable_coordinate_errors() {
+ // #564: a caller that HAS a coordinate but whose pointer misses used to be
+ // written into the server default — a real, attributed, searchable page that
+ // nobody goes looking for. Refuse instead.
+ let tmp = tempfile::TempDir::new().unwrap();
+ let (store, default_ws, default_proj, team_ws, team_proj) = scoped_fixture(&tmp).await;
+
+ let active_project = ActiveProject::new();
+ let publisher = ActorKey {
+ user: Some("alice".into()),
+ session_id: Some("s1".into()),
+ };
+ active_project.set_for(&publisher, team_ws, team_proj, false);
+
+ // A different operator entirely: carries a coordinate, matches nothing.
+ let stranger = ActorKey {
+ user: Some("bob".into()),
+ session_id: Some("s9".into()),
+ };
+
+ let resolver = ScopeResolver::new(&store.reader, default_ws, default_proj)
+ .with_writer(&store.writer)
+ .with_active_project(&active_project);
+
+ let err = resolver
+ .resolve_write_args(None, None, &stranger)
+ .await
+ .unwrap_err();
+ assert_eq!(err, ScopeResolutionError::AmbiguousUnscopedWrite);
+ assert!(err.is_bad_request());
+ }
+
+ #[tokio::test]
+ async fn unscoped_write_without_any_coordinate_uses_the_shared_slot() {
+ // Anonymous/legacy callers resolve through the shared slot by design and must
+ // keep working — the error is only for a caller that HAS a coordinate. Note
+ // this resolves to the last published pointer, not the server default:
+ // `set_for` writes the shared slot alongside the per-actor entry.
+ let tmp = tempfile::TempDir::new().unwrap();
+ let (store, default_ws, default_proj, team_ws, team_proj) = scoped_fixture(&tmp).await;
+
+ let active_project = ActiveProject::new();
+ let publisher = ActorKey {
+ user: Some("alice".into()),
+ session_id: Some("s1".into()),
+ };
+ active_project.set_for(&publisher, team_ws, team_proj, false);
+
+ let resolver = ScopeResolver::new(&store.reader, default_ws, default_proj)
+ .with_writer(&store.writer)
+ .with_active_project(&active_project);
+
+ let scope = resolver
+ .resolve_write_args(None, None, &ActorKey::default())
+ .await
+ .unwrap();
+ assert_eq!(scope.as_tuple(), (team_ws, team_proj));
+ }
+
+ #[tokio::test]
+ async fn unscoped_write_on_an_install_with_no_pointer_uses_the_default() {
+ // An install with no lifecycle hooks feeding the pointer has never keyed
+ // anything and has an empty shared slot. There is no better information
+ // anywhere, so the configured default stays the answer — including for a
+ // caller that does carry a coordinate.
+ let tmp = tempfile::TempDir::new().unwrap();
+ let (store, default_ws, default_proj, _team_ws, _team_proj) = scoped_fixture(&tmp).await;
+
+ let active_project = ActiveProject::new();
+ let actor = ActorKey {
+ user: Some("alice".into()),
+ session_id: Some("s1".into()),
+ };
+
+ let resolver = ScopeResolver::new(&store.reader, default_ws, default_proj)
+ .with_writer(&store.writer)
+ .with_active_project(&active_project);
+
+ let scope = resolver
+ .resolve_write_args(None, None, &actor)
+ .await
+ .unwrap();
+ assert_eq!(scope.as_tuple(), (default_ws, default_proj));
+ }
+
+ #[tokio::test]
+ async fn unscoped_write_with_resolving_pointer_uses_it() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let (store, default_ws, default_proj, team_ws, team_proj) = scoped_fixture(&tmp).await;
+
+ let active_project = ActiveProject::new();
+ let actor = ActorKey {
+ user: Some("alice".into()),
+ session_id: Some("s1".into()),
+ };
+ active_project.set_for(&actor, team_ws, team_proj, false);
+
+ let resolver = ScopeResolver::new(&store.reader, default_ws, default_proj)
+ .with_writer(&store.writer)
+ .with_active_project(&active_project);
+
+ let scope = resolver
+ .resolve_write_args(None, None, &actor)
+ .await
+ .unwrap();
+ assert_eq!(scope.as_tuple(), (team_ws, team_proj));
+ }
+
+ #[tokio::test]
+ async fn unscoped_read_with_unresolvable_coordinate_still_falls_back() {
+ // Reads keep the fallback: a read answering from the default project is a
+ // wrong answer the caller can see; a write is a misfile they cannot.
+ let tmp = tempfile::TempDir::new().unwrap();
+ let (store, default_ws, default_proj, team_ws, team_proj) = scoped_fixture(&tmp).await;
+
+ let active_project = ActiveProject::new();
+ let publisher = ActorKey {
+ user: Some("alice".into()),
+ session_id: Some("s1".into()),
+ };
+ active_project.set_for(&publisher, team_ws, team_proj, false);
+ let stranger = ActorKey {
+ user: Some("bob".into()),
+ session_id: Some("s9".into()),
+ };
+
+ let resolver = ScopeResolver::new(&store.reader, default_ws, default_proj)
+ .with_active_project(&active_project);
+
+ let scope = resolver
+ .resolve_read_args(None, None, &stranger)
+ .await
+ .unwrap();
+ assert_eq!(scope.as_tuple(), (default_ws, default_proj));
+ }
}