Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(serve): harden base-path web hosting
AkitaOnRailsac425c420287
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 78ee6301..6ff74eda 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- `ai-memory serve --transport http` can host the entire HTTP surface under a+ configurable subpath with `--base-path` / `AI_MEMORY_BASE_PATH`; `/mcp`,+ `/hook`, `/admin/*`, `/api/v1`, and the web UI all move under that prefix.+ The web UI mount can also be changed with `--web-slug`, and custom+ `--web-ui-dir` SPAs receive injected `<base href>` plus+ `ai-memory-base-path` metadata for same-origin API calls behind reverse+ proxies ([#65]).- `ai-memory move-project` can move projects across workspaces via the adminAPI. Fresh destinations use a lossless true move that keeps the same`project_id`, sessions, observations, handoffs, embeddings, and page history;@@ -24,6 +31,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0before removal ([#55]).### Fixed+- Custom `--web-ui-dir` frontends no longer serve raw `/index.html` without+ base-path injection; direct index requests and SPA fallback routes now return+ the injected shell, while static assets remain untouched ([#65]).- `move-project` true moves now run through a wiki mutation gate: normalpage writes/reindexes validate the `(workspace_id, project_id)` pair beforetouching disk, while true moves hold the exclusive side across the directorydiff --git a/README.md b/README.mdindex 23531e40..023e6896 100644--- a/README.md+++ b/README.md@@ -369,6 +369,13 @@ Useful entry points:screenshots and e2e tests — lives at[djalmajr/ai-memory-ui](https://github.com/djalmajr/ai-memory-ui).+ When a reverse proxy hosts ai-memory under a URL subpath, set+ `--base-path` (or `AI_MEMORY_BASE_PATH`) so every HTTP surface moves+ together. Example: `--base-path /wiki` serves MCP at `/wiki/mcp`, hooks at+ `/wiki/hook`, the API at `/wiki/api/v1`, and the default browser at+ `/wiki/web`. Set `--web-slug /` if you want the browser or custom SPA at+ `/wiki` itself.+Install the routing snippet once so agents proactively call the rightMCP tool for those prompts:diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 4fa27e17..f232e9ca 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -1,5 +1,6 @@//! `ai-memory serve` — MCP server with optional filesystem watcher.+use std::convert::Infallible;use std::path::Path;use std::sync::Arc;use std::time::Duration;@@ -24,6 +25,7 @@ use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,};use tokio_util::sync::CancellationToken;+use tower::service_fn;use tower_http::cors::CorsLayer;use tower_http::services::ServeDir;use tracing::info;@@ -297,7 +299,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {&args.web_slug,&base_href,&base_path,- );+ )?;let router = apply_http_layers(router, auth_state, config.allowed_hosts.clone());// Host the entire surface under the configured base path. Empty// base = root (unchanged). The auth/host layers are already@@ -885,9 +887,9 @@ fn mount_web_router(web_slug: &str,base_href: &str,base_path: &str,-) -> axum::Router {+) -> Result<axum::Router> {if !enable_web {- return router;+ return Ok(router);}// Register the web surfaces BEFORE applying the bearer middleware. In// axum 0.8, `.layer()` only attaches to routes registered before the@@ -928,24 +930,16 @@ fn mount_web_router(// URLs resolve under `{base_path}{web_slug}`.if let Some(dir) = web_ui_dir {let dir = dir.to_path_buf();- let raw = std::fs::read_to_string(dir.join("index.html")).unwrap_or_default();+ let raw = std::fs::read_to_string(dir.join("index.html"))+ .with_context(|| format!("reading custom web UI index at {}", dir.display()))?;let injected = inject_base_path_meta(&inject_base_href(&raw, base_href), base_path);info!(mount, base_href, base_path, "custom web UI mounted");- // Assets are served as files; any unmatched path (SPA client route)- // falls back to the injected index. `append_index_html_on_directories`- // is off so the directory index also flows through the injecting- // fallback rather than serving the raw on-disk index.html.- let spa = ServeDir::new(dir)- .append_index_html_on_directories(false)- .fallback(axum::routing::get(move || {- let body = injected.clone();- async move { axum::response::Html(body) }- }));- return if slug.is_empty() {- router.fallback_service(spa)+ let spa = custom_spa_router(dir, injected);+ return Ok(if slug.is_empty() {+ router.merge(spa)} else {- router.nest_service(&slug, spa)- };+ router.nest(&slug, spa)+ });}// The built-in server-rendered browser emits RELATIVE asset/link URLs@@ -958,7 +952,7 @@ fn mount_web_router();info!(mount, base_href, "read-only wiki browser mounted");if slug.is_empty() {- router.merge(web_router)+ Ok(router.merge(web_router))} else {// Strip-trailing-slash redirect. The target must carry the full// external prefix (`{base_path}{slug}`), because the surrounding@@ -972,7 +966,7 @@ fn mount_web_router(trimmed.to_string()}};- router+ Ok(router.route(&format!("{slug}/"),axum::routing::get(move || {@@ -980,10 +974,46 @@ fn mount_web_router(async move { axum::response::Redirect::permanent(&to) }}),)- .nest(&slug, web_router)+ .nest(&slug, web_router))}}+fn custom_spa_router(dir: std::path::PathBuf, injected_index: String) -> axum::Router {+ let index = Arc::new(injected_index);+ let root_index = index.clone();+ let direct_index = index.clone();+ let fallback_index = index.clone();++ // Assets are served as files; any missing asset path falls back to the+ // injected index for SPA client routes. Direct `/index.html` is routed+ // explicitly so it cannot bypass injection by being served from disk.+ let assets = ServeDir::new(dir)+ .append_index_html_on_directories(false)+ .fallback(service_fn(move |_req: Request<Body>| {+ let body = fallback_index.clone();+ async move {+ Ok::<_, Infallible>(axum::response::Html((*body).clone()).into_response())+ }+ }));++ axum::Router::new()+ .route(+ "/",+ axum::routing::get(move || {+ let body = root_index.clone();+ async move { axum::response::Html((*body).clone()) }+ }),+ )+ .route(+ "/index.html",+ axum::routing::get(move || {+ let body = direct_index.clone();+ async move { axum::response::Html((*body).clone()) }+ }),+ )+ .route_service("/{*path}", assets)+}+/// Response middleware: inject `<base href>` into `text/html` responses from/// the built-in server-rendered web browser, so its relative URLs resolve/// under the configured `{base_path}{web_slug}` prefix. Non-HTML responses@@ -1168,7 +1198,8 @@ mod tests {"/web","/web/","",- );+ )+ .unwrap();let router = apply_http_layers(router,Arc::new(AuthState::new(Some("secret".to_string()))),@@ -1210,7 +1241,8 @@ mod tests {web_slug,&base_href,&base,- );+ )+ .unwrap();let router = if base.is_empty() {router} else {@@ -1349,6 +1381,167 @@ mod tests {);}+ #[tokio::test]+ async fn custom_spa_index_routes_are_injected_under_base_path() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let ui = TempDir::new().unwrap();+ std::fs::write(+ ui.path().join("index.html"),+ "<!doctype html><html><head><title>spa</title></head><body>shell</body></html>",+ )+ .unwrap();+ std::fs::write(ui.path().join("app.js"), "console.log('asset');").unwrap();++ let base = normalize_prefix("/wiki");+ let base_href = web_base_href("/wiki", "/web");+ let router = mount_web_router(+ axum::Router::new(),+ true,+ store.reader.clone(),+ wiki,+ Some(ui.path()),+ &[],+ "/web",+ &base_href,+ &base,+ )+ .unwrap();+ let router = axum::Router::new().nest(&base, router);++ for uri in [+ "/wiki/web",+ "/wiki/web/index.html",+ "/wiki/web/client/route",+ ] {+ let resp = router+ .clone()+ .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK, "{uri}");+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ let html = std::str::from_utf8(&body).unwrap();+ assert!(+ html.contains(r#"<base href="/wiki/web/">"#),+ "{uri} must receive injected base href: {html}"+ );+ assert!(+ html.contains(r#"<meta name="ai-memory-base-path" content="/wiki">"#),+ "{uri} must receive injected API base-path meta: {html}"+ );+ assert!(html.contains("shell"), "{uri} returns the SPA shell");+ }++ let asset = router+ .oneshot(+ Request::builder()+ .uri("/wiki/web/app.js")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(asset.status(), StatusCode::OK);+ let body = axum::body::to_bytes(asset.into_body(), usize::MAX)+ .await+ .unwrap();+ let js = std::str::from_utf8(&body).unwrap();+ assert_eq!(js, "console.log('asset');");+ }++ #[tokio::test]+ async fn custom_spa_root_slug_does_not_shadow_api_routes() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let ui = TempDir::new().unwrap();+ std::fs::write(+ ui.path().join("index.html"),+ "<!doctype html><html><head><title>spa</title></head><body>root shell</body></html>",+ )+ .unwrap();+ std::fs::write(ui.path().join("app.js"), "console.log('root asset');").unwrap();++ let base = normalize_prefix("/wiki");+ let base_href = web_base_href("/wiki", "/");+ let router = mount_web_router(+ axum::Router::new(),+ true,+ store.reader.clone(),+ wiki,+ Some(ui.path()),+ &[],+ "/",+ &base_href,+ &base,+ )+ .unwrap();+ let router = axum::Router::new().nest(&base, router);++ for uri in ["/wiki", "/wiki/index.html", "/wiki/client/route"] {+ let resp = router+ .clone()+ .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK, "{uri}");+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ let html = std::str::from_utf8(&body).unwrap();+ assert!(+ html.contains(r#"<base href="/wiki/">"#),+ "{uri} must receive injected base href: {html}"+ );+ assert!(+ html.contains(r#"<meta name="ai-memory-base-path" content="/wiki">"#),+ "{uri} must receive injected API base-path meta: {html}"+ );+ assert!(html.contains("root shell"), "{uri} returns the SPA shell");+ }++ let api = router+ .clone()+ .oneshot(+ Request::builder()+ .uri("/wiki/api/v1/projects")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(api.status(), StatusCode::OK);+ let content_type = api+ .headers()+ .get(header::CONTENT_TYPE)+ .and_then(|h| h.to_str().ok())+ .unwrap_or_default();+ assert!(+ content_type.starts_with("application/json"),+ "API route must not be shadowed by the root SPA: {content_type}"+ );++ let asset = router+ .oneshot(+ Request::builder()+ .uri("/wiki/app.js")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(asset.status(), StatusCode::OK);+ let body = axum::body::to_bytes(asset.into_body(), usize::MAX)+ .await+ .unwrap();+ let js = std::str::from_utf8(&body).unwrap();+ assert_eq!(js, "console.log('root asset');");+ }+#[tokio::test]async fn embedder_mismatch_warns_but_keeps_server_startable() {let tmp = TempDir::new().unwrap();@@ -1492,7 +1685,8 @@ mod tests {"/web","/web/","",- );+ )+ .unwrap();// No auth layer so we can reach /api/v1 directly.let resp = router.oneshot(@@ -1544,7 +1738,8 @@ mod tests {"/web","/web/","",- );+ )+ .unwrap();let resp = router.oneshot(Request::builder()@@ -1585,7 +1780,8 @@ mod tests {"/web","/web/","",- );+ )+ .unwrap();// /web is a non-api route; sending an Origin header must not trigger CORS.let resp = router.oneshot(diff --git a/docs/frontend-api.md b/docs/frontend-api.mdindex c6697370..90637d63 100644--- a/docs/frontend-api.md+++ b/docs/frontend-api.md@@ -12,7 +12,7 @@| | What you can do | What you can't do ||---|---|---|| `/api/v1/*` | Browse workspaces, projects, pages; read full page markdown + frontmatter + back-links; FTS5 search (global or scoped, single or multi-project); aggregate "overview" snapshots; drill into stale / duplicate / orphan pages. | Write, delete, rename, lint, consolidate, run sweeps, manage handoffs. The `/api/v1` surface is **read-only by construction** — the handlers contain zero writer calls. Writes still go through `/admin/*` (used by the CLI) or MCP tools. |-| `--web-ui-dir` | Host any SPA at `/web`, 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 — there's no CORS layer yet (see §9). |+| `--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@@ -341,7 +341,7 @@ across all projects in the workspace:on every request. If your UI polls aggressively, consider client-sidedebouncing; server-side caching is a planned iteration.-## 6. Custom UI hosting (`--web-ui-dir`)+## 6. Custom UI hosting and base paths```bashai-memory serve \@@ -364,6 +364,26 @@ The static directory is served at `/web` via `tower-http::ServeDir`:- **Pre-startup validation:** the directory must exist *and* contain`index.html`, or `ai-memory serve` exits with a clear error beforebinding. Requires `--enable-web` to also be set.+- **Base-path injection:** ai-memory injects `<base href="...">` and+ `<meta name="ai-memory-base-path" content="...">` into the SPA shell. This+ covers direct `/web`, `/web/index.html`, and client-router fallback paths;+ static assets are served unchanged.++When a reverse proxy keeps ai-memory under a URL subpath, set+`--base-path` (or `AI_MEMORY_BASE_PATH`) so every HTTP surface moves together:++```bash+ai-memory serve \+ --transport http \+ --bind 127.0.0.1:49374 \+ --enable-web \+ --base-path /wiki+```++With `--base-path /wiki`, the API lives at `/wiki/api/v1`, MCP at+`/wiki/mcp`, hooks at `/wiki/hook`, admin routes at `/wiki/admin/*`, and the+default web UI at `/wiki/web`. Set `--web-slug /` to mount the web UI or custom+SPA at the base root (`/wiki`) instead of `/wiki/web`.When `--web-ui-dir` is **absent**, the built-in server-side `/web`browser is the default (read-only HTML rendering, FTS5 search,@@ -372,8 +392,12 @@ project tree). No regression.## 7. Worked example: minimal SPA fetch```js-// Resolve the API base from the SPA's own origin (same-origin model).-const API = `${location.origin}/api/v1`;+// Resolve the API base from the SPA shell injected by ai-memory. The meta tag+// is empty at host root and e.g. "/wiki" behind a subpath reverse proxy.+const basePath = document+ .querySelector('meta[name="ai-memory-base-path"]')+ ?.getAttribute("content") ?? "";+const API = `${location.origin}${basePath}/api/v1`;const TOKEN = localStorage.getItem("ai-memory-token"); // your storage choiceasync function apiGet(path, params) {diff --git a/docs/https-via-proxy.md b/docs/https-via-proxy.mdindex 0a7c5d38..e8e6fce4 100644--- a/docs/https-via-proxy.md+++ b/docs/https-via-proxy.md@@ -127,6 +127,38 @@ The `AI_MEMORY_ALLOWED_HOSTS` must include the public hostname orai-memory's DNS-rebinding guard will refuse Caddy's forwardedrequests.+### Hosting under a subpath++If ai-memory shares a hostname with other apps, keep the prefix when proxying+and tell ai-memory about it:++```bash+AI_MEMORY_BASE_PATH=/wiki+```++```caddyfile+memory.example.com {+ handle /wiki/* {+ reverse_proxy ai-memory:49374+ }+}+```++Do **not** use `handle_path /wiki/*` for this deployment: it strips `/wiki`+before forwarding, while ai-memory intentionally serves all routes under the+configured prefix. With the example above, clients use:++```bash+ai-memory install-mcp --client claude-code --apply \+ --server-url "https://memory.example.com/wiki/mcp" --auth-token "$AI_MEMORY_AUTH_TOKEN"+ai-memory install-hooks --agent claude-code --apply \+ --server-url "https://memory.example.com/wiki" --auth-token "$AI_MEMORY_AUTH_TOKEN"+```++The built-in browser is then at `https://memory.example.com/wiki/web`; add+`AI_MEMORY_WEB_SLUG=/` if you want the browser or custom `--web-ui-dir` SPA at+`https://memory.example.com/wiki` itself.+### MCP client config (Claude Code shown — others follow the same shape)```bash