Skip to content

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

Rust
72.3 KB
Raw Blame
//! `ai-memory upgrade` — refresh a GitHub-release native install.
//!
//! Docker-wrapper installs never reach this path: [`bin/ai-memory`] intercepts
//! `upgrade` and pulls the container image. This command covers the release
//! binary laid down under a writable user prefix (macOS/Linux tarball in
//! `docs/macos.md`, Windows zip in `docs/windows.md` Scenario C): download the
//! matching archive + `.sha256`, verify, replace the on-disk binary (and sibling
//! `hooks/` when present), then re-run `install-hooks --apply` for every staged
//! agent and every existing ai-memory-owned generated TypeScript integration.
//!
//! Client-only: never claims to upgrade a remote/homelab server.
//!
//! Egress decisions (AR004-style, cited): **timeout** — every request runs
//! with a hard 120 s client timeout and non-2xx fail-fast
//! ([`HTTP_TIMEOUT_SECS`]); **cache** — explicit none, this is a one-shot
//! CLI fetch, the extract `TempDir` is discarded after the replace, and a
//! cached archive would only add a stale-binary risk; **rate limit / load
//! shedding** — n/a (single outbound GET from a user-invoked CLI command,
//! no ingress). The 128 MiB body cap plus entry-count and 512 MiB expanded-size
//! caps are security limits, not resilience decisions (see
//! [`MAX_RELEASE_DOWNLOAD_BYTES`]).
//!
//! Ownership (live CLI command — kept in one module by convention):
//! - install classification (container / package-managed / writable)
//! - release fetch + checksum
//! - archive extract + path allowlist (`.tar.gz` or `.zip`)
//! - atomic binary/dir replace (Unix rename-over; Windows rename-aside)
//! - staged hook refresh

use std::fs;
use std::io::Cursor;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;

use anyhow::{Context, Result, bail};
use clap::ValueEnum;
use flate2::read::GzDecoder;
use sha2::{Digest, Sha256};
use tracing::info;

use crate::cli::{AgentChoice, HookInstallScope, InstallHooksArgs, UpgradeArgs};
use crate::commands::install_hooks;
use crate::config::Config;
use crate::install_layout::{HOOKS_DIR_NAME, shipped_binary_name};

const RELEASE_OWNER_REPO: &str = "akitaonrails/ai-memory";
const USER_AGENT: &str = concat!("ai-memory-cli/", env!("CARGO_PKG_VERSION"));
/// Hard cap on any single upgrade HTTP body (release tarball, `.sha256`,
/// or tag JSON). Current release archives are ~15–17 MiB; 128 MiB leaves
/// headroom while refusing multi-GB DoS if a mirror or compromised host
/// advertises / streams an oversized payload.
const MAX_RELEASE_DOWNLOAD_BYTES: usize = 128 * 1024 * 1024;
/// Refuse an archive whose directory contains an unreasonable number of
/// records, even when every individual path is allowed.
const MAX_RELEASE_ARCHIVE_ENTRIES: usize = 4_096;
/// Limit declared expanded bytes separately from the compressed HTTP body so
/// an otherwise valid-looking archive cannot exhaust the install disk.
const MAX_RELEASE_EXPANDED_BYTES: u64 = 512 * 1024 * 1024;
const HTTP_TIMEOUT_SECS: u64 = 120;
#[cfg(unix)]
const UNIX_EXECUTABLE_MODE: u32 = 0o755;

/// Known agent dir + parsed choice pairs from a staged hooks root.
type StagedAgentList = Vec<(String, AgentChoice)>;

/// Run the `upgrade` subcommand.
pub async fn run(config: &Config, config_path: Option<&Path>, args: UpgradeArgs) -> Result<()> {
    let exe = resolve_current_exe()?;
    ensure_supported_install(&exe)?;

    let fetcher = ReqwestFetcher::new()?;
    let base = release_base_url(config);
    let tag = resolve_tag(&fetcher, &base, args.version.as_deref()).await?;
    if skip_when_current(&tag, args.force) {
        refresh_plugins(config, &super::user_service::SystemRunner);
        return Ok(());
    }

    let extract_root = download_and_extract_release(&fetcher, &base, &tag).await?;
    apply_extracted_release(extract_root.path(), &exe)?;

    // The running process still contains the old release's embedded templates.
    // Re-enter through the replacement executable so every generated hook is
    // rendered by the version that was just installed.
    run_replacement_refresh(&exe, &config.data_dir, config_path)?;
    refresh_plugins(config, &super::user_service::SystemRunner);
    warn_remote_server(config);
    println!("✓ upgraded to {tag}");
    info!(%tag, path = %exe.display(), "native upgrade complete");
    Ok(())
}

/// Refresh staged and generated integrations from the replacement process.
/// This is reached only through the hidden `upgrade-refresh-hooks` command.
pub(crate) fn refresh_after_replace(config: &Config) -> Result<()> {
    refresh_staged_hooks(config)?;
    refresh_generated_integrations(config);
    Ok(())
}

fn run_replacement_refresh(exe: &Path, data_dir: &Path, config_path: Option<&Path>) -> Result<()> {
    let mut command = replacement_refresh_command(exe, data_dir, config_path);
    let status = command
        .status()
        .with_context(|| format!("starting replacement executable {}", exe.display()))?;
    if !status.success() {
        bail!(
            "the new binary was installed, but its hook refresh exited with {status}; \
             run `{} --data-dir {} upgrade-refresh-hooks`",
            exe.display(),
            data_dir.display()
        );
    }
    Ok(())
}

fn replacement_refresh_command(exe: &Path, data_dir: &Path, config_path: Option<&Path>) -> Command {
    let mut command = Command::new(exe);
    command.arg("--data-dir").arg(data_dir);
    if let Some(path) = config_path {
        command.arg("--config").arg(path);
    }
    command.arg("upgrade-refresh-hooks").stdin(Stdio::null());
    command
}

fn resolve_current_exe() -> Result<PathBuf> {
    let exe = std::env::current_exe().context("resolving current executable path")?;
    Ok(fs::canonicalize(&exe).unwrap_or(exe))
}

fn ensure_supported_install(exe: &Path) -> Result<()> {
    match classify_install(exe)? {
        InstallClass::Supported => Ok(()),
        InstallClass::Unsupported(reason) => bail!("{reason}"),
    }
}

fn skip_when_current(tag: &str, force: bool) -> bool {
    let current = env!("CARGO_PKG_VERSION");
    if !force && versions_match(tag, current) {
        println!("already up to date ({current})");
        return true;
    }
    false
}

async fn download_and_extract_release(
    fetcher: &ReqwestFetcher,
    base: &str,
    tag: &str,
) -> Result<tempfile::TempDir> {
    let asset = release_asset_name().context("no GitHub release asset for this OS/arch")?;
    let archive_bytes = fetch_verified_archive(fetcher, base, tag, asset).await?;
    let extract_root = tempfile::tempdir().context("creating extract temp dir")?;
    extract_release_archive(&archive_bytes, extract_root.path(), asset)
        .context("extracting release archive")?;
    ensure_extracted_binary(extract_root.path())?;
    Ok(extract_root)
}

async fn fetch_verified_archive(
    fetcher: &ReqwestFetcher,
    base: &str,
    tag: &str,
    asset: &str,
) -> Result<Vec<u8>> {
    let archive_url = format!("{base}/download/{tag}/{asset}");
    let checksum_url = format!("{archive_url}.sha256");
    println!("→ downloading {asset} ({tag})");
    let archive_bytes = fetcher
        .get_bytes(&archive_url)
        .await
        .with_context(|| format!("downloading {archive_url}"))?;
    let checksum_text = fetcher
        .get_text(&checksum_url)
        .await
        .with_context(|| format!("downloading {checksum_url}"))?;
    verify_archive_checksum(&archive_bytes, &checksum_text, asset)?;
    Ok(archive_bytes)
}

fn ensure_extracted_binary(extract_root: &Path) -> Result<()> {
    let name = shipped_binary_name();
    if extract_root.join(name).is_file() {
        return Ok(());
    }
    bail!("release archive is missing the {name} binary");
}

fn verify_archive_checksum(archive_bytes: &[u8], checksum_text: &str, asset: &str) -> Result<()> {
    let expected = parse_sha256_sidecar(checksum_text, asset)
        .with_context(|| format!("parsing checksum sidecar for {asset}"))?;
    let actual = sha256_hex(archive_bytes);
    if !actual.eq_ignore_ascii_case(&expected) {
        bail!("release archive checksum mismatch (expected {expected}, got {actual})");
    }
    println!("  ✓ checksum ok");
    Ok(())
}

fn apply_extracted_release(extract_root: &Path, exe: &Path) -> Result<()> {
    let install_dir = exe
        .parent()
        .map(Path::to_path_buf)
        .context("executable has no parent directory")?;
    replace_binary(extract_root, exe)?;
    maybe_refresh_sibling_hooks(extract_root, &install_dir)?;
    Ok(())
}

fn replace_binary(extract_root: &Path, exe: &Path) -> Result<()> {
    let new_binary = extract_root.join(shipped_binary_name());
    println!("→ replacing {}", exe.display());
    replace_file_atomic(&new_binary, exe).with_context(|| {
        format!(
            "replacing {}; if this fails mid-way look for {}.new / {}.old",
            exe.display(),
            exe.display(),
            exe.display()
        )
    })
}

fn maybe_refresh_sibling_hooks(extract_root: &Path, install_dir: &Path) -> Result<()> {
    let extracted_hooks = extract_root.join(HOOKS_DIR_NAME);
    let sibling_hooks = install_dir.join(HOOKS_DIR_NAME);
    if !(extracted_hooks.is_dir() && sibling_hooks.exists()) {
        return Ok(());
    }
    println!("→ refreshing {}", sibling_hooks.display());
    replace_dir_atomic(&extracted_hooks, &sibling_hooks)
        .with_context(|| format!("replacing {}", sibling_hooks.display()))
}

#[derive(Debug, PartialEq, Eq)]
enum InstallClass {
    Supported,
    Unsupported(String),
}

fn classify_install(exe: &Path) -> Result<InstallClass> {
    if let Some(reason) = container_refusal() {
        return Ok(InstallClass::Unsupported(reason));
    }
    if let Some(reason) = package_managed_refusal(exe) {
        return Ok(InstallClass::Unsupported(reason));
    }
    if let Some(reason) = unwritable_refusal(exe)? {
        return Ok(InstallClass::Unsupported(reason));
    }
    Ok(InstallClass::Supported)
}

fn container_refusal() -> Option<String> {
    if ai_memory_wiki::backup::running_in_container() {
        Some(
            "refusing to self-upgrade inside a container; run `ai-memory upgrade` on the \
             host Docker wrapper, or replace the image with `docker pull`"
                .into(),
        )
    } else {
        None
    }
}

fn package_managed_refusal(exe: &Path) -> Option<String> {
    let path_str = exe.to_string_lossy();
    for prefix in package_managed_prefixes() {
        if path_str.starts_with(prefix) {
            return Some(format!(
                "refusing to self-upgrade a package-managed install at {}; \
                 use your package manager (Homebrew, AUR, apt, …) instead",
                exe.display()
            ));
        }
    }
    None
}

fn unwritable_refusal(exe: &Path) -> Result<Option<String>> {
    let parent = exe
        .parent()
        .ok_or_else(|| anyhow::anyhow!("executable has no parent directory"))?;
    // Only the parent directory must be writable: atomic replace uses rename,
    // and Linux returns ETXTBSY when opening a running executable for write.
    if is_writable_dir(parent) {
        return Ok(None);
    }
    Ok(Some(format!(
        "refusing to self-upgrade: {} is not writable by this user; \
         install under ~/.local (or another user-owned prefix) and re-run",
        exe.display()
    )))
}

fn package_managed_prefixes() -> &'static [&'static str] {
    &[
        "/opt/homebrew/",
        "/usr/local/Cellar/",
        "/home/linuxbrew/.linuxbrew/",
        "/usr/bin/",
        "/bin/",
        "/sbin/",
        "/usr/sbin/",
        "/nix/store/",
    ]
}

fn is_writable_dir(path: &Path) -> bool {
    let probe = path.join(".ai-memory-upgrade-write-probe");
    match fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&probe)
    {
        Ok(_) => {
            let _ = fs::remove_file(&probe);
            true
        }
        Err(_) => false,
    }
}

fn release_base_url(config: &Config) -> String {
    config
        .release_base_url
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .unwrap_or_else(|| format!("https://github.com/{RELEASE_OWNER_REPO}/releases"))
}

fn release_asset_name() -> Option<&'static str> {
    release_asset_name_for(std::env::consts::OS, std::env::consts::ARCH)
}

/// Map an OS/arch pair to the GitHub release archive name.
///
/// Pure so every CI host can assert the full matrix (Unix tarballs + Windows
/// x86_64 zip; Windows aarch64 stays `None` — no release asset) without
/// cross-compiling. Callers use [`release_asset_name`] for the running host.
fn release_asset_name_for(os: &str, arch: &str) -> Option<&'static str> {
    match (os, arch) {
        ("linux", "x86_64") => Some("ai-memory-linux-x86_64.tar.gz"),
        ("linux", "aarch64") => Some("ai-memory-linux-aarch64.tar.gz"),
        ("macos", "aarch64") => Some("ai-memory-macos-aarch64.tar.gz"),
        ("macos", "x86_64") => Some("ai-memory-macos-x86_64.tar.gz"),
        ("windows", "x86_64") => Some("ai-memory-windows-x86_64.zip"),
        _ => None,
    }
}

fn versions_match(tag: &str, current: &str) -> bool {
    normalize_version(tag) == normalize_version(current)
}

fn normalize_version(raw: &str) -> String {
    raw.trim().trim_start_matches('v').to_string()
}

async fn resolve_tag(fetcher: &ReqwestFetcher, base: &str, pinned: Option<&str>) -> Result<String> {
    if let Some(pinned) = pinned {
        return normalize_pinned_tag(pinned);
    }
    if base.contains("github.com") {
        return fetch_github_latest_tag(fetcher).await;
    }
    fetch_text_latest_tag(fetcher, base).await
}

fn normalize_pinned_tag(pinned: &str) -> Result<String> {
    let tag = pinned.trim();
    if tag.is_empty() {
        bail!("--version must be a non-empty release tag (e.g. v2.3.2)");
    }
    Ok(if tag.starts_with('v') {
        tag.to_string()
    } else {
        format!("v{tag}")
    })
}

async fn fetch_github_latest_tag(fetcher: &ReqwestFetcher) -> Result<String> {
    let api = format!("https://api.github.com/repos/{RELEASE_OWNER_REPO}/releases/latest");
    let body = fetcher
        .get_text(&api)
        .await
        .context("fetching latest release")?;
    let json: serde_json::Value =
        serde_json::from_str(&body).context("parsing latest release JSON")?;
    let tag = json
        .get("tag_name")
        .and_then(|v| v.as_str())
        .context("latest release JSON missing tag_name")?;
    Ok(tag.to_string())
}

async fn fetch_text_latest_tag(fetcher: &ReqwestFetcher, base: &str) -> Result<String> {
    // Prefer the GitHub API when talking to github.com; for a test base URL
    // fall back to a `{base}/latest/tag` text endpoint.
    let tag = fetcher
        .get_text(&format!("{base}/latest/tag"))
        .await
        .context("fetching latest tag")?
        .trim()
        .to_string();
    if tag.is_empty() {
        bail!("latest tag endpoint returned empty body");
    }
    Ok(tag)
}

fn parse_sha256_sidecar(text: &str, expected_filename: &str) -> Result<String> {
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut parts = line.split_whitespace();
        let hash = parts.next().context("checksum line missing hash")?;
        if hash.len() != 64 || !hash.chars().all(|c| c.is_ascii_hexdigit()) {
            bail!("checksum line has invalid sha256 hash: {hash}");
        }
        if let Some(name) = parts.next() {
            let name = name.trim_start_matches('*');
            if name != expected_filename {
                bail!("checksum sidecar names {name}, expected {expected_filename}");
            }
        }
        return Ok(hash.to_ascii_lowercase());
    }
    bail!("checksum sidecar contained no hash line");
}

fn sha256_hex(bytes: &[u8]) -> String {
    format!("{:x}", Sha256::digest(bytes))
}

fn extract_release_archive(bytes: &[u8], dest: &Path, asset: &str) -> Result<()> {
    if asset.ends_with(".zip") {
        extract_release_zip(bytes, dest)
    } else if asset.ends_with(".tar.gz") || asset.ends_with(".tgz") {
        extract_release_tar_gz(bytes, dest)
    } else {
        bail!("unsupported release archive format for asset {asset}");
    }
}

fn extract_release_tar_gz(bytes: &[u8], dest: &Path) -> Result<()> {
    let decoder = GzDecoder::new(bytes);
    let mut archive = tar::Archive::new(decoder);
    archive.set_preserve_permissions(false);
    let mut budget = ReleaseArchiveBudget::default();
    for entry in archive.entries()? {
        let mut entry = entry?;
        let path = entry.path()?.into_owned();
        let entry_type = entry.header().entry_type();
        let action = validate_release_tar_entry(&path, entry_type)?;
        budget.account(entry.header().size()?)?;
        if action == ReleaseEntryAction::Extract {
            entry
                .unpack_in(dest)
                .with_context(|| format!("extracting {}", path.display()))?;
        }
    }
    Ok(())
}

fn extract_release_zip(bytes: &[u8], dest: &Path) -> Result<()> {
    let cursor = Cursor::new(bytes);
    let mut archive = zip::ZipArchive::new(cursor).context("opening release zip")?;
    archive
        .validate_header_consistency()
        .context("validating release zip headers")?;
    let mut budget = ReleaseArchiveBudget::default();
    for i in 0..archive.len() {
        let mut file = archive
            .by_index(i)
            .with_context(|| format!("reading zip entry {i}"))?;
        let Some(enclosed) = file.enclosed_name() else {
            bail!("release archive contains unsafe path: {}", file.name());
        };
        if file.is_symlink() {
            bail!(
                "release archive contains unsupported link entry: {}",
                enclosed.display()
            );
        }
        let action = validate_release_path(&enclosed, file.is_dir())?;
        budget.account(file.size())?;
        if action == ReleaseEntryAction::Ignore {
            continue;
        }
        let out_path = dest.join(&enclosed);
        if file.is_dir() {
            fs::create_dir_all(&out_path)
                .with_context(|| format!("creating {}", out_path.display()))?;
            continue;
        }
        if let Some(parent) = out_path.parent() {
            fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
        }
        let mut out = fs::File::create(&out_path)
            .with_context(|| format!("creating {}", out_path.display()))?;
        std::io::copy(&mut file, &mut out)
            .with_context(|| format!("extracting {}", enclosed.display()))?;
    }
    Ok(())
}

fn is_regular_file(entry_type: tar::EntryType) -> bool {
    entry_type.is_file() || entry_type == tar::EntryType::GNUSparse
}

fn validate_release_tar_entry(
    path: &Path,
    entry_type: tar::EntryType,
) -> Result<ReleaseEntryAction> {
    if entry_type.is_symlink() || entry_type.is_hard_link() {
        bail!(
            "release archive contains unsupported link entry: {}",
            path.display()
        );
    }
    if !(is_regular_file(entry_type) || entry_type.is_dir()) {
        bail!(
            "release archive contains unsupported entry type: {}",
            path.display()
        );
    }
    validate_release_path(path, entry_type.is_dir())
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReleaseEntryAction {
    Extract,
    Ignore,
}

#[derive(Default)]
struct ReleaseArchiveBudget {
    entries: usize,
    expanded_bytes: u64,
}

impl ReleaseArchiveBudget {
    fn account(&mut self, expanded_bytes: u64) -> Result<()> {
        self.entries = self
            .entries
            .checked_add(1)
            .context("release archive entry count overflow")?;
        if self.entries > MAX_RELEASE_ARCHIVE_ENTRIES {
            bail!("release archive contains more than {MAX_RELEASE_ARCHIVE_ENTRIES} entries");
        }
        self.expanded_bytes = self
            .expanded_bytes
            .checked_add(expanded_bytes)
            .context("release archive expanded size overflow")?;
        if self.expanded_bytes > MAX_RELEASE_EXPANDED_BYTES {
            bail!("release archive expands past the {MAX_RELEASE_EXPANDED_BYTES}-byte limit");
        }
        Ok(())
    }
}

/// Shared path gates for tar and zip entries (allowlist + traversal).
fn validate_release_path(path: &Path, is_dir: bool) -> Result<ReleaseEntryAction> {
    let normalized = normalize_release_entry_path(path)?;
    // `tar -C dist/$artifact -czf … .` (release.yml) emits `./` as the
    // archive root — empty after stripping CurDir; allow that directory only.
    if normalized.as_os_str().is_empty() {
        if is_dir {
            return Ok(ReleaseEntryAction::Ignore);
        }
        bail!("release archive contains unsafe path: {}", path.display());
    }
    let key = release_path_key(&normalized);
    let is_runtime_file = !is_dir && matches!(key.as_str(), "ai-memory" | "ai-memory.exe");
    let is_hook_entry = (is_dir && key == HOOKS_DIR_NAME)
        || key
            .strip_prefix(HOOKS_DIR_NAME)
            .is_some_and(|rest| rest.starts_with('/'));
    let action = if is_runtime_file || is_hook_entry {
        Some(ReleaseEntryAction::Extract)
    } else if (is_dir && RELEASE_SUPPORT_DIRS.contains(&key.as_str()))
        || (!is_dir && RELEASE_SUPPORT_FILES.contains(&key.as_str()))
    {
        Some(ReleaseEntryAction::Ignore)
    } else {
        None
    };
    match action {
        Some(action) => Ok(action),
        None => bail!(
            "release archive contains unexpected path: {}",
            path.display()
        ),
    }
}

/// Drop `Component::CurDir` (release tarballs use `./ai-memory`); reject
/// anything that is not a normal component after that.
fn normalize_release_entry_path(path: &Path) -> Result<PathBuf> {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::Normal(part) => out.push(part),
            _ => bail!("release archive contains unsafe path: {}", path.display()),
        }
    }
    Ok(out)
}

/// Portable forward-slash key so Windows `Path` separators do not break
/// the allowlist string checks.
fn release_path_key(path: &Path) -> String {
    path.components()
        .filter_map(|c| match c {
            Component::Normal(part) => Some(part.to_string_lossy()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("/")
}

/// Directory entries emitted by the Linux, macOS, and Windows release jobs.
/// These are validated but not copied into the temporary self-upgrade tree.
const RELEASE_SUPPORT_DIRS: &[&str] = &[
    "crates",
    "crates/ai-memory-cli",
    "crates/ai-memory-cli/templates",
    "docs",
    "packaging",
    "packaging/env",
    "packaging/launchd",
    "packaging/systemd",
    "packaging/sysusers",
    "packaging/tmpfiles",
];

/// Non-runtime files copied into release archives by `release.yml`. Keep this
/// exact rather than admitting whole documentation or packaging subtrees.
const RELEASE_SUPPORT_FILES: &[&str] = &[
    "LICENSE",
    "README.md",
    "crates/ai-memory-cli/templates/config.default.toml",
    "docs/install.md",
    "docs/macos.md",
    "docs/windows.md",
    "packaging/env/ai-memory.env",
    "packaging/launchd/com.github.akitaonrails.ai-memory.plist",
    "packaging/systemd/ai-memory-user.service",
    "packaging/systemd/ai-memory.service",
    "packaging/sysusers/ai-memory.conf",
    "packaging/tmpfiles/ai-memory.conf",
];

fn replace_file_atomic(src: &Path, dest: &Path) -> Result<()> {
    let tmp = dest.with_extension("new");
    if tmp.exists() {
        fs::remove_file(&tmp).with_context(|| format!("removing stale {}", tmp.display()))?;
    }
    fs::copy(src, &tmp).with_context(|| format!("copying to {}", tmp.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&tmp, fs::Permissions::from_mode(UNIX_EXECUTABLE_MODE))
            .with_context(|| format!("chmod +x {}", tmp.display()))?;
    }
    #[cfg(windows)]
    {
        replace_file_windows_rename_aside(&tmp, dest)
    }
    #[cfg(not(windows))]
    {
        fs::rename(&tmp, dest).with_context(|| {
            format!(
                "renaming {} -> {} (left {} in place on failure)",
                tmp.display(),
                dest.display(),
                tmp.display()
            )
        })?;
        Ok(())
    }
}

/// Linear backoff, 100 ms + 200 ms + … + 1.2 s: a scanner holds a fresh
/// 100 MB binary for a few seconds.
#[cfg(windows)]
const SWAP_RETRY_ATTEMPTS: u32 = 12;
#[cfg(windows)]
const SWAP_RETRY_BASE_DELAY: Duration = Duration::from_millis(100);

/// Windows allows renaming a running image aside, but not overwriting it.
/// Stage to `.new`, move live `dest` → `.old`, promote `.new` → `dest`, then
/// best-effort delete `.old` (often fails while this process still maps it).
///
/// Both renames retry a sharing violation: a scanner holding the running
/// binary or the fresh `.new` used to fail the upgrade.
#[cfg(windows)]
fn replace_file_windows_rename_aside(tmp: &Path, dest: &Path) -> Result<()> {
    let rename = |from: &Path, to: &Path| {
        ai_memory_wiki::rename_with_retry(from, to, SWAP_RETRY_ATTEMPTS, SWAP_RETRY_BASE_DELAY)
    };
    let old = dest.with_extension("old");
    if old.exists() {
        let _ = fs::remove_file(&old);
    }
    let had_dest = dest.exists();
    if had_dest {
        rename(dest, &old).with_context(|| {
            format!(
                "moving running binary aside {} -> {}",
                dest.display(),
                old.display()
            )
        })?;
    }
    if let Err(err) = rename(tmp, dest) {
        if had_dest {
            let _ = rename(&old, dest);
        }
        return Err(err).with_context(|| {
            format!(
                "renaming {} -> {} (attempted rollback of {})",
                tmp.display(),
                dest.display(),
                old.display()
            )
        });
    }
    let _ = fs::remove_file(&old);
    Ok(())
}

fn replace_dir_atomic(src: &Path, dest: &Path) -> Result<()> {
    let parent = dest
        .parent()
        .ok_or_else(|| anyhow::anyhow!("destination {} has no parent", dest.display()))?;
    let tmp = prepare_dir_swap_staging(src, parent, dest)?;
    let backup = move_aside_for_swap(parent, dest)?;
    commit_dir_swap(&tmp, dest, &backup)
}

fn prepare_dir_swap_staging(src: &Path, parent: &Path, dest: &Path) -> Result<PathBuf> {
    let tmp = sibling_swap_path(parent, dest, "new");
    remove_dir_if_exists(&tmp)?;
    copy_dir_recursive(src, &tmp)?;
    Ok(tmp)
}

fn move_aside_for_swap(parent: &Path, dest: &Path) -> Result<PathBuf> {
    let backup = sibling_swap_path(parent, dest, "old");
    remove_dir_if_exists(&backup)?;
    if dest.exists() {
        fs::rename(dest, &backup)
            .with_context(|| format!("moving {} aside to {}", dest.display(), backup.display()))?;
    }
    Ok(backup)
}

fn commit_dir_swap(tmp: &Path, dest: &Path, backup: &Path) -> Result<()> {
    if let Err(err) = fs::rename(tmp, dest) {
        if backup.exists() {
            let _ = fs::rename(backup, dest);
        }
        return Err(err)
            .with_context(|| format!("renaming {} -> {}", tmp.display(), dest.display()));
    }
    let _ = remove_dir_if_exists(backup);
    Ok(())
}

fn remove_dir_if_exists(path: &Path) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }
    fs::remove_dir_all(path).with_context(|| format!("removing stale {}", path.display()))
}

fn sibling_swap_path(parent: &Path, dest: &Path, suffix: &str) -> PathBuf {
    let name = dest
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(HOOKS_DIR_NAME);
    parent.join(format!(".{name}.{suffix}"))
}

fn copy_dir_recursive(src: &Path, dest: &Path) -> Result<()> {
    fs::create_dir_all(dest).with_context(|| format!("creating {}", dest.display()))?;
    for entry in fs::read_dir(src).with_context(|| format!("reading {}", src.display()))? {
        let entry = entry?;
        let ty = entry.file_type()?;
        let to = dest.join(entry.file_name());
        if ty.is_dir() {
            copy_dir_recursive(&entry.path(), &to)?;
        } else if ty.is_file() {
            fs::copy(entry.path(), &to)
                .with_context(|| format!("copying {}", entry.path().display()))?;
        }
    }
    Ok(())
}

/// List agent dirs under a staged hooks root, skipping shared helper dirs.
///
/// `lib` and `_*-prefixed` directories hold shared helpers, not agents (#38).
/// Unknown directory names are omitted (callers may log them).
fn list_staged_agents(hooks_root: &Path) -> Result<(StagedAgentList, Vec<String>)> {
    let mut agents = StagedAgentList::new();
    let mut unknown = Vec::new();
    for entry in fs::read_dir(hooks_root)
        .with_context(|| format!("reading staged hooks at {}", hooks_root.display()))?
    {
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            continue;
        }
        let name = entry.file_name();
        let Some(name) = name.to_str() else {
            continue;
        };
        if name == "lib" || name.starts_with('_') {
            continue;
        }
        match AgentChoice::from_str(name, true) {
            Ok(agent) => agents.push((name.to_string(), agent)),
            Err(_) => unknown.push(name.to_string()),
        }
    }
    agents.sort_by(|a, b| a.0.cmp(&b.0));
    unknown.sort();
    Ok((agents, unknown))
}

fn refresh_staged_hooks(config: &Config) -> Result<()> {
    let hooks_root = staged_hooks_root(config);
    if !hooks_root.is_dir() {
        println!("→ no staged hook scripts found at {}", hooks_root.display());
        println!("  (nothing to refresh — install-hooks hasn't been run with --apply yet)");
        return Ok(());
    }
    let agents = collect_refreshable_agents(&hooks_root)?;
    if agents.is_empty() {
        println!(
            "→ no staged agent dirs found under {}",
            hooks_root.display()
        );
        return Ok(());
    }
    refresh_agent_list(config, &agents);
    Ok(())
}

const GENERATED_INTEGRATIONS: &[(&str, AgentChoice)] = &[
    ("opencode", AgentChoice::OpenCode),
    ("opencode2", AgentChoice::OpenCode2),
    ("omp", AgentChoice::Omp),
    ("pi", AgentChoice::Pi),
    ("openclaw", AgentChoice::Openclaw),
];

fn refresh_generated_integrations(config: &Config) {
    for &(name, agent) in GENERATED_INTEGRATIONS {
        let path = match default_generated_integration_path(agent) {
            Ok(path) => path,
            Err(err) => {
                println!("  (skipping generated {name} integration — {err:#})");
                continue;
            }
        };
        let owned = fs::read_to_string(&path).is_ok_and(|content| {
            install_hooks::generated_integration_content_is_owned(agent, &content)
        });
        if !owned {
            continue;
        }

        println!("→ refreshing generated {name} integration");
        let mut args = apply_hooks_args(agent);
        args.config_file = if agent == AgentChoice::Openclaw {
            path.parent().map(Path::to_path_buf)
        } else {
            Some(path.clone())
        };
        let result = if agent == AgentChoice::OpenCode {
            install_hooks::run_with_opencode_dialect(
                config,
                args,
                Some(ai_memory_workstream::OpenCodeDialect::V1),
            )
        } else {
            install_hooks::run(config, args)
        };
        if let Err(err) = result {
            println!(
                "      (skipped — {err:#}; re-run `ai-memory install-hooks --agent {name} --apply`)"
            );
        }
    }
}

fn default_generated_integration_path(agent: AgentChoice) -> Result<PathBuf> {
    match agent {
        AgentChoice::OpenCode => install_hooks::opencode_plugin_path(),
        AgentChoice::OpenCode2 => install_hooks::opencode2_plugin_path(),
        AgentChoice::Omp => install_hooks::omp_extension_path(None),
        AgentChoice::Pi => install_hooks::pi_extension_path(),
        AgentChoice::Openclaw => Ok(crate::commands::openclaw_plugin::default_plugin_dir()?
            .join(crate::commands::openclaw_plugin::ENTRYPOINT_TS)),
        _ => bail!("not a generated TypeScript integration: {agent:?}"),
    }
}

/// Keep the marketplace plugins in step with the binary (#1166). Claude Code
/// does not auto-update a third-party marketplace unless the user turned that
/// on, so the Claude Code plugin is updated here. Codex is only told what to
/// run: its hooks must be re-trusted only when a command changes, and the
/// operator should see that happen in Codex itself.
fn refresh_plugins(config: &Config, runner: &dyn super::user_service::CommandRunner) {
    use super::agent_plugins::{self, PluginHarness};
    let Some(home) = super::run::native_home(config) else {
        return;
    };
    let env = |name: &str| {
        config
            .runtime_env
            .process_env()
            .iter()
            .find(|(key, _)| key.as_os_str() == name)
            .map(|(_, value)| value.clone())
    };
    for plugin in agent_plugins::installed(&home, &env) {
        match plugin.harness {
            PluginHarness::ClaudeCode => {
                println!("→ updating the ai-memory Claude Code plugin");
                for line in agent_plugins::update_claude_code(runner) {
                    println!("    {line}");
                }
            }
            PluginHarness::Codex => println!(
                "→ the ai-memory Codex plugin is installed: run `codex plugin marketplace upgrade \
                 ai-memory` and `codex plugin add {}` to update it",
                agent_plugins::PLUGIN_ID
            ),
        }
    }
}

fn staged_hooks_root(config: &Config) -> PathBuf {
    install_hooks::hook_staging_root(
        &config.data_dir,
        ai_memory_wiki::backup::running_in_container(),
    )
    .join(HOOKS_DIR_NAME)
}

fn collect_refreshable_agents(hooks_root: &Path) -> Result<StagedAgentList> {
    let (agents, unknown) = list_staged_agents(hooks_root)?;
    for name in &unknown {
        println!("  (skipping unknown staged agent dir `{name}`)");
    }
    Ok(agents)
}

fn refresh_agent_list(config: &Config, agents: &StagedAgentList) {
    let names: Vec<_> = agents.iter().map(|(n, _)| n.as_str()).collect();
    println!("→ refreshing staged hook scripts for: {}", names.join(" "));
    for (name, agent) in agents {
        apply_staged_agent_hooks(config, name, *agent);
    }
}

fn apply_staged_agent_hooks(config: &Config, name: &str, agent: AgentChoice) {
    if agent == AgentChoice::ClaudeCode
        && let Some(settings) = claude_user_level_install_absent()
    {
        println!(
            "    (no ai-memory hooks in {} — skipping the user-level re-apply; the staged \
             scripts are refreshed, but `--scope project` files are not rewritten: re-run \
             `ai-memory install-hooks --agent {name} --scope project --apply` in each such \
             checkout to pick up hook-command changes)",
            settings.display()
        );
        match install_hooks::restage_claude_code_scripts(&config.data_dir, None) {
            Ok(staged) => println!("    restaged {}", staged.display()),
            Err(err) => println!(
                "      (skipped — {err:#}; re-run `ai-memory install-hooks \
                 --agent {name} --scope project --apply` in each checkout)"
            ),
        }
        return;
    }
    println!("    ai-memory install-hooks --agent {name} --apply");
    if let Err(err) = install_hooks::run(config, apply_hooks_args(agent)) {
        println!(
            "      (skipped — {err:#}; re-run with the same --server-url / --auth-token used originally)"
        );
    }
}

/// The user-level Claude Code settings path when that file provably holds no
/// ai-memory install: it is missing, or parses without one of our hooks. A
/// `--scope project` install stages the same scripts without touching that
/// file, so a staged `claude-code` dir alone no longer proves a user-level
/// install exists — and a bare re-apply would create one the operator never
/// asked for. `None` when the file carries our hooks, and also when it cannot
/// be read or parsed: the re-apply then runs and reports that error, as it
/// did before project scope existed.
fn claude_user_level_install_absent() -> Option<PathBuf> {
    claude_user_level_install_absent_at(install_hooks::claude_settings_path().ok()?)
}

fn claude_user_level_install_absent_at(path: PathBuf) -> Option<PathBuf> {
    let content = match fs::read_to_string(&path) {
        Ok(content) => content,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Some(path),
        Err(_) => return None,
    };
    let document: serde_json::Value = serde_json::from_str(&content).ok()?;
    (!install_hooks::document_carries_ai_memory_hooks(&document)).then_some(path)
}

fn apply_hooks_args(agent: AgentChoice) -> InstallHooksArgs {
    InstallHooksArgs {
        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,
    }
}

fn warn_remote_server(config: &Config) {
    if !config.server_url_configured() {
        return;
    }
    if is_local_server_url(&config.server_url) {
        return;
    }
    eprintln!(
        "note: AI_MEMORY_SERVER_URL={} looks remote — this upgrade refreshed only the local \
         binary and hooks; redeploy the remote server separately",
        config.server_url
    );
}

/// Loopback, or the `0.0.0.0` bind address a local server is often reached
/// through. Only decides whether to print the remote-server note.
fn is_local_server_url(url: &str) -> bool {
    crate::http_client::is_loopback_url(url)
        || reqwest::Url::parse(url).is_ok_and(|parsed| parsed.host_str() == Some("0.0.0.0"))
}

struct ReqwestFetcher {
    client: reqwest::Client,
    max_bytes: usize,
}

impl ReqwestFetcher {
    fn new() -> Result<Self> {
        Self::with_max_bytes(MAX_RELEASE_DOWNLOAD_BYTES)
    }

    fn with_max_bytes(max_bytes: usize) -> Result<Self> {
        if max_bytes == 0 {
            bail!("upgrade download limit must be greater than zero");
        }
        let client = reqwest::Client::builder()
            .user_agent(USER_AGENT)
            .timeout(Duration::from_secs(HTTP_TIMEOUT_SECS))
            .build()
            .context("building HTTP client")?;
        Ok(Self { client, max_bytes })
    }

    async fn get_bytes(&self, url: &str) -> Result<Vec<u8>> {
        let mut response = self
            .client
            .get(url)
            .send()
            .await
            .with_context(|| format!("GET {url}"))?;
        let status = response.status();
        if !status.is_success() {
            bail!("GET {url} returned {status}");
        }
        refuse_oversized_content_length(url, response.content_length(), self.max_bytes)?;
        read_body_capped(&mut response, url, self.max_bytes).await
    }

    async fn get_text(&self, url: &str) -> Result<String> {
        let bytes = self.get_bytes(url).await?;
        String::from_utf8(bytes).context("response body is not UTF-8")
    }
}

fn refuse_oversized_content_length(
    url: &str,
    content_len: Option<u64>,
    max_bytes: usize,
) -> Result<()> {
    if let Some(len) = content_len
        && content_length_exceeds_limit(len, max_bytes)
    {
        bail!(
            "GET {url} Content-Length {len} exceeds upgrade download limit \
             of {max_bytes} bytes"
        );
    }
    Ok(())
}

async fn read_body_capped(
    response: &mut reqwest::Response,
    url: &str,
    max_bytes: usize,
) -> Result<Vec<u8>> {
    // Stream with a hard cap — Content-Length can lie or be absent.
    let mut out = reserve_body_buffer(response.content_length(), max_bytes);
    while let Some(chunk) = response
        .chunk()
        .await
        .with_context(|| format!("reading body from {url}"))?
    {
        append_chunk_within_limit(&mut out, &chunk, url, max_bytes)?;
    }
    Ok(out)
}

fn reserve_body_buffer(content_len: Option<u64>, max_bytes: usize) -> Vec<u8> {
    let mut out = Vec::new();
    if let Some(len) = content_len
        && let Ok(hint) = usize::try_from(len)
    {
        out.reserve(hint.min(max_bytes));
    }
    out
}

fn append_chunk_within_limit(
    out: &mut Vec<u8>,
    chunk: &[u8],
    url: &str,
    max_bytes: usize,
) -> Result<()> {
    let over_limit = out
        .len()
        .checked_add(chunk.len())
        .is_none_or(|next| next > max_bytes);
    if over_limit {
        bail!("GET {url} body exceeded upgrade download limit of {max_bytes} bytes");
    }
    out.extend_from_slice(chunk);
    Ok(())
}

/// `true` when `content_length` is strictly greater than `max_bytes`.
///
/// Compares in `u64` so a 32-bit `usize` limit never truncates via `as u64`
/// in the wrong direction. If `max_bytes` somehow cannot fit in `u64`
/// (theoretical >64-bit usize), every finite Content-Length is treated as
/// under the limit and the streamed `checked_add` gate still enforces it.
fn content_length_exceeds_limit(content_length: u64, max_bytes: usize) -> bool {
    match u64::try_from(max_bytes) {
        Ok(max) => content_length > max,
        Err(_) => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write as _;
    use tar::Header;
    use zip::ZipWriter;
    use zip::write::SimpleFileOptions;

    #[test]
    fn replacement_binary_refresh_receives_the_loaded_config_coordinates() {
        let exe = Path::new("/opt/ai memory/bin/ai-memory");
        let data = Path::new("/srv/memory data");
        let config = Path::new("/etc/ai memory/config.toml");
        let command = replacement_refresh_command(exe, data, Some(config));

        assert_eq!(command.get_program(), exe.as_os_str());
        assert_eq!(
            command.get_args().collect::<Vec<_>>(),
            [
                "--data-dir".as_ref(),
                data.as_os_str(),
                "--config".as_ref(),
                config.as_os_str(),
                "upgrade-refresh-hooks".as_ref(),
            ]
        );

        let command = replacement_refresh_command(exe, data, None);
        assert_eq!(
            command.get_args().collect::<Vec<_>>(),
            [
                "--data-dir".as_ref(),
                data.as_os_str(),
                "upgrade-refresh-hooks".as_ref(),
            ]
        );
    }

    /// `upgrade` keeps an installed Claude Code plugin in step with the
    /// binary: marketplace update, then plugin update. Without the plugin,
    /// and for the Codex plugin, it runs nothing.
    #[test]
    fn upgrade_updates_an_installed_claude_code_plugin_only() {
        use crate::commands::agent_plugins::test_support::{
            RecordingRunner, install_claude_plugin, install_codex_plugin,
        };
        let home = tempfile::tempdir().unwrap();
        let config = Config {
            home_dir: Some(home.path().to_string_lossy().into_owned()),
            ..Config::default()
        };

        let runner = RecordingRunner::new(None);
        refresh_plugins(&config, &runner);
        install_codex_plugin(home.path());
        refresh_plugins(&config, &runner);
        assert!(runner.calls.borrow().is_empty(), "{:?}", runner.calls);

        install_claude_plugin(home.path(), "0.0.1", true);
        refresh_plugins(&config, &runner);
        assert_eq!(
            *runner.calls.borrow(),
            vec![
                "claude plugin marketplace update ai-memory",
                "claude plugin update ai-memory@ai-memory"
            ]
        );
    }

    #[test]
    fn release_asset_name_for_covers_unix_and_windows_matrix() {
        // Table-driven so Linux CI still guards macos-* and windows mapping.
        let cases: &[(&str, &str, Option<&str>)] = &[
            ("linux", "x86_64", Some("ai-memory-linux-x86_64.tar.gz")),
            ("linux", "aarch64", Some("ai-memory-linux-aarch64.tar.gz")),
            ("macos", "aarch64", Some("ai-memory-macos-aarch64.tar.gz")),
            ("macos", "x86_64", Some("ai-memory-macos-x86_64.tar.gz")),
            ("windows", "x86_64", Some("ai-memory-windows-x86_64.zip")),
            ("windows", "aarch64", None),
            ("linux", "arm", None),
            ("freebsd", "x86_64", None),
            ("unknown", "unknown", None),
        ];
        for &(os, arch, expected) in cases {
            assert_eq!(
                release_asset_name_for(os, arch),
                expected,
                "os={os} arch={arch}"
            );
        }
        // Host still maps through the same function (never invent a name).
        assert_eq!(
            release_asset_name(),
            release_asset_name_for(std::env::consts::OS, std::env::consts::ARCH)
        );
    }

    #[test]
    fn shipped_binary_name_matches_host() {
        #[cfg(windows)]
        assert_eq!(shipped_binary_name(), "ai-memory.exe");
        #[cfg(not(windows))]
        assert_eq!(shipped_binary_name(), "ai-memory");
    }

    #[test]
    fn allowlist_extracts_only_runtime_assets() -> Result<()> {
        assert_eq!(
            validate_release_path(Path::new(shipped_binary_name()), false)?,
            ReleaseEntryAction::Extract
        );
        assert_eq!(
            validate_release_path(Path::new("hooks/claude-code/x.sh"), false)?,
            ReleaseEntryAction::Extract
        );
        assert_eq!(
            validate_release_path(Path::new("docs/install.md"), false)?,
            ReleaseEntryAction::Ignore
        );
        Ok(())
    }

    #[test]
    fn parse_sha256_sidecar_accepts_sha256sum_format() -> Result<()> {
        let text = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef  ai-memory-macos-aarch64.tar.gz\n";
        let hash = parse_sha256_sidecar(text, "ai-memory-macos-aarch64.tar.gz")?;
        assert_eq!(
            hash,
            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
        );
        Ok(())
    }

    #[test]
    fn parse_sha256_sidecar_rejects_wrong_filename() -> Result<()> {
        let text =
            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef  other.tar.gz\n";
        match parse_sha256_sidecar(text, "ai-memory-macos-aarch64.tar.gz") {
            Ok(_) => bail!("wrong filename must fail"),
            Err(err) => assert!(err.to_string().contains("expected")),
        }
        Ok(())
    }

    #[test]
    fn parse_sha256_sidecar_rejects_bad_hash() -> Result<()> {
        match parse_sha256_sidecar("not-a-hash  file.tar.gz\n", "file.tar.gz") {
            Ok(_) => bail!("bad hash must fail"),
            Err(err) => assert!(err.to_string().contains("invalid sha256")),
        }
        Ok(())
    }

    #[test]
    fn versions_match_strips_v_prefix() {
        assert!(versions_match("v2.3.2", "2.3.2"));
        assert!(versions_match("2.3.2", "v2.3.2"));
        assert!(!versions_match("v2.3.2", "2.3.1"));
    }

    #[test]
    fn classify_rejects_homebrew_prefix() -> Result<()> {
        let class = classify_install(Path::new("/opt/homebrew/bin/ai-memory"))?;
        assert!(matches!(class, InstallClass::Unsupported(_)));
        Ok(())
    }

    #[test]
    fn classify_rejects_usr_bin() -> Result<()> {
        let class = classify_install(Path::new("/usr/bin/ai-memory"))?;
        assert!(matches!(class, InstallClass::Unsupported(_)));
        Ok(())
    }

    #[test]
    fn homebrew_is_package_managed() {
        let exe = Path::new("/opt/homebrew/bin/ai-memory");
        assert!(package_managed_refusal(exe).is_some());
    }

    #[test]
    fn linuxbrew_is_package_managed() {
        let exe = Path::new("/home/linuxbrew/.linuxbrew/Cellar/ai-memory/2.4.0/bin/ai-memory");
        assert!(package_managed_refusal(exe).is_some());
    }

    /// Focused predicate test for the writability refusal (the composite
    /// `classify_install` cases above would all pass if the refusal branch
    /// were deleted). Skipped when the effective uid ignores directory
    /// permission bits (root CI runners).
    #[cfg(unix)]
    #[test]
    fn classify_refuses_unwritable_parent_directory() -> Result<()> {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir()?;
        let parent = dir.path().join("ro");
        fs::create_dir(&parent)?;
        let exe = parent.join(shipped_binary_name());
        fs::write(&exe, b"fake")?;
        fs::set_permissions(&parent, fs::Permissions::from_mode(0o555))?;
        let probe = parent.join(".root-probe");
        if fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&probe)
            .is_ok()
        {
            let _ = fs::remove_file(&probe);
            eprintln!("skipping: uid ignores directory permissions (root runner)");
            return Ok(());
        }
        let class = classify_install(&exe)?;
        assert!(
            matches!(class, InstallClass::Unsupported(ref reason) if reason.contains("writable")),
            "expected a writability refusal, got {class:?}"
        );
        fs::set_permissions(&parent, fs::Permissions::from_mode(0o755))?;
        Ok(())
    }

    #[test]
    fn classify_accepts_writable_user_prefix() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let exe = dir.path().join(shipped_binary_name());
        fs::write(&exe, b"fake")?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&exe, fs::Permissions::from_mode(0o755))?;
        }
        let class = classify_install(&exe)?;
        // In CI containers (or when AI_MEMORY_IN_CONTAINER is set) Unsupported
        // is correct — do not depend on /.dockerenv alone.
        if ai_memory_wiki::backup::running_in_container() {
            assert!(matches!(class, InstallClass::Unsupported(_)));
        } else {
            assert_eq!(class, InstallClass::Supported);
        }
        Ok(())
    }

    #[test]
    fn validate_rejects_path_traversal() -> Result<()> {
        match validate_release_tar_entry(Path::new("../evil"), tar::EntryType::Regular) {
            Ok(_) => bail!("path traversal must fail"),
            Err(err) => assert!(err.to_string().contains("unsafe"), "{err}"),
        }
        Ok(())
    }

    #[test]
    fn validate_rejects_unexpected_paths() -> Result<()> {
        match validate_release_tar_entry(Path::new("etc/passwd"), tar::EntryType::Regular) {
            Ok(_) => bail!("unexpected path must fail"),
            Err(err) => assert!(err.to_string().contains("unexpected"), "{err}"),
        }
        Ok(())
    }

    #[test]
    fn validate_accepts_dot_slash_prefixed_binary() -> Result<()> {
        assert_eq!(
            validate_release_tar_entry(Path::new("./ai-memory"), tar::EntryType::Regular)?,
            ReleaseEntryAction::Extract
        );
        assert_eq!(
            validate_release_tar_entry(Path::new("./"), tar::EntryType::Directory)?,
            ReleaseEntryAction::Ignore
        );
        Ok(())
    }

    #[test]
    fn release_workflow_support_assets_are_exact_and_ignored() -> Result<()> {
        for directory in RELEASE_SUPPORT_DIRS {
            assert_eq!(
                validate_release_path(Path::new(directory), true)?,
                ReleaseEntryAction::Ignore,
                "support directory {directory}"
            );
        }
        for file in RELEASE_SUPPORT_FILES {
            assert_eq!(
                validate_release_path(Path::new(file), false)?,
                ReleaseEntryAction::Ignore,
                "support file {file}"
            );
        }

        for near_miss in [
            "docs/unshipped.md",
            "packaging/launchd/extra.plist",
            "crates/ai-memory-cli/templates/extra.toml",
        ] {
            match validate_release_path(Path::new(near_miss), false) {
                Ok(_) => bail!("unshipped support path {near_miss} must fail"),
                Err(err) => assert!(err.to_string().contains("unexpected"), "{err}"),
            }
        }
        Ok(())
    }

    #[test]
    fn extracts_archive_built_like_release_yml() -> Result<()> {
        let src = tempfile::tempdir()?;
        fs::write(src.path().join(shipped_binary_name()), b"bin")?;
        fs::create_dir_all(src.path().join("hooks/claude-code"))?;
        fs::write(src.path().join("hooks/claude-code/x.sh"), b"#!/bin/sh")?;
        for directory in [
            "packaging/launchd",
            "crates/ai-memory-cli/templates",
            "docs",
        ] {
            fs::create_dir_all(src.path().join(directory))?;
        }
        for (path, body) in [
            (
                "packaging/launchd/com.github.akitaonrails.ai-memory.plist",
                b"plist".as_slice(),
            ),
            (
                "crates/ai-memory-cli/templates/config.default.toml",
                b"config".as_slice(),
            ),
            ("docs/install.md", b"install".as_slice()),
            ("docs/macos.md", b"macos".as_slice()),
            ("README.md", b"readme".as_slice()),
            ("LICENSE", b"license".as_slice()),
        ] {
            fs::write(src.path().join(path), body)?;
        }
        let out = tempfile::tempdir()?;
        let archive = out.path().join("a.tar.gz");
        // Same invocation as .github/workflows/release.yml. COPYFILE_DISABLE
        // keeps macOS tar from injecting AppleDouble `._*` sidecars that Linux
        // release runners never produce.
        let status = std::process::Command::new("tar")
            .env("COPYFILE_DISABLE", "1")
            .arg("-C")
            .arg(src.path())
            .arg("-czf")
            .arg(&archive)
            .arg(".")
            .status()?;
        assert!(status.success());
        let dest = tempfile::tempdir()?;
        extract_release_archive(
            &fs::read(&archive)?,
            dest.path(),
            "ai-memory-macos-aarch64.tar.gz",
        )?;
        assert!(dest.path().join(shipped_binary_name()).is_file());
        assert!(dest.path().join("hooks/claude-code/x.sh").is_file());
        assert!(!dest.path().join("docs/install.md").exists());
        assert!(!dest.path().join("packaging").exists());
        assert!(!dest.path().join("README.md").exists());
        Ok(())
    }

    #[test]
    fn release_archive_budget_rejects_entry_count_and_expanded_size() -> Result<()> {
        let mut count_budget = ReleaseArchiveBudget::default();
        for _ in 0..MAX_RELEASE_ARCHIVE_ENTRIES {
            count_budget.account(0)?;
        }
        match count_budget.account(0) {
            Ok(()) => bail!("entry count past the cap must fail"),
            Err(err) => assert!(err.to_string().contains("entries"), "{err}"),
        }

        let mut size_budget = ReleaseArchiveBudget::default();
        size_budget.account(MAX_RELEASE_EXPANDED_BYTES)?;
        match size_budget.account(1) {
            Ok(()) => bail!("expanded size past the cap must fail"),
            Err(err) => assert!(err.to_string().contains("expands past"), "{err}"),
        }
        Ok(())
    }

    #[test]
    fn tar_extract_rejects_declared_expansion_past_limit() -> Result<()> {
        let mut header = Header::new_gnu();
        header.set_entry_type(tar::EntryType::Regular);
        header.set_path("ai-memory")?;
        header.set_size(MAX_RELEASE_EXPANDED_BYTES + 1);
        header.set_mode(0o755);
        header.set_cksum();

        let mut tar_bytes = header.as_bytes().to_vec();
        tar_bytes.extend_from_slice(&[0_u8; 1_024]);
        let mut gz_bytes = Vec::new();
        {
            use flate2::Compression;
            use flate2::write::GzEncoder;
            let mut encoder = GzEncoder::new(&mut gz_bytes, Compression::fast());
            encoder.write_all(&tar_bytes)?;
            encoder.finish()?;
        }
        let dest = tempfile::tempdir()?;
        match extract_release_archive(&gz_bytes, dest.path(), "ai-memory-linux-x86_64.tar.gz") {
            Ok(()) => bail!("declared expanded size past the cap must fail"),
            Err(err) => assert!(err.to_string().contains("expands past"), "{err:#}"),
        }
        assert!(!dest.path().join("ai-memory").exists());
        Ok(())
    }

    #[test]
    fn extract_and_verify_round_trip() -> Result<()> {
        let mut tar_bytes = Vec::new();
        {
            let mut builder = tar::Builder::new(&mut tar_bytes);
            let mut header = Header::new_gnu();
            header.set_entry_type(tar::EntryType::Regular);
            header.set_path("ai-memory")?;
            header.set_size(11);
            header.set_mode(0o755);
            header.set_cksum();
            builder.append(&header, &b"hello-world"[..])?;
            builder.finish()?;
        }
        let mut gz_bytes = Vec::new();
        {
            use flate2::Compression;
            use flate2::write::GzEncoder;
            let mut enc = GzEncoder::new(&mut gz_bytes, Compression::fast());
            std::io::Write::write_all(&mut enc, &tar_bytes)?;
            enc.finish()?;
        }
        let hash = sha256_hex(&gz_bytes);
        let sidecar = format!("{hash}  ai-memory-macos-aarch64.tar.gz\n");
        assert_eq!(
            parse_sha256_sidecar(&sidecar, "ai-memory-macos-aarch64.tar.gz")?,
            hash
        );
        let dest = tempfile::tempdir()?;
        extract_release_archive(&gz_bytes, dest.path(), "ai-memory-macos-aarch64.tar.gz")?;
        assert_eq!(fs::read(dest.path().join("ai-memory"))?, b"hello-world");
        Ok(())
    }

    fn build_test_zip(entries: &[(&str, &[u8])]) -> Result<Vec<u8>> {
        let mut cursor = Cursor::new(Vec::new());
        {
            let mut zip = ZipWriter::new(&mut cursor);
            let options =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
            for &(path, body) in entries {
                if path.ends_with('/') {
                    zip.add_directory(path, options)?;
                } else {
                    zip.start_file(path, options)?;
                    zip.write_all(body)?;
                }
            }
            zip.finish()?;
        }
        Ok(cursor.into_inner())
    }

    #[test]
    fn extracts_zip_happy_path_with_hooks() -> Result<()> {
        let bytes = build_test_zip(&[
            ("ai-memory.exe", b"win-bin"),
            ("hooks/", b""),
            ("hooks/claude-code/x.ps1", b"hook"),
            ("crates/", b""),
            ("crates/ai-memory-cli/", b""),
            ("crates/ai-memory-cli/templates/", b""),
            (
                "crates/ai-memory-cli/templates/config.default.toml",
                b"config",
            ),
            ("docs/", b""),
            ("docs/install.md", b"install"),
            ("docs/windows.md", b"windows"),
            ("README.md", b"readme"),
            ("LICENSE", b"license"),
        ])?;
        let dest = tempfile::tempdir()?;
        extract_release_archive(&bytes, dest.path(), "ai-memory-windows-x86_64.zip")?;
        assert_eq!(fs::read(dest.path().join("ai-memory.exe"))?, b"win-bin");
        assert_eq!(
            fs::read(dest.path().join("hooks/claude-code/x.ps1"))?,
            b"hook"
        );
        assert!(!dest.path().join("docs").exists());
        assert!(!dest.path().join("crates").exists());
        assert!(!dest.path().join("README.md").exists());
        Ok(())
    }

    #[test]
    fn zip_extract_rejects_path_traversal() -> Result<()> {
        let bytes = build_test_zip(&[("../evil.exe", b"nope")])?;
        let dest = tempfile::tempdir()?;
        match extract_release_archive(&bytes, dest.path(), "ai-memory-windows-x86_64.zip") {
            Ok(()) => bail!("path traversal must fail"),
            Err(err) => assert!(
                err.to_string().contains("unsafe") || err.to_string().contains("unexpected"),
                "{err}"
            ),
        }
        Ok(())
    }

    #[test]
    fn zip_extract_rejects_inconsistent_local_and_central_names() -> Result<()> {
        let mut bytes = build_test_zip(&[("ai-memory.exe", b"binary")])?;
        let local_name = bytes
            .windows(b"ai-memory.exe".len())
            .position(|window| window == b"ai-memory.exe")
            .expect("local header filename");
        bytes[local_name..local_name + b"ai-memory.exe".len()].copy_from_slice(b"bad-memory.ex");

        let dest = tempfile::tempdir()?;
        let error = extract_release_archive(&bytes, dest.path(), "ai-memory-windows-x86_64.zip")
            .expect_err("dual-header archive must be rejected");
        assert!(error.to_string().contains("validating release zip headers"));
        assert!(!dest.path().join("ai-memory.exe").exists());
        Ok(())
    }

    #[test]
    fn zip_extract_rejects_unexpected_paths() -> Result<()> {
        let bytes = build_test_zip(&[("etc/passwd", b"nope")])?;
        let dest = tempfile::tempdir()?;
        match extract_release_archive(&bytes, dest.path(), "ai-memory-windows-x86_64.zip") {
            Ok(()) => bail!("unexpected path must fail"),
            Err(err) => assert!(err.to_string().contains("unexpected"), "{err}"),
        }
        Ok(())
    }

    #[test]
    fn replace_file_atomic_swaps_contents() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let dest = dir.path().join(shipped_binary_name());
        let src = dir.path().join("fresh");
        fs::write(&dest, b"old")?;
        fs::write(&src, b"new")?;
        replace_file_atomic(&src, &dest)?;
        assert_eq!(fs::read(&dest)?, b"new");
        assert!(!dest.with_extension("new").exists());
        // Windows may leave `.old` while a process still maps it; unit test
        // has no live mapping so it should be gone, but tolerate leftovers.
        let old = dest.with_extension("old");
        if old.exists() {
            assert_eq!(fs::read(&old)?, b"old");
        }
        Ok(())
    }

    /// A scanner holds the running binary when the swap moves it aside; the
    /// swap waits it out. Fails without the retry.
    #[cfg(windows)]
    #[test]
    fn replace_file_atomic_waits_out_a_transient_hold_on_the_running_binary() -> Result<()> {
        use std::os::windows::fs::OpenOptionsExt as _;
        const FILE_SHARE_READ: u32 = 1;

        let dir = tempfile::tempdir()?;
        let dest = dir.path().join(shipped_binary_name());
        let src = dir.path().join("fresh");
        fs::write(&dest, b"old")?;
        fs::write(&src, b"new")?;
        let holder = fs::OpenOptions::new()
            .read(true)
            .share_mode(FILE_SHARE_READ)
            .open(&dest)?;
        assert_eq!(
            fs::rename(&dest, dest.with_extension("probe"))
                .unwrap_err()
                .raw_os_error(),
            Some(32),
            "the hold must be a real sharing violation"
        );
        let release = std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(400));
            drop(holder);
        });

        replace_file_atomic(&src, &dest)?;

        release.join().expect("release thread");
        assert_eq!(fs::read(&dest)?, b"new");
        assert!(!dest.with_extension("new").exists());
        Ok(())
    }

    #[test]
    fn replace_file_atomic_cleans_stale_old_before_swap() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let dest = dir.path().join(shipped_binary_name());
        let src = dir.path().join("fresh");
        let old = dest.with_extension("old");
        fs::write(&dest, b"current")?;
        fs::write(&old, b"stale-old")?;
        fs::write(&src, b"new")?;
        replace_file_atomic(&src, &dest)?;
        assert_eq!(fs::read(&dest)?, b"new");
        Ok(())
    }

    #[test]
    fn replace_dir_atomic_swaps_tree_and_cleans_backup() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let dest = dir.path().join("hooks");
        let src = dir.path().join("fresh-hooks");
        fs::create_dir_all(dest.join("claude-code"))?;
        fs::write(dest.join("claude-code/old.sh"), b"old")?;
        fs::create_dir_all(src.join("claude-code"))?;
        fs::write(src.join("claude-code/new.sh"), b"new")?;

        replace_dir_atomic(&src, &dest)?;

        assert_eq!(fs::read(dest.join("claude-code/new.sh"))?, b"new");
        assert!(!dest.join("claude-code/old.sh").exists());
        assert!(!dir.path().join(".hooks.old").exists());
        assert!(!dir.path().join(".hooks.new").exists());
        Ok(())
    }

    #[test]
    fn release_base_url_prefers_config_override() {
        let mut config = Config::default();
        assert!(release_base_url(&config).contains("github.com/akitaonrails/ai-memory/releases"));
        config.release_base_url = Some(" http://127.0.0.1:9/releases ".into());
        assert_eq!(release_base_url(&config), "http://127.0.0.1:9/releases");
    }

    #[tokio::test]
    async fn resolve_tag_reads_latest_tag_from_non_github_base() -> Result<()> {
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
        let addr = listener.local_addr()?;
        tokio::spawn(async move {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };
            let mut buf = [0_u8; 4096];
            let _ = stream.read(&mut buf).await;
            let body = "v9.9.9";
            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len()
            );
            let _ = stream.write_all(response.as_bytes()).await;
        });

        let fetcher = ReqwestFetcher::new()?;
        let base = format!("http://{addr}/releases");
        let tag = resolve_tag(&fetcher, &base, None).await?;
        assert_eq!(tag, "v9.9.9");
        Ok(())
    }

    #[tokio::test]
    async fn resolve_tag_honors_pinned_version_without_network() -> Result<()> {
        let fetcher = ReqwestFetcher::new()?;
        let tag = resolve_tag(&fetcher, "http://127.0.0.1:1/unused", Some("2.3.2")).await?;
        assert_eq!(tag, "v2.3.2");
        Ok(())
    }

    #[tokio::test]
    async fn get_bytes_rejects_oversized_content_length() -> Result<()> {
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
        let addr = listener.local_addr()?;
        tokio::spawn(async move {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };
            let mut buf = [0_u8; 4096];
            let _ = stream.read(&mut buf).await;
            let response = "HTTP/1.1 200 OK\r\nContent-Length: 999\r\nConnection: close\r\n\r\n";
            let _ = stream.write_all(response.as_bytes()).await;
        });

        let fetcher = ReqwestFetcher::with_max_bytes(64)?;
        match fetcher.get_bytes(&format!("http://{addr}/big")).await {
            Ok(_) => bail!("oversized Content-Length must fail"),
            Err(err) => assert!(
                err.to_string().contains("Content-Length"),
                "unexpected error: {err:#}"
            ),
        }
        Ok(())
    }

    #[tokio::test]
    async fn get_bytes_rejects_stream_past_limit_without_content_length() -> Result<()> {
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
        let addr = listener.local_addr()?;
        tokio::spawn(async move {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };
            let mut buf = [0_u8; 4096];
            let _ = stream.read(&mut buf).await;
            // No Content-Length; body is 80 bytes against a 64-byte cap.
            let body = vec![b'x'; 80];
            let header = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
            let _ = stream.write_all(header.as_bytes()).await;
            let _ = stream.write_all(&body).await;
        });

        let fetcher = ReqwestFetcher::with_max_bytes(64)?;
        match fetcher.get_bytes(&format!("http://{addr}/stream")).await {
            Ok(_) => bail!("stream past limit must fail"),
            Err(err) => assert!(
                err.to_string().contains("exceeded upgrade download limit"),
                "unexpected error: {err:#}"
            ),
        }
        Ok(())
    }

    #[test]
    fn with_max_bytes_rejects_zero() -> Result<()> {
        match ReqwestFetcher::with_max_bytes(0) {
            Ok(_) => bail!("zero cap must fail"),
            Err(err) => assert!(err.to_string().contains("greater than zero")),
        }
        Ok(())
    }

    #[test]
    fn content_length_limit_compare_is_strict() {
        assert!(!content_length_exceeds_limit(64, 64));
        assert!(content_length_exceeds_limit(65, 64));
        assert!(!content_length_exceeds_limit(0, 1));
    }

    /// The claude-code refresh guard: a missing or third-party-only user-level
    /// settings file means the hooks live in a `--scope project` file, and the
    /// refresh must not create a user-level install. A file that exists but
    /// does not parse is not "absent": the re-apply must run and report it.
    #[test]
    fn claude_refresh_skips_only_a_provably_absent_user_level_install() {
        let tmp = tempfile::TempDir::new().unwrap();
        let settings = tmp.path().join("settings.json");
        let absent = |why: &str| {
            assert_eq!(
                claude_user_level_install_absent_at(settings.clone()).as_deref(),
                Some(settings.as_path()),
                "{why}"
            );
        };
        let present = |why: &str| {
            assert_eq!(
                claude_user_level_install_absent_at(settings.clone()),
                None,
                "{why}"
            );
        };
        absent("a missing file holds no install");
        fs::write(
            &settings,
            r#"{"hooks":{"Notification":[{"matcher":"","hooks":[{"type":"command","command":"/usr/bin/n.sh"}]}]}}"#,
        )
        .unwrap();
        absent("a third-party hook is not an ai-memory install");
        fs::write(&settings, "{ not json").unwrap();
        present("an unparsable file must reach install_hooks::run so the error surfaces");
        fs::write(
            &settings,
            r#"{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"AI_MEMORY_HOOK_URL=http://127.0.0.1:49374 /h/.local/share/ai-memory/hooks/claude-code/stop.sh"}]}]}}"#,
        )
        .unwrap();
        present("our hook means a user-level install to refresh");
    }

    /// With only project-scoped installs, the refresh must still re-copy the
    /// scripts those installs point at.
    #[test]
    fn restage_refreshes_the_claude_scripts_without_a_settings_file() {
        let data = tempfile::TempDir::new().unwrap();
        let hooks_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../hooks");
        let staged =
            install_hooks::restage_claude_code_scripts(data.path(), Some(&hooks_dir)).unwrap();
        assert!(staged.starts_with(data.path()), "{staged:?}");
        let scripts = fs::read_dir(&staged)
            .unwrap()
            .filter_map(Result::ok)
            .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "sh"))
            .count();
        assert!(scripts > 0, "no hook scripts staged under {staged:?}");
    }

    #[test]
    fn local_server_url_detects_common_forms() {
        assert!(is_local_server_url("http://127.0.0.1:49374"));
        assert!(is_local_server_url("http://localhost:49374"));
        assert!(is_local_server_url("http://0.0.0.0:49374"));
        assert!(!is_local_server_url("http://192.168.1.10:49374"));
        // A host that merely contains a loopback name is remote.
        assert!(!is_local_server_url("http://localhost.example.com:49374"));
        assert!(!is_local_server_url("http://127.0.0.1.example.com"));
    }

    #[test]
    fn list_staged_agents_keeps_known_and_skips_helpers() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let hooks = dir.path();
        for name in ["claude-code", "cursor", "lib", "_shared", "not-an-agent"] {
            fs::create_dir(hooks.join(name))?;
        }
        fs::write(hooks.join("README.md"), b"ignore files")?;

        let (agents, unknown) = list_staged_agents(hooks)?;
        let names: Vec<_> = agents.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(names, ["claude-code", "cursor"]);
        assert_eq!(unknown, ["not-an-agent"]);
        assert!(
            agents
                .iter()
                .all(|(_, a)| { matches!(a, AgentChoice::ClaudeCode | AgentChoice::Cursor) })
        );
        Ok(())
    }

    #[test]
    fn list_staged_agents_empty_root_returns_empty() -> Result<()> {
        let dir = tempfile::tempdir()?;
        fs::create_dir(dir.path().join("lib"))?;
        let (agents, unknown) = list_staged_agents(dir.path())?;
        assert!(agents.is_empty());
        assert!(unknown.is_empty());
        Ok(())
    }
}