Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

51.5 KB
Raw Blame
#!/bin/sh
# Copyright 2026 Ix Infrastructure Inc.

# Ix — Standalone Installer
#
# Installs everything needed to run Ix without cloning the repo:
#   1. Node.js (checks / installs / upgrades)
#   2. Docker (checks / prompts)
#   3. Backend (ArangoDB + Memory Layer via Docker)
#   4. ix CLI
#
# Usage:
#   curl -fsSL https://ix-infra.com/install.sh | sh
#
# Options (env vars):
#   IX_VERSION=0.2.0          Override version (default: latest)
#   IX_SKIP_BACKEND=1         Skip Docker backend setup

set -eu

# -- Config --

GITHUB_ORG="ix-infrastructure"
GITHUB_REPO="Ix"
GITHUB_RAW="https://raw.githubusercontent.com/${GITHUB_ORG}/${GITHUB_REPO}/main"

IX_HOME="${IX_HOME:-$HOME/.ix}"
COMPOSE_DIR="$IX_HOME/backend"

HEALTH_URL="http://localhost:8090/v1/health"

NODE_MIN_MAJOR=22

# -- Windows / POSIX docker compose wrapper --
#
case "$(uname -s)" in
  MINGW*|MSYS*|CYGWIN*)
    dc() { MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' docker compose "$@"; }
    ;;
  *)
    dc() { docker compose "$@"; }
    ;;
esac
# -- Helpers --

info()  { printf "  \033[32m[ok]\033[0m %s\n" "$*"; }
warn()  { printf "  \033[33m[!!]\033[0m %s\n" "$*" >&2; }
err()   { printf "  \033[31m[error]\033[0m %s\n" "$*" >&2; exit 1; }
step()  { printf "\n-- %s --\n" "$*"; }

# -- Download helpers (curl or wget) --
#
# _fetch URL         — write response to stdout
# _download URL FILE — write response to FILE

# _location URL     — the Location header URL redirects to, without following it

if command -v curl >/dev/null 2>&1; then
  _fetch()    { curl -fsSL "$1"; }
  _download() { curl -fL --progress-bar "$1" -o "$2"; }
  _location() { curl -fsSI "$1" 2>/dev/null | tr -d '\r' | sed -n 's/^[Ll]ocation:[[:space:]]*//p' | tail -1; }
elif command -v wget >/dev/null 2>&1; then
  _fetch()    { wget -qO- "$1"; }
  _download() { wget --show-progress -qO "$2" "$1" 2>&1 || wget -O "$2" "$1"; }
  _location() { wget -S --spider --max-redirect=0 "$1" 2>&1 | tr -d '\r' | sed -n 's/^[[:space:]]*[Ll]ocation:[[:space:]]*\([^[:space:]]*\).*/\1/p' | tail -1; }
else
  err "curl or wget is required but neither was found.
  Install one first and re-run:
    apt-get install -y curl    # Debian/Ubuntu
    apk add curl               # Alpine
    dnf install -y curl        # Fedora/RHEL"
fi

# Pick a bin dir that is already in PATH and writable
pick_bin_dir() {
  if [ -w "/usr/local/bin" ] || [ -w "/usr/local" ]; then
    echo "/usr/local/bin"
    return
  fi
  mkdir -p "$HOME/.local/bin"
  echo "$HOME/.local/bin"
}

IX_BIN="$(pick_bin_dir)"

ensure_path() {
  # Only needed when using ~/.local/bin
  if [ "$IX_BIN" = "/usr/local/bin" ]; then return; fi

  # Single quotes intentional: $HOME/$PATH must expand at shell startup, not install time
  # shellcheck disable=SC2016
  path_line='export PATH="$HOME/.local/bin:$PATH"'
  added=0

  # Update any rc files that already exist
  for rc in "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile"; do
    [ -f "$rc" ] || continue
    if ! grep -Fq '.local/bin' "$rc" 2>/dev/null; then
      printf '\n# Added by Ix installer\n%s\n' "$path_line" >> "$rc"
    fi
    added=1
  done

  # No rc files found — fall back to ~/.profile (POSIX login shell)
  if [ "$added" = "0" ]; then
    touch "$HOME/.profile"
    if ! grep -Fq '.local/bin' "$HOME/.profile" 2>/dev/null; then
      printf '\n# Added by Ix installer\n%s\n' "$path_line" >> "$HOME/.profile"
    fi
    echo "  Note: ~/.local/bin added to PATH in ~/.profile"
  fi

  echo "  Run this to use ix now (or open a new terminal):"
  echo "    export PATH=\"\$HOME/.local/bin:\$PATH\""
}

# -- Resolve version --

resolve_version() {
  if [ -n "${IX_VERSION:-}" ]; then
    echo "$IX_VERSION"
    return
  fi

  latest=$(_fetch "https://api.github.com/repos/${GITHUB_ORG}/${GITHUB_REPO}/releases/latest" 2>/dev/null \
    | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"v\([^"]*\)".*/\1/p' || true)
  if [ -z "$latest" ]; then
    # Second source: the web redirect from /releases/latest to /releases/tag/v<x>,
    # which works when the API is rate-limited or blocked.
    latest=$(_location "https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/releases/latest" \
      | sed -n 's#.*/releases/tag/v\([^/?]*\)$#\1#p' || true)
  fi
  # Never guess. The old fallback named a version (0.1.0) that was never
  # released, so an unreachable API turned into a 404 after the install had
  # already started changing things.
  if [ -z "$latest" ]; then
    return 1
  fi
  echo "$latest"
}

# version_lt A B — true when release A is older than release B. Compares the
# numeric x.y.z; a pre-release (x.y.z-rc1) sorts before its release.
version_lt() {
  awk -v a="$1" -v b="$2" 'BEGIN {
    split(a, A, "-"); split(b, B, "-"); split(A[1], x, "."); split(B[1], y, ".")
    for (i = 1; i <= 3; i++) { xi = x[i] + 0; yi = y[i] + 0; if (xi < yi) exit 0; if (xi > yi) exit 1 }
    exit !(A[2] != "" && B[2] == "")
  }'
}

# sha256_of FILE — hex digest, with whichever tool this system has.
sha256_of() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}'
  elif command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | awk '{print $1}'
  elif command -v openssl >/dev/null 2>&1; then openssl dgst -sha256 "$1" | awk '{print $NF}'
  else return 1
  fi
}

# verify_checksum FILE URL NAME — check FILE against the release's published
# URL.sha256 (sha256sum format, naming NAME). Fails closed: a missing,
# malformed or mismatching checksum stops the install before anything is
# extracted. Removes $TMP_DIR on failure.
verify_checksum() {
  vc_file=$1; vc_url=$2; vc_name=$3
  vc_sums="$vc_file.sha256"
  if ! _fetch "$vc_url.sha256" > "$vc_sums" 2>/dev/null; then
    rm -rf "$TMP_DIR" || true
    err "No published checksum at $vc_url.sha256. Refusing to install an unverified archive."
  fi
  vc_expected=$(awk 'NF { print tolower($1); exit }' "$vc_sums")
  vc_named=$(awk 'NF { print $2; exit }' "$vc_sums" | sed 's/^[*]//')
  case "$vc_expected" in
    *[!0-9a-f]*|"") vc_expected="" ;;
  esac
  if [ "${#vc_expected}" -ne 64 ] || { [ -n "$vc_named" ] && [ "$(basename "$vc_named")" != "$vc_name" ]; }; then
    rm -rf "$TMP_DIR" || true
    err "The checksum file at $vc_url.sha256 is not a sha256 for $vc_name. Refusing to install."
  fi
  if ! vc_actual=$(sha256_of "$vc_file"); then
    rm -rf "$TMP_DIR" || true
    err "No SHA-256 tool found (sha256sum, shasum or openssl). Install one and re-run."
  fi
  vc_actual=$(printf '%s' "$vc_actual" | tr 'A-F' 'a-f')
  if [ "$vc_actual" != "$vc_expected" ]; then
    rm -rf "$TMP_DIR" || true
    err "Checksum mismatch for $vc_name: expected $vc_expected, got $vc_actual. The download was not installed."
  fi
}

resolve_backend_version() {
  _fetch "https://api.github.com/repos/${GITHUB_ORG}/ix-memory-layer-dist/releases/latest" 2>/dev/null \
    | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"v\([^"]*\)".*/\1/p' || true
}

# resolve_compass_version() was removed with Ix#376: the compass this script
# installs comes from the release tarball, so the latest ix-compass-dist release
# number was never the right thing to stamp it with. Nothing here needs to know
# what dist has published — `ix upgrade` asks that question, at a point where it
# can also tell which series the installed bundle belongs to.

# -- Detect platform --

detect_platform() {
  os="$(uname -s | tr '[:upper:]' '[:lower:]')"
  arch="$(uname -m)"

  case "$os" in
    darwin)
      os="darwin"
      # uname lies under Rosetta — detect real hardware
      real_arm="$(sysctl -n hw.optional.arm64 2>/dev/null || echo 0)"
      if [ "$real_arm" = "1" ]; then
        arch="arm64"
      fi
      ;;
    linux)  os="linux" ;;
    mingw*|msys*|cygwin*) os="windows" ;;
    *)      err "Unsupported OS: $os" ;;
  esac

  case "$arch" in
    x86_64|amd64) arch="amd64" ;;
    arm64|aarch64) arch="arm64" ;;
    *)             err "Unsupported architecture: $arch. Supported: x86_64, arm64" ;;
  esac

  echo "${os}-${arch}"
}

# ==============================================================================
#  MAIN
# ==============================================================================

echo ""
echo "╔══════════════════════════════════════════╗"
echo "║       Ix — Install                ║"
echo "╚══════════════════════════════════════════╝"
echo ""

VERSION=$(resolve_version) || err "Could not find the latest Ix release: GitHub did not answer. Set IX_VERSION=<version> to install a specific release."
PLATFORM=$(detect_platform)
echo "  Version:  $VERSION"
echo "  Platform: $PLATFORM"

# -- Step 0: System prerequisites --

step "0. System prerequisites (git, Homebrew)"

# Homebrew — macOS package manager (used to install Node, Docker, git)
case "$(uname -s)" in
  Darwin)
    if ! command -v brew >/dev/null 2>&1; then
      echo "  Installing Homebrew (macOS package manager)..."
      /bin/bash -c "$(_fetch https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" < /dev/null
      # Add brew to PATH for this session (Apple Silicon vs Intel)
      if [ -x "/opt/homebrew/bin/brew" ]; then
        eval "$(/opt/homebrew/bin/brew shellenv)"
      elif [ -x "/usr/local/bin/brew" ]; then
        eval "$(/usr/local/bin/brew shellenv)"
      fi
      if command -v brew >/dev/null 2>&1; then
        info "Homebrew installed"
      else
        warn "Homebrew installed but not in PATH yet — open a new terminal after install"
      fi
    else
      info "Homebrew is available"
    fi
    ;;
esac

# git — required by ix CLI
if ! command -v git >/dev/null 2>&1; then
  echo "  Installing git..."
  case "$(uname -s)" in
    Darwin)
      if command -v xcode-select >/dev/null 2>&1; then
        echo "  Installing Xcode Command Line Tools (includes git)..."
        echo "  A dialog may appear — click Install and wait."
        xcode-select --install 2>/dev/null || true
        printf "  Waiting for git..."
        i=0
        while [ "$i" -lt 120 ]; do
          if command -v git >/dev/null 2>&1; then break; fi
          printf "."
          sleep 2
          i=$((i + 1))
        done
        echo ""
      fi
      if ! command -v git >/dev/null 2>&1 && command -v brew >/dev/null 2>&1; then
        brew install git < /dev/null
      fi
      ;;
    Linux)
      if command -v apt-get >/dev/null 2>&1; then
        sudo apt-get update -qq < /dev/null && sudo apt-get install -y git < /dev/null
      elif command -v dnf >/dev/null 2>&1; then
        sudo dnf install -y git < /dev/null
      elif command -v yum >/dev/null 2>&1; then
        sudo yum install -y git < /dev/null
      elif command -v apk >/dev/null 2>&1; then
        sudo apk add git < /dev/null
      fi
      ;;
  esac
  if ! command -v git >/dev/null 2>&1; then
    err "git is required. Install it manually: https://git-scm.com/downloads"
  fi
  info "git installed"
else
  info "git is available"
fi

# ripgrep — used by "ix text" for fast codebase search
if ! command -v rg >/dev/null 2>&1; then
  echo "  Installing ripgrep..."
  case "$(uname -s)" in
    Darwin)
      if command -v brew >/dev/null 2>&1; then
        brew install ripgrep < /dev/null 2>/dev/null
      fi
      ;;
    Linux)
      if command -v apt-get >/dev/null 2>&1; then
        sudo apt-get install -y ripgrep < /dev/null 2>/dev/null
      elif command -v dnf >/dev/null 2>&1; then
        sudo dnf install -y ripgrep < /dev/null 2>/dev/null
      elif command -v apk >/dev/null 2>&1; then
        sudo apk add ripgrep < /dev/null 2>/dev/null
      fi
      ;;
  esac
  if command -v rg >/dev/null 2>&1; then
    info "ripgrep installed"
  else
    warn "ripgrep not installed — 'ix text' will not be available"
  fi
else
  info "ripgrep is available"
fi

# -- Step 1: Check / Install Node.js --

step "1. Node.js (runtime)"

node_version_major() {
  node -v 2>/dev/null | sed 's/^v//' | cut -d. -f1
}

install_or_upgrade_node() {
  action="$1"  # "Installing" or "Upgrading"
  case "$(uname -s)" in
    Darwin)
      if command -v brew >/dev/null 2>&1; then
        echo "  ${action} Node.js via Homebrew..."
        if [ "$action" = "Upgrading" ]; then
          brew upgrade node < /dev/null 2>/dev/null || brew install node < /dev/null
        else
          brew install node < /dev/null 2>/dev/null || true
        fi
        # Handle "installed but not linked" — common when a previous version left stale symlinks
        if ! command -v node >/dev/null 2>&1; then
          echo "  Linking Node.js..."
          if ! brew link --overwrite node < /dev/null 2>/dev/null; then
            # Fix ownership on dirs Homebrew needs to symlink into
            for dir in /usr/local/include/node /usr/local/lib/node_modules /usr/local/share/doc/node; do
              if [ -d "$dir" ] && [ ! -w "$dir" ]; then
                sudo chown -R "$(whoami)" "$dir" < /dev/null 2>/dev/null || true
              fi
            done
            brew link --overwrite node < /dev/null 2>/dev/null || true
          fi
        fi
      else
        echo "  ${action} Node.js via official installer..."
        node_pkg=$(mktemp /tmp/node-XXXXXX.pkg)
        node_arch="$(uname -m)"
        node_ver=$(_fetch "https://nodejs.org/dist/index.json" \
          | sed -n 's/.*"version":"v\([^"]*\)".*"lts":[^f].*/\1/p' \
          | head -1 || true)
        if [ -z "$node_ver" ]; then node_ver="22.14.0"; fi
        if [ "$node_arch" = "arm64" ]; then
          _download "https://nodejs.org/dist/v${node_ver}/node-v${node_ver}-darwin-arm64.pkg" "$node_pkg"
        else
          _download "https://nodejs.org/dist/v${node_ver}/node-v${node_ver}-darwin-x64.pkg" "$node_pkg"
        fi
        sudo installer -pkg "$node_pkg" -target / < /dev/null
        rm -f "$node_pkg"
      fi
      ;;
    Linux)
      if command -v apt-get >/dev/null 2>&1; then
        echo "  ${action} Node.js via NodeSource (apt)..."
        _fetch https://deb.nodesource.com/setup_22.x | sudo -E bash -
        sudo apt-get install -y nodejs < /dev/null
      elif command -v dnf >/dev/null 2>&1; then
        echo "  ${action} Node.js via NodeSource (dnf)..."
        _fetch https://rpm.nodesource.com/setup_22.x | sudo bash -
        sudo dnf install -y nodejs < /dev/null
      elif command -v yum >/dev/null 2>&1; then
        echo "  ${action} Node.js via NodeSource (yum)..."
        _fetch https://rpm.nodesource.com/setup_22.x | sudo bash -
        sudo yum install -y nodejs < /dev/null
      elif command -v apk >/dev/null 2>&1; then
        echo "  ${action} Node.js via apk..."
        sudo apk add --update nodejs npm < /dev/null
      else
        err "No supported package manager found (apt, dnf, yum, apk).
  Install Node.js ${NODE_MIN_MAJOR}+ manually, then re-run:
    https://nodejs.org/en/download/"
      fi
      ;;
    MINGW*|MSYS*|CYGWIN*)
      echo ""
      echo "  Node.js ${NODE_MIN_MAJOR}+ is required."
      echo "  Download from: https://nodejs.org/"
      echo ""
      err "Install Node.js and re-run this installer."
      ;;
    *)
      err "Unsupported OS. Install Node.js ${NODE_MIN_MAJOR}+ manually: https://nodejs.org/"
      ;;
  esac
}

if command -v node >/dev/null 2>&1; then
  CURRENT_NODE=$(node_version_major)
  if [ "$CURRENT_NODE" -ge "$NODE_MIN_MAJOR" ]; then
    info "Node.js $(node -v) is installed (>= ${NODE_MIN_MAJOR} required)"
  else
    warn "Node.js $(node -v) is too old (>= ${NODE_MIN_MAJOR} required)"
    install_or_upgrade_node "Upgrading"
    if ! command -v node >/dev/null 2>&1; then
      err "Node.js upgrade failed. Install Node.js ${NODE_MIN_MAJOR}+ manually: https://nodejs.org/"
    fi
    CURRENT_NODE=$(node_version_major)
    if [ "$CURRENT_NODE" -lt "$NODE_MIN_MAJOR" ]; then
      err "Node.js upgrade resulted in $(node -v), still below ${NODE_MIN_MAJOR}. Install manually: https://nodejs.org/"
    fi
    info "Node.js upgraded to $(node -v)"
  fi
else
  install_or_upgrade_node "Installing"
  # Rehash PATH — brew/apt may have just added node
  hash -r 2>/dev/null || true
  if ! command -v node >/dev/null 2>&1; then
    # Try common install locations
    for p in /usr/local/bin/node /opt/homebrew/bin/node; do
      if [ -x "$p" ]; then
        _bindir="$(dirname "$p")"
        export PATH="$_bindir:$PATH"
        break
      fi
    done
  fi
  if ! command -v node >/dev/null 2>&1; then
    err "Node.js installation failed. Install Node.js ${NODE_MIN_MAJOR}+ manually: https://nodejs.org/"
  fi
  info "Node.js $(node -v) installed"
fi

# -- Step 2: Check / Install Docker + Docker Compose --

step "2. Docker + Docker Compose"

install_docker() {
  case "$(uname -s)" in
    Darwin)
      # Kill any lingering Docker processes from a previous install/run
      osascript -e 'quit app "Docker"' 2>/dev/null || true
      pkill -f "Docker Desktop" 2>/dev/null || true
      pkill -f "com.docker" 2>/dev/null || true
      sleep 1

      # Detect real hardware — uname lies under Rosetta (reports x86_64 on ARM)
      real_arch="$(sysctl -n hw.optional.arm64 2>/dev/null || echo 0)"
      if [ "$real_arch" = "1" ]; then
        arch_suffix="arm64"
      else
        arch_suffix="amd64"
      fi

      echo "  Installing Docker Desktop for macOS ($arch_suffix)..."
      echo "  (this downloads ~700MB — may take a few minutes)"
      echo ""

      # Remove any existing Docker binaries from previous installs
      for f in /usr/local/bin/docker /usr/local/bin/docker-compose \
               /usr/local/bin/docker-credential-desktop \
               /usr/local/bin/docker-credential-ecr-login \
               /usr/local/bin/docker-credential-osxkeychain \
               /usr/local/bin/com.docker.cli \
               /usr/local/bin/kubectl.docker /usr/local/bin/hub-tool \
               /usr/local/bin/docker-index /usr/local/bin/hyperkit; do
        if [ -e "$f" ] || [ -L "$f" ]; then
          rm -f "$f" 2>/dev/null || sudo rm -f "$f" 2>/dev/null || true
        fi
      done
      brew uninstall --cask docker 2>/dev/null || true

      dmg=$(mktemp /tmp/docker-XXXXXX.dmg)
      echo "  Downloading Docker Desktop..."
      _download "https://desktop.docker.com/mac/main/${arch_suffix}/Docker.dmg" "$dmg"
      echo "  Mounting installer..."
      hdiutil attach "$dmg" -quiet -nobrowse -mountpoint /Volumes/Docker < /dev/null
      echo "  Copying to /Applications (may require your password)..."
      sudo rm -rf /Applications/Docker.app 2>/dev/null || true
      sudo cp -R /Volumes/Docker/Docker.app /Applications/ < /dev/null &
      CP_PID=$!
      while kill -0 "$CP_PID" 2>/dev/null; do
        printf "."
        sleep 1
      done
      wait "$CP_PID" || true
      echo " done"
      hdiutil detach /Volumes/Docker -quiet
      rm -f "$dmg"
      info "Docker Desktop installed"
      ;;
    Linux)
      echo "  Installing Docker Engine via get.docker.com..."
      # Download to a file instead of piping into `sh`. This installer is
      # normally run as `curl ... | sh`, so commands get `< /dev/null` to stop
      # them consuming the piped installer off stdin. On a *pipe into* `sh`
      # that redirect wins over the pipe: sh read the install script from
      # /dev/null, did nothing, and exited 0 — so Docker was never installed
      # and the failure was silent. (The Homebrew call above is safe: it uses
      # command substitution, not a pipe.)
      # No `.sh` suffix on the template: BusyBox mktemp (Alpine) passes the
      # template straight to mkstemp() and rejects anything not ending in
      # XXXXXX. `sh FILE` does not care about the extension. Handle a mktemp
      # failure explicitly too — under `set -e` it would otherwise abort with
      # just "mktemp: Invalid argument" and no hint at which step died.
      get_docker=$(mktemp /tmp/get-docker-XXXXXX) || err "Could not create a temporary file for the Docker install script.
  Install Docker manually: https://docs.docker.com/engine/install/"
      if ! _download https://get.docker.com "$get_docker"; then
        rm -f "$get_docker"
        err "Could not download the Docker install script from get.docker.com.
  Install Docker manually: https://docs.docker.com/engine/install/"
      fi
      if ! sh "$get_docker" < /dev/null; then
        rm -f "$get_docker"
        err "Docker Engine install failed.
  Install Docker manually: https://docs.docker.com/engine/install/"
      fi
      rm -f "$get_docker"
      if ! id -nG "$USER" 2>/dev/null | grep -qw docker; then
        echo "  Adding $USER to the docker group..."
        sudo usermod -aG docker "$USER" < /dev/null 2>/dev/null || true
      fi
      if command -v systemctl >/dev/null 2>&1; then
        sudo systemctl start docker < /dev/null 2>/dev/null || true
        sudo systemctl enable docker < /dev/null 2>/dev/null || true
      fi
      if ! docker compose version >/dev/null 2>&1; then
        echo "  Installing Docker Compose plugin..."
        compose_arch="x86_64"
        if [ "$(uname -m)" = "aarch64" ]; then compose_arch="aarch64"; fi
        compose_url="https://github.com/docker/compose/releases/latest/download/docker-compose-linux-${compose_arch}"
        if ! sudo mkdir -p /usr/local/lib/docker/cli-plugins; then
          err "Could not create /usr/local/lib/docker/cli-plugins.
  Install Docker Compose manually: https://docs.docker.com/compose/install/linux/"
        fi
        # `_download` is a shell function, so it cannot be run through sudo:
        # sudo execs a program and functions do not survive the exec, so this
        # died with "sudo: _download: command not found". Fetch as the current
        # user, then place the binary with sudo.
        compose_bin=$(mktemp /tmp/docker-compose-XXXXXX) || err "Could not create a temporary file for the Docker Compose plugin.
  Install it manually: https://docs.docker.com/compose/install/linux/"
        if ! _download "$compose_url" "$compose_bin"; then
          rm -f "$compose_bin"
          err "Could not download the Docker Compose plugin.
  Install it manually: https://docs.docker.com/compose/install/linux/"
        fi
        if ! sudo install -m 0755 "$compose_bin" /usr/local/lib/docker/cli-plugins/docker-compose; then
          rm -f "$compose_bin"
          err "Could not install the Docker Compose plugin.
  Install it manually: https://docs.docker.com/compose/install/linux/"
        fi
        rm -f "$compose_bin"
      fi
      ;;
    MINGW*|MSYS*|CYGWIN*)
      echo ""
      echo "  Docker Desktop is required on Windows."
      echo "  Download and install from:"
      echo "    https://docs.docker.com/desktop/install/windows-install/"
      echo ""
      echo "  After installing, restart your terminal and re-run this installer."
      echo ""
      echo "  To install the CLI only (no backend):"
      echo "    IX_SKIP_BACKEND=1 sh install.sh"
      err "Automatic Docker install is not supported on Windows."
      ;;
    *)
      err "Unsupported OS. Install Docker manually: https://docs.docker.com/engine/install/"
      ;;
  esac
}

wait_for_docker_daemon() {
  max_wait="$1"
  printf "  Waiting for Docker daemon..."
  i=0
  while [ "$i" -lt "$max_wait" ]; do
    if docker info < /dev/null >/dev/null 2>&1; then
      echo ""
      return 0
    fi
    printf "."
    sleep 2
    i=$((i + 1))
  done
  echo ""
  return 1
}

start_docker_daemon() {
  case "$(uname -s)" in
    Darwin)
      if [ -d "/Applications/Docker.app" ]; then
        echo "  Starting Docker Desktop..."
        open -g -a Docker
        osascript -e 'tell application "Docker" to activate' 2>/dev/null || true
        if ! wait_for_docker_daemon 15; then
          echo ""
          echo "  ┌─────────────────────────────────────────────────────────────┐"
          echo "  │  Docker Desktop needs you to complete setup in its window.  │"
          echo "  │                                                             │"
          echo "  │  1. Accept the Docker Desktop license agreement             │"
          echo "  │  2. Skip or complete sign-in (sign-in is optional)          │"
          echo "  │  3. Wait for the engine to finish starting                  │"
          echo "  │     (whale icon in menu bar stops animating)                │"
          echo "  │                                                             │"
          echo "  │  This installer will continue automatically once ready.     │"
          echo "  └─────────────────────────────────────────────────────────────┘"
          echo ""
          if ! wait_for_docker_daemon 150; then
            return 1
          fi
        fi
      fi
      ;;
    Linux)
      if command -v systemctl >/dev/null 2>&1; then
        echo "  Starting Docker daemon..."
        sudo systemctl start docker < /dev/null 2>/dev/null || true
        sleep 2
      fi
      if ! docker info < /dev/null >/dev/null 2>&1; then
        if sudo docker info < /dev/null >/dev/null 2>&1; then
          echo "  Docker requires sudo (group not yet active). Using sudo for this session."
          dc() { sudo docker compose "$@"; }
        fi
      fi
      ;;
  esac
}

if [ "${IX_SKIP_BACKEND:-}" = "1" ]; then
  echo "  (skipped via IX_SKIP_BACKEND=1)"
else
  # Find docker binary by absolute path — command -v breaks in piped sh
  find_docker() {
    for p in /usr/local/bin/docker /opt/homebrew/bin/docker /usr/bin/docker; do
      if [ -x "$p" ]; then echo "$p"; return; fi
    done
  }

  DOCKER_BIN="$(find_docker)"

  # Already installed and running? Skip everything.
  if [ -n "$DOCKER_BIN" ] && "$DOCKER_BIN" info < /dev/null >/dev/null 2>&1; then
    info "Docker is ready"
    export PATH="/usr/local/bin:$PATH"
    dc() { "$DOCKER_BIN" compose "$@"; }

  else
    # Install if binary doesn't exist at all
    if [ -z "$DOCKER_BIN" ] && ! [ -d "/Applications/Docker.app" ]; then
      install_docker
      DOCKER_BIN="$(find_docker)"
    fi

    # macOS: launch Docker Desktop and wait for daemon
    case "$(uname -s)" in
      Darwin)
        if [ -d "/Applications/Docker.app" ]; then
          # Docker Desktop installed but daemon not running — just start it
          echo "  Starting Docker Desktop..."
          open -a Docker
          osascript -e 'tell application "Docker" to activate' 2>/dev/null || true

          printf "  Waiting for Docker to be ready..."
          i=0
          ready=0
          while [ "$i" -lt 60 ]; do
            DOCKER_BIN="$(find_docker)"
            if [ -n "$DOCKER_BIN" ] && "$DOCKER_BIN" info < /dev/null >/dev/null 2>&1; then
              ready=1; break
            fi
            printf "."; sleep 2; i=$((i + 1))
          done
          echo ""

          # Only show license prompt if still not ready after 2 minutes
          if [ "$ready" = "0" ]; then
            osascript -e 'tell application "Docker" to activate' 2>/dev/null || true
            echo ""
            echo "  ┌─────────────────────────────────────────────────────────────┐"
            echo "  │  Docker Desktop needs you to complete setup in its window:  │"
            echo "  │                                                             │"
            echo "  │  1. Accept the license agreement (if shown)                 │"
            echo "  │  2. Skip sign-in (or sign in — it is optional)             │"
            echo "  │  3. Wait for the engine to start                            │"
            echo "  │                                                             │"
            echo "  │  This installer will continue automatically.                │"
            echo "  └─────────────────────────────────────────────────────────────┘"
            echo ""
            printf "  Waiting..."
            while [ "$i" -lt 180 ]; do
              DOCKER_BIN="$(find_docker)"
              if [ -n "$DOCKER_BIN" ] && "$DOCKER_BIN" info < /dev/null >/dev/null 2>&1; then
                ready=1; break
              fi
              printf "."; sleep 2; i=$((i + 1))
            done
            echo ""
          fi

          # Wire up docker for rest of script
          DOCKER_BIN="$(find_docker)"
          if [ -n "$DOCKER_BIN" ]; then
            export PATH="/usr/local/bin:$PATH"
            dc() { "$DOCKER_BIN" compose "$@"; }
          fi
        fi
        ;;
    Linux)
      if [ -n "$DOCKER_BIN" ] && ! "$DOCKER_BIN" info < /dev/null >/dev/null 2>&1; then
        if command -v systemctl >/dev/null 2>&1; then
          echo "  Starting Docker daemon..."
          sudo systemctl start docker < /dev/null 2>/dev/null || true
          sleep 2
        fi
        if ! "$DOCKER_BIN" info < /dev/null >/dev/null 2>&1; then
          if sudo "$DOCKER_BIN" info < /dev/null >/dev/null 2>&1; then
            echo "  Docker requires sudo (group not yet active). Using sudo for this session."
            dc() { sudo "$DOCKER_BIN" compose "$@"; }
          fi
        fi
      fi
      ;;
    MINGW*|MSYS*|CYGWIN*)
      # Windows: docker should be in PATH after Docker Desktop install
      DOCKER_BIN="$(find_docker)"
      if [ -z "$DOCKER_BIN" ] && command -v docker >/dev/null 2>&1; then
        DOCKER_BIN="docker"
      fi
      ;;
    esac

    # Final check
    DOCKER_BIN="$(find_docker)"
    if [ -z "$DOCKER_BIN" ]; then
      err "Docker not found. Restart your terminal and re-run this installer."
    fi
    if ! "$DOCKER_BIN" info < /dev/null >/dev/null 2>&1; then
      err "Docker is not running. Start Docker Desktop and re-run this installer."
    fi
    info "Docker is ready"

    if ! "$DOCKER_BIN" compose version >/dev/null 2>&1; then
      err "Docker Compose v2 is required. Update Docker or install the compose plugin."
    fi
    info "Docker Compose $("$DOCKER_BIN" compose version --short 2>/dev/null || echo 'v2') is available"
  fi
fi

# -- Step 3: Start Backend --

step "3. Backend (ArangoDB + Memory Layer)"

# ArangoDB publishes no host port, so ask Compose for its container's health.
# No compose file or no arangodb container means some other stack serves the
# backend: judge it by the memory layer's health alone, which reports 503
# while it cannot reach its database.
arango_ok() {
  [ -f "$COMPOSE_DIR/docker-compose.yml" ] || return 0
  _arango_health=$(dc -f "$COMPOSE_DIR/docker-compose.yml" ps --format '{{.Health}}' arangodb < /dev/null 2>/dev/null) || return 0
  [ -z "$_arango_health" ] || [ "$_arango_health" = "healthy" ]
}

if [ "${IX_SKIP_BACKEND:-}" = "1" ]; then
  echo "  (skipped via IX_SKIP_BACKEND=1)"
else
  if _fetch "$HEALTH_URL" >/dev/null 2>&1 && arango_ok; then
    info "Backend is already running and healthy"
  else
    if command -v lsof >/dev/null 2>&1; then
      stale_pid=$(lsof -ti :8090 2>/dev/null || true)
      if [ -n "$stale_pid" ]; then
        stale_cmd=$(ps -p "$stale_pid" -o comm= 2>/dev/null || true)
        if [ "$stale_cmd" != "com.docker.ba" ] && [ "$stale_cmd" != "docker" ]; then
          warn "Killing stale process on port 8090 (PID $stale_pid: $stale_cmd)"
          kill "$stale_pid" 2>/dev/null || true
          sleep 1
        fi
      fi
    fi

    mkdir -p "$COMPOSE_DIR"

    _download "${GITHUB_RAW}/docker-compose.standalone.yml" "$COMPOSE_DIR/docker-compose.yml"
    info "Downloaded docker-compose.yml"

    # Pull images first so we catch rate limits / auth errors clearly
    echo "  Pulling Docker images (this may take a few minutes on first run)..."
    PULL_LOG=$(mktemp /tmp/ix-pull-XXXXXX) || err "Could not create a temporary file for the image pull log."
    dc -f "$COMPOSE_DIR/docker-compose.yml" pull < /dev/null >"$PULL_LOG" 2>&1 &
    PULL_PID=$!
    while kill -0 "$PULL_PID" 2>/dev/null; do
      printf "."
      sleep 2
    done
    echo ""
    if ! wait "$PULL_PID"; then
      echo ""
      # Match 429 only where it is HTTP status text. A bare "429" also matches
      # ordinary pull progress ("429.4MB/1.02GB") and hex layer IDs
      # ("8f4291f2b1a0"), either of which would route a GHCR denial into the
      # Docker Hub branch below and hand back exactly the wrong fix -- the bug
      # this change exists to fix. Both spellings are needed: Docker Hub's edge
      # limiter can surface as "error parsing HTTP 429 response body: ... Too
      # Many Requests (HAP429)", carrying neither "toomanyrequests" nor a
      # spaceless "429 Too Many Requests".
      if grep -qi "toomanyrequests\|rate limit\|429 too many requests\|http 429" "$PULL_LOG" 2>/dev/null; then
        echo "  ┌─────────────────────────────────────────────────────────────┐"
        echo "  │  Docker Hub rate-limited the pull.                          │"
        echo "  │                                                             │"
        echo "  │  Docker Hub limits unauthenticated pulls to 100 per 6hrs.   │"
        echo "  │  Sign in to Docker Hub (free account) to raise the limit:   │"
        echo "  │                                                             │"
        echo "  │    docker login                                             │"
        echo "  │                                                             │"
        echo "  │  Then re-run this installer.                                │"
        echo "  └─────────────────────────────────────────────────────────────┘"
      elif grep -qi "denied\|unauthorized" "$PULL_LOG" 2>/dev/null; then
        echo "  ┌─────────────────────────────────────────────────────────────┐"
        echo "  │  Docker was denied access to the Ix backend image.          │"
        echo "  │                                                             │"
        echo "  │  This image is public and needs no login. This error        │"
        echo "  │  usually means Docker is sending stale ghcr.io              │"
        echo "  │  credentials from an earlier login, and GHCR rejects        │"
        echo "  │  them instead of falling back to an anonymous pull.         │"
        echo "  │                                                             │"
        echo "  │    docker logout ghcr.io                                    │"
        echo "  │                                                             │"
        echo "  │  Then re-run this installer.                                │"
        echo "  └─────────────────────────────────────────────────────────────┘"
      else
        echo "  Image pull failed. Error output:"
        head -20 "$PULL_LOG"
        echo ""
        echo "  If Docker just started, it may need a moment — try again."
      fi
      rm -f "$PULL_LOG"
      err "Failed to pull Docker images."
    fi
    rm -f "$PULL_LOG"
    info "Docker images pulled"

    # Start services
    printf "  Starting backend services..."
    # The printf above left the cursor mid-line, so break it before erroring.
    START_LOG=$(mktemp /tmp/ix-start-XXXXXX) || { echo ""; err "Could not create a temporary file for the startup log."; }
    if ! dc -f "$COMPOSE_DIR/docker-compose.yml" up -d < /dev/null >"$START_LOG" 2>&1; then
      echo ""
      echo "  Failed to start backend. Error output:"
      head -20 "$START_LOG"
      rm -f "$START_LOG"
      err "docker compose up failed."
    fi
    rm -f "$START_LOG"
    echo " started"

    printf "  Waiting for services to become healthy..."
    i=0
    while [ "$i" -lt 45 ]; do
      if _fetch "$HEALTH_URL" >/dev/null 2>&1 && arango_ok; then
        break
      fi
      printf "."
      sleep 2
      i=$((i + 1))
    done
    echo ""

    if _fetch "$HEALTH_URL" >/dev/null 2>&1; then
      info "Backend is ready"
    else
      warn "Backend may still be starting — check: docker compose -f $COMPOSE_DIR/docker-compose.yml logs"
    fi
  fi

  echo "  Memory Layer: http://localhost:8090"
fi

# -- Step 4: Install ix CLI --

step "4. ix CLI"

if [ "$PLATFORM" = "windows-amd64" ]; then
  TARBALL_NAME="ix-${VERSION}-${PLATFORM}.zip"
else
  TARBALL_NAME="ix-${VERSION}-${PLATFORM}.tar.gz"
fi
TARBALL_URL="https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/releases/download/v${VERSION}/${TARBALL_NAME}"
INSTALL_DIR="$IX_HOME/cli"

# Remove any stale ix from other locations
for old_ix in "$HOME/.local/bin/ix" "/usr/local/bin/ix"; do
  if [ "$old_ix" != "$IX_BIN/ix" ] && [ -f "$old_ix" ]; then
    rm -f "$old_ix" 2>/dev/null || true
  fi
done

# Check if already installed at correct version
# On Windows, avoid invoking the shim (calls cmd.exe, hangs in sh subshell)
check_installed_version() {
  if [ "$PLATFORM" = "windows-amd64" ]; then
    # Read the version out of the installed package rather than inferring it
    # from a version-named directory. That directory no longer exists — the
    # extract below collapses it — and probing for it would report "unknown"
    # against a perfectly current install, wiping and re-laying it on every
    # run, including one install.ps1 had just laid down correctly.
    if [ -f "$INSTALL_DIR/cli/package.json" ]; then
      sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' \
        "$INSTALL_DIR/cli/package.json" | head -1
    else
      echo "unknown"
    fi
  else
    "$IX_BIN/ix" --version 2>/dev/null || echo "unknown"
  fi
}

# Intel Macs have no pre-built asset on the current release matrix —
# darwin-amd64 is deliberately omitted because the macos-13 runners queue
# indefinitely. Decide this BEFORE the upgrade branch below removes the existing
# install: reaching it after `rm -rf "$INSTALL_DIR"` would delete a working CLI
# and then abort, leaving the user worse off than not running the script.
#
# Only for the resolved-latest path. IX_VERSION is an explicit request for a
# specific release, and every build before #259 did publish darwin-amd64 — so a
# pinned rollback is allowed through to the normal download-and-404 handling.
SKIP_CLI_INSTALL=0
CLI_EXTRACTED=0
if [ "$PLATFORM" = "darwin-amd64" ] && [ -z "${IX_VERSION:-}" ]; then
  echo ""
  warn "Ix does not publish a pre-built CLI for Intel Macs (darwin-amd64)."
  echo ""
  echo "  Install the CLI with Homebrew instead — it builds from source:"
  echo "    brew tap ${GITHUB_ORG}/ix https://github.com/${GITHUB_ORG}/${GITHUB_REPO}"
  echo "    brew install ix"
  echo ""
  if [ -x "$IX_BIN/ix" ]; then
    # A CLI is already here (Homebrew, or a pre-#259 release). Leave it exactly
    # as it is and carry on with the backend setup, which is platform-neutral
    # and is the rest of what this script does.
    warn "Leaving your existing ix CLI untouched and continuing with the backend setup."
    echo ""
    SKIP_CLI_INSTALL=1
  else
    echo "  Apple Silicon Macs are supported by this installer directly."
    echo ""
    err "No darwin-amd64 release asset. Install the CLI with Homebrew (above), then re-run this script to set up the backend."
  fi
fi

if [ "$SKIP_CLI_INSTALL" = "0" ] && [ -x "$IX_BIN/ix" ]; then
  existing_version=$(check_installed_version)
  if [ "$existing_version" = "$VERSION" ]; then
    info "ix CLI v${VERSION} is already installed"
  elif [ -z "${IX_VERSION:-}" ] && [ "$existing_version" != "unknown" ] && version_lt "$VERSION" "$existing_version"; then
    # "Latest" older than what is installed means a stale API answer or a
    # pulled release, not a request to go back. A rollback must be asked for.
    warn "Installed ix CLI v${existing_version} is newer than the latest release (v${VERSION}); leaving it in place."
    warn "To install v${VERSION} anyway, re-run with IX_VERSION=${VERSION}."
    SKIP_CLI_INSTALL=1
  else
    # Nothing is removed here: the new tree is downloaded, verified and staged
    # first, and only then swapped in (swap_into_place).
    echo "  Upgrading ix CLI from $existing_version to $VERSION..."
  fi
fi

# swap_into_place DIR — make DIR the CLI install. The old install is moved
# aside rather than deleted and put back if the swap fails, the same shape as
# install.ps1 and swapInStagedTree in upgrade.ts.
#
# $INSTALL_DIR may hold a working CLI from either installer (install.ps1 writes
# %IX_HOME%\bin\ix.cmd rather than $IX_BIN/ix, and pick_bin_dir() can resolve
# differently than it did last run). Deleting it outright would destroy a
# working CLI with nothing to restore from, and `mv` onto a directory that
# survived would silently nest the tree inside it.
swap_into_place() {
  CLI_BACKUP="$IX_HOME/.cli-backup-$$"
  # `|| true` on every cleanup rm below. Under `set -e` a bare rm that fails
  # aborts the script where it stands — verified — and the ones after the swap
  # sit between the new tree and the shim write, so a locked leftover would
  # install the CLI and then skip the launcher, ensure_path and both version
  # stamps. That is the brick rmQuiet() exists to prevent on the TS side and
  # that install.ps1 avoids with -ErrorAction SilentlyContinue.
  if ! rm -rf "$CLI_BACKUP" 2>/dev/null && [ -e "$CLI_BACKUP" ]; then
    rm -rf "$1" "$TMP_DIR" || true
    err "Could not clear a leftover backup at $CLI_BACKUP. Remove it and re-run. The existing install is untouched."
  fi
  # An empty directory left by an older installer is not an install, and
  # moving it aside would report restoring a CLI that never existed. rmdir
  # fails harmlessly on a populated install, which is the one to move aside.
  rmdir "$INSTALL_DIR" 2>/dev/null || true
  if [ -e "$INSTALL_DIR" ] && ! mv "$INSTALL_DIR" "$CLI_BACKUP"; then
    rm -rf "$1" "$TMP_DIR" || true
    err "Could not move the existing install aside from $INSTALL_DIR. It is untouched."
  fi
  if mv "$1" "$INSTALL_DIR"; then
    rm -rf "$CLI_BACKUP" || true
  else
    # if/else, not `mv ... && warn`: with && a *failed* restore short-circuits
    # and says nothing at all, so the user is never told the only surviving
    # copy is at $CLI_BACKUP — which is the case the backup exists for.
    if [ -d "$CLI_BACKUP" ] && [ ! -e "$INSTALL_DIR" ] && mv "$CLI_BACKUP" "$INSTALL_DIR"; then
      warn "Restored the previous CLI after a failed update."
    elif [ -d "$CLI_BACKUP" ]; then
      warn "Your previous CLI is at $CLI_BACKUP — move it to $INSTALL_DIR to restore it."
    fi
    rm -rf "$1" "$TMP_DIR" || true
    err "Could not install to $INSTALL_DIR."
  fi
}

if [ "$SKIP_CLI_INSTALL" = "0" ] && { [ ! -x "$IX_BIN/ix" ] || [ "$(check_installed_version)" != "$VERSION" ]; }; then
  # Records that the compass now under $IX_HOME/cli came out of THIS release
  # tarball. The stamp block near the end of the script needs to know: it must
  # never label a bundle it did not install (Ix#376).
  CLI_EXTRACTED=1

  TMP_DIR=$(mktemp -d)
  TMP_FILE="$TMP_DIR/${TARBALL_NAME}"

  echo "  Downloading ix CLI v${VERSION} for ${PLATFORM}..."
  echo "  URL: $TARBALL_URL"
  if ! _download "$TARBALL_URL" "$TMP_FILE" 2>/dev/null; then
    rm -rf "$TMP_DIR"
    echo ""
    warn "Could not download pre-built CLI from:"
    warn "  $TARBALL_URL"
    echo ""
    echo "  This likely means the release asset has not been uploaded yet."
    echo "  Check available releases at:"
    echo "    https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/releases"
    echo ""
    # This branch is reached on every platform, so the advice has to work on
    # every platform. Homebrew is the right answer on macOS specifically; it is
    # no help at all to the Linux and Windows users who also land here.
    case "$PLATFORM" in
      darwin-*)
        echo "  Or install with Homebrew, which builds from source:"
        echo "    brew tap ${GITHUB_ORG}/ix https://github.com/${GITHUB_ORG}/${GITHUB_REPO}"
        echo "    brew install ix"
        ;;
      *)
        # scripts/dev/setup.sh, not ./setup.sh — the root-level script this used
        # to cite has never existed in this repo.
        echo "  Or build from source:"
        echo "    git clone https://github.com/${GITHUB_ORG}/${GITHUB_REPO}.git"
        echo "    cd ${GITHUB_REPO} && ./scripts/dev/setup.sh"
        ;;
    esac
    echo ""
    err "CLI download failed. See above for alternatives."
  fi

  # Before anything reads the archive.
  verify_checksum "$TMP_FILE" "$TARBALL_URL" "$TARBALL_NAME"
  info "Checksum verified"

  # Extract
  if [ "$PLATFORM" = "windows-amd64" ]; then
    # unzip has no --strip-components, and the zip nests everything under
    # ix-<version>-windows-amd64/. Extracting straight into $INSTALL_DIR left a
    # bundled compass at cli/ix-<version>-windows-amd64/compass while the CLI
    # only ever reads cli/compass (COMPASS_DIR in upgrade.ts, findCompassDist in
    # view.ts), so `ix view` was unavailable on every Windows install made from
    # this script — the same break install.ps1 had.
    #
    # Unzip into staging and move the single top-level directory into place, so
    # both installers and `ix upgrade` lay down one shape. Without this the two
    # installers disagree on the same platform and half-break each other:
    # check_installed_version below reads the flat entry point, so a nested
    # tree reports "unknown" and gets replaced, and vice versa.
    ZIP_STAGING="$TMP_DIR/staged"
    mkdir -p "$ZIP_STAGING"
    unzip -q "$TMP_FILE" -d "$ZIP_STAGING"
    # Exactly one directory, matching soleChildDir in upgrade.ts and the guard
    # in install.ps1. Anything else is not a release we recognise, and
    # collapsing an arbitrary one of several would install the wrong tree.
    ZIP_TOP_COUNT=$(find "$ZIP_STAGING" -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ')
    ZIP_TOP=$(find "$ZIP_STAGING" -mindepth 1 -maxdepth 1 -type d | head -1)
    if [ "$ZIP_TOP_COUNT" != "1" ] || [ ! -f "$ZIP_TOP/ix.cmd" ]; then
      rm -rf "$TMP_DIR"
      err "Extracted archive is not an ix release: expected one top-level directory containing ix.cmd, found $ZIP_TOP_COUNT."
    fi
    swap_into_place "$ZIP_TOP"
  else
    # Extract into a staging directory beside the install and swap it in only
    # once it holds a launcher. Extracting straight into $INSTALL_DIR after
    # deleting it left no CLI at all whenever the download or the extract failed.
    CLI_STAGING="$IX_HOME/.cli-staging-$$"
    rm -rf "$CLI_STAGING" 2>/dev/null || true
    mkdir -p "$CLI_STAGING"
    if ! tar -xzf "$TMP_FILE" -C "$CLI_STAGING" --strip-components=1 || [ ! -x "$CLI_STAGING/ix" ]; then
      rm -rf "$CLI_STAGING" "$TMP_DIR" || true
      err "The CLI archive did not extract to an ix release. The existing install is untouched."
    fi
    swap_into_place "$CLI_STAGING"
  fi
  rm -rf "$TMP_DIR"
  info "Extracted CLI"

  # Create wrapper shim in bin dir
  if [ "$PLATFORM" = "windows-amd64" ]; then
    # No version in the path any more: the tree is flat, and refreshLaunchers
    # in upgrade.ts rewrites this shim to exactly this form after an upgrade.
    IX_JS="$INSTALL_DIR/cli/dist/cli/main.js"
    cat > "$IX_BIN/ix" <<SHIM
#!/bin/sh
exec node "$IX_JS" "\$@"
SHIM
  else
    cat > "$IX_BIN/ix" <<SHIM
#!/bin/sh
exec "$INSTALL_DIR/ix" "\$@"
SHIM
  fi
  chmod +x "$IX_BIN/ix"

  ensure_path

  info "Installed: $IX_BIN/ix"
fi

# -- Stamp installed versions so upgrade checker doesn't nag --

BACKEND_VER=$(resolve_backend_version)
[ -n "$BACKEND_VER" ] && printf '%s' "$BACKEND_VER" > "$IX_HOME/.backend-version"

# Only stamp compass if a compass was actually installed. Stamping unconditionally
# created $IX_HOME/cli/compass/ containing nothing but a .version file, which made
# `ix upgrade` believe compass was already current (it compares against this stamp)
# and permanently skip the download that would have repaired it — so `ix view`
# stayed broken forever. The bundle ships inside the release tarball; if it is
# absent, leaving the stamp off lets `ix upgrade` self-heal from ix-compass-dist.
# This tests the path the CLI actually reads (COMPASS_DIR in upgrade.ts,
# findCompassDist in view.ts). The Windows extract above now collapses the
# archive's top-level directory, so that is also where the bundled compass
# lands and this branch stamps a bundle `ix view` can genuinely serve — the
# warning below is a real failure signal on every platform, not the normal
# Windows path. Keep the -f test on index.html: stamping a version for a
# compass that is not on disk is what made `ix upgrade` skip the repair
# download and break `ix view` permanently.
#
# The compass installed here always comes from the release tarball, never from
# ix-compass-dist — so it must be stamped as a *release* bundle. This used to
# write the latest ix-compass-dist release number instead, which mislabelled a
# release bundle as a dist build and clobbered the correct stamp the tarball
# already carried. The result was live on real installs: a v0.9.x bundle
# stamped `0.2.0`, against a dist latest of `0.3.0`, so `ix upgrade` reported an
# update and would have *downgraded* the bundle to an older build (Ix#376).
#
# Prefer the stamp the tarball shipped with, which since v0.9.3 carries the
# source commit too. Only write one if the bundle has none — tarballs up to
# v0.9.2 predate the stamp.
#
# Gated on CLI_EXTRACTED, and that gate is the whole correctness argument. This
# block runs even when the CLI install was skipped: the version on disk already
# matched, or SKIP_CLI_INSTALL=1 on darwin-amd64. In that case the compass under
# cli/ is whatever was already there, which can be an *ix-compass-dist* bundle
# left unstamped by an interrupted `ix upgrade` (its stage="stamp" failure
# installs the bundle and then fails to write .version). Stamping that
# `+release` would freeze it: shouldOfferCompassUpgradeFor refuses every future
# dist update for a release bundle, so a genuinely stale compass would never be
# replaced and `ix upgrade` would print a claim about it that is simply untrue.
#
# Nothing is lost by skipping it. When we DID extract, the tarball's own stamp
# has already landed and is authoritative — which is also what repairs an
# install mislabelled by the pre-#376 installer. One line, semver build
# metadata: see the note in release.yml on why this file must stay readable by
# already-shipped CLIs.
if [ -f "$IX_HOME/cli/compass/index.html" ]; then
  if [ "$CLI_EXTRACTED" = "1" ] && [ ! -s "$IX_HOME/cli/compass/.version" ]; then
    printf '%s+release\n' "$VERSION" > "$IX_HOME/cli/compass/.version"
  fi
elif [ ! -f "$IX_HOME/cli/compass/index.html" ]; then
  warn "System Compass is not installed at $IX_HOME/cli/compass — 'ix view' is unavailable until you run 'ix upgrade', which will fetch it."
fi

# -- Done --

echo ""
echo "╔══════════════════════════════════════════╗"
echo "║       Ix is ready!                ║"
echo "╚══════════════════════════════════════════╝"
echo ""
echo "  Backend:  http://localhost:8090"
echo ""

# Verify CLI works
if [ "$PLATFORM" = "windows-amd64" ]; then
  if [ -x "$IX_BIN/ix" ]; then
    info "ix CLI v${VERSION} installed at $IX_BIN/ix"
    echo "  Run 'ix --version' in a new terminal to verify"
  fi
elif command -v ix >/dev/null 2>&1; then
  CLI_VERSION=$(ix --version 2>/dev/null || echo "unknown")
  info "ix CLI v${CLI_VERSION} is working"
elif [ -x "$IX_BIN/ix" ]; then
  CLI_VERSION=$("$IX_BIN/ix" --version 2>/dev/null || echo "unknown")
  info "ix CLI v${CLI_VERSION} installed at $IX_BIN/ix"
  if [ "$IX_BIN" != "/usr/local/bin" ]; then
    echo "  Open a new terminal for 'ix' to be in your PATH"
  fi
else
  warn "ix not found in PATH — something may have gone wrong"
fi

echo ""
echo "  Connect a project:"
echo "    cd ~/my-project && ix map ."
echo ""
echo "  To uninstall:"
echo "    curl -fsSL https://ix-infra.com/uninstall.sh | sh"
echo ""