Skip to content

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

Rust

phase 4: backup + write-page become HTTP clients; drop vestigial watch

AkitaOnRails46bc071f0f34
diff --git a/CLAUDE.md b/CLAUDE.md
index 6cd6fc7d..dde1b615 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -110,11 +110,17 @@ blocking issue:**
writer of wiki + SQLite. CLI commands NEVER call `Store::open`,
`Wiki::new`, `build_provider`, or `build_embedder`. State
mutations go through `/admin/*` HTTP routes; reads go through
- MCP tools or `/admin/*` GETs. The two exceptions are
- `init` / `serve` / `generate-auth-token` / `install-*` /
- `setup-agent` — local-only setup commands that don't touch
- server state. Use the shared `crate::http_client::{ServerEndpoint,
- get_json, post_json}` plumbing for every new client subcommand.
+ MCP tools or `/admin/*` GETs. Exceptions to "always an HTTP client":
+ - `init`, `generate-auth-token`, `install-*`, `setup-agent` —
+ pre-server local setup (no state mutation).
+ - `serve` — IS the server.
+ - `llm-test` — pre-server credential smoke test (hits the external
+ LLM only; no ai-memory state).
+ - `reset`, `restore` — lifecycle ops that fundamentally require the
+ server stopped (a live writer would race with the wipe/extract).
+ Both use `sysinfo` to refuse if any sibling `ai-memory` is alive.
+ Use the shared `crate::http_client::{ServerEndpoint, get_json,
+ post_json}` plumbing for every new client subcommand.
## Mistakes documented in the research — do NOT repeat
diff --git a/Cargo.lock b/Cargo.lock
index f09ad686..134dbc7b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -171,11 +171,13 @@ dependencies = [
"ai-memory-wiki",
"anyhow",
"axum",
+ "flate2",
"jiff",
"rmcp",
"schemars",
"serde",
"serde_json",
+ "tar",
"tempfile",
"thiserror 2.0.18",
"tokio",
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index f90cba99..32b3fe21 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -35,8 +35,6 @@ pub enum Command {
Search(SearchArgs),
/// Write or update a wiki page atomically (also indexes it in the store).
WritePage(WritePageArgs),
- /// Run the filesystem watcher (foreground; Ctrl-C to stop).
- Watch(WatchArgs),
/// Run the MCP server (with watcher) over stdio or HTTP.
Serve(ServeArgs),
/// Wipe the data directory's wiki/, db/, raw/ contents.
@@ -294,17 +292,6 @@ pub struct SearchArgs {
pub json: bool,
}
-/// Arguments for `watch`.
-#[derive(Debug, Args)]
-pub struct WatchArgs {
- /// Workspace name to attribute discovered files to (auto-created).
- #[arg(long, default_value = "default")]
- pub workspace: String,
- /// Project name within the workspace (auto-created).
- #[arg(long, default_value = "scratch")]
- pub project: String,
-}
-
/// Arguments for `reset`.
#[derive(Debug, Args)]
pub struct ResetArgs {
diff --git a/crates/ai-memory-cli/src/commands/backup.rs b/crates/ai-memory-cli/src/commands/backup.rs
index b85261dd..bf0e81da 100644
--- a/crates/ai-memory-cli/src/commands/backup.rs
+++ b/crates/ai-memory-cli/src/commands/backup.rs
@@ -1,83 +1,45 @@
-//! `ai-memory backup --to <tarball>` — make a consistent point-in-time
-//! snapshot of the data dir.
+//! `ai-memory backup --to <tarball>` — POST to the server's
+//! `/admin/backup` endpoint and save the returned gzip tarball.
//!
-//! Uses SQLite's online backup API so the source DB stays writable for
-//! the duration of the copy. The tarball is gzip-compressed and
-//! contains `wiki/`, a fresh `db/memory.sqlite` snapshot, and the
-//! `config.toml` (if present).
+//! The server uses SQLite's online backup API so the live DB is never
+//! raced. This client simply receives the bytes and writes them to
+//! the caller-supplied path.
-use std::path::Path;
-
-use ai_memory_store::Store;
-use anyhow::{Context, Result, bail};
-use flate2::Compression;
-use flate2::write::GzEncoder;
+use anyhow::{Context, Result};
use tracing::info;
use crate::cli::BackupArgs;
use crate::config::Config;
-use crate::process_guard::{busy_message, sibling_processes};
+use crate::http_client::{ServerEndpoint, post_bytes};
/// Run the `backup` subcommand.
///
/// # Errors
-/// Returns an error if another `ai-memory` process is running, the
-/// store cannot be opened, the SQLite snapshot fails, or the tarball
-/// cannot be written.
-pub async fn run(config: &Config, args: BackupArgs) -> Result<()> {
- let siblings = sibling_processes();
- if !siblings.is_empty() {
- bail!(busy_message("backup", &siblings));
- }
-
- let store = Store::open(&config.data_dir)
- .with_context(|| format!("opening store at {}", config.data_dir.display()))?;
-
- let staging = tempfile::tempdir()?;
- let snapshot_path = staging.path().join("memory.sqlite");
- info!(snapshot = %snapshot_path.display(), "snapshotting SQLite");
- store
- .reader
- .snapshot_to(snapshot_path.clone())
+/// Returns an error if the POST to `/admin/backup` fails, the server
+/// returns a non-2xx status, or the output file cannot be written.
+pub async fn run(_config: &Config, args: BackupArgs) -> Result<()> {
+ let endpoint = ServerEndpoint::from_env();
+ let bytes = post_bytes(&endpoint, "/admin/backup")
.await
- .context("running SQLite online backup")?;
+ .context("requesting backup from server")?;
let dest = &args.to;
if let Some(parent) = dest.parent()
&& !parent.as_os_str().is_empty()
{
- std::fs::create_dir_all(parent)?;
- }
- let file =
- std::fs::File::create(dest).with_context(|| format!("creating {}", dest.display()))?;
- let encoder = GzEncoder::new(file, Compression::default());
- let mut tar = tar::Builder::new(encoder);
- tar.mode(tar::HeaderMode::Deterministic);
-
- // wiki/ goes in as-is.
- let wiki_dir = config.data_dir.join("wiki");
- if wiki_dir.is_dir() {
- tar.append_dir_all("wiki", &wiki_dir)
- .with_context(|| format!("archiving {}", wiki_dir.display()))?;
+ std::fs::create_dir_all(parent)
+ .with_context(|| format!("creating parent dir for {}", dest.display()))?;
}
+ std::fs::write(dest, &bytes)
+ .with_context(|| format!("writing backup to {}", dest.display()))?;
- // db/memory.sqlite from the snapshot, not the live file.
- tar.append_path_with_name(&snapshot_path, "db/memory.sqlite")
- .context("archiving db snapshot")?;
-
- // config.toml, if present.
- let cfg = config.data_dir.join("config.toml");
- if cfg.is_file() {
- tar.append_path_with_name(&cfg, "config.toml")
- .context("archiving config.toml")?;
- }
-
- let encoder = tar.into_inner()?;
- encoder.finish()?;
-
- let size = std::fs::metadata(dest).map(|m| m.len()).unwrap_or(0);
+ let size = bytes.len() as u64;
info!(path = %dest.display(), bytes = size, "backup written");
- println!("backup -> {} ({})", dest.display(), human_bytes(size));
+ println!(
+ "✓ wrote backup to {} ({})",
+ dest.display(),
+ human_bytes(size)
+ );
Ok(())
}
@@ -95,8 +57,3 @@ fn human_bytes(n: u64) -> String {
format!("{value:.2} {}", UNITS[unit])
}
}
-
-#[allow(dead_code)] // Reserved for cross-platform diagnostics later.
-fn rel_path<'a>(base: &Path, full: &'a Path) -> Option<&'a Path> {
- full.strip_prefix(base).ok()
-}
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index b320b8cc..345ceb7a 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -25,7 +25,6 @@ pub mod search;
pub mod serve;
pub mod setup_agent;
pub mod status;
-pub mod watch;
pub mod write_page;
/// Resolve the effective project name for a client command.
diff --git a/crates/ai-memory-cli/src/commands/restore.rs b/crates/ai-memory-cli/src/commands/restore.rs
index 434802b5..8ba883fb 100644
--- a/crates/ai-memory-cli/src/commands/restore.rs
+++ b/crates/ai-memory-cli/src/commands/restore.rs
@@ -4,6 +4,15 @@
//! Refuses while another `ai-memory` process is alive. After extraction,
//! re-opens the store so any pending migrations run (and a corrupt
//! snapshot fails loudly).
+//!
+//! # Exception to invariant §16
+//!
+//! `restore` is one of the documented exceptions to the rule that the CLI
+//! is always a thin HTTP client. Restoration is a lifecycle operation that
+//! fundamentally requires the server to be stopped: extracting a tarball
+//! over a live SQLite WAL writer would corrupt the database. The sysinfo
+//! guard at the top of `run` enforces this precondition by refusing to
+//! proceed when any sibling `ai-memory` process is detected.
use ai_memory_store::Store;
use anyhow::{Context, Result, bail};
diff --git a/crates/ai-memory-cli/src/commands/watch.rs b/crates/ai-memory-cli/src/commands/watch.rs
deleted file mode 100644
index 40507fd3..00000000
--- a/crates/ai-memory-cli/src/commands/watch.rs
+++ /dev/null
@@ -1,43 +0,0 @@
-//! `ai-memory watch` — foreground watcher loop.
-//!
-//! In v1 this is a standalone command; in M2 the watcher folds into
-//! `ai-memory serve` alongside the MCP transport.
-
-use ai_memory_store::Store;
-use ai_memory_wiki::{WatcherHandle, Wiki};
-use anyhow::{Context, Result};
-
-use crate::cli::WatchArgs;
-use crate::config::Config;
-
-/// Run the `watch` subcommand.
-///
-/// # Errors
-/// Returns an error if the store cannot be opened or the watcher
-/// cannot install its filesystem hooks.
-pub async fn run(config: &Config, args: WatchArgs) -> Result<()> {
- let store = Store::open(&config.data_dir)
- .with_context(|| format!("opening store at {}", config.data_dir.display()))?;
- let ws = store
- .writer
- .get_or_create_workspace(args.workspace.clone())
- .await?;
- let proj = store
- .writer
- .get_or_create_project(ws, args.project.clone(), None)
- .await?;
-
- let wiki = Wiki::new(&config.data_dir, store.writer.clone())?;
- let handle = WatcherHandle::start(wiki.clone(), ws, proj)?;
- tracing::info!(
- root = %wiki.root().display(),
- workspace = %args.workspace,
- project = %args.project,
- "watching wiki (Ctrl-C to stop)"
- );
-
- tokio::signal::ctrl_c().await?;
- tracing::info!("shutting down watcher");
- handle.shutdown().await;
- Ok(())
-}
diff --git a/crates/ai-memory-cli/src/commands/write_page.rs b/crates/ai-memory-cli/src/commands/write_page.rs
index ee2c1ad0..e9ec3e68 100644
--- a/crates/ai-memory-cli/src/commands/write_page.rs
+++ b/crates/ai-memory-cli/src/commands/write_page.rs
@@ -1,85 +1,80 @@
-//! `ai-memory write-page` — testing helper for the M1-C wiki write path.
+//! `ai-memory write-page` — write or update a wiki page via the server.
//!
-//! Once hooks (M3) and consolidation (M7) are wired, real callers will
-//! flow through those, not this command. It stays around as a manual
-//! escape hatch and to exercise the chain in development.
+//! Sends a `POST /admin/write-page` request to the running server.
+//! The server handles workspace/project resolution, tier parsing,
+//! frontmatter framing, and the atomic wiki write.
use std::io::Read;
-use ai_memory_core::{PagePath, Tier};
-use ai_memory_store::Store;
-use ai_memory_wiki::{Wiki, WritePageRequest};
use anyhow::{Context, Result};
-use serde_json::{Map, Value};
+use serde::{Deserialize, Serialize};
use crate::cli::WritePageArgs;
use crate::config::Config;
+use crate::http_client::{ServerEndpoint, post_json};
+
+#[derive(Serialize)]
+struct WritePageBody {
+ workspace: String,
+ project: String,
+ path: String,
+ body: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ title: Option<String>,
+ tier: String,
+ tags: Vec<String>,
+ pinned: bool,
+}
+
+#[derive(Deserialize)]
+struct WritePageResponseBody {
+ page_id: String,
+ path: String,
+}
/// Run the `write-page` subcommand.
///
/// # Errors
-/// Returns an error if the store cannot be opened, the path is invalid,
-/// the tier is unknown, the body cannot be read, or the underlying
-/// `Wiki::write_page` call fails.
-pub async fn run(config: &Config, args: WritePageArgs) -> Result<()> {
- let body = if args.body == "-" {
+/// Returns an error if stdin cannot be read (when `body == "-"`), or if
+/// the POST to `/admin/write-page` fails.
+pub async fn run(_config: &Config, args: WritePageArgs) -> Result<()> {
+ let body_text = if args.body == "-" {
let mut buf = String::new();
- std::io::stdin().read_to_string(&mut buf)?;
+ std::io::stdin()
+ .read_to_string(&mut buf)
+ .context("reading body from stdin")?;
buf
} else {
args.body
};
- let tier: Tier = args.tier.parse()?;
- let path = PagePath::new(args.path.clone())?;
- let store = Store::open(&config.data_dir)
- .with_context(|| format!("opening store at {}", config.data_dir.display()))?;
- let ws = store
- .writer
- .get_or_create_workspace(args.workspace.clone())
- .await?;
- let proj = store
- .writer
- .get_or_create_project(ws, args.project.clone(), None)
- .await?;
-
- let wiki = Wiki::new(&config.data_dir, store.writer.clone())?;
-
- let mut fm = Map::new();
- if let Some(title) = args.title {
- fm.insert("title".into(), Value::String(title));
- }
- if !args.tag.is_empty() {
- fm.insert(
- "tags".into(),
- Value::Array(args.tag.into_iter().map(Value::String).collect()),
- );
- }
- if args.pinned {
- fm.insert("pinned".into(), Value::Bool(true));
- }
- let frontmatter = if fm.is_empty() {
- Value::Null
- } else {
- Value::Object(fm)
- };
+ // `project` has a non-empty default ("scratch"); pass it directly so the
+ // explicit --project flag always wins. The auto-detect path is only useful
+ // for commands whose project arg is truly optional (no default).
+ let project = args.project.clone();
- let id = wiki
- .write_page(WritePageRequest {
- workspace_id: ws,
- project_id: proj,
- path: path.clone(),
- frontmatter,
- body,
- tier,
+ let endpoint = ServerEndpoint::from_env();
+ let resp: WritePageResponseBody = post_json(
+ &endpoint,
+ "/admin/write-page",
+ &WritePageBody {
+ workspace: args.workspace.clone(),
+ project: project.clone(),
+ path: args.path.clone(),
+ body: body_text,
+ title: args.title,
+ tier: args.tier,
+ tags: args.tag,
pinned: args.pinned,
- title: None,
- })
- .await?;
+ },
+ )
+ .await
+ .context("writing page via server")?;
+ let short_id = &resp.page_id[..resp.page_id.len().min(8)];
println!(
- "wrote {} ({}) under workspace={} project={}",
- path, id, args.workspace, args.project
+ "✓ wrote {} (page_id={}) under {}/{}",
+ resp.path, short_id, args.workspace, project
);
Ok(())
}
diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rs
index 225d7cbb..442c5d9a 100644
--- a/crates/ai-memory-cli/src/http_client.rs
+++ b/crates/ai-memory-cli/src/http_client.rs
@@ -123,6 +123,34 @@ pub async fn post_json<B: Serialize, T: DeserializeOwned>(
.with_context(|| format!("parsing JSON body from POST {url}"))
}
+/// POST an empty body to `<endpoint>{path}`, return the raw response bytes.
+///
+/// Intended for routes whose response is binary (e.g. `POST /admin/backup`
+/// returns an `application/gzip` tarball). On non-2xx the response body is
+/// consumed and returned as an error string.
+///
+/// # Errors
+/// Returns an error when the connection fails, the response is non-2xx,
+/// or the body cannot be read.
+pub async fn post_bytes(endpoint: &ServerEndpoint, path: &str) -> Result<Vec<u8>> {
+ let client = reqwest::Client::new();
+ let url = format!("{}{path}", endpoint.url);
+ let req = endpoint.authenticate(client.post(&url));
+ 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.bytes()
+ .await
+ .map(|b| b.to_vec())
+ .with_context(|| format!("reading response bytes from POST {url}"))
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 542d1e3a..2b9dc655 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -43,7 +43,6 @@ async fn main() -> Result<()> {
Command::Status(args) => commands::status::run(&config, args).await,
Command::Search(args) => commands::search::run(&config, args).await,
Command::WritePage(args) => commands::write_page::run(&config, args).await,
- Command::Watch(args) => commands::watch::run(&config, args).await,
Command::Serve(args) => commands::serve::run(&config, args).await,
Command::Reset(args) => commands::reset::run(&config, args),
Command::Backup(args) => commands::backup::run(&config, args).await,
diff --git a/crates/ai-memory-mcp/Cargo.toml b/crates/ai-memory-mcp/Cargo.toml
index 579e10f7..38d6a38a 100644
--- a/crates/ai-memory-mcp/Cargo.toml
+++ b/crates/ai-memory-mcp/Cargo.toml
@@ -16,6 +16,9 @@ ai-memory-store.workspace = true
ai-memory-wiki.workspace = true
anyhow.workspace = true
thiserror.workspace = true
+flate2.workspace = true
+tar.workspace = true
+tempfile.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
@@ -29,7 +32,11 @@ axum.workspace = true
jiff.workspace = true
[dev-dependencies]
-tempfile.workspace = true
+ai-memory-core.workspace = true
+ai-memory-store.workspace = true
+ai-memory-wiki.workspace = true
+flate2.workspace = true
+tar.workspace = true
tower.workspace = true
[lints]
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 34986a14..47112a72 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -1,6 +1,7 @@
//! Admin HTTP routes — state-touching operations invoked by the CLI
//! over plain HTTP (not MCP). Currently exposes:
//!
+//! - `POST /admin/backup` — snapshot db + wiki into a gzip tarball (binary response).
//! - `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.
@@ -12,6 +13,7 @@
//! - `POST /admin/commit` — stage + commit the wiki tree via git.
//! - `POST /admin/purge-project` — delete a project and all its data.
//! - `POST /admin/rename-project` — rename a project (column-only; no files move).
+//! - `POST /admin/write-page` — write or update a wiki page atomically.
//!
//! The CLI is responsible for filesystem access (collecting sources from
//! the project repo, rendering output for humans); the server is
@@ -25,20 +27,23 @@ use ai_memory_consolidate::{
Bootstrap, BootstrapConfig, BootstrapOutcome, BootstrapSource, SourceCounts, run_lint,
run_sweep,
};
-use ai_memory_core::{ProjectId, SessionId, WorkspaceId};
+use ai_memory_core::{PagePath, ProjectId, SessionId, Tier, WorkspaceId};
use ai_memory_llm::{Embedder, LlmProvider};
use ai_memory_store::{
DecayParams, PurgeSummary, ReaderPool, StoreError, WriterHandle, f32_vec_to_bytes,
};
-use ai_memory_wiki::Wiki;
+use ai_memory_wiki::{Wiki, WritePageRequest};
use axum::Json;
use axum::Router;
+use axum::body::Body;
use axum::extract::{Query, State};
-use axum::http::StatusCode;
-use axum::response::IntoResponse;
+use axum::http::{StatusCode, header};
+use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
+use flate2::Compression;
+use flate2::write::GzEncoder;
use serde::{Deserialize, Serialize};
-use tracing::warn;
+use tracing::{info, warn};
/// Shared state for the admin router.
#[derive(Clone)]
@@ -90,6 +95,7 @@ fn default_max_input_tokens() -> usize {
}
/// Build the admin axum [`Router`]. Mounts:
+/// - `POST /admin/backup`
/// - `POST /admin/bootstrap`
/// - `GET /admin/status`
/// - `GET /admin/search`
@@ -100,8 +106,10 @@ fn default_max_input_tokens() -> usize {
/// - `POST /admin/commit`
/// - `POST /admin/purge-project`
/// - `POST /admin/rename-project`
+/// - `POST /admin/write-page`
pub fn admin_router(state: AdminState) -> Router {
Router::new()
+ .route("/admin/backup", post(handle_backup))
.route("/admin/bootstrap", post(handle_bootstrap))
.route("/admin/status", get(handle_status))
.route("/admin/search", get(handle_search))
@@ -112,9 +120,91 @@ pub fn admin_router(state: AdminState) -> Router {
.route("/admin/commit", post(handle_commit))
.route("/admin/purge-project", post(handle_purge_project))
.route("/admin/rename-project", post(handle_rename_project))
+ .route("/admin/write-page", post(handle_write_page))
.with_state(Arc::new(state))
}
+// ---------------------------------------------------------------------
+// backup
+// ---------------------------------------------------------------------
+
+/// Handler for `POST /admin/backup`.
+///
+/// Snapshots the live SQLite DB via the online backup API, then
+/// tar-gzips `wiki/`, the snapshot, and `config.toml` (if present)
+/// into an in-memory buffer. The response body IS the tarball bytes —
+/// `Content-Type: application/gzip`, no JSON wrapper.
+async fn handle_backup(State(state): State<Arc<AdminState>>) -> Response {
+ match build_backup_tarball(&state).await {
+ Ok(bytes) => Response::builder()
+ .status(StatusCode::OK)
+ .header(header::CONTENT_TYPE, "application/gzip")
+ .header(
+ header::CONTENT_DISPOSITION,
+ "attachment; filename=\"backup.tar.gz\"",
+ )
+ .body(Body::from(bytes))
+ .unwrap_or_else(|_| {
+ Response::builder()
+ .status(StatusCode::INTERNAL_SERVER_ERROR)
+ .body(Body::empty())
+ .unwrap()
+ }),
+ Err(e) => {
+ warn!(error = %e, "backup failed");
+ let body = serde_json::to_vec(&serde_json::json!({ "error": e.to_string() }))
+ .unwrap_or_default();
+ Response::builder()
+ .status(StatusCode::INTERNAL_SERVER_ERROR)
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(Body::from(body))
+ .unwrap_or_else(|_| {
+ Response::builder()
+ .status(StatusCode::INTERNAL_SERVER_ERROR)
+ .body(Body::empty())
+ .unwrap()
+ })
+ }
+ }
+}
+
+async fn build_backup_tarball(state: &AdminState) -> anyhow::Result<Vec<u8>> {
+ let staging = tempfile::tempdir()?;
+ let snapshot_path = staging.path().join("memory.sqlite");
+ info!(snapshot = %snapshot_path.display(), "snapshotting SQLite for backup");
+ state
+ .reader
+ .snapshot_to(snapshot_path.clone())
+ .await
+ .map_err(|e| anyhow::anyhow!("sqlite snapshot: {e}"))?;
+
+ let mut buf = Vec::new();
+ {
+ let encoder = GzEncoder::new(&mut buf, Compression::default());
+ let mut tar = tar::Builder::new(encoder);
+ tar.mode(tar::HeaderMode::Deterministic);
+
+ let wiki_dir = state.data_dir.join("wiki");
+ if wiki_dir.is_dir() {
+ tar.append_dir_all("wiki", &wiki_dir)
+ .map_err(|e| anyhow::anyhow!("archiving wiki/: {e}"))?;
+ }
+
+ tar.append_path_with_name(&snapshot_path, "db/memory.sqlite")
+ .map_err(|e| anyhow::anyhow!("archiving db snapshot: {e}"))?;
+
+ let cfg = state.data_dir.join("config.toml");
+ if cfg.is_file() {
+ tar.append_path_with_name(&cfg, "config.toml")
+ .map_err(|e| anyhow::anyhow!("archiving config.toml: {e}"))?;
+ }
+
+ let encoder = tar.into_inner()?;
+ encoder.finish()?;
+ }
+ Ok(buf)
+}
+
// ---------------------------------------------------------------------
// status
// ---------------------------------------------------------------------
@@ -1121,3 +1211,118 @@ async fn handle_rename_project(
Json(serde_json::to_value(&summary).unwrap_or_else(|_| serde_json::json!({}))),
)
}
+
+// ---------------------------------------------------------------------
+// write-page
+// ---------------------------------------------------------------------
+
+/// JSON request body for `POST /admin/write-page`.
+#[derive(Deserialize)]
+struct WritePageAdminRequest {
+ /// Workspace name (auto-created if absent).
+ workspace: String,
+ /// Project name (auto-created if absent).
+ project: String,
+ /// Relative wiki path (e.g. `concepts/foo.md`).
+ path: String,
+ /// Markdown body. The server frames it with frontmatter; pass plain body content.
+ body: String,
+ /// Optional title; derived from first H1 or path stem when absent.
+ #[serde(default)]
+ title: Option<String>,
+ /// Tier name (`working`, `episodic`, `semantic`, `procedural`).
+ #[serde(default = "default_write_tier")]
+ tier: String,
+ /// Tags to attach to the page.
+ #[serde(default)]
+ tags: Vec<String>,
+ /// Pin the page so the decay sweep skips it.
+ #[serde(default)]
+ pinned: bool,
+}
+
+fn default_write_tier() -> String {
+ "semantic".to_string()
+}
+
+/// JSON response body for `POST /admin/write-page`.
+#[derive(Serialize)]
+struct WritePageResponse {
+ /// UUID of the written page.
+ page_id: String,
+ /// Canonical wiki path.
+ path: String,
+}
+
+async fn handle_write_page(
+ State(state): State<Arc<AdminState>>,
+ Json(req): Json<WritePageAdminRequest>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ let tier: Tier = req.tier.parse().map_err(|_| {
+ (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(serde_json::json!({
+ "error": format!("unknown tier '{}'", req.tier)
+ })),
+ )
+ })?;
+
+ let path = PagePath::new(req.path.clone()).map_err(|e| {
+ (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(serde_json::json!({ "error": format!("invalid path: {e}") })),
+ )
+ })?;
+
+ let (ws, proj) = resolve_ws_proj(&state, &req.workspace, &req.project).await?;
+
+ let mut fm = serde_json::Map::new();
+ if let Some(title) = &req.title {
+ fm.insert("title".into(), serde_json::Value::String(title.clone()));
+ }
+ if !req.tags.is_empty() {
+ fm.insert(
+ "tags".into(),
+ serde_json::Value::Array(
+ req.tags
+ .into_iter()
+ .map(serde_json::Value::String)
+ .collect(),
+ ),
+ );
+ }
+ if req.pinned {
+ fm.insert("pinned".into(), serde_json::Value::Bool(true));
+ }
+ let frontmatter = if fm.is_empty() {
+ serde_json::Value::Null
+ } else {
+ serde_json::Value::Object(fm)
+ };
+
+ let page_id = state
+ .wiki
+ .write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: path.clone(),
+ frontmatter,
+ body: req.body,
+ tier,
+ pinned: req.pinned,
+ title: req.title,
+ })
+ .await
+ .map_err(|e| internal_err(e.to_string()))?;
+
+ Ok((
+ StatusCode::OK,
+ Json(
+ serde_json::to_value(WritePageResponse {
+ page_id: page_id.to_string(),
+ path: path.to_string(),
+ })
+ .unwrap_or_else(|_| serde_json::json!({})),
+ ),
+ ))
+}
diff --git a/crates/ai-memory-mcp/tests/admin_backup.rs b/crates/ai-memory-mcp/tests/admin_backup.rs
new file mode 100644
index 00000000..ac46186a
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/admin_backup.rs
@@ -0,0 +1,172 @@
+//! Integration tests for `POST /admin/backup`.
+//!
+//! Builds a real [`AdminState`] over a tmpdir-backed store + wiki,
+//! seeds a page, POSTs to `/admin/backup`, and asserts:
+//! - the response Content-Type is `application/gzip`,
+//! - the body is a valid gzip/tar stream,
+//! - the seeded wiki file appears in the tarball.
+
+use ai_memory_core::{NewPage, PagePath, Tier};
+use ai_memory_mcp::{AdminState, admin_router};
+use ai_memory_store::{DecayParams, Store};
+use ai_memory_wiki::Wiki;
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use flate2::read::GzDecoder;
+use tar::Archive;
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+async fn make_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,
+ embedder: None,
+ decay_params: DecayParams::default(),
+ data_dir: tmp.path().to_path_buf(),
+ db_path,
+ bind: "127.0.0.1:0".to_string(),
+ };
+ (state, store)
+}
+
+/// Seed a page directly into the store (index only — we also need the
+/// on-disk wiki file for the tarball). Use `AdminState.wiki.write_page`
+/// via the state, but here we seed through the store + write the file
+/// directly to exercise the backup path.
+async fn seed_page(store: &Store, tmp: &TempDir, 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();
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new(path).unwrap(),
+ title: "Test".to_string(),
+ body: body.to_string(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ })
+ .await
+ .unwrap();
+
+ // Also write the file on disk so the tarball picks it up.
+ let full = tmp.path().join("wiki").join(path);
+ if let Some(parent) = full.parent() {
+ std::fs::create_dir_all(parent).unwrap();
+ }
+ std::fs::write(&full, body).unwrap();
+}
+
+#[tokio::test]
+async fn backup_returns_application_gzip_content_type() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ seed_page(&store, &tmp, "concepts/karpathy.md", "compile not retrieve").await;
+
+ let router = admin_router(state);
+ let req = Request::builder()
+ .method("POST")
+ .uri("/admin/backup")
+ .body(Body::empty())
+ .unwrap();
+ let resp = router.oneshot(req).await.unwrap();
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ let ct = resp
+ .headers()
+ .get("content-type")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("");
+ assert!(
+ ct.contains("application/gzip"),
+ "expected application/gzip content-type, got: {ct}"
+ );
+}
+
+#[tokio::test]
+async fn backup_body_is_valid_gzip_and_contains_seeded_page() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ seed_page(
+ &store,
+ &tmp,
+ "concepts/karpathy.md",
+ "compile-not-retrieve from Karpathy LLM wiki",
+ )
+ .await;
+
+ let router = admin_router(state);
+ let req = Request::builder()
+ .method("POST")
+ .uri("/admin/backup")
+ .body(Body::empty())
+ .unwrap();
+ let resp = router.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ assert!(!bytes.is_empty(), "backup body must not be empty");
+
+ // Decompress and list entries.
+ let decoder = GzDecoder::new(bytes.as_ref());
+ let mut archive = Archive::new(decoder);
+ let entries: Vec<String> = archive
+ .entries()
+ .expect("tarball must be readable")
+ .map(|e| {
+ e.expect("entry must be readable")
+ .path()
+ .unwrap()
+ .to_string_lossy()
+ .into_owned()
+ })
+ .collect();
+
+ assert!(
+ entries.iter().any(|p| p.contains("concepts/karpathy.md")),
+ "tarball must contain the seeded page; entries: {entries:?}"
+ );
+ assert!(
+ entries.iter().any(|p| p.contains("memory.sqlite")),
+ "tarball must contain the db snapshot; entries: {entries:?}"
+ );
+}
+
+#[tokio::test]
+async fn backup_empty_store_still_succeeds() {
+ // Even with no wiki pages, the backup must not return an error.
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+
+ let router = admin_router(state);
+ let req = Request::builder()
+ .method("POST")
+ .uri("/admin/backup")
+ .body(Body::empty())
+ .unwrap();
+ let resp = router.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ assert!(!bytes.is_empty());
+}
diff --git a/crates/ai-memory-mcp/tests/admin_write_page.rs b/crates/ai-memory-mcp/tests/admin_write_page.rs
new file mode 100644
index 00000000..b529fbff
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/admin_write_page.rs
@@ -0,0 +1,187 @@
+//! Integration tests for `POST /admin/write-page`.
+//!
+//! Exercises the route through the axum router: post a synthetic page,
+//! verify it appears in `/admin/search` results. Also tests that an
+//! unknown tier returns 422.
+
+use ai_memory_mcp::{AdminState, admin_router};
+use ai_memory_store::{DecayParams, Store};
+use ai_memory_wiki::Wiki;
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use serde_json::json;
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+async fn make_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,
+ embedder: None,
+ decay_params: DecayParams::default(),
+ data_dir: tmp.path().to_path_buf(),
+ db_path,
+ bind: "127.0.0.1:0".to_string(),
+ }
+}
+
+async fn post_json(
+ state: AdminState,
+ uri: &str,
+ body: serde_json::Value,
+) -> axum::response::Response {
+ let router = admin_router(state);
+ let req = Request::builder()
+ .method("POST")
+ .uri(uri)
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap();
+ router.oneshot(req).await.unwrap()
+}
+
+async fn body_json(resp: axum::response::Response) -> serde_json::Value {
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)
+}
+
+#[tokio::test]
+async fn write_page_returns_page_id_and_path() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ let resp = post_json(
+ state,
+ "/admin/write-page",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "path": "notes/test-write.md",
+ "body": "This is a test page written via the admin route.",
+ "tier": "semantic",
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK, "write-page must succeed");
+
+ let body = body_json(resp).await;
+ assert!(
+ body["page_id"].is_string(),
+ "response must have page_id: {body}"
+ );
+ assert_eq!(
+ body["path"].as_str().unwrap(),
+ "notes/test-write.md",
+ "response path must match request: {body}"
+ );
+}
+
+#[tokio::test]
+async fn write_page_appears_in_search() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ // Write a page with a distinctive term.
+ let write_resp = post_json(
+ state.clone(),
+ "/admin/write-page",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "path": "notes/unique-term.md",
+ "body": "The xyloquartz pattern enables distributed widget fusion.",
+ "tier": "semantic",
+ }),
+ )
+ .await;
+ assert_eq!(write_resp.status(), StatusCode::OK);
+
+ // Now search for the distinctive term.
+ let router = admin_router(state);
+ let search_req = Request::builder()
+ .method("GET")
+ .uri("/admin/search?q=xyloquartz&limit=10")
+ .body(Body::empty())
+ .unwrap();
+ let search_resp = router.oneshot(search_req).await.unwrap();
+ assert_eq!(search_resp.status(), StatusCode::OK);
+
+ let hits: Vec<serde_json::Value> = serde_json::from_slice(
+ &axum::body::to_bytes(search_resp.into_body(), usize::MAX)
+ .await
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(
+ hits.len(),
+ 1,
+ "written page must appear in search results: {hits:?}"
+ );
+ assert_eq!(hits[0]["path"].as_str().unwrap(), "notes/unique-term.md");
+}
+
+#[tokio::test]
+async fn write_page_invalid_tier_returns_422() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ let resp = post_json(
+ state,
+ "/admin/write-page",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "path": "notes/bad-tier.md",
+ "body": "Some content.",
+ "tier": "legendary",
+ }),
+ )
+ .await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "unknown tier must return 422"
+ );
+
+ let body = body_json(resp).await;
+ assert!(
+ body["error"].as_str().unwrap_or("").contains("legendary"),
+ "error must mention the unknown tier name: {body}"
+ );
+}
+
+#[tokio::test]
+async fn write_page_with_tags_and_pinned() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ let resp = post_json(
+ state,
+ "/admin/write-page",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "path": "notes/tagged.md",
+ "body": "Tagged and pinned content.",
+ "tier": "procedural",
+ "tags": ["rust", "memory"],
+ "pinned": true,
+ }),
+ )
+ .await;
+ assert_eq!(
+ resp.status(),
+ StatusCode::OK,
+ "tagged+pinned page must succeed"
+ );
+
+ let body = body_json(resp).await;
+ assert!(body["page_id"].is_string(), "must have page_id: {body}");
+}