#!/usr/bin/env bash
# ArgosBrain MCP — one-line installer.
#
# Usage:
#   curl -fsSL https://app.argosbrain.com/install | bash
#
# Or pinned to a specific version:
#   curl -fsSL https://app.argosbrain.com/install | bash -s -- --version v0.1.0
#
# With your licence key (saved on this computer, like
# `argosbrain init --no-config --key`):
#   curl -fsSL https://app.argosbrain.com/install | bash -s -- --key <key>
#
# What it does:
#   1. Detects your OS + architecture.
#   2. Downloads the matching release tarball through app.argosbrain.com
#      (macOS Apple Silicon and Linux x86_64; Intel Mac and Linux ARM64
#      from v0.112.0).
#   3. Verifies the ed25519 release signature over checksums.sha256
#      (v0.86.47+ releases; needs OpenSSL 3.0+, otherwise warns) and the
#      SHA-256 checksum. A failed check stops the install.
#   4. Installs to ~/.local/bin (or $ARGOSBRAIN_INSTALL_DIR if set).
#   5. Prints the claude_desktop_config.json snippet to paste.
#
# No sudo, no package manager, no persistent daemon.

# `curl … | sh` runs this under dash on Debian / Ubuntu, which stops at
# `set -o pipefail` with "Illegal option". Say what to run instead.
# (POSIX sh only above this line.)
if [ -z "${BASH_VERSION:-}" ]; then
    echo "The ArgosBrain installer needs bash. Run:" >&2
    echo "  curl -fsSL https://app.argosbrain.com/install | bash" >&2
    exit 1
fi

set -euo pipefail

# ── Release signing key (red-team 2026-10-25, Chain 3) ───────────────────
# release.yml signs the exact bytes of checksums.sha256 with the ArgosBrain
# ed25519 release key and ships the raw 64-byte signature as
# checksums.sha256.sig next to it. checksums.sha256 alone only proves the
# tarball matches a file served from the same place as the tarball; the
# signature proves both came out of the protected release job.
#
# The PEM between the markers below MUST equal keys/release_ed25519.pub.pem
# (CI enforces it: scripts/ci/release-key.sh). Update it ONLY with
# `scripts/ci/release-key.sh embed` — see docs/RELEASE_CHECKLIST.md.
# An empty block makes this installer refuse to install anything.
# BEGIN ARGOSBRAIN RELEASE KEY
RELEASE_PUBKEY_PEM="$(cat <<'ARGOSBRAIN_RELEASE_KEY_EOF'
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAfE7EWdRyUoJEanrznjLWwfLPnG2rifB1fmhMyXvijaA=
-----END PUBLIC KEY-----
ARGOSBRAIN_RELEASE_KEY_EOF
)"
# END ARGOSBRAIN RELEASE KEY
# First release whose checksums.sha256 is signed. Older tags have no .sig
# and install with a warning (checksum-only, as before).
SIGNED_SINCE="v0.86.47"
# ── Platforms ────────────────────────────────────────────────────────────
# Must equal the `target:` list of the build matrix in
# .github/workflows/release.yml (CI: scripts/ci/check-release-targets.sh).
SUPPORTED_TARGETS="aarch64-macos x86_64-linux x86_64-macos aarch64-linux"
# First release with Intel Mac and Linux ARM64 builds. Those two are
# built best-effort: if one fails on release day, that release ships
# without it and this script says so.
NEW_TARGETS_SINCE="v0.112.0"
# The Intel Mac build links Microsoft's ONNX Runtime dylib (shipped in its
# tarball), which needs this macOS or newer. release.yml refuses a dylib
# that needs more (scripts/ci/fetch-onnxruntime-intel.sh).
INTEL_MAC_MIN_MACOS="13.4"
# Four binaries ship in the same tarball:
#   - `argosbrain`          — short human CLI (init, dashboard, status)
#   - `argosbrain-mcp`      — stdio transport the MCP client spawns
#   - `argosbrain-manager`  — supervisor / IPC broker so multiple MCP
#                             clients (e.g. Cursor + Claude Code on the
#                             same laptop) share one in-memory brain
#                             instead of fighting over brain.bin's
#                             exclusive flock. argosbrain-mcp looks for
#                             it next to itself in $INSTALL_DIR; if it's
#                             missing we silently fall through to direct
#                             stdio, which is exactly the bug that bit
#                             v0.9.2 dual-IDE setups.
#   - `argosbrain-embedder` — v0.30.1 standalone embedder daemon. Loads
#                             the ~600 MB ONNX model once and serves
#                             embedding requests over a Unix socket so
#                             multiple managers (one per project) share
#                             a single resident copy of the model
#                             instead of paying ~600 MB per manager.
#                             Opt-in via ARGOSBRAIN_EMBEDDER_SOCKET env
#                             var; absent that variable, managers
#                             fall back to in-process loading exactly
#                             like pre-v0.30.
#   - `argosbrain-dashboard` — v0.34.0 standalone dashboard daemon.
#                             Owns 127.0.0.1:3733 via launchd socket
#                             activation; survives manager idle-shutdown
#                             so the user's browser tab stays alive
#                             across MCP-session lifecycles. Spawned
#                             lazily by launchd; idle-exits after
#                             30 min of no requests, auto-respawns on
#                             next browser hit. Without this binary on
#                             disk, `argosbrain daemon install-plist`
#                             would write a launchd plist pointing at
#                             a missing path — fail-loop on every
#                             browser request. v0.34.3 closed the
#                             packaging gap that left v0.34.0/.1/.2
#                             tarballs without the daemon binary.
#   - `argosbrain-ingester`  — v0.35.0 standalone file-watcher daemon.
#                             Long-lived watcher that survives
#                             manager idle-shutdown so save-and-leave-
#                             it editing keeps the brain fresh.
#                             Reads brain-identities.json + arms a
#                             debounced fsevents watcher per project
#                             root; on debounced events spawns
#                             argosbrain-manager --worker-mode via
#                             the singleton-protected spawn helper.
#                             Soft-fallback gate in supervisor + mcp
#                             main skips their in-process watcher
#                             when this daemon is loaded.
#   - `argosbrain-spawner`   — v0.38.0 wake-on-click dashboard spawner.
#                             Tiny always-on daemon on 127.0.0.1:3732
#                             that forks `argosbrain-dashboard`
#                             processes on demand at user-click time
#                             from app.argosbrain.com. Replaces the
#                             v0.37.x per-project plist model — one
#                             plist serves any number of projects.
#                             Idle-exits child dashboards after 10 min
#                             so steady-state cost stays ~5 MB. Without
#                             this binary on disk, `argosbrain doctor`
#                             would report "BinaryMissing" for the
#                             spawner plist install — v0.38.1 closes
#                             the packaging gap left by v0.38.0 (same
#                             v0.34.3 lesson: every workspace binary the
#                             install path expects MUST be in the cargo
#                             build invocation + dist cp loop + tar
#                             bundle + this BINS list).
# All seven land in $INSTALL_DIR.
BINS="argosbrain argosbrain-mcp argosbrain-manager argosbrain-embedder argosbrain-dashboard argosbrain-ingester argosbrain-spawner"
INSTALL_DIR="${ARGOSBRAIN_INSTALL_DIR:-$HOME/.local/bin}"
VERSION=""
LICENSE_KEY=""
# 1 once `--key` saved the licence (the closing text then skips the
# "activate your licence" box).
LICENSE_SAVED=0

# ── Arg parsing ───────────────────────────────────────────────────────────
while [ $# -gt 0 ]; do
    case "$1" in
        --version)
            VERSION="$2"
            shift 2
            ;;
        --key)
            # v0.117.0 — save the licence on this computer once the
            # binaries are in, like `argosbrain init --no-config --key`.
            [ $# -ge 2 ] && [ -n "$2" ] || { echo "--key needs your licence key" >&2; exit 2; }
            LICENSE_KEY="$2"
            shift 2
            ;;
        --install-dir)
            INSTALL_DIR="$2"
            shift 2
            ;;
        --skip-skills)
            ARGOSBRAIN_SKIP_SKILLS=1
            shift
            ;;
        --global-skills)
            ARGOSBRAIN_GLOBAL_SKILLS=1
            shift
            ;;
        --skip-app)
            ARGOSBRAIN_SKIP_APP=1
            shift
            ;;
        -h|--help)
            cat <<EOF
ArgosBrain MCP installer.

Options:
  --version <tag>       Install a specific release tag (default: latest).
  --key <licence key>   Also save your licence on this computer (the key
                        from https://app.argosbrain.com/dashboard). Then
                        run 'argosbrain init' in each project.
  --install-dir <path>  Install into this directory (default: \$HOME/.local/bin).
  --skip-skills         Don't install the ArgosBrain skill bundle
                        (just the binary).
  --global-skills       Also put the /argos-* skills in ~/.claude/skills
                        (every project). Default: skills are installed per
                        project by 'argosbrain init'; an existing global
                        install is refreshed.
  --skip-app            On an Apple Silicon Mac, don't install or update the
                        ArgosBrain app in ~/Applications.
  -h, --help            Show this message.

Env vars:
  ARGOSBRAIN_INSTALL_DIR  Same as --install-dir.
  ARGOSBRAIN_SKIP_SKILLS  Same as --skip-skills (set to 1).
  ARGOSBRAIN_GLOBAL_SKILLS  Same as --global-skills (set to 1).
  ARGOSBRAIN_SKIP_APP     Same as --skip-app (set to 1).
  ARGOSBRAIN_OPENSSL      OpenSSL 3.x binary used to verify the release
                          signature (default: auto-detect).
EOF
            exit 0
            ;;
        *)
            echo "unknown flag: $1" >&2
            exit 2
            ;;
    esac
done

# ── Utility ──────────────────────────────────────────────────────────────
log()  { printf '\033[1;34m==>\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m⚠\033[0m  %s\n' "$*" >&2; }
die()  { printf '\033[1;31m✗\033[0m  %s\n' "$*" >&2; update_ui_failed; exit 1; }

# ── v0.91.16 — one progress bar on `argosbrain update` ───────────────────
# An update used to scroll ~40 lines of installer log past the user
# ("Installed: …" per binary, curl progress, model checks, the embedder
# plist), burying the one thing worth reading. On an update the log now
# goes to ~/.argosbrain/logs/update.log and the terminal shows one bar.
#   UPDATE_UI=plain   fresh install, `update --verbose`, or no terminal:
#                     the full log, as before.
#   UPDATE_UI=events  `argosbrain update` v0.91.16+ draws the bar for the
#                     whole update: this script writes `progress <pct>
#                     <label>` lines to fd 3, its log to
#                     $ARGOSBRAIN_UPDATE_LOG and warnings to stderr.
#   UPDATE_UI=bar     an older `argosbrain update` runs this script: it
#                     draws the bar itself, keeps warnings for the end and
#                     prints the dashboard panel when that CLI does not.
UPDATE_UI="plain"
UPDATE_LOG=""
UPDATE_NOTES=""
UPDATE_REPORTED=0
CURL_PROGRESS="--progress-bar"
if [ "${ARGOSBRAIN_UPDATE:-}" = "1" ]; then
    case "${ARGOSBRAIN_UPDATE_UI:-}" in
        events) [ -n "${ARGOSBRAIN_UPDATE_LOG:-}" ] && UPDATE_UI="events" ;;
        plain)  : ;;
        *)      [ -t 1 ] && UPDATE_UI="bar" ;;
    esac
fi
case "$UPDATE_UI" in
    events)
        UPDATE_LOG="$ARGOSBRAIN_UPDATE_LOG"
        exec 3>&1 1>>"$UPDATE_LOG"
        CURL_PROGRESS="--silent"
        ;;
    bar)
        # Read before this script replaces it: the CLI running the update.
        OLD_CLI_VERSION="$("${INSTALL_DIR}/argosbrain" --version 2>/dev/null | awk '{print $NF}' || true)"
        mkdir -p "${HOME}/.argosbrain/logs"
        UPDATE_LOG="${HOME}/.argosbrain/logs/update.log"
        UPDATE_NOTES="$(mktemp)"
        exec 3>&1 1>"$UPDATE_LOG" 2>"$UPDATE_NOTES"
        CURL_PROGRESS="--silent"
        ;;
esac

# progress <pct> <label> — move the update bar; a no-op on a plain install.
progress() {
    local pct="$1"
    shift
    case "$UPDATE_UI" in
        events) printf 'progress %s %s\n' "$pct" "$*" >&3 ;;
        bar)    draw_update_bar "$pct" "$*" ;;
    esac
}

draw_update_bar() {
    local pct="$1" label="$2" width=30 fill i=0 bar=""
    fill=$(( pct * width / 100 ))
    while [ "$i" -lt "$width" ]; do
        if [ "$i" -lt "$fill" ]; then bar="${bar}█"; else bar="${bar}░"; fi
        i=$(( i + 1 ))
    done
    printf '\r\033[2K  %s %3s%%  %s' "$bar" "$pct" "$label" >&3
}

# Bar mode only: end the bar line and show what went wrong, once.
update_ui_failed() {
    [ "$UPDATE_UI" = "bar" ] && [ "$UPDATE_REPORTED" = "0" ] || return 0
    UPDATE_REPORTED=1
    printf '\n\n' >&3
    cat "$UPDATE_NOTES" >&3 2>/dev/null || true
    printf '\n  The update stopped. Full log: %s\n' "$UPDATE_LOG" >&3
}

# EXIT trap: drop the temp dir; in bar mode an exit that did not go
# through die() (a failed command under `set -e`) still says so.
on_exit() {
    local rc=$?
    [ -n "${TMPDIR:-}" ] && [ "${TMPDIR_OURS:-0}" = "1" ] && rm -rf "$TMPDIR"
    [ "$rc" -ne 0 ] && update_ui_failed
    [ -n "$UPDATE_NOTES" ] && rm -f "$UPDATE_NOTES"
    return 0
}
trap on_exit EXIT

# The panel `argosbrain update` ends with. Keep the text in sync with
# DASHBOARD_PANEL in the argosbrain CLI source (a test there checks
# it).
print_dashboard_panel() {
    local width=62 rule="" i=0 line
    while [ "$i" -lt $(( width + 2 )) ]; do rule="${rule}─"; i=$(( i + 1 )); done
    printf '\033[1;36m╭%s╮\n' "$rule"
    while IFS= read -r line; do
        printf '│ %-62s │\n' "$line"
    done <<'PANEL'
YOUR DASHBOARD  ->  app.argosbrain.com

Everything ArgosBrain knows about your code, in one place:

  * Code Audit (Pro)        security + quality score, every
                            finding, signed PDF export
  * Code Architecture (Pro) how modules, routes and
                            dependencies connect
  * Secret Guard            every API key your code uses, the
                            leaks Argos stopped, and
                            step-by-step key rotation
  * Done Verification (Pro) whether Claude Code, Codex or
                            Cursor really finished the work
  * Live Impact             what each edit touches, live

Had a dashboard tab open during the update? Close it and open
it again from app.argosbrain.com, so it connects to the
updated Argos.
PANEL
    printf '╰%s╯\033[0m\n' "$rule"
}

require() {
    if ! command -v "$1" >/dev/null 2>&1; then
        die "missing required tool: $1"
    fi
}
require curl
require tar

# version_lt <a> <b> — true when vX.Y.Z <a> is strictly older than <b>.
# Pre-release suffixes (-rc1, …) are ignored: v0.86.47-rc1 counts as
# v0.86.47, i.e. it must be signed too.
version_lt() {
    awk -v a="$1" -v b="$2" '
        function part(s, i,    p) { sub(/^v/, "", s); sub(/-.*/, "", s); split(s, p, "."); return p[i] + 0 }
        BEGIN {
            for (i = 1; i <= 3; i++) {
                if (part(a, i) < part(b, i)) exit 0
                if (part(a, i) > part(b, i)) exit 1
            }
            exit 1
        }'
}

# find_ed25519_openssl — print the first OpenSSL that can do one-shot
# ed25519 (`pkeyutl -rawin`, OpenSSL >= 3.0). Probes by actually
# generating a throwaway key, signing and verifying in a temp dir, so a
# binary that merely accepts the flags is not trusted. macOS
# /usr/bin/openssl is LibreSSL 3.x and fails this probe; Homebrew's
# openssl@3 passes. Order: $ARGOSBRAIN_OPENSSL, Homebrew (Apple Silicon,
# then Intel), then whatever `openssl` is on PATH.
find_ed25519_openssl() {
    local probe c
    probe="$(mktemp -d)"
    for c in "${ARGOSBRAIN_OPENSSL:-}" /opt/homebrew/bin/openssl \
             /usr/local/opt/openssl@3/bin/openssl /opt/homebrew/opt/openssl@3/bin/openssl \
             "$(command -v openssl 2>/dev/null || true)"; do
        [ -n "$c" ] && [ -x "$c" ] || continue
        printf 'argosbrain-probe' > "${probe}/m"
        if "$c" genpkey -algorithm ed25519 -out "${probe}/k.pem" >/dev/null 2>&1 \
            && "$c" pkey -in "${probe}/k.pem" -pubout -out "${probe}/p.pem" >/dev/null 2>&1 \
            && "$c" pkeyutl -sign -rawin -inkey "${probe}/k.pem" -in "${probe}/m" -out "${probe}/s" >/dev/null 2>&1 \
            && "$c" pkeyutl -verify -rawin -pubin -inkey "${probe}/p.pem" -in "${probe}/m" -sigfile "${probe}/s" >/dev/null 2>&1; then
            rm -rf "$probe"
            printf '%s\n' "$c"
            return 0
        fi
        rm -f "${probe}/k.pem" "${probe}/p.pem" "${probe}/s"
    done
    rm -rf "$probe"
    return 1
}

# verify_release_signature <checksums-file> <sig-file>
#   returns 0  signature verified
#   returns 2  no ed25519-capable OpenSSL on this machine (caller warns)
#   dies       malformed or BAD signature — never installs those
verify_release_signature() {
    local sums="$1" sig="$2" ossl sig_len
    sig_len="$(wc -c < "$sig" | tr -d '[:space:]')"
    [ "$sig_len" = "64" ] || die "checksums.sha256.sig is ${sig_len} bytes (expected a 64-byte ed25519 signature) — refusing to install"
    ossl="$(find_ed25519_openssl)" || return 2
    printf '%s\n' "$RELEASE_PUBKEY_PEM" > "${TMPDIR}/release_ed25519.pub.pem"
    if ! "$ossl" pkeyutl -verify -rawin -pubin -inkey "${TMPDIR}/release_ed25519.pub.pem" \
            -in "$sums" -sigfile "$sig" >/dev/null 2>&1; then
        die "release signature verification FAILED for ${VERSION}: checksums.sha256 was not signed by the ArgosBrain release key.
    Refusing to install. Do not retry with another source — report it to contact@argosbrain.com."
    fi
    return 0
}

# ── Install-dir safety (review finding M6) ───────────────────────────────
# The user can pass any string; validate before `mkdir -p` and `mv`, so we
# never touch system directories by accident (e.g. `--install-dir /usr/bin`
# from a curl|sh on a box where /usr/bin is world-writable).
validate_install_dir() {
    local dir="$1"
    if [ -z "$dir" ]; then
        die "--install-dir cannot be empty"
    fi
    case "$dir" in
        *..*)
            die "--install-dir contains '..': $dir"
            ;;
        /|/bin|/boot|/dev|/etc|/lib|/lib64|/proc|/root|/sbin|/sys|/usr|/usr/bin|/usr/sbin|/usr/lib|/usr/lib64|/var)
            die "refusing to install into system path: $dir (use a user-owned directory)"
            ;;
        /bin/*|/sbin/*|/etc/*|/usr/bin/*|/usr/sbin/*|/usr/lib/*|/usr/lib64/*|/lib/*|/lib64/*|/boot/*|/dev/*|/proc/*|/sys/*)
            die "refusing to install under a system path: $dir"
            ;;
    esac
}
validate_install_dir "$INSTALL_DIR"

# ── Detect OS + arch ──────────────────────────────────────────────────────
OS="$(uname -s)"
ARCH="$(uname -m)"

# Stops before any download when no binary is published for this
# machine, instead of failing later on a 404 for the tarball.
no_prebuilt_binary() {
    cat <<EOF >&2

  ArgosBrain has no pre-built binary for $1 yet.

  Pre-built binaries exist for:
    • macOS on Apple Silicon (M1 or newer)
    • macOS on Intel, macOS ${INTEL_MAC_MIN_MACOS} or newer (from ${NEW_TARGETS_SINCE})
    • Linux on x86_64
    • Linux on ARM64 (from ${NEW_TARGETS_SINCE})

${2:+  $2

}  To hear when your platform is added, write to contact@argosbrain.com.

EOF
    exit 1
}

case "$OS" in
    Linux)   OS_ID="linux" ;;
    Darwin)  OS_ID="macos" ;;
    MINGW*|MSYS*|CYGWIN*) no_prebuilt_binary "Windows" \
        "On Windows, run this command inside WSL2 (Ubuntu): the Linux x86_64 build runs there." ;;
    *)       no_prebuilt_binary "$OS" ;;
esac

case "$ARCH" in
    x86_64|amd64)    ARCH_ID="x86_64" ;;
    arm64|aarch64)   ARCH_ID="aarch64" ;;
    *)               no_prebuilt_binary "${OS} on ${ARCH}" ;;
esac

TARGET="${ARCH_ID}-${OS_ID}"

# ── Test mode (scripts/ci/test-install-verify.sh only) ───────────────────
# Reads a fake release from a LOCAL directory (file:// URLs only, so it
# can never point at another server) and may swap in a test release key
# and target. Nothing here is honoured without ARGOSBRAIN_TEST_RELEASES_DIR.
RELEASES_PROXY="https://app.argosbrain.com/releases"
TEST_MODE=0
if [ -n "${ARGOSBRAIN_TEST_RELEASES_DIR:-}" ]; then
    case "$ARGOSBRAIN_TEST_RELEASES_DIR" in
        /*) [ -d "$ARGOSBRAIN_TEST_RELEASES_DIR" ] || die "ARGOSBRAIN_TEST_RELEASES_DIR is not a directory" ;;
        *)  die "ARGOSBRAIN_TEST_RELEASES_DIR must be an absolute path" ;;
    esac
    TEST_MODE=1
    RELEASES_PROXY="file://${ARGOSBRAIN_TEST_RELEASES_DIR}"
    if [ -n "${ARGOSBRAIN_TEST_RELEASE_PUBKEY_FILE:-}" ]; then
        RELEASE_PUBKEY_PEM="$(cat "$ARGOSBRAIN_TEST_RELEASE_PUBKEY_FILE")"
    fi
    [ -n "${ARGOSBRAIN_TEST_TARGET:-}" ] && TARGET="$ARGOSBRAIN_TEST_TARGET"
    warn "TEST MODE: reading releases from ${RELEASES_PROXY}"
fi

progress 2 "Checking this machine"
log "Detected: ${OS} / ${ARCH}  →  ${TARGET}"

# SUPPORTED_TARGETS must equal the release.yml matrix (CI checks it).
case " ${SUPPORTED_TARGETS} " in
    *" ${TARGET} "*) : ;;
    *) no_prebuilt_binary "${OS} on ${ARCH}" ;;
esac

# v0.112.0 — Intel Mac: the build needs macOS ${INTEL_MAC_MIN_MACOS}+ (its
# ONNX Runtime library does); stop here on older systems.
if [ "$TARGET" = "x86_64-macos" ] && [ "$TEST_MODE" = "0" ]; then
    MACOS_VERSION="$(sw_vers -productVersion 2>/dev/null || true)"
    if [ -n "$MACOS_VERSION" ] && version_lt "$MACOS_VERSION" "$INTEL_MAC_MIN_MACOS"; then
        no_prebuilt_binary "Intel Macs on macOS ${MACOS_VERSION}" \
            "The Intel Mac build needs macOS ${INTEL_MAC_MIN_MACOS} or newer — update macOS, then run this again."
    fi
fi
# Upstream publishes no Intel Mac build of scip-ruby after 0.4.7, so Ruby
# projects on Intel Macs use that version (Apple Silicon and Linux get the
# current one). Nothing on our side can build a newer one.
if [ "$TARGET" = "x86_64-macos" ]; then
    log "Note for Ruby projects: on Intel Macs ArgosBrain reads Ruby with scip-ruby 0.4.7,"
    log "  the last version its makers built for Intel Macs. Newer Ruby syntax may be read less precisely."
fi

# ── Resolve version ───────────────────────────────────────────────────────
# We download all artifacts through the argosbrain.com proxy
# (`/releases/<tag>/<filename>`) instead of github.com directly, because
# our release repository is private and its release assets require
# authentication — the proxy holds a read-only token and serves the
# bytes anonymously to end users. (RELEASES_PROXY is set above, next to the test mode.)

if [ -z "$VERSION" ]; then
    log "Resolving latest release"
    LATEST_TAG="$(curl -fsSL "${RELEASES_PROXY}/latest/tag" 2>/dev/null | tr -d '[:space:]' || true)"
    # v0.114.0 — the newest release with a build for THIS machine: the
    # Intel Mac and Linux ARM64 builds are added to a release after the
    # others, and until then the server names the previous release that
    # has one. Its own signed checksums are verified below, as for latest.
    # An older server without this answer → plain latest, as before.
    VERSION="$(curl -fsSL "${RELEASES_PROXY}/latest/tag-${TARGET}" 2>/dev/null | tr -d '[:space:]' || true)"
    if [ -z "$VERSION" ]; then
        VERSION="$LATEST_TAG"
    elif [ -n "$LATEST_TAG" ] && [ "$VERSION" != "$LATEST_TAG" ]; then
        log "The latest release (${LATEST_TAG}) has no build for this computer yet;"
        log "  installing ${VERSION}, the newest release that has one. Run this again later to get ${LATEST_TAG}."
    fi
    [ -n "$VERSION" ] || die "couldn't resolve latest release — pass --version vX.Y.Z"
fi

# Sanity-check: version tags are `vX.Y.Z` (+ optional suffix). Anything
# else — particularly shell metacharacters — should not land in a URL
# we curl. Fail fast.
case "$VERSION" in
    v[0-9]*|[0-9]*) : ;;
    *) die "unexpected version format: $VERSION (expected vX.Y.Z)" ;;
esac
log "Version: ${VERSION}"

# v0.112.0 — Intel Mac and Linux ARM64 builds start at NEW_TARGETS_SINCE
# and are built best-effort (a release can miss one).
BEST_EFFORT_LABEL=""
case "$TARGET" in
    x86_64-macos)  BEST_EFFORT_LABEL="Intel Macs" ;;
    aarch64-linux) BEST_EFFORT_LABEL="Linux on ARM64" ;;
esac
if [ -n "$BEST_EFFORT_LABEL" ] && version_lt "$VERSION" "$NEW_TARGETS_SINCE"; then
    die "ArgosBrain ${VERSION} has no build for ${BEST_EFFORT_LABEL}: they start at ${NEW_TARGETS_SINCE}.
    Run this again without --version (latest), or with --version ${NEW_TARGETS_SINCE} or newer."
fi

# ── Download ──────────────────────────────────────────────────────────────
ASSET="argosbrain-${VERSION}-${TARGET}.tar.gz"
URL="${RELEASES_PROXY}/${VERSION}/${ASSET}"
SUMS_URL="${RELEASES_PROXY}/${VERSION}/checksums.sha256"
SIG_URL="${RELEASES_PROXY}/${VERSION}/checksums.sha256.sig"

TMPDIR="$(mktemp -d)"
TMPDIR_OURS=1   # removed by on_exit

progress 5 "Downloading ${VERSION}"
log "Downloading ${ASSET}"
if ! curl -fSL $CURL_PROGRESS "$URL" -o "${TMPDIR}/${ASSET}"; then
    if [ -n "$BEST_EFFORT_LABEL" ]; then
        die "ArgosBrain ${VERSION} has no build for ${BEST_EFFORT_LABEL} yet — it is added to the release
    after the other builds, or that build did not finish this time.
    Try again later, install an earlier release with --version vX.Y.Z
    (${NEW_TARGETS_SINCE} or newer), or write to contact@argosbrain.com."
    fi
    die "download failed: ${URL}"
fi

progress 35 "Verifying the download"
log "Verifying checksum"
# Fail closed on every branch — a soft-fail here becomes a supply-chain
# hole (attacker drops the sums request while letting the binary through
# and we'd install unverified code). The only opt-out is an explicit
# --skip-checksum flag, which we deliberately do not ship; rebuild from
# source if you need to bypass.
if [ -n "${ARGOSBRAIN_VERIFIED_CHECKSUMS:-}" ] && [ -f "${ARGOSBRAIN_VERIFIED_CHECKSUMS}" ]; then
    # v0.86.47 — `argosbrain update` already verified this release's
    # checksums.sha256 against the release key compiled into the running
    # binary (and this very script against those checksums). Use that
    # exact file; the tarball below is checked against it.
    cp "${ARGOSBRAIN_VERIFIED_CHECKSUMS}" "${TMPDIR}/checksums.sha256"
    log "Release signature verified natively by argosbrain"
else
    if ! curl -fsSL "$SUMS_URL" -o "${TMPDIR}/checksums.sha256"; then
        die "couldn't fetch checksums.sha256 from ${SUMS_URL} — refusing to install unverified binary"
    fi
    # v0.86.47 — the checksums file must carry a valid ed25519 signature
    # from the release key embedded above:
    #   * bad / malformed signature            → abort
    #   * no ed25519-capable OpenSSL here      → warn, continue (checksum only)
    #   * no .sig, release older than SIGNED_SINCE (never signed) → warn, continue
    #   * no .sig, release SIGNED_SINCE or newer → abort
    log "Verifying release signature"
    # An installer published without its key is a packaging bug — fail
    # closed for every version rather than silently skipping verification.
    [ -n "$RELEASE_PUBKEY_PEM" ] || die "this installer has no release signing key embedded (empty ARGOSBRAIN RELEASE KEY block).
        Refusing to install. This is a packaging bug on our side — please
        report it to contact@argosbrain.com."
    if curl -fsSL "$SIG_URL" -o "${TMPDIR}/checksums.sha256.sig"; then
        sig_rc=0
        verify_release_signature "${TMPDIR}/checksums.sha256" "${TMPDIR}/checksums.sha256.sig" || sig_rc=$?
        if [ "$sig_rc" -eq 0 ]; then
            log "Signature OK (ArgosBrain release key)"
        else
            # No ed25519-capable OpenSSL (e.g. stock macOS LibreSSL). A BAD
            # signature never reaches here — verify_release_signature dies.
            warn "release signature not verified: this machine's OpenSSL lacks ed25519 (needs OpenSSL 3.0+)."
            warn "  This install is protected by HTTPS + the sha256 checksum only."
            warn "  To enable verification: brew install openssl@3 (macOS) or your distro's OpenSSL 3 package,"
            warn "  or set ARGOSBRAIN_OPENSSL=/path/to/openssl3. 'argosbrain update' verifies signatures natively."
        fi
    elif version_lt "$VERSION" "$SIGNED_SINCE"; then
        warn "${VERSION} predates signed releases (${SIGNED_SINCE}+): no checksums.sha256.sig, verifying the sha256 checksum only"
    else
        die "couldn't fetch checksums.sha256.sig from ${SIG_URL} — ${VERSION} must be signed; refusing to install unverified binary"
    fi
fi
EXPECTED="$(grep -F "$ASSET" "${TMPDIR}/checksums.sha256" | awk '{print $1}')"
if [ -z "$EXPECTED" ]; then
    die "checksum entry missing for ${ASSET} in checksums.sha256 — refusing to install unverified binary"
fi
if command -v sha256sum >/dev/null 2>&1; then
    ACTUAL="$(sha256sum "${TMPDIR}/${ASSET}" | awk '{print $1}')"
else
    ACTUAL="$(shasum -a 256 "${TMPDIR}/${ASSET}" | awk '{print $1}')"
fi
[ "$EXPECTED" = "$ACTUAL" ] || die "checksum mismatch (expected ${EXPECTED}, got ${ACTUAL})"
log "Checksum OK"
if [ "$TEST_MODE" = "1" ] && [ "${ARGOSBRAIN_TEST_VERIFY_ONLY:-}" = "1" ]; then
    log "TEST MODE: every check passed — stopping before anything is installed"
    exit 0
fi

# ── Extract + install ─────────────────────────────────────────────────────
progress 45 "Unpacking"
log "Extracting"
tar -xzf "${TMPDIR}/${ASSET}" -C "$TMPDIR"

# ── v0.36.10 — delivery-render pipeline extraction ────────────────────────
# The tarball now contains a `delivery-render/` subdirectory with the
# corporate-delivery PDF/Swagger/Redoc render scripts (5 files,
# ~36 KB). Extract to `$HOME/.argosbrain/delivery-render/` — the
# CLI's `cmd_delivery` precedence path #4 finds it there
# automatically. We use the user's home dir (no sudo) so the install
# script stays unprivileged.
if [ -d "${TMPDIR}/delivery-render" ]; then
    DELIVERY_DIR="${HOME}/.argosbrain/delivery-render"
    mkdir -p "${DELIVERY_DIR}"
    cp -R "${TMPDIR}/delivery-render/." "${DELIVERY_DIR}/"
    chmod +x "${DELIVERY_DIR}/render-package.sh" \
             "${DELIVERY_DIR}/html-to-pdf.js" \
             "${DELIVERY_DIR}/render-charts.py" 2>/dev/null || true
    # v0.61.2 — silent install (was: log "Installed: …delivery-render…").
    # Private enterprise pipeline; no user-visible advertisement.
fi

# ── v0.44.0 Lean Launch Phase 3 — split install layout ─────────────────
# Only `argosbrain` (the user CLI) lands on `PATH` via $INSTALL_DIR
# (~/.local/bin/). The 6 daemon binaries — argosbrain-mcp,
# argosbrain-manager, argosbrain-embedder, argosbrain-dashboard,
# argosbrain-ingester, argosbrain-spawner — move into the private
# `~/.argosbrain/libexec/` directory. The user tab-completes ONE
# command ("there is `argosbrain`"); the daemons are plumbing they
# never see, exactly the Tailscale / Ollama model.
#
# v0.44.0+ binaries on disk are resolved by `find_sibling_binary`
# (in the CLI's path helpers) which checks libexec first
# and falls back to `current_exe().parent()` so in-place upgrades
# keep working until the migration cleanup below runs.
CLI_BIN="argosbrain"
DAEMON_BINS="argosbrain-mcp argosbrain-manager argosbrain-embedder argosbrain-dashboard argosbrain-ingester argosbrain-spawner"
LIBEXEC_DIR="${HOME}/.argosbrain/libexec"

# atomic_install <src> <dst>
# v0.29.5 — atomic-replace pattern, parity with argosbrain-site/
# install.sh. `mv` from `${TMPDIR}` (mktemp -d, on macOS lands under
# /var/folders) to a destination under $HOME crosses APFS containers
# in some configs and degrades to copy+unlink, which truncate-rewrites
# the destination file. If any process has the OLD binary mmap'd via
# dyld, that corrupts its backing image and every subsequent exec()
# at the path hangs at `_dyld_start` (kernel UE state). Same-FS cp +
# `mv -f` does a true `rename(2)`: the OLD inode survives for any
# process whose mmap holds it, NEW spawns at the path get the NEW
# inode. Standard "atomic file replace" pattern.
#
# v0.143.0 — the temp name carries this process's id. Two `argosbrain
# update` runs at once (two sessions finishing the same release) shared
# `${dst}.new`: the first renamed it away and the second's `mv` failed
# with "No such file or directory", so a working install was reported
# as failed.
atomic_install() {
    local src="$1"
    local dst="$2"
    local tmp="${dst}.new.$$"
    cp "$src" "$tmp"
    chmod +x "$tmp"
    mv -f "$tmp" "$dst"
}

# ── v0.86.16 — disk-space preflight (split-brain prevention) ──────────
# We're about to write the CLI (~62 MB) + 6 daemon binaries (~80 MB
# each → ~500 MB) under $HOME. Pre-v0.86.16, if the disk filled up
# during the daemon loop below, the first `cp … .new` died with ENOSPC,
# leaving a half-written `.new`, the OLD daemons in place, and — because
# the CLI installs FIRST (just below) and the post-update verify only
# checked the CLI — `argosbrain update` REPORTED SUCCESS while the
# dashboard / MCP daemons silently kept running stale code (split-brain).
# Observed live on a 94%-full disk: every `argosbrain update` died
# identically and silently. Fail loud + early instead of corrupting the
# install. `df -Pk` → POSIX single-line output, portable macOS + Linux;
# `|| true` keeps `set -e` from aborting on a transient du/df hiccup.
NEED_KB="$(du -sk "$TMPDIR"/argosbrain* 2>/dev/null | awk '{s+=$1} END {print s+0}' || true)"
NEED_KB=$(( ${NEED_KB:-0} + ${NEED_KB:-0} / 5 ))   # +20% headroom for the .new transients
AVAIL_KB="$(df -Pk "$HOME" 2>/dev/null | awk 'NR==2 {print $4+0}' || true)"
if [ "${NEED_KB:-0}" -gt 0 ] && [ "${AVAIL_KB:-0}" -gt 0 ] && [ "$AVAIL_KB" -lt "$NEED_KB" ]; then
    die "not enough free disk space to install ArgosBrain safely.
     need  ~$(( NEED_KB / 1024 )) MB free under ${HOME}
     have  ~$(( AVAIL_KB / 1024 )) MB free
   A partial install would leave your background daemons on the OLD
   version while reporting success — refusing to start.
   Free some space and re-run. Biggest reclaimers, usually:
     • Rust build caches:  find ~ -name target -type d -prune   (then cargo clean / rm -rf)
     • old Argos backups:  rm -f ~/.local/bin/*.bak* ~/.argosbrain/libexec/*.bak ~/.argosbrain/libexec/*.new"
fi

# Clean any `.new` left behind by a previously-interrupted install
# (e.g. an earlier ENOSPC). They waste ~80 MB each and would otherwise
# trip the split-brain detector in `verify_install_paths_after_update`.
rm -f "${LIBEXEC_DIR}/"*.new 2>/dev/null || true

# 1. The user CLI lands on PATH.
progress 55 "Installing the new binaries"
mkdir -p "$INSTALL_DIR"
if [ ! -f "${TMPDIR}/${CLI_BIN}" ]; then
    die "tarball missing expected binary: ${CLI_BIN}"
fi
atomic_install "${TMPDIR}/${CLI_BIN}" "${INSTALL_DIR}/${CLI_BIN}"
log "Installed: ${INSTALL_DIR}/${CLI_BIN}"

# 2. The 6 daemons land in the private libexec dir.
mkdir -p "$LIBEXEC_DIR"
for bin in $DAEMON_BINS; do
    if [ ! -f "${TMPDIR}/${bin}" ]; then
        die "tarball missing expected binary: ${bin}"
    fi
    atomic_install "${TMPDIR}/${bin}" "${LIBEXEC_DIR}/${bin}"
    log "Installed: ${LIBEXEC_DIR}/${bin}"
done

# v0.86.16 — post-loop integrity gate. Belt-and-braces with the
# preflight above: if any daemon failed to land (an ENOSPC that slipped
# past the size estimate, a partial write, an interrupted process), fail
# loud NOW. `set -e` already aborts on a hard `cp` failure, but a 0-byte
# survivor would slip through — so re-check every daemon is present and
# non-empty before declaring the install good. Never let `argosbrain
# update` report success on a split-brain install where the CLI is new
# but a daemon is missing or truncated.
for bin in $DAEMON_BINS; do
    if [ ! -s "${LIBEXEC_DIR}/${bin}" ]; then
        die "daemon binary did not install: ${LIBEXEC_DIR}/${bin} (missing or empty).
   The install did not complete — your daemons may still be on the old
   version. If your disk is low on space, free some and re-run
   \`argosbrain update\`."
    fi
done

# v0.112.0 — the Intel Mac tarball carries the ONNX Runtime library its
# binaries load from their own directory (rpath @executable_path): put it
# next to the daemons AND next to the CLI. Other tarballs have none.
ORT_DYLIBS=""
for lib in "${TMPDIR}"/libonnxruntime.*.dylib; do
    [ -f "$lib" ] || continue
    name="$(basename "$lib")"
    atomic_install "$lib" "${LIBEXEC_DIR}/${name}"
    atomic_install "$lib" "${INSTALL_DIR}/${name}"
    ORT_DYLIBS="${ORT_DYLIBS} ${name}"
    log "Installed: ${name} (ONNX Runtime) in ${LIBEXEC_DIR} and ${INSTALL_DIR}"
done

# 3. Migration cleanup: if a previous v0.43.x install left daemons in
#    $INSTALL_DIR alongside the CLI, remove them. The fresh copies
#    above are authoritative; leaving stale daemons on $PATH would
#    let an out-of-date binary win a spawn race.
for bin in $DAEMON_BINS; do
    if [ -f "${INSTALL_DIR}/${bin}" ]; then
        rm -f "${INSTALL_DIR}/${bin}"
        log "Migrated away: removed stale ${INSTALL_DIR}/${bin}"
    fi
done

# v0.44.3 — close the migration trap left by Phase 3.
#
# The rm loop above deletes the OLD daemon binaries from
# `${INSTALL_DIR}/argosbrain-{spawner,ingester,embedder}`. But on a
# v0.43.x machine, launchd has already loaded plists at
# `~/Library/LaunchAgents/com.argosbrain.{spawner,ingester,embedder}.plist`
# whose `<key>ProgramArguments</key>` first-string points at exactly
# those now-deleted paths. After upgrade:
#   - `launchctl list` still reports the labels as loaded (the old
#     process is in RAM, holding its mmap'd inode).
#   - any new spawn (e.g. clicking "Open" on the dashboard) calls
#     `posix_spawn` against the dead `${INSTALL_DIR}` path → ENOENT
#     → "Spawn failed".
#   - `argosbrain doctor`'s self-heal saw `loaded == true` and skipped
#     the install branch, so it never noticed the plist was rotten.
#
# Fix: at install time, walk the three known daemon plists. If a plist
# exists AND its first ProgramArguments string contains `${INSTALL_DIR}/`,
# it's the stale Phase-2 layout — bootout the launchd registration and
# delete the plist. The next `argosbrain doctor` (or `dashboard` / any
# CLI command that calls `try_silent_self_heal`) re-installs a fresh
# plist pointing at `${LIBEXEC_DIR}` via `find_sibling_binary`.
#
# This complements the Rust-side fix in `heal_one_daemon` (which detects
# the trap reactively when doctor runs); doing it here too means the
# user is healed *before* their first post-upgrade spawn attempt, not
# after the inevitable failure.
PLIST_DIR="${HOME}/Library/LaunchAgents"
STALE_LABELS="com.argosbrain.spawner com.argosbrain.ingester com.argosbrain.embedder"
if [ -d "$PLIST_DIR" ]; then
    for label in $STALE_LABELS; do
        plist="${PLIST_DIR}/${label}.plist"
        if [ -f "$plist" ] && grep -q "${INSTALL_DIR}/argosbrain-" "$plist" 2>/dev/null; then
            log "Booting out stale plist: ${label} (referenced removed ${INSTALL_DIR} binary)"
            launchctl bootout "gui/$(id -u)/${label}" 2>/dev/null || true
            rm -f "$plist"
        fi
    done
fi

# v0.44.5 — compat symlinks for ALL 6 daemon binaries.
# v0.44.7 — extended from `argosbrain-mcp` alone to every daemon.
#
# Background. v0.44.0 (Phase 3) moved all daemons out of `${INSTALL_DIR}`
# (~/.local/bin/) into the private `${LIBEXEC_DIR}` (~/.argosbrain/libexec/).
# Three classes of caller still read from `${INSTALL_DIR}`:
#
#   1. **MCP-client configs written by `argosbrain init` BEFORE v0.44.0**
#      — bake an absolute path to `${INSTALL_DIR}/argosbrain-mcp` into
#      ~/.claude.json / ~/.cursor/mcp.json / ~/.codex/config.toml.
#      Without the symlink every spawn fails with ENOENT — silently,
#      since MCP subprocess stderr rarely surfaces to the user.
#   2. **The legacy `~/.argosbrain-bin/` mirror loop below** (v0.30.9):
#      `cp "${INSTALL_DIR}/${bin}" "${LEGACY_GLOBAL_DIR}/…"` for every
#      entry in `$BINS`. Pre-v0.44.7 this `cp` referenced the OLD layout
#      (everything in INSTALL_DIR) and the loop never noticed Phase 3
#      had moved the daemons out — so the loop failed with
#      `cp: …/argosbrain-manager: No such file or directory` on every
#      machine that had `~/.argosbrain-bin/` present, after the FIRST
#      v0.44.x update. The v0.44.7 fix to that loop also reads from
#      libexec for daemons, but the symlinks are the belt for the
#      braces — any other tool / script that expects daemons on PATH
#      keeps working too.
#   3. **Future external integrations** (homebrew bottles, distro
#      packages, `which`-based shell scripts) that assume the
#      pre-v0.44.0 layout. Same answer — symlinks make those keep
#      working without us pre-emptively patching every consumer.
#
# Symlinking restores backward compatibility forever (Tailscale / Ollama
# pattern). New installs land here too; the symlinks are dormant for
# them (their configs go directly to libexec via `find_sibling_binary`).
#
# `argosbrain refresh-mcp-config --quiet` runs at the end of install too
# (see below) — that one updates MCP-config files themselves. The
# symlinks are the safety net for the gap between install and the next
# refresh, and for callers we don't yet auto-update (custom MCP clients,
# hand-edited files, third-party tooling, etc.).
#
# `ln -sfn`:
#   -s   symbolic (not hard) — survives target binary swaps via mv -f
#   -f   force overwrite — replaces stale files / symlinks left by
#        prior install layouts. Idempotent: re-running install is a
#        no-op when the link already points where we want.
#   -n   treat existing symlink-to-directory as a file — defends
#        against the edge case where the target path is somehow a
#        directory (test-fixture mishaps).
for daemon in $DAEMON_BINS; do
    ln -sfn "${LIBEXEC_DIR}/${daemon}" "${INSTALL_DIR}/${daemon}"
done
log "Compat symlinks: ${INSTALL_DIR}/argosbrain-{mcp,manager,dashboard,embedder,ingester,spawner} → ${LIBEXEC_DIR}/"

# v0.44.5 — auto-refresh MCP-client configs to point at the current
# canonical `argosbrain-mcp` path. Future-proofing: when we move the
# binary again (libexec → /opt/argosbrain/, rename, whatever), the
# next `argosbrain update` propagates the path to every config
# (Claude Code, Cursor, Cline, Codex) with zero user action.
#
# Best-effort:
#   - `2>/dev/null` swallows transient errors (HOME unset in CI,
#     missing config dirs, malformed user-edited configs we can't
#     safely patch).
#   - `|| true` so a refresh failure NEVER fails the install.
#   - `--quiet` so a clean install doesn't spam the terminal —
#     errors still surface on stderr.
#   - Skipped entirely on the very first ever install when no
#     argosbrain CLI is yet executable (defensive — should never
#     fire because we just installed the CLI two cp's ago).
if [ -x "${INSTALL_DIR}/argosbrain" ]; then
    "${INSTALL_DIR}/argosbrain" refresh-mcp-config --quiet 2>/dev/null || true
fi

# v0.30.9 — also sync to legacy ~/.argosbrain-bin/ when it exists.
# v0.44.7 — source-path resolution rewritten + tolerant on missing binaries.
#
# The pre-v0.15 global install path was ~/.argosbrain-bin/. Per-project
# install (v0.15+) moved everything to ./.argosbrain/bin/ and ~/.local/
# bin/, but the legacy path stays alive on existing machines because
# the running argosbrain-mcp / manager processes keep the binaries
# mmap'd from there. When `argosbrain update` runs and writes the new
# binary only to ${INSTALL_DIR}, three of the four binaries somehow
# get re-synced to ~/.argosbrain-bin/ via an unrelated mechanism (the
# argosbrain CLI's restart logic), but argosbrain-embedder is missed
# and stays at the version before this update — silently producing
# the wrong embedding precision because the running daemon spawns
# from the legacy path. Discovered live on 2026-05-09 (v0.30.8 ship)
# when v0.30.7 install succeeded but the embedder daemon kept loading
# v0.30.6 weights.
#
# **v0.44.7 fix.** Pre-v0.44.7 this loop read every source from
# `${INSTALL_DIR}/${bin}` — which was correct under the pre-Phase-3
# layout but FAILS under v0.44.0+: the daemons live in `${LIBEXEC_DIR}`,
# `${INSTALL_DIR}/argosbrain-${daemon}` does NOT exist on a fresh
# install, and the `cp` errors out with `No such file or directory`,
# halting the whole installer.
#
# A user reported this hitting on v0.44.1, v0.44.3, and v0.44.4 — the
# pattern was: every new auxiliary daemon added to `$BINS` would break
# the legacy mirror loop on the first user without that daemon already
# mirrored into ~/.local/bin/. v0.44.5 only fixed the symptom for
# `argosbrain-mcp` (one symlink). v0.44.7 fixes the root cause:
#   * CLI (`argosbrain`) is read from `${INSTALL_DIR}` (its home).
#   * Daemons are read from `${LIBEXEC_DIR}` (Phase 3 home).
#   * Any source that turns out to be missing is logged + skipped, not
#     a hard failure — the legacy mirror is a best-effort UX
#     optimisation, not a correctness gate.
LEGACY_GLOBAL_DIR="${HOME}/.argosbrain-bin"
if [ -d "$LEGACY_GLOBAL_DIR" ]; then
    log "Legacy global install at ${LEGACY_GLOBAL_DIR} detected — mirroring binaries"
    for bin in $BINS; do
        # Resolve the canonical source path for this binary. CLI lives
        # in ${INSTALL_DIR}; daemons live in ${LIBEXEC_DIR} (v0.44.0+).
        if [ "$bin" = "argosbrain" ]; then
            src="${INSTALL_DIR}/${bin}"
        else
            src="${LIBEXEC_DIR}/${bin}"
        fi
        if [ ! -f "$src" ]; then
            # Skip rather than fail. The legacy mirror is a UX nicety
            # (running daemons keep working), not a correctness gate
            # (those daemons are still mmap'd from their old inodes
            # until they restart, and the canonical copy in libexec
            # is what new spawns use). One missing binary should never
            # halt the whole install.
            warn "Legacy mirror: skipping ${bin} (source not found at ${src})"
            continue
        fi
        atomic_install "$src" "${LEGACY_GLOBAL_DIR}/${bin}"
        log "  Mirrored: ${LEGACY_GLOBAL_DIR}/${bin}"
    done
    # v0.112.0 — the mirrored Intel Mac binaries need their dylib too.
    for name in $ORT_DYLIBS; do
        atomic_install "${LIBEXEC_DIR}/${name}" "${LEGACY_GLOBAL_DIR}/${name}"
        log "  Mirrored: ${LEGACY_GLOBAL_DIR}/${name}"
    done
fi

# ── Install ArgosBrain skills (v0.42.1 Lean Launch Phase 1) ───────────────
# The LEAN default bundle ships the 7 default skills (v0.115.0) — the six
# reviews (argos-security, -architecture, -testing, -onboarding, -migration,
# -ai-engineering) and argos-doctor — as a
# platform-agnostic tarball alongside the binaries. They land in ~/.claude/skills/ where
# Claude Code auto-discovers them on next launch. Existing user files
# in that directory are preserved — we only write the argos-* subdirs.
#
# docs/LEAN_LAUNCH_PLAN.md §4: a flood of /argos-* commands degrades the
# agent's tool selection — the lean default stays small (5). The full
# ~45-skill catalogue ships as argosbrain-skills-enterprise-<tag>.tar.gz
# and is pulled by the Enterprise unlock path, not this default install.
#
# Set ARGOSBRAIN_SKIP_SKILLS=1 (env or `--skip-skills` flag below) to
# opt out. Failures are non-fatal: the binary install still succeeds
# even if the skills tarball is missing (e.g. older release tags).
#
# v0.86.39 — skills are PROJECT-scoped: `argosbrain init` writes them to
# <project>/.claude/skills/ and `argosbrain refresh-skills` keeps them
# current. Extracting into ~/.claude/skills/ on every install made the
# /argos-* commands appear in every project on the machine, so this
# global copy is now written only on request (`--global-skills` /
# ARGOSBRAIN_GLOBAL_SKILLS=1) or to refresh a global install that
# already holds our skills (an `init --global` setup).
progress 68 "Checking skills"
SKILLS_DIR="${HOME}/.claude/skills"
HAS_GLOBAL_ARGOS_SKILLS=0
if grep -qs '<!-- argosbrain:' "${SKILLS_DIR}"/argos-*/SKILL.md; then
    HAS_GLOBAL_ARGOS_SKILLS=1
fi
if [ "${ARGOSBRAIN_SKIP_SKILLS:-0}" != "1" ] \
    && [ "${ARGOSBRAIN_GLOBAL_SKILLS:-0}" != "1" ] \
    && [ "$HAS_GLOBAL_ARGOS_SKILLS" != "1" ]; then
    log "Skills: installed per project by \`argosbrain init\` (none written to ${SKILLS_DIR})"
    ARGOSBRAIN_SKIP_SKILLS=1
fi
if [ "${ARGOSBRAIN_SKIP_SKILLS:-0}" != "1" ]; then
    SKILLS_ASSET="argosbrain-skills-${VERSION}.tar.gz"
    SKILLS_URL="${RELEASES_PROXY}/${VERSION}/${SKILLS_ASSET}"

    log "Downloading skills bundle (${SKILLS_ASSET})"
    if curl -fSL $CURL_PROGRESS "$SKILLS_URL" -o "${TMPDIR}/${SKILLS_ASSET}" 2>/dev/null; then
        # Verify checksum (same checksums.sha256 covers both binary + skills).
        EXPECTED_SKILLS="$(grep -F "$SKILLS_ASSET" "${TMPDIR}/checksums.sha256" | awk '{print $1}')"
        if [ -n "$EXPECTED_SKILLS" ]; then
            if command -v sha256sum >/dev/null 2>&1; then
                ACTUAL_SKILLS="$(sha256sum "${TMPDIR}/${SKILLS_ASSET}" | awk '{print $1}')"
            else
                ACTUAL_SKILLS="$(shasum -a 256 "${TMPDIR}/${SKILLS_ASSET}" | awk '{print $1}')"
            fi
            if [ "$EXPECTED_SKILLS" = "$ACTUAL_SKILLS" ]; then
                mkdir -p "$SKILLS_DIR"
                tar -xzf "${TMPDIR}/${SKILLS_ASSET}" -C "$SKILLS_DIR"
                SKILL_COUNT="$(find "$SKILLS_DIR" -maxdepth 2 -name SKILL.md -path "*/argos-*" 2>/dev/null | wc -l | tr -d ' ')"
                log "Installed ${SKILL_COUNT} ArgosBrain skills to ${SKILLS_DIR}"
                # v0.116.0 — the lean bundle holds each skill's SKILL.md
                # only; the `steps/` folders are written by the binary
                # (the same files every update refreshes), so a first
                # --global-skills install is complete at once.
                if [ -x "${INSTALL_DIR}/argosbrain" ] \
                    && "${INSTALL_DIR}/argosbrain" refresh-skills >/dev/null 2>&1; then
                    log "Wrote the skills' step files"
                else
                    warn "the skills' step files are written by the next \`argosbrain update\`"
                fi
            else
                warn "skills bundle checksum mismatch — skipping skill install"
            fi
        else
            warn "no checksum entry for skills bundle — skipping (binary installed OK)"
        fi
    else
        warn "skills bundle not available for ${VERSION} — binary installed OK; skills can be added later"
    fi
fi

# ── v0.121.0 — ArgosBrain for Mac (Apple Silicon) ─────────────────────────
# The Mac app (the Supervisor dashboard with a terminal panel) ships as
# argosbrain-app-<tag>-aarch64-macos.zip, signed with the release's
# Developer ID and notarised by Apple. It is installed or updated in
# ~/Applications only when the signed checksums.sha256 lists it, its
# sha256 matches, and its signature is ours; anything else is a warning,
# never a failed install (the command-line tools are already in place).
# `argosbrain app` opens it. Skip with --skip-app / ARGOSBRAIN_SKIP_APP=1.
APP_TEAM_ID="9CVC5F8XJZ"
# v0.121.0 — and for the Intel Mac (argosbrain-app-<tag>-x86_64-macos.zip),
# best effort: a release without it installs the command line only.
if { [ "$TARGET" = "aarch64-macos" ] || [ "$TARGET" = "x86_64-macos" ]; } \
    && [ "${ARGOSBRAIN_SKIP_APP:-0}" != "1" ] && [ "$TEST_MODE" != "1" ]; then
    APP_ASSET="argosbrain-app-${VERSION}-${TARGET}.zip"
    APP_DIR="${HOME}/Applications"
    APP_PATH="${APP_DIR}/ArgosBrain.app"
    EXPECTED_APP="$(awk -v f="$APP_ASSET" '$2 == f || $2 == "*" f { print $1; exit }' "${TMPDIR}/checksums.sha256")"
    if [ -z "$EXPECTED_APP" ]; then
        log "The Mac app is not part of ${VERSION} — skipped"
    elif ! curl -fsSL "${RELEASES_PROXY}/${VERSION}/${APP_ASSET}" -o "${TMPDIR}/${APP_ASSET}" 2>/dev/null; then
        warn "couldn't download the Mac app — the command-line tools are installed; 'argosbrain update' tries again"
    elif [ "$(shasum -a 256 "${TMPDIR}/${APP_ASSET}" | awk '{print $1}')" != "$EXPECTED_APP" ]; then
        warn "the Mac app's checksum does not match — not installed"
    else
        APP_NEW="${APP_DIR}/.ArgosBrain.app.new-$$"
        APP_OLD="${APP_DIR}/.ArgosBrain.app.old-$$"
        rm -rf "$APP_NEW" "$APP_OLD"
        mkdir -p "$APP_NEW"
        if ! ditto -x -k "${TMPDIR}/${APP_ASSET}" "$APP_NEW" 2>/dev/null \
            || [ ! -d "${APP_NEW}/ArgosBrain.app" ]; then
            warn "the Mac app's zip does not open — not installed"
        elif ! codesign --verify --deep --strict "${APP_NEW}/ArgosBrain.app" 2>/dev/null \
            || ! APP_SIG="$(codesign --display --verbose=2 "${APP_NEW}/ArgosBrain.app" 2>&1)" \
            || ! grep -qx "TeamIdentifier=${APP_TEAM_ID}" <<< "$APP_SIG"; then
            warn "the Mac app is not signed by ArgosBrain — not installed"
        else
            # Swap in place: the old app (even one that is open) is moved
            # aside first, so a failed move leaves it where it was.
            if [ -e "$APP_PATH" ]; then
                mv "$APP_PATH" "$APP_OLD" || true
            fi
            if mv "${APP_NEW}/ArgosBrain.app" "$APP_PATH"; then
                rm -rf "$APP_OLD"
                log "Installed the ArgosBrain app in ${APP_DIR} — open it with 'argosbrain app'"
                if pgrep -x ArgosBrain >/dev/null 2>&1; then
                    log "Quit and reopen the ArgosBrain app to use ${VERSION}"
                fi
            else
                [ -e "$APP_OLD" ] && mv "$APP_OLD" "$APP_PATH"
                warn "couldn't put the Mac app in ${APP_DIR} — the command-line tools are installed"
            fi
        fi
        rm -rf "$APP_NEW"
    fi
fi

# ── Jina-Code-v2 quantized models (v0.30.6+) ──────────────────────────────
# v0.30.5 made INT8-quantized embeddings the daemon's default for new
# installs (smaller RAM, faster ingestion, near-zero quality cost on
# argos's structural-first search path). The default code-path looks
# for FP16 weights cached at `~/.cache/argosbrain/jina-quantized/` —
# pre-v0.30.6 the user had to run `scripts/download_jina_quantized.py`
# by hand or the daemon silently fell back to fastembed FP32 (~600 MB
# per manager process). That's a footgun for fresh installs, especially
# the curl-pipe-sh path that doesn't even have the python script
# locally. We now pre-fetch the cache as part of install.sh so every
# fresh box gets the small-RAM default working out of the box.
#
# Two repos × five files each = ~300 MB one-time download.
#
#   embedder:  jinaai/jina-embeddings-v2-base-code  (~150 MB)
#   reranker:  jinaai/jina-reranker-v2-base-multilingual  (~150 MB)
#
# Idempotent: skipped entirely if model.onnx already exists in both
# target dirs. Best-effort: a network failure here is logged but
# doesn't block the install — the daemon will fall back to fastembed
# FP32 with a warning, same as before. Set ARGOSBRAIN_SKIP_QUANTIZED=1
# to bypass entirely (CI runners that don't need embeddings, air-
# gapped boxes that mirror the cache themselves).
QUANTIZED_DIR="${HOME}/.cache/argosbrain/jina-quantized"
EMBEDDER_DIR="${QUANTIZED_DIR}/embedder"
RERANKER_DIR="${QUANTIZED_DIR}/reranker"

# v0.86.45 (red-team 2026-10-25) — every model file is fetched from a
# PINNED commit (never `resolve/main`, which the model owner can move)
# and checked against a sha256 recorded here before it lands under its
# final name. Downloads go to `<dest>.part` and are renamed only after
# verification, so an interrupted fetch is never mistaken for a cached
# file again (the old `[ -s "$dest" ]` check trusted partial files
# forever). An existing cached file is re-hashed and replaced on
# mismatch. Bump a revision → re-hash its five files in the same commit.
EMB_REPO="jinaai/jina-embeddings-v2-base-code"
EMB_REV="516f4baf13dec4ddddda8631e019b5737c8bc250"
RR_REPO="jinaai/jina-reranker-v2-base-multilingual"
RR_REV="9cfeff2df7d40d1b78e75e5e9cebec92a99813c9"

sha256_of() {
    if command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$1" | awk '{print $1}'
    else
        shasum -a 256 "$1" | awk '{print $1}'
    fi
}

# download_hf_file <repo> <revision> <remote-path> <dest> <sha256>
download_hf_file() {
    local repo="$1"
    local rev="$2"
    local remote="$3"
    local dest="$4"
    local want="$5"
    if [ -f "$dest" ]; then
        if [ "$(sha256_of "$dest")" = "$want" ]; then
            return 0
        fi
        warn "  cached ${dest##*/} does not match its pinned sha256 — re-fetching"
        rm -f "$dest"
    fi
    mkdir -p "$(dirname "$dest")"
    local part="${dest}.part"
    rm -f "$part"
    local url="https://huggingface.co/${repo}/resolve/${rev}/${remote}"
    if ! curl -fSL --proto '=https' $CURL_PROGRESS "$url" -o "$part" 2>&1; then
        warn "  failed to fetch ${remote} from ${repo} — daemon will fall back to FP32"
        rm -f "$part"
        return 1
    fi
    if [ "$(sha256_of "$part")" != "$want" ]; then
        warn "  ${remote} from ${repo}@${rev} failed its sha256 check — discarded (daemon will fall back to FP32)"
        rm -f "$part"
        return 1
    fi
    mv -f "$part" "$dest"
    return 0
}

progress 75 "Checking the embedding models"
if [ "${ARGOSBRAIN_SKIP_QUANTIZED:-0}" = "1" ]; then
    echo ""
    echo "→ ARGOSBRAIN_SKIP_QUANTIZED=1 set — skipping quantized model fetch"
else
    echo ""
    echo "→ Verifying / fetching Jina-Code-v2 quantized models (~880 MB on first install)..."
    echo "  Cache: ${QUANTIZED_DIR}/"

    # Embedder — five files. The big one (model.onnx ~320 MB) is the
    # FP16 ONNX export; the rest are tokenizer + config sidecars
    # required by fastembed's UserDefinedEmbeddingModel loader.
    echo "  Embedder (${EMB_REPO}@${EMB_REV})..."
    download_hf_file "${EMB_REPO}" "${EMB_REV}" "onnx/model_fp16.onnx" "${EMBEDDER_DIR}/model.onnx" \
        "1aafc4fcd63d2e6899e88402ff731e7c646c2e435048294a3cbc908a40d45d7c" || true
    download_hf_file "${EMB_REPO}" "${EMB_REV}" "tokenizer.json" "${EMBEDDER_DIR}/tokenizer.json" \
        "b01c78a902aa4facb2f47f95449f48e2f7bbfea5d2472ee2f6ce92323c6f86e5" || true
    download_hf_file "${EMB_REPO}" "${EMB_REV}" "config.json" "${EMBEDDER_DIR}/config.json" \
        "e426aa684c7f9a95c5f020aa855faf93a24f065f5fad0c9e17b124670cabdea6" || true
    download_hf_file "${EMB_REPO}" "${EMB_REV}" "special_tokens_map.json" "${EMBEDDER_DIR}/special_tokens_map.json" \
        "06e405a36dfe4b9604f484f6a1e619af1a7f7d09e34a8555eb0b77b66318067f" || true
    download_hf_file "${EMB_REPO}" "${EMB_REV}" "tokenizer_config.json" "${EMBEDDER_DIR}/tokenizer_config.json" \
        "f477aeb15ff9f78d3c1ddf2361d2b0b8b20cf55220f839f29a37f3a18efddd89" || true

    # Reranker — same five-file shape. Used by the v0.10+ cross-encoder
    # rerank stage when ARGOSBRAIN_RERANKER=1; pre-fetched so the env
    # flip is instant rather than triggering a ~560 MB download mid-
    # query.
    echo "  Reranker (${RR_REPO}@${RR_REV})..."
    download_hf_file "${RR_REPO}" "${RR_REV}" "onnx/model_fp16.onnx" "${RERANKER_DIR}/model.onnx" \
        "4ad94bcc1d7313ec5f76e18de8ffa7469e3f34b76810b8fd7206619b9cde1bc4" || true
    download_hf_file "${RR_REPO}" "${RR_REV}" "tokenizer.json" "${RERANKER_DIR}/tokenizer.json" \
        "3a56def25aa40facc030ea8b0b87f3688e4b3c39eb8b45d5702b3a1300fe2a20" || true
    download_hf_file "${RR_REPO}" "${RR_REV}" "config.json" "${RERANKER_DIR}/config.json" \
        "af16fe07e9b623d5a47b42bde0daba1b6510344212c03363145c51a81e9e4572" || true
    download_hf_file "${RR_REPO}" "${RR_REV}" "special_tokens_map.json" "${RERANKER_DIR}/special_tokens_map.json" \
        "8c785abebea9ae3257b61681b4e6fd8365ceafde980c21970d001e834cf10835" || true
    download_hf_file "${RR_REPO}" "${RR_REV}" "tokenizer_config.json" "${RERANKER_DIR}/tokenizer_config.json" \
        "4bf8eb7ce5367af6f7bcef4bef6fa5945c345ee5a7ecbe6464712a7d96f98015" || true

    if [ -s "${EMBEDDER_DIR}/model.onnx" ]; then
        echo "✓ Quantized models verified — daemon will use INT8 path on next start"
    else
        echo "⚠ Quantized model fetch failed — daemon will fall back to FP32 fastembed"
        echo "   Network issue? Re-run \`argosbrain update\` to retry, or set"
        echo "   ARGOSBRAIN_QUANTIZED=0 in your shell to silence the fallback warning."
    fi
fi

# ── Embedder daemon autostart (v0.30.10+) ─────────────────────────────────
# The embedder daemon (`argosbrain-embedder`) is a per-user singleton
# process that loads the Jina-Code-v2 ONNX model ONCE in memory and
# serves embedding requests over a Unix socket at
# `~/.argosbrain/embedder.sock`. Without it, every argosbrain-manager
# (one per active project — and `argosbrain-manager --worker-mode`
# spawns one PER ingest job too) loads its own ~600 MB copy. On a
# 4-project workflow with concurrent ingest, this cost the testers
# ~6 GB of redundant resident memory (and ballooned to 60+ GB
# displayed in macOS Activity Monitor via MALLOC_LARGE_REUSABLE
# overcounting).
#
# v0.30.0 shipped the daemon BINARY but no autostart wiring — users
# had to manually run `argosbrain-embedder &` or set
# `ARGOSBRAIN_EMBEDDER_SOCKET` for the client to even try the daemon.
# v0.30.10 closes the loop:
#
#   - macOS: drop a per-user LaunchAgent at
#     ~/Library/LaunchAgents/com.argosbrain.embedder.plist with
#     RunAtLoad=true + KeepAlive=true (auto-restart on crash) +
#     ThrottleInterval=30s (don't crashloop the CPU). `launchctl
#     bootstrap` activates it for the current login session.
#
#   - Linux: drop a systemd user unit at
#     ~/.config/systemd/user/argosbrain-embedder.service with
#     Restart=on-failure. `systemctl --user enable --now`
#     activates + autostart-on-login. Note: `loginctl enable-linger`
#     is required for the daemon to keep running while the user is
#     not logged in; we DON'T do that automatically (sudo prompt
#     would be hostile in a curl-pipe-sh path) — documented in
#     ARGOSBRAIN_DAEMON_LINGER for users who need it.
#
# Opt-out: ARGOSBRAIN_SKIP_DAEMON=1 skips both. The client
# transparently falls back to in-process embeddings — same
# behavior as pre-v0.30.10. Use this for CI runners, airgapped
# boxes, or when the user wants in-process explicitly.
progress 88 "Starting the embedder"
if [ "${ARGOSBRAIN_SKIP_DAEMON:-0}" = "1" ]; then
    echo ""
    echo "→ ARGOSBRAIN_SKIP_DAEMON=1 set — skipping embedder daemon autostart."
    echo "  Each argosbrain-mcp / -manager will load its own ONNX model in-process."
elif [ "$(uname)" = "Darwin" ]; then
    PLIST_DIR="${HOME}/Library/LaunchAgents"
    PLIST_PATH="${PLIST_DIR}/com.argosbrain.embedder.plist"
    EMBEDDER_BIN="${INSTALL_DIR}/argosbrain-embedder"
    LOG_DIR="${HOME}/.argosbrain"
    LOG_FILE="${LOG_DIR}/embedder.log"
    SOCKET_PATH="${LOG_DIR}/embedder.sock"

    mkdir -p "$PLIST_DIR" "$LOG_DIR"

    cat > "$PLIST_PATH" <<PLIST_EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.argosbrain.embedder</string>
    <key>ProgramArguments</key>
    <array>
        <string>${EMBEDDER_BIN}</string>
    </array>
    <key>EnvironmentVariables</key>
    <dict>
        <key>HOME</key>
        <string>${HOME}</string>
        <key>RUST_LOG</key>
        <string>info</string>
    </dict>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>ThrottleInterval</key>
    <integer>30</integer>
    <key>StandardOutPath</key>
    <string>${LOG_FILE}</string>
    <key>StandardErrorPath</key>
    <string>${LOG_FILE}</string>
</dict>
</plist>
PLIST_EOF

    echo ""
    echo "→ Embedder daemon: installing launchd plist at ${PLIST_PATH}"

    # `launchctl bootout` of an existing entry first — ignored if
    # not loaded yet. Then `bootstrap` to register, then `kickstart
    # -k` to ensure a fresh process picks up the new binary.
    launchctl bootout "gui/$(id -u)" "$PLIST_PATH" 2>/dev/null || true
    if launchctl bootstrap "gui/$(id -u)" "$PLIST_PATH" 2>/dev/null; then
        # Wait briefly for first cold-load to start writing the
        # socket file (10-60s for ONNX model init; we don't block
        # the install on it, but emit a hint so the user knows
        # what's happening).
        echo "  ✓ Bootstrapped — daemon will start; first cold load takes 10-60s"
        echo "  ✓ Socket: ${SOCKET_PATH}"
        echo "  ✓ Log:    ${LOG_FILE}"
        echo "  → Verify after ~30s with: argosbrain daemon status"
        echo "  → Disable any time with: launchctl bootout gui/\$(id -u) ${PLIST_PATH}"
    else
        warn "launchctl bootstrap failed — daemon plist installed but not active."
        echo "  Manual activation: launchctl bootstrap gui/\$(id -u) ${PLIST_PATH}"
        echo "  Or skip the daemon entirely with ARGOSBRAIN_SKIP_DAEMON=1 next time."
    fi

elif [ "$(uname)" = "Linux" ]; then
    # systemd user unit. Works on every modern systemd-based distro
    # (Ubuntu 16.04+, Debian 9+, Fedora 25+, Arch, etc.). Falls
    # back gracefully if `systemctl` is missing (busybox / Alpine
    # / containers) — daemon stays not-running, client transparently
    # falls back to in-process.
    if command -v systemctl >/dev/null 2>&1; then
        SYSTEMD_DIR="${HOME}/.config/systemd/user"
        UNIT_PATH="${SYSTEMD_DIR}/argosbrain-embedder.service"
        EMBEDDER_BIN="${INSTALL_DIR}/argosbrain-embedder"
        LOG_DIR="${HOME}/.argosbrain"
        SOCKET_PATH="${LOG_DIR}/embedder.sock"

        mkdir -p "$SYSTEMD_DIR" "$LOG_DIR"

        cat > "$UNIT_PATH" <<UNIT_EOF
[Unit]
Description=ArgosBrain embedder daemon (Jina-Code-v2 ONNX model server)
After=default.target

[Service]
Type=simple
ExecStart=${EMBEDDER_BIN}
Environment=RUST_LOG=info
Restart=on-failure
RestartSec=30
StandardOutput=append:${LOG_DIR}/embedder.log
StandardError=append:${LOG_DIR}/embedder.log

[Install]
WantedBy=default.target
UNIT_EOF

        echo ""
        echo "→ Embedder daemon: installing systemd user unit at ${UNIT_PATH}"
        systemctl --user daemon-reload 2>/dev/null || true
        if systemctl --user enable --now argosbrain-embedder 2>/dev/null; then
            echo "  ✓ Enabled + started — first cold load takes 10-60s"
            echo "  ✓ Socket: ${SOCKET_PATH}"
            echo "  → Verify after ~30s with: argosbrain daemon status"
            echo "  → For the daemon to keep running while you're logged out:"
            echo "      sudo loginctl enable-linger \$USER"
            echo "  → Disable any time with: systemctl --user disable --now argosbrain-embedder"
        else
            warn "systemctl --user enable failed — unit file installed but not active."
            echo "  Manual activation: systemctl --user enable --now argosbrain-embedder"
        fi
    else
        echo ""
        echo "→ Embedder daemon: systemctl not available; skipping autostart."
        echo "  Manual: run 'argosbrain daemon start' to launch the daemon yourself."
        echo "  (Cross-init systems like OpenRC, runit, or s6 work too — adapt the unit"
        echo "   file to your init system. The daemon binary is at ${INSTALL_DIR}/argosbrain-embedder.)"
    fi
fi

progress 95 "Checking your PATH"
# ── PATH auto-fix ─────────────────────────────────────────────────────────
# v0.7.1 (B2): users hit "command not found: argosbrain" right after a
# successful install because ~/.local/bin isn't on the default macOS
# zsh PATH. We now auto-append the export to the shell rc file the
# user is actually running, AND warn that the change takes effect
# only in a NEW shell. We never touch the rc file if the path is
# already on PATH or if the rc file doesn't exist (we don't create
# one). Skipped entirely for non-default install dirs the user passed
# explicitly via --install-dir or ARGOSBRAIN_INSTALL_DIR — those are
# considered intentional and the user owns the PATH setup.
case ":$PATH:" in
    *":${INSTALL_DIR}:"*) : ;;  # already on PATH, nothing to do
    *)
        # Stale binary at /usr/local/bin warning — this was the
        # most-reported v0.7.0 install problem. `which argosbrain`
        # would resolve to the OLD copy from a prior cargo install /
        # manual install, shadowing the freshly-installed v0.7.x
        # binary in ~/.local/bin and producing confusing errors.
        if [ -x "/usr/local/bin/argosbrain" ] && [ "${INSTALL_DIR}" != "/usr/local/bin" ]; then
            warn "An OLDER argosbrain exists at /usr/local/bin/argosbrain"
            echo "   It will shadow this fresh install on your \$PATH."
            echo "   To replace it (recommended):"
            echo "     sudo cp ${INSTALL_DIR}/argosbrain /usr/local/bin/argosbrain"
            echo "     sudo cp ${INSTALL_DIR}/argosbrain-mcp /usr/local/bin/argosbrain-mcp"
            echo "     sudo cp ${INSTALL_DIR}/argosbrain-manager /usr/local/bin/argosbrain-manager"
            echo ""
        fi

        # Default install dir (no --install-dir / no env override) →
        # safe to auto-fix the rc file. Custom install dirs we leave
        # alone.
        if [ -z "${ARGOSBRAIN_INSTALL_DIR:-}" ] && [ "${INSTALL_DIR}" = "${HOME}/.local/bin" ]; then
            # Pick the rc file to edit based on the user's shell.
            # Fall back to .profile (always sourced) when in doubt.
            user_shell="$(basename "${SHELL:-/bin/sh}")"
            case "$user_shell" in
                zsh)  rc_file="${HOME}/.zshrc"  ;;
                bash) rc_file="${HOME}/.bashrc" ;;
                fish) rc_file="${HOME}/.config/fish/config.fish" ;;
                *)    rc_file="${HOME}/.profile" ;;
            esac

            if [ -f "$rc_file" ]; then
                # Idempotent: don't append if our marker is already in
                # the file (catches a previous install run).
                marker="# Added by argosbrain installer"
                if grep -qF "$marker" "$rc_file" 2>/dev/null; then
                    log "${INSTALL_DIR} already configured in ${rc_file}"
                else
                    {
                        echo ""
                        echo "$marker"
                        if [ "$user_shell" = "fish" ]; then
                            echo "fish_add_path -gP \"${INSTALL_DIR}\""
                        else
                            echo "export PATH=\"${INSTALL_DIR}:\$PATH\""
                        fi
                    } >> "$rc_file"
                    log "Added ${INSTALL_DIR} to PATH via ${rc_file}"
                    warn "The PATH change takes effect in NEW shells."
                    echo "   Right now, run argosbrain with the full path:"
                    echo "     ${INSTALL_DIR}/argosbrain init --key <your-key>"
                    echo "   Or open a new terminal tab and \`argosbrain\` will work."
                fi
            else
                warn "${INSTALL_DIR} is not on your \$PATH and ${rc_file} doesn't exist"
                echo "   Add this to your shell rc file:"
                echo "     export PATH=\"${INSTALL_DIR}:\$PATH\""
            fi
        else
            # Custom install dir — user is on their own.
            warn "${INSTALL_DIR} is not on your \$PATH"
            echo "   Add this to your shell rc file:"
            echo "     export PATH=\"${INSTALL_DIR}:\$PATH\""
        fi
        ;;
esac

# ── Next steps ────────────────────────────────────────────────────────────
# v0.43.0 Lean Launch Phase 2 — `argosbrain init` is now a single
# command that wires the config, builds the brain, starts the
# dashboard, and prints "ArgosBrain is ready." No more "now run
# ingest, then run dashboard" follow-ups. install.sh just hands off.
mkdir -p "${HOME}/.argosbrain"

# ── v0.117.0 — `--key`: save the licence on this computer ────────────────
# The same step as `argosbrain init --no-config --key <key>` (the binary
# just installed checks the key's signature and writes ~/.argosbrain's
# licence file). It sets up no project and no coding tool. A refused key
# never fails the install: the binaries are in, the key can be added later.
# ARGOSBRAIN_INSTALLER=1 tells `init` that this script prints the next
# step itself.
if [ -n "$LICENSE_KEY" ]; then
    if ARGOSBRAIN_INSTALLER=1 "${INSTALL_DIR}/argosbrain" init --no-config --key "$LICENSE_KEY"; then
        LICENSE_SAVED=1
    else
        warn "Your licence was not saved (see above). ArgosBrain is installed; to add the key later run:"
        echo "     ${INSTALL_DIR}/argosbrain init --no-config --key <your-key>" >&2
    fi
fi
LICENSE_KEY=""

# v0.86.29 — UPDATE path skips the first-install onboarding footer (license
# activation + the `argosbrain init` walkthrough). `argosbrain update` sets
# ARGOSBRAIN_UPDATE=1; a fresh `curl … | bash` never does, so new users still
# get the full guided footer below. An update just needs the one-line "done".
if [ "${ARGOSBRAIN_UPDATE:-}" = "1" ]; then
    printf '\n✓ ArgosBrain %s installed.\n' "${VERSION}"
    progress 100 "Done"
else
# v0.117.0 — the same three steps as the account page: (1) this computer
# (install + licence), (2) `argosbrain init` in each project, (3) restart
# Claude Code, Cursor or Codex.
printf '\n✓ ArgosBrain %s installed.\n' "${VERSION}"
if [ "$LICENSE_SAVED" = "1" ]; then
    printf '✓ Your licence is saved on this computer.\n'
else
cat <<EOF

────────────────────────────────────────────────────────────────
Save your licence on this computer (Pro / Team):

  ${INSTALL_DIR}/argosbrain init --no-config --key <paste-key-here>

Get your key at https://app.argosbrain.com/dashboard.
────────────────────────────────────────────────────────────────
EOF
fi
cat <<EOF

Next: in each project, run \`argosbrain init\`:

  cd ~/code/your-project
  ${INSTALL_DIR}/argosbrain init

It sets ArgosBrain up for Claude Code, Cursor and Codex in that project,
reads the code once and opens the dashboard. Then restart Claude Code,
Cursor or Codex so it starts using ArgosBrain.

Account: https://app.argosbrain.com/dashboard
Help: contact@argosbrain.com
EOF
fi

# ── v0.10.2 — running-MCP detection + graceful restart hint ──────────────
# Newly-installed binaries don't take effect until the running MCPs
# are restarted. Without this hint, users either keep using the OLD
# binary (because their IDE session pinned the spawned child) or get
# stuck behind a stale brain.bin lock from the previous PID. Detect
# active processes and recommend the graceful path.
# v0.91.16 — not on an update: `argosbrain update` says what happens to
# the open sessions itself (they move to the new release on their own
# since v0.91.15), and this block told them to quit their IDE.
if [ "${ARGOSBRAIN_UPDATE:-}" != "1" ] \
    && { pgrep -f argosbrain-mcp >/dev/null 2>&1 || pgrep -f argosbrain-manager >/dev/null 2>&1; }; then
    cat <<EOF

⚠  Detected running argosbrain process(es) using the OLD binary.

   Your installed binary is at ${INSTALL_DIR}/argosbrain-mcp, but the
   currently-running MCP was spawned from the previous version. To
   pick up ${VERSION}, do ONE of these:

     • Recommended: restart Claude Code or Cursor (full quit + reopen).
       The new MCP child process inherits the latest binary cleanly.

     • Power-user path: ${INSTALL_DIR}/argosbrain restart
       Sends SIGTERM to all argosbrain processes; the v0.10 graceful
       shutdown handler flushes each brain to disk before exit. Then
       restart your IDE.

   (Hard \`pkill -9\` is also possible but loses any in-RAM state since
    the last save — only use it if graceful restart times out.)

EOF
fi

# ── v0.91.16 — end of the update bar (bar mode) ──────────────────────────
# The bar is at 100%; what follows is all the user reads: the warnings
# the install hit, then the dashboard panel unless the CLI that runs this
# update prints it (v0.91.14+ does).
if [ "$UPDATE_UI" = "bar" ]; then
    printf '\n' >&3
    if [ -s "$UPDATE_NOTES" ]; then
        printf '\nNotes from the install (full log: %s):\n' "$UPDATE_LOG" >&3
        cat "$UPDATE_NOTES" >&3
    fi
    printf '\n✓ ArgosBrain %s installed.\n' "${VERSION}" >&3
    if [ -z "${OLD_CLI_VERSION:-}" ] || version_lt "$OLD_CLI_VERSION" "0.91.14"; then
        printf '\n' >&3
        print_dashboard_panel >&3
    fi
    printf '\n' >&3
fi
