Skip to content

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

Rust

cli: phase 2 — status + search become HTTP clients

AkitaOnRailscdb84b4398fa
diff --git a/crates/ai-memory-cli/src/commands/bootstrap.rs b/crates/ai-memory-cli/src/commands/bootstrap.rs
index eda269ba..8cf1f75b 100644
--- a/crates/ai-memory-cli/src/commands/bootstrap.rs
+++ b/crates/ai-memory-cli/src/commands/bootstrap.rs
@@ -19,6 +19,7 @@ use tracing::info;
use crate::cli::BootstrapArgs;
use crate::config::Config;
+use crate::http_client::{ServerEndpoint, post_json};
/// Run the `bootstrap` subcommand.
///
@@ -30,20 +31,8 @@ use crate::config::Config;
/// path is not a git repo, when source collection fails, or when the
/// server returns a non-2xx response.
pub async fn run(_config: &Config, args: BootstrapArgs) -> Result<()> {
- // ---- server URL — defaults to loopback ------------------------
- // The CLI is a thin HTTP client. With no env var it talks to a
- // local server on the default port; set AI_MEMORY_SERVER_URL to
- // point at a remote (e.g. homelab).
- let server_url = std::env::var("AI_MEMORY_SERVER_URL")
- .ok()
- .filter(|s| !s.is_empty())
- .unwrap_or_else(|| "http://127.0.0.1:49374".to_string());
- // Bearer is optional: only sent when the env var is non-empty.
- // A loopback server with no token set accepts every request.
- let auth_token = std::env::var("AI_MEMORY_AUTH_TOKEN")
- .ok()
- .filter(|s| !s.is_empty());
- info!(%server_url, auth = auth_token.is_some(), "bootstrap CLI configured");
+ let ep = ServerEndpoint::from_env();
+ info!(server = %ep.url, auth = ep.auth_token.is_some(), "bootstrap CLI configured");
// ---- repo path — auto-detect if absent -------------------------
let repo_path = match args.repo_path {
@@ -70,8 +59,6 @@ pub async fn run(_config: &Config, args: BootstrapArgs) -> Result<()> {
info!(sources = sources.len(), "collected sources from repo");
// ---- POST to server -------------------------------------------
- let client = reqwest::Client::new();
- let url = format!("{}/admin/bootstrap", server_url.trim_end_matches('/'));
let body = serde_json::json!({
"workspace": args.workspace,
"project": args.project,
@@ -80,20 +67,7 @@ pub async fn run(_config: &Config, args: BootstrapArgs) -> Result<()> {
"dry_run": args.dry_run,
"force": args.force,
});
- let mut req = client.post(&url).json(&body);
- if let Some(t) = &auth_token {
- req = req.bearer_auth(t);
- }
- let resp = req.send().await.context("POST /admin/bootstrap")?;
- if !resp.status().is_success() {
- let status = resp.status();
- let text = resp.text().await.unwrap_or_default();
- bail!("server returned {}: {}", status, text);
- }
- let outcome: BootstrapOutcome = resp
- .json()
- .await
- .context("parsing BootstrapOutcome JSON from server response")?;
+ let outcome: BootstrapOutcome = post_json(&ep, "/admin/bootstrap", &body).await?;
print_human_report(&outcome, &args.workspace, &args.project);
let report = serde_json::to_string_pretty(&outcome)?;
diff --git a/crates/ai-memory-cli/src/commands/search.rs b/crates/ai-memory-cli/src/commands/search.rs
index ed7b3eb5..2e54bd4d 100644
--- a/crates/ai-memory-cli/src/commands/search.rs
+++ b/crates/ai-memory-cli/src/commands/search.rs
@@ -1,23 +1,37 @@
//! `ai-memory search` — run an FTS5 query against the wiki index.
+//!
+//! Thin HTTP client. Calls `GET /admin/search?q=…&limit=…`; renders
+//! the hits as human text or JSON. Never opens the store directly.
-use ai_memory_store::Store;
-use anyhow::{Context, Result};
+use anyhow::Result;
+use serde::{Deserialize, Serialize};
use crate::cli::SearchArgs;
use crate::config::Config;
+use crate::http_client::{ServerEndpoint, get_json};
+
+/// FTS5 hit, mirrors `ai_memory_store::PageHit` fields used here.
+#[derive(Debug, Deserialize, Serialize)]
+struct Hit {
+ path: String,
+ title: String,
+ snippet: String,
+ rank: f64,
+}
/// Run the `search` subcommand.
///
/// # Errors
-/// Returns an error if the store cannot be opened, the query is malformed,
-/// or JSON serialisation fails.
-pub async fn run(config: &Config, args: SearchArgs) -> Result<()> {
- let store = Store::open(&config.data_dir)
- .with_context(|| format!("opening store at {}", config.data_dir.display()))?;
- let hits = store
- .reader
- .search_pages(args.query.clone(), args.limit)
- .await?;
+/// Returns an error if the server is unreachable or returns non-2xx.
+pub async fn run(_config: &Config, args: SearchArgs) -> Result<()> {
+ let ep = ServerEndpoint::from_env();
+ let limit_str = args.limit.to_string();
+ let hits: Vec<Hit> = get_json(
+ &ep,
+ "/admin/search",
+ &[("q", args.query.as_str()), ("limit", limit_str.as_str())],
+ )
+ .await?;
if args.json {
println!("{}", serde_json::to_string_pretty(&hits)?);
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 1c3b690d..cce69df2 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -180,6 +180,9 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
reader: store.reader.clone(),
wiki: wiki.clone(),
llm: admin_llm,
+ data_dir: config.data_dir.clone(),
+ db_path: store.db_path().to_path_buf(),
+ bind: bind.clone(),
});
// Build the auth state. Precedence (highest first):
// 1. AI_MEMORY_AUTH_TOKEN env var
diff --git a/crates/ai-memory-cli/src/commands/status.rs b/crates/ai-memory-cli/src/commands/status.rs
index 1ce743bc..0083d642 100644
--- a/crates/ai-memory-cli/src/commands/status.rs
+++ b/crates/ai-memory-cli/src/commands/status.rs
@@ -1,46 +1,70 @@
//! `ai-memory status` — report runtime config and persisted counts.
+//!
+//! Thin HTTP client. Calls `GET /admin/status` on the configured
+//! server; renders the response as human text or JSON. Never opens
+//! the store directly — the server is the source of truth.
-use std::path::Path;
-
-use ai_memory_store::{StatusCounts, Store};
-use anyhow::{Context, Result};
-use serde::Serialize;
+use anyhow::Result;
+use serde::Deserialize;
use crate::cli::StatusArgs;
use crate::config::Config;
+use crate::http_client::{ServerEndpoint, get_json};
+
+/// Server-shaped response. Mirrors `ai_memory_mcp::admin::StatusReport`.
+#[derive(Debug, Deserialize)]
+struct Report {
+ /// Server binary version.
+ version: String,
+ /// Server-side data directory path.
+ data_dir: String,
+ /// Server bind address.
+ bind: String,
+ /// Server-side SQLite path.
+ db_path: String,
+ /// Lifetime counts.
+ counts: Counts,
+}
-#[derive(Debug, Serialize)]
-struct Report<'a> {
- version: &'a str,
- data_dir: &'a Path,
- bind: &'a str,
- db_path: &'a Path,
- counts: StatusCounts,
+#[derive(Debug, Deserialize)]
+struct Counts {
+ pages_latest: u64,
+ pages_all: u64,
+ sessions: u64,
+ observations: u64,
}
/// Run the `status` subcommand.
///
/// # Errors
-/// Returns an error if the store cannot be opened or JSON serialisation fails.
-pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {
- let store = Store::open(&config.data_dir)
- .with_context(|| format!("opening store at {}", config.data_dir.display()))?;
- let counts = store.reader.status_counts().await?;
-
- let report = Report {
- version: env!("CARGO_PKG_VERSION"),
- data_dir: &config.data_dir,
- bind: &config.bind,
- db_path: store.db_path(),
- counts,
- };
+/// Returns an error if the server is unreachable, returns non-2xx, or
+/// the response can't be parsed.
+pub async fn run(_config: &Config, args: StatusArgs) -> Result<()> {
+ let ep = ServerEndpoint::from_env();
+ let report: Report = get_json(&ep, "/admin/status", &[]).await?;
if args.json {
- println!("{}", serde_json::to_string_pretty(&report)?);
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&serde_json::json!({
+ "version": report.version,
+ "data_dir": report.data_dir,
+ "bind": report.bind,
+ "db_path": report.db_path,
+ "counts": {
+ "pages_latest": report.counts.pages_latest,
+ "pages_all": report.counts.pages_all,
+ "sessions": report.counts.sessions,
+ "observations": report.counts.observations,
+ },
+ "client": { "server_url": ep.url, "auth": ep.auth_token.is_some() },
+ }))?
+ );
} else {
- println!("ai-memory {}", report.version);
- println!(" data-dir: {}", report.data_dir.display());
- println!(" db: {}", report.db_path.display());
+ println!("ai-memory {} (server)", report.version);
+ println!(" server: {}", ep.url);
+ println!(" data-dir: {}", report.data_dir);
+ println!(" db: {}", report.db_path);
println!(" bind: {}", report.bind);
println!(
" pages: {} (all versions: {})",
diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rs
new file mode 100644
index 00000000..d61dda82
--- /dev/null
+++ b/crates/ai-memory-cli/src/http_client.rs
@@ -0,0 +1,113 @@
+//! Shared HTTP-client glue for thin-client CLI subcommands.
+//!
+//! Every state-touching subcommand (status, search, bootstrap, …) goes
+//! through these helpers so URL resolution + bearer-auth handling stays
+//! consistent in one place.
+//!
+//! ## Configuration
+//!
+//! Two environment variables drive the client:
+//!
+//! - `AI_MEMORY_SERVER_URL` — base URL. Defaults to
+//! `http://127.0.0.1:49374` for the single-laptop case.
+//! - `AI_MEMORY_AUTH_TOKEN` — bearer token. Optional; only sent when
+//! non-empty. A loopback server with no token set accepts every
+//! request, so the default flow needs no credentials at all.
+
+use anyhow::{Context, Result, bail};
+use serde::Serialize;
+use serde::de::DeserializeOwned;
+
+/// Resolved server target — base URL + optional bearer token.
+#[derive(Debug, Clone)]
+pub struct ServerEndpoint {
+ /// Base URL with any trailing slash stripped, e.g.
+ /// `http://127.0.0.1:49374` or `http://192.168.0.90:49374`.
+ pub url: String,
+ /// Bearer token when present, else `None`.
+ pub auth_token: Option<String>,
+}
+
+impl ServerEndpoint {
+ /// Read the endpoint from `AI_MEMORY_SERVER_URL` +
+ /// `AI_MEMORY_AUTH_TOKEN`. Both are optional; the URL defaults to
+ /// loopback, the token defaults to unset.
+ #[must_use]
+ pub fn from_env() -> Self {
+ let url = std::env::var("AI_MEMORY_SERVER_URL")
+ .ok()
+ .filter(|s| !s.is_empty())
+ .unwrap_or_else(|| "http://127.0.0.1:49374".to_string())
+ .trim_end_matches('/')
+ .to_string();
+ let auth_token = std::env::var("AI_MEMORY_AUTH_TOKEN")
+ .ok()
+ .filter(|s| !s.is_empty());
+ Self { url, auth_token }
+ }
+
+ /// Apply auth header to a `reqwest::RequestBuilder` if a token is set.
+ pub(crate) fn authenticate(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
+ match &self.auth_token {
+ Some(t) => req.bearer_auth(t),
+ None => req,
+ }
+ }
+}
+
+/// GET `<endpoint>{path}` with optional query params, deserialise JSON.
+///
+/// # Errors
+/// Returns an error when the connection fails, the response is non-2xx,
+/// or the body can't be deserialised into `T`.
+pub async fn get_json<T: DeserializeOwned>(
+ endpoint: &ServerEndpoint,
+ path: &str,
+ query: &[(&str, &str)],
+) -> Result<T> {
+ let client = reqwest::Client::new();
+ let url = format!("{}{path}", endpoint.url);
+ let mut req = client.get(&url);
+ if !query.is_empty() {
+ req = req.query(query);
+ }
+ req = endpoint.authenticate(req);
+ let resp = req
+ .send()
+ .await
+ .with_context(|| format!("GET {url} (is the server running at {}?)", endpoint.url))?;
+ let status = resp.status();
+ if !status.is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ bail!("server returned {status}: {body}");
+ }
+ resp.json::<T>()
+ .await
+ .with_context(|| format!("parsing JSON body from GET {url}"))
+}
+
+/// POST JSON body to `<endpoint>{path}`, deserialise JSON response.
+///
+/// # Errors
+/// Same as [`get_json`].
+pub async fn post_json<B: Serialize, T: DeserializeOwned>(
+ endpoint: &ServerEndpoint,
+ path: &str,
+ body: &B,
+) -> Result<T> {
+ let client = reqwest::Client::new();
+ let url = format!("{}{path}", endpoint.url);
+ let req = endpoint.authenticate(client.post(&url).json(body));
+ let resp = req
+ .send()
+ .await
+ .with_context(|| format!("POST {url} (is the server running at {}?)", endpoint.url))?;
+ let status = resp.status();
+ if !status.is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ bail!("server returned {status}: {body}");
+ }
+ resp.json::<T>()
+ .await
+ .with_context(|| format!("parsing JSON body from POST {url}"))
+}
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 3efe8f29..36811f0b 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -17,6 +17,7 @@ mod auth;
mod cli;
mod commands;
mod config;
+mod http_client;
mod logging;
mod process_guard;
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 5591be33..3e6127b8 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -1,14 +1,19 @@
//! Admin HTTP routes — state-touching operations invoked by the CLI
-//! over plain HTTP (not MCP). Currently exposes `POST /admin/bootstrap`.
+//! over plain HTTP (not MCP). Currently exposes:
//!
-//! The bootstrap route accepts a pre-collected source bundle from the
-//! CLI, runs the LLM summarisation + wiki write server-side, and
-//! returns the [`BootstrapOutcome`] as JSON. The CLI is responsible for
-//! filesystem access (collecting sources from the project repo); the
-//! server is responsible for all state writes.
+//! - `POST /admin/bootstrap` — ingest a pre-collected source bundle
+//! into seed wiki pages via the configured LLM provider.
+//! - `GET /admin/status` — lifetime counts + server data-dir info.
+//! - `GET /admin/search?q=` — FTS5 hits against the wiki index.
+//!
+//! The CLI is responsible for filesystem access (collecting sources from
+//! the project repo, rendering output for humans); the server is
+//! responsible for all state reads/writes against the wiki + SQLite.
use std::sync::Arc;
+use std::path::PathBuf;
+
use ai_memory_consolidate::{
Bootstrap, BootstrapConfig, BootstrapOutcome, BootstrapSource, SourceCounts,
};
@@ -17,11 +22,11 @@ use ai_memory_store::{ReaderPool, WriterHandle};
use ai_memory_wiki::Wiki;
use axum::Json;
use axum::Router;
-use axum::extract::State;
+use axum::extract::{Query, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
-use axum::routing::post;
-use serde::Deserialize;
+use axum::routing::{get, post};
+use serde::{Deserialize, Serialize};
/// Shared state for the admin router.
#[derive(Clone)]
@@ -34,6 +39,14 @@ pub struct AdminState {
pub wiki: Wiki,
/// Optional LLM provider. When `None`, bootstrap returns 503.
pub llm: Option<Arc<dyn LlmProvider>>,
+ /// Server's resolved data directory (e.g. `/data` in the docker
+ /// image). Surfaced via `/admin/status` so the CLI can report
+ /// "where the wiki + db actually live".
+ pub data_dir: PathBuf,
+ /// Resolved SQLite path inside `data_dir`. Same purpose as above.
+ pub db_path: PathBuf,
+ /// Server's bind address — informational, surfaced in /admin/status.
+ pub bind: String,
}
/// JSON request body for `POST /admin/bootstrap`.
@@ -60,13 +73,100 @@ fn default_max_input_tokens() -> usize {
50_000
}
-/// Build the admin axum [`Router`]. Mounts `POST /admin/bootstrap`.
+/// Build the admin axum [`Router`]. Mounts:
+/// - `POST /admin/bootstrap`
+/// - `GET /admin/status`
+/// - `GET /admin/search`
pub fn admin_router(state: AdminState) -> Router {
Router::new()
.route("/admin/bootstrap", post(handle_bootstrap))
+ .route("/admin/status", get(handle_status))
+ .route("/admin/search", get(handle_search))
.with_state(Arc::new(state))
}
+// ---------------------------------------------------------------------
+// status
+// ---------------------------------------------------------------------
+
+/// JSON response body for `GET /admin/status`. The CLI's `status`
+/// subcommand renders this either as JSON (`--json`) or as a small
+/// human-friendly text block.
+#[derive(Debug, Serialize)]
+pub struct StatusReport {
+ /// Server binary version (Cargo package version).
+ pub version: String,
+ /// Absolute data directory the server uses (server-side path).
+ pub data_dir: String,
+ /// Bind address the HTTP transport is listening on.
+ pub bind: String,
+ /// Absolute SQLite path inside `data_dir`.
+ pub db_path: String,
+ /// Lifetime counts: pages_latest, pages_all, sessions, observations.
+ pub counts: ai_memory_store::StatusCounts,
+}
+
+async fn handle_status(State(state): State<Arc<AdminState>>) -> impl IntoResponse {
+ match state.reader.status_counts().await {
+ Ok(counts) => {
+ let report = StatusReport {
+ version: env!("CARGO_PKG_VERSION").to_string(),
+ data_dir: state.data_dir.display().to_string(),
+ bind: state.bind.clone(),
+ db_path: state.db_path.display().to_string(),
+ counts,
+ };
+ (
+ StatusCode::OK,
+ Json(serde_json::to_value(&report).unwrap_or_else(|_| serde_json::json!({}))),
+ )
+ }
+ Err(e) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ ),
+ }
+}
+
+// ---------------------------------------------------------------------
+// search
+// ---------------------------------------------------------------------
+
+/// Query string for `GET /admin/search?q=…&limit=…`.
+#[derive(Debug, Deserialize)]
+struct SearchQuery {
+ /// FTS5 query expression.
+ q: String,
+ /// Max number of hits to return. Capped at 100 server-side.
+ #[serde(default = "default_search_limit")]
+ limit: usize,
+}
+
+fn default_search_limit() -> usize {
+ 10
+}
+
+async fn handle_search(
+ State(state): State<Arc<AdminState>>,
+ Query(query): Query<SearchQuery>,
+) -> impl IntoResponse {
+ let limit = query.limit.clamp(1, 100);
+ match state.reader.search_pages(query.q, limit).await {
+ Ok(hits) => (
+ StatusCode::OK,
+ Json(serde_json::to_value(&hits).unwrap_or_else(|_| serde_json::json!([]))),
+ ),
+ Err(e) => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ ),
+ }
+}
+
+// ---------------------------------------------------------------------
+// bootstrap
+// ---------------------------------------------------------------------
+
async fn handle_bootstrap(
State(state): State<Arc<AdminState>>,
Json(req): Json<BootstrapRequest>,
diff --git a/crates/ai-memory-mcp/tests/admin_bootstrap.rs b/crates/ai-memory-mcp/tests/admin_bootstrap.rs
index 00c38c82..a7515aae 100644
--- a/crates/ai-memory-mcp/tests/admin_bootstrap.rs
+++ b/crates/ai-memory-mcp/tests/admin_bootstrap.rs
@@ -19,11 +19,15 @@ use tower::ServiceExt;
async fn make_admin_state(tmp: &TempDir) -> AdminState {
let store = Store::open(tmp.path()).unwrap();
let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let db_path = store.db_path().to_path_buf();
AdminState {
writer: store.writer.clone(),
reader: store.reader.clone(),
wiki,
llm: None, // no LLM — dry-run path only
+ data_dir: tmp.path().to_path_buf(),
+ db_path,
+ bind: "127.0.0.1:0".to_string(),
}
}
diff --git a/crates/ai-memory-mcp/tests/admin_status_search.rs b/crates/ai-memory-mcp/tests/admin_status_search.rs
new file mode 100644
index 00000000..668d0410
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/admin_status_search.rs
@@ -0,0 +1,183 @@
+//! Integration tests for `GET /admin/status` and `GET /admin/search`.
+//!
+//! Exercises the read-only admin surface end-to-end through the axum
+//! router: build an `AdminState` over a real on-disk store + wiki,
+//! seed a couple of pages, and hit each route.
+
+use ai_memory_core::{NewPage, PagePath, Tier};
+use ai_memory_mcp::{AdminState, admin_router};
+use ai_memory_store::Store;
+use ai_memory_wiki::Wiki;
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+async fn make_admin_state(tmp: &TempDir) -> (AdminState, Store) {
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let db_path = store.db_path().to_path_buf();
+ let state = AdminState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ llm: None,
+ data_dir: tmp.path().to_path_buf(),
+ db_path,
+ bind: "127.0.0.1:49374".to_string(),
+ };
+ (state, store)
+}
+
+async fn seed_page(store: &Store, title: &str, path: &str, body: &str) {
+ let ws = store
+ .writer
+ .get_or_create_workspace("default".to_string())
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch".to_string(), None)
+ .await
+ .unwrap();
+ let page = NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new(path).unwrap(),
+ title: title.to_string(),
+ body: body.to_string(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ };
+ store.writer.upsert_page(page).await.unwrap();
+}
+
+async fn body_bytes(resp: axum::response::Response) -> Vec<u8> {
+ use axum::body::to_bytes;
+ to_bytes(resp.into_body(), 1_000_000)
+ .await
+ .unwrap()
+ .to_vec()
+}
+
+#[tokio::test]
+async fn status_returns_counts_and_paths() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_admin_state(&tmp).await;
+ seed_page(
+ &store,
+ "Karpathy LLM wiki",
+ "concepts/karpathy.md",
+ "Compile-not-retrieve pattern from Karpathy's notes.",
+ )
+ .await;
+ let app = admin_router(state);
+
+ let resp = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/admin/status")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let body: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap();
+ // Sanity-check the JSON shape.
+ assert!(body["version"].is_string());
+ assert_eq!(body["bind"], "127.0.0.1:49374");
+ assert!(
+ body["data_dir"]
+ .as_str()
+ .unwrap()
+ .contains(tmp.path().to_str().unwrap())
+ );
+ assert!(body["db_path"].as_str().unwrap().ends_with(".sqlite"));
+ assert_eq!(body["counts"]["pages_latest"].as_u64().unwrap(), 1);
+ assert_eq!(body["counts"]["pages_all"].as_u64().unwrap(), 1);
+}
+
+#[tokio::test]
+async fn search_returns_matching_hits() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_admin_state(&tmp).await;
+ seed_page(
+ &store,
+ "Storage architecture",
+ "concepts/storage.md",
+ "We use SQLite in WAL mode with a single-writer actor for safe concurrency.",
+ )
+ .await;
+ seed_page(
+ &store,
+ "Hook fire-and-forget",
+ "concepts/hooks.md",
+ "Lifecycle hooks POST with a 200ms hard timeout — fire and forget.",
+ )
+ .await;
+ let app = admin_router(state);
+
+ let resp = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/admin/search?q=sqlite&limit=10")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let hits: Vec<serde_json::Value> = serde_json::from_slice(&body_bytes(resp).await).unwrap();
+ assert_eq!(hits.len(), 1, "only the storage page mentions sqlite");
+ assert_eq!(hits[0]["path"].as_str().unwrap(), "concepts/storage.md");
+ assert_eq!(hits[0]["title"].as_str().unwrap(), "Storage architecture");
+}
+
+#[tokio::test]
+async fn search_with_empty_results_returns_empty_array() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_admin_state(&tmp).await;
+ let app = admin_router(state);
+
+ let resp = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/admin/search?q=nonexistentterm")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let hits: Vec<serde_json::Value> = serde_json::from_slice(&body_bytes(resp).await).unwrap();
+ assert!(hits.is_empty());
+}
+
+#[tokio::test]
+async fn search_limit_is_clamped_to_100() {
+ // Server-side clamp prevents callers from requesting a million
+ // hits; verify by passing a huge limit and ensuring we still get
+ // a 200 (no panic, no OOM).
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_admin_state(&tmp).await;
+ let app = admin_router(state);
+
+ let resp = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/admin/search?q=anything&limit=9999999")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+}