Skip to content

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

Rust

cli: bootstrap becomes a thin HTTP client; server owns wiki + db

AkitaOnRails371805e88630
diff --git a/Cargo.lock b/Cargo.lock
index f78ea974..f09ad686 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -50,6 +50,7 @@ dependencies = [
"flate2",
"getrandom 0.3.4",
"jiff",
+ "reqwest",
"rmcp",
"secrecy",
"serde",
@@ -178,6 +179,7 @@ dependencies = [
"tempfile",
"thiserror 2.0.18",
"tokio",
+ "tower",
"tracing",
]
diff --git a/README.md b/README.md
index 5f261c02..7bdd4128 100644
--- a/README.md
+++ b/README.md
@@ -34,6 +34,11 @@ priors are at the [bottom](#influences-and-prior-art).
You need: Docker + an agent CLI (Claude Code, Codex, OpenCode, Cursor,
or anything else that speaks MCP).
+The default quick-start has **no authentication** — the server binds
+to loopback only, so on a single-user laptop nothing else can reach
+it. Adding a bearer token is a one-line change once you're ready to
+expose the server on the LAN; see [Security](#security) below.
+
```bash
# 1. Install the ai-memory CLI wrapper (a ~3 KB shell script that
# runs the binary inside docker with your $HOME mounted). This is
@@ -46,52 +51,50 @@ chmod +x ~/.local/bin/ai-memory
# ai-memory` comes up empty, add this to ~/.bashrc / ~/.zshrc:
# export PATH="$HOME/.local/bin:$PATH"
-# 2. Generate a bearer token (one-time; save it).
-export AI_MEMORY_AUTH_TOKEN=$(ai-memory generate-auth-token)
-
-# 3. Start the server. `--restart unless-stopped` makes it come back
+# 2. Start the server. `--restart unless-stopped` makes it come back
# on docker daemon restart and on machine boot (provided your
# docker service is enabled at boot — `sudo systemctl enable
-# docker` on most distros). Omit the LLM / EMBEDDING lines for
-# zero-LLM mode — FTS5 search still works without any keys.
+# docker` on most distros). Loopback-only bind (`127.0.0.1:49374`)
+# so nothing outside this machine can reach it. Omit the LLM /
+# EMBEDDING lines for zero-LLM mode — FTS5 search still works
+# without any keys.
docker run -d --name ai-memory \
--restart unless-stopped \
- -p 49374:49374 \
+ -p 127.0.0.1:49374:49374 \
-v ai-memory-data:/data \
- -e AI_MEMORY_AUTH_TOKEN="$AI_MEMORY_AUTH_TOKEN" \
-e AI_MEMORY_LLM_PROVIDER=anthropic \
-e ANTHROPIC_API_KEY=sk-ant-... \
-e AI_MEMORY_EMBEDDING_PROVIDER=openai \
-e OPENAI_API_KEY=sk-... \
akitaonrails/ai-memory:latest
-# 4. Wire your agent CLI in two commands. The wrapper takes care of
+# 3. Wire your agent CLI in two commands. The wrapper takes care of
# mounts + auto-detecting ~/.claude/settings.json. Re-run with
# `--agent codex`, `--agent opencode`, `--client cursor`, etc.
# for additional agents; full list in docs/install.md.
-ai-memory install-mcp --client claude-code --apply \
- --server-url "http://localhost:49374/mcp"
-ai-memory install-hooks --agent claude-code --apply \
- --server-url "http://localhost:49374"
+ai-memory install-mcp --client claude-code --apply
+ai-memory install-hooks --agent claude-code --apply
```
-Both `install-mcp` and `install-hooks` are idempotent — re-runs
-replace ai-memory's entry, preserve every other server / hook the
-user has configured, and write a timestamped `.bak-<ts>` next to the
-file before each modifying write. The hook scripts are staged into
-`~/.local/share/ai-memory/hooks/<agent>/` automatically; re-running
-overwrites them so future image updates ship updated hooks. Drop
-`--apply` to print the snippet instead of mutating.
-
That's it. Start a Claude Code session as usual — every prompt and
tool call now lands in ai-memory, and the next session you open in
this project will see a handoff with where you left off.
+The `install-mcp` / `install-hooks` commands default to
+`http://127.0.0.1:49374` (matching the server above) and no bearer
+token. Both are idempotent — re-runs replace ai-memory's entry,
+preserve every other server / hook you have configured, and write a
+timestamped `.bak-<ts>` next to the file before each modifying
+write. The hook scripts are staged into
+`~/.local/share/ai-memory/hooks/<agent>/` automatically; re-running
+overwrites them so future image updates ship updated hooks. Drop
+`--apply` to print the snippet instead of mutating.
+
> **Prefer docker compose?** Clone the repo and run
> `docker compose -f docker/docker-compose.yml up -d` instead of
-> step 3. The bundled compose file already has
+> step 2. The bundled compose file already has
> `restart: unless-stopped`, a healthcheck, and the named volume
-> wired up; step 4 is identical.
+> wired up; step 3 is identical.
### Keeping ai-memory up to date
@@ -131,6 +134,97 @@ needed), running ai-memory without docker, the full subcommand
reference, the homelab deploy pattern, security hardening — see
[**`docs/install.md`**](docs/install.md).
+## Configuring the CLI
+
+The `ai-memory` binary is a thin HTTP client. It never opens the
+wiki or SQLite directly — every state-touching command goes through
+the running server, which is the sole writer.
+
+Configuration is two environment variables, both **optional**:
+
+| Variable | Default | When to set it |
+|---|---|---|
+| `AI_MEMORY_SERVER_URL` | `http://127.0.0.1:49374` | When the server runs somewhere other than this machine (e.g. a homelab at `http://192.168.0.90:49374`). |
+| `AI_MEMORY_AUTH_TOKEN` | unset (no auth) | When the server has bearer auth enabled — see [Security](#security). |
+
+For the **single-laptop local case** you don't need either: the CLI
+talks to the loopback server with no credentials and just works.
+
+For a **remote / homelab** server, set both in your shell rc (or a
+`.envrc` if you use direnv):
+
+```bash
+export AI_MEMORY_SERVER_URL="http://192.168.0.90:49374"
+export AI_MEMORY_AUTH_TOKEN="b9a5075d…"
+```
+
+The `init`, `serve`, `install-*`, `generate-auth-token`, and
+`setup-agent` subcommands don't need these env vars — they either
+set up local files or start the server itself.
+
+## Security
+
+The default Quick start runs **without authentication** because the
+server is bound to loopback (`127.0.0.1:49374`) — no process outside
+this machine can reach it. That's the safest default for a personal
+laptop and matches the "single-user, single-machine" use case the
+project is optimised for.
+
+You need to enable bearer authentication if **any of these are
+true:**
+
+- The server is exposed beyond loopback (LAN, VPN, reverse proxy,
+ cloud).
+- More than one untrusted process runs on the same machine.
+- The data dir contains observations from sensitive projects you
+ wouldn't want any local user to read.
+
+To enable it:
+
+```bash
+# 1. Generate a token (one-time; save the output somewhere).
+TOKEN=$(ai-memory generate-auth-token)
+echo "$TOKEN" # 64 hex chars
+
+# 2. Pass it to the server on startup.
+docker run -d --name ai-memory \
+ --restart unless-stopped \
+ -p 0.0.0.0:49374:49374 \
+ -v ai-memory-data:/data \
+ -e AI_MEMORY_AUTH_TOKEN="$TOKEN" \
+ -e AI_MEMORY_LLM_PROVIDER=anthropic \
+ -e ANTHROPIC_API_KEY=sk-ant-... \
+ akitaonrails/ai-memory:latest
+
+# 3. Set the same token in every client environment that needs to
+# reach this server:
+export AI_MEMORY_AUTH_TOKEN="$TOKEN"
+
+# 4. Re-run install-mcp / install-hooks so the agent configs pick
+# up the new token + URL. The wrapper reads AI_MEMORY_AUTH_TOKEN
+# from your env and embeds it in the generated config.
+ai-memory install-mcp --client claude-code --apply \
+ --server-url "http://192.168.0.90:49374/mcp"
+ai-memory install-hooks --agent claude-code --apply \
+ --server-url "http://192.168.0.90:49374"
+```
+
+When the server has `AI_MEMORY_AUTH_TOKEN` set, every request to
+`/mcp`, `/hook`, `/handoff`, `/admin/*`, and `/web/*` must present
+the token. For HTTP clients (MCP, hooks, CLI) that means the
+`Authorization: Bearer <token>` header. For the `/web/*` browser
+flow it's HTTP Basic auth (the browser shows a native dialog;
+username is ignored, paste the token as the password). Constant-time
+token comparison via `subtle::ConstantTimeEq` rules out timing-based
+recovery.
+
+When the server has **no** `AI_MEMORY_AUTH_TOKEN` set AND binds to a
+non-loopback address, it logs a loud `warn` on startup. That's the
+signal to either lock the bind back to `127.0.0.1` or set a token.
+
+See [`docs/deploy.md`](docs/deploy.md) for the full homelab pattern
+(bearer + TLS via cloudflared + reverse proxy).
+
## How it works in practice
You mostly don't think about it. Hooks capture every prompt + tool
@@ -173,10 +267,12 @@ solves that by LLM-summarising your existing `git log`, README,
`docs/`, and module-level doc-comments into seed wiki pages.
```bash
-# Run from your project's repo root (requires an LLM provider on the
-# server). Default settings ingest everything; budget caps at 50k
-# input tokens (~$0.05 with Claude Haiku 4.5). The wrapper auto-mounts the
-# data volume and $PWD into the container.
+# Run from your project's repo root. The CLI collects sources locally
+# (git log, README, docs/, module headers) and POSTs them to the server
+# at AI_MEMORY_SERVER_URL, where the LLM call and wiki writes happen.
+# Requires an LLM provider configured on the server. Budget caps at
+# 50k input tokens (~$0.05 with Claude Haiku 4.5).
+export AI_MEMORY_SERVER_URL="http://localhost:49374"
ai-memory bootstrap --workspace homelab --project myproj
```
diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.toml
index b67c4cf8..5dbb323c 100644
--- a/crates/ai-memory-cli/Cargo.toml
+++ b/crates/ai-memory-cli/Cargo.toml
@@ -21,6 +21,7 @@ ai-memory-mcp.workspace = true
ai-memory-store.workspace = true
ai-memory-web.workspace = true
ai-memory-wiki.workspace = true
+reqwest.workspace = true
secrecy.workspace = true
subtle.workspace = true
getrandom.workspace = true
diff --git a/crates/ai-memory-cli/src/commands/bootstrap.rs b/crates/ai-memory-cli/src/commands/bootstrap.rs
index 7f4cdafe..eda269ba 100644
--- a/crates/ai-memory-cli/src/commands/bootstrap.rs
+++ b/crates/ai-memory-cli/src/commands/bootstrap.rs
@@ -1,21 +1,19 @@
//! `ai-memory bootstrap` — ingest an existing project's history.
//!
-//! Thin CLI wrapper around `ai_memory_consolidate::Bootstrap`. The
-//! heavy lifting (source collection, prioritisation, LLM call,
-//! wiki write) lives in the consolidate crate; this file just
-//! resolves CLI args into a `BootstrapConfig` and dispatches.
+//! Thin HTTP client wrapper. Source collection (git log, README, docs/,
+//! Rust module headers, project-rules files) happens locally via
+//! `ai_memory_consolidate::collect_sources`; the resulting bundle is
+//! POSTed to `POST /admin/bootstrap` on the running server, which does
+//! the LLM call and wiki writes. The CLI never opens a `Store` or `Wiki`
+//! directly.
//!
-//! Resolves the repo path via `git rev-parse --show-toplevel` when
-//! `--repo-path` is omitted, so running from any subdirectory of
-//! the target project works.
+//! Required environment variables (see "Configuring the CLI" in README):
+//! - `AI_MEMORY_SERVER_URL` — base URL of the running server.
+//! - `AI_MEMORY_AUTH_TOKEN` — bearer token if the server has auth enabled.
use std::path::PathBuf;
-use std::sync::Arc;
-use ai_memory_consolidate::{Bootstrap, BootstrapConfig, BootstrapOutcome};
-use ai_memory_llm::{build_provider, provider_from_env};
-use ai_memory_store::Store;
-use ai_memory_wiki::Wiki;
+use ai_memory_consolidate::{BootstrapOutcome, collect_sources};
use anyhow::{Context, Result, bail};
use tracing::info;
@@ -24,27 +22,30 @@ use crate::config::Config;
/// Run the `bootstrap` subcommand.
///
+/// Collects sources locally from the project repo, then POSTs the
+/// bundle to the server's `POST /admin/bootstrap` endpoint.
+///
/// # Errors
-/// Bails when an LLM provider isn't configured (bootstrap can't run
-/// without one), when the resolved repo path isn't a git repo, when
-/// the project was already bootstrapped without `--force`, or when
-/// any source-collection / LLM / wiki write fails.
-pub async fn run(config: &Config, args: BootstrapArgs) -> Result<()> {
- // ---- LLM provider — required ----
- let Some(llm_cfg) = provider_from_env()? else {
- bail!(
- "bootstrap requires an LLM provider. Set AI_MEMORY_LLM_PROVIDER \
- (and the matching API key) and try again."
- );
- };
- let llm = build_provider(llm_cfg).context("building LLM provider from env")?;
- info!(
- provider = llm.name(),
- model = llm.model(),
- "bootstrap LLM enabled"
- );
+/// Bails when `AI_MEMORY_SERVER_URL` is unset, when the resolved repo
+/// 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");
- // ---- repo path — auto-detect if absent ----
+ // ---- repo path — auto-detect if absent -------------------------
let repo_path = match args.repo_path {
Some(p) => p,
None => resolve_repo_root().context("auto-detecting --repo-path via git rev-parse")?,
@@ -57,41 +58,44 @@ pub async fn run(config: &Config, args: BootstrapArgs) -> Result<()> {
);
}
- // ---- open store + wiki ----
- 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())?;
+ // ---- collect sources locally ----------------------------------
+ let sources = collect_sources(
+ &repo_path,
+ args.since.as_deref(),
+ !args.exclude_git,
+ !args.exclude_readme,
+ !args.exclude_docs,
+ !args.exclude_code,
+ )?;
+ 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,
+ "sources": sources,
+ "max_input_tokens": args.max_input_tokens,
+ "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")?;
- // ---- run bootstrap ----
- let cfg = BootstrapConfig {
- repo_path: repo_path.clone(),
- workspace_id: ws,
- project_id: proj,
- max_input_tokens: args.max_input_tokens,
- include_git: !args.exclude_git,
- include_readme: !args.exclude_readme,
- include_docs: !args.exclude_docs,
- include_code: !args.exclude_code,
- since: args.since,
- dry_run: args.dry_run,
- force: args.force,
- };
- let bootstrap = Bootstrap {
- reader: store.reader.clone(),
- wiki,
- llm: Arc::clone(&llm),
- };
- let outcome = bootstrap.run(&cfg).await?;
print_human_report(&outcome, &args.workspace, &args.project);
- // Also emit the machine-readable JSON at the end for scripted callers.
let report = serde_json::to_string_pretty(&outcome)?;
println!("\n--- machine-readable ---\n{report}");
Ok(())
@@ -107,7 +111,7 @@ fn print_human_report(outcome: &BootstrapOutcome, workspace: &str, project: &str
} else {
"Bootstrap"
};
- println!("\n✓ {kind} complete for {workspace}/{project}\n");
+ println!("\n{kind} complete for {workspace}/{project}\n");
println!("Sources loaded into the LLM:");
let c = &outcome.sources_by_kind;
@@ -137,13 +141,13 @@ fn print_human_report(outcome: &BootstrapOutcome, workspace: &str, project: &str
}
if c.project_rules > 0 {
println!(
- " - {} project-rules file{} (CLAUDE.md / AGENTS.md / …)",
+ " - {} project-rules file{} (CLAUDE.md / AGENTS.md / ...)",
c.project_rules,
if c.project_rules == 1 { "" } else { "s" }
);
}
println!(
- " → ~{} input tokens estimated{}",
+ " -> ~{} input tokens estimated{}",
outcome.estimated_input_tokens,
if outcome.sources_dropped > 0 {
format!(
@@ -161,7 +165,7 @@ fn print_human_report(outcome: &BootstrapOutcome, workspace: &str, project: &str
);
if outcome.dry_run {
- println!("\n(dry-run — no LLM call, no pages written)");
+ println!("\n(dry-run -- no LLM call, no pages written)");
} else {
println!(
"\nGenerated {} wiki page{}:",
@@ -181,7 +185,7 @@ fn print_human_report(outcome: &BootstrapOutcome, workspace: &str, project: &str
}
println!(
- "\n⚠ What ai-memory knows now\n \
+ "\nWhat ai-memory knows now\n \
Only the sources listed above. NOT every file in your project,\n \
NOT every commit since project start, NOT runtime behaviour or\n \
test logs. As you use Claude Code (or another MCP agent) the\n \
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 5aa4dec6..1c3b690d 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -5,8 +5,8 @@ use std::sync::Arc;
use ai_memory_consolidate::Consolidator;
use ai_memory_core::Sanitizer;
use ai_memory_hooks::{HookState, hook_router};
-use ai_memory_llm::{build_embedder, embedder_from_env, provider_from_env};
-use ai_memory_mcp::AiMemoryServer;
+use ai_memory_llm::{build_embedder, build_provider, embedder_from_env, provider_from_env};
+use ai_memory_mcp::{AdminState, AiMemoryServer, admin_router};
use ai_memory_store::Store;
use ai_memory_web;
use ai_memory_wiki::{WatcherHandle, Wiki};
@@ -106,10 +106,12 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
server = server.with_embedder(e);
}
// Build the consolidator (if LLM configured) once, then share the
- // Arc between the MCP server (for `memory_consolidate` + lint) and
- // the hook router (for PreCompact checkpointing).
+ // Arc between the MCP server (for `memory_consolidate` + lint),
+ // the hook router (for PreCompact checkpointing), and the admin
+ // router (for `POST /admin/bootstrap`).
+ let mut admin_llm: Option<Arc<dyn ai_memory_llm::LlmProvider>> = None;
let consolidator: Option<Arc<Consolidator>> = if let Some(cfg) = provider_from_env()? {
- let llm = ai_memory_llm::build_provider(cfg).context("building LLM provider from env")?;
+ let llm = build_provider(cfg).context("building LLM provider from env")?;
info!(
provider = llm.name(),
model = llm.model(),
@@ -123,7 +125,8 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
ws,
proj,
));
- server = server.with_consolidator_arc(wiki.clone(), llm, c.clone());
+ server = server.with_consolidator_arc(wiki.clone(), llm.clone(), c.clone());
+ admin_llm = Some(llm);
Some(c)
} else {
info!(
@@ -172,6 +175,12 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
std::collections::HashMap::new(),
)),
});
+ let admin = admin_router(AdminState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki: wiki.clone(),
+ llm: admin_llm,
+ });
// Build the auth state. Precedence (highest first):
// 1. AI_MEMORY_AUTH_TOKEN env var
// 2. config.toml [auth].bearer_token
@@ -187,7 +196,8 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
let auth_enabled = auth_state.enabled();
let mut router = axum::Router::new()
.nest_service("/mcp", mcp_service)
- .merge(hooks);
+ .merge(hooks)
+ .merge(admin);
// Register the web router BEFORE applying the bearer
// middleware. In axum 0.8, `.layer()` only attaches to
diff --git a/crates/ai-memory-consolidate/src/bootstrap.rs b/crates/ai-memory-consolidate/src/bootstrap.rs
index 348f418a..aefdadc7 100644
--- a/crates/ai-memory-consolidate/src/bootstrap.rs
+++ b/crates/ai-memory-consolidate/src/bootstrap.rs
@@ -80,7 +80,8 @@ pub enum BootstrapError {
}
/// What kind of source we collected text from.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
pub enum SourceKind {
/// A line summary of one commit.
GitCommit,
@@ -117,7 +118,7 @@ impl SourceKind {
}
/// One unit of source text fed to the LLM.
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BootstrapSource {
/// Origin (used for prioritisation when over budget).
pub kind: SourceKind,
@@ -168,7 +169,7 @@ pub struct BootstrapBatch {
/// CLI surface "we loaded 23 commits + the README + 8 docs" rather
/// than a single opaque sources-count, so the user can calibrate
/// what ai-memory actually saw vs. didn't.
-#[derive(Debug, Clone, Default, Serialize)]
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SourceCounts {
/// Number of git-commit summaries kept.
pub git_commits: usize,
@@ -201,7 +202,7 @@ impl SourceCounts {
}
/// Outcome reported back to the CLI.
-#[derive(Debug, Clone, Serialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BootstrapOutcome {
/// Number of sources collected (before any budget pruning).
pub sources_collected: usize,
@@ -266,13 +267,18 @@ pub struct Bootstrap {
}
impl Bootstrap {
- /// Run the bootstrap pipeline end-to-end.
+ /// Process pre-collected sources end-to-end: prune to budget,
+ /// call the LLM, write pages, return the outcome. Server-side
+ /// entry point — does NOT collect from disk.
///
/// # Errors
- /// Propagates [`BootstrapError`] for any of: missing repo, LLM
- /// failure, wiki write failure, or already-bootstrapped (without
- /// `--force`).
- pub async fn run(&self, cfg: &BootstrapConfig) -> Result<BootstrapOutcome, BootstrapError> {
+ /// Propagates [`BootstrapError`] for any of: LLM failure, wiki
+ /// write failure, or already-bootstrapped (without `--force`).
+ pub async fn process_sources(
+ &self,
+ cfg: &BootstrapConfig,
+ sources: Vec<BootstrapSource>,
+ ) -> Result<BootstrapOutcome, BootstrapError> {
// ---- idempotency check ------------------------------------
// The reader pool's recent_pages isn't (workspace, project)-
// scoped, so we use the wiki's filesystem read as the cheap
@@ -286,22 +292,6 @@ impl Bootstrap {
}
}
- // ---- source collection ------------------------------------
- let mut sources = Vec::<BootstrapSource>::new();
- if cfg.include_git {
- sources.extend(collect_git_commits(&cfg.repo_path, cfg.since.as_deref())?);
- }
- if cfg.include_readme {
- sources.extend(collect_readme(&cfg.repo_path)?);
- }
- if cfg.include_docs {
- sources.extend(collect_docs(&cfg.repo_path)?);
- }
- if cfg.include_code {
- sources.extend(collect_rust_module_headers(&cfg.repo_path)?);
- }
- sources.extend(collect_project_rules(&cfg.repo_path)?);
-
if sources.is_empty() {
return Err(BootstrapError::NoSources);
}
@@ -407,12 +397,65 @@ impl Bootstrap {
dry_run: false,
})
}
+
+ /// Convenience wrapper that collects sources from disk then runs
+ /// [`Self::process_sources`]. Used by tests and any direct caller
+ /// that has filesystem access.
+ ///
+ /// # Errors
+ /// Propagates [`BootstrapError`] from either collection or processing.
+ pub async fn run(&self, cfg: &BootstrapConfig) -> Result<BootstrapOutcome, BootstrapError> {
+ let sources = collect_sources(
+ &cfg.repo_path,
+ cfg.since.as_deref(),
+ cfg.include_git,
+ cfg.include_readme,
+ cfg.include_docs,
+ cfg.include_code,
+ )?;
+ self.process_sources(cfg, sources).await
+ }
}
// --------------------------------------------------------------------
// Source collection
// --------------------------------------------------------------------
+/// Collect sources from a project repo on disk. IO-only — no LLM,
+/// no store, no wiki. The CLI calls this before posting the bundle
+/// to the server; the server's own bootstrap-route handler does NOT
+/// call this (the server can't see the caller's filesystem).
+///
+/// # Errors
+/// Returns [`BootstrapError`] when the repo path is invalid, files
+/// can't be read, or the git history can't be walked.
+pub fn collect_sources(
+ repo_path: &std::path::Path,
+ since: Option<&str>,
+ include_git: bool,
+ include_readme: bool,
+ include_docs: bool,
+ include_code: bool,
+) -> Result<Vec<BootstrapSource>, BootstrapError> {
+ let mut sources = Vec::<BootstrapSource>::new();
+ if include_git {
+ sources.extend(collect_git_commits(repo_path, since)?);
+ }
+ if include_readme {
+ sources.extend(collect_readme(repo_path)?);
+ }
+ if include_docs {
+ sources.extend(collect_docs(repo_path)?);
+ }
+ if include_code {
+ sources.extend(collect_rust_module_headers(repo_path)?);
+ }
+ // Project-rules files (CLAUDE.md / AGENTS.md) are always collected —
+ // they're the highest-signal input and very small.
+ sources.extend(collect_project_rules(repo_path)?);
+ Ok(sources)
+}
+
/// Read commits, format each as a one-paragraph entry. We include
/// only commits with a substantive body (more than ~120 chars
/// total) — drive-by typo-fix commits aren't worth tokens.
diff --git a/crates/ai-memory-consolidate/src/lib.rs b/crates/ai-memory-consolidate/src/lib.rs
index 82d050c0..cb79fef0 100644
--- a/crates/ai-memory-consolidate/src/lib.rs
+++ b/crates/ai-memory-consolidate/src/lib.rs
@@ -14,7 +14,10 @@ pub mod lint;
pub mod sweep;
pub mod types;
-pub use bootstrap::{Bootstrap, BootstrapConfig, BootstrapError, BootstrapOutcome};
+pub use bootstrap::{
+ Bootstrap, BootstrapConfig, BootstrapError, BootstrapOutcome, BootstrapSource, SourceCounts,
+ SourceKind, collect_sources,
+};
pub use consolidator::{
BATCH_SYSTEM_PROMPT, Consolidator, ConsolidatorError, ConsolidatorResult, build_batch_request,
};
diff --git a/crates/ai-memory-mcp/Cargo.toml b/crates/ai-memory-mcp/Cargo.toml
index f7b4e58e..579e10f7 100644
--- a/crates/ai-memory-mcp/Cargo.toml
+++ b/crates/ai-memory-mcp/Cargo.toml
@@ -30,6 +30,7 @@ jiff.workspace = true
[dev-dependencies]
tempfile.workspace = true
+tower.workspace = true
[lints]
workspace = true
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
new file mode 100644
index 00000000..5591be33
--- /dev/null
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -0,0 +1,209 @@
+//! Admin HTTP routes — state-touching operations invoked by the CLI
+//! over plain HTTP (not MCP). Currently exposes `POST /admin/bootstrap`.
+//!
+//! 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.
+
+use std::sync::Arc;
+
+use ai_memory_consolidate::{
+ Bootstrap, BootstrapConfig, BootstrapOutcome, BootstrapSource, SourceCounts,
+};
+use ai_memory_llm::LlmProvider;
+use ai_memory_store::{ReaderPool, WriterHandle};
+use ai_memory_wiki::Wiki;
+use axum::Json;
+use axum::Router;
+use axum::extract::State;
+use axum::http::StatusCode;
+use axum::response::IntoResponse;
+use axum::routing::post;
+use serde::Deserialize;
+
+/// Shared state for the admin router.
+#[derive(Clone)]
+pub struct AdminState {
+ /// Writer actor handle — used to get-or-create workspace/project.
+ pub writer: WriterHandle,
+ /// Reader pool — used by the idempotency check inside Bootstrap.
+ pub reader: ReaderPool,
+ /// Wiki handle — pages are written here.
+ pub wiki: Wiki,
+ /// Optional LLM provider. When `None`, bootstrap returns 503.
+ pub llm: Option<Arc<dyn LlmProvider>>,
+}
+
+/// JSON request body for `POST /admin/bootstrap`.
+#[derive(Deserialize)]
+struct BootstrapRequest {
+ /// Workspace name (auto-created if it doesn't exist).
+ workspace: String,
+ /// Project name (auto-created if it doesn't exist).
+ project: String,
+ /// Sources pre-collected on the client side.
+ sources: Vec<BootstrapSource>,
+ /// Maximum input tokens for LLM call.
+ #[serde(default = "default_max_input_tokens")]
+ max_input_tokens: usize,
+ /// Skip the LLM call and page writes — returns a dry-run outcome.
+ #[serde(default)]
+ dry_run: bool,
+ /// Allow re-bootstrap when `wiki/bootstrap.md` already exists.
+ #[serde(default)]
+ force: bool,
+}
+
+fn default_max_input_tokens() -> usize {
+ 50_000
+}
+
+/// Build the admin axum [`Router`]. Mounts `POST /admin/bootstrap`.
+pub fn admin_router(state: AdminState) -> Router {
+ Router::new()
+ .route("/admin/bootstrap", post(handle_bootstrap))
+ .with_state(Arc::new(state))
+}
+
+async fn handle_bootstrap(
+ State(state): State<Arc<AdminState>>,
+ Json(req): Json<BootstrapRequest>,
+) -> impl IntoResponse {
+ // LLM is required only for live runs. Dry-runs never call the LLM
+ // so we handle them directly here without constructing Bootstrap.
+ if !req.dry_run && state.llm.is_none() {
+ return (
+ StatusCode::SERVICE_UNAVAILABLE,
+ Json(serde_json::json!({
+ "error": "LLM provider not configured on server"
+ })),
+ );
+ }
+
+ // Resolve workspace + project — create if absent.
+ let ws = match state.writer.get_or_create_workspace(req.workspace).await {
+ Ok(id) => id,
+ Err(e) => {
+ return (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({ "error": format!("workspace: {e}") })),
+ );
+ }
+ };
+ let proj = match state
+ .writer
+ .get_or_create_project(ws, req.project, None)
+ .await
+ {
+ Ok(id) => id,
+ Err(e) => {
+ return (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({ "error": format!("project: {e}") })),
+ );
+ }
+ };
+
+ // Dry-run with no LLM: compute the budget-pruned source counts and
+ // return early without constructing Bootstrap (which requires an LLM).
+ if req.dry_run && state.llm.is_none() {
+ return dry_run_outcome(req.sources, req.max_input_tokens);
+ }
+
+ let llm = Arc::clone(
+ state
+ .llm
+ .as_ref()
+ .expect("llm is Some: checked above (non-dry-run without LLM returns 503)"),
+ );
+
+ let cfg = BootstrapConfig {
+ // repo_path is unused by process_sources — the path field is
+ // only consumed by collect_sources on the client side.
+ repo_path: std::path::PathBuf::new(),
+ workspace_id: ws,
+ project_id: proj,
+ max_input_tokens: req.max_input_tokens,
+ // The individual include_* flags don't matter here: sources
+ // are already collected; process_sources ignores them.
+ include_git: true,
+ include_readme: true,
+ include_docs: true,
+ include_code: true,
+ since: None,
+ dry_run: req.dry_run,
+ force: req.force,
+ };
+
+ let bootstrap = Bootstrap {
+ reader: state.reader.clone(),
+ wiki: state.wiki.clone(),
+ llm,
+ };
+
+ match bootstrap.process_sources(&cfg, req.sources).await {
+ Ok(outcome) => (
+ StatusCode::OK,
+ Json(serde_json::to_value(&outcome).unwrap_or_else(|_| serde_json::json!({}))),
+ ),
+ Err(e) => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ ),
+ }
+}
+
+/// Build a dry-run [`BootstrapOutcome`] without an LLM by applying the
+/// same budget-pruning logic that `Bootstrap::process_sources` would use.
+fn dry_run_outcome(
+ sources: Vec<BootstrapSource>,
+ max_input_tokens: usize,
+) -> (StatusCode, Json<serde_json::Value>) {
+ use ai_memory_consolidate::BootstrapError;
+ if sources.is_empty() {
+ return (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(serde_json::json!({
+ "error": BootstrapError::NoSources.to_string()
+ })),
+ );
+ }
+ // Mirror the prune logic: sort by drop_priority desc, drop until
+ // under budget. We replicate the constants here rather than
+ // exposing prune_to_budget publicly (it's an implementation detail
+ // of the consolidation pipeline).
+ const CHARS_PER_TOKEN: usize = 4;
+ let collected = sources.len();
+ let usable = max_input_tokens.saturating_sub(1_000);
+ let mut sorted = sources;
+ sorted.sort_by_key(|s| std::cmp::Reverse(s.kind.drop_priority()));
+ let mut total: usize = sorted
+ .iter()
+ .map(|s| (s.label.len() + s.text.len() + 16).div_ceil(CHARS_PER_TOKEN))
+ .sum();
+ while total > usable && !sorted.is_empty() {
+ let victim_tokens =
+ (sorted[0].label.len() + sorted[0].text.len() + 16).div_ceil(CHARS_PER_TOKEN);
+ total = total.saturating_sub(victim_tokens);
+ sorted.remove(0);
+ }
+ let kept = &sorted;
+ let dropped = collected - kept.len();
+ let counts = SourceCounts::from_sources(kept);
+ let outcome = BootstrapOutcome {
+ sources_collected: collected,
+ sources_sent: kept.len(),
+ sources_dropped: dropped,
+ sources_by_kind: counts,
+ estimated_input_tokens: total,
+ pages_written: Vec::new(),
+ rationale: "(dry-run; LLM not invoked)".to_string(),
+ dry_run: true,
+ };
+ (
+ StatusCode::OK,
+ Json(serde_json::to_value(&outcome).unwrap_or_else(|_| serde_json::json!({}))),
+ )
+}
diff --git a/crates/ai-memory-mcp/src/lib.rs b/crates/ai-memory-mcp/src/lib.rs
index 4741b1b6..5b9db9c2 100644
--- a/crates/ai-memory-mcp/src/lib.rs
+++ b/crates/ai-memory-mcp/src/lib.rs
@@ -8,6 +8,8 @@
//! agentmemory #510 / #553 "negotiated-down to a version the client
//! discards tools for" failure mode.
+pub mod admin;
mod server;
+pub use admin::{AdminState, admin_router};
pub use server::{AiMemoryServer, MEMORY_INSTRUCTIONS};
diff --git a/crates/ai-memory-mcp/tests/admin_bootstrap.rs b/crates/ai-memory-mcp/tests/admin_bootstrap.rs
new file mode 100644
index 00000000..00c38c82
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/admin_bootstrap.rs
@@ -0,0 +1,170 @@
+//! Integration tests for `POST /admin/bootstrap`.
+//!
+//! Exercises the dry-run path (no LLM required) end-to-end through the
+//! axum router: marshal a synthetic [`BootstrapSource`] bundle, POST it
+//! to the router, and assert the response shape matches [`BootstrapOutcome`].
+//! The LLM path is covered by the consolidate-crate unit tests.
+
+use ai_memory_consolidate::{BootstrapOutcome, BootstrapSource, SourceKind};
+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 serde_json::json;
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+/// Build a minimal `AdminState` backed by a real on-disk store + wiki.
+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();
+ AdminState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ llm: None, // no LLM — dry-run path only
+ }
+}
+
+/// Synthetic sources that represent a small project.
+fn synthetic_sources() -> Vec<BootstrapSource> {
+ vec![
+ BootstrapSource {
+ kind: SourceKind::Readme,
+ label: "README (README.md)".into(),
+ text: "# my-project\n\nA toy project used for testing bootstrap ingestion.".into(),
+ },
+ BootstrapSource {
+ kind: SourceKind::ProjectRules,
+ label: "rules: CLAUDE.md".into(),
+ text: "## Rules\n\n- Always write tests first.\n- Prefer composition.".into(),
+ },
+ BootstrapSource {
+ kind: SourceKind::GitCommit,
+ label: "git: feat: add initial storage layer".into(),
+ text: "Commit abc12345\nAuthor: Test\nDate: 2026-01-01\n\nfeat: add initial storage layer\n\nAdded SQLite-backed store with WAL mode.".into(),
+ },
+ ]
+}
+
+/// POST a JSON body to the admin router and return the response.
+async fn post_bootstrap(state: AdminState, body: serde_json::Value) -> axum::response::Response {
+ let router = admin_router(state);
+ let req = Request::builder()
+ .method("POST")
+ .uri("/admin/bootstrap")
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap();
+ router.oneshot(req).await.unwrap()
+}
+
+/// Dry-run with no LLM returns a valid [`BootstrapOutcome`] with
+/// `dry_run: true` and no pages written.
+#[tokio::test]
+async fn dry_run_returns_outcome_without_llm() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_admin_state(&tmp).await;
+
+ let body = json!({
+ "workspace": "test-ws",
+ "project": "test-proj",
+ "sources": synthetic_sources(),
+ "max_input_tokens": 50_000,
+ "dry_run": true,
+ "force": false,
+ });
+
+ let resp = post_bootstrap(state, body).await;
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let outcome: BootstrapOutcome = serde_json::from_slice(&bytes).unwrap();
+
+ assert!(outcome.dry_run, "must be a dry-run outcome");
+ assert_eq!(outcome.pages_written.len(), 0, "dry-run writes no pages");
+ assert_eq!(outcome.sources_collected, 3, "three sources were supplied");
+ assert!(outcome.sources_sent <= outcome.sources_collected);
+}
+
+/// When no LLM is configured and `dry_run=false`, the server returns
+/// 503 with a descriptive error body — not a panic.
+#[tokio::test]
+async fn non_dry_run_without_llm_returns_503() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_admin_state(&tmp).await;
+
+ let body = json!({
+ "workspace": "test-ws",
+ "project": "test-proj",
+ "sources": synthetic_sources(),
+ "max_input_tokens": 50_000,
+ "dry_run": false,
+ "force": false,
+ });
+
+ let resp = post_bootstrap(state, body).await;
+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
+
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let val: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ let error_msg = val["error"].as_str().unwrap_or("");
+ assert!(
+ error_msg.contains("LLM") || error_msg.contains("provider"),
+ "error message must mention LLM/provider: {error_msg}"
+ );
+}
+
+/// Empty source list returns an error — the server must not panic or
+/// produce a misleading success response.
+#[tokio::test]
+async fn empty_sources_returns_error() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_admin_state(&tmp).await;
+
+ let body = json!({
+ "workspace": "test-ws",
+ "project": "test-proj",
+ "sources": [],
+ "dry_run": true,
+ });
+
+ let resp = post_bootstrap(state, body).await;
+ // Empty sources with dry_run=true goes through process_sources which
+ // returns BootstrapError::NoSources -> UNPROCESSABLE_ENTITY.
+ assert_ne!(
+ resp.status(),
+ StatusCode::OK,
+ "empty sources must not succeed"
+ );
+}
+
+/// The workspace + project are auto-created by the handler; posting the
+/// same workspace/project a second time with `force=true` must not error
+/// (idempotent upsert).
+#[tokio::test]
+async fn workspace_and_project_auto_created_idempotent() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_admin_state(&tmp).await;
+
+ let body = json!({
+ "workspace": "idempotent-ws",
+ "project": "idempotent-proj",
+ "sources": synthetic_sources(),
+ "dry_run": true,
+ "force": true,
+ });
+
+ // First call.
+ let resp1 = post_bootstrap(state.clone(), body.clone()).await;
+ assert_eq!(resp1.status(), StatusCode::OK);
+
+ // Second call — workspace + project already exist; must still succeed.
+ let resp2 = post_bootstrap(state, body).await;
+ assert_eq!(resp2.status(), StatusCode::OK);
+}