Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(setup): two-command native install with install.sh and ai-memory setup
AkitaOnRails021509b7ecc8
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 639cb097..c3fa6412 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -525,6 +525,15 @@ jobs:sha256sum ai-memory-hooks.tar.gz > ai-memory-hooks.tar.gz.sha256)+ - name: Stage checksum-verified install script+ run: |+ set -euo pipefail+ install -m 0755 install.sh artifacts/install.sh+ (+ cd artifacts+ sha256sum install.sh > install.sh.sha256+ )+- name: Generate release bodyrun: |echo "## Checksums (SHA256)" > body.md@@ -534,6 +543,10 @@ jobs:echo "" >> body.mdecho "## Install" >> body.mdecho '```bash' >> body.md+ echo "# Linux/macOS, no root: checksum-verified release binary under ~/.local, then one-step setup" >> body.md+ echo "curl -fsSL https://github.com/akitaonrails/ai-memory/releases/download/${GITHUB_REF_NAME}/install.sh | AI_MEMORY_VERSION=${{ needs.validate-version.outputs.version }} sh" >> body.md+ echo "ai-memory setup" >> body.md+ echo "" >> body.mdecho "# Arch Linux (AUR)" >> body.mdecho "yay -S ai-memory-bin # prebuilt Linux x86_64/aarch64 binary" >> body.mdecho "yay -S ai-memory # builds from source" >> body.mddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2839b64d..e6063a42 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -40,6 +40,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0retry command. The page is read-only and is gated like `/web/pending`: on amulti-user server anonymous requests get a 401 and database users a 403. Itnever shows provider error text, page content or project names.+- Added a two-command native install for Linux and macOS:+ `curl -fsSL https://github.com/akitaonrails/ai-memory/releases/latest/download/install.sh | sh`,+ then `ai-memory setup`. `install.sh` is a new release asset with its own+ `install.sh.sha256`. It downloads the release tarball for the machine, checks+ it against the published `.sha256` file and refuses to install when that file+ is missing, names another asset or does not match, or when the archive holds+ an absolute or `..` path. It unpacks under `~/.local/lib/ai-memory`, links+ `~/.local/bin/ai-memory`, needs no root, leaves an existing non-link+ `ai-memory` (such as the Docker wrapper) alone, and runs nothing when the+ download is cut short. The new `ai-memory setup [--yes] [--agent <name>]...+ [--no-service]` runs `init` (a fresh data dir gets the root bearer token),+ installs and starts a per-user service rendered from the packaged systemd+ user unit or launchd LaunchAgent with this install's binary, data dir and+ config, wires MCP, hooks and global Agent Skills for each named or detected+ agent, and ends with a read-only check of `/healthz`, `memory_status` and+ `doctor`. It shows the plan and asks first; without a terminal it changes+ nothing unless given `--yes`. A second run changes nothing. Windows has no+ service step. `INSTALL_FOR_AGENTS.md` tells an AI agent how to install+ ai-memory for its user, and `scripts/onboarding-acceptance.sh` measures the+ path from a clean home to the first returned memory.- Added page history and session replay to the read-only web UI. Each pagelinks to its history (`/web/w/<ws>/<proj>/h/<path>`): every stored version,newest first, superseded ones included, so a version a concurrent writediff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdnew file mode 100644index 00000000..9fec09e4--- /dev/null+++ b/INSTALL_FOR_AGENTS.md@@ -0,0 +1,48 @@+# Installing ai-memory for your user (instructions for AI agents)++You are an AI coding agent and your user asked you to install ai-memory. On+Linux or macOS it takes two commands, and neither needs root.++1. Install the release binary. The script checks the download against the+ release's published SHA-256 checksum, puts the binary under+ `~/.local/lib/ai-memory` and links `~/.local/bin/ai-memory` to it:++ ```bash+ curl -fsSL https://github.com/akitaonrails/ai-memory/releases/latest/download/install.sh | sh+ ```++ If `~/.local/bin` is not on `PATH`, call `~/.local/bin/ai-memory` directly+ in the next step, and tell your user to add the directory to `PATH`.++2. Set it up for yourself, naming your own harness:++ ```bash+ ai-memory setup --yes --agent <self>+ ```++ `<self>` is one of `claude-code`, `codex`, `opencode`, `opencode2`,+ `gemini-cli`, `cursor`, `kimi-code`, `kiro-cli`, `grok`, `copilot-cli`,+ `antigravity-cli`, `command-code`, `devin`, `omp`, `pi`, `openclaw`+ (`ai-memory setup --help` lists every value). Repeat `--agent` to wire+ several harnesses. Without `--agent`, `setup` wires every harness it finds+ under the home directory.++`setup` creates the data directory with a root bearer token in an owner-only+file, starts a per-user service (systemd `--user` on Linux, a LaunchAgent on+macOS), registers the MCP server and installs the lifecycle hooks and Agent+Skills for each harness, then checks that the server answers. The token is+never printed and never written into a harness config. Running `setup` again+changes nothing.++Afterwards:++- Tell your user to restart the harness so it loads the new MCP entry and+ hooks.+- If `setup` exits non-zero, show your user the `problem:` lines it printed.+ Do not work around them by editing harness configs by hand.+- If the server already runs another way (Docker, a packaged system unit), add+ `--no-service`.+- On Windows, follow [`docs/windows.md`](docs/windows.md) instead; `setup` has+ no service step there.++Full reference: [`docs/install.md`](docs/install.md#one-step-native-install-installsh--ai-memory-setup).diff --git a/README.md b/README.mdindex e73c9b58..96d26e46 100644--- a/README.md+++ b/README.md@@ -194,6 +194,26 @@ differs, and the published benchmark, is in [How ai-memory compares](docs/compar## Quick start+### Linux and macOS (two commands, no root)++```bash+curl -fsSL https://github.com/akitaonrails/ai-memory/releases/latest/download/install.sh | sh+ai-memory setup+```++`install.sh` downloads the release for your OS and CPU, checks it against the+release's published SHA-256 checksum (it refuses to install without a match),+and links `~/.local/bin/ai-memory`. `ai-memory setup` then creates the data+directory with a bearer token in an owner-only file, starts a per-user service+(systemd `--user` or a launchd LaunchAgent), and wires MCP, hooks and Agent+Skills for every agent it finds, or the ones you name with `--agent`. It shows+the plan and asks first; `--yes` skips the question, and running it again+changes nothing. Restart your agents afterwards. Details, the environment+variables and how to verify the script before running it are in+[`docs/install.md`](docs/install.md#one-step-native-install-installsh--ai-memory-setup).+An AI agent installing ai-memory for you can follow+[`INSTALL_FOR_AGENTS.md`](INSTALL_FOR_AGENTS.md).+### Arch Linux (AUR)For native Arch installs, use the AUR packages. They installdiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 9f07e16e..6fac2f2a 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -113,6 +113,11 @@ pub struct Cli {pub enum Command {/// Initialise the data directory layout.Init(InitArgs),+ /// Set up a native install in one step: `init`, a user service+ /// (systemd `--user` or a launchd LaunchAgent), and hooks, MCP and skills+ /// for every detected agent, then a read-only self-check. Shows the plan+ /// and asks first unless `--yes` is given. Re-running changes nothing.+ Setup(SetupArgs),/// Print runtime status (counts, paths, version).Status(StatusArgs),/// List every workspace/project pair the server knows about (plain,@@ -1974,6 +1979,26 @@ pub struct InitArgs {pub force: bool,}+/// Arguments for `setup`.+#[derive(Debug, Args)]+pub struct SetupArgs {+ /// Apply the plan without asking. Without it, `setup` shows the plan and+ /// asks on a terminal, or exits non-zero when there is no terminal to+ /// ask on.+ #[arg(long, short = 'y')]+ pub yes: bool,+ /// Wire this agent instead of the detected ones. Repeat for several.+ /// Detection looks for each harness's session store or MCP config under+ /// your home; OpenCode 2 and the Kiro CLI v3 engine are only wired when+ /// named here.+ #[arg(long = "agent", value_enum)]+ pub agents: Vec<AgentChoice>,+ /// Do not install or start a user service; use this when the server+ /// already runs some other way (Docker, a packaged system unit).+ #[arg(long)]+ pub no_service: bool,+}+/// Arguments for `status`.#[derive(Debug, Args)]pub struct StatusArgs {diff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rsindex 259e5c20..5251c1ce 100644--- a/crates/ai-memory-cli/src/commands/doctor.rs+++ b/crates/ai-memory-cli/src/commands/doctor.rs@@ -282,6 +282,24 @@ pub(crate) fn relocated_session_dir(harness: ManagedHarness) -> Option<PathBuf>.and_then(|plan| plan.session_dir)}+/// [`relocated_session_dir`] reading the relocation variables through `env`,+/// for `setup`, which reads the environment `Config::load` captured.+pub(crate) fn relocated_session_dir_with(+ harness: ManagedHarness,+ env: &dyn Fn(&str) -> Option<std::ffi::OsString>,+) -> Option<PathBuf> {+ ai_memory_workstream::build_launch_plan_with_env_lookup(+ harness,+ None,+ Vec::new(),+ None,+ |name: &str| env(name),+ None,+ )+ .ok()+ .and_then(|plan| plan.session_dir)+}+/// Harnesses whose native "memory" store location is known, so `doctor` can/// report on it (harness-issue #1003). Only Claude Code's is established/// today — `~/.claude/projects/<project>/memory/`, found viadiff --git a/crates/ai-memory-cli/src/commands/init.rs b/crates/ai-memory-cli/src/commands/init.rsindex 861ff89a..e0067347 100644--- a/crates/ai-memory-cli/src/commands/init.rs+++ b/crates/ai-memory-cli/src/commands/init.rs@@ -80,17 +80,22 @@ bearer_token_file = {}/// another way gets a new token at `auth-tokens/default`./// - Anything else, an existing install above all, records nothing and keeps/// the loopback no-auth behaviour it had (`ai-memory auth enable` opts in).-fn root_bearer_for_new_config(config: &Config, fresh: bool) -> Result<Option<String>> {+fn root_bearer_for_new_config(config: &Config, fresh: bool) -> Result<Option<RecordedBearer>> {if let Some(raw) = config.auth.bearer_token_file.as_ref().filter(|raw| !raw.as_os_str().is_empty()){- if let Some(path) = config.auth.token_file_path() {- crate::local_auth::provision_root_token(path)?;- }- return Ok(Some(raw.to_string_lossy().into_owned()));+ let token = config+ .auth+ .token_file_path()+ .map(crate::local_auth::provision_root_token)+ .transpose()?;+ return Ok(Some(RecordedBearer {+ raw: raw.to_string_lossy().into_owned(),+ token,+ }));}if !fresh || config.auth.bearer_token.is_some() {return Ok(None);@@ -104,7 +109,29 @@ fn root_bearer_for_new_config(config: &Config, fresh: bool) -> Result<Option<Strroute but /healthz; hooks, the CLI and `ai-memory mcp-bridge` read it from there.",minted.path.display());- Ok(Some(crate::server_profiles::ROOT_TOKEN_RELATIVE.to_owned()))+ Ok(Some(RecordedBearer {+ raw: crate::server_profiles::ROOT_TOKEN_RELATIVE.to_owned(),+ token: Some(minted),+ }))+}++/// The `bearer_token_file` a written config records, and the token read from+/// (or minted into) that file.+struct RecordedBearer {+ raw: String,+ token: Option<crate::local_auth::RootToken>,+}++/// What one `init` did, for a caller (`setup`) that keeps going in the same+/// process after it.+pub(crate) struct InitOutcome {+ /// The config file `init` wrote or found.+ pub(crate) config_path: PathBuf,+ /// False when a config file already existed and was left untouched.+ pub(crate) config_written: bool,+ /// The root bearer the written config names in `bearer_token_file`, so the+ /// caller can adopt it the way `Config::load` would have.+ pub(crate) root_token: Option<crate::local_auth::RootToken>,}/// Run the `init` subcommand.@@ -122,6 +149,18 @@ fn root_bearer_for_new_config(config: &Config, fresh: bool) -> Result<Option<Str/// Returns an error if directories cannot be created or the config file/// cannot be written.pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> Result<()> {+ initialize(config, &args, config_path).map(|_| ())+}++/// [`run`], reporting what it did.+///+/// # Errors+/// As [`run`].+pub(crate) fn initialize(+ config: &Config,+ args: &InitArgs,+ config_path: Option<&Path>,+) -> Result<InitOutcome> {let root = &config.data_dir;let cfg_path = init_config_path(root, config_path);// Decided before anything is created: a data dir that already has a@@ -138,6 +177,11 @@ pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> Resultracing::info!(path = %path.display(), "ensured directory");}+ let mut outcome = InitOutcome {+ config_path: cfg_path.clone(),+ config_written: false,+ root_token: None,+ };if cfg_path.exists() && !args.force {tracing::info!(path = %cfg_path.display(),@@ -154,9 +198,12 @@ pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> Resul// (anyhow's `with_context` would conflict), so map manually.let pepper = generate_token_hex(TOKEN_PEPPER_BYTES).map_err(|e| anyhow::anyhow!("generating auth token_pepper: {e}"))?;- let bearer_line = root_bearer_for_new_config(config, fresh)?- .map(|raw| render_bearer_token_file_line(&raw))+ let recorded = root_bearer_for_new_config(config, fresh)?;+ let bearer_line = recorded+ .as_ref()+ .map(|bearer| render_bearer_token_file_line(&bearer.raw)).unwrap_or_default();+ outcome.root_token = recorded.and_then(|bearer| bearer.token);let body = format!("{}{}{}",DEFAULT_CONFIG_TOML,@@ -168,10 +215,11 @@ pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> Resulf.write_all(body.as_bytes()).with_context(|| format!("writing {}", cfg_path.display()))?;tracing::info!(path = %cfg_path.display(), "wrote default config");+ outcome.config_written = true;}tracing::info!("init complete");- Ok(())+ Ok(outcome)}/// Create missing directory components with owner-only access without changingdiff --git a/crates/ai-memory-cli/src/commands/mcp_bridge.rs b/crates/ai-memory-cli/src/commands/mcp_bridge.rsindex ffa46e27..d91465bf 100644--- a/crates/ai-memory-cli/src/commands/mcp_bridge.rs+++ b/crates/ai-memory-cli/src/commands/mcp_bridge.rs@@ -80,7 +80,7 @@ fn upstream_error(error: ServiceError) -> McpError {}}-fn upstream_config(+pub(crate) fn upstream_config(server_url: &str,session_id: Option<&str>,auth_token: Option<&str>,diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 313ffd8e..8d2ab35c 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -100,6 +100,7 @@ pub mod run_autowire;pub mod search;pub mod serve;pub mod server;+pub mod setup;pub mod setup_agent;pub mod show;pub mod status;@@ -107,6 +108,7 @@ pub mod transcript_capture;pub mod uninstall;pub mod upgrade;pub mod user;+pub mod user_service;pub mod workstream_search;pub mod workstreams;pub mod write_page;diff --git a/crates/ai-memory-cli/src/commands/setup.rs b/crates/ai-memory-cli/src/commands/setup.rsnew file mode 100644index 00000000..f4311957--- /dev/null+++ b/crates/ai-memory-cli/src/commands/setup.rs@@ -0,0 +1,708 @@+//! `ai-memory setup` — a native install in one command.+//!+//! A composition of the commands a native install otherwise runs by hand, in+//! order, through their own library functions:+//!+//! 1. `init`, which on a fresh data dir also mints the root bearer token into+//! `<data_dir>/auth-tokens/default` and records `[auth] bearer_token_file`;+//! 2. a per-user service running `serve` on that install+//! ([`super::user_service`]): a systemd `--user` unit or a launchd+//! LaunchAgent, rendered from the packaged templates. Windows has none;+//! 3. for each agent (named with `--agent`, else detected from its session+//! store or MCP config under the home, the way `doctor` finds them):+//! `install-mcp --apply`, `install-hooks --apply` and global+//! `install-skills`;+//! 4. a self-check that writes nothing: `/healthz`, a `memory_status` call+//! over MCP with the install's credential, and `doctor`.+//!+//! The token is never printed or passed on a command line. The installers keep+//! it out of every harness config (hooks read the credential files `init`+//! seeds; MCP clients go through `mcp-bridge` or an env-var reference), as+//! they do when run by hand.+//!+//! Every step is idempotent, so a second `setup` changes nothing. Without+//! `--yes` the plan is shown first and confirmed on a terminal; with no+//! terminal to ask on, `setup` changes nothing and exits non-zero.++use std::collections::BTreeSet;+use std::ffi::OsString;+use std::io::{BufRead as _, IsTerminal as _, Write as _};+use std::path::{Path, PathBuf};+use std::time::{Duration, Instant};++use ai_memory_workstream::{ManagedHarness, OpenCodeDialect, native_store_root};+use anyhow::{Context as _, Result, bail};++use super::user_service::{self, CommandRunner, ServiceChange, ServiceManager, ServiceUnit};+use super::{doctor, init, install_hooks, install_mcp, install_skills, run_autowire};+use crate::cli::{+ AgentChoice, DoctorArgs, HookInstallScope, InitArgs, InstallHooksArgs, InstallMcpArgs,+ InstallSkillsAgent, InstallSkillsArgs, InstallSkillsScope, McpClient, SetupArgs,+};+use crate::config::Config;+use crate::http_client::{ServerEndpoint, ServerProbe, probe_server};++/// How long `setup` waits for a service it just started to answer.+const SERVICE_READY_TIMEOUT: Duration = Duration::from_secs(30);++/// The MCP entry name every installer writes by default.+const ENTRY_NAME: &str = "ai-memory";++/// Harnesses that share a native store with another one, so finding the store+/// cannot tell them apart: OpenCode 2 shares OpenCode's, and the Kiro CLI v3+/// engine's store contains the v2 engine's. Wiring both would write two+/// dialects into one config, so only the stable one is detected; the other is+/// wired when named with `--agent`.+const EXPLICIT_ONLY: &[ManagedHarness] = &[ManagedHarness::OpenCode2, ManagedHarness::KiroV3];++/// What `setup` will do.+#[derive(Debug)]+struct SetupPlan {+ data_dir: PathBuf,+ config_path: PathBuf,+ /// No config file yet: `init` writes one (and mints the token when the+ /// data dir has no database either).+ fresh: bool,+ service: ServicePlan,+ agents: Vec<AgentPlan>,+ /// Agents came from detection, not `--agent`.+ detected: bool,+}++#[derive(Debug)]+enum ServicePlan {+ Install(ServiceUnit),+ Skip(String),+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+struct AgentPlan {+ agent: AgentChoice,+ mcp: Option<McpClient>,+ skills: InstallSkillsAgent,+}++impl AgentPlan {+ fn new(agent: AgentChoice) -> Self {+ Self {+ agent,+ mcp: install_hooks::mcp_client_for_agent(agent),+ skills: skills_for(agent),+ }+ }+}++/// The skill directory family an agent reads; agents without one of their+/// own read the cross-client `~/.agents/skills`.+fn skills_for(agent: AgentChoice) -> InstallSkillsAgent {+ match agent {+ AgentChoice::ClaudeCode => InstallSkillsAgent::ClaudeCode,+ AgentChoice::Grok => InstallSkillsAgent::Grok,+ AgentChoice::CopilotCli => InstallSkillsAgent::CopilotCli,+ AgentChoice::Devin => InstallSkillsAgent::Devin,+ AgentChoice::Hermes => InstallSkillsAgent::Hermes,+ _ => InstallSkillsAgent::Agents,+ }+}++/// The OpenCode major version an agent names outright, so neither installer+/// probes `opencode --version` and picks one dialect for both.+fn opencode_dialect(agent: AgentChoice) -> Option<OpenCodeDialect> {+ match agent {+ AgentChoice::OpenCode => Some(OpenCodeDialect::V1),+ AgentChoice::OpenCode2 => Some(OpenCodeDialect::V2),+ _ => None,+ }+}++/// Run `setup`.+///+/// # Errors+/// When the plan cannot be built, the operator declines it (or there is no+/// terminal to ask on and no `--yes`), or any step fails; the other steps+/// still run and the error counts the failures.+pub async fn run(config: &Config, args: SetupArgs, config_path: Option<&Path>) -> Result<()> {+ let captured = config.runtime_env.process_env().to_vec();+ let env = move |name: &str| -> Option<OsString> {+ captured+ .iter()+ .find(|(key, _)| key.as_os_str() == name)+ .map(|(_, value)| value.clone())+ };+ let home = super::run::native_home(config).context("locating your home directory")?;+ let exe = std::env::current_exe().context("locating the running ai-memory binary")?;+ let exe = std::fs::canonicalize(&exe).unwrap_or(exe);++ let written_config = init_config_path(config, config_path);+ let agents = if args.agents.is_empty() {+ detect_agents(+ &home,+ &|harness| doctor::relocated_session_dir_with(harness, &env),+ &|client| install_mcp::mcp_config_path_with(client, &env).ok(),+ )+ } else {+ dedup(args.agents.iter().copied())+ };+ let service = if args.no_service {+ ServicePlan::Skip("skipped (--no-service)".to_owned())+ } else {+ let spec = user_service::ServiceSpec {+ exe,+ data_dir: config.data_dir.clone(),+ config_path: written_config.clone(),+ home: home.clone(),+ xdg_config_home: env("XDG_CONFIG_HOME").map(PathBuf::from),+ };+ let reachable = matches!(+ probe_server(&ServerEndpoint::from_config_resolving_auth(config).await).await,+ ServerProbe::Reachable+ );+ plan_service(+ ServiceManager::current(),+ &spec,+ &config.server_url,+ reachable,+ )+ };+ let plan = SetupPlan {+ data_dir: config.data_dir.clone(),+ fresh: !written_config.exists(),+ config_path: written_config,+ service,+ agents: agents.into_iter().map(AgentPlan::new).collect(),+ detected: args.agents.is_empty(),+ };++ print_plan(&plan);+ if !args.yes {+ confirm()?;+ }+ execute(+ config,+ config_path,+ plan,+ &user_service::SystemRunner,+ SERVICE_READY_TIMEOUT,+ )+ .await+}++fn init_config_path(config: &Config, explicit: Option<&Path>) -> PathBuf {+ explicit.map_or_else(|| config.data_dir.join("config.toml"), Path::to_path_buf)+}++fn dedup(agents: impl Iterator<Item = AgentChoice>) -> Vec<AgentChoice> {+ let mut seen = Vec::new();+ for agent in agents {+ if !seen.contains(&agent) {+ seen.push(agent);+ }+ }+ seen+}++/// The agents to wire when none was named: every harness `doctor` scans whose+/// session store exists, or whose MCP config file does, under `home`.+fn detect_agents(+ home: &Path,+ session_dir_for: &dyn Fn(ManagedHarness) -> Option<PathBuf>,+ mcp_config_for: &dyn Fn(McpClient) -> Option<PathBuf>,+) -> Vec<AgentChoice> {+ let found = doctor::SCANNED_HARNESSES+ .iter()+ .copied()+ .filter(|harness| !EXPLICIT_ONLY.contains(harness))+ .filter_map(|harness| {+ let agent = run_autowire::agent_choice_for_harness(harness)?;+ let store = native_store_root(harness, home, session_dir_for(harness).as_deref());+ let config = install_hooks::mcp_client_for_agent(agent)+ .and_then(mcp_config_for)+ .is_some_and(|path| path.is_file());+ (store.is_dir() || config).then_some(agent)+ });+ dedup(found)+}++/// Decide the service step. A server already answering with no unit of ours+/// in place is left in charge (Docker, a packaged unit, a foreground+/// `serve`): a second server could not bind the port anyway.+fn plan_service(+ manager: Option<ServiceManager>,+ spec: &user_service::ServiceSpec,+ server_url: &str,+ reachable: bool,+) -> ServicePlan {+ let Some(manager) = manager else {+ return ServicePlan::Skip(+ "not supported on this platform (Windows has no service step); start the server \+ with `ai-memory serve --transport http` and see docs/windows.md"+ .to_owned(),+ );+ };+ if !super::hook_spool::is_loopback_url(server_url) {+ return ServicePlan::Skip(format!(+ "the configured server {server_url} is not on this machine; no local service"+ ));+ }+ match user_service::render(manager, spec) {+ Ok(unit) if reachable && !unit.path.exists() => ServicePlan::Skip(format!(+ "a server already answers at {server_url}; leaving it in charge (pass --no-service \+ to skip this check)"+ )),+ Ok(unit) => ServicePlan::Install(unit),+ Err(error) => ServicePlan::Skip(format!("cannot render the service: {error:#}")),+ }+}++fn print_plan(plan: &SetupPlan) {+ println!("ai-memory setup will:");+ if plan.fresh {+ println!(+ " - create the data dir {} and write {} (with a new root bearer token in \+ auth-tokens/default when the data dir is new)",+ plan.data_dir.display(),+ plan.config_path.display()+ );+ } else {+ println!(+ " - keep the existing install at {} ({})",+ plan.data_dir.display(),+ plan.config_path.display()+ );+ }+ match &plan.service {+ ServicePlan::Install(unit) => println!(+ " - install and start a {} at {}",+ unit.manager.describe(),+ unit.path.display()+ ),+ ServicePlan::Skip(reason) => println!(" - service: {reason}"),+ }+ if plan.agents.is_empty() {+ println!(+ " - wire no agent: none {}; name one with --agent <name>",+ if plan.detected {+ "was detected"+ } else {+ "was named"+ }+ );+ }+ for agent in &plan.agents {+ let name = agent.agent.kind().as_str();+ let mcp = if agent.mcp.is_some() {+ "MCP + hooks"+ } else {+ "hooks"+ };+ println!(+ " - wire {name}{}: {mcp} + skills",+ if plan.detected { " (detected)" } else { "" }+ );+ }+ println!(" - check /healthz, memory_status and doctor (read-only)");+}++/// Ask on a terminal; refuse without one.+fn confirm() -> Result<()> {+ if !std::io::stdin().is_terminal() {+ bail!(+ "nothing was changed: there is no terminal to confirm this plan on. Re-run \+ `ai-memory setup --yes` to apply it."+ );+ }+ print!("Proceed? [y/N] ");+ std::io::stdout().flush().ok();+ let mut answer = String::new();+ std::io::stdin()+ .lock()+ .read_line(&mut answer)+ .context("reading the answer")?;+ if matches!(answer.trim(), "y" | "Y" | "yes" | "YES" | "Yes") {+ Ok(())+ } else {+ bail!("nothing was changed")+ }+}++/// Apply the plan. Every step runs even when an earlier one failed, so the+/// report names every problem at once.+async fn execute(+ config: &Config,+ config_path: Option<&Path>,+ plan: SetupPlan,+ runner: &dyn CommandRunner,+ ready_timeout: Duration,+) -> Result<()> {+ let mut problems: Vec<String> = Vec::new();++ println!("\n== init");+ let outcome = init::initialize(config, &InitArgs { force: false }, config_path)?;+ let mut config = config.clone();+ if let Some(token) = outcome.root_token+ && config.auth.bearer_token.is_none()+ {+ config.auth.adopt_token_file(token.path, token.token);+ }+ println!(+ "config: {} {}",+ if outcome.config_written {+ "wrote"+ } else {+ "kept"+ },+ outcome.config_path.display()+ );++ println!("\n== service");+ let mut wait_for_server = false;+ match &plan.service {+ ServicePlan::Skip(reason) => println!("service: {reason}"),+ ServicePlan::Install(unit) => match user_service::install(unit, runner) {+ Ok(change) => {+ wait_for_server = change != ServiceChange::Unchanged;+ println!(+ "service: {} {}",+ match change {+ ServiceChange::Installed => "installed and started",+ ServiceChange::Updated => "updated and restarted",+ ServiceChange::Started => "started",+ ServiceChange::Unchanged => "already running from",+ },+ unit.path.display()+ );+ }+ Err(error) => problems.push(format!(+ "service: {error:#}. Start the server yourself with `ai-memory serve --transport \+ http`, or re-run with --no-service when it runs some other way."+ )),+ },+ }+ let endpoint = ServerEndpoint::from_config_resolving_auth(&config).await;+ if wait_for_server && !wait_until_reachable(&endpoint, ready_timeout).await {+ problems.push(format!(+ "service: the server did not answer at {} within {}s",+ endpoint.url,+ ready_timeout.as_secs()+ ));+ }++ let mut skills_done = BTreeSet::new();+ for agent in &plan.agents {+ println!("\n== {}", agent.agent.kind().as_str());+ for problem in wire_agent(&config, *agent, &mut skills_done) {+ problems.push(format!("{}: {problem}", agent.agent.kind().as_str()));+ }+ }++ println!("\n== self-check");+ for problem in self_check(&config, &endpoint).await {+ problems.push(format!("self-check: {problem}"));+ }++ println!();+ if config.auth.bearer_token.is_none() {+ println!("auth: none (loopback); run `ai-memory auth enable` to require a bearer token");+ } else {+ println!("auth: bearer token (owner-only file; never printed)");+ }+ if problems.is_empty() {+ println!(+ "ai-memory is set up. Restart your agents so they load the new hooks and MCP entry."+ );+ return Ok(());+ }+ for problem in &problems {+ eprintln!("problem: {problem}");+ }+ bail!(+ "setup finished with {} problem(s); fix them and re-run `ai-memory setup`",+ problems.len()+ )+}++async fn wait_until_reachable(endpoint: &ServerEndpoint, timeout: Duration) -> bool {+ let deadline = Instant::now() + timeout;+ loop {+ if matches!(probe_server(endpoint).await, ServerProbe::Reachable) {+ return true;+ }+ if Instant::now() >= deadline {+ return false;+ }+ tokio::time::sleep(Duration::from_millis(200)).await;+ }+}++/// `install-mcp`, `install-hooks` and `install-skills` for one agent, MCP+/// first so an OpenCode major-version move has one entry before the hook+/// installer reads it (the order `ai-memory run` auto-wire uses). Returns the+/// failures.+fn wire_agent(config: &Config, plan: AgentPlan, skills_done: &mut BTreeSet<String>) -> Vec<String> {+ let mut problems = Vec::new();+ let dialect = opencode_dialect(plan.agent);+ if let Some(client) = plan.mcp {+ if install_mcp::existing_entry_is_session_aware(client, None, ENTRY_NAME) {+ println!("mcp: keeping the existing session-aware entry");+ } else {+ let args = InstallMcpArgs {+ client,+ server_url: None,+ name: ENTRY_NAME.to_owned(),+ auth_token: None,+ apply: true,+ config_file: None,+ session_aware: false,+ flavor: None,+ token_env_var: false,+ stdio_bridge: false,+ };+ if let Err(error) = install_mcp::run_with_opencode_dialect(config, args, dialect) {+ problems.push(format!("install-mcp: {error:#}"));+ }+ }+ }+ let hooks = InstallHooksArgs {+ agent: plan.agent,+ hooks_dir: None,+ server_url: None,+ auth_token: None,+ as_user: None,+ apply: true,+ config_file: None,+ scope: HookInstallScope::Global,+ project_strategy: None,+ capture_assistant: false,+ capture_mode: None,+ no_capture_prompts: false,+ capture_prompts: false,+ profile: None,+ };+ if let Err(error) =+ install_hooks::run_with_opencode_dialect_and_mcp_path(config, hooks, dialect, None)+ {+ problems.push(format!("install-hooks: {error:#}"));+ }+ let skills_key = format!("{:?}", plan.skills);+ if skills_done.insert(skills_key) {+ let args = InstallSkillsArgs {+ scope: InstallSkillsScope::Global,+ agent: plan.skills,+ target_dir: None,+ print: false,+ force: false,+ };+ if let Err(error) = install_skills::run(config, args) {+ problems.push(format!("install-skills: {error:#}"));+ }+ }+ problems+}++/// `/healthz`, `memory_status` over MCP, and `doctor`; none of them writes a+/// file. Returns the failures.+async fn self_check(config: &Config, endpoint: &ServerEndpoint) -> Vec<String> {+ let mut problems = Vec::new();+ let healthz = endpoint.build_url("/healthz");+ match reqwest::Client::new()+ .get(&healthz)+ .timeout(Duration::from_secs(5))+ .send()+ .await+ {+ Ok(response) if response.status().is_success() => println!("healthz: ok ({healthz})"),+ Ok(response) => problems.push(format!("{healthz} answered {}", response.status())),+ Err(error) => {+ problems.push(format!("{healthz} did not answer: {error}"));+ // Nothing else can pass without a server.+ return problems;+ }+ }+ match memory_status(config).await {+ Ok(()) => println!("memory_status: ok"),+ Err(error) => problems.push(format!("memory_status: {error:#}")),+ }+ let doctor = DoctorArgs {+ workspace: None,+ project: None,+ since_days: 30,+ json: false,+ };+ if let Err(error) = doctor::run(config, doctor).await {+ problems.push(format!("doctor: {error:#}"));+ }+ problems+}++/// One `memory_status` call over the server's MCP endpoint, authenticated the+/// way `mcp-bridge` authenticates, so a refused credential shows here rather+/// than in the agent's first session.+async fn memory_status(config: &Config) -> Result<()> {+ use rmcp::ServiceExt as _;+ use rmcp::model::CallToolRequestParams;+ use rmcp::transport::StreamableHttpClientTransport;++ let url = install_mcp::mcp_server_url_from_base(&config.server_url);+ let transport = StreamableHttpClientTransport::from_config(super::mcp_bridge::upstream_config(+ &url,+ None,+ config.auth.bearer_token.as_deref(),+ )?);+ let client = ().serve(transport).await.with_context(|| format!("connecting to {url}"))?;+ let result = client+ .peer()+ .call_tool(CallToolRequestParams::new("memory_status"))+ .await;+ client.cancel().await.ok();+ let result = result.context("calling memory_status")?;+ if result.is_error == Some(true) {+ bail!("memory_status reported an error");+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn spec(home: &Path) -> user_service::ServiceSpec {+ user_service::ServiceSpec {+ exe: PathBuf::from("/opt/ai-memory/ai-memory"),+ data_dir: home.join("data"),+ config_path: home.join("data").join("config.toml"),+ home: home.to_path_buf(),+ xdg_config_home: None,+ }+ }++ #[test]+ fn detection_finds_harness_stores_and_mcp_configs_under_home() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ // Claude Code by its session store, Codex by its MCP config only.+ std::fs::create_dir_all(home.join(".claude").join("projects")).unwrap();+ let codex_config = home.join("codex-config.toml");+ std::fs::write(&codex_config, "").unwrap();+ let mcp = |client: McpClient| (client == McpClient::Codex).then(|| codex_config.clone());+ let found = detect_agents(home, &|_| None, &mcp);+ assert_eq!(found, vec![AgentChoice::ClaudeCode, AgentChoice::Codex]);+ }++ /// Control: an empty home detects nothing, and a named-but-missing MCP+ /// config path does not count as present.+ #[test]+ fn an_empty_home_detects_nothing() {+ let tmp = tempfile::tempdir().unwrap();+ let missing = tmp.path().join("nope.json");+ let found = detect_agents(tmp.path(), &|_| None, &|_| Some(missing.clone()));+ assert!(found.is_empty(), "{found:?}");+ }++ /// OpenCode 2 shares OpenCode's store; detection must not wire both+ /// dialects into the one config file.+ #[test]+ fn a_shared_store_detects_only_the_stable_harness() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ std::fs::create_dir_all(home.join(".local/share/opencode")).unwrap();+ std::fs::create_dir_all(home.join(".kiro/sessions/cli")).unwrap();+ let found = detect_agents(home, &|_| None, &|_| None);+ assert_eq!(found, vec![AgentChoice::OpenCode, AgentChoice::KiroCli]);+ }++ /// A relocated store (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, …) is looked for+ /// where the relocation points, not under the home.+ #[test]+ fn detection_follows_a_relocated_store() {+ let tmp = tempfile::tempdir().unwrap();+ let elsewhere = tmp.path().join("relocated-claude");+ std::fs::create_dir_all(&elsewhere).unwrap();+ let relocate = |harness: ManagedHarness| {+ (harness == ManagedHarness::Claude).then(|| elsewhere.clone())+ };+ let found = detect_agents(&tmp.path().join("home"), &relocate, &|_| None);+ assert_eq!(found, vec![AgentChoice::ClaudeCode]);+ }++ #[test]+ fn skills_go_to_each_agents_own_directory_or_the_shared_one() {+ assert_eq!(+ skills_for(AgentChoice::ClaudeCode),+ InstallSkillsAgent::ClaudeCode+ );+ assert_eq!(skills_for(AgentChoice::Grok), InstallSkillsAgent::Grok);+ assert_eq!(+ skills_for(AgentChoice::CopilotCli),+ InstallSkillsAgent::CopilotCli+ );+ assert_eq!(skills_for(AgentChoice::Codex), InstallSkillsAgent::Agents);+ assert_eq!(+ skills_for(AgentChoice::KimiCode),+ InstallSkillsAgent::Agents+ );+ }++ #[test]+ fn named_agents_are_deduplicated_in_order() {+ assert_eq!(+ dedup(+ [+ AgentChoice::Codex,+ AgentChoice::ClaudeCode,+ AgentChoice::Codex+ ]+ .into_iter()+ ),+ vec![AgentChoice::Codex, AgentChoice::ClaudeCode]+ );+ }++ #[test]+ fn windows_has_no_service_step_and_says_so() {+ let tmp = tempfile::tempdir().unwrap();+ let ServicePlan::Skip(reason) =+ plan_service(None, &spec(tmp.path()), "http://127.0.0.1:49374", false)+ else {+ panic!("expected a skip");+ };+ assert!(reason.contains("Windows"), "{reason}");+ }++ #[test]+ fn a_remote_server_gets_no_local_service() {+ let tmp = tempfile::tempdir().unwrap();+ let plan = plan_service(+ Some(ServiceManager::SystemdUser),+ &spec(tmp.path()),+ "https://memory.example.com",+ true,+ );+ assert!(+ matches!(plan, ServicePlan::Skip(reason) if reason.contains("not on this machine"))+ );+ }++ /// A server that already answers with no unit of ours in place is not+ /// ours to replace; once our unit exists, a running server is the one it+ /// started and the unit is managed as usual.+ #[test]+ fn an_answering_server_without_our_unit_is_left_in_charge() {+ let tmp = tempfile::tempdir().unwrap();+ let spec = spec(tmp.path());+ let url = "http://127.0.0.1:49374";+ let plan = plan_service(Some(ServiceManager::SystemdUser), &spec, url, true);+ assert!(matches!(plan, ServicePlan::Skip(reason) if reason.contains("already answers")));++ let ServicePlan::Install(unit) =+ plan_service(Some(ServiceManager::SystemdUser), &spec, url, false)+ else {+ panic!("expected an install when nothing answers");+ };+ std::fs::create_dir_all(unit.path.parent().unwrap()).unwrap();+ std::fs::write(&unit.path, &unit.contents).unwrap();+ assert!(matches!(+ plan_service(Some(ServiceManager::SystemdUser), &spec, url, true),+ ServicePlan::Install(_)+ ));+ }+}diff --git a/crates/ai-memory-cli/src/commands/user_service.rs b/crates/ai-memory-cli/src/commands/user_service.rsnew file mode 100644index 00000000..bbc3da21--- /dev/null+++ b/crates/ai-memory-cli/src/commands/user_service.rs@@ -0,0 +1,691 @@+//! The per-user service `ai-memory setup` installs: a systemd `--user` unit on+//! Linux, a launchd LaunchAgent on macOS.+//!+//! Both are rendered from the packaged templates+//! (`packaging/systemd/ai-memory-user.service` and+//! `packaging/launchd/com.github.akitaonrails.ai-memory.plist`), with the+//! running binary, the data dir and the config file `setup` used substituted+//! in. Spelling the data dir and config out matters: a server started against+//! another config would not require the token `init` recorded there, while the+//! hooks and MCP entries `setup` writes would present it.+//!+//! The service manager is driven through [`CommandRunner`], so tests render+//! into a temp dir and record the `systemctl` / `launchctl` calls instead of+//! touching a real user session. Windows has no service step.++use std::path::{Path, PathBuf};++use anyhow::{Context as _, Result, bail};++/// The systemd user unit template the AUR and RPM packages ship.+const SYSTEMD_USER_TEMPLATE: &str =+ include_str!("../../../../packaging/systemd/ai-memory-user.service");+/// The macOS LaunchAgent template `docs/macos.md` and the menu bar app use.+const LAUNCHD_TEMPLATE: &str =+ include_str!("../../../../packaging/launchd/com.github.akitaonrails.ai-memory.plist");++/// The unit name, the same one the packages install, so a user unit written+/// here takes precedence over a packaged `/usr/lib/systemd/user` copy instead+/// of starting a second server on the same port.+pub(crate) const SYSTEMD_UNIT_NAME: &str = "ai-memory.service";+/// The LaunchAgent label, shared with the macOS menu bar app.+pub(crate) const LAUNCHD_LABEL: &str = "com.github.akitaonrails.ai-memory";++/// Template text each renderer replaces; a template edited so one of them no+/// longer matches fails the render rather than shipping a unit that silently+/// keeps the packaged defaults.+const SYSTEMD_BIN: &str = "/usr/bin/ai-memory";+const SYSTEMD_DATA_DIR: &str = "%h/.local/share/ai-memory";+const SYSTEMD_CONFIG: &str = "%h/.config/ai-memory/config.toml";+const LAUNCHD_BIN: &str = "<string>__AI_MEMORY_BIN__</string>";+const LAUNCHD_HOME: &str = "<string>__HOME__/";++/// Which service manager this platform uses.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ServiceManager {+ SystemdUser,+ Launchd,+}++impl ServiceManager {+ /// The manager for the platform this binary was built for; `None` on+ /// Windows and anything else without a supported per-user manager.+ pub(crate) const fn current() -> Option<Self> {+ if cfg!(target_os = "linux") {+ Some(Self::SystemdUser)+ } else if cfg!(target_os = "macos") {+ Some(Self::Launchd)+ } else {+ None+ }+ }++ pub(crate) const fn describe(self) -> &'static str {+ match self {+ Self::SystemdUser => "systemd user unit",+ Self::Launchd => "launchd LaunchAgent",+ }+ }+}++/// What the rendered service runs.+#[derive(Debug, Clone)]+pub(crate) struct ServiceSpec {+ /// Absolute path of the `ai-memory` binary to run.+ pub(crate) exe: PathBuf,+ pub(crate) data_dir: PathBuf,+ pub(crate) config_path: PathBuf,+ /// The operator's home, where the unit or LaunchAgent is installed.+ pub(crate) home: PathBuf,+ /// `$XDG_CONFIG_HOME`, when set (systemd only).+ pub(crate) xdg_config_home: Option<PathBuf>,+}++/// A rendered service file and where it goes.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ServiceUnit {+ pub(crate) manager: ServiceManager,+ pub(crate) path: PathBuf,+ pub(crate) contents: String,+}++impl ServiceUnit {+ /// Whether the file on disk already holds exactly this unit.+ pub(crate) fn is_current(&self) -> bool {+ std::fs::read_to_string(&self.path).is_ok_and(|text| text == self.contents)+ }+}++/// Render the unit for `manager`.+///+/// # Errors+/// A path that is relative or holds a control character (which no unit+/// syntax can carry safely), or a template that no longer has the text the+/// renderer replaces.+pub(crate) fn render(manager: ServiceManager, spec: &ServiceSpec) -> Result<ServiceUnit> {+ for (what, path) in [+ ("binary", &spec.exe),+ ("data dir", &spec.data_dir),+ ("config file", &spec.config_path),+ ("home", &spec.home),+ ] {+ checked_path(what, path)?;+ }+ match manager {+ ServiceManager::SystemdUser => render_systemd(spec),+ ServiceManager::Launchd => render_launchd(spec),+ }+}++fn checked_path<'a>(what: &str, path: &'a Path) -> Result<&'a str> {+ let text = path+ .to_str()+ .with_context(|| format!("the {what} path {} is not UTF-8", path.display()))?;+ if !path.is_absolute() {+ bail!("the {what} path {text} is not absolute");+ }+ if text.chars().any(char::is_control) {+ bail!("the {what} path {text:?} contains a control character");+ }+ Ok(text)+}++/// One `ExecStart=` word: double-quoted, with `\` and `"` escaped for the+/// unit parser, `%` doubled so it is no specifier, and `$` doubled so it is+/// no variable expansion.+fn systemd_word(text: &str) -> String {+ let mut out = String::with_capacity(text.len() + 2);+ out.push('"');+ for ch in text.chars() {+ match ch {+ '\\' => out.push_str("\\\\"),+ '"' => out.push_str("\\\""),+ '%' => out.push_str("%%"),+ '$' => out.push_str("$$"),+ other => out.push(other),+ }+ }+ out.push('"');+ out+}++fn render_systemd(spec: &ServiceSpec) -> Result<ServiceUnit> {+ let exec = SYSTEMD_USER_TEMPLATE+ .lines()+ .find(|line| line.starts_with("ExecStart="))+ .context("the packaged systemd user unit has no ExecStart line")?;+ for needle in [SYSTEMD_BIN, SYSTEMD_DATA_DIR, SYSTEMD_CONFIG] {+ if !exec.contains(needle) {+ bail!("the packaged systemd user unit's ExecStart no longer contains {needle}");+ }+ }+ let rendered_exec = exec+ .replacen(+ SYSTEMD_BIN,+ &systemd_word(checked_path("binary", &spec.exe)?),+ 1,+ )+ .replacen(+ SYSTEMD_DATA_DIR,+ &systemd_word(checked_path("data dir", &spec.data_dir)?),+ 1,+ )+ .replacen(+ SYSTEMD_CONFIG,+ &systemd_word(checked_path("config file", &spec.config_path)?),+ 1,+ );+ let body = SYSTEMD_USER_TEMPLATE.replacen(exec, &rendered_exec, 1);+ let contents = format!(+ "# Written by `ai-memory setup` from packaging/systemd/ai-memory-user.service.\n\+ # Re-run `ai-memory setup` instead of editing; it rewrites this file.\n{body}"+ );+ let config_home = spec+ .xdg_config_home+ .clone()+ .filter(|dir| dir.is_absolute())+ .unwrap_or_else(|| spec.home.join(".config"));+ Ok(ServiceUnit {+ manager: ServiceManager::SystemdUser,+ path: config_home+ .join("systemd")+ .join("user")+ .join(SYSTEMD_UNIT_NAME),+ contents,+ })+}++fn xml_text(text: &str) -> String {+ text.replace('&', "&")+ .replace('<', "<")+ .replace('>', ">")+ .replace('"', """)+ .replace('\'', "'")+}++fn render_launchd(spec: &ServiceSpec) -> Result<ServiceUnit> {+ if !LAUNCHD_TEMPLATE.contains(LAUNCHD_BIN) || !LAUNCHD_TEMPLATE.contains(LAUNCHD_HOME) {+ bail!("the packaged LaunchAgent no longer has the placeholders `setup` fills in");+ }+ let string = |text: &str| format!("<string>{}</string>", xml_text(text));+ // The template leaves the data dir and config to the macOS defaults; pass+ // them so the agent serves the install `setup` initialised, whatever+ // `--data-dir` / `AI_MEMORY_DATA_DIR` / `--config` chose.+ let program = [+ string(checked_path("binary", &spec.exe)?),+ string("--data-dir"),+ string(checked_path("data dir", &spec.data_dir)?),+ string("--config"),+ string(checked_path("config file", &spec.config_path)?),+ ]+ .join("\n ");+ let home = format!("<string>{}/", xml_text(checked_path("home", &spec.home)?));+ let contents = LAUNCHD_TEMPLATE+ .replacen(LAUNCHD_BIN, &program, 1)+ .replace(LAUNCHD_HOME, &home);+ if contents.contains("<string>__") {+ bail!("the packaged LaunchAgent has a placeholder `setup` does not fill in");+ }+ Ok(ServiceUnit {+ manager: ServiceManager::Launchd,+ path: spec+ .home+ .join("Library")+ .join("LaunchAgents")+ .join(format!("{LAUNCHD_LABEL}.plist")),+ contents,+ })+}++/// The directory launchd writes the agent's logs to; launchd creates the+/// files but not the directory.+pub(crate) fn launchd_log_dir(home: &Path) -> PathBuf {+ home.join("Library").join("Logs").join("ai-memory")+}++/// The result of one service-manager command.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct CommandOutcome {+ pub(crate) success: bool,+ pub(crate) stdout: String,+ pub(crate) stderr: String,+}++/// Runs `systemctl` / `launchctl` / `id`. Injectable so tests never reach a+/// real service manager.+pub(crate) trait CommandRunner {+ /// Run `program` with `args`; an `Err` means it could not be started.+ fn run(&self, program: &str, args: &[&str]) -> Result<CommandOutcome>;+}++/// Runs commands for real, resolved through `PATH`.+pub(crate) struct SystemRunner;++impl CommandRunner for SystemRunner {+ fn run(&self, program: &str, args: &[&str]) -> Result<CommandOutcome> {+ let output = std::process::Command::new(program)+ .args(args)+ .stdin(std::process::Stdio::null())+ .output()+ .with_context(|| format!("running {program}"))?;+ Ok(CommandOutcome {+ success: output.status.success(),+ stdout: String::from_utf8_lossy(&output.stdout).into_owned(),+ stderr: String::from_utf8_lossy(&output.stderr).into_owned(),+ })+ }+}++/// What installing the service did.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ServiceChange {+ /// The unit was written for the first time and the service started.+ Installed,+ /// The unit changed and the service was restarted on it.+ Updated,+ /// The unit was current but the service was not running; it was started.+ Started,+ /// The unit was current and the service already running: nothing done.+ Unchanged,+}++/// Write `unit` when it differs from the file on disk, then make sure the+/// service is enabled and running on it. A current unit whose service already+/// runs is left alone, so a second `setup` changes nothing.+///+/// # Errors+/// A failed write, or a service-manager command that could not be run or+/// failed; the error carries its output.+pub(crate) fn install(unit: &ServiceUnit, runner: &dyn CommandRunner) -> Result<ServiceChange> {+ let existed = unit.path.exists();+ let current = unit.is_current();+ let running = match unit.manager {+ ServiceManager::SystemdUser => systemd_running(runner),+ ServiceManager::Launchd => launchd_loaded(runner, &launchd_domain(runner)?),+ };+ if current && running {+ return Ok(ServiceChange::Unchanged);+ }+ if !current {+ write_unit(unit)?;+ }+ match unit.manager {+ ServiceManager::SystemdUser => start_systemd(runner)?,+ ServiceManager::Launchd => start_launchd(unit, runner, running)?,+ }+ Ok(match (existed, current) {+ (false, _) => ServiceChange::Installed,+ (true, false) => ServiceChange::Updated,+ (true, true) => ServiceChange::Started,+ })+}++fn write_unit(unit: &ServiceUnit) -> Result<()> {+ if let Some(parent) = unit.path.parent() {+ std::fs::create_dir_all(parent)+ .with_context(|| format!("creating {}", parent.display()))?;+ }+ ai_memory_wiki::write_atomic(&unit.path, unit.contents.as_bytes())+ .with_context(|| format!("writing {}", unit.path.display()))?;+ // No secret lives in a unit; keep the conventional mode, since launchd+ // refuses a LaunchAgent other users can write and systemd only reads it.+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::set_permissions(&unit.path, std::fs::Permissions::from_mode(0o644))+ .with_context(|| format!("setting the mode of {}", unit.path.display()))?;+ }+ Ok(())+}++fn require(runner: &dyn CommandRunner, program: &str, args: &[&str]) -> Result<CommandOutcome> {+ let outcome = runner.run(program, args)?;+ if !outcome.success {+ bail!(+ "`{program} {}` failed: {}",+ args.join(" "),+ outcome.stderr.trim()+ );+ }+ Ok(outcome)+}++fn succeeds(runner: &dyn CommandRunner, program: &str, args: &[&str]) -> bool {+ runner+ .run(program, args)+ .is_ok_and(|outcome| outcome.success)+}++fn systemd_running(runner: &dyn CommandRunner) -> bool {+ succeeds(+ runner,+ "systemctl",+ &["--user", "is-active", "--quiet", SYSTEMD_UNIT_NAME],+ ) && succeeds(+ runner,+ "systemctl",+ &["--user", "is-enabled", "--quiet", SYSTEMD_UNIT_NAME],+ )+}++fn start_systemd(runner: &dyn CommandRunner) -> Result<()> {+ require(runner, "systemctl", &["--user", "daemon-reload"])?;+ require(+ runner,+ "systemctl",+ &["--user", "enable", SYSTEMD_UNIT_NAME],+ )?;+ require(+ runner,+ "systemctl",+ &["--user", "restart", SYSTEMD_UNIT_NAME],+ )?;+ Ok(())+}++fn launchd_domain(runner: &dyn CommandRunner) -> Result<String> {+ let uid = require(runner, "id", &["-u"])?.stdout.trim().to_owned();+ if uid.is_empty() || !uid.chars().all(|c| c.is_ascii_digit()) {+ bail!("`id -u` printed {uid:?}, not a user id");+ }+ Ok(format!("gui/{uid}"))+}++fn launchd_loaded(runner: &dyn CommandRunner, domain: &str) -> bool {+ succeeds(+ runner,+ "launchctl",+ &["print", &format!("{domain}/{LAUNCHD_LABEL}")],+ )+}++fn start_launchd(unit: &ServiceUnit, runner: &dyn CommandRunner, loaded: bool) -> Result<()> {+ let domain = launchd_domain(runner)?;+ if let Some(home) = unit+ .path+ .parent()+ .and_then(Path::parent)+ .and_then(Path::parent)+ {+ let logs = launchd_log_dir(home);+ std::fs::create_dir_all(&logs).with_context(|| format!("creating {}", logs.display()))?;+ }+ if loaded {+ require(+ runner,+ "launchctl",+ &["bootout", &format!("{domain}/{LAUNCHD_LABEL}")],+ )?;+ }+ let plist = unit.path.to_string_lossy();+ require(runner, "launchctl", &["bootstrap", &domain, &plist])?;+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::cell::RefCell;++ /// Records every call and answers from a script: the first matching+ /// `(program, first args)` prefix wins, anything else succeeds.+ #[derive(Default)]+ struct FakeRunner {+ calls: RefCell<Vec<String>>,+ failing: Vec<&'static str>,+ stdout: Vec<(&'static str, &'static str)>,+ }++ impl CommandRunner for FakeRunner {+ fn run(&self, program: &str, args: &[&str]) -> Result<CommandOutcome> {+ let line = format!("{program} {}", args.join(" "));+ self.calls.borrow_mut().push(line.clone());+ let success = !self.failing.iter().any(|prefix| line.starts_with(prefix));+ let stdout = self+ .stdout+ .iter()+ .find(|(prefix, _)| line.starts_with(prefix))+ .map_or_else(String::new, |(_, out)| (*out).to_owned());+ Ok(CommandOutcome {+ success,+ stdout,+ stderr: if success {+ String::new()+ } else {+ "boom".into()+ },+ })+ }+ }++ fn spec(root: &Path) -> ServiceSpec {+ ServiceSpec {+ exe: root.join("bin").join("ai-memory"),+ data_dir: root.join("data"),+ config_path: root.join("data").join("config.toml"),+ home: root.join("home"),+ xdg_config_home: None,+ }+ }++ fn exec_line(unit: &ServiceUnit) -> String {+ unit.contents+ .lines()+ .find(|line| line.starts_with("ExecStart="))+ .unwrap()+ .to_owned()+ }++ #[test]+ fn the_systemd_unit_runs_this_binary_on_this_install() {+ let root = Path::new("/srv/u");+ let unit = render(ServiceManager::SystemdUser, &spec(root)).unwrap();+ assert_eq!(+ unit.path,+ Path::new("/srv/u/home/.config/systemd/user/ai-memory.service")+ );+ assert_eq!(+ exec_line(&unit),+ "ExecStart=\"/srv/u/bin/ai-memory\" --data-dir \"/srv/u/data\" --config \+ \"/srv/u/data/config.toml\" serve --transport http --enable-web"+ );+ // Everything else is the packaged unit, untouched.+ for line in SYSTEMD_USER_TEMPLATE+ .lines()+ .filter(|line| !line.starts_with("ExecStart="))+ {+ assert!(unit.contents.contains(line), "lost template line {line}");+ }+ }++ #[test]+ fn the_systemd_unit_honours_an_absolute_xdg_config_home_only() {+ let mut spec = spec(Path::new("/srv/u"));+ spec.xdg_config_home = Some(PathBuf::from("/srv/xdg"));+ let unit = render(ServiceManager::SystemdUser, &spec).unwrap();+ assert_eq!(+ unit.path,+ Path::new("/srv/xdg/systemd/user/ai-memory.service")+ );+ spec.xdg_config_home = Some(PathBuf::from("relative/xdg"));+ let unit = render(ServiceManager::SystemdUser, &spec).unwrap();+ assert!(unit.path.starts_with("/srv/u/home/.config"));+ }++ /// A path with a space, a quote, a specifier and a variable must reach the+ /// server as one literal argument, never as a split word, a `%h`+ /// expansion or an environment lookup.+ #[test]+ fn hostile_paths_are_quoted_as_single_literal_words() {+ let mut spec = spec(Path::new("/srv/u"));+ spec.data_dir = PathBuf::from("/srv/my data/%h/$HOME/\"q\"/back\\slash");+ let unit = render(ServiceManager::SystemdUser, &spec).unwrap();+ assert!(+ exec_line(&unit).contains(+ "--data-dir \"/srv/my data/%%h/$$HOME/\\\"q\\\"/back\\\\slash\" --config"+ ),+ "{}",+ exec_line(&unit)+ );+ }++ #[test]+ fn control_characters_and_relative_paths_are_refused() {+ let mut bad = spec(Path::new("/srv/u"));+ bad.data_dir = PathBuf::from("/srv/u/data\nExecStartPre=/bin/sh -c evil");+ for manager in [ServiceManager::SystemdUser, ServiceManager::Launchd] {+ let err = render(manager, &bad).unwrap_err();+ assert!(format!("{err:#}").contains("control character"), "{err:#}");+ }+ let mut relative = spec(Path::new("/srv/u"));+ relative.exe = PathBuf::from("bin/ai-memory");+ assert!(render(ServiceManager::SystemdUser, &relative).is_err());+ }++ #[test]+ fn the_launch_agent_fills_every_placeholder_and_escapes_xml() {+ let mut spec = spec(Path::new("/Users/a"));+ spec.data_dir = PathBuf::from("/Users/a/<x>&y");+ let unit = render(ServiceManager::Launchd, &spec).unwrap();+ assert_eq!(+ unit.path,+ Path::new("/Users/a/home/Library/LaunchAgents/com.github.akitaonrails.ai-memory.plist")+ );+ assert!(+ unit.contents+ .contains("<string>/Users/a/bin/ai-memory</string>")+ );+ assert!(unit.contents.contains(+ "<string>--data-dir</string>\n <string>/Users/a/<x>&y</string>"+ ));+ assert!(+ unit.contents+ .contains("<string>/Users/a/home/Library/Logs/ai-memory/stdout.log</string>")+ );+ assert!(!unit.contents.contains("<string>__"));+ assert!(unit.contents.contains("<string>serve</string>"));+ }++ #[test]+ fn a_first_systemd_install_writes_the_unit_and_starts_it() {+ let tmp = tempfile::tempdir().unwrap();+ let unit = render(ServiceManager::SystemdUser, &spec(tmp.path())).unwrap();+ let runner = FakeRunner {+ failing: vec!["systemctl --user is-active"],+ ..FakeRunner::default()+ };+ assert_eq!(install(&unit, &runner).unwrap(), ServiceChange::Installed);+ assert!(unit.is_current());+ assert_eq!(+ runner.calls.borrow().clone(),+ vec![+ "systemctl --user is-active --quiet ai-memory.service",+ "systemctl --user daemon-reload",+ "systemctl --user enable ai-memory.service",+ "systemctl --user restart ai-memory.service",+ ]+ );+ }++ /// The idempotence contract: a current unit with a running service makes+ /// no write and no state-changing call.+ #[test]+ fn a_current_running_systemd_unit_is_left_alone() {+ let tmp = tempfile::tempdir().unwrap();+ let unit = render(ServiceManager::SystemdUser, &spec(tmp.path())).unwrap();+ write_unit(&unit).unwrap();+ let before = std::fs::metadata(&unit.path).unwrap().modified().unwrap();+ let runner = FakeRunner::default();+ assert_eq!(install(&unit, &runner).unwrap(), ServiceChange::Unchanged);+ assert_eq!(+ std::fs::metadata(&unit.path).unwrap().modified().unwrap(),+ before+ );+ assert!(+ runner+ .calls+ .borrow()+ .iter()+ .all(|call| call.contains("is-active") || call.contains("is-enabled")),+ "{:?}",+ runner.calls.borrow()+ );+ }++ #[test]+ fn a_changed_unit_is_rewritten_and_restarted() {+ let tmp = tempfile::tempdir().unwrap();+ let unit = render(ServiceManager::SystemdUser, &spec(tmp.path())).unwrap();+ std::fs::create_dir_all(unit.path.parent().unwrap()).unwrap();+ std::fs::write(&unit.path, "stale").unwrap();+ let runner = FakeRunner::default();+ assert_eq!(install(&unit, &runner).unwrap(), ServiceChange::Updated);+ assert!(unit.is_current());+ assert!(+ runner+ .calls+ .borrow()+ .contains(&"systemctl --user restart ai-memory.service".to_owned())+ );+ }++ #[test]+ fn a_failing_service_manager_is_an_error_with_its_output() {+ let tmp = tempfile::tempdir().unwrap();+ let unit = render(ServiceManager::SystemdUser, &spec(tmp.path())).unwrap();+ let runner = FakeRunner {+ failing: vec!["systemctl"],+ ..FakeRunner::default()+ };+ let err = install(&unit, &runner).unwrap_err();+ assert!(+ format!("{err:#}").contains("daemon-reload` failed: boom"),+ "{err:#}"+ );+ }++ #[test]+ fn a_launch_agent_is_bootstrapped_into_the_gui_domain() {+ let tmp = tempfile::tempdir().unwrap();+ let unit = render(ServiceManager::Launchd, &spec(tmp.path())).unwrap();+ let runner = FakeRunner {+ failing: vec!["launchctl print"],+ stdout: vec![("id -u", "501\n")],+ ..FakeRunner::default()+ };+ assert_eq!(install(&unit, &runner).unwrap(), ServiceChange::Installed);+ let plist = unit.path.to_string_lossy().into_owned();+ assert_eq!(+ runner.calls.borrow().clone(),+ vec![+ "id -u".to_owned(),+ "launchctl print gui/501/com.github.akitaonrails.ai-memory".to_owned(),+ "id -u".to_owned(),+ format!("launchctl bootstrap gui/501 {plist}"),+ ]+ );+ assert!(launchd_log_dir(&tmp.path().join("home")).is_dir());++ // Changed while loaded: booted out first, then bootstrapped again.+ std::fs::write(&unit.path, "stale").unwrap();+ let runner = FakeRunner {+ stdout: vec![("id -u", "501\n")],+ ..FakeRunner::default()+ };+ assert_eq!(install(&unit, &runner).unwrap(), ServiceChange::Updated);+ assert!(+ runner.calls.borrow().contains(+ &"launchctl bootout gui/501/com.github.akitaonrails.ai-memory".to_owned()+ )+ );+ }++ #[test]+ fn a_non_numeric_uid_is_refused() {+ let runner = FakeRunner {+ stdout: vec![("id -u", "501; rm -rf ~\n")],+ ..FakeRunner::default()+ };+ assert!(launchd_domain(&runner).is_err());+ }+}diff --git a/crates/ai-memory-cli/src/lib.rs b/crates/ai-memory-cli/src/lib.rsindex 42d84f01..45e4e25b 100644--- a/crates/ai-memory-cli/src/lib.rs+++ b/crates/ai-memory-cli/src/lib.rs@@ -85,6 +85,7 @@ pub async fn run() -> Result<()> {match command {Command::Init(args) => commands::init::run(&config, args, config_path.as_deref()),+ Command::Setup(args) => commands::setup::run(&config, args, config_path.as_deref()).await,Command::Status(args) => commands::status::run(&config, args).await,Command::ListProjects(args) => commands::list_projects::run(&config, args).await,Command::Doctor(args) => commands::doctor::run(&config, args).await,diff --git a/crates/ai-memory-cli/tests/suite/install_script.rs b/crates/ai-memory-cli/tests/suite/install_script.rsnew file mode 100644index 00000000..857cfa8b--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/install_script.rs@@ -0,0 +1,386 @@+//! `install.sh` against a fake release served over local HTTP.+//!+//! The script must install a verified release under a temp home and must+//! refuse, before unpacking anything, a checksum mismatch, a missing or+//! foreign checksum file, and an archive with an escaping path. A copy cut+//! short in transit must run nothing.++#![cfg(unix)]++use std::io::{BufRead as _, BufReader, Read as _, Write as _};+use std::net::TcpListener;+use std::path::{Path, PathBuf};+use std::process::{Command, Output, Stdio};+use std::sync::{Arc, Mutex};++use sha2::{Digest as _, Sha256};++const TARGET: &str = "linux-x86_64";+const ASSET: &str = "ai-memory-linux-x86_64.tar.gz";++fn script() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../install.sh")+}++/// Serves files from `root` over HTTP/1.0, 404 for anything missing, and+/// records each request path.+struct Release {+ root: PathBuf,+ base: String,+ requests: Arc<Mutex<Vec<String>>>,+}++impl Release {+ fn serve(root: &Path) -> Self {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let base = format!("http://{}/releases", listener.local_addr().unwrap());+ let requests = Arc::new(Mutex::new(Vec::new()));+ let seen = requests.clone();+ let files = root.to_path_buf();+ std::thread::spawn(move || {+ for mut stream in listener.incoming().flatten() {+ let mut line = String::new();+ if BufReader::new(&mut stream).read_line(&mut line).is_err() {+ continue;+ }+ let path = line.split_whitespace().nth(1).unwrap_or("/").to_owned();+ seen.lock().unwrap().push(path.clone());+ let local = files.join(path.trim_start_matches('/'));+ let reply = match std::fs::read(&local) {+ Ok(body) if !path.contains("..") => {+ let mut reply = format!(+ "HTTP/1.0 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",+ body.len()+ )+ .into_bytes();+ reply.extend(body);+ reply+ }+ _ => {+ b"HTTP/1.0 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"+ .to_vec()+ }+ };+ let _ = stream.write_all(&reply);+ }+ });+ Self {+ root: root.to_path_buf(),+ base,+ requests,+ }+ }++ fn latest(&self) -> PathBuf {+ let dir = self.root.join("releases/latest/download");+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ /// Publish `archive` with a correct `.sha256` sidecar.+ fn publish(&self, archive: &[u8]) {+ std::fs::write(self.latest().join(ASSET), archive).unwrap();+ let sum = format!("{:x}", Sha256::digest(archive));+ self.publish_sidecar(&format!("{sum} {ASSET}\n"));+ }++ fn publish_sidecar(&self, text: &str) {+ std::fs::write(self.latest().join(format!("{ASSET}.sha256")), text).unwrap();+ }+}++/// A release archive laid out like `release.yml` builds it, with a stub+/// binary that answers `--version`.+fn release_archive(extra: &[(&str, &[u8])]) -> Vec<u8> {+ let mut builder = tar::Builder::new(flate2::write::GzEncoder::new(+ Vec::new(),+ flate2::Compression::fast(),+ ));+ let mut add = |name: &str, body: &[u8], mode: u32| {+ let mut header = tar::Header::new_gnu();+ let bytes = name.as_bytes();+ // Written raw so a test can plant a name `set_path` would refuse.+ header.as_old_mut().name[..bytes.len()].copy_from_slice(bytes);+ header.set_size(body.len() as u64);+ header.set_mode(mode);+ header.set_entry_type(tar::EntryType::Regular);+ header.set_cksum();+ builder.append(&header, body).unwrap();+ };+ add(+ "ai-memory",+ b"#!/bin/sh\necho 'ai-memory 0.0.0-install-test'\n",+ 0o755,+ );+ add("hooks/claude-code/stop.sh", b"#!/bin/sh\n", 0o755);+ for (name, body) in extra {+ add(name, body, 0o644);+ }+ builder.into_inner().unwrap().finish().unwrap()+}++struct Home {+ _tmp: tempfile::TempDir,+ root: PathBuf,+ home: PathBuf,+}++impl Home {+ fn new() -> Self {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path().to_path_buf();+ let home = root.join("home");+ std::fs::create_dir_all(&home).unwrap();+ Self {+ _tmp: tmp,+ root,+ home,+ }+ }++ fn link(&self) -> PathBuf {+ self.home.join(".local/bin/ai-memory")+ }++ fn lib(&self) -> PathBuf {+ self.home.join(".local/lib/ai-memory")+ }++ fn command(&self, release: &Release) -> Command {+ let mut cmd = Command::new("sh");+ for (key, _) in std::env::vars_os() {+ if key.to_string_lossy().starts_with("AI_MEMORY_") {+ cmd.env_remove(key);+ }+ }+ cmd.env("HOME", &self.home)+ .env("TMPDIR", &self.root)+ .env("AI_MEMORY_RELEASE_BASE_URL", &release.base)+ .env("AI_MEMORY_INSTALL_TARGET", TARGET)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ cmd+ }++ fn install(&self, release: &Release) -> Output {+ self.command(release).arg(script()).output().unwrap()+ }++ /// `curl … | sh`: the script arrives on stdin.+ fn pipe(&self, release: &Release, body: &[u8]) -> Output {+ let mut child = self.command(release).stdin(Stdio::piped()).spawn().unwrap();+ child.stdin.take().unwrap().write_all(body).unwrap();+ child.wait_with_output().unwrap()+ }++ /// Nothing was installed and the work dir was cleaned up.+ fn assert_untouched(&self) {+ assert!(!self.link().exists() && self.link().symlink_metadata().is_err());+ assert!(!self.lib().exists());+ let leftovers: Vec<_> = std::fs::read_dir(&self.root)+ .unwrap()+ .flatten()+ .map(|e| e.file_name())+ .filter(|name| name != "home")+ .collect();+ assert!(leftovers.is_empty(), "left behind {leftovers:?}");+ }+}++fn report(out: &Output) -> String {+ format!(+ "status: {}\nstdout: {}\nstderr: {}",+ out.status,+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ )+}++#[test]+fn installs_a_verified_release_under_the_home() {+ let files = tempfile::tempdir().unwrap();+ let release = Release::serve(files.path());+ release.publish(&release_archive(&[]));+ let home = Home::new();++ let out = home.install(&release);+ assert!(out.status.success(), "{}", report(&out));+ assert!(String::from_utf8_lossy(&out.stdout).contains("checksum verified"));+ assert_eq!(+ std::fs::read_link(home.link()).unwrap(),+ home.lib().join("ai-memory")+ );+ assert!(home.lib().join("hooks/claude-code/stop.sh").is_file());+ let version = Command::new(home.link()).arg("--version").output().unwrap();+ assert_eq!(+ String::from_utf8_lossy(&version.stdout).trim(),+ "ai-memory 0.0.0-install-test"+ );+ assert!(+ release+ .requests+ .lock()+ .unwrap()+ .contains(&format!("/releases/latest/download/{ASSET}.sha256"))+ );++ // Re-running replaces the release in place and keeps the link.+ let again = home.install(&release);+ assert!(again.status.success(), "{}", report(&again));+ assert!(home.lib().join("ai-memory").is_file());+}++#[test]+fn a_pinned_version_downloads_that_tag() {+ let files = tempfile::tempdir().unwrap();+ let release = Release::serve(files.path());+ let archive = release_archive(&[]);+ let dir = files.path().join("releases/download/v9.9.9");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join(ASSET), &archive).unwrap();+ std::fs::write(+ dir.join(format!("{ASSET}.sha256")),+ format!("{:x} {ASSET}\n", Sha256::digest(&archive)),+ )+ .unwrap();+ let home = Home::new();+ let out = home+ .command(&release)+ .env("AI_MEMORY_VERSION", "9.9.9")+ .arg(script())+ .output()+ .unwrap();+ assert!(out.status.success(), "{}", report(&out));+}++#[test]+fn a_checksum_mismatch_installs_nothing() {+ let files = tempfile::tempdir().unwrap();+ let release = Release::serve(files.path());+ release.publish(&release_archive(&[]));+ release.publish_sidecar(&format!("{} {ASSET}\n", "0".repeat(64)));+ let home = Home::new();++ let out = home.install(&release);+ assert!(!out.status.success(), "{}", report(&out));+ assert!(+ String::from_utf8_lossy(&out.stderr).contains("checksum mismatch"),+ "{}",+ report(&out)+ );+ home.assert_untouched();+}++#[test]+fn a_missing_checksum_file_installs_nothing() {+ let files = tempfile::tempdir().unwrap();+ let release = Release::serve(files.path());+ std::fs::write(release.latest().join(ASSET), release_archive(&[])).unwrap();+ let home = Home::new();++ let out = home.install(&release);+ assert!(!out.status.success(), "{}", report(&out));+ assert!(+ String::from_utf8_lossy(&out.stderr).contains("without a checksum"),+ "{}",+ report(&out)+ );+ home.assert_untouched();+}++/// A sidecar copied from another asset (right hash format, wrong name) or+/// one that is not a hash at all is refused too.+#[test]+fn a_foreign_or_malformed_checksum_file_installs_nothing() {+ let files = tempfile::tempdir().unwrap();+ let release = Release::serve(files.path());+ let archive = release_archive(&[]);+ release.publish(&archive);+ for sidecar in [+ format!(+ "{:x} ai-memory-macos-aarch64.tar.gz\n",+ Sha256::digest(&archive)+ ),+ "<html>not found</html>\n".to_owned(),+ String::new(),+ ] {+ release.publish_sidecar(&sidecar);+ let home = Home::new();+ let out = home.install(&release);+ assert!(!out.status.success(), "{sidecar:?}: {}", report(&out));+ home.assert_untouched();+ }+}++#[test]+fn an_archive_with_an_escaping_path_installs_nothing() {+ let files = tempfile::tempdir().unwrap();+ let release = Release::serve(files.path());+ release.publish(&release_archive(&[("../escaped", b"owned")]));+ let home = Home::new();++ let out = home.install(&release);+ assert!(!out.status.success(), "{}", report(&out));+ assert!(+ String::from_utf8_lossy(&out.stderr).contains("unsafe path"),+ "{}",+ report(&out)+ );+ home.assert_untouched();+ assert!(!home.root.join("escaped").exists());+}++/// Whatever sits at the link path and is not a link is the user's: a Docker+/// wrapper or a hand-built binary is never replaced.+#[test]+fn an_existing_binary_at_the_link_path_is_left_alone() {+ let files = tempfile::tempdir().unwrap();+ let release = Release::serve(files.path());+ release.publish(&release_archive(&[]));+ let home = Home::new();+ std::fs::create_dir_all(home.link().parent().unwrap()).unwrap();+ std::fs::write(home.link(), "#!/bin/sh\necho wrapper\n").unwrap();++ let out = home.install(&release);+ assert!(!out.status.success(), "{}", report(&out));+ assert_eq!(+ std::fs::read_to_string(home.link()).unwrap(),+ "#!/bin/sh\necho wrapper\n"+ );+ assert!(!home.lib().exists());+}++/// `curl … | sh` with the download cut short: every cut point leaves a+/// script that defines functions at most, so nothing is fetched or written.+#[test]+fn a_truncated_script_runs_nothing() {+ let files = tempfile::tempdir().unwrap();+ let release = Release::serve(files.path());+ release.publish(&release_archive(&[]));+ let mut full = Vec::new();+ std::fs::File::open(script())+ .unwrap()+ .read_to_end(&mut full)+ .unwrap();+ let main_call = full.len() - "main \"$@\"\n".len();+ assert!(+ full.ends_with(b"main \"$@\"\n"),+ "main must be the last line"+ );++ for cut in (0..main_call).step_by(97).chain([main_call]) {+ let home = Home::new();+ let _ = home.pipe(&release, &full[..cut]);+ home.assert_untouched();+ }+ assert!(+ release.requests.lock().unwrap().is_empty(),+ "a truncated script reached the network"+ );++ // Control: the whole script, piped the same way, installs.+ let home = Home::new();+ let out = home.pipe(&release, &full);+ assert!(out.status.success(), "{}", report(&out));+ assert!(home.link().exists());+}diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex e4b448c6..d750582b 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -21,6 +21,7 @@ mod external_capture_powershell;mod external_capture_ts;mod hook_drain;mod hook_payload;+mod install_script;mod jail_toggles_e2e;mod marker_scope;mod message_e2e;@@ -34,6 +35,7 @@ mod routing_skills;mod run_offline;mod serve_shutdown;mod server_profiles;+mod setup_e2e;mod shutdown_signals;mod upgrade_e2e;mod workstream_provenance;diff --git a/crates/ai-memory-cli/tests/suite/packaging.rs b/crates/ai-memory-cli/tests/suite/packaging.rsindex 6ab9c3ff..3bfbf2e4 100644--- a/crates/ai-memory-cli/tests/suite/packaging.rs+++ b/crates/ai-memory-cli/tests/suite/packaging.rs@@ -671,6 +671,7 @@ fn wrapper_updates_and_install_docs_use_verified_release_assets() {"ai-memory-wrapper.cmd","ai-memory-install-hooks","ai-memory-hooks.tar.gz",+ "install.sh",] {assert!(release.contains(asset), "release must publish {asset}");assert!(diff --git a/crates/ai-memory-cli/tests/suite/setup_e2e.rs b/crates/ai-memory-cli/tests/suite/setup_e2e.rsnew file mode 100644index 00000000..af8840f6--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/setup_e2e.rs@@ -0,0 +1,400 @@+//! `ai-memory setup` through the shipped binary, in a temp home.+//!+//! The service manager is a test double: a `systemctl` script first on `PATH`+//! that records every call and, on `restart`, runs the rendered unit's+//! `ExecStart` in the background. No real user session, unit directory or+//! harness config is touched.++#![cfg(unix)]++use std::path::{Path, PathBuf};+use std::process::{Command, Output, Stdio};++use crate::e2e_support::hermetic;++const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");++/// A temp root holding the operator's home and a directory of fake tools.+struct Sandbox {+ _tmp: tempfile::TempDir,+ root: PathBuf,+ home: PathBuf,+}++impl Sandbox {+ fn new() -> Self {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path().to_path_buf();+ let home = root.join("home");+ std::fs::create_dir_all(&home).unwrap();+ Self {+ _tmp: tmp,+ root,+ home,+ }+ }++ fn data_dir(&self) -> PathBuf {+ self.home.join(".local/share/ai-memory")+ }++ /// Every file under the home with its contents, the database and logs+ /// aside (the running server owns those).+ fn snapshot(&self) -> Vec<(PathBuf, Vec<u8>)> {+ let skip = [self.data_dir().join("db"), self.data_dir().join("logs")];+ let mut files = Vec::new();+ let mut pending = vec![self.home.clone()];+ while let Some(dir) = pending.pop() {+ for entry in std::fs::read_dir(&dir).unwrap().flatten() {+ let path = entry.path();+ if skip.iter().any(|s| path.starts_with(s)) {+ continue;+ }+ if path.is_dir() {+ pending.push(path);+ } else {+ files.push((path.clone(), std::fs::read(&path).unwrap_or_default()));+ }+ }+ }+ files.sort();+ files+ }++ fn cmd(&self, port: Option<u16>) -> Command {+ let mut cmd = hermetic(BIN);+ cmd.env("HOME", &self.home)+ .env("AI_MEMORY_HOME", &self.home)+ .env("XDG_CONFIG_HOME", self.home.join(".config"))+ .env("XDG_DATA_HOME", self.home.join(".local/share"))+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")+ .env("AI_MEMORY_BACKFILL_ON_START", "false")+ .env("AI_MEMORY_AUTO_IMPROVE__SCHEDULER__ENABLED", "false")+ .env("RUST_LOG", "off")+ .env_remove("CLAUDE_CODE_SESSION_ID")+ .current_dir(&self.home)+ .stdin(Stdio::null());+ if let Some(port) = port {+ // Never the default port: a real server may be listening there.+ cmd.env("AI_MEMORY_BIND", format!("127.0.0.1:{port}"))+ .env("AI_MEMORY_SERVER_URL", format!("http://127.0.0.1:{port}"));+ }+ cmd+ }+}++fn text(out: &Output) -> String {+ format!(+ "status: {}\nstdout: {}\nstderr: {}",+ out.status,+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ )+}++/// Without `--yes` and with no terminal on stdin, `setup` shows the plan,+/// changes nothing and exits non-zero naming `--yes`.+#[test]+fn setup_without_yes_and_without_a_terminal_changes_nothing() {+ let sandbox = Sandbox::new();+ std::fs::create_dir_all(sandbox.home.join(".claude/projects")).unwrap();+ let before = sandbox.snapshot();+ let port = crate::e2e_support::free_port();+ let out = sandbox.cmd(Some(port)).arg("setup").output().unwrap();+ assert!(!out.status.success(), "{}", text(&out));+ let stdout = String::from_utf8_lossy(&out.stdout);+ assert!(stdout.contains("ai-memory setup will:"), "{}", text(&out));+ assert!(+ stdout.contains("wire claude-code (detected)"),+ "{}",+ text(&out)+ );+ assert!(+ String::from_utf8_lossy(&out.stderr).contains("--yes"),+ "{}",+ text(&out)+ );+ // Any command opens its log under the data dir; nothing else may appear.+ assert!(!sandbox.data_dir().join("config.toml").exists());+ assert!(!sandbox.data_dir().join("auth-tokens").exists());+ assert_eq!(sandbox.snapshot(), before, "setup wrote without --yes");+}++/// Spawns a server through the fake service manager: the slow tier.+#[cfg(target_os = "linux")]+mod slow {+ use super::*;+ use serde_json::{Value, json};+ use std::time::{Duration, Instant};++ /// `systemctl --user` stand-in. `restart` runs the unit's `ExecStart`+ /// (the rendered paths carry no `%` or `$`, so shell word splitting+ /// matches systemd's here).+ const FAKE_SYSTEMCTL: &str = r#"#!/bin/sh+state="${FAKE_SYSTEMD_STATE:?}"+mkdir -p "$state"+printf '%s\n' "$*" >> "$state/calls"+[ "$1" = "--user" ] || exit 2+shift+unit="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/ai-memory.service"+alive() { [ -f "$state/pid" ] && kill -0 "$(cat "$state/pid")" 2>/dev/null; }+case "$1" in+ daemon-reload) ;;+ enable) touch "$state/enabled" ;;+ is-enabled) [ -f "$state/enabled" ] ;;+ is-active) alive ;;+ restart)+ if alive; then kill "$(cat "$state/pid")"; sleep 0.2; fi+ line="$(sed -n 's/^ExecStart=//p' "$unit")"+ eval "set -- $line"+ "$@" >"$state/server.log" 2>&1 &+ echo $! > "$state/pid"+ ;;+ *) exit 3 ;;+esac+"#;++ struct Service {+ state: PathBuf,+ bin: PathBuf,+ }++ impl Service {+ fn new(root: &Path) -> Self {+ use std::os::unix::fs::PermissionsExt as _;+ let bin = root.join("fakebin");+ std::fs::create_dir_all(&bin).unwrap();+ let script = bin.join("systemctl");+ std::fs::write(&script, FAKE_SYSTEMCTL).unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();+ Self {+ state: root.join("systemd"),+ bin,+ }+ }++ fn calls(&self) -> Vec<String> {+ std::fs::read_to_string(self.state.join("calls"))+ .unwrap_or_default()+ .lines()+ .map(str::to_owned)+ .collect()+ }++ fn apply(&self, cmd: &mut Command) {+ let path = std::env::var_os("PATH").unwrap_or_default();+ let mut joined = std::ffi::OsString::from(&self.bin);+ joined.push(":");+ joined.push(path);+ cmd.env("PATH", joined)+ .env("FAKE_SYSTEMD_STATE", &self.state);+ }+ }++ impl Drop for Service {+ fn drop(&mut self) {+ if let Ok(pid) = std::fs::read_to_string(self.state.join("pid")) {+ let _ = Command::new("kill").arg(pid.trim()).status();+ }+ }+ }++ fn setup(sandbox: &Sandbox, service: &Service, port: u16, args: &[&str]) -> Output {+ let mut cmd = sandbox.cmd(Some(port));+ service.apply(&mut cmd);+ cmd.arg("setup").args(args).output().unwrap()+ }++ async fn captured_sessions(base: &str, token: &str, workspace: &str, project: &str) -> u64 {+ let client = reqwest::Client::new();+ let deadline = Instant::now() + Duration::from_secs(15);+ loop {+ let resp = client+ .get(format!("{base}/admin/sessions/by-agent"))+ .bearer_auth(token)+ .query(&[("workspace", workspace), ("project", project)])+ .send()+ .await+ .unwrap();+ let count = if resp.status().is_success() {+ let body: Value = resp.json().await.unwrap();+ body["by_agent"]+ .as_array()+ .map(|a| a.iter().filter_map(|x| x["sessions"].as_u64()).sum())+ .unwrap_or(0)+ } else {+ 0+ };+ if count > 0 || Instant::now() >= deadline {+ return count;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ }++ /// Fresh home with Claude Code present: one `setup --yes` initialises the+ /// install with a token, writes and starts the user unit on this install,+ /// wires MCP, hooks and skills without the token in any harness file, and+ /// passes its own self-check. A captured hook event reaches the server. A+ /// second run changes no file and makes no state-changing service call.+ #[tokio::test]+ async fn setup_installs_wires_and_a_second_run_changes_nothing() {+ let sandbox = Sandbox::new();+ let service = Service::new(&sandbox.root);+ std::fs::create_dir_all(sandbox.home.join(".claude/projects")).unwrap();+ let repo = sandbox.home.join("work/repo");+ std::fs::create_dir_all(&repo).unwrap();+ std::fs::write(+ repo.join(".ai-memory.toml"),+ "workspace = \"setup-ws\"\nproject = \"setup-project\"\n",+ )+ .unwrap();+ let port = crate::e2e_support::free_port();+ let base = format!("http://127.0.0.1:{port}");++ let first = setup(&sandbox, &service, port, &["--yes"]);+ assert!(first.status.success(), "{}", text(&first));+ let stdout = String::from_utf8_lossy(&first.stdout);+ assert!(stdout.contains("healthz: ok"), "{}", text(&first));+ assert!(stdout.contains("memory_status: ok"), "{}", text(&first));++ let data_dir = sandbox.data_dir();+ let token = std::fs::read_to_string(data_dir.join("auth-tokens/default"))+ .unwrap()+ .trim()+ .to_owned();+ assert!(!token.is_empty());+ assert!(!stdout.contains(&token), "setup printed the token");+ let unit =+ std::fs::read_to_string(sandbox.home.join(".config/systemd/user/ai-memory.service"))+ .unwrap();+ let exec = unit+ .lines()+ .find(|line| line.starts_with("ExecStart="))+ .unwrap();+ assert!(+ exec.contains(&format!("--data-dir \"{}\"", data_dir.display())),+ "{exec}"+ );+ assert!(+ exec.contains(&format!(+ "--config \"{}\"",+ data_dir.join("config.toml").display()+ )),+ "{exec}"+ );+ assert!(!unit.contains(&token), "the unit holds the token");+ assert_eq!(+ service.calls(),+ vec![+ "--user is-active --quiet ai-memory.service",+ "--user daemon-reload",+ "--user enable ai-memory.service",+ "--user restart ai-memory.service",+ ]+ );++ // The token lives only in the token file and the hook credential files.+ let allowed = [+ data_dir.join("auth-tokens/default"),+ data_dir.join("auth-token"),+ data_dir.join("auth-header"),+ data_dir.join("hook-spool"),+ data_dir.join("db"),+ ];+ let leaks: Vec<_> = sandbox+ .snapshot()+ .into_iter()+ .filter(|(path, bytes)| {+ !allowed.iter().any(|a| path.starts_with(a))+ && bytes.windows(token.len()).any(|w| w == token.as_bytes())+ })+ .map(|(path, _)| path)+ .collect();+ assert!(leaks.is_empty(), "token found in {leaks:?}");++ // Wired: MCP through the bridge, hooks, skills.+ let claude: Value = serde_json::from_str(+ &std::fs::read_to_string(sandbox.home.join(".claude.json")).unwrap(),+ )+ .unwrap();+ assert_eq!(claude["mcpServers"]["ai-memory"]["args"][0], "mcp-bridge");+ let settings = std::fs::read_to_string(sandbox.home.join(".claude/settings.json")).unwrap();+ assert!(settings.contains("user-prompt-submit"), "{settings}");+ assert!(+ sandbox+ .home+ .join(".claude/skills/ai-memory-retrieval/SKILL.md")+ .is_file()+ );++ // A hook event, the way the installed hook sends it, is captured.+ let mut hook = sandbox.cmd(Some(port));+ let mut child = hook+ .args([+ "hook",+ "--event",+ "user-prompt-submit",+ "--agent",+ "claude-code",+ "--server-url",+ &base,+ ])+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .spawn()+ .unwrap();+ {+ use std::io::Write as _;+ let payload = json!({+ "session_id": "setup-e2e-session",+ "cwd": repo,+ "prompt": "setup e2e prompt",+ });+ child+ .stdin+ .take()+ .unwrap()+ .write_all(payload.to_string().as_bytes())+ .unwrap();+ }+ assert!(child.wait().unwrap().success());+ let drain = sandbox.cmd(Some(port)).arg("hook-drain").output().unwrap();+ assert!(drain.status.success(), "{}", text(&drain));+ assert_eq!(+ captured_sessions(&base, &token, "setup-ws", "setup-project").await,+ 1+ );++ // Second run: same bytes everywhere, no state-changing call.+ let before = sandbox.snapshot();+ let calls_before = service.calls().len();+ let second = setup(&sandbox, &service, port, &["--yes"]);+ assert!(second.status.success(), "{}", text(&second));+ assert!(+ String::from_utf8_lossy(&second.stdout).contains("already running"),+ "{}",+ text(&second)+ );+ let after = sandbox.snapshot();+ let changed: Vec<_> = before+ .iter()+ .zip(after.iter())+ .filter(|(a, b)| a != b)+ .map(|(a, _)| a.0.clone())+ .collect();+ assert_eq!(+ before.len(),+ after.len(),+ "the second run added or removed files"+ );+ assert!(changed.is_empty(), "the second run changed {changed:?}");+ assert_eq!(+ service.calls()[calls_before..].to_vec(),+ vec![+ "--user is-active --quiet ai-memory.service",+ "--user is-enabled --quiet ai-memory.service",+ ]+ );+ }+}diff --git a/docker/Dockerfile b/docker/Dockerfileindex ad0629d8..140f8d26 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -26,6 +26,10 @@ COPY evals ./evals# `docs/logo*.png` are include_bytes!'d by ai-memory-web's static# routes at compile time, so they must be in the build context.COPY docs ./docs+# `ai-memory setup` renders the user service from these packaged templates,+# include_str!'d at compile time.+COPY packaging/systemd ./packaging/systemd+COPY packaging/launchd ./packaging/launchdRUN --mount=type=cache,target=/usr/local/cargo/registry \--mount=type=cache,target=/work/target \cargo build --locked --release -p ai-memory-cli \diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex e1b3050c..de7ce5f3 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -779,11 +779,25 @@ api-key export-okf messagedoctor backfill projectreclaim-ledger-versions repair-backfill-timestampsserver backup-agents restore-agents-profile+profile setup```Run `ai-memory --help` for the full tree.+`setup` is the one-step native install. It is a thin composition of existing+library calls: `init` (which mints the root bearer on a fresh data dir), a+per-user service rendered from `packaging/systemd/ai-memory-user.service` or+the launchd LaunchAgent template with the running binary, data dir and config+path filled in, then `install-mcp`, `install-hooks` and global+`install-skills` for each agent named with `--agent` or detected from its+session store or MCP config (the stores `doctor` scans). It finishes with a+read-only self-check: `/healthz`, a `memory_status` call over MCP, and+`doctor`. The service manager is reached through an injectable runner, so the+unit rendering and the `systemctl`/`launchctl` calls are tested without a real+session. Windows has no service step. A second run changes no file.+`install.sh`, a release asset with its own `.sha256`, installs the release+tarball under `~/.local` after checking it against the published checksum.+`auth enable` turns on the root bearer for an install created beforenew installs got one; see [`[auth]` root bearer](#auth-root-bearer).diff --git a/docs/install.md b/docs/install.mdindex 056dd90b..859c1738 100644--- a/docs/install.md+++ b/docs/install.md@@ -4,6 +4,8 @@ The [README quick-start](../README.md#quick-start) covers the happypaths (Docker + Claude Code, Arch AUR, Fedora RPM, macOS menu bar app). Thispage covers everything else:+- [One-step native install](#one-step-native-install-installsh--ai-memory-setup)+ (`install.sh` + `ai-memory setup`, Linux and macOS, no root)- [Server on a different machine](#server-on-a-different-machine)(homelab, LAN box, remote server)- [Configuring the CLI URL and auth](#configuring-the-cli-url-and-auth)@@ -51,6 +53,105 @@ Silicon Macs and ARM64 Linux hosts should not need `--platform linux/amd64`.---+## One-step native install (`install.sh` + `ai-memory setup`)++On Linux (x86_64, aarch64) and macOS (Apple Silicon, Intel), two commands go+from nothing to a running server with your agents wired. Neither needs root.++```bash+curl -fsSL https://github.com/akitaonrails/ai-memory/releases/latest/download/install.sh | sh+ai-memory setup+```++`install.sh` is published with every release, next to its own+`install.sh.sha256`. It picks `ai-memory-<os>-<arch>.tar.gz` for the machine,+downloads it with its `.sha256` file, and stops before unpacking anything when+the checksum file is missing, names another asset, or does not match. It also+refuses an archive holding an absolute or `..` path. The release goes to+`~/.local/lib/ai-memory`, and `~/.local/bin/ai-memory` becomes a link to the+binary, so the bundled `hooks/` directory sits beside it and+`ai-memory upgrade` can later replace both. An `ai-memory` at the link path that+is not such a link (the Docker wrapper, a hand-built binary) is left alone and+the script exits. The whole script runs from one function called on its last+line, so a download cut short runs nothing. To read it before running it:++```bash+curl -fsSLO https://github.com/akitaonrails/ai-memory/releases/latest/download/install.sh+curl -fsSLO https://github.com/akitaonrails/ai-memory/releases/latest/download/install.sh.sha256+sha256sum -c install.sh.sha256 # macOS: shasum -a 256 -c install.sh.sha256+sh install.sh+```++| Variable | Default | Effect |+|---|---|---|+| `AI_MEMORY_VERSION` | latest | Install this release, e.g. `2.7.0` |+| `AI_MEMORY_BIN_DIR` | `~/.local/bin` | Where the `ai-memory` link goes |+| `AI_MEMORY_LIB_DIR` | `~/.local/lib/ai-memory` | Where the release is unpacked |+| `AI_MEMORY_RELEASE_BASE_URL` | GitHub Releases | A mirror serving `latest/download/<asset>` and `download/v<version>/<asset>`; the same variable `ai-memory upgrade` reads. The checksum comes from the same origin as the archive, so use only a mirror you control. |+| `AI_MEMORY_INSTALL_TARGET` | detected | Force `linux-x86_64`, `linux-aarch64`, `macos-x86_64` or `macos-aarch64` |++Windows is not covered by the script; use the zip in+[`docs/windows.md`](windows.md).++`ai-memory setup [--yes] [--agent <name>]... [--no-service]` 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+ `<data_dir>/auth-tokens/default` (owner-only) and records+ `[auth] bearer_token_file`, as described in+ [`[auth]` root bearer](ARCHITECTURE.md#auth-root-bearer). An existing install+ keeps its config and its auth posture; `ai-memory auth enable` is still the+ opt-in for a token there.+2. A per-user service running `serve --transport http --enable-web` on that+ data dir and config: `~/.config/systemd/user/ai-memory.service` (or under+ `$XDG_CONFIG_HOME`) on Linux, rendered from the packaged user unit, or+ `~/Library/LaunchAgents/com.github.akitaonrails.ai-memory.plist` on macOS,+ rendered from the packaged LaunchAgent. The unit runs the binary `setup` ran+ from. The step is skipped when a server already answers at the configured+ URL and no unit of ours exists yet (Docker, a packaged system unit, a+ foreground `serve`), when the configured server is not on this machine,+ with `--no-service`, and on Windows.+3. For each agent: `install-mcp --apply`, `install-hooks --apply` and+ `install-skills --scope global`. With no `--agent`, `setup` wires every+ harness whose session store or MCP config exists under your home, using the+ same store locations as `doctor` (including `CLAUDE_CONFIG_DIR`,+ `CODEX_HOME` and similar relocations). OpenCode 2 and the Kiro CLI v3+ engine share a store with OpenCode and Kiro CLI, so they are wired only+ when named, for example `--agent opencode2`.+4. A self-check that writes nothing: `GET /healthz`, a `memory_status` call+ over MCP with the install's credential, and `doctor`.++Without `--yes`, `setup` prints this plan and asks on a terminal; with no+terminal (a script, an agent's tool call) it changes nothing and exits+non-zero, asking for `--yes`. Each step is idempotent: a second run rewrites no+file and leaves a running service alone. A step that fails does not stop the+others; `setup` lists each `problem:` at the end and exits non-zero. The token+is never printed or passed on a command line, and no harness config holds it:+hooks read the credential files `init` writes, and MCP clients reach the+server through `ai-memory mcp-bridge`.++`uninstall --apply` removes the hooks, MCP entries and skills `setup` wired,+but not the service. Remove that by hand:++```bash+# Linux+systemctl --user disable --now ai-memory.service+rm ~/.config/systemd/user/ai-memory.service+# macOS+launchctl bootout "gui/$(id -u)/com.github.akitaonrails.ai-memory"+rm ~/Library/LaunchAgents/com.github.akitaonrails.ai-memory.plist+```++An AI agent installing ai-memory for its user can follow+[`INSTALL_FOR_AGENTS.md`](../INSTALL_FOR_AGENTS.md), which comes down to+`ai-memory setup --yes --agent <self>`.++`scripts/onboarding-acceptance.sh` measures this path in a clean temporary+home against a locally built release: two commands, and about one second from+the first command to a `memory_query` that returns a captured hook event (a+debug build on a Linux workstation, local embeddings off so no model download+is counted). The target is 60 seconds.+## Server on a different machineWhen the ai-memory server runs on a LAN box (homelab, headless server)diff --git a/docs/macos.md b/docs/macos.mdindex dc462aa5..90918eb9 100644--- a/docs/macos.md+++ b/docs/macos.md@@ -51,6 +51,18 @@ normal Terminal.## Scenario A: Prebuilt Release Binary (Recommended, No Toolchain)+The shortest route is two commands: `install.sh` downloads and verifies the+tarball for your chip, and `ai-memory setup` initialises the data dir, installs+and starts the LaunchAgent below for you, and wires your agents:++```bash+curl -fsSL https://github.com/akitaonrails/ai-memory/releases/latest/download/install.sh | sh+ai-memory setup+```++See [`docs/install.md`](install.md#one-step-native-install-installsh--ai-memory-setup)+for what each step does. The manual steps follow.+Use this when you want a local server plus native hooks without a Rust toolchainor Docker. Each tagged release publishes a macOS tarball per architecture.diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex f0155953..7e55a181 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -79,7 +79,7 @@ means the boundary is not built yet.| 11h | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks` and upgrade refreshes through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network. Only an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` retains the documented script compatibility path and its warning; `AI_MEMORY_NATIVE_BIN` may not point back to the wrapper. For a server initialized on the named volume, `bin/ai-memory` `refresh_volume_token` (run only by `install-hooks`) copies `/data/auth-tokens/default` (only when `/data/config.toml` names it) to an owner-only `native-runner/server-token` through the helper's stdout, and `use_volume_token` points the native client at that copy (the managed host commands and `mcp-bridge` only read it and never enter the container engine) with `AI_MEMORY_AUTH__BEARER_TOKEN_FILE`, so it is a file-sourced token (never rendered into a harness config) and never an argv; a bind-mounted `AI_MEMORY_DATA_DIR` is read directly and an explicit `AI_MEMORY_AUTH_TOKEN` wins | `scripts/check-native-packaging.sh` `Checking host-launch wrapper routing`: a default allowlist install reaches the fake native client while a Docker executable that always fails proves no container fallback occurred; the explicit `posix` control reaches fake Docker and adds no native invocation; the self-referential native override is refused; `Checking the wrapper hands host commands the volume's root bearer`: for `mcp-bridge`, `install-hooks` and `run` the fake native client receives the token file (mode 600, right content) and the token is absent from its argv; controls: a bind-mounted data dir and an explicit `AI_MEMORY_AUTH_TOKEN` make no copy and ask no container (bite: dropping the export fails the check); `auth_default_e2e.rs` `a_host_client_given_the_token_file_by_env_authenticates` (the native side of the handoff, with a no-variable control) | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 || 11j | Offline recovery journal and transcript replay | `ai-memory-cli/src/commands/recovery.rs` keeps bounded locators, ordered semantic transcript digests, pre-launch cursors and persistent correlated-delivery/loss evidence in an atomic journal, refuses a symlinked data dir and any symlinked component inside it (ancestors above the data dir are trusted, so macOS `/var` → `/private/var` works), sanitizes/caps failure reasons, and bounds each replay plus the whole pass; `hook_spool` coordinates enqueue and quarantine with short filesystem locks, canonically resolves partial scope from the recorded cwd, bounds per-file reads and current global occupancy across the main spool and recovery directories, sweeps completed tombstones, and holds correlated events outside drain until replay succeeds or restores them on failure; degraded resumes use `ai-memory-workstream`'s adapter-validated delta export, whose blocking parse and baseline scans are capped by record, event-count, source-byte and serialized-byte totals; `backfill::import_exact_session` chunks by item and byte limits and requires per-item durable acknowledgements; `run.rs` journals every session launch, including explicit spool-only evidence for unsupported exporters, and journals a resumed export only after capturing its exact pre-launch cursor; `workstream.rs` `/recover/finish` retains owner/project authorization, rejects superseded runs, and validates a finished retry by durable transcript/native/cursor/exit identity without regenerating its checkpoint; validated recovery ingest keys bind session, agent, event kind and sanitized event identity until session purge | `transcript.rs` `persisted_baseline_exports_only_offline_append_and_rejects_rewrite`, parser/baseline cap and ordered-semantic digest tests; CLI `run_offline.rs` real degraded spool-only and overlap/idempotency tests; `recovery.rs` `spool_only_without_correlated_evidence_never_auto_clears`, `a_dropped_spool_event_stays_lost_on_the_next_empty_pass`, loss/time-budget tests, `symlinked_journal_and_ancestor_are_refused`, `a_symlinked_ancestor_of_the_data_dir_is_trusted`, `a_symlink_inside_a_data_dir_under_a_symlinked_ancestor_is_refused`; `hook_spool.rs` partial-scope late enqueue, completion-race, occupancy churn/active-cap, bounded-read and tombstone-sweep tests, plus interval isolation (`completed_tombstone_keeps_a_later_resume_of_the_same_session` proves a post-interval resume hook is delivered, `completing_one_recovery_interval_leaves_the_other_intervals_entries_intact` proves one interval's completion never consumes another's evidence and ambiguous entries fail closed into the main spool); `backfill.rs` `two_sequential_recovery_intervals_on_one_resumed_session_replay_exactly_once` proves the second interval's content and session-end are stored with end-of-session effects while reruns stay pure replays; `transcript.rs` `an_oversized_first_record_is_skipped_by_session_listing_caps` proves the first-record byte caps bite before allocation; store `insert_observation_ingest_dedups_on_key` rejects cross-session and changed-event preclaims; hooks `expired_run_recovery_is_owner_only_and_refuses_superseded_runs` proves changed transcript refusal and changed-checkpoint no-op | STRONG on Unix integration coverage; Unix lock opens use no-follow and atomic replacement rechecks the destination. Windows owner-only ACL/reparse and lock semantics require the PR `windows` lane || 11i | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label |-| 12 | Network/auth posture, including auth on by default for new installs (an existing install keeps loopback no-auth until `ai-memory auth enable`) | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart`; new-install default: `commands/init.rs` `root_bearer_for_new_config` mints a root bearer only on a fresh data dir (no config file and no database) and only when no bearer is supplied otherwise, via `local_auth.rs` `provision_root_token` (`auth-tokens/` `0700`, file `0600`, atomic, reused when present) and records the relative `[auth].bearer_token_file`; `config.rs` `apply_bearer_token_file` reads it once (`AI_MEMORY_AUTH_TOKEN` wins, inline + file together refused, a missing or blank file leaves no bearer) and `discover_root_token` lets a packaged install's client commands use `<data_dir>/auth-tokens/default` only with no config file at the probed path, a loopback server URL and no registered `default` profile; `serve.rs` `refuse_a_missing_token_file` stops a server whose configured file holds no token; `AuthSettings::renderable_bearer_token` keeps a file-sourced token out of every renderer: `install_mcp.rs` `route_file_token` (Claude Code gets the session-aware `ai-memory mcp-bridge` entry, Codex and Prime Agent name `AI_MEMORY_AUTH_TOKEN`, every other client a `stdio_bridge_entry` that runs `mcp-bridge --no-session-id` in its documented stdio shape, Pi keeps its extension, ZCode (HTTP-only) is refused) and `mcp_bridge.rs`, which authenticates with the config-resolved bearer and connects upstream before serving stdio, so a refused token ends it with `401 Unauthorized` instead of hanging; `uninstall.rs` `mcp_entry_is_ours` / `toml_mcp_entry_targets` recognise bridge entries by `install_mcp::bridge_entry_url`; `auth_enable.rs` `rewire_clients` re-registers every client whose entry targets this server, `install_hooks.rs` (persisted to the hook credential files, never inlined, not even on the F5 persist-failure fallback), `setup_agent.rs`, `run_autowire.rs`; `local_auth.rs` `seed_hook_credential` gives hooks the token through `auth-token`/`auth-header` and keeps a different stored credential; `uninstall.rs` keeps the root bearer (`server_profiles::clear_tokens` `keep`); `commands/auth_enable.rs` is the idempotent opt-in | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls; `cli/tests/suite/auth_default_e2e.rs` against the shipped binary: `a_fresh_install_requires_the_token_and_its_own_clients_still_work` (after `init`, unauthenticated `/mcp`, `/hook`, `/api/v1/projects`, `/admin/status` → 401 and `/healthz` → 200; the same requests with the token succeed; the native hook delivers with no token in its environment, `status` authenticates through config, `mcp-bridge` lists tools; the token is in neither process's `/proc/<pid>/cmdline`; after `install-hooks`, `install-mcp --apply` for every client it writes (21, by default config path under the test home), a refused ZCode install and `auth enable` twice, a scan of the whole home finds the token nowhere and a scan of the data dir finds it only in the token file and the two hook credential files), `an_existing_install_is_unchanged_until_auth_enable` (control: a pre-default install serves every route open and `status` names the fix; `auth enable` twice is idempotent, rewires Claude Code to the bridge, and after a restart the routes refuse and the hook still delivers), `a_packaged_install_with_an_external_config_wires_its_clients`, `uninstall_keeps_the_root_bearer_and_a_missing_one_stops_the_server`, `a_host_client_given_the_token_file_by_env_authenticates`; `init.rs` `a_fresh_init_mints_a_root_bearer_the_loader_reads`, `init_on_an_existing_install_does_not_turn_auth_on`, `init_with_a_supplied_bearer_mints_nothing`, `re_running_init_keeps_the_same_root_bearer`; `config.rs` `a_relative_bearer_token_file_resolves_against_the_data_dir`, `a_missing_or_blank_bearer_token_file_is_reported_not_guessed`, `the_env_token_wins_over_the_bearer_token_file`, `an_inline_bearer_and_a_bearer_token_file_together_are_refused`, `a_client_without_a_config_file_discovers_the_root_bearer`, `root_bearer_discovery_is_refused_outside_its_narrow_case` (existing config, remote URL, `default` profile, env token); `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (`tools/list` and a scoped `memory_query` through `mcp-bridge --no-session-id` against a fresh auth-on server, the token in neither the bridge's `/proc/<pid>/cmdline` nor its `/proc/<pid>/environ`; control: the session-aware mode still refuses to start without `CLAUDE_CODE_SESSION_ID`) and `a_bridge_without_the_token_is_refused_cleanly_not_hung` (exits promptly naming `401 Unauthorized`); `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id`, `a_session_less_upstream_config_carries_no_session_header`, `stdio_bridge_forwards_tools_and_session_header_in_both_http_modes` (control); `install_mcp.rs` `a_file_sourced_token_wires_every_client_without_entering_its_config` (every written client: no token, no header, an entry that reaches the server; ZCode refused and unwritten), `stdio_bridge_entries_follow_each_clients_documented_shape`, `inline_and_explicit_tokens_still_embed_as_before` (control); `uninstall.rs` `bridge_entries_are_recognised_by_their_upstream_url` (JSON, OpenCode array and TOML shapes; a bridge to another server and a foreign command are kept); `install_hooks.rs` `a_file_sourced_token_is_persisted_but_never_embedded`; `auth_enable.rs` `enable_twice_is_idempotent_and_leaks_the_token_into_no_harness_config` (every client pre-wired over HTTP is re-registered, ZCode reported as manual, the second run byte-identical), `enable_leaves_an_entry_for_another_server_alone`, `enable_refuses_while_a_default_profile_would_share_the_token`; `local_auth.rs` `the_root_bearer_is_owner_only`, `seeding_never_replaces_a_different_hook_credential` | STRONG. Bite checks for the new-install default: with fresh-install minting disabled the fresh e2e routes answer without a token and the `init` tests fail; with `renderable_bearer_token` returning the file token, `install-mcp`, `install-hooks`, `auth enable` and the e2e scans find it in harness configs; without the `serve` refusal a server whose token file was deleted keeps running (the e2e times out on it); without the hook seeding the fresh e2e hook is refused; without `clear_tokens` `keep` uninstall deletes the root bearer; with `route_file_token` no longer choosing the stdio bridge the every-client and `auth enable` tests fail; with `auth enable` skipping the re-registration its test fails; with the session-less mode forwarding an inherited id the bridge unit test fails; without the 401 naming the refusal e2e fails; without bridge-entry recognition the uninstall test fails; with discovery removed the packaged e2e gets 401, and with each discovery guard removed the matching case of `root_bearer_discovery_is_refused_outside_its_narrow_case` fails. Residual: a hand-edited `servers.toml` that adds a `default` profile after the root bearer exists would read the root bearer as that profile's token (`server add` refuses it, `auth enable` refuses while it exists); ZCode takes only HTTP entries and is refused, so it needs a manual entry; the stdio entries for Zero, Muse Code and DeepSeek Harness follow their documented or source-level format but were not run against those clients |+| 12 | Network/auth posture, including auth on by default for new installs (an existing install keeps loopback no-auth until `ai-memory auth enable`) | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart`; new-install default: `commands/init.rs` `root_bearer_for_new_config` mints a root bearer only on a fresh data dir (no config file and no database) and only when no bearer is supplied otherwise, via `local_auth.rs` `provision_root_token` (`auth-tokens/` `0700`, file `0600`, atomic, reused when present) and records the relative `[auth].bearer_token_file`; `config.rs` `apply_bearer_token_file` reads it once (`AI_MEMORY_AUTH_TOKEN` wins, inline + file together refused, a missing or blank file leaves no bearer) and `discover_root_token` lets a packaged install's client commands use `<data_dir>/auth-tokens/default` only with no config file at the probed path, a loopback server URL and no registered `default` profile; `serve.rs` `refuse_a_missing_token_file` stops a server whose configured file holds no token; `AuthSettings::renderable_bearer_token` keeps a file-sourced token out of every renderer: `install_mcp.rs` `route_file_token` (Claude Code gets the session-aware `ai-memory mcp-bridge` entry, Codex and Prime Agent name `AI_MEMORY_AUTH_TOKEN`, every other client a `stdio_bridge_entry` that runs `mcp-bridge --no-session-id` in its documented stdio shape, Pi keeps its extension, ZCode (HTTP-only) is refused) and `mcp_bridge.rs`, which authenticates with the config-resolved bearer and connects upstream before serving stdio, so a refused token ends it with `401 Unauthorized` instead of hanging; `uninstall.rs` `mcp_entry_is_ours` / `toml_mcp_entry_targets` recognise bridge entries by `install_mcp::bridge_entry_url`; `auth_enable.rs` `rewire_clients` re-registers every client whose entry targets this server, `install_hooks.rs` (persisted to the hook credential files, never inlined, not even on the F5 persist-failure fallback), `setup_agent.rs`, `run_autowire.rs`, `setup.rs` (runs `init`, adopts the minted token in memory through `adopt_token_file`, and calls the installers with no explicit token; the rendered user unit carries none); `local_auth.rs` `seed_hook_credential` gives hooks the token through `auth-token`/`auth-header` and keeps a different stored credential; `uninstall.rs` keeps the root bearer (`server_profiles::clear_tokens` `keep`); `commands/auth_enable.rs` is the idempotent opt-in | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls; `cli/tests/suite/auth_default_e2e.rs` against the shipped binary: `a_fresh_install_requires_the_token_and_its_own_clients_still_work` (after `init`, unauthenticated `/mcp`, `/hook`, `/api/v1/projects`, `/admin/status` → 401 and `/healthz` → 200; the same requests with the token succeed; the native hook delivers with no token in its environment, `status` authenticates through config, `mcp-bridge` lists tools; the token is in neither process's `/proc/<pid>/cmdline`; after `install-hooks`, `install-mcp --apply` for every client it writes (21, by default config path under the test home), a refused ZCode install and `auth enable` twice, a scan of the whole home finds the token nowhere and a scan of the data dir finds it only in the token file and the two hook credential files), `an_existing_install_is_unchanged_until_auth_enable` (control: a pre-default install serves every route open and `status` names the fix; `auth enable` twice is idempotent, rewires Claude Code to the bridge, and after a restart the routes refuse and the hook still delivers), `a_packaged_install_with_an_external_config_wires_its_clients`, `uninstall_keeps_the_root_bearer_and_a_missing_one_stops_the_server`, `a_host_client_given_the_token_file_by_env_authenticates`; `init.rs` `a_fresh_init_mints_a_root_bearer_the_loader_reads`, `init_on_an_existing_install_does_not_turn_auth_on`, `init_with_a_supplied_bearer_mints_nothing`, `re_running_init_keeps_the_same_root_bearer`; `config.rs` `a_relative_bearer_token_file_resolves_against_the_data_dir`, `a_missing_or_blank_bearer_token_file_is_reported_not_guessed`, `the_env_token_wins_over_the_bearer_token_file`, `an_inline_bearer_and_a_bearer_token_file_together_are_refused`, `a_client_without_a_config_file_discovers_the_root_bearer`, `root_bearer_discovery_is_refused_outside_its_narrow_case` (existing config, remote URL, `default` profile, env token); `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (`tools/list` and a scoped `memory_query` through `mcp-bridge --no-session-id` against a fresh auth-on server, the token in neither the bridge's `/proc/<pid>/cmdline` nor its `/proc/<pid>/environ`; control: the session-aware mode still refuses to start without `CLAUDE_CODE_SESSION_ID`) and `a_bridge_without_the_token_is_refused_cleanly_not_hung` (exits promptly naming `401 Unauthorized`); `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id`, `a_session_less_upstream_config_carries_no_session_header`, `stdio_bridge_forwards_tools_and_session_header_in_both_http_modes` (control); `install_mcp.rs` `a_file_sourced_token_wires_every_client_without_entering_its_config` (every written client: no token, no header, an entry that reaches the server; ZCode refused and unwritten), `stdio_bridge_entries_follow_each_clients_documented_shape`, `inline_and_explicit_tokens_still_embed_as_before` (control); `uninstall.rs` `bridge_entries_are_recognised_by_their_upstream_url` (JSON, OpenCode array and TOML shapes; a bridge to another server and a foreign command are kept); `install_hooks.rs` `a_file_sourced_token_is_persisted_but_never_embedded`; `auth_enable.rs` `enable_twice_is_idempotent_and_leaks_the_token_into_no_harness_config` (every client pre-wired over HTTP is re-registered, ZCode reported as manual, the second run byte-identical), `enable_leaves_an_entry_for_another_server_alone`, `enable_refuses_while_a_default_profile_would_share_the_token`; `local_auth.rs` `the_root_bearer_is_owner_only`, `seeding_never_replaces_a_different_hook_credential`; `setup_e2e.rs` `setup_installs_wires_and_a_second_run_changes_nothing` (one `setup --yes` in a fresh temp home: the token is in no file under the home but the token file and the two hook credential files, not in the user unit and not in `setup`'s output; the self-check's `memory_status` and a hook event authenticate through the file) | STRONG. Bite checks for the new-install default: with fresh-install minting disabled the fresh e2e routes answer without a token and the `init` tests fail; with `renderable_bearer_token` returning the file token, `install-mcp`, `install-hooks`, `auth enable` and the e2e scans find it in harness configs; without the `serve` refusal a server whose token file was deleted keeps running (the e2e times out on it); without the hook seeding the fresh e2e hook is refused; without `clear_tokens` `keep` uninstall deletes the root bearer; with `route_file_token` no longer choosing the stdio bridge the every-client and `auth enable` tests fail; with `auth enable` skipping the re-registration its test fails; with the session-less mode forwarding an inherited id the bridge unit test fails; without the 401 naming the refusal e2e fails; without bridge-entry recognition the uninstall test fails; with `setup` handing the token to `install-mcp` its scan finds it in `.claude.json`; with discovery removed the packaged e2e gets 401, and with each discovery guard removed the matching case of `root_bearer_discovery_is_refused_outside_its_narrow_case` fails. Residual: a hand-edited `servers.toml` that adds a `default` profile after the root bearer exists would read the root bearer as that profile's token (`server add` refuses it, `auth enable` refuses while it exists); ZCode takes only HTTP entries and is refused, so it needs a manual entry; the stdio entries for Zero, Muse Code and DeepSeek Harness follow their documented or source-level format but were not run against those clients || 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten || 12c | Browser cross-origin writes refused on an unauthenticated server (a foreign page in the operator's browser, DNS rebinding, and a LAN host where browsers send no fetch metadata) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403; and `is_non_script_browser_request`: any `Sec-Fetch-Dest` other than `empty` (case-insensitive; non-UTF-8 refused) → 403 whatever `Sec-Fetch-Site` says, so links, images, navigations, iframes and form posts are refused even as `same-origin` or `none`. Browsers send fetch metadata over plain HTTP only to a potentially trustworthy host, so on any other `Host` (a LAN address or name in the allowlist, `0.0.0.0`, `host.docker.internal`; `is_loopback_host` admits only `localhost`, `*.localhost`, `127.0.0.0/8` and `[::1]`) `handoff_fetch_lacks_client_marker` also refuses `GET`/`HEAD /handoff` without a non-empty `X-AI-Memory-Client` header (`ai_memory_hooks::CLIENT_MARKER_HEADER`) → 403 whose body names both remedies (re-stage hooks, or set a bearer token). A page cannot add that header without a preflight these routes never answer. `/handoff` is the one state-changing `GET` on these routes; the other `GET`s are reads a foreign page cannot see the answer to, and every cross-origin `POST` carries `Origin`. Every first-party client sends the marker: the native hook (`hook_capture.rs` `post_hook`/`post_batch`/`get_handoff`), CLI subcommands (`http_client.rs` `ServerEndpoint::authenticate`), every curl in `hooks/_lib.sh`, both header tables in `hooks/lib/ai-memory-hook.ps1`, and the generated TypeScript integrations (`render_shared.rs` `ts_auth_headers_fn` plus the spool drain). Loopback hosts keep accepting a fetch without it, so hooks staged before the header existed still work on a default install, except that a request carrying any proxy forwarding header (`Forwarded`, `X-Forwarded-For`/`-Host`/`-Proto`/`-Server`/`-Port`, `X-Original-Forwarded-For`, `X-Real-IP`, `X-Client-IP`, `CF-Connecting-IP`, `True-Client-IP`, `Via`; `PROXY_HEADERS`) counts as non-loopback, since a plain-HTTP proxy can rewrite `Host` to loopback while the browser behind it sent no fetch metadata. No first-party client sends those headers. Hooks, the CLI and MCP clients send none of these headers; the web UI's same-origin `/admin/pending-writes` calls are `fetch()` (`Sec-Fetch-Dest: empty`) and pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment Every `/web` surface (built-in pages including `/web/pending`, the login page, a custom SPA and `/api/v1`) answers `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'` (`ai-memory-web/src/mount.rs` `deny_framing`), because a framed page's own Approve/Reject `fetch()` is same-origin and the guard rightly lets it through | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`; `GET /handoff` as a same-origin `document` or `image` and as a `Sec-Fetch-Site: none` `document` → 403 with the baton still open. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` and `non_script_browser_request_detection` (header tables) and `cross_origin_browser_guard_applies_only_without_auth` (same-origin `image` and `none` `document` refused, same-origin `empty` passes, both pass with auth on); `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control. `cross_origin_e2e.rs` `handoff_fetch_on_a_lan_host_requires_the_client_marker`, against a `serve` that allowlists a LAN name and address: `GET` and `HEAD /handoff` through either without the marker, and with an empty one → 403 carrying the remedy text, with the baton still open and the active-project pointer unmoved; controls: a marked fetch through the LAN name claims the baton, and a marker-less fetch through `127.0.0.1` (a hook staged before the marker) claims the next one; then a `127.0.0.1` fetch carrying each proxy forwarding header and no marker → 403 with the baton still open, and the same fetch with the marker claims it. `serve.rs` `loopback_host_detection`, `handoff_fetch_client_marker_decision` (incl. a loopback `Host` with each proxy header, refused without the marker and admitted with it, and a named row per header so none can drop out of the list) and `handoff_client_marker_guard_on_lan_hosts_and_under_a_base_path` (also under a `--base-path` nest; inactive with auth on). Front-door parity: `hook_capture.rs` `every_native_hook_request_carries_the_client_marker` (handoff GET, hook POST, batch POST), `http_client.rs` `authenticate_no_token_sets_only_the_client_marker`, the client-marker block of `tests/hooks/test_lib.sh` (every curl branch of the GET, the POST and the drain, plus a static check that every PowerShell header table carries it and every `Invoke-WebRequest` passes one), `render_shared.rs` `assert_every_ts_request_carries_client_marker` run for OpenCode, OpenCode 2, OMP, Pi and OpenClaw, `external_capture_ts.rs` (the rendered OpenCode plugin under Node sends no unmarked request) and `external_capture_powershell.rs` `every_request_carries_the_client_marker` (Windows leg); `ai-memory-web/src/mount.rs` `web_surfaces_refuse_to_be_framed` (`/web`, `/web/pending`, `/web/login`, `/api/v1/projects` all carry both headers; bites with `deny_framing` neutralized) | STRONG with listed residuals. Bite checks: with the marker check disabled, the LAN e2e marker-less `GET /handoff` returns 200 and the unit layer test fails; with the proxy-header rule disabled, the proxied loopback e2e fetch claims the baton and the unit decision test fails; dropping the marker from the native handoff GET, the shell token-drain curl, a PowerShell header table or the TypeScript spool drain fails the matching front-door test. With the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the `Sec-Fetch-Dest` check removed, the same-origin `document` `GET /handoff` returns 200 and the unit guard test lets a same-origin image through; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residual, closed by setting a bearer token: a browser that sends no fetch metadata even to a loopback host (Safari before 16.4) sends no `Sec-Fetch-*` header and no `Origin` on an image `GET` or a link click, so such a request to a loopback host still reaches `/handoff` (loopback keeps accepting marker-less legacy hooks) and the other, read-only `GET` routes. On a non-loopback host the marker requirement closes `/handoff` for every browser. A plain-HTTP proxy that rewrites `Host` to its loopback upstream and adds no forwarding header (nginx's default `proxy_pass`) looks exactly like a local client, so in front of an unauthenticated server it must add `X-Forwarded-For` or keep `proxy_set_header Host $host`, or the server must sit behind TLS or use a bearer token (`security.md`, `https-via-proxy.md`). Browsers that send fetch metadata no longer have the earlier link residuals: a link opened from another app (`Sec-Fetch-Site: none`) and a link clicked in a stored page (`same-origin` navigation) both carry a non-`empty` destination and are refused. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op || 12d | The web UI and `/api/v1` cannot write, and render stored text inert | `crates/ai-memory-web/clippy.toml` `disallowed-methods`: every `Wiki` write and destructive method (`write_page`, `write_page_if`, `apply_batch`, the delete/evict/purge/restore/move/reindex/remove-dir helpers, `commit_all`, `approve_auto_improve_proposal`) and the `writer()` / `git()` accessors are lint errors in the crate, so the `Wiki` held by `WebState` stays read-only under `cargo clippy -D warnings`; only the integration-test module carries the `allow`, for fixtures. Templates are askama with HTML auto-escaping; the history diff (`templates/history.html`) and the session timeline (`templates/session.html`) print page lines, observation titles and bodies escaped, with no `|safe`, and no captured value is interpolated into a script | `ai-memory-web` `history_replay.rs` `session_timeline_renders_captured_markup_inert` (a `<script>` title and body plus `"><img onerror>` and `' onmouseover='` payloads, checked to survive ingest first, render escaped) and `history_diff_renders_page_markup_inert` (the same payloads in a page version's diff lines); `mount.rs` `web_surfaces_refuse_to_be_framed` covers the history, timeline and history-API routes (200 with both anti-framing headers) | STRONG. Bite checks: a `Wiki::write_page` and a `Wiki::delete_page` call added to `routes/history.rs` fail `cargo clippy -p ai-memory-web --all-targets -- -D warnings` with `use of a disallowed method`; `|safe` on the observation body or a diff line fails the matching inert-render test. The lint is per crate: a write reached through another crate's helper is outside it, which review and the `/api/v1` "zero writer calls" rule still cover |diff --git a/docs/windows.md b/docs/windows.mdindex e2cbe023..2b878458 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -180,6 +180,12 @@ the fast native hook path **without** installing a Rust toolchain orDocker. Each tagged release publishes`ai-memory-windows-x86_64.zip` (see the repo's Releases page).+`install.sh` does not cover native Windows. `ai-memory setup` runs here, but it+has no service step on Windows: it initialises the data dir and wires your+agents, and says so when it skips the service. Start the server yourself, or+register it with Scenario E. Inside WSL2 the Linux `install.sh` and `setup`+path works unchanged.+```powershell# First-time install: download + extract into your user data dir (any stable# path works; the native hook exec-form command is rendered from whereverdiff --git a/install.sh b/install.shnew file mode 100755index 00000000..be30fa95--- /dev/null+++ b/install.sh@@ -0,0 +1,209 @@+#!/bin/sh+# Install the ai-memory release binary for the current user.+#+# curl -fsSL https://github.com/akitaonrails/ai-memory/releases/latest/download/install.sh | sh+#+# Downloads ai-memory-<os>-<arch>.tar.gz from a GitHub release, verifies it+# against the release's published .sha256 file, unpacks it under+# ~/.local/lib/ai-memory and links ~/.local/bin/ai-memory to the binary. No+# sudo, and nothing outside those two directories is touched. A missing or+# mismatched checksum stops the install before anything is unpacked.+#+# Then run `ai-memory setup` to create the data dir, start the user service+# and wire your agents.+#+# Environment (all optional):+# AI_MEMORY_VERSION release to install, e.g. 2.7.0 (default: latest)+# AI_MEMORY_BIN_DIR where the `ai-memory` link goes (default: ~/.local/bin)+# AI_MEMORY_LIB_DIR where the release is unpacked+# (default: ~/.local/lib/ai-memory)+# AI_MEMORY_RELEASE_BASE_URL Releases-compatible URL prefix, the one+# `ai-memory upgrade` reads (default: GitHub).+# The checksum comes from the same place as the+# archive, so point it only at an origin you trust.+# AI_MEMORY_INSTALL_TARGET force a target: linux-x86_64, linux-aarch64,+# macos-x86_64 or macos-aarch64+#+# Everything runs inside main(), called on the last line, so a download cut+# short runs nothing.++set -eu++DEFAULT_RELEASE_BASE="https://github.com/akitaonrails/ai-memory/releases"++say() {+ printf 'ai-memory install: %s\n' "$*"+}++die() {+ printf 'ai-memory install: error: %s\n' "$*" >&2+ exit 1+}++detect_target() {+ if [ -n "${AI_MEMORY_INSTALL_TARGET:-}" ]; then+ case "$AI_MEMORY_INSTALL_TARGET" in+ linux-x86_64 | linux-aarch64 | macos-x86_64 | macos-aarch64)+ printf '%s\n' "$AI_MEMORY_INSTALL_TARGET"+ return 0+ ;;+ *) die "AI_MEMORY_INSTALL_TARGET must be linux-x86_64, linux-aarch64, macos-x86_64 or macos-aarch64" ;;+ esac+ fi+ os="$(uname -s)"+ arch="$(uname -m)"+ case "$os" in+ Linux) os=linux ;;+ Darwin) os=macos ;;+ MINGW* | MSYS* | CYGWIN* | Windows_NT)+ die "Windows is not supported by this script; download ai-memory-windows-x86_64.zip from the release page and follow docs/windows.md"+ ;;+ *) die "unsupported operating system: $os" ;;+ esac+ case "$arch" in+ x86_64 | amd64) arch=x86_64 ;;+ aarch64 | arm64) arch=aarch64 ;;+ *) die "unsupported architecture: $arch" ;;+ esac+ # An x86_64 shell under Rosetta on Apple Silicon still wants the native build.+ if [ "$os" = macos ] && [ "$arch" = x86_64 ] &&+ [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 1 ]; then+ arch=aarch64+ fi+ printf '%s-%s\n' "$os" "$arch"+}++# download <url> <dest>: fails on any HTTP error, so a missing file never+# leaves a page of HTML behind.+download() {+ if command -v curl >/dev/null 2>&1; then+ if [ "$release_base" = "$DEFAULT_RELEASE_BASE" ]; then+ curl -fsSL --proto '=https' --tlsv1.2 -o "$2" "$1"+ else+ curl -fsSL -o "$2" "$1"+ fi+ elif command -v wget >/dev/null 2>&1; then+ wget -q -O "$2" "$1"+ else+ die "curl or wget is required"+ fi+}++sha256_of() {+ if command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$1" | awk '{print $1}'+ elif command -v shasum >/dev/null 2>&1; then+ shasum -a 256 "$1" | awk '{print $1}'+ elif command -v openssl >/dev/null 2>&1; then+ openssl dgst -sha256 "$1" | awk '{print $NF}'+ else+ die "no SHA-256 tool found (sha256sum, shasum or openssl)"+ fi+}++# verify <archive> <checksum-file> <asset-name>+verify() {+ # The sidecar is "<hex> <asset>": one line, for exactly this asset.+ line="$(head -n 1 "$2")"+ expected="$(printf '%s\n' "$line" | awk '{print $1}')"+ named="$(printf '%s\n' "$line" | awk '{print $2}' | sed 's/^\*//')"+ case "$expected" in+ *[!0-9a-f]* | "") die "checksum file for $3 is malformed; refusing installation" ;;+ esac+ [ "${#expected}" -eq 64 ] || die "checksum file for $3 is malformed; refusing installation"+ [ "$named" = "$3" ] || die "checksum file names '$named', not $3; refusing installation"+ actual="$(sha256_of "$1")"+ [ "$actual" = "$expected" ] || die "checksum mismatch for $3 (expected $expected, got $actual); refusing installation"+}++# Refuse an archive with an absolute or parent-relative member before tar+# writes anything.+check_members() {+ tar -tzf "$1" >"$2" || die "cannot read $3"+ while IFS= read -r member; do+ case "$member" in+ /* | ../* | */../* | .. | */..) die "$3 contains an unsafe path ($member); refusing installation" ;;+ esac+ done <"$2"+}++main() {+ home="${HOME:-}"+ [ -n "$home" ] || die "HOME is not set"+ bin_dir="${AI_MEMORY_BIN_DIR:-$home/.local/bin}"+ lib_dir="${AI_MEMORY_LIB_DIR:-$home/.local/lib/ai-memory}"+ release_base="${AI_MEMORY_RELEASE_BASE_URL:-$DEFAULT_RELEASE_BASE}"+ release_base="${release_base%/}"+ version="${AI_MEMORY_VERSION:-latest}"++ case "$bin_dir$lib_dir" in+ *"+"*) die "install paths must not contain a newline" ;;+ esac+ case "$version" in+ latest) url_dir="$release_base/latest/download" ;;+ *[!0-9A-Za-z.+-]*) die "AI_MEMORY_VERSION must look like 2.7.0" ;;+ v*) url_dir="$release_base/download/$version" ;;+ *) url_dir="$release_base/download/v$version" ;;+ esac++ target="$(detect_target)"+ asset="ai-memory-$target.tar.gz"+ link="$bin_dir/ai-memory"++ # Never replace something this script did not put there: a Docker wrapper+ # or a hand-built binary at the same path is the user's.+ if [ -e "$link" ] || [ -L "$link" ]; then+ [ -L "$link" ] || die "$link already exists and is not a link to an install.sh release; move it aside or set AI_MEMORY_BIN_DIR"+ fi+ if [ -e "$lib_dir" ] && [ ! -f "$lib_dir/ai-memory" ]; then+ die "$lib_dir exists but holds no ai-memory release; move it aside or set AI_MEMORY_LIB_DIR"+ fi++ work="$(mktemp -d "${TMPDIR:-/tmp}/ai-memory-install.XXXXXX")"+ trap 'rm -rf "$work"' EXIT+ trap 'exit 1' INT TERM++ say "downloading $asset ($version)"+ download "$url_dir/$asset" "$work/$asset" || die "could not download $url_dir/$asset"+ download "$url_dir/$asset.sha256" "$work/$asset.sha256" ||+ die "could not download $url_dir/$asset.sha256; refusing installation without a checksum"+ verify "$work/$asset" "$work/$asset.sha256" "$asset"+ say "checksum verified"++ check_members "$work/$asset" "$work/members" "$asset"+ mkdir -p "$work/release"+ tar -xzf "$work/$asset" -C "$work/release"+ [ -f "$work/release/ai-memory" ] || die "$asset has no ai-memory binary"+ chmod 0755 "$work/release/ai-memory"+ "$work/release/ai-memory" --version >/dev/null 2>&1 ||+ die "the downloaded binary does not run on this machine"++ mkdir -p "$(dirname "$lib_dir")" "$bin_dir"+ staged="$lib_dir.new.$$"+ rm -rf "$staged"+ mv "$work/release" "$staged"+ if [ -e "$lib_dir" ]; then+ previous="$lib_dir.old.$$"+ mv "$lib_dir" "$previous"+ if ! mv "$staged" "$lib_dir"; then+ mv "$previous" "$lib_dir"+ die "could not move the new release into $lib_dir; the previous one was kept"+ fi+ rm -rf "$previous"+ else+ mv "$staged" "$lib_dir"+ fi+ rm -f "$link"+ ln -s "$lib_dir/ai-memory" "$link"++ say "installed $("$link" --version 2>/dev/null || echo ai-memory) to $lib_dir"+ say "linked $link"+ case ":${PATH:-}:" in+ *":$bin_dir:"*) ;;+ *) say "$bin_dir is not on PATH; add it, e.g. export PATH=\"$bin_dir:\$PATH\"" ;;+ esac+ say "next: ai-memory setup"+}++main "$@"diff --git a/scripts/onboarding-acceptance.sh b/scripts/onboarding-acceptance.shnew file mode 100755index 00000000..a1964f4f--- /dev/null+++ b/scripts/onboarding-acceptance.sh@@ -0,0 +1,227 @@+#!/usr/bin/env bash+# Onboarding acceptance: commands and time from nothing to the first memory.+#+# In a clean temporary HOME, with nothing from the real one:+# 1. `curl -fsSL <release>/install.sh | sh` against a release tarball built+# from a local binary and served over local HTTP;+# 2. `ai-memory setup --yes`, with a stand-in service manager first on PATH+# (`systemctl` on Linux, `launchctl` on macOS) that runs the rendered+# unit's command in the background and never reaches a real session;+# 3. one synthetic hook event, as the installed Claude Code hook sends it;+# 4. `memory_query` over `ai-memory mcp-bridge` until it returns the event.+#+# Reports the user-facing command count (target 2) and the time from the first+# command to the memory being returned (target <= 60 s). Local embeddings are+# off so the optional model download is not in the measurement.+#+# Usage: scripts/onboarding-acceptance.sh [path/to/ai-memory]+# default binary: target/release/ai-memory, else target/debug/ai-memory+# KEEP=1 keeps the temp dir for inspection.+# Needs: curl, tar, python3, and sha256sum or shasum.++set -euo pipefail++repo="$(cd "$(dirname "$0")/.." && pwd)"+bin="${1:-}"+if [ -z "$bin" ]; then+ for candidate in "$repo/target/release/ai-memory" "$repo/target/debug/ai-memory"; do+ if [ -x "$candidate" ]; then bin="$candidate"; break; fi+ done+fi+[ -n "$bin" ] && [ -x "$bin" ] || { echo "no ai-memory binary; build one or pass its path" >&2; exit 2; }+bin="$(cd "$(dirname "$bin")" && pwd)/$(basename "$bin")"++# The commands the tarball path in docs/install.md and docs/macos.md asks for+# before the first captured observation, for comparison.+baseline=(+ "curl -fsSL -O <release>/ai-memory-<os>-<arch>.tar.gz"+ "tar -xzf ai-memory-<os>-<arch>.tar.gz"+ "ai-memory init"+ "write a systemd user unit or LaunchAgent by hand"+ "systemctl --user daemon-reload (or launchctl bootstrap)"+ "systemctl --user enable --now ai-memory.service"+ "ai-memory install-mcp --client claude-code --apply"+ "ai-memory install-hooks --agent claude-code --apply"+ "ai-memory install-skills --scope global"+)++case "$(uname -s)-$(uname -m)" in+ Linux-x86_64 | Linux-amd64) target=linux-x86_64 ;;+ Linux-aarch64 | Linux-arm64) target=linux-aarch64 ;;+ Darwin-arm64 | Darwin-aarch64) target=macos-aarch64 ;;+ Darwin-x86_64) target=macos-x86_64 ;;+ *) echo "unsupported host $(uname -s)-$(uname -m)" >&2; exit 2 ;;+esac+asset="ai-memory-$target.tar.gz"++work="$(mktemp -d "${TMPDIR:-/tmp}/ai-memory-onboarding.XXXXXX")"+server_pid=""+cleanup() {+ if [ -f "$work/service/pid" ]; then kill "$(cat "$work/service/pid")" 2>/dev/null || true; fi+ if [ -n "$server_pid" ]; then kill "$server_pid" 2>/dev/null || true; fi+ if [ "${KEEP:-0}" = 1 ]; then echo "kept $work"; else rm -rf "$work"; fi+}+trap cleanup EXIT++sha256() {+ if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}'+ else shasum -a 256 "$1" | awk '{print $1}'; fi+}++# A release laid out the way release.yml publishes one.+release="$work/release/latest/download"+mkdir -p "$release" "$work/stage/packaging"+cp "$bin" "$work/stage/ai-memory"+cp -R "$repo/hooks" "$work/stage/hooks"+cp -R "$repo/packaging/systemd" "$repo/packaging/launchd" "$work/stage/packaging/"+(cd "$work/stage" && COPYFILE_DISABLE=1 tar -czf "$release/$asset" .)+printf '%s %s\n' "$(sha256 "$release/$asset")" "$asset" > "$release/$asset.sha256"+cp "$repo/install.sh" "$release/install.sh"++free_port() {+ python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])'+}+http_port="$(free_port)"+python3 -m http.server "$http_port" --bind 127.0.0.1 --directory "$work" >"$work/http.log" 2>&1 &+server_pid=$!+for _ in $(seq 1 50); do+ curl -fs "http://127.0.0.1:$http_port/release/latest/download/install.sh" >/dev/null 2>&1 && break+ sleep 0.1+done+base="http://127.0.0.1:$http_port/release"++# The stand-in service managers. Each records its calls and runs the+# rendered service's command in the background.+mkdir -p "$work/fakebin" "$work/service"+cat > "$work/fakebin/systemctl" <<'EOF'+#!/bin/sh+state="$FAKE_SERVICE_STATE"+printf '%s\n' "$*" >> "$state/calls"+[ "$1" = "--user" ] || exit 2+shift+unit="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/ai-memory.service"+alive() { [ -f "$state/pid" ] && kill -0 "$(cat "$state/pid")" 2>/dev/null; }+case "$1" in+ daemon-reload) ;;+ enable) touch "$state/enabled" ;;+ is-enabled) [ -f "$state/enabled" ] ;;+ is-active) alive ;;+ restart)+ if alive; then kill "$(cat "$state/pid")"; sleep 0.2; fi+ line="$(sed -n 's/^ExecStart=//p' "$unit")"+ eval "set -- $line"+ "$@" >"$state/server.log" 2>&1 &+ echo $! > "$state/pid" ;;+ *) exit 3 ;;+esac+EOF+cat > "$work/fakebin/launchctl" <<'EOF'+#!/bin/sh+state="$FAKE_SERVICE_STATE"+printf '%s\n' "$*" >> "$state/calls"+alive() { [ -f "$state/pid" ] && kill -0 "$(cat "$state/pid")" 2>/dev/null; }+case "$1" in+ print) alive ;;+ bootout) if alive; then kill "$(cat "$state/pid")"; fi; rm -f "$state/pid" ;;+ bootstrap)+ python3 -c 'import plistlib, subprocess, sys+args = plistlib.load(open(sys.argv[1], "rb"))["ProgramArguments"]+log = open(sys.argv[2], "w")+print(subprocess.Popen(args, stdout=log, stderr=log, start_new_session=True).pid)' \+ "$3" "$state/server.log" > "$state/pid" ;;+ *) exit 3 ;;+esac+EOF+chmod +x "$work/fakebin/systemctl" "$work/fakebin/launchctl"++home="$work/home"+mkdir -p "$home/.claude/projects" "$home/work/repo"+printf 'workspace = "onboarding"\nproject = "acceptance"\n' > "$home/work/repo/.ai-memory.toml"+port="$(free_port)"++# A clean login: nothing from the caller's environment but a basic PATH.+clean() {+ env -i \+ HOME="$home" \+ TMPDIR="$work" \+ LANG=C.UTF-8 \+ PATH="$work/fakebin:$home/.local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \+ FAKE_SERVICE_STATE="$work/service" \+ AI_MEMORY_RELEASE_BASE_URL="$base" \+ AI_MEMORY_BIND="127.0.0.1:$port" \+ AI_MEMORY_SERVER_URL="http://127.0.0.1:$port" \+ AI_MEMORY_EMBEDDING_PROVIDER=none \+ RUST_LOG=off \+ "$@"+}++now() { python3 -c 'import time; print(time.time())'; }++commands=0+start="$(now)"++echo "== 1. curl -fsSL $base/latest/download/install.sh | sh"+commands=$((commands + 1))+clean sh -c "curl -fsSL '$base/latest/download/install.sh' | sh"++echo "== 2. ai-memory setup --yes"+commands=$((commands + 1))+(cd "$home" && clean ai-memory setup --yes)+installed="$(now)"++echo "== hook event + memory_query"+marker="onboarding-acceptance-$(date +%s)-$$"+payload="{\"session_id\":\"$marker-session\",\"cwd\":\"$home/work/repo\",\"prompt\":\"please remember $marker\"}"+printf '%s' "$payload" | clean ai-memory hook --event user-prompt-submit --agent claude-code \+ --server-url "http://127.0.0.1:$port" >/dev/null+clean ai-memory hook-drain >/dev/null++found=""+for _ in $(seq 1 100); do+ if clean python3 - "$marker" <<'EOF'+import json, subprocess, sys+marker = sys.argv[1]+bridge = subprocess.Popen(+ ["ai-memory", "mcp-bridge", "--no-session-id"],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True,+)+def send(message):+ bridge.stdin.write(json.dumps(message) + "\n")+ bridge.stdin.flush()+def reply(wanted):+ for line in bridge.stdout:+ message = json.loads(line)+ if message.get("id") == wanted:+ return message+send({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {+ "protocolVersion": "2025-06-18", "capabilities": {},+ "clientInfo": {"name": "onboarding-acceptance", "version": "0"}}})+reply(1)+send({"jsonrpc": "2.0", "method": "notifications/initialized"})+send({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {+ "name": "memory_query",+ "arguments": {"query": marker, "workspace": "onboarding", "project": "acceptance"}}})+answer = reply(2)+bridge.stdin.close()+bridge.wait(timeout=10)+sys.exit(0 if marker in json.dumps(answer) else 1)+EOF+ then+ found="$(now)"+ break+ fi+ sleep 0.2+done+[ -n "$found" ] || { echo "memory_query never returned the hook event" >&2; exit 1; }++python3 - "$start" "$installed" "$found" "$commands" "${#baseline[@]}" <<'EOF'+import sys+start, installed, found = map(float, sys.argv[1:4])+commands, baseline = int(sys.argv[4]), int(sys.argv[5])+total = found - start+print()+print(f"commands from zero to first memory: {commands} (target 2; manual tarball path: {baseline})")+print(f"install + setup: {installed - start:.1f}s")+print(f"time to first memory: {total:.1f}s (target <= 60s, model download excluded)")+sys.exit(0 if commands <= 2 and total <= 60 else 1)+EOF