#!/bin/sh
# Agent Control Tower Installer
# Usage: curl -fsSL https://actower.io/install.sh | bash
#
# Or with options:
#   curl -fsSL https://actower.io/install.sh | bash -s -- --help
#   curl -fsSL https://actower.io/install.sh | bash -s -- --uninstall
#
# The script itself is POSIX sh and also runs under `| sh`.

set -e

# Configuration
ACTOWER_VERSION="${ACTOWER_VERSION:-1.3.7}"
ACTOWER_HOME="${ACTOWER_HOME:-$HOME/.actower}"
# A quoted ACTOWER_HOME='~/.actower' arrives unexpanded. Expand a leading ~ /
# $HOME / ${HOME} ONCE, here, so mkdir/rm -rf and the default-home check
# (_is_default_home) always see the same path — never $PWD/~/.actower.
# A bare ~ / $HOME becomes $HOME itself, which _refuse_unsafe_home then rejects
# before any mkdir or rm -rf.
for _ah_pfx in '~' '$HOME' '${HOME}'; do
    case "$ACTOWER_HOME" in
        "$_ah_pfx")   ACTOWER_HOME="$HOME"; break ;;
        "$_ah_pfx"/*) ACTOWER_HOME="$HOME/${ACTOWER_HOME#"$_ah_pfx"/}"; break ;;
    esac
done
unset _ah_pfx
S3_BUCKET="actower-releases"
ACTOWER_STAGE="${ACTOWER_STAGE:-prod}"
RELEASE_URL="https://${S3_BUCKET}.s3.us-west-2.amazonaws.com/${ACTOWER_STAGE}/v${ACTOWER_VERSION}"

# Colors (disabled if not interactive)
if [ -t 1 ]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[0;33m'
    BLUE='\033[0;34m'
    BOLD='\033[1m'
    NC='\033[0m' # No Color
else
    RED=''
    GREEN=''
    YELLOW=''
    BLUE=''
    BOLD=''
    NC=''
fi

# Logging functions
info() {
    printf "${BLUE}==>${NC} ${BOLD}%s${NC}\n" "$1"
}

success() {
    printf "${GREEN}==>${NC} ${BOLD}%s${NC}\n" "$1"
}

warn() {
    printf "${YELLOW}Warning:${NC} %s\n" "$1"
}

error() {
    printf "${RED}Error:${NC} %s\n" "$1" >&2
}

die() {
    error "$1"
    exit 1
}

# Detect platform
detect_platform() {
    case "$(uname -s)" in
        Darwin)
            PLATFORM="macos"
            if [ "$(uname -m)" = "arm64" ]; then
                ARCH="arm64"
            else
                ARCH="x86_64"
            fi
            ;;
        Linux)
            if grep -q Microsoft /proc/version 2>/dev/null; then
                PLATFORM="wsl"
            else
                PLATFORM="linux"
            fi
            ARCH="$(uname -m)"
            ;;
        MINGW*|CYGWIN*|MSYS*)
            die "Native Windows is not supported. Please use WSL.\nInstall WSL: wsl --install"
            ;;
        *)
            die "Unsupported platform: $(uname -s)"
            ;;
    esac

    # Detect Linux distribution
    if [ "$PLATFORM" = "linux" ] || [ "$PLATFORM" = "wsl" ]; then
        if [ -f /etc/os-release ]; then
            . /etc/os-release
            DISTRO="$ID"
        elif [ -f /etc/debian_version ]; then
            DISTRO="debian"
        elif [ -f /etc/fedora-release ]; then
            DISTRO="fedora"
        elif [ -f /etc/arch-release ]; then
            DISTRO="arch"
        else
            DISTRO="unknown"
        fi
    fi
}

# Check if command exists
has_cmd() {
    command -v "$1" >/dev/null 2>&1
}

# Find bash 4+ and return its version
# Sets BASH4_PATH as side effect
get_bash_version() {
    BASH4_PATH=""

    # Check common Homebrew/Linuxbrew paths first (these usually have bash 4+)
    for bash_path in /opt/homebrew/bin/bash /usr/local/bin/bash /home/linuxbrew/.linuxbrew/bin/bash; do
        if [ -x "$bash_path" ]; then
            ver=$("$bash_path" -c 'echo ${BASH_VERSINFO[0]}' 2>/dev/null || echo "0")
            if [ "$ver" -ge 4 ] 2>/dev/null; then
                BASH4_PATH="$bash_path"
                echo "$ver"
                return 0
            fi
        fi
    done

    # Fallback: check PATH bash
    if has_cmd bash; then
        ver=$(bash -c 'echo ${BASH_VERSINFO[0]}' 2>/dev/null || echo "0")
        if [ "$ver" -ge 4 ] 2>/dev/null; then
            BASH4_PATH="bash"
            echo "$ver"
            return 0
        fi
        echo "$ver"
        return 0
    fi

    echo "0"
}

# The places a dependency commonly lives WITHOUT being on PATH: Homebrew's bins
# (Apple Silicon, Intel, Linuxbrew), the python@3.11 kegs and the python.org
# framework build. Searched for python3.11 AND tmux, in this order — on the
# server they sat side by side in /usr/local/bin over a non-login shell.
# ACTOWER_DEPS_DIRS is a TEST SEAM (tests cannot write /usr/local/bin, and a dev
# Mac always has a real /opt/homebrew/bin/tmux); it replaces the WHOLE list.
# Last, when it exists: a pyenv-built 3.11 (`${PYENV_ROOT:-~/.pyenv}/versions/
# 3.11*/bin`, the last in glob order — any 3.11.x will do, the finder still
# checks the version). A path with a space is skipped: callers word-split.
#
# KEEP IN SYNC with libexec/actower-venv.sh:actower_deps_dirs — the CLI's copy
# (`actower doctor` / `actower setup` / the venv resolver). This script cannot
# source that file: check_deps runs before the tarball is downloaded.
# tests/test_deps_dirs_parity.sh asserts the two print the same list.
_deps_dirs() {
    if [ -n "${ACTOWER_DEPS_DIRS:-}" ]; then
        printf '%s\n' "$ACTOWER_DEPS_DIRS"
        return 0
    fi
    _dd_pyenv=""
    for _dd_d in "${PYENV_ROOT:-${HOME:-}/.pyenv}"/versions/3.11*/bin; do
        case "$_dd_d" in *" "*) continue ;; esac
        [ -d "$_dd_d" ] && _dd_pyenv="$_dd_d"
    done
    printf '%s\n' "/opt/homebrew/opt/python@3.11/bin /opt/homebrew/bin /usr/local/opt/python@3.11/bin /usr/local/bin /Library/Frameworks/Python.framework/Versions/3.11/bin /home/linuxbrew/.linuxbrew/bin${_dd_pyenv:+ $_dd_pyenv}"
    unset _dd_d _dd_pyenv
}

# tmux off PATH (see _deps_dirs). On a hit: TMUX_FOUND_DIR is set, the ✓ line
# names where, and ensure_deps puts the dir on PATH for the rest of the install
# (`actower setup` checks `command -v tmux`). Returns 1, printing nothing, when
# there is none — the not-found case keeps check_deps' output as it was.
_find_tmux_offpath() {
    TMUX_FOUND_DIR=""
    for _ft_dir in $(_deps_dirs); do
        if [ ! -x "$_ft_dir/tmux" ] || [ -d "$_ft_dir/tmux" ]; then
            continue
        fi
        # Trusted only if it runs, as python3.11 is trusted only if it reports
        # 3.11: a broken or mis-linked binary is not tmux.
        if _ft_ver=$("$_ft_dir/tmux" -V 2>/dev/null) && [ -n "$_ft_ver" ]; then
            _ft_ver=$(printf '%s\n' "$_ft_ver" | cut -d' ' -f2)
            printf "  ${GREEN}✓${NC} tmux %s (%s — not on PATH)\n" "${_ft_ver:-unknown}" "$_ft_dir/tmux"
            TMUX_FOUND_DIR="$_ft_dir"
            unset _ft_dir _ft_ver
            return 0
        fi
    done
    unset _ft_dir _ft_ver
    return 1
}

# Resolve a Python 3.11 interpreter into PYTHON_CMD, printing check_deps' line
# for it. Returns 1 (after printing the ✗ line) when there is none.
#
# PATH first, with today's output byte-for-byte: python3 when its minor is 11,
# else python3.11. Then the places a python3.11 commonly lives WITHOUT being on
# PATH — a non-login shell, a fresh Homebrew whose shellenv is not loaded yet,
# a python.org framework build. Seen on the server 2026-10-06: the check found
# Python 3.9.6 and stopped while /usr/local/bin/python3.11 sat right there.
# A found-off-PATH interpreter is used by its ABSOLUTE path (every PYTHON_CMD
# consumer quotes it) and its directory is recorded in PY311_FOUND_DIR so
# ensure_deps can put it on PATH for the rest of the install — `actower setup`
# probes `command -v python3.11` itself and exits 10 without it.
#
# The candidate is trusted only if it really reports 3.11: a dangling or
# mis-linked python3.11 is not 3.11.
_find_python311() {
    PY311_FOUND_DIR=""
    if has_cmd python3; then
        PYTHON_VER=$(python3 --version 2>/dev/null | cut -d' ' -f2 || echo "0.0.0")
        PYTHON_MINOR=$(echo "$PYTHON_VER" | cut -d. -f2)
    else
        PYTHON_VER=""
        PYTHON_MINOR=""
    fi

    if [ "${PYTHON_MINOR:-0}" -eq "$PYTHON_REQUIRED_MINOR" ] 2>/dev/null; then
        # Default python3 IS 3.11 — perfect
        printf "  ${GREEN}✓${NC} python3 %s\n" "$PYTHON_VER"
        PYTHON_CMD="python3"
        return 0
    fi
    if has_cmd python3.11; then
        # python3.11 available as versioned command — use it
        PY311_VER=$(python3.11 --version 2>/dev/null | cut -d' ' -f2)
        if [ -n "$PYTHON_VER" ]; then
            printf "  ${GREEN}✓${NC} python3 %s (using python3.11 %s for install)\n" "$PYTHON_VER" "$PY311_VER"
        else
            printf "  ${GREEN}✓${NC} python3.11 %s\n" "$PY311_VER"
        fi
        PYTHON_CMD="python3.11"
        return 0
    fi

    for _fp_dir in $(_deps_dirs); do
        _fp_py="$_fp_dir/python3.11"
        if [ ! -x "$_fp_py" ]; then
            continue
        fi
        _fp_ver=$("$_fp_py" --version 2>/dev/null | cut -d' ' -f2) || _fp_ver=""
        case "$_fp_ver" in
            3.11|3.11.*)
                printf "  ${GREEN}✓${NC} python3.11 %s (%s — not on PATH)\n" "$_fp_ver" "$_fp_py"
                PYTHON_CMD="$_fp_py"
                PY311_FOUND_DIR="$_fp_dir"
                unset _fp_dir _fp_py _fp_ver
                return 0
                ;;
        esac
    done
    unset _fp_dir _fp_py _fp_ver

    # No python3.11 found
    if [ -n "$PYTHON_VER" ]; then
        printf "  ${RED}✗${NC} python3 %s (need exactly 3.11.x for PyArmor compatibility)\n" "$PYTHON_VER"
    else
        printf "  ${RED}✗${NC} python3 not found (need 3.11.x)\n"
    fi
    return 1
}

# Does apt know a candidate version of package $1? `apt-cache policy` needs no
# sudo and reads no stdin; a package the archive lacks prints nothing or
# "Candidate: (none)". LC_ALL=C because apt translates the label — a German
# desktop prints "Installationskandidat:", and an English-only grep would then
# read every package as missing a candidate (gettext ignores LANGUAGE under C).
_apt_has_candidate() {
    LC_ALL=C apt-cache policy "$1" 2>/dev/null | grep -q 'Candidate: [^(]'
}

# Are apt's package lists on disk? Docker images routinely delete them; then an
# INSTALLED python3 still shows a candidate (from dpkg's status file) while
# python3.11 shows none — which says nothing about the archive.
# ACTOWER_APT_LISTS_DIR is a TEST SEAM.
_apt_lists_present() {
    for _al_f in "${ACTOWER_APT_LISTS_DIR:-/var/lib/apt/lists}"/*Packages*; do
        if [ -e "$_al_f" ]; then
            unset _al_f
            return 0
        fi
    done
    unset _al_f
    return 1
}

# True only when apt can be SEEN to have no python3.11. If the package lists
# are absent (never fetched, or deleted) we cannot tell, so the offer stands and
# its `apt-get update` decides.
_apt_lacks_python311() {
    if ! has_cmd apt-cache; then
        return 1
    fi
    if ! _apt_lists_present; then
        return 1
    fi
    if _apt_has_candidate python3.11; then
        return 1
    fi
    if ! _apt_has_candidate python3; then
        return 1
    fi
    return 0
}

# Record the package-manager token(s) for a missing dep ($1: bash|tmux|
# python3.11|curl) in DEP_PKGS — a FIXED table, so no input ever reaches the
# command line. A dep this machine's manager cannot supply (python3.11 on Arch
# is AUR-only; an unrecognised distro) goes to DEP_UNINSTALLABLE instead, and
# then nothing is offered: installing half and still refusing helps nobody.
# apt gets python3.11-venv too: without it Debian/Ubuntu build a venv with no
# pip, and the Web UI dependencies are then silently skipped.
#
# apt's python3.11 is checked against the archive first: Ubuntu 24.04+ and
# Debian 13 ship no python3.11 (deadsnakes PPA / none), and apt then rejects the
# WHOLE transaction — tmux included — after the user has said yes and typed a
# sudo password. Same footing as Arch: no offer, the refusal with its hint.
_dep_pkg() {
    _dp_pkg=""
    case "$PLATFORM" in
        macos)
            case "$1" in
                python3.11) _dp_pkg="python@3.11" ;;
                *)          _dp_pkg="$1" ;;
            esac
            ;;
        linux|wsl)
            case "$DISTRO" in
                ubuntu|debian)
                    case "$1" in
                        python3.11)
                            if ! _apt_lacks_python311; then
                                _dp_pkg="python3.11 python3.11-venv"
                            fi
                            ;;
                        *)          _dp_pkg="$1" ;;
                    esac
                    ;;
                fedora|rhel|centos)
                    _dp_pkg="$1"
                    ;;
                arch|manjaro)
                    case "$1" in
                        python3.11) ;;
                        *)          _dp_pkg="$1" ;;
                    esac
                    ;;
            esac
            ;;
    esac
    if [ -n "$_dp_pkg" ]; then
        DEP_PKGS="${DEP_PKGS:+$DEP_PKGS }$_dp_pkg"
    else
        DEP_UNINSTALLABLE="$DEP_UNINSTALLABLE $1"
    fi
    unset _dp_pkg
}

# The refusal block — byte-identical to what check_deps has always printed, so
# every path that ends in "install them yourself" reads exactly as it did.
_print_missing_deps() {
    echo ""
    error "Missing dependencies:$MISSING_DEPS"
    echo ""
    echo "Install them with:"
    printf "$INSTALL_CMDS\n"
    echo ""

    # On macOS, check if Homebrew is installed
    if [ "$PLATFORM" = "macos" ] && ! has_cmd brew; then
        echo "First install Homebrew:"
        echo '  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"'
        echo ""
    fi
}

# Check dependencies
check_deps() {
    info "Checking dependencies..."

    MISSING_DEPS=""
    INSTALL_CMDS=""
    # The package-manager tokens for what is missing (see _dep_pkg) and the deps
    # this machine's package manager cannot supply. INSTALL_CMDS stays display
    # text only — it is never run.
    DEP_PKGS=""
    DEP_UNINSTALLABLE=""
    PYTHON_CMD="python3"  # Will be resolved to python3.11 interpreter

    # Check bash 4+
    BASH_VER=$(get_bash_version)
    if [ "$BASH_VER" -lt 4 ] 2>/dev/null; then
        MISSING_DEPS="$MISSING_DEPS bash(4+)"
        _dep_pkg bash
        case "$PLATFORM" in
            macos)
                INSTALL_CMDS="$INSTALL_CMDS\n  brew install bash"
                ;;
            linux|wsl)
                case "$DISTRO" in
                    ubuntu|debian)
                        # Usually bash 4+ is already installed on Linux
                        INSTALL_CMDS="$INSTALL_CMDS\n  sudo apt update && sudo apt install -y bash"
                        ;;
                    fedora|rhel|centos)
                        INSTALL_CMDS="$INSTALL_CMDS\n  sudo dnf install -y bash"
                        ;;
                    arch|manjaro)
                        INSTALL_CMDS="$INSTALL_CMDS\n  sudo pacman -S bash"
                        ;;
                esac
                ;;
        esac
    else
        if [ -n "$BASH4_PATH" ] && [ "$BASH4_PATH" != "bash" ]; then
            printf "  ${GREEN}✓${NC} bash %s (%s)\n" "$BASH_VER" "$BASH4_PATH"
        else
            printf "  ${GREEN}✓${NC} bash %s\n" "$BASH_VER"
        fi
    fi

    # Check tmux
    TMUX_FOUND_DIR=""
    if ! has_cmd tmux && ! _find_tmux_offpath; then
        MISSING_DEPS="$MISSING_DEPS tmux"
        _dep_pkg tmux
        case "$PLATFORM" in
            macos)
                INSTALL_CMDS="$INSTALL_CMDS\n  brew install tmux"
                ;;
            linux|wsl)
                case "$DISTRO" in
                    ubuntu|debian)
                        INSTALL_CMDS="$INSTALL_CMDS\n  sudo apt update && sudo apt install -y tmux"
                        ;;
                    fedora|rhel|centos)
                        INSTALL_CMDS="$INSTALL_CMDS\n  sudo dnf install -y tmux"
                        ;;
                    arch|manjaro)
                        INSTALL_CMDS="$INSTALL_CMDS\n  sudo pacman -S tmux"
                        ;;
                esac
                ;;
        esac
    elif [ -z "$TMUX_FOUND_DIR" ]; then
        # On PATH (an off-PATH hit already printed its own line).
        TMUX_VER=$(tmux -V 2>/dev/null | cut -d' ' -f2 || echo "unknown")
        printf "  ${GREEN}✓${NC} tmux %s\n" "$TMUX_VER"
    fi

    # Check python3 (need exactly 3.11.x for PyArmor runtime compatibility)
    # PyArmor obfuscated code is ABI-locked to the exact Python minor version used at build time.
    # We build with Python 3.11, so the runtime only works on 3.11.x — not 3.12, 3.13, 3.14, etc.
    PYTHON_REQUIRED_MINOR=11

    _suggest_python311_install() {
        case "$PLATFORM" in
            macos)
                INSTALL_CMDS="$INSTALL_CMDS\n  brew install python@3.11"
                ;;
            linux|wsl)
                case "$DISTRO" in
                    ubuntu|debian)
                        INSTALL_CMDS="$INSTALL_CMDS\n  sudo apt update && sudo apt install -y python3.11\n  # Ubuntu 22.04: sudo add-apt-repository ppa:deadsnakes/ppa first"
                        ;;
                    fedora|rhel|centos)
                        INSTALL_CMDS="$INSTALL_CMDS\n  sudo dnf install -y python3.11"
                        ;;
                    arch|manjaro)
                        INSTALL_CMDS="$INSTALL_CMDS\n  yay -S python311  # from AUR (not in official repos)"
                        ;;
                esac
                ;;
        esac
    }

    if ! _find_python311; then
        MISSING_DEPS="$MISSING_DEPS python3.11"
        _suggest_python311_install
        _dep_pkg python3.11
    fi

    # Check curl or wget for downloading
    if ! has_cmd curl && ! has_cmd wget; then
        MISSING_DEPS="$MISSING_DEPS curl"
        _dep_pkg curl
        case "$PLATFORM" in
            macos)
                INSTALL_CMDS="$INSTALL_CMDS\n  brew install curl"
                ;;
            linux|wsl)
                case "$DISTRO" in
                    ubuntu|debian)
                        INSTALL_CMDS="$INSTALL_CMDS\n  sudo apt update && sudo apt install -y curl"
                        ;;
                    fedora|rhel|centos)
                        INSTALL_CMDS="$INSTALL_CMDS\n  sudo dnf install -y curl"
                        ;;
                    arch|manjaro)
                        INSTALL_CMDS="$INSTALL_CMDS\n  sudo pacman -S curl"
                        ;;
                esac
                ;;
        esac
    else
        if has_cmd curl; then
            printf "  ${GREEN}✓${NC} curl\n"
        else
            printf "  ${GREEN}✓${NC} wget\n"
        fi
    fi

    # Report missing dependencies. With CHECK_DEPS_QUIET_REPORT set (ensure_deps
    # sets it when it can offer to install them) the caller prints instead: an
    # "Error: Missing dependencies" block followed by "Install these now?" would
    # read as a refusal and a question at once.
    if [ -n "$MISSING_DEPS" ]; then
        if [ -z "${CHECK_DEPS_QUIET_REPORT:-}" ]; then
            _print_missing_deps
        fi
        return 1
    fi

    # Optional: system notifications (only shown when required deps pass)
    echo ""
    info "Optional dependencies..."
    case "$PLATFORM" in
        macos)
            if has_cmd terminal-notifier; then
                printf "  ${GREEN}✓${NC} terminal-notifier (click-to-open notifications)\n"
            else
                printf "  ${YELLOW}○${NC} terminal-notifier (recommended for click-to-open notifications)\n"
                printf "    Install: ${BOLD}brew install terminal-notifier${NC}\n"
                printf "    Without it, notifications use osascript (no click action)\n"
            fi
            ;;
        linux|wsl)
            if has_cmd notify-send; then
                printf "  ${GREEN}✓${NC} notify-send (desktop notifications)\n"
            else
                printf "  ${YELLOW}○${NC} notify-send (recommended for desktop notifications)\n"
                case "$DISTRO" in
                    ubuntu|debian)
                        printf "    Install: ${BOLD}sudo apt install -y libnotify-bin${NC}\n"
                        ;;
                    fedora|rhel|centos)
                        printf "    Install: ${BOLD}sudo dnf install -y libnotify${NC}\n"
                        ;;
                    arch|manjaro)
                        printf "    Install: ${BOLD}sudo pacman -S libnotify${NC}\n"
                        ;;
                esac
            fi
            ;;
    esac

    return 0
}

# ── Installing missing dependencies (one question) ───────────────────
#
# A fresh Mac has bash 3.2, no tmux and Python 3.9 at best — so the audience
# pasting the install line from an invite met three manual installs and a
# rerun. The Homebrew formula gets these as declared dependencies; the curl
# installer now offers the same, with ONE question, and then continues.
#
# Rules: nothing is installed without an explicit yes (or --yes /
# ACTOWER_INSTALL_YES); with no terminal to ask on, the outcome is identical to
# before (the refusal block, exit 1); the install is attempted ONCE and the
# check re-run ONCE — never a loop; Homebrew itself is NEVER installed (it needs
# the user's password and Xcode's command line tools).

# Where to read the answer from — and what to hand install commands as stdin.
# Under `curl | bash` stdin IS this script, so neither the answer nor any child
# may ever read it. Same rule as run_desktop_check: `-r /dev/tty` is true even
# with no controlling terminal, so actually open it. Prints the path, or
# nothing when there is no terminal. ACTOWER_DEPS_TTY is a TEST SEAM: a file
# holding the answer, or "none" for no terminal.
_deps_tty_in() {
    if [ -n "${ACTOWER_DEPS_TTY:-}" ]; then
        if [ "$ACTOWER_DEPS_TTY" != "none" ]; then
            printf '%s\n' "$ACTOWER_DEPS_TTY"
        fi
    elif ( exec < /dev/tty ) 2>/dev/null; then
        printf '%s\n' /dev/tty
    fi
    return 0
}

# --yes, or ACTOWER_INSTALL_YES set to anything but "" / "0" (the same rule as
# NO_DESKTOP_CHECK: =true must not leave the question armed in a script).
_deps_yes() {
    if [ -n "${DEPS_YES:-}" ]; then
        return 0
    fi
    if [ -n "${ACTOWER_INSTALL_YES:-}" ] && [ "${ACTOWER_INSTALL_YES}" != "0" ]; then
        return 0
    fi
    return 1
}

# MISSING_DEPS in words: "tmux", "tmux and Python 3.11", "bash 4+, tmux and
# Python 3.11".
_deps_human() {
    _dh_out=""
    _dh_last=""
    for _dh_dep in $MISSING_DEPS; do
        case "$_dh_dep" in
            bash*)      _dh_name="bash 4+" ;;
            python3.11) _dh_name="Python 3.11" ;;
            *)          _dh_name="$_dh_dep" ;;
        esac
        if [ -n "$_dh_last" ]; then
            _dh_out="${_dh_out:+$_dh_out, }$_dh_last"
        fi
        _dh_last="$_dh_name"
    done
    if [ -n "$_dh_out" ]; then
        printf '%s and %s' "$_dh_out" "$_dh_last"
    else
        printf '%s' "$_dh_last"
    fi
    unset _dh_out _dh_last _dh_dep _dh_name
}

# Work out what can install the missing deps on this machine ($1 = the answer
# source from _deps_tty_in, "" without a terminal). Sets DEP_MGR (brew|apt|dnf|
# pacman), DEP_MGR_BIN (what is run — a name on PATH, or brew's absolute path),
# DEP_MGR_LABEL, DEP_SUDO and DEP_BREW_OFFPATH. Returns 1 with DEP_BLOCKER set
# (no-brew|no-sudo|no-manager) when nothing usable is there.
# ACTOWER_BREW_CANDIDATES is a TEST SEAM (a dev Mac always has a real brew).
_detect_dep_installer() {
    DEP_MGR=""
    DEP_MGR_BIN=""
    DEP_MGR_LABEL=""
    DEP_SUDO=""
    DEP_BREW_OFFPATH=""
    DEP_BLOCKER=""
    case "$PLATFORM" in
        macos)
            # A Homebrew installed a minute ago is often not on PATH yet in this
            # shell (its shellenv line is read by NEW shells) — look where it
            # puts itself before saying there is none.
            if has_cmd brew; then
                DEP_MGR_BIN="brew"
            else
                for _di_brew in ${ACTOWER_BREW_CANDIDATES:-/opt/homebrew/bin/brew /usr/local/bin/brew}; do
                    if [ -x "$_di_brew" ]; then
                        DEP_MGR_BIN="$_di_brew"
                        DEP_BREW_OFFPATH=1
                        break
                    fi
                done
                unset _di_brew
            fi
            if [ -z "$DEP_MGR_BIN" ]; then
                DEP_BLOCKER="no-brew"
                return 1
            fi
            DEP_MGR="brew"
            DEP_MGR_LABEL="Homebrew"
            return 0
            ;;
        linux|wsl)
            case "$DISTRO" in
                ubuntu|debian)      DEP_MGR="apt";    DEP_MGR_BIN="apt-get" ;;
                fedora|rhel|centos) DEP_MGR="dnf";    DEP_MGR_BIN="dnf" ;;
                arch|manjaro)       DEP_MGR="pacman"; DEP_MGR_BIN="pacman" ;;
            esac
            if [ -z "$DEP_MGR" ] || ! has_cmd "$DEP_MGR_BIN"; then
                DEP_MGR=""
                DEP_MGR_BIN=""
                DEP_BLOCKER="no-manager"
                return 1
            fi
            DEP_MGR_LABEL="$DEP_MGR"
            if [ "$(id -u 2>/dev/null || echo x)" = "0" ]; then
                return 0
            fi
            if ! has_cmd sudo; then
                DEP_BLOCKER="no-sudo"
                return 1
            fi
            DEP_SUDO="sudo"
            # Usable without a password, or with one typed at a real terminal
            # (sudo asks on the terminal itself). With neither, it cannot work.
            if sudo -n true < /dev/null > /dev/null 2>&1; then
                return 0
            fi
            if [ -n "$1" ]; then
                return 0
            fi
            DEP_SUDO=""
            DEP_BLOCKER="no-sudo"
            return 1
            ;;
    esac
    DEP_BLOCKER="no-manager"
    return 1
}

# One install step: print it ($1 = print) or announce and run it ($1 = run)
# with stdin from $2 — never this script's own stdin.
_dep_step() {
    _ds_mode="$1"
    _ds_in="$2"
    shift 2
    if [ "$_ds_mode" = "print" ]; then
        printf '  %s\n' "$*"
        return 0
    fi
    printf "${BLUE}==>${NC} ${BOLD}%s${NC}\n" "$*"
    "$@" < "$_ds_in"
}

# THE install commands, defined once so what is printed before the question is
# exactly what runs after it. DEP_PKGS are fixed tokens (no glob characters),
# split on purpose; INSTALL_CMDS is display text and is never run.
_dep_install_steps() {
    # shellcheck disable=SC2086
    case "$DEP_MGR" in
        brew)
            _dep_step "$1" "$2" "$DEP_MGR_BIN" install $DEP_PKGS
            ;;
        apt)
            _dep_step "$1" "$2" $DEP_SUDO "$DEP_MGR_BIN" update || return 1
            _dep_step "$1" "$2" $DEP_SUDO "$DEP_MGR_BIN" install -y $DEP_PKGS
            ;;
        dnf)
            _dep_step "$1" "$2" $DEP_SUDO "$DEP_MGR_BIN" install -y $DEP_PKGS
            ;;
        pacman)
            _dep_step "$1" "$2" $DEP_SUDO "$DEP_MGR_BIN" -S --needed --noconfirm $DEP_PKGS
            ;;
        *)
            return 1
            ;;
    esac
}

# Nothing on this machine can install them: say so plainly, in two lines.
_print_no_installer() {
    _pn_what=$(_deps_human)
    echo ""
    case "$DEP_BLOCKER" in
        no-brew)
            printf "ACTower needs Homebrew to install %s.\n" "$_pn_what"
            echo "Install Homebrew first (https://brew.sh), then run this installer again."
            ;;
        no-sudo)
            printf "ACTower needs administrator rights (sudo) to install %s.\n" "$_pn_what"
            echo "Ask an administrator to run the commands below (or run this installer as root), then run this installer again."
            printf "$INSTALL_CMDS\n"
            ;;
        *)
            printf "ACTower could not find a package manager to install %s.\n" "$_pn_what"
            echo "Install them yourself, then run this installer again."
            if [ -n "$INSTALL_CMDS" ]; then
                printf "$INSTALL_CMDS\n"
            fi
            ;;
    esac
    echo ""
    unset _pn_what
}

# Show what will run and ask the ONE question ($1 = answer source, may be ""
# only under --yes). Returns 0 to go ahead. EOF or a read error is a NO.
_offer_deps_install() {
    echo ""
    printf "ACTower needs %s. This will run:\n" "$(_deps_human)"
    _dep_install_steps print ""
    if _deps_yes; then
        echo "Installing them now (--yes)."
        return 0
    fi
    printf "Install these now with %s? [Y/n] " "$DEP_MGR_LABEL"
    _od_ans=""
    if ! read -r _od_ans < "$1"; then
        _od_ans="n"
    fi
    case "$_od_ans" in
        ""|y|Y|yes|Yes|YES)
            unset _od_ans
            return 0
            ;;
    esac
    unset _od_ans
    return 1
}

# Append dirs to PATH (for this installer process only) — where python3.11 /
# tmux were found off PATH, and an off-PATH brew's bin, where it just put tmux. Appended, not
# prepended, so nothing the user already resolves changes. `actower setup`
# (run_setup) checks `command -v tmux` / `command -v python3.11` and exits 10
# without them; the shell rc is never touched here.
_deps_extend_path() {
    _dx_brew_dir=""
    if [ -n "${DEP_BREW_OFFPATH:-}" ] && [ -n "${DEP_MGR_BIN:-}" ]; then
        _dx_brew_dir=$(dirname "$DEP_MGR_BIN")
    fi
    # The off-PATH folders a dependency was USED from are remembered here, in
    # DEPS_OFFPATH_DIRS, for print_completion's PATH hint. Not read back from
    # PY311_FOUND_DIR / TMUX_FOUND_DIR: check_deps resets those, and the re-check
    # after an install then finds the tools through the PATH extended here — so
    # by print_completion they would be empty exactly when an install also ran.
    for _dx_dir in "${PY311_FOUND_DIR:-}" "${TMUX_FOUND_DIR:-}"; do
        if [ -z "$_dx_dir" ]; then
            continue
        fi
        case " ${DEPS_OFFPATH_DIRS:-} " in
            *" $_dx_dir "*) ;;
            *) DEPS_OFFPATH_DIRS="${DEPS_OFFPATH_DIRS:+$DEPS_OFFPATH_DIRS }$_dx_dir" ;;
        esac
    done
    for _dx_dir in "${PY311_FOUND_DIR:-}" "${TMUX_FOUND_DIR:-}" "$_dx_brew_dir"; do
        if [ -z "$_dx_dir" ]; then
            continue
        fi
        case ":$PATH:" in
            *":$_dx_dir:"*) ;;
            *) PATH="$PATH:$_dx_dir" ;;
        esac
    done
    export PATH
    unset _dx_dir _dx_brew_dir
}

# Step 2 of main(): check, and when something is missing offer to install it.
#   0 — everything is present (possibly after installing it)
#   1 — refused; the "Missing dependencies / Install them with" block is shown
#   2 — nothing here can install them; the two-line reason is shown
ensure_deps() {
    DEPS_INSTALLED=""
    DEPS_OFFPATH_DIRS=""
    _ed_in=""
    _ed_offer=""
    if [ -z "${NO_DEPS_INSTALL:-}" ]; then
        _ed_in=$(_deps_tty_in)
        if [ -n "$_ed_in" ] || _deps_yes; then
            _ed_offer=1
        fi
    fi

    # No offer possible (no terminal and no --yes, or --no-deps-install): a
    # loud check_deps, i.e. exactly the old refuse-only behaviour.
    CHECK_DEPS_QUIET_REPORT="$_ed_offer"
    if check_deps; then
        CHECK_DEPS_QUIET_REPORT=""
        _deps_extend_path
        unset _ed_in _ed_offer
        return 0
    fi
    CHECK_DEPS_QUIET_REPORT=""
    if [ -z "$_ed_offer" ]; then
        unset _ed_in _ed_offer
        return 1
    fi

    if [ -n "$DEP_UNINSTALLABLE" ]; then
        _print_missing_deps
        unset _ed_in _ed_offer
        return 1
    fi
    if ! _detect_dep_installer "$_ed_in"; then
        _print_no_installer
        unset _ed_in _ed_offer
        return 2
    fi
    if [ -z "$_ed_in" ]; then
        _ed_in=/dev/null  # --yes with no terminal: children read nothing
    fi
    if ! _offer_deps_install "$_ed_in"; then
        _print_missing_deps
        unset _ed_in _ed_offer
        return 1
    fi

    echo ""
    if ! _dep_install_steps run "$_ed_in"; then
        echo ""
        error "The install command failed."
        _print_missing_deps
        unset _ed_in _ed_offer
        return 1
    fi
    DEPS_INSTALLED=1
    unset _ed_in _ed_offer

    # Re-check ONCE, loudly: a failure now prints the refusal block. There is
    # no second offer.
    echo ""
    _deps_extend_path
    if ! check_deps; then
        return 1
    fi
    _deps_extend_path
    return 0
}

# Download file using curl or wget
download() {
    url="$1"
    output="$2"

    if has_cmd curl; then
        curl -fsSL "$url" -o "$output"
    elif has_cmd wget; then
        wget -q "$url" -O "$output"
    else
        die "Neither curl nor wget found"
    fi
}

# Create directory structure and install files
install_actower() {
    info "Installing Agent Control Tower v${ACTOWER_VERSION}..."

    # Never mkdir/chmod 700/rm -rf subtrees straight into $HOME or /.
    _refuse_unsafe_home

    # Create directories with secure permissions
    umask 077
    mkdir -p "$ACTOWER_HOME"/{bin,libexec,lib,share/actower,logs}
    chmod 700 "$ACTOWER_HOME"

    # For now, we'll do a local install from the repo if ACTOWER_LOCAL is set
    # Otherwise, download from GitHub releases
    if [ -n "$ACTOWER_LOCAL" ] && [ -d "$ACTOWER_LOCAL" ]; then
        info "Installing from local source: $ACTOWER_LOCAL"

        # Copy files from local source
        cp "$ACTOWER_LOCAL/bin/actower" "$ACTOWER_HOME/bin/"
        cp "$ACTOWER_LOCAL/libexec/actower-core.bash" "$ACTOWER_HOME/libexec/"
        # The shared venv module. NOT optional: setup_web_venv() sources it a
        # few steps below, and the installed CLI's _ensure_venv refuses to run
        # without it ("missing … reinstall to repair"), so omitting it here
        # produces a local install with no venv AND no way to self-heal.
        # release.sh has its own copy + tripwire for the tarball path; this
        # branch enumerates libexec files by name, so it needs its own line.
        cp "$ACTOWER_LOCAL/libexec/actower-venv.sh" "$ACTOWER_HOME/libexec/"
        # The shared skills-sync module — NOT optional either: install_skills()
        # sources it, and the CLI's first run after a version change uses it.
        cp "$ACTOWER_LOCAL/libexec/actower-skills.sh" "$ACTOWER_HOME/libexec/"
        cp "$ACTOWER_LOCAL/share/actower/version.txt" "$ACTOWER_HOME/share/actower/"

        # Copy top-level lib scripts/modules. Guarded so an optional file
        # missing in the source tree doesn't abort the install under `set -e`.
        # (The classifier was split into per-agent packages — see below.)
        for f in monitor-agents.sh agent-responder.sh pane_utils.sh quickstart.sh \
                 report.py log_digest.py activity.py dispatch_classify.py summary_writer.py \
                 safe_rules.py safe_rules_cli.py install_marker.py tmux_theme.py; do
            if [ -f "$ACTOWER_LOCAL/lib/$f" ]; then
                cp "$ACTOWER_LOCAL/lib/$f" "$ACTOWER_HOME/lib/"
            fi
        done

        # 1.3.2 (W2): the `prefix + Tab` helper ACTower's tmux look binds.
        if [ -d "$ACTOWER_LOCAL/lib/tmux" ]; then
            mkdir -p "$ACTOWER_HOME/lib/tmux"
            cp "$ACTOWER_LOCAL/lib/tmux/"*.sh "$ACTOWER_HOME/lib/tmux/" 2>/dev/null || true
            chmod 755 "$ACTOWER_HOME/lib/tmux/"*.sh 2>/dev/null || true
        fi

        # Copy bundled tmux theme configs. Must land in $ACTOWER_HOME/lib/
        # for `actower quickstart` to resolve them on a dev-install (the
        # tarball path already includes them via release.sh).
        if [ -d "$ACTOWER_LOCAL/lib/themes" ]; then
            mkdir -p "$ACTOWER_HOME/lib/themes"
            cp "$ACTOWER_LOCAL/lib/themes/"*.conf "$ACTOWER_HOME/lib/themes/" 2>/dev/null || true
        fi

        # Copy Python packages: adapter registry, per-agent classifiers
        # (claude/codex/agy), and the safety policy. Recursive copy then prune
        # __pycache__ so we don't ship stale bytecode.
        for pkg in adapters claude codex agy safety; do
            if [ -d "$ACTOWER_LOCAL/lib/$pkg" ]; then
                rm -rf "$ACTOWER_HOME/lib/$pkg"
                cp -r "$ACTOWER_LOCAL/lib/$pkg" "$ACTOWER_HOME/lib/"
                rm -rf "$ACTOWER_HOME/lib/$pkg/__pycache__"
            fi
        done

        # Copy vendored ecosystem scaffold (invoked by `actower ecosystem`).
        # The dispatcher resolves scaffold.py via ${SCRIPT_DIR}/ecosystem, which
        # in an installed layout is $ACTOWER_HOME/libexec/ecosystem — without
        # this copy the command dies with "ecosystem scaffold not found".
        if [ -d "$ACTOWER_LOCAL/libexec/ecosystem" ]; then
            rm -rf "$ACTOWER_HOME/libexec/ecosystem" 2>/dev/null || true
            cp -r "$ACTOWER_LOCAL/libexec/ecosystem" "$ACTOWER_HOME/libexec/"
            find "$ACTOWER_HOME/libexec/ecosystem" -name __pycache__ -type d -prune -exec rm -rf {} + 2>/dev/null || true
        fi

        # Copy web UI files if present
        if [ -d "$ACTOWER_LOCAL/lib/web" ]; then
            mkdir -p "$ACTOWER_HOME/lib/web/core" "$ACTOWER_HOME/lib/web/core/backends" "$ACTOWER_HOME/lib/web/api" "$ACTOWER_HOME/lib/web/static"
            cp "$ACTOWER_LOCAL/lib/web/"*.py "$ACTOWER_HOME/lib/web/" 2>/dev/null || true
            cp "$ACTOWER_LOCAL/lib/web/core/"*.py "$ACTOWER_HOME/lib/web/core/" 2>/dev/null || true
            # 1.3.3: the pane-backend package (a subdirectory the flat glob misses).
            cp "$ACTOWER_LOCAL/lib/web/core/backends/"*.py "$ACTOWER_HOME/lib/web/core/backends/" 2>/dev/null || true
            cp "$ACTOWER_LOCAL/lib/web/api/"*.py "$ACTOWER_HOME/lib/web/api/" 2>/dev/null || true
            # Copy static files if frontend is built
            # Prefer web-ui/dist/ (fresh build) over lib/web/static/ (stale copy)
            if [ -d "$ACTOWER_LOCAL/web-ui/dist" ] && [ -f "$ACTOWER_LOCAL/web-ui/dist/index.html" ]; then
                rm -rf "$ACTOWER_HOME/lib/web/static/assets" 2>/dev/null || true
                cp -r "$ACTOWER_LOCAL/web-ui/dist/"* "$ACTOWER_HOME/lib/web/static/"
            elif [ -d "$ACTOWER_LOCAL/lib/web/static" ] && [ -f "$ACTOWER_LOCAL/lib/web/static/index.html" ]; then
                cp -r "$ACTOWER_LOCAL/lib/web/static/"* "$ACTOWER_HOME/lib/web/static/"
            fi
        fi

        # Bundled end-user skills (Task 2). Copy the sources so dev/local
        # installs land the same toolkit the tarball ships (the download path
        # gets them via `tar --strip-components=1`). install_skills() later
        # copies these into ~/.claude/skills/ (Claude Code only).
        if [ -d "$ACTOWER_LOCAL/share/skills" ]; then
            rm -rf "$ACTOWER_HOME/share/skills" 2>/dev/null || true
            cp -r "$ACTOWER_LOCAL/share/skills" "$ACTOWER_HOME/share/"
            find "$ACTOWER_HOME/share/skills" -name .DS_Store -delete 2>/dev/null || true
        fi
    else
        # Download from GitHub releases
        TARBALL_URL="${RELEASE_URL}/actower-${ACTOWER_VERSION}.tar.gz"
        # A per-run temp file, never a predictable /tmp/actower-<ver>.tar.gz:
        # on a shared machine another user could pre-place that name (we would
        # extract their file, or fail to overwrite it), and a failed run left it
        # behind. `mktemp "<dir>/actower-XXXXXX"` rather than `mktemp -t`: BSD
        # `-t prefix` appends its own suffix and keeps the X's literally, GNU
        # reads it as a template — this form behaves the same on both and
        # honours TMPDIR (same form as uninstall's rc rewrite). tar does not
        # need a .tar.gz suffix.
        _ia_tmp=$(mktemp "${TMPDIR:-/tmp}/actower-XXXXXX") \
            || die "Could not create a temporary file for the download (TMPDIR=${TMPDIR:-/tmp})."
        TARBALL="$_ia_tmp"
        # Removed on every exit path: die/exit and a `set -e` abort (EXIT), and
        # Ctrl-C / TERM (their own traps: dash does not run EXIT on a signal
        # death). Cleared right after extraction, before Step 8's INT trap.
        trap 'rm -f "$_ia_tmp"' EXIT
        trap 'rm -f "$_ia_tmp"; exit 130' INT
        trap 'rm -f "$_ia_tmp"; exit 143' TERM

        info "Downloading from ${TARBALL_URL}..."

        if ! download "$TARBALL_URL" "$TARBALL" 2>/dev/null; then
            # Fallback: try without version suffix
            TARBALL_URL="${RELEASE_URL}/actower.tar.gz"
            if ! download "$TARBALL_URL" "$TARBALL" 2>/dev/null; then
                die "Failed to download release. Check your internet connection or try:\n  ACTOWER_LOCAL=/path/to/actower sh install.sh"
            fi
        fi

        # Extract tarball. Clear the previous release's skill bundle first: tar
        # extracts OVER the existing tree, so a skill a later release stopped
        # bundling would otherwise linger in share/skills/ (the sync never
        # installs a retired name, but the bundle should be this release's).
        # Same as the ACTOWER_LOCAL branch above, which replaces it wholesale.
        info "Extracting..."
        rm -rf "$ACTOWER_HOME/share/skills" 2>/dev/null || true
        tar -xzf "$TARBALL" -C "$ACTOWER_HOME" --strip-components=1
        rm -f "$_ia_tmp"
        trap - EXIT INT TERM
        unset _ia_tmp
    fi

    # Make scripts executable
    chmod +x "$ACTOWER_HOME/bin/actower"
    chmod +x "$ACTOWER_HOME/libexec/actower-core.bash"
    chmod +x "$ACTOWER_HOME/lib/"*.sh 2>/dev/null || true

    # Create license placeholder files (empty = free tier)
    touch "$ACTOWER_HOME/license.key"
    chmod 600 "$ACTOWER_HOME/license.key"

    success "Files installed to $ACTOWER_HOME"
}

# Detect user's shell
detect_shell() {
    # Check SHELL env var first
    case "$SHELL" in
        */zsh)  echo "zsh" ;;
        */bash) echo "bash" ;;
        */fish) echo "fish" ;;
        *)
            # Fallback: check what exists
            if [ -f "$HOME/.zshrc" ]; then
                echo "zsh"
            elif [ -f "$HOME/.bashrc" ]; then
                echo "bash"
            else
                echo "bash"  # Default
            fi
            ;;
    esac
}

# Get shell config file
get_shell_config() {
    shell="$1"
    case "$shell" in
        zsh)
            if [ -f "$HOME/.zshrc" ]; then
                echo "$HOME/.zshrc"
            else
                echo "$HOME/.zprofile"
            fi
            ;;
        bash)
            if [ -f "$HOME/.bashrc" ]; then
                echo "$HOME/.bashrc"
            elif [ -f "$HOME/.bash_profile" ]; then
                echo "$HOME/.bash_profile"
            else
                echo "$HOME/.profile"
            fi
            ;;
        fish)
            echo "$HOME/.config/fish/config.fish"
            ;;
    esac
}

# ── Shell-config (rc) block ────────────────────────────────────────────
# The installer owns exactly one thing in a shell rc file: this three-line
# block (preceded by the blank line it appends before it), written only for
# the DEFAULT home:
#
#     # Agent Control Tower
#     export ACTOWER_HOME="<home>"
#     export PATH="$ACTOWER_HOME/bin:$PATH"          (fish: set -gx PATH ...)
#
# A custom ACTOWER_HOME (a smoke-test home, a second side-by-side install)
# never touches the rc file: a block for it would make every new terminal use
# the test home instead of the real one. Uninstall removes only a block whose
# export names the home being uninstalled — never other lines that merely
# mention ACTOWER_HOME (user-written exports, a second install's block).
RC_BLOCK_MARKER="# Agent Control Tower"
RC_PATH_LINE_SH='export PATH="$ACTOWER_HOME/bin:$PATH"'
RC_PATH_LINE_FISH='set -gx PATH $ACTOWER_HOME/bin $PATH'

# Echo a canonical absolute form of a directory path, for COMPARING homes:
# a leading ~ / $HOME / ${HOME} is expanded, trailing slashes are dropped and
# symlinks are resolved (pwd -P) on the deepest ancestor that exists, so a
# not-yet-created default home still compares equal. Never fails.
_canon_path() {
    _cp="$1"
    # Prefixes live in a variable: quote handling inside a double-quoted
    # ${var#'...'} differs between bash and dash.
    for _cp_pfx in '~' '$HOME' '${HOME}'; do
        case "$_cp" in
            "$_cp_pfx")   _cp="$HOME"; break ;;
            "$_cp_pfx"/*) _cp="$HOME/${_cp#"$_cp_pfx"/}"; break ;;
        esac
    done
    unset _cp_pfx
    case "$_cp" in
        /*) ;;
        *)  _cp="$(pwd -P)/$_cp" ;;
    esac
    # Drop trailing slashes (but keep a bare "/").
    while :; do
        case "$_cp" in
            /) break ;;
            */) _cp="${_cp%/}" ;;
            *) break ;;
        esac
    done
    # Walk up to the deepest existing directory, resolve it, re-append the rest.
    _cp_dir="$_cp"
    _cp_rest=""
    while [ ! -d "$_cp_dir" ]; do
        _cp_rest="/${_cp_dir##*/}$_cp_rest"
        _cp_dir="${_cp_dir%/*}"
        [ -n "$_cp_dir" ] || { _cp_dir="/"; break; }
    done
    _cp_real=$(CDPATH='' cd -- "$_cp_dir" 2>/dev/null && pwd -P) || _cp_real=""
    if [ -n "$_cp_real" ]; then
        [ "$_cp_real" = "/" ] && _cp_real=""
        _cp="$_cp_real$_cp_rest"
        [ -n "$_cp" ] || _cp="/"
    fi
    printf '%s\n' "$_cp"
    unset _cp _cp_dir _cp_rest _cp_real
}

# True when ACTOWER_HOME is the default home ($HOME/.actower), compared after
# resolving ~, trailing slashes and symlinks on both sides.
_is_default_home() {
    [ "$(_canon_path "$ACTOWER_HOME")" = "$(_canon_path "$HOME/.actower")" ]
}

# Die unless ACTOWER_HOME is safe to create, chmod 700 and rm -rf: never "/",
# never $HOME itself and never an ancestor of it. ACTOWER_HOME='~' or '$HOME'
# (the leading-~ expansion above makes those $HOME) or a shell-expanded
# ACTOWER_HOME=$HOME would otherwise turn --uninstall into rm -rf "$HOME".
# Called first thing by install_actower and uninstall_actower.
_refuse_unsafe_home() {
    _us_ah=$(_canon_path "$ACTOWER_HOME")
    _us_why=""
    if [ "$_us_ah" = "/" ]; then
        _us_why="it is the root directory"
    elif [ -n "${HOME:-}" ]; then
        _us_hm=$(_canon_path "$HOME")
        if [ "$_us_ah" = "$_us_hm" ]; then
            _us_why="it is your home directory"
        else
            case "$_us_hm/" in
                "$_us_ah"/*) _us_why="it contains your home directory" ;;
            esac
        fi
    fi
    if [ -n "$_us_why" ]; then
        die "Refusing to use ACTOWER_HOME=$ACTOWER_HOME ($_us_ah): $_us_why. Point ACTOWER_HOME at a dedicated folder, e.g. ~/.actower."
    fi
    unset _us_ah _us_hm _us_why
}

# True when directory $1 holds an actower install (the launcher, the core
# dispatcher or the version stamp). uninstall_actower only rm -rf's a
# directory that passes this, so a mistyped ACTOWER_HOME pointing at some
# other folder is left alone.
_looks_like_install() {
    [ -f "$1/bin/actower" ] || [ -f "$1/libexec/actower-core.bash" ] \
        || [ -f "$1/share/actower/version.txt" ]
}

# Print the line numbers ("N N+1 N+2", one block per output line) of every
# installer-written block in rc file $1 whose export names the home $2
# (already canonical). A block is the marker line followed by EXACTLY the
# installer's export line and PATH line (sh or fish form); anything else —
# a hand-edited block, a user export, another home's block — is not ours.
_rc_block_lines() {
    _rb_rc="$1"
    _rb_home="$2"
    [ -f "$_rb_rc" ] || return 0
    grep -n -x -F "$RC_BLOCK_MARKER" "$_rb_rc" 2>/dev/null | cut -d: -f1 | while read -r _rb_n; do
        _rb_l2=$(sed -n "$((_rb_n + 1))p" "$_rb_rc")
        _rb_l3=$(sed -n "$((_rb_n + 2))p" "$_rb_rc")
        case "$_rb_l2" in
            'export ACTOWER_HOME="'*'"') ;;
            *) continue ;;
        esac
        _rb_v="${_rb_l2#export ACTOWER_HOME=\"}"
        _rb_v="${_rb_v%\"}"
        case "$_rb_v" in *\"*|"") continue ;; esac
        [ "$_rb_l3" = "$RC_PATH_LINE_SH" ] || [ "$_rb_l3" = "$RC_PATH_LINE_FISH" ] || continue
        [ "$(_canon_path "$_rb_v")" = "$_rb_home" ] || continue
        printf '%s %s %s\n' "$_rb_n" "$((_rb_n + 1))" "$((_rb_n + 2))"
    done
    unset _rb_rc _rb_home _rb_n _rb_l2 _rb_l3 _rb_v
}

# Print "N:value" for every line of rc file $1 that SETS ACTOWER_HOME —
# `export ACTOWER_HOME=…` (sh/zsh/bash, and the installer's own fish line) or
# `set -gx ACTOWER_HOME …` (fish) — with surrounding quotes stripped. A quoted
# value ends at its closing quote and an unquoted one at the first blank, so a
# trailing `  # comment` is not part of the value. Plain [ \t] rather than
# [[:space:]]: mawk (Debian's awk) has no POSIX classes.
_rc_home_setters() {
    [ -f "$1" ] || return 0
    awk '
        /^[ \t]*export[ \t]+ACTOWER_HOME=/ {
            v = $0; sub(/^[ \t]*export[ \t]+ACTOWER_HOME=/, "", v)
        }
        /^[ \t]*set[ \t]+-[A-Za-z]+[ \t]+ACTOWER_HOME[ \t]/ {
            v = $0; sub(/^[ \t]*set[ \t]+-[A-Za-z]+[ \t]+ACTOWER_HOME[ \t]+/, "", v)
        }
        v != "" {
            q = sprintf("%c", 39)
            c = substr(v, 1, 1)
            if ((c == "\"" || c == q) && (e = index(substr(v, 2), c)) > 0)
                v = substr(v, 2, e - 1)
            else {
                sub(/[ \t]+#.*$/, "", v)
                sub(/[ \t]+$/, "", v)
            }
            print NR ":" v
            v = ""
        }
    ' "$1" 2>/dev/null
}

# Warn about every line of rc file $1 AFTER line $3 that sets ACTOWER_HOME to
# something other than the home $2 (canonical): the last such line is what a
# new terminal uses. Warn-only — the file is never edited here.
_warn_other_homes() {
    _rc_home_setters "$1" | while IFS= read -r _wo_line; do
        _wo_n="${_wo_line%%:*}"
        _wo_v="${_wo_line#*:}"
        [ "$_wo_n" -gt "$3" ] || continue
        if [ "$(_canon_path "$_wo_v")" != "$2" ]; then
            warn "line $_wo_n of $1 sets ACTOWER_HOME to $_wo_v, not $ACTOWER_HOME — new terminals will use that home"
        fi
    done
}

# Print the line numbers (sorted, one per line) in rc file $1 that mention the
# home $2 (canonical; $3 = the home as given): its installer block, lines that
# set ACTOWER_HOME to it, and lines naming either path as a WHOLE path — the
# character after it must not continue a file name, so /x/.act never matches
# /x/.actower or /x/.act2, and the one before it must not be part of a longer
# path. Read-only.
_rc_mention_lines() {
    [ -f "$1" ] || return 0
    {
        _rc_block_lines "$1" "$2" | tr ' ' '\n'
        # `if`, not `[ … ] && printf`: under install.sh's set -e a loop whose
        # last test is false fails the pipeline and aborts this group before
        # the awk below runs.
        _rc_home_setters "$1" | while IFS= read -r _ml_line; do
            if [ "$(_canon_path "${_ml_line#*:}")" = "$2" ]; then
                printf '%s\n' "${_ml_line%%:*}"
            fi
        done
        awk -v p1="$3" -v p2="$2" '
            function hit(s, p,   i, off, before, after) {
                if (p == "") return 0
                off = 0
                while ((i = index(substr(s, off + 1), p)) > 0) {
                    i += off
                    before = (i > 1) ? substr(s, i - 1, 1) : ""
                    after = substr(s, i + length(p), 1)
                    if (before !~ /[A-Za-z0-9._\/~-]/ && after !~ /[A-Za-z0-9._-]/) return 1
                    off = i
                }
                return 0
            }
            hit($0, p1) || hit($0, p2) { print NR }
        ' "$1" 2>/dev/null
    } | sort -n -u
}

# The two lines that put $ACTOWER_HOME/bin on PATH for shell type $1 — the
# same text the installer writes for the default home. The home is written
# raw inside "…": a home containing " $ ` or \ is not escaped here, because
# _rc_block_lines reads the block back by that exact text (pre-existing; such
# a $HOME is not a real-world shape).
_rc_path_lines() {
    printf 'export ACTOWER_HOME="%s"\n' "$ACTOWER_HOME"
    case "$1" in
        fish) printf '%s\n' "$RC_PATH_LINE_FISH" ;;
        *)    printf '%s\n' "$RC_PATH_LINE_SH" ;;
    esac
}

# The command that runs THIS install without PATH. A custom home must also
# carry ACTOWER_HOME: libexec/actower-core.bash defaults it to ~/.actower, so a
# bare full path would run this home's code against the default home's config,
# logs and venv.
_run_cmd() {
    if _is_default_home; then
        printf '%s\n' "$(_shq "$ACTOWER_HOME/bin/actower")"
    else
        printf 'ACTOWER_HOME="%s" %s\n' "$(_dq_escape "$ACTOWER_HOME")" "$(_shq "$ACTOWER_HOME/bin/actower")"
    fi
}

# Echo $1 double-quoted when it holds anything a shell would split or expand
# (a home with a space), so a printed command can be pasted as is.
_shq() {
    case "$1" in
        *[!A-Za-z0-9_./+@%:,=-]*) printf '"%s"' "$(_dq_escape "$1")" ;;
        *) printf '%s' "$1" ;;
    esac
}

# Echo $1 with the characters that stay special inside "…" (\ " $ `)
# backslash-escaped, so a printed "…" pastes back as the same string.
_dq_escape() {
    printf '%s' "$1" | sed 's/[\\"$`]/\\&/g'
}

# Tell the user how to run an install whose PATH the installer did not touch.
_print_run_hint() {
    printf "    Run it by full path:  %s\n" "$(_run_cmd)"
    printf "    To put it on PATH, add these two lines to %s:\n" "$SHELL_CONFIG"
    _rc_path_lines "$SHELL_TYPE" | sed 's/^/      /'
}

# add_to_path found the default home already set up (on PATH, our block, or a
# user's own lines) and writes nothing. Warn — never edit — when a line that
# wins over it sets ACTOWER_HOME to another home: anything after our last
# block, or anywhere when there is no block. This is the rc shape the pre-4a-6a
# installer left behind (real block, then a smoke-test home's block below it).
_warn_rc_overrides() {
    [ -f "$SHELL_CONFIG" ] || return 0
    _wr_home=$(_canon_path "$ACTOWER_HOME")
    _wr_after=$(_rc_block_lines "$SHELL_CONFIG" "$_wr_home" | tail -n 1 | cut -d' ' -f2)
    _warn_other_homes "$SHELL_CONFIG" "$_wr_home" "${_wr_after:-0}"
    unset _wr_home _wr_after
}

# How add_to_path left PATH, read by print_completion:
#   added | configured | on-path | user-config | custom-home | no-path
PATH_RESULT=""

# Add to PATH
add_to_path() {
    info "Configuring PATH..."

    SHELL_TYPE=$(detect_shell)
    SHELL_CONFIG=$(get_shell_config "$SHELL_TYPE")

    # A custom home never touches the shell config (see RC_BLOCK_MARKER above).
    if ! _is_default_home; then
        PATH_RESULT="custom-home"
        printf "  ${GREEN}✓${NC} Custom ACTOWER_HOME (%s): %s left unchanged\n" "$ACTOWER_HOME" "$SHELL_CONFIG"
        _print_run_hint
        export ACTOWER_HOME="$ACTOWER_HOME"
        return 0
    fi

    # --no-path: the user asked us not to edit any shell config.
    if [ -n "${NO_PATH_EDIT:-}" ]; then
        PATH_RESULT="no-path"
        printf "  ${GREEN}✓${NC} --no-path: %s left unchanged\n" "$SHELL_CONFIG"
        _print_run_hint
        export ACTOWER_HOME="$ACTOWER_HOME"
        return 0
    fi

    # Check if already in PATH
    case ":$PATH:" in
        *":$ACTOWER_HOME/bin:"*)
            PATH_RESULT="on-path"
            printf "  ${GREEN}✓${NC} Already in PATH\n"
            _warn_rc_overrides
            return 0
            ;;
    esac

    # Our own block for this home is already there: never add a second one.
    if [ -n "$(_rc_block_lines "$SHELL_CONFIG" "$(_canon_path "$ACTOWER_HOME")")" ]; then
        PATH_RESULT="configured"
        printf "  ${GREEN}✓${NC} Already configured in %s\n" "$SHELL_CONFIG"
        _warn_rc_overrides
        return 0
    fi

    # The user (or another install) already manages ACTOWER_HOME in this file:
    # leave it alone, as before — but say so when it points somewhere else,
    # because new terminals will then use THAT home, not this one.
    if [ -f "$SHELL_CONFIG" ] && grep -q "ACTOWER_HOME" "$SHELL_CONFIG" 2>/dev/null; then
        PATH_RESULT="user-config"
        printf "  ${GREEN}✓${NC} %s already sets ACTOWER_HOME — left unchanged\n" "$SHELL_CONFIG"
        _warn_rc_overrides
        return 0
    fi

    # Add PATH configuration. The blank line separates our block; uninstall
    # removes it again. If the rc did not end in a newline, this echo instead
    # terminates the user's last line, and that newline stays after uninstall
    # (the file then ends in one, as a text file should — harmless).
    echo "" >> "$SHELL_CONFIG"
    {
        echo "$RC_BLOCK_MARKER"
        _rc_path_lines "$SHELL_TYPE"
    } >> "$SHELL_CONFIG"

    PATH_RESULT="added"
    printf "  ${GREEN}✓${NC} Added to %s (use --no-path to skip this)\n" "$SHELL_CONFIG"

    # Export for current session
    export ACTOWER_HOME="$ACTOWER_HOME"
    export PATH="$ACTOWER_HOME/bin:$PATH"
}

# Echo the version actually ON DISK ($ACTOWER_HOME/share/actower/version.txt),
# falling back to $ACTOWER_VERSION when that file is missing or empty. Shared by
# the marker write and the install summary so the two can never disagree.
_on_disk_version() {
    _odv=""
    if [ -r "$ACTOWER_HOME/share/actower/version.txt" ]; then
        _odv=$(cat "$ACTOWER_HOME/share/actower/version.txt" 2>/dev/null) || _odv=""
    fi
    [ -n "$_odv" ] || _odv="$ACTOWER_VERSION"
    printf '%s\n' "$_odv"
    unset _odv
}

# Write the install marker — the record of HOW this machine got actower, and the
# source of truth for `actower doctor`, /api/version's install_method, the
# outbound telemetry headers, and the CLI's transparent re-exec into the copy the
# user actually installed. This is the authoritative `curl` writer (the brew
# formula's post_install writes method="brew"; `actower setup` only fills a
# MISSING marker).
#
# The shape + the atomic write live in one pure Python function so tests can
# exercise them against a temp path — never a real home. See lib/install_marker.py.
#
# Fail-soft by design: a marker that can't be written costs diagnostics quality,
# never a working install, so this warns and returns instead of calling die.
write_install_marker() {
    if [ -z "$PYTHON_CMD" ]; then
        warn "Skipping install marker (no python3 resolved)"
        return 0
    fi
    # Record what is actually ON DISK, not the installer's own default.
    # $ACTOWER_VERSION falls back to a hardcoded literal at the top of this file,
    # which the --local path never updates — it copies version.txt verbatim. The
    # two agree today and would drift on the next bump, leaving doctor reporting a
    # version this install does not have. version.txt is in place by now.
    # POSIX sh has no `local`, so these are function-scoped only by convention —
    # prefixed to keep them out of the installer's shared namespace, and unset
    # before returning.
    _im_version=$(_on_disk_version)
    if "$PYTHON_CMD" -c '
import sys
sys.path.insert(0, sys.argv[1])
from install_marker import write_marker
write_marker(path=sys.argv[2], method="curl", version=sys.argv[3], cli_path=sys.argv[4])
' "$ACTOWER_HOME/lib" "$ACTOWER_HOME/install-marker.json" \
        "$_im_version" "$ACTOWER_HOME/bin/actower" 2>/dev/null; then
        success "Install marker written (curl, v${_im_version})"
    else
        warn "Could not write install marker (non-fatal; 'actower doctor' will say so)"
    fi
    unset _im_version
    return 0
}

# Run setup
run_setup() {
    info "Running initial setup..."

    # Run actower setup if available.
    # ACTOWER_FROM_INSTALLER tells `actower setup` to skip its standalone
    # "Setup complete! Run 'actower monitor'..." epilogue — the installer
    # owns the final getting-started banner (printed after Web UI deps +
    # API endpoint config), so setup's own line would be premature here.
    if [ -x "$ACTOWER_HOME/bin/actower" ]; then
        ACTOWER_FROM_INSTALLER=1 "$ACTOWER_HOME/bin/actower" setup
    else
        # Manual setup fallback
        mkdir -p "$ACTOWER_HOME/logs" "$ACTOWER_HOME/captures"

        # Create default config if not exists
        if [ ! -f "$ACTOWER_HOME/config.json" ]; then
            cat > "$ACTOWER_HOME/config.json" << 'EOF'
{
    "captures_enabled": false,
    "retention_days": 30,
    "redaction_mode": "redact"
}
EOF
        fi
        success "Created default configuration"
    fi

    # Set up web UI venv (optional, will skip if web files not installed)
    setup_web_venv

    # Write api_endpoint to config.json based on stage so the CLI's license
    # validation hits the right backend. The compiled-in LICENSE_DEFAULT_API
    # default is PROD (repo source; stamped per-stage into the tarball by
    # release.sh), so prod installs are already correct without this. It stays
    # load-bearing for dev/qa installs: it writes the dev URL so a dev/qa CLI
    # validates against the dev backend instead of the prod-stamped default.
    set_api_endpoint
}

# Configure the API endpoint in config.json based on ACTOWER_STAGE
set_api_endpoint() {
    case "$ACTOWER_STAGE" in
        prod)
            API_ENDPOINT="https://api.actower.io"
            ;;
        *)
            # dev and qa share the dev API (qa frontend hits dev backend by design)
            API_ENDPOINT="https://l3lz0ov2re.execute-api.us-west-2.amazonaws.com/api"
            ;;
    esac

    if [ ! -f "$ACTOWER_HOME/config.json" ]; then
        return 0  # Setup hasn't created config yet — nothing to update
    fi

    "$PYTHON_CMD" -c "
import json, sys
config_file = '$ACTOWER_HOME/config.json'
api_endpoint = '$API_ENDPOINT'
try:
    with open(config_file) as f:
        c = json.load(f)
except Exception:
    c = {}
c['api_endpoint'] = api_endpoint
with open(config_file, 'w') as f:
    json.dump(c, f, indent=2)
" 2>/dev/null && success "API endpoint set: $API_ENDPOINT (stage: $ACTOWER_STAGE)"
}

# Install / keep current the bundled end-user skills in ~/.claude/skills/ (Claude
# Code only). AP-52EC79CF: the body MOVED to libexec/actower-skills.sh so the
# CLI's first command after a version change (`actower-core.bash:
# _sync_skills_if_version_changed` — what Homebrew users get, since the formula
# never touches skills) runs the SAME rules:
#   - first-time install → copy + record provenance (SHA-256) in the manifest
#   - ACTower's own UNMODIFIED copy with an older version → updated, no prompt
#     (piped `curl … | sh` included)
#   - a copy the user edited (or of unknown provenance) → never overwritten;
#     reported, with how to take the new one
#   - --upgrade-skills → back up edited copies, then replace
#   - --skip-skills / config skills.auto_install=false → skip entirely
#   - a skill ACTower no longer bundles → its unedited copy removed, an edited
#     one kept and named once (the module's _as_retire, every install path)
# All operations are offline. ACTOWER_SKILLS_LIB is a test seam.
install_skills() {
    SKILLS_LIB="${ACTOWER_SKILLS_LIB:-$ACTOWER_HOME/libexec/actower-skills.sh}"
    _skills_ver=$(cat "$ACTOWER_HOME/share/actower/version.txt" 2>/dev/null || true)

    # CLI-flag opt-out. The stamp is still written, so the CLI's first run does
    # not install what the user skipped for this version.
    if [ "${SKIP_SKILLS:-0}" = "1" ]; then
        info "Skills install skipped (--skip-skills)."
        if [ -r "$SKILLS_LIB" ]; then
            # shellcheck disable=SC1090
            . "$SKILLS_LIB"
            command -v actower_skills_stamp >/dev/null 2>&1 \
                && actower_skills_stamp "$ACTOWER_HOME" "$_skills_ver"
        fi
        return 0
    fi

    if [ ! -r "$SKILLS_LIB" ]; then
        warn "Missing $SKILLS_LIB — skipping skills."
        warn "Re-run the installer to repair the install."
        return 0
    fi
    # shellcheck disable=SC1090
    . "$SKILLS_LIB"
    if ! command -v actower_sync_skills >/dev/null 2>&1; then
        warn "$SKILLS_LIB is incomplete — skipping skills. Re-run the installer to repair the install."
        return 0
    fi

    if [ "${UPGRADE_SKILLS:-0}" = "1" ]; then
        actower_sync_skills --mode installer --upgrade --src "$ACTOWER_HOME/share/skills" \
            --home "$ACTOWER_HOME" --version "$_skills_ver" --python "${PYTHON_CMD:-}"
    else
        actower_sync_skills --mode installer --src "$ACTOWER_HOME/share/skills" \
            --home "$ACTOWER_HOME" --version "$_skills_ver" --python "${PYTHON_CMD:-}"
    fi
    return 0
}

# Set up Python venv for web UI (also used by `actower ecosystem`).
# The name is historical — the venv now covers both features. If you ever
# refactor a minimal install that skips lib/web, split this into a
# setup_python_venv() so `actower ecosystem` still gets jinja2/pyyaml.
#
# v1.2.16 (P0-2): the body of this function MOVED to libexec/actower-venv.sh so
# the CLI's own first-run self-heal (`actower-core.bash:_ensure_venv`, which
# exists because Homebrew's post_install sandbox cannot write the real home) runs
# the SAME implementation rather than a second copy that drifts. Everything a
# curl user sees is unchanged: `--mode installer` reproduces this function's
# previous output and its fail-soft contract line for line.
#
# WHY SOURCE IT INSTEAD OF CALLING `actower setup`: delegating to the installed
# binary would drag the install-marker re-exec router (_maybe_reexec) into the
# middle of an install, where it could hand venv creation to a DIFFERENT install
# on a dual-install box. Sourcing keeps install.sh doing the work in its own
# process.
#
# The lib/web guard below deliberately stays HERE rather than moving into the
# shared module: on a brew machine $ACTOWER_HOME/lib/web never exists (the code
# lives in the Cellar), so a lifted guard would silently make the CLI path a
# no-op on exactly the machines the CLI path exists for.
setup_web_venv() {
    # Check if web files exist
    if [ ! -d "$ACTOWER_HOME/lib/web" ]; then
        return 0  # Web UI not installed, skip
    fi

    info "Setting up Web UI dependencies..."

    # install_actower() has already unpacked the tree by the time run_setup()
    # reaches us (it also invokes "$ACTOWER_HOME/bin/actower setup" just above),
    # so the shipped module is on disk. ACTOWER_VENV_LIB is a test seam.
    VENV_LIB="${ACTOWER_VENV_LIB:-$ACTOWER_HOME/libexec/actower-venv.sh}"
    if [ ! -r "$VENV_LIB" ]; then
        warn "Missing $VENV_LIB — skipping Web UI dependencies."
        warn "Re-run the installer to repair the install."
        return 0
    fi
    # shellcheck disable=SC1090
    . "$VENV_LIB"

    # $PYTHON_CMD was resolved by check_deps to an interpreter that IS 3.11.
    actower_ensure_venv --mode installer --python "$PYTHON_CMD" "$ACTOWER_HOME/.venv"
}

# Uninstall
uninstall_actower() {
    info "Uninstalling Agent Control Tower..."

    # Before anything else, and before the prompt: a y must never reach
    # rm -rf "$HOME" or rm -rf /.
    _refuse_unsafe_home

    if [ ! -d "$ACTOWER_HOME" ]; then
        warn "Agent Control Tower is not installed at $ACTOWER_HOME"
        return 0
    fi
    if ! _looks_like_install "$ACTOWER_HOME"; then
        warn "$ACTOWER_HOME does not look like an Agent Control Tower install (no bin/actower, libexec/actower-core.bash or share/actower/version.txt) — nothing removed. If it really is one, delete it by hand."
        return 0
    fi

    # Confirm uninstall
    printf "This will remove:\n"
    printf "  - $ACTOWER_HOME (all files, logs, and web venv)\n"
    if _is_default_home; then
        printf "  - the '%s' PATH block the installer added to your shell config\n" "$RC_BLOCK_MARKER"
    else
        printf "  (custom ACTOWER_HOME: your shell config is not changed)\n"
    fi
    # As of M3 that directory also holds ecosystem identity material, and unlike
    # everything else on the list it is NOT restored by reinstalling: a
    # regenerated ed25519 key has a different fingerprint, so every outstanding
    # invite's `kid` stops matching, every member's trusted-founder record goes
    # stale, and deploy keys already registered on GitHub can no longer be
    # revoked through this tool. The upgrade path never touches it (it removes
    # $ACTOWER_HOME/libexec/ecosystem, the vendored CODE, which is a different
    # tree) — only this explicit uninstall does. Naming it is the difference
    # between a reversible action and a silent one.
    if [ -d "$ACTOWER_HOME/ecosystem" ]; then
        printf "\n"
        printf "  ${YELLOW}!${NC} This includes your ecosystem signing identity and trusted founders:\n"
        printf "      $ACTOWER_HOME/ecosystem/\n"
        printf "      Reinstalling does NOT restore them. A new key has a new fingerprint,\n"
        printf "      so outstanding invites stop verifying and issued deploy keys can no\n"
        printf "      longer be revoked with this tool. Back that folder up first if you\n"
        printf "      have ever run 'actower ecosystem invite'.\n"
    fi
    printf "\n"
    printf "Continue? [y/N] "
    read -r response
    case "$response" in
        [yY][eE][sS]|[yY])
            ;;
        *)
            echo "Aborted."
            exit 0
            ;;
    esac

    # Work out the rc lines BEFORE the directory goes. Every path in the rc
    # file is compared after symlink resolution, and once `rm -rf` has removed
    # a symlinked ~/.actower, a block naming "$HOME/.actower" no longer
    # resolves to the target this home resolves to — it would silently stop
    # matching. Resolve both sides while the link is still there.
    _un_home=$(_canon_path "$ACTOWER_HOME")
    SHELL_TYPE=$(detect_shell)
    SHELL_CONFIG=$(get_shell_config "$SHELL_TYPE")
    _un_default=""
    _un_lines=""
    if _is_default_home; then
        _un_default=1
        _un_lines=$(_rc_block_lines "$SHELL_CONFIG" "$_un_home")
    else
        _un_raw="$ACTOWER_HOME"
        while :; do
            case "$_un_raw" in /) break ;; */) _un_raw="${_un_raw%/}" ;; *) break ;; esac
        done
        _un_lines=$(_rc_mention_lines "$SHELL_CONFIG" "$_un_home" "$_un_raw")
        unset _un_raw
    fi

    # Scheduled Ops tasks live OUTSIDE the home (LaunchAgents, systemd user
    # units, the crontab): unload them first, or they keep firing a deleted venv.
    _remove_ops_schedule_units

    # Remove directory
    rm -rf "$ACTOWER_HOME"
    success "Removed $ACTOWER_HOME"

    # Shell config: only the installer's own block, and only for the default home.
    if [ -z "$_un_default" ]; then
        _uninstall_report_rc_lines "$_un_lines"
    elif [ -f "$SHELL_CONFIG" ]; then
        _uninstall_remove_rc_block "$_un_lines"
    fi
    unset _un_home _un_default _un_lines

    success "Agent Control Tower has been uninstalled"
}

# Uninstall of a CUSTOM home: never edit the rc file. Name the lines that
# mention that home ($1: line numbers from _rc_mention_lines — its installer
# block, lines setting ACTOWER_HOME to it, lines naming its path as a whole
# path) so the user can remove them by hand.
_uninstall_report_rc_lines() {
    _ur_lines="$1"
    printf "  Custom ACTOWER_HOME: %s was not changed.\n" "$SHELL_CONFIG"
    [ -f "$SHELL_CONFIG" ] || { unset _ur_lines; return 0; }
    if [ -n "$_ur_lines" ]; then
        printf "  These lines in %s mention %s — remove them if you no longer need them:\n" "$SHELL_CONFIG" "$ACTOWER_HOME"
        for _ur_n in $_ur_lines; do
            printf "    %s: %s\n" "$_ur_n" "$(sed -n "${_ur_n}p" "$SHELL_CONFIG")"
        done
    fi
    unset _ur_lines _ur_n
}

# Uninstall of the DEFAULT home: delete exactly the installer-written block(s)
# for that home ($1: _rc_block_lines output, computed before the home was
# removed), plus the blank line the installer appended before each.
# Other lines — user exports, "# notes" mentioning ACTOWER_HOME, a second
# install's block — are kept. The file is rewritten in place (cat >), so a
# symlinked rc keeps its link and the target's permissions.
_uninstall_remove_rc_block() {
    _ub_blocks="$1"
    if [ -z "$_ub_blocks" ]; then
        printf "  No Agent Control Tower PATH block in %s — left unchanged.\n" "$SHELL_CONFIG"
        unset _ub_blocks
        return 0
    fi
    _ub_del=""
    for _ub_n in $_ub_blocks; do
        _ub_del="$_ub_del $_ub_n"
    done
    # The blank line the installer wrote just before each marker.
    for _ub_n in $(printf '%s\n' "$_ub_blocks" | cut -d' ' -f1); do
        _ub_p=$((_ub_n - 1))
        if [ "$_ub_p" -ge 1 ] && [ -z "$(sed -n "${_ub_p}p" "$SHELL_CONFIG")" ]; then
            _ub_del="$_ub_del $_ub_p"
        fi
    done
    _ub_tmp=$(mktemp "${TMPDIR:-/tmp}/actower-rc.XXXXXX") || {
        warn "Could not create a temp file; $SHELL_CONFIG left unchanged"
        unset _ub_blocks _ub_del _ub_n _ub_p
        return 0
    }
    if ! awk -v dels="$_ub_del" '
        BEGIN { n = split(dels, a, " "); for (i = 1; i <= n; i++) d[a[i]] = 1 }
        !(NR in d)
    ' "$SHELL_CONFIG" > "$_ub_tmp"; then
        rm -f "$_ub_tmp"
        warn "Could not update $SHELL_CONFIG; remove the '$RC_BLOCK_MARKER' block by hand"
    elif cat "$_ub_tmp" > "$SHELL_CONFIG"; then
        rm -f "$_ub_tmp"
        success "Removed the Agent Control Tower PATH block from $SHELL_CONFIG"
    else
        # `cat >` truncated the rc before it failed (disk full, I/O error), so
        # the temp file may now be the only complete copy: keep it.
        warn "Could not rewrite $SHELL_CONFIG — it may be incomplete. The intended contents are in $_ub_tmp; copy that file over it."
    fi
    if grep -q "ACTOWER_HOME" "$SHELL_CONFIG" 2>/dev/null; then
        printf "  Other lines mentioning ACTOWER_HOME were left as they are:\n"
        grep -n "ACTOWER_HOME" "$SHELL_CONFIG" | sed 's/^/    /; s/:/: /'
    fi
    unset _ub_blocks _ub_del _ub_n _ub_p _ub_tmp
}

# Show help
show_help() {
    cat << EOF
Agent Control Tower Installer

Usage:
  curl -fsSL https://actower.io/install.sh | bash
  curl -fsSL https://actower.io/install.sh | bash -s -- [options]

Options:
  --help          Show this help message
  --uninstall     Remove Agent Control Tower. For the default home this also
                  removes the "# Agent Control Tower" PATH block the installer
                  added to your shell config — and nothing else in that file.
                  A custom ACTOWER_HOME never edits the shell config.
  --no-path       Do not edit your shell config (.zshrc, .bashrc, config.fish)
                  to put actower on PATH; run it as \$ACTOWER_HOME/bin/actower
                  instead. Always the case for a custom ACTOWER_HOME.
  --version VER   Install specific version (default: $ACTOWER_VERSION)
  --local PATH    Install from local directory instead of downloading
  --skip-skills   Do not install the bundled Claude Code skills
  --upgrade-skills Force-upgrade bundled skills (local edits are backed up first)
  --no-desktop-check
                  Skip the post-install desktop-app (ACTower.app) version check.
                  Use for CI / headless / Docker installs — a terminal can be
                  spoofed, so this is the reliable way to never be prompted.
                  Any flag needs the "-s --" form shown above; with a bare
                  "| bash" pipeline use NO_DESKTOP_CHECK=1 instead.
  --yes, -y       Install missing dependencies (tmux, Python 3.11, bash 4+)
                  without asking. Without it the installer asks once, on the
                  terminal, before running Homebrew (macOS) or apt/dnf/pacman
                  (Linux, via sudo); with no terminal it only lists them.
                  Homebrew itself is never installed.
  --no-deps-install
                  Never install dependencies: list what is missing and stop.

Environment Variables:
  ACTOWER_HOME    Installation directory (default: ~/.actower). Any other home
                  (e.g. a smoke-test home) is installed WITHOUT touching your
                  shell config, so new terminals keep using the default one.
  ACTOWER_VERSION Version to install (default: $ACTOWER_VERSION)
  ACTOWER_LOCAL   Local source directory for development installs
  NO_DESKTOP_CHECK
                  Set to 1 (or any non-empty value except "0") for the same
                  effect as --no-desktop-check. The env-var form is what works
                  with the documented one-liner, which cannot carry flags.
  ACTOWER_INSTALL_YES
                  Set to 1 (or any non-empty value except "0") for the same
                  effect as --yes.

Examples:
  # Standard install
  curl -fsSL https://actower.io/install.sh | bash

  # Install specific version
  curl -fsSL https://actower.io/install.sh | bash -s -- --version 0.2.0

  # Install from local development copy
  ACTOWER_LOCAL=./scripts/agent-control-tower sh install.sh

  # Install without editing your shell config
  curl -fsSL https://actower.io/install.sh | bash -s -- --no-path

  # Uninstall
  curl -fsSL https://actower.io/install.sh | bash -s -- --uninstall

  # CI / headless: never prompt about the desktop app (either form)
  curl -fsSL https://actower.io/install.sh | bash -s -- --no-desktop-check
  curl -fsSL https://actower.io/install.sh | NO_DESKTOP_CHECK=1 bash

  # Scripted: install missing dependencies without the question (either form)
  curl -fsSL https://actower.io/install.sh | bash -s -- --yes
  curl -fsSL https://actower.io/install.sh | ACTOWER_INSTALL_YES=1 bash

EOF
}

# Print completion message
print_completion() {
    echo ""
    echo "=============================================="
    success "Agent Control Tower installed successfully!"
    echo "=============================================="
    echo ""
    # We installed tmux/Python with a Homebrew that is not on this shell's PATH:
    # this run found them because it added brew's bin for itself, but a new
    # terminal will not, and actower looks tmux up on PATH. Homebrew owns that
    # line in the profile, so print it rather than edit the profile ourselves.
    _pc_brew_dir=""
    if [ -n "${DEPS_INSTALLED:-}" ] && [ -n "${DEP_BREW_OFFPATH:-}" ] && [ -n "${DEP_MGR_BIN:-}" ]; then
        _pc_brew_dir=$(dirname "$DEP_MGR_BIN")
        printf "${YELLOW}Homebrew is not on your PATH yet${NC}, so new terminals will not find tmux.\n"
        echo "Add it once with:"
        _pc_sh=$(detect_shell)
        if [ "$_pc_sh" = "fish" ]; then
            printf "     echo '%s shellenv | source' >> %s\n" "$DEP_MGR_BIN" "$(get_shell_config fish)"
        else
            printf "     echo 'eval \"\$(%s shellenv)\"' >> %s\n" "$DEP_MGR_BIN" "$(get_shell_config "$_pc_sh")"
        fi
        unset _pc_sh
        echo ""
    fi
    # python3.11 / tmux were used from a folder that is not on PATH. This run
    # added it for itself; a new terminal will not have it, and `actower setup` /
    # `actower doctor` look both up on PATH. (The installed venv keeps working —
    # it was built from the interpreter's full path.) Printed, never written.
    # DEPS_OFFPATH_DIRS (ensure_deps) survives the post-install re-check. A dir
    # the brew shellenv line above already covers is not repeated.
    for _pc_d in ${DEPS_OFFPATH_DIRS:-}; do
        if [ "$_pc_d" = "$_pc_brew_dir" ]; then
            continue
        fi
        printf "${YELLOW}%s is not on your PATH${NC}; this install used it, but new terminals will not.\n" "$_pc_d"
        echo "Add it once with:"
        if [ "$(detect_shell)" = "fish" ]; then
            printf "     echo 'fish_add_path -a %s' >> %s\n" "$_pc_d" "$(get_shell_config fish)"
        else
            printf "     echo 'export PATH=\"\$PATH:%s\"' >> %s\n" "$_pc_d" "$(get_shell_config "$(detect_shell)")"
        fi
        echo ""
    done
    unset _pc_d _pc_brew_dir
    echo "To get started:"
    echo ""
    # A custom home / --no-path install is not on PATH: show full-path commands.
    # The "source <rc>" step prints only when this terminal does NOT have
    # actower on PATH yet — the rc was edited now (`added`) or already carries
    # the lines this shell hasn't loaded (`configured` / `user-config`) — and
    # names that file. After "Already in PATH" (`on-path`) it says nothing. The
    # steps are numbered by a counter so the list starts at 1 whichever print.
    _pc_cmd="actower"
    _pc_n=0
    case "${PATH_RESULT:-}" in
        custom-home|no-path)
            _pc_cmd=$(_run_cmd)
            _pc_n=$((_pc_n + 1))
            if [ "$PATH_RESULT" = "custom-home" ]; then
                printf "  ${BOLD}%s.${NC} Custom ACTOWER_HOME: your shell config was not changed, so run\n" "$_pc_n"
            else
                printf "  ${BOLD}%s.${NC} --no-path: your shell config was not changed, so run\n" "$_pc_n"
            fi
            echo "     actower by its full path (or add the two lines shown above):"
            echo "     $_pc_cmd"
            echo ""
            ;;
        added|configured|user-config)
            # `configured` / `user-config` are reached only AFTER add_to_path's
            # "Already in PATH" check failed: the rc has the lines, but THIS
            # terminal has not loaded them (a second run without restarting), so
            # `actower doctor` below would be "command not found" without this
            # step (cycle-1 review). Only `added` says the lines were written now.
            _pc_rc="${SHELL_CONFIG:-}"
            [ -n "$_pc_rc" ] || _pc_rc=$(get_shell_config "$(detect_shell)")
            _pc_n=$((_pc_n + 1))
            printf "  ${BOLD}%s.${NC} Restart your shell or run:\n" "$_pc_n"
            echo "     source $_pc_rc"
            if [ "$PATH_RESULT" = "added" ]; then
                echo "     (The PATH lines were added to that file; install with --no-path"
                echo "     to leave your shell config alone.)"
            fi
            echo ""
            unset _pc_rc
            ;;
    esac
    _pc_n=$((_pc_n + 1))
    printf "  ${BOLD}%s.${NC} Verify installation:\n" "$_pc_n"
    echo "     $_pc_cmd doctor"
    echo ""
    _pc_n=$((_pc_n + 1))
    printf "  ${BOLD}%s.${NC} Start monitoring your agents:\n" "$_pc_n"
    echo "     $_pc_cmd monitor --all --classify --active --alert-done"
    echo ""
    _pc_n=$((_pc_n + 1))
    printf "  ${BOLD}%s.${NC} Start the responder (auto-approve safe actions):\n" "$_pc_n"
    echo "     $_pc_cmd responder --auto --alert"
    echo ""
    _pc_n=$((_pc_n + 1))
    printf "  ${BOLD}%s.${NC} Launch the desktop app (macOS):\n" "$_pc_n"
    echo "     $_pc_cmd desktop"
    echo ""
    _pc_n=$((_pc_n + 1))
    printf "  ${BOLD}%s.${NC} Or launch the web dashboard (cross-platform):\n" "$_pc_n"
    echo "     $_pc_cmd web"
    echo ""
    printf "  Run ${GREEN}%s help${NC} for all available commands.\n" "$_pc_cmd"
    unset _pc_cmd _pc_n
    echo ""
    echo "Note: If you run 'actower web' or 'actower desktop' in a foreground"
    echo "      terminal (no background service), restart that process to pick"
    echo "      up this new version."
    echo ""
    echo "Documentation: https://actower.io/docs"
    echo ""
}

# Restart the io.actower.web LaunchAgent so an in-place upgrade takes effect
# immediately. Without this, the running Python backend keeps the OLD code +
# license state in memory until its next process recycle — Settings shows the
# old version and license "last validated" stays stale (v1.2.9-observed).
#
# Gated so it is a clean no-op where it can't/shouldn't run:
#   - non-macOS (no launchd)
#   - launchctl unavailable
#   - the LaunchAgent isn't currently loaded (fresh install; user hasn't set up
#     the desktop/web service yet, OR they run `actower web` in a foreground
#     terminal — that process is theirs to restart)
#   - a custom ACTOWER_HOME (smoke-test / side-by-side install): the one
#     io.actower.web agent belongs to the main install, and recycling it would
#     restart the user's real service for code this install never gave it. A
#     one-line note says so instead.
# A kickstart failure warns but never fails the install (user can run the
# printed command manually).
#
# NOTE: this helper is intentionally duplicated in libexec/actower-core.bash
# (bash) for the `actower login` fire site. install.sh is POSIX sh, curl-piped,
# and must stay self-contained — it cannot source a runtime file. Keep the two
# copies' gate logic in sync. (The custom-home gate is install.sh-only for now.)
_kickstart_web_if_loaded() {
    # No-op on non-macOS
    [ "$(uname -s)" = "Darwin" ] || return 0
    # No-op if launchctl unavailable
    command -v launchctl > /dev/null 2>&1 || return 0
    UID_N=$(id -u)
    # No-op if the LaunchAgent isn't loaded (fresh install; user hasn't set up yet)
    if launchctl list 2>/dev/null | grep -q io.actower.web; then
        if ! _is_default_home; then
            # The desktop app (which owns this agent) does not honour
            # ACTOWER_HOME (desktop/install-paths.js), so the agent always
            # runs the ~/.actower install — never this one.
            info "Custom ACTOWER_HOME: not restarting the Web UI service (io.actower.web) — it runs the default ~/.actower install, not this one."
            return 0
        fi
        info "Restarting Web UI service to load new code..."
        if launchctl kickstart -k "gui/${UID_N}/io.actower.web" 2>/dev/null; then
            info "✓ Web UI service restarted"
        else
            info "⚠ Web UI restart failed — restart it manually if you use the desktop app: launchctl kickstart -k gui/${UID_N}/io.actower.web"
        fi
    fi
    return 0
}

# ── Scheduled Ops tasks: rebuild their units after an install/upgrade ──
# Each scheduled Ops task is a LaunchAgent / systemd user timer / crontab line
# that calls this install's venv python and lib/ by absolute path. After an
# upgrade they must point at the new code, so run `actower autopilot schedule
# sync` (it rewrites every unit from its schedule record). Never fails the
# install: a sync problem is a warning naming the command to run by hand.
#
#   - no schedules (no $ACTOWER_HOME/ops/schedules/*.json): no-op, and no Python
#     is started — a fresh install is untouched;
#   - custom ACTOWER_HOME: no-op with a note (the units run the default
#     ~/.actower install, like the io.actower.web agent above).
#
# Sourceable (ACTOWER_INSTALL_LIB=1) — see tests/test_install_schedule_sync.sh.
_sync_ops_schedules() {
    _so_any=""
    for _so_f in "$ACTOWER_HOME/ops/schedules"/*.json; do
        if [ -f "$_so_f" ]; then
            _so_any=1
            break
        fi
    done
    if [ -z "$_so_any" ]; then
        unset _so_any _so_f
        return 0
    fi
    unset _so_any _so_f
    if ! _is_default_home; then
        info "Custom ACTOWER_HOME: not rebuilding scheduled Ops tasks — their units run the default ~/.actower install, not this one."
        return 0
    fi
    info "Updating scheduled Ops tasks to this version..."
    if _so_out=$("$ACTOWER_HOME/bin/actower" autopilot schedule sync 2>&1); then
        info "✓ Scheduled Ops tasks updated"
    else
        warn "Scheduled Ops tasks could not all be updated. Run this to see why and retry: actower autopilot schedule sync"
        [ -n "$_so_out" ] && printf '%s\n' "$_so_out" | sed 's/^/    /' >&2
    fi
    unset _so_out
    return 0
}

# ── Scheduled Ops tasks: remove their units on uninstall ──
# The units call the default ~/.actower venv by absolute path, so only an
# uninstall of the default home removes them (a custom home's uninstall leaves
# the default install's schedules alone). Only ACTower's own units are touched:
# io.actower.ops.*.plist, actower-ops-*.timer/.service, and the lines between
# "# actower-ops <id> begin" / "end" markers in the crontab (left as is when a
# begin marker has no end — the rest of the crontab would go with it).
# Never fails the uninstall. Sourceable (ACTOWER_INSTALL_LIB=1).
_remove_ops_schedule_units() {
    _is_default_home || return 0
    _ru_n=0
    _ru_agents="${ACTOWER_SCHEDULES_LAUNCHAGENTS_DIR:-$HOME/Library/LaunchAgents}"
    for _ru_p in "$_ru_agents"/io.actower.ops.*.plist; do
        [ -f "$_ru_p" ] || continue
        if command -v launchctl >/dev/null 2>&1; then
            launchctl bootout "gui/$(id -u)/$(basename "$_ru_p" .plist)" >/dev/null 2>&1 || true
        fi
        rm -f "$_ru_p"
        _ru_n=$((_ru_n + 1))
    done
    _ru_sd=""
    _ru_units="${ACTOWER_SCHEDULES_SYSTEMD_DIR:-$HOME/.config/systemd/user}"
    for _ru_t in "$_ru_units"/actower-ops-*.timer; do
        [ -f "$_ru_t" ] || continue
        if command -v systemctl >/dev/null 2>&1; then
            systemctl --user disable --now "$(basename "$_ru_t")" >/dev/null 2>&1 || true
        fi
        rm -f "$_ru_t" "${_ru_t%.timer}.service"
        _ru_sd=1
        _ru_n=$((_ru_n + 1))
    done
    if [ -n "$_ru_sd" ] && command -v systemctl >/dev/null 2>&1; then
        systemctl --user daemon-reload >/dev/null 2>&1 || true
    fi
    if command -v crontab >/dev/null 2>&1 && _ru_cron=$(crontab -l 2>/dev/null); then
        # Same markers the Python backend recognises (trailing blanks or a
        # CR from a hand edit included).
        _ru_begin=$(printf '%s\n' "$_ru_cron" | grep -c '^# actower-ops [^ ][^ ]* begin[[:space:]]*$' || true)
        _ru_end=$(printf '%s\n' "$_ru_cron" | grep -c '^# actower-ops [^ ][^ ]* end[[:space:]]*$' || true)
        if [ "${_ru_begin:-0}" -gt 0 ] && [ "$_ru_begin" = "$_ru_end" ]; then
            if printf '%s\n' "$_ru_cron" | awk '
                /^# actower-ops [^ ]+ begin[[:space:]]*$/ { skip = 1; next }
                skip && /^# actower-ops [^ ]+ end[[:space:]]*$/ { skip = 0; next }
                !skip { print }' | crontab - >/dev/null 2>&1; then
                _ru_n=$((_ru_n + _ru_begin))
            else
                warn "Could not remove the scheduled Ops task lines from your crontab — remove the '# actower-ops' blocks with: crontab -e"
            fi
        elif [ "${_ru_begin:-0}" -gt 0 ]; then
            warn "Your crontab has an '# actower-ops' block without its end line — remove the '# actower-ops' lines by hand with: crontab -e"
        fi
    fi
    if [ "$_ru_n" -gt 0 ]; then
        success "Removed $_ru_n scheduled Ops task unit(s)"
    fi
    unset _ru_n _ru_agents _ru_p _ru_sd _ru_units _ru_t _ru_cron _ru_begin _ru_end
    return 0
}

# ── Dual-install PATH-shadowing detection ─────────────────────────────
# actower can be installed via BOTH this curl installer (~/.actower/bin/actower)
# AND Homebrew (/opt/homebrew/bin or /usr/local/bin). When both exist, PATH order
# silently decides which (possibly stale) copy runs. Warn — never auto-heal.
# brew is macOS-only for us, so this detection only runs on macOS.
#
# Sourceable (ACTOWER_INSTALL_LIB=1) for offline unit tests — see
# tests/test_shadow_detection.sh.

# Echo the first existing "other-method" (Homebrew) actower binary path and
# return 0; return 1 if none found or not on macOS. ACTOWER_BREW_BIN_OVERRIDE is
# a test seam: when set (non-empty) it is AUTHORITATIVE — only that path is
# checked, and the real Homebrew locations are skipped (keeps tests deterministic
# on machines that happen to have a real brew install).
detect_shadow_install() {
    [ "${PLATFORM:-}" = "macos" ] || return 1
    if [ -n "${ACTOWER_BREW_BIN_OVERRIDE:-}" ]; then
        if [ -e "${ACTOWER_BREW_BIN_OVERRIDE}" ]; then
            echo "${ACTOWER_BREW_BIN_OVERRIDE}"
            return 0
        fi
        return 1
    fi
    for _cand in /opt/homebrew/bin/actower /usr/local/bin/actower; do
        if [ -e "$_cand" ]; then
            echo "$_cand"
            return 0
        fi
    done
    return 1
}

# Print the multi-line shadow warning for a found brew binary path ($1).
# Pure output, no prompt (keeps it unit-testable).
warn_shadow_install() {
    _brew_path="$1"
    printf "\n"
    printf "${YELLOW}⚠${NC}  Detected an existing actower installation via Homebrew at %s.\n" "$_brew_path"
    printf "   You're now installing via the curl installer at %s/bin/actower.\n" "$ACTOWER_HOME"
    printf "   Only one should be active — the other will be shadowed depending on your PATH.\n"
    printf "\n"
    printf "   Recommended: pick ONE install method and remove the other.\n"
    printf "\n"
    printf "   To keep this curl install:      brew uninstall actower\n"
    printf "   To keep the Homebrew install:   rm -rf %s/bin && rehash\n" "$ACTOWER_HOME"
    printf "\n"
}

# Detect a shadowing brew install; if found, warn and require Enter to continue.
# curl | sh puts the pipe on stdin, so read from /dev/tty when available;
# degrade to a non-blocking note when there's no tty (scripted installs never hang).
# Never aborts automatically — Ctrl-C is the user's abort.
maybe_prompt_shadow() {
    _brew_path=$(detect_shadow_install) || return 0
    warn_shadow_install "$_brew_path"
    if [ -r /dev/tty ]; then
        printf "   Or continue and manage it yourself.  ${BOLD}Press Enter to continue, Ctrl-C to abort.${NC}"
        # shellcheck disable=SC2034
        read -r _ignored < /dev/tty || true
        echo ""
    else
        printf "   (non-interactive — continuing; run 'actower doctor' after install to review)\n\n"
    fi
}

# ── Install summary + post-install desktop re-check (Phase B) ─────────
# Before the new binary lands, snapshot the highest previously-installed actower
# across ALL installs (the marker + every actower on PATH); after it lands, print
# "Previous → Now installed" honestly — no upgrade/downgrade wording, the user
# chose it. Then ask the JUST-INSTALLED binary whether ACTower.app is behind.
#
# POSIX sh throughout (no `local`): temporaries are prefixed and unset. Sourceable
# (ACTOWER_INSTALL_LIB=1) for offline tests — see tests/test_install_summary.sh.
# The PATH-scan seams (ACTOWER_SHADOW_WHICH / ACTOWER_SHADOW_VERSIONS) have the
# exact semantics of actower-core.bash's _shadow_which_all / _shadow_version_for.

# Echo one STRING field of $ACTOWER_HOME/install-marker.json, or nothing.
# POSIX port of actower-core.bash:_read_marker_field (same one-key-per-line scan).
# Pure shell rather than install_marker.read_marker: at snapshot time
# $ACTOWER_HOME/lib is either the OLD copy or absent.
_marker_field() {
    _mf_file="$ACTOWER_HOME/install-marker.json"
    if [ -f "$_mf_file" ] && [ -r "$_mf_file" ]; then
        while IFS= read -r _mf_line || [ -n "$_mf_line" ]; do
            case "$_mf_line" in
                *"\"$1\""*:*)
                    _mf_val="${_mf_line#*\"$1\"}"
                    _mf_val="${_mf_val#*:}"
                    _mf_val="${_mf_val#*\"}"
                    _mf_val="${_mf_val%%\"*}"
                    printf '%s\n' "$_mf_val"
                    break
                    ;;
            esac
        done < "$_mf_file" 2>/dev/null || true
    fi
    unset _mf_file _mf_line _mf_val
    return 0
}

# Newline-separated paths of every executable `actower` on PATH, deduped, PATH
# order preserved. ACTOWER_SHADOW_WHICH (non-empty) is authoritative.
_peer_paths() {
    if [ -n "${ACTOWER_SHADOW_WHICH:-}" ]; then
        printf '%s\n' "$ACTOWER_SHADOW_WHICH"
        return 0
    fi
    (
        set -f
        IFS=:
        for _pp_dir in $PATH; do
            [ -n "$_pp_dir" ] || continue
            # Absolute entries only. A relative PATH entry ("rel", ".") would
            # both render a non-canonical "Previous:" path and make the version
            # probe depend on wherever the installer happens to be running —
            # i.e. execute an arbitrary ./actower out of the user's cwd.
            case "$_pp_dir" in /*) ;; *) continue ;; esac
            if [ -f "$_pp_dir/actower" ] && [ -x "$_pp_dir/actower" ]; then
                printf '%s\n' "$_pp_dir/actower"
            fi
        done
    ) | awk '!seen[$0]++' || true
}

# Installs that exist but are NOT on PATH, appended after the PATH scan (so PATH
# order still wins ties). Two of them, both cases this installer already knows
# about by other means:
#   - the Homebrew copy detect_shadow_install/maybe_prompt_shadow just warned
#     about. It is located by EXISTENCE, not by PATH — and `curl | sh` from a
#     non-login shell routinely has no /opt/homebrew/bin on PATH, which is the
#     exact brew population this feature exists for. Warning about an install in
#     Step 2b and then omitting it from "Previous:" in Step 8 would be the
#     installer contradicting itself (cycle-1 review).
#   - the curl copy being replaced. Normally covered by its marker; this also
#     catches a deleted/never-written marker, and it is the path this very script
#     installs to, so it can never be someone else's binary.
# detect_shadow_install honours ACTOWER_BREW_BIN_OVERRIDE (authoritative) and
# returns 1 off macOS, so tests stay deterministic and no real install is probed.
_offpath_candidates() {
    _oc_brew=$(detect_shadow_install 2>/dev/null) || _oc_brew=""
    [ -n "$_oc_brew" ] && [ -f "$_oc_brew" ] && [ -x "$_oc_brew" ] && printf '%s\n' "$_oc_brew"
    if [ -f "$ACTOWER_HOME/bin/actower" ] && [ -x "$ACTOWER_HOME/bin/actower" ]; then
        printf '%s\n' "$ACTOWER_HOME/bin/actower"
    fi
    unset _oc_brew
    return 0
}

# Echo the version the actower at $1 reports, or nothing. ACTOWER_SHADOW_VERSIONS
# (`path=ver;path=ver`) is authoritative when set. The real probe sets
# ACTOWER_SHADOW_PROBE=1, which also stops the peer from re-exec'ing.
_peer_version() {
    if [ -n "${ACTOWER_SHADOW_VERSIONS:-}" ]; then
        (
            set -f
            IFS=';'
            for _pv_pair in $ACTOWER_SHADOW_VERSIONS; do
                if [ "${_pv_pair%%=*}" = "$1" ]; then
                    printf '%s\n' "${_pv_pair#*=}"
                    break
                fi
            done
        )
        return 0
    fi
    [ -x "$1" ] || return 0
    ACTOWER_SHADOW_PROBE=1 "$1" version 2>/dev/null </dev/null \
        | grep -oE '[0-9]+\.[0-9]+\.[0-9]+[^ ]*' | head -1 || true
}

# Install method implied by a binary's location, in marker vocabulary
# (curl/brew), or the literal "unknown". dmg is never inferred from a path.
# /usr/local/bin counts as brew, matching detect_shadow_install.
_infer_method() {
    case "$1" in
        "$ACTOWER_HOME"/bin/actower|*/.actower/bin/actower)
            echo "curl" ;;
        /opt/homebrew/*|/usr/local/Cellar/*|/usr/local/bin/actower|/home/linuxbrew/.linuxbrew/*)
            echo "brew" ;;
        *)
            echo "unknown" ;;
    esac
}

# Is version $1 strictly newer than version $2? POSIX port of
# actower-core.bash:_version_gt — numeric per dotted field (1.2.13 > 1.2.9),
# leading `v` and `-suffix` ignored, each field truncated at its first non-digit
# (so 1.2.13rc1 is 1.2.13, never 1.2.131). Empty $1 loses; empty $2 loses to any.
# Identical to the bash original for every field that fits the shell's integer
# type — which is every version this project can produce — and deliberately
# better beyond it (see the width note in the loop).
_semver_gt() {
    _sg_a="${1#v}"; _sg_b="${2#v}"
    _sg_a="${_sg_a%%-*}"; _sg_b="${_sg_b%%-*}"
    if [ -z "$_sg_a" ]; then unset _sg_a _sg_b; return 1; fi
    if [ -z "$_sg_b" ]; then unset _sg_a _sg_b; return 0; fi
    _sg_rc=1
    while [ -n "$_sg_a" ] || [ -n "$_sg_b" ]; do
        _sg_x="${_sg_a%%.*}"; _sg_y="${_sg_b%%.*}"
        case "$_sg_a" in *.*) _sg_a="${_sg_a#*.}" ;; *) _sg_a="" ;; esac
        case "$_sg_b" in *.*) _sg_b="${_sg_b#*.}" ;; *) _sg_b="" ;; esac
        _sg_x="${_sg_x%%[!0-9]*}"; _sg_y="${_sg_y%%[!0-9]*}"
        # Strip leading zeros so `[ -gt ]` never sees an octal-looking operand.
        while [ "${_sg_x#0}" != "$_sg_x" ]; do _sg_x="${_sg_x#0}"; done
        while [ "${_sg_y#0}" != "$_sg_y" ]; do _sg_y="${_sg_y#0}"; done
        [ -n "$_sg_x" ] || _sg_x=0
        [ -n "$_sg_y" ] || _sg_y=0
        # `[ -gt ]` ERRORS on an operand too wide for the shell's integer type,
        # and the `2>/dev/null` that hid that made both comparisons fall through
        # — i.e. two different fields were silently treated as equal. Only a
        # corrupt marker or a peer reporting nonsense can be that wide, but
        # "silently equal" is the worst possible answer, so fall back to a digit
        # STRING compare: leading zeros are already stripped, so a longer string
        # is the larger number and equal-length all-digit strings order
        # correctly. (The bash original wraps around instead; this is the one
        # place the port is deliberately better rather than identical.)
        # The 18-digit bound is what intmax_t gives us in dash and bash — the
        # only two shells `curl … | sh` can land on (macOS /bin/sh is bash,
        # Debian/Ubuntu is dash). ksh93 loses precision above 2^53 and would get
        # ~16-18-digit fields wrong, but that is pre-existing (the pre-width-guard
        # code was wrong there too) and ksh is not a supported interpreter here.
        if [ "${#_sg_x}" -le 18 ] && [ "${#_sg_y}" -le 18 ]; then
            if [ "$_sg_x" -gt "$_sg_y" ]; then _sg_rc=0; break; fi
            if [ "$_sg_x" -lt "$_sg_y" ]; then break; fi
        elif [ "${#_sg_x}" -ne "${#_sg_y}" ]; then
            if [ "${#_sg_x}" -gt "${#_sg_y}" ]; then _sg_rc=0; fi
            break
        elif [ "$_sg_x" != "$_sg_y" ]; then
            if [ "$_sg_x" \> "$_sg_y" ]; then _sg_rc=0; fi
            break
        fi
    done
    unset _sg_a _sg_b _sg_x _sg_y
    # Every temporary is unset before returning, _sg_rc included — hence the
    # save-then-unset-then-return dance (the convention this function documents).
    _sg_ret="$_sg_rc"
    unset _sg_rc
    set -- "$_sg_ret"
    unset _sg_ret
    return "$1"
}

# Set PREV_VERSION / PREV_METHOD / PREV_PATH to the highest pre-existing install
# (all empty on a truly fresh install). Marker vs. peers: the higher version
# wins; a tie goes to the marker (the user's stated intent). Fail-soft: nothing
# here may abort the install under `set -e`.
snapshot_previous_install() {
    PREV_VERSION=""; PREV_METHOD=""; PREV_PATH=""
    _sp_mver=$(_marker_field installed_version) || _sp_mver=""
    _sp_mmethod=$(_marker_field method) || _sp_mmethod=""
    _sp_mpath=$(_marker_field cli_path) || _sp_mpath=""

    _sp_pver=""; _sp_ppath=""
    # PATH scan first, then the off-PATH installs; `awk !seen` keeps the first
    # occurrence, so a candidate already on PATH is not probed twice.
    _sp_list=$(
        { _peer_paths; _offpath_candidates; } | awk 'NF && !seen[$0]++'
    ) || _sp_list=""
    # Here-doc, not a pipe: the loop must run in THIS shell to keep its results.
    while IFS= read -r _sp_p; do
        [ -n "$_sp_p" ] || continue
        _sp_v=$(_peer_version "$_sp_p") || _sp_v=""
        [ -n "$_sp_v" ] || continue
        if [ -z "$_sp_pver" ] || _semver_gt "$_sp_v" "$_sp_pver"; then
            _sp_pver="$_sp_v"; _sp_ppath="$_sp_p"
        fi
    done <<EOF
$_sp_list
EOF

    if [ -n "$_sp_mver" ] && { [ -z "$_sp_pver" ] || ! _semver_gt "$_sp_pver" "$_sp_mver"; }; then
        PREV_VERSION="$_sp_mver"; PREV_METHOD="$_sp_mmethod"; PREV_PATH="$_sp_mpath"
    elif [ -n "$_sp_pver" ]; then
        PREV_VERSION="$_sp_pver"; PREV_PATH="$_sp_ppath"
        PREV_METHOD=$(_infer_method "$_sp_ppath")
    fi
    if [ -n "$PREV_VERSION" ] && [ -z "$PREV_METHOD" ]; then
        PREV_METHOD=$(_infer_method "$PREV_PATH")
    fi
    PREV_VERSION="${PREV_VERSION#v}"
    # The marker readers (here and in actower-core.bash) assume every value is a
    # quoted string; a hand-edited marker can therefore hand back the raw
    # remainder of the line. Phase B is the first code to PRINT that, so validate
    # before it reaches the user: a version that isn't version-shaped means we
    # know nothing trustworthy about the previous install, and reporting nothing
    # is better than reporting garbage.
    case "$PREV_VERSION" in
        ""|[!0-9]*|*[!0-9A-Za-z.+_-]*)
            PREV_VERSION=""; PREV_METHOD=""; PREV_PATH="" ;;
    esac
    # Method stays in the marker's own vocabulary — never a substituted label.
    case "$PREV_METHOD" in
        brew|curl|dmg|"") ;;
        *) PREV_METHOD="unknown" ;;
    esac
    # Same reasoning for the path, which cycle 1 left out: it is a marker value
    # printed straight to a terminal, and a hand-edited marker can carry the raw
    # remainder of the line — including ESC sequences that repaint the summary.
    # Every path we can legitimately report is absolute (peers are filtered to
    # absolute PATH entries above), so anything else falls back to "unknown".
    case "$PREV_PATH" in
        /*) case "$PREV_PATH" in *[[:cntrl:]]*) PREV_PATH="" ;; esac ;;
        *) PREV_PATH="" ;;
    esac
    unset _sp_mver _sp_mmethod _sp_mpath _sp_pver _sp_ppath _sp_list _sp_p _sp_v
    return 0
}

# Print the Previous → Now summary. No comparison wording in either direction.
print_install_summary() {
    _is_now=$(_on_disk_version) || _is_now="$ACTOWER_VERSION"
    echo ""
    echo "ACTower installed:"
    if [ -n "${PREV_VERSION:-}" ]; then
        printf '  Previous:      v%s (%s, %s)\n' "$PREV_VERSION" "${PREV_METHOD:-unknown}" "${PREV_PATH:-unknown}"
    fi
    printf '  Now installed: v%s (%s, %s)\n' "${_is_now#v}" "curl" "$ACTOWER_HOME/bin/actower"
    echo ""
    unset _is_now
    return 0
}

# Ask the JUST-INSTALLED binary (full path, never PATH-resolved — PATH may hit a
# shadowed peer) whether ACTower.app is older than it; it offers the DMG upgrade
# only at a real terminal and is silent otherwise. Always returns 0: a failed
# DMG update never fails a successful CLI install.
run_desktop_check() {
    # Platform gate FIRST: the desktop app is macOS-only, so on Linux/WSL there
    # is no check to skip and announcing a skipped one would only confuse.
    [ "${PLATFORM:-}" = "macos" ] || return 0
    # Any non-empty value other than "0" disables the check, matching this
    # release's sibling switch ACTOWER_NO_TELEMETRY rather than demanding the
    # exact string "1". This hatch exists to stop a prompt hanging a CI or Docker
    # install, so NO_DESKTOP_CHECK=true silently leaving the prompt armed is the
    # one failure it must not have. "0" still means "leave the check on".
    if [ -n "${NO_DESKTOP_CHECK:-}" ] && [ "${NO_DESKTOP_CHECK}" != "0" ]; then
        info "Desktop app check skipped (--no-desktop-check)."
        return 0
    fi
    _dc_bin="$ACTOWER_HOME/bin/actower"
    if [ ! -x "$_dc_bin" ]; then
        unset _dc_bin
        return 0
    fi
    # curl | sh: stdin IS this script — the child must never read it. Hand it the
    # controlling terminal when one can actually be opened (`-r /dev/tty` is true
    # even without one), else /dev/null. ACTOWER_DESKTOP_CHECK_TTY is a test seam
    # that forces the child's stdin.
    if [ -n "${ACTOWER_DESKTOP_CHECK_TTY:-}" ]; then
        _dc_in="$ACTOWER_DESKTOP_CHECK_TTY"
    elif ( exec < /dev/tty ) 2>/dev/null; then
        _dc_in=/dev/tty
    else
        _dc_in=/dev/null
    fi
    # Ctrl-C at the DMG prompt (or mid-download) is delivered to the whole
    # foreground process group, this script included — and no trap of
    # install.sh is active here (install_actower's download trap is cleared
    # right after extraction), so it would die at Step 8 with the CLI fully installed: exit 130,
    # and print_completion (the ONLY place the user is told to source their shell
    # rc, without which the just-installed actower is not on PATH) never runs.
    # Ignore INT for the duration of this optional step only. The child still
    # takes the default action and dies — POSIX resets caught signals to default
    # across exec — so the download is still interruptible; only the installer
    # survives, to finish reporting an install that already succeeded.
    # `trap - INT` restores the DEFAULT, not a caller's handler. install.sh sets
    # no other trap at this point (the download trap in install_actower is
    # cleared before this step) and no harness that sources it sets an INT trap either, so
    # there is nothing to clobber today; a future caller with its own INT handler
    # would need this widened to a save/restore (POSIX gives no portable way to
    # read a trap back, so that is deliberately not attempted here).
    trap ':' INT
    # ACTOWER_NO_REEXEC: run THIS binary, even if a marker/peer would route away.
    ACTOWER_NO_REEXEC=1 "$_dc_bin" desktop --check-update < "$_dc_in" && _dc_rc=0 || _dc_rc=$?
    trap - INT
    if [ "$_dc_rc" -eq 0 ]; then
        :
    elif { [ "$_dc_rc" -gt 128 ] && [ "$_dc_rc" -le 159 ]; } \
      || { [ "$_dc_rc" -gt 256 ] && [ "$_dc_rc" -le 287 ]; }; then
        # Stopped by a signal — a Ctrl-C, almost always. POSIX shells report
        # 128+N; ksh93 reports 256+N (measured, not assumed). Both ranges are
        # bounded to real signal numbers so a generic 255 still reads as a
        # failure. A cancellation is not a failed upgrade, so no failure
        # warning. It is NOT silent either, though: cmd_desktop
        # has a destructive window — it moves the old bundle to ACTower.app.bak.$$
        # and then copies the new one in, with no rollback trap of its own — so an
        # interrupt in that window can leave ACTower.app missing. Saying nothing
        # here would follow it with an unqualified "installed successfully!".
        # Neutral wording: nothing is wrong in the common case (cancelled at the
        # prompt), and the recovery command is right there if something is.
        printf "  Desktop app check cancelled. If ACTower.app is missing, run 'actower desktop --update'.\n"
    else
        printf "${YELLOW}⚠ DMG update failed; retry via 'actower desktop --update'.${NC}\n"
    fi
    unset _dc_bin _dc_in _dc_rc
    return 0
}

# Main
main() {
    # --no-path is a flag only: never inherit a stray NO_PATH_EDIT from the env.
    NO_PATH_EDIT=""
    # Same for --no-deps-install. (--yes has an env twin, ACTOWER_INSTALL_YES.)
    NO_DEPS_INSTALL=""
    DEPS_YES=""
    # Parse arguments
    while [ $# -gt 0 ]; do
        case "$1" in
            --help|-h)
                show_help
                exit 0
                ;;
            --uninstall)
                detect_platform
                uninstall_actower
                exit 0
                ;;
            --version)
                ACTOWER_VERSION="$2"
                shift
                ;;
            --local)
                ACTOWER_LOCAL="$2"
                shift
                ;;
            --upgrade-skills)
                UPGRADE_SKILLS=1
                ;;
            --skip-skills)
                SKIP_SKILLS=1
                ;;
            --no-desktop-check)
                NO_DESKTOP_CHECK=1
                ;;
            --no-path)
                NO_PATH_EDIT=1
                ;;
            --yes|-y)
                DEPS_YES=1
                ;;
            --no-deps-install)
                NO_DEPS_INSTALL=1
                ;;
            *)
                warn "Unknown option: $1"
                ;;
        esac
        shift
    done

    echo ""
    echo "=================================="
    echo " Agent Control Tower Installer"
    echo " Version: ${ACTOWER_VERSION}"
    echo "=================================="
    echo ""
    # What the dependency step may do — said only where it is true: not with
    # --yes (no question) or --no-deps-install (nothing installed), and in the
    # Linux wording on Linux.
    if [ -z "$NO_DEPS_INSTALL" ] && ! _deps_yes; then
        case "$(uname -s 2>/dev/null || echo unknown)" in
            Darwin)
                echo "On a Mac the installer uses Homebrew to add tmux and Python if they are missing; it asks first."
                echo ""
                ;;
            Linux)
                echo "On Linux the installer uses apt, dnf or pacman (with sudo) to add tmux and Python if they are missing; it asks first."
                echo ""
                ;;
        esac
    fi

    # Step 1: Detect platform
    info "Detecting platform..."
    detect_platform
    printf "  ${GREEN}✓${NC} %s (%s)\n" "$PLATFORM" "$ARCH"
    if [ -n "$DISTRO" ]; then
        printf "  ${GREEN}✓${NC} Distribution: %s\n" "$DISTRO"
    fi
    echo ""

    # Step 2: Check dependencies — and, with a terminal to ask on (or --yes),
    # offer to install what is missing with one question, then re-check once.
    ensure_deps && _deps_rc=0 || _deps_rc=$?
    case "$_deps_rc" in
        0) ;;
        2) exit 1 ;;  # the two-line "needs Homebrew / sudo" reason is already shown
        *)
            echo ""
            die "Please install missing dependencies and run this installer again."
            ;;
    esac
    unset _deps_rc
    echo ""

    # Step 2b: Warn if the OTHER install method (Homebrew) is already present —
    # dual installs shadow each other by PATH order. Warn-only; never auto-heal.
    maybe_prompt_shadow

    # Step 2c: Snapshot the previous install (marker + every actower on PATH)
    # BEFORE the new binary is written, for the install summary printed at the
    # end. Read-only and fail-soft.
    snapshot_previous_install

    # Step 3: Install files
    install_actower
    echo ""

    # Step 3b: Record HOW actower got here. Deliberately ordered:
    #   - AFTER install_actower, so $ACTOWER_HOME/lib/install_marker.py exists;
    #   - BEFORE run_setup, so `actower setup`'s write-if-missing bootstrap finds
    #     the authoritative curl marker already in place and stays a no-op;
    #   - BEFORE _kickstart_web_if_loaded, so the recycled backend serves the
    #     right install_method on /api/version immediately.
    # Writing it "at the end" (after print_completion) would invert all three.
    write_install_marker
    echo ""

    # Step 4: Add to PATH
    add_to_path
    echo ""

    # Step 5: Run setup
    run_setup

    # Step 6: Install bundled end-user skills into ~/.claude/skills/ (Claude
    # Code only). Runs AFTER install_actower (sources present at
    # $ACTOWER_HOME/share/skills) and AFTER run_setup (config.json exists, so
    # skills.auto_install is readable). Non-destructive + offline.
    install_skills

    # Step 7: If a desktop/web LaunchAgent is already loaded, recycle it so the
    # backend picks up the just-installed code + license state now (no manual
    # kickstart needed). Clean no-op on a fresh install / non-macOS / foreground
    # `actower web`. Runs last, after every file is in place.
    _kickstart_web_if_loaded

    # Step 7b: Point every scheduled Ops task's unit at the code just
    # installed (`actower autopilot schedule sync`). No-op without schedules.
    _sync_ops_schedules

    # Step 8: Summarise what was replaced by what, then re-check the desktop app
    # against the just-installed CLI. Ordered after every file (binary + marker)
    # is in place and setup has run, so the summary reports the final state and
    # the optional interactive DMG prompt is not buried mid-install. Neither step
    # can fail the install.
    print_install_summary
    run_desktop_check

    # Done!
    print_completion
}

# Run main unless the file is being sourced for unit tests. Tests set
# ACTOWER_INSTALL_LIB=1 and source install.sh to exercise install_skills() in
# isolation (offline, no venv/network) — see tests/test_install_skills.sh.
[ -n "${ACTOWER_INSTALL_LIB:-}" ] || main "$@"
