Skip to content

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

Rust

Add frontend API and optional custom web UI directory (#7)

Djalma Júniorae81472c3bbf
diff --git a/Cargo.lock b/Cargo.lock
index b4131cf8..365f48d4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -63,6 +63,7 @@ dependencies = [
"tokio-util",
"toml_edit",
"tower",
+ "tower-http",
"tracing",
"tracing-appender",
"tracing-subscriber",
@@ -1138,6 +1139,12 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "http-range-header"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c"
+
[[package]]
name = "httparse"
version = "1.10.1"
@@ -2975,10 +2982,19 @@ checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"bitflags",
"bytes",
+ "futures-core",
"futures-util",
"http",
"http-body",
+ "http-body-util",
+ "http-range-header",
+ "httpdate",
+ "mime",
+ "mime_guess",
+ "percent-encoding",
"pin-project-lite",
+ "tokio",
+ "tokio-util",
"tower",
"tower-layer",
"tower-service",
diff --git a/Cargo.toml b/Cargo.toml
index f0f8b052..eaf6aab6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -98,6 +98,7 @@ schemars = "1"
axum = "0.8"
# Direct dep so tests can use `Router::oneshot` via `ServiceExt`.
tower = { version = "0.5", features = ["util"] }
+tower-http = { version = "0.6", features = ["fs"] }
# Backup / restore archive format.
tar = "0.4"
diff --git a/README.md b/README.md
index d8c4d10e..1f2af7ca 100644
--- a/README.md
+++ b/README.md
@@ -306,7 +306,39 @@ Useful entry points:
- Run `ai-memory bootstrap` once when adopting ai-memory in an existing
project with months of history.
- Start the server with `--enable-web` and visit `/web` for a read-only
- browser view of the markdown wiki.
+ browser view of the markdown wiki. `--enable-web` also mounts a
+ read-only JSON frontend API at `/api/v1` (workspaces, projects, pages,
+ recent, briefing, search) so custom web UIs can read the memory without
+ opening SQLite or wiki files directly:
+
+ ```text
+ GET /api/v1/workspaces
+ GET /api/v1/projects?workspace=...
+ GET /api/v1/workspaces/{workspace}/projects/{project}/pages
+ GET /api/v1/workspaces/{workspace}/projects/{project}/pages/{path}
+ GET /api/v1/workspaces/{workspace}/projects/{project}/recent?limit=...
+ GET /api/v1/workspaces/{workspace}/projects/{project}/briefing?limit=...
+ GET /api/v1/workspaces/{workspace}/overview?limit=...
+ GET /api/v1/workspaces/{workspace}/projects/{project}/overview?limit=...
+ GET /api/v1/search?q=...&workspace=...&project=...&limit=...
+ POST /api/v1/search { "q": "...", "scopes": [{ "workspace": "...", "project": "..." }] }
+ ```
+
+ `overview` bundles the open handoff + briefing + memory-health for a workspace
+ or project in one call (the data a project overview screen needs).
+
+ To serve your own static frontend instead of the built-in UI, point
+ `--web-ui-dir` at the frontend's build output (same-origin with
+ `/api/v1`, `/mcp`, `/admin/*`, so the existing auth applies):
+
+ ```bash
+ ai-memory serve --transport http --bind 127.0.0.1:49374 \
+ --enable-web --web-ui-dir ../ai-memory-ui/dist
+ ```
+
+ A reference implementation — a SolidJS knowledge browser with
+ screenshots and e2e tests — lives at
+ [djalmajr/ai-memory-ui](https://github.com/djalmajr/ai-memory-ui).
Install the routing snippet once so agents proactively call the right
MCP tool for those prompts:
diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.toml
index 5dbb323c..428a7a14 100644
--- a/crates/ai-memory-cli/Cargo.toml
+++ b/crates/ai-memory-cli/Cargo.toml
@@ -41,6 +41,7 @@ tar.workspace = true
jiff.workspace = true
tokio.workspace = true
tokio-util.workspace = true
+tower-http.workspace = true
tracing.workspace = true
tracing-appender.workspace = true
tracing-subscriber.workspace = true
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 4d8a847b..3a8e555b 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -705,10 +705,17 @@ pub struct ServeArgs {
pub project: String,
/// Mount the read-only wiki browser at /web. Off by default. When
/// enabled, anyone who can reach the MCP endpoint can also browse
- /// the wiki — keep the bind loopback-only or front with a reverse
- /// proxy that handles its own auth if you expose it.
+ /// the wiki and the read-only frontend API under /api/v1 — keep
+ /// the bind loopback-only or front with a reverse proxy that
+ /// handles its own auth if you expose it.
#[arg(long)]
pub enable_web: bool,
+ /// Serve this static directory at /web instead of the built-in UI.
+ ///
+ /// The read-only /api/v1 frontend API is still mounted when
+ /// --enable-web is set.
+ #[arg(long)]
+ pub web_ui_dir: Option<PathBuf>,
/// Run the HTTP transport in stateful (session) mode: the server
/// issues an `Mcp-Session-Id` on `initialize` and requires it on
/// every later request, with SSE-framed responses. Off by default —
@@ -734,6 +741,9 @@ pub struct WritePageArgs {
/// in the body, or the path stem.
#[arg(long)]
pub title: Option<String>,
+ /// Semantic kind: fact | rule | decision | gotcha (stored in frontmatter)
+ #[arg(long)]
+ pub kind: Option<String>,
/// Repeatable tag to add to the frontmatter `tags` array.
#[arg(long, short = 't')]
pub tag: Vec<String>,
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index bbe77d2f..60604437 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -1,5 +1,6 @@
//! `ai-memory serve` — MCP server with optional filesystem watcher.
+use std::path::Path;
use std::sync::Arc;
use ai_memory_consolidate::{Consolidator, run_lint, run_sweep};
@@ -22,6 +23,7 @@ use rmcp::transport::streamable_http_server::{
StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
};
use tokio_util::sync::CancellationToken;
+use tower_http::services::{ServeDir, ServeFile};
use tracing::info;
use crate::auth::{AuthState, require_bearer};
@@ -53,6 +55,8 @@ struct ConsolidatorSetup {
/// Returns an error if the store cannot be opened, the watcher cannot
/// install, or the transport setup fails.
pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
+ validate_web_ui_args(args.enable_web, args.web_ui_dir.as_deref())?;
+
let store = Store::open(&config.data_dir)
.with_context(|| format!("opening store at {}", config.data_dir.display()))?;
@@ -199,8 +203,13 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
.merge(hooks)
.layer(DefaultBodyLimit::max(MAX_BODY_BYTES))
.merge(admin.layer(DefaultBodyLimit::max(BOOTSTRAP_MAX_BODY_BYTES)));
- let router =
- mount_web_router(router, args.enable_web, store.reader.clone(), wiki.clone());
+ let router = mount_web_router(
+ router,
+ args.enable_web,
+ store.reader.clone(),
+ wiki.clone(),
+ args.web_ui_dir.as_deref(),
+ );
let router = apply_http_layers(router, auth_state, config.allowed_hosts.clone());
let listener = tokio::net::TcpListener::bind(&bind)
.await
@@ -540,6 +549,23 @@ fn configure_consolidator(
})
}
+fn validate_web_ui_args(enable_web: bool, web_ui_dir: Option<&Path>) -> Result<()> {
+ if web_ui_dir.is_some() && !enable_web {
+ anyhow::bail!("--web-ui-dir requires --enable-web");
+ }
+
+ if let Some(dir) = web_ui_dir {
+ if !dir.is_dir() {
+ anyhow::bail!("--web-ui-dir is not a directory: {}", dir.display());
+ }
+ if !dir.join("index.html").is_file() {
+ anyhow::bail!("--web-ui-dir is missing index.html: {}", dir.display());
+ }
+ }
+
+ Ok(())
+}
+
fn llm_retry_hint(provider: &str, model: &str, base_url: Option<&str>) -> String {
let mut command = format!("ai-memory llm-test --provider {provider} --model {model}");
if let Some(base_url) = base_url {
@@ -554,13 +580,32 @@ fn mount_web_router(
enable_web: bool,
reader: ReaderPool,
wiki: Wiki,
+ web_ui_dir: Option<&Path>,
) -> axum::Router {
if !enable_web {
return router;
}
- // Register the web router BEFORE applying the bearer middleware. In
+ // Register the web surfaces BEFORE applying the bearer middleware. In
// axum 0.8, `.layer()` only attaches to routes registered before the
// call; nesting after the layer would silently bypass auth for /web/*.
+
+ // Read-only JSON API for third-party frontends (e.g. the custom UI).
+ let router = router.nest(
+ "/api/v1",
+ ai_memory_web::api_router(reader.clone(), wiki.clone()),
+ );
+
+ // Custom SPA via --web-ui-dir (SPA fallback to index.html), otherwise
+ // the built-in server-side wiki browser.
+ if let Some(dir) = web_ui_dir {
+ let dir = dir.to_path_buf();
+ let index = dir.join("index.html");
+ info!(dir = %dir.display(), "custom web UI mounted at /web");
+ // ServeDir already answers /web and /web/ (SPA fallback to index.html);
+ // an explicit /web/ route here would conflict with the nest_service.
+ return router.nest_service("/web", ServeDir::new(dir).fallback(ServeFile::new(index)));
+ }
+
let web_router = ai_memory_web::router(reader, wiki);
info!("read-only wiki browser mounted at /web");
router
@@ -654,12 +699,58 @@ mod tests {
assert_eq!(host_without_port("[::1]:49374"), "::1");
}
+ #[test]
+ fn web_ui_dir_requires_enable_web() {
+ let ui = TempDir::new().unwrap();
+ std::fs::write(ui.path().join("index.html"), "custom ui").unwrap();
+
+ let err = validate_web_ui_args(false, Some(ui.path())).unwrap_err();
+ assert!(
+ err.to_string()
+ .contains("--web-ui-dir requires --enable-web"),
+ "unexpected error: {err}"
+ );
+ }
+
+ #[test]
+ fn web_ui_dir_must_be_directory() {
+ let tmp = TempDir::new().unwrap();
+ let file = tmp.path().join("index.html");
+ std::fs::write(&file, "custom ui").unwrap();
+
+ let err = validate_web_ui_args(true, Some(&file)).unwrap_err();
+ assert!(
+ err.to_string().contains("--web-ui-dir is not a directory"),
+ "unexpected error: {err}"
+ );
+ }
+
+ #[test]
+ fn web_ui_dir_must_include_index_html() {
+ let ui = TempDir::new().unwrap();
+
+ let err = validate_web_ui_args(true, Some(ui.path())).unwrap_err();
+ assert!(
+ err.to_string()
+ .contains("--web-ui-dir is missing index.html"),
+ "unexpected error: {err}"
+ );
+ }
+
+ #[test]
+ fn valid_web_ui_dir_passes_validation() {
+ let ui = TempDir::new().unwrap();
+ std::fs::write(ui.path().join("index.html"), "custom ui").unwrap();
+
+ validate_web_ui_args(true, Some(ui.path())).unwrap();
+ }
+
#[tokio::test]
async fn web_routes_are_inside_auth_layer() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path()).unwrap();
let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
- let router = mount_web_router(axum::Router::new(), true, store.reader.clone(), wiki);
+ let router = mount_web_router(axum::Router::new(), true, store.reader.clone(), wiki, None);
let router = apply_http_layers(
router,
Arc::new(AuthState::new(Some("secret".to_string()))),
diff --git a/crates/ai-memory-cli/src/commands/write_page.rs b/crates/ai-memory-cli/src/commands/write_page.rs
index bf45d547..92ea7246 100644
--- a/crates/ai-memory-cli/src/commands/write_page.rs
+++ b/crates/ai-memory-cli/src/commands/write_page.rs
@@ -21,6 +21,8 @@ struct WritePageBody {
body: String,
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ kind: Option<String>,
tier: String,
tags: Vec<String>,
pinned: bool,
@@ -63,6 +65,7 @@ pub async fn run(config: &Config, args: WritePageArgs) -> Result<()> {
path: args.path.clone(),
body: body_text,
title: args.title,
+ kind: args.kind,
tier: args.tier,
tags: args.tag,
pinned: args.pinned,
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index da339c79..539129bb 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -368,7 +368,13 @@ impl Config {
provider,
model,
auth: self.provider_auth(provider, None),
- base_url: self.llm_base_url.clone(),
+ // base_url falls back to the runtime env (LLM_BASE_URL), mirroring
+ // how auth is sourced — otherwise openai-compat is only
+ // configurable via config.toml even though the key comes from env.
+ base_url: self
+ .llm_base_url
+ .clone()
+ .or_else(|| self.runtime_env.llm_base_url.clone()),
}))
}
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index f6c1edc0..0ab58771 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -1411,6 +1411,11 @@ struct WritePageAdminRequest {
/// Optional title; derived from first H1 or path stem when absent.
#[serde(default)]
title: Option<String>,
+ /// Semantic kind (`fact`, `rule`, `decision`, `gotcha`). Stored in
+ /// the page frontmatter; the reader falls back to a path-derived
+ /// kind when absent.
+ #[serde(default)]
+ kind: Option<String>,
/// Tier name (`working`, `episodic`, `semantic`, `procedural`).
#[serde(default = "default_write_tier")]
tier: String,
@@ -1461,6 +1466,12 @@ async fn handle_write_page(
if let Some(title) = &req.title {
fm.insert("title".into(), serde_json::Value::String(title.clone()));
}
+ if let Some(kind) = req.kind.as_deref() {
+ let kind = kind.trim();
+ if !kind.is_empty() {
+ fm.insert("kind".into(), serde_json::Value::String(kind.to_string()));
+ }
+ }
if !req.tags.is_empty() {
fm.insert(
"tags".into(),
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index ff93c381..8188229f 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -1,5 +1,6 @@
//! [`AiMemoryServer`] — the MCP server skeleton + tool router.
+use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use std::sync::Arc;
@@ -8,7 +9,7 @@ use ai_memory_core::{
ActiveProject, AgentKind, NewHandoff, PageId, PagePath, ProjectId, SessionId, Tier, WorkspaceId,
};
use ai_memory_llm::{Embedder, LlmProvider};
-use ai_memory_store::{DecayParams, ReaderPool, WriterHandle};
+use ai_memory_store::{DecayParams, PageHit, ReaderPool, WriterHandle};
use ai_memory_wiki::{Wiki, WritePageRequest};
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
@@ -132,6 +133,16 @@ pub struct AiMemoryServer {
tool_router: ToolRouter<Self>,
}
+const MAX_QUERY_SCOPES: usize = 25;
+
+#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
+struct MemoryScopeArg {
+ /// Project to read inside the workspace.
+ project: String,
+ /// Workspace to read.
+ workspace: String,
+}
+
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct QueryArgs {
/// FTS5 query expression (e.g. `"karpathy wiki"` or `quick OR slow`).
@@ -145,6 +156,15 @@ struct QueryArgs {
/// one shared server fields several projects at once.
#[serde(default)]
project: Option<String>,
+ /// Workspace to search together with `project`. Omit to use the
+ /// current/default workspace resolution chain.
+ #[serde(default)]
+ workspace: Option<String>,
+ /// Explicit multi-project scopes to search. Use this when a task
+ /// needs context from a client project plus shared practice/project
+ /// knowledge. Cannot be combined with `workspace`/`project`.
+ #[serde(default)]
+ scopes: Vec<MemoryScopeArg>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
@@ -156,6 +176,10 @@ struct RecentArgs {
/// working in (resolved from recent hook activity). **Omit unless the user explicitly names a *different* project.**
#[serde(default)]
project: Option<String>,
+ /// Workspace to read together with `project`. Omit to use the
+ /// current/default workspace resolution chain.
+ #[serde(default)]
+ workspace: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
@@ -164,6 +188,10 @@ struct StatusArgs {
/// currently working in (resolved from recent hook activity). **Omit unless the user explicitly names a *different* project.**
#[serde(default)]
project: Option<String>,
+ /// Workspace to report together with `project`. Omit to use the
+ /// current/default workspace resolution chain.
+ #[serde(default)]
+ workspace: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -260,6 +288,10 @@ struct BriefingArgs {
/// working in (resolved from recent hook activity). **Omit unless the user explicitly names a *different* project.**
#[serde(default)]
project: Option<String>,
+ /// Workspace to brief together with `project`. Omit to use the
+ /// current/default workspace resolution chain.
+ #[serde(default)]
+ workspace: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
@@ -277,6 +309,10 @@ struct ExploreArgs {
/// working in (resolved from recent hook activity). **Omit unless the user explicitly names a *different* project.**
#[serde(default)]
project: Option<String>,
+ /// Workspace to explore together with `project`. Omit to use the
+ /// current/default workspace resolution chain.
+ #[serde(default)]
+ workspace: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
@@ -378,6 +414,119 @@ impl AiMemoryServer {
.unwrap_or((self.workspace_id, self.project_id))
}
+ async fn effective_ids_for_read_args(
+ &self,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+ ) -> Result<(WorkspaceId, ProjectId), McpError> {
+ match (
+ trimmed_opt(explicit_workspace),
+ trimmed_opt(explicit_project),
+ ) {
+ (Some(workspace), Some(project)) => self.lookup_ids(workspace, project).await,
+ (Some(_), None) => Err(McpError::internal_error(
+ "workspace and project must be provided together",
+ None,
+ )),
+ (None, project) => Ok(self.effective_ids(project).await),
+ }
+ }
+
+ async fn lookup_ids(
+ &self,
+ workspace: &str,
+ project: &str,
+ ) -> Result<(WorkspaceId, ProjectId), McpError> {
+ let workspace_id = self
+ .reader
+ .find_workspace(workspace.to_owned())
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?
+ .ok_or_else(|| {
+ McpError::internal_error(format!("workspace '{workspace}' not found"), None)
+ })?;
+ let project_id = self
+ .reader
+ .find_project(workspace_id, project.to_owned())
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?
+ .ok_or_else(|| {
+ McpError::internal_error(format!("project '{project}' not found"), None)
+ })?;
+ Ok((workspace_id, project_id))
+ }
+
+ async fn resolve_query_scopes(
+ &self,
+ scopes: &[MemoryScopeArg],
+ ) -> Result<Vec<(WorkspaceId, ProjectId)>, McpError> {
+ if scopes.len() > MAX_QUERY_SCOPES {
+ return Err(McpError::internal_error(
+ format!("at most {MAX_QUERY_SCOPES} scopes are allowed"),
+ None,
+ ));
+ }
+ let mut seen = HashSet::new();
+ let mut resolved = Vec::new();
+ for scope in scopes {
+ let workspace = trimmed_opt(Some(&scope.workspace))
+ .ok_or_else(|| McpError::internal_error("scope workspace cannot be empty", None))?;
+ let project = trimmed_opt(Some(&scope.project))
+ .ok_or_else(|| McpError::internal_error("scope project cannot be empty", None))?;
+ let ids = self.lookup_ids(workspace, project).await?;
+ if seen.insert(ids) {
+ resolved.push(ids);
+ }
+ }
+ Ok(resolved)
+ }
+
+ async fn embed_query(&self, query: &str) -> Option<Vec<f32>> {
+ let Some(embedder) = &self.embedder else {
+ return None;
+ };
+ match embedder.embed(query).await {
+ Ok(qv) => Some(qv),
+ Err(e) => {
+ tracing::warn!(
+ provider = embedder.provider(),
+ model = embedder.model(),
+ error = %e,
+ "embedder failed; degrading memory_query to BM25-only"
+ );
+ None
+ }
+ }
+ }
+
+ async fn search_project(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ query: &str,
+ query_vec: Option<&[f32]>,
+ limit: usize,
+ ) -> ai_memory_store::StoreResult<Vec<PageHit>> {
+ if let (Some(embedder), Some(qv)) = (&self.embedder, query_vec) {
+ return self
+ .reader
+ .hybrid_search(
+ workspace_id,
+ project_id,
+ query.to_owned(),
+ Some(qv.to_vec()),
+ embedder.provider().to_string(),
+ embedder.model().to_string(),
+ embedder.dim(),
+ limit,
+ )
+ .await;
+ }
+ self.reader
+ .search_pages_for_project(workspace_id, project_id, query.to_owned(), limit)
+ .await
+ }
+
/// Override the retention-sweep parameters (typically populated
/// from the user's config.toml `[decay]` table).
#[must_use]
@@ -448,66 +597,66 @@ impl AiMemoryServer {
Parameters(args): Parameters<QueryArgs>,
) -> Result<CallToolResult, McpError> {
let limit = args.limit.unwrap_or(self.default_limit).clamp(1, 100);
- let (ws, proj) = self.effective_ids(args.project.as_deref()).await;
+ if !args.scopes.is_empty()
+ && (args
+ .workspace
+ .as_deref()
+ .is_some_and(|s| !s.trim().is_empty())
+ || args
+ .project
+ .as_deref()
+ .is_some_and(|s| !s.trim().is_empty()))
+ {
+ return Err(McpError::internal_error(
+ "scopes cannot be combined with workspace/project",
+ None,
+ ));
+ }
+
let query = args.query.clone();
- // Hybrid path: try to embed the query; if it fails (provider
- // outage, cold-start timeout, billing, etc.) degrade to BM25
- // instead of erroring the whole query — losing semantic
- // re-ranking is acceptable, denying the user any search isn't.
- let hits = if let Some(embedder) = &self.embedder {
- match embedder.embed_query(&args.query).await {
- Ok(qv) => {
- self.reader
- .hybrid_search(
- ws,
- proj,
- query.clone(),
- Some(qv),
- embedder.provider().to_string(),
- embedder.model().to_string(),
- embedder.dim(),
- limit,
- )
- .await
- }
- Err(e) => {
- tracing::warn!(
- provider = embedder.provider(),
- model = embedder.model(),
- error = %e,
- "embedder failed; degrading memory_query to BM25-only"
- );
- self.reader
- .hybrid_search(
- ws,
- proj,
- query.clone(),
- None,
- String::new(),
- String::new(),
- 0,
- limit,
- )
- .await
+ let query_vec = self.embed_query(&args.query).await;
+ let hits = if args.scopes.is_empty() {
+ let (ws, proj) = self
+ .effective_ids_for_read_args(args.workspace.as_deref(), args.project.as_deref())
+ .await?;
+ self.search_project(ws, proj, &args.query, query_vec.as_deref(), limit)
+ .await
+ } else {
+ let scopes = self.resolve_query_scopes(&args.scopes).await?;
+ let mut hits_by_id: HashMap<PageId, PageHit> = HashMap::new();
+ for (ws, proj) in scopes {
+ let hits = self
+ .search_project(ws, proj, &args.query, query_vec.as_deref(), limit)
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ for hit in hits {
+ hits_by_id
+ .entry(hit.id)
+ .and_modify(|existing| {
+ if hit.rank < existing.rank {
+ *existing = hit.clone();
+ }
+ })
+ .or_insert(hit);
}
}
- } else {
- self.reader
- .hybrid_search(
- ws,
- proj,
- query.clone(),
- None,
- String::new(),
- String::new(),
- 0,
- limit,
- )
- .await
+ let mut hits: Vec<PageHit> = hits_by_id.into_values().collect();
+ hits.sort_by(|a, b| {
+ a.rank
+ .partial_cmp(&b.rank)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ });
+ hits.truncate(limit);
+ Ok(hits)
};
let hits = hits.map_err(|e| McpError::internal_error(e.to_string(), None))?;
self.spawn_access_bump(hits.iter().map(|h| h.id).collect());
- let raw_hits = if hits.is_empty() {
+ // Raw-observation fallback only applies to a single resolved
+ // project; for multi-scope queries there is no single (ws, proj).
+ let raw_hits = if hits.is_empty() && args.scopes.is_empty() {
+ let (ws, proj) = self
+ .effective_ids_for_read_args(args.workspace.as_deref(), args.project.as_deref())
+ .await?;
self.reader
.search_observations_for_project(ws, proj, query, limit)
.await
@@ -531,7 +680,9 @@ impl AiMemoryServer {
Parameters(args): Parameters<RecentArgs>,
) -> Result<CallToolResult, McpError> {
let limit = args.limit.unwrap_or(self.default_limit).clamp(1, 100);
- let (ws, proj) = self.effective_ids(args.project.as_deref()).await;
+ let (ws, proj) = self
+ .effective_ids_for_read_args(args.workspace.as_deref(), args.project.as_deref())
+ .await?;
let hits = self
.reader
.recent_pages_for_project(ws, proj, limit)
@@ -798,7 +949,9 @@ impl AiMemoryServer {
&self,
Parameters(args): Parameters<StatusArgs>,
) -> Result<CallToolResult, McpError> {
- let (ws, proj) = self.effective_ids(args.project.as_deref()).await;
+ let (ws, proj) = self
+ .effective_ids_for_read_args(args.workspace.as_deref(), args.project.as_deref())
+ .await?;
let counts = self
.reader
.status_counts_for_project(ws, proj)
@@ -822,7 +975,9 @@ impl AiMemoryServer {
Parameters(args): Parameters<BriefingArgs>,
) -> Result<CallToolResult, McpError> {
let limit = args.recent_pages_limit.unwrap_or(10);
- let (ws, proj) = self.effective_ids(args.project.as_deref()).await;
+ let (ws, proj) = self
+ .effective_ids_for_read_args(args.workspace.as_deref(), args.project.as_deref())
+ .await?;
let snapshot = self
.reader
.briefing_for_project(ws, proj, limit)
@@ -850,7 +1005,9 @@ impl AiMemoryServer {
Parameters(args): Parameters<ExploreArgs>,
) -> Result<CallToolResult, McpError> {
let limit = args.recent_pages_limit.unwrap_or(10);
- let (ws, proj) = self.effective_ids(args.project.as_deref()).await;
+ let (ws, proj) = self
+ .effective_ids_for_read_args(args.workspace.as_deref(), args.project.as_deref())
+ .await?;
let snapshot = self
.reader
.briefing_for_project(ws, proj, limit)
@@ -972,6 +1129,10 @@ fn ok_json<T: Serialize>(value: &T) -> Result<CallToolResult, McpError> {
Ok(CallToolResult::success(vec![Content::text(s)]))
}
+fn trimmed_opt(value: Option<&str>) -> Option<&str> {
+ value.map(str::trim).filter(|s| !s.is_empty())
+}
+
/// Description of how long it's been since the last observation.
/// `memory_explore` uses this both to size its prompt verbosity and
/// to give the LLM an explicit "time gap is N hours" cue.
@@ -1221,6 +1382,8 @@ mod tests {
query: "karpathy".into(),
limit: Some(5),
project: None,
+ scopes: Vec::new(),
+ workspace: None,
}))
.await
.unwrap();
@@ -1267,6 +1430,8 @@ mod tests {
query: "quokka".into(),
limit: Some(5),
project: None,
+ scopes: Vec::new(),
+ workspace: None,
}))
.await
.unwrap();
@@ -1285,11 +1450,164 @@ mod tests {
assert!(text.contains("quokka"), "expected raw snippet; got {text}");
}
+ #[tokio::test]
+ async fn memory_query_can_target_explicit_workspace_project() {
+ let (_tmp, store, server, _ws, _pj) = setup_server().await;
+ let practice_ws = store
+ .writer
+ .get_or_create_workspace("practice")
+ .await
+ .unwrap();
+ let testing = store
+ .writer
+ .get_or_create_project(practice_ws, "unit-testing", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: practice_ws,
+ project_id: testing,
+ path: PagePath::new("patterns.md").unwrap(),
+ title: "Testing Patterns".into(),
+ body: "workspace_specific_token belongs to practice".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ })
+ .await
+ .unwrap();
+
+ let result = server
+ .memory_query(Parameters(QueryArgs {
+ query: "workspace_specific_token".into(),
+ limit: Some(5),
+ project: Some("unit-testing".into()),
+ scopes: Vec::new(),
+ workspace: Some("practice".into()),
+ }))
+ .await
+ .unwrap();
+ let text = result
+ .content
+ .first()
+ .and_then(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .unwrap();
+ assert!(text.contains("patterns.md"), "expected hit; got {text}");
+ }
+
+ #[tokio::test]
+ async fn memory_query_can_search_multiple_scopes() {
+ let (_tmp, store, server, ws, _pj) = setup_server().await;
+ let product = store
+ .writer
+ .get_or_create_project(ws, "product", None)
+ .await
+ .unwrap();
+ let hidden = store
+ .writer
+ .get_or_create_project(ws, "hidden", None)
+ .await
+ .unwrap();
+ let practice_ws = store
+ .writer
+ .get_or_create_workspace("practice")
+ .await
+ .unwrap();
+ let testing = store
+ .writer
+ .get_or_create_project(practice_ws, "unit-testing", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: product,
+ path: PagePath::new("product.md").unwrap(),
+ title: "Product Rules".into(),
+ body: "multi_scope_token belongs to product".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: practice_ws,
+ project_id: testing,
+ path: PagePath::new("patterns.md").unwrap(),
+ title: "Testing Patterns".into(),
+ body: "multi_scope_token belongs to practice".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: hidden,
+ path: PagePath::new("hidden.md").unwrap(),
+ title: "Hidden".into(),
+ body: "multi_scope_token must not be returned".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ })
+ .await
+ .unwrap();
+
+ let result = server
+ .memory_query(Parameters(QueryArgs {
+ query: "multi_scope_token".into(),
+ limit: Some(10),
+ project: None,
+ scopes: vec![
+ MemoryScopeArg {
+ project: "product".into(),
+ workspace: "default".into(),
+ },
+ MemoryScopeArg {
+ project: "unit-testing".into(),
+ workspace: "practice".into(),
+ },
+ ],
+ workspace: None,
+ }))
+ .await
+ .unwrap();
+ let text = result
+ .content
+ .first()
+ .and_then(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .unwrap();
+ assert!(text.contains("product.md"), "expected product hit: {text}");
+ assert!(
+ text.contains("patterns.md"),
+ "expected practice hit: {text}"
+ );
+ assert!(!text.contains("hidden.md"), "unexpected hidden hit: {text}");
+ }
+
#[tokio::test]
async fn memory_status_returns_counts() {
let (_tmp, _store, server, _ws, _pj) = setup_server().await;
let result = server
- .memory_status(Parameters(StatusArgs { project: None }))
+ .memory_status(Parameters(StatusArgs {
+ project: None,
+ workspace: None,
+ }))
.await
.unwrap();
let text = result
@@ -1308,6 +1626,7 @@ mod tests {
.memory_briefing(Parameters(BriefingArgs {
recent_pages_limit: Some(5),
project: None,
+ workspace: None,
}))
.await
.unwrap();
@@ -1352,6 +1671,7 @@ mod tests {
focus: None,
recent_pages_limit: Some(5),
project: None,
+ workspace: None,
}))
.await
.unwrap();
@@ -1411,6 +1731,7 @@ mod tests {
.memory_recent(Parameters(RecentArgs {
limit: Some(5),
project: None,
+ workspace: None,
}))
.await
.unwrap();
@@ -1465,6 +1786,7 @@ mod tests {
.memory_recent(Parameters(RecentArgs {
limit: Some(5),
project: None,
+ workspace: None,
}))
.await
.unwrap();
@@ -1509,6 +1831,7 @@ mod tests {
.memory_briefing(Parameters(BriefingArgs {
recent_pages_limit: Some(5),
project: None,
+ workspace: None,
}))
.await
.unwrap();
@@ -1668,6 +1991,8 @@ mod tests {
query: "Karpathy".into(),
limit: Some(99_999),
project: None,
+ scopes: Vec::new(),
+ workspace: None,
}))
.await
.expect("oversized limit should be clamped, not refused");
@@ -1693,6 +2018,8 @@ mod tests {
query: "\"unbalanced".into(),
limit: Some(10),
project: None,
+ scopes: Vec::new(),
+ workspace: None,
}))
.await;
// Either a tidy 0-hit Ok (FTS5 is occasionally lenient) or
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 61834b03..a003d8a5 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -27,8 +27,9 @@ pub use error::{StoreError, StoreResult};
pub use ops::{EmbeddingWrite, PurgeSummary, ReorgSummary};
pub use reader::{
ActivityWindow, BriefingPage, BriefingSnapshot, DecayCandidate, DerivedIndexStatus,
- EmbeddingTripleCount, ObservationHit, PageHit, PageHitWithMeta, PageMeta, PageSummary,
- ProjectSummary, ReaderPool, StatusCounts, StoredEmbedding, f32_vec_to_bytes,
+ EmbeddingTripleCount, HealthDetail, HealthPage, ObservationHit, PageHit, PageHitWithMeta,
+ PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool, RelatedPage, StatusCounts,
+ StoredEmbedding, WorkspaceSummary, f32_vec_to_bytes,
};
pub use writer::WriterHandle;
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 3242ab59..b2f8fbf6 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -204,6 +204,21 @@ pub struct ProjectSummary {
pub last_updated: Option<String>,
}
+/// One row per workspace with aggregate stats.
+/// Returned by [`ReaderPool::list_workspaces_with_stats`].
+#[derive(Debug, Clone, Serialize)]
+pub struct WorkspaceSummary {
+ /// Name of the workspace.
+ pub workspace_name: String,
+ /// Number of projects in this workspace.
+ pub project_count: u64,
+ /// Number of `is_latest = 1` pages across the workspace.
+ pub page_count: u64,
+ /// ISO-8601 timestamp of the newest `updated_at`, or `None` when
+ /// the workspace has no pages yet.
+ pub last_updated: Option<String>,
+}
+
/// Page summary for tree-view rendering (no body).
/// Returned by [`ReaderPool::list_pages`].
#[derive(Debug, Clone, Serialize)]
@@ -250,6 +265,58 @@ pub struct PageMeta {
pub supersedes: Option<String>,
}
+/// A page related to another through the link graph — used by the
+/// page-view "references / referenced by" panel. Body is omitted; just
+/// enough to render a clickable row.
+#[derive(Debug, Clone, Serialize)]
+pub struct RelatedPage {
+ /// Relative wiki path of the related page.
+ pub path: String,
+ /// Title of the related page.
+ pub title: String,
+ /// Semantic kind of the related page.
+ pub kind: String,
+}
+
+/// Resolved outgoing links and incoming back-links for one page.
+/// Returned by [`ReaderPool::page_links`].
+#[derive(Debug, Clone, Default, Serialize)]
+pub struct PageLinks {
+ /// Latest pages this page references (resolved outgoing links).
+ pub links: Vec<RelatedPage>,
+ /// Latest pages that reference this page (incoming back-links).
+ pub backlinks: Vec<RelatedPage>,
+}
+
+/// One page flagged by a workspace health check, with enough identity to
+/// render a clickable drill-down row across projects.
+#[derive(Debug, Clone, Serialize)]
+pub struct HealthPage {
+ /// Workspace name.
+ pub workspace: String,
+ /// Project name within the workspace.
+ pub project: String,
+ /// Relative wiki path.
+ pub path: String,
+ /// Page title.
+ pub title: String,
+ /// Semantic kind.
+ pub kind: String,
+}
+
+/// Drill-down lists backing the workspace "memory health" counters.
+/// Each list is capped; the headline counts stay authoritative.
+/// Returned by [`ReaderPool::health_detail_for_workspace`].
+#[derive(Debug, Clone, Default, Serialize)]
+pub struct HealthDetail {
+ /// Episodic latest pages untouched for over 30 days.
+ pub stale: Vec<HealthPage>,
+ /// Latest pages sharing a title with at least one other page.
+ pub duplicates: Vec<HealthPage>,
+ /// Latest pages with no incoming or outgoing links.
+ pub orphans: Vec<HealthPage>,
+}
+
/// Cheap, cloneable read-only connection pool handle.
#[derive(Clone)]
pub struct ReaderPool {
@@ -1278,7 +1345,15 @@ impl ReaderPool {
// `kind = "rule"` — see consolidator.rs::slugify_for_rule.
let mut rules_stmt = conn.prepare_cached(
"SELECT path, title, \
- COALESCE(json_extract(frontmatter_json, '$.kind'), 'fact') AS kind, \
+ COALESCE( \
+ json_extract(frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN path LIKE 'decisions/%' THEN 'decision' \
+ WHEN path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ) AS kind, \
updated_at \
FROM pages \
WHERE is_latest = 1 AND path GLOB '_rules/*' \
@@ -1306,7 +1381,15 @@ impl ReaderPool {
let mut recent_stmt = conn.prepare_cached(
"SELECT path, title, \
- COALESCE(json_extract(frontmatter_json, '$.kind'), 'fact') AS kind, \
+ COALESCE( \
+ json_extract(frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN path LIKE 'decisions/%' THEN 'decision' \
+ WHEN path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ) AS kind, \
updated_at \
FROM pages \
WHERE is_latest = 1 \
@@ -1402,7 +1485,15 @@ impl ReaderPool {
let mut rules_stmt = conn.prepare_cached(
"SELECT path, title, \
- COALESCE(json_extract(frontmatter_json, '$.kind'), 'fact') AS kind, \
+ COALESCE( \
+ json_extract(frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN path LIKE 'decisions/%' THEN 'decision' \
+ WHEN path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ) AS kind, \
updated_at \
FROM pages \
WHERE workspace_id = ?1 AND project_id = ?2 AND is_latest = 1 AND path GLOB '_rules/*' \
@@ -1430,7 +1521,15 @@ impl ReaderPool {
let mut recent_stmt = conn.prepare_cached(
"SELECT path, title, \
- COALESCE(json_extract(frontmatter_json, '$.kind'), 'fact') AS kind, \
+ COALESCE( \
+ json_extract(frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN path LIKE 'decisions/%' THEN 'decision' \
+ WHEN path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ) AS kind, \
updated_at \
FROM pages \
WHERE workspace_id = ?1 AND project_id = ?2 AND is_latest = 1 \
@@ -1457,6 +1556,443 @@ impl ReaderPool {
.await
}
+ /// Return the latest open handoff for the workspace, aggregating
+ /// across all of its projects (no project filter).
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn latest_open_handoff_for_workspace(
+ &self,
+ workspace_id: WorkspaceId,
+ ) -> StoreResult<Option<Handoff>> {
+ self.with_conn(move |conn| {
+ let row_opt = conn
+ .query_row(
+ "SELECT id, workspace_id, project_id, from_session_id, from_agent, to_agent, \
+ cwd, summary, open_questions, next_steps, files_touched, state, \
+ created_at, accepted_by, accepted_at, accepted_by_session \
+ FROM handoffs \
+ WHERE workspace_id = ?1 AND state = 'open' \
+ ORDER BY created_at DESC LIMIT 1",
+ params![workspace_id.as_bytes()],
+ row_to_handoff,
+ )
+ .optional()?;
+ row_opt.transpose()
+ })
+ .await
+ }
+
+ /// Look up a project name by id within a workspace.
+ ///
+ /// Returns `None` when no matching project exists.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn project_name_by_id(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ ) -> StoreResult<Option<String>> {
+ self.with_conn(move |conn| {
+ let row_opt = conn
+ .query_row(
+ "SELECT name FROM projects WHERE id = ?1 AND workspace_id = ?2",
+ params![project_id.as_bytes(), workspace_id.as_bytes()],
+ |row| row.get::<_, String>(0),
+ )
+ .optional()?;
+ Ok(row_opt)
+ })
+ .await
+ }
+
+ /// Build a [`BriefingSnapshot`] aggregated across all projects in a
+ /// workspace.
+ ///
+ /// Mirrors [`ReaderPool::briefing_for_project`] but scopes every query
+ /// to the workspace only (no `project_id` filter).
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn briefing_for_workspace(
+ &self,
+ workspace_id: WorkspaceId,
+ recent_pages_limit: usize,
+ ) -> StoreResult<BriefingSnapshot> {
+ let recent_limit = recent_pages_limit.clamp(1, 100) as i64;
+ self.with_conn(move |conn| {
+ let now_us = jiff::Timestamp::now().as_microsecond();
+ let day_us: i64 = 86_400 * 1_000_000;
+ let cutoff_7d = now_us - 7 * day_us;
+ let cutoff_30d = now_us - 30 * day_us;
+
+ let counts = StatusCounts {
+ pages_latest: count_workspace(
+ conn,
+ "SELECT COUNT(*) FROM pages WHERE workspace_id = ?1 AND is_latest = 1",
+ workspace_id,
+ )?,
+ pages_all: count_workspace(
+ conn,
+ "SELECT COUNT(*) FROM pages WHERE workspace_id = ?1",
+ workspace_id,
+ )?,
+ sessions: count_workspace(
+ conn,
+ "SELECT COUNT(*) FROM sessions WHERE workspace_id = ?1",
+ workspace_id,
+ )?,
+ observations: count_workspace(
+ conn,
+ "SELECT COUNT(*) FROM observations WHERE workspace_id = ?1",
+ workspace_id,
+ )?,
+ };
+
+ let activity_7d = window_activity_workspace(conn, 7, cutoff_7d, workspace_id)?;
+ let activity_30d = window_activity_workspace(conn, 30, cutoff_30d, workspace_id)?;
+
+ let last_observation_at: Option<i64> = conn
+ .query_row(
+ "SELECT MAX(created_at) FROM observations WHERE workspace_id = ?1",
+ params![workspace_id.as_bytes()],
+ |row| row.get::<_, Option<i64>>(0),
+ )
+ .optional()?
+ .flatten();
+ let last_observation_at = last_observation_at
+ .and_then(|us| jiff::Timestamp::from_microsecond(us).ok())
+ .map(|ts| ts.to_string());
+
+ let pending_handoff_count = count_workspace(
+ conn,
+ "SELECT COUNT(*) FROM handoffs WHERE workspace_id = ?1 AND state = 'open'",
+ workspace_id,
+ )?;
+
+ let mut rules_stmt = conn.prepare_cached(
+ "SELECT path, title, \
+ COALESCE( \
+ json_extract(frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN path LIKE 'decisions/%' THEN 'decision' \
+ WHEN path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ) AS kind, \
+ updated_at \
+ FROM pages \
+ WHERE workspace_id = ?1 AND is_latest = 1 AND path GLOB '_rules/*' \
+ ORDER BY updated_at DESC",
+ )?;
+ let rules: Vec<BriefingPage> = rules_stmt
+ .query_map(params![workspace_id.as_bytes()], briefing_page_from_row)?
+ .collect::<Result<Vec<_>, _>>()?
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>()?;
+
+ let mut slots_stmt = conn.prepare_cached(
+ "SELECT path, title, \
+ COALESCE(json_extract(frontmatter_json, '$.kind'), 'slot') AS kind, \
+ updated_at \
+ FROM pages \
+ WHERE workspace_id = ?1 AND is_latest = 1 AND path GLOB '_slots/*' \
+ ORDER BY path ASC",
+ )?;
+ let slots: Vec<BriefingPage> = slots_stmt
+ .query_map(params![workspace_id.as_bytes()], briefing_page_from_row)?
+ .collect::<Result<Vec<_>, _>>()?
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>()?;
+
+ let mut recent_stmt = conn.prepare_cached(
+ "SELECT path, title, \
+ COALESCE( \
+ json_extract(frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN path LIKE 'decisions/%' THEN 'decision' \
+ WHEN path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ) AS kind, \
+ updated_at \
+ FROM pages \
+ WHERE workspace_id = ?1 AND is_latest = 1 \
+ ORDER BY updated_at DESC \
+ LIMIT ?2",
+ )?;
+ let recent_pages: Vec<BriefingPage> = recent_stmt
+ .query_map(
+ params![workspace_id.as_bytes(), recent_limit],
+ briefing_page_from_row,
+ )?
+ .collect::<Result<Vec<_>, _>>()?
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>()?;
+
+ Ok(BriefingSnapshot {
+ counts,
+ activity_7d,
+ activity_30d,
+ last_observation_at,
+ pending_handoff_count,
+ rules,
+ slots,
+ recent_pages,
+ })
+ })
+ .await
+ }
+
+ /// Compute basic memory-health counters for a workspace.
+ ///
+ /// Returns `(stale, duplicates, orphans)`:
+ /// - `stale`: latest episodic pages not updated within `STALE_DAYS` (30).
+ /// - `duplicates`: extra latest pages that share a title.
+ /// - `orphans`: latest pages with no inbound or outbound links.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn memory_health_for_workspace(
+ &self,
+ workspace_id: WorkspaceId,
+ ) -> StoreResult<(u64, u64, u64)> {
+ self.memory_health_scoped(workspace_id, None).await
+ }
+
+ /// Per-project variant of [`ReaderPool::memory_health_for_workspace`]:
+ /// the same stale / duplicate / orphan counters, confined to one project.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn memory_health_for_project(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ ) -> StoreResult<(u64, u64, u64)> {
+ self.memory_health_scoped(workspace_id, Some(project_id))
+ .await
+ }
+
+ async fn memory_health_scoped(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: Option<ProjectId>,
+ ) -> StoreResult<(u64, u64, u64)> {
+ self.with_conn(move |conn| {
+ let now_us = jiff::Timestamp::now().as_microsecond();
+ let cutoff_30d = now_us - 30 * 86_400 * 1_000_000;
+ let proj = project_id.map(|p| Value::Blob(p.as_bytes().to_vec()));
+ let ws = || Value::Blob(workspace_id.as_bytes().to_vec());
+ // Optional project filter, anonymous-`?` style. The orphan query
+ // aliases pages as `p`, so it needs its own qualified clause.
+ let clause = if proj.is_some() {
+ " AND project_id = ?"
+ } else {
+ ""
+ };
+ let clause_p = if proj.is_some() {
+ " AND p.project_id = ?"
+ } else {
+ ""
+ };
+
+ let stale: i64 = conn
+ .query_row(
+ &format!(
+ "SELECT COUNT(*) FROM pages \
+ WHERE workspace_id = ? AND is_latest = 1 \
+ AND tier = 'episodic' AND updated_at < ?{clause}"
+ ),
+ params_from_iter(
+ [ws(), Value::Integer(cutoff_30d)]
+ .into_iter()
+ .chain(proj.clone()),
+ ),
+ |row| row.get(0),
+ )
+ .optional()?
+ .unwrap_or(0);
+
+ let duplicates: i64 = conn
+ .query_row(
+ &format!(
+ "SELECT COALESCE(SUM(c - 1), 0) FROM ( \
+ SELECT COUNT(*) c FROM pages \
+ WHERE workspace_id = ? AND is_latest = 1{clause} \
+ GROUP BY title HAVING c > 1 \
+ )"
+ ),
+ params_from_iter(std::iter::once(ws()).chain(proj.clone())),
+ |row| row.get(0),
+ )
+ .optional()?
+ .unwrap_or(0);
+
+ let orphans: i64 = conn
+ .query_row(
+ &format!(
+ "SELECT COUNT(*) FROM pages p \
+ WHERE p.workspace_id = ? AND p.is_latest = 1{clause_p} \
+ AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id) \
+ AND NOT EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)"
+ ),
+ params_from_iter(std::iter::once(ws()).chain(proj.clone())),
+ |row| row.get(0),
+ )
+ .optional()?
+ .unwrap_or(0);
+
+ Ok((
+ u64::try_from(stale).unwrap_or(0),
+ u64::try_from(duplicates).unwrap_or(0),
+ u64::try_from(orphans).unwrap_or(0),
+ ))
+ })
+ .await
+ }
+
+ /// Drill-down lists behind [`ReaderPool::memory_health_for_workspace`]'s
+ /// counters: the actual stale / duplicate / orphan pages, each capped at
+ /// `limit`. Definitions mirror the counters exactly so the lists explain
+ /// the headline numbers.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn health_detail_for_workspace(
+ &self,
+ workspace_id: WorkspaceId,
+ limit: usize,
+ ) -> StoreResult<HealthDetail> {
+ self.health_detail_scoped(workspace_id, None, limit).await
+ }
+
+ /// Per-project variant of [`ReaderPool::health_detail_for_workspace`].
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn health_detail_for_project(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ limit: usize,
+ ) -> StoreResult<HealthDetail> {
+ self.health_detail_scoped(workspace_id, Some(project_id), limit)
+ .await
+ }
+
+ async fn health_detail_scoped(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: Option<ProjectId>,
+ limit: usize,
+ ) -> StoreResult<HealthDetail> {
+ let limit = i64::try_from(limit).unwrap_or(i64::MAX);
+ self.with_conn(move |conn| {
+ let now_us = jiff::Timestamp::now().as_microsecond();
+ let cutoff_30d = now_us - 30 * 86_400 * 1_000_000;
+ let proj = project_id.map(|p| Value::Blob(p.as_bytes().to_vec()));
+ let ws = || Value::Blob(workspace_id.as_bytes().to_vec());
+ let clause = if proj.is_some() {
+ " AND pg.project_id = ?"
+ } else {
+ ""
+ };
+ let inner_clause = if proj.is_some() {
+ " AND project_id = ?"
+ } else {
+ ""
+ };
+
+ // Shared SELECT prefix: identity + path-inferred `kind`.
+ let select = "SELECT w.name, p.name, pg.path, pg.title, \
+ COALESCE( \
+ json_extract(pg.frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN pg.path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN pg.path LIKE 'decisions/%' THEN 'decision' \
+ WHEN pg.path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ) \
+ FROM pages pg \
+ JOIN projects p ON p.id = pg.project_id \
+ JOIN workspaces w ON w.id = pg.workspace_id ";
+
+ // Params follow placeholder order: ws, cutoff, [proj], limit.
+ let stale_sql = format!(
+ "{select} WHERE pg.workspace_id = ? AND pg.is_latest = 1 \
+ AND pg.tier = 'episodic' AND pg.updated_at < ?{clause} \
+ ORDER BY pg.updated_at ASC LIMIT ?"
+ );
+ let mut stale_stmt = conn.prepare(&stale_sql)?;
+ let stale = stale_stmt
+ .query_map(
+ params_from_iter(
+ [ws(), Value::Integer(cutoff_30d)]
+ .into_iter()
+ .chain(proj.clone())
+ .chain(std::iter::once(Value::Integer(limit))),
+ ),
+ health_page_from_row,
+ )?
+ .collect::<Result<Vec<_>, _>>()?;
+
+ // Params: ws, [proj], ws(inner), [proj(inner)], limit.
+ let dup_sql = format!(
+ "{select} WHERE pg.workspace_id = ? AND pg.is_latest = 1{clause} \
+ AND pg.title IN ( \
+ SELECT title FROM pages \
+ WHERE workspace_id = ? AND is_latest = 1{inner_clause} \
+ GROUP BY title HAVING COUNT(*) > 1 \
+ ) \
+ ORDER BY pg.title, p.name LIMIT ?"
+ );
+ let mut dup_stmt = conn.prepare(&dup_sql)?;
+ let duplicates = dup_stmt
+ .query_map(
+ params_from_iter(
+ std::iter::once(ws())
+ .chain(proj.clone())
+ .chain(std::iter::once(ws()))
+ .chain(proj.clone())
+ .chain(std::iter::once(Value::Integer(limit))),
+ ),
+ health_page_from_row,
+ )?
+ .collect::<Result<Vec<_>, _>>()?;
+
+ // Params: ws, [proj], limit.
+ let orphan_sql = format!(
+ "{select} WHERE pg.workspace_id = ? AND pg.is_latest = 1{clause} \
+ AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = pg.id) \
+ AND NOT EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = pg.id) \
+ ORDER BY pg.updated_at DESC LIMIT ?"
+ );
+ let mut orphan_stmt = conn.prepare(&orphan_sql)?;
+ let orphans = orphan_stmt
+ .query_map(
+ params_from_iter(
+ std::iter::once(ws())
+ .chain(proj.clone())
+ .chain(std::iter::once(Value::Integer(limit))),
+ ),
+ health_page_from_row,
+ )?
+ .collect::<Result<Vec<_>, _>>()?;
+
+ Ok(HealthDetail {
+ stale,
+ duplicates,
+ orphans,
+ })
+ })
+ .await
+ }
+
/// Look up a page's workspace and project names by page id.
///
/// # Errors
@@ -1466,7 +2002,15 @@ impl ReaderPool {
let row_opt = conn
.query_row(
"SELECT w.name, p.name, w.id, p.id, pg.path, pg.title, \
- COALESCE(json_extract(pg.frontmatter_json, '$.kind'), 'fact'), \
+ COALESCE( \
+ json_extract(pg.frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN pg.path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN pg.path LIKE 'decisions/%' THEN 'decision' \
+ WHEN pg.path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ), \
pg.tier, pg.pinned, pg.created_at, pg.updated_at, \
sp.path AS supersedes_path \
FROM pages pg \
@@ -1497,7 +2041,15 @@ impl ReaderPool {
let row_opt = conn
.query_row(
"SELECT w.name, p.name, w.id, p.id, pg.path, pg.title, \
- COALESCE(json_extract(pg.frontmatter_json, '$.kind'), 'fact'), \
+ COALESCE( \
+ json_extract(pg.frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN pg.path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN pg.path LIKE 'decisions/%' THEN 'decision' \
+ WHEN pg.path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ), \
pg.tier, pg.pinned, pg.created_at, pg.updated_at, \
sp.path AS supersedes_path \
FROM pages pg \
@@ -1515,6 +2067,91 @@ impl ReaderPool {
.await
}
+ /// Resolve the outgoing links and incoming back-links for the latest
+ /// version of a page identified by `(workspace_id, project_id, path)`.
+ ///
+ /// Both ends are constrained to `is_latest = 1`, so superseded versions
+ /// never leak into the link panel. Returns empty lists when the page is
+ /// missing or has no links.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn page_links(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ path: String,
+ ) -> StoreResult<PageLinks> {
+ self.with_conn(move |conn| {
+ let id_opt: 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(id_bytes) = id_opt else {
+ return Ok(PageLinks::default());
+ };
+
+ // Outgoing: latest pages this page links to. Incoming: latest
+ // pages that link here. Both reuse the path-inference `kind`
+ // fallback so untagged pages still classify.
+ let outgoing = "SELECT DISTINCT pg.path, pg.title, \
+ COALESCE( \
+ json_extract(pg.frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN pg.path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN pg.path LIKE 'decisions/%' THEN 'decision' \
+ WHEN pg.path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ) \
+ FROM links l \
+ JOIN pages pg ON pg.id = l.to_page_id \
+ WHERE l.from_page_id = ?1 AND pg.is_latest = 1 \
+ ORDER BY pg.path";
+ let incoming = "SELECT DISTINCT pg.path, pg.title, \
+ COALESCE( \
+ json_extract(pg.frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN pg.path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN pg.path LIKE 'decisions/%' THEN 'decision' \
+ WHEN pg.path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ) \
+ FROM links l \
+ JOIN pages pg ON pg.id = l.from_page_id \
+ WHERE l.to_page_id = ?1 AND pg.is_latest = 1 \
+ ORDER BY pg.path";
+
+ let collect = |sql: &str| -> StoreResult<Vec<RelatedPage>> {
+ let mut stmt = conn.prepare(sql)?;
+ let rows = stmt.query_map(params![id_bytes], |row| {
+ Ok(RelatedPage {
+ path: row.get(0)?,
+ title: row.get(1)?,
+ kind: row.get(2)?,
+ })
+ })?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ };
+
+ Ok(PageLinks {
+ links: collect(outgoing)?,
+ backlinks: collect(incoming)?,
+ })
+ })
+ .await
+ }
+
/// Return one row per (workspace, project) with page-count and
/// last-updated aggregates. Used by the web UI project-list view.
///
@@ -1523,7 +2160,28 @@ impl ReaderPool {
/// # Errors
/// Propagates any SQL or pool error.
pub async fn list_projects_with_stats(&self) -> StoreResult<Vec<ProjectSummary>> {
- self.with_conn(|conn| {
+ self.list_projects_with_stats_filtered(None).await
+ }
+
+ /// Return one row per project within one workspace.
+ ///
+ /// Only `is_latest = 1` pages are counted.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn list_projects_with_stats_for_workspace(
+ &self,
+ workspace: String,
+ ) -> StoreResult<Vec<ProjectSummary>> {
+ self.list_projects_with_stats_filtered(Some(workspace))
+ .await
+ }
+
+ async fn list_projects_with_stats_filtered(
+ &self,
+ workspace: Option<String>,
+ ) -> StoreResult<Vec<ProjectSummary>> {
+ self.with_conn(move |conn| {
let mut stmt = conn.prepare(
"SELECT w.name AS workspace_name, \
p.name AS project_name, \
@@ -1532,10 +2190,11 @@ impl ReaderPool {
FROM workspaces w \
JOIN projects p ON p.workspace_id = w.id \
LEFT JOIN pages pg ON pg.project_id = p.id AND pg.is_latest = 1 \
+ WHERE (?1 IS NULL OR w.name = ?1) \
GROUP BY w.id, p.id \
ORDER BY last_updated_us DESC NULLS LAST",
)?;
- let rows = stmt.query_map([], |row| {
+ let rows = stmt.query_map(params![workspace], |row| {
let workspace_name: String = row.get(0)?;
let project_name: String = row.get(1)?;
let page_count: i64 = row.get(2)?;
@@ -1561,6 +2220,53 @@ impl ReaderPool {
.await
}
+ /// Return one row per workspace with project/page-count and
+ /// last-updated aggregates. Used by custom frontends that need a
+ /// workspace chooser before narrowing into projects.
+ ///
+ /// Only `is_latest = 1` pages are counted.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn list_workspaces_with_stats(&self) -> StoreResult<Vec<WorkspaceSummary>> {
+ self.with_conn(|conn| {
+ let mut stmt = conn.prepare(
+ "SELECT w.name AS workspace_name, \
+ COUNT(DISTINCT p.id) AS project_count, \
+ COUNT(pg.id) AS page_count, \
+ MAX(pg.updated_at) AS last_updated_us \
+ FROM workspaces w \
+ LEFT JOIN projects p ON p.workspace_id = w.id \
+ LEFT JOIN pages pg ON pg.project_id = p.id AND pg.is_latest = 1 \
+ GROUP BY w.id \
+ ORDER BY w.name ASC",
+ )?;
+ let rows = stmt.query_map([], |row| {
+ let workspace_name: String = row.get(0)?;
+ let project_count: i64 = row.get(1)?;
+ let page_count: i64 = row.get(2)?;
+ let last_updated_us: Option<i64> = row.get(3)?;
+ Ok((workspace_name, project_count, page_count, last_updated_us))
+ })?;
+ let mut out = Vec::new();
+ for r in rows {
+ let (workspace_name, project_count, page_count, last_updated_us) = r?;
+ let last_updated = last_updated_us
+ .and_then(|us| jiff::Timestamp::from_microsecond(us).ok())
+ .map(|ts| ts.to_string());
+ #[allow(clippy::cast_sign_loss)]
+ out.push(WorkspaceSummary {
+ workspace_name,
+ project_count: project_count.max(0) as u64,
+ page_count: page_count.max(0) as u64,
+ last_updated,
+ });
+ }
+ Ok(out)
+ })
+ .await
+ }
+
/// All `is_latest = 1` pages under a given (workspace, project),
/// ordered by path ascending. Used by the web UI tree view.
///
@@ -1576,7 +2282,15 @@ impl ReaderPool {
self.with_conn(move |conn| {
let mut stmt = conn.prepare(
"SELECT pg.path, pg.title, \
- COALESCE(json_extract(pg.frontmatter_json, '$.kind'), 'fact') AS kind, \
+ COALESCE( \
+ json_extract(pg.frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN pg.path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN pg.path LIKE 'decisions/%' THEN 'decision' \
+ WHEN pg.path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ) AS kind, \
pg.tier, pg.updated_at \
FROM pages pg \
JOIN projects p ON p.id = pg.project_id \
@@ -1630,7 +2344,15 @@ impl ReaderPool {
let row_opt = conn
.query_row(
"SELECT w.name, p.name, w.id, p.id, pg.path, pg.title, \
- COALESCE(json_extract(pg.frontmatter_json, '$.kind'), 'fact'), \
+ COALESCE( \
+ json_extract(pg.frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN pg.path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN pg.path LIKE 'decisions/%' THEN 'decision' \
+ WHEN pg.path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ), \
pg.tier, pg.pinned, pg.created_at, pg.updated_at, \
sp.path AS supersedes_path \
FROM pages pg \
@@ -1858,6 +2580,17 @@ impl ReaderPool {
}
}
+/// Map a `(workspace, project, path, title, kind)` row to a [`HealthPage`].
+fn health_page_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<HealthPage> {
+ Ok(HealthPage {
+ workspace: row.get(0)?,
+ project: row.get(1)?,
+ path: row.get(2)?,
+ title: row.get(3)?,
+ kind: row.get(4)?,
+ })
+}
+
fn page_meta_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<PageMeta>> {
let workspace_name: String = row.get(0)?;
let project_name: String = row.get(1)?;
@@ -2228,6 +2961,13 @@ fn count_project(
Ok(u64::try_from(n.unwrap_or(0)).unwrap_or(0))
}
+fn count_workspace(conn: &Connection, sql: &str, workspace_id: WorkspaceId) -> StoreResult<u64> {
+ let n: Option<i64> = conn
+ .query_row(sql, params![workspace_id.as_bytes()], |row| row.get(0))
+ .optional()?;
+ Ok(u64::try_from(n.unwrap_or(0)).unwrap_or(0))
+}
+
fn normalize_fts_query(query: &str) -> String {
// Delegates to prepare_fts5_query: neutralises `word:` column syntax and
// quotes tokens so `-` / `*` are not FTS5 operators.
@@ -2286,6 +3026,34 @@ fn window_activity_project(
})
}
+fn window_activity_workspace(
+ conn: &Connection,
+ days: u32,
+ cutoff_us: i64,
+ workspace_id: WorkspaceId,
+) -> StoreResult<ActivityWindow> {
+ let count_since = |sql: &str| -> StoreResult<u64> {
+ let n: Option<i64> = conn
+ .query_row(sql, params![workspace_id.as_bytes(), cutoff_us], |row| {
+ row.get(0)
+ })
+ .optional()?;
+ Ok(u64::try_from(n.unwrap_or(0)).unwrap_or(0))
+ };
+ Ok(ActivityWindow {
+ days,
+ sessions: count_since(
+ "SELECT COUNT(*) FROM sessions WHERE workspace_id = ?1 AND started_at > ?2",
+ )?,
+ observations: count_since(
+ "SELECT COUNT(*) FROM observations WHERE workspace_id = ?1 AND created_at > ?2",
+ )?,
+ pages_updated: count_since(
+ "SELECT COUNT(*) FROM pages WHERE workspace_id = ?1 AND is_latest = 1 AND updated_at > ?2",
+ )?,
+ })
+}
+
/// Materialise one row from the briefing's recent-pages / rules queries
/// into a [`BriefingPage`]. The row shape is `(path, title, kind,
/// updated_at_us)` — all queries above MUST select those columns in
diff --git a/crates/ai-memory-web/src/lib.rs b/crates/ai-memory-web/src/lib.rs
index dbc22639..586d1fcb 100644
--- a/crates/ai-memory-web/src/lib.rs
+++ b/crates/ai-memory-web/src/lib.rs
@@ -14,6 +14,10 @@
//! - `GET /search?q=…` → FTS5 hit list
//! - `GET /static/*` → embedded CSS + logos
//!
+//! The companion `api_router` exposes the same read-only data as JSON
+//! for custom frontends. It intentionally does not expose write/admin
+//! operations.
+//!
//! Theme follows `prefers-color-scheme` via the included Tailwind
//! stylesheet; no JS toggle, no cookie.
@@ -37,3 +41,13 @@ pub fn router(reader: ReaderPool, wiki: Wiki) -> Router {
let state = Arc::new(WebState::new(reader, wiki));
routes::build(state)
}
+
+/// Build the read-only JSON API router for third-party web UIs.
+///
+/// The host should `nest("/api/v1", api_router(...))` alongside `/web`
+/// so custom frontends can browse memory without reading SQLite or wiki
+/// files directly.
+pub fn api_router(reader: ReaderPool, wiki: Wiki) -> Router {
+ let state = Arc::new(WebState::new(reader, wiki));
+ routes::build_api(state)
+}
diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rs
new file mode 100644
index 00000000..4a82b2e2
--- /dev/null
+++ b/crates/ai-memory-web/src/routes/api.rs
@@ -0,0 +1,765 @@
+//! JSON routes for third-party read-only frontends.
+
+use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
+
+use ai_memory_core::{PageId, PagePath, ProjectId, WorkspaceId};
+use ai_memory_store::{BriefingSnapshot, HealthPage, PageHit, RelatedPage};
+use axum::extract::{Path, Query, RawQuery, State};
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::{Json, Router};
+use serde::{Deserialize, Serialize};
+
+use crate::state::WebState;
+
+/// Build the `/api/v1` router from a shared [`WebState`].
+pub(crate) fn build(state: Arc<WebState>) -> Router {
+ Router::new()
+ .route("/workspaces", axum::routing::get(workspaces_handler))
+ .route("/projects", axum::routing::get(projects_handler))
+ .route(
+ "/workspaces/{workspace}/projects/{project}/pages",
+ axum::routing::get(pages_handler),
+ )
+ .route(
+ "/workspaces/{workspace}/projects/{project}/pages/{*path}",
+ axum::routing::get(page_handler),
+ )
+ .route(
+ "/search",
+ axum::routing::get(search_handler).post(search_post_handler),
+ )
+ .route(
+ "/workspaces/{workspace}/projects/{project}/recent",
+ axum::routing::get(recent_handler),
+ )
+ .route(
+ "/workspaces/{workspace}/projects/{project}/briefing",
+ axum::routing::get(briefing_handler),
+ )
+ .route(
+ "/workspaces/{workspace}/overview",
+ axum::routing::get(overview_handler),
+ )
+ .route(
+ "/workspaces/{workspace}/projects/{project}/overview",
+ axum::routing::get(project_overview_handler),
+ )
+ .with_state(state)
+}
+
+async fn workspaces_handler(State(state): State<Arc<WebState>>) -> Result<Response, Response> {
+ let workspaces = state
+ .reader
+ .list_workspaces_with_stats()
+ .await
+ .map_err(internal_error)?;
+ Ok(Json(workspaces).into_response())
+}
+
+async fn projects_handler(
+ State(state): State<Arc<WebState>>,
+ Query(query): Query<ProjectListQuery>,
+) -> Result<Response, Response> {
+ let workspace = query
+ .workspace
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty());
+ let projects = if let Some(workspace) = workspace {
+ state
+ .reader
+ .list_projects_with_stats_for_workspace(workspace.to_owned())
+ .await
+ } else {
+ state.reader.list_projects_with_stats().await
+ }
+ .map_err(internal_error)?;
+ Ok(Json(projects).into_response())
+}
+
+async fn pages_handler(
+ State(state): State<Arc<WebState>>,
+ Path((workspace, project)): Path<(String, String)>,
+) -> Result<Response, Response> {
+ let _ = lookup_project(&state, &workspace, &project).await?;
+ let pages = state
+ .reader
+ .list_pages(&workspace, &project)
+ .await
+ .map_err(internal_error)?;
+ Ok(Json(pages).into_response())
+}
+
+async fn page_handler(
+ State(state): State<Arc<WebState>>,
+ Path((workspace, project, path)): Path<(String, String, String)>,
+) -> Result<Response, Response> {
+ let meta = state
+ .reader
+ .page_meta(&workspace, &project, &path)
+ .await
+ .map_err(internal_error)?
+ .ok_or_else(|| not_found("page not found"))?;
+
+ let page_path = PagePath::new(&path)
+ .map_err(|e| json_error(StatusCode::BAD_REQUEST, format!("invalid path: {e}")))?;
+ let markdown = state
+ .wiki
+ .read_page(meta.workspace_id, meta.project_id, &page_path)
+ .map_err(|_| not_found("page file not found"))?;
+
+ let links = state
+ .reader
+ .page_links(meta.workspace_id, meta.project_id, meta.path.clone())
+ .await
+ .map_err(internal_error)?;
+
+ Ok(Json(ApiPage {
+ backlinks: links.backlinks,
+ body_markdown: markdown.body,
+ created_at: meta.created_at,
+ frontmatter: markdown.frontmatter,
+ kind: meta.kind,
+ links: links.links,
+ path: meta.path,
+ pinned: meta.pinned,
+ project: meta.project_name,
+ supersedes: meta.supersedes,
+ tier: meta.tier,
+ title: meta.title,
+ updated_at: meta.updated_at,
+ workspace: meta.workspace_name,
+ })
+ .into_response())
+}
+
+async fn search_handler(
+ State(state): State<Arc<WebState>>,
+ RawQuery(raw_query): RawQuery,
+) -> Result<Response, Response> {
+ let query = SearchQuery::from_raw(raw_query.as_deref()).map_err(ApiFailure::into_response)?;
+ let request = query
+ .try_into_request()
+ .map_err(ApiFailure::into_response)?;
+ search_with_request(&state, request).await
+}
+
+async fn search_post_handler(
+ State(state): State<Arc<WebState>>,
+ Json(request): Json<SearchRequest>,
+) -> Result<Response, Response> {
+ search_with_request(&state, request).await
+}
+
+// NOTE (deferred): vector/semantic search. `ReaderPool::hybrid_search` already
+// RRF-fuses FTS5 + cosine over stored embeddings + link-graph expansion, but it
+// needs a query embedding — and `WebState` is read-only (reader + wiki), with no
+// embedder. Wiring true semantic search means injecting an embedding client into
+// `WebState` (touching `lib.rs`/`serve.rs`/`Cargo.toml`) and confirming the
+// embedding provider (Ollama) is reachable from the deployment. Until then this
+// handler stays FTS5-only. Link-graph "related pages" already ship via the
+// page-view `links`/`backlinks` (`ReaderPool::page_links`).
+async fn search_with_request(
+ state: &WebState,
+ request: SearchRequest,
+) -> Result<Response, Response> {
+ let term = request.q.trim().to_owned();
+ if term.is_empty() {
+ return Ok(Json(Vec::<ApiSearchHit>::new()).into_response());
+ }
+
+ let limit = request.limit.unwrap_or_else(default_limit).clamp(1, 100);
+ if !request.scopes.is_empty()
+ && (request
+ .workspace
+ .as_deref()
+ .is_some_and(|s| !s.trim().is_empty())
+ || request
+ .project
+ .as_deref()
+ .is_some_and(|s| !s.trim().is_empty()))
+ {
+ return Err(json_error(
+ StatusCode::BAD_REQUEST,
+ "scopes cannot be combined with workspace/project",
+ ));
+ }
+ let hits = match scoped_search_mode(state, &request).await? {
+ SearchMode::Global => state.reader.search_pages(term, limit).await,
+ SearchMode::Scoped(scopes) => search_scopes(state, scopes, term, limit).await,
+ }
+ .map_err(internal_error)?;
+
+ Ok(Json(enrich_hits(state, hits).await?).into_response())
+}
+
+async fn scoped_search_mode(
+ state: &WebState,
+ request: &SearchRequest,
+) -> Result<SearchMode, Response> {
+ if !request.scopes.is_empty() {
+ if request.scopes.len() > MAX_SEARCH_SCOPES {
+ return Err(json_error(
+ StatusCode::BAD_REQUEST,
+ format!("at most {MAX_SEARCH_SCOPES} scopes are allowed"),
+ ));
+ }
+ let scopes = resolve_scopes(state, &request.scopes).await?;
+ return Ok(SearchMode::Scoped(scopes));
+ }
+
+ match (
+ trimmed_opt(request.workspace.as_deref()),
+ trimmed_opt(request.project.as_deref()),
+ ) {
+ (Some(workspace), Some(project)) => {
+ let (workspace_id, project_id) = lookup_project(state, workspace, project).await?;
+ Ok(SearchMode::Scoped(vec![ResolvedSearchScope {
+ project_id,
+ workspace_id,
+ }]))
+ }
+ (Some(_), None) | (None, Some(_)) => Err(json_error(
+ StatusCode::BAD_REQUEST,
+ "workspace and project must be provided together",
+ )),
+ _ => Ok(SearchMode::Global),
+ }
+}
+
+async fn resolve_scopes(
+ state: &WebState,
+ scopes: &[ApiSearchScope],
+) -> Result<Vec<ResolvedSearchScope>, Response> {
+ let mut seen = HashSet::new();
+ let mut resolved = Vec::new();
+ for scope in scopes {
+ let workspace = trimmed_opt(Some(&scope.workspace)).ok_or_else(|| {
+ json_error(StatusCode::BAD_REQUEST, "scope workspace cannot be empty")
+ })?;
+ let project = trimmed_opt(Some(&scope.project))
+ .ok_or_else(|| json_error(StatusCode::BAD_REQUEST, "scope project cannot be empty"))?;
+ let (workspace_id, project_id) = lookup_project(state, workspace, project).await?;
+ if seen.insert((workspace_id, project_id)) {
+ resolved.push(ResolvedSearchScope {
+ project_id,
+ workspace_id,
+ });
+ }
+ }
+ Ok(resolved)
+}
+
+async fn search_scopes(
+ state: &WebState,
+ scopes: Vec<ResolvedSearchScope>,
+ term: String,
+ limit: usize,
+) -> ai_memory_store::StoreResult<Vec<PageHit>> {
+ let mut hits_by_id: HashMap<PageId, PageHit> = HashMap::new();
+ for scope in scopes {
+ let hits = state
+ .reader
+ .search_pages_for_project(scope.workspace_id, scope.project_id, term.clone(), limit)
+ .await?;
+ for hit in hits {
+ hits_by_id
+ .entry(hit.id)
+ .and_modify(|existing| {
+ if hit.rank < existing.rank {
+ *existing = hit.clone();
+ }
+ })
+ .or_insert(hit);
+ }
+ }
+ let mut hits: Vec<PageHit> = hits_by_id.into_values().collect();
+ hits.sort_by(|a, b| {
+ a.rank
+ .partial_cmp(&b.rank)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ });
+ hits.truncate(limit);
+ Ok(hits)
+}
+
+async fn recent_handler(
+ State(state): State<Arc<WebState>>,
+ Path((workspace, project)): Path<(String, String)>,
+ Query(query): Query<LimitQuery>,
+) -> Result<Response, Response> {
+ let _ = lookup_project(&state, &workspace, &project).await?;
+ let mut pages = state
+ .reader
+ .list_pages(&workspace, &project)
+ .await
+ .map_err(internal_error)?;
+ pages.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
+ pages.truncate(query.limit.clamp(1, 100));
+ Ok(Json(pages).into_response())
+}
+
+async fn briefing_handler(
+ State(state): State<Arc<WebState>>,
+ Path((workspace, project)): Path<(String, String)>,
+ Query(query): Query<LimitQuery>,
+) -> Result<Response, Response> {
+ let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;
+ let briefing = state
+ .reader
+ .briefing_for_project(workspace_id, project_id, query.limit.clamp(1, 100))
+ .await
+ .map_err(internal_error)?;
+ Ok(Json(briefing).into_response())
+}
+
+async fn overview_handler(
+ State(state): State<Arc<WebState>>,
+ Path(workspace): Path<String>,
+ Query(query): Query<LimitQuery>,
+) -> Result<Response, Response> {
+ let workspace_id = state
+ .reader
+ .find_workspace(workspace.clone())
+ .await
+ .map_err(internal_error)?
+ .ok_or_else(|| not_found(format!("workspace '{workspace}' not found")))?;
+
+ let handoff = match state
+ .reader
+ .latest_open_handoff_for_workspace(workspace_id)
+ .await
+ .map_err(internal_error)?
+ {
+ Some(h) => {
+ let project = state
+ .reader
+ .project_name_by_id(workspace_id, h.project_id)
+ .await
+ .map_err(internal_error)?
+ .unwrap_or_default();
+ Some(ApiHandoff {
+ agent: h.from_agent.as_str().to_owned(),
+ at: h.created_at.to_string(),
+ project,
+ summary: h.summary,
+ open_questions: h.open_questions,
+ next_steps: h.next_steps,
+ })
+ }
+ None => None,
+ };
+
+ let briefing = state
+ .reader
+ .briefing_for_workspace(workspace_id, query.limit.clamp(1, 100))
+ .await
+ .map_err(internal_error)?;
+
+ let (stale, duplicates, orphans) = state
+ .reader
+ .memory_health_for_workspace(workspace_id)
+ .await
+ .map_err(internal_error)?;
+ let detail = state
+ .reader
+ .health_detail_for_workspace(workspace_id, query.limit.clamp(1, 100))
+ .await
+ .map_err(internal_error)?;
+ let health = ApiHealth {
+ stale,
+ duplicates,
+ contradictions: 0,
+ orphans,
+ audited_at: None,
+ stale_pages: detail.stale,
+ duplicate_pages: detail.duplicates,
+ orphan_pages: detail.orphans,
+ };
+
+ Ok(Json(ApiOverview {
+ handoff,
+ briefing,
+ health,
+ })
+ .into_response())
+}
+
+async fn project_overview_handler(
+ State(state): State<Arc<WebState>>,
+ Path((workspace, project)): Path<(String, String)>,
+ Query(query): Query<LimitQuery>,
+) -> Result<Response, Response> {
+ let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;
+ let limit = query.limit.clamp(1, 100);
+
+ let handoff = state
+ .reader
+ .latest_open_handoff(workspace_id, project_id, None)
+ .await
+ .map_err(internal_error)?
+ .map(|h| ApiHandoff {
+ agent: h.from_agent.as_str().to_owned(),
+ at: h.created_at.to_string(),
+ project: project.clone(),
+ summary: h.summary,
+ open_questions: h.open_questions,
+ next_steps: h.next_steps,
+ });
+
+ let briefing = state
+ .reader
+ .briefing_for_project(workspace_id, project_id, limit)
+ .await
+ .map_err(internal_error)?;
+
+ let (stale, duplicates, orphans) = state
+ .reader
+ .memory_health_for_project(workspace_id, project_id)
+ .await
+ .map_err(internal_error)?;
+ let detail = state
+ .reader
+ .health_detail_for_project(workspace_id, project_id, limit)
+ .await
+ .map_err(internal_error)?;
+ let health = ApiHealth {
+ stale,
+ duplicates,
+ contradictions: 0,
+ orphans,
+ audited_at: None,
+ stale_pages: detail.stale,
+ duplicate_pages: detail.duplicates,
+ orphan_pages: detail.orphans,
+ };
+
+ Ok(Json(ApiOverview {
+ handoff,
+ briefing,
+ health,
+ })
+ .into_response())
+}
+
+async fn lookup_project(
+ state: &WebState,
+ workspace: &str,
+ project: &str,
+) -> Result<(WorkspaceId, ProjectId), Response> {
+ let workspace_id = state
+ .reader
+ .find_workspace(workspace.to_owned())
+ .await
+ .map_err(internal_error)?
+ .ok_or_else(|| not_found(format!("workspace '{workspace}' not found")))?;
+ let project_id = state
+ .reader
+ .find_project(workspace_id, project.to_owned())
+ .await
+ .map_err(internal_error)?
+ .ok_or_else(|| not_found(format!("project '{project}' not found")))?;
+ Ok((workspace_id, project_id))
+}
+
+async fn enrich_hits(state: &WebState, hits: Vec<PageHit>) -> Result<Vec<ApiSearchHit>, Response> {
+ let mut out = Vec::with_capacity(hits.len());
+ for hit in hits {
+ if let Some(meta) = state
+ .reader
+ .page_meta_by_id(hit.id)
+ .await
+ .map_err(internal_error)?
+ {
+ out.push(ApiSearchHit {
+ kind: meta.kind,
+ path: meta.path,
+ project: meta.project_name,
+ rank: hit.rank,
+ snippet: hit.snippet,
+ title: hit.title,
+ workspace: meta.workspace_name,
+ });
+ }
+ }
+ Ok(out)
+}
+
+fn internal_error(e: impl std::fmt::Display) -> Response {
+ json_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
+}
+
+fn not_found(message: impl Into<String>) -> Response {
+ json_error(StatusCode::NOT_FOUND, message)
+}
+
+fn json_error(status: StatusCode, message: impl Into<String>) -> Response {
+ (
+ status,
+ Json(ErrorResponse {
+ error: message.into(),
+ }),
+ )
+ .into_response()
+}
+
+fn default_limit() -> usize {
+ 10
+}
+
+const MAX_SEARCH_SCOPES: usize = 25;
+
+#[derive(Debug, Deserialize)]
+struct ProjectListQuery {
+ #[serde(default)]
+ workspace: Option<String>,
+}
+
+#[derive(Debug)]
+struct SearchQuery {
+ q: String,
+ workspace: Option<String>,
+ project: Option<String>,
+ scope: Vec<String>,
+ limit: usize,
+}
+
+impl SearchQuery {
+ fn from_raw(raw_query: Option<&str>) -> ApiParseResult<Self> {
+ let mut query = Self {
+ limit: default_limit(),
+ project: None,
+ q: String::new(),
+ scope: Vec::new(),
+ workspace: None,
+ };
+ let Some(raw_query) = raw_query else {
+ return Ok(query);
+ };
+ for pair in raw_query.split('&').filter(|pair| !pair.is_empty()) {
+ let (raw_key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
+ let key = decode_query_component(raw_key)?;
+ let value = decode_query_component(raw_value)?;
+ match key.as_str() {
+ "limit" => {
+ query.limit = value
+ .parse::<usize>()
+ .map_err(|_| ApiFailure::bad_request("limit must be an integer"))?;
+ }
+ "project" => query.project = Some(value),
+ "q" | "query" => query.q = value,
+ "scope" => query.scope.push(value),
+ "workspace" => query.workspace = Some(value),
+ _ => {}
+ }
+ }
+ Ok(query)
+ }
+
+ fn try_into_request(self) -> ApiParseResult<SearchRequest> {
+ let scopes = self
+ .scope
+ .iter()
+ .flat_map(|raw| raw.split(','))
+ .map(str::trim)
+ .filter(|scope| !scope.is_empty())
+ .map(parse_scope_param)
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(SearchRequest {
+ limit: Some(self.limit),
+ project: self.project,
+ q: self.q,
+ scopes,
+ workspace: self.workspace,
+ })
+ }
+}
+
+#[derive(Debug, Deserialize)]
+struct SearchRequest {
+ #[serde(default, alias = "query")]
+ q: String,
+ #[serde(default)]
+ workspace: Option<String>,
+ #[serde(default)]
+ project: Option<String>,
+ #[serde(default)]
+ scopes: Vec<ApiSearchScope>,
+ #[serde(default)]
+ limit: Option<usize>,
+}
+
+#[derive(Debug, Deserialize)]
+struct ApiSearchScope {
+ workspace: String,
+ project: String,
+}
+
+#[derive(Debug)]
+struct ResolvedSearchScope {
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+}
+
+#[derive(Debug)]
+enum SearchMode {
+ Global,
+ Scoped(Vec<ResolvedSearchScope>),
+}
+
+#[derive(Debug, Deserialize)]
+struct LimitQuery {
+ #[serde(default = "default_limit")]
+ limit: usize,
+}
+
+#[derive(Debug, Serialize)]
+struct ApiPage {
+ workspace: String,
+ project: String,
+ path: String,
+ title: String,
+ kind: String,
+ tier: String,
+ pinned: bool,
+ created_at: String,
+ updated_at: String,
+ supersedes: Option<String>,
+ frontmatter: serde_json::Value,
+ body_markdown: String,
+ /// Latest pages this page references (resolved outgoing links).
+ links: Vec<RelatedPage>,
+ /// Latest pages that reference this page (incoming back-links).
+ backlinks: Vec<RelatedPage>,
+}
+
+#[derive(Debug, Serialize)]
+struct ApiSearchHit {
+ workspace: String,
+ project: String,
+ path: String,
+ title: String,
+ kind: String,
+ snippet: String,
+ rank: f64,
+}
+
+#[derive(Debug, Serialize)]
+struct ApiOverview {
+ handoff: Option<ApiHandoff>,
+ briefing: BriefingSnapshot,
+ health: ApiHealth,
+}
+
+#[derive(Debug, Serialize)]
+struct ApiHandoff {
+ agent: String,
+ at: String,
+ project: String,
+ summary: String,
+ open_questions: Vec<String>,
+ next_steps: Vec<String>,
+}
+
+#[derive(Debug, Serialize)]
+struct ApiHealth {
+ stale: u64,
+ duplicates: u64,
+ contradictions: u64,
+ orphans: u64,
+ audited_at: Option<String>,
+ /// Capped drill-down lists explaining each counter.
+ stale_pages: Vec<HealthPage>,
+ duplicate_pages: Vec<HealthPage>,
+ orphan_pages: Vec<HealthPage>,
+}
+
+#[derive(Debug, Serialize)]
+struct ErrorResponse {
+ error: String,
+}
+
+type ApiParseResult<T> = Result<T, ApiFailure>;
+
+#[derive(Debug)]
+struct ApiFailure {
+ message: String,
+ status: StatusCode,
+}
+
+impl ApiFailure {
+ fn bad_request(message: impl Into<String>) -> Self {
+ Self {
+ message: message.into(),
+ status: StatusCode::BAD_REQUEST,
+ }
+ }
+
+ fn into_response(self) -> Response {
+ json_error(self.status, self.message)
+ }
+}
+
+fn parse_scope_param(raw: &str) -> ApiParseResult<ApiSearchScope> {
+ let Some((workspace, project)) = raw.split_once('/') else {
+ return Err(ApiFailure::bad_request(
+ "scope must use the workspace/project format",
+ ));
+ };
+ let workspace = workspace.trim();
+ let project = project.trim();
+ if workspace.is_empty() || project.is_empty() || project.contains('/') {
+ return Err(ApiFailure::bad_request(
+ "scope must use the workspace/project format",
+ ));
+ }
+ Ok(ApiSearchScope {
+ project: project.to_owned(),
+ workspace: workspace.to_owned(),
+ })
+}
+
+fn trimmed_opt(value: Option<&str>) -> Option<&str> {
+ value.map(str::trim).filter(|s| !s.is_empty())
+}
+
+fn decode_query_component(raw: &str) -> ApiParseResult<String> {
+ let mut bytes = Vec::with_capacity(raw.len());
+ let raw_bytes = raw.as_bytes();
+ let mut i = 0;
+ while i < raw_bytes.len() {
+ match raw_bytes[i] {
+ b'+' => {
+ bytes.push(b' ');
+ i += 1;
+ }
+ b'%' => {
+ if i + 2 >= raw_bytes.len() {
+ return Err(ApiFailure::bad_request("invalid percent-encoding in query"));
+ }
+ let hi = hex_value(raw_bytes[i + 1])
+ .ok_or_else(|| ApiFailure::bad_request("invalid percent-encoding in query"))?;
+ let lo = hex_value(raw_bytes[i + 2])
+ .ok_or_else(|| ApiFailure::bad_request("invalid percent-encoding in query"))?;
+ bytes.push((hi << 4) | lo);
+ i += 3;
+ }
+ byte => {
+ bytes.push(byte);
+ i += 1;
+ }
+ }
+ }
+ String::from_utf8(bytes).map_err(|_| ApiFailure::bad_request("query must be valid UTF-8"))
+}
+
+fn hex_value(byte: u8) -> Option<u8> {
+ match byte {
+ b'0'..=b'9' => Some(byte - b'0'),
+ b'a'..=b'f' => Some(byte - b'a' + 10),
+ b'A'..=b'F' => Some(byte - b'A' + 10),
+ _ => None,
+ }
+}
diff --git a/crates/ai-memory-web/src/routes/mod.rs b/crates/ai-memory-web/src/routes/mod.rs
index 19c1da2d..3e675d8d 100644
--- a/crates/ai-memory-web/src/routes/mod.rs
+++ b/crates/ai-memory-web/src/routes/mod.rs
@@ -7,6 +7,7 @@ use axum::routing::get;
use crate::state::WebState;
+mod api;
mod index;
mod page;
mod project;
@@ -25,3 +26,8 @@ pub(crate) fn build(state: Arc<WebState>) -> Router {
.route("/static/logo-dark.png", get(statics::logo_dark))
.with_state(state)
}
+
+/// Build the read-only JSON API router from a shared [`WebState`].
+pub(crate) fn build_api(state: Arc<WebState>) -> Router {
+ api::build(state)
+}
diff --git a/crates/ai-memory-web/tests/routes.rs b/crates/ai-memory-web/tests/routes.rs
index 3deccf46..ca7f0d2e 100644
--- a/crates/ai-memory-web/tests/routes.rs
+++ b/crates/ai-memory-web/tests/routes.rs
@@ -3,12 +3,13 @@
//! Spins up a `Store` + `Wiki` in a tempdir, seeds two pages, builds
//! the router, and exercises each route via `tower::ServiceExt::oneshot`.
-use ai_memory_core::{NewPage, PagePath, Tier};
+use ai_memory_core::{AgentKind, NewHandoff, NewPage, PagePath, Tier};
use ai_memory_store::Store;
-use ai_memory_web::router;
+use ai_memory_web::{api_router, router};
use ai_memory_wiki::{Wiki, WritePageRequest};
use axum::body::Body;
-use axum::http::{Request, StatusCode};
+use axum::http::{Method, Request, StatusCode};
+use serde_json::Value;
use tempfile::TempDir;
use tower::ServiceExt;
@@ -272,3 +273,1185 @@ async fn smoke_page_not_found_returns_404() {
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
+
+#[tokio::test]
+async fn api_projects_returns_project_stats() {
+ 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, "scratch", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(ws, proj, "foo.md", "Foo Page", "Hello world"))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/projects")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json[0]["workspace_name"], "default");
+ assert_eq!(json[0]["project_name"], "scratch");
+ assert_eq!(json[0]["page_count"], 1);
+}
+
+#[tokio::test]
+async fn api_workspaces_returns_workspace_stats() {
+ let (_tmp, store, wiki) = setup().await;
+ let default_ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let practice_ws = store
+ .writer
+ .get_or_create_workspace("practice")
+ .await
+ .unwrap();
+ let scratch = store
+ .writer
+ .get_or_create_project(default_ws, "scratch", None)
+ .await
+ .unwrap();
+ let testing = store
+ .writer
+ .get_or_create_project(practice_ws, "unit-testing", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ default_ws,
+ scratch,
+ "foo.md",
+ "Foo Page",
+ "Hello world",
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ practice_ws,
+ testing,
+ "patterns.md",
+ "Testing Patterns",
+ "Shared testing notes",
+ ))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json.as_array().unwrap().len(), 2);
+ assert_eq!(json[0]["workspace_name"], "default");
+ assert_eq!(json[0]["project_count"], 1);
+ assert_eq!(json[0]["page_count"], 1);
+ assert_eq!(json[1]["workspace_name"], "practice");
+}
+
+#[tokio::test]
+async fn api_projects_can_filter_by_workspace() {
+ let (_tmp, store, wiki) = setup().await;
+ let default_ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let practice_ws = store
+ .writer
+ .get_or_create_workspace("practice")
+ .await
+ .unwrap();
+ let scratch = store
+ .writer
+ .get_or_create_project(default_ws, "scratch", None)
+ .await
+ .unwrap();
+ let testing = store
+ .writer
+ .get_or_create_project(practice_ws, "unit-testing", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ default_ws, scratch, "foo.md", "Foo Page", "default",
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ practice_ws,
+ testing,
+ "patterns.md",
+ "Testing Patterns",
+ "practice",
+ ))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/projects?workspace=practice")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json.as_array().unwrap().len(), 1);
+ assert_eq!(json[0]["workspace_name"], "practice");
+ assert_eq!(json[0]["project_name"], "unit-testing");
+}
+
+#[tokio::test]
+async fn api_pages_returns_latest_pages_only() {
+ 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, "scratch", None)
+ .await
+ .unwrap();
+ wiki.write_page(wiki_req(ws, proj, "foo.md", "# First\n\nOld"))
+ .await
+ .unwrap();
+ wiki.write_page(wiki_req(ws, proj, "foo.md", "# Second\n\nNew"))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json.as_array().unwrap().len(), 1);
+ assert_eq!(json[0]["path"], "foo.md");
+ assert_eq!(json[0]["title"], "Second");
+}
+
+#[tokio::test]
+async fn api_pages_derives_kind_from_path_when_frontmatter_absent() {
+ 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, "scratch", None)
+ .await
+ .unwrap();
+
+ // Page WITHOUT a `kind` in its frontmatter, sitting under `decisions/`.
+ // The reader must derive `kind = "decision"` from the path.
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new("decisions/adr-x.md").unwrap(),
+ title: "ADR X".to_owned(),
+ body: "A decision".to_owned(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ })
+ .await
+ .unwrap();
+
+ // Page WITH an explicit `kind = "rule"` in its frontmatter, sitting at
+ // a path that would otherwise derive `fact`. The explicit kind must win.
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new("notes/anything.md").unwrap(),
+ title: "Explicit Rule".to_owned(),
+ body: "An explicit rule".to_owned(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({"kind": "rule"}),
+ pinned: false,
+ links: Vec::new(),
+ })
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ let pages = json.as_array().unwrap();
+
+ let decision = pages
+ .iter()
+ .find(|p| p["path"] == "decisions/adr-x.md")
+ .expect("decisions/adr-x.md present");
+ assert_eq!(
+ decision["kind"], "decision",
+ "kind derived from `decisions/` path when frontmatter has none"
+ );
+
+ let rule = pages
+ .iter()
+ .find(|p| p["path"] == "notes/anything.md")
+ .expect("notes/anything.md present");
+ assert_eq!(
+ rule["kind"], "rule",
+ "explicit frontmatter kind wins over path derivation"
+ );
+}
+
+#[tokio::test]
+async fn api_page_returns_markdown_and_metadata() {
+ 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, "scratch", None)
+ .await
+ .unwrap();
+ wiki.write_page(wiki_req(ws, proj, "foo.md", "# Foo\n\nHello world"))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages/foo.md")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["workspace"], "default");
+ assert_eq!(json["project"], "scratch");
+ assert_eq!(json["path"], "foo.md");
+ assert_eq!(json["title"], "Foo");
+ assert_eq!(json["frontmatter"]["kind"], "fact");
+ assert!(
+ json["body_markdown"]
+ .as_str()
+ .unwrap()
+ .contains("Hello world")
+ );
+}
+
+#[tokio::test]
+async fn api_search_can_scope_to_project() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let scratch = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let other = store
+ .writer
+ .get_or_create_project(ws, "other", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ ws,
+ scratch,
+ "foo.md",
+ "Scratch Page",
+ "shared_unique_term",
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ ws,
+ other,
+ "bar.md",
+ "Other Page",
+ "shared_unique_term",
+ ))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/search?q=shared_unique_term&workspace=default&project=scratch&limit=1")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json.as_array().unwrap().len(), 1);
+ assert_eq!(json[0]["project"], "scratch");
+ assert_eq!(json[0]["title"], "Scratch Page");
+}
+
+#[tokio::test]
+async fn api_search_can_read_from_multiple_scopes() {
+ let (_tmp, store, wiki) = setup().await;
+ let client_ws = store
+ .writer
+ .get_or_create_workspace("client-a")
+ .await
+ .unwrap();
+ let practice_ws = store
+ .writer
+ .get_or_create_workspace("practice")
+ .await
+ .unwrap();
+ let product = store
+ .writer
+ .get_or_create_project(client_ws, "product", None)
+ .await
+ .unwrap();
+ let unit_testing = store
+ .writer
+ .get_or_create_project(practice_ws, "unit-testing", None)
+ .await
+ .unwrap();
+ let unrelated = store
+ .writer
+ .get_or_create_project(client_ws, "unrelated", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ client_ws,
+ product,
+ "product.md",
+ "Product Rules",
+ "shared_scope_token belongs to the product",
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ practice_ws,
+ unit_testing,
+ "patterns.md",
+ "Testing Patterns",
+ "shared_scope_token belongs to practice",
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ client_ws,
+ unrelated,
+ "hidden.md",
+ "Hidden Page",
+ "shared_scope_token must not appear",
+ ))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/search?q=shared_scope_token&scope=client-a/product&scope=practice/unit-testing")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ let hits = json.as_array().unwrap();
+ assert_eq!(hits.len(), 2);
+ assert!(hits.iter().any(|hit| hit["project"] == "product"));
+ assert!(hits.iter().any(|hit| hit["project"] == "unit-testing"));
+ assert!(!hits.iter().any(|hit| hit["project"] == "unrelated"));
+}
+
+#[tokio::test]
+async fn api_search_post_accepts_multi_scope_body() {
+ let (_tmp, store, wiki) = setup().await;
+ let client_ws = store
+ .writer
+ .get_or_create_workspace("client-a")
+ .await
+ .unwrap();
+ let practice_ws = store
+ .writer
+ .get_or_create_workspace("practice")
+ .await
+ .unwrap();
+ let product = store
+ .writer
+ .get_or_create_project(client_ws, "product", None)
+ .await
+ .unwrap();
+ let unit_testing = store
+ .writer
+ .get_or_create_project(practice_ws, "unit-testing", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ client_ws,
+ product,
+ "product.md",
+ "Product Rules",
+ "post_scope_token belongs to the product",
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ practice_ws,
+ unit_testing,
+ "patterns.md",
+ "Testing Patterns",
+ "post_scope_token belongs to practice",
+ ))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let body = serde_json::json!({
+ "q": "post_scope_token",
+ "limit": 10,
+ "scopes": [
+ {"workspace": "client-a", "project": "product"},
+ {"workspace": "practice", "project": "unit-testing"}
+ ]
+ });
+ let req = Request::builder()
+ .method(Method::POST)
+ .uri("/search")
+ .header("content-type", "application/json")
+ .body(Body::from(body.to_string()))
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json.as_array().unwrap().len(), 2);
+}
+
+#[tokio::test]
+async fn api_routes_do_not_accept_writes() {
+ let (_tmp, store, wiki) = setup().await;
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .method(Method::POST)
+ .uri("/projects")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
+}
+
+#[tokio::test]
+async fn api_search_rejects_partial_scope() {
+ let (_tmp, store, wiki) = setup().await;
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/search?q=anything&workspace=default")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ json["error"],
+ "workspace and project must be provided together"
+ );
+}
+
+#[tokio::test]
+async fn api_search_rejects_malformed_scope_param() {
+ let (_tmp, store, wiki) = setup().await;
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/search?q=anything&scope=missing-project")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["error"], "scope must use the workspace/project format");
+}
+
+#[tokio::test]
+async fn api_search_rejects_ambiguous_scope_inputs() {
+ let (_tmp, store, wiki) = setup().await;
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/search?q=anything&workspace=default&project=scratch&scope=default/scratch")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ json["error"],
+ "scopes cannot be combined with workspace/project"
+ );
+}
+
+#[tokio::test]
+async fn api_project_routes_return_404_for_missing_project() {
+ let (_tmp, store, wiki) = setup().await;
+ store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces/default/projects/missing/pages")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+}
+
+#[tokio::test]
+async fn api_recent_and_briefing_return_project_data() {
+ 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, "scratch", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(ws, proj, "foo.md", "Foo Page", "Hello world"))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let recent_req = Request::builder()
+ .uri("/workspaces/default/projects/scratch/recent?limit=1")
+ .body(Body::empty())
+ .unwrap();
+ let recent_resp = app.clone().oneshot(recent_req).await.unwrap();
+ assert_eq!(recent_resp.status(), StatusCode::OK);
+
+ let briefing_req = Request::builder()
+ .uri("/workspaces/default/projects/scratch/briefing?limit=1")
+ .body(Body::empty())
+ .unwrap();
+ let briefing_resp = app.oneshot(briefing_req).await.unwrap();
+ assert_eq!(briefing_resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(briefing_resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["counts"]["pages_latest"], 1);
+ assert_eq!(json["recent_pages"][0]["path"], "foo.md");
+}
+
+#[tokio::test]
+async fn api_workspace_overview_returns_aggregated_overview() {
+ 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, "scratch", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(ws, proj, "foo.md", "Foo Page", "Hello world"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(ws, proj, "bar.md", "Bar Page", "Second page"))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces/default/overview?limit=10")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+
+ assert!(json.get("handoff").is_some(), "missing handoff key");
+ assert!(json["handoff"].is_null(), "expected null handoff");
+ assert!(json.get("briefing").is_some(), "missing briefing key");
+ assert_eq!(json["briefing"]["counts"]["pages_latest"], 2);
+
+ let health = &json["health"];
+ assert!(health.is_object(), "missing health object");
+ assert!(health.get("stale").is_some(), "missing health.stale");
+ assert!(
+ health.get("duplicates").is_some(),
+ "missing health.duplicates"
+ );
+ assert!(
+ health.get("contradictions").is_some(),
+ "missing health.contradictions"
+ );
+ assert!(health.get("orphans").is_some(), "missing health.orphans");
+ assert_eq!(health["contradictions"], 0);
+}
+
+#[tokio::test]
+async fn api_workspace_overview_aggregates_briefing_and_health() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let alpha = store
+ .writer
+ .get_or_create_project(ws, "alpha", None)
+ .await
+ .unwrap();
+ let beta = store
+ .writer
+ .get_or_create_project(ws, "beta", None)
+ .await
+ .unwrap();
+
+ // One normal page + one _rules/ page in each project, so we prove
+ // the overview endpoint aggregates across the whole workspace.
+ store
+ .writer
+ .upsert_page(new_page(ws, alpha, "intro.md", "Alpha Intro", "alpha body"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ ws,
+ alpha,
+ "_rules/style.md",
+ "Alpha Style Rule",
+ "always do X",
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(ws, beta, "intro.md", "Beta Intro", "beta body"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(
+ ws,
+ beta,
+ "_rules/naming.md",
+ "Beta Naming Rule",
+ "name things well",
+ ))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces/default/overview?limit=10")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+
+ // 4 pages total across both projects in the workspace.
+ assert_eq!(json["briefing"]["counts"]["pages_latest"], 4);
+
+ // rules aggregates the _rules/ pages from BOTH projects.
+ let rules = json["briefing"]["rules"].as_array().expect("rules array");
+ assert_eq!(rules.len(), 2, "expected both _rules pages: {rules:?}");
+ let rule_paths: Vec<&str> = rules.iter().map(|r| r["path"].as_str().unwrap()).collect();
+ assert!(rule_paths.contains(&"_rules/style.md"));
+ assert!(rule_paths.contains(&"_rules/naming.md"));
+
+ // Health: no contradictions, every page is an orphan (new_page uses
+ // empty links), so orphans == total page count.
+ assert_eq!(json["health"]["contradictions"], 0);
+ assert_eq!(json["health"]["orphans"], 4);
+}
+
+#[tokio::test]
+async fn api_workspace_overview_includes_open_handoff() {
+ 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, "scratch", None)
+ .await
+ .unwrap();
+
+ store
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "handoff_summary_marker".into(),
+ open_questions: vec!["open_question_marker".into()],
+ next_steps: vec!["next_step_marker".into()],
+ files_touched: vec![],
+ })
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces/default/overview")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+
+ let handoff = &json["handoff"];
+ assert!(!handoff.is_null(), "expected a non-null handoff: {json}");
+ assert_eq!(handoff["summary"], "handoff_summary_marker");
+ assert_eq!(handoff["open_questions"][0], "open_question_marker");
+ assert_eq!(handoff["next_steps"][0], "next_step_marker");
+ assert_eq!(handoff["project"], "scratch");
+ assert_eq!(handoff["agent"], "claude-code");
+}
+
+#[tokio::test]
+async fn api_project_overview_aggregates_handoff_briefing_health() {
+ 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, "scratch", None)
+ .await
+ .unwrap();
+ // Another project that must NOT bleed into the scratch overview.
+ let other = store
+ .writer
+ .get_or_create_project(ws, "other", None)
+ .await
+ .unwrap();
+
+ store
+ .writer
+ .upsert_page(new_page(ws, proj, "alpha.md", "Alpha", "body"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(ws, other, "beta.md", "Beta", "body"))
+ .await
+ .unwrap();
+
+ store
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "scratch_handoff_marker".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ })
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces/default/projects/scratch/overview")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+
+ // Handoff is the scratch one, scoped to the project.
+ assert_eq!(json["handoff"]["summary"], "scratch_handoff_marker");
+ assert_eq!(json["handoff"]["project"], "scratch");
+
+ // Briefing + health count only the scratch page, not other/beta.md.
+ assert_eq!(json["briefing"]["counts"]["pages_latest"], 1);
+ let orphans = json["health"]["orphan_pages"]
+ .as_array()
+ .expect("orphan_pages");
+ let orphan_paths: Vec<&str> = orphans.iter().filter_map(|p| p["path"].as_str()).collect();
+ assert_eq!(
+ orphan_paths,
+ vec!["alpha.md"],
+ "scoped to scratch only: {json}"
+ );
+}
+
+#[tokio::test]
+async fn api_workspace_overview_health_detail_lists_pages() {
+ 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, "scratch", None)
+ .await
+ .unwrap();
+
+ // All three pages are orphans (no links). Two share a title → duplicates.
+ store
+ .writer
+ .upsert_page(new_page(ws, proj, "alpha.md", "Alpha", "body"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(ws, proj, "dup-a.md", "SharedTitle", "body a"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(new_page(ws, proj, "dup-b.md", "SharedTitle", "body b"))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces/default/overview")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ let health = &json["health"];
+
+ let orphans = health["orphan_pages"]
+ .as_array()
+ .expect("orphan_pages array");
+ let orphan_paths: Vec<&str> = orphans.iter().filter_map(|p| p["path"].as_str()).collect();
+ assert!(
+ orphan_paths.contains(&"alpha.md"),
+ "orphan list should include the unlinked page: {health}"
+ );
+ assert_eq!(orphans.len(), 3, "all three pages are orphans");
+
+ let dups = health["duplicate_pages"]
+ .as_array()
+ .expect("duplicate_pages array");
+ let dup_paths: Vec<&str> = dups.iter().filter_map(|p| p["path"].as_str()).collect();
+ assert!(dup_paths.contains(&"dup-a.md") && dup_paths.contains(&"dup-b.md"));
+ assert!(dups.iter().all(|p| p["title"] == "SharedTitle"));
+ assert!(
+ health["stale_pages"]
+ .as_array()
+ .expect("stale_pages array")
+ .is_empty(),
+ "freshly-written pages are not stale"
+ );
+}
+
+#[tokio::test]
+async fn api_page_returns_resolved_links_and_backlinks() {
+ 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, "scratch", None)
+ .await
+ .unwrap();
+
+ // Target page first so the source's link resolves on write.
+ wiki.write_page(wiki_req(
+ ws,
+ proj,
+ "decisions/target.md",
+ "# Target\n\nThe canonical decision.",
+ ))
+ .await
+ .unwrap();
+ // Source links to the target via a wikilink (resolves to decisions/target.md).
+ wiki.write_page(wiki_req(
+ ws,
+ proj,
+ "notes/source.md",
+ "# Source\n\nSee [[decisions/target]] for the rationale.",
+ ))
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+
+ // Source page exposes the outgoing link, no back-links.
+ let src_req = Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages/notes/source.md")
+ .body(Body::empty())
+ .unwrap();
+ let src_resp = app.clone().oneshot(src_req).await.unwrap();
+ assert_eq!(src_resp.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(src_resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let src: Value = serde_json::from_slice(&body).unwrap();
+ let links = src["links"].as_array().expect("links array");
+ assert_eq!(links.len(), 1, "source has one outgoing link: {src}");
+ assert_eq!(links[0]["path"], "decisions/target.md");
+ // `wiki_req` writes an explicit `kind: fact` frontmatter, which the
+ // resolver surfaces verbatim on the related-page row.
+ assert_eq!(links[0]["kind"], "fact");
+ assert!(
+ src["backlinks"]
+ .as_array()
+ .expect("backlinks array")
+ .is_empty(),
+ "source has no back-links"
+ );
+
+ // Target page exposes the incoming back-link, no outgoing links.
+ let tgt_req = Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages/decisions/target.md")
+ .body(Body::empty())
+ .unwrap();
+ let tgt_resp = app.oneshot(tgt_req).await.unwrap();
+ assert_eq!(tgt_resp.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(tgt_resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let tgt: Value = serde_json::from_slice(&body).unwrap();
+ let backlinks = tgt["backlinks"].as_array().expect("backlinks array");
+ assert_eq!(backlinks.len(), 1, "target has one back-link: {tgt}");
+ assert_eq!(backlinks[0]["path"], "notes/source.md");
+ assert!(
+ tgt["links"].as_array().expect("links array").is_empty(),
+ "target has no outgoing links"
+ );
+}
+
+#[tokio::test]
+async fn api_page_returns_404_for_missing_page() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+
+ // workspace/project existem, mas a página não → 404 (não 500)
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages/does/not/exist.md")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["error"], "page not found");
+}
+
+#[tokio::test]
+async fn api_search_empty_query_returns_empty_array() {
+ let (_tmp, store, wiki) = setup().await;
+
+ // q só com espaços (%20) → termo vazio após trim → 200 com [] (sem tocar o FTS)
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/search?q=%20%20")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert!(
+ json.as_array().expect("array").is_empty(),
+ "empty query yields no hits: {json}"
+ );
+}
+
+#[tokio::test]
+async fn api_search_rejects_non_integer_limit() {
+ let (_tmp, store, wiki) = setup().await;
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/search?q=anything&limit=abc")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["error"], "limit must be an integer");
+}
+
+#[tokio::test]
+async fn api_search_rejects_invalid_percent_encoding() {
+ let (_tmp, store, wiki) = setup().await;
+
+ // %zz não é hex válido → o decoder manual da querystring rejeita com 400
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/search?q=%zz")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["error"], "invalid percent-encoding in query");
+}
diff --git a/deny.toml b/deny.toml
index 32f3c6b0..e80e4620 100644
--- a/deny.toml
+++ b/deny.toml
@@ -28,7 +28,6 @@ allow = [
"BSD-2-Clause",
"BSD-3-Clause",
"ISC",
- "Unicode-DFS-2016",
"Unicode-3.0",
"Zlib",
"MPL-2.0",
diff --git a/docker/Dockerfile b/docker/Dockerfile
index e87a9173..09b60b9e 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -14,7 +14,7 @@
FROM rust:1.95-slim-bookworm AS builder
WORKDIR /work
RUN apt-get update \
- && apt-get install -y --no-install-recommends pkg-config build-essential curl \
+ && apt-get install -y --no-install-recommends pkg-config build-essential curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
COPY Cargo.toml Cargo.lock rust-toolchain.toml deny.toml ./
COPY crates ./crates