Skip to content

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

Rust

feat(read-page): opt-in bounded related-pages walk on memory_read_page

AkitaOnRails3ee87372a2b5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d39c26ed..e6c53e75 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- `memory_read_page` gained an opt-in related-pages graph walk (default false;
+ targets the 2.4 line). Passing `include_related: true` adds a `related` array
+ of the pages reachable from the read page through the link graph — a bounded
+ breadth-first walk that reuses the single-hop link primitive per node,
+ following both outgoing links and incoming back-links out to `related_depth`
+ hops (default 1, hard-capped at 3). Each entry carries its
+ path/title/kind/workspace/project plus the hop `depth` and edge `direction`
+ (`link`/`backlink`) it was reached by; the walk is cross-project aware,
+ dedup- and cycle-safe via a global visited set, and bounded by a total-node
+ cap. Default-off behaviour is byte-identical to the previous single-page
+ response (no `related` field) (#NNN).
- `memory_query` gained an opt-in `include_superseded` argument (default false;
targets the 2.4 line). When set, project and explicit-scope searches also
return superseded (older) page versions across the FTS/entity/vector/graph
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
index 13893288..e778e5a8 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
@@ -12,7 +12,7 @@ Use this skill for read-only ai-memory lookups, catch-up, and evaluating remembe
- `memory_query` searches the current project's wiki for prior decisions, gotchas, procedures, rules, and session notes.
- `memory_recent` lists the most recently updated pages when the user wants a light activity check.
-- `memory_read_page` fetches a full page body after a search hit or direct path lookup.
+- `memory_read_page` fetches a full page body after a search hit or direct path lookup. Pass `include_related: true` (optional `related_depth`, default 1, hard cap 3) to also walk the link graph outward and return a `related` array of reachable pages, each with its hop `depth` and edge `direction` (`link`/`backlink`); default off omits it.
- `memory_read_session_observations` reads one session's raw hook observations (prompts, tool calls, stops) in capture order, paged and body-capped, when the user asks what actually happened in a session or wants to check a compiled page against its evidence.
- `memory_status` reports whether ai-memory is healthy and how large the knowledge base is.
- `memory_briefing` returns a structured read-only snapshot for agent consumption.
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index a55ec518..ece40e80 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -316,7 +316,10 @@ should be proposed from a completed session, or at explicit wrap-up \
the client-aware project-scope rule above; session-aware clients add \
explicit scope 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\
+ not just snippets. Pass `include_related: true` (with an optional \
+ `related_depth`, default 1, max 3) to also walk the link graph outward and \
+ get a `related` array of the pages reachable from this one, each tagged \
+ with its hop `depth` and `direction`.\n\
- `memory_read_session_observations` — when the user asks what actually \
happened in a session, wants to check a compiled page against its raw \
evidence, or needs the exact prompt/tool text behind a `memory_query` \
@@ -1293,6 +1296,16 @@ struct ReadPageArgs {
/// both for the current project; static MCP clients must pass both.
#[serde(default)]
workspace: Option<String>,
+ /// Opt-in: also walk the link graph outward from this page and return the
+ /// reachable pages in a `related` array. Default false → the response is
+ /// byte-identical to a plain single-page read (no `related` field).
+ #[serde(default)]
+ include_related: bool,
+ /// How many hops to walk when `include_related` is set. Default 1 (direct
+ /// neighbours only); hard-capped at 3, so a larger value is clamped.
+ /// Ignored when `include_related` is false.
+ #[serde(default)]
+ related_depth: Option<u8>,
}
/// Bounds for `memory_read_session_observations`. The defaults keep one call
@@ -3237,7 +3250,15 @@ impl AiMemoryServer {
this when the user asks to read, open, or show a specific page by \
name or topic — not just snippets. 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.")]
+ served from the DB fallback). \
+ \
+ Set `include_related: true` to also walk the link graph outward from \
+ this page and get a `related` array of the reachable pages, each with \
+ its `path`/`title`/`kind`/`workspace`/`project` plus the `depth` (hop \
+ distance) and `direction` (`link`/`backlink`) it was reached by; \
+ `related_depth` (default 1, hard-capped at 3) sets how far to walk. \
+ Default off → the response omits `related` entirely. Errors if the \
+ page is not found.")]
async fn memory_read_page(
&self,
Parameters(args): Parameters<ReadPageArgs>,
@@ -3305,6 +3326,32 @@ impl AiMemoryServer {
// 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.
+ //
+ // Opt-in related-pages walk. Computed once against the resolved scope so
+ // both the disk and DB-fallback branches attach the same `related`
+ // block; default off → `attach_related` is a no-op and the response
+ // stays byte-identical to a plain single-page read.
+ let related = if args.include_related {
+ let depth = args.related_depth.unwrap_or(1);
+ Some(
+ self.reader
+ .related_walk(ws, proj, page_path.to_string(), depth)
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?,
+ )
+ } else {
+ None
+ };
+ let attach_related = |mut value: serde_json::Value| {
+ if let (Some(nodes), Some(map)) = (&related, value.as_object_mut()) {
+ map.insert(
+ "related".into(),
+ serde_json::to_value(nodes).unwrap_or(serde_json::Value::Null),
+ );
+ }
+ value
+ };
+
match wiki.read_page(ws, proj, &page_path) {
Ok(md) => {
// Derive the title so an empty/absent frontmatter `title`
@@ -3313,12 +3360,12 @@ impl AiMemoryServer {
// frontmatter title was never filled otherwise read back
// titleless despite a proper `# Heading` (#599).
let title = ai_memory_wiki::derive_title(&md.frontmatter, &md.body, &page_path);
- ok_json(&serde_json::json!({
+ ok_json(&attach_related(serde_json::json!({
"path": page_path.to_string(),
"title": title,
"body": md.body,
"frontmatter": md.frontmatter,
- }))
+ })))
}
Err(disk_err) if is_missing_wiki_file(&disk_err) => {
match self
@@ -3336,13 +3383,13 @@ impl AiMemoryServer {
.and_then(|v| v.as_str())
.map(str::to_string)
.or(Some(stored.title));
- ok_json(&serde_json::json!({
+ ok_json(&attach_related(serde_json::json!({
"path": page_path.to_string(),
"title": title,
"body": stored.body,
"frontmatter": frontmatter,
"served_from": "db-fallback",
- }))
+ })))
}
None => {
// Not on disk and not in the DB under the resolved
@@ -8610,6 +8657,8 @@ mod tests {
path: None,
project: None,
workspace: None,
+ include_related: false,
+ related_depth: None,
}),
OptionalParts(test_parts_default()),
)
@@ -8660,6 +8709,8 @@ mod tests {
path: Some("notes/sibling.md".into()),
project: Some("docs".into()),
workspace: Some("practice".into()),
+ include_related: false,
+ related_depth: None,
}),
OptionalParts(test_parts_default()),
)
@@ -8713,6 +8764,8 @@ mod tests {
path: Some("notes/db-only-tool.md".into()),
project: None,
workspace: None,
+ include_related: false,
+ related_depth: None,
}),
OptionalParts(test_parts_default()),
)
@@ -8749,6 +8802,8 @@ mod tests {
path: Some("does-not-exist.md".into()),
project: Some("scratch".into()),
workspace: Some("default".into()),
+ include_related: false,
+ related_depth: None,
}),
test_optional_parts(),
)
@@ -8772,6 +8827,8 @@ mod tests {
path: Some("does-not-exist.md".into()),
project: None,
workspace: None,
+ include_related: false,
+ related_depth: None,
}),
test_optional_parts(),
)
@@ -10344,6 +10401,8 @@ mod tests {
path: Some("notes/default.md".into()),
project: Some("typo".into()),
workspace: None,
+ include_related: false,
+ related_depth: None,
}),
OptionalParts(test_parts_default()),
)
@@ -10421,6 +10480,8 @@ mod tests {
path: Some("notes/temp.md".into()),
project: None,
workspace: None,
+ include_related: false,
+ related_depth: None,
}),
OptionalParts(test_parts_default()),
)
@@ -10513,6 +10574,8 @@ mod tests {
path: Some("notes/keep.md".into()),
project: None,
workspace: None,
+ include_related: false,
+ related_depth: None,
}),
OptionalParts(test_parts_default()),
)
@@ -10622,6 +10685,8 @@ mod tests {
path: Some("notes/twin.md".into()),
project: Some("shared".into()),
workspace: Some("alpha".into()),
+ include_related: false,
+ related_depth: None,
}),
OptionalParts(test_parts_default()),
)
@@ -10639,6 +10704,8 @@ mod tests {
path: Some("notes/twin.md".into()),
project: Some("shared".into()),
workspace: Some("beta".into()),
+ include_related: false,
+ related_depth: None,
}),
OptionalParts(test_parts_default()),
)
@@ -11454,6 +11521,8 @@ mod tests {
path: Some("notes/bob-authored.md".into()),
project: None,
workspace: None,
+ include_related: false,
+ related_depth: None,
}),
OptionalParts(alice_parts),
)
diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rs
index 42ee7b84..aca28f5d 100644
--- a/crates/ai-memory-mcp/tests/suite/mod.rs
+++ b/crates/ai-memory-mcp/tests/suite/mod.rs
@@ -23,6 +23,7 @@ mod handoff_admission;
mod handoff_identity;
mod mcp_stateless_http;
mod query_superseded;
+mod read_page_related;
mod retrieval_via_tools;
mod slot_identity;
mod stress_autoscope;
diff --git a/crates/ai-memory-mcp/tests/suite/read_page_related.rs b/crates/ai-memory-mcp/tests/suite/read_page_related.rs
new file mode 100644
index 00000000..322ba8d5
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/suite/read_page_related.rs
@@ -0,0 +1,323 @@
+//! Opt-in related-pages graph walk on `memory_read_page`. By default the tool
+//! returns one page and nothing else; with `include_related: true` it also
+//! returns the pages reachable from that page through the link graph, out to
+//! `related_depth` hops (default 1, hard-capped at 3). Each related entry
+//! carries its identity plus how far and in which direction it was reached.
+//!
+//! Default-off must be byte-identical to the previous single-page response.
+
+use ai_memory_core::{NewPage, PagePath, Tier, WorkspaceId};
+use ai_memory_mcp::AiMemoryServer;
+use ai_memory_store::Store;
+use ai_memory_wiki::Wiki;
+use axum::Router;
+use axum::body::Body;
+use axum::http::Request;
+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
+use serde_json::{Value, json};
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+const WS: &str = "default";
+const PROJ: &str = "scratch";
+const SIBLING: &str = "lib";
+
+struct Harness {
+ router: Router,
+ store: Store,
+ ws: WorkspaceId,
+ _tmp: TempDir,
+}
+
+fn mount(server: AiMemoryServer) -> Router {
+ let service = StreamableHttpService::new(
+ move || Ok(server.clone()),
+ LocalSessionManager::default().into(),
+ StreamableHttpServerConfig::default()
+ .with_stateful_mode(false)
+ .with_json_response(true),
+ );
+ Router::new().nest_service("/mcp", service)
+}
+
+async fn harness() -> Harness {
+ let tmp = TempDir::new().expect("tempdir");
+ let store = Store::open(tmp.path()).expect("store");
+ let ws = store.writer.get_or_create_workspace(WS).await.expect("ws");
+ let proj = store
+ .writer
+ .get_or_create_project(ws, PROJ, None)
+ .await
+ .expect("proj");
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).expect("wiki");
+ let server =
+ AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj).with_wiki(wiki);
+
+ Harness {
+ router: mount(server),
+ store,
+ ws,
+ _tmp: tmp,
+ }
+}
+
+async fn call(router: &Router, name: &str, arguments: Value) -> Value {
+ let body = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": { "name": name, "arguments": arguments },
+ });
+ let req = Request::builder()
+ .method("POST")
+ .uri("/mcp")
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ .header("accept", "application/json, text/event-stream")
+ .body(Body::from(body.to_string()))
+ .expect("mcp req");
+ let resp = router.clone().oneshot(req).await.expect("oneshot");
+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)
+ .await
+ .expect("body");
+ let text = String::from_utf8(bytes.to_vec()).expect("utf8");
+ let v: Value = serde_json::from_str(&text).unwrap_or_else(|e| panic!("non-JSON: {text}: {e}"));
+ if let Some(err) = v.get("error") {
+ panic!("JSON-RPC error: {err}\nfull: {text}");
+ }
+ let joined = v
+ .pointer("/result/content")
+ .and_then(|c| c.as_array())
+ .unwrap_or_else(|| panic!("missing result.content: {text}"))
+ .iter()
+ .filter_map(|i| i.get("text").and_then(|t| t.as_str()))
+ .collect::<Vec<_>>()
+ .join("\n");
+ serde_json::from_str(&joined).unwrap_or_else(|e| panic!("tool text not JSON: {joined}: {e}"))
+}
+
+async fn write_page(router: &Router, path: &str, body: &str) {
+ let resp = call(
+ router,
+ "memory_write_page",
+ json!({ "workspace": WS, "project": PROJ, "path": path, "body": body }),
+ )
+ .await;
+ assert!(resp.get("page_id").is_some(), "page not written: {resp}");
+}
+
+/// Seed the graph through the real write path so links form from `[[wiki-links]]`
+/// in the bodies:
+///
+/// ```text
+/// notes/d.md ──▶ notes/a.md ──▶ notes/b.md ──▶ notes/c.md
+/// └────────▶ lib:notes/x.md (cross-project)
+/// ```
+async fn seed(h: &Harness) {
+ // Cross-project sibling target, created directly so the [[lib:...]] link
+ // resolves. This exercises the cross-project awareness of the walk.
+ let lib = h
+ .store
+ .writer
+ .get_or_create_project(h.ws, SIBLING, None)
+ .await
+ .expect("sibling proj");
+ h.store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: h.ws,
+ project_id: lib,
+ path: PagePath::new("notes/x.md").unwrap(),
+ title: "Sibling X".into(),
+ body: "cross-project leaf".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ author_id: None,
+ expires_at: None,
+ entities: Vec::new(),
+ evidence: Vec::new(),
+ })
+ .await
+ .expect("sibling page");
+
+ write_page(&h.router, "notes/c.md", "# C\n\nleaf page").await;
+ write_page(
+ &h.router,
+ "notes/b.md",
+ "# B\n\nsee [[notes/c.md]] and [[lib:notes/x.md]]",
+ )
+ .await;
+ write_page(&h.router, "notes/a.md", "# A\n\nsee [[notes/b.md]]").await;
+ write_page(&h.router, "notes/d.md", "# D\n\nsee [[notes/a.md]]").await;
+}
+
+fn related(resp: &Value) -> &Vec<Value> {
+ resp.get("related")
+ .and_then(|r| r.as_array())
+ .unwrap_or_else(|| panic!("no related array: {resp}"))
+}
+
+fn paths(nodes: &[Value]) -> Vec<String> {
+ let mut v: Vec<String> = nodes
+ .iter()
+ .map(|n| n.get("path").and_then(|p| p.as_str()).unwrap().to_string())
+ .collect();
+ v.sort();
+ v
+}
+
+fn read_args(extra: Value) -> Value {
+ let mut base = json!({ "workspace": WS, "project": PROJ, "path": "notes/a.md" });
+ let obj = base.as_object_mut().unwrap();
+ for (k, v) in extra.as_object().unwrap() {
+ obj.insert(k.clone(), v.clone());
+ }
+ base
+}
+
+#[tokio::test]
+async fn default_off_is_byte_identical_and_has_no_related_block() {
+ let h = harness().await;
+ seed(&h).await;
+
+ let plain = call(&h.router, "memory_read_page", read_args(json!({}))).await;
+ assert!(
+ plain.get("related").is_none(),
+ "a plain read must not carry a related block: {plain}"
+ );
+
+ // include_related:false is exactly the same response as omitting it.
+ let explicit_off = call(
+ &h.router,
+ "memory_read_page",
+ read_args(json!({ "include_related": false })),
+ )
+ .await;
+ assert_eq!(
+ plain, explicit_off,
+ "include_related:false must be byte-identical to the default read"
+ );
+}
+
+#[tokio::test]
+async fn include_related_default_depth_returns_direct_neighbours() {
+ let h = harness().await;
+ seed(&h).await;
+
+ let resp = call(
+ &h.router,
+ "memory_read_page",
+ read_args(json!({ "include_related": true })),
+ )
+ .await;
+
+ // The single page is still returned unchanged.
+ assert_eq!(
+ resp.get("path").and_then(|p| p.as_str()),
+ Some("notes/a.md")
+ );
+
+ let nodes = related(&resp);
+ assert_eq!(
+ paths(nodes),
+ vec!["notes/b.md".to_string(), "notes/d.md".to_string()],
+ "default depth 1 returns only direct neighbours (outgoing b, incoming d): {resp}"
+ );
+
+ let b = nodes
+ .iter()
+ .find(|n| n.get("path").and_then(|p| p.as_str()) == Some("notes/b.md"))
+ .unwrap();
+ assert_eq!(b.get("depth").and_then(Value::as_u64), Some(1));
+ assert_eq!(b.get("direction").and_then(|d| d.as_str()), Some("link"));
+ assert!(
+ b.get("title").and_then(|t| t.as_str()).is_some(),
+ "carries a title"
+ );
+ assert!(
+ b.get("kind").and_then(|k| k.as_str()).is_some(),
+ "carries a kind"
+ );
+
+ let d = nodes
+ .iter()
+ .find(|n| n.get("path").and_then(|p| p.as_str()) == Some("notes/d.md"))
+ .unwrap();
+ assert_eq!(
+ d.get("direction").and_then(|x| x.as_str()),
+ Some("backlink")
+ );
+}
+
+#[tokio::test]
+async fn related_depth_controls_how_far_the_walk_reaches() {
+ let h = harness().await;
+ seed(&h).await;
+
+ let depth2 = call(
+ &h.router,
+ "memory_read_page",
+ read_args(json!({ "include_related": true, "related_depth": 2 })),
+ )
+ .await;
+
+ let nodes = related(&depth2);
+ assert_eq!(
+ paths(nodes),
+ vec![
+ "notes/b.md".to_string(),
+ "notes/c.md".to_string(),
+ "notes/d.md".to_string(),
+ "notes/x.md".to_string(),
+ ],
+ "depth 2 adds c (via b) and the cross-project lib:x (via b): {depth2}"
+ );
+
+ let c = nodes
+ .iter()
+ .find(|n| n.get("path").and_then(|p| p.as_str()) == Some("notes/c.md"))
+ .unwrap();
+ assert_eq!(
+ c.get("depth").and_then(Value::as_u64),
+ Some(2),
+ "c is two hops out"
+ );
+
+ let x = nodes
+ .iter()
+ .find(|n| n.get("path").and_then(|p| p.as_str()) == Some("notes/x.md"))
+ .unwrap();
+ assert_eq!(
+ x.get("project").and_then(|p| p.as_str()),
+ Some(SIBLING),
+ "the cross-project neighbour carries its real project"
+ );
+}
+
+#[tokio::test]
+async fn related_depth_is_clamped_to_the_hard_cap() {
+ let h = harness().await;
+ seed(&h).await;
+
+ let at_cap = call(
+ &h.router,
+ "memory_read_page",
+ read_args(json!({ "include_related": true, "related_depth": 3 })),
+ )
+ .await;
+ let over_cap = call(
+ &h.router,
+ "memory_read_page",
+ read_args(json!({ "include_related": true, "related_depth": 200 })),
+ )
+ .await;
+
+ assert_eq!(
+ paths(related(&over_cap)),
+ paths(related(&at_cap)),
+ "a related_depth beyond the hard cap is clamped, not honoured"
+ );
+}
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 04714625..7796e1ea 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -64,10 +64,11 @@ pub use reader::{
DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding, GraphVia, HealthDetail, HealthPage,
ObservationHit, ObservationOrder, ObservationPage, ObservationPageResult, ObservationRecord,
OpenSession, PageAuthor, PageHit, PageHitWithMeta, PageLinks, PageMeta, PageSummary,
- ProjectSummary, ReaderPool, ReindexTargetStatus, RelatedPage, RrfContributions, ScopeRow,
- SearchExplain, SessionDependentRows, SessionEndDisposition, SessionSummary, SettledPage,
- StatusCounts, StorageStatus, StoredEmbedding, StoredPageBody, WorkspaceScopeRow,
- WorkspaceSummary, f32_vec_to_bytes,
+ ProjectSummary, RELATED_WALK_MAX_DEPTH, RELATED_WALK_MAX_NODES, ReaderPool,
+ ReindexTargetStatus, RelatedNode, RelatedPage, RrfContributions, ScopeRow, SearchExplain,
+ SessionDependentRows, SessionEndDisposition, SessionSummary, SettledPage, StatusCounts,
+ StorageStatus, StoredEmbedding, StoredPageBody, WorkspaceScopeRow, WorkspaceSummary,
+ f32_vec_to_bytes,
};
pub use retrieval_tuning::{RetrievalTuning, is_session_recall_query};
pub use scope::{
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 51fb97f2..b564095f 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1482,6 +1482,36 @@ pub struct PageLinks {
pub backlinks: Vec<RelatedPage>,
}
+/// Hard ceiling on how far [`ReaderPool::related_walk`] traverses the link
+/// graph. A caller's requested depth is clamped into `1..=RELATED_WALK_MAX_DEPTH`
+/// — a deeper walk is refused, not honoured, so one read cannot fan out across
+/// an unbounded slice of the graph.
+pub const RELATED_WALK_MAX_DEPTH: u8 = 3;
+
+/// Hard ceiling on the total number of distinct related nodes a single
+/// [`ReaderPool::related_walk`] returns. Bounds the response regardless of
+/// depth so a dense hub page cannot blow up a read; the walk stops as soon as
+/// this many nodes are collected.
+pub const RELATED_WALK_MAX_NODES: usize = 50;
+
+/// One node discovered by [`ReaderPool::related_walk`]: a [`RelatedPage`]
+/// (flattened into the same fields as a single-hop link) plus how it was
+/// reached — its hop distance from the seed and the direction of the edge that
+/// first reached it.
+#[derive(Debug, Clone, Serialize)]
+pub struct RelatedNode {
+ /// Identity of the related page (path/title/kind/workspace/project),
+ /// flattened so a node serializes exactly like a `page_links` entry with
+ /// two extra fields.
+ #[serde(flatten)]
+ pub page: RelatedPage,
+ /// Hop distance from the seed page (1 = a direct neighbour).
+ pub depth: u8,
+ /// Direction of the edge that first reached this node: `"link"` (the seed
+ /// side links out to it) or `"backlink"` (it links back toward the seed).
+ pub direction: &'static str,
+}
+
/// One page flagged by a workspace health check, with enough identity to
/// render a clickable drill-down row across projects.
#[derive(Debug, Clone, Serialize)]
@@ -6551,6 +6581,127 @@ impl ReaderPool {
.await
}
+ /// Bounded breadth-first walk of the link graph outward from one seed
+ /// page, following both outgoing links and incoming back-links.
+ ///
+ /// This is the multi-hop generalisation of [`Self::page_links`]: depth 1
+ /// returns exactly the seed's direct neighbours (the union of `links` and
+ /// `backlinks`), and each further hop expands the frontier by one edge.
+ /// Like `page_links`, both ends are constrained to `is_latest = 1`, and
+ /// neighbours in sibling projects/workspaces resolve and carry their real
+ /// coordinate — the walk is cross-project aware.
+ ///
+ /// Bounds (all enforced regardless of the caller):
+ /// - `depth` is clamped into `1..=`[`RELATED_WALK_MAX_DEPTH`].
+ /// - A global visited set makes the walk dedup- and cycle-safe: no page is
+ /// returned twice, cycles terminate, and the seed itself is never
+ /// returned.
+ /// - At most [`RELATED_WALK_MAX_NODES`] nodes are returned; the walk stops
+ /// as soon as the cap is reached.
+ ///
+ /// Returns an empty vec when the seed is missing or has no neighbours.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn related_walk(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ path: String,
+ depth: u8,
+ ) -> StoreResult<Vec<RelatedNode>> {
+ let depth = depth.clamp(1, RELATED_WALK_MAX_DEPTH);
+ self.with_conn(move |conn| {
+ let seed: Option<Vec<u8>> = conn
+ .query_row(
+ "SELECT id FROM pages \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 \
+ AND is_latest = 1",
+ params![workspace_id.as_bytes(), project_id.as_bytes(), path],
+ |row| row.get(0),
+ )
+ .optional()?;
+ let Some(seed) = seed else {
+ return Ok(Vec::new());
+ };
+
+ // Per-node expansion reuses the exact `page_links` resolution
+ // (latest-only, cross-project) but also selects `pg.id` so the walk
+ // can continue from each neighbour.
+ let kind_expr = page_kind_expr("pg.path", "pg.frontmatter_json");
+ let outgoing = format!(
+ "SELECT DISTINCT pg.id, pg.path, pg.title, {kind_expr}, ws.name, pr.name \
+ FROM links l \
+ JOIN pages pg ON pg.id = l.to_page_id \
+ JOIN projects pr ON pr.id = pg.project_id \
+ JOIN workspaces ws ON ws.id = pg.workspace_id \
+ WHERE l.from_page_id = ?1 AND pg.is_latest = 1 \
+ ORDER BY ws.name, pr.name, pg.path"
+ );
+ let incoming = format!(
+ "SELECT DISTINCT pg.id, pg.path, pg.title, {kind_expr}, ws.name, pr.name \
+ FROM links l \
+ JOIN pages pg ON pg.id = l.from_page_id \
+ JOIN projects pr ON pr.id = pg.project_id \
+ JOIN workspaces ws ON ws.id = pg.workspace_id \
+ WHERE l.to_page_id = ?1 AND pg.is_latest = 1 \
+ ORDER BY ws.name, pr.name, pg.path"
+ );
+ let mut out_stmt = conn.prepare(&outgoing)?;
+ let mut in_stmt = conn.prepare(&incoming)?;
+
+ let mut visited: std::collections::HashSet<Vec<u8>> = std::collections::HashSet::new();
+ visited.insert(seed.clone());
+ let mut results: Vec<RelatedNode> = Vec::new();
+ let mut frontier: Vec<Vec<u8>> = vec![seed];
+
+ 'walk: for hop in 1..=depth {
+ let mut next: Vec<Vec<u8>> = Vec::new();
+ for node in &frontier {
+ // Outgoing edges are labelled "link", incoming "backlink";
+ // a node reachable both ways keeps its first-reached label.
+ for (direction, stmt) in [("link", &mut out_stmt), ("backlink", &mut in_stmt)] {
+ let rows = stmt.query_map(params![node], |row| {
+ let id: Vec<u8> = row.get(0)?;
+ Ok((
+ id,
+ RelatedPage {
+ path: row.get(1)?,
+ title: row.get(2)?,
+ kind: row.get(3)?,
+ workspace: row.get(4)?,
+ project: row.get(5)?,
+ },
+ ))
+ })?;
+ for row in rows {
+ let (id, page) = row?;
+ if !visited.insert(id.clone()) {
+ continue;
+ }
+ results.push(RelatedNode {
+ page,
+ depth: hop,
+ direction,
+ });
+ next.push(id);
+ if results.len() >= RELATED_WALK_MAX_NODES {
+ break 'walk;
+ }
+ }
+ }
+ }
+ if next.is_empty() {
+ break;
+ }
+ frontier = next;
+ }
+
+ Ok(results)
+ })
+ .await
+ }
+
/// List unresolved cross-project links authored by pages in this project
/// — declared dependencies on another project's page that don't resolve.
/// Each row says whether the named target project exists, so the lint can
diff --git a/crates/ai-memory-store/tests/suite/mod.rs b/crates/ai-memory-store/tests/suite/mod.rs
index ff0e3f5e..a66c56df 100644
--- a/crates/ai-memory-store/tests/suite/mod.rs
+++ b/crates/ai-memory-store/tests/suite/mod.rs
@@ -12,6 +12,7 @@ mod fts_drift_status;
mod handoff_ownership;
mod most_recently_active_scope;
mod multi_session;
+mod related_walk;
mod retrieval_superseded;
mod retrieval_tuning_streams;
mod session_ids_touching_scope;
diff --git a/crates/ai-memory-store/tests/suite/related_walk.rs b/crates/ai-memory-store/tests/suite/related_walk.rs
new file mode 100644
index 00000000..fff2121d
--- /dev/null
+++ b/crates/ai-memory-store/tests/suite/related_walk.rs
@@ -0,0 +1,321 @@
+//! Bounded related-pages graph walk (`ReaderPool::related_walk`): a
+//! breadth-first traversal over the resolved link graph, starting from one
+//! seed page and following both outgoing links and incoming back-links out to
+//! a requested hop depth. It is the multi-hop generalisation of the
+//! single-hop `page_links` primitive.
+//!
+//! The invariants under test:
+//! - **Depth controls reach.** Depth 1 returns only direct neighbours; depth 2
+//! also returns their neighbours; and so on.
+//! - **The depth is hard-capped** at `RELATED_WALK_MAX_DEPTH`; a larger request
+//! is clamped, never honoured.
+//! - **A global visited set makes the walk dedup- and cycle-safe:** no page is
+//! returned twice and no cycle loops forever; the seed itself is never in the
+//! result.
+//! - **A total-node cap** bounds the response regardless of depth.
+//! - **Cross-project links resolve** and carry their real workspace/project.
+
+use ai_memory_core::{NewPage, PagePath, ProjectId, Tier, WorkspaceId};
+use ai_memory_store::{RELATED_WALK_MAX_DEPTH, RELATED_WALK_MAX_NODES, Store};
+
+fn page_with_links(
+ ws: WorkspaceId,
+ proj: ProjectId,
+ path: &str,
+ links: Vec<ai_memory_core::LinkTarget>,
+) -> NewPage {
+ NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new(path).unwrap(),
+ title: path.to_string(),
+ body: "body".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links,
+ author_id: None,
+ expires_at: None,
+ entities: Vec::new(),
+ evidence: Vec::new(),
+ }
+}
+
+fn same_project_link(path: &str) -> ai_memory_core::LinkTarget {
+ ai_memory_core::LinkTarget {
+ workspace: None,
+ project: None,
+ path: PagePath::new(path).unwrap(),
+ relation: None,
+ }
+}
+
+fn cross_project_link(project: &str, path: &str) -> ai_memory_core::LinkTarget {
+ ai_memory_core::LinkTarget {
+ workspace: None,
+ project: Some(project.to_string()),
+ path: PagePath::new(path).unwrap(),
+ relation: None,
+ }
+}
+
+/// Seeds the small graph:
+///
+/// ```text
+/// d ── links to ──▶ a ── links to ──▶ b ── links to ──▶ c
+/// ▲ │
+/// └── links to ─────┘ (cycle b⇄c)
+/// └── links to ──▶ lib:x (cross-project)
+/// ```
+///
+/// From `a`: depth 1 = {b (outgoing), d (incoming)}; depth 2 adds {c, lib:x}.
+/// The `c → b` edge closes a cycle without shortening any distance from `a`.
+async fn seeded_graph() -> (tempfile::TempDir, Store, WorkspaceId, ProjectId) {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default".to_string())
+ .await
+ .unwrap();
+ let app = store
+ .writer
+ .get_or_create_project(ws, "app".to_string(), None)
+ .await
+ .unwrap();
+ let lib = store
+ .writer
+ .get_or_create_project(ws, "lib".to_string(), None)
+ .await
+ .unwrap();
+
+ // Cross-project target first so the link resolves at write time.
+ store
+ .writer
+ .upsert_page(page_with_links(ws, lib, "notes/x.md", vec![]))
+ .await
+ .unwrap();
+
+ // Links back-resolve when their target lands, so creation order is free.
+ store
+ .writer
+ .upsert_page(page_with_links(
+ ws,
+ app,
+ "notes/b.md",
+ vec![
+ same_project_link("notes/c.md"),
+ cross_project_link("lib", "notes/x.md"),
+ ],
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(page_with_links(
+ ws,
+ app,
+ "notes/c.md",
+ vec![same_project_link("notes/b.md")],
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(page_with_links(
+ ws,
+ app,
+ "notes/a.md",
+ vec![same_project_link("notes/b.md")],
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(page_with_links(
+ ws,
+ app,
+ "notes/d.md",
+ vec![same_project_link("notes/a.md")],
+ ))
+ .await
+ .unwrap();
+
+ (tmp, store, ws, app)
+}
+
+#[tokio::test]
+async fn depth_one_returns_only_direct_neighbours() {
+ let (_tmp, store, ws, app) = seeded_graph().await;
+
+ let nodes = store
+ .reader
+ .related_walk(ws, app, "notes/a.md".into(), 1)
+ .await
+ .unwrap();
+
+ let mut paths: Vec<&str> = nodes.iter().map(|n| n.page.path.as_str()).collect();
+ paths.sort_unstable();
+ assert_eq!(
+ paths,
+ vec!["notes/b.md", "notes/d.md"],
+ "depth 1 is direct neighbours only (outgoing b, incoming d)"
+ );
+ for n in &nodes {
+ assert_eq!(n.depth, 1, "every depth-1 node is one hop away: {n:?}");
+ }
+ let b = nodes.iter().find(|n| n.page.path == "notes/b.md").unwrap();
+ assert_eq!(b.direction, "link", "b is reached as an outgoing link");
+ let d = nodes.iter().find(|n| n.page.path == "notes/d.md").unwrap();
+ assert_eq!(
+ d.direction, "backlink",
+ "d is reached as an incoming back-link"
+ );
+}
+
+#[tokio::test]
+async fn depth_two_adds_second_hop_including_cross_project() {
+ let (_tmp, store, ws, app) = seeded_graph().await;
+
+ let nodes = store
+ .reader
+ .related_walk(ws, app, "notes/a.md".into(), 2)
+ .await
+ .unwrap();
+
+ let mut paths: Vec<&str> = nodes.iter().map(|n| n.page.path.as_str()).collect();
+ paths.sort_unstable();
+ assert_eq!(
+ paths,
+ vec!["notes/b.md", "notes/c.md", "notes/d.md", "notes/x.md"],
+ "depth 2 adds c (via b) and the cross-project lib:x (via b)"
+ );
+
+ let c = nodes.iter().find(|n| n.page.path == "notes/c.md").unwrap();
+ assert_eq!(c.depth, 2, "c is two hops from a");
+
+ let x = nodes.iter().find(|n| n.page.path == "notes/x.md").unwrap();
+ assert_eq!(x.depth, 2, "the cross-project neighbour is two hops from a");
+ assert_eq!(
+ x.page.project, "lib",
+ "cross-project link resolves to its real project"
+ );
+ assert_eq!(x.page.workspace, "default");
+}
+
+#[tokio::test]
+async fn depth_is_clamped_to_the_hard_cap() {
+ let (_tmp, store, ws, app) = seeded_graph().await;
+
+ let capped = store
+ .reader
+ .related_walk(ws, app, "notes/a.md".into(), RELATED_WALK_MAX_DEPTH)
+ .await
+ .unwrap();
+ // Anything past the cap must behave exactly like the cap, not walk further.
+ let over = store
+ .reader
+ .related_walk(ws, app, "notes/a.md".into(), 100)
+ .await
+ .unwrap();
+
+ let paths = |ns: &[ai_memory_store::RelatedNode]| {
+ let mut v: Vec<String> = ns.iter().map(|n| n.page.path.clone()).collect();
+ v.sort_unstable();
+ v
+ };
+ assert_eq!(
+ paths(&over),
+ paths(&capped),
+ "a request beyond RELATED_WALK_MAX_DEPTH is clamped to the cap"
+ );
+}
+
+#[tokio::test]
+async fn walk_is_dedup_and_cycle_safe() {
+ let (_tmp, store, ws, app) = seeded_graph().await;
+
+ // b⇄c is a cycle. A deep walk must terminate, never return the
+ // seed, and never return a page twice.
+ let nodes = store
+ .reader
+ .related_walk(ws, app, "notes/a.md".into(), RELATED_WALK_MAX_DEPTH)
+ .await
+ .unwrap();
+
+ let mut seen = std::collections::HashSet::new();
+ for n in &nodes {
+ assert!(
+ seen.insert(n.page.path.clone()),
+ "page {} returned twice",
+ n.page.path
+ );
+ assert_ne!(
+ n.page.path, "notes/a.md",
+ "the seed is never in its own related set"
+ );
+ }
+}
+
+#[tokio::test]
+async fn total_node_cap_bounds_a_dense_hub() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default".to_string())
+ .await
+ .unwrap();
+ let app = store
+ .writer
+ .get_or_create_project(ws, "app".to_string(), None)
+ .await
+ .unwrap();
+
+ // A hub linking to far more than the cap's worth of direct neighbours.
+ let spoke_count = RELATED_WALK_MAX_NODES + 10;
+ let mut links = Vec::new();
+ for i in 0..spoke_count {
+ let path = format!("spokes/s{i}.md");
+ store
+ .writer
+ .upsert_page(page_with_links(ws, app, &path, vec![]))
+ .await
+ .unwrap();
+ links.push(same_project_link(&path));
+ }
+ store
+ .writer
+ .upsert_page(page_with_links(ws, app, "hub.md", links))
+ .await
+ .unwrap();
+
+ let nodes = store
+ .reader
+ .related_walk(ws, app, "hub.md".into(), 1)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ nodes.len(),
+ RELATED_WALK_MAX_NODES,
+ "the total-node cap bounds the walk even when a hub has more neighbours"
+ );
+ let unique: std::collections::HashSet<_> = nodes.iter().map(|n| &n.page.path).collect();
+ assert_eq!(
+ unique.len(),
+ nodes.len(),
+ "capped result still has no duplicates"
+ );
+}
+
+#[tokio::test]
+async fn missing_seed_returns_empty() {
+ let (_tmp, store, ws, app) = seeded_graph().await;
+ let nodes = store
+ .reader
+ .related_walk(ws, app, "notes/does-not-exist.md".into(), 2)
+ .await
+ .unwrap();
+ assert!(nodes.is_empty(), "a missing seed yields no related pages");
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index d1997fef..45728708 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -371,7 +371,7 @@ invariants below.
|---|---|---|
| `memory_query` | read-only | FTS5 + entity-match + graph RRF + optional vector RRF search, followed by bounded kind/tier/pinned/tag authority adjustment and raw fallback. Bumps access counters for page hits. Defaults to the current project; default-scoped calls also union the reserved `_global` preferences scope as `global_scope_hits`; `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). With `AI_MEMORY_RERANKER=llm`, project/scopes candidate pools are fused before at most one final LLM relevance pass; query/title/snippet data is bounded and JSON-encoded, and any timeout, provider error, invalid/incomplete score set, or four-call concurrency saturation preserves the adjusted order. The distinct `global=true` FTS-only ranker and supplemental global-preference hits are not reranked. `explain=true` attaches per-hit `score_details` (per-stream ranks, matched entities, raw FTS/cosine/entity inverse-frequency scores, RRF contributions, graph provenance including the typed edge kind (`causes`/`fixes`/`contradicts`) a neighbour was reached by, the page's evidence count, authority multiplier, and optional rerank score) to project/scopes hits plus a top-level `streams_active` list. The global FTS-only ranker reports its active stream without per-hit details. `include_expired=true` also returns TTL-expired pages. `include_superseded=true` also returns superseded (non-latest) page versions across the FTS/entity/vector/graph streams, each hit labelled `superseded: true` (the current version is never marked); default-off is byte-identical to the latest-only behaviour, and `global=true` / `as_of` are unaffected. |
| `memory_recent` | read-only | Most-recently-updated `is_latest=1` pages. |
-| `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. Use when an agent needs more than the 24-word snippets from `memory_query`. |
+| `memory_read_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`. `include_related=true` also walks the link graph outward from the page (bounded BFS reusing the `page_links` primitive per node: default 1 hop, hard cap 3, global visited set for dedup/cycle-safety, total-node cap 50, cross-project aware) and returns a `related` array of reachable pages, each labelled with its `depth` (hop distance) and `direction` (`link`/`backlink`); default-off is byte-identical (no `related` field). |
| `memory_read_session_observations` | read-only | Page through ONE session's raw hook observations (`ObservationRecord` with full sanitized body, capped per row by `body_max_chars`), restricted to the rows that landed in the resolved scope and to sessions the caller may see; `total` and `elided_other_scope` report the in-scope count and the rows the session left in another project. `session_id` omitted reads the latest completed visible session. |
| `memory_status` | read-only | Counts, paths, version. |
| `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. Opt-in `settled_first: true` leads with up to 8 of the project's highest-standing `rule`/`decision` pages, ordered by evidence count then recency; off by default. |