Skip to content

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

Rust

feat(web): recall trace on project search and a root-only health panel

AkitaOnRails6e85985fedc0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ebd12125..212f0ef0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added a recall trace to web search. A project page has its own search box,
+ and a search with `workspace` and `project`
+ (`/web/search?q=…&workspace=…&project=…`) now ranks with the same hybrid
+ ranker as `memory_query` for that project: FTS5, entity, vector, graph and
+ observation streams, the authority adjustment, and the reranker when one is
+ configured. The server now hands its configured embedder and reranker to the
+ web UI, and the reranker's four-call concurrency limit is shared with
+ `memory_query`. With "Explain ranking" (`explain=1`) each hit shows its rank,
+ raw score and RRF contribution in every stream, the fused score, the
+ authority multiplier, and the intent boost and rerank score when present;
+ the page also lists the streams that ran, the embedder and reranker in use,
+ and each stream's time in milliseconds. A scoped `/api/v1/search` (one
+ project or `scopes`) uses the same ranker, so it returns the same order as
+ `memory_query`, and its `rank` is now the fused rank. A search without a
+ scope is still the cross-project FTS5 search, as `memory_query(global=true)`
+ is. Project search follows the per-project read rule: a viewer without a
+ grant on a restricted project gets a 403 and no trace, and an unknown project
+ is a 404.
+- Added a root-only server health page at `/web/health`, linked from the web UI
+ header. It shows the hook counters since the server started (accepted, shed
+ with 429 by saturation or rate limit, stored, failed, dropped), the writer
+ queue depth, the hook spool and recovery journal in the server's data
+ directory, the consolidation queue (last completion, pending, running,
+ completed and failed jobs), the configured embedder, both providers' status
+ and the stored vector identities. Failing checks are listed with the command
+ that fixes them, the same lines `ai-memory status` prints: `ai-memory
+ recover` for a backed-up spool or journal, `ai-memory compact --confirm` for
+ reclaimable space, `ai-memory embed` for pages without vectors, `ai-memory
+ embed --force` for vectors made under another model, and the LLM provider's
+ retry command. The page is read-only and is gated like `/web/pending`: on a
+ multi-user server anonymous requests get a 401 and database users a 403. It
+ never shows provider error text, page content or project names.
- Added page history and session replay to the read-only web UI. Each page
links to its history (`/web/w/<ws>/<proj>/h/<path>`): every stored version,
newest first, superseded ones included, so a version a concurrent write
diff --git a/Cargo.lock b/Cargo.lock
index 36e2d0da..bf097a07 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -215,6 +215,7 @@ dependencies = [
"ai-memory-hooks",
"ai-memory-llm",
"ai-memory-store",
+ "ai-memory-web",
"ai-memory-wiki",
"anyhow",
"async-trait",
@@ -276,10 +277,12 @@ name = "ai-memory-web"
version = "2.6.5"
dependencies = [
"ai-memory-core",
+ "ai-memory-llm",
"ai-memory-store",
"ai-memory-wiki",
"anyhow",
"askama",
+ "async-trait",
"axum",
"base64 0.22.1",
"jiff",
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 915773ec..55bcd2d5 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -1766,6 +1766,21 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
base_href: &base_href,
base_path: &base_path,
trusted_proxy_identity: trusted_proxy_identity_enabled(&config.auth),
+ // The same embedder and rerank stage `memory_query`
+ // holds (the stage shares its concurrency gate), so web
+ // project search ranks like the MCP tool.
+ recall: ai_memory_web::Recall {
+ embedder: embedder.clone(),
+ rerank: server.rerank_stage(),
+ },
+ health: Some(Arc::new(ai_memory_web::health::HealthSources {
+ ingest: ingest_metrics.clone(),
+ providers: provider_health.clone(),
+ probe: Arc::new(ServeHealthProbe {
+ writer: store.writer.clone(),
+ data_dir: config.data_dir.clone(),
+ }),
+ })),
},
)?;
// HTML navigational 401/403 → builtin login / change-password.
@@ -2865,6 +2880,38 @@ fn configure_consolidator(
})
}
+/// What the web health page reads from this process: the writer queue,
+/// and the hook spool and recovery journal under this server's data
+/// directory (a hook client on another machine spools there, not here).
+struct ServeHealthProbe {
+ writer: ai_memory_store::WriterHandle,
+ data_dir: std::path::PathBuf,
+}
+
+impl ai_memory_web::health::HealthProbe for ServeHealthProbe {
+ fn process_state(&self) -> ai_memory_web::health::ProcessState {
+ use ai_memory_web::health::{JournalState, ProcessState, SpoolState};
+ let spool = super::hook_spool::spool_health(&super::hook_spool::spool_dir(&self.data_dir));
+ let (pending, degraded, finish_failed, error) =
+ super::recovery::journal_summary(&self.data_dir);
+ ProcessState {
+ write_queue: Some(self.writer.queue_depth()),
+ spool: Some(SpoolState {
+ pending: spool.pending,
+ oldest_age_ms: spool.oldest_age_ms,
+ retries_total: spool.retries_total,
+ capacity: spool.capacity,
+ }),
+ journal: Some(JournalState {
+ pending,
+ degraded,
+ finish_failed,
+ unreadable: error.is_some(),
+ }),
+ }
+ }
+}
+
/// Validate a list of CORS origins before the server binds.
///
/// Rules match the spec: wildcard + credentials is forbidden, each entry
@@ -5847,6 +5894,8 @@ mod tests {
base_href: "/web/",
base_path: "",
trusted_proxy_identity: false,
+ recall: ai_memory_web::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -5949,6 +5998,8 @@ mod tests {
base_href: "/web/",
base_path: "",
trusted_proxy_identity: false,
+ recall: ai_memory_web::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -6021,6 +6072,8 @@ mod tests {
base_href: "/web/",
base_path: "",
trusted_proxy_identity: false,
+ recall: ai_memory_web::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -6167,6 +6220,8 @@ mod tests {
base_href: "/web/",
base_path: "",
trusted_proxy_identity: false,
+ recall: ai_memory_web::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -6229,6 +6284,8 @@ mod tests {
base_href: "/",
base_path: "",
trusted_proxy_identity: false,
+ recall: ai_memory_web::Recall::default(),
+ health: None,
},
)
.unwrap();
diff --git a/crates/ai-memory-cli/src/commands/status.rs b/crates/ai-memory-cli/src/commands/status.rs
index 1b3a6d65..0b87ea75 100644
--- a/crates/ai-memory-cli/src/commands/status.rs
+++ b/crates/ai-memory-cli/src/commands/status.rs
@@ -4,6 +4,7 @@
//! server; renders the response as human text or JSON. Never opens
//! the store directly — the server is the source of truth.
+use ai_memory_core::fix_lines;
use ai_memory_llm::{ProviderHealthSnapshot, ProviderHealthStatus, ProviderRoleHealthSnapshot};
use anyhow::Result;
use serde::{Deserialize, Serialize};
@@ -115,15 +116,6 @@ struct Derived {
stale_links_from_latest_pages: u64,
}
-/// Suggest compaction only above this share of the file. Below it the
-/// exclusive lock costs more than the space is worth, and SQLite will reuse
-/// those pages on its own as the store grows.
-const RECLAIM_ADVICE_PCT: f64 = 20.0;
-
-/// …and only when the absolute figure is worth a stall. 20% of a 4 MiB
-/// database is not a reason to block every write.
-const RECLAIM_ADVICE_MIN_BYTES: u64 = 64 * 1024 * 1024;
-
#[derive(Debug, Default, Deserialize, Serialize)]
struct Storage {
page_size: u64,
@@ -212,8 +204,9 @@ fn report_offline_recovery_hint(config: &Config, spool: &SpoolHealth, json: bool
return;
}
eprintln!(
- " run `ai-memory recover` once the server is back to deliver queued events and \
- repair unrecorded runs ({journal_pending} journaled)"
+ " run `{}` once the server is back to deliver queued events and \
+ repair unrecorded runs ({journal_pending} journaled)",
+ fix_lines::RECOVER
);
}
@@ -334,12 +327,13 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {
if let Some(free) = report.storage.data_dir_free_bytes {
println!(" filesystem free: {}", super::compact::human_bytes(free));
}
- if pct >= RECLAIM_ADVICE_PCT
- && report.storage.reclaimable_bytes >= RECLAIM_ADVICE_MIN_BYTES
- {
+ if fix_lines::reclaim_advised(
+ report.storage.reclaimable_bytes,
+ report.storage.database_bytes,
+ ) {
println!(
- " `ai-memory compact --confirm` would return it \
- (blocks writes while it runs)"
+ " `{}` would return it (blocks writes while it runs)",
+ fix_lines::COMPACT
);
}
}
@@ -391,7 +385,7 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {
if let Some(error) = &journal_error {
println!(" error: {error}");
}
- println!(" action: run `ai-memory recover`");
+ println!(" action: run `{}`", fix_lines::RECOVER);
}
if let Some(ingest) = &report.ingest {
println!(" ingest (server, this process):");
diff --git a/crates/ai-memory-core/src/fix_lines.rs b/crates/ai-memory-core/src/fix_lines.rs
new file mode 100644
index 00000000..6db0c1e9
--- /dev/null
+++ b/crates/ai-memory-core/src/fix_lines.rs
@@ -0,0 +1,52 @@
+//! Operator fix commands shared by `ai-memory status` and the web health
+//! page, so both print the same line for the same condition.
+
+/// Returns reclaimable SQLite pages to the filesystem.
+pub const COMPACT: &str = "ai-memory compact --confirm";
+
+/// Delivers spooled hook events and replays the recovery journal.
+pub const RECOVER: &str = "ai-memory recover";
+
+/// Embeds latest pages that have no vector yet.
+pub const EMBED: &str = "ai-memory embed";
+
+/// Re-embeds pages whose stored vectors were made under another
+/// `{provider, model, dim}`.
+pub const EMBED_FORCE: &str = "ai-memory embed --force";
+
+/// Suggest compaction only above this share of the file. Below it the
+/// exclusive lock costs more than the space is worth, and SQLite will reuse
+/// those pages on its own as the store grows.
+pub const RECLAIM_ADVICE_PCT: f64 = 20.0;
+
+/// …and only when the absolute figure is worth a stall. 20% of a 4 MiB
+/// database is not a reason to block every write.
+pub const RECLAIM_ADVICE_MIN_BYTES: u64 = 64 * 1024 * 1024;
+
+/// Whether `reclaimable_bytes` of a `database_bytes` file is worth
+/// suggesting [`COMPACT`] for.
+#[must_use]
+pub fn reclaim_advised(reclaimable_bytes: u64, database_bytes: u64) -> bool {
+ if database_bytes == 0 {
+ return false;
+ }
+ let pct = (reclaimable_bytes as f64 / database_bytes as f64) * 100.0;
+ pct >= RECLAIM_ADVICE_PCT && reclaimable_bytes >= RECLAIM_ADVICE_MIN_BYTES
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reclaim_needs_both_the_share_and_the_size() {
+ let gib = 1024 * 1024 * 1024;
+ assert!(reclaim_advised(gib / 4, gib), "25% of 1 GiB");
+ assert!(!reclaim_advised(gib / 10, gib), "10% is below the share");
+ assert!(
+ !reclaim_advised(2 * 1024 * 1024, 4 * 1024 * 1024),
+ "50% of 4 MiB is below the size floor"
+ );
+ assert!(!reclaim_advised(0, 0), "an empty file never advises");
+ }
+}
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index a5a60c9d..10f2e966 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -9,6 +9,7 @@ pub mod active_project;
pub mod actor;
pub mod agent_backup;
pub mod error;
+pub mod fix_lines;
pub mod handoff;
pub mod ingest_metrics;
pub use ingest_metrics::{IngestMetrics, IngestMetricsSnapshot};
diff --git a/crates/ai-memory-llm/src/embedding.rs b/crates/ai-memory-llm/src/embedding.rs
index 52cf2a21..6d39274a 100644
--- a/crates/ai-memory-llm/src/embedding.rs
+++ b/crates/ai-memory-llm/src/embedding.rs
@@ -87,6 +87,51 @@ pub trait Embedder: Send + Sync {
}
}
+/// A search query embedded for the vector stream, with the stored-vector
+/// identity it may be compared against.
+#[derive(Debug, Clone)]
+pub struct QueryVector {
+ /// The query embedding.
+ pub vector: Vec<f32>,
+ /// Provider of the eligible stored vectors.
+ pub provider: String,
+ /// Model identity of the eligible stored vectors. This is
+ /// [`Embedder::model_identity`], not [`Embedder::model`]: stored vectors
+ /// are keyed by the document identity, which a configured document
+ /// prefix folds in.
+ pub model: String,
+ /// Dimensionality of the eligible stored vectors.
+ pub dim: u32,
+}
+
+/// Embed `query` for hybrid retrieval, or `None` when the embedder fails.
+///
+/// The one place every search surface (`memory_query`, the web search) turns
+/// a query into a vector, so they select the same stored vectors. A failure
+/// degrades the search to FTS5 + entity + graph rather than failing it.
+pub async fn embed_search_query(embedder: &dyn Embedder, query: &str) -> Option<QueryVector> {
+ // `embed_query`, not `embed`: an asymmetric embedder (configured
+ // query/document prefixes, or Google's RETRIEVAL_QUERY task type)
+ // must see this text on the query side, not the document side.
+ match embedder.embed_query(query).await {
+ Ok(vector) => Some(QueryVector {
+ vector,
+ provider: embedder.provider().to_string(),
+ model: embedder.model_identity(),
+ dim: embedder.dim(),
+ }),
+ Err(e) => {
+ tracing::warn!(
+ provider = embedder.provider(),
+ model = embedder.model(),
+ error = %e,
+ "embedder failed; degrading search to FTS5 + entity + graph"
+ );
+ None
+ }
+ }
+}
+
/// OpenAI Embeddings API (`text-embedding-3-small` by default, 1536 dim).
pub struct OpenAiEmbedder {
client: reqwest::Client,
diff --git a/crates/ai-memory-llm/src/lib.rs b/crates/ai-memory-llm/src/lib.rs
index 28be970a..204a227d 100644
--- a/crates/ai-memory-llm/src/lib.rs
+++ b/crates/ai-memory-llm/src/lib.rs
@@ -112,7 +112,8 @@ pub use copilot::{
};
pub use cursor_agent::{CURSOR_DEFAULT_MODEL, CursorAgentProvider, cursor_executable};
pub use embedding::{
- Embedder, OpenAiCompatEmbedder, OpenAiEmbedder, SyntheticEmbedder, VoyageEmbedder, cosine,
+ Embedder, OpenAiCompatEmbedder, OpenAiEmbedder, QueryVector, SyntheticEmbedder, VoyageEmbedder,
+ cosine, embed_search_query,
};
pub use error::{LlmError, LlmResult};
pub use factory::{
@@ -146,7 +147,7 @@ pub use opencode::{
OPENCODE_DEFAULT_MODEL, OPENCODE_GO_BASE_URL, OPENCODE_SESSION_HEADER, OpenCodeProvider,
};
pub use provider::{LlmProvider, complete_structured, complete_structured_with_operation_id};
-pub use reranker::{LlmReranker, RerankCandidate, RerankScore, Reranker};
+pub use reranker::{LlmReranker, RerankCandidate, RerankScore, RerankStage, Reranker};
pub use stored_token::StoredOAuthToken;
pub use types::{
ChatMessage, ChatRequest, ChatResponse, ExtraHeaders, LlmOperationId, ReasoningEffort, Role,
diff --git a/crates/ai-memory-llm/src/reranker.rs b/crates/ai-memory-llm/src/reranker.rs
index c00dc272..b6ff2885 100644
--- a/crates/ai-memory-llm/src/reranker.rs
+++ b/crates/ai-memory-llm/src/reranker.rs
@@ -16,8 +16,11 @@
use async_trait::async_trait;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
use std::sync::Arc;
-use tracing::debug;
+use std::time::Duration;
+use tokio::sync::Semaphore;
+use tracing::{debug, warn};
use crate::error::LlmResult;
use crate::provider::{LlmProvider, complete_structured};
@@ -205,6 +208,179 @@ impl Reranker for LlmReranker {
}
}
+/// How many extra candidates to fetch for the reranker to reorder. The
+/// point of reranking is promoting a hit RRF put below the cut, so the
+/// candidate pool has to be deeper than the caller's limit.
+pub const RERANK_OVERFETCH: usize = 3;
+/// Hard cap on rerank candidates, whatever `limit * RERANK_OVERFETCH`
+/// works out to — bounds both prompt size and latency.
+pub const RERANK_MAX_CANDIDATES: usize = 30;
+/// Maximum number of provider-backed rerank calls executing concurrently,
+/// across every search surface sharing one [`RerankStage`]. Saturated
+/// requests keep the locally computed order without waiting.
+pub const RERANK_MAX_IN_FLIGHT: usize = 4;
+/// Wall-clock budget for one rerank call. Past this, the search answers
+/// from the adjusted pre-rerank order instead of waiting.
+pub const RERANK_TIMEOUT: Duration = Duration::from_secs(20);
+
+/// The post-fusion rerank step every search surface runs: the configured
+/// [`Reranker`] behind one shared concurrency gate.
+///
+/// Cloning shares the gate, so `memory_query` and the web search together
+/// never hold more than [`RERANK_MAX_IN_FLIGHT`] provider calls.
+#[derive(Clone)]
+pub struct RerankStage {
+ reranker: Arc<dyn Reranker>,
+ gate: Arc<Semaphore>,
+}
+
+impl RerankStage {
+ /// Wrap a reranker with a fresh concurrency gate.
+ #[must_use]
+ pub fn new(reranker: Arc<dyn Reranker>) -> Self {
+ Self {
+ reranker,
+ gate: Arc::new(Semaphore::new(RERANK_MAX_IN_FLIGHT)),
+ }
+ }
+
+ /// The wrapped reranker.
+ #[must_use]
+ pub fn reranker(&self) -> &Arc<dyn Reranker> {
+ &self.reranker
+ }
+
+ /// The shared concurrency gate.
+ #[must_use]
+ pub fn gate(&self) -> &Arc<Semaphore> {
+ &self.gate
+ }
+
+ /// How many fused candidates to fetch so the reranker can promote a hit
+ /// from below the caller's `limit`.
+ #[must_use]
+ pub fn fetch_limit(&self, limit: usize) -> usize {
+ limit.max(
+ limit
+ .saturating_mul(RERANK_OVERFETCH)
+ .min(RERANK_MAX_CANDIDATES),
+ )
+ }
+
+ /// Reorder the bounded prefix of `hits` by reranker relevance and cut to
+ /// `limit`. `candidate` describes a hit to the reranker; `record` stores
+ /// the relevance it got. On saturation, a provider error, a timeout or a
+ /// malformed answer the fused order is kept (cut to `limit`), never an
+ /// error.
+ pub async fn apply<T>(
+ &self,
+ query: &str,
+ mut hits: Vec<T>,
+ limit: usize,
+ timeout: Duration,
+ candidate: impl Fn(&T) -> RerankCandidate,
+ mut record: impl FnMut(&mut T, f32),
+ ) -> Vec<T> {
+ let reranker = &self.reranker;
+ let candidate_count = hits.len().min(RERANK_MAX_CANDIDATES);
+ if candidate_count < 2 {
+ hits.truncate(limit);
+ return hits;
+ }
+ let Ok(_permit) = self.gate.clone().try_acquire_owned() else {
+ debug!(
+ reranker = reranker.name(),
+ model = reranker.model(),
+ max_in_flight = RERANK_MAX_IN_FLIGHT,
+ "reranker concurrency limit reached; keeping pre-rerank order"
+ );
+ hits.truncate(limit);
+ return hits;
+ };
+ let candidates: Vec<RerankCandidate> =
+ hits.iter().take(candidate_count).map(candidate).collect();
+ let scored = match tokio::time::timeout(timeout, reranker.rerank(query, &candidates)).await
+ {
+ Ok(Ok(scores)) => scores,
+ Ok(Err(e)) => {
+ // Redacted fields only: the `Display` of a provider
+ // failure carries the upstream response body.
+ warn!(
+ reranker = reranker.name(),
+ model = reranker.model(),
+ error_class = %e.class(),
+ error_status = ?e.http_status(),
+ "reranker failed; keeping pre-rerank order"
+ );
+ hits.truncate(limit);
+ return hits;
+ }
+ Err(_) => {
+ warn!(
+ reranker = reranker.name(),
+ model = reranker.model(),
+ timeout_secs = timeout.as_secs_f64(),
+ "reranker timed out; keeping pre-rerank order"
+ );
+ hits.truncate(limit);
+ return hits;
+ }
+ };
+ let candidate_index: HashMap<&str, usize> = candidates
+ .iter()
+ .enumerate()
+ .map(|(idx, candidate)| (candidate.id.as_str(), idx))
+ .collect();
+ let mut relevance = vec![None; candidates.len()];
+ let mut invalid = scored.len() != candidates.len();
+ for score in &scored {
+ let Some(&idx) = candidate_index.get(score.id.as_str()) else {
+ invalid = true;
+ continue;
+ };
+ if !score.relevance.is_finite()
+ || !(0.0..=1.0).contains(&score.relevance)
+ || relevance[idx].replace(score.relevance).is_some()
+ {
+ invalid = true;
+ }
+ }
+ if invalid || relevance.iter().any(Option::is_none) {
+ warn!(
+ reranker = reranker.name(),
+ model = reranker.model(),
+ scored = scored.len(),
+ candidates = candidates.len(),
+ "reranker returned incomplete or invalid scores; keeping pre-rerank order"
+ );
+ hits.truncate(limit);
+ return hits;
+ }
+ let relevance: Vec<f32> = relevance
+ .into_iter()
+ .map(Option::unwrap_or_default)
+ .collect();
+
+ let tail = hits.split_off(candidate_count);
+ let mut indexed: Vec<(usize, T)> = hits.into_iter().enumerate().collect();
+ indexed.sort_by(|a, b| {
+ relevance[b.0]
+ .total_cmp(&relevance[a.0])
+ .then(a.0.cmp(&b.0))
+ });
+ let mut out: Vec<T> = indexed
+ .into_iter()
+ .map(|(idx, mut entry)| {
+ record(&mut entry, relevance[idx]);
+ entry
+ })
+ .collect();
+ out.extend(tail);
+ out.truncate(limit);
+ out
+ }
+}
+
/// Map 1-based prompt indices back onto candidate ids, dropping
/// out-of-range indices and duplicates (a model that hallucinates
/// `[99]` loses that judgement instead of corrupting the ranking).
@@ -241,6 +417,91 @@ mod tests {
use super::*;
use crate::{ChatResponse, LlmError};
+ /// Scores candidates in reverse order and counts its calls.
+ struct Reverse(std::sync::atomic::AtomicUsize);
+
+ #[async_trait]
+ impl Reranker for Reverse {
+ fn name(&self) -> &'static str {
+ "reverse"
+ }
+ fn model(&self) -> &str {
+ "reverse"
+ }
+ async fn rerank(
+ &self,
+ _query: &str,
+ candidates: &[RerankCandidate],
+ ) -> LlmResult<Vec<RerankScore>> {
+ self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ let n = candidates.len() as f32;
+ Ok(candidates
+ .iter()
+ .enumerate()
+ .map(|(i, c)| RerankScore {
+ id: c.id.clone(),
+ relevance: (i as f32 + 1.0) / n,
+ })
+ .collect())
+ }
+ }
+
+ fn apply_ids(
+ stage: &RerankStage,
+ ids: &[&str],
+ ) -> impl std::future::Future<Output = Vec<String>> {
+ let stage = stage.clone();
+ let hits: Vec<(String, Option<f32>)> =
+ ids.iter().map(|id| ((*id).to_owned(), None)).collect();
+ async move {
+ stage
+ .apply(
+ "q",
+ hits,
+ 10,
+ RERANK_TIMEOUT,
+ |(id, _)| RerankCandidate {
+ id: id.clone(),
+ title: id.clone(),
+ snippet: String::new(),
+ },
+ |(_, score), relevance| *score = Some(relevance),
+ )
+ .await
+ .into_iter()
+ .map(|(id, _)| id)
+ .collect()
+ }
+ }
+
+ #[tokio::test]
+ async fn rerank_stage_reorders_and_clones_share_one_gate() {
+ let reranker = Arc::new(Reverse(std::sync::atomic::AtomicUsize::new(0)));
+ let stage = RerankStage::new(reranker.clone());
+ assert_eq!(apply_ids(&stage, &["a", "b", "c"]).await, ["c", "b", "a"]);
+
+ // A clone (the web search's copy) draws on the same permits: with
+ // them all held through the original, the clone keeps fused order and
+ // never calls the provider.
+ let web_copy = stage.clone();
+ let _held: Vec<_> = (0..RERANK_MAX_IN_FLIGHT)
+ .map(|_| stage.gate().clone().try_acquire_owned().unwrap())
+ .collect();
+ assert_eq!(
+ apply_ids(&web_copy, &["a", "b", "c"]).await,
+ ["a", "b", "c"]
+ );
+ assert_eq!(reranker.0.load(std::sync::atomic::Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn fetch_limit_overfetches_up_to_the_cap() {
+ let stage = RerankStage::new(Arc::new(Reverse(std::sync::atomic::AtomicUsize::new(0))));
+ assert_eq!(stage.fetch_limit(5), 15);
+ assert_eq!(stage.fetch_limit(20), RERANK_MAX_CANDIDATES);
+ assert_eq!(stage.fetch_limit(50), 50);
+ }
+
fn candidates() -> Vec<RerankCandidate> {
vec![
RerankCandidate {
diff --git a/crates/ai-memory-mcp/Cargo.toml b/crates/ai-memory-mcp/Cargo.toml
index 365eaa7f..2ee9dcd3 100644
--- a/crates/ai-memory-mcp/Cargo.toml
+++ b/crates/ai-memory-mcp/Cargo.toml
@@ -48,6 +48,9 @@ jiff.workspace = true
ai-memory-core.workspace = true
ai-memory-hooks.workspace = true
ai-memory-store.workspace = true
+# The web search parity test drives `/web` and `/api/v1` next to
+# `memory_query`. Test-only: the server crate does not depend on the web UI.
+ai-memory-web.workspace = true
ai-memory-wiki.workspace = true
async-trait.workspace = true
flate2.workspace = true
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index d8e5c235..9de6f39f 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -510,9 +510,12 @@ pub struct AiMemoryServer {
/// M9 embedder for hybrid query. When `None`, `memory_query`
/// still fuses FTS5 with entity matches and graph-neighbour expansion.
embedder: Option<Arc<dyn Embedder>>,
- /// Optional post-RRF reranker. When `None`, `memory_query` returns
- /// fused, authority-adjusted order and stays on the zero-LLM path.
- reranker: Option<Arc<dyn ai_memory_llm::Reranker>>,
+ /// Optional post-RRF reranker behind its concurrency gate, shared with
+ /// the web search so cloned request handlers and both surfaces together
+ /// cannot create an unbounded number of billable provider calls. When
+ /// `None`, `memory_query` returns fused, authority-adjusted order and
+ /// stays on the zero-LLM path.
+ rerank: Option<ai_memory_llm::RerankStage>,
/// Per-client MCP tool-call counters, buffered in memory and folded
/// into `client_activity` at most once per flush interval so a query
/// burst costs the writer one tiny upsert batch, not one write per
@@ -526,9 +529,6 @@ pub struct AiMemoryServer {
/// running pass the moment the operator returns — consolidation must never
/// contend with live work.
activity_clock: ai_memory_consolidate::ActivityClock,
- /// Shared across cloned request handlers so concurrent searches cannot
- /// create an unbounded number of billable provider calls.
- rerank_gate: Arc<tokio::sync::Semaphore>,
/// Privacy strip. Applied to agent-supplied handoff fields in
/// `memory_handoff_begin` (handoffs bypass `Wiki::write_page` so
/// the wiki-level scrub doesn't cover them).
@@ -791,13 +791,52 @@ impl From<ai_memory_store::PageHit> for QueryHit {
#[derive(Clone, Copy)]
struct ProjectSearchOptions<'a> {
query: &'a str,
- query_vec: Option<&'a [f32]>,
+ query_vec: Option<&'a ai_memory_llm::QueryVector>,
limit: usize,
include_expired: bool,
explain: bool,
include_superseded: bool,
}
+/// Borrow an embedded query as the store's vector-stream input.
+fn vector_query(qv: &ai_memory_llm::QueryVector) -> ai_memory_store::VectorQuery<'_> {
+ ai_memory_store::VectorQuery {
+ vector: &qv.vector,
+ provider: &qv.provider,
+ model: &qv.model,
+ dim: qv.dim,
+ }
+}
+
+/// Rerank fused page hits through `stage`, recording each judged hit's
+/// relevance in its explain details.
+async fn rerank_page_hits(
+ stage: &ai_memory_llm::RerankStage,
+ query: &str,
+ hits: Vec<(PageHit, Option<ai_memory_store::SearchExplain>)>,
+ limit: usize,
+ timeout: std::time::Duration,
+) -> Vec<(PageHit, Option<ai_memory_store::SearchExplain>)> {
+ stage
+ .apply(
+ query,
+ hits,
+ limit,
+ timeout,
+ |(hit, _)| ai_memory_llm::RerankCandidate {
+ id: hit.id.to_string(),
+ title: hit.title.clone(),
+ snippet: hit.snippet.clone(),
+ },
+ |(_, explain), relevance| {
+ if let Some(explain) = explain.as_mut() {
+ explain.rerank_score = Some(relevance);
+ }
+ },
+ )
+ .await
+}
+
/// Synthesized "dialectic" answer attached to a `memory_query` response when
/// the caller opts in with `answer=true` and a provider is configured. The
/// `text` is a natural-language answer drawn strictly from the retrieved hit
@@ -907,20 +946,6 @@ struct AnsweredScope {
resolved_by: &'static str,
}
-/// How many extra candidates to fetch for the reranker to reorder. The
-/// point of reranking is promoting a hit RRF put below the cut, so the
-/// candidate pool has to be deeper than the caller's limit.
-const RERANK_OVERFETCH: usize = 3;
-/// Hard cap on rerank candidates, whatever `limit * RERANK_OVERFETCH`
-/// works out to — bounds both prompt size and latency.
-const RERANK_MAX_CANDIDATES: usize = 30;
-/// Maximum number of provider-backed rerank calls executing concurrently.
-/// Saturated requests keep the locally computed order without waiting.
-const RERANK_MAX_IN_FLIGHT: usize = 4;
-/// Wall-clock budget for one rerank call. Past this, `memory_query`
-/// answers from the adjusted pre-rerank order instead of waiting.
-const RERANK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
-
/// Microseconds in one UTC day, for `client_activity` bucketing.
const US_PER_DAY: i64 = 86_400_000_000;
/// How long buffered client-activity counts may age before a background
@@ -1806,13 +1831,12 @@ impl AiMemoryServer {
contradiction_band_min: ai_memory_consolidate::DEFAULT_CONTRADICTION_SIM_LOW,
contradiction_band_max: ai_memory_consolidate::DEFAULT_CONTRADICTION_SIM_HIGH,
embedder: None,
- reranker: None,
+ rerank: None,
client_activity: Arc::new(std::sync::Mutex::new(ClientActivityBuffer::new())),
mcp_metrics: Arc::new(crate::McpMetrics::default()),
activity_clock: ai_memory_consolidate::ActivityClock::new(
jiff::Timestamp::now().as_microsecond(),
),
- rerank_gate: Arc::new(tokio::sync::Semaphore::new(RERANK_MAX_IN_FLIGHT)),
sanitizer: ai_memory_core::Sanitizer::builtin(),
auto_improve_require_approval: false,
auto_improve_review_config: default_auto_improve_review_config(),
@@ -2364,25 +2388,9 @@ impl AiMemoryServer {
))
}
- async fn embed_query(&self, query: &str) -> Option<Vec<f32>> {
- let Some(embedder) = &self.embedder else {
- return None;
- };
- // `embed_query`, not `embed`: an asymmetric embedder (configured
- // query/document prefixes, or Google's RETRIEVAL_QUERY task type)
- // must see this text on the query side, not the document side.
- match embedder.embed_query(query).await {
- Ok(qv) => Some(qv),
- Err(e) => {
- tracing::warn!(
- provider = embedder.provider(),
- model = embedder.model(),
- error = %e,
- "embedder failed; degrading memory_query to FTS5 + entity + graph"
- );
- None
- }
- }
+ async fn embed_query(&self, query: &str) -> Option<ai_memory_llm::QueryVector> {
+ let embedder = self.embedder.as_ref()?;
+ ai_memory_llm::embed_search_query(embedder.as_ref(), query).await
}
/// One project's fused hits, plus per-stream timings when
@@ -2395,73 +2403,45 @@ impl AiMemoryServer {
) -> ai_memory_store::StoreResult<(
Vec<(PageHit, Option<ai_memory_store::SearchExplain>)>,
Option<ai_memory_store::StreamTimings>,
+ )> {
+ self.search_scopes(&[(workspace_id, project_id)], options)
+ .await
+ }
+
+ /// Fused hits over `scopes` through the shared hybrid ranker
+ /// ([`ai_memory_store::ReaderPool::hybrid_search_scopes`]), the same call
+ /// the web search makes.
+ async fn search_scopes(
+ &self,
+ scopes: &[(WorkspaceId, ProjectId)],
+ options: ProjectSearchOptions<'_>,
+ ) -> ai_memory_store::StoreResult<(
+ Vec<(PageHit, Option<ai_memory_store::SearchExplain>)>,
+ Option<ai_memory_store::StreamTimings>,
)> {
// `i64::MIN` as the expiry cutoff makes every stored TTL pass
// the `expires_at > cutoff` guard, i.e. expired pages stay
// searchable when the caller opted in.
let expiry_cutoff = options.include_expired.then_some(i64::MIN);
- // Provider/model/dim only select which stored vectors are
- // eligible; with no query vector the vector stream never runs,
- // so the empty triple is inert rather than a fake identity.
- let (provider, model, dim) = match (&self.embedder, options.query_vec) {
- // Not `.model()`: eligible stored vectors are keyed by the
- // DOCUMENT identity they were embedded under, which a
- // configured document prefix folds in. See
- // `Embedder::model_identity`.
- (Some(e), Some(_)) => (e.provider().to_string(), e.model_identity(), e.dim()),
- _ => (String::new(), String::new(), 0),
- };
- if options.explain {
- let (hits, timings) = self
- .reader
- .hybrid_search_explained_timed(
- workspace_id,
- project_id,
- options.query.to_owned(),
- options.query_vec.map(<[f32]>::to_vec),
- provider,
- model,
- dim,
- options.limit,
- expiry_cutoff,
- options.include_superseded,
- )
- .await?;
- Ok((
- hits.into_iter()
- .map(|(hit, details)| (hit, Some(details)))
- .collect(),
- Some(timings),
- ))
- } else {
- let hits = self
- .reader
- .hybrid_search(
- workspace_id,
- project_id,
- options.query.to_owned(),
- options.query_vec.map(<[f32]>::to_vec),
- provider,
- model,
- dim,
- options.limit,
- expiry_cutoff,
- options.include_superseded,
- )
- .await?;
- Ok((hits.into_iter().map(|hit| (hit, None)).collect(), None))
- }
+ self.reader
+ .hybrid_search_scopes(
+ scopes,
+ ai_memory_store::HybridSearch {
+ query: options.query,
+ vector: options.query_vec.map(vector_query),
+ limit: options.limit,
+ expiry_cutoff_us: expiry_cutoff,
+ include_superseded: options.include_superseded,
+ explain: options.explain,
+ },
+ )
+ .await
}
fn rerank_fetch_limit(&self, limit: usize) -> usize {
- if self.reranker.is_none() {
- return limit;
- }
- limit.max(
- limit
- .saturating_mul(RERANK_OVERFETCH)
- .min(RERANK_MAX_CANDIDATES),
- )
+ self.rerank
+ .as_ref()
+ .map_or(limit, |stage| stage.fetch_limit(limit))
}
async fn rerank_hits(
@@ -2470,7 +2450,7 @@ impl AiMemoryServer {
hits: Vec<(PageHit, Option<ai_memory_store::SearchExplain>)>,
limit: usize,
) -> Vec<(PageHit, Option<ai_memory_store::SearchExplain>)> {
- self.rerank_hits_with_timeout(query, hits, limit, RERANK_TIMEOUT)
+ self.rerank_hits_with_timeout(query, hits, limit, ai_memory_llm::reranker::RERANK_TIMEOUT)
.await
}
@@ -2481,116 +2461,11 @@ impl AiMemoryServer {
limit: usize,
timeout: std::time::Duration,
) -> Vec<(PageHit, Option<ai_memory_store::SearchExplain>)> {
- let Some(reranker) = &self.reranker else {
+ let Some(stage) = &self.rerank else {
hits.truncate(limit);
return hits;
};
- let candidate_count = hits.len().min(RERANK_MAX_CANDIDATES);
- if candidate_count < 2 {
- hits.truncate(limit);
- return hits;
- }
- let Ok(_permit) = self.rerank_gate.clone().try_acquire_owned() else {
- tracing::debug!(
- reranker = reranker.name(),
- model = reranker.model(),
- max_in_flight = RERANK_MAX_IN_FLIGHT,
- "reranker concurrency limit reached; keeping pre-rerank order"
- );
- hits.truncate(limit);
- return hits;
- };
- let candidates: Vec<ai_memory_llm::RerankCandidate> = hits
- .iter()
- .take(candidate_count)
- .map(|(hit, _)| ai_memory_llm::RerankCandidate {
- id: hit.id.to_string(),
- title: hit.title.clone(),
- snippet: hit.snippet.clone(),
- })
- .collect();
- let scored = match tokio::time::timeout(timeout, reranker.rerank(query, &candidates)).await
- {
- Ok(Ok(scores)) => scores,
- Ok(Err(e)) => {
- // Redacted fields only: the `Display` of a provider failure
- // carries the upstream response body.
- tracing::warn!(
- reranker = reranker.name(),
- model = reranker.model(),
- error_class = %e.class(),
- error_status = ?e.http_status(),
- "reranker failed; keeping pre-rerank order"
- );
- hits.truncate(limit);
- return hits;
- }
- Err(_) => {
- tracing::warn!(
- reranker = reranker.name(),
- model = reranker.model(),
- timeout_secs = timeout.as_secs_f64(),
- "reranker timed out; keeping pre-rerank order"
- );
- hits.truncate(limit);
- return hits;
- }
- };
- let candidate_index: HashMap<&str, usize> = candidates
- .iter()
- .enumerate()
- .map(|(idx, candidate)| (candidate.id.as_str(), idx))
- .collect();
- let mut relevance = vec![None; candidates.len()];
- let mut invalid = scored.len() != candidates.len();
- for score in &scored {
- let Some(&idx) = candidate_index.get(score.id.as_str()) else {
- invalid = true;
- continue;
- };
- if !score.relevance.is_finite()
- || !(0.0..=1.0).contains(&score.relevance)
- || relevance[idx].replace(score.relevance).is_some()
- {
- invalid = true;
- }
- }
- if invalid || relevance.iter().any(Option::is_none) {
- tracing::warn!(
- reranker = reranker.name(),
- model = reranker.model(),
- scored = scored.len(),
- candidates = candidates.len(),
- "reranker returned incomplete or invalid scores; keeping pre-rerank order"
- );
- hits.truncate(limit);
- return hits;
- }
- let relevance: Vec<f32> = relevance
- .into_iter()
- .map(Option::unwrap_or_default)
- .collect();
-
- let tail = hits.split_off(candidate_count);
- let mut indexed: Vec<(usize, (PageHit, Option<ai_memory_store::SearchExplain>))> =
- hits.into_iter().enumerate().collect();
- indexed.sort_by(|a, b| {
- relevance[b.0]
- .total_cmp(&relevance[a.0])
- .then(a.0.cmp(&b.0))
- });
- let mut out: Vec<(PageHit, Option<ai_memory_store::SearchExplain>)> = indexed
- .into_iter()
- .map(|(idx, mut entry)| {
- if let Some(explain) = entry.1.as_mut() {
- explain.rerank_score = Some(relevance[idx]);
- }
- entry
- })
- .collect();
- out.extend(tail);
- out.truncate(limit);
- out
+ rerank_page_hits(stage, query, hits, limit, timeout).await
}
/// The process counters this server records into. `serve` hands the same
@@ -2603,11 +2478,25 @@ impl AiMemoryServer {
/// Attach a reranker. Without one, `memory_query` keeps its
/// RRF-only, zero-LLM behaviour.
#[must_use]
- pub fn with_reranker(mut self, reranker: Arc<dyn ai_memory_llm::Reranker>) -> Self {
- self.reranker = Some(reranker);
+ pub fn with_reranker(self, reranker: Arc<dyn ai_memory_llm::Reranker>) -> Self {
+ self.with_rerank_stage(ai_memory_llm::RerankStage::new(reranker))
+ }
+
+ /// Attach a rerank stage built elsewhere, sharing its concurrency gate
+ /// (`serve` hands the same stage to the web search).
+ #[must_use]
+ pub fn with_rerank_stage(mut self, stage: ai_memory_llm::RerankStage) -> Self {
+ self.rerank = Some(stage);
self
}
+ /// The configured rerank stage, if any, so another search surface can
+ /// share its reranker and concurrency gate.
+ #[must_use]
+ pub fn rerank_stage(&self) -> Option<ai_memory_llm::RerankStage> {
+ self.rerank.clone()
+ }
+
/// Attach a bare LLM provider so `memory_query(answer=true)` can synthesize
/// a cited answer over the retrieved hits, without the full consolidation
/// pipeline that [`with_consolidator_arc`](Self::with_consolidator_arc)
@@ -2891,52 +2780,16 @@ impl AiMemoryServer {
// Explain-only: per-stream timings of the primary search, summed over
// `scopes`. `None` on the normal path, which reads no clocks for it.
let mut timings: Option<ai_memory_store::StreamTimings> = None;
+ let options = ProjectSearchOptions {
+ query: &args.query,
+ query_vec: query_vec.as_ref(),
+ limit: candidate_limit,
+ include_expired,
+ explain,
+ include_superseded,
+ };
let hits = if let Some(scopes) = &resolved_scopes {
- let mut hits_by_id: HashMap<PageId, (PageHit, Option<ai_memory_store::SearchExplain>)> =
- HashMap::new();
- for &(ws, proj) in scopes {
- let (hits, scope_timings) = self
- .search_project(
- ws,
- proj,
- ProjectSearchOptions {
- query: &args.query,
- query_vec: query_vec.as_deref(),
- limit: candidate_limit,
- include_expired,
- explain,
- include_superseded,
- },
- )
- .await
- .map_err(|e| McpError::internal_error(e.to_string(), None))?;
- if let Some(scope_timings) = scope_timings {
- timings
- .get_or_insert_with(Default::default)
- .accumulate(&scope_timings);
- }
- for hit in hits {
- hits_by_id
- .entry(hit.0.id)
- .and_modify(|existing| {
- if hit.0.rank < existing.0.rank {
- *existing = hit.clone();
- }
- })
- .or_insert(hit);
- }
- }
- let mut hits: Vec<(PageHit, Option<ai_memory_store::SearchExplain>)> =
- hits_by_id.into_values().collect();
- hits.sort_by(|a, b| {
- a.0.rank
- .partial_cmp(&b.0.rank)
- .unwrap_or(std::cmp::Ordering::Equal)
- .then_with(|| a.0.path.as_str().cmp(b.0.path.as_str()))
- .then_with(|| a.0.id.as_bytes().cmp(b.0.id.as_bytes()))
- });
- hits.truncate(candidate_limit);
- Ok(hits)
+ self.search_scopes(scopes, options).await
} else {
let (ws, proj) = self
.effective_ids_for_read_args_with_actor(
@@ -2946,26 +2799,14 @@ impl AiMemoryServer {
Self::viewer_from_parts(Some(&parts)),
)
.await?;
- self.search_project(
- ws,
- proj,
- ProjectSearchOptions {
- query: &args.query,
- query_vec: query_vec.as_deref(),
- limit: candidate_limit,
- include_expired,
- explain,
- include_superseded,
- },
- )
- .await
- .map(|(hits, project_timings)| {
- timings = project_timings;
- hits
- })
- };
+ self.search_project(ws, proj, options).await
+ }
+ .map(|(hits, search_timings)| {
+ timings = search_timings;
+ hits
+ });
let hits = hits.map_err(|e| McpError::internal_error(e.to_string(), None))?;
- let rerank_started = (explain && self.reranker.is_some()).then(std::time::Instant::now);
+ let rerank_started = (explain && self.rerank.is_some()).then(std::time::Instant::now);
let hits = self.rerank_hits(&args.query, hits, limit).await;
if let (Some(timings), Some(started)) = (timings.as_mut(), rerank_started) {
timings.rerank_ms = Some(started.elapsed().as_secs_f64() * 1000.0);
@@ -3053,7 +2894,7 @@ impl AiMemoryServer {
scope.project_id,
ProjectSearchOptions {
query: &args.query,
- query_vec: query_vec.as_deref(),
+ query_vec: query_vec.as_ref(),
limit,
include_expired,
explain,
@@ -3122,7 +2963,7 @@ impl AiMemoryServer {
scope.project_id,
ProjectSearchOptions {
query: &args.query,
- query_vec: query_vec.as_deref(),
+ query_vec: query_vec.as_ref(),
limit,
include_expired,
explain,
@@ -3147,20 +2988,7 @@ impl AiMemoryServer {
}
}
}
- let streams_active = explain.then(|| {
- let mut streams = vec!["fts", "entity"];
- if query_vec.is_some() {
- streams.push("vector");
- if self.reader.retrieval_tuning().abstract_vectors {
- streams.push("abstract");
- }
- }
- streams.push("graph");
- if self.reader.retrieval_tuning().observation_stream {
- streams.push("observation");
- }
- streams
- });
+ let streams_active = explain.then(|| self.reader.active_streams(query_vec.is_some()));
let hits: Vec<QueryHit> = hits
.into_iter()
.map(|(hit, score_details)| QueryHit {
@@ -7563,7 +7391,7 @@ mod tests {
let query_vec = server.embed_query("anything").await;
assert_eq!(
- query_vec.as_deref(),
+ query_vec.as_ref().map(|qv| qv.vector.as_slice()),
Some([0.0_f32, 1.0].as_slice()),
"memory_query's embed_query helper must call Embedder::embed_query \
(query-side vector [0.0, 1.0]), not the generic Embedder::embed \
@@ -7831,8 +7659,9 @@ mod tests {
let (_tmp, _store, server, _ws, _proj) = setup_server().await;
let (reranker, calls, _) = stub_reranker(StubRerankOutcome::Reverse, Duration::ZERO);
let server = server.with_reranker(reranker);
- let _permits: Vec<_> = (0..RERANK_MAX_IN_FLIGHT)
- .map(|_| server.rerank_gate.clone().try_acquire_owned().unwrap())
+ let gate = server.rerank_stage().unwrap().gate().clone();
+ let _permits: Vec<_> = (0..ai_memory_llm::reranker::RERANK_MAX_IN_FLIGHT)
+ .map(|_| gate.clone().try_acquire_owned().unwrap())
.collect();
let hits = rerank_test_hits(4);
let original_ids: Vec<PageId> = hits.iter().map(|(hit, _)| hit.id).collect();
diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rs
index ede91b10..1c8fb5c4 100644
--- a/crates/ai-memory-mcp/tests/suite/mod.rs
+++ b/crates/ai-memory-mcp/tests/suite/mod.rs
@@ -39,3 +39,4 @@ mod read_page_related;
mod retrieval_via_tools;
mod slot_identity;
mod stress_autoscope;
+mod web_search_parity;
diff --git a/crates/ai-memory-mcp/tests/suite/web_search_parity.rs b/crates/ai-memory-mcp/tests/suite/web_search_parity.rs
new file mode 100644
index 00000000..b5226433
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/suite/web_search_parity.rs
@@ -0,0 +1,450 @@
+//! The web search ranks a project the way `memory_query` does.
+//!
+//! `memory_query` and the web search (`/web/search` with a project,
+//! `/api/v1/search` scoped) both call `ai_memory_llm::embed_search_query`,
+//! `ReaderPool::hybrid_search_scopes` and the shared `RerankStage`. These
+//! tests seed one store, drive `memory_query` over the real JSON-RPC
+//! transport and the web routers as `serve` mounts them, and require the same
+//! top-k order from each, with a deterministic embedder and with none.
+//!
+//! The controls prove the comparison can fail: a web search built without the
+//! embedder, or the old FTS-only scoped search, ranks differently from a
+//! `memory_query` that has one.
+
+use std::sync::Arc;
+
+use ai_memory_core::{ActorContext, PagePath, ProjectId, Tier, WorkspaceId};
+use ai_memory_llm::{Embedder, SyntheticEmbedder};
+use ai_memory_mcp::AiMemoryServer;
+use ai_memory_store::Store;
+use ai_memory_web::{Recall, WebMountSpec, split_web_routers};
+use ai_memory_wiki::{Wiki, WritePageRequest};
+use axum::Router;
+use axum::body::Body;
+use axum::http::Request;
+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
+use serde_json::{Value, json};
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+const LIMIT: usize = 8;
+
+/// Small enough that unrelated words share buckets, so the vector stream
+/// reaches pages FTS does not and moves the fused order.
+fn embedder() -> Arc<dyn Embedder> {
+ Arc::new(SyntheticEmbedder::new(8))
+}
+
+struct Seeded {
+ _tmp: TempDir,
+ store: Store,
+ wiki: Wiki,
+ ws: WorkspaceId,
+ alpha: ProjectId,
+}
+
+const ALPHA_PAGES: &[(&str, &str)] = &[
+ (
+ "notes/token-rotation.md",
+ "# Token rotation\n\nRotate the signing token every week. See [[notes/key-store]].",
+ ),
+ (
+ "notes/key-store.md",
+ "# Key store\n\nKeys live in the vault; rotation writes a new version.",
+ ),
+ (
+ "notes/db-migration.md",
+ "# Database migration\n\nMigrations run before deploy; rollback drops the new table.",
+ ),
+ (
+ "notes/rollback.md",
+ "# Rollback plan\n\nA failed deploy rolls back the release and the database.",
+ ),
+ (
+ "notes/cache.md",
+ "# Cache invalidation\n\nThe cache is keyed by page id and invalidated on write.",
+ ),
+ (
+ "notes/deploy.md",
+ "# Deploy pipeline\n\nThe pipeline builds, migrates the database, then swaps traffic. See [[notes/rollback]].",
+ ),
+ (
+ "notes/oncall.md",
+ "# On-call\n\nPage the owner when the pipeline or the vault is down.",
+ ),
+ (
+ "notes/weekly.md",
+ "# Weekly chores\n\nEvery week: rotate logs, prune the cache, review alerts.",
+ ),
+ (
+ "decisions/vault.md",
+ "# Use the vault for secrets\n\nDecision: signing keys and tokens stay in the vault.",
+ ),
+ (
+ "gotchas/migration-lock.md",
+ "# Migration lock\n\nTwo deploys at once deadlock on the migration lock table.",
+ ),
+];
+
+const BETA_PAGES: &[(&str, &str)] = &[
+ (
+ "notes/beta-token.md",
+ "# Beta token rotation\n\nBeta rotates its token and database keys every week.",
+ ),
+ (
+ "notes/beta-deploy.md",
+ "# Beta deploy\n\nBeta deploy pipeline with cache rollback and migration.",
+ ),
+];
+
+fn write_req(ws: WorkspaceId, proj: ProjectId, path: &str, body: &str) -> WritePageRequest {
+ WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new(path).unwrap(),
+ frontmatter: json!({"kind": "fact"}),
+ body: body.to_owned(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: None,
+ admission_ctx: None,
+ author_id: None,
+ actor: ActorContext::anonymous(),
+ evidence: Vec::new(),
+ }
+}
+
+/// Pages written through a `Wiki` that embeds on write, so every page has a
+/// vector under the synthetic triple.
+async fn seed() -> Seeded {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ 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();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_embedder(embedder());
+ for (path, body) in ALPHA_PAGES {
+ wiki.write_page(write_req(ws, alpha, path, body))
+ .await
+ .unwrap();
+ }
+ for (path, body) in BETA_PAGES {
+ wiki.write_page(write_req(ws, beta, path, body))
+ .await
+ .unwrap();
+ }
+ let status = store.reader.derived_index_status().await.unwrap();
+ assert_eq!(
+ status.latest_pages_missing_embeddings, 0,
+ "every seeded page must carry a vector"
+ );
+ Seeded {
+ _tmp: tmp,
+ store,
+ wiki: wiki.without_embedder(),
+ ws,
+ alpha,
+ }
+}
+
+fn mcp_router(server: AiMemoryServer) -> Router {
+ let service = StreamableHttpService::new(
+ move || Ok(server.clone()),
+ LocalSessionManager::default().into(),
+ StreamableHttpServerConfig::default()
+ .with_stateful_mode(false)
+ .with_json_response(true),
+ );
+ Router::new().nest_service("/mcp", service)
+}
+
+fn server(s: &Seeded, embedder: Option<Arc<dyn Embedder>>) -> Router {
+ let mut server = AiMemoryServer::new(
+ s.store.reader.clone(),
+ s.store.writer.clone(),
+ s.ws,
+ s.alpha,
+ )
+ .with_wiki(s.wiki.clone());
+ if let Some(embedder) = embedder {
+ server = server.with_embedder(embedder);
+ }
+ mcp_router(server)
+}
+
+/// `/web` and `/api/v1`, mounted the way `serve` mounts them.
+fn web(s: &Seeded, embedder: Option<Arc<dyn Embedder>>) -> Router {
+ split_web_routers(
+ true,
+ s.store.reader.clone(),
+ s.wiki.clone(),
+ WebMountSpec {
+ enable_api: true,
+ web_ui_dir: None,
+ cors_origins: &[],
+ web_slug: "/web",
+ base_href: "/web/",
+ base_path: "",
+ trusted_proxy_identity: false,
+ recall: Recall {
+ embedder,
+ rerank: None,
+ },
+ health: None,
+ },
+ )
+ .unwrap()
+ .protected
+}
+
+async fn memory_query(router: &Router, arguments: Value) -> Value {
+ let body = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": { "name": "memory_query", "arguments": arguments },
+ });
+ let req = Request::builder()
+ .method("POST")
+ .uri("/mcp")
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ .header("accept", "application/json, text/event-stream")
+ .body(Body::from(body.to_string()))
+ .unwrap();
+ let resp = router.clone().oneshot(req).await.unwrap();
+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)
+ .await
+ .unwrap();
+ let v: Value = serde_json::from_slice(&bytes).unwrap();
+ assert!(v.get("error").is_none(), "JSON-RPC error: {v}");
+ let text = v
+ .pointer("/result/content/0/text")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| panic!("no tool text: {v}"));
+ serde_json::from_str(text).unwrap()
+}
+
+fn paths(hits: &Value) -> Vec<String> {
+ hits.as_array()
+ .unwrap_or_else(|| panic!("not an array: {hits}"))
+ .iter()
+ .map(|h| h["path"].as_str().unwrap().to_owned())
+ .collect()
+}
+
+async fn mcp_paths(router: &Router, query: &str, explain: bool) -> Vec<String> {
+ let response = memory_query(
+ router,
+ json!({
+ "query": query,
+ "workspace": "default",
+ "project": "alpha",
+ "limit": LIMIT,
+ "explain": explain,
+ }),
+ )
+ .await;
+ paths(&response["hits"])
+}
+
+async fn get(router: &Router, uri: &str) -> (u16, String) {
+ let resp = router
+ .clone()
+ .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+ let status = resp.status().as_u16();
+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)
+ .await
+ .unwrap();
+ (status, String::from_utf8(bytes.to_vec()).unwrap())
+}
+
+fn encode(query: &str) -> String {
+ query.replace(' ', "%20")
+}
+
+async fn api_paths(router: &Router, query: &str) -> Vec<String> {
+ let (status, body) = get(
+ router,
+ &format!(
+ "/api/v1/search?q={}&workspace=default&project=alpha&limit={LIMIT}",
+ encode(query)
+ ),
+ )
+ .await;
+ assert_eq!(status, 200, "{body}");
+ paths(&serde_json::from_str(&body).unwrap())
+}
+
+/// Hit paths in page order, read from the `data-hit-path` attribute.
+fn html_paths(body: &str) -> Vec<String> {
+ body.split("data-hit-path=\"")
+ .skip(1)
+ .map(|rest| rest.split('"').next().unwrap().to_owned())
+ .collect()
+}
+
+async fn web_paths(router: &Router, query: &str, explain: bool) -> Vec<String> {
+ let (status, body) = get(
+ router,
+ &format!(
+ "/web/search?q={}&workspace=default&project=alpha&limit={LIMIT}{}",
+ encode(query),
+ if explain { "&explain=1" } else { "" }
+ ),
+ )
+ .await;
+ assert_eq!(status, 200, "{body}");
+ html_paths(&body)
+}
+
+const QUERIES: &[&str] = &[
+ "token rotation",
+ "database migration rollback",
+ "cache invalidation",
+ "deploy pipeline vault",
+ "weekly",
+];
+
+#[tokio::test]
+async fn web_search_returns_memory_query_order_with_an_embedder() {
+ let s = seed().await;
+ let mcp = server(&s, Some(embedder()));
+ let web = web(&s, Some(embedder()));
+ for query in QUERIES {
+ let expected = mcp_paths(&mcp, query, false).await;
+ assert!(!expected.is_empty(), "{query}: memory_query found nothing");
+ assert!(
+ expected.iter().all(|p| !p.contains("beta")),
+ "{query}: another project leaked into memory_query: {expected:?}"
+ );
+ assert_eq!(api_paths(&web, query).await, expected, "{query}: /api/v1");
+ assert_eq!(
+ web_paths(&web, query, false).await,
+ expected,
+ "{query}: /web"
+ );
+ // Explain changes what is reported, never the order.
+ assert_eq!(
+ mcp_paths(&mcp, query, true).await,
+ expected,
+ "{query}: explain"
+ );
+ assert_eq!(
+ web_paths(&web, query, true).await,
+ expected,
+ "{query}: /web explain"
+ );
+ }
+}
+
+#[tokio::test]
+async fn web_search_returns_memory_query_order_without_an_embedder() {
+ let s = seed().await;
+ let mcp = server(&s, None);
+ let web = web(&s, None);
+ for query in QUERIES {
+ let expected = mcp_paths(&mcp, query, false).await;
+ assert_eq!(api_paths(&web, query).await, expected, "{query}: /api/v1");
+ assert_eq!(
+ web_paths(&web, query, true).await,
+ expected,
+ "{query}: /web"
+ );
+ }
+}
+
+#[tokio::test]
+async fn scoped_api_search_merges_scopes_like_memory_query() {
+ let s = seed().await;
+ let mcp = server(&s, Some(embedder()));
+ let web = web(&s, Some(embedder()));
+ for query in QUERIES {
+ let response = memory_query(
+ &mcp,
+ json!({
+ "query": query,
+ "scopes": [
+ {"workspace": "default", "project": "alpha"},
+ {"workspace": "default", "project": "beta"}
+ ],
+ "limit": LIMIT,
+ }),
+ )
+ .await;
+ let expected = paths(&response["hits"]);
+ let req = Request::builder()
+ .method("POST")
+ .uri("/api/v1/search")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ json!({
+ "q": query,
+ "scopes": [
+ {"workspace": "default", "project": "alpha"},
+ {"workspace": "default", "project": "beta"}
+ ],
+ "limit": LIMIT,
+ })
+ .to_string(),
+ ))
+ .unwrap();
+ let resp = web.clone().oneshot(req).await.unwrap();
+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)
+ .await
+ .unwrap();
+ let got = paths(&serde_json::from_slice(&bytes).unwrap());
+ assert_eq!(got, expected, "{query}: scopes");
+ }
+}
+
+/// The parity assertions above can fail: without the embedder (the web
+/// search before it was injected) or with the old FTS-only scoped search,
+/// at least one query ranks differently from a `memory_query` that embeds.
+#[tokio::test]
+async fn parity_controls_detect_a_web_search_that_skips_the_ranker() {
+ let s = seed().await;
+ let mcp = server(&s, Some(embedder()));
+ let web_without_embedder = web(&s, None);
+ let mut differs_without_embedder = false;
+ let mut differs_from_fts_only = false;
+ for query in QUERIES {
+ let expected = mcp_paths(&mcp, query, false).await;
+ differs_without_embedder |= api_paths(&web_without_embedder, query).await != expected;
+ let fts_only: Vec<String> = s
+ .store
+ .reader
+ .search_pages_for_project(s.ws, s.alpha, (*query).to_owned(), LIMIT, None)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|hit| hit.path.as_str().to_owned())
+ .collect();
+ differs_from_fts_only |= fts_only != expected;
+ }
+ assert!(
+ differs_without_embedder,
+ "the vector stream never moved the order; the embedder parity test proves nothing"
+ );
+ assert!(
+ differs_from_fts_only,
+ "FTS-only search matched the hybrid ranker everywhere; the parity test proves nothing"
+ );
+}
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index f38a17b2..65776365 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -86,16 +86,16 @@ pub use reader::{
AutoImproveParkedClaim, BriefPageBody, BriefingPage, BriefingSnapshot, ClientActivity,
ContaminationFinding, ContaminationReport, ContaminationSummary, ContradictionEdge,
DecayCandidate, DecayTombstone, DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding,
- GraphVia, HealthDetail, HealthPage, InboxCount, InboxEntry, ObservationHit, ObservationOrder,
- ObservationPage, ObservationPageResult, ObservationRecord, OpenSession,
+ GraphVia, HealthDetail, HealthPage, HybridSearch, InboxCount, InboxEntry, ObservationHit,
+ ObservationOrder, ObservationPage, ObservationPageResult, ObservationRecord, OpenSession,
PAGE_VERSIONS_MAX_LIMIT, PageAuthor, PageHit, PageHitWithMeta, PageLinks, PageMeta,
PageSummary, PageVersion, PageVersionBody, PageVersions, ProjectCoordinateCollisionReason,
ProjectCoordinateDiagnostic, ProjectCoordinateStatus, ProjectSummary, RELATED_WALK_MAX_DEPTH,
RELATED_WALK_MAX_NODES, ReaderPool, ReindexTargetStatus, RelatedNode, RelatedPage,
- RrfContributions, ScopeRow, SearchExplain, SessionConsolidationSummary, SessionDependentRows,
- SessionEndDisposition, SessionSummary, SettledPage, StatusCounts, StorageStatus,
- StoredEmbedding, StoredPageBody, StreamTimings, WorkspaceScopeRow, WorkspaceSummary,
- f32_vec_to_bytes,
+ RrfContributions, ScopeRow, SearchExplain, SessionConsolidationQueue,
+ SessionConsolidationSummary, SessionDependentRows, SessionEndDisposition, SessionSummary,
+ SettledPage, StatusCounts, StorageStatus, StoredEmbedding, StoredPageBody, StreamTimings,
+ VectorQuery, WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
};
pub use retrieval_tuning::{RetrievalTuning, is_session_recall_query};
pub use scope::{
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 791e8e24..5d338d56 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -729,6 +729,37 @@ fn is_zero(v: &f64) -> bool {
*v == 0.0
}
+/// A query embedding plus the stored-vector identity it may be compared
+/// against, borrowed for one [`ReaderPool::hybrid_search_scopes`] call.
+#[derive(Debug, Clone, Copy)]
+pub struct VectorQuery<'a> {
+ /// The query embedding.
+ pub vector: &'a [f32],
+ /// Provider of the eligible stored vectors.
+ pub provider: &'a str,
+ /// Model identity of the eligible stored vectors.
+ pub model: &'a str,
+ /// Dimensionality of the eligible stored vectors.
+ pub dim: u32,
+}
+
+/// One [`ReaderPool::hybrid_search_scopes`] request.
+#[derive(Debug, Clone, Copy)]
+pub struct HybridSearch<'a> {
+ /// Free-text query.
+ pub query: &'a str,
+ /// Query embedding; `None` skips the vector stream.
+ pub vector: Option<VectorQuery<'a>>,
+ /// Most hits returned.
+ pub limit: usize,
+ /// See [`ReaderPool::search_pages_for_project`]; `None` means now.
+ pub expiry_cutoff_us: Option<i64>,
+ /// Let superseded page versions into the candidate pool.
+ pub include_superseded: bool,
+ /// Attach per-hit [`SearchExplain`] and per-stream [`StreamTimings`].
+ pub explain: bool,
+}
+
/// Per-query wall time of each retrieval stream, in milliseconds, for an
/// `explain=true` query. Measured only on the explained path, so a normal
/// query takes no clock readings for it. A `None` field is a stream that did
@@ -963,6 +994,25 @@ pub struct SessionConsolidationSummary {
pub attempts: u32,
}
+/// Server-wide state of the SessionEnd consolidation queue, for the health
+/// panel. Counts and timestamps only: no session ids, scopes or provider
+/// error text.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
+pub struct SessionConsolidationQueue {
+ /// Jobs waiting for a worker (including ones backing off to retry).
+ pub pending: u64,
+ /// Jobs a worker holds right now.
+ pub running: u64,
+ /// Jobs that finished.
+ pub completed: u64,
+ /// Jobs that gave up after their attempts.
+ pub failed: u64,
+ /// Unix microseconds of the newest completed job, if any.
+ pub last_completed_at_us: Option<i64>,
+ /// Unix microseconds the oldest pending job was requested, if any.
+ pub oldest_pending_requested_at_us: Option<i64>,
+}
+
/// One session as listed from a scope by [`ReaderPool::sessions_for_scope`]
/// and [`ReaderPool::session_summary_scoped`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
@@ -5943,6 +5993,123 @@ impl ReaderPool {
))
}
+ /// The hybrid ranker over one or more resolved scopes — the single entry
+ /// point `memory_query` and the web search both rank project/scopes
+ /// results through.
+ ///
+ /// One scope returns [`Self::hybrid_search`]'s order untouched. Several
+ /// scopes are searched one at a time and merged: a page id found in more
+ /// than one keeps its best rank, then the union is sorted by rank, path
+ /// and id and cut to `search.limit`. Per-hit [`SearchExplain`] and the
+ /// summed [`StreamTimings`] are returned only when `search.explain` asks
+ /// for them; the normal path reads no clock for them.
+ ///
+ /// The caller resolves `scopes` (and so decides who may read them); this
+ /// never widens past them.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn hybrid_search_scopes(
+ &self,
+ scopes: &[(WorkspaceId, ProjectId)],
+ search: HybridSearch<'_>,
+ ) -> StoreResult<(Vec<(PageHit, Option<SearchExplain>)>, Option<StreamTimings>)> {
+ // Provider/model/dim only select which stored vectors are eligible;
+ // with no query vector the vector stream never runs, so the empty
+ // triple is inert rather than a fake identity.
+ let (vector, provider, model, dim) = match search.vector {
+ Some(v) => (
+ Some(v.vector.to_vec()),
+ v.provider.to_owned(),
+ v.model.to_owned(),
+ v.dim,
+ ),
+ None => (None, String::new(), String::new(), 0),
+ };
+ let mut timings: Option<StreamTimings> = None;
+ let mut per_scope = Vec::with_capacity(scopes.len());
+ for &(workspace_id, project_id) in scopes {
+ let (hits, scope_timings) = self
+ .hybrid_search_inner(
+ workspace_id,
+ project_id,
+ search.query.to_owned(),
+ vector.clone(),
+ provider.clone(),
+ model.clone(),
+ dim,
+ search.limit,
+ search.expiry_cutoff_us,
+ search.explain,
+ search.include_superseded,
+ )
+ .await?;
+ if search.explain {
+ timings
+ .get_or_insert_with(Default::default)
+ .accumulate(&scope_timings);
+ }
+ per_scope.push(hits);
+ }
+ let hits = if per_scope.len() == 1 {
+ per_scope.pop().unwrap_or_default()
+ } else {
+ let mut hits_by_id: std::collections::HashMap<
+ PageId,
+ (PageHit, Option<SearchExplain>),
+ > = std::collections::HashMap::new();
+ for hit in per_scope.into_iter().flatten() {
+ match hits_by_id.entry(hit.0.id) {
+ std::collections::hash_map::Entry::Occupied(mut existing) => {
+ if hit.0.rank < existing.get().0.rank {
+ existing.insert(hit);
+ }
+ }
+ std::collections::hash_map::Entry::Vacant(slot) => {
+ slot.insert(hit);
+ }
+ }
+ }
+ let mut hits: Vec<(PageHit, Option<SearchExplain>)> =
+ hits_by_id.into_values().collect();
+ hits.sort_by(|a, b| {
+ a.0.rank
+ .partial_cmp(&b.0.rank)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ .then_with(|| a.0.path.as_str().cmp(b.0.path.as_str()))
+ .then_with(|| a.0.id.as_bytes().cmp(b.0.id.as_bytes()))
+ });
+ hits.truncate(search.limit);
+ hits
+ };
+ let hits = if search.explain {
+ hits.into_iter()
+ .map(|(hit, explain)| (hit, Some(explain.unwrap_or_default())))
+ .collect()
+ } else {
+ hits
+ };
+ Ok((hits, timings))
+ }
+
+ /// The streams [`Self::hybrid_search_scopes`] runs for a query, in the
+ /// order `memory_query` reports them as `streams_active`.
+ #[must_use]
+ pub fn active_streams(&self, has_query_vector: bool) -> Vec<&'static str> {
+ let mut streams = vec!["fts", "entity"];
+ if has_query_vector {
+ streams.push("vector");
+ if self.tuning.abstract_vectors {
+ streams.push("abstract");
+ }
+ }
+ streams.push("graph");
+ if self.tuning.observation_stream {
+ streams.push("observation");
+ }
+ streams
+ }
+
#[allow(clippy::too_many_arguments)]
async fn hybrid_search_inner(
&self,
@@ -10499,6 +10666,46 @@ impl ReaderPool {
.await
}
+ /// Server-wide [`SessionConsolidationQueue`] state.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn session_consolidation_queue(&self) -> StoreResult<SessionConsolidationQueue> {
+ self.with_conn(|conn| {
+ let mut queue = SessionConsolidationQueue::default();
+ let mut stmt = conn
+ .prepare("SELECT state, COUNT(*) FROM session_consolidation_jobs GROUP BY state")?;
+ let rows = stmt.query_map([], |row| {
+ Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
+ })?;
+ for row in rows {
+ let (state, n) = row?;
+ let n = u64::try_from(n).unwrap_or(0);
+ match state.as_str() {
+ "pending" => queue.pending = n,
+ "running" => queue.running = n,
+ "completed" => queue.completed = n,
+ "failed" => queue.failed = n,
+ _ => {}
+ }
+ }
+ queue.last_completed_at_us = conn.query_row(
+ "SELECT MAX(completed_at) FROM session_consolidation_jobs \
+ WHERE state = 'completed'",
+ [],
+ |row| row.get(0),
+ )?;
+ queue.oldest_pending_requested_at_us = conn.query_row(
+ "SELECT MIN(requested_at) FROM session_consolidation_jobs \
+ WHERE state = 'pending'",
+ [],
+ |row| row.get(0),
+ )?;
+ Ok(queue)
+ })
+ .await
+ }
+
/// Physical storage figures for the database file.
///
/// Three `PRAGMA` reads, no table scan, so it is cheap enough to sit in
diff --git a/crates/ai-memory-store/tests/suite/session_observations.rs b/crates/ai-memory-store/tests/suite/session_observations.rs
index a7f53461..693e57ca 100644
--- a/crates/ai-memory-store/tests/suite/session_observations.rs
+++ b/crates/ai-memory-store/tests/suite/session_observations.rs
@@ -765,3 +765,64 @@ async fn mixed_capture_count_scopes_observations_and_preserves_owner_and_window(
.is_empty()
);
}
+
+/// The health panel's server-wide queue read: counts per state, the newest
+/// completion and the oldest pending request. No ids, scopes or error text.
+#[tokio::test]
+async fn consolidation_queue_counts_states_and_bounds_times() {
+ let (_tmp, store) = open_seeded();
+ assert_eq!(
+ store.reader.session_consolidation_queue().await.unwrap(),
+ ai_memory_store::SessionConsolidationQueue::default(),
+ "an empty queue reports nothing"
+ );
+ let conn = Connection::open(store.db_path()).unwrap();
+ for (sid, proj, generation, state, requested, completed, error) in [
+ (10, proj_a(), 1, "completed", NOW, Some(NOW + 5), None),
+ (10, proj_a(), 2, "pending", NOW + 10, None, None),
+ (11, proj_a(), 1, "pending", NOW + 3, None, None),
+ (12, proj_b(), 1, "completed", NOW + 1, Some(NOW + 9), None),
+ (
+ 12,
+ proj_b(),
+ 2,
+ "failed",
+ NOW + 2,
+ Some(NOW + 20),
+ Some("sk-provider-body"),
+ ),
+ (13, proj_a(), 1, "running", NOW + 4, None, None),
+ (13, proj_a(), 2, "superseded", NOW + 4, None, None),
+ ] {
+ conn.execute(
+ "INSERT INTO session_consolidation_jobs \
+ (session_id, workspace_id, project_id, generation, state, requested_at, \
+ next_attempt_at, completed_at, attempts, last_error) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, ?7, 1, ?8)",
+ params![
+ session(sid).as_bytes(),
+ ws().as_bytes(),
+ proj.as_bytes(),
+ generation,
+ state,
+ requested,
+ completed,
+ error
+ ],
+ )
+ .unwrap();
+ }
+ let queue = store.reader.session_consolidation_queue().await.unwrap();
+ assert_eq!(
+ queue,
+ ai_memory_store::SessionConsolidationQueue {
+ pending: 2,
+ running: 1,
+ completed: 2,
+ failed: 1,
+ // The failed job's later `completed_at` is not a completion.
+ last_completed_at_us: Some(NOW + 9),
+ oldest_pending_requested_at_us: Some(NOW + 3),
+ }
+ );
+}
diff --git a/crates/ai-memory-web/Cargo.toml b/crates/ai-memory-web/Cargo.toml
index 90978bc7..7d856c83 100644
--- a/crates/ai-memory-web/Cargo.toml
+++ b/crates/ai-memory-web/Cargo.toml
@@ -10,6 +10,7 @@ description = "Read-only HTTP browser for the ai-memory wiki (project list, tree
[dependencies]
ai-memory-core.workspace = true
+ai-memory-llm.workspace = true
ai-memory-store.workspace = true
ai-memory-wiki.workspace = true
anyhow.workspace = true
@@ -34,6 +35,7 @@ anyhow.workspace = true
sha2.workspace = true
[dev-dependencies]
+async-trait.workspace = true
rusqlite.workspace = true
tempfile.workspace = true
tower.workspace = true
diff --git a/crates/ai-memory-web/src/health.rs b/crates/ai-memory-web/src/health.rs
new file mode 100644
index 00000000..03d9be47
--- /dev/null
+++ b/crates/ai-memory-web/src/health.rs
@@ -0,0 +1,551 @@
+//! The root-only health page's data model and its checks.
+//!
+//! Everything here is a count, a timestamp, a configured provider/model
+//! label or a fixed fix command. Nothing reads page bodies, prompts,
+//! observations, scope names, provider error text or credentials, so the page
+//! cannot leak them however the counters move.
+//!
+//! The hook counters are the process [`IngestMetrics`] that
+//! `GET /admin/metrics` and `ai-memory status` read; the fix lines come from
+//! [`ai_memory_core::fix_lines`], the same constants `ai-memory status`
+//! prints.
+
+use std::sync::Arc;
+
+use ai_memory_core::{IngestMetrics, IngestMetricsSnapshot, fix_lines};
+use ai_memory_llm::{ProviderHealth, ProviderHealthSnapshot, ProviderHealthStatus};
+use ai_memory_store::{DerivedIndexStatus, SessionConsolidationQueue, StorageStatus};
+
+/// Process-side state the server holds outside SQLite, read once per page
+/// load. `serve` implements it over the writer queue, the local hook spool
+/// and the recovery journal in its data directory.
+pub trait HealthProbe: Send + Sync {
+ /// Write-queue depth, local spool and recovery journal, as far as this
+ /// process can see them.
+ fn process_state(&self) -> ProcessState;
+}
+
+/// Process-side state for one page load. `None` means the server cannot
+/// see that part (a hook client on another machine spools there, not here).
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct ProcessState {
+ /// `(queued, capacity)` of the single writer's channel.
+ pub write_queue: Option<(usize, usize)>,
+ /// The hook spool under this server's data directory.
+ pub spool: Option<SpoolState>,
+ /// The recovery journal under this server's data directory.
+ pub journal: Option<JournalState>,
+}
+
+/// Local hook spool counts. Content-free, like the spool's own health read.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct SpoolState {
+ /// Events queued for delivery.
+ pub pending: usize,
+ /// Age of the oldest queued event, in milliseconds.
+ pub oldest_age_ms: Option<u64>,
+ /// Failed delivery attempts summed over the queued events.
+ pub retries_total: u64,
+ /// Most events the spool holds before it evicts the oldest.
+ pub capacity: usize,
+}
+
+/// Recovery journal counts.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct JournalState {
+ /// Journaled runs waiting for `ai-memory recover`.
+ pub pending: usize,
+ /// Of those, runs that degraded mid-flight.
+ pub degraded: usize,
+ /// Of those, runs whose finish step failed.
+ pub finish_failed: usize,
+ /// The journal exists but could not be read. Its error text is not kept:
+ /// it can carry a path.
+ pub unreadable: bool,
+}
+
+/// What `serve` hands the web state for the health page.
+#[derive(Clone)]
+pub struct HealthSources {
+ /// The hook ingestion counters the `/hook` router records into.
+ pub ingest: Arc<IngestMetrics>,
+ /// Passive provider health the LLM and embedder wrappers record into.
+ pub providers: ProviderHealth,
+ /// Writer queue, spool and journal.
+ pub probe: Arc<dyn HealthProbe>,
+}
+
+/// The configured embedder's identity, as the vector stream matches it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct EmbedderIdentity {
+ /// Provider label.
+ pub provider: String,
+ /// Model identity stored next to each vector.
+ pub model: String,
+ /// Vector dimensionality.
+ pub dim: u32,
+}
+
+/// Every input of one health page load.
+#[derive(Debug, Clone)]
+pub struct HealthSnapshot {
+ /// Hook counters since the server started.
+ pub ingest: IngestMetricsSnapshot,
+ /// LLM and embedding provider health.
+ pub providers: ProviderHealthSnapshot,
+ /// Writer queue, spool, journal.
+ pub process: ProcessState,
+ /// Derived-index readiness.
+ pub derived: DerivedIndexStatus,
+ /// Database file and reclaimable space.
+ pub storage: StorageStatus,
+ /// SessionEnd consolidation queue.
+ pub consolidation: SessionConsolidationQueue,
+ /// The configured embedder; `None` on a zero-LLM server.
+ pub embedder: Option<EmbedderIdentity>,
+}
+
+/// How bad one check is.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CheckStatus {
+ /// Worth a look; nothing is lost yet.
+ Warn,
+ /// Something is failing or being lost.
+ Error,
+}
+
+impl CheckStatus {
+ /// Display label.
+ #[must_use]
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::Warn => "warn",
+ Self::Error => "error",
+ }
+ }
+}
+
+/// One failed check, with the command that fixes it when one exists.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct HealthCheck {
+ /// Stable identifier, for tests and anchors.
+ pub id: &'static str,
+ /// Severity.
+ pub status: CheckStatus,
+ /// What is wrong, with the counts that show it.
+ pub detail: String,
+ /// The exact command to run, when there is one.
+ pub fix: Option<String>,
+}
+
+/// The checks that fail for `s`, most severe first. An empty list is a
+/// healthy server.
+#[must_use]
+pub fn checks(s: &HealthSnapshot) -> Vec<HealthCheck> {
+ let mut out = Vec::new();
+ let mut push = |id, status, detail: String, fix: Option<&str>| {
+ out.push(HealthCheck {
+ id,
+ status,
+ detail,
+ fix: fix.map(str::to_owned),
+ });
+ };
+
+ let shed = s.ingest.shed_saturated + s.ingest.shed_rate_limited;
+ if shed > 0 {
+ push(
+ "hook_shed",
+ CheckStatus::Warn,
+ format!(
+ "{shed} hook event(s) were answered 429 since the server started \
+ ({} saturated, {} rate-limited); clients spool and retry them.",
+ s.ingest.shed_saturated, s.ingest.shed_rate_limited
+ ),
+ None,
+ );
+ }
+ if s.ingest.failed > 0 {
+ push(
+ "hook_failed",
+ CheckStatus::Error,
+ format!(
+ "{} hook delivery(ies) failed to store since the server started.",
+ s.ingest.failed
+ ),
+ None,
+ );
+ }
+ if let Some((queued, capacity)) = s.process.write_queue
+ && capacity > 0
+ && queued.saturating_mul(4) >= capacity.saturating_mul(3)
+ {
+ push(
+ "write_queue",
+ CheckStatus::Warn,
+ format!("The write queue holds {queued} of {capacity} commands."),
+ None,
+ );
+ }
+ if let Some(spool) = s.process.spool {
+ if spool.capacity > 0 && spool.pending >= spool.capacity {
+ push(
+ "spool_evicting",
+ CheckStatus::Error,
+ format!(
+ "The hook spool is full ({} events): each new event evicts the oldest \
+ undelivered one.",
+ spool.pending
+ ),
+ Some(fix_lines::RECOVER),
+ );
+ } else if spool.pending > 0 {
+ push(
+ "spool_pending",
+ CheckStatus::Warn,
+ format!("{} hook event(s) wait in the local spool.", spool.pending),
+ Some(fix_lines::RECOVER),
+ );
+ }
+ }
+ if let Some(journal) = s.process.journal {
+ if journal.unreadable {
+ push(
+ "journal_unreadable",
+ CheckStatus::Error,
+ "The recovery journal could not be read.".to_owned(),
+ Some(fix_lines::RECOVER),
+ );
+ } else if journal.pending > 0 {
+ push(
+ "journal_pending",
+ CheckStatus::Warn,
+ format!(
+ "{} run(s) wait in the recovery journal ({} degraded, {} finish-failed).",
+ journal.pending, journal.degraded, journal.finish_failed
+ ),
+ Some(fix_lines::RECOVER),
+ );
+ }
+ }
+ if s.providers.llm.status == ProviderHealthStatus::Error {
+ push(
+ "llm_provider",
+ CheckStatus::Error,
+ format!(
+ "The LLM provider's last call failed{}.",
+ s.providers
+ .llm
+ .last_error_status
+ .map(|status| format!(" (HTTP {status})"))
+ .unwrap_or_default()
+ ),
+ s.providers.llm.retry_hint.as_deref(),
+ );
+ }
+ if s.providers.embedding.status == ProviderHealthStatus::Error {
+ push(
+ "embedding_provider",
+ CheckStatus::Error,
+ format!(
+ "The embedding provider's last call failed{}; searches run without the \
+ vector stream until it answers.",
+ s.providers
+ .embedding
+ .last_error_status
+ .map(|status| format!(" (HTTP {status})"))
+ .unwrap_or_default()
+ ),
+ None,
+ );
+ }
+ if let Some(embedder) = &s.embedder {
+ let stale: u64 = s
+ .derived
+ .embedding_triples
+ .iter()
+ .filter(|t| {
+ t.provider != embedder.provider
+ || t.model != embedder.model
+ || t.dim != embedder.dim
+ })
+ .map(|t| t.count)
+ .sum();
+ if stale > 0 {
+ push(
+ "stale_vectors",
+ CheckStatus::Warn,
+ format!(
+ "{stale} stored vector(s) were made under another provider, model or \
+ dimension and are ignored."
+ ),
+ Some(fix_lines::EMBED_FORCE),
+ );
+ }
+ let missing = s.derived.latest_pages_missing_embeddings;
+ let failed = s.derived.embed_failures_unresolved;
+ if missing > 0 || failed > 0 {
+ push(
+ "missing_vectors",
+ CheckStatus::Warn,
+ format!(
+ "{missing} latest page(s) have no vector ({failed} after a failed or \
+ skipped embed)."
+ ),
+ Some(fix_lines::EMBED),
+ );
+ }
+ }
+ if fix_lines::reclaim_advised(s.storage.reclaimable_bytes, s.storage.database_bytes) {
+ push(
+ "storage_reclaim",
+ CheckStatus::Warn,
+ format!(
+ "{} of the {}-byte database is reclaimable; compacting blocks writes while \
+ it runs.",
+ s.storage.reclaimable_bytes, s.storage.database_bytes
+ ),
+ Some(fix_lines::COMPACT),
+ );
+ }
+ if s.consolidation.failed > 0 {
+ push(
+ "consolidation_failed",
+ CheckStatus::Warn,
+ format!(
+ "{} session consolidation job(s) gave up after their retries.",
+ s.consolidation.failed
+ ),
+ None,
+ );
+ }
+ out.sort_by_key(|check| match check.status {
+ CheckStatus::Error => 0,
+ CheckStatus::Warn => 1,
+ });
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ai_memory_store::EmbeddingTripleCount;
+
+ /// A healthy server: every input present, nothing failing.
+ fn healthy() -> HealthSnapshot {
+ HealthSnapshot {
+ ingest: IngestMetrics::default().snapshot(),
+ providers: ProviderHealthSnapshot::default(),
+ process: ProcessState {
+ write_queue: Some((0, 1024)),
+ spool: Some(SpoolState {
+ capacity: 500,
+ ..SpoolState::default()
+ }),
+ journal: Some(JournalState::default()),
+ },
+ derived: DerivedIndexStatus::default(),
+ storage: StorageStatus::default(),
+ consolidation: SessionConsolidationQueue::default(),
+ embedder: Some(EmbedderIdentity {
+ provider: "synthetic".into(),
+ model: "bag-of-words-v1".into(),
+ dim: 16,
+ }),
+ }
+ }
+
+ fn only(snapshot: &HealthSnapshot) -> HealthCheck {
+ let found = checks(snapshot);
+ assert_eq!(found.len(), 1, "{found:?}");
+ found.into_iter().next().unwrap()
+ }
+
+ #[test]
+ fn a_healthy_server_fails_no_check() {
+ assert_eq!(checks(&healthy()), Vec::new());
+ }
+
+ #[test]
+ fn shed_hooks_warn_without_a_fix() {
+ let ingest = IngestMetrics::default();
+ ingest.record_shed_rate_limited();
+ let snapshot = HealthSnapshot {
+ ingest: ingest.snapshot(),
+ ..healthy()
+ };
+ let check = only(&snapshot);
+ assert_eq!(
+ (check.id, check.status, check.fix),
+ ("hook_shed", CheckStatus::Warn, None)
+ );
+ }
+
+ #[test]
+ fn failed_deliveries_are_an_error() {
+ let ingest = IngestMetrics::default();
+ ingest.record_failed();
+ let snapshot = HealthSnapshot {
+ ingest: ingest.snapshot(),
+ ..healthy()
+ };
+ let check = only(&snapshot);
+ assert_eq!(
+ (check.id, check.status),
+ ("hook_failed", CheckStatus::Error)
+ );
+ }
+
+ #[test]
+ fn a_three_quarters_full_write_queue_warns() {
+ let mut snapshot = healthy();
+ snapshot.process.write_queue = Some((767, 1024));
+ assert!(checks(&snapshot).is_empty(), "below three quarters");
+ snapshot.process.write_queue = Some((768, 1024));
+ assert_eq!(only(&snapshot).id, "write_queue");
+ }
+
+ #[test]
+ fn spool_and_journal_point_at_recover() {
+ let mut snapshot = healthy();
+ snapshot.process.spool = Some(SpoolState {
+ pending: 3,
+ capacity: 500,
+ ..SpoolState::default()
+ });
+ let check = only(&snapshot);
+ assert_eq!(check.id, "spool_pending");
+ assert_eq!(check.fix.as_deref(), Some(fix_lines::RECOVER));
+
+ snapshot.process.spool = Some(SpoolState {
+ pending: 500,
+ capacity: 500,
+ ..SpoolState::default()
+ });
+ let check = only(&snapshot);
+ assert_eq!(
+ (check.id, check.status),
+ ("spool_evicting", CheckStatus::Error)
+ );
+ assert_eq!(check.fix.as_deref(), Some(fix_lines::RECOVER));
+
+ let mut snapshot = healthy();
+ snapshot.process.journal = Some(JournalState {
+ pending: 2,
+ ..JournalState::default()
+ });
+ let check = only(&snapshot);
+ assert_eq!(check.id, "journal_pending");
+ assert_eq!(check.fix.as_deref(), Some(fix_lines::RECOVER));
+
+ snapshot.process.journal = Some(JournalState {
+ unreadable: true,
+ ..JournalState::default()
+ });
+ assert_eq!(only(&snapshot).id, "journal_unreadable");
+ }
+
+ #[test]
+ fn an_unseen_spool_or_journal_is_not_a_failure() {
+ let mut snapshot = healthy();
+ snapshot.process = ProcessState::default();
+ assert!(checks(&snapshot).is_empty());
+ }
+
+ #[test]
+ fn provider_errors_carry_the_llm_retry_hint_only() {
+ let mut snapshot = healthy();
+ snapshot.providers.llm.status = ProviderHealthStatus::Error;
+ snapshot.providers.llm.last_error_status = Some(429);
+ snapshot.providers.llm.retry_hint = Some("ai-memory llm-test --prompt ping".into());
+ snapshot.providers.llm.last_error_message = Some("sk-secret-body".into());
+ let check = only(&snapshot);
+ assert_eq!(check.id, "llm_provider");
+ assert_eq!(
+ check.fix.as_deref(),
+ Some("ai-memory llm-test --prompt ping")
+ );
+ assert!(check.detail.contains("HTTP 429"), "{}", check.detail);
+ assert!(!check.detail.contains("sk-secret-body"), "{}", check.detail);
+
+ let mut snapshot = healthy();
+ snapshot.providers.embedding.status = ProviderHealthStatus::Error;
+ snapshot.providers.embedding.last_error_message = Some("sk-secret-body".into());
+ let check = only(&snapshot);
+ assert_eq!((check.id, check.fix.clone()), ("embedding_provider", None));
+ assert!(!check.detail.contains("sk-secret-body"), "{}", check.detail);
+ }
+
+ fn triple(provider: &str, model: &str, dim: u32, count: u64) -> EmbeddingTripleCount {
+ EmbeddingTripleCount {
+ provider: provider.into(),
+ model: model.into(),
+ dim,
+ count,
+ }
+ }
+
+ #[test]
+ fn vectors_under_another_identity_are_stale() {
+ let mut snapshot = healthy();
+ snapshot.derived.embedding_triples = vec![
+ triple("synthetic", "bag-of-words-v1", 16, 10),
+ triple("synthetic", "bag-of-words-v1", 8, 3),
+ triple("openai", "bag-of-words-v1", 16, 2),
+ ];
+ let check = only(&snapshot);
+ assert_eq!(check.id, "stale_vectors");
+ assert!(check.detail.starts_with("5 stored"), "{}", check.detail);
+ assert_eq!(check.fix.as_deref(), Some(fix_lines::EMBED_FORCE));
+ }
+
+ #[test]
+ fn missing_vectors_point_at_embed() {
+ let mut snapshot = healthy();
+ snapshot.derived.latest_pages_missing_embeddings = 4;
+ snapshot.derived.embed_failures_unresolved = 1;
+ let check = only(&snapshot);
+ assert_eq!(check.id, "missing_vectors");
+ assert_eq!(check.fix.as_deref(), Some(fix_lines::EMBED));
+ }
+
+ #[test]
+ fn vector_checks_need_a_configured_embedder() {
+ let mut snapshot = healthy();
+ snapshot.embedder = None;
+ snapshot.derived.latest_pages_missing_embeddings = 4;
+ snapshot.derived.embedding_triples = vec![triple("x", "y", 3, 1)];
+ assert!(checks(&snapshot).is_empty());
+ }
+
+ #[test]
+ fn reclaimable_storage_points_at_compact() {
+ let mut snapshot = healthy();
+ snapshot.storage.database_bytes = 1024 * 1024 * 1024;
+ snapshot.storage.reclaimable_bytes = 300 * 1024 * 1024;
+ let check = only(&snapshot);
+ assert_eq!(check.id, "storage_reclaim");
+ assert_eq!(check.fix.as_deref(), Some(fix_lines::COMPACT));
+ }
+
+ #[test]
+ fn failed_consolidation_jobs_warn() {
+ let mut snapshot = healthy();
+ snapshot.consolidation.failed = 2;
+ let check = only(&snapshot);
+ assert_eq!((check.id, check.fix), ("consolidation_failed", None));
+ }
+
+ #[test]
+ fn errors_sort_before_warnings() {
+ let ingest = IngestMetrics::default();
+ ingest.record_shed_saturated();
+ ingest.record_failed();
+ let snapshot = HealthSnapshot {
+ ingest: ingest.snapshot(),
+ ..healthy()
+ };
+ let ids: Vec<_> = checks(&snapshot).into_iter().map(|c| c.id).collect();
+ assert_eq!(ids, ["hook_failed", "hook_shed"]);
+ }
+}
diff --git a/crates/ai-memory-web/src/lib.rs b/crates/ai-memory-web/src/lib.rs
index 79685722..fbf4e344 100644
--- a/crates/ai-memory-web/src/lib.rs
+++ b/crates/ai-memory-web/src/lib.rs
@@ -13,9 +13,12 @@
//! - `GET /w/:workspace/:project/p/*path` → rendered markdown + metadata
//! - `GET /w/:workspace/:project/h/*path` → version history + unified diff
//! - `GET /w/:workspace/:project/s/:session` → session timeline, paged
-//! - `GET /search?q=…` → FTS5 hit list
+//! - `GET /search?q=…` → cross-project FTS5 hit list
+//! - `GET /search?q=…&workspace=…&project=…&explain=1` → project search
+//! through `memory_query`'s hybrid ranker, with the recall trace
//! - `GET /pending` → root-only pending-writes triage;
//! its buttons post to `/admin/pending-writes/*`, not to this crate
+//! - `GET /health` → root-only server health panel
//! - `GET /login` / `GET /change-password` → public human-auth HTML forms
//! - `GET /static/*` → embedded CSS + logo (public)
//!
@@ -34,9 +37,11 @@ use ai_memory_wiki::Wiki;
use axum::Router;
mod diff;
+pub mod health;
mod html_auth;
mod markdown;
pub mod mount;
+pub mod recall;
mod routes;
mod state;
mod templates;
@@ -46,6 +51,7 @@ pub use mount::{
SplitWebRouters, WebMountSpec, inject_base_href, inject_base_path_meta, normalize_prefix,
split_web_routers, web_base_href,
};
+pub use recall::Recall;
pub use state::WebState;
/// Build the read-only web router. Call once at server startup and
diff --git a/crates/ai-memory-web/src/mount.rs b/crates/ai-memory-web/src/mount.rs
index 3b93f6ee..9e15e5b0 100644
--- a/crates/ai-memory-web/src/mount.rs
+++ b/crates/ai-memory-web/src/mount.rs
@@ -314,6 +314,11 @@ pub struct WebMountSpec<'a> {
/// A trusted identity proxy is configured; the root-only pending-writes
/// page needs it to decide whether operators are told apart.
pub trusted_proxy_identity: bool,
+ /// The server's configured embedder and reranker, so project search in
+ /// `/web` and `/api/v1` ranks like `memory_query`.
+ pub recall: crate::Recall,
+ /// Process-side sources for the root-only health page.
+ pub health: Option<Arc<crate::health::HealthSources>>,
}
/// Public SPA vs dual-auth wiki/API split.
@@ -379,7 +384,13 @@ fn split_web_routers_unframed(
html_auth: None,
});
}
- let api = build_api_router(&reader, &wiki, spec.cors_origins);
+ let mut state = crate::WebState::new(reader, wiki)
+ .with_trusted_proxy_identity(spec.trusted_proxy_identity)
+ .with_recall(spec.recall);
+ if let Some(health) = spec.health {
+ state = state.with_health(health);
+ }
+ let api = build_api_router(state.clone(), spec.cors_origins);
let protected_api = axum::Router::new().nest("/api/v1", api);
if !enable_web {
return Ok(SplitWebRouters {
@@ -422,14 +433,7 @@ fn split_web_routers_unframed(
spec.base_path,
mount,
),
- protected: mount_builtin_browser(
- protected_api,
- crate::WebState::new(reader, wiki)
- .with_trusted_proxy_identity(spec.trusted_proxy_identity),
- &slug,
- mount,
- browser_inject,
- ),
+ protected: mount_builtin_browser(protected_api, state, &slug, mount, browser_inject),
html_auth: Some(auth_cfg),
})
}
@@ -453,8 +457,8 @@ fn mount_web_router(
/// the operator configured any. The layer is scoped to this router only
/// (CORS_NOT_APPLIED_TO_OTHER_ROUTES invariant — `/mcp`, `/hook`,
/// `/admin`, and `/web` must remain CORS-free).
-fn build_api_router(reader: &ReaderPool, wiki: &Wiki, cors_origins: &[String]) -> axum::Router {
- let api = crate::api_router(reader.clone(), wiki.clone());
+fn build_api_router(state: crate::WebState, cors_origins: &[String]) -> axum::Router {
+ let api = crate::routes::build_api(Arc::new(state));
if cors_origins.is_empty() {
return api;
}
@@ -722,6 +726,8 @@ mod tests {
base_href: &base_href,
base_path: &base,
trusted_proxy_identity: false,
+ recall: crate::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -1124,6 +1130,8 @@ mod tests {
base_href: &base_href,
base_path: &base,
trusted_proxy_identity: false,
+ recall: crate::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -1202,6 +1210,8 @@ mod tests {
base_href: &base_href,
base_path: "",
trusted_proxy_identity: false,
+ recall: crate::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -1288,6 +1298,8 @@ mod tests {
base_href: &base_href,
base_path: "",
trusted_proxy_identity: false,
+ recall: crate::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -1358,6 +1370,8 @@ mod tests {
base_href: &base_href,
base_path: "",
trusted_proxy_identity: false,
+ recall: crate::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -1418,6 +1432,8 @@ mod tests {
base_href: &base_href,
base_path: &base,
trusted_proxy_identity: false,
+ recall: crate::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -1507,6 +1523,8 @@ mod tests {
base_href: "/web/",
base_path: "",
trusted_proxy_identity: false,
+ recall: crate::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -1564,6 +1582,8 @@ mod tests {
base_href: "/web/",
base_path: "",
trusted_proxy_identity: false,
+ recall: crate::Recall::default(),
+ health: None,
},
)
.unwrap();
@@ -1610,6 +1630,8 @@ mod tests {
base_href: "/web/",
base_path: "",
trusted_proxy_identity: false,
+ recall: crate::Recall::default(),
+ health: None,
},
)
.unwrap();
diff --git a/crates/ai-memory-web/src/recall.rs b/crates/ai-memory-web/src/recall.rs
new file mode 100644
index 00000000..520304af
--- /dev/null
+++ b/crates/ai-memory-web/src/recall.rs
@@ -0,0 +1,122 @@
+//! Project search through the same hybrid ranker as `memory_query`.
+//!
+//! `memory_query` ranks a project or `scopes` search in three steps: embed the
+//! query with the configured embedder, fuse the streams with
+//! [`ReaderPool::hybrid_search_scopes`], then let the optional reranker reorder
+//! a bounded prefix. This module runs the same three steps over the same
+//! shared functions (`ai_memory_llm::embed_search_query`,
+//! `hybrid_search_scopes`, `ai_memory_llm::RerankStage`), so a query returns
+//! the same order from the web as from MCP. The parity test in
+//! `ai-memory-mcp/tests/suite/web_search_parity.rs` holds the two together.
+//!
+//! The caller resolves the scopes through the guarded scope helpers, so a
+//! search never reaches past what the viewer may read.
+//!
+//! [`ReaderPool::hybrid_search_scopes`]: ai_memory_store::ReaderPool::hybrid_search_scopes
+
+use std::sync::Arc;
+
+use ai_memory_core::{ProjectId, WorkspaceId};
+use ai_memory_llm::{Embedder, QueryVector, RerankCandidate, RerankStage};
+use ai_memory_store::{
+ HybridSearch, PageHit, SearchExplain, StoreResult, StreamTimings, VectorQuery,
+};
+
+use crate::state::WebState;
+
+/// The server's configured retrieval models, handed to the web state once
+/// at startup (invariant 1: `serve` reads config once and passes it down).
+#[derive(Clone, Default)]
+pub struct Recall {
+ /// The embedder `memory_query` uses; `None` skips the vector stream.
+ pub embedder: Option<Arc<dyn Embedder>>,
+ /// The rerank stage `memory_query` uses, sharing its concurrency gate;
+ /// `None` keeps the fused order.
+ pub rerank: Option<RerankStage>,
+}
+
+/// One ranked search and, when asked for, how it was ranked.
+pub(crate) struct RecallResult {
+ /// Hits best first, each with its explain details when `explain` was set.
+ pub hits: Vec<(PageHit, Option<SearchExplain>)>,
+ /// Per-stream wall time, summed over the scopes; `explain` only.
+ pub timings: Option<StreamTimings>,
+ /// The streams that ran, in `memory_query`'s `streams_active` order.
+ pub streams_active: Vec<&'static str>,
+}
+
+/// Rank `query` over `scopes` exactly as a `memory_query` project/scopes
+/// search does (latest versions only, expired pages hidden).
+pub(crate) async fn search_scopes(
+ state: &WebState,
+ scopes: &[(WorkspaceId, ProjectId)],
+ query: &str,
+ limit: usize,
+ explain: bool,
+) -> StoreResult<RecallResult> {
+ let query_vector: Option<QueryVector> = match &state.recall.embedder {
+ Some(embedder) => ai_memory_llm::embed_search_query(embedder.as_ref(), query).await,
+ None => None,
+ };
+ let fetch_limit = state
+ .recall
+ .rerank
+ .as_ref()
+ .map_or(limit, |stage| stage.fetch_limit(limit));
+ let (hits, mut timings) = state
+ .reader
+ .hybrid_search_scopes(
+ scopes,
+ HybridSearch {
+ query,
+ vector: query_vector.as_ref().map(|qv| VectorQuery {
+ vector: &qv.vector,
+ provider: &qv.provider,
+ model: &qv.model,
+ dim: qv.dim,
+ }),
+ limit: fetch_limit,
+ expiry_cutoff_us: None,
+ include_superseded: false,
+ explain,
+ },
+ )
+ .await?;
+ let hits = match &state.recall.rerank {
+ Some(stage) => {
+ let started = explain.then(std::time::Instant::now);
+ let hits = stage
+ .apply(
+ query,
+ hits,
+ limit,
+ ai_memory_llm::reranker::RERANK_TIMEOUT,
+ |(hit, _)| RerankCandidate {
+ id: hit.id.to_string(),
+ title: hit.title.clone(),
+ snippet: hit.snippet.clone(),
+ },
+ |(_, details), relevance| {
+ if let Some(details) = details.as_mut() {
+ details.rerank_score = Some(relevance);
+ }
+ },
+ )
+ .await;
+ if let (Some(timings), Some(started)) = (timings.as_mut(), started) {
+ timings.rerank_ms = Some(started.elapsed().as_secs_f64() * 1000.0);
+ }
+ hits
+ }
+ None => {
+ let mut hits = hits;
+ hits.truncate(limit);
+ hits
+ }
+ };
+ Ok(RecallResult {
+ hits,
+ timings,
+ streams_active: state.reader.active_streams(query_vector.is_some()),
+ })
+}
diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rs
index 26647020..aa5ecb5f 100644
--- a/crates/ai-memory-web/src/routes/api.rs
+++ b/crates/ai-memory-web/src/routes/api.rs
@@ -1,9 +1,8 @@
//! JSON routes for third-party read-only frontends.
-use std::collections::HashMap;
use std::sync::Arc;
-use ai_memory_core::{ObservationKind, PageId, PagePath, ProjectId, SessionId, WorkspaceId};
+use ai_memory_core::{ObservationKind, PagePath, ProjectId, SessionId, WorkspaceId};
use ai_memory_store::{
BriefingSnapshot, HealthPage, ObservationOrder, ObservationPage, ObservationRecord, PageHit,
RelatedPage, ScopeName, ScopeResolutionError, SessionSummary, lookup_existing_scope_guarded,
@@ -367,15 +366,10 @@ async fn search_post_handler(
search_with_request(&state, request, viewer_of(viewer)).await
}
-// NOTE (deferred): vector/semantic search. `ReaderPool::hybrid_search` already
-// RRF-fuses FTS5 + entity matching + 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`).
+// A global search is FTS5 over every readable repository, as
+// `memory_query(global=true)` is. A scoped one (one project or `scopes`)
+// runs the hybrid ranker `memory_query` runs, with the server's embedder
+// and reranker (`crate::recall`), so the two surfaces agree on order.
async fn search_with_request(
state: &WebState,
request: SearchRequest,
@@ -404,7 +398,15 @@ async fn search_with_request(
}
let hits = match scoped_search_mode(state, &request, viewer).await? {
SearchMode::Global => state.reader.search_pages(term, limit, viewer).await,
- SearchMode::Scoped(scopes) => search_scopes(state, scopes, term, limit).await,
+ SearchMode::Scoped(scopes) => {
+ let scopes: Vec<(WorkspaceId, ProjectId)> = scopes
+ .iter()
+ .map(|scope| (scope.workspace_id, scope.project_id))
+ .collect();
+ crate::recall::search_scopes(state, &scopes, &term, limit, false)
+ .await
+ .map(|result| result.hits.into_iter().map(|(hit, _)| hit).collect())
+ }
}
.map_err(internal_error)?;
@@ -479,45 +481,6 @@ async fn resolve_scopes(
.map_err(scope_error_response)
}
-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,
- None,
- )
- .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)
-}
-
#[derive(Deserialize)]
struct RecentQuery {
#[serde(default = "default_limit")]
diff --git a/crates/ai-memory-web/src/routes/health.rs b/crates/ai-memory-web/src/routes/health.rs
new file mode 100644
index 00000000..c508388a
--- /dev/null
+++ b/crates/ai-memory-web/src/routes/health.rs
@@ -0,0 +1,327 @@
+//! `GET /health` — root-only server health panel.
+//!
+//! Reads hook counters, the writer queue, the local spool and recovery
+//! journal, the consolidation queue, embedder and provider state, and runs
+//! the server-side checks in [`crate::health::checks`] with their fix lines.
+//! It only reads: there is no button on the page and no write path behind
+//! it. Root-only on a multi-user server through the same `Capability::Admin`
+//! gate as `/pending` and every `/admin/*` route, because the counters
+//! describe the whole server, not one repository.
+
+use std::sync::Arc;
+
+use ai_memory_core::{AuthLevel, IngestMetrics};
+use ai_memory_llm::{ProviderHealthSnapshot, ProviderRoleHealthSnapshot};
+use askama::Template;
+use axum::Extension;
+use axum::extract::State;
+use axum::http::{HeaderValue, StatusCode, header};
+use axum::response::{Html, IntoResponse, Response};
+
+use crate::health::{EmbedderIdentity, HealthSnapshot, ProcessState, checks};
+use crate::state::WebState;
+use crate::templates::{HealthCheckRow, HealthRow, HealthSection, HealthView};
+
+/// Handler for `GET /health`.
+pub(crate) async fn handler(
+ State(state): State<Arc<WebState>>,
+ level: Option<Extension<AuthLevel>>,
+) -> Response {
+ if let Err(response) = super::require_admin(&state, level).await {
+ return response;
+ }
+ let internal = |error: ai_memory_store::StoreError| {
+ tracing::error!(%error, "web health read failed");
+ StatusCode::INTERNAL_SERVER_ERROR.into_response()
+ };
+ let derived = match state.reader.derived_index_status().await {
+ Ok(derived) => derived,
+ Err(error) => return internal(error),
+ };
+ // Pragma reads; a failure must not take the whole page down.
+ let storage = state.reader.storage_status().await.unwrap_or_default();
+ let consolidation = match state.reader.session_consolidation_queue().await {
+ Ok(queue) => queue,
+ Err(error) => return internal(error),
+ };
+ let (ingest, providers, process) = match &state.health {
+ Some(sources) => {
+ // The spool and journal reads touch the filesystem; keep them off
+ // the async workers.
+ let probe = Arc::clone(&sources.probe);
+ let process = tokio::task::spawn_blocking(move || probe.process_state())
+ .await
+ .unwrap_or_default();
+ (
+ sources.ingest.snapshot(),
+ sources.providers.snapshot(),
+ process,
+ )
+ }
+ None => (
+ IngestMetrics::default().snapshot(),
+ ProviderHealthSnapshot::default(),
+ ProcessState::default(),
+ ),
+ };
+ let snapshot = HealthSnapshot {
+ ingest,
+ providers,
+ process,
+ derived,
+ storage,
+ consolidation,
+ embedder: state
+ .recall
+ .embedder
+ .as_ref()
+ .map(|embedder| EmbedderIdentity {
+ provider: embedder.provider().to_owned(),
+ model: embedder.model_identity(),
+ dim: embedder.dim(),
+ }),
+ };
+ let view = HealthView {
+ wired: state.health.is_some(),
+ checks: checks(&snapshot)
+ .into_iter()
+ .map(|check| HealthCheckRow {
+ id: check.id,
+ status: check.status.label(),
+ detail: check.detail,
+ fix: check.fix,
+ })
+ .collect(),
+ sections: sections(&snapshot, state.recall.rerank.is_some()),
+ };
+ match view.render() {
+ Ok(body) => {
+ let mut response = Html(body).into_response();
+ // Server-wide operator state: never cache it in a shared proxy.
+ response.headers_mut().insert(
+ header::CACHE_CONTROL,
+ HeaderValue::from_static("private, no-store"),
+ );
+ response
+ }
+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+}
+
+fn row(label: &'static str, value: impl Into<String>) -> HealthRow {
+ HealthRow {
+ label,
+ value: value.into(),
+ }
+}
+
+fn micros(us: Option<i64>) -> String {
+ us.and_then(|us| jiff::Timestamp::from_microsecond(us).ok())
+ .map_or_else(|| "never".to_owned(), |ts| ts.to_string())
+}
+
+fn age(ms: Option<u64>) -> String {
+ let Some(ms) = ms else {
+ return "n/a".to_owned();
+ };
+ let secs = ms / 1000;
+ match secs {
+ 0..60 => format!("{secs}s"),
+ 60..3600 => format!("{}m", secs / 60),
+ 3600..86_400 => format!("{}h", secs / 3600),
+ _ => format!("{}d", secs / 86_400),
+ }
+}
+
+/// `status provider/model[ dim N] · last ok … · last error … (HTTP n)`.
+/// The provider's error message is left out: it can quote a response body.
+fn provider_line(role: &ProviderRoleHealthSnapshot) -> String {
+ let mut out = role.status.as_str().to_owned();
+ if let Some(provider) = &role.provider {
+ out.push_str(&format!(
+ " · {provider}/{}",
+ role.model.as_deref().unwrap_or("?")
+ ));
+ }
+ if let Some(dim) = role.dim {
+ out.push_str(&format!(" (dim {dim})"));
+ }
+ if let Some(at) = role.last_success_at {
+ out.push_str(&format!(" · last ok {at}"));
+ }
+ if let Some(at) = role.last_error_at {
+ out.push_str(&format!(" · last error {at}"));
+ if let Some(status) = role.last_error_status {
+ out.push_str(&format!(" (HTTP {status})"));
+ }
+ }
+ out
+}
+
+fn sections(s: &HealthSnapshot, rerank: bool) -> Vec<HealthSection> {
+ let ingest = &s.ingest;
+ let hooks = HealthSection {
+ title: "Hooks (since the server started)",
+ rows: vec![
+ row("accepted", ingest.accepted.to_string()),
+ row(
+ "shed (429)",
+ format!(
+ "{} ({} saturated, {} rate-limited)",
+ ingest.shed_saturated + ingest.shed_rate_limited,
+ ingest.shed_saturated,
+ ingest.shed_rate_limited
+ ),
+ ),
+ row(
+ "outcomes",
+ format!(
+ "{} stored, {} replayed, {} resumed, {} ignored end, {} failed",
+ ingest.stored,
+ ingest.replayed,
+ ingest.resumed,
+ ingest.ignored_end,
+ ingest.failed
+ ),
+ ),
+ row(
+ "dropped",
+ format!(
+ "{} capture policy, {} unauthorized, {} collision, {} invalid",
+ ingest.dropped_by_policy,
+ ingest.dropped_unauthorized,
+ ingest.dropped_collision,
+ ingest.dropped_invalid
+ ),
+ ),
+ row(
+ "last write",
+ micros(
+ ingest
+ .last_persisted_ms
+ .and_then(|ms| i64::try_from(ms).ok())
+ .map(|ms| ms.saturating_mul(1000)),
+ ),
+ ),
+ ],
+ };
+ let process = &s.process;
+ let local = HealthSection {
+ title: "Writer, spool and recovery",
+ rows: vec![
+ row(
+ "write queue",
+ process.write_queue.map_or_else(
+ || "unknown".to_owned(),
+ |(queued, capacity)| format!("{queued}/{capacity}"),
+ ),
+ ),
+ row(
+ "hook spool",
+ process.spool.map_or_else(
+ || "not visible to this server".to_owned(),
+ |spool| {
+ format!(
+ "{} pending of {} (oldest {}, {} retries)",
+ spool.pending,
+ spool.capacity,
+ age(spool.oldest_age_ms),
+ spool.retries_total
+ )
+ },
+ ),
+ ),
+ row(
+ "recovery journal",
+ process.journal.map_or_else(
+ || "not visible to this server".to_owned(),
+ |journal| {
+ if journal.unreadable {
+ "unreadable".to_owned()
+ } else {
+ format!(
+ "{} pending ({} degraded, {} finish-failed)",
+ journal.pending, journal.degraded, journal.finish_failed
+ )
+ }
+ },
+ ),
+ ),
+ ],
+ };
+ let queue = &s.consolidation;
+ let consolidation = HealthSection {
+ title: "Consolidation",
+ rows: vec![
+ row("last completed", micros(queue.last_completed_at_us)),
+ row(
+ "queue",
+ format!(
+ "{} pending, {} running, {} completed, {} failed",
+ queue.pending, queue.running, queue.completed, queue.failed
+ ),
+ ),
+ row(
+ "oldest pending since",
+ micros(queue.oldest_pending_requested_at_us),
+ ),
+ ],
+ };
+ let mut models = vec![
+ row(
+ "embedder",
+ s.embedder.as_ref().map_or_else(
+ || "none (FTS5 + entity + graph only)".to_owned(),
+ |e| format!("{}/{} (dim {})", e.provider, e.model, e.dim),
+ ),
+ ),
+ row("embedding provider", provider_line(&s.providers.embedding)),
+ row("llm provider", provider_line(&s.providers.llm)),
+ row("reranker", if rerank { "on" } else { "off" }),
+ row(
+ "vectors",
+ format!(
+ "{} rows; {} latest pages missing; {} unembeddable",
+ s.derived.embedding_rows,
+ s.derived.latest_pages_missing_embeddings,
+ s.derived.latest_pages_unembeddable
+ ),
+ ),
+ ];
+ for triple in &s.derived.embedding_triples {
+ models.push(row(
+ "stored triple",
+ format!(
+ "{}/{} dim {}: {} rows",
+ triple.provider, triple.model, triple.dim, triple.count
+ ),
+ ));
+ }
+ let models = HealthSection {
+ title: "Embedder and models",
+ rows: models,
+ };
+ let index = HealthSection {
+ title: "Index and storage",
+ rows: vec![
+ row(
+ "fts",
+ format!(
+ "pages {}/{}; observations {}/{}",
+ s.derived.pages_fts_rows,
+ s.derived.pages_rows,
+ s.derived.observations_fts_rows,
+ s.derived.observations_rows
+ ),
+ ),
+ row(
+ "database",
+ format!(
+ "{} bytes, {} reclaimable",
+ s.storage.database_bytes, s.storage.reclaimable_bytes
+ ),
+ ),
+ ],
+ };
+ vec![hooks, local, consolidation, models, index]
+}
diff --git a/crates/ai-memory-web/src/routes/mod.rs b/crates/ai-memory-web/src/routes/mod.rs
index bf36699e..aca25f2d 100644
--- a/crates/ai-memory-web/src/routes/mod.rs
+++ b/crates/ai-memory-web/src/routes/mod.rs
@@ -9,6 +9,7 @@ use crate::html_auth::HtmlAuthRedirectConfig;
use crate::state::WebState;
mod api;
+mod health;
mod history;
mod index;
mod login;
@@ -70,6 +71,43 @@ pub(crate) async fn resolve_read_scope(
.await
}
+/// Refuse a root-only page unless the caller may use `/admin`, with the same
+/// `Capability::Admin` decision `require_root_for_multiuser_admin` makes:
+/// anonymous on a multi-user server is 401, a non-root user 403.
+pub(crate) async fn require_admin(
+ state: &WebState,
+ level: Option<axum::Extension<ai_memory_core::AuthLevel>>,
+) -> Result<(), axum::response::Response> {
+ use axum::http::StatusCode;
+ use axum::response::{Html, IntoResponse};
+ let level = level.map_or(
+ ai_memory_core::AuthLevel::Anonymous,
+ |axum::Extension(level)| level,
+ );
+ let distinguishes_operators = state
+ .reader
+ .distinguishes_operators(state.trusted_proxy_identity)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
+ match level.authorize(ai_memory_core::Capability::Admin, distinguishes_operators) {
+ Ok(()) => Ok(()),
+ Err(e) if e.is_authentication_required() => Err(StatusCode::UNAUTHORIZED.into_response()),
+ Err(_) => {
+ use askama::Template;
+ let mut response = match (crate::templates::AdminRequiredView {}).render() {
+ Ok(body) => (StatusCode::FORBIDDEN, Html(body)).into_response(),
+ Err(_) => StatusCode::FORBIDDEN.into_response(),
+ };
+ // A 403 here means "not root", not "change your password": keep
+ // the HTML auth redirect from sending the user to that form.
+ response
+ .extensions_mut()
+ .insert(crate::html_auth::AdminRequired);
+ Err(response)
+ }
+ }
+}
+
/// Build the read-only wiki page router (no static assets — those are public).
pub(crate) fn build(state: Arc<WebState>) -> Router {
Router::new()
@@ -83,6 +121,7 @@ pub(crate) fn build(state: Arc<WebState>) -> Router {
)
.route("/search", get(search::handler))
.route("/pending", get(pending::handler))
+ .route("/health", get(health::handler))
.with_state(state)
}
diff --git a/crates/ai-memory-web/src/routes/pending.rs b/crates/ai-memory-web/src/routes/pending.rs
index 2d907720..ab87e1a5 100644
--- a/crates/ai-memory-web/src/routes/pending.rs
+++ b/crates/ai-memory-web/src/routes/pending.rs
@@ -8,7 +8,7 @@
use std::sync::Arc;
-use ai_memory_core::{AuthLevel, Capability};
+use ai_memory_core::AuthLevel;
use ai_memory_store::{PendingAutoImproveReview, PendingAutoImproveScope};
use askama::Template;
use axum::Extension;
@@ -17,10 +17,9 @@ use axum::http::StatusCode;
use axum::response::{Html, IntoResponse, Response};
use serde::Deserialize;
-use crate::html_auth::AdminRequired;
use crate::state::WebState;
use crate::templates::{
- AdminRequiredView, PendingRow, PendingView, SelectOption, encode_segment, humanize, page_href,
+ PendingRow, PendingView, SelectOption, encode_segment, humanize, page_href,
};
/// Most proposals one page load reads. A queue this long needs the CLI, and
@@ -56,7 +55,7 @@ pub(crate) async fn handler(
level: Option<Extension<AuthLevel>>,
Query(query): Query<PendingQuery>,
) -> Response {
- if let Err(response) = require_admin(&state, level).await {
+ if let Err(response) = super::require_admin(&state, level).await {
return response;
}
@@ -139,31 +138,6 @@ fn scope_key(scope: &PendingAutoImproveScope) -> String {
)
}
-/// Refuse the page unless the caller may use `/admin`, with the same
-/// `Capability::Admin` decision `require_root_for_multiuser_admin` makes.
-async fn require_admin(
- state: &WebState,
- level: Option<Extension<AuthLevel>>,
-) -> Result<(), Response> {
- let level = level.map_or(AuthLevel::Anonymous, |Extension(level)| level);
- let distinguishes_operators = state
- .reader
- .distinguishes_operators(state.trusted_proxy_identity)
- .await
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
- match level.authorize(Capability::Admin, distinguishes_operators) {
- Ok(()) => Ok(()),
- Err(e) if e.is_authentication_required() => Err(StatusCode::UNAUTHORIZED.into_response()),
- Err(_) => {
- let mut response = render(AdminRequiredView {}, StatusCode::FORBIDDEN);
- // A 403 here means "not root", not "change your password": keep
- // the HTML auth redirect from sending the user to that form.
- response.extensions_mut().insert(AdminRequired);
- Err(response)
- }
- }
-}
-
fn scope_label(review: &PendingAutoImproveReview) -> String {
display_scope(&review.workspace_name, &review.project_name)
}
diff --git a/crates/ai-memory-web/src/routes/search.rs b/crates/ai-memory-web/src/routes/search.rs
index a4926927..e4faf07a 100644
--- a/crates/ai-memory-web/src/routes/search.rs
+++ b/crates/ai-memory-web/src/routes/search.rs
@@ -1,16 +1,38 @@
-//! `GET /search?q=…` — FTS5 search results.
+//! `GET /search?q=…` — search, with an optional recall trace.
+//!
+//! Two modes, the same two `memory_query` has:
+//!
+//! - **Project search** (`workspace` + `project`): the hybrid ranker
+//! (FTS5 + entity + vector + graph + observation RRF, authority, optional
+//! rerank) through [`crate::recall`], so the order matches `memory_query`
+//! for the same project. `explain=1` adds the recall trace: per-hit stream
+//! ranks, raw scores, RRF contributions, authority and rerank score, plus
+//! per-stream timings.
+//! - **Cross-project search** (no scope): FTS5 over every repository the
+//! viewer may read, as `memory_query(global=true)` does. Its trace is the
+//! FTS time alone; there are no per-hit streams to show.
use std::sync::Arc;
+use ai_memory_store::{SearchExplain, StreamTimings};
use askama::Template;
use axum::extract::{Query, State};
use axum::http::StatusCode;
-use axum::response::Html;
+use axum::response::{Html, IntoResponse, Response};
use serde::Deserialize;
use crate::markdown;
use crate::state::WebState;
-use crate::templates::{SearchHit, SearchView, page_href};
+use crate::templates::{
+ HitTrace, SearchHit, SearchView, StreamTraceRow, TimingRow, encode_segment, page_href,
+};
+
+/// Hits a cross-project search returns when the request names no `limit`.
+const GLOBAL_DEFAULT_LIMIT: usize = 50;
+/// Hits a project search returns when the request names no `limit`.
+const SCOPED_DEFAULT_LIMIT: usize = 20;
+/// Upper bound on `limit`, the same clamp `memory_query` applies.
+const MAX_LIMIT: usize = 100;
/// Query-string parameters for the search endpoint.
#[derive(Debug, Deserialize)]
@@ -18,57 +40,267 @@ pub(crate) struct SearchParams {
/// The free-text search query.
#[serde(default)]
pub q: String,
+ /// Workspace of a project search; must come with `project`.
+ #[serde(default)]
+ pub workspace: Option<String>,
+ /// Project of a project search; must come with `workspace`.
+ #[serde(default)]
+ pub project: Option<String>,
+ /// Most hits to show, clamped to `1..=100`.
+ #[serde(default)]
+ pub limit: Option<usize>,
+ /// `1`/`true`/`on` shows the recall trace.
+ #[serde(default)]
+ pub explain: Option<String>,
+}
+
+fn non_empty(value: Option<&str>) -> Option<&str> {
+ value.map(str::trim).filter(|v| !v.is_empty())
}
/// Handler for `GET /search?q=…`.
///
-/// Searches only the repositories the viewer may read (#708) — see
+/// A project search resolves the scope through the guarded, no-create
+/// lookup (#708): a project the viewer may not read is refused before any
+/// ranking runs, so the trace cannot describe it. A cross-project search
+/// covers only readable repositories — see
/// `ReaderPool::search_pages_with_meta`. No viewer (no database users, or
-/// root) searches everything, as before.
+/// root) reads everything, as before.
pub(crate) async fn handler(
State(state): State<Arc<WebState>>,
viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
Query(params): Query<SearchParams>,
-) -> Result<Html<String>, StatusCode> {
+) -> Response {
let query = params.q.trim().to_owned();
-
- let hits = if query.is_empty() {
- Vec::new()
- } else {
- let raw = state
- .reader
- .search_pages_with_meta(
- query.clone(),
- 50,
- None,
- viewer.map(|axum::Extension(viewer)| viewer.user()),
+ let explain = params
+ .explain
+ .as_deref()
+ .is_some_and(|v| matches!(v, "1" | "true" | "on" | "yes"));
+ let viewer = viewer.map(|axum::Extension(viewer)| viewer.user());
+ let scope = match (
+ non_empty(params.workspace.as_deref()),
+ non_empty(params.project.as_deref()),
+ ) {
+ (Some(workspace), Some(project)) => Some((workspace.to_owned(), project.to_owned())),
+ (None, None) => None,
+ _ => {
+ return (
+ StatusCode::BAD_REQUEST,
+ "workspace and project must be provided together",
)
- .await
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
-
- let mut results = Vec::with_capacity(raw.len());
- for h in raw {
- let path = h.path.as_str().to_owned();
- let href = page_href(&h.workspace_name, &h.project_name, &path);
- results.push(SearchHit {
- workspace: h.workspace_name,
- project: h.project_name,
- path,
- href,
- title: h.title,
- snippet: markdown::escape_snippet(&h.snippet),
- });
+ .into_response();
}
- results
};
+ let internal = |error: ai_memory_store::StoreError| {
+ tracing::error!(%error, "web search failed");
+ StatusCode::INTERNAL_SERVER_ERROR.into_response()
+ };
+
+ let mut hits = Vec::new();
+ let mut timings = None;
+ let mut streams_active: Vec<&'static str> = Vec::new();
+ match &scope {
+ Some((workspace, project)) => {
+ let resolved = match super::resolve_read_scope(&state, viewer, workspace, project).await
+ {
+ Ok(resolved) => resolved,
+ Err(refusal) => return super::page::refusal_response(&refusal),
+ };
+ if !query.is_empty() {
+ let limit = params
+ .limit
+ .unwrap_or(SCOPED_DEFAULT_LIMIT)
+ .clamp(1, MAX_LIMIT);
+ let result = match crate::recall::search_scopes(
+ &state,
+ &[(resolved.workspace_id, resolved.project_id)],
+ &query,
+ limit,
+ explain,
+ )
+ .await
+ {
+ Ok(result) => result,
+ Err(error) => return internal(error),
+ };
+ timings = result.timings;
+ streams_active = result.streams_active;
+ for (position, (hit, details)) in result.hits.into_iter().enumerate() {
+ let path = hit.path.as_str().to_owned();
+ hits.push(SearchHit {
+ href: page_href(workspace, project, &path),
+ workspace: workspace.clone(),
+ project: project.clone(),
+ path,
+ title: hit.title,
+ snippet: markdown::escape_snippet(&hit.snippet),
+ trace: details
+ .filter(|_| explain)
+ .map(|details| hit_trace(position + 1, hit.rank, &details)),
+ });
+ }
+ }
+ }
+ None if !query.is_empty() => {
+ let limit = params
+ .limit
+ .unwrap_or(GLOBAL_DEFAULT_LIMIT)
+ .clamp(1, MAX_LIMIT);
+ let started = explain.then(std::time::Instant::now);
+ let raw = match state
+ .reader
+ .search_pages_with_meta(query.clone(), limit, None, viewer)
+ .await
+ {
+ Ok(raw) => raw,
+ Err(error) => return internal(error),
+ };
+ if let Some(started) = started {
+ timings = Some(StreamTimings {
+ fts_ms: Some(started.elapsed().as_secs_f64() * 1000.0),
+ ..StreamTimings::default()
+ });
+ streams_active = vec!["fts"];
+ }
+ for h in raw {
+ let path = h.path.as_str().to_owned();
+ hits.push(SearchHit {
+ href: page_href(&h.workspace_name, &h.project_name, &path),
+ workspace: h.workspace_name,
+ project: h.project_name,
+ path,
+ title: h.title,
+ snippet: markdown::escape_snippet(&h.snippet),
+ trace: None,
+ });
+ }
+ }
+ None => {}
+ }
+ let (workspace, project) = scope.unwrap_or_default();
let hit_count = hits.len();
- let html = SearchView {
+ let global_href = format!("search?q={}", encode_segment(&query));
+ let view = SearchView {
+ global_href,
query,
hits,
hit_count,
+ workspace,
+ project,
+ explain,
+ streams_active: streams_active.join(", "),
+ timings: timings.as_ref().map(timing_rows).unwrap_or_default(),
+ embedder: state.recall.embedder.as_ref().map_or_else(
+ || "none".to_owned(),
+ |e| format!("{} / {} (dim {})", e.provider(), e.model(), e.dim()),
+ ),
+ reranker: state.recall.rerank.as_ref().map_or_else(
+ || "none".to_owned(),
+ |stage| format!("{} / {}", stage.reranker().name(), stage.reranker().model()),
+ ),
+ };
+ match view.render() {
+ Ok(html) => Html(html).into_response(),
+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
- .render()
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
- Ok(Html(html))
+}
+
+fn dash() -> String {
+ "—".to_owned()
+}
+
+fn fmt_rank(rank: Option<usize>) -> String {
+ rank.map_or_else(dash, |r| r.to_string())
+}
+
+fn fmt_f64(value: Option<f64>) -> String {
+ value.map_or_else(dash, |v| format!("{v:.4}"))
+}
+
+fn fmt_rrf(value: f64) -> String {
+ if value == 0.0 {
+ dash()
+ } else {
+ format!("{value:.5}")
+ }
+}
+
+/// One hit's trace rows, in the stream order `streams_active` uses.
+fn hit_trace(position: usize, rank: f64, d: &SearchExplain) -> HitTrace {
+ let mut streams = vec![
+ StreamTraceRow {
+ stream: "fts",
+ rank: fmt_rank(d.fts_rank),
+ raw: fmt_f64(d.fts_score),
+ rrf: fmt_rrf(d.rrf.fts),
+ },
+ StreamTraceRow {
+ stream: "entity",
+ rank: fmt_rank(d.entity_rank),
+ raw: fmt_f64(d.entity_weight),
+ rrf: fmt_rrf(d.rrf.entity),
+ },
+ StreamTraceRow {
+ stream: "vector",
+ rank: fmt_rank(d.vector_rank),
+ raw: fmt_f64(d.cosine.map(f64::from)),
+ rrf: fmt_rrf(d.rrf.vector),
+ },
+ ];
+ if d.abstract_rank.is_some() || d.rrf.abstract_vector != 0.0 {
+ streams.push(StreamTraceRow {
+ stream: "abstract",
+ rank: fmt_rank(d.abstract_rank),
+ raw: fmt_f64(d.abstract_cosine.map(f64::from)),
+ rrf: fmt_rrf(d.rrf.abstract_vector),
+ });
+ }
+ streams.push(StreamTraceRow {
+ stream: "graph",
+ rank: fmt_rank(d.graph_rank),
+ raw: dash(),
+ rrf: fmt_rrf(d.rrf.graph),
+ });
+ if d.observation_rank.is_some() || d.rrf.observation != 0.0 {
+ streams.push(StreamTraceRow {
+ stream: "observation",
+ rank: fmt_rank(d.observation_rank),
+ raw: dash(),
+ rrf: fmt_rrf(d.rrf.observation),
+ });
+ }
+ HitTrace {
+ position,
+ rank: format!("{rank:.5}"),
+ fused: format!("{:.5}", d.fused),
+ authority: fmt_f64(d.authority),
+ intent_boost: d.intent_boost.map(|v| format!("{v:.3}")),
+ rerank_score: d.rerank_score.map(|v| format!("{v:.3}")),
+ streams,
+ matched_entities: d.matched_entities.join(", "),
+ graph_via: d.graph_via.as_ref().map(|via| match &via.edge {
+ Some(edge) => format!("{} ({}, {edge})", via.seed_path, via.direction),
+ None => format!("{} ({})", via.seed_path, via.direction),
+ }),
+ }
+}
+
+fn timing_rows(t: &StreamTimings) -> Vec<TimingRow> {
+ [
+ ("fts", t.fts_ms),
+ ("entity", t.entity_ms),
+ ("vector", t.vector_ms),
+ ("graph", t.graph_ms),
+ ("observation", t.observation_ms),
+ ("rerank", t.rerank_ms),
+ ]
+ .into_iter()
+ .filter_map(|(stream, ms)| {
+ ms.map(|ms| TimingRow {
+ stream,
+ ms: format!("{ms:.2}"),
+ })
+ })
+ .collect()
}
diff --git a/crates/ai-memory-web/src/state.rs b/crates/ai-memory-web/src/state.rs
index 176a297d..283ddb80 100644
--- a/crates/ai-memory-web/src/state.rs
+++ b/crates/ai-memory-web/src/state.rs
@@ -4,9 +4,14 @@
//! (everything inside is `Arc`-shaped already), so axum's
//! `State<Arc<WebState>>` extractor stays free of clone-heavy code.
+use std::sync::Arc;
+
use ai_memory_store::ReaderPool;
use ai_memory_wiki::Wiki;
+use crate::health::HealthSources;
+use crate::recall::Recall;
+
/// Shared state for every web route. Construct once via
/// [`crate::router`].
#[derive(Clone)]
@@ -20,6 +25,12 @@ pub struct WebState {
/// operators apart even with no `users` rows. Root-only pages pass it to
/// `ReaderPool::distinguishes_operators`, as the `/admin` gate does.
pub trusted_proxy_identity: bool,
+ /// The configured embedder and reranker, so project search runs the same
+ /// hybrid ranker as `memory_query`. Empty on a zero-LLM server.
+ pub recall: Recall,
+ /// Process-side sources for the root-only health page. `None` when the
+ /// host did not wire them (the page then says so).
+ pub health: Option<Arc<HealthSources>>,
}
impl WebState {
@@ -30,6 +41,8 @@ impl WebState {
reader,
wiki,
trusted_proxy_identity: false,
+ recall: Recall::default(),
+ health: None,
}
}
@@ -39,4 +52,18 @@ impl WebState {
self.trusted_proxy_identity = trusted_proxy_identity;
self
}
+
+ /// Use the server's configured embedder and reranker for search.
+ #[must_use]
+ pub fn with_recall(mut self, recall: Recall) -> Self {
+ self.recall = recall;
+ self
+ }
+
+ /// Attach the process-side sources the health page reads.
+ #[must_use]
+ pub fn with_health(mut self, health: Arc<HealthSources>) -> Self {
+ self.health = Some(health);
+ self
+ }
}
diff --git a/crates/ai-memory-web/src/templates.rs b/crates/ai-memory-web/src/templates.rs
index 2c596e1c..8822c112 100644
--- a/crates/ai-memory-web/src/templates.rs
+++ b/crates/ai-memory-web/src/templates.rs
@@ -511,7 +511,7 @@ pub(crate) struct SessionView {
// search.html
// ---------------------------------------------------------------------------
-/// One FTS5 search hit.
+/// One search hit.
pub(crate) struct SearchHit {
/// Workspace name.
pub workspace: String,
@@ -525,6 +525,51 @@ pub(crate) struct SearchHit {
pub title: String,
/// FTS5 snippet (HTML-marked with `<mark>` tags).
pub snippet: String,
+ /// How the ranker placed this hit; set on an explained project search.
+ pub trace: Option<HitTrace>,
+}
+
+/// One hit's recall trace: what each stream saw and how the fused score
+/// became the final order. Every number is pre-formatted for display.
+pub(crate) struct HitTrace {
+ /// 1-based position in the result list.
+ pub position: usize,
+ /// The returned rank (lower is better).
+ pub rank: String,
+ /// Sum of the RRF contributions.
+ pub fused: String,
+ /// The bounded authority multiplier, or `—` when the page had none.
+ pub authority: String,
+ /// The query-intent boost, when routing applied one.
+ pub intent_boost: Option<String>,
+ /// Reranker relevance, when the reranker judged this hit.
+ pub rerank_score: Option<String>,
+ /// One row per stream that ran.
+ pub streams: Vec<StreamTraceRow>,
+ /// Entity names that matched the query, comma-separated.
+ pub matched_entities: String,
+ /// `seed path (direction[, edge])` when the graph stream pulled it in.
+ pub graph_via: Option<String>,
+}
+
+/// One stream's view of one hit.
+pub(crate) struct StreamTraceRow {
+ /// Stream name as `streams_active` reports it.
+ pub stream: &'static str,
+ /// 1-based rank in that stream, or `—` when the hit missed it.
+ pub rank: String,
+ /// The stream's raw score (bm25, cosine, entity weight), or `—`.
+ pub raw: String,
+ /// The stream's RRF contribution.
+ pub rrf: String,
+}
+
+/// One stream's wall time on an explained search.
+pub(crate) struct TimingRow {
+ /// `fts`, `entity`, `vector`, `graph`, `observation` or `rerank`.
+ pub stream: &'static str,
+ /// Milliseconds, formatted.
+ pub ms: String,
}
/// View-model for `GET /search?q=…`.
@@ -533,10 +578,33 @@ pub(crate) struct SearchHit {
pub(crate) struct SearchView {
/// The raw query string.
pub query: String,
- /// FTS5 search hits.
+ /// Search hits, best first.
pub hits: Vec<SearchHit>,
/// Pre-computed hit count for display (avoids needing `|length` filter).
pub hit_count: usize,
+ /// Workspace of a project search; empty for a cross-project search.
+ pub workspace: String,
+ /// Project of a project search; empty for a cross-project search.
+ pub project: String,
+ /// The viewer asked for the recall trace.
+ pub explain: bool,
+ /// Streams that ran, comma-separated (explain only).
+ pub streams_active: String,
+ /// Per-stream wall time (explain only).
+ pub timings: Vec<TimingRow>,
+ /// `provider / model (dim N)` of the embedder, or `none`.
+ pub embedder: String,
+ /// `name / model` of the reranker, or `none`.
+ pub reranker: String,
+ /// The same query across every project.
+ pub global_href: String,
+}
+
+impl SearchView {
+ /// A project search (hybrid ranker) rather than a cross-project one.
+ pub(crate) fn scoped(&self) -> bool {
+ !self.workspace.is_empty()
+ }
}
// ---------------------------------------------------------------------------
@@ -609,6 +677,50 @@ pub(crate) struct PendingView {
pub limit: usize,
}
+// ---------------------------------------------------------------------------
+// health.html
+// ---------------------------------------------------------------------------
+
+/// One failed health check.
+pub(crate) struct HealthCheckRow {
+ /// Stable check id.
+ pub id: &'static str,
+ /// `warn` or `error`.
+ pub status: &'static str,
+ /// What is wrong.
+ pub detail: String,
+ /// The exact command that fixes it, when there is one.
+ pub fix: Option<String>,
+}
+
+/// One label/value line on the health page.
+pub(crate) struct HealthRow {
+ /// Label.
+ pub label: &'static str,
+ /// Value.
+ pub value: String,
+}
+
+/// A titled group of health rows.
+pub(crate) struct HealthSection {
+ /// Section heading.
+ pub title: &'static str,
+ /// Its rows.
+ pub rows: Vec<HealthRow>,
+}
+
+/// View-model for the root-only `GET /health`.
+#[derive(Template)]
+#[template(path = "health.html")]
+pub(crate) struct HealthView {
+ /// The host wired the process-side sources (hook counters, spool…).
+ pub wired: bool,
+ /// Failed checks, most severe first.
+ pub checks: Vec<HealthCheckRow>,
+ /// Counter groups.
+ pub sections: Vec<HealthSection>,
+}
+
/// View-model for a non-root session that opens a root-only page.
#[derive(Template)]
#[template(path = "admin_required.html")]
diff --git a/crates/ai-memory-web/static/tailwind.css b/crates/ai-memory-web/static/tailwind.css
index 7f67edbf..55e06500 100644
--- a/crates/ai-memory-web/static/tailwind.css
+++ b/crates/ai-memory-web/static/tailwind.css
@@ -1 +1 @@
-*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.17 | MIT License | https://tailwindcss.com*/*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-tap-highlight-color:transparent}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-size:1em;font-variation-settings:normal}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-feature-settings:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#9ca3af;opacity:1}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]:where(:not([hidden=until-found])){display:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{inset:0}.right-2{right:.5rem}.top-0{top:0}.top-14{top:3.5rem}.top-2{top:.5rem}.z-10{z-index:10}.z-50{z-index:50}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-10{margin-bottom:2.5rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-auto{margin-left:auto}.mt-1{margin-top:.25rem}.mt-16{margin-top:4rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-14{height:3.5rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-7{height:1.75rem}.h-full{height:100%}.max-h-96{max-height:24rem}.min-h-full{min-height:100%}.w-20{width:5rem}.w-32{width:8rem}.w-4{width:1rem}.w-40{width:10rem}.w-auto{width:auto}.w-full{width:100%}.min-w-0{min-width:0}.max-w-3xl{max-width:48rem}.max-w-7xl{max-width:80rem}.max-w-md{max-width:28rem}.max-w-xl{max-width:36rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-8{gap:2rem}.gap-x-3{-moz-column-gap:.75rem;column-gap:.75rem}.gap-y-1{row-gap:.25rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.125rem*var(--tw-space-y-reverse));margin-top:calc(.125rem*(1 - var(--tw-space-y-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.25rem*var(--tw-space-y-reverse));margin-top:calc(.25rem*(1 - var(--tw-space-y-reverse)))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.75rem*var(--tw-space-y-reverse));margin-top:calc(.75rem*(1 - var(--tw-space-y-reverse)))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1rem*var(--tw-space-y-reverse));margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse:0;border-bottom-width:calc(1px*var(--tw-divide-y-reverse));border-top-width:calc(1px*(1 - var(--tw-divide-y-reverse)))}.divide-slate-100>:not([hidden])~:not([hidden]){--tw-divide-opacity:1;border-color:rgb(241 245 249/var(--tw-divide-opacity,1))}.overflow-auto{overflow:auto}.overflow-x-auto{overflow-x:auto}.truncate{overflow:hidden;text-overflow:ellipsis}.truncate,.whitespace-nowrap{white-space:nowrap}.whitespace-pre{white-space:pre}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-amber-200{--tw-border-opacity:1;border-color:rgb(253 230 138/var(--tw-border-opacity,1))}.border-blue-200{--tw-border-opacity:1;border-color:rgb(191 219 254/var(--tw-border-opacity,1))}.border-slate-100{--tw-border-opacity:1;border-color:rgb(241 245 249/var(--tw-border-opacity,1))}.border-slate-200{--tw-border-opacity:1;border-color:rgb(226 232 240/var(--tw-border-opacity,1))}.border-slate-300{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.bg-amber-100{--tw-bg-opacity:1;background-color:rgb(254 243 199/var(--tw-bg-opacity,1))}.bg-amber-50{--tw-bg-opacity:1;background-color:rgb(255 251 235/var(--tw-bg-opacity,1))}.bg-blue-50{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.bg-emerald-50{--tw-bg-opacity:1;background-color:rgb(236 253 245/var(--tw-bg-opacity,1))}.bg-green-50{--tw-bg-opacity:1;background-color:rgb(240 253 244/var(--tw-bg-opacity,1))}.bg-red-50{--tw-bg-opacity:1;background-color:rgb(254 242 242/var(--tw-bg-opacity,1))}.bg-red-600{--tw-bg-opacity:1;background-color:rgb(220 38 38/var(--tw-bg-opacity,1))}.bg-rose-50{--tw-bg-opacity:1;background-color:rgb(255 241 242/var(--tw-bg-opacity,1))}.bg-slate-100{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.bg-slate-50{--tw-bg-opacity:1;background-color:rgb(248 250 252/var(--tw-bg-opacity,1))}.bg-slate-900{--tw-bg-opacity:1;background-color:rgb(15 23 42/var(--tw-bg-opacity,1))}.bg-slate-900\/50{background-color:rgba(15,23,42,.5)}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.p-1{padding:.25rem}.p-12{padding:3rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-0\.5{padding-bottom:.125rem;padding-top:.125rem}.py-1{padding-bottom:.25rem;padding-top:.25rem}.py-1\.5{padding-bottom:.375rem;padding-top:.375rem}.py-2{padding-bottom:.5rem;padding-top:.5rem}.py-20{padding-bottom:5rem;padding-top:5rem}.py-3{padding-bottom:.75rem;padding-top:.75rem}.py-4{padding-bottom:1rem;padding-top:1rem}.py-8{padding-bottom:2rem;padding-top:2rem}.pl-2{padding-left:.5rem}.pr-10{padding-right:2.5rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.text-left{text-align:left}.text-center{text-align:center}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-6xl{font-size:3.75rem;line-height:1}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-5{line-height:1.25rem}.leading-relaxed{line-height:1.625}.tracking-wide{letter-spacing:.025em}.text-amber-700{--tw-text-opacity:1;color:rgb(180 83 9/var(--tw-text-opacity,1))}.text-amber-800{--tw-text-opacity:1;color:rgb(146 64 14/var(--tw-text-opacity,1))}.text-amber-900{--tw-text-opacity:1;color:rgb(120 53 15/var(--tw-text-opacity,1))}.text-blue-600{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity,1))}.text-emerald-900{--tw-text-opacity:1;color:rgb(6 78 59/var(--tw-text-opacity,1))}.text-green-800{--tw-text-opacity:1;color:rgb(22 101 52/var(--tw-text-opacity,1))}.text-red-800{--tw-text-opacity:1;color:rgb(153 27 27/var(--tw-text-opacity,1))}.text-rose-900{--tw-text-opacity:1;color:rgb(136 19 55/var(--tw-text-opacity,1))}.text-slate-200{--tw-text-opacity:1;color:rgb(226 232 240/var(--tw-text-opacity,1))}.text-slate-300{--tw-text-opacity:1;color:rgb(203 213 225/var(--tw-text-opacity,1))}.text-slate-400{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}.text-slate-500{--tw-text-opacity:1;color:rgb(100 116 139/var(--tw-text-opacity,1))}.text-slate-600{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}.text-slate-700{--tw-text-opacity:1;color:rgb(51 65 85/var(--tw-text-opacity,1))}.text-slate-800{--tw-text-opacity:1;color:rgb(30 41 59/var(--tw-text-opacity,1))}.text-slate-900{--tw-text-opacity:1;color:rgb(15 23 42/var(--tw-text-opacity,1))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.underline{text-decoration-line:underline}.placeholder-slate-400::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(148 163 184/var(--tw-placeholder-opacity,1))}.placeholder-slate-400::placeholder{--tw-placeholder-opacity:1;color:rgb(148 163 184/var(--tw-placeholder-opacity,1))}.shadow-xl{--tw-shadow:0 20px 25px -5px rgba(0,0,0,.1),0 8px 10px -6px rgba(0,0,0,.1);--tw-shadow-colored:0 20px 25px -5px var(--tw-shadow-color),0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.hover\:border-blue-400:hover{--tw-border-opacity:1;border-color:rgb(96 165 250/var(--tw-border-opacity,1))}.hover\:border-blue-500:hover{--tw-border-opacity:1;border-color:rgb(59 130 246/var(--tw-border-opacity,1))}.hover\:bg-amber-100:hover{--tw-bg-opacity:1;background-color:rgb(254 243 199/var(--tw-bg-opacity,1))}.hover\:bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity,1))}.hover\:bg-red-700:hover{--tw-bg-opacity:1;background-color:rgb(185 28 28/var(--tw-bg-opacity,1))}.hover\:bg-slate-700:hover{--tw-bg-opacity:1;background-color:rgb(51 65 85/var(--tw-bg-opacity,1))}.hover\:text-amber-950:hover{--tw-text-opacity:1;color:rgb(69 26 3/var(--tw-text-opacity,1))}.hover\:text-blue-600:hover{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-sm:hover{--tw-shadow:0 1px 2px 0 rgba(0,0,0,.05);--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(59 130 246/var(--tw-ring-opacity,1))}.disabled\:opacity-50:disabled{opacity:.5}@media (min-width:640px){.sm\:inline{display:inline}.sm\:w-48{width:12rem}.sm\:w-64{width:16rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}}@media (min-width:768px){.md\:w-56{width:14rem}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:flex-row{flex-direction:row}}@media (min-width:1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\:divide-slate-800>:not([hidden])~:not([hidden]){--tw-divide-opacity:1;border-color:rgb(30 41 59/var(--tw-divide-opacity,1))}.dark\:border-amber-800{--tw-border-opacity:1;border-color:rgb(146 64 14/var(--tw-border-opacity,1))}.dark\:border-amber-900\/50{border-color:rgba(120,53,15,.5)}.dark\:border-blue-800{--tw-border-opacity:1;border-color:rgb(30 64 175/var(--tw-border-opacity,1))}.dark\:border-slate-600{--tw-border-opacity:1;border-color:rgb(71 85 105/var(--tw-border-opacity,1))}.dark\:border-slate-700{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.dark\:border-slate-800{--tw-border-opacity:1;border-color:rgb(30 41 59/var(--tw-border-opacity,1))}.dark\:bg-amber-900{--tw-bg-opacity:1;background-color:rgb(120 53 15/var(--tw-bg-opacity,1))}.dark\:bg-amber-900\/40{background-color:rgba(120,53,15,.4)}.dark\:bg-amber-950{--tw-bg-opacity:1;background-color:rgb(69 26 3/var(--tw-bg-opacity,1))}.dark\:bg-amber-950\/30{background-color:rgba(69,26,3,.3)}.dark\:bg-blue-950{--tw-bg-opacity:1;background-color:rgb(23 37 84/var(--tw-bg-opacity,1))}.dark\:bg-emerald-950\/40{background-color:rgba(2,44,34,.4)}.dark\:bg-rose-950\/40{background-color:rgba(76,5,25,.4)}.dark\:bg-slate-100{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.dark\:bg-slate-800{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}.dark\:bg-slate-800\/60{background-color:rgba(30,41,59,.6)}.dark\:bg-slate-900{--tw-bg-opacity:1;background-color:rgb(15 23 42/var(--tw-bg-opacity,1))}.dark\:bg-slate-950{--tw-bg-opacity:1;background-color:rgb(2 6 23/var(--tw-bg-opacity,1))}.dark\:text-amber-200{--tw-text-opacity:1;color:rgb(253 230 138/var(--tw-text-opacity,1))}.dark\:text-amber-300{--tw-text-opacity:1;color:rgb(252 211 77/var(--tw-text-opacity,1))}.dark\:text-amber-300\/90{color:rgba(252,211,77,.9)}.dark\:text-blue-300{--tw-text-opacity:1;color:rgb(147 197 253/var(--tw-text-opacity,1))}.dark\:text-blue-400{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}.dark\:text-emerald-200{--tw-text-opacity:1;color:rgb(167 243 208/var(--tw-text-opacity,1))}.dark\:text-rose-200{--tw-text-opacity:1;color:rgb(254 205 211/var(--tw-text-opacity,1))}.dark\:text-slate-100{--tw-text-opacity:1;color:rgb(241 245 249/var(--tw-text-opacity,1))}.dark\:text-slate-200{--tw-text-opacity:1;color:rgb(226 232 240/var(--tw-text-opacity,1))}.dark\:text-slate-300{--tw-text-opacity:1;color:rgb(203 213 225/var(--tw-text-opacity,1))}.dark\:text-slate-400{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}.dark\:text-slate-500{--tw-text-opacity:1;color:rgb(100 116 139/var(--tw-text-opacity,1))}.dark\:text-slate-600{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}.dark\:text-slate-700{--tw-text-opacity:1;color:rgb(51 65 85/var(--tw-text-opacity,1))}.dark\:text-slate-800{--tw-text-opacity:1;color:rgb(30 41 59/var(--tw-text-opacity,1))}.dark\:text-slate-900{--tw-text-opacity:1;color:rgb(15 23 42/var(--tw-text-opacity,1))}.dark\:hover\:border-blue-600:hover{--tw-border-opacity:1;border-color:rgb(37 99 235/var(--tw-border-opacity,1))}.dark\:hover\:bg-amber-900\/40:hover{background-color:rgba(120,53,15,.4)}.dark\:hover\:bg-slate-300:hover{--tw-bg-opacity:1;background-color:rgb(203 213 225/var(--tw-bg-opacity,1))}.dark\:hover\:text-amber-100:hover{--tw-text-opacity:1;color:rgb(254 243 199/var(--tw-text-opacity,1))}.dark\:hover\:text-blue-400:hover{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}}.\[\&_a\]\:text-blue-600 a{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.\[\&_a\]\:underline a{text-decoration-line:underline}@media (prefers-color-scheme:dark){.\[\&_a\]\:dark\:text-blue-400 a{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}}.\[\&_blockquote\]\:my-3 blockquote{margin-bottom:.75rem;margin-top:.75rem}.\[\&_blockquote\]\:border-l-4 blockquote{border-left-width:4px}.\[\&_blockquote\]\:border-slate-300 blockquote{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_blockquote\]\:pl-4 blockquote{padding-left:1rem}.\[\&_blockquote\]\:italic blockquote{font-style:italic}.\[\&_blockquote\]\:text-slate-600 blockquote{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}@media (prefers-color-scheme:dark){.\[\&_blockquote\]\:dark\:border-slate-700 blockquote{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.\[\&_blockquote\]\:dark\:text-slate-400 blockquote{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}}.\[\&_code\]\:rounded code{border-radius:.25rem}.\[\&_code\]\:bg-slate-100 code{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.\[\&_code\]\:px-1 code{padding-left:.25rem;padding-right:.25rem}.\[\&_code\]\:py-0\.5 code{padding-bottom:.125rem;padding-top:.125rem}.\[\&_code\]\:font-mono code{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.\[\&_code\]\:text-sm code{font-size:.875rem;line-height:1.25rem}@media (prefers-color-scheme:dark){.\[\&_code\]\:dark\:bg-slate-800 code{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_h1\]\:mb-3 h1{margin-bottom:.75rem}.\[\&_h1\]\:mt-6 h1{margin-top:1.5rem}.\[\&_h1\]\:text-3xl h1{font-size:1.875rem;line-height:2.25rem}.\[\&_h1\]\:font-bold h1{font-weight:700}.\[\&_h2\]\:mb-2 h2{margin-bottom:.5rem}.\[\&_h2\]\:mt-5 h2{margin-top:1.25rem}.\[\&_h2\]\:text-2xl h2{font-size:1.5rem;line-height:2rem}.\[\&_h2\]\:font-semibold h2{font-weight:600}.\[\&_h3\]\:mb-2 h3{margin-bottom:.5rem}.\[\&_h3\]\:mt-4 h3{margin-top:1rem}.\[\&_h3\]\:text-xl h3{font-size:1.25rem;line-height:1.75rem}.\[\&_h3\]\:font-semibold h3{font-weight:600}.\[\&_h4\]\:mb-1 h4{margin-bottom:.25rem}.\[\&_h4\]\:mt-3 h4{margin-top:.75rem}.\[\&_h4\]\:text-lg h4{font-size:1.125rem;line-height:1.75rem}.\[\&_h4\]\:font-semibold h4{font-weight:600}.\[\&_hr\]\:my-6 hr{margin-bottom:1.5rem;margin-top:1.5rem}.\[\&_hr\]\:border-slate-200 hr{--tw-border-opacity:1;border-color:rgb(226 232 240/var(--tw-border-opacity,1))}@media (prefers-color-scheme:dark){.\[\&_hr\]\:dark\:border-slate-800 hr{--tw-border-opacity:1;border-color:rgb(30 41 59/var(--tw-border-opacity,1))}}.\[\&_li\]\:my-1 li{margin-bottom:.25rem;margin-top:.25rem}.\[\&_mark\]\:bg-yellow-200 mark{--tw-bg-opacity:1;background-color:rgb(254 240 138/var(--tw-bg-opacity,1))}.\[\&_mark\]\:px-0\.5 mark{padding-left:.125rem;padding-right:.125rem}@media (prefers-color-scheme:dark){.\[\&_mark\]\:dark\:bg-yellow-800 mark{--tw-bg-opacity:1;background-color:rgb(133 77 14/var(--tw-bg-opacity,1))}}.\[\&_ol\]\:my-3 ol{margin-bottom:.75rem;margin-top:.75rem}.\[\&_ol\]\:list-decimal ol{list-style-type:decimal}.\[\&_ol\]\:pl-5 ol{padding-left:1.25rem}.\[\&_p\]\:my-3 p{margin-bottom:.75rem;margin-top:.75rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_pre\]\:my-3 pre{margin-bottom:.75rem;margin-top:.75rem}.\[\&_pre\]\:overflow-x-auto pre{overflow-x:auto}.\[\&_pre\]\:rounded pre{border-radius:.25rem}.\[\&_pre\]\:bg-slate-100 pre{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.\[\&_pre\]\:p-3 pre{padding:.75rem}@media (prefers-color-scheme:dark){.\[\&_pre\]\:dark\:bg-slate-800 pre{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_pre_code\]\:bg-transparent pre code{background-color:transparent}.\[\&_pre_code\]\:p-0 pre code{padding:0}.\[\&_table\]\:my-3 table{margin-bottom:.75rem;margin-top:.75rem}.\[\&_table\]\:w-full table{width:100%}.\[\&_table\]\:border-collapse table{border-collapse:collapse}.\[\&_td\]\:border td{border-width:1px}.\[\&_td\]\:border-slate-300 td{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_td\]\:px-3 td{padding-left:.75rem;padding-right:.75rem}.\[\&_td\]\:py-2 td{padding-bottom:.5rem;padding-top:.5rem}@media (prefers-color-scheme:dark){.\[\&_td\]\:dark\:border-slate-700 td{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}}.\[\&_th\]\:border th{border-width:1px}.\[\&_th\]\:border-slate-300 th{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_th\]\:bg-slate-50 th{--tw-bg-opacity:1;background-color:rgb(248 250 252/var(--tw-bg-opacity,1))}.\[\&_th\]\:px-3 th{padding-left:.75rem;padding-right:.75rem}.\[\&_th\]\:py-2 th{padding-bottom:.5rem;padding-top:.5rem}.\[\&_th\]\:text-left th{text-align:left}@media (prefers-color-scheme:dark){.\[\&_th\]\:dark\:border-slate-700 th{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.\[\&_th\]\:dark\:bg-slate-800 th{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_ul\]\:my-3 ul{margin-bottom:.75rem;margin-top:.75rem}.\[\&_ul\]\:list-disc ul{list-style-type:disc}.\[\&_ul\]\:pl-5 ul{padding-left:1.25rem}
\ No newline at end of file
+*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.17 | MIT License | https://tailwindcss.com*/*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-tap-highlight-color:transparent}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-size:1em;font-variation-settings:normal}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-feature-settings:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#9ca3af;opacity:1}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]:where(:not([hidden=until-found])){display:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{inset:0}.right-2{right:.5rem}.top-0{top:0}.top-14{top:3.5rem}.top-2{top:.5rem}.z-10{z-index:10}.z-50{z-index:50}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-10{margin-bottom:2.5rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-auto{margin-left:auto}.mt-1{margin-top:.25rem}.mt-16{margin-top:4rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-14{height:3.5rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-7{height:1.75rem}.h-full{height:100%}.max-h-96{max-height:24rem}.min-h-full{min-height:100%}.w-20{width:5rem}.w-32{width:8rem}.w-4{width:1rem}.w-40{width:10rem}.w-auto{width:auto}.w-full{width:100%}.min-w-0{min-width:0}.max-w-3xl{max-width:48rem}.max-w-7xl{max-width:80rem}.max-w-md{max-width:28rem}.max-w-xl{max-width:36rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-8{gap:2rem}.gap-x-3{-moz-column-gap:.75rem;column-gap:.75rem}.gap-x-4{-moz-column-gap:1rem;column-gap:1rem}.gap-y-1{row-gap:.25rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.125rem*var(--tw-space-y-reverse));margin-top:calc(.125rem*(1 - var(--tw-space-y-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.25rem*var(--tw-space-y-reverse));margin-top:calc(.25rem*(1 - var(--tw-space-y-reverse)))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.75rem*var(--tw-space-y-reverse));margin-top:calc(.75rem*(1 - var(--tw-space-y-reverse)))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1rem*var(--tw-space-y-reverse));margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse:0;border-bottom-width:calc(1px*var(--tw-divide-y-reverse));border-top-width:calc(1px*(1 - var(--tw-divide-y-reverse)))}.divide-slate-100>:not([hidden])~:not([hidden]){--tw-divide-opacity:1;border-color:rgb(241 245 249/var(--tw-divide-opacity,1))}.overflow-auto{overflow:auto}.overflow-x-auto{overflow-x:auto}.truncate{overflow:hidden;text-overflow:ellipsis}.truncate,.whitespace-nowrap{white-space:nowrap}.whitespace-pre{white-space:pre}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-amber-200{--tw-border-opacity:1;border-color:rgb(253 230 138/var(--tw-border-opacity,1))}.border-amber-300{--tw-border-opacity:1;border-color:rgb(252 211 77/var(--tw-border-opacity,1))}.border-blue-200{--tw-border-opacity:1;border-color:rgb(191 219 254/var(--tw-border-opacity,1))}.border-slate-100{--tw-border-opacity:1;border-color:rgb(241 245 249/var(--tw-border-opacity,1))}.border-slate-200{--tw-border-opacity:1;border-color:rgb(226 232 240/var(--tw-border-opacity,1))}.border-slate-300{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.bg-amber-100{--tw-bg-opacity:1;background-color:rgb(254 243 199/var(--tw-bg-opacity,1))}.bg-amber-50{--tw-bg-opacity:1;background-color:rgb(255 251 235/var(--tw-bg-opacity,1))}.bg-blue-50{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.bg-emerald-50{--tw-bg-opacity:1;background-color:rgb(236 253 245/var(--tw-bg-opacity,1))}.bg-green-50{--tw-bg-opacity:1;background-color:rgb(240 253 244/var(--tw-bg-opacity,1))}.bg-red-50{--tw-bg-opacity:1;background-color:rgb(254 242 242/var(--tw-bg-opacity,1))}.bg-red-600{--tw-bg-opacity:1;background-color:rgb(220 38 38/var(--tw-bg-opacity,1))}.bg-rose-50{--tw-bg-opacity:1;background-color:rgb(255 241 242/var(--tw-bg-opacity,1))}.bg-slate-100{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.bg-slate-50{--tw-bg-opacity:1;background-color:rgb(248 250 252/var(--tw-bg-opacity,1))}.bg-slate-900{--tw-bg-opacity:1;background-color:rgb(15 23 42/var(--tw-bg-opacity,1))}.bg-slate-900\/50{background-color:rgba(15,23,42,.5)}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.p-1{padding:.25rem}.p-12{padding:3rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-0\.5{padding-bottom:.125rem;padding-top:.125rem}.py-1{padding-bottom:.25rem;padding-top:.25rem}.py-1\.5{padding-bottom:.375rem;padding-top:.375rem}.py-2{padding-bottom:.5rem;padding-top:.5rem}.py-20{padding-bottom:5rem;padding-top:5rem}.py-3{padding-bottom:.75rem;padding-top:.75rem}.py-4{padding-bottom:1rem;padding-top:1rem}.py-8{padding-bottom:2rem;padding-top:2rem}.pl-2{padding-left:.5rem}.pr-10{padding-right:2.5rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-6xl{font-size:3.75rem;line-height:1}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-5{line-height:1.25rem}.leading-relaxed{line-height:1.625}.tracking-wide{letter-spacing:.025em}.text-amber-700{--tw-text-opacity:1;color:rgb(180 83 9/var(--tw-text-opacity,1))}.text-amber-800{--tw-text-opacity:1;color:rgb(146 64 14/var(--tw-text-opacity,1))}.text-amber-900{--tw-text-opacity:1;color:rgb(120 53 15/var(--tw-text-opacity,1))}.text-blue-600{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity,1))}.text-emerald-900{--tw-text-opacity:1;color:rgb(6 78 59/var(--tw-text-opacity,1))}.text-green-700{--tw-text-opacity:1;color:rgb(21 128 61/var(--tw-text-opacity,1))}.text-green-800{--tw-text-opacity:1;color:rgb(22 101 52/var(--tw-text-opacity,1))}.text-red-700{--tw-text-opacity:1;color:rgb(185 28 28/var(--tw-text-opacity,1))}.text-red-800{--tw-text-opacity:1;color:rgb(153 27 27/var(--tw-text-opacity,1))}.text-rose-900{--tw-text-opacity:1;color:rgb(136 19 55/var(--tw-text-opacity,1))}.text-slate-200{--tw-text-opacity:1;color:rgb(226 232 240/var(--tw-text-opacity,1))}.text-slate-300{--tw-text-opacity:1;color:rgb(203 213 225/var(--tw-text-opacity,1))}.text-slate-400{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}.text-slate-500{--tw-text-opacity:1;color:rgb(100 116 139/var(--tw-text-opacity,1))}.text-slate-600{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}.text-slate-700{--tw-text-opacity:1;color:rgb(51 65 85/var(--tw-text-opacity,1))}.text-slate-800{--tw-text-opacity:1;color:rgb(30 41 59/var(--tw-text-opacity,1))}.text-slate-900{--tw-text-opacity:1;color:rgb(15 23 42/var(--tw-text-opacity,1))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.underline{text-decoration-line:underline}.placeholder-slate-400::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(148 163 184/var(--tw-placeholder-opacity,1))}.placeholder-slate-400::placeholder{--tw-placeholder-opacity:1;color:rgb(148 163 184/var(--tw-placeholder-opacity,1))}.shadow-xl{--tw-shadow:0 20px 25px -5px rgba(0,0,0,.1),0 8px 10px -6px rgba(0,0,0,.1);--tw-shadow-colored:0 20px 25px -5px var(--tw-shadow-color),0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.hover\:border-blue-400:hover{--tw-border-opacity:1;border-color:rgb(96 165 250/var(--tw-border-opacity,1))}.hover\:border-blue-500:hover{--tw-border-opacity:1;border-color:rgb(59 130 246/var(--tw-border-opacity,1))}.hover\:bg-amber-100:hover{--tw-bg-opacity:1;background-color:rgb(254 243 199/var(--tw-bg-opacity,1))}.hover\:bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity,1))}.hover\:bg-red-700:hover{--tw-bg-opacity:1;background-color:rgb(185 28 28/var(--tw-bg-opacity,1))}.hover\:bg-slate-700:hover{--tw-bg-opacity:1;background-color:rgb(51 65 85/var(--tw-bg-opacity,1))}.hover\:text-amber-950:hover{--tw-text-opacity:1;color:rgb(69 26 3/var(--tw-text-opacity,1))}.hover\:text-blue-600:hover{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-sm:hover{--tw-shadow:0 1px 2px 0 rgba(0,0,0,.05);--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(59 130 246/var(--tw-ring-opacity,1))}.disabled\:opacity-50:disabled{opacity:.5}@media (min-width:640px){.sm\:inline{display:inline}.sm\:w-48{width:12rem}.sm\:w-64{width:16rem}.sm\:grid-cols-\[12rem_1fr\]{grid-template-columns:12rem 1fr}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}}@media (min-width:768px){.md\:w-56{width:14rem}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:flex-row{flex-direction:row}}@media (min-width:1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\:divide-slate-800>:not([hidden])~:not([hidden]){--tw-divide-opacity:1;border-color:rgb(30 41 59/var(--tw-divide-opacity,1))}.dark\:border-amber-700{--tw-border-opacity:1;border-color:rgb(180 83 9/var(--tw-border-opacity,1))}.dark\:border-amber-800{--tw-border-opacity:1;border-color:rgb(146 64 14/var(--tw-border-opacity,1))}.dark\:border-amber-900\/50{border-color:rgba(120,53,15,.5)}.dark\:border-blue-800{--tw-border-opacity:1;border-color:rgb(30 64 175/var(--tw-border-opacity,1))}.dark\:border-slate-600{--tw-border-opacity:1;border-color:rgb(71 85 105/var(--tw-border-opacity,1))}.dark\:border-slate-700{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.dark\:border-slate-800{--tw-border-opacity:1;border-color:rgb(30 41 59/var(--tw-border-opacity,1))}.dark\:bg-amber-900{--tw-bg-opacity:1;background-color:rgb(120 53 15/var(--tw-bg-opacity,1))}.dark\:bg-amber-900\/40{background-color:rgba(120,53,15,.4)}.dark\:bg-amber-950{--tw-bg-opacity:1;background-color:rgb(69 26 3/var(--tw-bg-opacity,1))}.dark\:bg-amber-950\/30{background-color:rgba(69,26,3,.3)}.dark\:bg-blue-950{--tw-bg-opacity:1;background-color:rgb(23 37 84/var(--tw-bg-opacity,1))}.dark\:bg-emerald-950\/40{background-color:rgba(2,44,34,.4)}.dark\:bg-rose-950\/40{background-color:rgba(76,5,25,.4)}.dark\:bg-slate-100{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.dark\:bg-slate-800{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}.dark\:bg-slate-800\/60{background-color:rgba(30,41,59,.6)}.dark\:bg-slate-900{--tw-bg-opacity:1;background-color:rgb(15 23 42/var(--tw-bg-opacity,1))}.dark\:bg-slate-950{--tw-bg-opacity:1;background-color:rgb(2 6 23/var(--tw-bg-opacity,1))}.dark\:text-amber-200{--tw-text-opacity:1;color:rgb(253 230 138/var(--tw-text-opacity,1))}.dark\:text-amber-300{--tw-text-opacity:1;color:rgb(252 211 77/var(--tw-text-opacity,1))}.dark\:text-amber-300\/90{color:rgba(252,211,77,.9)}.dark\:text-amber-400{--tw-text-opacity:1;color:rgb(251 191 36/var(--tw-text-opacity,1))}.dark\:text-blue-300{--tw-text-opacity:1;color:rgb(147 197 253/var(--tw-text-opacity,1))}.dark\:text-blue-400{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}.dark\:text-emerald-200{--tw-text-opacity:1;color:rgb(167 243 208/var(--tw-text-opacity,1))}.dark\:text-green-400{--tw-text-opacity:1;color:rgb(74 222 128/var(--tw-text-opacity,1))}.dark\:text-red-400{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.dark\:text-rose-200{--tw-text-opacity:1;color:rgb(254 205 211/var(--tw-text-opacity,1))}.dark\:text-slate-100{--tw-text-opacity:1;color:rgb(241 245 249/var(--tw-text-opacity,1))}.dark\:text-slate-200{--tw-text-opacity:1;color:rgb(226 232 240/var(--tw-text-opacity,1))}.dark\:text-slate-300{--tw-text-opacity:1;color:rgb(203 213 225/var(--tw-text-opacity,1))}.dark\:text-slate-400{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}.dark\:text-slate-500{--tw-text-opacity:1;color:rgb(100 116 139/var(--tw-text-opacity,1))}.dark\:text-slate-600{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}.dark\:text-slate-700{--tw-text-opacity:1;color:rgb(51 65 85/var(--tw-text-opacity,1))}.dark\:text-slate-800{--tw-text-opacity:1;color:rgb(30 41 59/var(--tw-text-opacity,1))}.dark\:text-slate-900{--tw-text-opacity:1;color:rgb(15 23 42/var(--tw-text-opacity,1))}.dark\:hover\:border-blue-600:hover{--tw-border-opacity:1;border-color:rgb(37 99 235/var(--tw-border-opacity,1))}.dark\:hover\:bg-amber-900\/40:hover{background-color:rgba(120,53,15,.4)}.dark\:hover\:bg-slate-300:hover{--tw-bg-opacity:1;background-color:rgb(203 213 225/var(--tw-bg-opacity,1))}.dark\:hover\:text-amber-100:hover{--tw-text-opacity:1;color:rgb(254 243 199/var(--tw-text-opacity,1))}.dark\:hover\:text-blue-400:hover{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}}.\[\&_a\]\:text-blue-600 a{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.\[\&_a\]\:underline a{text-decoration-line:underline}@media (prefers-color-scheme:dark){.\[\&_a\]\:dark\:text-blue-400 a{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}}.\[\&_blockquote\]\:my-3 blockquote{margin-bottom:.75rem;margin-top:.75rem}.\[\&_blockquote\]\:border-l-4 blockquote{border-left-width:4px}.\[\&_blockquote\]\:border-slate-300 blockquote{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_blockquote\]\:pl-4 blockquote{padding-left:1rem}.\[\&_blockquote\]\:italic blockquote{font-style:italic}.\[\&_blockquote\]\:text-slate-600 blockquote{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}@media (prefers-color-scheme:dark){.\[\&_blockquote\]\:dark\:border-slate-700 blockquote{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.\[\&_blockquote\]\:dark\:text-slate-400 blockquote{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}}.\[\&_code\]\:rounded code{border-radius:.25rem}.\[\&_code\]\:bg-slate-100 code{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.\[\&_code\]\:px-1 code{padding-left:.25rem;padding-right:.25rem}.\[\&_code\]\:py-0\.5 code{padding-bottom:.125rem;padding-top:.125rem}.\[\&_code\]\:font-mono code{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.\[\&_code\]\:text-sm code{font-size:.875rem;line-height:1.25rem}@media (prefers-color-scheme:dark){.\[\&_code\]\:dark\:bg-slate-800 code{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_h1\]\:mb-3 h1{margin-bottom:.75rem}.\[\&_h1\]\:mt-6 h1{margin-top:1.5rem}.\[\&_h1\]\:text-3xl h1{font-size:1.875rem;line-height:2.25rem}.\[\&_h1\]\:font-bold h1{font-weight:700}.\[\&_h2\]\:mb-2 h2{margin-bottom:.5rem}.\[\&_h2\]\:mt-5 h2{margin-top:1.25rem}.\[\&_h2\]\:text-2xl h2{font-size:1.5rem;line-height:2rem}.\[\&_h2\]\:font-semibold h2{font-weight:600}.\[\&_h3\]\:mb-2 h3{margin-bottom:.5rem}.\[\&_h3\]\:mt-4 h3{margin-top:1rem}.\[\&_h3\]\:text-xl h3{font-size:1.25rem;line-height:1.75rem}.\[\&_h3\]\:font-semibold h3{font-weight:600}.\[\&_h4\]\:mb-1 h4{margin-bottom:.25rem}.\[\&_h4\]\:mt-3 h4{margin-top:.75rem}.\[\&_h4\]\:text-lg h4{font-size:1.125rem;line-height:1.75rem}.\[\&_h4\]\:font-semibold h4{font-weight:600}.\[\&_hr\]\:my-6 hr{margin-bottom:1.5rem;margin-top:1.5rem}.\[\&_hr\]\:border-slate-200 hr{--tw-border-opacity:1;border-color:rgb(226 232 240/var(--tw-border-opacity,1))}@media (prefers-color-scheme:dark){.\[\&_hr\]\:dark\:border-slate-800 hr{--tw-border-opacity:1;border-color:rgb(30 41 59/var(--tw-border-opacity,1))}}.\[\&_li\]\:my-1 li{margin-bottom:.25rem;margin-top:.25rem}.\[\&_mark\]\:bg-yellow-200 mark{--tw-bg-opacity:1;background-color:rgb(254 240 138/var(--tw-bg-opacity,1))}.\[\&_mark\]\:px-0\.5 mark{padding-left:.125rem;padding-right:.125rem}@media (prefers-color-scheme:dark){.\[\&_mark\]\:dark\:bg-yellow-800 mark{--tw-bg-opacity:1;background-color:rgb(133 77 14/var(--tw-bg-opacity,1))}}.\[\&_ol\]\:my-3 ol{margin-bottom:.75rem;margin-top:.75rem}.\[\&_ol\]\:list-decimal ol{list-style-type:decimal}.\[\&_ol\]\:pl-5 ol{padding-left:1.25rem}.\[\&_p\]\:my-3 p{margin-bottom:.75rem;margin-top:.75rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_pre\]\:my-3 pre{margin-bottom:.75rem;margin-top:.75rem}.\[\&_pre\]\:overflow-x-auto pre{overflow-x:auto}.\[\&_pre\]\:rounded pre{border-radius:.25rem}.\[\&_pre\]\:bg-slate-100 pre{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.\[\&_pre\]\:p-3 pre{padding:.75rem}@media (prefers-color-scheme:dark){.\[\&_pre\]\:dark\:bg-slate-800 pre{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_pre_code\]\:bg-transparent pre code{background-color:transparent}.\[\&_pre_code\]\:p-0 pre code{padding:0}.\[\&_table\]\:my-3 table{margin-bottom:.75rem;margin-top:.75rem}.\[\&_table\]\:w-full table{width:100%}.\[\&_table\]\:border-collapse table{border-collapse:collapse}.\[\&_td\]\:border td{border-width:1px}.\[\&_td\]\:border-slate-300 td{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_td\]\:px-3 td{padding-left:.75rem;padding-right:.75rem}.\[\&_td\]\:py-2 td{padding-bottom:.5rem;padding-top:.5rem}@media (prefers-color-scheme:dark){.\[\&_td\]\:dark\:border-slate-700 td{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}}.\[\&_th\]\:border th{border-width:1px}.\[\&_th\]\:border-slate-300 th{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_th\]\:bg-slate-50 th{--tw-bg-opacity:1;background-color:rgb(248 250 252/var(--tw-bg-opacity,1))}.\[\&_th\]\:px-3 th{padding-left:.75rem;padding-right:.75rem}.\[\&_th\]\:py-2 th{padding-bottom:.5rem;padding-top:.5rem}.\[\&_th\]\:text-left th{text-align:left}@media (prefers-color-scheme:dark){.\[\&_th\]\:dark\:border-slate-700 th{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.\[\&_th\]\:dark\:bg-slate-800 th{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_ul\]\:my-3 ul{margin-bottom:.75rem;margin-top:.75rem}.\[\&_ul\]\:list-disc ul{list-style-type:disc}.\[\&_ul\]\:pl-5 ul{padding-left:1.25rem}
\ No newline at end of file
diff --git a/crates/ai-memory-web/templates/base.html b/crates/ai-memory-web/templates/base.html
index 2c3ebdae..0dddbe3c 100644
--- a/crates/ai-memory-web/templates/base.html
+++ b/crates/ai-memory-web/templates/base.html
@@ -25,6 +25,7 @@
>
</form>
<a href="pending" class="text-sm font-medium text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">Pending</a>
+ <a href="health" class="text-sm font-medium text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">Health</a>
<button
type="button"
id="ai-memory-logout"
diff --git a/crates/ai-memory-web/templates/health.html b/crates/ai-memory-web/templates/health.html
new file mode 100644
index 00000000..2bff936f
--- /dev/null
+++ b/crates/ai-memory-web/templates/health.html
@@ -0,0 +1,42 @@
+{% extends "base.html" %}
+
+{% block title %}Health — ai-memory{% endblock %}
+
+{% block content %}
+<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-2">Server health</h1>
+<p class="text-sm text-slate-500 dark:text-slate-400 mb-6">Counters, queues and model state for this server process. Read-only: each fix is a command to run, not a button.</p>
+
+{% if !wired %}
+<p class="mb-6 rounded-md border border-amber-300 dark:border-amber-700 p-3 text-sm text-amber-800 dark:text-amber-300">This server did not wire its process counters into the web UI; hook, spool and provider figures below are empty.</p>
+{% endif %}
+
+<section class="mb-8" aria-label="Checks">
+ <h2 class="text-xs font-semibold uppercase tracking-wide text-slate-400 dark:text-slate-500 mb-3">Checks</h2>
+ {% if checks.is_empty() %}
+ <p class="text-sm text-green-700 dark:text-green-400" data-check="none">Every server-side check passes.</p>
+ {% else %}
+ <ul class="space-y-3">
+ {% for check in checks %}
+ <li class="rounded-md border border-slate-200 dark:border-slate-800 p-3" data-check="{{ check.id }}">
+ <p class="text-sm"><span class="font-mono text-xs uppercase {% if check.status == "error" %}text-red-700 dark:text-red-400{% else %}text-amber-700 dark:text-amber-400{% endif %}">{{ check.status }}</span> {{ check.detail }}</p>
+ {% if let Some(fix) = check.fix %}
+ <p class="mt-1 text-sm text-slate-600 dark:text-slate-400">Fix: <code class="font-mono">{{ fix }}</code></p>
+ {% endif %}
+ </li>
+ {% endfor %}
+ </ul>
+ {% endif %}
+</section>
+
+{% for section in sections %}
+<section class="mb-6" aria-label="{{ section.title }}">
+ <h2 class="text-xs font-semibold uppercase tracking-wide text-slate-400 dark:text-slate-500 mb-2">{{ section.title }}</h2>
+ <dl class="grid grid-cols-1 sm:grid-cols-[12rem_1fr] gap-x-4 gap-y-1 text-sm">
+ {% for row in section.rows %}
+ <dt class="text-slate-500 dark:text-slate-400">{{ row.label }}</dt>
+ <dd class="font-mono text-slate-800 dark:text-slate-200 break-words">{{ row.value }}</dd>
+ {% endfor %}
+ </dl>
+</section>
+{% endfor %}
+{% endblock %}
diff --git a/crates/ai-memory-web/templates/project.html b/crates/ai-memory-web/templates/project.html
index c7517759..274d4188 100644
--- a/crates/ai-memory-web/templates/project.html
+++ b/crates/ai-memory-web/templates/project.html
@@ -13,6 +13,22 @@
<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-6">{{ workspace }}/{{ project }}</h1>
+<form action="search" method="get" class="mb-8 flex flex-wrap items-center gap-2" aria-label="Search this project">
+ <input type="hidden" name="workspace" value="{{ workspace }}">
+ <input type="hidden" name="project" value="{{ project }}">
+ <input
+ name="q"
+ type="search"
+ placeholder="Search this project…"
+ class="flex-1 max-w-md rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
+ >
+ <label class="flex items-center gap-1 text-sm text-slate-600 dark:text-slate-400">
+ <input type="checkbox" name="explain" value="1">
+ Explain ranking
+ </label>
+ <button type="submit" class="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">Search</button>
+</form>
+
<div class="flex flex-col md:flex-row gap-8">
<!-- Sidebar: folder tree -->
<aside class="w-full md:w-56 shrink-0">
diff --git a/crates/ai-memory-web/templates/search.html b/crates/ai-memory-web/templates/search.html
index b2576faf..52c1762d 100644
--- a/crates/ai-memory-web/templates/search.html
+++ b/crates/ai-memory-web/templates/search.html
@@ -11,9 +11,16 @@
Search
{% endif %}
</h1>
+ {% if self.scoped() %}
+ <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">In {{ workspace }}/{{ project }} · <a href="{{ global_href }}" class="hover:text-blue-600 dark:hover:text-blue-400 underline">search every project</a></p>
+ {% endif %}
</div>
-<form action="search" method="get" class="mb-8 flex gap-2">
+<form action="search" method="get" class="mb-8 flex flex-wrap items-center gap-2">
+ {% if self.scoped() %}
+ <input type="hidden" name="workspace" value="{{ workspace }}">
+ <input type="hidden" name="project" value="{{ project }}">
+ {% endif %}
<input
name="q"
type="search"
@@ -21,11 +28,37 @@
placeholder="Search pages…"
class="flex-1 max-w-md rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
+ <label class="flex items-center gap-1 text-sm text-slate-600 dark:text-slate-400">
+ <input type="checkbox" name="explain" value="1"{% if explain %} checked{% endif %}>
+ Explain ranking
+ </label>
<button type="submit" class="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">
Search
</button>
</form>
+{% if explain && query != "" %}
+<section class="mb-8 rounded-md border border-slate-200 dark:border-slate-800 p-4 text-sm" aria-label="Recall trace">
+ <h2 class="text-xs font-semibold uppercase tracking-wide text-slate-400 dark:text-slate-500 mb-2">Recall trace</h2>
+ {% if self.scoped() %}
+ <p class="text-slate-600 dark:text-slate-400">Hybrid ranker (the one <code>memory_query</code> uses for a project). Streams: <span class="font-mono">{{ streams_active }}</span></p>
+ <p class="text-slate-600 dark:text-slate-400">Embedder: <span class="font-mono">{{ embedder }}</span> · Reranker: <span class="font-mono">{{ reranker }}</span></p>
+ {% else %}
+ <p class="text-slate-600 dark:text-slate-400">Cross-project search is FTS5 only, like <code>memory_query(global=true)</code>, so hits carry no per-stream details. Search from a project page to see the full trace.</p>
+ {% endif %}
+ {% if !timings.is_empty() %}
+ <table class="mt-3 text-xs">
+ <thead><tr><th class="pr-4 text-left font-medium text-slate-500">Stream</th><th class="text-right font-medium text-slate-500">ms</th></tr></thead>
+ <tbody>
+ {% for t in timings %}
+ <tr><td class="pr-4 font-mono">{{ t.stream }}</td><td class="text-right font-mono">{{ t.ms }}</td></tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ {% endif %}
+</section>
+{% endif %}
+
{% if query == "" %}
<p class="text-sm text-slate-500 dark:text-slate-400">Enter a search term above.</p>
{% else if hits.is_empty() %}
@@ -34,13 +67,28 @@
<p class="text-sm text-slate-500 dark:text-slate-400 mb-4">{{ hit_count }} result{% if hit_count != 1 %}s{% endif %}</p>
<ul class="divide-y divide-slate-100 dark:divide-slate-800">
{% for hit in hits %}
- <li class="py-4">
+ <li class="py-4" data-hit-path="{{ hit.path }}">
<a href="{{ hit.href }}"
class="text-base font-medium text-blue-700 dark:text-blue-400 hover:underline block mb-1">
{{ hit.title }}
</a>
<div class="text-sm text-slate-600 dark:text-slate-400 mb-1">{{ hit.snippet|safe }}</div>
<div class="text-xs text-slate-400 dark:text-slate-500">{{ hit.workspace }}/{{ hit.project }} · {{ hit.path }}</div>
+ {% if let Some(trace) = hit.trace %}
+ <div class="mt-2 overflow-x-auto" data-trace>
+ <p class="text-xs text-slate-500 dark:text-slate-400">#{{ trace.position }} · rank <span class="font-mono">{{ trace.rank }}</span> · fused <span class="font-mono">{{ trace.fused }}</span> · authority <span class="font-mono">{{ trace.authority }}</span>{% if let Some(boost) = trace.intent_boost %} · intent boost <span class="font-mono">{{ boost }}</span>{% endif %}{% if let Some(score) = trace.rerank_score %} · rerank <span class="font-mono">{{ score }}</span>{% endif %}</p>
+ <table class="mt-1 text-xs">
+ <thead><tr><th class="pr-4 text-left font-medium text-slate-500">Stream</th><th class="pr-4 text-right font-medium text-slate-500">Rank</th><th class="pr-4 text-right font-medium text-slate-500">Raw score</th><th class="text-right font-medium text-slate-500">RRF</th></tr></thead>
+ <tbody>
+ {% for row in trace.streams %}
+ <tr><td class="pr-4 font-mono">{{ row.stream }}</td><td class="pr-4 text-right font-mono">{{ row.rank }}</td><td class="pr-4 text-right font-mono">{{ row.raw }}</td><td class="text-right font-mono">{{ row.rrf }}</td></tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ {% if trace.matched_entities != "" %}<p class="text-xs text-slate-500 dark:text-slate-400">Matched entities: {{ trace.matched_entities }}</p>{% endif %}
+ {% if let Some(via) = trace.graph_via %}<p class="text-xs text-slate-500 dark:text-slate-400">Reached through: {{ via }}</p>{% endif %}
+ </div>
+ {% endif %}
</li>
{% endfor %}
</ul>
diff --git a/crates/ai-memory-web/tests/suite/health.rs b/crates/ai-memory-web/tests/suite/health.rs
new file mode 100644
index 00000000..d92e3496
--- /dev/null
+++ b/crates/ai-memory-web/tests/suite/health.rs
@@ -0,0 +1,569 @@
+//! The root-only `GET /health` panel.
+//!
+//! It describes the whole server, so it must refuse anyone `/admin` refuses
+//! (row 3b's pattern: anonymous 401 once operators are told apart, a database
+//! user 403 without the change-password redirect, root and the single-operator
+//! loopback admitted). Each check it renders is driven by a fixture here, and
+//! the page is scanned for secret-shaped strings planted in a provider error,
+//! a page body, a page title and a project name.
+
+use std::sync::Arc;
+
+use ai_memory_core::{
+ ActorContext, AuthLevel, IngestMetrics, NewUser, PagePath, ProjectId, Tier, UserRole,
+ WorkspaceId,
+};
+use ai_memory_llm::{
+ ChatRequest, ChatResponse, Embedder, LlmError, LlmProvider, LlmResult, ProviderHealth,
+ SyntheticEmbedder,
+};
+use ai_memory_store::Store;
+use ai_memory_web::health::{HealthProbe, HealthSources, JournalState, ProcessState, SpoolState};
+use ai_memory_web::{
+ HtmlAuthRedirectConfig, Recall, WebMountSpec, html_auth_redirect_mw, split_web_routers,
+};
+use ai_memory_wiki::{Wiki, WritePageRequest};
+use axum::body::Body;
+use axum::http::{Method, Request, StatusCode, header};
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+const PLANTED_PROVIDER: &str = "sk-PLANTEDPROVIDERSECRET0123456789";
+const PLANTED_EMBED: &str = "sk-PLANTEDEMBEDDERSECRET0123456789";
+const PLANTED_BODY: &str = "aim_PLANTEDBODYSECRET0123456789";
+const PLANTED_TITLE: &str = "PLANTEDTITLESECRET";
+const PLANTED_PROJECT: &str = "proj-PLANTEDSCOPESECRET";
+const RETRY_HINT: &str = "ai-memory llm-test --provider openai --model gpt-test --prompt ping";
+
+struct FailingLlm;
+
+#[async_trait::async_trait]
+impl LlmProvider for FailingLlm {
+ fn name(&self) -> &'static str {
+ "openai"
+ }
+ fn model(&self) -> &str {
+ "gpt-test"
+ }
+ async fn complete(&self, _request: ChatRequest) -> LlmResult<ChatResponse> {
+ Err(LlmError::Provider {
+ status: 401,
+ body: format!("invalid api key {PLANTED_PROVIDER}"),
+ })
+ }
+ async fn complete_structured_raw(
+ &self,
+ _request: ChatRequest,
+ _schema: serde_json::Value,
+ ) -> LlmResult<serde_json::Value> {
+ Err(LlmError::Provider {
+ status: 401,
+ body: PLANTED_PROVIDER.into(),
+ })
+ }
+}
+
+struct FailingEmbedder;
+
+#[async_trait::async_trait]
+impl Embedder for FailingEmbedder {
+ fn provider(&self) -> &'static str {
+ "openai"
+ }
+ fn model(&self) -> &str {
+ "text-embedding-test"
+ }
+ fn dim(&self) -> u32 {
+ 16
+ }
+ async fn embed(&self, _text: &str) -> LlmResult<Vec<f32>> {
+ Err(LlmError::Provider {
+ status: 503,
+ body: format!("upstream said {PLANTED_EMBED}"),
+ })
+ }
+}
+
+struct FixedProbe(ProcessState);
+
+impl HealthProbe for FixedProbe {
+ fn process_state(&self) -> ProcessState {
+ self.0
+ }
+}
+
+struct Fixture {
+ _tmp: TempDir,
+ store: Store,
+ wiki: Wiki,
+}
+
+fn page(ws: WorkspaceId, proj: ProjectId, path: &str, body: &str) -> WritePageRequest {
+ WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new(path).unwrap(),
+ frontmatter: serde_json::json!({"kind": "fact", "title": PLANTED_TITLE}),
+ body: body.to_owned(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: None,
+ admission_ctx: None,
+ author_id: None,
+ actor: ActorContext::anonymous(),
+ evidence: Vec::new(),
+ }
+}
+
+/// One page embedded under an 8-dim synthetic triple, one with no vector,
+/// both carrying planted secrets in body and title, in a project whose name
+/// is itself secret-shaped.
+async fn fixture() -> Fixture {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, PLANTED_PROJECT, None)
+ .await
+ .unwrap();
+ let embedding_wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_embedder(Arc::new(SyntheticEmbedder::new(8)));
+ embedding_wiki
+ .write_page(page(
+ ws,
+ proj,
+ "notes/a.md",
+ &format!("token {PLANTED_BODY}"),
+ ))
+ .await
+ .unwrap();
+ let wiki = embedding_wiki.without_embedder();
+ wiki.write_page(page(
+ ws,
+ proj,
+ "notes/b.md",
+ &format!("other {PLANTED_BODY}"),
+ ))
+ .await
+ .unwrap();
+ Fixture {
+ _tmp: tmp,
+ store,
+ wiki,
+ }
+}
+
+/// Provider health with a failed LLM call and a failed embed recorded, the
+/// way the wrappers record them in production.
+async fn failing_providers() -> ProviderHealth {
+ let health = ProviderHealth::default();
+ let llm = health.wrap_llm_provider(
+ Arc::new(FailingLlm),
+ "openai",
+ "gpt-test",
+ Some(RETRY_HINT.into()),
+ );
+ let embedder = health.wrap_embedder(
+ Arc::new(FailingEmbedder),
+ "openai",
+ "text-embedding-test",
+ 16,
+ );
+ assert!(
+ llm.complete(ChatRequest::user_prompt("ping"))
+ .await
+ .is_err()
+ );
+ assert!(embedder.embed_query("ping").await.is_err());
+ health
+}
+
+fn app(
+ f: &Fixture,
+ level: AuthLevel,
+ health: Option<HealthSources>,
+ recall: Recall,
+) -> axum::Router {
+ let cfg = Arc::new(HtmlAuthRedirectConfig::from_mount("", "/web"));
+ split_web_routers(
+ true,
+ f.store.reader.clone(),
+ f.wiki.clone(),
+ WebMountSpec {
+ enable_api: false,
+ web_ui_dir: None,
+ cors_origins: &[],
+ web_slug: "/web",
+ base_href: "/web/",
+ base_path: "",
+ trusted_proxy_identity: false,
+ recall,
+ health: health.map(Arc::new),
+ },
+ )
+ .unwrap()
+ .protected
+ .layer(axum::middleware::from_fn(
+ move |mut req: Request<Body>, next: axum::middleware::Next| async move {
+ req.extensions_mut().insert(level);
+ next.run(req).await
+ },
+ ))
+ .layer(axum::middleware::from_fn_with_state(
+ cfg,
+ html_auth_redirect_mw,
+ ))
+}
+
+async fn get(app: axum::Router, html: bool) -> (StatusCode, Option<String>, String) {
+ let mut req = Request::builder().uri("/web/health");
+ if html {
+ req = req
+ .header(header::ACCEPT, "text/html")
+ .header("sec-fetch-dest", "document");
+ }
+ let resp = app.oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
+ let status = resp.status();
+ let location = resp
+ .headers()
+ .get(header::LOCATION)
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_owned);
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (status, location, String::from_utf8(body.to_vec()).unwrap())
+}
+
+async fn add_db_user(store: &Store) {
+ store
+ .writer
+ .create_human_user(
+ NewUser {
+ username: "alice".into(),
+ name: None,
+ email: None,
+ },
+ UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+}
+
+/// Every process-side check failing at once: shed and failed hooks, a
+/// near-full write queue, a full spool, an unreadable journal, both
+/// providers erroring.
+async fn failing_sources() -> HealthSources {
+ let ingest = Arc::new(IngestMetrics::default());
+ for _ in 0..3 {
+ ingest.record_accepted();
+ }
+ ingest.record_shed_saturated();
+ ingest.record_shed_saturated();
+ ingest.record_shed_rate_limited();
+ ingest.record_failed();
+ HealthSources {
+ ingest,
+ providers: failing_providers().await,
+ probe: Arc::new(FixedProbe(ProcessState {
+ write_queue: Some((90, 100)),
+ spool: Some(SpoolState {
+ pending: 500,
+ oldest_age_ms: Some(7_200_000),
+ retries_total: 12,
+ capacity: 500,
+ }),
+ journal: Some(JournalState {
+ unreadable: true,
+ ..JournalState::default()
+ }),
+ })),
+ }
+}
+
+fn configured_embedder() -> Recall {
+ // 16 dims against vectors stored at 8: the stored ones are stale.
+ Recall {
+ embedder: Some(Arc::new(SyntheticEmbedder::new(16))),
+ rerank: None,
+ }
+}
+
+fn assert_check(body: &str, id: &str, fix: Option<&str>) {
+ let start = body
+ .find(&format!("data-check=\"{id}\""))
+ .unwrap_or_else(|| panic!("check {id} not rendered:\n{body}"));
+ let item = &body[start..];
+ let item = &item[..item.find("</li>").unwrap_or(item.len())];
+ match fix {
+ Some(fix) => assert!(
+ item.contains(&format!("Fix: <code class=\"font-mono\">{fix}</code>")),
+ "check {id} lacks its fix line {fix:?}:\n{item}"
+ ),
+ None => assert!(!item.contains("Fix:"), "check {id} has a fix line:\n{item}"),
+ }
+}
+
+#[tokio::test]
+async fn health_page_renders_each_failing_check_with_its_fix_line() {
+ let f = fixture().await;
+ let (status, _, body) = get(
+ app(
+ &f,
+ AuthLevel::Root,
+ Some(failing_sources().await),
+ configured_embedder(),
+ ),
+ true,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_check(&body, "hook_shed", None);
+ assert_check(&body, "hook_failed", None);
+ assert_check(&body, "write_queue", None);
+ assert_check(&body, "spool_evicting", Some("ai-memory recover"));
+ assert_check(&body, "journal_unreadable", Some("ai-memory recover"));
+ assert_check(&body, "llm_provider", Some(RETRY_HINT));
+ assert_check(&body, "embedding_provider", None);
+ assert_check(&body, "stale_vectors", Some("ai-memory embed --force"));
+ assert_check(&body, "missing_vectors", Some("ai-memory embed"));
+ assert!(body.contains("HTTP 401"), "{body}");
+ // The counters behind them.
+ assert!(body.contains("3 (2 saturated, 1 rate-limited)"), "{body}");
+ assert!(body.contains("90/100"), "{body}");
+ assert!(
+ body.contains("500 pending of 500 (oldest 2h, 12 retries)"),
+ "{body}"
+ );
+ assert!(
+ body.contains("synthetic/bag-of-words-v1 (dim 16)"),
+ "{body}"
+ );
+ assert!(
+ body.contains("synthetic/bag-of-words-v1 dim 8: 1 rows"),
+ "{body}"
+ );
+ assert!(
+ body.contains("0 pending, 0 running, 0 completed, 0 failed"),
+ "{body}"
+ );
+ assert!(!body.contains("data-check=\"none\""), "{body}");
+}
+
+#[tokio::test]
+async fn health_page_renders_pending_spool_and_journal_checks() {
+ let f = fixture().await;
+ let sources = HealthSources {
+ ingest: Arc::new(IngestMetrics::default()),
+ providers: ProviderHealth::default(),
+ probe: Arc::new(FixedProbe(ProcessState {
+ write_queue: Some((0, 100)),
+ spool: Some(SpoolState {
+ pending: 4,
+ oldest_age_ms: Some(30_000),
+ retries_total: 1,
+ capacity: 500,
+ }),
+ journal: Some(JournalState {
+ pending: 2,
+ degraded: 1,
+ finish_failed: 1,
+ unreadable: false,
+ }),
+ })),
+ };
+ let (status, _, body) = get(
+ app(&f, AuthLevel::Root, Some(sources), Recall::default()),
+ true,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_check(&body, "spool_pending", Some("ai-memory recover"));
+ assert_check(&body, "journal_pending", Some("ai-memory recover"));
+ // No embedder configured: vector checks stay quiet.
+ assert!(!body.contains("data-check=\"stale_vectors\""), "{body}");
+ assert!(!body.contains("data-check=\"missing_vectors\""), "{body}");
+ assert!(!body.contains("data-check=\"write_queue\""), "{body}");
+}
+
+#[tokio::test]
+async fn health_page_reports_a_healthy_server_as_passing() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let f = Fixture {
+ _tmp: tmp,
+ store,
+ wiki,
+ };
+ let sources = HealthSources {
+ ingest: Arc::new(IngestMetrics::default()),
+ providers: ProviderHealth::default(),
+ probe: Arc::new(FixedProbe(ProcessState {
+ write_queue: Some((0, 100)),
+ spool: Some(SpoolState {
+ capacity: 500,
+ ..SpoolState::default()
+ }),
+ journal: Some(JournalState::default()),
+ })),
+ };
+ let (status, _, body) = get(
+ app(&f, AuthLevel::Root, Some(sources), Recall::default()),
+ true,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(body.contains("data-check=\"none\""), "{body}");
+ assert!(!body.contains("This server did not wire"), "{body}");
+
+ // A host that wired nothing says so instead of showing zeros as fact.
+ let (_, _, body) = get(app(&f, AuthLevel::Root, None, Recall::default()), true).await;
+ assert!(body.contains("This server did not wire"), "{body}");
+}
+
+#[tokio::test]
+async fn health_page_carries_no_secret_material() {
+ let f = fixture().await;
+ let (status, _, body) = get(
+ app(
+ &f,
+ AuthLevel::Root,
+ Some(failing_sources().await),
+ configured_embedder(),
+ ),
+ true,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ for planted in [
+ PLANTED_PROVIDER,
+ PLANTED_EMBED,
+ PLANTED_BODY,
+ PLANTED_TITLE,
+ PLANTED_PROJECT,
+ "PLANTED",
+ "invalid api key",
+ "upstream said",
+ ] {
+ assert!(
+ !body.contains(planted),
+ "health page leaked {planted}:\n{body}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn health_page_refuses_anonymous_once_operators_are_distinguished() {
+ let f = fixture().await;
+ add_db_user(&f.store).await;
+ let sources = failing_sources().await;
+ let (status, _, body) = get(
+ app(
+ &f,
+ AuthLevel::Anonymous,
+ Some(sources.clone()),
+ Recall::default(),
+ ),
+ false,
+ )
+ .await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert!(!body.contains("Server health"), "{body}");
+ assert!(!body.contains("ai-memory recover"), "{body}");
+
+ let (status, location, _) = get(
+ app(&f, AuthLevel::Anonymous, Some(sources), Recall::default()),
+ true,
+ )
+ .await;
+ assert_eq!(status, StatusCode::SEE_OTHER);
+ assert!(
+ location
+ .as_deref()
+ .is_some_and(|l| l.starts_with("/web/login?next=")),
+ "{location:?}"
+ );
+}
+
+#[tokio::test]
+async fn health_page_refuses_a_db_user_and_admits_root() {
+ let f = fixture().await;
+ add_db_user(&f.store).await;
+ let sources = failing_sources().await;
+ let (status, location, body) = get(
+ app(
+ &f,
+ AuthLevel::User,
+ Some(sources.clone()),
+ Recall::default(),
+ ),
+ true,
+ )
+ .await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert_eq!(location, None, "a non-root 403 is not a password redirect");
+ assert!(body.contains("Root access required"), "{body}");
+ for leaked in ["Server health", "ai-memory recover", "90/100", "saturated"] {
+ assert!(!body.contains(leaked), "DB user saw {leaked}: {body}");
+ }
+
+ // Control: root on the same multi-user server.
+ let (status, _, body) = get(
+ app(&f, AuthLevel::Root, Some(sources), Recall::default()),
+ true,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(body.contains("Server health"), "{body}");
+}
+
+#[tokio::test]
+async fn health_page_follows_the_admin_gate_on_a_single_operator_server() {
+ // No users and no trusted proxy: `/admin` admits the anonymous loopback
+ // operator, so this page does too.
+ let f = fixture().await;
+ let (status, _, body) = get(
+ app(
+ &f,
+ AuthLevel::Anonymous,
+ Some(failing_sources().await),
+ Recall::default(),
+ ),
+ true,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(body.contains("Server health"), "{body}");
+}
+
+#[tokio::test]
+async fn health_page_has_no_write_route() {
+ let f = fixture().await;
+ for method in [Method::POST, Method::PUT, Method::DELETE] {
+ let resp = app(
+ &f,
+ AuthLevel::Root,
+ Some(failing_sources().await),
+ Recall::default(),
+ )
+ .oneshot(
+ Request::builder()
+ .method(method.clone())
+ .uri("/web/health")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED, "{method}");
+ }
+}
diff --git a/crates/ai-memory-web/tests/suite/mod.rs b/crates/ai-memory-web/tests/suite/mod.rs
index 687f5d8c..18cbe557 100644
--- a/crates/ai-memory-web/tests/suite/mod.rs
+++ b/crates/ai-memory-web/tests/suite/mod.rs
@@ -2,6 +2,8 @@
//! test harness (see the `integration` module in `src/lib.rs`), so they cost
//! no extra binary; a new file must be declared below.
+mod health;
mod history_replay;
mod pending;
+mod recall_trace;
mod routes;
diff --git a/crates/ai-memory-web/tests/suite/pending.rs b/crates/ai-memory-web/tests/suite/pending.rs
index 0acf679e..dcb23c96 100644
--- a/crates/ai-memory-web/tests/suite/pending.rs
+++ b/crates/ai-memory-web/tests/suite/pending.rs
@@ -442,6 +442,8 @@ async fn pending_page_gate_sees_the_trusted_proxy_setting_through_the_mount() {
base_href: "/web/",
base_path: "",
trusted_proxy_identity,
+ recall: ai_memory_web::Recall::default(),
+ health: None,
},
)
.unwrap();
diff --git a/crates/ai-memory-web/tests/suite/recall_trace.rs b/crates/ai-memory-web/tests/suite/recall_trace.rs
new file mode 100644
index 00000000..35bc5b36
--- /dev/null
+++ b/crates/ai-memory-web/tests/suite/recall_trace.rs
@@ -0,0 +1,389 @@
+//! The recall trace on `/web/search` and the scope rules of project search.
+//!
+//! A project search runs `memory_query`'s hybrid ranker (the order parity is
+//! proven in `ai-memory-mcp/tests/suite/web_search_parity.rs`). Here: what
+//! `explain=1` renders, and that a project search, with or without the trace,
+//! follows `memory_query`'s scope rules — a restricted project refused to a
+//! viewer without a grant, an unknown project not found and never created,
+//! partial scope rejected, and no other project's pages in the result or the
+//! trace.
+
+use std::sync::Arc;
+
+use ai_memory_core::{
+ ActorContext, AuthorizedViewer, NewUser, PagePath, ProjectId, Tier, UserId, UserRole,
+ WorkspaceId,
+};
+use ai_memory_llm::{Embedder, SyntheticEmbedder};
+use ai_memory_store::{GrantLevel, Store};
+use ai_memory_web::{Recall, WebMountSpec, split_web_routers};
+use ai_memory_wiki::{Wiki, WritePageRequest};
+use axum::body::Body;
+use axum::http::{Method, Request, StatusCode};
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+struct Fixture {
+ _tmp: TempDir,
+ store: Store,
+ wiki: Wiki,
+ alpha: ProjectId,
+}
+
+fn embedder() -> Arc<dyn Embedder> {
+ Arc::new(SyntheticEmbedder::new(16))
+}
+
+fn req(ws: WorkspaceId, proj: ProjectId, path: &str, body: &str) -> WritePageRequest {
+ WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new(path).unwrap(),
+ frontmatter: serde_json::json!({"kind": "fact"}),
+ body: body.to_owned(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: None,
+ admission_ctx: None,
+ author_id: None,
+ actor: ActorContext::anonymous(),
+ evidence: Vec::new(),
+ }
+}
+
+/// `alpha` holds the target pages (one links to another, so the graph
+/// stream has something to follow); `beta` holds a page that matches the
+/// same query better and must never surface from an `alpha` search.
+async fn fixture(restricted: bool) -> Fixture {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ if restricted {
+ store
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ }
+ 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();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_embedder(embedder());
+ for (path, body) in [
+ (
+ "notes/rotation.md",
+ "# Token rotation\n\nRotate the signing token weekly. See [[notes/vault]].",
+ ),
+ (
+ "notes/vault.md",
+ "# Vault\n\nKeys live in the vault and are confidential.",
+ ),
+ ("notes/deploy.md", "# Deploy\n\nThe pipeline swaps traffic."),
+ ] {
+ wiki.write_page(req(ws, alpha, path, body)).await.unwrap();
+ }
+ wiki.write_page(req(
+ ws,
+ beta,
+ "notes/beta-rotation.md",
+ "# Beta token rotation\n\nBETA-ONLY-MARKER token rotation token rotation.",
+ ))
+ .await
+ .unwrap();
+ Fixture {
+ _tmp: tmp,
+ store,
+ wiki: wiki.without_embedder(),
+ alpha,
+ }
+}
+
+fn web(f: &Fixture, recall: Recall) -> axum::Router {
+ split_web_routers(
+ true,
+ f.store.reader.clone(),
+ f.wiki.clone(),
+ WebMountSpec {
+ enable_api: true,
+ web_ui_dir: None,
+ cors_origins: &[],
+ web_slug: "/web",
+ base_href: "/web/",
+ base_path: "",
+ trusted_proxy_identity: false,
+ recall,
+ health: None,
+ },
+ )
+ .unwrap()
+ .protected
+}
+
+async fn get(app: &axum::Router, uri: &str, viewer: Option<UserId>) -> (StatusCode, String) {
+ let mut request = Request::builder().uri(uri);
+ if let Some(viewer) = viewer {
+ request = request.extension(AuthorizedViewer(viewer));
+ }
+ let resp = app
+ .clone()
+ .oneshot(request.body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+ let status = resp.status();
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (status, String::from_utf8_lossy(&body).into_owned())
+}
+
+async fn human(store: &Store, name: &str) -> UserId {
+ store
+ .writer
+ .create_human_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap()
+}
+
+#[tokio::test]
+async fn explain_renders_stream_ranks_rrf_authority_and_timings() {
+ let f = fixture(false).await;
+ let app = web(
+ &f,
+ Recall {
+ embedder: Some(embedder()),
+ rerank: None,
+ },
+ );
+ let (status, body) = get(
+ &app,
+ "/web/search?q=token%20rotation&workspace=default&project=alpha&explain=1",
+ None,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(body.contains("Recall trace"), "{body}");
+ assert!(body.contains("Hybrid ranker"), "{body}");
+ // The streams that ran, the embedder that fed the vector stream.
+ assert!(
+ body.contains("fts, entity, vector, graph"),
+ "streams_active missing: {body}"
+ );
+ assert!(
+ body.contains("synthetic / bag-of-words-v1 (dim 16)"),
+ "{body}"
+ );
+ // Per-stream timings, one row each, vector included.
+ for stream in ["fts", "entity", "vector", "graph"] {
+ assert!(
+ body.contains(&format!(
+ "<tr><td class=\"pr-4 font-mono\">{stream}</td><td class=\"text-right font-mono\">"
+ )),
+ "no {stream} timing row: {body}"
+ );
+ }
+ // Per-hit trace: rank, fused, authority, and the stream table.
+ assert!(body.contains("data-trace"), "{body}");
+ assert!(
+ body.contains("· fused <span class=\"font-mono\">"),
+ "{body}"
+ );
+ assert!(
+ body.contains("· authority <span class=\"font-mono\">"),
+ "{body}"
+ );
+ assert!(body.contains(">RRF</th>"), "{body}");
+ // The page the FTS stream ranked first carries an FTS rank of 1.
+ assert!(
+ body.contains(
+ "<td class=\"pr-4 font-mono\">fts</td><td class=\"pr-4 text-right font-mono\">1</td>"
+ ),
+ "{body}"
+ );
+ // Nothing from beta: neither its path nor its body, though it matches
+ // the query better.
+ assert!(!body.contains("beta-rotation"), "{body}");
+ assert!(!body.contains("BETA-ONLY-MARKER"), "{body}");
+
+ // Without explain the same search renders no trace.
+ let (_, plain) = get(
+ &app,
+ "/web/search?q=token%20rotation&workspace=default&project=alpha",
+ None,
+ )
+ .await;
+ assert!(plain.contains("notes/rotation.md"), "{plain}");
+ assert!(!plain.contains("data-trace"), "{plain}");
+ assert!(!plain.contains("Recall trace"), "{plain}");
+}
+
+#[tokio::test]
+async fn explain_without_an_embedder_reports_no_vector_stream() {
+ let f = fixture(false).await;
+ let app = web(&f, Recall::default());
+ let (status, body) = get(
+ &app,
+ "/web/search?q=token%20rotation&workspace=default&project=alpha&explain=1",
+ None,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(
+ body.contains("Embedder: <span class=\"font-mono\">none</span>"),
+ "{body}"
+ );
+ assert!(body.contains("fts, entity, graph"), "{body}");
+ assert!(!body.contains("fts, entity, vector"), "{body}");
+ assert!(body.contains("notes/rotation.md"), "{body}");
+}
+
+#[tokio::test]
+async fn cross_project_explain_is_fts_only_and_carries_no_per_hit_trace() {
+ let f = fixture(false).await;
+ let app = web(
+ &f,
+ Recall {
+ embedder: Some(embedder()),
+ rerank: None,
+ },
+ );
+ let (status, body) = get(&app, "/web/search?q=rotation&explain=1", None).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(body.contains("Cross-project search is FTS5 only"), "{body}");
+ assert!(!body.contains("data-trace"), "{body}");
+ // Both projects' pages, as a global search should.
+ assert!(body.contains("notes/rotation.md"), "{body}");
+ assert!(body.contains("notes/beta-rotation.md"), "{body}");
+}
+
+#[tokio::test]
+async fn project_search_refuses_a_restricted_project_without_a_grant() {
+ let f = fixture(true).await;
+ let alice = human(&f.store, "alice").await;
+ let bob = human(&f.store, "bob").await;
+ f.store
+ .writer
+ .grant_memory(alice, f.alpha, GrantLevel::Read, None)
+ .await
+ .unwrap();
+ let app = web(
+ &f,
+ Recall {
+ embedder: Some(embedder()),
+ rerank: None,
+ },
+ );
+ for uri in [
+ "/web/search?q=token%20rotation&workspace=default&project=alpha&explain=1",
+ "/web/search?q=token%20rotation&workspace=default&project=alpha",
+ "/api/v1/search?q=token%20rotation&workspace=default&project=alpha",
+ ] {
+ let (status, body) = get(&app, uri, Some(bob)).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{uri}: {body}");
+ assert!(body.contains("not authorized for alpha"), "{uri}: {body}");
+ for leaked in ["notes/rotation.md", "confidential", "data-trace", "fused"] {
+ assert!(!body.contains(leaked), "{uri} leaked {leaked}: {body}");
+ }
+ // Controls: the granted reader and an unrestricted viewer find it.
+ let (status, body) = get(&app, uri, Some(alice)).await;
+ assert_eq!(status, StatusCode::OK, "{uri}: {body}");
+ assert!(body.contains("notes/rotation.md"), "{uri}: {body}");
+ let (status, body) = get(&app, uri, None).await;
+ assert_eq!(status, StatusCode::OK, "{uri}: {body}");
+ assert!(body.contains("notes/rotation.md"), "{uri}: {body}");
+ }
+
+ // The same refusal through `scopes`, when one of them is foreign.
+ let request = Request::builder()
+ .method(Method::POST)
+ .uri("/api/v1/search")
+ .header("content-type", "application/json")
+ .extension(AuthorizedViewer(bob))
+ .body(Body::from(
+ serde_json::json!({
+ "q": "token rotation",
+ "scopes": [
+ {"workspace": "default", "project": "beta"},
+ {"workspace": "default", "project": "alpha"}
+ ]
+ })
+ .to_string(),
+ ))
+ .unwrap();
+ let resp = app.clone().oneshot(request).await.unwrap();
+ let status = resp.status();
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let body = String::from_utf8_lossy(&body);
+ assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
+ assert!(!body.contains("notes/rotation.md"), "{body}");
+}
+
+#[tokio::test]
+async fn project_search_fails_closed_on_unknown_and_partial_scope() {
+ let f = fixture(false).await;
+ let app = web(&f, Recall::default());
+ let before = f
+ .store
+ .reader
+ .list_projects_with_stats(None)
+ .await
+ .unwrap()
+ .len();
+
+ let (status, body) = get(
+ &app,
+ "/web/search?q=token&workspace=default&project=nope&explain=1",
+ None,
+ )
+ .await;
+ assert_eq!(status, StatusCode::NOT_FOUND, "{body}");
+ let (status, body) = get(
+ &app,
+ "/web/search?q=token&workspace=elsewhere&project=alpha&explain=1",
+ None,
+ )
+ .await;
+ assert_eq!(status, StatusCode::NOT_FOUND, "{body}");
+ assert!(!body.contains("notes/rotation.md"), "{body}");
+ // A read never creates the scope it was asked about.
+ assert_eq!(
+ f.store
+ .reader
+ .list_projects_with_stats(None)
+ .await
+ .unwrap()
+ .len(),
+ before
+ );
+
+ for uri in [
+ "/web/search?q=token&workspace=default",
+ "/web/search?q=token&project=alpha",
+ ] {
+ let (status, _) = get(&app, uri, None).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{uri}");
+ }
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index b7f58940..e1b3050c 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -715,6 +715,45 @@ series, and scope is never a label. The route sits behind the same
`require_root_for_multiuser_admin` gate as every `/admin/*` route: root-only once
the deployment distinguishes operators. Counters reset on restart.
+### Web search and the recall trace
+
+A project search in the web UI (`/web/search` with `workspace` and `project`)
+and a scoped `/api/v1/search` (one project or `scopes`) rank through the same
+three shared steps as a `memory_query` project/scopes search:
+`ai_memory_llm::embed_search_query` embeds the query with the configured
+embedder, `ReaderPool::hybrid_search_scopes` fuses FTS5, entity, vector, graph
+and observation streams and applies the authority adjustment (merging several
+scopes by best rank, then rank, path and id), and the optional
+`ai_memory_llm::RerankStage` reorders a bounded prefix. `serve` reads the config
+once and hands the same embedder and rerank stage to the MCP server and to
+`WebState` (`ai_memory_web::Recall`); the stage's four-call concurrency gate is
+shared, so the web search cannot add provider calls past it. A search with no
+scope stays the cross-project FTS5 ranker, as `memory_query(global=true)` is.
+`ai-memory-mcp/tests/suite/web_search_parity.rs` holds the orders together.
+`explain=1` on a project search renders, per hit, each stream's rank, raw score
+and RRF contribution, the fused score, the authority multiplier, the intent
+boost and the rerank score when present, plus the per-stream timings
+(`StreamTimings`). A project search resolves its scope with the guarded no-create
+lookup, so a restricted project refuses a viewer with no grant before any ranking
+runs.
+
+### Web health panel
+
+`/web/health` is a read-only page behind the same `Capability::Admin` decision
+as `/web/pending` and `/admin/*`: root-only once the deployment distinguishes
+operators. It shows the hook counters (the `IngestMetrics` behind
+`/admin/metrics`, including the 429s from saturation and rate limiting), the
+writer queue depth, the hook spool and recovery journal under the server's data
+directory (`ServeHealthProbe` in `serve.rs`), the SessionEnd consolidation queue
+(`ReaderPool::session_consolidation_queue`: counts per state, last completion,
+oldest pending request), the configured embedder and both providers' passive
+health, and the derived-index and storage figures. `ai_memory_web::health::checks`
+turns those into warnings with the fix commands `ai-memory status` prints
+(`ai_memory_core::fix_lines`: `ai-memory recover`, `ai-memory compact --confirm`,
+`ai-memory embed`, `ai-memory embed --force`, and the LLM provider's retry hint).
+The page holds counts, timestamps and configured labels only; provider error text,
+page content and scope names never reach it.
+
## CLI subcommand surface
```
@@ -1351,7 +1390,9 @@ the server URL is loopback and no `default` server profile is registered.
* **Richer read surfaces for the web UI.** The multi-workspace read-only
wiki browser shipped in `ai-memory-web` (`/web`: project list, page
tree, page view, page history with a server-side unified diff, a paged
- session timeline, search, and the root-only `/web/pending` triage page,
+ session timeline, project search through `memory_query`'s hybrid ranker
+ with a recall trace, the root-only `/web/health` panel, and the root-only
+ `/web/pending` triage page,
whose approve and reject buttons post to the existing
`/admin/pending-writes/*` routes). It stays read-only by design: the wiki is a
machine-authored record, and a browser edit surface would break the
@@ -1363,7 +1404,7 @@ the server URL is loopback and no `default` server profile is registered.
applies: an expired version is neither listed nor readable by id, and a page
whose live version expired shows no history, since the forget sweep deletes
every row at its path. Better *reading*
- (graph exploration, recall traces) is open. See
+ (graph exploration) is open. See
[`docs/frontend-api.md`](frontend-api.md#10-known-gaps-and-deliberate-non-goals).
* **Real LongMemEval-S harness.** The recall-eval framework exists
([`crates/ai-memory-consolidate/tests/suite/recall_eval.rs`](../crates/ai-memory-consolidate/tests/suite/recall_eval.rs));
diff --git a/docs/frontend-api.md b/docs/frontend-api.md
index b63dab7d..246fae6a 100644
--- a/docs/frontend-api.md
+++ b/docs/frontend-api.md
@@ -11,7 +11,7 @@
| | What you can do | What you can't do |
|---|---|---|
-| `/api/v1/*` | Browse workspaces, projects, pages; read full page markdown + frontmatter + back-links; list a page's stored versions and diff two of them; FTS5 search (global or scoped, single or multi-project); aggregate "overview" snapshots; drill into stale / duplicate / orphan pages; list a project's sessions and read one session's raw observations. | Write, delete, rename, lint, consolidate, run sweeps, manage handoffs. The `/api/v1` surface is **read-only by construction**: the handlers contain zero writer calls, and `crates/ai-memory-web/clippy.toml` forbids the `Wiki` write and destructive methods anywhere in the crate, so adding one fails `cargo clippy -D warnings`. Writes still go through `/admin/*` (used by the CLI) or MCP tools. |
+| `/api/v1/*` | Browse workspaces, projects, pages; read full page markdown + frontmatter + back-links; list a page's stored versions and diff two of them; search (global FTS5, or scoped through `memory_query`'s hybrid ranker, single or multi-project); aggregate "overview" snapshots; drill into stale / duplicate / orphan pages; list a project's sessions and read one session's raw observations. | Write, delete, rename, lint, consolidate, run sweeps, manage handoffs. The `/api/v1` surface is **read-only by construction**: the handlers contain zero writer calls, and `crates/ai-memory-web/clippy.toml` forbids the `Wiki` write and destructive methods anywhere in the crate, so adding one fails `cargo clippy -D warnings`. Writes still go through `/admin/*` (used by the CLI) or MCP tools. |
| `--web-ui-dir` | Host any SPA at `/web` (or `--web-slug`), same-origin with the API, behind the same auth. The default built-in `/web` browser stays the fallback when the flag is absent. | Host the SPA on a *different* origin without a reverse proxy. Use same-origin hosting or configure CORS deliberately (see §9). |
## 2. Auth model
@@ -50,7 +50,20 @@ position). Both follow the same per-project read rule as the page view.
The builtin wiki also serves the root-only `GET {web_slug}/pending` page. It
lists pending auto-improvement proposals and posts approve and reject to the
existing `/admin/pending-writes/*` routes. A signed-in non-root user gets a
-403 page, not the change-password redirect. Start
+403 page, not the change-password redirect. The root-only
+`GET {web_slug}/health` page follows the same gate: hook counters (accepted,
+shed, 429), writer queue, the spool and recovery journal under the server's
+data directory, the consolidation queue, embedder and provider state, and the
+failing server-side checks with their fix commands. It is HTML only, answers
+`Cache-Control: private, no-store`, and shows counts, timestamps and configured
+labels, never provider error text or page content.
+`GET {web_slug}/search?q=…&workspace=…&project=…&explain=1` is the project
+search: the same hybrid ranker and per-project read rule as a scoped
+`/api/v1/search` (§4.5), and with `explain=1` a recall trace (per-hit stream
+ranks, raw scores, RRF contributions, fused score, authority, intent boost,
+rerank score, plus per-stream timings). `limit` clamps to `1..=100`, default
+`20`; without a scope it is the cross-project FTS5 search (default `50`), whose
+trace is the FTS time alone. Start
with:
```http
@@ -265,7 +278,16 @@ Rules:
top-level `workspace`/`project`.
- `snippet` contains FTS5 HTML markers (`<mark>…</mark>`) around the
matched terms.
-- `rank` is FTS5 rank; **lower is better** (closer to query terms).
+- A **global** search (no scope) is FTS5 over every project the caller may
+ read, like `memory_query(global=true)`; `rank` is the FTS5 rank.
+- A **scoped** search (`workspace`+`project`, or `scopes`) runs the hybrid
+ ranker `memory_query` uses for a project: FTS5, entity, vector (when the
+ server has an embedder), graph and observation streams fused by RRF, the
+ bounded authority adjustment, and the optional reranker. The same query
+ returns the same order as `memory_query`; `rank` is the negated,
+ authority-adjusted fused score. Several `scopes` merge by best rank per
+ page.
+- `rank`: **lower is better** in both modes.
### 4.6 Recent
@@ -773,7 +795,7 @@ The trailing-slash redirect at `{base_path}{web_slug}/` →
client-side and never reach the server.
When `--web-ui-dir` is **absent**, the built-in server-side `/web`
-browser is the default (read-only HTML rendering, FTS5 search,
+browser is the default (read-only HTML rendering, search,
project tree), unchanged from before.
## 7. Worked example: minimal SPA fetch
@@ -865,6 +887,8 @@ Read these:
| Response structs (`PageHit`, `WorkspaceSummary`, `BriefingSnapshot`, `HealthPage`, `SessionSummary`, `ObservationRecord`, …) | `crates/ai-memory-store/src/reader.rs` |
| Session listing + per-session observation readers (`sessions_for_scope`, `session_summary_scoped`, `session_observations_scoped`) | `crates/ai-memory-store/src/reader.rs` |
| Page-history readers (`page_versions`, `page_version_body`) and the bounded diff | `crates/ai-memory-store/src/reader.rs`, `crates/ai-memory-web/src/diff.rs` |
+| Scoped search ranker shared with `memory_query` (`hybrid_search_scopes`) | `crates/ai-memory-web/src/recall.rs`, `crates/ai-memory-store/src/reader.rs` |
+| Health panel checks and fix lines | `crates/ai-memory-web/src/health.rs`, `crates/ai-memory-core/src/fix_lines.rs` |
| 27 integration tests covering every endpoint (auth, 400s, 404s, multi-scope correctness, SPA fallback) | `crates/ai-memory-web/tests/routes.rs` |
| Auth + middleware layering | `crates/ai-memory-cli/src/commands/serve.rs` (`mount_web_router`, `apply_http_layers`) |
| Custom-UI dir validation | `crates/ai-memory-cli/src/commands/serve.rs` (`validate_web_ui_args`) |
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 476b636c..f0155953 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -36,6 +36,7 @@ means the boundary is not built yet.
| 3b | Browser triage of pending writes (#855) | `ai-memory-web/src/routes/pending.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, trusted-proxy flag from `WebMountSpec`) gates `GET {web_slug}/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect; decisions post to the existing `/admin/pending-writes/{id}/approve\|reject` behind `require_dual_auth` (session + CSRF) and `require_root_for_multiuser_admin`. `ai-memory-web` has no write route | `ai-memory-web` `tests/suite/pending.rs` — anonymous refused (401, login redirect), DB user refused (403, no proposal text, no redirect), trusted-proxy flag reaches the gate, single-operator control admits, POSTs to `/pending*` refused, project filter keys do not collide on `/` in names, projects past the 500-row read cap stay counted and reachable; `ai-memory-mcp` `tests/suite/admin_pending_writes_session.rs` — anonymous and DB-user sessions refused, root session without a matching CSRF header refused (each leaves the proposal pending and no file), root approval keeps `auto_improve_proposal_id`/`auto_improve_run_id` and records the approver, root reject writes no file (each proven to fail with its guard removed); `ai-memory-mcp` `admin.rs` `pending_write_approve_foreign_scope_returns_404` and `pending_write_reject_foreign_scope_returns_404` — an id staged in workspace `alpha` requested through an existing `default` scope is 404 (never approved or rejected across the boundary), with the in-scope reject as the legitimate control (each proven to fail with 500 with the `pending_detail` guard removed, #1205) | STRONG |
| 3c | Public human-auth routes refuse bodies a foreign page can send without a preflight (login CSRF, password guessing, root recovery) | `ai-memory-mcp/src/human_auth.rs` `handle_login` / `handle_recovery` read their bodies by hand (to rate-limit first), so each checks `declares_json_body` before reading: a `Content-Type` other than `application/json` or `application/*+json` (parameters and case ignored), or none, → 415 before any password or recovery-token check and without charging the per-IP failure budget. `text/plain`, form-urlencoded and multipart are the only bodies a cross-site page can `POST` without a preflight, and `/auth/*` carries no CORS layer. The built-in login page, the `docs/frontend-api.md` examples and the recovery `curl` in `docs/install.md` send `application/json` | `human_auth.rs` `public_auth_routes_refuse_preflight_free_browser_bodies`: valid root credentials and a valid recovery token, sent from a foreign origin as `text/plain`, form-urlencoded, multipart and with no content type, more times than the per-IP failure budget → 415, no session cookie; controls: a same-origin JSON login then succeeds (password unchanged, budget untouched) and a JSON recovery returns 204. `json_body_declaration` (header table) | STRONG. Bite check: with the check removed, the `text/plain` login returns 200 with the session cookie (the pre-fix behaviour) and the test fails. `/auth/password` and `/auth/logout` were already closed: they run behind `require_session`, whose unsafe methods need the `x-csrf-token` header (a custom header, so preflighted), and `/auth/password` also uses axum `Json` |
| 3d | `GET /admin/metrics` is root-only on a multi-user server and content-free | `ai-memory-mcp/src/admin.rs` mounts `/admin/metrics` inside the operational router under `require_root_for_multiuser_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`); `ai-memory-mcp/src/metrics.rs` `render_prometheus` writes only counts and durations under compile-time metric names and the closed label set `result` / `outcome` / `kind` / `le`; `McpMetrics::record_tool_call` takes only a read/write bit (no client name); `ai-memory-core/src/latency.rs` `LatencyHistogram` holds bucket counts and a sum, nothing keyed on a request; scope is never a label | mcp `integration::admin_metrics` `metrics_count_queries_and_hooks_without_leaking_any_content` (secret-shaped strings planted in a `memory_query` query, a `/hook` prompt and the project name never appear in the scrape, nor do the session id, workspace name or root token; every label key is from the closed set; control: the query and hook histograms, the accepted-hook counter and the read tool-call counter move by exactly what was sent), `metrics_are_root_only_on_a_multi_user_server` (production `require_dual_auth` with a real DB-user key: anonymous 401, DB user 403, unknown bearer 401, root control 200); `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` include the route, `multiuser_operational_admin_routes_allow_root` admits root | STRONG. Bite checks: with the route mounted outside the gate the three refusal tests fail; with the query, the project name or the hook body rendered as a label value the leak test fails on each |
+| 3e | The web health panel is root-only on a multi-user server, read-only and content-free | `ai-memory-web/src/routes/mod.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, shared with `/web/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect) gates `GET {web_slug}/health`, a GET-only route; `routes/health.rs` renders only counters, timestamps and configured provider/model labels, `provider_line` leaves out `last_error_message` (it can quote a response body), and the process side comes through `health::HealthProbe` as counts (`ServeHealthProbe` in `ai-memory-cli/src/commands/serve.rs` drops the journal's error text); the response is `Cache-Control: private, no-store` | `ai-memory-web` `tests/suite/health.rs` — `health_page_refuses_anonymous_once_operators_are_distinguished` (401, login redirect on navigation, no counters or fix lines), `health_page_refuses_a_db_user_and_admits_root` (403 "Root access required", no redirect, no counters; root control 200), `health_page_follows_the_admin_gate_on_a_single_operator_server` (control), `health_page_carries_no_secret_material` (secret-shaped strings planted in a failed LLM call's and a failed embed's provider error body, a page body, a page title and the project name never appear), `health_page_has_no_write_route` (POST/PUT/DELETE 405), plus a fixture per rendered check (`health_page_renders_each_failing_check_with_its_fix_line`, `health_page_renders_pending_spool_and_journal_checks`, `health_page_reports_a_healthy_server_as_passing`, and `src/health.rs` unit tests for every check id) | STRONG. Bite checks: with the `require_admin` call removed from the handler, the anonymous and DB-user tests fail; with `last_error_message` appended to the provider line, the planted-secret test fails |
| 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS; the receiver-session check, which requires the receiving session to exist in the claim's own workspace, project and agent kind and refuses with `InvalidState` before the handoff row is touched; an ended receiver is final EXCEPT for the agents where `AgentKind::reuses_session_id_after_end()` holds — Grok and Kimi Code, whose harnesses reuse the native session id across SessionEnd→resume, so accepting reopens `ended_at` only after the claim-once guard) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff`; `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (receivers from a sibling project, another workspace, a different agent kind, and a nonexistent session are each refused as `InvalidState` with the handoff left open and every `accepted_*` column NULL; the matching receiver claims it; the same receiver retrying and a second matching session get `false` with the first claim intact; fails with the `project_id` or `agent_kind` predicate, or the missing-session refusal, removed. The `workspace_id` predicate is redundant defence in depth: project ids are globally unique, so the cross-workspace receiver is already caught by `project_id`); `multi_session.rs` `accept_reopens_an_ended_receiver_session_but_keeps_claim_once` (Grok reopen + no-steal) and `accept_reopens_an_ended_kimi_receiver_but_keeps_every_guard` (Kimi Code resume claims and reopens `ended_at`; adversarial controls: an ended claude-code receiver stays refused, a kimi-code receiver in another project stays refused, and the already-claimed guard still refuses the resumed kimi session a second baton) | STRONG |
| 4b | Handoff owner-scoped recovery (`any_owner` admin gate) | `ai-memory-mcp/src/server.rs` `require_admin_capability` on `memory_handoff_accept`/`_cancel` `any_owner` | `handoff_admission.rs` — cancel gate + **accept gate** (adversarial: non-admin `any_owner` accept refused) | STRONG |
| 4c | Turn-checkpoint baton is owner+scope-bound | `ai-memory-store/src/ops.rs` `checkpoint_session_handoff` — reads the session's own `(workspace, project, owner_user)` from `sessions WHERE id=?1 AND ended_at IS NULL`, refuses on scope/owner mismatch, refreshes only that session's own `state='open'` baton (id preserved), returns `None` when the session already ended | `ops.rs` `checkpoint_session_handoff_refreshes_only_the_live_sessions_own_baton` (#865) | STRONG |
@@ -98,6 +99,7 @@ means the boundary is not built yet.
| 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG |
| 14e | `memory_write_page` session evidence cites only a session of the target project (#708) | `ai-memory-mcp/src/server.rs` `memory_write_page` — a `session_id` is accepted only when `require_session_in_scope` resolves the session (where its observations landed, else its session row, as `Consolidator::session_target` does) to the same `(workspace_id, project_id)` the write grant was checked against; unknown and foreign ids get one refusal, so the error is no existence oracle; `scope: "global"` with a `session_id` is refused; `refuse_pinned_page_overwrite` keeps a write that cites a session off a pinned page; only a write to `sessions/<id>.md` reconciles the session's queued SessionEnd job | `server.rs` `write_page_refuses_a_session_from_another_project` (a foreign and an unknown session refused, no evidence row written, the foreign job still queued; control: the project's own session accepted), `session_evidence_write_leaves_a_pinned_page_alone` (control: the same write without `session_id` edits the page), `session_evidence_on_another_path_leaves_the_job_queued`, `write_page_rejects_a_malformed_or_global_session_id` — each of the scope check, the pinned check and the session-page-only reconcile proven to fail its test when removed | STRONG |
| 14f | Consolidation apply path validates cross-scope wikilinks against the store (#1218) | `ai-memory-consolidate/src/link_guard.rs` `unresolved_cross_scope_links` — every `[[project:path]]` / `[[workspace/project:path]]` / `[[_global:path]]` target in a proposed body is resolved with the no-create `lookup_existing_scope` (never creates a scope) and batch-checked via `reader.rs` `existing_latest_paths`; a missing workspace/project, an ambiguous project name, or a missing target page de-links the wikilink, while a genuine store failure aborts the consolidation before any write. Typed `relations:` frontmatter targets go through the same check, and `prune_relations` drops an unresolved entry (an emptied relation and an emptied map with it). `delink_body` → `ai-memory-wiki/src/markdown.rs` `delink_wikilinks` drops the brackets and keeps the label, skipping code fences and inline code exactly as `extract_links` does. Wired into all three apply paths (`consolidator.rs` single-page and batch, `bootstrap.rs`) after the pinned/foreign-slot/portable guards and before the atomic `Wiki::apply_batch` / `write_page`, so an invented cross-project dependency can no longer be written and flagged by the lint pass later. Same-project `[[target]]` links stay untouched by design (the target may be written later). The probe runs with no viewer, so it reports nothing for a `restricted` project (the global preferences project excepted): a link into one is always de-linked, and whether a link survived says nothing about which paths exist there | `consolidator.rs` `batch_delinks_invented_cross_scope_wikilinks` (invented `[[_global:nope]]`, `[[otherproj:notes/missing.md]]`, `[[ghostproj:x.md]]` de-linked to plain text; controls: a cross-scope link to an existing page and a same-project pending link survive byte-identical; `dangling_cross_project_links` left empty), `single_page_delinks_invented_cross_scope_wikilinks`, `single_page_drops_unresolved_cross_scope_relations` (unresolved `relations:` entries dropped; controls: a live cross-scope and a same-project target stay), `link_guard.rs` `prune_relations_drops_only_unresolved_cross_scope_entries`, `bootstrap.rs` `bootstrap_delinks_invented_cross_scope_wikilinks` — each proven to fail with the guard neutralized; `markdown.rs` `delink_wikilinks_strips_only_listed_cross_scope_links`, `delink_wikilinks_without_label_keeps_the_target_text`, `delink_wikilinks_skips_code_and_leaves_empty_set_untouched`; store `multi_session.rs` `existing_latest_paths_reports_exactly_the_live_paths` (exact live-path set, superseded path still resolves, foreign scope sees nothing), `existing_latest_paths_reports_nothing_for_a_restricted_project` (real and absent paths answer alike while restricted; control: reopened, the page is seen) | STRONG |
+| 14g | Web project search and its recall trace honour `memory_query`'s scope rules (#708) and never describe another project | `ai-memory-web/src/routes/search.rs` resolves `workspace`+`project` through `resolve_read_scope` (`lookup_existing_scope_guarded`, no-create, `ProjectAccess::Read`) before any ranking, and refuses partial scope; scoped `/api/v1/search` keeps `lookup_project` / `resolve_many_existing_scopes_guarded`; `ai-memory-web/src/recall.rs` ranks only the resolved scopes through `ReaderPool::hybrid_search_scopes`, whose streams and graph expansion are bound to each `(workspace_id, project_id)`; a search with no scope stays `search_pages_with_meta(.., viewer)` (readable repositories only) | `ai-memory-web` `tests/suite/recall_trace.rs` — `project_search_refuses_a_restricted_project_without_a_grant` (bob, with no grant, gets 403 from `/web/search` with and without `explain=1` and from scoped `/api/v1/search`, with no path, body text or trace in the response, and a `scopes` POST naming the restricted project next to an open one is refused; alice's grant and an unrestricted viewer are the controls), `project_search_fails_closed_on_unknown_and_partial_scope` (unknown project or workspace 404 with nothing created, partial scope 400), `explain_renders_stream_ranks_rrf_authority_and_timings` (a better-matching page in a sibling project never reaches the hits or the trace); `ai-memory-mcp` `tests/suite/web_search_parity.rs` (same top-k order as `memory_query` from `/web` and `/api/v1`, with a deterministic embedder and with none, explain on and off, and merged `scopes`; controls show a web search without the embedder, or the old FTS-only scoped search, would fail it) | STRONG. Bite checks: passing no viewer to `resolve_read_scope` in the search handler, to `lookup_project` or to `resolve_scopes` in the API each fails the restricted-project test; dropping the query vector in `recall.rs` fails the embedder parity tests |
| 15 | Agent-archive restore path confinement, resource bounds, and consistency | `ai-memory-cli/src/commands/restore_agents.rs` stages only bounded regular UTF-8 entries; requires a one-to-one manifest/body/checksum/target mapping; allowlists destinations by scope; rejects symlinked descendants; writes each file atomically and rolls back earlier writes after a later failure. `backup_agents.rs` skips direct and directory-root source symlinks, bounds individual assets, and atomically replaces a private archive only after gzip completion | `backup_agents.rs` `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`, `restore_agents_requires_a_complete_one_to_one_manifest`, `restore_agents_rejects_oversized_entries_from_the_header`, `restore_agents_rejects_a_symlinked_destination_parent`, `backup_agents_does_not_follow_config_or_asset_root_symlinks`, and `failed_backup_leaves_the_previous_archive_intact`; `backup_and_restore_agents_round_trip` is the valid-path control; `restore_agents::tests::rollback_removes_new_files_and_restores_overwrites` covers recovery | STRONG |
| 16 | Relay queue identity, migration, and private filesystem state | `companions/ai-memory-relay/src/queue.rs` `Queue::open_inner` performs read-only identity preflight, rechecks under `IMMEDIATE`, commits schema and metadata together; `configure` checks the presence of user objects and rechecks `identity`/`schema_version` metadata on the same connection before every bounded BUSY/LOCKED retry; `fsguard.rs` checks existing paths and creates owner-only files before SQLite opens them | `tests/relay.rs` `a_foreign_database_is_refused_byte_for_byte`, `unknown_schemas_refuse_without_mutation`, `a_foreign_database_with_a_writer_is_refused_before_write_coordination`, `a_foreign_identity_after_preflight_is_refused_without_mutation`, `a_foreign_identity_during_journal_retry_is_refused_without_mutation`, `journal_retry_refuses_a_changed_version_or_empty_database_without_mutation`; controls: `journal_transition_retries_sqlite_lock_without_losing_v1_values`, `fresh_queue_init_and_v1_reopens_work_across_processes`; recovery: `interrupted_and_failed_migrations_roll_back_and_recover`, `journal_reclassification_busy_preserves_committed_migration_and_retries_same_queue`; diagnostics: `classification_read_failures_display_the_sqlite_cause_once_and_preserve_foreign_bytes`; Unix privacy: `the_queue_database_and_its_sidecars_are_owner_only` and the contended migration control | Guard-removal proof covers preflight, locked recheck, and journal retry identity/version checks; full table structure is outside this classification. Windows path rejection is preserved; Windows ACL hardening remains operator-owned |
diff --git a/docs/usage.md b/docs/usage.md
index 2a9ab14d..fb1aba2a 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -513,7 +513,14 @@ command: ["serve", "--transport", "http", "--bind", "0.0.0.0:49374", "--enable-w
```
The web UI is read-only: project list, per-project page tree,
-breadcrumbs, rendered markdown, metadata, and FTS5 search. Each page links
+breadcrumbs, rendered markdown, metadata, and search. The search box in the
+header searches every project with FTS5, like `memory_query(global=true)`. The
+search on a project page ranks with the same hybrid ranker as `memory_query`
+for that project, and its "Explain ranking" box shows each hit's stream ranks,
+RRF contributions, authority and rerank score, plus the per-stream timings.
+Root also gets `/web/health`: hook counters (429s included), the writer queue,
+the local spool and recovery journal, the consolidation queue, embedder and
+provider state, and the failing checks with the command that fixes each. Each page links
to its history (`/web/w/<ws>/<proj>/h/<path>`): every stored version, newest
first, with the author where the write was attributed, and a unified diff
between any two of them (by default the latest against the version it