Skip to content

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

Rust

feat(mcp): report which scope answered memory_status and warn on fallback (#757)

rafaelkenedyae52fdfe70f4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aedb30ba..838fce48 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- `memory_status` now reports which project answered: a `scope` object with
+ `workspace`, `project`, and `resolved_by` (`explicit`, `session`,
+ `shared_slot`, `startup_seed`, `default`, or `default_after_mismatch`). An
+ unscoped call from a static MCP client, whose transport session id is not a
+ lifecycle-hook session id, returned plausible counts for a project it never
+ named, with nothing in the response to question them; `resolved_by` now makes
+ that visible. The server also logs a warning whenever an unscoped MCP read is
+ resolved by the startup seed or by the default after a session mismatch,
+ rather than by the caller's own hook session (#757).
+
### Fixed
- The generated OpenCode and OpenCode 2 plugins now forward a subagent session's
`parentID` as the `agent_id` marker, so `[capture] drop_subagent_captures` can
diff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rs
index d765564d..927ab48e 100644
--- a/crates/ai-memory-core/src/active_project.rs
+++ b/crates/ai-memory-core/src/active_project.rs
@@ -193,6 +193,36 @@ pub enum ActiveProjectLookup {
Unset,
}
+/// Outcome of [`ActiveProject::read_pointer`]: the read-path answer and the
+/// source that gave it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ReadPointer {
+ /// The caller's own keyed entry.
+ Session(WorkspaceId, ProjectId),
+ /// The process-wide slot — whichever project published last. What a
+ /// caller with no coordinate reads, and every caller in `single` mode.
+ SharedSlot(WorkspaceId, ProjectId),
+ /// The startup seed (#678), standing in until the first hook event.
+ StartupSeed(WorkspaceId, ProjectId),
+ /// The caller carries a coordinate that matched no live hook session.
+ Mismatch,
+ /// No pointer information exists for this caller.
+ Unset,
+}
+
+impl ReadPointer {
+ /// The resolved ids, if any source gave one.
+ #[must_use]
+ pub fn ids(self) -> Option<(WorkspaceId, ProjectId)> {
+ match self {
+ Self::Session(workspace_id, project_id)
+ | Self::SharedSlot(workspace_id, project_id)
+ | Self::StartupSeed(workspace_id, project_id) => Some((workspace_id, project_id)),
+ Self::Mismatch | Self::Unset => None,
+ }
+ }
+}
+
impl ActiveProjectLookup {
fn from_single(slot: Option<(WorkspaceId, ProjectId)>) -> Self {
match slot {
@@ -565,12 +595,32 @@ impl ActiveProject {
/// attributed to a project reconstructed from someone else's history.
#[must_use]
pub fn get_for_read(&self, actor: &ActorKey) -> Option<(WorkspaceId, ProjectId)> {
- match self.lookup_for(actor) {
- ActiveProjectLookup::Resolved(workspace_id, project_id) => {
- Some((workspace_id, project_id))
+ self.read_pointer(actor).ids()
+ }
+
+ /// Read-path resolution with its provenance: the same answer as
+ /// [`Self::get_for_read`], plus which of the pointer's sources gave it.
+ ///
+ /// A keyed entry is evidence about *this* caller; the shared slot and the
+ /// startup seed are not — they hold whichever project published last, or
+ /// was active last on disk. Reporting that difference is what lets a caller
+ /// see it was answered about someone else's project (#757).
+ #[must_use]
+ pub fn read_pointer(&self, actor: &ActorKey) -> ReadPointer {
+ match self.lookup_traced(actor) {
+ (ActiveProjectLookup::Resolved(workspace_id, project_id), true) => {
+ ReadPointer::Session(workspace_id, project_id)
}
- ActiveProjectLookup::Unset => self.read_seeded(),
- ActiveProjectLookup::Mismatch => None,
+ (ActiveProjectLookup::Resolved(workspace_id, project_id), false) => {
+ ReadPointer::SharedSlot(workspace_id, project_id)
+ }
+ (ActiveProjectLookup::Unset, _) => match self.read_seeded() {
+ Some((workspace_id, project_id)) => {
+ ReadPointer::StartupSeed(workspace_id, project_id)
+ }
+ None => ReadPointer::Unset,
+ },
+ (ActiveProjectLookup::Mismatch, _) => ReadPointer::Mismatch,
}
}
@@ -584,19 +634,29 @@ impl ActiveProject {
/// information at all, which has always used the default and must keep doing so.
#[must_use]
pub fn lookup_for(&self, actor: &ActorKey) -> ActiveProjectLookup {
+ self.lookup_traced(actor).0
+ }
+
+ /// [`Self::lookup_for`], plus whether a `Resolved` answer came from the
+ /// caller's own keyed entry (`true`) or from the shared slot (`false`).
+ fn lookup_traced(&self, actor: &ActorKey) -> (ActiveProjectLookup, bool) {
+ let shared = |slot| (ActiveProjectLookup::from_single(slot), false);
if self.mode == ActiveProjectMode::Single || actor.is_empty() {
- return ActiveProjectLookup::from_single(self.read_single());
+ return shared(self.read_single());
}
let scoped = self.scoped_key(actor);
if scoped.is_empty() {
- return ActiveProjectLookup::from_single(self.read_single());
+ return shared(self.read_single());
}
let now = Instant::now();
let mut guard = self.per_actor.write().unwrap_or_else(|e| e.into_inner());
if let Some((workspace_id, project_id)) = guard.get(&scoped, now) {
- return ActiveProjectLookup::Resolved(workspace_id, project_id);
+ return (
+ ActiveProjectLookup::Resolved(workspace_id, project_id),
+ true,
+ );
}
// A keyed miss means one of two very different things.
@@ -618,14 +678,14 @@ impl ActiveProject {
session_id: None,
};
if guard.get(&identity_only, now).is_some() {
- return ActiveProjectLookup::Mismatch;
+ return (ActiveProjectLookup::Mismatch, false);
}
}
drop(guard);
if self.ever_keyed.load(Ordering::Relaxed) {
- return ActiveProjectLookup::Mismatch;
+ return (ActiveProjectLookup::Mismatch, false);
}
- ActiveProjectLookup::from_single(self.read_single())
+ shared(self.read_single())
}
/// Whether the actor opted this session into `default_global` recall (via
@@ -1699,4 +1759,45 @@ mod tests {
);
}
}
+
+ /// #757: `read_pointer` answers exactly what `get_for_read` does, and says
+ /// which source answered — a keyed hit is about this caller, the shared
+ /// slot and the seed are not.
+ #[test]
+ fn read_pointer_reports_the_source_of_each_answer() {
+ let (ws, seeded_proj) = ids(1);
+ let (_, own_proj) = ids(2);
+ let alice = key_actor("alice", "s-alice");
+ let stranger = key_actor("bob", "s-bob");
+
+ let ap = per_actor();
+ assert_eq!(ap.read_pointer(&stranger), ReadPointer::Unset);
+
+ ap.seed_read_fallback(ws, seeded_proj);
+ assert_eq!(
+ ap.read_pointer(&stranger),
+ ReadPointer::StartupSeed(ws, seeded_proj)
+ );
+
+ ap.set_for(&alice, ws, own_proj, false);
+ assert_eq!(ap.read_pointer(&alice), ReadPointer::Session(ws, own_proj));
+ assert_eq!(ap.read_pointer(&stranger), ReadPointer::Mismatch);
+ assert_eq!(
+ ap.read_pointer(&empty_actor()),
+ ReadPointer::SharedSlot(ws, own_proj),
+ "a caller with no coordinate reads whichever project published last"
+ );
+
+ for actor in [&alice, &stranger, &empty_actor()] {
+ assert_eq!(ap.read_pointer(actor).ids(), ap.get_for_read(actor));
+ }
+
+ let single = ActiveProject::with_mode(ActiveProjectMode::Single);
+ single.set_for(&alice, ws, own_proj, false);
+ assert_eq!(
+ single.read_pointer(&alice),
+ ReadPointer::SharedSlot(ws, own_proj),
+ "single mode has no keyed entries, even for the publisher"
+ );
+ }
}
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 2a5d61d7..f52e510b 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -43,7 +43,7 @@ pub const GLOBAL_SCOPE_PROJECT: &str = "_global";
pub use active_project::{
ActiveProject, ActiveProjectLookup, ActiveProjectMode, ActorKey, DEFAULT_MAX_ENTRIES,
- DEFAULT_PER_KEY_TTL, MidSessionRouting,
+ DEFAULT_PER_KEY_TTL, MidSessionRouting, ReadPointer,
};
pub use actor::{
ActorContext, AuthLevel, AuthzError, Capability, IdentityKey, OwnerFilter,
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index e1b78c22..0522f1f7 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -665,6 +665,20 @@ struct MemoryRecentResponse {
#[derive(Debug, Serialize)]
struct StatusResponse {
counts: ai_memory_store::StatusCounts,
+ /// Which project the counts belong to, and how it was chosen (#757).
+ scope: AnsweredScope,
+}
+
+/// The scope a response was answered from. Without it an unscoped call that
+/// fell back to another project returns plausible numbers the caller has no
+/// way to question.
+#[derive(Debug, Serialize)]
+struct AnsweredScope {
+ workspace: String,
+ project: String,
+ /// `explicit`, `session`, `shared_slot`, `startup_seed`, `default`, or
+ /// `default_after_mismatch`.
+ resolved_by: &'static str,
}
/// How many extra candidates to fetch for the reranker to reorder. The
@@ -1620,11 +1634,37 @@ impl AiMemoryServer {
explicit_project: Option<&str>,
actor: &ai_memory_core::ActorKey,
) -> Result<(WorkspaceId, ProjectId), McpError> {
- self.scope_resolver()
- .resolve_read_args(explicit_workspace, explicit_project, actor)
+ self.traced_ids_for_read_args(explicit_workspace, explicit_project, actor)
.await
- .map(ai_memory_store::ResolvedScope::as_tuple)
- .map_err(Self::scope_error)
+ .map(|(ids, _)| ids)
+ }
+
+ /// [`Self::effective_ids_for_read_args_with_actor`], plus where the scope
+ /// came from. Every unscoped read passes through here, so this is where a
+ /// fallback gets logged: a static MCP client answered from a project it
+ /// never named is otherwise indistinguishable from a correct answer (#757).
+ async fn traced_ids_for_read_args(
+ &self,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+ actor: &ai_memory_core::ActorKey,
+ ) -> Result<((WorkspaceId, ProjectId), ai_memory_store::ScopeSource), McpError> {
+ let (scope, source) = self
+ .scope_resolver()
+ .resolve_read_args_traced(explicit_workspace, explicit_project, actor)
+ .await
+ .map_err(Self::scope_error)?;
+ if source.is_fallback() {
+ tracing::warn!(
+ resolved_by = %source,
+ has_session_id = actor.session_id.is_some(),
+ workspace_id = %scope.workspace_id,
+ project_id = %scope.project_id,
+ "unscoped MCP read resolved by fallback, not by the caller's hook session; \
+ static MCP clients should pass workspace + project explicitly"
+ );
+ }
+ Ok((scope.as_tuple(), source))
}
/// Resolve the target for a WRITE, **creating** the workspace/project when
@@ -1704,6 +1744,17 @@ impl AiMemoryServer {
ws: ai_memory_core::WorkspaceId,
proj: ai_memory_core::ProjectId,
) -> String {
+ let (ws_name, proj_name) = self.scope_names(ws, proj).await;
+ format!("{ws_name}/{proj_name}")
+ }
+
+ /// Workspace and project names for a resolved scope, with the same
+ /// placeholders as [`Self::scope_label`] when a lookup fails.
+ async fn scope_names(
+ &self,
+ ws: ai_memory_core::WorkspaceId,
+ proj: ai_memory_core::ProjectId,
+ ) -> (String, String) {
let ws_name = self.reader.workspace_name_by_id(ws).await.ok().flatten();
let proj_name = self
.reader
@@ -1711,10 +1762,9 @@ impl AiMemoryServer {
.await
.ok()
.flatten();
- format!(
- "{}/{}",
- ws_name.as_deref().unwrap_or("<unknown-workspace>"),
- proj_name.as_deref().unwrap_or("<unknown-project>")
+ (
+ ws_name.unwrap_or_else(|| "<unknown-workspace>".to_owned()),
+ proj_name.unwrap_or_else(|| "<unknown-project>".to_owned()),
)
}
@@ -4192,15 +4242,18 @@ impl AiMemoryServer {
#[tool(description = "Report aggregate memory counts and runtime status \
(pages latest, pages all versions, sessions, observations). \
Use this at session start to see how much context the agent has \
- accumulated for this workspace.")]
+ accumulated for this workspace. `scope` names the workspace and \
+ project the counts belong to and `resolved_by` how it was chosen; \
+ `default_after_mismatch` or `startup_seed` means the call was not \
+ matched to this session, so pass `workspace` + `project`.")]
async fn memory_status(
&self,
Parameters(args): Parameters<StatusArgs>,
OptionalParts(parts): OptionalParts,
) -> Result<CallToolResult, McpError> {
let aps_actor = Self::actor_key_from_parts(Some(&parts));
- let (ws, proj) = self
- .effective_ids_for_read_args_with_actor(
+ let ((ws, proj), source) = self
+ .traced_ids_for_read_args(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
@@ -4211,7 +4264,15 @@ impl AiMemoryServer {
.status_counts_for_project(ws, proj)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
- let response = StatusResponse { counts };
+ let (workspace, project) = self.scope_names(ws, proj).await;
+ let response = StatusResponse {
+ counts,
+ scope: AnsweredScope {
+ workspace,
+ project,
+ resolved_by: source.as_str(),
+ },
+ };
ok_json(&response)
}
@@ -9547,6 +9608,77 @@ mod tests {
assert!(text.contains("\"pages_latest\": 1"));
}
+ #[tokio::test]
+ async fn memory_status_names_the_project_that_answered() {
+ // #757: a static MCP client's transport session id is not a hook
+ // session id, so its unscoped read cannot follow the caller's cwd. The
+ // counts must say whose they are, or they read as plausible and wrong.
+ let (_tmp, store, server, ws, _pj) = setup_server().await;
+ let neighbour = store
+ .writer
+ .get_or_create_project(ws, "neighbour", None)
+ .await
+ .unwrap();
+ let hook_session = ai_memory_core::ActorKey {
+ user: None,
+ session_id: Some("hook-session".into()),
+ };
+ let pointer = ActiveProject::new();
+ pointer.set_for(&hook_session, ws, neighbour, false);
+ let server = server.with_active_project(pointer);
+
+ let status = |session: &'static str, workspace: Option<&str>, project: Option<&str>| {
+ let mut parts = test_parts_default();
+ parts
+ .headers
+ .insert("mcp-session-id", session.parse().unwrap());
+ let args = StatusArgs {
+ workspace: workspace.map(str::to_owned),
+ project: project.map(str::to_owned),
+ };
+ let server = &server;
+ async move {
+ let result = server
+ .memory_status(Parameters(args), OptionalParts(parts))
+ .await
+ .unwrap();
+ let text = result
+ .content
+ .first()
+ .and_then(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .unwrap();
+ serde_json::from_str::<serde_json::Value>(&text).unwrap()["scope"].clone()
+ }
+ };
+
+ assert_eq!(
+ status("hook-session", None, None).await,
+ serde_json::json!({
+ "workspace": "default",
+ "project": "neighbour",
+ "resolved_by": "session",
+ })
+ );
+ assert_eq!(
+ status("transport-session", None, None).await,
+ serde_json::json!({
+ "workspace": "default",
+ "project": "scratch",
+ "resolved_by": "default_after_mismatch",
+ }),
+ "a static client falls back to the server default and says so"
+ );
+ assert_eq!(
+ status("transport-session", Some("default"), Some("neighbour")).await,
+ serde_json::json!({
+ "workspace": "default",
+ "project": "neighbour",
+ "resolved_by": "explicit",
+ })
+ );
+ }
+
#[tokio::test]
async fn memory_briefing_returns_structured_snapshot() {
let (_tmp, _store, server, _ws, _pj) = setup_server().await;
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 6d7f58b3..40e40272 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -71,9 +71,10 @@ pub use reader::{
};
pub use retrieval_tuning::{RetrievalTuning, is_session_recall_query};
pub use scope::{
- ResolvedScope, ScopeName, ScopeResolutionError, ScopeResolver, WORKSPACE_PROJECT_PAIR_REQUIRED,
- create_explicit_scope, create_global_scope, lookup_existing_scope, lookup_existing_workspace,
- lookup_global_scope, resolve_many_existing_scopes,
+ ResolvedScope, ScopeName, ScopeResolutionError, ScopeResolver, ScopeSource,
+ WORKSPACE_PROJECT_PAIR_REQUIRED, create_explicit_scope, create_global_scope,
+ lookup_existing_scope, lookup_existing_workspace, lookup_global_scope,
+ resolve_many_existing_scopes,
};
pub use session_consolidation::{SESSION_CONSOLIDATION_MAX_ATTEMPTS, SessionConsolidationJob};
pub use users::{
diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rs
index 8b36f6cb..abbed5c9 100644
--- a/crates/ai-memory-store/src/scope.rs
+++ b/crates/ai-memory-store/src/scope.rs
@@ -9,7 +9,9 @@
use std::collections::HashSet;
use std::fmt;
-use ai_memory_core::{ActiveProject, ActiveProjectLookup, ActorKey, ProjectId, WorkspaceId};
+use ai_memory_core::{
+ ActiveProject, ActiveProjectLookup, ActorKey, ProjectId, ReadPointer, WorkspaceId,
+};
use crate::error::StoreError;
use crate::{ReaderPool, WriterHandle};
@@ -60,6 +62,65 @@ impl ResolvedScope {
}
}
+/// Where a resolved read scope came from.
+///
+/// An unscoped read never fails: it degrades through the pointer, the startup
+/// seed and the server default. That keeps reads working, and it also means a
+/// caller cannot tell a correct answer from one about a different project
+/// (#757). Surfaces report this next to the scope they answered from.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum ScopeSource {
+ /// The caller named the project (with or without its workspace).
+ Explicit,
+ /// The caller's own keyed active-project entry — its hook session.
+ Session,
+ /// The process-wide slot: whichever project published last. The answer
+ /// for a caller with no coordinate, and for every caller in `single` mode.
+ SharedSlot,
+ /// The startup seed (#678): the most recently active project on disk,
+ /// standing in until the first hook event after a restart.
+ StartupSeed,
+ /// The server default, because no pointer information exists at all.
+ Default,
+ /// The server default, because the caller's coordinate matched no hook
+ /// session — a static MCP client whose transport session id is not a
+ /// lifecycle-hook session id.
+ DefaultAfterMismatch,
+}
+
+impl ScopeSource {
+ /// Stable snake_case label for responses and logs.
+ #[must_use]
+ pub fn as_str(self) -> &'static str {
+ match self {
+ ScopeSource::Explicit => "explicit",
+ ScopeSource::Session => "session",
+ ScopeSource::SharedSlot => "shared_slot",
+ ScopeSource::StartupSeed => "startup_seed",
+ ScopeSource::Default => "default",
+ ScopeSource::DefaultAfterMismatch => "default_after_mismatch",
+ }
+ }
+
+ /// True when the scope is a guess standing in for a caller the server
+ /// could not identify, rather than information about that caller. The
+ /// shared slot and the plain default are how pointer-less installs have
+ /// always worked, so they do not count.
+ #[must_use]
+ pub fn is_fallback(self) -> bool {
+ matches!(
+ self,
+ ScopeSource::StartupSeed | ScopeSource::DefaultAfterMismatch
+ )
+ }
+}
+
+impl fmt::Display for ScopeSource {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(self.as_str())
+ }
+}
+
/// Scope-resolution failure, independent of HTTP/MCP response types.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScopeResolutionError {
@@ -371,13 +432,28 @@ impl<'a> ScopeResolver<'a> {
explicit_project: Option<&str>,
actor: &ActorKey,
) -> Result<ResolvedScope, ScopeResolutionError> {
+ self.resolve_read_args_traced(explicit_workspace, explicit_project, actor)
+ .await
+ .map(|(scope, _)| scope)
+ }
+
+ /// [`Self::resolve_read_args`], plus where the scope came from.
+ pub async fn resolve_read_args_traced(
+ &self,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+ actor: &ActorKey,
+ ) -> Result<(ResolvedScope, ScopeSource), ScopeResolutionError> {
match (
trimmed_opt(explicit_workspace),
trimmed_opt(explicit_project),
) {
- (Some(workspace), Some(project)) => self.lookup_existing(workspace, project).await,
+ (Some(workspace), Some(project)) => self
+ .lookup_existing(workspace, project)
+ .await
+ .map(|scope| (scope, ScopeSource::Explicit)),
(Some(_), None) => Err(ScopeResolutionError::WorkspaceProjectPairRequired),
- (None, project) => self.resolve_current_or_project(project, actor).await,
+ (None, project) => self.resolve_current_or_project_traced(project, actor).await,
}
}
@@ -388,13 +464,33 @@ impl<'a> ScopeResolver<'a> {
explicit_project: Option<&str>,
actor: &ActorKey,
) -> Result<ResolvedScope, ScopeResolutionError> {
- // Read path, so `get_for_read`: it adds the startup seed for a caller
+ self.resolve_current_or_project_traced(explicit_project, actor)
+ .await
+ .map(|(scope, _)| scope)
+ }
+
+ async fn resolve_current_or_project_traced(
+ &self,
+ explicit_project: Option<&str>,
+ actor: &ActorKey,
+ ) -> Result<(ResolvedScope, ScopeSource), ScopeResolutionError> {
+ // Read path, so `read_pointer`: it adds the startup seed for a caller
// the pointer knows nothing about, which is every caller in the window
// between a restart and the first hook event (#678). `resolve_write_args`
// below deliberately stays on `get_for` / `lookup_for` — a write must
// not be attributed to a project reconstructed from history the caller
// never named.
- let active = self.active_project.and_then(|a| a.get_for_read(actor));
+ let pointer = self
+ .active_project
+ .map_or(ReadPointer::Unset, |a| a.read_pointer(actor));
+ let source = match pointer {
+ ReadPointer::Session(..) => ScopeSource::Session,
+ ReadPointer::SharedSlot(..) => ScopeSource::SharedSlot,
+ ReadPointer::StartupSeed(..) => ScopeSource::StartupSeed,
+ ReadPointer::Mismatch => ScopeSource::DefaultAfterMismatch,
+ ReadPointer::Unset => ScopeSource::Default,
+ };
+ let active = pointer.ids();
if let Some(project) = trimmed_opt(explicit_project) {
if let Some((active_ws, _)) = active
&& let Some(project_id) = self
@@ -402,10 +498,11 @@ impl<'a> ScopeResolver<'a> {
.find_project(active_ws, project.to_owned())
.await?
{
- return Ok(ResolvedScope {
+ let scope = ResolvedScope {
workspace_id: active_ws,
project_id,
- });
+ };
+ return Ok((scope, ScopeSource::Explicit));
}
if active.map(|(ws, _)| ws) != Some(self.default_workspace_id)
&& let Some(project_id) = self
@@ -413,10 +510,11 @@ impl<'a> ScopeResolver<'a> {
.find_project(self.default_workspace_id, project.to_owned())
.await?
{
- return Ok(ResolvedScope {
+ let scope = ResolvedScope {
workspace_id: self.default_workspace_id,
project_id,
- });
+ };
+ return Ok((scope, ScopeSource::Explicit));
}
return Err(ScopeResolutionError::ProjectNotFoundInActiveOrDefault {
project: project.to_owned(),
@@ -424,10 +522,11 @@ impl<'a> ScopeResolver<'a> {
}
let (workspace_id, project_id) =
active.unwrap_or((self.default_workspace_id, self.default_project_id));
- Ok(ResolvedScope {
+ let scope = ResolvedScope {
workspace_id,
project_id,
- })
+ };
+ Ok((scope, source))
}
/// Resolve a write target. Explicit names may create the workspace/project;
@@ -1207,4 +1306,144 @@ mod tests {
.unwrap();
assert_eq!(named.as_tuple(), (team_ws, team_proj));
}
+
+ #[tokio::test]
+ async fn traced_read_resolution_reports_where_the_scope_came_from() {
+ // #757: every row is a read that succeeds, so the source is the only
+ // way a caller can tell an answer about its own project from one about
+ // somebody else's.
+ let tmp = tempfile::TempDir::new().unwrap();
+ let (store, default_ws, default_proj, team_ws, team_proj) = scoped_fixture(&tmp).await;
+ let hook_session = ActorKey {
+ user: None,
+ session_id: Some("hook-session".into()),
+ };
+ let static_client = ActorKey {
+ user: None,
+ session_id: Some("mcp-transport-session".into()),
+ };
+
+ let unset = ActiveProject::new();
+ let seeded = ActiveProject::new();
+ seeded.seed_read_fallback(team_ws, team_proj);
+ let live = ActiveProject::new();
+ live.set_for(&hook_session, team_ws, team_proj, false);
+
+ struct Case<'a> {
+ name: &'static str,
+ pointer: Option<&'a ActiveProject>,
+ workspace: Option<&'static str>,
+ project: Option<&'static str>,
+ actor: &'a ActorKey,
+ expected: (WorkspaceId, ProjectId),
+ source: ScopeSource,
+ }
+ let cases = [
+ Case {
+ name: "explicit pair",
+ pointer: Some(&live),
+ workspace: Some("default"),
+ project: Some("scratch"),
+ actor: &static_client,
+ expected: (default_ws, default_proj),
+ source: ScopeSource::Explicit,
+ },
+ Case {
+ name: "project only",
+ pointer: Some(&live),
+ workspace: None,
+ project: Some("real-work"),
+ actor: &hook_session,
+ expected: (team_ws, team_proj),
+ source: ScopeSource::Explicit,
+ },
+ Case {
+ name: "caller's own hook session",
+ pointer: Some(&live),
+ workspace: None,
+ project: None,
+ actor: &hook_session,
+ expected: (team_ws, team_proj),
+ source: ScopeSource::Session,
+ },
+ Case {
+ name: "static client on a live install",
+ pointer: Some(&live),
+ workspace: None,
+ project: None,
+ actor: &static_client,
+ expected: (default_ws, default_proj),
+ source: ScopeSource::DefaultAfterMismatch,
+ },
+ Case {
+ name: "caller with no coordinate",
+ pointer: Some(&live),
+ workspace: None,
+ project: None,
+ actor: &ActorKey::default(),
+ expected: (team_ws, team_proj),
+ source: ScopeSource::SharedSlot,
+ },
+ Case {
+ name: "restart window",
+ pointer: Some(&seeded),
+ workspace: None,
+ project: None,
+ actor: &static_client,
+ expected: (team_ws, team_proj),
+ source: ScopeSource::StartupSeed,
+ },
+ Case {
+ name: "no pointer information",
+ pointer: Some(&unset),
+ workspace: None,
+ project: None,
+ actor: &static_client,
+ expected: (default_ws, default_proj),
+ source: ScopeSource::Default,
+ },
+ Case {
+ name: "no pointer attached",
+ pointer: None,
+ workspace: None,
+ project: None,
+ actor: &hook_session,
+ expected: (default_ws, default_proj),
+ source: ScopeSource::Default,
+ },
+ ];
+
+ for case in cases {
+ let mut resolver = ScopeResolver::new(&store.reader, default_ws, default_proj);
+ if let Some(pointer) = case.pointer {
+ resolver = resolver.with_active_project(pointer);
+ }
+ let (scope, source) = resolver
+ .resolve_read_args_traced(case.workspace, case.project, case.actor)
+ .await
+ .unwrap();
+ assert_eq!(scope.as_tuple(), case.expected, "{}", case.name);
+ assert_eq!(source, case.source, "{}", case.name);
+ let untraced = resolver
+ .resolve_read_args(case.workspace, case.project, case.actor)
+ .await
+ .unwrap();
+ assert_eq!(
+ untraced, scope,
+ "{}: tracing must not change the answer",
+ case.name
+ );
+ }
+
+ assert!(ScopeSource::DefaultAfterMismatch.is_fallback());
+ assert!(ScopeSource::StartupSeed.is_fallback());
+ for honest in [
+ ScopeSource::Explicit,
+ ScopeSource::Session,
+ ScopeSource::SharedSlot,
+ ScopeSource::Default,
+ ] {
+ assert!(!honest.is_fallback(), "{honest}");
+ }
+ }
}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index c7b43e16..93be6dce 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -373,7 +373,7 @@ invariants below.
| `memory_recent` | read-only | Most-recently-updated `is_latest=1` pages. |
| `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. Use when an agent needs more than the 24-word snippets from `memory_query`. |
| `memory_read_session_observations` | read-only | Page through ONE session's raw hook observations (`ObservationRecord` with full sanitized body, capped per row by `body_max_chars`), restricted to the rows that landed in the resolved scope and to sessions the caller may see; `total` and `elided_other_scope` report the in-scope count and the rows the session left in another project. `session_id` omitted reads the latest completed visible session. |
-| `memory_status` | read-only | Counts, paths, version. |
+| `memory_status` | read-only | Counts, paths, version, plus the `scope` that answered: `workspace`, `project`, and `resolved_by` (`explicit`, `session`, `shared_slot`, `startup_seed`, `default`, `default_after_mismatch`). Unscoped reads resolved by `startup_seed` or `default_after_mismatch` also log a server warning. |
| `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. Opt-in `settled_first: true` leads with up to 8 of the project's highest-standing `rule`/`decision` pages, ordered by evidence count then recency; off by default. |
| `memory_explore` | read-only | LLM prose digest over the briefing snapshot, degrading to JSON without a provider. |
| `memory_handoff_begin` | destructive | Open an owner-scoped handoff for the next agent; `shared=true` deliberately publishes it to the project. Optional `workspace` + `project` targets a named sibling workspace/project. |