Skip to content

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

Rust

refactor: centralize scope auth and wiki consistency

AkitaOnRailsaf6a20b65351
diff --git a/AGENTS.md b/AGENTS.md
index ffca4de2..359e9739 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -96,16 +96,28 @@ without disturbing the rest of the file.
library functions, render output. Provider-specific behavior belongs in the
provider module, not in command handlers.
- Treat typed boundaries as load-bearing: IDs, `PagePath`, `AgentKind`,
- sanitization, workspace/project resolution, and provider dialects should be
- parsed or normalized once and reused.
-- Preserve workspace/project isolation at shared helper boundaries. Read,
- search, embed, retention, and destructive paths must use no-create lookups
- and fail closed on partial or missing scope; only explicit write/create
- paths may create workspaces or projects.
-- Preserve auth boundaries at shared router/helper boundaries. In multi-user
- mode, every `/admin/*` route is root-only; DB-user tokens are for normal
- MCP/API read/write attribution and must not bypass admin gates or admission
- webhooks.
+ sanitization, workspace/project resolution, auth capability, and provider
+ dialects should be parsed or normalized once and reused.
+- Preserve workspace/project isolation through the shared scope framework.
+ New MCP/admin/web routes must use `ai_memory_store::ScopeResolver` or its
+ explicit helpers (`lookup_existing_scope`, `create_explicit_scope`,
+ `resolve_many_existing_scopes`) instead of hand-rolled workspace/project
+ lookup chains. Read, search, embed, retention, and destructive paths must use
+ no-create lookups and fail closed on partial or missing scope; only explicit
+ write/create paths may create workspaces or projects. PRs touching scope
+ resolution need table-driven tests for partial scope, missing explicit scope,
+ active-project precedence, and cross-workspace isolation.
+- Preserve auth boundaries through `AuthLevel::authorize(Capability::...)`.
+ Do not open-code username comparisons or ad hoc root checks in handlers. In
+ multi-user mode, every `/admin/*` route is root-only; DB-user tokens are for
+ normal MCP/API read/write attribution and must not bypass admin gates or
+ admission webhooks. PRs touching permissions need tests for root, DB-user,
+ and anonymous behavior.
+- Treat markdown as the source of truth and SQLite as the derived index. Wiki
+ mutations must go through `Wiki::write_page`, `Wiki::apply_batch`, or the
+ existing destructive helpers so sanitization, admission, attribution,
+ rollback, and index updates stay together. Do not write wiki files directly
+ from handlers; add recovery/rollback tests for any new disk+SQL mutation.
- Prefer explicit fallbacks over `unwrap`, `expect`, or `unreachable!` in
runtime paths. Panics are acceptable in tests only.
- Do not use `unsafe` for performance work in this project unless profiling
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fae4641a..8b1d7b40 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Changed
+- Centralized workspace/project scope resolution in `ai_memory_store::ScopeResolver`
+ and shared explicit helpers, then migrated MCP, admin, and web API routes onto
+ the common no-create/create-on-write policies.
+- Centralized auth checks behind `AuthLevel::authorize(Capability::...)` so admin,
+ user-management, and admission-skip behavior share one permission framework.
+- Tightened wiki/SQLite consistency semantics: markdown remains the source of
+ truth, batch writes install files before committing the derived SQL index, and
+ runtime SQL failures roll installed files back best-effort.
+
+### Added
+- Regression tests for shared scope policies, capability authorization, and
+ wiki-file rollback when `write_page` / `apply_batch` store upserts fail.
+
## [1.0.5] - 2026-06-14
### Fixed
diff --git a/crates/ai-memory-core/src/actor.rs b/crates/ai-memory-core/src/actor.rs
index c7c5be40..8f9253a1 100644
--- a/crates/ai-memory-core/src/actor.rs
+++ b/crates/ai-memory-core/src/actor.rs
@@ -111,6 +111,53 @@ pub enum AuthLevel {
User,
}
+/// Coarse-grained capabilities guarded by the auth layer.
+///
+/// This is intentionally smaller than a role/RBAC system: ai-memory v1 is
+/// single-tenant, so the policy surface is "normal read/write is allowed"
+/// versus "this operational action needs root". Keeping that decision in one
+/// enum prevents future handlers from open-coding subtly different checks.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Capability {
+ /// Operational `/admin/*` routes. In multi-user mode these are root-only;
+ /// in single-user/no-auth mode historical behavior is preserved.
+ Admin,
+ /// User lifecycle routes (`/admin/users*`). These are root-only even when
+ /// multi-user mode is not fully configured.
+ UserManagement,
+ /// Regular read surfaces (MCP/query/API/wiki reads).
+ NormalRead,
+ /// Regular write surfaces that attribute to the resolved actor.
+ NormalWrite,
+ /// Loop-prevention admission-chain skip header.
+ SkipAdmissionChain,
+}
+
+/// Authorization failure independent of any HTTP framework.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AuthzError {
+ /// The caller must authenticate before the capability can be used.
+ AuthenticationRequired(&'static str),
+ /// The caller authenticated, but the capability is root-only.
+ Forbidden(&'static str),
+}
+
+impl AuthzError {
+ /// Human-readable policy message for HTTP/MCP responses.
+ #[must_use]
+ pub fn message(self) -> &'static str {
+ match self {
+ AuthzError::AuthenticationRequired(msg) | AuthzError::Forbidden(msg) => msg,
+ }
+ }
+
+ /// True when the response should be an authentication challenge (HTTP 401).
+ #[must_use]
+ pub fn is_authentication_required(self) -> bool {
+ matches!(self, AuthzError::AuthenticationRequired(_))
+ }
+}
+
impl AuthLevel {
/// `true` if this tier is allowed to perform root-only admin
/// operations (currently just `Root`). Centralises the
@@ -120,6 +167,49 @@ impl AuthLevel {
pub fn is_root(self) -> bool {
matches!(self, AuthLevel::Root)
}
+
+ /// Check whether this auth tier can use `capability`.
+ ///
+ /// `multi_user_enabled` mirrors the configured `[auth].token_pepper` gate:
+ /// operational admin routes keep their historical single-user behavior
+ /// until multi-user mode is enabled, while user-management is always
+ /// root-only.
+ pub fn authorize(
+ self,
+ capability: Capability,
+ multi_user_enabled: bool,
+ ) -> Result<(), AuthzError> {
+ match capability {
+ Capability::NormalRead | Capability::NormalWrite => Ok(()),
+ Capability::SkipAdmissionChain => match self {
+ AuthLevel::User => {
+ Err(AuthzError::Forbidden("admission webhook skip is root-only"))
+ }
+ AuthLevel::Anonymous | AuthLevel::Root => Ok(()),
+ },
+ Capability::Admin if !multi_user_enabled => Ok(()),
+ Capability::Admin => self.require_root(
+ "admin operation requires authentication in multi-user mode",
+ "admin operation is root-only in multi-user mode",
+ ),
+ Capability::UserManagement => self.require_root(
+ "user management requires authentication",
+ "user management is root-only",
+ ),
+ }
+ }
+
+ fn require_root(
+ self,
+ anonymous_message: &'static str,
+ user_message: &'static str,
+ ) -> Result<(), AuthzError> {
+ match self {
+ AuthLevel::Root => Ok(()),
+ AuthLevel::Anonymous => Err(AuthzError::AuthenticationRequired(anonymous_message)),
+ AuthLevel::User => Err(AuthzError::Forbidden(user_message)),
+ }
+ }
}
impl ActorContext {
@@ -160,6 +250,68 @@ mod tests {
assert_eq!(a, ActorContext::anonymous());
}
+ #[test]
+ fn admin_capability_preserves_single_user_mode() {
+ for level in [AuthLevel::Anonymous, AuthLevel::Root, AuthLevel::User] {
+ assert_eq!(level.authorize(Capability::Admin, false), Ok(()));
+ }
+ }
+
+ #[test]
+ fn admin_capability_is_root_only_in_multi_user_mode() {
+ assert_eq!(AuthLevel::Root.authorize(Capability::Admin, true), Ok(()));
+ assert!(matches!(
+ AuthLevel::Anonymous.authorize(Capability::Admin, true),
+ Err(AuthzError::AuthenticationRequired(
+ "admin operation requires authentication in multi-user mode"
+ ))
+ ));
+ assert!(matches!(
+ AuthLevel::User.authorize(Capability::Admin, true),
+ Err(AuthzError::Forbidden(
+ "admin operation is root-only in multi-user mode"
+ ))
+ ));
+ }
+
+ #[test]
+ fn user_management_is_always_root_only() {
+ assert_eq!(
+ AuthLevel::Root.authorize(Capability::UserManagement, false),
+ Ok(())
+ );
+ assert_eq!(
+ AuthLevel::Root.authorize(Capability::UserManagement, true),
+ Ok(())
+ );
+ assert!(matches!(
+ AuthLevel::Anonymous.authorize(Capability::UserManagement, false),
+ Err(AuthzError::AuthenticationRequired(
+ "user management requires authentication"
+ ))
+ ));
+ assert!(matches!(
+ AuthLevel::User.authorize(Capability::UserManagement, true),
+ Err(AuthzError::Forbidden("user management is root-only"))
+ ));
+ }
+
+ #[test]
+ fn skip_admission_chain_rejects_db_users() {
+ assert_eq!(
+ AuthLevel::Root.authorize(Capability::SkipAdmissionChain, true),
+ Ok(())
+ );
+ assert_eq!(
+ AuthLevel::Anonymous.authorize(Capability::SkipAdmissionChain, true),
+ Ok(())
+ );
+ assert!(matches!(
+ AuthLevel::User.authorize(Capability::SkipAdmissionChain, true),
+ Err(AuthzError::Forbidden("admission webhook skip is root-only"))
+ ));
+ }
+
#[test]
fn has_any_truth_table() {
// Each field individually flips has_any() to true. Catches an
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 03b6ae77..5fbc57d2 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -25,7 +25,7 @@ pub const DEFAULT_PROJECT_NAME: &str = "scratch";
pub use active_project::{
ActiveProject, ActiveProjectMode, ActorKey, DEFAULT_MAX_ENTRIES, DEFAULT_PER_KEY_TTL,
};
-pub use actor::{ActorContext, AuthLevel};
+pub use actor::{ActorContext, AuthLevel, AuthzError, Capability};
pub use error::{MemoryError, MemoryResult};
pub use handoff::{Handoff, HandoffState, NewHandoff};
pub use ids::{
diff --git a/crates/ai-memory-mcp/src/actor.rs b/crates/ai-memory-mcp/src/actor.rs
index c1e2124e..a7c426ad 100644
--- a/crates/ai-memory-mcp/src/actor.rs
+++ b/crates/ai-memory-mcp/src/actor.rs
@@ -24,7 +24,7 @@
//! bypass a reject-policy admission webhook by setting a client-controlled
//! header.
-use ai_memory_core::{ActorContext, AuthLevel, UserId};
+use ai_memory_core::{ActorContext, AuthLevel, Capability, UserId};
use axum::http::HeaderMap;
use axum::http::request::Parts;
@@ -98,11 +98,18 @@ pub fn skip_webhooks_from_headers(headers: &HeaderMap) -> Vec<String> {
/// Parse the skip-list header only for trusted re-entry contexts.
#[must_use]
pub fn skip_webhooks_from_parts(parts: &Parts) -> Vec<String> {
- match parts.extensions.get::<AuthLevel>().copied() {
- Some(AuthLevel::User) => Vec::new(),
- Some(AuthLevel::Root | AuthLevel::Anonymous) | None => {
- skip_webhooks_from_headers(&parts.headers)
- }
+ let level = parts
+ .extensions
+ .get::<AuthLevel>()
+ .copied()
+ .unwrap_or(AuthLevel::Anonymous);
+ if level
+ .authorize(Capability::SkipAdmissionChain, true)
+ .is_ok()
+ {
+ skip_webhooks_from_headers(&parts.headers)
+ } else {
+ Vec::new()
}
}
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 8b2a5c16..207b3aea 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -35,12 +35,13 @@ use ai_memory_consolidate::{
prune_sources_to_budget, run_lint, run_sweep,
};
use ai_memory_core::{
- ActiveProject, DEFAULT_PROJECT_NAME, DEFAULT_WORKSPACE_NAME, PagePath, ProjectId, SessionId,
- Tier, WorkspaceId,
+ ActiveProject, Capability, DEFAULT_PROJECT_NAME, DEFAULT_WORKSPACE_NAME, PagePath, ProjectId,
+ SessionId, Tier, WorkspaceId,
};
use ai_memory_llm::{Embedder, LlmProvider, ProviderHealth, ProviderHealthSnapshot};
use ai_memory_store::{
- DecayParams, EmbeddingWrite, ReaderPool, StoreError, WriterHandle, f32_vec_to_bytes,
+ DecayParams, EmbeddingWrite, ReaderPool, ScopeResolutionError, StoreError, WriterHandle,
+ create_explicit_scope, f32_vec_to_bytes, lookup_existing_scope,
};
use ai_memory_wiki::{AdmissionContext, AdmissionOp, Markdown, Wiki, WikiError, WritePageRequest};
use axum::Json;
@@ -212,29 +213,27 @@ async fn require_root_for_multiuser_admin(
req: axum::http::Request<Body>,
next: Next,
) -> Response {
- if state.token_pepper.is_none() {
- return next.run(req).await;
- }
let level = req
.extensions()
.get::<ai_memory_core::AuthLevel>()
.copied()
.unwrap_or(ai_memory_core::AuthLevel::Anonymous);
- if level.is_root() {
- return next.run(req).await;
+ match level.authorize(Capability::Admin, state.token_pepper.is_some()) {
+ Ok(()) => next.run(req).await,
+ Err(e) => (
+ authz_status(e),
+ Json(serde_json::json!({ "error": e.message() })),
+ )
+ .into_response(),
+ }
+}
+
+fn authz_status(err: ai_memory_core::AuthzError) -> StatusCode {
+ if err.is_authentication_required() {
+ StatusCode::UNAUTHORIZED
+ } else {
+ StatusCode::FORBIDDEN
}
- let (code, msg) = match level {
- ai_memory_core::AuthLevel::Anonymous => (
- StatusCode::UNAUTHORIZED,
- "admin operation requires authentication in multi-user mode",
- ),
- ai_memory_core::AuthLevel::User => (
- StatusCode::FORBIDDEN,
- "admin operation is root-only in multi-user mode",
- ),
- ai_memory_core::AuthLevel::Root => return next.run(req).await,
- };
- (code, Json(serde_json::json!({ "error": msg }))).into_response()
}
// ---------------------------------------------------------------------
@@ -624,17 +623,10 @@ async fn create_ws_proj(
workspace: &str,
project: &str,
) -> Result<(WorkspaceId, ProjectId), (StatusCode, Json<serde_json::Value>)> {
- let ws = state
- .writer
- .get_or_create_workspace(workspace.to_string())
- .await
- .map_err(|e| internal_err(format!("workspace: {e}")))?;
- let proj = state
- .writer
- .get_or_create_project(ws, project.to_string(), None)
+ create_explicit_scope(&state.writer, workspace, project)
.await
- .map_err(|e| internal_err(format!("project: {e}")))?;
- Ok((ws, proj))
+ .map(ai_memory_store::ResolvedScope::as_tuple)
+ .map_err(scope_err)
}
/// Look up workspace + project by name **without** auto-creating them.
@@ -646,31 +638,41 @@ async fn lookup_ws_proj_no_create(
workspace: &str,
project: &str,
) -> Result<(WorkspaceId, ProjectId), (StatusCode, Json<serde_json::Value>)> {
- let ws_id = match state.reader.find_workspace(workspace.to_string()).await {
- Ok(Some(id)) => id,
- Ok(None) => {
- return Err((
- StatusCode::NOT_FOUND,
- Json(serde_json::json!({
- "error": format!("workspace '{workspace}' not found")
- })),
- ));
- }
- Err(e) => return Err(internal_err(e.to_string())),
- };
- let proj_id = match state.reader.find_project(ws_id, project.to_string()).await {
- Ok(Some(id)) => id,
- Ok(None) => {
- return Err((
- StatusCode::NOT_FOUND,
- Json(serde_json::json!({
- "error": format!("project '{project}' not found in workspace '{workspace}'")
- })),
- ));
- }
- Err(e) => return Err(internal_err(e.to_string())),
+ lookup_existing_scope(&state.reader, workspace, project)
+ .await
+ .map(ai_memory_store::ResolvedScope::as_tuple)
+ .map_err(scope_err)
+}
+
+fn scope_err(err: ScopeResolutionError) -> (StatusCode, Json<serde_json::Value>) {
+ let status = if err.is_bad_request() {
+ StatusCode::BAD_REQUEST
+ } else if err.is_not_found() {
+ StatusCode::NOT_FOUND
+ } else {
+ StatusCode::INTERNAL_SERVER_ERROR
};
- Ok((ws_id, proj_id))
+ (
+ status,
+ Json(serde_json::json!({ "error": err.to_string() })),
+ )
+}
+
+fn skip_webhooks_for_admin_request(
+ level_ext: Option<axum::Extension<ai_memory_core::AuthLevel>>,
+ headers: &HeaderMap,
+) -> Vec<String> {
+ let level = level_ext
+ .map(|axum::Extension(level)| level)
+ .unwrap_or(ai_memory_core::AuthLevel::Anonymous);
+ if level
+ .authorize(Capability::SkipAdmissionChain, true)
+ .is_ok()
+ {
+ crate::actor::skip_webhooks_from_headers(headers)
+ } else {
+ Vec::new()
+ }
}
// ---------------------------------------------------------------------
@@ -2847,12 +2849,7 @@ async fn handle_write_page(
.map(|axum::Extension(actor)| actor)
.unwrap_or_else(ai_memory_core::ActorContext::anonymous);
let author_id = author_ext.map(|axum::Extension(author_id)| author_id);
- let skip_webhooks = match level_ext.map(|axum::Extension(level)| level) {
- Some(ai_memory_core::AuthLevel::User) => Vec::new(),
- Some(ai_memory_core::AuthLevel::Root | ai_memory_core::AuthLevel::Anonymous) | None => {
- crate::actor::skip_webhooks_from_headers(&headers)
- }
- };
+ let skip_webhooks = skip_webhooks_for_admin_request(level_ext, &headers);
let admission_ctx = if actor.has_any() || !skip_webhooks.is_empty() {
Some(AdmissionContext {
op: AdmissionOp::WritePage,
@@ -2974,12 +2971,7 @@ async fn handle_delete_page(
let actor = actor_ext
.map(|axum::Extension(actor)| actor)
.unwrap_or_else(ai_memory_core::ActorContext::anonymous);
- let skip_webhooks = match level_ext.map(|axum::Extension(level)| level) {
- Some(ai_memory_core::AuthLevel::User) => Vec::new(),
- Some(ai_memory_core::AuthLevel::Root | ai_memory_core::AuthLevel::Anonymous) | None => {
- crate::actor::skip_webhooks_from_headers(&headers)
- }
- };
+ let skip_webhooks = skip_webhooks_for_admin_request(level_ext, &headers);
let admission_ctx = if actor.has_any() || !skip_webhooks.is_empty() {
Some(AdmissionContext {
actor,
@@ -3064,18 +3056,14 @@ struct UserListResponse {
fn require_root(
level: ai_memory_core::AuthLevel,
) -> Result<(), (StatusCode, Json<serde_json::Value>)> {
- if level.is_root() {
- return Ok(());
- }
- let (code, msg) = match level {
- ai_memory_core::AuthLevel::Anonymous => (
- StatusCode::UNAUTHORIZED,
- "user management requires authentication",
- ),
- ai_memory_core::AuthLevel::User => (StatusCode::FORBIDDEN, "user management is root-only"),
- ai_memory_core::AuthLevel::Root => return Ok(()),
- };
- Err((code, Json(serde_json::json!({ "error": msg }))))
+ level
+ .authorize(Capability::UserManagement, true)
+ .map_err(|e| {
+ (
+ authz_status(e),
+ Json(serde_json::json!({ "error": e.message() })),
+ )
+ })
}
/// Get the active token-pepper. Returns 503 when multi-user wasn't
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 0cd0d22f..75467581 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -1,6 +1,6 @@
//! [`AiMemoryServer`] — the MCP server skeleton + tool router.
-use std::collections::{HashMap, HashSet};
+use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
@@ -10,7 +10,7 @@ use ai_memory_core::{
SessionId, Tier, WorkspaceId,
};
use ai_memory_llm::{Embedder, LlmProvider};
-use ai_memory_store::{DecayParams, PageHit, ReaderPool, WriterHandle};
+use ai_memory_store::{DecayParams, PageHit, ReaderPool, ScopeName, ScopeResolver, WriterHandle};
use ai_memory_wiki::{Wiki, WikiError, WritePageRequest};
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::tool::Extension;
@@ -502,6 +502,16 @@ struct WritePageArgs {
#[tool_router]
impl AiMemoryServer {
+ fn scope_resolver(&self) -> ScopeResolver<'_> {
+ ScopeResolver::new(&self.reader, self.workspace_id, self.project_id)
+ .with_writer(&self.writer)
+ .with_active_project(&self.active_project)
+ }
+
+ fn scope_error(err: ai_memory_store::ScopeResolutionError) -> McpError {
+ McpError::internal_error(err.to_string(), None)
+ }
+
/// Construct a server backed by the given reader/writer + 3-tuple
/// identity coordinates.
#[must_use]
@@ -609,32 +619,17 @@ impl AiMemoryServer {
/// `actor` is built by [`Self::actor_key_from_parts`]; pass
/// `ActorKey::default()` when the call site has no request context.
/// Empty actor → fall back to the single slot (legacy behaviour).
+ #[cfg(test)]
async fn effective_ids_with_actor(
&self,
explicit_project: Option<&str>,
actor: &ai_memory_core::ActorKey,
) -> Result<(WorkspaceId, ProjectId), McpError> {
- let active = self.active_project.get_for(actor);
- if let Some(name) = explicit_project.map(str::trim).filter(|s| !s.is_empty()) {
- if let Some((active_ws, _)) = active
- && let Ok(Some(pid)) = self.reader.find_project(active_ws, name.to_string()).await
- {
- return Ok((active_ws, pid));
- }
- if active.map(|(ws, _)| ws) != Some(self.workspace_id)
- && let Ok(Some(pid)) = self
- .reader
- .find_project(self.workspace_id, name.to_string())
- .await
- {
- return Ok((self.workspace_id, pid));
- }
- return Err(McpError::internal_error(
- format!("project '{name}' not found in the active or default workspace"),
- None,
- ));
- }
- Ok(active.unwrap_or((self.workspace_id, self.project_id)))
+ self.scope_resolver()
+ .resolve_current_or_project(explicit_project, actor)
+ .await
+ .map(ai_memory_store::ResolvedScope::as_tuple)
+ .map_err(Self::scope_error)
}
async fn effective_ids_for_read_args_with_actor(
@@ -643,41 +638,11 @@ impl AiMemoryServer {
explicit_project: Option<&str>,
actor: &ai_memory_core::ActorKey,
) -> Result<(WorkspaceId, ProjectId), McpError> {
- match (
- trimmed_opt(explicit_workspace),
- trimmed_opt(explicit_project),
- ) {
- (Some(workspace), Some(project)) => self.lookup_ids(workspace, project).await,
- (Some(_), None) => Err(McpError::internal_error(
- "workspace and project must be provided together",
- None,
- )),
- (None, project) => self.effective_ids_with_actor(project, actor).await,
- }
- }
-
- async fn lookup_ids(
- &self,
- workspace: &str,
- project: &str,
- ) -> Result<(WorkspaceId, ProjectId), McpError> {
- let workspace_id = self
- .reader
- .find_workspace(workspace.to_owned())
- .await
- .map_err(|e| McpError::internal_error(e.to_string(), None))?
- .ok_or_else(|| {
- McpError::internal_error(format!("workspace '{workspace}' not found"), None)
- })?;
- let project_id = self
- .reader
- .find_project(workspace_id, project.to_owned())
+ self.scope_resolver()
+ .resolve_read_args(explicit_workspace, explicit_project, actor)
.await
- .map_err(|e| McpError::internal_error(e.to_string(), None))?
- .ok_or_else(|| {
- McpError::internal_error(format!("project '{project}' not found"), None)
- })?;
- Ok((workspace_id, project_id))
+ .map(ai_memory_store::ResolvedScope::as_tuple)
+ .map_err(Self::scope_error)
}
/// Resolve the target for a WRITE, **creating** the workspace/project when
@@ -719,65 +684,31 @@ impl AiMemoryServer {
explicit_project: Option<&str>,
actor: &ai_memory_core::ActorKey,
) -> Result<(WorkspaceId, ProjectId), McpError> {
- let Some(project) = trimmed_opt(explicit_project) else {
- if trimmed_opt(explicit_workspace).is_some() {
- return Err(McpError::internal_error(
- "workspace and project must be provided together",
- None,
- ));
- }
- // No explicit project → current project (hook-published active, or
- // the baked default).
- return Ok(self
- .active_project
- .get_for(actor)
- .unwrap_or((self.workspace_id, self.project_id)));
- };
- let workspace_id = match trimmed_opt(explicit_workspace) {
- Some(name) => self
- .writer
- .get_or_create_workspace(name.to_string())
- .await
- .map_err(|e| McpError::internal_error(e.to_string(), None))?,
- // No explicit workspace → the cwd's (active) workspace, not the
- // baked global default — keeps writes consistent with reads.
- None => self
- .active_project
- .get_for(actor)
- .map(|(ws, _)| ws)
- .unwrap_or(self.workspace_id),
- };
- let project_id = self
- .writer
- .get_or_create_project(workspace_id, project.to_string(), None)
+ self.scope_resolver()
+ .resolve_write_args(explicit_workspace, explicit_project, actor)
.await
- .map_err(|e| McpError::internal_error(e.to_string(), None))?;
- Ok((workspace_id, project_id))
+ .map(ai_memory_store::ResolvedScope::as_tuple)
+ .map_err(Self::scope_error)
}
async fn resolve_query_scopes(
&self,
scopes: &[MemoryScopeArg],
) -> Result<Vec<(WorkspaceId, ProjectId)>, McpError> {
- if scopes.len() > MAX_QUERY_SCOPES {
- return Err(McpError::internal_error(
- format!("at most {MAX_QUERY_SCOPES} scopes are allowed"),
- None,
- ));
- }
- let mut seen = HashSet::new();
- let mut resolved = Vec::new();
- for scope in scopes {
- let workspace = trimmed_opt(Some(&scope.workspace))
- .ok_or_else(|| McpError::internal_error("scope workspace cannot be empty", None))?;
- let project = trimmed_opt(Some(&scope.project))
- .ok_or_else(|| McpError::internal_error("scope project cannot be empty", None))?;
- let ids = self.lookup_ids(workspace, project).await?;
- if seen.insert(ids) {
- resolved.push(ids);
- }
- }
- Ok(resolved)
+ let names: Vec<_> = scopes
+ .iter()
+ .map(|scope| ScopeName::new(&scope.workspace, &scope.project))
+ .collect();
+ self.scope_resolver()
+ .resolve_many_existing(&names, MAX_QUERY_SCOPES)
+ .await
+ .map(|scopes| {
+ scopes
+ .into_iter()
+ .map(ai_memory_store::ResolvedScope::as_tuple)
+ .collect()
+ })
+ .map_err(Self::scope_error)
}
async fn embed_query(&self, query: &str) -> Option<Vec<f32>> {
@@ -1829,10 +1760,6 @@ fn is_missing_wiki_file(err: &WikiError) -> bool {
matches!(err, WikiError::Io(e) if e.kind() == std::io::ErrorKind::NotFound)
}
-fn trimmed_opt(value: Option<&str>) -> Option<&str> {
- value.map(str::trim).filter(|s| !s.is_empty())
-}
-
/// Description of how long it's been since the last observation.
/// `memory_explore` uses this both to size its prompt verbosity and
/// to give the LLM an explicit "time gap is N hours" cue.
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index b2c16b7f..21655025 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -18,6 +18,7 @@ mod fts_query;
mod migrations;
mod ops;
mod reader;
+mod scope;
pub mod users;
mod writer;
@@ -33,6 +34,10 @@ pub use reader::{
ReindexTargetStatus, RelatedPage, ScopeRow, StatusCounts, StoredEmbedding, StoredPageBody,
WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
};
+pub use scope::{
+ ResolvedScope, ScopeName, ScopeResolutionError, ScopeResolver, WORKSPACE_PROJECT_PAIR_REQUIRED,
+ create_explicit_scope, lookup_existing_scope, resolve_many_existing_scopes,
+};
pub use users::{TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, generate_token, hash_token};
pub use writer::WriterHandle;
diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rs
new file mode 100644
index 00000000..a8da5cbe
--- /dev/null
+++ b/crates/ai-memory-store/src/scope.rs
@@ -0,0 +1,601 @@
+//! Shared workspace/project scope resolution.
+//!
+//! HTTP admin routes, MCP tools, and the read-only web API all need the same
+//! boundary rules: explicit read scopes fail closed, write scopes are the only
+//! place that may create projects, and current-project defaults must respect the
+//! actor-scoped active-project pointer. Keeping those policies here prevents
+//! each surface from growing its own subtly different fallback chain.
+
+use std::collections::HashSet;
+use std::fmt;
+
+use ai_memory_core::{ActiveProject, ActorKey, ProjectId, WorkspaceId};
+
+use crate::error::StoreError;
+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";
+
+/// Human-readable workspace/project pair supplied by an API caller.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct ScopeName {
+ /// Workspace name.
+ pub workspace: String,
+ /// Project name within the workspace.
+ pub project: String,
+}
+
+impl ScopeName {
+ /// Build a scope name from any string-like values.
+ #[must_use]
+ pub fn new(workspace: impl Into<String>, project: impl Into<String>) -> Self {
+ Self {
+ workspace: workspace.into(),
+ project: project.into(),
+ }
+ }
+}
+
+/// Resolved database ids for a project scope.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct ResolvedScope {
+ /// Owning workspace id.
+ pub workspace_id: WorkspaceId,
+ /// Project id inside the workspace.
+ pub project_id: ProjectId,
+}
+
+impl ResolvedScope {
+ /// Return the ids as the tuple used by existing reader/writer APIs.
+ #[must_use]
+ pub fn as_tuple(self) -> (WorkspaceId, ProjectId) {
+ (self.workspace_id, self.project_id)
+ }
+}
+
+/// Scope-resolution failure, independent of HTTP/MCP response types.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ScopeResolutionError {
+ /// Only one of workspace/project was provided.
+ WorkspaceProjectPairRequired,
+ /// A multi-scope entry had an empty workspace.
+ ScopeWorkspaceEmpty,
+ /// A multi-scope entry had an empty project.
+ ScopeProjectEmpty,
+ /// The caller supplied more scopes than the surface allows.
+ TooManyScopes {
+ /// Maximum number of scopes allowed by the caller surface.
+ max: usize,
+ /// Number of scopes the request supplied.
+ actual: usize,
+ },
+ /// A workspace name did not resolve.
+ WorkspaceNotFound {
+ /// Workspace name supplied by the caller.
+ workspace: String,
+ },
+ /// A project name did not resolve inside the provided workspace.
+ ProjectNotFoundInWorkspace {
+ /// Workspace name supplied by the caller.
+ workspace: String,
+ /// Project name supplied by the caller.
+ project: String,
+ },
+ /// A project-only read did not resolve in either the actor's active
+ /// workspace or the server's default workspace.
+ ProjectNotFoundInActiveOrDefault {
+ /// Project name supplied by the caller.
+ project: String,
+ },
+ /// A write-create policy was requested without a writer handle.
+ WriterRequired,
+ /// Underlying store failure.
+ Store(String),
+}
+
+impl ScopeResolutionError {
+ /// True when the error is caused by malformed caller input rather than a
+ /// missing object or an internal store failure.
+ #[must_use]
+ pub fn is_bad_request(&self) -> bool {
+ matches!(
+ self,
+ ScopeResolutionError::WorkspaceProjectPairRequired
+ | ScopeResolutionError::ScopeWorkspaceEmpty
+ | ScopeResolutionError::ScopeProjectEmpty
+ | ScopeResolutionError::TooManyScopes { .. }
+ )
+ }
+
+ /// True when the caller named a scope that does not exist.
+ #[must_use]
+ pub fn is_not_found(&self) -> bool {
+ matches!(
+ self,
+ ScopeResolutionError::WorkspaceNotFound { .. }
+ | ScopeResolutionError::ProjectNotFoundInWorkspace { .. }
+ | ScopeResolutionError::ProjectNotFoundInActiveOrDefault { .. }
+ )
+ }
+}
+
+impl fmt::Display for ScopeResolutionError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ ScopeResolutionError::WorkspaceProjectPairRequired => {
+ f.write_str(WORKSPACE_PROJECT_PAIR_REQUIRED)
+ }
+ ScopeResolutionError::ScopeWorkspaceEmpty => {
+ f.write_str("scope workspace cannot be empty")
+ }
+ ScopeResolutionError::ScopeProjectEmpty => f.write_str("scope project cannot be empty"),
+ ScopeResolutionError::TooManyScopes { max, .. } => {
+ write!(f, "at most {max} scopes are allowed")
+ }
+ ScopeResolutionError::WorkspaceNotFound { workspace } => {
+ write!(f, "workspace '{workspace}' not found")
+ }
+ ScopeResolutionError::ProjectNotFoundInWorkspace { workspace, project } => {
+ write!(
+ f,
+ "project '{project}' not found in workspace '{workspace}'"
+ )
+ }
+ ScopeResolutionError::ProjectNotFoundInActiveOrDefault { project } => {
+ write!(
+ f,
+ "project '{project}' not found in the active or default workspace"
+ )
+ }
+ ScopeResolutionError::WriterRequired => {
+ f.write_str("scope resolver requires a writer for create-on-write resolution")
+ }
+ ScopeResolutionError::Store(msg) => f.write_str(msg),
+ }
+ }
+}
+
+impl std::error::Error for ScopeResolutionError {}
+
+impl From<StoreError> for ScopeResolutionError {
+ fn from(value: StoreError) -> Self {
+ ScopeResolutionError::Store(value.to_string())
+ }
+}
+
+/// Resolves workspace/project names according to the policy requested by the
+/// caller. Construct per request; it only borrows existing handles.
+pub struct ScopeResolver<'a> {
+ reader: &'a ReaderPool,
+ writer: Option<&'a WriterHandle>,
+ active_project: Option<&'a ActiveProject>,
+ default_workspace_id: WorkspaceId,
+ default_project_id: ProjectId,
+}
+
+/// Look up an explicit workspace/project pair without creating anything.
+///
+/// This free function serves surfaces like admin/web routes that do not have a
+/// current-project default. [`ScopeResolver::lookup_existing`] delegates here.
+pub async fn lookup_existing_scope(
+ reader: &ReaderPool,
+ workspace: &str,
+ project: &str,
+) -> Result<ResolvedScope, ScopeResolutionError> {
+ let workspace_id = reader
+ .find_workspace(workspace.to_owned())
+ .await?
+ .ok_or_else(|| ScopeResolutionError::WorkspaceNotFound {
+ workspace: workspace.to_owned(),
+ })?;
+ let project_id = reader
+ .find_project(workspace_id, project.to_owned())
+ .await?
+ .ok_or_else(|| ScopeResolutionError::ProjectNotFoundInWorkspace {
+ workspace: workspace.to_owned(),
+ project: project.to_owned(),
+ })?;
+ Ok(ResolvedScope {
+ workspace_id,
+ project_id,
+ })
+}
+
+/// Create or fetch an explicit workspace/project pair.
+///
+/// This is the only helper that may create a scope, and should only be used by
+/// write-style paths whose public contract says they create missing projects.
+pub async fn create_explicit_scope(
+ writer: &WriterHandle,
+ workspace: &str,
+ project: &str,
+) -> Result<ResolvedScope, ScopeResolutionError> {
+ let workspace_id = writer.get_or_create_workspace(workspace.to_owned()).await?;
+ let project_id = writer
+ .get_or_create_project(workspace_id, project.to_owned(), None)
+ .await?;
+ Ok(ResolvedScope {
+ workspace_id,
+ project_id,
+ })
+}
+
+/// Resolve and de-duplicate explicit multi-scope names without creating
+/// anything. Surfaces that do not have a current-project default (admin/web)
+/// can call this directly; [`ScopeResolver::resolve_many_existing`] delegates
+/// here.
+pub async fn resolve_many_existing_scopes(
+ reader: &ReaderPool,
+ scopes: &[ScopeName],
+ max: usize,
+) -> Result<Vec<ResolvedScope>, ScopeResolutionError> {
+ if scopes.len() > max {
+ return Err(ScopeResolutionError::TooManyScopes {
+ max,
+ actual: scopes.len(),
+ });
+ }
+ let mut seen = HashSet::new();
+ let mut resolved = Vec::new();
+ for scope in scopes {
+ let workspace =
+ trimmed_opt(Some(&scope.workspace)).ok_or(ScopeResolutionError::ScopeWorkspaceEmpty)?;
+ let project =
+ trimmed_opt(Some(&scope.project)).ok_or(ScopeResolutionError::ScopeProjectEmpty)?;
+ let ids = lookup_existing_scope(reader, workspace, project).await?;
+ if seen.insert(ids) {
+ resolved.push(ids);
+ }
+ }
+ Ok(resolved)
+}
+
+impl<'a> ScopeResolver<'a> {
+ /// Build a resolver for read-only policies.
+ #[must_use]
+ pub fn new(
+ reader: &'a ReaderPool,
+ default_workspace_id: WorkspaceId,
+ default_project_id: ProjectId,
+ ) -> Self {
+ Self {
+ reader,
+ writer: None,
+ active_project: None,
+ default_workspace_id,
+ default_project_id,
+ }
+ }
+
+ /// Attach the writer handle needed by create-on-write resolution.
+ #[must_use]
+ pub fn with_writer(mut self, writer: &'a WriterHandle) -> Self {
+ self.writer = Some(writer);
+ self
+ }
+
+ /// Attach the active-project map used for current-project defaults.
+ #[must_use]
+ pub fn with_active_project(mut self, active_project: &'a ActiveProject) -> Self {
+ self.active_project = Some(active_project);
+ self
+ }
+
+ /// Look up an explicit workspace/project pair without creating anything.
+ /// Used by read, maintenance, and destructive paths.
+ pub async fn lookup_existing(
+ &self,
+ workspace: &str,
+ project: &str,
+ ) -> Result<ResolvedScope, ScopeResolutionError> {
+ lookup_existing_scope(self.reader, workspace, project).await
+ }
+
+ /// Resolve MCP-style read arguments: explicit pair if both names are
+ /// provided, reject partial pair, otherwise use project-only lookup or the
+ /// current-project/default fallback chain.
+ pub async fn resolve_read_args(
+ &self,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+ actor: &ActorKey,
+ ) -> Result<ResolvedScope, ScopeResolutionError> {
+ match (
+ trimmed_opt(explicit_workspace),
+ trimmed_opt(explicit_project),
+ ) {
+ (Some(workspace), Some(project)) => self.lookup_existing(workspace, project).await,
+ (Some(_), None) => Err(ScopeResolutionError::WorkspaceProjectPairRequired),
+ (None, project) => self.resolve_current_or_project(project, actor).await,
+ }
+ }
+
+ /// Resolve a project-only read, or the current/default project when no
+ /// project was supplied.
+ pub async fn resolve_current_or_project(
+ &self,
+ explicit_project: Option<&str>,
+ actor: &ActorKey,
+ ) -> Result<ResolvedScope, ScopeResolutionError> {
+ let active = self.active_project.and_then(|a| a.get_for(actor));
+ if let Some(project) = trimmed_opt(explicit_project) {
+ if let Some((active_ws, _)) = active
+ && let Some(project_id) = self
+ .reader
+ .find_project(active_ws, project.to_owned())
+ .await?
+ {
+ return Ok(ResolvedScope {
+ workspace_id: active_ws,
+ project_id,
+ });
+ }
+ if active.map(|(ws, _)| ws) != Some(self.default_workspace_id)
+ && let Some(project_id) = self
+ .reader
+ .find_project(self.default_workspace_id, project.to_owned())
+ .await?
+ {
+ return Ok(ResolvedScope {
+ workspace_id: self.default_workspace_id,
+ project_id,
+ });
+ }
+ return Err(ScopeResolutionError::ProjectNotFoundInActiveOrDefault {
+ project: project.to_owned(),
+ });
+ }
+ let (workspace_id, project_id) =
+ active.unwrap_or((self.default_workspace_id, self.default_project_id));
+ Ok(ResolvedScope {
+ workspace_id,
+ project_id,
+ })
+ }
+
+ /// Resolve a write target. Explicit names may create the workspace/project;
+ /// absence means current-project/default. Partial explicit scopes fail.
+ pub async fn resolve_write_args(
+ &self,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+ actor: &ActorKey,
+ ) -> Result<ResolvedScope, ScopeResolutionError> {
+ let Some(project) = trimmed_opt(explicit_project) else {
+ 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));
+ return Ok(ResolvedScope {
+ workspace_id,
+ project_id,
+ });
+ };
+ let Some(writer) = self.writer else {
+ return Err(ScopeResolutionError::WriterRequired);
+ };
+ let active = self.active_project.and_then(|a| a.get_for(actor));
+ let workspace_id = match trimmed_opt(explicit_workspace) {
+ Some(workspace) => writer.get_or_create_workspace(workspace.to_owned()).await?,
+ None => active
+ .map(|(workspace_id, _)| workspace_id)
+ .unwrap_or(self.default_workspace_id),
+ };
+ let project_id = writer
+ .get_or_create_project(workspace_id, project.to_owned(), None)
+ .await?;
+ Ok(ResolvedScope {
+ workspace_id,
+ project_id,
+ })
+ }
+
+ /// Create or fetch an explicit workspace/project pair. Admin write-style
+ /// operations use this when there is no current-project fallback involved.
+ pub async fn create_explicit(
+ &self,
+ workspace: &str,
+ project: &str,
+ ) -> Result<ResolvedScope, ScopeResolutionError> {
+ let Some(writer) = self.writer else {
+ return Err(ScopeResolutionError::WriterRequired);
+ };
+ create_explicit_scope(writer, workspace, project).await
+ }
+
+ /// Resolve and de-duplicate an explicit multi-scope list.
+ pub async fn resolve_many_existing(
+ &self,
+ scopes: &[ScopeName],
+ max: usize,
+ ) -> Result<Vec<ResolvedScope>, ScopeResolutionError> {
+ resolve_many_existing_scopes(self.reader, scopes, max).await
+ }
+}
+
+fn trimmed_opt(value: Option<&str>) -> Option<&str> {
+ value.map(str::trim).filter(|s| !s.is_empty())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::Store;
+
+ #[tokio::test]
+ async fn read_args_reject_partial_scope() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let project = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let resolver = ScopeResolver::new(&store.reader, ws, project);
+ let err = resolver
+ .resolve_read_args(Some("default"), None, &ActorKey::default())
+ .await
+ .unwrap_err();
+ assert_eq!(err, ScopeResolutionError::WorkspaceProjectPairRequired);
+ assert_eq!(err.to_string(), WORKSPACE_PROJECT_PAIR_REQUIRED);
+ }
+
+ #[tokio::test]
+ async fn project_only_read_prefers_active_workspace_then_default() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let default_ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let default_scratch = store
+ .writer
+ .get_or_create_project(default_ws, "scratch", None)
+ .await
+ .unwrap();
+ let active_ws = store.writer.get_or_create_workspace("team").await.unwrap();
+ let active_scratch = store
+ .writer
+ .get_or_create_project(active_ws, "scratch", None)
+ .await
+ .unwrap();
+ let active_project = ActiveProject::new();
+ let actor = ActorKey {
+ user: Some("alice".into()),
+ session_id: Some("s1".into()),
+ };
+ active_project.set_for(&actor, active_ws, active_scratch);
+
+ let resolver = ScopeResolver::new(&store.reader, default_ws, default_scratch)
+ .with_active_project(&active_project);
+ let scope = resolver
+ .resolve_read_args(None, Some("scratch"), &actor)
+ .await
+ .unwrap();
+ assert_eq!(scope.as_tuple(), (active_ws, active_scratch));
+
+ let err = resolver
+ .resolve_read_args(None, Some("missing"), &actor)
+ .await
+ .unwrap_err();
+ assert_eq!(
+ err,
+ ScopeResolutionError::ProjectNotFoundInActiveOrDefault {
+ project: "missing".into()
+ }
+ );
+ }
+
+ #[tokio::test]
+ async fn write_args_create_project_in_active_workspace() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let default_ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let default_project = store
+ .writer
+ .get_or_create_project(default_ws, "scratch", None)
+ .await
+ .unwrap();
+ let active_ws = store.writer.get_or_create_workspace("team").await.unwrap();
+ let active_project_id = store
+ .writer
+ .get_or_create_project(active_ws, "current", None)
+ .await
+ .unwrap();
+ let active_project = ActiveProject::new();
+ let actor = ActorKey {
+ user: None,
+ session_id: Some("s1".into()),
+ };
+ active_project.set_for(&actor, active_ws, active_project_id);
+ let resolver = ScopeResolver::new(&store.reader, default_ws, default_project)
+ .with_writer(&store.writer)
+ .with_active_project(&active_project);
+
+ let created = resolver
+ .resolve_write_args(None, Some("new-project"), &actor)
+ .await
+ .unwrap();
+ assert_eq!(created.workspace_id, active_ws);
+ assert!(
+ store
+ .reader
+ .find_project(default_ws, "new-project".into())
+ .await
+ .unwrap()
+ .is_none(),
+ "project-only writes must not recreate the baked default workspace"
+ );
+ assert_eq!(
+ store
+ .reader
+ .find_project(active_ws, "new-project".into())
+ .await
+ .unwrap(),
+ Some(created.project_id)
+ );
+ }
+
+ #[tokio::test]
+ async fn multi_scope_resolution_deduplicates_and_validates() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let project = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let resolver = ScopeResolver::new(&store.reader, ws, project);
+ let scopes = vec![
+ ScopeName::new("default", "scratch"),
+ ScopeName::new(" default ", " scratch "),
+ ];
+ let resolved = resolver.resolve_many_existing(&scopes, 25).await.unwrap();
+ assert_eq!(
+ resolved,
+ vec![ResolvedScope {
+ workspace_id: ws,
+ project_id: project
+ }]
+ );
+
+ let err = resolver
+ .resolve_many_existing(&[ScopeName::new("", "scratch")], 25)
+ .await
+ .unwrap_err();
+ assert_eq!(err, ScopeResolutionError::ScopeWorkspaceEmpty);
+
+ let err = resolver
+ .resolve_many_existing(
+ &[
+ ScopeName::new("default", "scratch"),
+ ScopeName::new("default", "scratch"),
+ ],
+ 1,
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(
+ err,
+ ScopeResolutionError::TooManyScopes { max: 1, actual: 2 }
+ );
+ }
+}
diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rs
index 63543812..f023425b 100644
--- a/crates/ai-memory-web/src/routes/api.rs
+++ b/crates/ai-memory-web/src/routes/api.rs
@@ -1,10 +1,13 @@
//! JSON routes for third-party read-only frontends.
-use std::collections::{HashMap, HashSet};
+use std::collections::HashMap;
use std::sync::Arc;
use ai_memory_core::{PageId, PagePath, ProjectId, WorkspaceId};
-use ai_memory_store::{BriefingSnapshot, HealthPage, PageHit, RelatedPage};
+use ai_memory_store::{
+ BriefingSnapshot, HealthPage, PageHit, RelatedPage, ScopeName, ScopeResolutionError,
+ lookup_existing_scope, resolve_many_existing_scopes,
+};
use axum::extract::{Path, Query, RawQuery, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
@@ -335,23 +338,22 @@ async fn resolve_scopes(
state: &WebState,
scopes: &[ApiSearchScope],
) -> Result<Vec<ResolvedSearchScope>, Response> {
- let mut seen = HashSet::new();
- let mut resolved = Vec::new();
- for scope in scopes {
- let workspace = trimmed_opt(Some(&scope.workspace)).ok_or_else(|| {
- json_error(StatusCode::BAD_REQUEST, "scope workspace cannot be empty")
- })?;
- let project = trimmed_opt(Some(&scope.project))
- .ok_or_else(|| json_error(StatusCode::BAD_REQUEST, "scope project cannot be empty"))?;
- let (workspace_id, project_id) = lookup_project(state, workspace, project).await?;
- if seen.insert((workspace_id, project_id)) {
- resolved.push(ResolvedSearchScope {
- project_id,
- workspace_id,
- });
- }
- }
- Ok(resolved)
+ let names: Vec<_> = scopes
+ .iter()
+ .map(|scope| ScopeName::new(&scope.workspace, &scope.project))
+ .collect();
+ resolve_many_existing_scopes(&state.reader, &names, MAX_SEARCH_SCOPES)
+ .await
+ .map(|scopes| {
+ scopes
+ .into_iter()
+ .map(|scope| ResolvedSearchScope {
+ workspace_id: scope.workspace_id,
+ project_id: scope.project_id,
+ })
+ .collect()
+ })
+ .map_err(scope_error_response)
}
async fn search_scopes(
@@ -560,19 +562,15 @@ async fn lookup_project(
workspace: &str,
project: &str,
) -> Result<(WorkspaceId, ProjectId), Response> {
- let workspace_id = state
- .reader
- .find_workspace(workspace.to_owned())
+ lookup_existing_scope(&state.reader, workspace, project)
.await
- .map_err(internal_error)?
- .ok_or_else(|| not_found(format!("workspace '{workspace}' not found")))?;
- let project_id = state
- .reader
- .find_project(workspace_id, project.to_owned())
- .await
- .map_err(internal_error)?
- .ok_or_else(|| not_found(format!("project '{project}' not found")))?;
- Ok((workspace_id, project_id))
+ .map(ai_memory_store::ResolvedScope::as_tuple)
+ .map_err(|err| match err {
+ ScopeResolutionError::ProjectNotFoundInWorkspace { project, .. } => {
+ not_found(format!("project '{project}' not found"))
+ }
+ other => scope_error_response(other),
+ })
}
async fn enrich_hits(state: &WebState, hits: Vec<PageHit>) -> Result<Vec<ApiSearchHit>, Response> {
@@ -606,6 +604,16 @@ fn not_found(message: impl Into<String>) -> Response {
json_error(StatusCode::NOT_FOUND, message)
}
+fn scope_error_response(err: ScopeResolutionError) -> Response {
+ if err.is_bad_request() {
+ json_error(StatusCode::BAD_REQUEST, err.to_string())
+ } else if err.is_not_found() {
+ json_error(StatusCode::NOT_FOUND, err.to_string())
+ } else {
+ internal_error(err)
+ }
+}
+
fn json_error(status: StatusCode, message: impl Into<String>) -> Response {
(
status,
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 3c86a5a4..36030027 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -776,8 +776,10 @@ impl Wiki {
}
/// Atomically apply a batch of page writes. Either all pages land
- /// (one SQL transaction) and their files are renamed into place,
- /// or no DB row changes and tempfiles are dropped.
+ /// (one SQL transaction) and their files are renamed into place.
+ /// Files are installed before the SQL batch so markdown remains the source
+ /// of truth; if the SQL batch fails at runtime, installed files are rolled
+ /// back best-effort to their prior contents.
///
/// # Errors
/// Returns [`WikiError`] for any filesystem, parsing, or store
@@ -877,15 +879,32 @@ impl Wiki {
})
.collect();
- let ids = self.writer.upsert_pages_batch(pages).await?;
-
- // SQL succeeded; rename tempfiles into place.
+ // Install files first so the DB is never ahead of markdown. If the
+ // SQL batch fails below, rollback restores the prior disk state;
+ // if the process crashes in this window, startup/reindex repairs
+ // the derived DB from the markdown source of truth.
+ let mut installed = Vec::with_capacity(staged_files.len());
let mut dispatches = Vec::with_capacity(staged_files.len());
for (req, tmp, abs, ctx) in staged_files {
- let persisted = tmp.persist(&abs)?;
- persisted.sync_data()?;
+ let install = match persist_tmp_with_rollback_snapshot(tmp, &abs) {
+ Ok(install) => install,
+ Err(e) => {
+ rollback_or_inconsistent(&installed, &e)?;
+ return Err(e);
+ }
+ };
+ installed.push(install);
dispatches.push((req.path, req.frontmatter, req.body, ctx));
}
+
+ let ids = match self.writer.upsert_pages_batch(pages).await {
+ Ok(ids) => ids,
+ Err(e) => {
+ rollback_or_inconsistent(&installed, &e)?;
+ return Err(e.into());
+ }
+ };
+
(ids, dispatches)
};
@@ -993,9 +1012,10 @@ impl Wiki {
if let Some(parent) = abs.parent() {
std::fs::create_dir_all(parent)?;
}
- atomic::write_atomic(&abs, emitted.as_bytes())?;
+ let installed = replace_file_with_rollback_snapshot(&abs, emitted.as_bytes())?;
- self.writer
+ match self
+ .writer
.upsert_page(NewPage {
workspace_id,
project_id,
@@ -1008,7 +1028,14 @@ impl Wiki {
links,
author_id,
})
- .await?
+ .await
+ {
+ Ok(id) => id,
+ Err(e) => {
+ rollback_or_inconsistent(std::slice::from_ref(&installed), &e)?;
+ return Err(e.into());
+ }
+ }
};
// Embed if configured. We do this on the caller's task so the
// tool reply still happens "indexes commit in the same
@@ -1103,6 +1130,79 @@ fn ai_memory_wiki_error(msg: &str) -> crate::WikiError {
crate::WikiError::Io(std::io::Error::other(msg.to_string()))
}
+#[derive(Debug)]
+struct InstalledFile {
+ path: PathBuf,
+ previous: Option<Vec<u8>>,
+}
+
+fn snapshot_existing_file(path: &Path) -> WikiResult<Option<Vec<u8>>> {
+ match std::fs::read(path) {
+ Ok(bytes) => Ok(Some(bytes)),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(e) => Err(WikiError::Io(e)),
+ }
+}
+
+fn sync_parent_best_effort(path: &Path) {
+ if let Some(parent) = path.parent()
+ && let Ok(dir) = std::fs::File::open(parent)
+ {
+ let _ = dir.sync_all();
+ }
+}
+
+fn persist_tmp_with_rollback_snapshot(
+ tmp: tempfile::NamedTempFile,
+ path: &Path,
+) -> WikiResult<InstalledFile> {
+ let previous = snapshot_existing_file(path)?;
+ let persisted = tmp.persist(path)?;
+ persisted.sync_data()?;
+ sync_parent_best_effort(path);
+ Ok(InstalledFile {
+ path: path.to_path_buf(),
+ previous,
+ })
+}
+
+fn replace_file_with_rollback_snapshot(path: &Path, bytes: &[u8]) -> WikiResult<InstalledFile> {
+ let previous = snapshot_existing_file(path)?;
+ atomic::write_atomic(path, bytes)?;
+ Ok(InstalledFile {
+ path: path.to_path_buf(),
+ previous,
+ })
+}
+
+fn rollback_installed_files(installed: &[InstalledFile]) -> WikiResult<()> {
+ for file in installed.iter().rev() {
+ match &file.previous {
+ Some(bytes) => {
+ atomic::write_atomic(&file.path, bytes)?;
+ }
+ None => match std::fs::remove_file(&file.path) {
+ Ok(()) => sync_parent_best_effort(&file.path),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(e) => return Err(WikiError::Io(e)),
+ },
+ }
+ }
+ Ok(())
+}
+
+fn rollback_or_inconsistent<E: std::fmt::Display>(
+ installed: &[InstalledFile],
+ cause: &E,
+) -> WikiResult<()> {
+ if let Err(rollback_err) = rollback_installed_files(installed) {
+ return Err(WikiError::Io(std::io::Error::other(format!(
+ "INCONSISTENT STATE: wiki files changed but store write failed ({cause}) and rollback failed ({rollback_err})"
+ ))));
+ }
+ Ok(())
+}
+
fn quarantine_file(path: &Path) -> std::io::Result<Option<PathBuf>> {
let Some(parent) = path.parent() else {
return Err(std::io::Error::other(
@@ -1329,6 +1429,61 @@ mod tests {
assert!(hits[0].snippet.contains("compile"));
}
+ #[tokio::test]
+ async fn write_page_rolls_back_file_when_store_upsert_fails() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let path = PagePath::new("notes/rollback.md").unwrap();
+
+ wiki.write_page(req(
+ ws,
+ proj,
+ path.as_str(),
+ "old body",
+ serde_json::json!({ "title": "Old" }),
+ ))
+ .await
+ .unwrap();
+
+ let mut bad = req(
+ ws,
+ proj,
+ path.as_str(),
+ "new body should not remain",
+ serde_json::json!({ "title": "New" }),
+ );
+ bad.author_id = Some(ai_memory_core::UserId::new());
+ let err = wiki.write_page(bad).await.unwrap_err();
+ assert!(
+ err.to_string().contains("FOREIGN KEY") || err.to_string().contains("constraint"),
+ "expected FK failure, got {err}"
+ );
+
+ let on_disk = std::fs::read_to_string(wiki.abs_path(ws, proj, &path)).unwrap();
+ assert!(on_disk.contains("old body"));
+ assert!(!on_disk.contains("new body should not remain"));
+
+ let stored = store
+ .reader
+ .page_body_by_ids(ws, proj, path.as_str())
+ .await
+ .unwrap()
+ .expect("old row should remain latest");
+ assert_eq!(stored.body, "old body");
+ assert_eq!(stored.title, "Old");
+ }
+
/// Defence-in-depth: anything that reaches `write_page` gets
/// scrubbed at the wiki boundary, even if upstream callers (LLM
/// consolidation output, manual `write-page` CLI input, MCP tool
@@ -1474,6 +1629,84 @@ mod tests {
assert_eq!(hits.len(), 5);
}
+ #[tokio::test]
+ async fn apply_batch_rolls_back_files_when_sql_batch_fails() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let existing = PagePath::new("batch/existing.md").unwrap();
+ let created = PagePath::new("batch/new.md").unwrap();
+
+ wiki.write_page(req(
+ ws,
+ proj,
+ existing.as_str(),
+ "old batch body",
+ serde_json::json!({ "title": "Old Batch" }),
+ ))
+ .await
+ .unwrap();
+
+ let mut replace_existing = req(
+ ws,
+ proj,
+ existing.as_str(),
+ "new batch body should roll back",
+ serde_json::json!({ "title": "New Batch" }),
+ );
+ replace_existing.author_id = Some(ai_memory_core::UserId::new());
+ let mut create_new = req(
+ ws,
+ proj,
+ created.as_str(),
+ "new file should be removed",
+ serde_json::json!({ "title": "Created" }),
+ );
+ create_new.author_id = Some(ai_memory_core::UserId::new());
+
+ let err = wiki
+ .apply_batch(vec![replace_existing, create_new])
+ .await
+ .unwrap_err();
+ assert!(
+ err.to_string().contains("FOREIGN KEY") || err.to_string().contains("constraint"),
+ "expected FK failure, got {err}"
+ );
+
+ let existing_body = std::fs::read_to_string(wiki.abs_path(ws, proj, &existing)).unwrap();
+ assert!(existing_body.contains("old batch body"));
+ assert!(!existing_body.contains("new batch body should roll back"));
+ assert!(!wiki.abs_path(ws, proj, &created).exists());
+
+ let counts = store.reader.status_counts().await.unwrap();
+ assert_eq!(counts.pages_latest, 1);
+ let stored = store
+ .reader
+ .page_body_by_ids(ws, proj, existing.as_str())
+ .await
+ .unwrap()
+ .expect("old row should remain latest");
+ assert_eq!(stored.body, "old batch body");
+ assert!(
+ store
+ .reader
+ .page_body_by_ids(ws, proj, created.as_str())
+ .await
+ .unwrap()
+ .is_none()
+ );
+ }
+
#[tokio::test]
async fn apply_batch_runs_admission_and_scrubs_webhook_mutations() {
use crate::admission::{
diff --git a/docs/auto-scope.md b/docs/auto-scope.md
index acce200f..4b4c597e 100644
--- a/docs/auto-scope.md
+++ b/docs/auto-scope.md
@@ -39,6 +39,25 @@ instead of falling back to the active/default project. A `workspace`
argument must be paired with `project`, and read/admin maintenance
paths use find-only lookups so typos do not create empty scopes.
+## Implementation contract
+
+Scope resolution is centralized in `ai_memory_store::ScopeResolver` and its
+explicit helpers:
+
+- `lookup_existing_scope` for read, search, maintenance, retention, embed, and
+ destructive paths. It never creates workspaces or projects.
+- `create_explicit_scope` for explicit write/create paths only.
+- `resolve_many_existing_scopes` for multi-project search scopes, with
+ deduplication and max-scope validation.
+- `ScopeResolver::resolve_read_args` and `resolve_write_args` for MCP tools
+ that also need actor-scoped active-project fallback.
+
+New MCP, admin, or web API routes should use those helpers instead of
+hand-rolling `find_workspace` / `find_project` chains. PRs that touch scope
+resolution should include table-driven tests for partial scope rejection,
+missing explicit scope, active-project precedence, and cross-workspace
+isolation.
+
## Configuration
```toml
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index 8708a0f0..61c0aefd 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -55,6 +55,14 @@ Three options surveyed:
- DB stores `(path, mtime, size, sha256, indexed_at, provider, model, dim)` per page. On startup, fast scan vs. cached SHAs; only changed files re-parsed.
- Embeddings keyed by `sha256(content) + provider + model + dim`. Re-embed only when content changes.
+**Consistency contract:** markdown is primary and SQLite is derived. There is no
+real cross-resource transaction between the filesystem and SQLite. Wiki writes
+must go through `Wiki::write_page`, `Wiki::apply_batch`, or the existing
+destructive helpers so sanitization, admission, attribution, rollback, and
+store updates stay together. Runtime store failures roll installed files back
+best-effort; crash windows are resolved by the existing markdown reindex path.
+Handlers must not write wiki files directly.
+
## 4. Database choice - single SQLite file
**Decision: one SQLite file with FTS5, packed-vector embeddings, and SQL tables for graph edges.**
diff --git a/docs/users.md b/docs/users.md
index d2679429..70a55be4 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -56,6 +56,22 @@ The rungs are sticky: a request is matched at the lowest tier that
applies, never escalates. Root token always wins over any users-row
collision; the two namespaces are intentionally distinct.
+## Implementation contract
+
+Request identity and authorization are separate:
+
+- `ActorContext` carries who made the request and is used for attribution,
+ frontmatter, audit payloads, and active-project keys.
+- `AuthLevel` carries what auth tier the middleware resolved.
+- `AuthLevel::authorize(Capability::...)` is the shared permission check for
+ admin routes, user-management routes, normal read/write surfaces, and the
+ admission-chain skip header.
+
+Handlers should not compare usernames, infer root from `ActorContext`, or add
+ad hoc root-only branches. PRs that touch auth behavior should cover root,
+DB-user, and anonymous callers, including the single-user compatibility mode
+where `[auth].token_pepper` is absent.
+
## Quick start
> Prerequisite: a fresh `ai-memory init`. Pre-v0.8 installs need