Skip to content

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

Rust

fix(mcp): constrain read-page DB fallback

AkitaOnRailsd3538c582638
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9d05b1cd..370b873b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
default to the active workspace published by hooks, and project-only reads use
the same active-workspace resolution so the write can be read back without an
explicit workspace ([#61]).
+- `memory_read_page` now accepts explicit `workspace` + `project` for sibling
+ projects and falls back to the stored DB body only when the markdown file is
+ missing, not when the disk source of truth is corrupt or unreadable ([#63]).
## [0.8.1] - 2026-05-30
diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rs
index 602bed89..ebbefe21 100644
--- a/crates/ai-memory-core/src/routing_snippet.rs
+++ b/crates/ai-memory-core/src/routing_snippet.rs
@@ -70,7 +70,7 @@ match the intent to the tool. They do not need to name the tool.
| "save context for the next session" / wrapping up | `memory_handoff_begin` (single-use handoff; terse summary; put detail in `open_questions` + `next_steps` bullets) |
| "consolidate this session" / "compile what we learned" (also runs on PreCompact; at session end only if `AI_MEMORY_CONSOLIDATE_ON_SESSION_END` is set) | `memory_consolidate` |
| "remember this permanently" / "save a note" / "add an annotation" / durable project knowledge | `memory_write_page` (write a wiki page; do **not** use handoff for permanent notes) |
-| "read the page about X" / "show me the full content of Y" / "open the page on Z" | `memory_read_page` (full body; pass a query to search or `path` for a direct lookup) |
+| "read the page about X" / "show me the full content of Y" / "open the page on Z" | `memory_read_page` (full body; pass a query to search or `path` for a direct lookup; pass `workspace` + `project` together only for a named sibling workspace/project) |
| "audit the wiki" / "find contradictions" / "what rules should we add?" | `memory_lint` |
| "prune old pages" / "memory cleanup" | `memory_forget_sweep` |
@@ -97,7 +97,8 @@ project** — shared `infra`, `ops`, or a related app. Don't conclude
short snippet does **not** mean the page is empty (a large page can
match outside the snippet window). To read the whole page, use
`memory_read_page` (by `path`, or pass a `query` to fetch the top hit's
-full body).
+full body; add `workspace` + `project` together only when the user names
+a sibling workspace/project).
### When you write a project rule, write it here
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 0af277a2..7a787676 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -36,7 +36,7 @@ use ai_memory_llm::{Embedder, LlmProvider, ProviderHealth, ProviderHealthSnapsho
use ai_memory_store::{
DecayParams, EmbeddingWrite, ReaderPool, StoreError, WriterHandle, f32_vec_to_bytes,
};
-use ai_memory_wiki::{Wiki, WritePageRequest};
+use ai_memory_wiki::{Wiki, WikiError, WritePageRequest};
use axum::Json;
use axum::Router;
use axum::body::Body;
@@ -394,6 +394,8 @@ struct ReadPageResponse {
title: Option<String>,
body: String,
frontmatter: serde_json::Value,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ served_from: Option<&'static str>,
}
async fn handle_read_page(
@@ -455,15 +457,16 @@ async fn handle_read_page(
title,
body: md.body,
frontmatter: md.frontmatter,
+ served_from: None,
};
(
StatusCode::OK,
Json(serde_json::to_value(&resp).unwrap_or_else(|_| serde_json::json!({}))),
)
}
- // On-disk read failed — fall back to the DB's faithful copy before
- // 404ing (index/disk skew; see gotchas/read-page-by-query-misses).
- Err(disk_err) => match state
+ // Only a missing markdown file can fall back to the DB copy. Other disk
+ // errors belong to the source-of-truth file and must be surfaced.
+ Err(disk_err) if is_missing_wiki_file(&disk_err) => match state
.reader
.page_body_by_ids(ws, proj, page_path.as_str())
.await
@@ -483,6 +486,7 @@ async fn handle_read_page(
title,
body: stored.body,
frontmatter,
+ served_from: Some("db-fallback"),
};
(
StatusCode::OK,
@@ -495,6 +499,7 @@ async fn handle_read_page(
),
Err(e) => internal_err(e.to_string()),
},
+ Err(disk_err) => internal_err(disk_err.to_string()),
}
}
@@ -510,6 +515,10 @@ fn internal_err(msg: impl Into<String>) -> (StatusCode, Json<serde_json::Value>)
)
}
+fn is_missing_wiki_file(err: &WikiError) -> bool {
+ matches!(err, WikiError::Io(e) if e.kind() == std::io::ErrorKind::NotFound)
+}
+
/// Resolve workspace + project IDs, creating them if absent. Returns
/// either the IDs or a ready-to-return error response.
async fn resolve_ws_proj(
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index b55f6ce6..ff3a35ea 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -10,7 +10,7 @@ use ai_memory_core::{
};
use ai_memory_llm::{Embedder, LlmProvider};
use ai_memory_store::{DecayParams, PageHit, ReaderPool, WriterHandle};
-use ai_memory_wiki::{Wiki, WritePageRequest};
+use ai_memory_wiki::{Wiki, WikiError, WritePageRequest};
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
@@ -80,7 +80,9 @@ the conversation calls for them:\n\
do NOT use `memory_handoff_begin` for permanent annotations.\n\
- `memory_read_page` — when the user asks to read, open, or show the \
full content of a specific page. Accepts a `query` (searches FTS5 and \
- returns the top hit's full body) or a `path` (direct lookup). Use \
+ returns the top hit's full body) or a `path` (direct lookup). Pass \
+ `workspace` + `project` together only when reading a page from a named \
+ sibling workspace/project. Use \
this instead of memory_query when the user wants the complete text, \
not just snippets.\n\
- `memory_lint` — when the user asks to audit the wiki for stale \
@@ -108,7 +110,8 @@ it' after one project misses. Note also that `memory_query` returns \
SNIPPETS, not full page bodies — an empty or short snippet does NOT \
mean the page is empty (a large page can match outside the snippet \
window); to read the whole page use `memory_read_page` (by `path`, \
-or a `query` for the top hit's body).\n\
+or a `query` for the top hit's body; add `workspace` + `project` \
+together only for a named sibling workspace/project).\n\
\n\
The routing snippet this very text comes from can also be installed \
into the project's CLAUDE.md / AGENTS.md so the guidance survives \
@@ -1035,7 +1038,8 @@ impl AiMemoryServer {
/// Fetch the full body of a single wiki page.
#[tool(description = "Fetch the FULL body of a wiki page for the current \
- project. Use this when the user asks to read, open, or show a specific \
+ project by default. Pass `workspace` + `project` together only when \
+ the user names a sibling workspace/project. Use this when the user asks to read, open, or show a specific \
page by name or topic — not just snippets. \
\
Two modes: \
@@ -1044,7 +1048,8 @@ impl AiMemoryServer {
(2) pass `path` — direct lookup by the page's relative wiki path \
(e.g. `notes/budget.md`). `path` takes precedence when both are given. \
\
- Returns `{ path, title, body, frontmatter }`. Errors if the page is \
+ Returns `{ path, title, body, frontmatter }` (plus `served_from` when \
+ a missing markdown file is served from the DB fallback). Errors if the page is \
not found or neither argument is supplied.")]
async fn memory_read_page(
&self,
@@ -1088,11 +1093,9 @@ impl AiMemoryServer {
));
};
- // Markdown on disk is the source of truth, but the on-disk read can
- // fail when the index is momentarily ahead of disk (recently-written
- // page, or a known watcher/disk skew — gotchas/read-page-by-query-misses).
- // Fall back to the DB's faithful copy before surfacing an error so the
- // agent never wrongly concludes a page it can see in search is gone.
+ // Markdown on disk is the source of truth. Only a missing markdown file
+ // uses the DB fallback; parse/permission/corruption errors must surface
+ // so operators can fix the disk source of truth.
match wiki.read_page(ws, proj, &page_path) {
Ok(md) => {
let title = md
@@ -1107,7 +1110,7 @@ impl AiMemoryServer {
"frontmatter": md.frontmatter,
}))
}
- Err(disk_err) => {
+ Err(disk_err) if is_missing_wiki_file(&disk_err) => {
match self
.reader
.page_body_by_ids(ws, proj, page_path.as_str())
@@ -1134,6 +1137,7 @@ impl AiMemoryServer {
None => Err(McpError::internal_error(disk_err.to_string(), None)),
}
}
+ Err(disk_err) => Err(McpError::internal_error(disk_err.to_string(), None)),
}
}
@@ -1412,6 +1416,10 @@ fn ok_json<T: Serialize>(value: &T) -> Result<CallToolResult, McpError> {
Ok(CallToolResult::success(vec![Content::text(s)]))
}
+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())
}
@@ -1530,7 +1538,7 @@ mod tests {
use super::*;
use ai_memory_core::{NewObservation, NewPage, NewSession, ObservationKind, PagePath, Tier};
use ai_memory_store::Store;
- use ai_memory_wiki::Wiki;
+ use ai_memory_wiki::{Wiki, WritePageRequest};
use tempfile::TempDir;
async fn setup_server() -> (TempDir, Store, AiMemoryServer, WorkspaceId, ProjectId) {
@@ -1992,6 +2000,108 @@ mod tests {
assert!(text.contains("patterns.md"), "expected hit; got {text}");
}
+ #[tokio::test]
+ async fn memory_read_page_can_target_explicit_workspace_project() {
+ let (tmp, store, server, _ws, _pj) = setup_server().await;
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let practice_ws = store
+ .writer
+ .get_or_create_workspace("practice")
+ .await
+ .unwrap();
+ let docs = store
+ .writer
+ .get_or_create_project(practice_ws, "docs", None)
+ .await
+ .unwrap();
+ wiki.write_page(WritePageRequest {
+ workspace_id: practice_ws,
+ project_id: docs,
+ path: PagePath::new("notes/sibling.md").unwrap(),
+ frontmatter: serde_json::json!({"title": "Sibling Page"}),
+ body: "workspace explicit read body".to_string(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: Some("Sibling Page".into()),
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ })
+ .await
+ .unwrap();
+
+ let result = server
+ .with_wiki(wiki)
+ .memory_read_page(Parameters(ReadPageArgs {
+ query: None,
+ path: Some("notes/sibling.md".into()),
+ project: Some("docs".into()),
+ workspace: Some("practice".into()),
+ }))
+ .await
+ .unwrap();
+ let text = result
+ .content
+ .first()
+ .and_then(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .unwrap();
+ assert!(
+ text.contains("workspace explicit read body"),
+ "expected sibling workspace body; got {text}"
+ );
+ assert!(
+ text.contains("notes/sibling.md"),
+ "expected sibling workspace path; got {text}"
+ );
+ }
+
+ #[tokio::test]
+ async fn memory_read_page_marks_db_fallback_when_file_missing() {
+ let (tmp, store, server, ws, proj) = setup_server().await;
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new("notes/db-only-tool.md").unwrap(),
+ title: "DB Only Tool".into(),
+ body: "tool fallback body".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({"title": "DB Only Tool"}),
+ pinned: false,
+ links: Vec::new(),
+ author_id: None,
+ })
+ .await
+ .unwrap();
+
+ let result = server
+ .with_wiki(wiki)
+ .memory_read_page(Parameters(ReadPageArgs {
+ query: None,
+ path: Some("notes/db-only-tool.md".into()),
+ project: None,
+ workspace: None,
+ }))
+ .await
+ .unwrap();
+ let text = result
+ .content
+ .first()
+ .and_then(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .unwrap();
+ assert!(
+ text.contains("tool fallback body"),
+ "expected DB body; got {text}"
+ );
+ assert!(
+ text.contains("db-fallback"),
+ "expected fallback diagnostic; got {text}"
+ );
+ }
+
#[tokio::test]
async fn memory_query_can_search_multiple_scopes() {
let (_tmp, store, server, ws, _pj) = setup_server().await;
diff --git a/crates/ai-memory-mcp/tests/admin_read_page.rs b/crates/ai-memory-mcp/tests/admin_read_page.rs
index ab7740cd..866f633f 100644
--- a/crates/ai-memory-mcp/tests/admin_read_page.rs
+++ b/crates/ai-memory-mcp/tests/admin_read_page.rs
@@ -1,7 +1,7 @@
//! Integration tests for `GET /admin/read-page`, focused on the DB-backed
-//! fallback: when the on-disk markdown read fails (index ahead of disk), the
-//! handler serves the store's faithful copy instead of 404ing
-//! (gotchas/read-page-by-query-misses).
+//! fallback: when the on-disk markdown file is missing (index ahead of disk),
+//! the handler serves the store's faithful copy instead of 404ing
+//! (gotchas/read-page-by-query-misses), while real parse errors still surface.
use ai_memory_core::{NewPage, PagePath, Tier};
use ai_memory_mcp::{AdminState, admin_router};
@@ -99,6 +99,7 @@ async fn read_page_falls_back_to_db_when_file_missing() {
"{body}"
);
assert_eq!(body["title"], "DB Only", "{body}");
+ assert_eq!(body["served_from"], "db-fallback", "{body}");
}
/// Sanity: a page written through the wiki (disk + index) is served from disk
@@ -146,6 +147,65 @@ async fn read_page_serves_on_disk_page() {
"written to disk via the wiki",
"{body}"
);
+ assert!(body.get("served_from").is_none(), "{body}");
+}
+
+/// A malformed markdown source must not be hidden by the DB fallback. The disk
+/// file is the source of truth; parse errors need to be visible to operators.
+#[tokio::test]
+async fn read_page_does_not_fall_back_when_disk_frontmatter_is_malformed() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default".to_string())
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch".to_string(), None)
+ .await
+ .unwrap();
+ let path = PagePath::new("notes/malformed.md").unwrap();
+ state
+ .wiki
+ .write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: path.clone(),
+ frontmatter: serde_json::json!({"title": "Stored Copy"}),
+ body: "stored copy must not mask a malformed disk file".to_string(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: Some("Stored Copy".into()),
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ })
+ .await
+ .unwrap();
+
+ let abs = state.wiki.abs_path(ws, proj, &path);
+ std::fs::write(
+ &abs,
+ "---\ntitle: [unterminated\n---\nmalformed disk body\n",
+ )
+ .unwrap();
+
+ let resp = get(
+ state,
+ "/admin/read-page?workspace=default&project=scratch&path=notes%2Fmalformed.md",
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
+ let body = body_json(resp).await;
+ assert!(
+ body["error"]
+ .as_str()
+ .unwrap_or("")
+ .contains("frontmatter yaml"),
+ "{body}"
+ );
+ assert!(body.get("served_from").is_none(), "{body}");
}
/// A genuinely-absent page (no DB row, no file) still 404s — the fallback
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 2ac717b3..bf1c3406 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -235,7 +235,7 @@ invariants below.
|---|---|---|
| `memory_query` | read-only | FTS5 + graph RRF + optional vector RRF search, with raw fallback. Bumps access counters for page hits. Defaults to the current project; `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). |
| `memory_recent` | read-only | Most-recently-updated `is_latest=1` pages. |
-| `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`. Use when an agent needs more than the 24-word snippets from `memory_query`. |
+| `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. Use when an agent needs more than the 24-word snippets from `memory_query`. |
| `memory_status` | read-only | Counts, paths, version. |
| `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. |
| `memory_explore` | read-only | LLM prose digest over the briefing snapshot, degrading to JSON without a provider. |