Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(windows): install.ps1 and a setup service step on Windows
AkitaOnRailsa4f23d3950dd
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex bef6fa0b..d779f51f 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -560,13 +560,15 @@ jobs:sha256sum ai-memory-claude-plugin.zip > ai-memory-claude-plugin.zip.sha256)- - name: Stage checksum-verified install script+ - name: Stage checksum-verified install scriptsrun: |set -euo pipefailinstall -m 0755 install.sh artifacts/install.sh+ install -m 0644 install.ps1 artifacts/install.ps1(cd artifactssha256sum install.sh > install.sh.sha256+ sha256sum install.ps1 > install.ps1.sha256)- name: Generate release body@@ -594,8 +596,9 @@ jobs:echo "# macOS aarch64/x86_64 (no toolchain): download the matching ai-memory-macos-<arch>.tar.gz below," >> body.mdecho "# extract it, and follow the bundled docs/macos.md." >> body.mdecho "" >> body.md- echo "# Windows x86_64 (no toolchain): download ai-memory-windows-x86_64.zip below," >> body.md- echo "# extract it, and follow the bundled docs/windows.md." >> body.md+ echo "# Windows x86_64, no admin (PowerShell): checksum-verified release under %LOCALAPPDATA%\\Programs, then one-step setup" >> body.md+ echo "\$env:AI_MEMORY_VERSION='${{ needs.validate-version.outputs.version }}'; irm https://github.com/akitaonrails/ai-memory/releases/download/${GITHUB_REF_NAME}/install.ps1 | iex" >> body.md+ echo "ai-memory setup" >> body.mdecho "" >> body.mdecho "# From source" >> body.mdecho "cargo install --locked --git https://github.com/akitaonrails/ai-memory --tag ${GITHUB_REF_NAME}" >> body.mddiff --git a/.github/workflows/windows.yml b/.github/workflows/windows.ymlindex daec90c6..f8a59605 100644--- a/.github/workflows/windows.yml+++ b/.github/workflows/windows.yml@@ -103,8 +103,12 @@ jobs:- 'crates/ai-memory-store/**'- 'crates/ai-memory-hooks/**'- 'crates/ai-memory-cli/src/commands/install_hooks.rs'+ - 'crates/ai-memory-cli/src/commands/service_host.rs'+ - 'crates/ai-memory-cli/src/commands/user_service.rs'- 'hooks/**'- 'tests/hooks/**'+ - 'install.ps1'+ - 'tests/install_ps1.ps1'- '.github/workflows/windows.yml'test:@@ -123,6 +127,8 @@ jobs:- uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable- uses: Swatinem/rust-cache@f0d9c3887740aee45f6153b24b3a6b815192ec16 # v2- run: cargo test --workspace --all-targets+ - name: install.ps1 against local releases+ run: pwsh -NoProfile -File tests/install_ps1.ps1 -Binary target/debug/ai-memory.exe- name: Check the external lifecycle relayenv:CARGO_TARGET_DIR: ${{ github.workspace }}/targetdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4389819c..62e2b27b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -39,6 +39,18 @@ version in [`docs/changelog/`](docs/changelog/):directory), numbers the agents, and lists the other agents `--agent`accepts. At the prompt you can type the numbers of the agents to wireinstead of `y`; a number outside the plan changes nothing. (#1270)+- Added a native Windows path to the two-command install. `install.ps1`,+ published with each release next to its own `.sha256`, checks the release+ zip against that checksum, refuses archive entries that are absolute or+ hold `..`, unpacks it under `%LOCALAPPDATA%\Programs\ai-memory` and adds+ that directory to the user `PATH` (`AI_MEMORY_NO_MODIFY_PATH=1` skips it),+ with no administrator rights. `ai-memory setup` now has a service step on+ Windows: it writes an `ai-memory` value under the per-user `Run` key that+ starts a hidden `ai-memory service-host` at logon, and starts it right away.+ The host runs the server with no console window and restarts it after a+ failure, giving up after five failures within ten seconds of starting.+ `ai-memory uninstall --apply` stops the host and removes the value when it+ still has the shape `setup` writes. (#1271)### Changed- `ai-memory setup` now ends by naming the agents to restart and the questiondiff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex ac8a1a5e..7c965bf4 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -1,7 +1,7 @@# 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.+You are an AI coding agent and your user asked you to install ai-memory. It+takes two commands, and neither needs root or administrator rights.1. Install the release binary. The script checks the download against therelease's published SHA-256 checksum, puts the binary under@@ -14,6 +14,16 @@ Linux or macOS it takes two commands, and neither needs root.If `~/.local/bin` is not on `PATH`, call `~/.local/bin/ai-memory` directlyin the next step, and tell your user to add the directory to `PATH`.+ On native Windows, in PowerShell, the equivalent script unpacks the release+ under `%LOCALAPPDATA%\Programs\ai-memory` and adds it to the user `PATH`:++ ```powershell+ irm https://github.com/akitaonrails/ai-memory/releases/latest/download/install.ps1 | iex+ ```++ A shell started before the install does not see the new `PATH`; call+ `& "$env:LOCALAPPDATA\Programs\ai-memory\ai-memory.exe"` directly there.+2. Set it up for yourself, naming your own harness:```bash@@ -30,7 +40,8 @@ Linux or macOS it takes two commands, and neither needs root.`setup` creates the data directory with a root bearer token in an owner-onlyfile, starts a per-user service (systemd `--user` on Linux, a LaunchAgent on-macOS), registers the MCP server and installs the lifecycle hooks and Agent+macOS, a logon entry on Windows that runs the server with no console window),+registers the MCP server and installs the lifecycle hooks and AgentSkills for each harness, then checks that the server answers. The token isnever printed and never written into a harness config. Running `setup` againchanges nothing.@@ -43,7 +54,7 @@ Afterwards: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.+- Inside WSL2, use the Linux commands; native Windows details are in+ [`docs/windows.md`](docs/windows.md).Full reference: [`docs/install.md`](docs/install.md#one-step-native-install-installsh--ai-memory-setup).diff --git a/README.md b/README.mdindex 2337a411..7fdfdfae 100644--- a/README.md+++ b/README.md@@ -232,6 +232,23 @@ codex plugin marketplace add akitaonrails/ai-memory && codex plugin add ai-memorCodex then asks you to trust the hooks in `/hooks`. See[Marketplace plugins](docs/install.md#marketplace-plugins).+### Windows (two commands, no admin)++In PowerShell:++```powershell+irm https://github.com/akitaonrails/ai-memory/releases/latest/download/install.ps1 | iex+ai-memory setup+```++`install.ps1` checks the release zip against its published SHA-256 checksum,+unpacks it under `%LOCALAPPDATA%\Programs\ai-memory` and adds that directory+to your user `PATH`. `ai-memory setup` then does what it does on Linux and+macOS, with a logon entry in place of the service: the server starts when you+sign in, with no console window, and restarts if it fails. Details and the+other Windows setups (WSL2, Docker Desktop, a real Windows service) are in+[`docs/windows.md`](docs/windows.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 b787cdda..0489a60c 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -238,6 +238,11 @@ pub enum Command {/// Hidden hook spool drainer used by native session-end hooks.#[command(hide = true, name = "hook-drain")]HookDrain(HookDrainArgs),+ /// Hidden Windows background host the logon entry `setup` installs+ /// starts: it runs `serve` with no console window and restarts it after+ /// a failure.+ #[command(hide = true, name = "service-host")]+ ServiceHost(ServiceHostArgs),/// Generate the marketplace plugins under `plugins/` and their catalogs/// (maintainer tool: `bin/release` and the drift test call it).#[command(hide = true, name = "render-plugins")]@@ -3107,6 +3112,14 @@ pub struct HookArgs {#[derive(Debug, Args)]pub struct HookDrainArgs {}+/// Arguments for hidden `service-host`.+#[derive(Debug, Args)]+pub struct ServiceHostArgs {+ /// Run the supervisor in this process instead of starting it detached.+ #[arg(long)]+ pub supervise: bool,+}+/// Arguments for hidden `render-plugins`.#[derive(Debug, Args)]pub struct RenderPluginsArgs {diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 6ea42772..58543830 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -104,6 +104,7 @@ pub mod run_autowire;pub mod search;pub mod serve;pub mod server;+pub mod service_host;pub mod setup;pub mod setup_agent;pub mod show;diff --git a/crates/ai-memory-cli/src/commands/service_host.rs b/crates/ai-memory-cli/src/commands/service_host.rsnew file mode 100644index 00000000..1ef573c4--- /dev/null+++ b/crates/ai-memory-cli/src/commands/service_host.rs@@ -0,0 +1,480 @@+//! `ai-memory service-host`: the background host behind the Windows logon+//! entry `ai-memory setup` installs.+//!+//! Windows has no per-user service manager like systemd `--user` or launchd.+//! A real Windows service needs an administrator to install it and, because+//! the data dir lives in the user's profile, the account password to run it+//! (docs/windows.md, Scenario E). A Scheduled Task runs its action inside a+//! job object that kills the server's process tree when the action exits, and+//! shows a console window while it runs. So `setup` writes an `ai-memory`+//! value under the per-user `HKCU\...\CurrentVersion\Run` key instead, which+//! needs no elevation, and that value runs this command at every logon:+//!+//! 1. Without `--supervise`, `service-host` starts itself again detached from+//! any console (`DETACHED_PROCESS | CREATE_NO_WINDOW`, breaking away from a+//! job when allowed) and exits, so the logon console closes at once.+//! 2. With `--supervise`, it runs `serve --transport http --enable-web` on the+//! same data dir and config with a hidden console (`CREATE_NO_WINDOW`), so+//! neither the server nor a process it starts (the Git CLI fallback, a+//! provider CLI) opens a window. It waits on the server and restarts it+//! after a failure, the way `Restart=on-failure` and launchd's `KeepAlive`+//! do, until the server exits cleanly or keeps failing within seconds of+//! starting (another server on the port, a broken config).+//!+//! The supervisor records its own pid and the server's in+//! `<data_dir>/service-host.json`, which `setup` reads to tell whether the+//! host runs and `uninstall` reads to stop it.++use std::path::{Path, PathBuf};+use std::time::{Duration, Instant};++use anyhow::{Context as _, Result};++use super::user_service::CommandRunner;+use crate::cli::ServiceHostArgs;+use crate::config::Config;++/// The host's state file name, under the data dir.+const STATE_FILE: &str = "service-host.json";++/// Wait before restarting a server that failed.+const RESTART_DELAY: Duration = Duration::from_secs(5);+/// A server that fails sooner than this after starting counts as a quick+/// failure; [`MAX_QUICK_FAILURES`] in a row stop the host.+const QUICK_FAILURE: Duration = Duration::from_secs(10);+const MAX_QUICK_FAILURES: u32 = 5;++/// What the running host recorded about itself.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub(crate) struct HostState {+ pub(crate) supervisor_pid: u32,+ pub(crate) server_pid: Option<u32>,+}++/// Where the host keeps its state for this data dir.+pub(crate) fn state_file(data_dir: &Path) -> PathBuf {+ data_dir.join(STATE_FILE)+}++fn read_state(path: &Path) -> Option<HostState> {+ let text = std::fs::read_to_string(path).ok()?;+ serde_json::from_str(&text).ok()+}++fn write_state(path: &Path, state: HostState) -> Result<()> {+ let text = serde_json::to_string(&state)?;+ ai_memory_wiki::write_atomic(path, text.as_bytes())+ .with_context(|| format!("writing {}", path.display()))?;+ Ok(())+}++/// Whether `pid` is a live ai-memory process. A recorded pid the system has+/// since handed to another program does not count.+fn is_live_ai_memory(pid: u32) -> bool {+ use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};+ let pid = Pid::from_u32(pid);+ let mut system = System::new();+ system.refresh_processes_specifics(+ ProcessesToUpdate::Some(&[pid]),+ true,+ ProcessRefreshKind::new(),+ );+ system.process(pid).is_some_and(|process| {+ process+ .name()+ .to_string_lossy()+ .to_ascii_lowercase()+ .starts_with("ai-memory")+ })+}++/// The recorded host when its supervisor is still alive.+pub(crate) fn running(state_file: &Path) -> Option<HostState> {+ read_state(state_file).filter(|state| is_live_ai_memory(state.supervisor_pid))+}++/// Every live pid the host recorded, supervisor first; `uninstall+/// --purge-data` leaves them out of its live-process check because it is+/// about to stop them.+pub(crate) fn live_pids(state_file: &Path) -> Vec<u32> {+ read_state(state_file)+ .map(|state| {+ std::iter::once(state.supervisor_pid)+ .chain(state.server_pid)+ .filter(|pid| is_live_ai_memory(*pid))+ .collect()+ })+ .unwrap_or_default()+}++/// Stop a running host: the supervisor's process tree, then a server left+/// behind by a supervisor that already died. A host that is not running is+/// no error. The state file goes with it.+///+/// # Errors+/// When `taskkill` could not be run, or refused a process that is still+/// alive afterwards.+pub(crate) fn stop(state_file: &Path, runner: &dyn CommandRunner) -> Result<()> {+ for pid in live_pids(state_file) {+ let pid_text = pid.to_string();+ let outcome = runner.run("taskkill", &["/PID", &pid_text, "/T", "/F"])?;+ if !outcome.success && is_live_ai_memory(pid) {+ anyhow::bail!(+ "`taskkill /PID {pid} /T /F` failed: {}",+ outcome.stderr.trim()+ );+ }+ }+ match std::fs::remove_file(state_file) {+ Err(error) if error.kind() != std::io::ErrorKind::NotFound => {+ Err(error).with_context(|| format!("removing {}", state_file.display()))+ }+ _ => Ok(()),+ }+}++/// What the supervisor does after the server exits.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Next {+ Stop,+ RestartAfter(Duration),+}++/// Decide after one server run. A clean exit is deliberate and ends the host;+/// a failure restarts it, unless the server has now failed quickly+/// [`MAX_QUICK_FAILURES`] times in a row, which a restart would not fix.+fn after_exit(succeeded: bool, ran: Duration, quick_failures: &mut u32) -> Next {+ if succeeded {+ return Next::Stop;+ }+ if ran < QUICK_FAILURE {+ *quick_failures += 1;+ } else {+ *quick_failures = 1;+ }+ if *quick_failures >= MAX_QUICK_FAILURES {+ Next::Stop+ } else {+ Next::RestartAfter(RESTART_DELAY)+ }+}++/// Run the server again and again per [`after_exit`]. `run_server` starts one+/// server, reports its pid through `started`, waits for it, and returns+/// whether it exited successfully. Returns the last outcome.+fn supervise(+ mut run_server: impl FnMut(&mut dyn FnMut(u32)) -> Result<bool>,+ mut started: impl FnMut(u32),+ mut sleep: impl FnMut(Duration),+ clock: impl Fn() -> Instant,+) -> Result<bool> {+ let mut quick_failures = 0;+ loop {+ let began = clock();+ let succeeded = run_server(&mut started)?;+ match after_exit(succeeded, clock() - began, &mut quick_failures) {+ Next::Stop => return Ok(succeeded),+ Next::RestartAfter(delay) => sleep(delay),+ }+ }+}++/// The global arguments that point a child at this install.+fn install_args(config: &Config, config_path: Option<&Path>) -> Vec<std::ffi::OsString> {+ let mut args = vec![+ "--data-dir".into(),+ config.data_dir.clone().into_os_string(),+ ];+ if let Some(path) = config_path {+ args.push("--config".into());+ args.push(path.as_os_str().to_owned());+ }+ args+}++/// Run `service-host`.+///+/// # Errors+/// On a platform other than Windows, or when the host cannot start itself or+/// the server.+pub async fn run(config: &Config, args: ServiceHostArgs, config_path: Option<&Path>) -> Result<()> {+ if !cfg!(windows) {+ anyhow::bail!(+ "`service-host` is the Windows logon entry's launcher; on this platform `ai-memory \+ setup` installs a systemd user unit or a LaunchAgent instead"+ );+ }+ let exe = std::env::current_exe().context("locating the running ai-memory binary")?;+ let install = install_args(config, config_path);+ if !args.supervise {+ let mut host_args = install.clone();+ host_args.extend(["service-host".into(), "--supervise".into()]);+ return windows::spawn_detached(&exe, &host_args)+ .with_context(|| format!("starting {} service-host --supervise", exe.display()));+ }++ let state_path = state_file(&config.data_dir);+ let own_pid = std::process::id();+ if running(&state_path).is_some_and(|state| state.supervisor_pid != own_pid) {+ // A second logon, or `setup` racing the Run entry: one host serves.+ return Ok(());+ }+ write_state(+ &state_path,+ HostState {+ supervisor_pid: own_pid,+ server_pid: None,+ },+ )?;+ let mut server_args = install;+ server_args.extend(["serve", "--transport", "http", "--enable-web"].map(Into::into));+ let outcome = tokio::task::spawn_blocking(move || {+ supervise(+ |started| windows::run_hidden(&exe, &server_args, started),+ |pid| {+ let state = HostState {+ supervisor_pid: own_pid,+ server_pid: Some(pid),+ };+ if let Err(error) = write_state(&state_path, state) {+ tracing::warn!(error = %format!("{error:#}"), "service-host: recording the server pid");+ }+ },+ std::thread::sleep,+ Instant::now,+ )+ .map(|succeeded| (succeeded, state_path))+ })+ .await+ .context("the service-host supervisor stopped unexpectedly")?;+ let (succeeded, state_path) = outcome?;+ std::fs::remove_file(&state_path).ok();+ if !succeeded {+ tracing::error!(+ "service-host: the server failed {MAX_QUICK_FAILURES} times within {}s of starting; \+ not restarting it. Run `ai-memory serve --transport http` in a terminal to see why.",+ QUICK_FAILURE.as_secs()+ );+ }+ Ok(())+}++#[cfg(windows)]+mod windows {+ use std::ffi::OsString;+ use std::os::windows::process::CommandExt as _;+ use std::path::Path;+ use std::process::{Command, Stdio};++ use anyhow::{Context as _, Result};++ const DETACHED_PROCESS: u32 = 0x0000_0008;+ const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;+ const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;+ const ERROR_ACCESS_DENIED: i32 = 5;++ fn command(exe: &Path, args: &[OsString], flags: u32) -> Command {+ let mut command = Command::new(exe);+ command+ .args(args)+ .creation_flags(flags)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ command+ }++ /// Start the supervisor with no console, out of whatever job started the+ /// logon entry when the job allows it, and do not wait for it.+ pub(super) fn spawn_detached(exe: &Path, args: &[OsString]) -> Result<()> {+ let flags = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW;+ match command(exe, args, flags | CREATE_BREAKAWAY_FROM_JOB).spawn() {+ Ok(_) => Ok(()),+ Err(error) if error.raw_os_error() == Some(ERROR_ACCESS_DENIED) => {+ command(exe, args, flags)+ .spawn()+ .map(|_| ())+ .map_err(Into::into)+ }+ Err(error) => Err(error.into()),+ }+ }++ /// Run the server on a hidden console of its own, which the processes it+ /// starts inherit instead of opening windows, and wait for it.+ pub(super) fn run_hidden(+ exe: &Path,+ args: &[OsString],+ started: &mut dyn FnMut(u32),+ ) -> Result<bool> {+ let mut child = command(exe, args, CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW)+ .spawn()+ .with_context(|| format!("starting {} serve", exe.display()))?;+ started(child.id());+ Ok(child.wait().context("waiting for the server")?.success())+ }+}++#[cfg(not(windows))]+mod windows {+ use std::ffi::OsString;+ use std::path::Path;++ use anyhow::{Result, bail};++ pub(super) fn spawn_detached(_exe: &Path, _args: &[OsString]) -> Result<()> {+ bail!("service-host runs only on Windows")+ }++ pub(super) fn run_hidden(+ _exe: &Path,+ _args: &[OsString],+ _started: &mut dyn FnMut(u32),+ ) -> Result<bool> {+ bail!("service-host runs only on Windows")+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::cell::{Cell, RefCell};++ /// A clean exit stops the host; failures restart it after the delay; a+ /// server that keeps failing quickly stops it on the fifth, and one that+ /// ran a while before failing starts the count over.+ #[test]+ fn restart_policy_follows_exit_status_and_how_long_it_ran() {+ let mut quick = 0;+ assert_eq!(after_exit(true, Duration::ZERO, &mut quick), Next::Stop);+ for _ in 1..MAX_QUICK_FAILURES {+ assert_eq!(+ after_exit(false, Duration::from_secs(1), &mut quick),+ Next::RestartAfter(RESTART_DELAY)+ );+ }+ assert_eq!(+ after_exit(false, Duration::from_secs(1), &mut quick),+ Next::Stop+ );++ let mut quick = MAX_QUICK_FAILURES - 1;+ assert_eq!(+ after_exit(false, Duration::from_secs(3600), &mut quick),+ Next::RestartAfter(RESTART_DELAY)+ );+ assert_eq!(quick, 1);+ }++ /// The loop restarts a failing server, reports each pid, sleeps between+ /// runs, and stops once the server exits cleanly.+ #[test]+ fn supervise_restarts_until_a_clean_exit() {+ let outcomes = RefCell::new(vec![false, false, true].into_iter());+ let pids = RefCell::new(Vec::new());+ let sleeps = Cell::new(0);+ let next_pid = Cell::new(100);+ let succeeded = supervise(+ |started| {+ next_pid.set(next_pid.get() + 1);+ started(next_pid.get());+ Ok(outcomes.borrow_mut().next().unwrap())+ },+ |pid| pids.borrow_mut().push(pid),+ |delay| {+ assert_eq!(delay, RESTART_DELAY);+ sleeps.set(sleeps.get() + 1);+ },+ Instant::now,+ )+ .unwrap();+ assert!(succeeded);+ assert_eq!(*pids.borrow(), vec![101, 102, 103]);+ assert_eq!(sleeps.get(), 2);+ }++ /// A server that never stays up stops the loop instead of spinning.+ #[test]+ fn supervise_gives_up_on_a_server_that_keeps_failing() {+ let runs = Cell::new(0);+ let succeeded = supervise(+ |_| {+ runs.set(runs.get() + 1);+ Ok(false)+ },+ |_| {},+ |_| {},+ Instant::now,+ )+ .unwrap();+ assert!(!succeeded);+ assert_eq!(runs.get(), MAX_QUICK_FAILURES);+ }++ /// A state file naming no live ai-memory process means no host runs, and+ /// stopping it then runs nothing and still removes the stale file.+ #[test]+ fn a_stale_state_file_is_not_a_running_host() {+ struct NoCalls;+ impl CommandRunner for NoCalls {+ fn run(+ &self,+ program: &str,+ _args: &[&str],+ ) -> Result<super::super::user_service::CommandOutcome> {+ panic!("{program} must not run for a dead host");+ }+ }+ let tmp = tempfile::tempdir().unwrap();+ let path = state_file(tmp.path());+ assert_eq!(running(&path), None);+ write_state(+ &path,+ HostState {+ supervisor_pid: u32::MAX - 1,+ server_pid: Some(u32::MAX - 2),+ },+ )+ .unwrap();+ assert_eq!(running(&path), None);+ assert!(live_pids(&path).is_empty());+ stop(&path, &NoCalls).unwrap();+ assert!(!path.exists());+ }++ #[test]+ fn children_are_pointed_at_the_same_install() {+ let config = Config {+ data_dir: PathBuf::from("/data"),+ ..Config::default()+ };+ assert_eq!(+ install_args(&config, Some(Path::new("/data/config.toml"))),+ ["--data-dir", "/data", "--config", "/data/config.toml"]+ .map(std::ffi::OsString::from)+ .to_vec()+ );+ assert_eq!(+ install_args(&config, None),+ ["--data-dir", "/data"]+ .map(std::ffi::OsString::from)+ .to_vec()+ );+ }++ #[test]+ fn service_host_refuses_off_windows() {+ if cfg!(windows) {+ return;+ }+ let config = Config::default();+ let error = tokio::runtime::Builder::new_current_thread()+ .build()+ .unwrap()+ .block_on(run(&config, ServiceHostArgs { supervise: false }, None))+ .unwrap_err()+ .to_string();+ assert!(error.contains("Windows logon entry"), "{error}");+ }+}diff --git a/crates/ai-memory-cli/src/commands/setup.rs b/crates/ai-memory-cli/src/commands/setup.rsindex 95d4676a..94711112 100644--- a/crates/ai-memory-cli/src/commands/setup.rs+++ b/crates/ai-memory-cli/src/commands/setup.rs@@ -7,7 +7,9 @@//! `<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;+//! LaunchAgent, rendered from the packaged templates, or on Windows a+//! logon entry under the per-user `Run` key that starts+//! [`super::service_host`];//! 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@@ -249,6 +251,7 @@ pub async fn run(config: &Config, args: SetupArgs, config_path: Option<&Path>) -&spec,&config.server_url,reachable,+ &user_service::SystemRunner,)};let mut plan = SetupPlan {@@ -443,11 +446,12 @@ fn plan_service(spec: &user_service::ServiceSpec,server_url: &str,reachable: bool,+ runner: &dyn CommandRunner,) -> 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"+ "not supported on this platform; start the server with `ai-memory serve \+ --transport http`".to_owned(),);};@@ -457,7 +461,7 @@ fn plan_service());}match user_service::render(manager, spec) {- Ok(unit) if reachable && !unit.path.exists() => ServicePlan::Skip(format!(+ Ok(unit) if reachable && !unit.exists(runner) => ServicePlan::Skip(format!("a server already answers at {server_url}; leaving it in charge (pass --no-service \to skip this check)")),@@ -484,9 +488,15 @@ fn print_plan(plan: &SetupPlan) {}match &plan.service {ServicePlan::Install(unit) => println!(- " - install and start a {} at {}",+ " - install and start a {} at {}{}",unit.manager.describe(),- unit.path.display()+ unit.path.display(),+ if unit.manager == ServiceManager::WindowsRun {+ " (it starts `ai-memory service-host` at logon, which runs the server with no \+ console window and restarts it after a failure)"+ } else {+ ""+ }),ServicePlan::Skip(reason) => println!(" - service: {reason}"),}@@ -1385,14 +1395,60 @@ mod tests {}#[test]- fn windows_has_no_service_step_and_says_so() {+ fn a_platform_without_a_manager_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 {+ let ServicePlan::Skip(reason) = plan_service(+ None,+ &spec(tmp.path()),+ "http://127.0.0.1:49374",+ false,+ &user_service::SystemRunner,+ ) else {panic!("expected a skip");};- assert!(reason.contains("Windows"), "{reason}");+ assert!(reason.contains("not supported"), "{reason}");+ }++ /// The Windows logon entry is planned like a unit: installed when nothing+ /// answers, left alone when a server answers and no entry of ours exists+ /// (`reg query` finds none), and managed once the entry is there.+ #[test]+ fn the_windows_logon_entry_is_planned_like_a_unit() {+ struct Reg(Option<&'static str>);+ impl CommandRunner for Reg {+ fn run(&self, program: &str, _args: &[&str]) -> Result<user_service::CommandOutcome> {+ assert_eq!(program, "reg");+ Ok(user_service::CommandOutcome {+ success: self.0.is_some(),+ stdout: self.0.map_or_else(String::new, |data| {+ format!("\r\nHKEY_CURRENT_USER\\...\\Run\r\n ai-memory REG_SZ {data}\r\n")+ }),+ stderr: String::new(),+ })+ }+ }+ let tmp = tempfile::tempdir().unwrap();+ let url = "http://127.0.0.1:49374";+ let manager = Some(ServiceManager::WindowsRun);+ let spec = spec(tmp.path());+ assert!(matches!(+ plan_service(manager, &spec, url, false, &Reg(None)),+ ServicePlan::Install(unit) if unit.manager == ServiceManager::WindowsRun+ ));+ assert!(matches!(+ plan_service(manager, &spec, url, true, &Reg(None)),+ ServicePlan::Skip(reason) if reason.contains("already answers")+ ));+ assert!(matches!(+ plan_service(+ manager,+ &spec,+ url,+ true,+ &Reg(Some("\"C:\\ai\\ai-memory.exe\" service-host"))+ ),+ ServicePlan::Install(_)+ ));}#[test]@@ -1403,6 +1459,7 @@ mod tests {&spec(tmp.path()),"https://memory.example.com",true,+ &user_service::SystemRunner,);assert!(matches!(plan, ServicePlan::Skip(reason) if reason.contains("not on this machine"))@@ -1419,18 +1476,34 @@ mod tests {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);+ let plan = plan_service(+ Some(ServiceManager::SystemdUser),+ &spec,+ url,+ true,+ &user_service::SystemRunner,+ );assert!(matches!(plan, ServicePlan::Skip(reason) if reason.contains("already answers")));- let ServicePlan::Install(unit) =- plan_service(Some(ServiceManager::SystemdUser), &spec, url, false)- else {+ let ServicePlan::Install(unit) = plan_service(+ Some(ServiceManager::SystemdUser),+ &spec,+ url,+ false,+ &user_service::SystemRunner,+ ) 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),+ plan_service(+ Some(ServiceManager::SystemdUser),+ &spec,+ url,+ true,+ &user_service::SystemRunner+ ),ServicePlan::Install(_)));}diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex dad55be9..54edc483 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -802,6 +802,7 @@ pub fn run(config: &Config, args: UninstallArgs) -> anyhow::Result<()> {stop_service_guarding_purge(service.as_ref(),args.purge_data,+ &config.data_dir,&user_service::SystemRunner,crate::process_guard::sibling_processes,std::time::Duration::from_secs(5),@@ -910,7 +911,10 @@ fn setup_service(config: &Config) -> Option<(ServiceManager, user_service::Remov.find(|(key, _)| key == "XDG_CONFIG_HOME").map(|(_, value)| PathBuf::from(value));let path = user_service::unit_path(manager, &home, xdg_config_home.as_deref());- Some((manager, user_service::planned_removal(&path)))+ Some((+ manager,+ user_service::planned_removal_for(manager, &path, &user_service::SystemRunner),+ ))}/// Stop the user service `setup` installed, refusing a data purge while any@@ -926,6 +930,7 @@ fn setup_service(config: &Config) -> Option<(ServiceManager, user_service::Removfn stop_service_guarding_purge(service: Option<&(ServiceManager, user_service::Removal)>,purge_data: bool,+ data_dir: &Path,runner: &dyn user_service::CommandRunner,siblings: impl Fn() -> Vec<sysinfo::Pid>,exit_wait: std::time::Duration,@@ -934,22 +939,24 @@ fn stop_service_guarding_purge(Some((manager, user_service::Removal::Removed(path))) => Some((*manager, path)),_ => None,};- let service_pid = if purge_data {- to_stop.and_then(|(manager, _)| service_main_pid(manager, runner))+ let service_pids = if purge_data {+ to_stop.map_or_else(Vec::new, |(manager, _)| {+ service_pids(manager, data_dir, runner)+ })} else {- None+ Vec::new()};if purge_data {let others: Vec<sysinfo::Pid> = siblings().into_iter()- .filter(|pid| Some(pid.as_u32()) != service_pid)+ .filter(|pid| !service_pids.contains(&pid.as_u32())).collect();if !others.is_empty() {anyhow::bail!(crate::process_guard::busy_message("purge data", &others));}}if let Some((manager, path)) = to_stop {- match user_service::remove(manager, path, runner)? {+ match user_service::remove(manager, path, data_dir, runner)? {user_service::Removal::Removed(path) => {println!("✓ stopped and removed the user service {}", path.display());}@@ -961,9 +968,9 @@ fn stop_service_guarding_purge(// give the service's own process a bounded moment to go before the// recheck refuses on it.let mut alive = siblings();- if let Some(service_pid) = service_pid {+ if !service_pids.is_empty() {let deadline = std::time::Instant::now() + exit_wait;- while alive.iter().any(|pid| pid.as_u32() == service_pid)+ while alive.iter().any(|pid| service_pids.contains(&pid.as_u32()))&& std::time::Instant::now() < deadline{std::thread::sleep(std::time::Duration::from_millis(50));@@ -977,6 +984,22 @@ fn stop_service_guarding_purge(Ok(())}+/// The running service's processes, as its manager reports them: the main+/// process for systemd and launchd, and the host's supervisor and server on+/// Windows. Empty when it is not running or the manager cannot say.+fn service_pids(+ manager: ServiceManager,+ data_dir: &Path,+ runner: &dyn user_service::CommandRunner,+) -> Vec<u32> {+ if manager == ServiceManager::WindowsRun {+ return crate::commands::service_host::live_pids(+ &crate::commands::service_host::state_file(data_dir),+ );+ }+ service_main_pid(manager, runner).into_iter().collect()+}+/// The running service's main process, as its manager reports it; `None`/// when it is not running or the manager cannot say.fn service_main_pid(@@ -1017,6 +1040,7 @@ fn service_main_pid(.ok()})?}+ ServiceManager::WindowsRun => return None,};(pid != 0).then_some(pid)}@@ -1838,6 +1862,7 @@ mod tests {let error = stop_service_guarding_purge(Some(&service),true,+ root.path(),&runner,|| pids(&[4242, 777]),Duration::ZERO,@@ -1855,6 +1880,7 @@ mod tests {stop_service_guarding_purge(Some(&service),true,+ root.path(),&runner,|| alive.replace(Vec::new()),Duration::ZERO,@@ -1882,6 +1908,7 @@ mod tests {let error = stop_service_guarding_purge(Some(&service),true,+ root.path(),&runner,|| vec![sysinfo::Pid::from_u32(4242)],Duration::from_millis(120),@@ -1907,6 +1934,7 @@ mod tests {stop_service_guarding_purge(Some(&service),true,+ root.path(),&runner,|| {polls.set(polls.get() + 1);diff --git a/crates/ai-memory-cli/src/commands/user_service.rs b/crates/ai-memory-cli/src/commands/user_service.rsindex 589ce973..0d424e10 100644--- a/crates/ai-memory-cli/src/commands/user_service.rs+++ b/crates/ai-memory-cli/src/commands/user_service.rs@@ -1,5 +1,6 @@//! The per-user service `ai-memory setup` installs: a systemd `--user` unit on-//! Linux, a launchd LaunchAgent on macOS.+//! Linux, a launchd LaunchAgent on macOS, and on Windows an `ai-memory` value+//! under the per-user `Run` key that starts [`super::service_host`] at logon.//!//! Both are rendered from the packaged templates//! (`packaging/systemd/ai-memory-user.service` and@@ -10,8 +11,8 @@//! 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.+//! into a temp dir and record the `systemctl` / `launchctl` / `reg` calls+//! instead of touching a real user session.use std::path::{Path, PathBuf};@@ -40,6 +41,13 @@ 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__/";+/// The per-user key whose values Windows runs at logon, and the value name.+/// No elevation is needed to write it, unlike a Windows service.+pub(crate) const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";+pub(crate) const RUN_VALUE: &str = "ai-memory";+/// The subcommand the logon entry runs.+const SERVICE_HOST: &str = "service-host";+/// Start of the identity line `setup` writes into every unit it renders. The/// rest of the line is the SHA-256 of the file without that line, so/// `uninstall` can tell a unit `setup` wrote, and nobody edited since, from a@@ -51,16 +59,19 @@ const IDENTITY_PREFIX: &str = "ai-memory-setup-unit sha256:";pub(crate) enum ServiceManager {SystemdUser,Launchd,+ WindowsRun,}impl ServiceManager {/// The manager for the platform this binary was built for; `None` on- /// Windows and anything else without a supported per-user manager.+ /// anything 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 if cfg!(windows) {+ Some(Self::WindowsRun)} else {None}@@ -70,6 +81,7 @@ impl ServiceManager {match self {Self::SystemdUser => "systemd user unit",Self::Launchd => "launchd LaunchAgent",+ Self::WindowsRun => "Windows logon entry",}}}@@ -87,12 +99,25 @@ pub(crate) struct ServiceSpec {pub(crate) xdg_config_home: Option<PathBuf>,}-/// A rendered service file and where it goes.+/// A rendered service file and where it goes. For [`ServiceManager::WindowsRun`]+/// `path` names the registry value (`HKCU\...\Run\ai-memory`) and `contents`+/// is its data, the command line Windows runs at logon.#[derive(Debug, Clone, PartialEq, Eq)]pub(crate) struct ServiceUnit {pub(crate) manager: ServiceManager,pub(crate) path: PathBuf,pub(crate) contents: String,+ /// How to start the Windows host now, without waiting for a logon.+ pub(crate) host: Option<HostLaunch>,+}++/// The command that starts the Windows background host, and the state file+/// it keeps.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct HostLaunch {+ pub(crate) exe: PathBuf,+ pub(crate) args: Vec<String>,+ pub(crate) state_file: PathBuf,}impl ServiceUnit {@@ -100,6 +125,15 @@ impl ServiceUnit {pub(crate) fn is_current(&self) -> bool {std::fs::read_to_string(&self.path).is_ok_and(|text| text == self.contents)}++ /// Whether a unit of ours is in place: the file, or on Windows the+ /// registry value.+ pub(crate) fn exists(&self, runner: &dyn CommandRunner) -> bool {+ match self.manager {+ ServiceManager::WindowsRun => run_value(runner).is_some(),+ _ => self.path.exists(),+ }+ }}/// Render the unit for `manager`.@@ -120,6 +154,7 @@ pub(crate) fn render(manager: ServiceManager, spec: &ServiceSpec) -> Result<Servmatch manager {ServiceManager::SystemdUser => render_systemd(spec),ServiceManager::Launchd => render_launchd(spec),+ ServiceManager::WindowsRun => render_windows(spec),}}@@ -194,6 +229,7 @@ fn render_systemd(spec: &ServiceSpec) -> Result<ServiceUnit> {spec.xdg_config_home.as_deref(),),contents: stamp(ServiceManager::SystemdUser, &unstamped),+ host: None,})}@@ -215,13 +251,16 @@ pub(crate) fn unit_path(.join("Library").join("LaunchAgents").join(format!("{LAUNCHD_LABEL}.plist")),+ ServiceManager::WindowsRun => PathBuf::from(format!("{RUN_KEY}\\{RUN_VALUE}")),}}fn identity_line(manager: ServiceManager, digest: &str) -> String {match manager {ServiceManager::SystemdUser => format!("# {IDENTITY_PREFIX}{digest}"),- ServiceManager::Launchd => format!("<!-- {IDENTITY_PREFIX}{digest} -->"),+ ServiceManager::Launchd | ServiceManager::WindowsRun => {+ format!("<!-- {IDENTITY_PREFIX}{digest} -->")+ }}}@@ -235,7 +274,7 @@ fn sha256_hex(text: &str) -> String {fn stamp(manager: ServiceManager, unstamped: &str) -> String {let line = identity_line(manager, &sha256_hex(unstamped));match manager {- ServiceManager::SystemdUser => format!("{line}\n{unstamped}"),+ ServiceManager::SystemdUser | ServiceManager::WindowsRun => format!("{line}\n{unstamped}"),ServiceManager::Launchd => match unstamped.split_once('\n') {Some((declaration, rest)) => format!("{declaration}\n{line}\n{rest}"),None => format!("{line}\n{unstamped}"),@@ -303,6 +342,82 @@ fn render_launchd(spec: &ServiceSpec) -> Result<ServiceUnit> {manager: ServiceManager::Launchd,path: unit_path(ServiceManager::Launchd, &spec.home, None),contents: stamp(ServiceManager::Launchd, &contents),+ host: None,+ })+}++/// One argument of a Windows command line, quoted the way+/// `CommandLineToArgvW` (and Rust's own argument parser) reads it back: in+/// double quotes, with the backslashes before the closing quote doubled. A+/// Windows path cannot hold `"`, so one that does is refused.+fn windows_arg(what: &str, text: &str) -> Result<String> {+ if text.contains('"') {+ bail!("the {what} path {text} contains a double quote");+ }+ let trailing = text.len() - text.trim_end_matches('\\').len();+ Ok(format!("\"{text}{}\"", "\\".repeat(trailing)))+}++/// The logon entry: the binary `setup` ran from, the data dir and config it+/// used, and `service-host`, as one command line.+fn render_windows(spec: &ServiceSpec) -> Result<ServiceUnit> {+ let exe = checked_path("binary", &spec.exe)?;+ let data_dir = checked_path("data dir", &spec.data_dir)?;+ let config = checked_path("config file", &spec.config_path)?;+ let contents = format!(+ "{} --data-dir {} --config {} {SERVICE_HOST}",+ windows_arg("binary", exe)?,+ windows_arg("data dir", data_dir)?,+ windows_arg("config file", config)?,+ );+ Ok(ServiceUnit {+ manager: ServiceManager::WindowsRun,+ path: unit_path(ServiceManager::WindowsRun, &spec.home, None),+ contents,+ host: Some(HostLaunch {+ exe: spec.exe.clone(),+ args: ["--data-dir", data_dir, "--config", config, SERVICE_HOST]+ .map(str::to_owned)+ .to_vec(),+ state_file: super::service_host::state_file(&spec.data_dir),+ }),+ })+}++/// Whether a `Run` value is a logon entry `setup` wrote: a quoted+/// `ai-memory.exe` followed by arguments that end in `service-host`. Anything+/// else under the name was written by someone else and is left alone.+pub(crate) fn is_setup_run_entry(data: &str) -> bool {+ let Some(rest) = data.strip_prefix('"') else {+ return false;+ };+ let Some((program, args)) = rest.split_once('"') else {+ return false;+ };+ let file = program.rsplit(['\\', '/']).next().unwrap_or(program);+ file.eq_ignore_ascii_case("ai-memory.exe")+ && args.trim_end().ends_with(&format!(" {SERVICE_HOST}"))+ && !args.contains('&')+ && !args.contains('|')+}++/// The data of the `ai-memory` value under the `Run` key, read with+/// `reg query`; `None` when it is absent or cannot be read.+pub(crate) fn run_value(runner: &dyn CommandRunner) -> Option<String> {+ let outcome = runner+ .run("reg", &["query", RUN_KEY, "/v", RUN_VALUE])+ .ok()+ .filter(|outcome| outcome.success)?;+ parse_reg_query(&outcome.stdout, RUN_VALUE)+}++/// Pick the data out of `reg query <key> /v <name>`, which prints the key,+/// then ` <name> REG_SZ <data>`.+fn parse_reg_query(stdout: &str, name: &str) -> Option<String> {+ stdout.lines().find_map(|line| {+ let rest = line.trim_start().strip_prefix(name)?;+ let rest = rest.trim_start().strip_prefix("REG_SZ")?;+ Some(rest.trim_start().trim_end_matches('\r').to_owned())})}@@ -325,6 +440,13 @@ pub(crate) struct CommandOutcome {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>;++ /// Run a launcher that leaves a background process behind, with no+ /// captured output. A pipe [`Self::run`] reads would be inherited by that+ /// process and held open, so reading it to the end would never return.+ fn run_launcher(&self, program: &str, args: &[&str]) -> Result<CommandOutcome> {+ self.run(program, args)+ }}/// Runs commands for real, resolved through `PATH`.@@ -343,6 +465,21 @@ impl CommandRunner for SystemRunner {stderr: String::from_utf8_lossy(&output.stderr).into_owned(),})}++ fn run_launcher(&self, program: &str, args: &[&str]) -> Result<CommandOutcome> {+ let status = std::process::Command::new(program)+ .args(args)+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status()+ .with_context(|| format!("running {program}"))?;+ Ok(CommandOutcome {+ success: status.success(),+ stdout: String::new(),+ stderr: format!("exited with {status}"),+ })+ }}/// What installing the service did.@@ -366,11 +503,15 @@ pub(crate) enum ServiceChange {/// 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> {+ if unit.manager == ServiceManager::WindowsRun {+ return install_windows(unit, runner);+ }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)?),+ ServiceManager::WindowsRun => false,};if current && running {return Ok(ServiceChange::Unchanged);@@ -381,6 +522,7 @@ pub(crate) fn install(unit: &ServiceUnit, runner: &dyn CommandRunner) -> Result<match unit.manager {ServiceManager::SystemdUser => start_systemd(runner)?,ServiceManager::Launchd => start_launchd(unit, runner, running)?,+ ServiceManager::WindowsRun => {}}Ok(match (existed, current) {(false, _) => ServiceChange::Installed,@@ -389,6 +531,54 @@ pub(crate) fn install(unit: &ServiceUnit, runner: &dyn CommandRunner) -> Result<})}+/// Write the logon entry when it differs, then (re)start the host now so the+/// server answers before the next logon. A current entry whose host runs is+/// left alone.+fn install_windows(unit: &ServiceUnit, runner: &dyn CommandRunner) -> Result<ServiceChange> {+ let host = unit+ .host+ .as_ref()+ .context("the Windows logon entry has no host command")?;+ let existing = run_value(runner);+ let current = existing.as_deref() == Some(unit.contents.as_str());+ if current && super::service_host::running(&host.state_file).is_some() {+ return Ok(ServiceChange::Unchanged);+ }+ if !current {+ require(+ runner,+ "reg",+ &[+ "add",+ RUN_KEY,+ "/v",+ RUN_VALUE,+ "/t",+ "REG_SZ",+ "/d",+ &unit.contents,+ "/f",+ ],+ )?;+ }+ super::service_host::stop(&host.state_file, runner)?;+ let exe = host.exe.to_string_lossy();+ let args: Vec<&str> = host.args.iter().map(String::as_str).collect();+ let started = runner.run_launcher(&exe, &args)?;+ if !started.success {+ bail!(+ "`{exe} {}` failed: {}",+ args.join(" "),+ started.stderr.trim()+ );+ }+ Ok(match (existing.is_some(), 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)@@ -503,6 +693,23 @@ pub(crate) enum Removal {NotOurs(PathBuf),}+/// Whether `manager`'s unit at `path` is one `uninstall` would remove; reads+/// only (on Windows, through `reg query`).+pub(crate) fn planned_removal_for(+ manager: ServiceManager,+ path: &Path,+ runner: &dyn CommandRunner,+) -> Removal {+ if manager != ServiceManager::WindowsRun {+ return planned_removal(path);+ }+ match run_value(runner) {+ None => Removal::Absent,+ Some(data) if is_setup_run_entry(&data) => Removal::Removed(path.to_path_buf()),+ Some(_) => Removal::NotOurs(path.to_path_buf()),+ }+}+/// Whether the unit at `path` is one `uninstall` would remove; reads only.pub(crate) fn planned_removal(path: &Path) -> Removal {match std::fs::read_to_string(path) {@@ -521,9 +728,10 @@ pub(crate) fn planned_removal(path: &Path) -> Removal {pub(crate) fn remove(manager: ServiceManager,path: &Path,+ data_dir: &Path,runner: &dyn CommandRunner,) -> Result<Removal> {- let planned = planned_removal(path);+ let planned = planned_removal_for(manager, path, runner);if !matches!(planned, Removal::Removed(_)) {return Ok(planned);}@@ -548,6 +756,10 @@ pub(crate) fn remove(}delete_unit(path)?;}+ ServiceManager::WindowsRun => {+ super::service_host::stop(&super::service_host::state_file(data_dir), runner)?;+ require(runner, "reg", &["delete", RUN_KEY, "/v", RUN_VALUE, "/f"])?;+ }}Ok(planned)}@@ -857,7 +1069,13 @@ mod tests {write_unit(&unit).unwrap();let runner = FakeRunner::default();assert_eq!(- remove(ServiceManager::SystemdUser, &unit.path, &runner).unwrap(),+ remove(+ ServiceManager::SystemdUser,+ &unit.path,+ Path::new("/unused"),+ &runner+ )+ .unwrap(),Removal::Removed(unit.path.clone()));assert!(!unit.path.exists());@@ -872,7 +1090,13 @@ mod tests {// A second removal finds nothing and calls nothing.let again = FakeRunner::default();assert_eq!(- remove(ServiceManager::SystemdUser, &unit.path, &again).unwrap(),+ remove(+ ServiceManager::SystemdUser,+ &unit.path,+ Path::new("/unused"),+ &again+ )+ .unwrap(),Removal::Absent);assert!(again.calls.borrow().is_empty());@@ -893,7 +1117,13 @@ mod tests {std::fs::write(&unit.path, &text).unwrap();let runner = FakeRunner::default();assert_eq!(- remove(ServiceManager::SystemdUser, &unit.path, &runner).unwrap(),+ remove(+ ServiceManager::SystemdUser,+ &unit.path,+ Path::new("/unused"),+ &runner+ )+ .unwrap(),Removal::NotOurs(unit.path.clone()));assert_eq!(std::fs::read_to_string(&unit.path).unwrap(), text);@@ -910,7 +1140,15 @@ mod tests {failing: vec!["systemctl --user disable"],..FakeRunner::default()};- assert!(remove(ServiceManager::SystemdUser, &unit.path, &runner).is_err());+ assert!(+ remove(+ ServiceManager::SystemdUser,+ &unit.path,+ Path::new("/unused"),+ &runner+ )+ .is_err()+ );assert!(unit.is_current());}@@ -924,7 +1162,13 @@ mod tests {..FakeRunner::default()};assert_eq!(- remove(ServiceManager::Launchd, &unit.path, &runner).unwrap(),+ remove(+ ServiceManager::Launchd,+ &unit.path,+ Path::new("/unused"),+ &runner+ )+ .unwrap(),Removal::Removed(unit.path.clone()));assert!(!unit.path.exists());@@ -937,4 +1181,210 @@ mod tests {]);}++ /// The logon entry: an unchanged entry whose host runs is left alone; a+ /// missing one is written with `reg add` and the host started now; a+ /// current one whose host died is only restarted.+ #[test]+ fn the_windows_logon_entry_is_written_once_and_the_host_started() {+ let root = tempfile::tempdir().unwrap();+ let unit = render(ServiceManager::WindowsRun, &spec(root.path())).unwrap();+ let host = unit.host.clone().unwrap();+ let exe = host.exe.display().to_string();++ let fresh = FakeRunner {+ failing: vec!["reg query"],+ ..FakeRunner::default()+ };+ assert_eq!(install(&unit, &fresh).unwrap(), ServiceChange::Installed);+ let calls = fresh.calls.borrow();+ assert_eq!(calls.len(), 3, "{calls:?}");+ assert!(calls[0].starts_with("reg query"));+ assert!(+ calls[1].starts_with(&format!("reg add {RUN_KEY} /v ai-memory /t REG_SZ /d ")),+ "{calls:?}"+ );+ assert!(calls[1].ends_with(" service-host /f"), "{calls:?}");+ assert!(+ calls[2].starts_with(&exe) && calls[2].ends_with(" service-host"),+ "{calls:?}"+ );+ drop(calls);++ let reg_output: &'static str = Box::leak(+ format!(+ "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\r\n \+ ai-memory REG_SZ {}\r\n\r\n",+ unit.contents+ )+ .into_boxed_str(),+ );+ let current = FakeRunner {+ stdout: vec![("reg query", reg_output)],+ ..FakeRunner::default()+ };+ assert_eq!(install(&unit, ¤t).unwrap(), ServiceChange::Started);+ assert!(+ !current+ .calls+ .borrow()+ .iter()+ .any(|c| c.starts_with("reg add")),+ "a current entry is not rewritten: {:?}",+ current.calls.borrow()+ );+ assert!(unit.exists(¤t));+ assert!(!unit.exists(&fresh));+ }++ /// `reg add` failing stops the install before the host is started.+ #[test]+ fn a_refused_registry_write_starts_no_host() {+ let root = tempfile::tempdir().unwrap();+ let unit = render(ServiceManager::WindowsRun, &spec(root.path())).unwrap();+ let runner = FakeRunner {+ failing: vec!["reg query", "reg add"],+ ..FakeRunner::default()+ };+ let error = install(&unit, &runner).unwrap_err().to_string();+ assert!(error.contains("reg add"), "{error}");+ assert_eq!(runner.calls.borrow().len(), 2);+ }++ /// Uninstall removes only an entry `setup` wrote; someone else's value+ /// under the same name is left, and an absent one is nothing to do.+ #[test]+ fn uninstall_removes_only_setups_logon_entry() {+ let root = tempfile::tempdir().unwrap();+ let path = unit_path(ServiceManager::WindowsRun, root.path(), None);+ let ours = FakeRunner {+ stdout: vec![(+ "reg query",+ " ai-memory REG_SZ \"C:\\x\\ai-memory.exe\" --data-dir \"C:\\d\" \+ --config \"C:\\d\\config.toml\" service-host\r\n",+ )],+ ..FakeRunner::default()+ };+ assert_eq!(+ remove(ServiceManager::WindowsRun, &path, root.path(), &ours).unwrap(),+ Removal::Removed(path.clone())+ );+ assert!(+ ours.calls+ .borrow()+ .iter()+ .any(|c| c == &format!("reg delete {RUN_KEY} /v ai-memory /f")),+ "{:?}",+ ours.calls.borrow()+ );++ let theirs = FakeRunner {+ stdout: vec![(+ "reg query",+ " ai-memory REG_SZ \"C:\\tools\\other.exe\" --start\r\n",+ )],+ ..FakeRunner::default()+ };+ assert_eq!(+ remove(ServiceManager::WindowsRun, &path, root.path(), &theirs).unwrap(),+ Removal::NotOurs(path.clone())+ );+ assert_eq!(theirs.calls.borrow().len(), 1, "only the query ran");++ let absent = FakeRunner {+ failing: vec!["reg query"],+ ..FakeRunner::default()+ };+ assert_eq!(+ remove(ServiceManager::WindowsRun, &path, root.path(), &absent).unwrap(),+ Removal::Absent+ );+ }+}++/// The Windows command-line pieces are plain text handling; they run on every+/// platform.+#[cfg(test)]+mod windows_entry_tests {+ use super::*;++ #[test]+ fn windows_args_are_quoted_so_argv_parsing_reads_them_back() {+ assert_eq!(+ windows_arg("data dir", r"C:\Users\me\AppData\Local\ai-memory").unwrap(),+ r#""C:\Users\me\AppData\Local\ai-memory""#+ );+ // A trailing backslash would otherwise escape the closing quote.+ assert_eq!(windows_arg("data dir", r"D:\").unwrap(), r#""D:\\""#);+ assert_eq!(+ windows_arg("data dir", r"C:\with space\dir").unwrap(),+ r#""C:\with space\dir""#+ );+ assert!(windows_arg("data dir", r#"C:\a"b"#).is_err());+ }++ #[test]+ fn reg_query_output_yields_the_value_data() {+ let out = "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\r\n \+ ai-memory REG_SZ \"C:\\a b\\ai-memory.exe\" --data-dir \"C:\\d\" service-host\r\n\r\n";+ assert_eq!(+ parse_reg_query(out, "ai-memory").as_deref(),+ Some("\"C:\\a b\\ai-memory.exe\" --data-dir \"C:\\d\" service-host")+ );+ assert_eq!(+ parse_reg_query(" other REG_SZ x\r\n", "ai-memory"),+ None+ );+ assert_eq!(+ parse_reg_query(" ai-memory REG_EXPAND_SZ x\r\n", "ai-memory"),+ None+ );+ }++ /// Only a quoted `ai-memory.exe` ending in `service-host` is ours; a+ /// value pointing elsewhere, an unquoted one, or one chaining another+ /// command is not, and uninstall leaves it.+ #[test]+ fn only_setups_entry_shape_counts_as_ours() {+ assert!(is_setup_run_entry(+ r#""C:\x\ai-memory.exe" --data-dir "C:\d" --config "C:\d\c.toml" service-host"#+ ));+ assert!(is_setup_run_entry(r#""C:\X\AI-MEMORY.EXE" service-host"#));+ for theirs in [+ r#""C:\x\other.exe" service-host"#,+ r#"C:\x\ai-memory.exe service-host"#,+ r#""C:\x\ai-memory.exe" serve"#,+ r#""C:\x\ai-memory.exe" service-host & calc"#,+ r#""C:\x\ai-memory.exe" x | y service-host"#,+ "",+ ] {+ assert!(!is_setup_run_entry(theirs), "{theirs}");+ }+ }++ /// The rendered entry is one setup recognises as its own, names the+ /// install's data dir and config, and its host command matches it.+ #[test]+ fn the_rendered_entry_is_recognised_as_setups() {+ let root = std::env::temp_dir().join("ai-memory-entry-test");+ let spec = ServiceSpec {+ exe: root.join("ai-memory.exe"),+ data_dir: root.join("data"),+ config_path: root.join("data").join("config.toml"),+ home: root.clone(),+ xdg_config_home: None,+ };+ let unit = render(ServiceManager::WindowsRun, &spec).unwrap();+ assert!(is_setup_run_entry(&unit.contents), "{}", unit.contents);+ assert!(+ unit.contents+ .contains(&format!("--data-dir \"{}\"", spec.data_dir.display()))+ );+ let host = unit.host.unwrap();+ assert_eq!(host.args.last().map(String::as_str), Some("service-host"));+ assert_eq!(+ host.state_file,+ super::super::service_host::state_file(&spec.data_dir)+ );+ }}diff --git a/crates/ai-memory-cli/src/lib.rs b/crates/ai-memory-cli/src/lib.rsindex 467a5c8e..a3b7490d 100644--- a/crates/ai-memory-cli/src/lib.rs+++ b/crates/ai-memory-cli/src/lib.rs@@ -88,6 +88,9 @@ 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::ServiceHost(args) => {+ commands::service_host::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/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex a9120f7d..793f646f 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -36,6 +36,7 @@ mod routing_skills;mod run_offline;mod serve_shutdown;mod server_profiles;+mod service_host_windows;mod setup_e2e;mod shutdown_signals;mod upgrade_e2e;diff --git a/crates/ai-memory-cli/tests/suite/packaging.rs b/crates/ai-memory-cli/tests/suite/packaging.rsindex 9457e1be..2f302a0c 100644--- a/crates/ai-memory-cli/tests/suite/packaging.rs+++ b/crates/ai-memory-cli/tests/suite/packaging.rs@@ -680,6 +680,7 @@ fn wrapper_updates_and_install_docs_use_verified_release_assets() {"ai-memory-install-hooks","ai-memory-hooks.tar.gz","install.sh",+ "install.ps1",] {assert!(release.contains(asset), "release must publish {asset}");assert!(@@ -712,6 +713,32 @@ fn wrapper_updates_and_install_docs_use_verified_release_assets() {assert!(!hook_installer.contains("raw.githubusercontent.com"));}+/// `install.ps1` runs only on Windows CI; these source checks keep its safety+/// properties visible to every platform's gate: the checksum is compared+/// before anything is unpacked, archive entries escaping the install dir are+/// refused, it never `exit`s (which would close the shell under `iex`), and+/// it runs from one function called on the last line.+#[test]+fn install_ps1_keeps_its_safety_checks() {+ let script = read_repo("install.ps1");+ let hash = script.find("Get-FileHash").expect("checksum computed");+ let mismatch = script.find("checksum mismatch").expect("mismatch refused");+ let unsafe_entry = script.find("unsafe path").expect("unsafe entries refused");+ let expand = script.find("Expand-Archive").expect("archive unpacked");+ assert!(hash < expand && mismatch < expand && unsafe_entry < expand);+ assert!(script.contains("$parts -contains '..'"));+ assert!(script.contains("ai-memory-windows-x86_64.zip"));+ assert!(script.contains("AI_MEMORY_NO_MODIFY_PATH"));+ assert!(+ !script+ .lines()+ .any(|line| line.trim_start().starts_with("exit")),+ "install.ps1 must throw, not exit"+ );+ assert_eq!(script.trim_end().lines().last(), Some("Install-AiMemory"));+ assert!(!script.contains("raw.githubusercontent.com"));+}+#[test]fn github_actions_are_pinned_to_full_commits() {for path in [".github/workflows/ci.yml", ".github/workflows/release.yml"] {diff --git a/crates/ai-memory-cli/tests/suite/service_host_windows.rs b/crates/ai-memory-cli/tests/suite/service_host_windows.rsnew file mode 100644index 00000000..2313cf6b--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/service_host_windows.rs@@ -0,0 +1,137 @@+//! `ai-memory service-host` on Windows, through the shipped binary: the+//! launcher returns at once, the detached supervisor starts the server and+//! records both pids, and a killed server is started again. Everything lives+//! in a temp data dir on a free port; the registry is never touched (that is+//! `setup`'s step, covered with a recording runner in the unit tests).++#![cfg(windows)]++use std::io::{Read as _, Write as _};+use std::net::TcpStream;+use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::time::{Duration, Instant};++use crate::e2e_support::{free_port, hermetic};++const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");++#[derive(serde::Deserialize)]+struct HostState {+ supervisor_pid: u32,+ server_pid: Option<u32>,+}++fn read_state(path: &Path) -> Option<HostState> {+ serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()+}++/// Kill whatever the host recorded when the test ends, pass or fail.+struct HostGuard(PathBuf);+impl Drop for HostGuard {+ fn drop(&mut self) {+ if let Some(state) = read_state(&self.0) {+ for pid in std::iter::once(state.supervisor_pid).chain(state.server_pid) {+ let _ = std::process::Command::new("taskkill")+ .args(["/PID", &pid.to_string(), "/T", "/F"])+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status();+ }+ }+ }+}++fn healthz(port: u16) -> bool {+ let Ok(mut stream) = TcpStream::connect(("127.0.0.1", port)) else {+ return false;+ };+ stream.set_read_timeout(Some(Duration::from_secs(2))).ok();+ if stream+ .write_all(b"GET /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")+ .is_err()+ {+ return false;+ }+ let mut answer = String::new();+ stream.read_to_string(&mut answer).ok();+ answer.starts_with("HTTP/1.1 200")+}++fn wait_for(what: &str, timeout: Duration, mut done: impl FnMut() -> bool) {+ let deadline = Instant::now() + timeout;+ while !done() {+ assert!(Instant::now() < deadline, "timed out waiting for {what}");+ std::thread::sleep(Duration::from_millis(200));+ }+}++/// The restart waits out the host's delay: the slow tier.+mod slow {+ use super::*;++ #[test]+ fn service_host_runs_the_server_and_restarts_it_after_it_is_killed() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let config = data_dir.join("config.toml");+ let port = free_port();+ let command = |args: &[&str]| {+ let mut cmd = hermetic(BIN);+ cmd.arg("--data-dir")+ .arg(&data_dir)+ .arg("--config")+ .arg(&config)+ .args(args)+ .env("AI_MEMORY_BIND", format!("127.0.0.1:{port}"))+ .env("AI_MEMORY_SERVER_URL", format!("http://127.0.0.1:{port}"))+ .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")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ cmd+ };+ assert!(command(&["init"]).status().unwrap().success());++ let state_file = data_dir.join("service-host.json");+ let _guard = HostGuard(state_file.clone());+ let started = Instant::now();+ assert!(command(&["service-host"]).status().unwrap().success());+ assert!(+ started.elapsed() < Duration::from_secs(10),+ "the launcher must return without waiting for the server"+ );++ wait_for("the server to answer", Duration::from_secs(60), || {+ healthz(port)+ });+ let first = read_state(&state_file).expect("the host records its state");+ let first_server = first.server_pid.expect("the host records the server pid");+ assert_ne!(first.supervisor_pid, first_server);++ // A second launch while the host runs starts no second supervisor.+ assert!(command(&["service-host"]).status().unwrap().success());+ std::thread::sleep(Duration::from_secs(2));+ assert_eq!(+ read_state(&state_file).map(|state| state.supervisor_pid),+ Some(first.supervisor_pid)+ );++ assert!(+ std::process::Command::new("taskkill")+ .args(["/PID", &first_server.to_string(), "/F"])+ .status()+ .unwrap()+ .success()+ );+ wait_for("a restarted server", Duration::from_secs(60), || {+ read_state(&state_file)+ .and_then(|state| state.server_pid)+ .is_some_and(|pid| pid != first_server)+ && healthz(port)+ });+ }+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 33576fad..e8737b20 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -806,12 +806,18 @@ path filled in, then `install-mcp`, `install-hooks` and globalsession store or MCP config (the stores `doctor` scans). It finishes with aread-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. Each+unit rendering and the `systemctl`/`launchctl`/`reg` calls are tested without a+real session. On Windows the "unit" is an `ai-memory` value under the per-user+`HKCU\...\CurrentVersion\Run` key that runs the hidden `service-host`+command at logon; `service-host` detaches from the console and supervises+`serve` with a hidden console, restarting it after a failure, and records both+pids in `<data_dir>/service-host.json`. A second run changes no file. Eachrendered unit carries an identity line with the SHA-256 of the rest of the-file; `uninstall` stops and removes only a unit whose digest still matches.-`install.sh`, a release asset with its own `.sha256`, installs the release-tarball under `~/.local` after checking it against the published checksum.+file; `uninstall` stops and removes only a unit whose digest still matches (on+Windows, only a `Run` value with the shape `setup` writes).+`install.sh` and, for Windows, `install.ps1` are release assets with their own+`.sha256` files; each installs the release archive after checking it against+the published checksum, under `~/.local` or `%LOCALAPPDATA%\Programs`.The hidden `render-plugins --out <dir>` generates the Claude Code and Codexmarketplace plugins under `plugins/` and their catalogsdiff --git a/docs/competitive-parity.md b/docs/competitive-parity.mdindex 3b6690ee..51bd1e51 100644--- a/docs/competitive-parity.md+++ b/docs/competitive-parity.md@@ -190,7 +190,10 @@ implemented without a separate decision.** Ordered by leverage.1.2 s from the first command to a returned memory, in a clean temporaryhome with a debug build served as a local release and no model download.That run drives the service step through a stand-in `systemctl`/`launchctl`,- not a real systemd or launchd, and Windows has no service step. Still open:+ not a real systemd or launchd. 3.1 brings native Windows to the same two+ commands: `install.ps1` (checksum-verified, no administrator rights) and a+ `setup` service step that registers a per-user logon entry running the+ server with no console window and restarting it after a failure. Still open:no npm package, and a "coming from Claude built-in?" importer (the`~/.claude/.../memory/` format is nearly identical markdown + `type`frontmatter, which makes it a cheap, strong on-ramp).diff --git a/docs/install.md b/docs/install.mdindex d2f39cb3..c3348191 100644--- a/docs/install.md+++ b/docs/install.md@@ -96,7 +96,25 @@ sh install.sh| `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+Native Windows has its own script, `install.ps1`, published next to+`install.sh` with its own `install.ps1.sha256`. In PowerShell (no+administrator rights needed):++```powershell+irm https://github.com/akitaonrails/ai-memory/releases/latest/download/install.ps1 | iex+ai-memory setup+```++It downloads `ai-memory-windows-x86_64.zip` and its `.sha256`, stops before+unpacking when the checksum file is missing, names another asset, or does not+match, and refuses an archive entry that is absolute or holds `..`. The+release goes to `%LOCALAPPDATA%\Programs\ai-memory` (`AI_MEMORY_INSTALL_DIR`+overrides it), which is added to your user `PATH` unless+`AI_MEMORY_NO_MODIFY_PATH=1`. An existing install there is left alone; update it+with `ai-memory upgrade`. `AI_MEMORY_VERSION` and `AI_MEMORY_RELEASE_BASE_URL`+work as for `install.sh`. On Windows on Arm it installs the x86_64 build, which+Windows 11 runs under emulation. Errors are thrown rather than exiting, so a+failure under `iex` leaves your PowerShell window open. Details are in[`docs/windows.md`](windows.md).`ai-memory setup [--yes] [--agent <name>]... [--no-service] [--plan [--json]]`@@ -119,10 +137,19 @@ runs, in order, the commands a native install otherwise needs one by one:link that resolves to the same file instead: the path as invoked, an`ai-memory` on `PATH` such as `~/.nix-profile/bin/ai-memory`, or Homebrew's`opt/ai-memory/bin/ai-memory` or `bin/ai-memory`. With no such link it names- the versioned path, and you re-run `setup` after upgrading. 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.+ the versioned path, and you re-run `setup` after upgrading.+ On Windows there is no per-user service manager, so `setup` writes an+ `ai-memory` value under `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`+ (no administrator rights needed) that runs `ai-memory service-host` at+ logon, and starts that host right away. The host runs `serve --transport+ http --enable-web` on the same data dir and config with no console window+ and restarts it after a failure, giving up after five failures within ten+ seconds of starting; see+ [`docs/windows.md`](windows.md#scenario-e-keep-the-server-running-native-windows-service).+ The step is skipped when a server already answers at the configured+ URL and no unit or logon entry of ours exists yet (Docker, a packaged system+ unit, a foreground `serve`), when the configured server is not on this+ machine, and with `--no-service`.3. For each agent: `install-mcp --apply`, `install-hooks --apply` and`install-skills --scope global`. With no `--agent`, `setup` wires everyharness whose session store or MCP config exists under your home, using thediff --git a/docs/windows.md b/docs/windows.mdindex 2b878458..d4592f5f 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -180,17 +180,31 @@ 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.+The quickest path is two commands in PowerShell, neither needing+administrator rights:```powershell-# First-time install: download + extract into your user data dir (any stable-# path works; the native hook exec-form command is rendered from wherever-# ai-memory.exe lives).-$Dest = "$env:LOCALAPPDATA\ai-memory"+irm https://github.com/akitaonrails/ai-memory/releases/latest/download/install.ps1 | iex+ai-memory setup+```++`install.ps1` downloads the zip and its `.sha256` from the release, refuses a+missing or mismatched checksum and any archive entry that is absolute or holds+`..`, unpacks the release to `%LOCALAPPDATA%\Programs\ai-memory` and adds that+directory to your user `PATH` (set `AI_MEMORY_NO_MODIFY_PATH=1` to skip that).+`ai-memory setup` then initialises the data dir (`%LOCALAPPDATA%\ai-memory`),+registers the server to start at logon (see+[Scenario E](#scenario-e-keep-the-server-running-native-windows-service)),+wires the agents it finds, and checks the result. Inside WSL2 the Linux+`install.sh` and `setup` path works unchanged.++To do the same by hand:++```powershell+# First-time install: download + extract into a stable per-user directory+# (any stable path works; the native hook exec-form command is rendered from+# wherever ai-memory.exe lives).+$Dest = "$env:LOCALAPPDATA\Programs\ai-memory"New-Item -ItemType Directory -Force $Dest | Out-NullInvoke-WebRequest `-Uri "https://github.com/akitaonrails/ai-memory/releases/latest/download/ai-memory-windows-x86_64.zip" `@@ -236,8 +250,8 @@ assets: it contains `ai-memory.exe`, the full `hooks/` bundle (`.ps1` +the `ai-memory.exe` path from the running binary, keep the extracted `.exe`at a stable location (re-run `install-hooks` if you move it).-This leaves the server running only while a terminal is open. To keep it-up across logoff and reboot, continue to [Scenario+Without `ai-memory setup`, the server runs only while a terminal is open. To+keep it up, run `setup` or continue to [ScenarioE](#scenario-e-keep-the-server-running-native-windows-service).## Scenario D: Native Windows Source Build@@ -326,10 +340,45 @@ Scenarios C and D both end at `ai-memory serve` in a foreground terminal.That works for a trial but not for daily use: when you close the window,log off, or reboot, the server stops.-On Linux the packaged units in `packaging/systemd/` supply-`Restart=on-failure` and `RestartSec=5s`. systemd performs those-restarts, not ai-memory. Native Windows gets the same arrangement through-a **service wrapper**. ai-memory does not+### The logon entry `ai-memory setup` installs++`ai-memory setup` keeps the server running for as long as you are signed in,+with no administrator rights and no password stored anywhere:++1. It writes an `ai-memory` value under+ `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`, the per-user key+ Windows runs at every logon:+ `"<path>\ai-memory.exe" --data-dir "<data dir>" --config "<config>" service-host`.+2. It starts that command once right away, so the server answers before your+ next logon.+3. `service-host` starts a copy of itself detached from any console and exits,+ so the logon console closes at once. The copy runs+ `serve --transport http --enable-web` with a hidden console, which the Git+ CLI fallback and any provider CLI the server starts inherit instead of+ opening windows of their own.+4. When the server exits with an error, the host starts it again after five+ seconds, the way the Linux unit's `Restart=on-failure` does. After five+ failures within ten seconds of starting (another server already on the+ port, a broken config) it stops trying; run+ `ai-memory serve --transport http` in a terminal to see the error.++The host records its own process id and the server's in+`<data dir>\service-host.json`. A second `setup` leaves a current entry with a+running host alone; a changed entry is rewritten and the host restarted.+`ai-memory uninstall --apply` stops the host and deletes the value, but only+when the value still has the shape `setup` writes (a quoted `ai-memory.exe`+ending in `service-host`); a value someone else put under the same name is+left in place.++The logon entry runs only while you are signed in, which matches a systemd+user unit without lingering and a macOS LaunchAgent. For a server that runs+before anyone signs in, or for other users of the machine, use a real Windows+service through WinSW, below, and pass `--no-service` to `setup`.++### A real Windows service++A Windows service, unlike the logon entry, runs without anyone signed in. It+needs a **service wrapper**, because ai-memory does notimplement a Windows Service control-code dispatcher, so `sc create` or`New-Service` pointed straight at `ai-memory.exe` will not work: the SCMstarts the process, waits for it to report in, never hears from it, anddiff --git a/install.ps1 b/install.ps1new file mode 100644index 00000000..31258ece--- /dev/null+++ b/install.ps1@@ -0,0 +1,143 @@+# Install the ai-memory release binary for the current Windows user.+#+# irm https://github.com/akitaonrails/ai-memory/releases/latest/download/install.ps1 | iex+#+# Downloads ai-memory-windows-x86_64.zip from a GitHub release, verifies it+# against the release's published .sha256 file, refuses an archive with an+# absolute or `..` entry, unpacks it into %LOCALAPPDATA%\Programs\ai-memory and+# adds that directory to your user PATH. No administrator rights, and nothing+# outside that directory and your PATH is touched. A missing or mismatched+# checksum stops the install before anything is unpacked.+#+# Then run `ai-memory setup` to create the data dir, register the server to+# start at logon and wire your agents.+#+# Environment (all optional):+# AI_MEMORY_VERSION release to install, e.g. 3.1.0 (default: latest)+# AI_MEMORY_INSTALL_DIR where the release is unpacked+# (default: %LOCALAPPDATA%\Programs\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_NO_MODIFY_PATH set to 1 to leave your user PATH alone+#+# Everything runs inside Install-AiMemory, called on the last line, so a+# download cut short runs nothing. Errors are thrown, never `exit`, so a failure+# under `iex` does not close your PowerShell window.++function Install-AiMemory {+ $ErrorActionPreference = 'Stop'+ $ProgressPreference = 'SilentlyContinue'+ $defaultBase = 'https://github.com/akitaonrails/ai-memory/releases'+ $asset = 'ai-memory-windows-x86_64.zip'++ function Say([string] $message) { Write-Host "ai-memory install: $message" }+ function Fail([string] $message) { throw "ai-memory install: error: $message" }++ # Windows PowerShell 5.1 may still default to TLS 1.0; GitHub needs 1.2.+ if ($PSVersionTable.PSVersion.Major -lt 6) {+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12+ }++ $arch = $env:PROCESSOR_ARCHITECTURE+ if ($env:PROCESSOR_ARCHITEW6432) { $arch = $env:PROCESSOR_ARCHITEW6432 }+ switch ($arch) {+ 'AMD64' { }+ 'ARM64' { Say 'no native ARM64 build yet; installing the x86_64 build, which Windows 11 runs under emulation' }+ default { Fail "unsupported processor architecture $arch; ai-memory publishes an x86_64 Windows build" }+ }++ $base = if ($env:AI_MEMORY_RELEASE_BASE_URL) { $env:AI_MEMORY_RELEASE_BASE_URL.TrimEnd('/') } else { $defaultBase }+ if ($base -eq $defaultBase -or $base.StartsWith('https://github.com/', [StringComparison]::OrdinalIgnoreCase)) {+ if (-not $base.StartsWith('https://', [StringComparison]::OrdinalIgnoreCase)) { Fail "refusing a non-https GitHub URL: $base" }+ }+ $version = $env:AI_MEMORY_VERSION+ if ($version) {+ $version = $version.TrimStart('v')+ if ($version -notmatch '^[0-9]+\.[0-9]+\.[0-9]+([-.][0-9A-Za-z.-]+)?$') { Fail "AI_MEMORY_VERSION must look like 3.1.0, not $version" }+ $url = "$base/download/v$version/$asset"+ } else {+ $url = "$base/latest/download/$asset"+ }++ $dest = if ($env:AI_MEMORY_INSTALL_DIR) { $env:AI_MEMORY_INSTALL_DIR } else { Join-Path $env:LOCALAPPDATA 'Programs\ai-memory' }+ if (-not [IO.Path]::IsPathRooted($dest)) { Fail "AI_MEMORY_INSTALL_DIR must be an absolute path, not $dest" }+ $exe = Join-Path $dest 'ai-memory.exe'+ if (Test-Path -LiteralPath $exe) {+ Fail "ai-memory is already installed at $exe; run ``ai-memory upgrade`` to update it"+ }++ $work = Join-Path ([IO.Path]::GetTempPath()) ("ai-memory-install-" + [Guid]::NewGuid().ToString('N'))+ New-Item -ItemType Directory -Path $work | Out-Null+ try {+ $zip = Join-Path $work $asset+ Say "downloading $url"+ try {+ Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $zip+ Invoke-WebRequest -UseBasicParsing -Uri "$url.sha256" -OutFile "$zip.sha256"+ } catch {+ Fail "download failed: $($_.Exception.Message)"+ }++ $line = (Get-Content -LiteralPath "$zip.sha256" -Raw).Trim()+ if ($line -notmatch "^([0-9a-fA-F]{64})\s+\*?$([regex]::Escape($asset))$") {+ Fail "the checksum file does not name $asset; nothing was installed"+ }+ $expected = $Matches[1].ToLowerInvariant()+ $actual = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash.ToLowerInvariant()+ if ($actual -ne $expected) {+ Fail "checksum mismatch for $asset (expected $expected, got $actual); nothing was installed"+ }++ Add-Type -AssemblyName System.IO.Compression.FileSystem+ $archive = [IO.Compression.ZipFile]::OpenRead($zip)+ try {+ foreach ($entry in $archive.Entries) {+ $name = $entry.FullName+ $parts = $name -split '[\\/]'+ if ($name.StartsWith('/') -or $name.StartsWith('\') -or $name -match '^[A-Za-z]:' -or $parts -contains '..') {+ Fail "the archive holds an unsafe path ($name); nothing was installed"+ }+ }+ } finally {+ $archive.Dispose()+ }++ $staged = Join-Path $work 'release'+ Expand-Archive -LiteralPath $zip -DestinationPath $staged+ $stagedExe = Join-Path $staged 'ai-memory.exe'+ if (-not (Test-Path -LiteralPath $stagedExe)) { Fail "$asset has no ai-memory.exe" }+ Get-ChildItem -LiteralPath $staged -Recurse -File | Unblock-File+ $reported = & $stagedExe --version 2>$null+ if ($LASTEXITCODE -ne 0) { Fail 'the downloaded binary does not run on this machine' }++ $parent = Split-Path -Parent $dest+ if ($parent) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }+ if (Test-Path -LiteralPath $dest) {+ # An empty or leftover directory with no binary: replace it.+ Remove-Item -LiteralPath $dest -Recurse -Force+ }+ Move-Item -LiteralPath $staged -Destination $dest+ } finally {+ Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue+ }++ Say "installed $reported to $dest"+ if ($env:AI_MEMORY_NO_MODIFY_PATH -eq '1') {+ Say "left your PATH alone (AI_MEMORY_NO_MODIFY_PATH=1)"+ Say "next: & `"$exe`" setup"+ return+ }+ $userPath = [Environment]::GetEnvironmentVariable('Path', 'User')+ $entries = if ($userPath) { $userPath -split ';' | Where-Object { $_ } } else { @() }+ if ($entries -notcontains $dest) {+ [Environment]::SetEnvironmentVariable('Path', (@($entries) + $dest) -join ';', 'User')+ Say "added $dest to your user PATH"+ }+ if (($env:Path -split ';') -notcontains $dest) { $env:Path = "$env:Path;$dest" }+ Say 'next: ai-memory setup'+ Say "(in a terminal opened before this install, run: & `"$exe`" setup)"+}++Install-AiMemorydiff --git a/install.sh b/install.shindex 52168f6a..3310f4b0 100755--- a/install.sh+++ b/install.sh@@ -56,7 +56,7 @@ detect_target() {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 "Windows is not supported by this script; in PowerShell run: irm https://github.com/akitaonrails/ai-memory/releases/latest/download/install.ps1 | iex";;*) die "unsupported operating system: $os" ;;esacdiff --git a/tests/install_ps1.ps1 b/tests/install_ps1.ps1new file mode 100644index 00000000..489fe7a9--- /dev/null+++ b/tests/install_ps1.ps1@@ -0,0 +1,104 @@+# install.ps1 against crafted releases served over local HTTP: a good release+# installs (under PowerShell 7 and Windows PowerShell 5.1), and a checksum+# mismatch, an archive entry escaping the install dir, and an existing install+# are each refused with nothing written. The user PATH is never touched+# (AI_MEMORY_NO_MODIFY_PATH=1). Needs python on PATH for the HTTP server.+#+# Usage: pwsh -NoProfile -File tests/install_ps1.ps1 -Binary target\debug\ai-memory.exe++param([Parameter(Mandatory = $true)][string] $Binary)++$ErrorActionPreference = 'Stop'+$root = Split-Path -Parent $PSScriptRoot+$script = Join-Path $root 'install.ps1'+$asset = 'ai-memory-windows-x86_64.zip'+$tmp = Join-Path ([IO.Path]::GetTempPath()) ("ai-memory-install-ps1-" + [Guid]::NewGuid().ToString('N'))+New-Item -ItemType Directory -Path $tmp | Out-Null+Add-Type -AssemblyName System.IO.Compression+Add-Type -AssemblyName System.IO.Compression.FileSystem++function Fail([string] $message) { throw "install_ps1: $message" }++# publish <name> [-Evil] [-BadSum]: a release dir serving latest/download/<asset>.+function Publish([string] $name, [switch] $Evil, [switch] $BadSum) {+ $dir = Join-Path $tmp "$name\latest\download"+ New-Item -ItemType Directory -Force -Path $dir | Out-Null+ $zip = Join-Path $dir $asset+ $archive = [IO.Compression.ZipFile]::Open($zip, 'Create')+ try {+ [IO.Compression.ZipFileExtensions]::CreateEntryFromFile($archive, (Resolve-Path $Binary), 'ai-memory.exe') | Out-Null+ $hook = $archive.CreateEntry('hooks/_lib.sh')+ $writer = New-Object IO.StreamWriter($hook.Open())+ $writer.Write('echo hook'); $writer.Dispose()+ if ($Evil) {+ $escape = $archive.CreateEntry('../escape.txt')+ $writer = New-Object IO.StreamWriter($escape.Open())+ $writer.Write('outside'); $writer.Dispose()+ }+ } finally {+ $archive.Dispose()+ }+ $hash = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash.ToLowerInvariant()+ if ($BadSum) { $hash = '0' * 64 }+ "$hash $asset`n" | Out-File -Encoding ascii -NoNewline "$zip.sha256"+ return (Join-Path $tmp $name)+}++$port = Get-Random -Minimum 20000 -Maximum 60000+$server = Start-Process python -ArgumentList @('-m', 'http.server', "$port", '--bind', '127.0.0.1', '--directory', $tmp) -PassThru -WindowStyle Hidden+try {+ $deadline = (Get-Date).AddSeconds(20)+ while ($true) {+ try { (New-Object Net.Sockets.TcpClient('127.0.0.1', $port)).Dispose(); break } catch { }+ if ((Get-Date) -gt $deadline) { Fail 'the local HTTP server did not start' }+ Start-Sleep -Milliseconds 200+ }++ # install <shell> <release> <dest>: run install.ps1 with the test env; returns the exit code.+ function Install([string] $shell, [string] $release, [string] $dest, [string] $log) {+ $env:AI_MEMORY_RELEASE_BASE_URL = "http://127.0.0.1:$port/$release"+ $env:AI_MEMORY_INSTALL_DIR = $dest+ $env:AI_MEMORY_NO_MODIFY_PATH = '1'+ try {+ & $shell -NoProfile -ExecutionPolicy Bypass -File $script *> $log+ return $LASTEXITCODE+ } finally {+ Remove-Item Env:AI_MEMORY_RELEASE_BASE_URL, Env:AI_MEMORY_INSTALL_DIR, Env:AI_MEMORY_NO_MODIFY_PATH -ErrorAction SilentlyContinue+ }+ }++ Publish good | Out-Null+ foreach ($shell in @('pwsh', 'powershell')) {+ $dest = Join-Path $tmp "inst-$shell\ai-memory"+ $log = Join-Path $tmp "good-$shell.log"+ if ((Install $shell 'good' $dest $log) -ne 0) { Fail "$shell refused a good release: $(Get-Content $log -Raw)" }+ if (-not (Test-Path (Join-Path $dest 'ai-memory.exe'))) { Fail "$shell did not unpack ai-memory.exe" }+ if (-not (Test-Path (Join-Path $dest 'hooks\_lib.sh'))) { Fail "$shell did not unpack hooks" }+ if ((Get-Content $log -Raw) -notmatch 'next: ') { Fail "$shell printed no next step: $(Get-Content $log -Raw)" }++ # A second run finds the install and points to `ai-memory upgrade`.+ $again = Join-Path $tmp "again-$shell.log"+ if ((Install $shell 'good' $dest $again) -eq 0) { Fail "$shell reinstalled over an existing install" }+ if ((Get-Content $again -Raw) -notmatch 'ai-memory upgrade') { Fail "$shell did not point to upgrade: $(Get-Content $again -Raw)" }+ }++ Publish badsum -BadSum | Out-Null+ $dest = Join-Path $tmp 'inst-badsum\ai-memory'+ $log = Join-Path $tmp 'badsum.log'+ if ((Install 'pwsh' 'badsum' $dest $log) -eq 0) { Fail 'a checksum mismatch was installed' }+ if ((Get-Content $log -Raw) -notmatch 'checksum mismatch') { Fail "mismatch not explained: $(Get-Content $log -Raw)" }+ if (Test-Path $dest) { Fail 'a refused release was unpacked' }++ Publish evil -Evil | Out-Null+ $dest = Join-Path $tmp 'inst-evil\ai-memory'+ $log = Join-Path $tmp 'evil.log'+ if ((Install 'pwsh' 'evil' $dest $log) -eq 0) { Fail 'an archive with a .. entry was installed' }+ if ((Get-Content $log -Raw) -notmatch 'unsafe path') { Fail "unsafe entry not explained: $(Get-Content $log -Raw)" }+ if (Test-Path $dest) { Fail 'a refused release was unpacked' }+ if (Test-Path (Join-Path $tmp 'inst-evil\escape.txt')) { Fail 'the .. entry escaped' }++ Write-Host 'install.ps1 checks passed'+} finally {+ Stop-Process -Id $server.Id -Force -ErrorAction SilentlyContinue+ Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue+}