Skip to content

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

Rust

Add a read-only wiki link graph in /web

Matt Van Horn63fbf1eeb7af
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 60f22c28..20bf70c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,22 @@ version in [`docs/changelog/`](docs/changelog/):
## [Unreleased]
+### Added
+
+- Added a read-only wiki link graph in `/web`. The header **Graph** link opens
+ `/web/graph`, a server-rendered map of resolved wikilinks whose endpoints sit
+ in different projects, plus a table of those edges. Each project page links
+ to `/web/w/<workspace>/<project>/graph`, which shows that project's latest
+ unexpired pages and the resolved same-project links between them as an SVG
+ and a table. Both pages are HTML with no JavaScript.
+ `GET /api/v1/graph` now accepts `workspace` and `project` together to return
+ only edges that touch that project (passing only one of them is `400`), and
+ `GET /api/v1/workspaces/{workspace}/projects/{project}/graph` returns the
+ in-project node and edge lists. A project graph keeps at most 120 pages,
+ preferring those with the most same-project neighbours and then the most
+ recently updated. Expired pages stay hidden. An edge still requires both
+ ends to be readable.
+
### Fixed
- `ai-memory auth login openai-oauth` and `auth login copilot` no longer print
a failed endpoint's whole response body. Error bodies are bounded, scrubbed
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 54b54287..b468743a 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -85,11 +85,12 @@ pub use reader::{
ActivityWindow, AgentSessionCount, AuditEvent, AuditLogFilter, AutoImproveCandidateSession,
AutoImproveParkedClaim, BriefPageBody, BriefingPage, BriefingSnapshot, ClientActivity,
ContaminationFinding, ContaminationReport, ContaminationSummary, ContradictionEdge,
- DecayCandidate, DecayTombstone, DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding,
- GraphVia, HealthDetail, HealthPage, HybridSearch, InboxCount, InboxEntry, ObservationHit,
- ObservationOrder, ObservationPage, ObservationPageResult, ObservationProjectionTotals,
- ObservationRecord, OpenSession, PAGE_KINDS, PAGE_VERSIONS_MAX_LIMIT, PageAuthor, PageFilter,
- PageHit, PageHitWithMeta, PageLinks, PageLinksPreview, PageMeta, PageSummary, PageVersion,
+ CrossProjectEdge, DecayCandidate, DecayTombstone, DerivedIndexStatus, EmbeddingTripleCount,
+ FeedbackFinding, GraphVia, HealthDetail, HealthPage, HybridSearch, InboxCount, InboxEntry,
+ LinkGraph, LinkGraphEdge, LinkGraphNode, ObservationHit, ObservationOrder, ObservationPage,
+ ObservationPageResult, ObservationProjectionTotals, ObservationRecord, OpenSession, PAGE_KINDS,
+ PAGE_VERSIONS_MAX_LIMIT, PROJECT_LINK_GRAPH_MAX_NODES, PageAuthor, PageFilter, PageHit,
+ PageHitWithMeta, PageLinks, PageLinksPreview, PageMeta, PageSummary, PageVersion,
PageVersionBody, PageVersions, ProjectCoordinateCollisionReason, ProjectCoordinateDiagnostic,
ProjectCoordinateStatus, ProjectSummary, RELATED_WALK_MAX_DEPTH, RELATED_WALK_MAX_NODES,
ReaderPool, ReindexTargetStatus, RelatedNode, RelatedPage, RrfContributions,
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index dfb8f870..a1e94752 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -6,6 +6,7 @@
//! soft cap: a connection that comes back when the pool is already full
//! is simply dropped.
+use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -2129,6 +2130,45 @@ pub struct PageMeta {
pub expired: bool,
}
+/// Soft cap on nodes in a project link graph. Pages with the fewest
+/// same-project neighbours drop first when a project is larger, then the
+/// oldest of those; the rest stay reachable from the page tree.
+pub const PROJECT_LINK_GRAPH_MAX_NODES: usize = 120;
+
+/// One latest page kept in a project link graph.
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+pub struct LinkGraphNode {
+ /// Relative wiki path.
+ pub path: String,
+ /// Page title.
+ pub title: String,
+ /// Number of resolved same-project neighbours (either direction).
+ pub degree: u64,
+}
+
+/// One resolved same-project edge in a project link graph.
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+pub struct LinkGraphEdge {
+ /// Source page path.
+ pub from_path: String,
+ /// Target page path.
+ pub to_path: String,
+}
+
+/// Latest unexpired pages in one project and the resolved wikilinks among
+/// them. Powers `/web/w/{workspace}/{project}/graph` and
+/// `GET /api/v1/workspaces/{workspace}/projects/{project}/graph`.
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+pub struct LinkGraph {
+ /// Pages kept after the degree-then-recency cap.
+ pub nodes: Vec<LinkGraphNode>,
+ /// Resolved same-project edges whose both ends are in `nodes`.
+ pub edges: Vec<LinkGraphEdge>,
+ /// `true` when the project has more live pages than
+ /// [`PROJECT_LINK_GRAPH_MAX_NODES`].
+ pub truncated: bool,
+}
+
/// One resolved cross-project edge (a link whose endpoints live in
/// different projects). The `/api/v1/graph` endpoint returns these; the UI
/// builds nodes from the endpoints and can aggregate to a project graph.
@@ -9265,6 +9305,117 @@ impl ReaderPool {
.await
}
+ /// Latest unexpired pages in one project and the resolved wikilinks
+ /// among them.
+ ///
+ /// Cross-project and unresolved links are omitted: this is the in-project
+ /// map the project graph page draws. Expired pages are hidden the same way
+ /// other retrieval surfaces hide them. When the project has more live
+ /// pages than [`PROJECT_LINK_GRAPH_MAX_NODES`], pages with the fewest
+ /// same-project neighbours drop first, then the oldest of those.
+ ///
+ /// Personal slots are included, matching [`Self::list_pages`]: the caller
+ /// has already authorized the project.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn project_link_graph(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ ) -> StoreResult<LinkGraph> {
+ self.with_conn(move |conn| {
+ let now = now_us();
+ let ttl = not_expired("pg", "?3");
+ let mut page_stmt = conn.prepare(&format!(
+ "SELECT pg.id, pg.path, pg.title, pg.updated_at \
+ FROM pages pg \
+ WHERE pg.workspace_id = ?1 AND pg.project_id = ?2 \
+ AND pg.is_latest = 1{ttl}"
+ ))?;
+ let page_rows = page_stmt.query_map(
+ params![workspace_id.as_bytes(), project_id.as_bytes(), now],
+ |row| {
+ let id: Vec<u8> = row.get(0)?;
+ Ok((id, row.get(1)?, row.get(2)?, row.get::<_, i64>(3)?))
+ },
+ )?;
+ let mut pages: Vec<(PageId, String, String, i64)> = Vec::new();
+ for row in page_rows {
+ let (id, path, title, updated_at) = row?;
+ pages.push((PageId::from_slice(&id)?, path, title, updated_at));
+ }
+
+ let from_ttl = not_expired("fp", "?3");
+ let to_ttl = not_expired("tp", "?3");
+ let mut edge_stmt = conn.prepare(&format!(
+ "SELECT DISTINCT fp.id, tp.id, fp.path, tp.path \
+ FROM links l \
+ JOIN pages fp ON fp.id = l.from_page_id AND fp.is_latest = 1{from_ttl} \
+ JOIN pages tp ON tp.id = l.to_page_id AND tp.is_latest = 1{to_ttl} \
+ WHERE fp.workspace_id = ?1 AND fp.project_id = ?2 \
+ AND tp.workspace_id = ?1 AND tp.project_id = ?2 \
+ ORDER BY fp.path, tp.path"
+ ))?;
+ let edge_rows = edge_stmt.query_map(
+ params![workspace_id.as_bytes(), project_id.as_bytes(), now],
+ |row| {
+ let from_id: Vec<u8> = row.get(0)?;
+ let to_id: Vec<u8> = row.get(1)?;
+ Ok((from_id, to_id, row.get(2)?, row.get(3)?))
+ },
+ )?;
+ let mut raw_edges: Vec<(PageId, PageId, String, String)> = Vec::new();
+ for row in edge_rows {
+ let (from_id, to_id, from_path, to_path) = row?;
+ raw_edges.push((
+ PageId::from_slice(&from_id)?,
+ PageId::from_slice(&to_id)?,
+ from_path,
+ to_path,
+ ));
+ }
+
+ let mut degree: HashMap<PageId, u64> = HashMap::new();
+ for (from_id, to_id, _, _) in &raw_edges {
+ *degree.entry(*from_id).or_insert(0) += 1;
+ if from_id != to_id {
+ *degree.entry(*to_id).or_insert(0) += 1;
+ }
+ }
+
+ pages.sort_by(|a, b| {
+ let da = degree.get(&a.0).copied().unwrap_or(0);
+ let db = degree.get(&b.0).copied().unwrap_or(0);
+ db.cmp(&da)
+ .then_with(|| b.3.cmp(&a.3))
+ .then_with(|| a.1.cmp(&b.1))
+ });
+ let truncated = pages.len() > PROJECT_LINK_GRAPH_MAX_NODES;
+ pages.truncate(PROJECT_LINK_GRAPH_MAX_NODES);
+ let keep: HashSet<PageId> = pages.iter().map(|page| page.0).collect();
+ let nodes = pages
+ .into_iter()
+ .map(|(id, path, title, _)| LinkGraphNode {
+ degree: degree.get(&id).copied().unwrap_or(0),
+ path,
+ title,
+ })
+ .collect();
+ let edges = raw_edges
+ .into_iter()
+ .filter(|(from_id, to_id, _, _)| keep.contains(from_id) && keep.contains(to_id))
+ .map(|(_, _, from_path, to_path)| LinkGraphEdge { from_path, to_path })
+ .collect();
+ Ok(LinkGraph {
+ nodes,
+ edges,
+ truncated,
+ })
+ })
+ .await
+ }
+
/// Return one row per (workspace, project) with page-count and
/// last-updated aggregates. Used by the web UI project-list view.
///
diff --git a/crates/ai-memory-store/tests/suite/mod.rs b/crates/ai-memory-store/tests/suite/mod.rs
index 54fef78e..592bb538 100644
--- a/crates/ai-memory-store/tests/suite/mod.rs
+++ b/crates/ai-memory-store/tests/suite/mod.rs
@@ -21,6 +21,7 @@ mod page_first_created;
mod pinned_pages;
mod profile;
mod project_authz;
+mod project_link_graph;
mod reclaim_ledger_versions;
mod related_walk;
mod retrieval_observation_stream;
diff --git a/crates/ai-memory-store/tests/suite/project_link_graph.rs b/crates/ai-memory-store/tests/suite/project_link_graph.rs
new file mode 100644
index 00000000..0610004a
--- /dev/null
+++ b/crates/ai-memory-store/tests/suite/project_link_graph.rs
@@ -0,0 +1,311 @@
+//! In-project link graph (`ReaderPool::project_link_graph`): latest
+//! unexpired pages in one project and the resolved wikilinks among them.
+//!
+//! The invariants under test:
+//! - Same-project resolved links become edges; isolated pages stay as nodes.
+//! - Cross-project and unresolved links never appear.
+//! - Expired pages are neither nodes nor endpoints.
+//! - When a project is larger than `PROJECT_LINK_GRAPH_MAX_NODES`, high-degree
+//! pages are kept ahead of isolated ones, then recency.
+
+use ai_memory_core::{NewPage, PagePath, ProjectId, Tier, WorkspaceId};
+use ai_memory_store::{PROJECT_LINK_GRAPH_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,
+ }
+}
+
+fn with_expiry(mut page: NewPage, expires_at: jiff::Timestamp) -> NewPage {
+ page.expires_at = Some(expires_at);
+ page
+}
+
+async fn seeded() -> (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();
+
+ store
+ .writer
+ .upsert_page(page_with_links(ws, lib, "notes/x.md", vec![]))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(page_with_links(ws, app, "notes/b.md", vec![]))
+ .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"),
+ same_project_link("notes/nope.md"),
+ cross_project_link("lib", "notes/x.md"),
+ ],
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(page_with_links(ws, app, "notes/isolated.md", vec![]))
+ .await
+ .unwrap();
+
+ (tmp, store, ws, app)
+}
+
+#[tokio::test]
+async fn project_graph_keeps_same_project_edges_and_isolated_pages() {
+ let (_tmp, store, ws, app) = seeded().await;
+ let graph = store.reader.project_link_graph(ws, app).await.unwrap();
+
+ let mut paths: Vec<&str> = graph.nodes.iter().map(|n| n.path.as_str()).collect();
+ paths.sort_unstable();
+ assert_eq!(
+ paths,
+ vec![
+ "notes/a.md",
+ "notes/b.md",
+ "notes/c.md",
+ "notes/isolated.md",
+ ]
+ );
+ assert!(!graph.truncated);
+
+ let mut pairs: Vec<(&str, &str)> = graph
+ .edges
+ .iter()
+ .map(|e| (e.from_path.as_str(), e.to_path.as_str()))
+ .collect();
+ pairs.sort_unstable();
+ assert_eq!(
+ pairs,
+ vec![("notes/a.md", "notes/b.md"), ("notes/c.md", "notes/b.md")]
+ );
+
+ let a = graph.nodes.iter().find(|n| n.path == "notes/a.md").unwrap();
+ let b = graph.nodes.iter().find(|n| n.path == "notes/b.md").unwrap();
+ let isolated = graph
+ .nodes
+ .iter()
+ .find(|n| n.path == "notes/isolated.md")
+ .unwrap();
+ assert_eq!(a.degree, 1);
+ assert_eq!(b.degree, 2, "b is cited by a and c");
+ assert_eq!(isolated.degree, 0);
+}
+
+#[tokio::test]
+async fn project_graph_omits_cross_project_and_unresolved_links() {
+ let (_tmp, store, ws, app) = seeded().await;
+ let graph = store.reader.project_link_graph(ws, app).await.unwrap();
+ let blob = format!("{graph:?}");
+ assert!(
+ !blob.contains("notes/x.md"),
+ "cross-project target must not appear: {blob}"
+ );
+ assert!(
+ !blob.contains("notes/nope.md"),
+ "unresolved target must not appear: {blob}"
+ );
+}
+
+#[tokio::test]
+async fn project_graph_hides_expired_pages_and_their_edges() {
+ 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 expired_at: jiff::Timestamp = "2000-01-01T00:00:00Z".parse().unwrap();
+ let future_at: jiff::Timestamp = "2099-01-01T00:00:00Z".parse().unwrap();
+
+ for page in [
+ page_with_links(ws, app, "notes/live.md", vec![]),
+ with_expiry(
+ page_with_links(ws, app, "notes/expired.md", vec![]),
+ expired_at,
+ ),
+ with_expiry(
+ page_with_links(ws, app, "notes/future.md", vec![]),
+ future_at,
+ ),
+ page_with_links(
+ ws,
+ app,
+ "notes/hub.md",
+ vec![
+ same_project_link("notes/live.md"),
+ same_project_link("notes/expired.md"),
+ same_project_link("notes/future.md"),
+ ],
+ ),
+ with_expiry(
+ page_with_links(
+ ws,
+ app,
+ "notes/expired_from.md",
+ vec![same_project_link("notes/live.md")],
+ ),
+ expired_at,
+ ),
+ ] {
+ store.writer.upsert_page(page).await.unwrap();
+ }
+
+ let graph = store.reader.project_link_graph(ws, app).await.unwrap();
+ let mut paths: Vec<&str> = graph.nodes.iter().map(|n| n.path.as_str()).collect();
+ paths.sort_unstable();
+ assert_eq!(
+ paths,
+ vec!["notes/future.md", "notes/hub.md", "notes/live.md"]
+ );
+ let mut pairs: Vec<(&str, &str)> = graph
+ .edges
+ .iter()
+ .map(|e| (e.from_path.as_str(), e.to_path.as_str()))
+ .collect();
+ pairs.sort_unstable();
+ assert_eq!(
+ pairs,
+ vec![
+ ("notes/hub.md", "notes/future.md"),
+ ("notes/hub.md", "notes/live.md"),
+ ]
+ );
+}
+
+#[tokio::test]
+async fn project_graph_caps_by_degree_then_recency() {
+ 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();
+
+ store
+ .writer
+ .upsert_page(page_with_links(ws, app, "notes/leaf.md", vec![]))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(page_with_links(
+ ws,
+ app,
+ "notes/hub.md",
+ vec![same_project_link("notes/leaf.md")],
+ ))
+ .await
+ .unwrap();
+
+ let isolated = PROJECT_LINK_GRAPH_MAX_NODES;
+ for i in 0..isolated {
+ store
+ .writer
+ .upsert_page(page_with_links(
+ ws,
+ app,
+ &format!("notes/iso-{i:03}.md"),
+ vec![],
+ ))
+ .await
+ .unwrap();
+ }
+
+ let graph = store.reader.project_link_graph(ws, app).await.unwrap();
+ assert!(graph.truncated);
+ assert_eq!(graph.nodes.len(), PROJECT_LINK_GRAPH_MAX_NODES);
+ let paths: Vec<&str> = graph.nodes.iter().map(|n| n.path.as_str()).collect();
+ assert!(
+ paths.contains(&"notes/hub.md") && paths.contains(&"notes/leaf.md"),
+ "linked pages outrank isolated ones: {paths:?}"
+ );
+ assert!(
+ graph
+ .edges
+ .iter()
+ .any(|e| e.from_path == "notes/hub.md" && e.to_path == "notes/leaf.md"),
+ "the kept edge must survive the cap: {:?}",
+ graph.edges
+ );
+}
diff --git a/crates/ai-memory-web/src/lib.rs b/crates/ai-memory-web/src/lib.rs
index 4159c741..09ca0f9c 100644
--- a/crates/ai-memory-web/src/lib.rs
+++ b/crates/ai-memory-web/src/lib.rs
@@ -9,7 +9,9 @@
//!
//! Routes (all under whatever prefix the host nests this router at):
//! - `GET /` → project list (cards)
+//! - `GET /graph` → cross-project link graph (SVG + table)
//! - `GET /w/:workspace/:project` → page tree + recent activity
+//! - `GET /w/:workspace/:project/graph` → in-project link graph (SVG + table)
//! - `GET /w/:workspace/:project/p/*path` → rendered markdown + metadata
//! - `GET /w/:workspace/:project/h/*path` → version history + unified diff
//! - `GET /w/:workspace/:project/s/:session` → session timeline, paged
diff --git a/crates/ai-memory-web/src/mount.rs b/crates/ai-memory-web/src/mount.rs
index 9e15e5b0..01e38f1c 100644
--- a/crates/ai-memory-web/src/mount.rs
+++ b/crates/ai-memory-web/src/mount.rs
@@ -1306,6 +1306,8 @@ mod tests {
let session_uri = format!("/web/w/default/scratch/s/{session}");
for uri in [
"/web",
+ "/web/graph",
+ "/web/w/default/scratch/graph",
"/web/pending",
"/web/login",
"/api/v1/projects",
diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rs
index bf2987cc..a343d886 100644
--- a/crates/ai-memory-web/src/routes/api.rs
+++ b/crates/ai-memory-web/src/routes/api.rs
@@ -75,6 +75,10 @@ pub(crate) fn build(state: Arc<WebState>) -> Router {
axum::routing::get(session_observations_handler),
)
.route("/graph", axum::routing::get(graph_handler))
+ .route(
+ "/workspaces/{workspace}/projects/{project}/graph",
+ axum::routing::get(project_graph_handler),
+ )
.with_state(state)
}
@@ -123,16 +127,36 @@ async fn workspaces_handler(
/// Cross-project dependency graph: every resolved link whose endpoints are
/// in different projects, each carrying both endpoints' workspace/project/
/// path. The UI builds nodes from the endpoints (and may aggregate to a
-/// project-level dependency graph). Global for now; project scoping is a
-/// follow-up query param. With authorization on, only edges whose both ends
+/// project-level dependency graph). Omit `workspace`/`project` for the
+/// whole graph; pass both to keep edges that touch that project. Partial
+/// scope is refused. With authorization on, only edges whose both ends
/// the viewer may read (#708).
async fn graph_handler(
State(state): State<Arc<WebState>>,
viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ Query(query): Query<GraphQuery>,
) -> Result<Response, Response> {
+ let viewer = viewer_of(viewer);
+ let scope = match (
+ trimmed_opt(query.workspace.as_deref()),
+ trimmed_opt(query.project.as_deref()),
+ ) {
+ (None, None) => None,
+ (Some(workspace), Some(project)) => {
+ let (workspace_id, project_id) =
+ lookup_project(&state, workspace, project, viewer).await?;
+ Some((workspace_id, project_id))
+ }
+ _ => {
+ return Err(json_error(
+ StatusCode::BAD_REQUEST,
+ "workspace and project must be provided together",
+ ));
+ }
+ };
let edges = state
.reader
- .cross_project_edges(None, viewer_of(viewer))
+ .cross_project_edges(scope, viewer)
.await
.map_err(internal_error)?;
Ok(with_cache(
@@ -141,6 +165,33 @@ async fn graph_handler(
))
}
+/// In-project link graph: latest unexpired pages and the resolved
+/// wikilinks among them. Same read grant as the project page list.
+async fn project_graph_handler(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ Path((workspace, project)): Path<(String, String)>,
+) -> Result<Response, Response> {
+ let (workspace_id, project_id) =
+ lookup_project(&state, &workspace, &project, viewer_of(viewer)).await?;
+ let graph = state
+ .reader
+ .project_link_graph(workspace_id, project_id)
+ .await
+ .map_err(internal_error)?;
+ Ok(with_cache(
+ Json(serde_json::json!({
+ "workspace": workspace,
+ "project": project,
+ "truncated": graph.truncated,
+ "nodes": graph.nodes,
+ "edges": graph.edges,
+ }))
+ .into_response(),
+ LIST_CACHE_MAX_AGE,
+ ))
+}
+
async fn projects_handler(
State(state): State<Arc<WebState>>,
viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
@@ -1358,6 +1409,14 @@ struct ProjectListQuery {
workspace: Option<String>,
}
+#[derive(Debug, Deserialize)]
+struct GraphQuery {
+ #[serde(default)]
+ workspace: Option<String>,
+ #[serde(default)]
+ project: Option<String>,
+}
+
#[derive(Debug)]
struct SearchQuery {
q: String,
diff --git a/crates/ai-memory-web/src/routes/graph.rs b/crates/ai-memory-web/src/routes/graph.rs
new file mode 100644
index 00000000..a4abfea0
--- /dev/null
+++ b/crates/ai-memory-web/src/routes/graph.rs
@@ -0,0 +1,303 @@
+//! Read-only wiki link graph pages.
+//!
+//! `GET /graph` draws resolved wikilinks whose endpoints sit in different
+//! projects. `GET /w/:workspace/:project/graph` draws the latest unexpired
+//! pages in that project and the resolved same-project links among them.
+//! Both answers are HTML: a circular SVG plus a table, with no JavaScript.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::sync::Arc;
+
+use askama::Template;
+use axum::extract::{Path, State};
+use axum::http::StatusCode;
+use axum::response::{Html, IntoResponse, Response};
+
+use ai_memory_store::{CrossProjectEdge, LinkGraph, PROJECT_LINK_GRAPH_MAX_NODES};
+
+use crate::state::WebState;
+use crate::templates::{
+ GraphEdgeRow, GraphSvgEdge, GraphSvgNode, GraphView, graph_href, page_href, project_href,
+};
+
+/// Pixel centre of the SVG viewBox.
+const SVG_CX: f64 = 400.0;
+/// Pixel centre of the SVG viewBox.
+const SVG_CY: f64 = 400.0;
+/// Radius of the node circle.
+const SVG_RADIUS: f64 = 300.0;
+/// Characters kept in an SVG node label before an ellipsis.
+const SVG_LABEL_CHARS: usize = 24;
+
+/// Handler for `GET /graph`.
+pub(crate) async fn global_handler(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+) -> Response {
+ let viewer_id = viewer.map(|axum::Extension(viewer)| viewer.user());
+ match render_global(&state, viewer_id).await {
+ Ok(html) => html.into_response(),
+ Err(status) => status.into_response(),
+ }
+}
+
+/// Handler for `GET /w/:workspace/:project/graph`.
+pub(crate) async fn project_handler(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ Path((workspace, project)): Path<(String, String)>,
+) -> Response {
+ let viewer_id = viewer.as_ref().map(|axum::Extension(viewer)| viewer.user());
+ let scope = match super::resolve_read_scope(&state, viewer_id, &workspace, &project).await {
+ Ok(scope) => scope,
+ Err(refusal) => return super::page::refusal_response(&refusal),
+ };
+ let graph = match state
+ .reader
+ .project_link_graph(scope.workspace_id, scope.project_id)
+ .await
+ {
+ Ok(graph) => graph,
+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ };
+ match render_project(&workspace, &project, graph) {
+ Ok(html) => html.into_response(),
+ Err(status) => status.into_response(),
+ }
+}
+
+async fn render_global(
+ state: &WebState,
+ viewer: Option<ai_memory_core::UserId>,
+) -> Result<Html<String>, StatusCode> {
+ let edges = state
+ .reader
+ .cross_project_edges(None, viewer)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ let (svg_nodes, svg_edges, rows) = aggregate_projects(&edges);
+ GraphView {
+ is_project: false,
+ workspace: String::new(),
+ project: String::new(),
+ project_href: String::new(),
+ heading: "Link graph".into(),
+ blurb: "Resolved wikilinks whose endpoints sit in different projects. \
+ An edge is shown only when both ends are readable."
+ .into(),
+ empty_message: "No cross-project links yet.".into(),
+ truncated: false,
+ shown: svg_nodes.len(),
+ node_cap: 0,
+ svg_nodes,
+ svg_edges,
+ rows,
+ }
+ .render()
+ .map(Html)
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+}
+
+fn render_project(
+ workspace: &str,
+ project: &str,
+ graph: LinkGraph,
+) -> Result<Html<String>, StatusCode> {
+ let (svg_nodes, svg_edges) = layout_pages(workspace, project, &graph);
+ let rows = graph
+ .edges
+ .iter()
+ .map(|edge| GraphEdgeRow {
+ from_href: page_href(workspace, project, &edge.from_path),
+ from_label: edge.from_path.clone(),
+ to_href: page_href(workspace, project, &edge.to_path),
+ to_label: edge.to_path.clone(),
+ })
+ .collect();
+ GraphView {
+ is_project: true,
+ workspace: workspace.to_owned(),
+ project: project.to_owned(),
+ project_href: project_href(workspace, project),
+ heading: format!("{workspace}/{project} link graph"),
+ blurb: "Latest pages in this project and the resolved wikilinks between them.".into(),
+ empty_message: "No pages in this project yet.".into(),
+ truncated: graph.truncated,
+ shown: graph.nodes.len(),
+ node_cap: PROJECT_LINK_GRAPH_MAX_NODES,
+ svg_nodes,
+ svg_edges,
+ rows,
+ }
+ .render()
+ .map(Html)
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+}
+
+fn aggregate_projects(
+ edges: &[CrossProjectEdge],
+) -> (Vec<GraphSvgNode>, Vec<GraphSvgEdge>, Vec<GraphEdgeRow>) {
+ let mut projects: BTreeSet<(String, String)> = BTreeSet::new();
+ for edge in edges {
+ projects.insert((edge.from_workspace.clone(), edge.from_project.clone()));
+ projects.insert((edge.to_workspace.clone(), edge.to_project.clone()));
+ }
+ let list: Vec<(String, String)> = projects.into_iter().collect();
+ let coords = circular_layout(list.len(), SVG_CX, SVG_CY, SVG_RADIUS);
+ let mut index: BTreeMap<(String, String), usize> = BTreeMap::new();
+ let svg_nodes: Vec<GraphSvgNode> = list
+ .iter()
+ .enumerate()
+ .map(|(i, (workspace, project))| {
+ index.insert((workspace.clone(), project.clone()), i);
+ let (x, y) = coords[i];
+ let full = format!("{workspace}/{project}");
+ GraphSvgNode {
+ href: graph_href(workspace, project),
+ tooltip: full.clone(),
+ label: truncate_label(&full, SVG_LABEL_CHARS),
+ x: x.round() as i32,
+ y: y.round() as i32,
+ label_y: (y + 22.0).round() as i32,
+ }
+ })
+ .collect();
+
+ let mut drawn: BTreeSet<(usize, usize)> = BTreeSet::new();
+ let mut svg_edges = Vec::new();
+ for edge in edges {
+ let Some(&from) = index.get(&(edge.from_workspace.clone(), edge.from_project.clone()))
+ else {
+ continue;
+ };
+ let Some(&to) = index.get(&(edge.to_workspace.clone(), edge.to_project.clone())) else {
+ continue;
+ };
+ let pair = if from <= to { (from, to) } else { (to, from) };
+ if from != to && drawn.insert(pair) {
+ svg_edges.push(svg_line(&coords[from], &coords[to]));
+ }
+ }
+
+ let rows = edges
+ .iter()
+ .map(|edge| GraphEdgeRow {
+ from_href: page_href(&edge.from_workspace, &edge.from_project, &edge.from_path),
+ from_label: format!(
+ "{}/{}:{}",
+ edge.from_workspace, edge.from_project, edge.from_path
+ ),
+ to_href: page_href(&edge.to_workspace, &edge.to_project, &edge.to_path),
+ to_label: format!("{}/{}:{}", edge.to_workspace, edge.to_project, edge.to_path),
+ })
+ .collect();
+ (svg_nodes, svg_edges, rows)
+}
+
+fn layout_pages(
+ workspace: &str,
+ project: &str,
+ graph: &LinkGraph,
+) -> (Vec<GraphSvgNode>, Vec<GraphSvgEdge>) {
+ let coords = circular_layout(graph.nodes.len(), SVG_CX, SVG_CY, SVG_RADIUS);
+ let mut index: BTreeMap<&str, usize> = BTreeMap::new();
+ let svg_nodes: Vec<GraphSvgNode> = graph
+ .nodes
+ .iter()
+ .enumerate()
+ .map(|(i, node)| {
+ index.insert(node.path.as_str(), i);
+ let (x, y) = coords[i];
+ GraphSvgNode {
+ href: page_href(workspace, project, &node.path),
+ tooltip: node.title.clone(),
+ label: truncate_label(&node.title, SVG_LABEL_CHARS),
+ x: x.round() as i32,
+ y: y.round() as i32,
+ label_y: (y + 22.0).round() as i32,
+ }
+ })
+ .collect();
+ let svg_edges = graph
+ .edges
+ .iter()
+ .filter_map(|edge| {
+ let from = *index.get(edge.from_path.as_str())?;
+ let to = *index.get(edge.to_path.as_str())?;
+ if from == to {
+ return None;
+ }
+ Some(svg_line(&coords[from], &coords[to]))
+ })
+ .collect();
+ (svg_nodes, svg_edges)
+}
+
+fn svg_line(from: &(f64, f64), to: &(f64, f64)) -> GraphSvgEdge {
+ GraphSvgEdge {
+ x1: from.0.round() as i32,
+ y1: from.1.round() as i32,
+ x2: to.0.round() as i32,
+ y2: to.1.round() as i32,
+ }
+}
+
+/// Place `n` points evenly around a circle, starting at the top.
+#[must_use]
+pub(crate) fn circular_layout(n: usize, cx: f64, cy: f64, radius: f64) -> Vec<(f64, f64)> {
+ match n {
+ 0 => Vec::new(),
+ 1 => vec![(cx, cy)],
+ _ => (0..n)
+ .map(|i| {
+ let angle =
+ std::f64::consts::TAU * (i as f64) / (n as f64) - std::f64::consts::FRAC_PI_2;
+ (cx + radius * angle.cos(), cy + radius * angle.sin())
+ })
+ .collect(),
+ }
+}
+
+fn truncate_label(text: &str, max_chars: usize) -> String {
+ let mut chars = text.chars();
+ let taken: String = chars.by_ref().take(max_chars).collect();
+ if chars.next().is_some() {
+ format!("{taken}…")
+ } else {
+ taken
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn circular_layout_is_empty_for_zero_and_centred_for_one() {
+ assert!(circular_layout(0, 400.0, 400.0, 300.0).is_empty());
+ assert_eq!(
+ circular_layout(1, 400.0, 400.0, 300.0),
+ vec![(400.0, 400.0)]
+ );
+ }
+
+ #[test]
+ fn circular_layout_starts_at_the_top() {
+ let pts = circular_layout(4, 0.0, 0.0, 10.0);
+ assert_eq!(pts.len(), 4);
+ assert!((pts[0].0 - 0.0).abs() < 1e-9);
+ assert!((pts[0].1 + 10.0).abs() < 1e-9);
+ }
+
+ #[test]
+ fn truncate_label_keeps_short_text_and_ellipsises_long() {
+ assert_eq!(truncate_label("short", 24), "short");
+ assert_eq!(
+ truncate_label("abcdefghijklmnopqrstuvwxyz", 24)
+ .chars()
+ .count(),
+ 25
+ );
+ assert!(truncate_label("abcdefghijklmnopqrstuvwxyz", 24).ends_with('…'));
+ }
+}
diff --git a/crates/ai-memory-web/src/routes/mod.rs b/crates/ai-memory-web/src/routes/mod.rs
index 9bce2bfd..3c469fc4 100644
--- a/crates/ai-memory-web/src/routes/mod.rs
+++ b/crates/ai-memory-web/src/routes/mod.rs
@@ -9,6 +9,7 @@ use crate::html_auth::HtmlAuthRedirectConfig;
use crate::state::WebState;
mod api;
+mod graph;
mod health;
mod history;
mod index;
@@ -112,7 +113,12 @@ pub(crate) async fn require_admin(
pub(crate) fn build(state: Arc<WebState>) -> Router {
Router::new()
.route("/", get(index::handler))
+ .route("/graph", get(graph::global_handler))
.route("/w/{workspace}/{project}", get(project::handler))
+ .route(
+ "/w/{workspace}/{project}/graph",
+ get(graph::project_handler),
+ )
.route("/w/{workspace}/{project}/p/{*path}", get(page::handler))
.route("/w/{workspace}/{project}/h/{*path}", get(history::handler))
.route(
diff --git a/crates/ai-memory-web/src/routes/project.rs b/crates/ai-memory-web/src/routes/project.rs
index 2fbf8ab3..a85f3b36 100644
--- a/crates/ai-memory-web/src/routes/project.rs
+++ b/crates/ai-memory-web/src/routes/project.rs
@@ -133,6 +133,7 @@ async fn render(
.collect();
let mailbox_capped = mailbox_total > mailbox.len() as u64;
+ let graph_href = crate::templates::graph_href(&workspace, &project);
let html = ProjectView {
workspace,
project,
@@ -143,6 +144,7 @@ async fn render(
mailbox_total,
mailbox_capped,
sessions,
+ graph_href,
}
.render()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
diff --git a/crates/ai-memory-web/src/templates.rs b/crates/ai-memory-web/src/templates.rs
index 9fa37be0..df7c14b4 100644
--- a/crates/ai-memory-web/src/templates.rs
+++ b/crates/ai-memory-web/src/templates.rs
@@ -56,6 +56,12 @@ pub(crate) fn session_href(workspace: &str, project: &str, session_id: &str) ->
)
}
+/// Build a project link-graph URL (`w/{ws}/{proj}/graph`), percent-encoded.
+#[must_use]
+pub(crate) fn graph_href(workspace: &str, project: &str) -> String {
+ format!("{}/graph", project_href(workspace, project))
+}
+
/// The last eight characters of a UUID, for display. The ids here are
/// UUIDv7, whose leading characters are a shared timestamp prefix.
#[must_use]
@@ -261,6 +267,8 @@ pub(crate) struct ProjectView {
pub mailbox_capped: bool,
/// The project's most recent sessions the viewer may see.
pub sessions: Vec<SessionRow>,
+ /// Link to this project's link graph.
+ pub graph_href: String,
}
/// One recent session on the project page.
@@ -822,6 +830,78 @@ pub(crate) struct HealthSection {
pub rows: Vec<HealthRow>,
}
+/// One node in the server-rendered SVG link graph.
+pub(crate) struct GraphSvgNode {
+ /// Target for the node (`w/…` or `w/…/p/…`).
+ pub href: String,
+ /// Full label for the SVG tooltip.
+ pub tooltip: String,
+ /// Truncated label drawn next to the node.
+ pub label: String,
+ /// Circle centre x, in viewBox pixels.
+ pub x: i32,
+ /// Circle centre y, in viewBox pixels.
+ pub y: i32,
+ /// Baseline y of the label.
+ pub label_y: i32,
+}
+
+/// One SVG line between two graph nodes.
+pub(crate) struct GraphSvgEdge {
+ /// Start x.
+ pub x1: i32,
+ /// Start y.
+ pub y1: i32,
+ /// End x.
+ pub x2: i32,
+ /// End y.
+ pub y2: i32,
+}
+
+/// One row of the graph's accessible edge table.
+pub(crate) struct GraphEdgeRow {
+ /// Link to the source page.
+ pub from_href: String,
+ /// Source label (path, or `workspace/project:path`).
+ pub from_label: String,
+ /// Link to the target page.
+ pub to_href: String,
+ /// Target label.
+ pub to_label: String,
+}
+
+/// View-model for `GET /graph` and `GET /w/:workspace/:project/graph`.
+#[derive(Template)]
+#[template(path = "graph.html")]
+pub(crate) struct GraphView {
+ /// Project graph (scoped header search and breadcrumb) vs the global one.
+ pub is_project: bool,
+ /// Workspace name; empty on the global graph.
+ pub workspace: String,
+ /// Project name; empty on the global graph.
+ pub project: String,
+ /// Link back to the project overview; empty on the global graph.
+ pub project_href: String,
+ /// Page heading.
+ pub heading: String,
+ /// One-line explanation under the heading.
+ pub blurb: String,
+ /// Empty-state copy when there are no nodes.
+ pub empty_message: String,
+ /// The node cap dropped some pages.
+ pub truncated: bool,
+ /// Nodes actually drawn.
+ pub shown: usize,
+ /// Cap shown in the truncation notice.
+ pub node_cap: usize,
+ /// SVG nodes.
+ pub svg_nodes: Vec<GraphSvgNode>,
+ /// SVG edges.
+ pub svg_edges: Vec<GraphSvgEdge>,
+ /// Accessible edge table.
+ pub rows: Vec<GraphEdgeRow>,
+}
+
/// View-model for the root-only `GET /health`.
#[derive(Template)]
#[template(path = "health.html")]
@@ -911,5 +991,9 @@ mod tests {
page_href("default", "scratch", "notes/a b%25.md"),
"w/default/scratch/p/notes/a%20b%2525.md"
);
+ assert_eq!(
+ graph_href("default space", "proj#one"),
+ "w/default%20space/proj%23one/graph"
+ );
}
}
diff --git a/crates/ai-memory-web/templates/base.html b/crates/ai-memory-web/templates/base.html
index 53fdaa6b..95025a31 100644
--- a/crates/ai-memory-web/templates/base.html
+++ b/crates/ai-memory-web/templates/base.html
@@ -38,6 +38,7 @@
>
</form>
{% endblock %}
+ <a href="graph" class="text-sm font-medium text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">Graph</a>
<a href="pending" class="text-sm font-medium text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">Pending</a>
<a href="health" class="text-sm font-medium text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">Health</a>
<button
diff --git a/crates/ai-memory-web/templates/graph.html b/crates/ai-memory-web/templates/graph.html
new file mode 100644
index 00000000..67b6340e
--- /dev/null
+++ b/crates/ai-memory-web/templates/graph.html
@@ -0,0 +1,91 @@
+{% extends "base.html" %}
+
+{% block title %}{% if is_project %}{{ workspace }}/{{ project }} graph — ai-memory{% else %}Link graph — ai-memory{% endif %}{% endblock %}
+
+{% block header_search %}
+{% if is_project %}
+{% include "_header_search_scoped.html" %}
+{% else %}
+<form action="search" method="get" class="flex items-center gap-2">
+ <label for="header-search" class="sr-only">Search pages</label>
+ <input
+ id="header-search"
+ name="q"
+ type="search"
+ placeholder="Search…"
+ class="w-40 sm:w-64 rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-1.5 text-sm placeholder-slate-500 dark:placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
+ >
+</form>
+{% endif %}
+{% endblock %}
+
+{% block content %}
+{% if is_project %}
+<nav aria-label="Breadcrumb" class="mb-6 flex items-center gap-1 text-sm text-slate-500 dark:text-slate-400">
+ <a href="." class="hover:text-blue-600 dark:hover:text-blue-400">home</a>
+ <span aria-hidden="true">/</span>
+ <span class="text-slate-500 dark:text-slate-400">{{ workspace }}</span>
+ <span aria-hidden="true">/</span>
+ <a href="{{ project_href }}" class="hover:text-blue-600 dark:hover:text-blue-400">{{ project }}</a>
+ <span aria-hidden="true">/</span>
+ <span aria-current="page" class="text-slate-700 dark:text-slate-200 font-medium">graph</span>
+</nav>
+{% else %}
+<nav aria-label="Breadcrumb" class="mb-6 flex items-center gap-1 text-sm text-slate-500 dark:text-slate-400">
+ <a href="." class="hover:text-blue-600 dark:hover:text-blue-400">home</a>
+ <span aria-hidden="true">/</span>
+ <span aria-current="page" class="text-slate-700 dark:text-slate-200 font-medium">graph</span>
+</nav>
+{% endif %}
+
+<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-2">{{ heading }}</h1>
+<p class="text-sm text-slate-500 dark:text-slate-400 mb-6">{{ blurb }}</p>
+
+{% if truncated %}
+<p class="mb-6 rounded-md border border-amber-200 dark:border-amber-900/50 bg-amber-50 dark:bg-amber-950/30 px-4 py-3 text-sm text-amber-900 dark:text-amber-200">Showing the {{ shown }} pages with the most same-project neighbours (cap {{ node_cap }}). The rest stay on the project page.</p>
+{% endif %}
+
+{% if svg_nodes.is_empty() %}
+<p class="text-sm text-slate-500 dark:text-slate-400">{{ empty_message }}</p>
+{% else %}
+<svg viewBox="0 0 800 800" class="w-full max-w-3xl mx-auto mb-10 text-slate-700 dark:text-slate-200" role="img" aria-labelledby="graph-heading">
+ <title id="graph-heading">{{ heading }}</title>
+ {% for edge in svg_edges %}
+ <line x1="{{ edge.x1 }}" y1="{{ edge.y1 }}" x2="{{ edge.x2 }}" y2="{{ edge.y2 }}" stroke="currentColor" stroke-opacity="0.35" stroke-width="1.5" />
+ {% endfor %}
+ {% for node in svg_nodes %}
+ <a href="{{ node.href }}">
+ <g>
+ <title>{{ node.tooltip }}</title>
+ <circle cx="{{ node.x }}" cy="{{ node.y }}" r="12" fill="#2563eb" />
+ <text x="{{ node.x }}" y="{{ node.label_y }}" text-anchor="middle" font-size="11" fill="currentColor">{{ node.label }}</text>
+ </g>
+ </a>
+ {% endfor %}
+</svg>
+{% endif %}
+
+<h2 class="text-xs font-semibold uppercase tracking-wide text-slate-500 dark:text-slate-400 mb-3">Edges</h2>
+{% if rows.is_empty() %}
+<p class="text-sm text-slate-500 dark:text-slate-400">No resolved links to list.</p>
+{% else %}
+<div class="overflow-x-auto">
+ <table class="min-w-full text-sm">
+ <thead>
+ <tr class="text-left text-xs uppercase tracking-wide text-slate-500 dark:text-slate-400">
+ <th class="py-2 pr-4 font-semibold">From</th>
+ <th class="py-2 font-semibold">To</th>
+ </tr>
+ </thead>
+ <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
+ {% for row in rows %}
+ <tr>
+ <td class="py-2 pr-4"><a href="{{ row.from_href }}" class="text-slate-800 dark:text-slate-100 hover:text-blue-600 dark:hover:text-blue-400">{{ row.from_label }}</a></td>
+ <td class="py-2"><a href="{{ row.to_href }}" class="text-slate-800 dark:text-slate-100 hover:text-blue-600 dark:hover:text-blue-400">{{ row.to_label }}</a></td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+</div>
+{% endif %}
+{% endblock %}
diff --git a/crates/ai-memory-web/templates/project.html b/crates/ai-memory-web/templates/project.html
index 03476b20..b34b425d 100644
--- a/crates/ai-memory-web/templates/project.html
+++ b/crates/ai-memory-web/templates/project.html
@@ -13,7 +13,8 @@
<span aria-current="page" class="text-slate-700 dark:text-slate-200 font-medium">{{ project }}</span>
</nav>
-<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-6">{{ workspace }}/{{ project }}</h1>
+<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-2">{{ workspace }}/{{ project }}</h1>
+<p class="mb-6"><a href="{{ graph_href }}" class="text-sm font-medium text-blue-600 dark:text-blue-400 hover:underline">Link graph</a></p>
<form action="search" method="get" class="mb-8 flex flex-wrap items-center gap-2" aria-label="Search this project">
<input type="hidden" name="workspace" value="{{ workspace }}">
diff --git a/crates/ai-memory-web/templates/projects.html b/crates/ai-memory-web/templates/projects.html
index 3d834446..dd2fdb08 100644
--- a/crates/ai-memory-web/templates/projects.html
+++ b/crates/ai-memory-web/templates/projects.html
@@ -5,7 +5,7 @@
{% block content %}
<div class="mb-6">
<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100">Projects</h1>
- <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">All workspaces and projects in your wiki.</p>
+ <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">All workspaces and projects in your wiki. <a href="graph" class="font-medium text-blue-600 dark:text-blue-400 hover:underline">Link graph</a></p>
</div>
{% if mail_total > 0 %}
diff --git a/crates/ai-memory-web/tests/suite/graph.rs b/crates/ai-memory-web/tests/suite/graph.rs
new file mode 100644
index 00000000..d43f0068
--- /dev/null
+++ b/crates/ai-memory-web/tests/suite/graph.rs
@@ -0,0 +1,219 @@
+//! Built-in `/web/graph` pages and the in-project `/api/v1/.../graph` JSON.
+
+use ai_memory_core::{NewPage, PagePath, Tier};
+use ai_memory_store::Store;
+use ai_memory_web::{api_router, router};
+use ai_memory_wiki::Wiki;
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+async fn setup() -> (TempDir, Store, Wiki) {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ (tmp, store, wiki)
+}
+
+fn page_with_links(
+ ws: ai_memory_core::WorkspaceId,
+ proj: ai_memory_core::ProjectId,
+ path: &str,
+ title: &str,
+ links: Vec<ai_memory_core::LinkTarget>,
+) -> NewPage {
+ NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new(path).unwrap(),
+ title: title.to_owned(),
+ body: "body".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({"kind": "fact"}),
+ 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,
+ }
+}
+
+async fn get(app: axum::Router, uri: &str) -> (StatusCode, String) {
+ let resp = app
+ .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+ let status = resp.status();
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (status, String::from_utf8(body.to_vec()).unwrap())
+}
+
+#[tokio::test]
+async fn graph_pages_render_svg_and_edge_table() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let app = store
+ .writer
+ .get_or_create_project(ws, "app", None)
+ .await
+ .unwrap();
+ let lib = store
+ .writer
+ .get_or_create_project(ws, "lib", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(page_with_links(ws, lib, "notes/x.md", "Lib note", vec![]))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(page_with_links(ws, app, "notes/b.md", "B", vec![]))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(page_with_links(
+ ws,
+ app,
+ "notes/a.md",
+ "A",
+ vec![
+ same_project_link("notes/b.md"),
+ cross_project_link("lib", "notes/x.md"),
+ ],
+ ))
+ .await
+ .unwrap();
+
+ let web = router(store.reader.clone(), wiki.clone());
+ let api = api_router(store.reader.clone(), wiki);
+
+ let (status, home) = get(web.clone(), "/").await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(home.contains(r#"href="graph""#), "{home}");
+ assert!(home.contains("Link graph"), "{home}");
+
+ let (status, project) = get(web.clone(), "/w/default/app").await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(project.contains("w/default/app/graph"), "{project}");
+
+ let (status, html) = get(web.clone(), "/graph").await;
+ assert_eq!(status, StatusCode::OK, "{html}");
+ assert!(html.contains("<svg"), "{html}");
+ assert!(html.contains("default/lib:notes/x.md"), "{html}");
+ assert!(html.contains("default/app:notes/a.md"), "{html}");
+ assert!(html.contains("w/default/lib/graph"), "{html}");
+
+ let (status, html) = get(web.clone(), "/w/default/app/graph").await;
+ assert_eq!(status, StatusCode::OK, "{html}");
+ assert!(html.contains("<svg"), "{html}");
+ assert!(html.contains("notes/a.md"), "{html}");
+ assert!(html.contains("notes/b.md"), "{html}");
+ assert!(
+ !html.contains("notes/x.md"),
+ "in-project graph must omit the cross-project target: {html}"
+ );
+ assert!(html.contains("w/default/app/p/notes/a.md"), "{html}");
+
+ let (status, body) = get(api.clone(), "/graph").await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(body.contains("notes/x.md"), "{body}");
+
+ let (status, body) = get(api, "/workspaces/default/projects/app/graph").await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let json: serde_json::Value = serde_json::from_str(&body).unwrap();
+ assert_eq!(json["workspace"], "default");
+ assert_eq!(json["project"], "app");
+ assert_eq!(json["truncated"], false);
+ let paths: Vec<&str> = json["nodes"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|n| n["path"].as_str().unwrap())
+ .collect();
+ assert!(
+ paths.contains(&"notes/a.md") && paths.contains(&"notes/b.md"),
+ "{body}"
+ );
+ assert!(!paths.contains(&"notes/x.md"), "{body}");
+ assert_eq!(json["edges"][0]["from_path"], "notes/a.md");
+ assert_eq!(json["edges"][0]["to_path"], "notes/b.md");
+}
+
+#[tokio::test]
+async fn graph_page_renders_hostile_titles_inert() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "app", None)
+ .await
+ .unwrap();
+ let title = "<script>alert('title')</script>";
+ store
+ .writer
+ .upsert_page(page_with_links(ws, proj, "notes/a.md", title, vec![]))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(page_with_links(
+ ws,
+ proj,
+ "notes/b.md",
+ "\"><img src=x onerror=alert(1)>",
+ vec![same_project_link("notes/a.md")],
+ ))
+ .await
+ .unwrap();
+
+ let web = router(store.reader, wiki);
+ let (status, html) = get(web, "/w/default/app/graph").await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(!html.contains("<script>alert("), "{html}");
+ assert!(!html.contains("<img src=x"), "{html}");
+ assert!(html.contains("&lt;script&gt;alert("), "{html}");
+}
+
+#[tokio::test]
+async fn project_graph_unknown_project_is_not_found() {
+ let (_tmp, store, wiki) = setup().await;
+ let web = router(store.reader.clone(), wiki.clone());
+ let api = api_router(store.reader, wiki);
+ let (status, body) = get(web, "/w/default/missing/graph").await;
+ assert_eq!(status, StatusCode::NOT_FOUND, "{body}");
+ let (status, body) = get(api, "/workspaces/default/projects/missing/graph").await;
+ assert_eq!(status, StatusCode::NOT_FOUND, "{body}");
+}
diff --git a/crates/ai-memory-web/tests/suite/mod.rs b/crates/ai-memory-web/tests/suite/mod.rs
index 473278fe..c2f182c6 100644
--- a/crates/ai-memory-web/tests/suite/mod.rs
+++ b/crates/ai-memory-web/tests/suite/mod.rs
@@ -2,6 +2,7 @@
//! test harness (see the `integration` module in `src/lib.rs`), so they cost
//! no extra binary; a new file must be declared below.
+mod graph;
mod health;
mod history_replay;
mod pending;
diff --git a/crates/ai-memory-web/tests/suite/routes.rs b/crates/ai-memory-web/tests/suite/routes.rs
index 3fb9c372..9f098750 100644
--- a/crates/ai-memory-web/tests/suite/routes.rs
+++ b/crates/ai-memory-web/tests/suite/routes.rs
@@ -4076,6 +4076,83 @@ async fn metadata_shows_only_what_the_viewer_may_read() {
);
}
+ // The HTML graph and the in-project graph use the same both-ends-readable
+ // rule. A scoped `/graph?workspace=&project=` call is not a way to see
+ // the far end of an edge the viewer cannot read.
+ for viewer in [Some(alice), Some(bob)] {
+ let (status, body) = get(web.clone(), "/graph", viewer).await;
+ assert_eq!(status, StatusCode::OK, "{viewer:?}");
+ assert!(
+ !shows(&body, "alpha-plan"),
+ "{viewer:?} sees the HTML edge: {body}"
+ );
+ assert!(
+ !shows(&body, "beta-plan"),
+ "{viewer:?} sees the HTML edge: {body}"
+ );
+ assert!(
+ !shows(&body, "client-work"),
+ "{viewer:?} HTML graph leaked client-work: {body}"
+ );
+ }
+ for viewer in [Some(carol), None] {
+ let (status, body) = get(web.clone(), "/graph", viewer).await;
+ assert_eq!(status, StatusCode::OK, "{viewer:?}");
+ assert!(
+ shows(&body, "beta-plan") && shows(&body, "alpha-plan"),
+ "{viewer:?} lost the HTML edge: {body}"
+ );
+ }
+
+ let (status, body) = get(web.clone(), "/w/shared/alpha/graph", Some(bob)).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
+ assert!(
+ !shows(&body, "alpha-plan"),
+ "bob's 403 leaked alpha: {body}"
+ );
+ let (status, body) = get(
+ api.clone(),
+ "/workspaces/shared/projects/alpha/graph",
+ Some(bob),
+ )
+ .await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
+ assert!(!shows(&body, "alpha-plan"), "{body}");
+
+ let (status, body) = get(web.clone(), "/w/shared/beta/graph", Some(bob)).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(shows(&body, "beta-plan"), "{body}");
+ assert!(
+ !shows(&body, "alpha-plan"),
+ "bob's project graph leaked alpha: {body}"
+ );
+
+ let (status, body) = get(
+ api.clone(),
+ "/graph?workspace=shared&project=beta",
+ Some(bob),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(
+ !shows(&body, "alpha-plan") && !shows(&body, "beta-plan"),
+ "bob scoped graph leaked the hidden far end: {body}"
+ );
+ let (status, body) = get(
+ api.clone(),
+ "/graph?workspace=shared&project=beta",
+ Some(carol),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(
+ shows(&body, "beta-plan") && shows(&body, "alpha-plan"),
+ "carol lost a scoped edge she can read: {body}"
+ );
+ let (status, body) = get(api.clone(), "/graph?workspace=shared", None).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
+ assert!(shows(&body, "together"), "{body}");
+
// A page's link panel is the same edge seen from one page. The panel,
// not the body: beta's own text names the link, and that text is bob's to
// read. What must not appear is the resolved far end — alpha's title,
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 5d905077..151914c7 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -1525,7 +1525,9 @@ the server URL is loopback and no `default` server profile is registered.
* **Richer read surfaces for the web UI.** The multi-workspace read-only
wiki browser shipped in `ai-memory-web` (`/web`: project list, page
tree, page view, page history with a server-side unified diff, a paged
- session timeline, project search through `memory_query`'s hybrid ranker
+ session timeline, a server-rendered link graph at `/web/graph` and
+ `/web/w/<workspace>/<project>/graph`, project search through
+ `memory_query`'s hybrid ranker
with a recall trace, the root-only `/web/health` panel, and the root-only
`/web/pending` triage page,
whose approve and reject buttons post to the existing
@@ -1538,8 +1540,8 @@ the server URL is loopback and no `default` server profile is registered.
a concurrent write replaced stays visible (invariant #16). TTL expiry still
applies: an expired version is neither listed nor readable by id, and a page
whose live version expired shows no history, since the forget sweep deletes
- every row at its path. Better *reading*
- (graph exploration) is open. See
+ every row at its path. The link graph is a circular SVG plus an edge table;
+ larger layouts and interactive clustering remain open. See
[`docs/frontend-api.md`](frontend-api.md#10-known-gaps-and-deliberate-non-goals).
* **Retrieval measurement gaps.** The LongMemEval-S harness ships in
`evals/` (pipeline, component and decomposition modes; results in
diff --git a/docs/frontend-api.md b/docs/frontend-api.md
index 092caeee..338cda61 100644
--- a/docs/frontend-api.md
+++ b/docs/frontend-api.md
@@ -11,7 +11,7 @@
| | What you can do | What you can't do |
|---|---|---|
-| `/api/v1/*` | Browse workspaces, projects, pages; read full page markdown + frontmatter + back-links; list a page's stored versions and diff two of them; search (global FTS5, or scoped through `memory_query`'s hybrid ranker, single or multi-project); aggregate "overview" snapshots; drill into stale / duplicate / orphan pages; list a project's sessions and read one session's raw observations. | Write, delete, rename, lint, consolidate, run sweeps, manage handoffs. The `/api/v1` surface is **read-only by construction**: the handlers contain zero writer calls, and `crates/ai-memory-web/clippy.toml` forbids the `Wiki` write and destructive methods anywhere in the crate, so adding one fails `cargo clippy -D warnings`. Writes still go through `/admin/*` (used by the CLI) or MCP tools. |
+| `/api/v1/*` | Browse workspaces, projects, pages; read full page markdown + frontmatter + back-links; list a page's stored versions and diff two of them; search (global FTS5, or scoped through `memory_query`'s hybrid ranker, single or multi-project); read the cross-project and in-project link graphs; aggregate "overview" snapshots; drill into stale / duplicate / orphan pages; list a project's sessions and read one session's raw observations. | Write, delete, rename, lint, consolidate, run sweeps, manage handoffs. The `/api/v1` surface is **read-only by construction**: the handlers contain zero writer calls, and `crates/ai-memory-web/clippy.toml` forbids the `Wiki` write and destructive methods anywhere in the crate, so adding one fails `cargo clippy -D warnings`. Writes still go through `/admin/*` (used by the CLI) or MCP tools. |
| `--web-ui-dir` | Host any SPA at `/web` (or `--web-slug`), same-origin with the API, behind the same auth. The default built-in `/web` browser stays the fallback when the flag is absent. | Host the SPA on a *different* origin without a reverse proxy. Use same-origin hosting or configure CORS deliberately (see §9). |
## 2. Auth model
@@ -47,6 +47,9 @@ observations in capture order, a page at a time, through the same readers,
visibility rule and caps as §4.11 and §4.12; `offset`, `limit` clamped
`1..=200`, default `50`, and `at` to jump to the page holding a 1-based
position). Both follow the same per-project read rule as the page view.
+The builtin wiki also serves `GET {web_slug}/graph` (the HTML twin of
+§4.9: a circular SVG of projects plus a table of page-level edges) and
+`GET {web_slug}/w/{workspace}/{project}/graph` (the HTML twin of §4.9.1).
The builtin wiki also serves the root-only `GET {web_slug}/pending` page. It
lists pending auto-improvement proposals and posts approve and reject to the
existing `/admin/pending-writes/*` routes. A signed-in non-root user gets a
@@ -496,11 +499,17 @@ either response, `handoff` is `null` when no open handoff matches the scope:
```http
GET /api/v1/graph
+GET /api/v1/graph?workspace={workspace}&project={project}
```
Returns every resolved wikilink whose endpoints sit in different
projects, with both endpoints' workspace + project + path. Useful for
-rendering a project-level dependency view in the SPA.
+rendering a project-level dependency view in the SPA. Omit the query
+string for the whole graph. `workspace` and `project` must be provided
+together and keep only edges that touch that project; passing only one
+of them is `400`. An unknown or unreadable project is the same refusal
+as the other scoped routes (`404` / `403`). With authorization on, an
+edge still requires both ends to be readable.
```json
{
@@ -517,8 +526,32 @@ rendering a project-level dependency view in the SPA.
}
```
-Global today (no workspace / project filter); narrower query params
-are a follow-up.
+### 4.9.1 Project link graph
+
+```http
+GET /api/v1/workspaces/{workspace}/projects/{project}/graph
+```
+
+Latest unexpired pages in that project and the resolved same-project
+wikilinks among them. Cross-project and unresolved links are omitted.
+When the project has more than 120 live pages, the response keeps the
+pages with the most same-project neighbours and then the most recently
+updated, and sets `truncated` to `true`. The same per-project read rule
+as the page list applies.
+
+```json
+{
+ "workspace": "default",
+ "project": "ai-memory",
+ "truncated": false,
+ "nodes": [
+ { "path": "decisions/0014-storage.md", "title": "Storage", "degree": 2 }
+ ],
+ "edges": [
+ { "from_path": "concepts/wiki.md", "to_path": "decisions/0014-storage.md" }
+ ]
+}
+```
### 4.10 Browser tab icon
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index e8b7008d..b474c3ff 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -116,6 +116,7 @@ means the boundary is not built yet.
| 14e | `memory_write_page` session evidence cites only a session of the target project (#708) | `ai-memory-mcp/src/server.rs` `memory_write_page` — a `session_id` is accepted only when `require_session_in_scope` resolves the session (where its observations landed, else its session row, as `Consolidator::session_target` does) to the same `(workspace_id, project_id)` the write grant was checked against; unknown and foreign ids get one refusal, so the error is no existence oracle; `scope: "global"` with a `session_id` is refused; `refuse_pinned_page_overwrite` keeps a write that cites a session off a pinned page; only a write to `sessions/<id>.md` reconciles the session's queued SessionEnd job | `server.rs` `write_page_refuses_a_session_from_another_project` (a foreign and an unknown session refused, no evidence row written, the foreign job still queued; control: the project's own session accepted), `session_evidence_write_leaves_a_pinned_page_alone` (control: the same write without `session_id` edits the page), `session_evidence_on_another_path_leaves_the_job_queued`, `write_page_rejects_a_malformed_or_global_session_id` — each of the scope check, the pinned check and the session-page-only reconcile proven to fail its test when removed | STRONG |
| 14f | Consolidation apply path validates generated cross-scope body links and every typed relation against the store (#1218, #1353) | `ai-memory-consolidate/src/link_guard.rs` `unresolved_generated_links` keeps body and relation refusals separate. Every `[[project:path]]` / `[[workspace/project:path]]` / `[[_global:path]]` target in a proposed body is resolved with the no-create `lookup_existing_scope` and batch-checked via `reader.rs` `existing_latest_paths`; a missing workspace/project, ambiguous project name, or missing target de-links the body link. Every typed `relations:` target is checked too, including same-project targets; a local target is admitted only when it already exists or is another page in the same atomic batch. `prune_relations` drops malformed and unresolved entries. Same-project body links stay untouched by design. Wired into consolidation single/batch and bootstrap before writes; restricted cross-project probes reveal no paths | `consolidator.rs` `batch_delinks_invented_cross_scope_wikilinks`, `single_page_delinks_invented_cross_scope_wikilinks`, `single_page_drops_unresolved_cross_scope_relations`; `link_guard.rs` `same_project_relations_require_existing_or_same_batch_targets` (missing local relation refused, same-batch relation and dangling local body link controls), malformed and cross-scope prune tests; bootstrap cross-scope test; store `multi_session.rs` `existing_latest_paths_reports_exactly_the_live_paths`, `existing_latest_paths_reports_nothing_for_a_restricted_project` | STRONG |
| 14g | Web project search and its recall trace honour `memory_query`'s scope rules (#708) and never describe another project | `ai-memory-web/src/routes/search.rs` resolves `workspace`+`project` through `resolve_read_scope` (`lookup_existing_scope_guarded`, no-create, `ProjectAccess::Read`) before any ranking, and refuses partial scope; scoped `/api/v1/search` keeps `lookup_project` / `resolve_many_existing_scopes_guarded`; `ai-memory-web/src/recall.rs` ranks only the resolved scopes through `ReaderPool::hybrid_search_scopes`, whose streams and graph expansion are bound to each `(workspace_id, project_id)`; a search with no scope stays `search_pages_with_meta(.., viewer)` (readable repositories only) | `ai-memory-web` `tests/suite/recall_trace.rs` — `project_search_refuses_a_restricted_project_without_a_grant` (bob, with no grant, gets 403 from `/web/search` with and without `explain=1` and from scoped `/api/v1/search`, with no path, body text or trace in the response, and a `scopes` POST naming the restricted project next to an open one is refused; alice's grant and an unrestricted viewer are the controls), `project_search_fails_closed_on_unknown_and_partial_scope` (unknown project or workspace 404 with nothing created, partial scope 400), `explain_renders_stream_ranks_rrf_authority_and_timings` (a better-matching page in a sibling project never reaches the hits or the trace), `search_scope_selector_lists_only_readable_projects` (the search page's "Search in" selector lists only projects the viewer may read, and a hand-typed `scope=` for an ungranted project is a 403 that leaks nothing; controls: the granted reader and an unrestricted viewer; passing no viewer to `list_projects_with_stats` in the handler fails it), `routes.rs` `search_page_scope_selector_round_trips_and_rejects_malformed_values` (a malformed `scope` is a 400); `recall_trace.rs` `kind_filter_does_not_widen_what_a_viewer_can_read` (a `kind`/`tier` filter only narrows: bob gets no hits and a 403 on a scoped search; alice and an unrestricted viewer are the controls), `search_filters_a_project_by_kind_and_tier_keeping_rank_order` (survivors of a filter keep the unfiltered order), `reranker_is_shown_only_the_pages_the_filter_keeps` (a dropped page never reaches the reranker), `kind_and_tier_filters_hold_in_every_stream` (FTS, entity, vector, observation and both graph directions each filter in SQL; dropping any one stream's predicate fails it), `kind_filter_finds_a_rare_kind_the_unfiltered_page_ranks_out` and `cross_project_kind_filter_sees_past_the_candidate_window` (the filter sees past the candidate window in both modes); `ai-memory-mcp` `tests/suite/web_search_parity.rs` (same top-k order as `memory_query` from `/web` and `/api/v1`, with a deterministic embedder and with none, explain on and off, and merged `scopes`; controls show a web search without the embedder, or the old FTS-only scoped search, would fail it) | STRONG. Bite checks: passing no viewer to `resolve_read_scope` in the search handler, to `lookup_project` or to `resolve_scopes` in the API each fails the restricted-project test; dropping the query vector in `recall.rs` fails the embedder parity tests |
+| 14h | Wiki link graph pages and JSON show only readable projects (#708) | `ai-memory-web/src/routes/graph.rs` `global_handler` calls `ReaderPool::cross_project_edges(None, viewer)` so an edge needs both ends readable; `project_handler` resolves through `resolve_read_scope` (`lookup_existing_scope_guarded`, no-create, `ProjectAccess::Read`) then `project_link_graph`, which lists only that project's latest unexpired pages and same-project resolved edges; `api.rs` `graph_handler` accepts `workspace`+`project` together (partial scope 400) and passes the same viewer filter, and `project_graph_handler` uses `lookup_project` | `routes.rs` `metadata_shows_only_what_the_viewer_may_read` (HTML `/web/graph`, `/web/w/…/graph`, `/api/v1/…/graph`, and scoped `/api/v1/graph?workspace=&project=`: bob cannot see alpha or client-work, a 403 on alpha's graph leaks neither title nor path, a scoped graph hides an edge whose far end he cannot read; carol and no-viewer controls keep the edge; partial scope 400); store `project_link_graph.rs` hides expired pages and omits cross-project and unresolved links; `graph.rs` `graph_page_renders_hostile_titles_inert` | STRONG. Bite checks: passing no viewer to `cross_project_edges` in the HTML global handler, or resolving the project graph through unguarded `lookup_existing_scope`, fails the restricted-project assertions |
| 15 | Agent-archive restore path confinement, resource bounds, and consistency | `ai-memory-cli/src/commands/restore_agents.rs` stages only bounded regular UTF-8 entries; requires a one-to-one manifest/body/checksum/target mapping; allowlists destinations by scope; rejects symlinked descendants; writes each file atomically and rolls back earlier writes after a later failure. `backup_agents.rs` skips direct and directory-root source symlinks, bounds individual assets, and atomically replaces a private archive only after gzip completion | `backup_agents.rs` `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`, `restore_agents_requires_a_complete_one_to_one_manifest`, `restore_agents_rejects_oversized_entries_from_the_header`, `restore_agents_rejects_a_symlinked_destination_parent`, `backup_agents_does_not_follow_config_or_asset_root_symlinks`, and `failed_backup_leaves_the_previous_archive_intact`; `backup_and_restore_agents_round_trip` is the valid-path control; `restore_agents::tests::rollback_removes_new_files_and_restores_overwrites` covers recovery | STRONG |
| 16 | Relay queue identity, migration, and private filesystem state | `companions/ai-memory-relay/src/queue.rs` `Queue::open_inner` performs read-only identity preflight, rechecks under `IMMEDIATE`, commits schema and metadata together; `configure` checks the presence of user objects and rechecks `identity`/`schema_version` metadata on the same connection before every bounded BUSY/LOCKED retry; `fsguard.rs` checks existing paths and creates owner-only files before SQLite opens them | `tests/relay.rs` `a_foreign_database_is_refused_byte_for_byte`, `unknown_schemas_refuse_without_mutation`, `a_foreign_database_with_a_writer_is_refused_before_write_coordination`, `a_foreign_identity_after_preflight_is_refused_without_mutation`, `a_foreign_identity_during_journal_retry_is_refused_without_mutation`, `journal_retry_refuses_a_changed_version_or_empty_database_without_mutation`; controls: `journal_transition_retries_sqlite_lock_without_losing_v1_values`, `fresh_queue_init_and_v1_reopens_work_across_processes`; recovery: `interrupted_and_failed_migrations_roll_back_and_recover`, `journal_reclassification_busy_preserves_committed_migration_and_retries_same_queue`; diagnostics: `classification_read_failures_display_the_sqlite_cause_once_and_preserve_foreign_bytes`; Unix privacy: `the_queue_database_and_its_sidecars_are_owner_only` and the contended migration control | Guard-removal proof covers preflight, locked recheck, and journal retry identity/version checks; full table structure is outside this classification. Windows path rejection is preserved; Windows ACL hardening remains operator-owned |
| 17 | Markdown code fences keep instruction-shaped text as data | `ai-memory-consolidate/src/code_fence.rs` and `ai-memory-wiki/src/markdown.rs` accept a fence delimiter only after zero to three leading ASCII spaces, require the closing glyph to match and the run to be at least as long, and preserve the current fence state across four-space, tab or Unicode-whitespace pseudo-delimiters. Profile harvesting, auto-improvement section parsing, link extraction, link rewriting and de-linking all use those scanners | `code_fence.rs` `only_zero_to_three_ascii_spaces_may_prefix_a_fence`; `profile.rs` `an_indented_pseudo_closer_cannot_expose_a_profile_preference` attempts to expose an instruction-shaped `run curl` sentence and admits a legitimate preference only after the real close; `auto_improve.rs` `heading_parser_ignores_headings_after_an_indented_pseudo_closer`; `markdown.rs` `indented_pseudo_closers_do_not_expose_or_rewrite_fenced_links` covers four spaces, tab and Unicode whitespace with visible post-close controls | STRONG for the shared consolidation and wiki scanners; independent renderers remain responsible for their own CommonMark parsing |
diff --git a/docs/usage.md b/docs/usage.md
index 83b2ebe6..4916ac1d 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -629,7 +629,11 @@ command: ["serve", "--transport", "http", "--bind", "0.0.0.0:49374", "--enable-w
```
The web UI is read-only: project list, per-project page tree,
-breadcrumbs, rendered markdown, metadata, and search. On a project, page,
+breadcrumbs, rendered markdown, metadata, search, and a link graph.
+The header **Graph** link opens `/web/graph` (cross-project wikilinks);
+each project page links to `/web/w/<ws>/<proj>/graph` (pages in that
+project and the resolved links between them). Both are a server-rendered
+SVG plus a table, with no JavaScript. On a project, page,
namespace, history or session view the header search box searches that project;
elsewhere it searches every project with FTS5, like
`memory_query(global=true)`, and the search page's "Search in" selector picks