Skip to content

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

Rust

release: v1.0.4

AkitaOnRails134bdf1e8f31
diff --git a/AGENTS.md b/AGENTS.md
index 501c7f77..04271b49 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -98,6 +98,10 @@ without disturbing the rest of the file.
- 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.
- 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 931d1ad0..b7711577 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
+
+## [1.0.4] - 2026-06-14
### Added
- `install-hooks --agent grok` (plus `setup-agent` / `uninstall` coverage) for
the xAI **Grok Build CLI**. Grok's `~/.grok/hooks/ai-memory.json` shares Claude
@@ -35,6 +37,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
only, so a cross-workspace handoff was routed by the per-actor active-project
fallback and could be written to — or read from — the wrong project.
`memory_handoff_cancel` already carried `workspace`.
+- Workspace/project resolution now fails closed across the MCP and admin
+ surfaces. Explicit MCP project misses no longer fall back to the active/default
+ project, write-style MCP calls reject `workspace` without `project`, admin
+ read/search/embed/lint/sweep paths use no-create lookups, and `/admin/reorg`
+ only moves sessions and graveyards latest pages inside the target workspace.
## [1.0.3] - 2026-06-13
### Added
@@ -999,7 +1006,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Consolidator used server startup default project instead of the
session's actual project.
-[Unreleased]: https://github.com/akitaonrails/ai-memory/compare/v1.0.3...HEAD
+[Unreleased]: https://github.com/akitaonrails/ai-memory/compare/v1.0.4...HEAD
+[1.0.4]: https://github.com/akitaonrails/ai-memory/releases/tag/v1.0.4
[1.0.3]: https://github.com/akitaonrails/ai-memory/releases/tag/v1.0.3
[1.0.2]: https://github.com/akitaonrails/ai-memory/releases/tag/v1.0.2
[1.0.1]: https://github.com/akitaonrails/ai-memory/releases/tag/v1.0.1
diff --git a/Cargo.lock b/Cargo.lock
index 66e9f714..51b716cb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -31,7 +31,7 @@ dependencies = [
[[package]]
name = "ai-memory-cli"
-version = "1.0.3"
+version = "1.0.4"
dependencies = [
"ai-memory-consolidate",
"ai-memory-core",
@@ -71,7 +71,7 @@ dependencies = [
[[package]]
name = "ai-memory-consolidate"
-version = "1.0.3"
+version = "1.0.4"
dependencies = [
"ai-memory-core",
"ai-memory-llm",
@@ -92,7 +92,7 @@ dependencies = [
[[package]]
name = "ai-memory-core"
-version = "1.0.3"
+version = "1.0.4"
dependencies = [
"jiff",
"regex",
@@ -106,7 +106,7 @@ dependencies = [
[[package]]
name = "ai-memory-eval"
-version = "1.0.3"
+version = "1.0.4"
dependencies = [
"ai-memory-consolidate",
"ai-memory-core",
@@ -125,7 +125,7 @@ dependencies = [
[[package]]
name = "ai-memory-hooks"
-version = "1.0.3"
+version = "1.0.4"
dependencies = [
"ai-memory-consolidate",
"ai-memory-core",
@@ -147,7 +147,7 @@ dependencies = [
[[package]]
name = "ai-memory-llm"
-version = "1.0.3"
+version = "1.0.4"
dependencies = [
"ai-memory-core",
"anyhow",
@@ -170,7 +170,7 @@ dependencies = [
[[package]]
name = "ai-memory-mcp"
-version = "1.0.3"
+version = "1.0.4"
dependencies = [
"ai-memory-consolidate",
"ai-memory-core",
@@ -197,7 +197,7 @@ dependencies = [
[[package]]
name = "ai-memory-store"
-version = "1.0.3"
+version = "1.0.4"
dependencies = [
"ai-memory-core",
"anyhow",
@@ -220,7 +220,7 @@ dependencies = [
[[package]]
name = "ai-memory-web"
-version = "1.0.3"
+version = "1.0.4"
dependencies = [
"ai-memory-core",
"ai-memory-store",
@@ -243,7 +243,7 @@ dependencies = [
[[package]]
name = "ai-memory-wiki"
-version = "1.0.3"
+version = "1.0.4"
dependencies = [
"ai-memory-core",
"ai-memory-llm",
diff --git a/Cargo.toml b/Cargo.toml
index d17a6873..8f67078e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -16,7 +16,7 @@ members = [
]
[workspace.package]
-version = "1.0.3"
+version = "1.0.4"
edition = "2024"
rust-version = "1.95"
license = "MIT"
@@ -25,14 +25,14 @@ authors = ["Fabio Akita <[email protected]>"]
[workspace.dependencies]
# Inter-crate dependencies.
-ai-memory-core = { path = "crates/ai-memory-core", version = "1.0.3" }
-ai-memory-store = { path = "crates/ai-memory-store", version = "1.0.3" }
-ai-memory-wiki = { path = "crates/ai-memory-wiki", version = "1.0.3" }
-ai-memory-mcp = { path = "crates/ai-memory-mcp", version = "1.0.3" }
-ai-memory-hooks = { path = "crates/ai-memory-hooks", version = "1.0.3" }
-ai-memory-llm = { path = "crates/ai-memory-llm", version = "1.0.3" }
-ai-memory-consolidate = { path = "crates/ai-memory-consolidate", version = "1.0.3" }
-ai-memory-web = { path = "crates/ai-memory-web", version = "1.0.3" }
+ai-memory-core = { path = "crates/ai-memory-core", version = "1.0.4" }
+ai-memory-store = { path = "crates/ai-memory-store", version = "1.0.4" }
+ai-memory-wiki = { path = "crates/ai-memory-wiki", version = "1.0.4" }
+ai-memory-mcp = { path = "crates/ai-memory-mcp", version = "1.0.4" }
+ai-memory-hooks = { path = "crates/ai-memory-hooks", version = "1.0.4" }
+ai-memory-llm = { path = "crates/ai-memory-llm", version = "1.0.4" }
+ai-memory-consolidate = { path = "crates/ai-memory-consolidate", version = "1.0.4" }
+ai-memory-web = { path = "crates/ai-memory-web", version = "1.0.4" }
# (Workspace shared deps follow below)
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index caa68d29..9d86d6ad 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -380,10 +380,10 @@ async fn handle_status(State(state): State<Arc<AdminState>>) -> impl IntoRespons
struct SearchQuery {
/// FTS5 query expression.
q: String,
- /// Workspace name to search within. When omitted with `project`, admin search is global.
+ /// Workspace name to search within. Must be provided together with `project`.
#[serde(default)]
workspace: Option<String>,
- /// Project name to search within. When omitted with `workspace`, admin search is global.
+ /// Project name to search within. Must be provided together with `workspace`.
#[serde(default)]
project: Option<String>,
/// Max number of hits to return. Capped at 100 server-side.
@@ -400,17 +400,29 @@ async fn handle_search(
Query(query): Query<SearchQuery>,
) -> impl IntoResponse {
let limit = query.limit.clamp(1, 100);
- let search_result = match (query.workspace.as_deref(), query.project.as_deref()) {
- (Some(workspace), Some(project)) => match resolve_ws_proj(&state, workspace, project).await
- {
- Ok((ws, proj)) => {
- state
- .reader
- .search_pages_for_project(ws, proj, query.q, limit)
- .await
+ let search_result = match (
+ trimmed_opt(query.workspace.as_deref()),
+ trimmed_opt(query.project.as_deref()),
+ ) {
+ (Some(workspace), Some(project)) => {
+ match lookup_ws_proj_no_create(&state, workspace, project).await {
+ Ok((ws, proj)) => {
+ state
+ .reader
+ .search_pages_for_project(ws, proj, query.q, limit)
+ .await
+ }
+ Err(e) => return e,
}
- Err(e) => return e,
- },
+ }
+ (Some(_), None) | (None, Some(_)) => {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": "workspace and project must be provided together"
+ })),
+ );
+ }
_ => state.reader.search_pages(query.q, limit).await,
};
match search_result {
@@ -466,15 +478,9 @@ async fn handle_read_page(
State(state): State<Arc<AdminState>>,
Query(query): Query<ReadPageQuery>,
) -> impl IntoResponse {
- let (ws, proj) = match resolve_ws_proj(&state, &query.workspace, &query.project).await {
- Ok(ids) => ids,
- Err(e) => return e,
- };
-
- // Resolve the page path: direct `path` takes precedence over `q`.
- let page_path = if let Some(raw) = query.path {
+ let direct_path = if let Some(raw) = query.path {
match ai_memory_core::PagePath::new(raw) {
- Ok(p) => p,
+ Ok(p) => Some(p),
Err(e) => {
return (
StatusCode::BAD_REQUEST,
@@ -482,6 +488,25 @@ async fn handle_read_page(
);
}
}
+ } else {
+ None
+ };
+ if direct_path.is_none() && query.q.is_none() {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({ "error": "provide `path` or `q`" })),
+ );
+ }
+
+ let (ws, proj) = match lookup_ws_proj_no_create(&state, &query.workspace, &query.project).await
+ {
+ Ok(ids) => ids,
+ Err(e) => return e,
+ };
+
+ // Resolve the page path: direct `path` takes precedence over `q`.
+ let page_path = if let Some(path) = direct_path {
+ path
} else if let Some(q) = query.q {
let hits = match state
.reader
@@ -583,9 +608,13 @@ 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())
+}
+
/// Resolve workspace + project IDs, creating them if absent. Returns
/// either the IDs or a ready-to-return error response.
-async fn resolve_ws_proj(
+async fn create_ws_proj(
state: &AdminState,
workspace: &str,
project: &str,
@@ -605,8 +634,8 @@ async fn resolve_ws_proj(
/// Look up workspace + project by name **without** auto-creating them.
/// Returns `(WorkspaceId, ProjectId)` on success, or a ready-to-return
-/// 404/500 error response. Used by destructive handlers (purge, rename)
-/// where auto-creation would silently succeed on a typo.
+/// 404/500 error response. Used by read, maintenance, and destructive
+/// handlers where auto-creation would silently succeed on a typo.
async fn lookup_ws_proj_no_create(
state: &AdminState,
workspace: &str,
@@ -670,7 +699,7 @@ async fn handle_bootstrap(
})),
));
}
- let (ws, proj) = resolve_ws_proj(&state, &req.workspace, &req.project).await?;
+ let (ws, proj) = create_ws_proj(&state, &req.workspace, &req.project).await?;
// Serialise live bootstrap runs. Two parallel `process_sources`
// calls would race the wiki's `commit_all` (libgit2 ops on the
@@ -850,16 +879,17 @@ pub struct ReorgReport {
/// `(session_id, project_id, cwd)` triples ordered by `started_at`.
async fn list_sessions_with_cwd(
reader: &ai_memory_store::ReaderPool,
+ workspace_id: WorkspaceId,
) -> Result<Vec<(SessionId, ProjectId, String)>, StoreError> {
reader
.with_conn(move |conn| {
let mut stmt = conn.prepare(
"SELECT id, project_id, cwd \
FROM sessions \
- WHERE cwd IS NOT NULL AND cwd != '' \
+ WHERE workspace_id = ?1 AND cwd IS NOT NULL AND cwd != '' \
ORDER BY started_at",
)?;
- let rows = stmt.query_map([], |row| {
+ let rows = stmt.query_map([workspace_id.as_bytes().as_slice()], |row| {
let id_bytes: Vec<u8> = row.get(0)?;
let proj_bytes: Vec<u8> = row.get(1)?;
let cwd: String = row.get(2)?;
@@ -945,7 +975,7 @@ async fn handle_reorg(
}
};
- let sessions = match list_sessions_with_cwd(&state.reader).await {
+ let sessions = match list_sessions_with_cwd(&state.reader, ws).await {
Ok(v) => v,
Err(e) => {
return (
@@ -1000,7 +1030,7 @@ async fn handle_reorg(
);
}
- let summary = match state.writer.reorg_sessions(writer_plan).await {
+ let summary = match state.writer.reorg_sessions(ws, writer_plan).await {
Ok(s) => s,
Err(e) => {
return (
@@ -1033,10 +1063,10 @@ async fn handle_reorg(
/// JSON request body for `POST /admin/lint`.
#[derive(Deserialize)]
struct LintRequest {
- /// Workspace name (auto-created if absent).
+ /// Workspace name (must already exist).
#[serde(default = "default_workspace")]
workspace: String,
- /// Project name (auto-created if absent).
+ /// Project name (must already exist).
#[serde(default = "default_project")]
project: String,
/// Don't write the lint report page.
@@ -1061,7 +1091,7 @@ async fn handle_lint(
State(state): State<Arc<AdminState>>,
Json(req): Json<LintRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
- let (ws, proj) = resolve_ws_proj(&state, &req.workspace, &req.project).await?;
+ let (ws, proj) = lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await?;
run_lint(
&state.reader,
@@ -1089,10 +1119,10 @@ async fn handle_lint(
/// JSON request body for `POST /admin/forget-sweep`.
#[derive(Deserialize)]
struct ForgetSweepRequest {
- /// Workspace name (auto-created if absent).
+ /// Workspace name (must already exist).
#[serde(default = "default_workspace")]
workspace: String,
- /// Project name (auto-created if absent).
+ /// Project name (must already exist).
#[serde(default = "default_project")]
project: String,
/// Report what would be evicted without actually mutating.
@@ -1104,7 +1134,7 @@ async fn handle_forget_sweep(
State(state): State<Arc<AdminState>>,
Json(req): Json<ForgetSweepRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
- let (ws, proj) = resolve_ws_proj(&state, &req.workspace, &req.project).await?;
+ let (ws, proj) = lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await?;
run_sweep(
&state.reader,
@@ -1131,10 +1161,10 @@ async fn handle_forget_sweep(
/// JSON request body for `POST /admin/embed`.
#[derive(Deserialize)]
struct EmbedRequest {
- /// Workspace name (auto-created if absent).
+ /// Workspace name (must already exist).
#[serde(default = "default_workspace")]
workspace: String,
- /// Project name (auto-created if absent). Ignored when
+ /// Project name (must already exist). Ignored when
/// [`Self::all_projects`] is true.
#[serde(default = "default_project")]
project: String,
@@ -1343,7 +1373,7 @@ async fn handle_embed(
}
}
} else {
- let (ws, proj) = resolve_ws_proj(&state, &req.workspace, &req.project).await?;
+ let (ws, proj) = lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await?;
if req.reembed && !req.dry_run {
let purged = state
.writer
@@ -2246,7 +2276,7 @@ async fn handle_move_project(
// MERGE: the destination already holds a same-named project. Get-or-create
// it (auto-creating the destination workspace) and copy the source's
// latest pages into it, then purge the source.
- let (dst_ws, dst_proj) = match resolve_ws_proj(&state, &req.to_workspace, &req.project).await {
+ let (dst_ws, dst_proj) = match create_ws_proj(&state, &req.to_workspace, &req.project).await {
Ok(ids) => ids,
Err(e) => return e,
};
@@ -2776,7 +2806,7 @@ async fn handle_write_page(
)
})?;
- let (ws, proj) = resolve_ws_proj(&state, &req.workspace, &req.project).await?;
+ let (ws, proj) = create_ws_proj(&state, &req.workspace, &req.project).await?;
let mut fm = serde_json::Map::new();
if let Some(title) = &req.title {
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 2e5ae42e..52651345 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -104,9 +104,8 @@ the conversation calls for them:\n\
- `memory_delete_page` — when the user explicitly asks to delete or \
remove a specific page (by exact path). Idempotent; fires the \
admission chain so mirrors/backups stay consistent. Pass `workspace` \
- + `project` together only when the page lives in a sibling workspace \
- (otherwise a project name that exists in multiple workspaces can \
- silently route the delete to the wrong slot).\n\
+ + `project` together only when the page lives in a sibling \
+ workspace/project; missing explicit scopes fail closed instead of falling back.\n\
- `memory_lint` — when the user asks to audit the wiki for stale \
pages, contradictions, or rule suggestions.\n\
- `memory_forget_sweep` — when the user wants to prune old / cold \
@@ -455,10 +454,8 @@ struct DeletePageArgs {
/// Workspace to delete from together with `project`. Omit to use the
/// current/default workspace resolution chain. Provide both to delete a
/// page that lives in a *different* workspace (e.g. a sibling project on
- /// a shared server). Without this, a delete targeting a project that
- /// exists in MULTIPLE workspaces can silently land in the wrong slot —
- /// fixed by routing scope resolution through the same path the read
- /// tools use (`effective_ids_for_read_args`).
+ /// a shared server). Missing explicit scopes fail closed instead of
+ /// falling back to the active/default project.
#[serde(default)]
workspace: Option<String>,
}
@@ -616,13 +613,13 @@ impl AiMemoryServer {
&self,
explicit_project: Option<&str>,
actor: &ai_memory_core::ActorKey,
- ) -> (WorkspaceId, ProjectId) {
+ ) -> 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 (active_ws, pid);
+ return Ok((active_ws, pid));
}
if active.map(|(ws, _)| ws) != Some(self.workspace_id)
&& let Ok(Some(pid)) = self
@@ -630,10 +627,14 @@ impl AiMemoryServer {
.find_project(self.workspace_id, name.to_string())
.await
{
- return (self.workspace_id, pid);
+ return Ok((self.workspace_id, pid));
}
+ return Err(McpError::internal_error(
+ format!("project '{name}' not found in the active or default workspace"),
+ None,
+ ));
}
- active.unwrap_or((self.workspace_id, self.project_id))
+ Ok(active.unwrap_or((self.workspace_id, self.project_id)))
}
async fn effective_ids_for_read_args_with_actor(
@@ -651,7 +652,7 @@ impl AiMemoryServer {
"workspace and project must be provided together",
None,
)),
- (None, project) => Ok(self.effective_ids_with_actor(project, actor).await),
+ (None, project) => self.effective_ids_with_actor(project, actor).await,
}
}
@@ -719,8 +720,14 @@ impl AiMemoryServer {
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). Explicit workspace alone has nothing to scope.
+ // the baked default).
return Ok(self
.active_project
.get_for(actor)
@@ -1372,8 +1379,8 @@ impl AiMemoryServer {
before the file is removed so backups/mirrors stay consistent. \
Idempotent — deleting a page that is already gone is a no-op. \
Pass `workspace` + `project` together when the page lives in a \
- sibling workspace (otherwise a project name that exists in multiple \
- workspaces can silently route the delete to the wrong slot). \
+ sibling workspace; missing explicit scopes fail closed instead of \
+ falling back to the active/default project. \
Returns `{ path, deleted }`.")]
async fn memory_delete_page(
&self,
@@ -2243,7 +2250,8 @@ mod tests {
assert_eq!(
server
.effective_ids_with_actor(None, &ai_memory_core::ActorKey::default())
- .await,
+ .await
+ .unwrap(),
(ws, baked)
);
@@ -2263,7 +2271,8 @@ mod tests {
assert_eq!(
server
.effective_ids_with_actor(None, &ai_memory_core::ActorKey::default())
- .await,
+ .await
+ .unwrap(),
(ws, other)
);
@@ -2271,22 +2280,21 @@ mod tests {
assert_eq!(
server
.effective_ids_with_actor(Some("scratch"), &ai_memory_core::ActorKey::default())
- .await,
+ .await
+ .unwrap(),
(ws, baked),
"explicit project arg should override the active pointer"
);
- // An explicit but unknown project name falls through to the
- // active pointer rather than erroring or returning a bogus id.
- assert_eq!(
- server
- .effective_ids_with_actor(
- Some("does-not-exist"),
- &ai_memory_core::ActorKey::default()
- )
- .await,
- (ws, other),
- "unknown explicit project falls through to the active pointer"
+ // An explicit but unknown project name fails closed instead of
+ // silently falling through to the active pointer.
+ let err = server
+ .effective_ids_with_actor(Some("does-not-exist"), &ai_memory_core::ActorKey::default())
+ .await
+ .expect_err("unknown explicit project must not fall back");
+ assert!(
+ err.to_string().contains("does-not-exist"),
+ "error should name the missing explicit project: {err}"
);
}
@@ -2362,6 +2370,21 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn write_target_ids_rejects_workspace_without_project() {
+ let (_tmp, _store, server, _baked_ws, _baked_proj) = setup_server().await;
+
+ let err = server
+ .write_target_ids(Some("default"), None)
+ .await
+ .expect_err("workspace-only writes must fail closed");
+ assert!(
+ err.to_string()
+ .contains("workspace and project must be provided together"),
+ "error should explain the required scope pair: {err}"
+ );
+ }
+
#[tokio::test]
async fn project_only_write_round_trips_with_project_only_read_in_active_workspace() {
let (tmp, store, server, baked_ws, _baked_proj) = setup_server().await;
@@ -2432,7 +2455,8 @@ mod tests {
assert_eq!(
server
.effective_ids_with_actor(Some("sibling"), &ai_memory_core::ActorKey::default())
- .await,
+ .await
+ .unwrap(),
(active_ws, sibling_proj),
"project-only read resolution should use the active workspace"
);
@@ -3144,6 +3168,100 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn memory_write_page_rejects_workspace_without_project() {
+ 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 server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki);
+
+ let err = server
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ path: "notes/invalid-scope.md".into(),
+ body: "# Invalid Scope".into(),
+ title: None,
+ tier: Some("semantic".into()),
+ tags: vec![],
+ pinned: false,
+ project: None,
+ workspace: Some("default".into()),
+ }),
+ rmcp::handler::server::tool::Extension(test_parts_default()),
+ )
+ .await
+ .expect_err("workspace-only memory_write_page must fail");
+ assert!(
+ err.to_string()
+ .contains("workspace and project must be provided together"),
+ "error should explain the required scope pair: {err}"
+ );
+ }
+
+ #[tokio::test]
+ async fn memory_read_page_unknown_explicit_project_does_not_fallback() {
+ 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 server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki);
+
+ server
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ path: "notes/default.md".into(),
+ body: "# Default\n\nThis page must not be read through a typo.".into(),
+ title: None,
+ tier: Some("semantic".into()),
+ tags: vec![],
+ pinned: false,
+ project: None,
+ workspace: None,
+ }),
+ rmcp::handler::server::tool::Extension(test_parts_default()),
+ )
+ .await
+ .unwrap();
+
+ let err = server
+ .memory_read_page(
+ Parameters(ReadPageArgs {
+ query: None,
+ path: Some("notes/default.md".into()),
+ project: Some("typo".into()),
+ workspace: None,
+ }),
+ rmcp::handler::server::tool::Extension(test_parts_default()),
+ )
+ .await
+ .expect_err("unknown explicit project must not fall back to scratch");
+ assert!(
+ err.to_string().contains("typo"),
+ "error should name the missing explicit project: {err}"
+ );
+ }
+
#[tokio::test]
async fn memory_delete_page_removes_the_page() {
let tmp = TempDir::new().unwrap();
@@ -3240,6 +3358,71 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn memory_delete_page_unknown_explicit_project_does_not_fallback() {
+ 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 server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki);
+
+ server
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ path: "notes/keep.md".into(),
+ body: "# Keep\n\nThis page must survive an explicit project typo.".into(),
+ title: None,
+ tier: Some("semantic".into()),
+ tags: vec![],
+ pinned: false,
+ project: None,
+ workspace: None,
+ }),
+ rmcp::handler::server::tool::Extension(test_parts_default()),
+ )
+ .await
+ .unwrap();
+
+ let err = server
+ .memory_delete_page(
+ Parameters(DeletePageArgs {
+ path: "notes/keep.md".into(),
+ project: Some("typo".into()),
+ workspace: None,
+ }),
+ rmcp::handler::server::tool::Extension(test_parts_default()),
+ )
+ .await
+ .expect_err("unknown explicit project must not delete from scratch");
+ assert!(
+ err.to_string().contains("typo"),
+ "error should name the missing explicit project: {err}"
+ );
+
+ let read = server
+ .memory_read_page(
+ Parameters(ReadPageArgs {
+ query: None,
+ path: Some("notes/keep.md".into()),
+ project: None,
+ workspace: None,
+ }),
+ rmcp::handler::server::tool::Extension(test_parts_default()),
+ )
+ .await;
+ assert!(read.is_ok(), "page must survive delete with typo'd project");
+ }
+
/// Bug 5 regression: when a project name lives in MULTIPLE workspaces,
/// `memory_delete_page` without `workspace` resolved scope via
/// `effective_ids(project)` and could silently land in the wrong slot
diff --git a/crates/ai-memory-mcp/tests/admin_phase3.rs b/crates/ai-memory-mcp/tests/admin_phase3.rs
index d164bd25..402e22b4 100644
--- a/crates/ai-memory-mcp/tests/admin_phase3.rs
+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs
@@ -202,6 +202,95 @@ async fn reorg_live_moves_sessions() {
assert!(!body["dry_run"].as_bool().unwrap());
}
+#[tokio::test]
+async fn reorg_live_graveyards_only_default_workspace_pages() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ seed_sessions_for_reorg(&store).await;
+
+ 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();
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: default_ws,
+ project_id: default_proj,
+ path: PagePath::new("notes/default-latest.md").unwrap(),
+ title: "Default latest".into(),
+ body: "default workspace page should be graveyarded".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ author_id: None,
+ })
+ .await
+ .unwrap();
+
+ let sibling_ws = store
+ .writer
+ .get_or_create_workspace("sibling")
+ .await
+ .unwrap();
+ let sibling_proj = store
+ .writer
+ .get_or_create_project(sibling_ws, "scratch", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: sibling_ws,
+ project_id: sibling_proj,
+ path: PagePath::new("notes/sibling-latest.md").unwrap(),
+ title: "Sibling latest".into(),
+ body: "sibling workspace page must remain latest".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ author_id: None,
+ })
+ .await
+ .unwrap();
+
+ let resp = post(state, "/admin/reorg", json!({ "dry_run": false })).await;
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = body_json(resp).await;
+ assert_eq!(body["summary"]["pages_graveyarded"].as_u64().unwrap(), 1);
+
+ let default_hits = store
+ .reader
+ .recent_pages_for_project(default_ws, default_proj, 10)
+ .await
+ .unwrap();
+ assert!(
+ default_hits.is_empty(),
+ "default workspace latest page should be graveyarded"
+ );
+
+ let sibling_hits = store
+ .reader
+ .recent_pages_for_project(sibling_ws, sibling_proj, 10)
+ .await
+ .unwrap();
+ assert_eq!(
+ sibling_hits.len(),
+ 1,
+ "sibling workspace latest page must survive default reorg"
+ );
+ assert_eq!(sibling_hits[0].path.as_str(), "notes/sibling-latest.md");
+}
+
#[tokio::test]
async fn reorg_empty_store_returns_empty_plan() {
let tmp = TempDir::new().unwrap();
@@ -279,7 +368,17 @@ async fn lint_dry_run_returns_lint_report_shape() {
#[tokio::test]
async fn forget_sweep_dry_run_returns_sweep_report_shape() {
let tmp = TempDir::new().unwrap();
- let (state, _store) = make_state(&tmp).await;
+ let (state, store) = make_state(&tmp).await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
let resp = post(
state,
@@ -343,6 +442,35 @@ async fn embed_without_embedder_returns_503() {
);
}
+#[tokio::test]
+async fn embed_missing_project_scope_does_not_create_workspace() {
+ let tmp = TempDir::new().unwrap();
+ let (mut state, store) = make_state(&tmp).await;
+ state.embedder = Some(Arc::new(SyntheticEmbedder::new(64)));
+
+ let resp = post(
+ state,
+ "/admin/embed",
+ json!({
+ "workspace": "missing",
+ "project": "ghost",
+ "reembed": false,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+
+ let missing_ws = store
+ .reader
+ .find_workspace("missing".to_string())
+ .await
+ .unwrap();
+ assert!(
+ missing_ws.is_none(),
+ "embed must not create a missing workspace"
+ );
+}
+
#[tokio::test]
async fn embed_all_projects_rebuilds_workspace_projects() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-mcp/tests/admin_read_page.rs b/crates/ai-memory-mcp/tests/admin_read_page.rs
index e5302abb..6118d1ab 100644
--- a/crates/ai-memory-mcp/tests/admin_read_page.rs
+++ b/crates/ai-memory-mcp/tests/admin_read_page.rs
@@ -237,3 +237,26 @@ async fn read_page_404_when_truly_absent() {
.await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
+
+#[tokio::test]
+async fn read_page_missing_scope_does_not_create_workspace_or_project() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+
+ let resp = get(
+ state,
+ "/admin/read-page?workspace=missing&project=ghost&path=notes%2Fnope.md",
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+
+ let missing_ws = store
+ .reader
+ .find_workspace("missing".to_string())
+ .await
+ .unwrap();
+ assert!(
+ missing_ws.is_none(),
+ "read-page must not create a missing workspace"
+ );
+}
diff --git a/crates/ai-memory-mcp/tests/admin_status_search.rs b/crates/ai-memory-mcp/tests/admin_status_search.rs
index bd8d2d29..8e443340 100644
--- a/crates/ai-memory-mcp/tests/admin_status_search.rs
+++ b/crates/ai-memory-mcp/tests/admin_status_search.rs
@@ -177,6 +177,34 @@ async fn search_with_empty_results_returns_empty_array() {
assert!(hits.is_empty());
}
+#[tokio::test]
+async fn search_rejects_partial_scope_instead_of_global_fallback() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_admin_state(&tmp).await;
+ let app = admin_router(state);
+
+ let resp = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/admin/search?q=anything&workspace=default")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ let body: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap();
+ assert!(
+ body["error"]
+ .as_str()
+ .unwrap_or("")
+ .contains("workspace and project must be provided together"),
+ "unexpected error body: {body}"
+ );
+}
+
#[tokio::test]
async fn search_limit_is_clamped_to_100() {
// Server-side clamp prevents callers from requesting a million
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index d7daba64..644e3e98 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -929,6 +929,7 @@ fn audit(
/// fresh consolidation can regenerate clean per-project pages.
pub fn reorg_sessions(
conn: &mut Connection,
+ workspace_id: &WorkspaceId,
plan: &[(SessionId, ProjectId)],
) -> StoreResult<ReorgSummary> {
if plan.is_empty() {
@@ -939,23 +940,34 @@ pub fn reorg_sessions(
let mut observations_updated = 0usize;
for (session_id, new_project_id) in plan {
let rows = tx.execute(
- "UPDATE sessions SET project_id = ?1 WHERE id = ?2 AND project_id != ?1",
- params![new_project_id.as_bytes(), session_id.as_bytes()],
+ "UPDATE sessions
+ SET project_id = ?1
+ WHERE id = ?2 AND workspace_id = ?3 AND project_id != ?1",
+ params![
+ new_project_id.as_bytes(),
+ session_id.as_bytes(),
+ workspace_id.as_bytes()
+ ],
)?;
sessions_moved += rows;
// Update observations whose session_id matches, keeping project_id
// in sync with the session row we just moved.
let obs_rows = tx.execute(
- "UPDATE observations SET project_id = ?1 WHERE session_id = ?2",
- params![new_project_id.as_bytes(), session_id.as_bytes()],
+ "UPDATE observations SET project_id = ?1 WHERE session_id = ?2 AND workspace_id = ?3",
+ params![
+ new_project_id.as_bytes(),
+ session_id.as_bytes(),
+ workspace_id.as_bytes()
+ ],
)?;
observations_updated += obs_rows;
}
- // Graveyard all current latest pages — they mixed observations from
- // multiple projects and must be regenerated per-project by the next
- // consolidation pass.
- let pages_graveyarded: usize =
- tx.execute("UPDATE pages SET is_latest = 0 WHERE is_latest = 1", [])?;
+ // Graveyard only this workspace's latest pages; sibling workspaces may
+ // have already-consolidated pages that must remain current.
+ let pages_graveyarded: usize = tx.execute(
+ "UPDATE pages SET is_latest = 0 WHERE workspace_id = ?1 AND is_latest = 1",
+ params![workspace_id.as_bytes()],
+ )?;
tx.commit()?;
Ok(ReorgSummary {
sessions_moved,
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index c12aba56..3013a4b4 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -94,6 +94,8 @@ pub(crate) enum WriteCmd {
/// Retro-fit sessions + observations to per-cwd projects and graveyard
/// mash-up pages. Executed in one transaction for atomicity.
Reorg {
+ /// Workspace whose legacy mash-up pages and sessions are being reorged.
+ workspace_id: WorkspaceId,
/// Each entry is `(session_id, new_project_id)`.
plan: Vec<(SessionId, ProjectId)>,
reply: oneshot::Sender<StoreResult<ReorgSummary>>,
@@ -636,10 +638,16 @@ impl WriterHandle {
/// propagates the SQL error from the reorg transaction.
pub async fn reorg_sessions(
&self,
+ workspace_id: WorkspaceId,
plan: Vec<(SessionId, ProjectId)>,
) -> StoreResult<ReorgSummary> {
let (tx, rx) = oneshot::channel();
- self.send(WriteCmd::Reorg { plan, reply: tx }).await?;
+ self.send(WriteCmd::Reorg {
+ workspace_id,
+ plan,
+ reply: tx,
+ })
+ .await?;
rx.await.map_err(|_| StoreError::WriterClosed)?
}
@@ -918,8 +926,12 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
let result = ops::cancel_handoff(&mut conn, &handoff_id);
send_or_warn(reply, result, "cancel_handoff");
}
- WriteCmd::Reorg { plan, reply } => {
- let result = ops::reorg_sessions(&mut conn, &plan);
+ WriteCmd::Reorg {
+ workspace_id,
+ plan,
+ reply,
+ } => {
+ let result = ops::reorg_sessions(&mut conn, &workspace_id, &plan);
send_or_warn(reply, result, "reorg_sessions");
}
WriteCmd::BumpAccess { page_ids, reply } => {
diff --git a/docs/auto-scope.md b/docs/auto-scope.md
index 112a6dd5..acce200f 100644
--- a/docs/auto-scope.md
+++ b/docs/auto-scope.md
@@ -32,6 +32,13 @@ legacy behavior, but it is not per-session isolation; use explicit
`workspace` + `project` arguments when a client cannot send actor
identity and concurrent runs matter.
+Explicit scope arguments fail closed. A `project` argument is resolved
+inside the active workspace first, then inside the server's default
+workspace; if neither contains that project, the tool returns an error
+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.
+
## Configuration
```toml