Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(setup): setup --web shows the plan as a local page and applies it
AkitaOnRailsbc845513549b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 62e2b27b..b86c7e99 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -51,6 +51,14 @@ version in [`docs/changelog/`](docs/changelog/):failure, giving up after five failures within ten seconds of starting.`ai-memory uninstall --apply` stops the host and removes the value when itstill has the shape `setup` writes. (#1271)+- Added `ai-memory setup --web`, which shows the setup plan as a page in+ your browser and applies the agents you tick there by running `ai-memory+ setup --yes --agent ...` and streaming its output to the page. The page is+ served on `127.0.0.1` behind a one-time address printed in the terminal+ (opened in the browser unless `--no-open` or there is no desktop), refuses+ requests with another `Host`, without the address's secret, or, for a+ change, without the page's own `Origin` and CSRF token, and holds no token.+ It stops on Finish, after 15 minutes without a request, or on Ctrl-C. (#1272)### Changed- `ai-memory setup` now ends by naming the agents to restart and the questiondiff --git a/Cargo.lock b/Cargo.lockindex 6abc8532..b71a4a02 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -58,6 +58,7 @@ dependencies = ["jiff","jsonc-parser","libc",+ "parking_lot","reqwest 0.12.28","rmcp","rstest",@@ -68,6 +69,7 @@ dependencies = ["serde_json","sha2","socket2",+ "subtle","sysinfo","tar","tempfile",diff --git a/README.md b/README.mdindex 7fdfdfae..e86c4df1 100644--- a/README.md+++ b/README.md@@ -213,7 +213,8 @@ directory with a bearer token in an owner-only file, starts a per-user serviceSkills for every agent it finds, or the ones you name with `--agent`. It showsthe plan, with where it found each agent, and asks first: answer `y`, or typethe numbers of the agents to wire. `--plan` prints the plan and changes-nothing, `--yes` skips the question, and running it again changes nothing.+nothing, `--web` shows the plan as a page in your browser and applies the agents+you tick there, `--yes` skips the question, and running it again changes nothing.Afterwards, restart your agents and ask one of them "What do you rememberabout this project?" to see it answer through ai-memory. Details, the environmentvariables and how to verify the script before running it are indiff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.tomlindex 0261aa99..7fca90da 100644--- a/crates/ai-memory-cli/Cargo.toml+++ b/crates/ai-memory-cli/Cargo.toml@@ -75,6 +75,8 @@ rmcp = { workspace = true, features = [rustls = { workspace = true }serde.workspace = trueserde_json.workspace = true+subtle.workspace = true+parking_lot.workspace = truetoml_edit.workspace = truesysinfo.workspace = truetar.workspace = truediff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 0489a60c..18133b3f 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1989,6 +1989,14 @@ pub struct SetupArgs {/// names the layout version) for a script or front end to render.#[arg(long, requires = "plan")]pub json: bool,+ /// Show the plan as a page in your browser, served on 127.0.0.1 behind a+ /// one-time address printed here, and apply the agents you pick there.+ /// Nothing changes until you press Apply.+ #[arg(long, conflicts_with_all = ["yes", "plan"])]+ pub web: bool,+ /// With `--web`, print the page's address without opening a browser.+ #[arg(long, requires = "web")]+ pub no_open: bool,}/// Arguments for `status`.diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 58543830..7f40c3dd 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -107,6 +107,7 @@ pub mod server;pub mod service_host;pub mod setup;pub mod setup_agent;+pub(crate) mod setup_web;pub mod show;pub mod status;pub mod transcript_capture;diff --git a/crates/ai-memory-cli/src/commands/service_host.rs b/crates/ai-memory-cli/src/commands/service_host.rsindex 1ef573c4..c63a093f 100644--- a/crates/ai-memory-cli/src/commands/service_host.rs+++ b/crates/ai-memory-cli/src/commands/service_host.rs@@ -180,7 +180,7 @@ fn supervise(}/// The global arguments that point a child at this install.-fn install_args(config: &Config, config_path: Option<&Path>) -> Vec<std::ffi::OsString> {+pub(crate) fn install_args(config: &Config, config_path: Option<&Path>) -> Vec<std::ffi::OsString> {let mut args = vec!["--data-dir".into(),config.data_dir.clone().into_os_string(),diff --git a/crates/ai-memory-cli/src/commands/setup.rs b/crates/ai-memory-cli/src/commands/setup.rsindex ae44d1c2..a5bd511a 100644--- a/crates/ai-memory-cli/src/commands/setup.rs+++ b/crates/ai-memory-cli/src/commands/setup.rs@@ -27,7 +27,8 @@//! operator can also pick which of the planned agents to wire; with no//! terminal to ask on, `setup` changes nothing and exits non-zero. `--plan`//! prints the plan (as JSON with `--json`, for a front end to render) and-//! changes nothing.+//! changes nothing. `--web` shows the same plan as a local page and applies+//! the agents picked there through `setup --yes` ([`super::setup_web`]).use std::collections::BTreeSet;use std::ffi::OsString;@@ -270,6 +271,26 @@ pub async fn run(config: &Config, args: SetupArgs, config_path: Option<&Path>) -println!("{}", serde_json::to_string_pretty(&plan_document(&plan))?);return Ok(());}+ if args.web {+ use clap::ValueEnum as _;+ let accepted = AgentChoice::value_variants()+ .iter()+ .map(|agent| agent_name(*agent))+ .collect();+ let flags = if args.no_service {+ vec!["--no-service".into()]+ } else {+ Vec::new()+ };+ return super::setup_web::serve(+ serde_json::to_value(plan_document(&plan))?,+ accepted,+ flags,+ super::service_host::install_args(config, config_path),+ !args.no_open,+ )+ .await;+ }print_plan(&plan);if args.plan {return Ok(());@@ -687,6 +708,12 @@ fn next_step(agents: &[AgentPlan]) -> String {.iter().map(|agent| agent.agent.kind().as_str()).collect();+ next_step_for_names(&names)+}++/// [`next_step`] for agents given by name.+pub(crate) fn next_step_for_names(names: &[impl AsRef<str>]) -> String {+ let names: Vec<&str> = names.iter().map(AsRef::as_ref).collect();match names.as_slice() {[] => "ai-memory is set up, but no agent is wired; run `ai-memory setup --agent <name>`.".to_owned(),diff --git a/crates/ai-memory-cli/src/commands/setup_web.rs b/crates/ai-memory-cli/src/commands/setup_web.rsnew file mode 100644index 00000000..0c7f2e6b--- /dev/null+++ b/crates/ai-memory-cli/src/commands/setup_web.rs@@ -0,0 +1,746 @@+//! `ai-memory setup --web`: the setup plan as a page in your browser.+//!+//! A one-shot server inside this process, separate from the long-running+//! server and its `/web` UI (which is read-only by design). It serves one page+//! that shows the plan `setup --plan --json` prints, lets the operator tick the+//! agents to wire, and applies the choice by running `ai-memory setup --yes+//! --agent ...` as a child process whose output streams back to the page. Every+//! change therefore goes through the same code path as the terminal command.+//!+//! The page holds no credential and can only start that one command, but a+//! browser is a confused deputy, so the server takes the precautions a local+//! admin page needs:+//!+//! - it binds `127.0.0.1` on a port the OS picks, and answers only a `Host`+//! of `127.0.0.1:<port>` or `localhost:<port>` (DNS rebinding);+//! - every route sits under a one-time 256-bit secret in the path, printed to+//! the terminal that started it and compared in constant time;+//! - a change is a POST that must carry this page's `Origin` and a CSRF token+//! the page reads from its own JSON, which a cross-origin page cannot read;+//! - agent names are checked against the values `--agent` accepts before they+//! reach the child's argument list;+//! - responses forbid caching, framing and referrers, and the page runs under+//! a Content-Security-Policy with a per-run nonce and no outside sources;+//! - it stops on Finish, after [`IDLE_TIMEOUT`] without a request, or on+//! Ctrl-C.++use std::ffi::OsString;+use std::path::PathBuf;+use std::sync::Arc;+use std::time::{Duration, Instant};++use anyhow::{Context as _, Result};+use axum::Router;+use axum::body::Body;+use axum::extract::{Query, Request, State};+use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};+use axum::middleware::Next;+use axum::response::{IntoResponse, Response};+use axum::routing::{get, post};+use parking_lot::Mutex;+use subtle::ConstantTimeEq as _;+use tokio::io::AsyncBufReadExt as _;+use tokio::sync::Notify;++/// The page; `__NONCE__` is replaced per run.+const PAGE: &str = include_str!("../../templates/setup_web.html");++/// Stop when no request arrived for this long.+const IDLE_TIMEOUT: Duration = Duration::from_secs(15 * 60);+/// Keep at most this many output lines from the child.+const MAX_LINES: usize = 5_000;+/// The header carrying the CSRF token on a POST.+const CSRF_HEADER: &str = "x-ai-memory-setup";++/// Starts the `ai-memory setup` child with these arguments and returns it+/// with its stdout and stderr piped. Injectable so tests never run a setup.+pub(crate) type Launch =+ Arc<dyn Fn(&[OsString]) -> std::io::Result<tokio::process::Child> + Send + Sync>;++/// What the child run has produced so far.+#[derive(Debug, Default)]+struct RunState {+ started: bool,+ lines: Vec<String>,+ done: bool,+ ok: bool,+ agents: Vec<String>,+}++pub(crate) struct Wizard {+ port: u16,+ secret: String,+ csrf: String,+ nonce: String,+ plan: serde_json::Value,+ /// Every `--agent` value, the only names `apply` accepts.+ accepted: Vec<String>,+ /// `setup` arguments every run carries (`--no-service`).+ setup_flags: Vec<OsString>,+ launch: Launch,+ run: Mutex<RunState>,+ last_seen: Mutex<Instant>,+ shutdown: Notify,+}++impl Wizard {+ /// A wizard for `plan` on `port`, with fresh secrets.+ ///+ /// # Errors+ /// When the OS random source fails.+ pub(crate) fn new(+ port: u16,+ plan: serde_json::Value,+ accepted: Vec<String>,+ setup_flags: Vec<OsString>,+ launch: Launch,+ ) -> Result<Self> {+ let random = |bytes| {+ ai_memory_mcp::auth::generate_token_hex(bytes)+ .map_err(|error| anyhow::anyhow!("generating a random secret: {error}"))+ };+ Ok(Self {+ port,+ secret: random(32)?,+ csrf: random(32)?,+ nonce: random(16)?,+ plan,+ accepted,+ setup_flags,+ launch,+ run: Mutex::new(RunState::default()),+ last_seen: Mutex::new(Instant::now()),+ shutdown: Notify::new(),+ })+ }++ /// The page's address.+ pub(crate) fn url(&self) -> String {+ format!("http://127.0.0.1:{}/s/{}/", self.port, self.secret)+ }++ fn host_allowed(&self, headers: &HeaderMap) -> bool {+ let Some(host) = headers.get(header::HOST).and_then(|v| v.to_str().ok()) else {+ return false;+ };+ host == format!("127.0.0.1:{}", self.port) || host == format!("localhost:{}", self.port)+ }++ fn origin_allowed(&self, headers: &HeaderMap) -> bool {+ let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) else {+ return false;+ };+ origin == format!("http://127.0.0.1:{}", self.port)+ || origin == format!("http://localhost:{}", self.port)+ }++ fn csrf_allowed(&self, headers: &HeaderMap) -> bool {+ headers+ .get(CSRF_HEADER)+ .is_some_and(|value| bool::from(value.as_bytes().ct_eq(self.csrf.as_bytes())))+ }+}++/// Run the wizard until it is finished, idle, or interrupted, and report+/// whether a setup ran and passed.+///+/// # Errors+/// When the listener cannot bind or the server fails.+pub(crate) async fn serve(+ plan: serde_json::Value,+ accepted: Vec<String>,+ setup_flags: Vec<OsString>,+ install_args: Vec<OsString>,+ open_browser: bool,+) -> Result<()> {+ let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))+ .await+ .context("binding the setup page to 127.0.0.1")?;+ let port = listener.local_addr()?.port();+ let exe = std::env::current_exe().context("locating the running ai-memory binary")?;+ let wizard = Arc::new(Wizard::new(+ port,+ plan,+ accepted,+ setup_flags,+ child_launcher(exe, install_args),+ )?);+ let url = wizard.url();+ println!("Open the setup page to choose your agents and apply:\n\n {url}\n");+ println!(+ "It answers only on this machine. Over SSH, forward the port first \+ (`ssh -L {port}:127.0.0.1:{port} <host>`) and open the same address. \+ Press Ctrl-C here to stop without changing anything."+ );+ if open_browser {+ open_in_browser(&url);+ }++ let idle = Arc::clone(&wizard);+ tokio::spawn(async move {+ loop {+ tokio::time::sleep(Duration::from_secs(5)).await;+ let running = {+ let run = idle.run.lock();+ run.started && !run.done+ };+ if !running && idle.last_seen.lock().elapsed() > IDLE_TIMEOUT {+ println!("The setup page was idle for 15 minutes; stopping it.");+ idle.shutdown.notify_one();+ return;+ }+ }+ });++ let stop = Arc::clone(&wizard);+ axum::serve(listener, router(Arc::clone(&wizard)))+ .with_graceful_shutdown(async move {+ tokio::select! {+ () = stop.shutdown.notified() => {}+ _ = tokio::signal::ctrl_c() => {}+ }+ })+ .await+ .context("serving the setup page")?;++ let run = wizard.run.lock();+ match (run.started, run.done, run.ok) {+ (false, _, _) => println!("The setup page closed; nothing was changed."),+ (true, true, true) => println!("{}", super::setup::next_step_for_names(&run.agents)),+ (true, true, false) => anyhow::bail!(+ "setup finished with problems; see the output on the page, or run `ai-memory setup` \+ here"+ ),+ (true, false, _) => anyhow::bail!("the setup page stopped while setup was still running"),+ }+ Ok(())+}++/// The real launcher: this binary, pointed at the same install, running+/// `setup` with the page's arguments.+fn child_launcher(exe: PathBuf, install_args: Vec<OsString>) -> Launch {+ Arc::new(move |setup_args: &[OsString]| {+ tokio::process::Command::new(&exe)+ .args(&install_args)+ .arg("setup")+ .args(setup_args)+ .env("NO_COLOR", "1")+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ .kill_on_drop(true)+ .spawn()+ })+}++/// Ask the desktop to open `url`; on a machine with no desktop, or when the+/// opener fails, the printed address is enough.+fn open_in_browser(url: &str) {+ let opener: Option<(&str, Vec<&str>)> = if cfg!(target_os = "macos") {+ Some(("open", vec![url]))+ } else if cfg!(windows) {+ Some(("rundll32", vec!["url.dll,FileProtocolHandler", url]))+ } else if std::env::var_os("DISPLAY").is_some() || std::env::var_os("WAYLAND_DISPLAY").is_some()+ {+ Some(("xdg-open", vec![url]))+ } else {+ None+ };+ if let Some((program, args)) = opener {+ let _ = std::process::Command::new(program)+ .args(args)+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .spawn();+ }+}++pub(crate) fn router(wizard: Arc<Wizard>) -> Router {+ Router::new()+ .route("/s/{secret}/", get(page))+ .route("/s/{secret}/plan", get(plan))+ .route("/s/{secret}/progress", get(progress))+ .route("/s/{secret}/apply", post(apply))+ .route("/s/{secret}/finish", post(finish))+ .fallback(|| async { StatusCode::NOT_FOUND })+ .layer(axum::middleware::from_fn_with_state(+ Arc::clone(&wizard),+ guard,+ ))+ .with_state(wizard)+}++/// Every request: a loopback `Host` naming our port, the secret path, and+/// for a POST this page's `Origin` and CSRF token. Then the response headers+/// every answer carries.+async fn guard(State(wizard): State<Arc<Wizard>>, request: Request, next: Next) -> Response {+ if !wizard.host_allowed(request.headers()) {+ return (StatusCode::FORBIDDEN, "unexpected Host header").into_response();+ }+ let secret_ok = request+ .uri()+ .path()+ .strip_prefix("/s/")+ .and_then(|rest| rest.split_once('/'))+ .is_some_and(|(secret, _)| bool::from(secret.as_bytes().ct_eq(wizard.secret.as_bytes())));+ if !secret_ok {+ return StatusCode::NOT_FOUND.into_response();+ }+ if request.method() == Method::POST+ && !(wizard.origin_allowed(request.headers()) && wizard.csrf_allowed(request.headers()))+ {+ return (StatusCode::FORBIDDEN, "refused: not sent by the setup page").into_response();+ }+ *wizard.last_seen.lock() = Instant::now();+ let mut response = next.run(request).await;+ let headers = response.headers_mut();+ for (name, value) in [+ (header::CACHE_CONTROL, "no-store"),+ (header::REFERRER_POLICY, "no-referrer"),+ (header::X_FRAME_OPTIONS, "DENY"),+ (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),+ ] {+ headers.insert(name, HeaderValue::from_static(value));+ }+ response+}++async fn page(State(wizard): State<Arc<Wizard>>) -> Response {+ let nonce = &wizard.nonce;+ let csp = format!(+ "default-src 'none'; script-src 'nonce-{nonce}'; style-src 'nonce-{nonce}'; \+ connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"+ );+ let mut response = Response::new(Body::from(PAGE.replace("__NONCE__", nonce)));+ let headers = response.headers_mut();+ headers.insert(+ header::CONTENT_TYPE,+ HeaderValue::from_static("text/html; charset=utf-8"),+ );+ if let Ok(value) = HeaderValue::from_str(&csp) {+ headers.insert(header::CONTENT_SECURITY_POLICY, value);+ }+ response+}++async fn plan(State(wizard): State<Arc<Wizard>>) -> Response {+ axum::Json(serde_json::json!({+ "plan": wizard.plan,+ "csrf": wizard.csrf,+ }))+ .into_response()+}++#[derive(serde::Deserialize)]+struct ProgressQuery {+ #[serde(default)]+ from: usize,+}++async fn progress(+ State(wizard): State<Arc<Wizard>>,+ Query(query): Query<ProgressQuery>,+) -> Response {+ let run = wizard.run.lock();+ let from = query.from.min(run.lines.len());+ axum::Json(serde_json::json!({+ "lines": &run.lines[from..],+ "next": run.lines.len(),+ "done": run.done,+ "ok": run.ok,+ "agents": run.agents,+ }))+ .into_response()+}++#[derive(serde::Deserialize)]+struct ApplyBody {+ agents: Vec<String>,+}++async fn apply(+ State(wizard): State<Arc<Wizard>>,+ axum::Json(body): axum::Json<ApplyBody>,+) -> Response {+ let mut agents: Vec<String> = Vec::new();+ for agent in body.agents {+ if !wizard.accepted.contains(&agent) {+ return (StatusCode::BAD_REQUEST, format!("unknown agent {agent:?}")).into_response();+ }+ if !agents.contains(&agent) {+ agents.push(agent);+ }+ }+ if agents.is_empty() {+ return (StatusCode::BAD_REQUEST, "pick at least one agent").into_response();+ }+ {+ let mut run = wizard.run.lock();+ if run.started && !run.done {+ return (StatusCode::CONFLICT, "setup is already running").into_response();+ }+ *run = RunState {+ started: true,+ agents: agents.clone(),+ ..RunState::default()+ };+ }+ let mut args: Vec<OsString> = vec!["--yes".into()];+ for agent in &agents {+ args.push("--agent".into());+ args.push(agent.into());+ }+ args.extend(wizard.setup_flags.iter().cloned());+ let mut child = match (wizard.launch)(&args) {+ Ok(child) => child,+ Err(error) => {+ let mut run = wizard.run.lock();+ run.lines+ .push(format!("could not start ai-memory setup: {error}"));+ run.done = true;+ return (+ StatusCode::INTERNAL_SERVER_ERROR,+ "could not start ai-memory setup",+ )+ .into_response();+ }+ };+ let collector = Arc::clone(&wizard);+ tokio::spawn(async move {+ let stdout = child.stdout.take();+ let stderr = child.stderr.take();+ let out = collect_lines(Arc::clone(&collector), stdout);+ let err = collect_lines(Arc::clone(&collector), stderr);+ tokio::join!(out, err);+ let ok = child.wait().await.is_ok_and(|status| status.success());+ let mut run = collector.run.lock();+ run.ok = ok;+ run.done = true;+ });+ StatusCode::ACCEPTED.into_response()+}++async fn collect_lines(wizard: Arc<Wizard>, stream: Option<impl tokio::io::AsyncRead + Unpin>) {+ let Some(stream) = stream else {+ return;+ };+ let mut lines = tokio::io::BufReader::new(stream).lines();+ while let Ok(Some(line)) = lines.next_line().await {+ let mut run = wizard.run.lock();+ if run.lines.len() < MAX_LINES {+ run.lines.push(strip_ansi(&line));+ }+ }+}++/// Drop terminal escape sequences (`ESC [ ... letter`), so a coloured log+/// line reads as text on the page.+fn strip_ansi(line: &str) -> String {+ let mut out = String::with_capacity(line.len());+ let mut chars = line.chars().peekable();+ while let Some(ch) = chars.next() {+ if ch == '\u{1b}' {+ if chars.peek() == Some(&'[') {+ chars.next();+ for next in chars.by_ref() {+ if next.is_ascii_alphabetic() {+ break;+ }+ }+ }+ continue;+ }+ out.push(ch);+ }+ out+}++async fn finish(State(wizard): State<Arc<Wizard>>) -> Response {+ {+ let run = wizard.run.lock();+ if run.started && !run.done {+ return (StatusCode::CONFLICT, "setup is still running").into_response();+ }+ }+ wizard.shutdown.notify_one();+ StatusCode::NO_CONTENT.into_response()+}++#[cfg(test)]+mod tests {+ use super::*;+ use tower::ServiceExt as _;++ const PORT: u16 = 41_234;++ /// A launcher that records its arguments and runs a stand-in child which+ /// prints two lines and exits with `code`.+ fn recording(code: i32) -> (Launch, Arc<Mutex<Vec<Vec<String>>>>) {+ let calls = Arc::new(Mutex::new(Vec::new()));+ let seen = Arc::clone(&calls);+ let launch: Launch = Arc::new(move |args: &[OsString]| {+ seen.lock().push(+ args.iter()+ .map(|arg| arg.to_string_lossy().into_owned())+ .collect(),+ );+ let script =+ format!("echo == claude-code; echo '\u{1b}[1mdone\u{1b}[0m' 1>&2; exit {code}");+ let mut command = if cfg!(windows) {+ let mut command = tokio::process::Command::new("cmd");+ command.args([+ "/C",+ &format!("echo == claude-code & echo done 1>&2 & exit /b {code}"),+ ]);+ command+ } else {+ let mut command = tokio::process::Command::new("sh");+ command.args(["-c", &script]);+ command+ };+ command+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ .spawn()+ });+ (launch, calls)+ }++ fn wizard(launch: Launch) -> Arc<Wizard> {+ Arc::new(+ Wizard::new(+ PORT,+ serde_json::json!({"agents": [{"agent": "claude-code"}]}),+ vec!["claude-code".into(), "codex".into()],+ vec!["--no-service".into()],+ launch,+ )+ .unwrap(),+ )+ }++ fn path(wizard: &Wizard, rest: &str) -> String {+ format!("/s/{}/{rest}", wizard.secret)+ }++ fn get(uri: &str, host: &str) -> Request {+ Request::builder()+ .uri(uri)+ .header(header::HOST, host)+ .body(Body::empty())+ .unwrap()+ }++ fn post(wizard: &Wizard, rest: &str) -> axum::http::request::Builder {+ Request::builder()+ .method(Method::POST)+ .uri(path(wizard, rest))+ .header(header::HOST, format!("127.0.0.1:{PORT}"))+ .header(header::CONTENT_TYPE, "application/json")+ }++ async fn send(wizard: &Arc<Wizard>, request: Request) -> (StatusCode, HeaderMap, String) {+ let response = router(Arc::clone(wizard)).oneshot(request).await.unwrap();+ let status = response.status();+ let headers = response.headers().clone();+ let body = axum::body::to_bytes(response.into_body(), 1 << 20)+ .await+ .unwrap();+ (status, headers, String::from_utf8_lossy(&body).into_owned())+ }++ fn legit(wizard: &Wizard, rest: &str, body: &str) -> Request {+ post(wizard, rest)+ .header(header::ORIGIN, format!("http://127.0.0.1:{PORT}"))+ .header(CSRF_HEADER, &wizard.csrf)+ .body(Body::from(body.to_owned()))+ .unwrap()+ }++ /// The page needs the loopback Host for our port and the secret path; it+ /// carries a CSP with this run's nonce, and the nonce reaches its tags.+ #[tokio::test]+ async fn the_page_is_served_only_to_our_host_and_secret() {+ let wizard = wizard(recording(0).0);+ let host = format!("127.0.0.1:{PORT}");+ let (status, headers, body) = send(&wizard, get(&path(&wizard, ""), &host)).await;+ assert_eq!(status, StatusCode::OK);+ let csp = headers[header::CONTENT_SECURITY_POLICY].to_str().unwrap();+ assert!(csp.contains(&format!("'nonce-{}'", wizard.nonce)), "{csp}");+ assert!(csp.starts_with("default-src 'none'"), "{csp}");+ assert_eq!(headers[header::CACHE_CONTROL], "no-store");+ assert_eq!(headers[header::REFERRER_POLICY], "no-referrer");+ assert_eq!(headers[header::X_FRAME_OPTIONS], "DENY");+ assert!(body.contains(&format!("nonce=\"{}\"", wizard.nonce)));+ assert!(!body.contains("__NONCE__"));++ let (status, _, _) = send(+ &wizard,+ get(&path(&wizard, ""), &format!("localhost:{PORT}")),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "localhost names the same server");++ // DNS rebinding: an attacker's name resolving to 127.0.0.1.+ for host in [+ format!("evil.example:{PORT}"),+ "127.0.0.1".to_owned(),+ format!("127.0.0.1:{}", PORT + 1),+ ] {+ let (status, _, _) = send(&wizard, get(&path(&wizard, ""), &host)).await;+ assert_eq!(status, StatusCode::FORBIDDEN, "{host}");+ }+ let wrong = format!("/s/{}/", "0".repeat(64));+ for uri in [wrong.as_str(), "/", "/s/", "/plan"] {+ let (status, _, _) = send(&wizard, get(uri, &host)).await;+ assert_eq!(status, StatusCode::NOT_FOUND, "{uri}");+ }+ }++ /// The plan JSON hands the page its CSRF token; it is readable only by a+ /// same-origin page, since nothing here allows a cross-origin read.+ #[tokio::test]+ async fn the_plan_carries_the_csrf_token_and_no_cors_grant() {+ let wizard = wizard(recording(0).0);+ let (status, headers, body) = send(+ &wizard,+ get(&path(&wizard, "plan"), &format!("127.0.0.1:{PORT}")),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));+ let json: serde_json::Value = serde_json::from_str(&body).unwrap();+ assert_eq!(json["csrf"], wizard.csrf);+ assert_eq!(json["plan"]["agents"][0]["agent"], "claude-code");+ }++ /// A change needs this page's Origin and the CSRF token; each missing or+ /// foreign piece is refused and starts nothing. Agent names outside the+ /// accepted list (including option-like strings) and an empty choice are+ /// refused before any child starts.+ #[tokio::test]+ async fn apply_refuses_cross_site_and_unknown_input_and_starts_nothing() {+ let (launch, calls) = recording(0);+ let wizard = wizard(launch);+ let body = r#"{"agents":["claude-code"]}"#;+ let cases = [+ post(&wizard, "apply")+ .header(CSRF_HEADER, &wizard.csrf)+ .body(Body::from(body))+ .unwrap(),+ post(&wizard, "apply")+ .header(header::ORIGIN, "http://evil.example")+ .header(CSRF_HEADER, &wizard.csrf)+ .body(Body::from(body))+ .unwrap(),+ post(&wizard, "apply")+ .header(header::ORIGIN, format!("http://127.0.0.1:{PORT}"))+ .body(Body::from(body))+ .unwrap(),+ post(&wizard, "apply")+ .header(header::ORIGIN, format!("http://127.0.0.1:{PORT}"))+ .header(CSRF_HEADER, "0".repeat(64))+ .body(Body::from(body))+ .unwrap(),+ ];+ for request in cases {+ let (status, _, _) = send(&wizard, request).await;+ assert_eq!(status, StatusCode::FORBIDDEN);+ }+ for bad in [+ r#"{"agents":["--force"]}"#,+ r#"{"agents":["claude-code","rm -rf"]}"#,+ r#"{"agents":[]}"#,+ ] {+ let (status, _, _) = send(&wizard, legit(&wizard, "apply", bad)).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}");+ }+ assert!(+ calls.lock().is_empty(),+ "nothing may start: {:?}",+ calls.lock()+ );+ assert!(!wizard.run.lock().started);+ }++ /// The legitimate path: the child gets `--yes`, each picked agent once as+ /// `--agent`, and the wizard's flags; its output (escape codes stripped)+ /// and exit status reach the progress endpoint. A second apply while it+ /// runs is refused, and so is finishing before it ends.+ #[tokio::test]+ async fn apply_runs_setup_with_the_picked_agents_and_streams_its_output() {+ let (launch, calls) = recording(0);+ let wizard = wizard(launch);+ let (status, _, _) = send(+ &wizard,+ legit(+ &wizard,+ "apply",+ r#"{"agents":["codex","claude-code","codex"]}"#,+ ),+ )+ .await;+ assert_eq!(status, StatusCode::ACCEPTED);+ assert_eq!(+ calls.lock().first().cloned(),+ Some(+ [+ "--yes",+ "--agent",+ "codex",+ "--agent",+ "claude-code",+ "--no-service"+ ]+ .map(str::to_owned)+ .to_vec()+ )+ );+ let host = format!("127.0.0.1:{PORT}");+ let deadline = Instant::now() + Duration::from_secs(20);+ let progress = loop {+ let (_, _, body) = send(&wizard, get(&path(&wizard, "progress?from=0"), &host)).await;+ let json: serde_json::Value = serde_json::from_str(&body).unwrap();+ if json["done"] == true {+ break json;+ }+ assert!(Instant::now() < deadline, "the child never finished");+ tokio::time::sleep(Duration::from_millis(50)).await;+ };+ assert_eq!(progress["ok"], true);+ let lines: Vec<&str> = progress["lines"]+ .as_array()+ .unwrap()+ .iter()+ .map(|line| line.as_str().unwrap().trim())+ .collect();+ assert!(lines.contains(&"== claude-code"), "{lines:?}");+ assert!(lines.contains(&"done"), "escape codes stripped: {lines:?}");+ assert_eq!(+ progress["agents"],+ serde_json::json!(["codex", "claude-code"])+ );++ let (status, _, _) = send(&wizard, legit(&wizard, "finish", "{}")).await;+ assert_eq!(status, StatusCode::NO_CONTENT);+ }++ #[tokio::test]+ async fn a_second_apply_or_a_finish_waits_for_the_running_setup() {+ let wizard = wizard(recording(0).0);+ wizard.run.lock().started = true;+ let (status, _, _) =+ send(&wizard, legit(&wizard, "apply", r#"{"agents":["codex"]}"#)).await;+ assert_eq!(status, StatusCode::CONFLICT);+ let (status, _, _) = send(&wizard, legit(&wizard, "finish", "{}")).await;+ assert_eq!(status, StatusCode::CONFLICT);+ }++ #[test]+ fn escape_sequences_are_stripped() {+ assert_eq!(strip_ansi("\u{1b}[1;32mok\u{1b}[0m done"), "ok done");+ assert_eq!(strip_ansi("plain"), "plain");+ }+}diff --git a/crates/ai-memory-cli/templates/setup_web.html b/crates/ai-memory-cli/templates/setup_web.htmlnew file mode 100644index 00000000..d7bc5042--- /dev/null+++ b/crates/ai-memory-cli/templates/setup_web.html@@ -0,0 +1,234 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<meta name="referrer" content="no-referrer">+<title>ai-memory setup</title>+<style nonce="__NONCE__">+:root {+ --bg: #fafaf9; --fg: #1c1917; --muted: #57534e; --line: #e7e5e4;+ --card: #ffffff; --accent: #0f766e; --accent-fg: #ffffff; --bad: #b91c1c; --good: #15803d;+ --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+}+@media (prefers-color-scheme: dark) {+ :root {+ --bg: #1c1917; --fg: #f5f5f4; --muted: #a8a29e; --line: #44403c;+ --card: #292524; --accent: #2dd4bf; --accent-fg: #042f2e; --bad: #f87171; --good: #4ade80;+ }+}+* { box-sizing: border-box; }+body { margin: 0; background: var(--bg); color: var(--fg); font: 15px/1.5 system-ui, sans-serif; }+main { max-width: 760px; margin: 0 auto; padding: 32px 16px 64px; }+h1 { font-size: 24px; margin: 0 0 4px; }+h2 { font-size: 16px; margin: 0 0 12px; }+p.lead { color: var(--muted); margin: 0 0 24px; }+section { background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 16px 18px; margin-bottom: 16px; }+code, pre { font-family: var(--mono); font-size: 13px; }+code { overflow-wrap: anywhere; }+dl { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 0; }+dt { color: var(--muted); }+dd { margin: 0; overflow-wrap: anywhere; }+label.agent { display: flex; gap: 10px; align-items: flex-start; padding: 8px 0; border-top: 1px solid var(--line); }+label.agent:first-of-type { border-top: 0; }+label.agent small { display: block; color: var(--muted); overflow-wrap: anywhere; }+details summary { cursor: pointer; color: var(--muted); margin-top: 8px; }+.others { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-top: 8px; }+.others label { display: inline-flex; gap: 6px; align-items: center; }+button { font: inherit; border: 0; border-radius: 8px; padding: 10px 18px; background: var(--accent); color: var(--accent-fg); cursor: pointer; }+button[disabled] { opacity: .5; cursor: default; }+button.secondary { background: transparent; color: var(--fg); border: 1px solid var(--line); }+.actions { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }+.note { color: var(--muted); font-size: 13px; }+pre#log { background: var(--bg); border: 1px solid var(--line); border-radius: 8px; padding: 12px; max-height: 360px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; margin: 12px 0 0; }+.result { font-weight: 600; margin-top: 12px; }+.result.ok { color: var(--good); }+.result.bad { color: var(--bad); }+.question { font-family: var(--mono); background: var(--bg); border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; display: inline-block; margin-top: 6px; }+[hidden] { display: none !important; }+</style>+</head>+<body>+<main>+ <h1>ai-memory setup</h1>+ <p class="lead">Check the plan, choose your agents, and apply. Nothing changes until you press Apply.</p>+ <p id="loading" class="note">Loading the plan…</p>+ <p id="failed" class="result bad" hidden></p>++ <div id="plan" hidden>+ <section>+ <h2>Install</h2>+ <dl>+ <dt>Data dir</dt><dd><code id="data-dir"></code></dd>+ <dt>Config</dt><dd><code id="config-path"></code></dd>+ <dt>State</dt><dd id="fresh"></dd>+ <dt>Service</dt><dd id="service"></dd>+ </dl>+ </section>++ <section>+ <h2>Agents</h2>+ <div id="agents"></div>+ <p id="no-agents" class="note" hidden>No agent was detected. Pick one below.</p>+ <details id="others-box">+ <summary>Other supported agents</summary>+ <div class="others" id="others"></div>+ </details>+ </section>++ <section>+ <div class="actions">+ <button id="apply" type="button">Apply</button>+ <span class="note">Runs <code>ai-memory setup --yes</code> with the agents you picked, then checks the result.</span>+ </div>+ <pre id="log" hidden></pre>+ <div id="outcome" hidden>+ <p id="result" class="result"></p>+ <p id="next" hidden>Restart <span id="restart"></span>, then ask it:<br><span class="question" id="question"></span></p>+ </div>+ <div class="actions" id="finish-row" hidden>+ <button id="finish" class="secondary" type="button">Finish and close the setup server</button>+ </div>+ </section>+ </div>+ <p id="closed" class="note" hidden>The setup server has stopped. You can close this tab.</p>+</main>+<script nonce="__NONCE__">+(function () {+ "use strict";+ var base = location.pathname.replace(/\/?$/, "/");+ var csrf = "";+ var $ = function (id) { return document.getElementById(id); };+ var text = function (id, value) { $(id).textContent = value; };++ function describeFound(found) {+ if (!found) return "named on the command line";+ var what = { session_store: "session store", mcp_config: "MCP config", config_dir: "directory" }[found.kind] || found.kind;+ return "found its " + what + " at " + found.path;+ }++ function wiring(value) {+ return { plugin: "left to its enabled ai-memory plugin", "mcp+hooks+skills": "MCP + hooks + skills", "hooks+skills": "hooks + skills" }[value] || value;+ }++ function checkbox(name, checked) {+ var box = document.createElement("input");+ box.type = "checkbox";+ box.name = "agent";+ box.value = name;+ box.checked = checked;+ return box;+ }++ function render(doc) {+ var plan = doc.plan;+ csrf = doc.csrf;+ text("data-dir", plan.data_dir);+ text("config-path", plan.config_path);+ text("fresh", plan.fresh ? "new install: creates the data dir, the config and a root bearer token" : "existing install: kept as it is");+ text("service", plan.service.action === "install"+ ? "install and start a " + plan.service.manager + " at " + plan.service.path+ : plan.service.reason);+ var agents = $("agents");+ plan.agents.forEach(function (agent) {+ var label = document.createElement("label");+ label.className = "agent";+ var body = document.createElement("span");+ var name = document.createElement("strong");+ name.textContent = agent.agent;+ var detail = document.createElement("small");+ detail.textContent = wiring(agent.wiring) + "; " + describeFound(agent.found);+ body.appendChild(name);+ body.appendChild(detail);+ label.appendChild(checkbox(agent.agent, true));+ label.appendChild(body);+ agents.appendChild(label);+ });+ $("no-agents").hidden = plan.agents.length > 0;+ if (plan.agents.length === 0) $("others-box").open = true;+ var others = $("others");+ plan.other_agents.forEach(function (name) {+ var label = document.createElement("label");+ label.appendChild(checkbox(name, false));+ label.appendChild(document.createTextNode(name));+ others.appendChild(label);+ });+ text("question", plan.first_question);+ $("loading").hidden = true;+ $("plan").hidden = false;+ }++ function fail(message) {+ $("failed").textContent = message;+ $("failed").hidden = false;+ }++ function post(path, body) {+ return fetch(base + path, {+ method: "POST",+ headers: { "content-type": "application/json", "x-ai-memory-setup": csrf },+ body: JSON.stringify(body || {})+ });+ }++ function chosen() {+ return Array.prototype.slice.call(document.querySelectorAll("input[name=agent]:checked"))+ .map(function (box) { return box.value; });+ }++ function poll(from) {+ fetch(base + "progress?from=" + from).then(function (r) { return r.json(); }).then(function (p) {+ var log = $("log");+ if (p.lines.length) {+ log.textContent += p.lines.join("\n") + "\n";+ log.scrollTop = log.scrollHeight;+ }+ if (!p.done) { setTimeout(function () { poll(p.next); }, 500); return; }+ $("outcome").hidden = false;+ var result = $("result");+ if (p.ok) {+ result.className = "result ok";+ result.textContent = "ai-memory is set up.";+ text("restart", p.agents.join(", "));+ $("next").hidden = p.agents.length === 0;+ } else {+ result.className = "result bad";+ result.textContent = "Setup finished with problems; see the lines starting with \"problem:\" above, fix them, and apply again.";+ $("apply").disabled = false;+ }+ $("finish-row").hidden = false;+ }).catch(function () { setTimeout(function () { poll(from); }, 1000); });+ }++ $("apply").addEventListener("click", function () {+ var agents = chosen();+ if (agents.length === 0) { fail("Pick at least one agent."); return; }+ $("failed").hidden = true;+ $("apply").disabled = true;+ $("log").hidden = false;+ $("log").textContent = "";+ $("outcome").hidden = true;+ post("apply", { agents: agents }).then(function (r) {+ if (r.status === 202) { poll(0); return; }+ return r.text().then(function (body) { fail(body || ("The server answered " + r.status)); $("apply").disabled = false; });+ }).catch(function () { fail("The setup server did not answer."); $("apply").disabled = false; });+ });++ $("finish").addEventListener("click", function () {+ post("finish").finally(function () {+ $("plan").hidden = true;+ $("closed").hidden = false;+ });+ });++ fetch(base + "plan").then(function (r) {+ if (!r.ok) throw new Error("status " + r.status);+ return r.json();+ }).then(render).catch(function (error) {+ $("loading").hidden = true;+ fail("Could not load the plan (" + error.message + "). Is `ai-memory setup --web` still running?");+ });+})();+</script>+</body>+</html>diff --git a/crates/ai-memory-cli/tests/suite/setup_e2e.rs b/crates/ai-memory-cli/tests/suite/setup_e2e.rsindex 6bdb8f9e..f09bea22 100644--- a/crates/ai-memory-cli/tests/suite/setup_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/setup_e2e.rs@@ -173,6 +173,122 @@ fn setup_plan_json_prints_the_plan_and_changes_nothing() {assert_eq!(sandbox.snapshot(), before, "a refused setup wrote");}+/// `setup --web` through the binary: the printed address serves the page and+/// plan, a foreign Host is refused, Apply runs `setup --yes --agent+/// claude-code` (which writes Claude Code's hooks), and Finish stops the+/// process. No server runs here, so that setup reports its failed self-check+/// and the wizard exits non-zero after Finish.+#[test]+fn setup_web_serves_the_plan_and_applies_the_picked_agent() {+ use std::io::{BufRead as _, Read as _, Write as _};+ use std::net::TcpStream;++ let sandbox = Sandbox::new();+ std::fs::create_dir_all(sandbox.home.join(".claude/projects")).unwrap();+ let port = crate::e2e_support::free_port();+ let mut child = sandbox+ .cmd(Some(port))+ .args(["setup", "--web", "--no-open", "--no-service"])+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .unwrap();+ struct Kill(std::process::Child);+ impl Drop for Kill {+ fn drop(&mut self) {+ let _ = self.0.kill();+ let _ = self.0.wait();+ }+ }+ let stdout = child.stdout.take().unwrap();+ let mut child = Kill(child);+ let mut url = String::new();+ for line in std::io::BufReader::new(stdout).lines() {+ let line = line.unwrap();+ if let Some(found) = line.trim().strip_prefix("http://127.0.0.1:") {+ url = format!("http://127.0.0.1:{found}");+ break;+ }+ }+ assert!(url.ends_with('/'), "no address printed: {url:?}");+ let authority = url+ .trim_start_matches("http://")+ .split('/')+ .next()+ .unwrap()+ .to_owned();+ let path = url+ .trim_start_matches(&format!("http://{authority}"))+ .to_owned();++ let request = |method: &str, rest: &str, host: &str, extra: &str, body: &str| -> String {+ let mut stream = TcpStream::connect(&authority).unwrap();+ write!(+ stream,+ "{method} {path}{rest} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\+ Content-Type: application/json\r\nContent-Length: {}\r\n{extra}\r\n{body}",+ body.len()+ )+ .unwrap();+ let mut answer = String::new();+ stream.read_to_string(&mut answer).unwrap();+ answer+ };+ let page = request("GET", "", &authority, "", "");+ assert!(page.starts_with("HTTP/1.1 200"), "{page}");+ assert!(page.contains("ai-memory setup"), "{page}");+ let rebound = request("GET", "", "attacker.example", "", "");+ assert!(rebound.starts_with("HTTP/1.1 403"), "{rebound}");++ let plan = request("GET", "plan", &authority, "", "");+ let json: serde_json::Value =+ serde_json::from_str(plan.split("\r\n\r\n").nth(1).unwrap()).unwrap();+ assert_eq!(json["plan"]["agents"][0]["agent"], "claude-code", "{json}");+ let csrf = json["csrf"].as_str().unwrap().to_owned();+ let headers = format!("Origin: http://{authority}\r\nx-ai-memory-setup: {csrf}\r\n");++ let applied = request(+ "POST",+ "apply",+ &authority,+ &headers,+ r#"{"agents":["claude-code"]}"#,+ );+ assert!(applied.starts_with("HTTP/1.1 202"), "{applied}");+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);+ let progress = loop {+ let answer = request("GET", "progress?from=0", &authority, "", "");+ let json: serde_json::Value =+ serde_json::from_str(answer.split("\r\n\r\n").nth(1).unwrap()).unwrap();+ if json["done"] == true {+ break json;+ }+ assert!(std::time::Instant::now() < deadline, "setup never finished");+ std::thread::sleep(std::time::Duration::from_millis(200));+ };+ let lines = progress["lines"].to_string();+ assert!(lines.contains("== claude-code"), "{lines}");+ assert!(+ sandbox.home.join(".claude/settings.json").is_file(),+ "{lines}"+ );++ let finished = request("POST", "finish", &authority, &headers, "{}");+ assert!(finished.starts_with("HTTP/1.1 204"), "{finished}");+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);+ let status = loop {+ if let Some(status) = child.0.try_wait().unwrap() {+ break status;+ }+ assert!(+ std::time::Instant::now() < deadline,+ "the wizard did not stop"+ );+ std::thread::sleep(std::time::Duration::from_millis(100));+ };+ assert_eq!(progress["ok"] == true, status.success(), "{lines}");+}+/// Spawns a server through the fake service manager: the slow tier.#[cfg(target_os = "linux")]mod slow {diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex e8737b20..91ea5b67 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -818,6 +818,11 @@ Windows, only a `Run` value with the shape `setup` writes).`install.sh` and, for Windows, `install.ps1` are release assets with their own`.sha256` files; each installs the release archive after checking it againstthe published checksum, under `~/.local` or `%LOCALAPPDATA%\Programs`.+`setup --web` serves the plan from a one-shot axum router in the CLI+(`commands/setup_web.rs`), separate from the read-only `/web` UI: loopback+only, a one-time path secret, an exact `Host` check, `Origin` plus CSRF on+every POST, and an Apply that runs `setup --yes --agent ...` as a child+process (security-boundaries row 17).The hidden `render-plugins --out <dir>` generates the Claude Code and Codexmarketplace plugins under `plugins/` and their catalogsdiff --git a/docs/install.md b/docs/install.mdindex c3348191..afd6d863 100644--- a/docs/install.md+++ b/docs/install.md@@ -117,7 +117,7 @@ Windows 11 runs under emulation. Errors are thrown rather than exiting, so afailure under `iex` leaves your PowerShell window open. Details are in[`docs/windows.md`](windows.md).-`ai-memory setup [--yes] [--agent <name>]... [--no-service] [--plan [--json]]`+`ai-memory setup [--yes] [--agent <name>]... [--no-service] [--plan [--json]] [--web [--no-open]]`runs, in order, the commands a native install otherwise needs one by one:1. `init`. On a fresh data dir this mints the root bearer token into@@ -171,7 +171,20 @@ naming a number outside the plan changes nothing. With no terminal (a script,an agent's tool call) it changes nothing and exits non-zero, asking for`--yes`. `--plan` prints the plan and exits without changing anything;`--plan --json` prints it as a JSON document for a script or front end, with a-`format` field that is bumped only when a field changes meaning or is removed. Each step is idempotent: a second run rewrites no+`format` field that is bumped only when a field changes meaning or is removed.++`ai-memory setup --web` shows the same plan as a page in your browser instead+of the terminal. It prints a one-time address on `127.0.0.1` (and opens it,+unless `--no-open` or there is no desktop), where you tick the agents to wire+and press Apply. Apply runs `ai-memory setup --yes --agent <each one you+picked>` and streams its output to the page, so the result is the same as the+terminal command; `--no-service` is passed through. The page answers only+requests that name its own address, carry the secret part of the URL, and,+for a change, come from the page itself, so another site open in the same+browser cannot drive it. It holds no token. It stops when you press Finish,+after 15 minutes without a request, or on Ctrl-C. On a remote machine,+forward the port it prints (`ssh -L <port>:127.0.0.1:<port> <host>`) and open+the same address locally. Each step is idempotent: a second run rewrites nofile and leaves a running service alone. A step that fails does not stop theothers; `setup` lists each `problem:` at the end and exits non-zero. When every steppassed it ends by naming the agents to restart and the question to ask one ofdiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 2fcbf3a1..e8b77bf3 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -109,7 +109,8 @@ means the boundary is not built yet.| 14g | Web project search and its recall trace honour `memory_query`'s scope rules (#708) and never describe another project | `ai-memory-web/src/routes/search.rs` resolves `workspace`+`project` through `resolve_read_scope` (`lookup_existing_scope_guarded`, no-create, `ProjectAccess::Read`) before any ranking, and refuses partial scope; scoped `/api/v1/search` keeps `lookup_project` / `resolve_many_existing_scopes_guarded`; `ai-memory-web/src/recall.rs` ranks only the resolved scopes through `ReaderPool::hybrid_search_scopes`, whose streams and graph expansion are bound to each `(workspace_id, project_id)`; a search with no scope stays `search_pages_with_meta(.., viewer)` (readable repositories only) | `ai-memory-web` `tests/suite/recall_trace.rs` — `project_search_refuses_a_restricted_project_without_a_grant` (bob, with no grant, gets 403 from `/web/search` with and without `explain=1` and from scoped `/api/v1/search`, with no path, body text or trace in the response, and a `scopes` POST naming the restricted project next to an open one is refused; alice's grant and an unrestricted viewer are the controls), `project_search_fails_closed_on_unknown_and_partial_scope` (unknown project or workspace 404 with nothing created, partial scope 400), `explain_renders_stream_ranks_rrf_authority_and_timings` (a better-matching page in a sibling project never reaches the hits or the trace), `search_scope_selector_lists_only_readable_projects` (the search page's "Search in" selector lists only projects the viewer may read, and a hand-typed `scope=` for an ungranted project is a 403 that leaks nothing; controls: the granted reader and an unrestricted viewer; passing no viewer to `list_projects_with_stats` in the handler fails it), `routes.rs` `search_page_scope_selector_round_trips_and_rejects_malformed_values` (a malformed `scope` is a 400); `recall_trace.rs` `kind_filter_does_not_widen_what_a_viewer_can_read` (a `kind`/`tier` filter only narrows: bob gets no hits and a 403 on a scoped search; alice and an unrestricted viewer are the controls), `search_filters_a_project_by_kind_and_tier_keeping_rank_order` (survivors of a filter keep the unfiltered order), `reranker_is_shown_only_the_pages_the_filter_keeps` (a dropped page never reaches the reranker), `kind_and_tier_filters_hold_in_every_stream` (FTS, entity, vector, observation and both graph directions each filter in SQL; dropping any one stream's predicate fails it), `kind_filter_finds_a_rare_kind_the_unfiltered_page_ranks_out` and `cross_project_kind_filter_sees_past_the_candidate_window` (the filter sees past the candidate window in both modes); `ai-memory-mcp` `tests/suite/web_search_parity.rs` (same top-k order as `memory_query` from `/web` and `/api/v1`, with a deterministic embedder and with none, explain on and off, and merged `scopes`; controls show a web search without the embedder, or the old FTS-only scoped search, would fail it) | STRONG. Bite checks: passing no viewer to `resolve_read_scope` in the search handler, to `lookup_project` or to `resolve_scopes` in the API each fails the restricted-project test; dropping the query vector in `recall.rs` fails the embedder parity tests || 15 | Agent-archive restore path confinement, resource bounds, and consistency | `ai-memory-cli/src/commands/restore_agents.rs` stages only bounded regular UTF-8 entries; requires a one-to-one manifest/body/checksum/target mapping; allowlists destinations by scope; rejects symlinked descendants; writes each file atomically and rolls back earlier writes after a later failure. `backup_agents.rs` skips direct and directory-root source symlinks, bounds individual assets, and atomically replaces a private archive only after gzip completion | `backup_agents.rs` `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`, `restore_agents_requires_a_complete_one_to_one_manifest`, `restore_agents_rejects_oversized_entries_from_the_header`, `restore_agents_rejects_a_symlinked_destination_parent`, `backup_agents_does_not_follow_config_or_asset_root_symlinks`, and `failed_backup_leaves_the_previous_archive_intact`; `backup_and_restore_agents_round_trip` is the valid-path control; `restore_agents::tests::rollback_removes_new_files_and_restores_overwrites` covers recovery | STRONG || 16 | Relay queue identity, migration, and private filesystem state | `companions/ai-memory-relay/src/queue.rs` `Queue::open_inner` performs read-only identity preflight, rechecks under `IMMEDIATE`, commits schema and metadata together; `configure` checks the presence of user objects and rechecks `identity`/`schema_version` metadata on the same connection before every bounded BUSY/LOCKED retry; `fsguard.rs` checks existing paths and creates owner-only files before SQLite opens them | `tests/relay.rs` `a_foreign_database_is_refused_byte_for_byte`, `unknown_schemas_refuse_without_mutation`, `a_foreign_database_with_a_writer_is_refused_before_write_coordination`, `a_foreign_identity_after_preflight_is_refused_without_mutation`, `a_foreign_identity_during_journal_retry_is_refused_without_mutation`, `journal_retry_refuses_a_changed_version_or_empty_database_without_mutation`; controls: `journal_transition_retries_sqlite_lock_without_losing_v1_values`, `fresh_queue_init_and_v1_reopens_work_across_processes`; recovery: `interrupted_and_failed_migrations_roll_back_and_recover`, `journal_reclassification_busy_preserves_committed_migration_and_retries_same_queue`; diagnostics: `classification_read_failures_display_the_sqlite_cause_once_and_preserve_foreign_bytes`; Unix privacy: `the_queue_database_and_its_sidecars_are_owner_only` and the contended migration control | Guard-removal proof covers preflight, locked recheck, and journal retry identity/version checks; full table structure is outside this classification. Windows path rejection is preserved; Windows ACL hardening remains operator-owned |-+| 17 | `ai-memory setup --web` local wizard: only the page this process printed can read the plan or apply a setup | `ai-memory-cli/src/commands/setup_web.rs` `guard` (binds `127.0.0.1` on an OS-picked port; every request needs a `Host` of exactly `127.0.0.1:<port>` or `localhost:<port>` and the one-time 256-bit path secret, compared with `subtle`; a POST also needs this page's `Origin` and the CSRF token the page reads from its own JSON; no CORS grant; `no-store`, `no-referrer`, `DENY` framing, and a CSP with a per-run nonce and no outside sources on the page) and `apply` (agent names must be `--agent` values, de-duplicated, at least one; the child is always `ai-memory setup --yes --agent ...` with the wizard's own flags, never a caller-chosen argument) | `setup_web.rs` `the_page_is_served_only_to_our_host_and_secret` (a rebinding `Host`, a bare `127.0.0.1`, another port, a wrong secret and a missing one refused; controls: `127.0.0.1` and `localhost` with the secret), `apply_refuses_cross_site_and_unknown_input_and_starts_nothing` (no `Origin`, a foreign `Origin`, no CSRF token and a wrong one each refused; `--force`, a shell-like name and an empty choice refused; no child starts), `apply_runs_setup_with_the_picked_agents_and_streams_its_output` (legitimate control: exact argument list); `tests/suite/setup_e2e.rs` `setup_web_serves_the_plan_and_applies_the_picked_agent` (the same through the binary); bite-checked by removing the `Host` check, the `Origin` check, the CSRF check and the agent allowlist one at a time | STRONG |+| 18 | `uninstall` removes only a service `setup` wrote, including the Windows logon entry | `ai-memory-cli/src/commands/user_service.rs` `planned_removal` / `is_rendered_by_setup` (a unit file whose identity digest still matches) and `planned_removal_for` / `is_setup_run_entry` (a `HKCU\...\Run\ai-memory` value that is a quoted `ai-memory.exe` ending in `service-host`, with no `&` or `|` chaining) before `remove` stops anything or deletes it | `user_service.rs` `uninstall_removes_only_setups_logon_entry` (another program's value under the same name is left with only the query run; absent value is nothing to do; control: setup's value is deleted with `reg delete`), `only_setups_entry_shape_counts_as_ours` (unquoted, other program, `serve`, `&`/`|` chaining all refused), and the unit-file identity tests in the same module | STRONG |## Keeping this current (the standing protocol)