#!/usr/bin/env bash
#
# Agentix — AiWork one-click installer
#
# Usage:
#   curl -fsSL <release-base-url>/install-aiwork.sh | bash -s -- --channel dev
#   ./install-aiwork.sh --version 1.0.1-dev
#   ./install-aiwork.sh --tag v1.0.2
#   ./install-aiwork.sh --channel CHANNEL
#   ./install-aiwork.sh --install-dir "$HOME/.agentix-dev" --skip-tui
#
# Behavior:
#   1. Downloads the matching AiWork release installer from OSS.
#   2. Installs the release package into platform-data program/<dist>/releases/<version-commit>.
#   3. Keeps the distribution command on PATH: aiwork, aiworkcn, or aiworkcli.
#   4. Bootstraps a coder agent if it does not exist.

set -euo pipefail

# Package history can be used by another installation. Preserve shared writes on
# failure; process visibility is not evidence that an old snapshot is safe.
CONNECTOR_SHARED_STATE_PROTECTED=false
refresh_connector_rollback_protection() {
  local ledger
  for ledger in "$1/connectors/packages.json" "$1/connectors-v2/packages.json"; do
    [[ ! -e "$ledger" && ! -L "$ledger" ]] || CONNECTOR_SHARED_STATE_PROTECTED=true
  done
}

DEFAULT_DTCLAW_BASE_URL='https://aiwork-dl.dtagi.cn/releases'
DEFAULT_OPENCODE_INSTALL_SCRIPT='https://aiwork-dl.dtagi.cn/install_dtcode.sh'
CONFIG_COMPAT_RULES_URL='https://aiwork-dl.dtagi.cn/releases/config-compat-rules.json'
SCRIPT_SOURCE="${BASH_SOURCE[0]-}"
SCRIPT_DIR=""
if [[ -n "$SCRIPT_SOURCE" ]]; then
  SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_SOURCE")" 2>/dev/null && pwd -P)" || SCRIPT_DIR=""
fi

DTCLAW_HOME="${AGENTIX_STATE_DIR:-$HOME/.agentix}"
PROGRAM_ROOT="${AGENTIX_PROGRAM_ROOT:-}"
BASE_URL="$DEFAULT_DTCLAW_BASE_URL"
CHANNEL='prod'
ALLOWED_CHANNELS='prod'
INSTALLER_SCOPE='root'
ROOT_DEFAULT_CHANNEL='prod'
DIST='external'
ORIGINAL_ARGS=("$@")
CHANNEL_EXPLICIT=false
BASE_URL_EXPLICIT=false
PRE_EXISTING_CONFIG=false
VERSION=""
REQUESTED_VERSION=""
COMMIT_SELECTOR=""
TAG=""
TARGET_TRIPLE=""
OPENCODE_INSTALL_SCRIPT="${AGENTIX_INSTALL_DTCODE_URL:-$DEFAULT_OPENCODE_INSTALL_SCRIPT}"
OPENCODE_BASE_URL=""
OPENCODE_VERSION=""
SKIP_OPENCODE=false
YES=false
KILL_RUNNING_DTCODER=false
CONTINUE_WITH_RUNNING_DTCODER=false
REPAIR_CODER_AGENT=false
CACHED_UPDATE_DIR=""
CACHED_INSTALL_ENV_FILE=""
DRY_RUN=false
NO_MODIFY_PATH=false
NO_SYMLINK=false
RUNNING_PROCESSES_STOPPED=false
INSTALL_LOCK_DIR=""
INSTALL_LOCK_HELD=false
INSTALL_IN_PROGRESS_MARKER=""
INSTALL_DTCODER_REMAP_FROM_VERSIONED_RELEASE=false
CODER_APP_PACK_BACKUP_DIR=""
CODER_APP_PACK_BACKUP_ID=""
CODER_APP_PACK_BACKUP_VERSION=""
CACHED_UPDATE_UNAVAILABLE_MESSAGE="cached update is no longer available; AiWork will check again on the next launch"
INSTALLER_DOWNLOAD_NOT_FOUND=44
LEGACY_GLOBAL_CONFIG_REPAIR_BACKUP=""
CONFIG_COMPAT_TARGET_VERSION=""
CONFIG_COMPAT_RULES_FILE=""
CONFIG_COMPAT_REPAIR_DONE=false
CONFIG_COMPAT_PRIVATE_DEFERRED=false
CONFIG_COMPAT_RESTORE_PROGRAM_DIR=""
ARCHIVE_GATEWAY_START_DEFERRED=false
ARCHIVE_GATEWAY_MAY_HAVE_STARTED=false
INSTALL_ACTIVATION_PROTECTED_RELEASE=""
INSTALL_ACTIVATION_PROTECTED_RELEASE_BACKUP=""

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

installer_log_prefix() {
  case "${DIST:-internal}" in
    external) printf '%s\n' "aiworkcn-install" ;;
    global) printf '%s\n' "aiworkcli-install" ;;
    *) printf '%s\n' "aiwork-install" ;;
  esac
}

info()  { echo -e "${CYAN}[$(installer_log_prefix)]${NC} $*"; }
ok()    { echo -e "${GREEN}[ok]${NC}             $*"; }
warn()  { echo -e "${YELLOW}[warn]${NC}           $*"; }
fail() {
  local message=$1 code=${2:-1} reason=${3:-}
  [[ -z "$reason" ]] || emit_install_lock_error "$reason"
  printf '%b[error]%b %s\n' "$RED" "$NC" "$message" >&2
  exit "$code"
}

ensure_valid_installer_cwd() {
  builtin pwd -P >/dev/null 2>&1 && return 0

  local candidate
  for candidate in "${HOME:-}" "${TMPDIR:-}" /tmp /; do
    [[ -n "$candidate" && -d "$candidate" ]] || continue
    if cd "$candidate" 2>/dev/null; then
      warn "current working directory is unavailable; continuing from: $candidate"
      return 0
    fi
  done

  fail "current working directory is unavailable and no fallback directory is accessible" 5
}

require_value() {
  local option=$1
  local value=${2:-}
  if [[ -z "$value" || "$value" == -* ]]; then
    fail "missing value for $option" 2
  fi
  printf '%s\n' "$value"
}

python3_healthy() {
  local candidate=$1
  [[ -n "$candidate" ]] || return 1
  "$candidate" - <<'PY' >/dev/null 2>&1
import json
import sys

sys.exit(0)
PY
}

apple_silicon_hardware() {
  [[ "$(uname -s)" == "Darwin" ]] || return 1
  [[ "$(uname -m)" == "arm64" ]] && return 0
  [[ "$(sysctl -n hw.optional.arm64 2>/dev/null || true)" == "1" ]]
}

python3_arch_compatible() {
  local candidate=$1
  local description
  [[ -n "$candidate" ]] || return 1
  apple_silicon_hardware || return 0
  command -v file >/dev/null 2>&1 || return 0
  description="$(file -L "$candidate" 2>/dev/null || true)"
  [[ "$description" == *"x86_64"* && "$description" != *"arm64"* && "$description" != *"universal"* ]] && return 1
  return 0
}

preferred_python3() {
  local path_python3=""
  local skip_path_python3=false
  if command -v python3 >/dev/null 2>&1; then
    path_python3="$(command -v python3 2>/dev/null || true)"
  fi

  if [[ "$(uname -s)" == "Darwin" && -x /usr/bin/python3 ]]; then
    if python3_healthy /usr/bin/python3; then
      printf '%s\n' /usr/bin/python3
      return 0
    fi
    warn "/usr/bin/python3 is not usable; falling back to PATH python3" >&2
    [[ "$path_python3" == "/usr/bin/python3" ]] && skip_path_python3=true
  fi

  if [[ -n "$path_python3" ]] && [[ "$skip_path_python3" != true ]]; then
    if ! python3_arch_compatible "$path_python3"; then
      warn "PATH python3 is x86_64-only on Apple Silicon; skipping it to avoid Rosetta" >&2
      return 0
    fi
    if python3_healthy "$path_python3"; then
      printf '%s\n' "$path_python3"
      return 0
    fi
  fi

  return 0
}

shell_json_string_field() {
  local path=$1
  local key=$2
  case "$key" in
    *[!A-Za-z0-9_]*|"") return 1 ;;
  esac
  [[ -f "$path" ]] || return 1
  sed -nE 's/.*"'"$key"'"[[:space:]]*:[[:space:]]*"([^"\\]*)".*/\1/p' "$path" | sed -n '1p'
}

flush_file_best_effort() {
  local path=$1
  if command -v sync >/dev/null 2>&1; then
    sync "$path" 2>/dev/null || sync 2>/dev/null || true
  fi
}

flush_dir_best_effort() {
  local dir=$1
  if command -v sync >/dev/null 2>&1; then
    sync "$dir" 2>/dev/null || sync 2>/dev/null || true
  fi
}

atomic_replace_with_tmp() {
  local tmp_path=$1
  local output_path=$2
  local output_dir
  output_dir="$(dirname "$output_path")"
  [[ -f "$tmp_path" ]] || return 1
  flush_file_best_effort "$tmp_path"
  mv "$tmp_path" "$output_path" || { rm -f "$tmp_path"; return 1; }
  flush_dir_best_effort "$output_dir"
}

usage() {
  sed -n '2,18p' "$0" | sed 's/^# \{0,1\}//'
  cat <<'USAGE'

Options:
  --version VERSION                 Install a specific Agentix product version.
  --tag TAG                         Compatibility alias for --version ${TAG#v}.
  --channel CHANNEL                 Install from the selected moving channel (default: prod;
                                    allowed set comes from the installer profile).
  --dist internal|external|global   Distribution profile (default: external). global uses
                                     ~/.agentix-global; external/global install
                                    use runtime distribution defaults for diagnostics and profiling;
                                    existing config.json is never overwritten.
  --base-url URL                    AiWork release base URL.
  --install-dir DIR                 Legacy alias for --state-dir (default: $AGENTIX_STATE_DIR or ~/.agentix).
  --state-dir DIR                   State root for config, agents, skills, and update markers.
  --program-root DIR                Program root containing <dist>/releases and <dist>/current.
  --target TRIPLE                   Override AiWork release target triple.
  --skip-tui                        Do not install the AiWork TUI.
  --opencode-install-script URL     Override AiWork TUI installer script.
  --opencode-base-url URL           Pass --base-url to the AiWork TUI installer.
  --opencode-version VERSION        Pass --version to the AiWork TUI installer.
  --yes, -y                         Run non-interactively; also stop running target AiWork processes.
  --kill-running-aiwork             Stop running AiWork processes before install.
  --repair-coder-agent              Backup and recreate coder if the existing agent cannot be loaded.
                                    Compatibility aliases --skip-opencode, --kill-running-dtcoder,
                                    --kill-running-opencode and -kill-running-opencode are accepted.
  --continue-with-running-dtcoder   Deprecated; running target processes now fail the install.
  --cached-update-dir DIR           Install AiWork from a pre-downloaded update cache.
  --no-modify-path                  Do not write the bin dir into ~/.zshrc / ~/.bashrc (only print a hint).
  --no-symlink                      Do not create product symlinks under ~/.local/bin.
  --dry-run                         Print the install actions without changing files.
  -h, --help                        Show help.
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --version) VERSION="$(require_value "$1" "${2:-}")"; shift 2 ;;
    --tag) TAG="$(require_value "$1" "${2:-}")"; shift 2 ;;
    --channel) CHANNEL="$(require_value "$1" "${2:-}")"; CHANNEL_EXPLICIT=true; shift 2 ;;
    --dist) DIST="$(require_value "$1" "${2:-}")"; shift 2 ;;
    --base-url) BASE_URL="$(require_value "$1" "${2:-}")"; BASE_URL_EXPLICIT=true; shift 2 ;;
    --install-dir|--dtclaw-home) DTCLAW_HOME="$(require_value "$1" "${2:-}")"; shift 2 ;;
    --state-dir) DTCLAW_HOME="$(require_value "$1" "${2:-}")"; shift 2 ;;
    --program-root) PROGRAM_ROOT="$(require_value "$1" "${2:-}")"; shift 2 ;;
    --target) TARGET_TRIPLE="$(require_value "$1" "${2:-}")"; shift 2 ;;
    --skip-tui|--skip-opencode) SKIP_OPENCODE=true; shift ;;
    --opencode-install-script) OPENCODE_INSTALL_SCRIPT="$(require_value "$1" "${2:-}")"; shift 2 ;;
    --opencode-base-url) OPENCODE_BASE_URL="$(require_value "$1" "${2:-}")"; shift 2 ;;
    --opencode-version) OPENCODE_VERSION="$(require_value "$1" "${2:-}")"; shift 2 ;;
    --yes|-y) YES=true; shift ;;
    --kill-running-aiwork|--kill-running-dtcoder|--kill-running-opencode|-kill-running-opencode) KILL_RUNNING_DTCODER=true; shift ;;
    --repair-coder-agent) REPAIR_CODER_AGENT=true; shift ;;
    --continue-with-running-dtcoder) CONTINUE_WITH_RUNNING_DTCODER=true; shift ;;
    --cached-update-dir) CACHED_UPDATE_DIR="$(require_value "$1" "${2:-}")"; shift 2 ;;
    --no-modify-path) NO_MODIFY_PATH=true; shift ;;
    --no-symlink) NO_SYMLINK=true; shift ;;
    --dry-run) DRY_RUN=true; shift ;;
    -h|--help) usage; exit 0 ;;
    *) fail "Unknown option: $1 (try --help)" 2 ;;
  esac
done

if [[ "$BASE_URL_EXPLICIT" == true ]]; then
  CONFIG_COMPAT_RULES_URL="${BASE_URL%/}/config-compat-rules.json"
fi

# Defensive tilde expansion: users may pass unexpanded ~ via export VAR="~/.agentix"
DTCLAW_HOME="${DTCLAW_HOME/#\~/$HOME}"
[[ -n "$PROGRAM_ROOT" ]] && PROGRAM_ROOT="${PROGRAM_ROOT/#\~/$HOME}"
[[ -n "$CACHED_UPDATE_DIR" ]] && CACHED_UPDATE_DIR="${CACHED_UPDATE_DIR/#\~/$HOME}"

if [[ "$CONTINUE_WITH_RUNNING_DTCODER" == true ]]; then
  fail "--continue-with-running-dtcoder is disabled for AiWork upgrades; stop running processes or rerun with --yes/--kill-running-aiwork" 2
fi
if [[ -n "$CACHED_UPDATE_DIR" && ! -d "$CACHED_UPDATE_DIR" && "$DRY_RUN" != true ]]; then
  fail "--cached-update-dir not found: $CACHED_UPDATE_DIR" 2
fi

validate_release_version() {
  case "$1" in
    *-rc.* )
      fail "invalid --version: $1 (rc prerelease versions are no longer supported)" 2
      ;;
    *[!0-9A-Za-z._-]*|""|.*|*..*|*-|*_ )
      fail "invalid --version: $1 (use values like v1.26261.0, 1.0.1-dev, or 1.0.2)" 2
      ;;
  esac
}

marker_comparable_version() {
  printf '%s\n' "${1#v}"
}

normalize_requested_version_selector() {
  [[ -n "${VERSION:-}" ]] || return 0
  REQUESTED_VERSION="$VERSION"
  COMMIT_SELECTOR=""
  if [[ "$VERSION" =~ ^v?(1\.[0-9]+\.[0-9]+)-([0-9A-Fa-f]{7,40})$ ]]; then
    VERSION="v${BASH_REMATCH[1]}"
    COMMIT_SELECTOR="$(printf '%s' "${BASH_REMATCH[2]}" | tr 'A-F' 'a-f')"
    REQUESTED_VERSION="${VERSION}-${COMMIT_SELECTOR}"
  fi
}

normalize_channel() {
  case " $ALLOWED_CHANNELS " in
    *" $1 "*) echo "$1" ;;
    *) fail "invalid --channel: $1 ($(printf '%s' "$ALLOWED_CHANNELS" | tr ' ' '|'))" 2 ;;
  esac
}

normalize_dist() {
  case "$1" in
    internal|external|global) echo "$1" ;;
    *) fail "invalid --dist: $1 (internal|external|global)" 2 ;;
  esac
}

state_dir_looks_like_versioned_release() {
  local dir=$1
  local real
  [[ -n "$dir" && -d "$dir" ]] || return 1
  real="$(cd "$dir" && pwd -P 2>/dev/null)" || real="$dir"
  case "$real" in
    */releases/*) ;;
    *) return 1 ;;
  esac
  [[ -d "$real/bin" ]] || return 1
  [[ -f "$real/VERSION" || -d "$real/skills/bundled" ]] || return 1
  return 0
}

default_user_state_dir() {
  local dist=${1:-internal}
  if [[ -n "${AGENTIX_STATE_DIR:-}" ]] && ! state_dir_looks_like_versioned_release "$AGENTIX_STATE_DIR"; then
    printf '%s\n' "$AGENTIX_STATE_DIR"
    return 0
  fi
  if [[ "$dist" == "global" ]]; then
    printf '%s\n' "$HOME/.agentix-global"
  else
    printf '%s\n' "$HOME/.agentix"
  fi
}

remap_dtclaw_home_if_release_payload() {
  local corrected
  state_dir_looks_like_versioned_release "$DTCLAW_HOME" || return 0
  corrected="$(default_user_state_dir "$DIST")"
  [[ "$corrected" != "$DTCLAW_HOME" ]] || return 0
  INSTALL_DTCODER_REMAP_FROM_VERSIONED_RELEASE=true
  warn "--install-dir points at a versioned program release ($DTCLAW_HOME); using state dir $corrected for config and bundled skills"
  DTCLAW_HOME="$corrected"
}

allowed_channels_for_dist() {
  case "$1" in
    internal) echo "beta dev prod" ;;
    external|global) echo "dev sit pre prod" ;;
    *) echo "$ALLOWED_CHANNELS" ;;
  esac
}

product_command_for_dist() {
  # 安装完成引导面向最终用户：推荐 aiwork 系列产品入口。
  case "$1" in
    internal) echo "aiwork" ;;
    external) echo "aiworkcn" ;;
    global) echo "aiworkcli" ;;
    *) echo "aiwork" ;;
  esac
}

product_login_command_for_dist() {
  printf '%s login\n' "$(product_command_for_dist "${1:-internal}")"
}

is_aiwork_entrypoint_for_dist() {
  local dist=$1
  local name=$2
  case "$name" in
    aiwork|aiworkcn|aiworkcli) [[ "$name" == "$(product_command_for_dist "$dist")" ]] ;;
    *) return 0 ;;
  esac
}

tui_command_for_program_dir() {
  local program_dir=$1
  if [[ -x "$program_dir/bin/aiwork-tui" ]]; then
    printf '%s\n' "aiwork-tui"
  elif [[ -x "$program_dir/bin/dtcoder-tui" ]]; then
    printf '%s\n' "dtcoder-tui"
  else
    printf '%s\n' "aiwork-tui"
  fi
}

if [[ -n "$TAG" && -z "$VERSION" ]]; then
  VERSION="${TAG#v}"
elif [[ -n "$TAG" && -n "$VERSION" && "${TAG#v}" != "$VERSION" ]]; then
  fail "--tag $TAG and --version $VERSION disagree" 2
fi

[[ -n "$VERSION" ]] && validate_release_version "$VERSION"
normalize_requested_version_selector
DIST='external'
ALLOWED_CHANNELS='prod'
CHANNEL="$(normalize_channel "$CHANNEL")"
INSTALLER_SCOPE="${INSTALLER_SCOPE:-channel}"
ROOT_DEFAULT_CHANNEL="$(normalize_channel "${ROOT_DEFAULT_CHANNEL:-$CHANNEL}")"
if [[ "$DIST" == "global" && -z "${AGENTIX_STATE_DIR:-}" && "$DTCLAW_HOME" == "$HOME/.agentix" ]]; then
  DTCLAW_HOME="$HOME/.agentix-global"
fi
remap_dtclaw_home_if_release_payload

default_program_root() {
  case "$(uname -s)" in
    Darwin) printf '%s\n' "$HOME/Library/Application Support/Agentix/program" ;;
    Linux) printf '%s\n' "${XDG_DATA_HOME:-$HOME/.local/share}/agentix/program" ;;
    *) fail "unsupported platform for default program root: $(uname -s)" 2 ;;
  esac
}
[[ -n "$PROGRAM_ROOT" ]] || PROGRAM_ROOT="$(default_program_root)"
# Keep the parent, backend, rollback and history on the same absolute roots.
[[ "$DTCLAW_HOME" == /* ]] || DTCLAW_HOME="$PWD/$DTCLAW_HOME"
[[ "$PROGRAM_ROOT" == /* ]] || PROGRAM_ROOT="$PWD/$PROGRAM_ROOT"

PROGRAM_DIR="$PROGRAM_ROOT/$DIST/current"

channel_path_for() {
  local channel=$1
  local channel_path="$channel"
  case "$DIST:$channel" in
    external:dev|external:sit) channel_path="external/$channel" ;;
    global:dev|global:sit) channel_path="global/$channel" ;;
  esac
  printf '%s\n' "$channel_path"
}

remote_subdir() {
  local channel_path
  channel_path="$(channel_path_for "$CHANNEL")"
  if [[ -n "$VERSION" ]]; then
    echo "${channel_path}/${VERSION}"
    return
  fi
  echo "${channel_path}/latest"
}

channel_latest_subdir() {
  local channel=$1
  printf '%s/latest\n' "$(channel_path_for "$channel")"
}

installer_backend_subdir() {
  if [[ -n "$VERSION" && "${AIWORK_USE_VERSIONED_INSTALLER:-}" != "1" ]]; then
    channel_latest_subdir "$CHANNEL"
    return 0
  fi
  remote_subdir
}

detect_target_triple() {
  [[ -n "$TARGET_TRIPLE" ]] && { echo "$TARGET_TRIPLE"; return 0; }
  local os arch
  os="$(uname -s)"
  arch="$(uname -m)"
  if [[ "$os" == "Darwin" && "$arch" == "x86_64" ]]; then
    if sysctl -n hw.optional.arm64 2>/dev/null | grep -q '1'; then
      arch="arm64"
    fi
  fi
  case "$os:$arch" in
    Linux:x86_64)  echo "x86_64-unknown-linux-gnu" ;;
    Linux:aarch64) echo "aarch64-unknown-linux-gnu" ;;
    Linux:arm64)   echo "aarch64-unknown-linux-gnu" ;;
    Darwin:x86_64) echo "x86_64-apple-darwin" ;;
    Darwin:arm64)  echo "aarch64-apple-darwin" ;;
    *) fail "unsupported platform: $os $arch (use --target to override)" 2 ;;
  esac
}

cache_bust_url() {
  local url=$1
  case "$url" in
    http://*|https://*)
      case "$url" in
        *\?*) printf '%s&_t=%s\n' "$url" "$(date +%s)" ;;
        *) printf '%s?_t=%s\n' "$url" "$(date +%s)" ;;
      esac
      ;;
    *) printf '%s\n' "$url" ;;
  esac
}

# Qoder-shaped bounded download. Connect/DNS 30s; 600s transfer budget (AiWork
# artifacts are ~3x Qoder's 40-60MB bootstrap, matching TUI/CI 600s).
# curl --max-time is per-attempt; --retry-max-time (curl >= 7.71) keeps retries
# in the same 600s cycle instead of 4x600s. Older curl has no that flag and
# treats unknown options as fatal (exit 2). Probe with
# `curl --retry-max-time 0 --version` — macOS curl 8.x hides the flag from
# short `--help`. Omit the flag when the probe fails.
# A retry started just before the budget ends can still run up to --max-time.
# GNU wget restores the old --timeout trio via --dns-timeout/--connect-timeout
# plus --read-timeout=600 (idle). BusyBox wget has no split flags and no
# --tries/--progress; fall back to --timeout=600 so wget-only Alpine/container
# installs still parse.
INSTALL_CURL_CONNECT_TIMEOUT=30
INSTALL_CURL_MAX_TIME=600
INSTALL_WGET_DNS_TIMEOUT=30
INSTALL_WGET_CONNECT_TIMEOUT=30
INSTALL_WGET_READ_TIMEOUT=600
INSTALL_WGET_TIMEOUT=600
_install_wget_split_timeouts=""
_install_curl_retry_max_time=""

wget_supports_split_timeouts() {
  if [[ -z "$_install_wget_split_timeouts" ]]; then
    if wget --help 2>&1 | grep -q -- '--read-timeout'; then
      _install_wget_split_timeouts=yes
    else
      _install_wget_split_timeouts=no
    fi
  fi
  [[ "$_install_wget_split_timeouts" == yes ]]
}

curl_supports_retry_max_time() {
  if [[ -z "$_install_curl_retry_max_time" ]]; then
    # macOS curl 8.x hides this flag from `curl --help`; unknown options exit 2.
    if curl --retry-max-time 0 --version >/dev/null 2>&1; then
      _install_curl_retry_max_time=yes
    else
      _install_curl_retry_max_time=no
    fi
  fi
  [[ "$_install_curl_retry_max_time" == yes ]]
}

install_curl() {
  if curl_supports_retry_max_time; then
    curl --retry 3 --retry-delay 2 --retry-max-time "$INSTALL_CURL_MAX_TIME" \
      --connect-timeout "$INSTALL_CURL_CONNECT_TIMEOUT" --max-time "$INSTALL_CURL_MAX_TIME" "$@"
  else
    curl --retry 3 --retry-delay 2 \
      --connect-timeout "$INSTALL_CURL_CONNECT_TIMEOUT" --max-time "$INSTALL_CURL_MAX_TIME" "$@"
  fi
}

install_wget() {
  local timeout_args=() arg filtered=()
  if wget_supports_split_timeouts; then
    timeout_args=(
      --dns-timeout="$INSTALL_WGET_DNS_TIMEOUT"
      --connect-timeout="$INSTALL_WGET_CONNECT_TIMEOUT"
      --read-timeout="$INSTALL_WGET_READ_TIMEOUT"
    )
    wget "${timeout_args[@]}" "$@"
    return
  fi
  timeout_args=(--timeout="$INSTALL_WGET_TIMEOUT")
  for arg in "$@"; do
    case "$arg" in
      --tries|--tries=*|--connect-timeout=*|--read-timeout=*|--dns-timeout=*|--progress|--progress=*) continue ;;
      *) filtered+=("$arg") ;;
    esac
  done
  wget "${timeout_args[@]}" ${filtered[@]+"${filtered[@]}"}
}

downloader() {
  if command -v curl >/dev/null 2>&1; then
    echo "curl"
  elif command -v wget >/dev/null 2>&1; then
    echo "wget"
  else
    fail "neither curl nor wget found; cannot download" 3
  fi
}

download_to() {
  local src=$1
  local dst=$2
  local tool

  case "$src" in
    http://*|https://*|file://*) ;;
    *)
      [[ -f "$src" ]] || fail "local script not found: $src" 3
      cp "$src" "$dst"
      return 0
      ;;
  esac

  tool="$(downloader)"
  case "$tool" in
    curl)
      local status=0
      install_curl -fsSL -o "$dst" "$src" || status=$?
      [[ "$status" -eq 0 ]] || fail_download "$src" "$status"
      ;;
    wget)
      local status=0
      install_wget -q --tries=3 -O "$dst" "$src" || status=$?
      [[ "$status" -eq 0 ]] || fail_download "$src" "$status"
      ;;
  esac
}

try_download_to() {
  local src=$1
  local dst=$2

  case "$src" in
    http://*|https://*|file://*) ;;
    *)
      [[ -f "$src" ]] || return 1
      cp "$src" "$dst" >/dev/null 2>&1
      return $?
      ;;
  esac

  if command -v curl >/dev/null 2>&1; then
    install_curl -fsSL -o "$dst" "$src" >/dev/null 2>&1
    return $?
  fi
  if command -v wget >/dev/null 2>&1; then
    install_wget -q --tries=3 -O "$dst" "$src" >/dev/null 2>&1
    return $?
  fi
  return 1
}

try_materialize_script() {
  local src=$1
  local dst=$2

  rm -f "$dst" 2>/dev/null || true
  case "$src" in
    http://*|https://*)
      if command -v curl >/dev/null 2>&1; then
        local status=0 http_code
        http_code="$(install_curl -fsSL -w '%{http_code}' -o "$dst" "$src" 2>/dev/null)" || status=$?
        if [[ "$status" -eq 0 ]]; then
          chmod +x "$dst"
          return 0
        fi
        rm -f "$dst" 2>/dev/null || true
        [[ "$http_code" == "404" ]] && return "$INSTALLER_DOWNLOAD_NOT_FOUND"
        return "$status"
      fi
      if command -v wget >/dev/null 2>&1; then
        local status=0 wget_output
        install_wget -q --tries=3 -O "$dst" "$src" >/dev/null 2>&1 || status=$?
        if [[ "$status" -eq 0 ]]; then
          chmod +x "$dst"
          return 0
        fi
        rm -f "$dst" 2>/dev/null || true
        wget_output="$(install_wget -S --spider --tries=1 "$src" 2>&1 || true)"
        printf '%s\n' "$wget_output" | grep -Eq 'HTTP/[0-9.]+ 404' && return "$INSTALLER_DOWNLOAD_NOT_FOUND"
        return "$status"
      fi
      return 1
      ;;
    file://*)
      local local_path="${src#file://}"
      [[ -f "$local_path" ]] || return "$INSTALLER_DOWNLOAD_NOT_FOUND"
      cp "$local_path" "$dst" >/dev/null 2>&1 || return $?
      chmod +x "$dst"
      return 0
      ;;
    *)
      [[ -f "$src" ]] || return "$INSTALLER_DOWNLOAD_NOT_FOUND"
      cp "$src" "$dst" >/dev/null 2>&1 || return $?
      chmod +x "$dst"
      return 0
      ;;
  esac
}

fail_download() {
  local src=$1
  local status=$2
  if [[ "$status" =~ ^[0-9]+$ && "$status" -ge 128 ]]; then
    local signal=$((status - 128))
    fail "download process was terminated by the system (signal $signal, exit $status): $src
This is commonly caused by endpoint security, EDR, terminal/network control, or a forced process kill.
Please allowlist the release domain and retry." 3
  fi
  fail "download failed: $src" 3
}

fail_cached_update_unavailable() {
  [[ "$DRY_RUN" == true ]] || rm -f "$DTCLAW_HOME/.update_ready.json" 2>/dev/null || true
  fail "$CACHED_UPDATE_UNAVAILABLE_MESSAGE" 3
}

INSTALL_ENV_SCHEMA=""
INSTALL_ENV_CHANNEL=""
INSTALL_ENV_VERSION=""
INSTALL_ENV_TARGET_TRIPLE=""
INSTALL_ENV_FILENAME=""
INSTALL_ENV_SHA256=""
INSTALL_ENV_DISTRIBUTION=""

reset_install_env_metadata() {
  INSTALL_ENV_SCHEMA=""
  INSTALL_ENV_CHANNEL=""
  INSTALL_ENV_VERSION=""
  INSTALL_ENV_TARGET_TRIPLE=""
  INSTALL_ENV_FILENAME=""
  INSTALL_ENV_SHA256=""
  INSTALL_ENV_DISTRIBUTION=""
}

install_env_value_is_safe() {
  [[ -z "$1" ]] && return 0
  printf '%s' "$1" | grep -Eq '^[A-Za-z0-9._:/@%+=,-]*$'
}

install_env_path_component_is_safe() {
  local value=$1
  [[ -n "$value" ]] || return 1
  case "$value" in
    */*|*\\*|*..*) return 1 ;;
  esac
  return 0
}

validate_install_env_metadata_fields() {
  install_env_path_component_is_safe "$INSTALL_ENV_FILENAME" || return 2
  printf '%s' "$INSTALL_ENV_SHA256" | grep -Eq '^[0-9A-Fa-f]{64}$' || return 2
  return 0
}

assign_install_env_key() {
  local key=$1 value=$2
  install_env_value_is_safe "$value" || return 2
  case "$key" in
    INSTALL_ENV_SCHEMA) INSTALL_ENV_SCHEMA="$value" ;;
    CHANNEL) INSTALL_ENV_CHANNEL="$value" ;;
    VERSION) INSTALL_ENV_VERSION="$value" ;;
    TARGET_TRIPLE) INSTALL_ENV_TARGET_TRIPLE="$value" ;;
    FILENAME) INSTALL_ENV_FILENAME="$value" ;;
    SHA256) INSTALL_ENV_SHA256="$value" ;;
    DISTRIBUTION) INSTALL_ENV_DISTRIBUTION="$value" ;;
    PRODUCT_VERSION|DISPLAY_VERSION|GIT_COMMIT|AGENTIX_GIT_COMMIT|CLI_GIT_COMMIT|UPDATED_AT|BUILD_NUMBER|RELEASE_LABEL) ;;
    *) return 2 ;;
  esac
}

read_install_env_metadata() {
  local env_path=$1 line key value
  [[ -f "$env_path" ]] || return 1
  reset_install_env_metadata
  while IFS= read -r line || [[ -n "$line" ]]; do
    case "$line" in
      ""|\#*) continue ;;
      *=*) ;;
      *) return 2 ;;
    esac
    key="${line%%=*}"
    value="${line#*=}"
    case "$key" in
      *[!A-Z0-9_]*|"") return 2 ;;
    esac
    assign_install_env_key "$key" "$value" || return 2
  done <"$env_path"
  [[ "$INSTALL_ENV_SCHEMA" == "1" ]] || return 2
  [[ -n "$INSTALL_ENV_VERSION" && -n "$INSTALL_ENV_TARGET_TRIPLE" && -n "$INSTALL_ENV_FILENAME" && -n "$INSTALL_ENV_SHA256" ]] || return 2
  validate_install_env_metadata_fields || return 2
}

validate_cached_update_latest_from_install_env() {
  local cached_archive=$1
  local expected_triple=$2
  local install_env="$WORK_DIR/install.env"
  local env_url expected_sha env_sha cached_name

  env_url="$(cache_bust_url "${BASE_URL%/}/$(channel_latest_subdir "$CHANNEL")/$expected_triple/install.env")"
  try_download_to "$env_url" "$install_env" || return 1
  read_install_env_metadata "$install_env" || return 2
  [[ "$INSTALL_ENV_TARGET_TRIPLE" == "$expected_triple" ]] || return 3
  [[ "$INSTALL_ENV_DISTRIBUTION" == "$DIST" ]] || return 3
  [[ "$INSTALL_ENV_CHANNEL" == "$CHANNEL" ]] || return 3
  cached_name="$(basename "$cached_archive")"
  [[ "$INSTALL_ENV_FILENAME" == "$cached_name" ]] || return 3
  expected_sha="$(awk 'NF { print $1; exit }' "$cached_archive.sha256" 2>/dev/null | tr 'A-F' 'a-f' || true)"
  env_sha="$(printf '%s' "$INSTALL_ENV_SHA256" | tr 'A-F' 'a-f')"
  [[ -n "$expected_sha" && "$env_sha" == "$expected_sha" ]] || return 3
  CACHED_INSTALL_ENV_FILE="$install_env"
  return 0
}

validate_cached_update_latest() {
  local cached_archive=$1
  local cached_meta="$CACHED_UPDATE_DIR/update.json"
  local versions_json="$WORK_DIR/versions.json"
  local versions_url
  local python3_bin
  local expected_triple

  CACHED_INSTALL_ENV_FILE=""
  expected_triple="$(detect_target_triple)"
  mkdir -p "$WORK_DIR" || fail_cached_update_unavailable
  local install_env_status=0
  validate_cached_update_latest_from_install_env "$cached_archive" "$expected_triple" || install_env_status=$?
  case "$install_env_status" in
    0) return 0 ;;
    2|3) fail_cached_update_unavailable ;;
  esac

  [[ -f "$cached_meta" ]] || fail_cached_update_unavailable
  python3_bin="$(preferred_python3)"
  [[ -n "$python3_bin" ]] || fail_cached_update_unavailable
  versions_url="$(cache_bust_url "${BASE_URL%/}/$(channel_latest_subdir "$CHANNEL")/versions.json")"
  try_download_to "$versions_url" "$versions_json" || fail_cached_update_unavailable

  "$python3_bin" - "$cached_meta" "$versions_json" "$expected_triple" "$cached_archive" "$DIST" "$CHANNEL" <<'PY' \
    || fail_cached_update_unavailable
import json
import os
import sys

meta_path, versions_path, expected_triple, archive_path, dist, channel = sys.argv[1:7]
with open(meta_path, encoding="utf-8") as handle:
    meta = json.load(handle)
with open(versions_path, encoding="utf-8") as handle:
    versions = json.load(handle)

def require_identity(obj):
    if not isinstance(obj, dict):
        return
    obj_dist = obj.get("distribution")
    obj_channel = obj.get("channel")
    if obj_dist is not None and obj_dist != dist:
        raise SystemExit(1)
    if obj_channel is not None and obj_channel != channel:
        raise SystemExit(1)

require_identity(versions)
meta_triple = str(meta.get("target_triple") or "")
if meta_triple != expected_triple:
    raise SystemExit(1)
if str(meta.get("distribution") or "") != dist:
    raise SystemExit(1)
if str(meta.get("channel") or "") != channel:
    raise SystemExit(1)

latest = (versions.get("latest") or {}).get(expected_triple)
if not latest or latest != meta.get("version"):
    raise SystemExit(1)
entry = (versions.get("versions") or {}).get(latest) or {}
require_identity(entry)
artifact = (entry.get("artifacts") or {}).get(expected_triple) or {}
require_identity(artifact)
filename = str(artifact.get("filename") or "")
sha256 = str(artifact.get("sha256") or "").lower()
if not filename or filename != meta.get("filename"):
    raise SystemExit(1)
if not sha256 or sha256 != str(meta.get("sha256") or "").lower():
    raise SystemExit(1)
if os.path.basename(archive_path) != filename:
    raise SystemExit(1)
PY
}

WORK_DIR=""
STATE_ROOT_OWNER_WRITE_RESTORED_DIR=""
INSTALL_LOCK_OWNER_TOKEN=""
INSTALL_HISTORY_STARTED=false

record_outer_install_history() {
  [[ "$INSTALL_HISTORY_STARTED" == true && "$DRY_RUN" != true ]] || return 0
  bash "$WORK_DIR/install-aiwork-archive.sh" --record-install-history \
    "$DTCLAW_HOME" "$PROGRAM_DIR" "$AGENTIX_INSTALL_HISTORY_ID" installer "$1" "$2" \
    || warn "could not record installer completion history"
}

cleanup() {
  local exit_status=$?
  # Finish rollback and unlock even if the user presses Ctrl-C again.
  trap '' HUP INT TERM
  trap - EXIT
  case "$exit_status" in
    129|130|143) warn "installation cancelled; finishing rollback and cleanup" ;;
  esac
  local rollback_failed=false
  refresh_connector_rollback_protection "$DTCLAW_HOME"
  if [[ "$exit_status" -ne 0 && "$CONNECTOR_SHARED_STATE_PROTECTED" == true ]]; then
    rollback_failed=true
    warn "Shared Connector state retained after failure; shared maintenance is not rolled back. Recovery evidence: $WORK_DIR"
  fi
  if [[ "$exit_status" -ne 0 && "${INSTALL_ACTIVATION_COMMITTED:-false}" != true && -n "${CODER_APP_PACK_BACKUP_DIR:-}" ]]; then
    restore_coder_app_pack_backup || true
  fi
  if [[ "$exit_status" -ne 0 && "${INSTALL_ACTIVATION_COMMITTED:-false}" != true ]]; then
    stop_gateway_after_failed_install
    restore_protected_current_release || rollback_failed=true
    if ! restore_install_activation_snapshot; then
      rollback_failed=true
      warn "install rollback incomplete; preserved recovery snapshot at $INSTALL_ACTIVATION_SNAPSHOT_DIR (work dir: $WORK_DIR); restore the failed paths before removing this backup"
    fi
  fi
  if [[ "$exit_status" -eq 0 ]]; then
    record_outer_install_history complete "$exit_status"
  else
    record_outer_install_history failed "$exit_status"
  fi
  if [[ "$INSTALL_LOCK_HELD" == true && -n "${INSTALL_LOCK_DIR:-}" ]]; then
    release_install_lock_if_owned || true
  fi
  if [[ "$rollback_failed" != true && -n "${WORK_DIR:-}" && -d "$WORK_DIR" ]]; then
    # Private backups retain immutable Connector directory modes. Restore only
    # directory write access, without following links, before retiring this copy.
    # Cleanup must not turn a committed install into failure or mask its error.
    if ! { find "$WORK_DIR" -type d -exec chmod u+rwx {} + && rm -rf "$WORK_DIR"; }; then
      warn "installer temporary cleanup pending: $WORK_DIR"
    fi
  fi
  close_install_lock_guard
  return "$exit_status"
}
INSTALL_LOCK_INITIALIZING=false
INSTALL_LOCK_PENDING_SIGNAL=0

handle_install_signal() {
  if [[ "$INSTALL_LOCK_INITIALIZING" == true ]]; then
    INSTALL_LOCK_PENDING_SIGNAL=$1
  else
    exit "$1"
  fi
}

trap cleanup EXIT
trap 'handle_install_signal 129' HUP
trap 'handle_install_signal 130' INT
trap 'handle_install_signal 143' TERM

installer_tmp_root() {
  local root="${AGENTIX_INSTALL_TMPDIR:-$DTCLAW_HOME/.install/tmp}"
  root="${root/#\~/$HOME}"
  mkdir -p "$root" || fail "failed to create installer temp dir: $root" 5
  chmod 700 "$root" 2>/dev/null || true
  (cd "$root" 2>/dev/null && pwd -P) || printf '%s\n' "$root"
}

prune_stale_installer_tmp() {
  local root=$1
  [[ -d "$root" ]] || return 0
  case "$root" in
    ""|"/") return 0 ;;
  esac
  # A remaining activation snapshot may be the only copy of credentials after
  # failed rollback (or an interrupted installer). Never age it out.
  find "$root" -maxdepth 1 -type d \( -name 'aiwork-install.*' -o -name 'dtcoder-install.*' \) -mtime +2 \
    -exec sh -c 'for dir do [ -d "$dir/install-activation-rollback" ] || [ -f "$dir/storage-forward-recovery-required" ] || [ -f "$dir/install-recovery-incomplete" ] || rm -rf "$dir"; done' sh {} + 2>/dev/null || true
}

create_installer_work_dir() {
  local root
  if [[ "$DRY_RUN" == true ]]; then
    root="${AGENTIX_INSTALL_TMPDIR:-$DTCLAW_HOME/.install/tmp}"
    root="${root/#\~/$HOME}"
    printf '%s\n' "$root/aiwork-install.DRYRUN"
    return 0
  fi
  root="$(installer_tmp_root)"
  prune_stale_installer_tmp "$root"
  mktemp -d "$root/aiwork-install.XXXXXX" || fail "failed to create installer work dir under $root" 5
}

install_lock_pid_exists() {
  local pid=$1
  [[ "$pid" =~ ^[0-9]+$ && "$pid" -gt 0 ]] || return 1
  kill -0 "$pid" 2>/dev/null && return 0
  # `kill -0` fails with EPERM for another user's live process.  Treat a PID
  # visible to ps as active so a cross-user install window does not fail open.
  ps -p "$pid" -o pid= >/dev/null 2>&1
}

linux_process_start_time_ticks() {
  local pid=$1
  [[ -r "/proc/$pid/stat" ]] || return 1
  local stat tail ticks
  stat="$(cat "/proc/$pid/stat" 2>/dev/null)" || return 1
  tail="${stat##*) }"
  ticks="$(printf '%s\n' "$tail" | awk '{print $20}')" || return 1
  [[ "$ticks" =~ ^[0-9]+$ ]] || return 1
  printf 'linux_starttime:%s\n' "$ticks"
}

ps_process_start_token() {
  local pid=$1
  local started_at
  started_at="$(ps -p "$pid" -o lstart= 2>/dev/null | sed -n '1{s/^[[:space:]]*//;s/[[:space:]]*$//;p;}')" || return 1
  [[ -n "$started_at" ]] || return 1
  printf 'ps_lstart:%s\n' "$started_at"
}

process_start_token() {
  local pid=$1
  linux_process_start_time_ticks "$pid" || ps_process_start_token "$pid"
}

install_lock_process_start_token() {
  local lock_dir=$1
  local marker="$lock_dir/in-progress.json"
  [[ -f "$marker" ]] || return 1
  local python3_bin token
  python3_bin="$(preferred_python3)"
  if [[ -n "$python3_bin" ]]; then
    "$python3_bin" - "$marker" <<'PY' 2>/dev/null
import json
import sys

try:
    with open(sys.argv[1], "r", encoding="utf-8") as f:
        token = json.load(f).get("process_start_token")
except Exception:
    raise SystemExit(1)
if not isinstance(token, str) or not token.strip():
    raise SystemExit(1)
print(token.strip())
PY
    return $?
  fi
  token="$(shell_json_string_field "$marker" "process_start_token" 2>/dev/null || true)"
  [[ -n "$token" ]] || return 1
  printf '%s\n' "$token"
}

install_lock_owner_token() {
  local lock_dir=$1
  local marker="$lock_dir/in-progress.json"
  [[ -f "$marker" ]] || return 1
  local python3_bin token
  python3_bin="$(preferred_python3)"
  if [[ -n "$python3_bin" ]]; then
    "$python3_bin" - "$marker" <<'PY' 2>/dev/null
import json
import sys

try:
    with open(sys.argv[1], "r", encoding="utf-8") as f:
        token = json.load(f).get("owner_token")
except Exception:
    raise SystemExit(1)
if not isinstance(token, str) or not token.strip():
    raise SystemExit(1)
print(token.strip())
PY
    return $?
  fi
  # Without a JSON runtime accept only our complete, fixed-order marker schema.
  # A matching owner substring in damaged JSON is not sufficient evidence.
  local document pattern
  document="$(cat "$marker" 2>/dev/null)" || return 1
  pattern='^[[:space:]]*\{[[:space:]]*"pid"[[:space:]]*:[[:space:]]*[0-9]+[[:space:]]*,[[:space:]]*"started_at"[[:space:]]*:[[:space:]]*"[0-9TZ:+.-]+"[[:space:]]*,[[:space:]]*("process_start_token"[[:space:]]*:[[:space:]]*"[A-Za-z0-9_:[:space:]]+"[[:space:]]*,[[:space:]]*)?"owner_token"[[:space:]]*:[[:space:]]*"[0-9]+:[0-9]+:[0-9]+:[0-9]+"[[:space:]]*\}[[:space:]]*$'
  [[ "$document" =~ $pattern ]] || return 1
  token="$(shell_json_string_field "$marker" "owner_token" 2>/dev/null || true)"
  [[ -n "$token" ]] || return 1
  printf '%s\n' "$token"
}

install_lock_tokens_match_or_are_inconclusive() {
  local expected=$1
  local observed=$2
  [[ -n "$expected" && -n "$observed" ]] || return 0
  [[ "$expected" == *:* && "$observed" == *:* ]] || return 0
  local expected_scheme="${expected%%:*}"
  local observed_scheme="${observed%%:*}"
  [[ "$expected_scheme" == "$observed_scheme" ]] || return 0
  [[ "$expected" == "$observed" ]]
}

install_lock_pid_is_active() {
  local pid=$1
  local lock_dir=$2
  install_lock_pid_exists "$pid" || return 1

  local expected observed
  expected="$(install_lock_process_start_token "$lock_dir" 2>/dev/null || true)"
  [[ -n "$expected" ]] || return 0
  observed="$(process_start_token "$pid" 2>/dev/null || true)"
  [[ -n "$observed" ]] || return 0
  install_lock_tokens_match_or_are_inconclusive "$expected" "$observed"
}

new_install_lock_owner_token() {
  printf '%s:%s:%s:%s\n' "$$" "$(date +%s 2>/dev/null || printf '0')" "${RANDOM:-0}" "${RANDOM:-0}"
}

install_lock_owned_by_current_installer() {
  [[ -n "${INSTALL_LOCK_DIR:-}" && -n "${INSTALL_LOCK_OWNER_TOKEN:-}" ]] || return 1
  local owner_token
  owner_token="$(install_lock_owner_token "$INSTALL_LOCK_DIR" 2>/dev/null || true)"
  [[ -n "$owner_token" && "$owner_token" == "$INSTALL_LOCK_OWNER_TOKEN" ]]
}

release_install_lock_if_owned() {
  install_lock_owned_by_current_installer || {
    warn "install lock owner changed; leaving lock in place: $INSTALL_LOCK_DIR"
    return 0
  }
  retire_install_lock_dir "$INSTALL_LOCK_DIR" "$$" "$INSTALL_LOCK_OWNER_TOKEN"
}

# FD 9 belongs to this installation transaction. Operation children inherit it
# until the complete identity directory is retired. A later transaction gets
# a new inode, so an old backend's background service cannot pin its lock.
INSTALL_LOCK_GUARD_HELD=false
INSTALL_LOCK_GUARD_PATH=""

install_lock_backend_available() {
  if [[ "$(uname -s)" == Darwin ]]; then
    local python3_bin
    python3_bin="$(preferred_python3)"
    [[ -n "$python3_bin" ]] && "$python3_bin" -c 'import fcntl, os' >/dev/null 2>&1
    return $?
  fi
  if [[ "$(uname -s)" == Linux ]] && command -v flock >/dev/null 2>&1; then
    return 0
  fi
  command -v perl >/dev/null 2>&1 && return 0
  [[ -n "$(preferred_python3)" ]]
}

lock_install_guard_fd() {
  local guard_path=$1
  if [[ "$(uname -s)" == Linux ]] && command -v flock >/dev/null 2>&1; then
    [[ /dev/fd/9 -ef "$guard_path" ]] || return 1
    flock -n 9
  elif [[ "$(uname -s)" != Darwin ]] && command -v perl >/dev/null 2>&1; then
    perl -MFcntl=:flock -e '
      my @fd = stat(STDIN); my @path = stat($ARGV[0]);
      @fd && @path && $fd[0] == $path[0] && $fd[1] == $path[1]
        or die "install lock descriptor does not match its path\n";
      flock(STDIN, LOCK_EX | LOCK_NB) or die "install lock: $!\n";
    ' "$guard_path" <&9
  else
    local python3_bin
    python3_bin="$(preferred_python3)"
    [[ -n "$python3_bin" ]] || {
      warn "a working Python 3 is required for this install lock"
      return 1
    }
    # fstat verifies the inherited FD even on Darwin's synthetic /dev/fd.
    "$python3_bin" -c '
import fcntl, os, sys
fd, path = os.fstat(9), os.stat(sys.argv[1])
if (fd.st_dev, fd.st_ino) != (path.st_dev, path.st_ino):
    raise SystemExit("install lock descriptor does not match its path")
fcntl.flock(9, fcntl.LOCK_EX | fcntl.LOCK_NB)
' "$guard_path"
  fi
}

install_lock_guard_is_held() {
  [[ "$INSTALL_LOCK_GUARD_HELD" == true && -n "$INSTALL_LOCK_GUARD_PATH" \
    && ! -L "$INSTALL_LOCK_GUARD_PATH" ]] || return 1
  lock_install_guard_fd "$INSTALL_LOCK_GUARD_PATH"
}

acquire_install_lock_guard() {
  local guard_path="$1/guard" create=${2:-false}
  [[ -d "$1" && ! -L "$1" ]] || return 1
  if [[ "$INSTALL_LOCK_GUARD_HELD" == true ]]; then
    [[ "$INSTALL_LOCK_GUARD_PATH" == "$guard_path" ]] && install_lock_guard_is_held
    return $?
  fi
  # Only the mkdir winner creates a guard. Reclaimers must open the existing
  # inode without recreating a missing fence or trusting a parent flag alone.
  if [[ "$create" == true ]]; then
    [[ ! -e "$guard_path" && ! -L "$guard_path" ]] || return 1
    exec 9>"$guard_path" || return 1
  else
    [[ -f "$guard_path" && ! -L "$guard_path" ]] || return 1
    if [[ "${DTCODER_PARENT_INSTALL_LOCK_HELD:-false}" != true ]]; then
      exec 9<"$guard_path" || return 1
    fi
  fi
  # A cancel recorded during initialization must not interrupt the helper
  # before PID/owner publication completes. The lock applies to our shared FD.
  if ! (trap '' HUP INT TERM; lock_install_guard_fd "$guard_path"); then
    exec 9>&-
    return 1
  fi
  INSTALL_LOCK_GUARD_PATH="$guard_path"
  INSTALL_LOCK_GUARD_HELD=true
}

close_install_lock_guard() {
  [[ "$INSTALL_LOCK_GUARD_HELD" == true ]] || return 0
  exec 9>&-
  INSTALL_LOCK_GUARD_HELD=false
  INSTALL_LOCK_GUARD_PATH=""
}

retire_install_lock_dir() {
  local lock_dir=$1 expected_pid=$2 expected_owner_token=$3
  [[ "$INSTALL_LOCK_GUARD_PATH" == "$lock_dir/guard" ]] || return 1
  install_lock_guard_is_held || return 1
  [[ "$expected_pid" =~ ^[0-9]+$ && "$expected_pid" -gt 0 \
    && "$expected_owner_token" =~ ^[0-9]+:[0-9]+:[0-9]+:[0-9]+$ \
    && "$expected_owner_token" == "$expected_pid:"* ]] || return 1
  [[ -d "$lock_dir" && ! -L "$lock_dir" ]] || return 1
  local retired current_pid current_owner_token
  retired="$(mktemp -d "$lock_dir.release.XXXXXX")" || return 1
  current_pid="$(cat "$lock_dir/pid" 2>/dev/null || true)"
  current_owner_token="$(install_lock_owner_token "$lock_dir" 2>/dev/null || true)"
  if [[ "$current_pid" != "$expected_pid" || "$current_owner_token" != "$expected_owner_token" ]]; then
    rmdir "$retired" 2>/dev/null || warn "install lock cleanup pending: $retired"
    warn "install lock owner changed; leaving lock in place: $lock_dir"
    return 1
  fi
  if ! install_lock_guard_is_held; then
    rmdir "$retired" 2>/dev/null || warn "install lock cleanup pending: $retired"
    return 1
  fi
  # FD 9 remains inherited by mv even if only the waiting shell is killed.
  if ! mv "$lock_dir" "$retired/lock"; then
    rmdir "$retired" 2>/dev/null || warn "install lock cleanup pending: $retired"
    warn "failed to release install lock; owner metadata retained: $lock_dir"
    return 1
  fi
  INSTALL_LOCK_HELD=false
  close_install_lock_guard
  # The public identity is retired. Garbage cleanup cannot undo this success.
  rm -f "$retired/lock/in-progress.json" "$retired/lock/pid" "$retired/lock/guard" \
    || warn "install lock cleanup pending (retired private directory; installation may be retried): $retired/lock"
  rmdir "$retired/lock" 2>/dev/null || warn "install lock cleanup pending (retired private directory; installation may be retried): $retired/lock"
  rmdir "$retired" 2>/dev/null || warn "install lock cleanup pending (retired private directory; installation may be retried): $retired"
  return 0
}

fail_install_lock_recovery() {
  local reason=$1 lock_path=$2 code=${3:-LOCK_IDENTITY_UNKNOWN}
  emit_install_lock_error "$code" "$lock_path"
  fail "$reason: $lock_path
Keep the lock and installation recovery journals. A dead parent PID does not prove its child writers have stopped.
Recovery steps (no source checkout or installed documentation required):
1. Pause installation, upgrade and automatic updates for this program root.
2. Verify the owner PID, process start identity, child writers and existing guard. Do not follow lock-directory symlinks or replace the guard.
3. Record the install command, distribution, program/state roots and this error; preserve transaction snapshots and rollback receipts with the lock.
4. Only after all writers have exited and the existing owner/guard can be verified, retry the same installer with the same distribution and roots. Its normal lock checks must still pass.
5. If owner identity or transaction safety remains unverified, keep the evidence and ask the installation maintainer for recovery. Do not delete or recreate the public lock to force installation." 7
}

# Stable, line-delimited diagnostics; normal Linux installation needs no JSON runtime.
install_error_json_quote() {
  local value=$1 char escaped i
  value=${value//\\/\\\\}; value=${value//\"/\\\"}
  for ((i=1; i<32; i++)); do
    printf -v char "\\$(printf '%03o' "$i")"
    printf -v escaped '\\u%04x' "$i"
    value=${value//"$char"/"$escaped"}
  done
  printf '"%s"' "$value"
}

emit_install_lock_error() {
  local reason=$1 lock_path=${2:-${INSTALL_LOCK_DIR:-}}
  printf 'AIWORK_INSTALL_ERROR_V1 {"schema_version":1,"stage":"lock","reason":"%s","lock_path":%s,"recovery":"inspect with recover-aiwork-install-lock.py; do not delete or fabricate lock files"}\n' \
    "$reason" "$(install_error_json_quote "$lock_path")" >&2
}

ensure_install_recovery_authorized() {
  local recovery="$1/.install.recovery" python3_bin
  [[ -e "$recovery" || -L "$recovery" ]] || return 0
  python3_bin="$(preferred_python3)"
  if [[ -n "$python3_bin" && -d "$recovery" && ! -L "$recovery" ]]; then
    if "$python3_bin" - "$recovery/guard" "${AIWORK_INSTALL_RECOVERY_FD:-}" <<'PYRECOVERY'
import fcntl, os, stat, sys
try:
    fd = int(sys.argv[2])
    if fd < 10:
        raise ValueError("invalid recovery descriptor")
    path = os.lstat(sys.argv[1])
    opened = os.fstat(fd)
    if not stat.S_ISREG(path.st_mode) or path.st_uid != os.getuid() or path.st_nlink != 1:
        raise ValueError("invalid recovery guard")
    if (path.st_dev, path.st_ino) != (opened.st_dev, opened.st_ino):
        raise ValueError("recovery descriptor changed")
    fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (OSError, ValueError):
    raise SystemExit(1)
PYRECOVERY
    then return 0; fi
  fi
  emit_install_lock_error RECOVERY_REQUIRED "$recovery"
  fail "install recovery requires verified resume; leaving it in place: $recovery" 7
}

acquire_install_lock() {
  [[ "$DRY_RUN" == true ]] && return 0

  ensure_state_root_owner_write_for_upgrade "$DTCLAW_HOME"
  # The release payload is owned by the logical program installation, not its
  # state root. `current` is swapped during activation, so keep the lock on its
  # stable parent rather than inside the release it points at.
  local lock_root
  if [[ "$(basename "$PROGRAM_DIR")" == "current" ]]; then
    lock_root="$(dirname "$PROGRAM_DIR")"
  else
    lock_root="$PROGRAM_DIR"
  fi
  INSTALL_LOCK_DIR="$lock_root/.install.lock"
  ensure_install_recovery_authorized "$lock_root"
  mkdir -p "$lock_root" || fail "failed to create program dir for lock: $lock_root" 7
  if ! install_lock_backend_available; then
    if [[ "$(uname -s)" == Darwin ]]; then
      fail "macOS installation requires Python 3 with fcntl. Install Python 3 and retry." 7 LOCK_BACKEND_UNAVAILABLE
    fi
    fail "installation requires flock, Perl, or a working Python 3 for its process lock" 7 LOCK_BACKEND_UNAVAILABLE
  fi
  local legacy_claim
  for legacy_claim in "$lock_root"/.install.lock.retiring-*; do
    if [[ -e "$legacy_claim" || -L "$legacy_claim" ]]; then
      fail_install_lock_recovery "legacy install retirement needs verified recovery; leaving it in place" "$legacy_claim" LOCK_LEGACY_RETIREMENT_PRESENT
    fi
  done
  INSTALL_LOCK_DIR="$lock_root/.install.lock"
  INSTALL_IN_PROGRESS_MARKER="$INSTALL_LOCK_DIR/in-progress.json"
  if [[ "${DTCODER_PARENT_INSTALL_LOCK_HELD:-false}" == true ]]; then
    acquire_install_lock_guard "$INSTALL_LOCK_DIR" \
      || fail_install_lock_recovery "parent install lock cannot be verified" "$INSTALL_LOCK_DIR" LOCK_GUARD_UNVERIFIABLE
  fi

  local pid attempt started_at start_token
  # Prepare external-command results before publishing the lock directory.
  INSTALL_LOCK_OWNER_TOKEN="$(new_install_lock_owner_token)"
  started_at="$(date -u '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || date '+%s')"
  start_token="$(process_start_token "$$" 2>/dev/null || true)"
  for ((attempt = 0; attempt < 2; attempt++)); do
    INSTALL_LOCK_INITIALIZING=true
    # Preserve a pending cancel while mkdir and builtin metadata writes finish.
    if (trap '' HUP INT TERM; mkdir "$INSTALL_LOCK_DIR") 2>/dev/null; then
      INSTALL_LOCK_HELD=true
      acquire_install_lock_guard "$INSTALL_LOCK_DIR" true \
        || fail "failed to initialize install lock guard: $INSTALL_LOCK_DIR" 7
      printf '%s\n' "$$" >"$INSTALL_LOCK_DIR/pid" 2>/dev/null \
        || fail "failed to write install lock pid: $INSTALL_LOCK_DIR/pid" 7
      write_install_in_progress_marker "$started_at" "$start_token" \
        || fail "failed to write install lock marker: $INSTALL_IN_PROGRESS_MARKER" 7
      INSTALL_LOCK_INITIALIZING=false
      [[ "$INSTALL_LOCK_PENDING_SIGNAL" == 0 ]] || exit "$INSTALL_LOCK_PENDING_SIGNAL"
      ensure_install_recovery_authorized "$lock_root"
      return 0
    fi
    INSTALL_LOCK_INITIALIZING=false
    [[ "$INSTALL_LOCK_PENDING_SIGNAL" == 0 ]] || exit "$INSTALL_LOCK_PENDING_SIGNAL"

    pid="$(cat "$INSTALL_LOCK_DIR/pid" 2>/dev/null || true)"
    if [[ ! "$pid" =~ ^[0-9]+$ || "$pid" -le 0 ]]; then
      fail_install_lock_recovery "install lock is being initialized or is not owner-verifiable" "$INSTALL_LOCK_DIR" LOCK_IDENTITY_UNKNOWN
    fi
    if install_lock_pid_is_active "$pid" "$INSTALL_LOCK_DIR"; then
      fail "another AiWork install appears to be running (pid $pid): $INSTALL_LOCK_DIR" 7 LOCK_OWNER_ACTIVE
    fi

    if [[ -d "$INSTALL_LOCK_DIR" && ! -L "$INSTALL_LOCK_DIR" ]]; then
      local stale_owner_token
      stale_owner_token="$(install_lock_owner_token "$INSTALL_LOCK_DIR" 2>/dev/null || true)"
      [[ "$stale_owner_token" =~ ^[0-9]+:[0-9]+:[0-9]+:[0-9]+$ \
        && "$stale_owner_token" == "$pid:"* ]] \
        || fail_install_lock_recovery "install lock is not owner-verifiable" "$INSTALL_LOCK_DIR" LOCK_IDENTITY_UNKNOWN
      acquire_install_lock_guard "$INSTALL_LOCK_DIR" \
        || fail_install_lock_recovery "another install holds the program lock or its lock cannot be verified" "$INSTALL_LOCK_DIR" LOCK_GUARD_UNVERIFIABLE
      warn "removing stale install lock: $INSTALL_LOCK_DIR"
      retire_install_lock_dir "$INSTALL_LOCK_DIR" "$pid" "$stale_owner_token" \
        || fail_install_lock_recovery "failed to reclaim stale install lock safely" "$INSTALL_LOCK_DIR"
      continue
    fi

    fail_install_lock_recovery "install lock path exists but is not a removable lock directory" "$INSTALL_LOCK_DIR"
  done

  fail "failed to acquire install lock: $INSTALL_LOCK_DIR" 7
}

write_install_in_progress_marker() {
  [[ "$INSTALL_LOCK_HELD" == true && -n "${INSTALL_IN_PROGRESS_MARKER:-}" ]] || return 0
  local started_at=$1 process_start_token=$2
  if [[ -n "$process_start_token" ]]; then
    printf '{\n  "pid": %s,\n  "started_at": "%s",\n  "process_start_token": "%s",\n  "owner_token": "%s"\n}\n' \
      "$$" "$started_at" "$process_start_token" "$INSTALL_LOCK_OWNER_TOKEN" >"$INSTALL_IN_PROGRESS_MARKER"
  else
    printf '{\n  "pid": %s,\n  "started_at": "%s",\n  "owner_token": "%s"\n}\n' \
      "$$" "$started_at" "$INSTALL_LOCK_OWNER_TOKEN" >"$INSTALL_IN_PROGRESS_MARKER"
  fi
}

restore_state_root_owner_write_for_upgrade() {
  local dir=$1
  [[ -d "$dir" ]] || return 0
  if chmod -R u+w "$dir" 2>/dev/null; then
    return 0
  fi
  fail "failed to restore owner write permission for install state root: $dir
Run this manually, then retry the installer:
  chmod -R u+w \"$dir\"" 7
}

ensure_state_root_owner_write_for_upgrade() {
  local dir=$1
  if [[ "$STATE_ROOT_OWNER_WRITE_RESTORED_DIR" == "$dir" ]]; then
    return 0
  fi
  restore_state_root_owner_write_for_upgrade "$dir"
  STATE_ROOT_OWNER_WRITE_RESTORED_DIR="$dir"
}

diagnose_version_failure() {
  local bin=$1
  local os
  os="$(uname -s)"
  case "$os" in
    Darwin)
      if command -v xattr >/dev/null 2>&1 && xattr -l "$bin" 2>/dev/null | grep -q com.apple.quarantine; then
        warn "macOS Gatekeeper quarantine detected on $bin"
        warn "Fix: xattr -d com.apple.quarantine \"$bin\""
      else
        warn "macOS: binary may lack code signature. Try: codesign -s - --force \"$bin\""
      fi
      if command -v codesign >/dev/null 2>&1; then
        warn "codesign details for $bin:"
        codesign -dv --verbose=4 "$bin" 2>&1 | sed 's/^/[codesign] /' >&2 || true
      fi
      if command -v spctl >/dev/null 2>&1; then
        warn "spctl assessment for $bin:"
        spctl -a -vvv -t execute "$bin" 2>&1 | sed 's/^/[spctl] /' >&2 || true
      fi
      ;;
    Linux)
      if command -v ldd >/dev/null 2>&1; then
        local ldd_out
        ldd_out="$(ldd "$bin" 2>&1)" || true
        if echo "$ldd_out" | grep -q 'not found'; then
          warn "missing shared libraries for $bin:"
          echo "$ldd_out" | grep 'not found' | sed 's/^/       /' >&2
        fi
      fi
      ;;
  esac
}

materialize_script() {
  local src=$1
  local dst=$2
  download_to "$src" "$dst"
  chmod +x "$dst"
}

maybe_redirect_root_installer() {
  [[ "$INSTALLER_SCOPE" == "root" ]] || return 0
  [[ "${INSTALL_DTCODER_REDIRECTED:-false}" != true ]] || return 0

  if [[ "$CHANNEL_EXPLICIT" != true ]]; then
    CHANNEL="$ROOT_DEFAULT_CHANNEL"
  fi
  CHANNEL="$(normalize_channel "$CHANNEL")"

  local installer_url installer subdir
  subdir="$(channel_latest_subdir "$CHANNEL")"
  installer_url="$(cache_bust_url "${BASE_URL%/}/${subdir}/install-aiwork.sh")"
  installer="$WORK_DIR/install-aiwork-channel.sh"

  # Bash 3.2 treats an empty array expansion as unbound under `set -u`.
  local redirect_args=()
  if [[ ${#ORIGINAL_ARGS[@]} -gt 0 ]]; then
    redirect_args=("${ORIGINAL_ARGS[@]}")
  fi
  if [[ "$CHANNEL_EXPLICIT" != true ]]; then
    redirect_args+=(--channel "$CHANNEL")
  fi

  info "root installer dispatch: channel=$CHANNEL"
  info "channel installer: $installer_url"
  if [[ "$DRY_RUN" == true ]]; then
    echo "[dry-run] download $installer_url -> $installer"
    echo "[dry-run] INSTALL_DTCODER_REDIRECTED=true bash $installer ${redirect_args[*]}"
    exit 0
  fi

  materialize_script "$installer_url" "$installer"
  INSTALL_DTCODER_REDIRECTED=true bash "$installer" "${redirect_args[@]}"
  exit 0
}

archive_installer_supported_options() {
  local installer=$1
  bash "$installer" --print-supported-options 2>/dev/null
}

verify_archive_installer_option_contract() {
  local installer=$1 installer_url=$2
  shift 2
  local supported
  if ! supported="$(archive_installer_supported_options "$installer")"; then
    fail "install script version mismatch: downloaded install-aiwork-archive.sh does not expose its supported option contract.
child installer: $installer_url" 3
  fi
  local arg
  for arg in "$@"; do
    [[ "$arg" == --* ]] || continue
    if ! grep -Fxq -- "$arg" <<< "$supported"; then
      fail "install script version mismatch: downloaded install-aiwork-archive.sh does not support required option: $arg
child installer: $installer_url" 3
    fi
  done
}

run_dtclaw_installer() {
  local package_subdir backend_subdir installer_url installer_backend_url installer local_installer release_root supported_options
  package_subdir="$(remote_subdir)"
  backend_subdir="$(installer_backend_subdir)"
  installer_url="${BASE_URL%/}/${backend_subdir}/install-aiwork-archive.sh"
  installer_backend_url="$installer_url"
  if [[ -z "$VERSION" || "$backend_subdir" == "$(channel_latest_subdir "$CHANNEL")" ]]; then
    installer_url="$(cache_bust_url "$installer_url")"
    installer_backend_url="$installer_url"
  fi
  installer="$WORK_DIR/install-aiwork-archive.sh"
  local_installer=""
  if [[ -n "$SCRIPT_DIR" && "$BASE_URL_EXPLICIT" != true && "$BASE_URL" == "$DEFAULT_DTCLAW_BASE_URL" ]]; then
    local_installer="$SCRIPT_DIR/install-aiwork-archive.sh"
  fi
  release_root="$PROGRAM_ROOT/$DIST/releases"

  local args=(--base-url "$BASE_URL" --dist "$DIST" --program-root "$PROGRAM_ROOT" --release-root "$release_root" --bin-dir "$HOME/.local/bin" --state-dir "$DTCLAW_HOME" --install-source oss)
  if [[ -n "$VERSION" ]]; then
    args+=(--version "${REQUESTED_VERSION:-$VERSION}")
  else
    args+=(--channel "$CHANNEL")
  fi
  [[ -n "$VERSION" ]] && args+=(--channel "$CHANNEL")
  [[ -n "$TARGET_TRIPLE" ]] && args+=(--target "$TARGET_TRIPLE")
  [[ "$DRY_RUN" == true ]] && args+=(--dry-run)
  [[ "$NO_SYMLINK" == true ]] && args+=(--no-symlink)
  if [[ -n "$CACHED_UPDATE_DIR" ]]; then
    local cached_archive cached_sha cached_manifest
    cached_archive="$(find "$CACHED_UPDATE_DIR" -maxdepth 1 -type f -name '*.tar.gz' | head -n 1 || true)"
    [[ -n "$cached_archive" ]] || fail "cached update archive not found in $CACHED_UPDATE_DIR" 3
    cached_sha="$cached_archive.sha256"
    cached_manifest="$CACHED_UPDATE_DIR/manifest.json"
    [[ -f "$cached_sha" ]] || fail "cached update checksum not found: $cached_sha" 3
    [[ -f "$cached_manifest" ]] || fail "cached update manifest not found: $cached_manifest" 3
    validate_cached_update_latest "$cached_archive"
    args+=(--archive-file "$cached_archive" --archive-sha256-file "$cached_sha" --manifest-file "$cached_manifest")
    [[ -n "$CACHED_INSTALL_ENV_FILE" ]] && args+=(--install-env-file "$CACHED_INSTALL_ENV_FILE")
  fi

  info "AiWork installer backend: $installer_url"
  if [[ -n "$VERSION" && "$backend_subdir" == "$(channel_latest_subdir "$CHANNEL")" ]]; then
    info "requested package version: ${REQUESTED_VERSION:-$VERSION} (metadata source: ${BASE_URL%/}/$package_subdir)"
  fi
  info "State dir:         $DTCLAW_HOME"
  if [[ "$DRY_RUN" == true ]]; then
    if [[ -n "$local_installer" && -f "$local_installer" ]]; then
      echo "[dry-run] copy $local_installer -> $installer"
    else
      echo "[dry-run] download $installer_url -> $installer"
    fi
    echo "[dry-run] bash $installer ${args[*]}"
    return 0
  fi

  if [[ -n "$local_installer" && -f "$local_installer" ]]; then
    cp "$local_installer" "$installer" || fail "failed to copy local AiWork installer backend: $local_installer" 3
    chmod +x "$installer"
  else
    local download_status=0
    try_materialize_script "$installer_url" "$installer" || download_status=$?
    if [[ "$download_status" -ne 0 ]]; then
      if [[ "$download_status" -eq "$INSTALLER_DOWNLOAD_NOT_FOUND" && -n "$VERSION" && "$backend_subdir" != "$(channel_latest_subdir "$CHANNEL")" ]]; then
        local fallback_installer_url fallback_download_status=0
        fallback_installer_url="$(cache_bust_url "${BASE_URL%/}/$(channel_latest_subdir "$CHANNEL")/install-aiwork-archive.sh")"
        warn "versioned installer backend not available for requested version ${REQUESTED_VERSION:-$VERSION}; using ${CHANNEL}/latest backend while keeping requested package version"
        info "AiWork installer backend fallback: $fallback_installer_url"
        try_materialize_script "$fallback_installer_url" "$installer" || fallback_download_status=$?
        if [[ "$fallback_download_status" -ne 0 ]]; then
          fail_download "$fallback_installer_url" "$fallback_download_status"
        fi
        installer_backend_url="$fallback_installer_url"
      elif [[ "$download_status" -eq "$INSTALLER_DOWNLOAD_NOT_FOUND" && -n "$VERSION" && "$backend_subdir" == "$(channel_latest_subdir "$CHANNEL")" ]]; then
        local versioned_installer_url versioned_download_status=0
        versioned_installer_url="${BASE_URL%/}/$package_subdir/install-aiwork-archive.sh"
        warn "${CHANNEL}/latest installer backend not available for requested version ${REQUESTED_VERSION:-$VERSION}; using versioned backend"
        info "AiWork installer backend fallback: $versioned_installer_url"
        try_materialize_script "$versioned_installer_url" "$installer" || versioned_download_status=$?
        if [[ "$versioned_download_status" -ne 0 ]]; then
          fail_download "$versioned_installer_url" "$versioned_download_status"
        fi
        installer_backend_url="$versioned_installer_url"
      else
        fail_download "$installer_url" "$download_status"
      fi
    fi
  fi
  # Receipt ownership is required from every selected backend, including
  # historical/versioned fallbacks. Refuse before executing an older child.
  args+=(--marker-receipt-dir "${DTCODER_INSTALL_MARKER_RECEIPT_DIR:-$WORK_DIR/installed-marker-receipts}")
  if [[ "$CONFIG_COMPAT_PRIVATE_DEFERRED" == true ]]; then
    args+=(--private-compat-work-dir "$WORK_DIR")
    CONFIG_COMPAT_RESTORE_PROGRAM_DIR="$WORK_DIR/config-rollback-repairer"
    CONFIG_COMPAT_REPAIR_PROGRAM_DIR="$CONFIG_COMPAT_RESTORE_PROGRAM_DIR"
  fi
  verify_archive_installer_option_contract "$installer" "$installer_backend_url" "${args[@]}"
  supported_options="$(archive_installer_supported_options "$installer")"
  if grep -Fxq -- --defer-gateway-start <<< "$supported_options" \
    && grep -Fxq -- --start-gateway-only <<< "$supported_options"; then
    args+=(--defer-gateway-start)
    ARCHIVE_GATEWAY_START_DEFERRED=true
  else
    ARCHIVE_GATEWAY_MAY_HAVE_STARTED=true
  fi
  if [[ "$DRY_RUN" != true ]] && grep -q '^record_install_history()' "$installer"; then
    export AGENTIX_INSTALL_HISTORY_ID="$(date +%s)-$$-${RANDOM}"
    if bash "$installer" --record-install-history "$DTCLAW_HOME" "$PROGRAM_DIR" \
      "$AGENTIX_INSTALL_HISTORY_ID" started started 0; then
      INSTALL_HISTORY_STARTED=true
    else
      unset AGENTIX_INSTALL_HISTORY_ID
      warn "could not start installation history"
    fi
  fi
  settle_running_processes_before_overwrite
  DTCODER_INSTALL_MARKER_RECEIPT_DIR="${DTCODER_INSTALL_MARKER_RECEIPT_DIR:-$WORK_DIR/installed-marker-receipts}" CONFIG_COMPAT_REPAIR_PROGRAM_DIR="${CONFIG_COMPAT_REPAIR_PROGRAM_DIR:-}" CONFIG_COMPAT_ROLLBACK_RECEIPT="${CONFIG_COMPAT_ROLLBACK_RECEIPT:-}" AGENTIX_DEFER_INSTALL_FINALIZATION=1 DTCODER_PARENT_INSTALL_LOCK_HELD=true bash "$installer" "${args[@]}"
  verify_requested_version_installed_marker
}

start_gateway_after_install() {
  [[ "$ARCHIVE_GATEWAY_START_DEFERRED" == true ]] || return 0
  bash "$WORK_DIR/install-aiwork-archive.sh" --start-gateway-only \
    --dist "$DIST" --state-dir "$DTCLAW_HOME" --install-dir "$PROGRAM_DIR"
}

stop_gateway_after_failed_install() {
  [[ "$ARCHIVE_GATEWAY_MAY_HAVE_STARTED" == true ]] || return 0
  local product_bin="$PROGRAM_ROOT/$DIST/current/bin/$(product_command_for_dist "$DIST")"
  [[ -x "$product_bin" ]] || return 0
  AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_ROOT/$DIST/current" \
    "$product_bin" gateway stop >/dev/null 2>&1 || warn "failed to stop Gateway started by the archive installer"
}

verify_requested_version_installed_marker() {
  [[ "$DRY_RUN" == true ]] && return 0
  [[ -n "${REQUESTED_VERSION:-}" ]] || return 0

  local marker="$DTCLAW_HOME/.installed_from.json"
  [[ -f "$marker" ]] || fail "installed marker missing after requested version install: $marker" 5

  local expected_version="$VERSION"
  local selector="$COMMIT_SELECTOR"
  expected_version="$(marker_comparable_version "$expected_version")"

  local python3_bin
  python3_bin="$(preferred_python3)"
  if [[ -n "$python3_bin" ]]; then
    "$python3_bin" - "$marker" "$expected_version" "$selector" <<'PY' \
      || fail "installed marker does not match requested version ${REQUESTED_VERSION}: $marker" 5
import json
import sys
from pathlib import Path

marker_path = Path(sys.argv[1])
expected_version = sys.argv[2]
selector = sys.argv[3].lower()

marker = json.loads(marker_path.read_text(encoding="utf-8"))
actual_version = str(marker.get("version") or "")
if actual_version.startswith("v"):
    actual_version = actual_version[1:]
if actual_version != expected_version:
    print(f"version mismatch: expected {expected_version}, got {actual_version}", file=sys.stderr)
    raise SystemExit(1)

if selector:
    commit_fields = (
        marker.get("git_commit"),
        marker.get("agentix_git_commit"),
        marker.get("cli_git_commit"),
    )
    if not any(str(value or "").lower().startswith(selector) for value in commit_fields):
        print(f"commit selector mismatch: expected prefix {selector}", file=sys.stderr)
        raise SystemExit(1)
PY
    return 0
  fi

  local actual_version
  actual_version="$(sed -nE 's/.*"version"[[:space:]]*:[[:space:]]*"([^"]*)".*/\1/p' "$marker" | head -n 1 || true)"
  actual_version="$(marker_comparable_version "$actual_version")"
  if [[ "$actual_version" != "$expected_version" ]]; then
    fail "installed marker version does not match requested version ${REQUESTED_VERSION}: $marker" 5
  fi
  if [[ -n "$selector" ]] && ! grep -Eiq "\"(git_commit|agentix_git_commit|cli_git_commit)\"[[:space:]]*:[[:space:]]*\"${selector}" "$marker"; then
    fail "installed marker commit does not match requested version ${REQUESTED_VERSION}: $marker" 5
  fi
}

write_dtcoder_install_marker_distribution() {
  [[ "$DRY_RUN" == true ]] && return 0
  local marker="$DTCLAW_HOME/.installed_from.json"
  [[ -f "$marker" ]] || return 0
  local receipt_dir="${DTCODER_INSTALL_MARKER_RECEIPT_DIR:-$WORK_DIR/installed-marker-receipts}"
  local receipt expected="" product_bin help python3_bin marker_state
  mkdir -p "$receipt_dir" || fail "failed to prepare installed marker receipt" 5
  receipt_dir="$(cd "$receipt_dir" && pwd -P)" || fail "invalid installed marker receipt directory" 5
  receipt="$receipt_dir/marker-outer.json"
  marker_state="$(cd "$DTCLAW_HOME" && pwd -P)" || fail "invalid installed marker state directory" 5
  marker="$marker_state/.installed_from.json"
  if [[ -f "$receipt_dir/marker-state.json" ]]; then
    expected="$receipt_dir/marker-state.json"
  elif [[ -f "$receipt_dir/program-marker-path" && -f "$receipt_dir/marker-program.json" ]] \
    && [[ "$marker" -ef "$(cat "$receipt_dir/program-marker-path")" ]]; then
    expected="$receipt_dir/marker-program.json"
  fi
  product_bin="$PROGRAM_DIR/bin/$(product_command_for_dist "$DIST")"
  help="$("$product_bin" __install publish-installed-marker --help 2>/dev/null)" || help=""
  if grep -Fq -- --distribution <<<"$help" && grep -Fq -- --expected-receipt <<<"$help"; then
    local args=(__install publish-installed-marker --state-dir "$marker_state" --marker "$marker"
      --distribution "$DIST" --release-base-url "${BASE_URL%/}" --rollback-receipt "$receipt")
    [[ -z "$expected" ]] || args+=(--expected-receipt "$expected")
    "$product_bin" "${args[@]}" || fail "failed to update installed marker" 5
    return 0
  fi
  python3_bin="$(preferred_python3)"
  [[ -n "$python3_bin" ]] || fail "No locked installed-marker publication helper is available" 5
  "$python3_bin" - "$marker_state" "$marker" "$DIST" "$BASE_URL" "$receipt" "$expected" <<'PYMARKER' \
    || fail "failed to update installed marker: $marker" 5
import fcntl
import json
import os
from pathlib import Path
import stat
import sys
import tempfile
state, path, distribution, base_url, receipt, expected = sys.argv[1:]
state, path, receipt = map(Path, (state, path, receipt))
def atomic(path, text, mode):
    fd, name = tempfile.mkstemp(prefix=".installed-marker.", dir=path.parent)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as out:
            out.write(text)
            os.fchmod(out.fileno(), mode)
            out.flush()
            os.fsync(out.fileno())
        os.replace(name, path)
    finally:
        if os.path.exists(name):
            os.unlink(name)
lock = state / "locks/config.lock"
lock.parent.mkdir(parents=True, exist_ok=True)
with lock.open("a") as handle:
    fcntl.flock(handle, fcntl.LOCK_EX)
    if path.is_symlink() or not path.is_file() or path.stat().st_nlink != 1:
        raise ValueError("installed marker must be a regular, unlinked file")
    path = path.resolve()
    before = path.read_text(encoding="utf-8")
    if expected:
        prior = json.loads(Path(expected).read_text(encoding="utf-8"))
        if prior["target"] != str(path) or prior["after"] != before:
            sys.exit(0)
    if receipt.exists():
        raise ValueError("installed marker receipt already exists")
    marker = json.loads(before)
    marker["distribution"] = distribution
    if not str(marker.get("release_base_url") or "").strip():
        marker["release_base_url"] = base_url.rstrip("/")
    after = json.dumps(marker, ensure_ascii=False, indent=2) + "\n"
    atomic(receipt, json.dumps({"target": str(path), "before": before, "after": after}), 0o600)
    atomic(path, after, stat.S_IMODE(path.stat().st_mode))
PYMARKER
}

run_opencode_installer() {
  [[ "$SKIP_OPENCODE" == true ]] && { info "AiWork TUI install skipped"; return 0; }

  local tui_name tui_bin
  tui_name="$(tui_command_for_program_dir "$PROGRAM_DIR")"
  tui_bin="$PROGRAM_DIR/bin/$tui_name"
  if [[ -x "$tui_bin" ]]; then
    local tui_probe_err
    if tui_probe_err="$({ cd "$PROGRAM_DIR" && AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" "$tui_bin" --version >/dev/null; } 2>&1)"; then
      ok "$tui_name already present in release package; skipping external installer"
      return 0
    fi
    warn "$tui_name is present but version probe failed; falling back to external installer: $tui_probe_err"
  fi

  local installer="$WORK_DIR/install-dtcoder-tui.sh"
  local args=()
  [[ -n "$OPENCODE_BASE_URL" ]] && args+=(--base-url "$OPENCODE_BASE_URL")
  [[ -n "$OPENCODE_VERSION" ]] && args+=(--version "$OPENCODE_VERSION")
  [[ "$YES" == true ]] && args+=(--yes)
  [[ "$KILL_RUNNING_DTCODER" == true ]] && args+=(--kill-running)

  info "AiWork TUI installer: $OPENCODE_INSTALL_SCRIPT"
  if [[ "$DRY_RUN" == true ]]; then
    echo "[dry-run] download $OPENCODE_INSTALL_SCRIPT -> $installer"
    if [[ ${#args[@]} -gt 0 ]]; then
      echo "[dry-run] AGENTIX_STATE_DIR=$DTCLAW_HOME AGENTIX_PROGRAM_DIR=$PROGRAM_DIR AGENTIX_PLUGIN_DIR=$PROGRAM_DIR/plugins bash $installer ${args[*]}"
    else
      echo "[dry-run] AGENTIX_STATE_DIR=$DTCLAW_HOME AGENTIX_PROGRAM_DIR=$PROGRAM_DIR AGENTIX_PLUGIN_DIR=$PROGRAM_DIR/plugins bash $installer"
    fi
    return 0
  fi

  materialize_script "$OPENCODE_INSTALL_SCRIPT" "$installer"
  if [[ ${#args[@]} -gt 0 ]]; then
    AGENTIX_HOME="$DTCLAW_HOME" AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" bash "$installer" "${args[@]}"
  else
    AGENTIX_HOME="$DTCLAW_HOME" AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" bash "$installer"
  fi
}

# Best-effort name backfill only. After a successful archive install the
# compiled wrapper already exists, so this is a no-op. Archive payloads must
# still ship a distinct compiled wrapper (`require_distinct_compiled_bin`);
# that fail-closed rule does not apply to this outer helper.
link_compat_bin_if_missing() {
  local source=$1
  local target=$2
  [[ -x "$source" ]] || return 0
  [[ ! -e "$target" && ! -L "$target" ]] || return 0
  (
    cd "$(dirname "$target")"
    ln -s "$(basename "$source")" "$(basename "$target")"
  ) || fail "failed to create compatibility symlink: $target -> $(basename "$source")" 5
}

# Drop the other-channel product names from PROGRAM_DIR/bin, then fill a
# missing compat wrapper *name* if the layout is incomplete (tests, mixed
# outer/child installer versions). A current archive install already has the
# real wrapper, so the ln -s branch does not run on that path.
ensure_aiwork_compat_symlinks() {
  [[ "$DRY_RUN" == true ]] && return 0
  local bin_dir="$PROGRAM_DIR/bin"
  [[ -d "$bin_dir" ]] || return 0

  case "$DIST" in
    internal)
      rm -f "$bin_dir/aiworkcn" "$bin_dir/aiworkcli"
      link_compat_bin_if_missing "$bin_dir/aiwork" "$bin_dir/dtcodercli-internal"
      ;;
    external)
      rm -f "$bin_dir/aiwork" "$bin_dir/aiworkcli"
      link_compat_bin_if_missing "$bin_dir/aiworkcn" "$bin_dir/dtcodercn"
      ;;
    global)
      rm -f "$bin_dir/aiwork" "$bin_dir/aiworkcn"
      link_compat_bin_if_missing "$bin_dir/aiworkcli" "$bin_dir/dtcodercli"
      ;;
  esac
}

# The daemon no longer locks product-managed skill trees with `chmod -R a-w`
# (skill::mutation does not mutate filesystem permissions; sandbox layer owns
# write protection). Restore owner write only remains as a one-shot legacy
# repair so trees left readonly by an older agentix version do not block
# upgrades; the tree is left owner-writable afterwards (no relock).
restore_owner_write_for_upgrade() {
  local dir
  for dir in "$@"; do
    [[ -d "$dir" ]] || continue
    chmod -R u+w "$dir" 2>/dev/null || true
  done
}

# A release payload may contain an empty app-packs directory.  Preserve the
# pack selected by the existing coder agent before that payload is overlaid so
# an upgrade never turns a working agent into an unregistered-pack runtime.
backup_coder_app_pack_before_release_overlay() {
  [[ "$DRY_RUN" == true ]] && return 0
  local coder_json="$DTCLAW_HOME/agents/coder/agent.json"
  [[ -f "$coder_json" ]] || return 0

  local origin app_pack_id version source status
  status=0
  origin="$(read_coder_app_pack_origin "$coder_json")" || status=$?
  if [[ "$status" -eq 2 ]]; then
    fail "cannot safely read existing coder app-pack origin without python3: $coder_json" 5
  fi
  [[ "$status" -eq 0 ]] || return 0
  app_pack_id="${origin%%$'\t'*}"
  version="${origin#*$'\t'}"
  validate_coder_app_pack_origin "$app_pack_id" "$version"
  source="$DTCLAW_HOME/app-packs/$app_pack_id/$version"
  [[ -d "$source" ]] || return 0

  CODER_APP_PACK_BACKUP_DIR="$WORK_DIR/coder-app-pack-backup"
  CODER_APP_PACK_BACKUP_ID="$app_pack_id"
  CODER_APP_PACK_BACKUP_VERSION="$version"
  mkdir -p "$CODER_APP_PACK_BACKUP_DIR"
  cp -a "$source" "$CODER_APP_PACK_BACKUP_DIR/app-pack"
  ok "preserved coder app-pack $app_pack_id@$version before release overlay"
}

restore_coder_app_pack_backup() {
  refresh_connector_rollback_protection "$DTCLAW_HOME"
  [[ "$CONNECTOR_SHARED_STATE_PROTECTED" != true ]] || return 0
  [[ -n "${CODER_APP_PACK_BACKUP_DIR:-}" && -d "$CODER_APP_PACK_BACKUP_DIR/app-pack" ]] || return 0
  local target="$DTCLAW_HOME/app-packs/$CODER_APP_PACK_BACKUP_ID/$CODER_APP_PACK_BACKUP_VERSION"
  mkdir -p "$(dirname "$target")"
  restore_owner_write_for_upgrade "$target/skills"
  rm -rf "$target"
  cp -a "$CODER_APP_PACK_BACKUP_DIR/app-pack" "$target"
  warn "restored preserved coder app-pack $CODER_APP_PACK_BACKUP_ID@$CODER_APP_PACK_BACKUP_VERSION after interrupted install"
}

restore_coder_app_pack_if_release_removed_it() {
  [[ -n "${CODER_APP_PACK_BACKUP_DIR:-}" && -d "$CODER_APP_PACK_BACKUP_DIR/app-pack" ]] || return 0
  local target="$DTCLAW_HOME/app-packs/$CODER_APP_PACK_BACKUP_ID/$CODER_APP_PACK_BACKUP_VERSION"
  [[ -f "$target/manifest.json" ]] && return 0
  mkdir -p "$(dirname "$target")"
  restore_owner_write_for_upgrade "$target/skills"
  rm -rf "$target"
  cp -a "$CODER_APP_PACK_BACKUP_DIR/app-pack" "$target"
  ok "restored coder app-pack removed by release overlay: $CODER_APP_PACK_BACKUP_ID@$CODER_APP_PACK_BACKUP_VERSION"
}

run_coder_agent_show() {
  local product_bin=$1
  local output_file=$2
  mkdir -p "$(dirname "$output_file")" 2>/dev/null || true
  AGENTIX_STATE_DIR="$DTCLAW_HOME" \
    AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" \
    AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" \
    "$product_bin" agent show coder >"$output_file" 2>&1
}

shell_quote() {
  printf '%q' "$1"
}

print_coder_agent_diagnosis_command() {
  local product_bin=$1
  warn "To inspect this machine, run:"
  warn "  AGENTIX_STATE_DIR=$(shell_quote "$DTCLAW_HOME") AGENTIX_PROGRAM_DIR=$(shell_quote "$PROGRAM_DIR") AGENTIX_PLUGIN_DIR=$(shell_quote "$PROGRAM_DIR/plugins") $(shell_quote "$product_bin") agent show coder"
}

print_coder_agent_repair_hint() {
  warn "To back up and recreate only the coder agent, rerun the same installer command with --repair-coder-agent."
}

run_install_config_repair() {
  local product_cmd product_bin args=()
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$PROGRAM_DIR/bin/$product_cmd"
  [[ -x "$product_bin" ]] || return 127
  local probe_status=0
  install_config_repair_supported || probe_status=$?
  if [[ "$probe_status" -ne 0 ]]; then
    if [[ "$probe_status" -eq 2 ]] && AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" \
      "$product_bin" --help >/dev/null 2>&1; then
      return 127
    fi
    warn "Cannot check install config repair support (exit $probe_status): $product_bin"
    return "$probe_status"
  fi
  args=(__install repair-config
    --state-dir "$DTCLAW_HOME"
    --config "$DTCLAW_HOME/config.json"
    --dist "$DIST")
  AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" \
    "$product_bin" "${args[@]}" "$@"
}

preserve_config_compat_restore_helper() {
  local repair_program=$1 product_cmd product_bin helper_dir helper_bin
  [[ -n "${CONFIG_COMPAT_RESTORE_PROGRAM_DIR:-}" ]] && return 0
  repair_program="$(cd "$repair_program" 2>/dev/null && pwd -P)" || return 1
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$repair_program/bin/$product_cmd"
  [[ -x "$product_bin" ]] || return 1
  AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$repair_program" AGENTIX_PLUGIN_DIR="$repair_program/plugins" \
    "$product_bin" __install restore-config --help >/dev/null 2>&1 || return 1

  helper_dir="$WORK_DIR/config-rollback-repairer"
  helper_bin="$helper_dir/bin/$product_cmd"
  mkdir -p "$helper_dir/bin" || return 1
  cp -p "$product_bin" "$helper_bin" || return 1
  chmod u+x "$helper_bin" || return 1
  AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$helper_dir" AGENTIX_PLUGIN_DIR="$helper_dir/plugins" \
    "$helper_bin" __install restore-config --help >/dev/null 2>&1 || return 1
  CONFIG_COMPAT_RESTORE_PROGRAM_DIR="$helper_dir"
  # Archive cleanup may remove the original release. Subsequent repair calls
  # and receipt rollback therefore use this transaction-owned binary.
  CONFIG_COMPAT_REPAIR_PROGRAM_DIR="$helper_dir"
}

apply_pre_activation_distribution_defaults_with_binary() {
  local repair_program=$1 product_cmd product_bin help result
  repair_program="$(cd "$repair_program" 2>/dev/null && pwd -P)" || return 127
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$repair_program/bin/$product_cmd"
  [[ -x "$product_bin" ]] || return 127
  help="$(AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$repair_program" AGENTIX_PLUGIN_DIR="$repair_program/plugins" \
    "$product_bin" __install repair-config --help 2>/dev/null)" || return 127
  grep -Fq -- "--rollback-receipt" <<<"$help" || return 127
  grep -Fq -- "--apply-distribution-defaults" <<<"$help" || return 127
  preserve_config_compat_restore_helper "$repair_program" || return 127

  result="$(CONFIG_COMPAT_ROLLBACK_RECEIPT="$CONFIG_COMPAT_ROLLBACK_RECEIPT" AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$repair_program" AGENTIX_PLUGIN_DIR="$repair_program/plugins" \
    "$product_bin" __install repair-config --state-dir "$DTCLAW_HOME" --config "$DTCLAW_HOME/config.json" --dist "$DIST" \
      --pre-existing-config --apply-distribution-defaults --rollback-receipt "$CONFIG_COMPAT_ROLLBACK_RECEIPT")" || return $?
  case "$result" in
    updated*) ok "distribution safety defaults applied before activation: $DTCLAW_HOME/config.json (dist=$DIST)" ;;
    unchanged*) info "distribution safety defaults already satisfied before activation: $DTCLAW_HOME/config.json" ;;
  esac
}

apply_pre_activation_distribution_defaults_with_python() {
  local config_json="$DTCLAW_HOME/config.json"
  local python3_bin
  python3_bin="$(preferred_python3)"
  [[ -n "$python3_bin" ]] || return 127

  "$python3_bin" - "$config_json" "$DTCLAW_HOME" "$DIST" <<'PYDEFAULTS'
import fcntl
import json
import os
import stat
import sys
import tempfile
from pathlib import Path

config_path = Path(sys.argv[1])
state_dir = Path(sys.argv[2])
distribution = sys.argv[3]
receipt_path = os.environ.get("CONFIG_COMPAT_ROLLBACK_RECEIPT")
lock_path = state_dir / "locks" / "config.lock"
lock_path.parent.mkdir(parents=True, exist_ok=True)
with lock_path.open("a") as lock:
    fcntl.flock(lock, fcntl.LOCK_EX)
    before = config_path.read_text(encoding="utf-8")
    def unique_object(pairs):
        value = {}
        for key, item in pairs:
            if key in value:
                raise ValueError(f"duplicate JSON key: {key}")
            value[key] = item
        return value
    def reject_non_finite(value):
        raise ValueError(f"non-finite JSON number: {value}")
    def read_json(text):
        return json.loads(text, object_pairs_hook=unique_object, parse_constant=reject_non_finite)
    config = read_json(before)
    if not isinstance(config, dict):
        raise ValueError("config must be a JSON object")
    changes = []
    def set_missing(path, value):
        current = config
        for segment in path[:-1]:
            if segment not in current:
                next_value = {}
                current[segment] = next_value
            else:
                next_value = current[segment]
            if not isinstance(next_value, dict):
                return False
            current = next_value
        if path[-1] in current:
            return False
        current[path[-1]] = value
        return True
    if distribution in ("external", "global"):
        defaults = [
            (("diagnostics", "upload", "mode"), "manual"),
            (("profiling", "enabled"), False),
            (("profiling", "export", "otlp", "enabled"), False),
            (("profiling", "export", "push_gateway", "enabled"), False),
            (("profiling", "export", "otel", "enabled"), False),
        ]
        for path, value in defaults:
            if set_missing(path, value):
                changes.append("config." + ".".join(path))
    if not changes:
        print("unchanged")
        raise SystemExit(0)
    target = config_path.resolve(strict=True)
    mode = stat.S_IMODE(target.stat().st_mode)
    def write_atomic(path, text, preserve_mode):
        fd, name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
        try:
            with os.fdopen(fd, "w", encoding="utf-8") as file:
                file.write(text)
                file.flush()
                if preserve_mode:
                    os.fchmod(file.fileno(), mode)
                os.fsync(file.fileno())
            os.replace(name, path)
        finally:
            if os.path.exists(name):
                os.unlink(name)
    try:
        write_atomic(target, json.dumps(config, ensure_ascii=False, indent=2) + "\n", True)
        if receipt_path:
            receipt_file = Path(receipt_path)
            previous = read_json(receipt_file.read_text(encoding="utf-8")) if receipt_file.is_file() else None
            if (previous is not None and (not isinstance(previous, dict)
                    or previous.get("target") != str(target)
                    or not isinstance(previous.get("after"), str)
                    or "before" not in previous)):
                raise ValueError("invalid config rollback receipt")
            after = target.read_text(encoding="utf-8")
            receipt_before = before
            if previous is not None and previous["after"] == before:
                receipt_before = previous["before"]
            write_atomic(receipt_file, json.dumps({"target": str(target), "before": receipt_before, "after": after}), False)
    except Exception:
        write_atomic(target, before, True)
        raise
    print("updated")
    for change in changes:
        print(f"change:{change}")
PYDEFAULTS
}

prepare_pre_activation_distribution_defaults() {
  [[ "$PRE_EXISTING_CONFIG" == true ]] || return 0
  if [[ "$DIST" != "external" && "$DIST" != "global" ]]; then
    return 0
  fi

  local status=0
  apply_pre_activation_distribution_defaults_with_binary "$PROGRAM_DIR" || status=$?
  if [[ "$status" -eq 0 ]]; then
    return 0
  fi
  if [[ "$status" -ne 127 ]]; then
    fail "failed to apply distribution safety defaults before activation: $DTCLAW_HOME/config.json" 5
  fi

  status=0
  apply_pre_activation_distribution_defaults_with_python || status=$?
  case "$status" in
    0) ;;
    127)
      fail "Distribution safety defaults require Python 3. Install Python 3 and retry." 6
      ;;
    *)
      fail "failed to apply distribution safety defaults before activation: $DTCLAW_HOME/config.json" 5
      ;;
  esac
}

install_config_repair_supported() {
  local product_cmd product_bin
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$PROGRAM_DIR/bin/$product_cmd"
  [[ -x "$product_bin" ]] || return 1
  AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" \
    "$product_bin" __install repair-config --help >/dev/null 2>&1
}

install_config_repair_supports_compat_rules() {
  local product_cmd product_bin help
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$PROGRAM_DIR/bin/$product_cmd"
  [[ -x "$product_bin" ]] || return 1
  help="$(AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" \
    "$product_bin" __install repair-config --help 2>/dev/null)" || return 1
  grep -Fq -- "--compat-rules-only" <<<"$help" && grep -Fq -- "--check-compat-rules" <<<"$help" && grep -Fq -- "--rollback-receipt" <<<"$help"
}

install_config_repair_supports_rollback_receipt() {
  local product_cmd product_bin help
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$PROGRAM_DIR/bin/$product_cmd"
  [[ -x "$product_bin" ]] || return 1
  help="$(AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" \
    "$product_bin" __install repair-config --help 2>/dev/null)" || return 1
  grep -Fq -- "--rollback-receipt" <<<"$help"
}

install_config_repair_can_be_skipped() {
  [[ -n "${REQUESTED_VERSION:-}" || -n "${COMMIT_SELECTOR:-}" ]]
}

install_config_repair_failure_is_unsupported() {
  local status=$1
  [[ "$status" -eq 2 || "$status" -eq 127 ]] || return 1
  install_config_repair_can_be_skipped || return 1
  local probe_status=0 product_cmd product_bin
  install_config_repair_supported || probe_status=$?
  [[ "$probe_status" -eq 2 ]] || return 1
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$PROGRAM_DIR/bin/$product_cmd"
  AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" \
    "$product_bin" --help >/dev/null 2>&1
}

coder_agent_validation_is_stale_router_auth_failure() {
  local output_file=$1
  [[ -s "$output_file" ]] || return 1
  if grep -Fq "Managed Router provider" "$output_file" \
    && grep -Fq "api_key must use an environment reference" "$output_file"; then
    return 0
  fi
  grep -Fq "router_auth.provider_ids must contain at least one" "$output_file"
}

coder_agent_validation_is_managed_router_env_missing() {
  local output_file=$1
  [[ -s "$output_file" ]] || return 1
  grep -Fq "Managed Router provider" "$output_file" \
    && grep -Fq "api_key environment variable" "$output_file" \
    && grep -Fq "is missing or empty" "$output_file"
}

warn_managed_router_login_required() {
  local login_cmd
  login_cmd="$(product_login_command_for_dist "$DIST")"
  warn "AiWork was installed, but the existing login credential is missing."
  warn "Run \`$login_cmd\` and then start AiWork again."
}

print_coder_agent_managed_router_login_hint() {
  local product_bin=$1
  local output_file=$2
  warn "coder agent validation needs a refreshed login credential."
  warn "To inspect this machine, run:"
  warn "  AGENTIX_STATE_DIR=$(shell_quote "$DTCLAW_HOME") AGENTIX_PROGRAM_DIR=$(shell_quote "$PROGRAM_DIR") AGENTIX_PLUGIN_DIR=$(shell_quote "$PROGRAM_DIR/plugins") $(shell_quote "$product_bin") agent show coder"
  if [[ -s "$output_file" ]]; then
    sed -n 's/^.*Managed Router provider \([^ ]*\) api_key environment variable \([^ ]*\) is missing or empty.*$/  Missing credential: provider=\1 env=\2/p' "$output_file" | sed -n '1,1p' >&2 || true
  fi
}

coder_agent_validation_is_global_config_failure() {
  local output_file=$1
  [[ -s "$output_file" ]] || return 1
  grep -Fq "Hook config is not yet supported" "$output_file" \
    && grep -Fq "daemon.hooks" "$output_file" \
    && return 0
  grep -Fq "Config validation failed" "$output_file" \
    && grep -Fq 'unknown variant `aiwork_router`' "$output_file"
}

coder_agent_validation_is_config_compatibility_failure() {
  local output_file=$1
  [[ -s "$output_file" ]] || return 1
  grep -Fq "Config validation failed" "$output_file" \
    || grep -Fq "Hook config is not yet supported" "$output_file"
}

allow_requested_version_coder_validation_warning() {
  local output_file=$1
  [[ -n "${REQUESTED_VERSION:-}" || -n "${VERSION:-}" ]] || return 1
  [[ "$REPAIR_CODER_AGENT" != true ]] || return 1
  coder_agent_validation_is_config_compatibility_failure "$output_file"
}

warn_requested_version_coder_validation_degraded() {
  warn "requested version was installed, but coder agent validation was skipped because existing config/state is newer than that version."
  warn "The installed version remains active. If this old version must run fully, retry with a clean state dir or manually downgrade config.json."
}

print_coder_agent_config_failure_hint() {
  local output_file=$1
  warn "This validation failure comes from global config.json, not the coder agent state."
  warn "  config: $DTCLAW_HOME/config.json"
  warn "Rerunning with --repair-coder-agent will not fix this config compatibility issue."
  if grep -Fq "daemon.hooks.ai_code_metrics_post_commit_enabled" "$output_file"; then
    warn "The requested version does not support daemon.hooks.ai_code_metrics_post_commit_enabled."
  fi
  if grep -Fq 'unknown variant `aiwork_router`' "$output_file"; then
    warn "The requested version expects the legacy dtcoder_router web_search engine name."
  fi
  if [[ -s "$output_file" ]] && grep -Fq "api_key must use an environment reference" "$output_file"; then
    warn "Managed Router api_key must stay an environment reference. Do not delete router_auth or drop live allowlist ids; fix the referenced env var, then retry."
  elif [[ -s "$output_file" ]] && grep -Eq 'router_auth|Managed Router provider' "$output_file"; then
    warn "Stale or empty router_auth.provider_ids should be removed from config.json, then retry the installer."
  fi
}

repair_stale_router_auth_for_coder_validation() {
  local config_json="$DTCLAW_HOME/config.json"
  [[ -f "$config_json" ]] || return 1

  local result_file status result
  result_file="$WORK_DIR/stale-router-auth-repair.result"
  mkdir -p "$WORK_DIR" 2>/dev/null || return 1

  status=0
  run_install_config_repair --repair-router-auth >"$result_file" || status=$?
  if [[ "$status" -ne 0 ]]; then
    if install_config_repair_failure_is_unsupported "$status"; then
      warn "installed version does not support install config repair; leaving router_auth metadata unchanged"
      return 1
    fi
    warn "failed to repair stale router_auth metadata: $config_json"
    return 1
  fi

  result="$(sed -n '1p' "$result_file" 2>/dev/null || true)"
  [[ "$result" == "updated" ]] || return 1
  ok "repaired stale router_auth metadata: $config_json"
  sed -n 's/^backup:/  backup:  /p' "$result_file" | while IFS= read -r line; do
    info "$line"
  done
  return 0
}

target_config_compat_version() {
  local version="${REQUESTED_VERSION:-${VERSION:-}}"
  [[ -n "$version" ]] || return 1
  printf '%s\n' "$version"
}

private_deployment_source() {
  local deployment_source
  [[ "$DIST" == external ]] || return 1
  if [[ "${AGENTIX_DEPLOYMENT_CONFIG+x}" == x ]]; then
    [[ "$AGENTIX_DEPLOYMENT_CONFIG" == /* && -f "$AGENTIX_DEPLOYMENT_CONFIG" ]] \
      || fail "Invalid explicit private deployment source; compatibility repair cannot use public rules" 6
    printf '%s\n' "$AGENTIX_DEPLOYMENT_CONFIG"
    return 0
  fi
  if [[ "${DTCODER_GUI_USER_DATA_DIR+x}" == x ]]; then
    [[ "$DTCODER_GUI_USER_DATA_DIR" == /* ]] \
      || fail "Private deployment GUI directory must be absolute before compatibility repair" 6
  fi
  deployment_source="${AGENTIX_DEPLOYMENT_CONFIG:-}"
  if [[ -z "$deployment_source" ]]; then
    case "$(uname -s)" in
      Darwin) deployment_source="$HOME/Library/Application Support/DTCoderCN/deployment.yaml" ;;
      *) deployment_source="${XDG_CONFIG_HOME:-$HOME/.config}/DTCoderCN/deployment.yaml" ;;
    esac
    if [[ -n "${DTCODER_GUI_USER_DATA_DIR:-}" ]]; then
      deployment_source="$DTCODER_GUI_USER_DATA_DIR/deployment.yaml"
    fi
  fi
  # This is a conservative bootstrap gate, not a second mode interpreter.
  # Existing mode/legacy records also require the staged Rust owner to decide;
  # missing YAML must never authorize public repair of a private config.
  local mode_record="${deployment_source%/*}/deployment-mode.json"
  [[ -e "$deployment_source" || -L "$deployment_source" \
    || -e "$mode_record" || -L "$mode_record" \
    || -e "$DTCLAW_HOME/deployment-mode.json" || -L "$DTCLAW_HOME/deployment-mode.json" \
    || -e "$DTCLAW_HOME/deployment.json" || -L "$DTCLAW_HOME/deployment.json" ]] || return 1
  printf '%s\n' "$deployment_source"
}

download_config_compat_rules() {
  local target_file=$1
  [[ "$DRY_RUN" == true ]] && return 1
  try_download_to "$(cache_bust_url "$CONFIG_COMPAT_RULES_URL")" "$target_file" >/dev/null 2>&1
}

apply_config_compat_rules_with_python() {
  local rules_file=$1
  local target_version=$2
  local config_json="$DTCLAW_HOME/config.json"
  [[ -f "$config_json" ]] || return 1

  local python3_bin
  python3_bin="$(preferred_python3)"
  if [[ -z "$python3_bin" ]]; then
    return 127
  fi

  "$python3_bin" - "$config_json" "$rules_file" "$target_version" "$DIST" "$DTCLAW_HOME" <<'PY'
import fcntl
import json
import math
import os
import re
import stat
import sys
import tempfile
from pathlib import Path

config_path = Path(sys.argv[1])
rules_path = Path(sys.argv[2])
target_version = sys.argv[3]
distribution = sys.argv[4]
state_dir = Path(sys.argv[5])

def parse_version(value):
    value = value.strip()
    if value.startswith("v"):
        value = value[1:]
    value = value.split("-", 1)[0]
    parts = value.split(".")
    if len(parts) != 3:
        return None
    if any(re.fullmatch(r"\+?[0-9]+", part) is None for part in parts):
        return None
    numbers = tuple(int(part) for part in parts)
    return numbers if all(part <= 2**64 - 1 for part in numbers) else None

def reject(message):
    raise ValueError(message)

def same_json_value(left, right):
    # Python equates True with 1 and 1 with 1.0; serde_json does not.
    if type(left) is not type(right):
        return False
    if isinstance(left, dict):
        return left.keys() == right.keys() and all(same_json_value(left[key], right[key]) for key in left)
    if isinstance(left, list):
        return len(left) == len(right) and all(same_json_value(a, b) for a, b in zip(left, right))
    return left == right

def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            reject("duplicate JSON object key")
        result[key] = value
    return result

def read_json(path):
    return json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique_object,
                      parse_float=finite_float,
                      parse_constant=lambda value: reject("non-finite JSON number"))

def finite_float(value):
    parsed = float(value)
    if not math.isfinite(parsed):
        reject("non-finite JSON number")
    return parsed

target = parse_version(target_version)
if target is None:
    reject("invalid config compat target version")

rules_doc = read_json(rules_path)
if (not isinstance(rules_doc, dict)
        or type(rules_doc.get("schema_version")) is not int
        or not 0 <= rules_doc["schema_version"] <= 2**64 - 1):
    reject("config compat schema_version must be a nonnegative integer")
# Exit 3 means this repairer lacks capability; malformed known rules still fail.
if rules_doc["schema_version"] != 1:
    sys.exit(3)
MODEL_INPUT_RULE_VALUES = ("video", "file", "audio")
sections = {
    "rules": "delete_json_pointer",
    "model_input_rules": "remove_model_input_modalities",
    "binding_rules": "remove_channel_bindings",
    "web_search_rules": "rename_web_search_engine",
}
supported = not (set(rules_doc) - set(sections) - {"schema_version", "revision", "published_at"})
entries = []
for section, expected_action in sections.items():
    rules = rules_doc.get(section, [])
    if not isinstance(rules, list):
        reject("config compat rules must be an array")
    entries.extend((rule, section, expected_action) for rule in rules)
# Validate the whole document before applying any rule, as Rust's typed
# deserialization does, including rules for other distributions/versions.
for rule, section, expected_action in entries:
    if not isinstance(rule, dict) or any(not isinstance(rule.get(key), str)
            for key in ("id", "action", "path")):
        reject("invalid config compat rule fields")
    if set(rule) - {"id", "distribution", "target_version_lt", "target_version_eq",
                    "action", "path", "values", "from", "to", "reason"}:
        supported = False
    for key in ("target_version_lt", "target_version_eq", "from", "to"):
        if rule.get(key) is not None and not isinstance(rule[key], str):
            reject("invalid config compat rule target version")
    values = rule.get("values", [])
    if not isinstance(values, list) or any(not isinstance(item, str) for item in values):
        reject("config compat rule values must be an array of strings")
    distributions = rule.get("distribution", [])
    if not isinstance(distributions, list) or any(not isinstance(item, str) for item in distributions):
        reject("config compat rule distribution must be an array of strings")
    if rule.get("reason") is not None and not isinstance(rule["reason"], str):
        reject("config compat rule reason must be a string")

def feature_key(path):
    prefix = "/agents/defaults/features/"
    if not path.startswith(prefix):
        reject("disallowed config compat rule path")
    key = path[len(prefix):]
    if not key or "/" in key:
        reject("config compat rule path must target one direct feature key")
    if re.search(r"~(?![01])", key):
        reject("invalid config compat rule JSON pointer token")
    return key.replace("~1", "/").replace("~0", "~")

selected = []
for rule, section, expected_action in entries:
    action = rule["action"]
    if action != expected_action and action in sections.values():
        reject("unsupported action in config compat rule section")
    distributions = rule.get("distribution", [])
    less_than, equal = rule.get("target_version_lt"), rule.get("target_version_eq")
    unknown_selector = any(key.startswith("target_version_")
                           for key in set(rule) - {"id", "distribution", "target_version_lt", "target_version_eq",
                                                    "action", "path", "values", "from", "to", "reason"})
    if unknown_selector:
        # A future selector can replace the legacy selector. Validate known
        # action scope below, but do not infer applicability or reject it.
        supported = False
        path = rule["path"]
        values = rule.get("values", [])
        if action == expected_action:
            if action == "remove_channel_bindings":
                if path != "/bindings" or not values or any(value != "wechat" for value in values):
                    reject("config compat rule must target bindings with wechat values")
            elif action == "rename_web_search_engine":
                if path != "/tools/web_search" or rule.get("from") != "aiwork_router" or rule.get("to") != "dtcoder_router":
                    reject("config compat rule must rename aiwork_router to dtcoder_router in web_search")
            elif action == "remove_model_input_modalities":
                if path != "/models/*/models/*/input" or not values or any(value not in MODEL_INPUT_RULE_VALUES for value in values):
                    reject("config compat rule must target model input with " + "/".join(MODEL_INPUT_RULE_VALUES) + " values")
            else:
                feature_key(path)
        continue
    if ((less_than is None) == (equal is None)
            or (equal is not None and section == "rules")):
        reject("config compat rule requires exactly one supported target version selector")
    boundary = parse_version(equal if equal is not None else less_than)
    if boundary is None:
        reject("invalid config compat rule target_version_lt")
    applies = (not distributions or distribution in distributions) and (
        target == boundary if equal is not None else target < boundary)
    path = rule["path"]
    if action != expected_action:
        if applies:
            supported = False
        continue
    # Validate every known action's scope before deciding capability, matching
    # Rust's preflight without reading or changing the user's configuration.
    values = rule.get("values", [])
    if action == "remove_channel_bindings":
        if path != "/bindings" or not values or any(value != "wechat" for value in values):
            reject("config compat rule must target bindings with wechat values")
    elif action == "rename_web_search_engine":
        if path != "/tools/web_search" or rule.get("from") != "aiwork_router" or rule.get("to") != "dtcoder_router":
            reject("config compat rule must rename aiwork_router to dtcoder_router in web_search")
    elif action == "remove_model_input_modalities":
        if path != "/models/*/models/*/input" or not values or any(value not in MODEL_INPUT_RULE_VALUES for value in values):
            reject("config compat rule must target model input with " + "/".join(MODEL_INPUT_RULE_VALUES) + " values")
    else:
        feature_key(path)
    if applies:
        selected.append(rule)

if not supported:
    sys.exit(3)

lock_path = state_dir / "locks" / "config.lock"
lock_path.parent.mkdir(parents=True, exist_ok=True)
config_lock = lock_path.open("a")
fcntl.flock(config_lock, fcntl.LOCK_EX)
before = config_path.read_text(encoding="utf-8")
receipt_path = os.environ.get("CONFIG_COMPAT_ROLLBACK_RECEIPT")
previous = read_json(Path(receipt_path)) if receipt_path and Path(receipt_path).is_file() else None
if previous is not None and (not isinstance(previous, dict)
        or not isinstance(previous.get("target"), str)
        or not isinstance(previous.get("after"), str)
        or "before" not in previous
        or (previous["before"] is not None and not isinstance(previous["before"], str))):
    reject("invalid config rollback receipt")
config = read_json(config_path)
if not isinstance(config, dict):
    reject("config must be a JSON object")
changed = []
for rule in selected:
    action, path, rule_id = rule["action"], rule["path"], rule["id"]
    if action == "remove_channel_bindings":
        values = rule.get("values", [])
        if "bindings" not in config:
            continue
        bindings = config["bindings"]
        if not isinstance(bindings, list):
            reject("bindings must be an array")
        if any(not isinstance(binding, dict)
               or not isinstance(binding.get("agent_id"), str)
               or not isinstance(binding.get("match"), dict)
               or not isinstance(binding["match"].get("channel"), str) for binding in bindings):
            reject("bindings must contain agent_id and match.channel strings")
        remaining = [binding for binding in bindings if binding["match"]["channel"] not in values]
        if len(remaining) != len(bindings):
            config["bindings"] = remaining
            changed.append((rule_id, "/bindings"))
        continue
    if action == "rename_web_search_engine":
        source, dest = rule.get("from"), rule.get("to")
        tools_config = config.get("tools")
        if not isinstance(tools_config, dict) or "web_search" not in tools_config:
            continue
        web = tools_config["web_search"]
        if not isinstance(web, dict):
            reject("web search config must be an object")
        if source in web:
            if web[source] is not None and not isinstance(web[source], dict):
                reject("web search aiwork_router config must be an object or null")
            if dest in web and web[dest] is not None and not isinstance(web[dest], dict):
                reject("web search dtcoder_router config must be an object or null")
            if web[source] is not None and web.get(dest) is not None and not same_json_value(web[dest], web[source]):
                reject("conflicting web search aiwork_router and dtcoder_router configs; refusing to overwrite either")
        if "engines" in web:
            engines = web["engines"]
            if not isinstance(engines, list) or any(not isinstance(engine, str) for engine in engines):
                reject("web search engines must be an array of strings")
            renamed = [dest if engine == source else engine for engine in engines]
            if renamed != engines:
                web["engines"] = renamed
                changed.append((rule_id, "/tools/web_search/engines"))
        if source in web:
            value = web.pop(source)
            if value is not None or dest not in web:
                web[dest] = value
            changed.append((rule_id, "/tools/web_search/" + source))
        continue
    if action == "remove_model_input_modalities":
        values = rule.get("values", [])
        providers = config.get("models")
        if not isinstance(providers, dict):
            continue
        for provider_id, provider in providers.items():
            models = provider.get("models") if isinstance(provider, dict) else None
            if not isinstance(models, list):
                continue
            for index, model in enumerate(models):
                inputs = model.get("input") if isinstance(model, dict) else None
                if not isinstance(inputs, list):
                    continue
                if any(not isinstance(item, str) for item in inputs):
                    reject("model input must be an array of strings")
                remaining = [item for item in inputs if item not in values]
                if remaining == inputs:
                    continue
                if remaining:
                    model["input"] = remaining
                else:
                    del model["input"]
                provider_token = provider_id.replace("~", "~0").replace("/", "~1")
                changed.append((rule_id, f"/models/{provider_token}/models/{index}/input"))
        continue
    key = feature_key(path)
    features = config
    for segment in ("agents", "defaults", "features"):
        features = features.get(segment) if isinstance(features, dict) else None
    if isinstance(features, dict) and key in features:
        del features[key]
        changed.append((rule_id, path))

if not changed:
    print("unchanged")
    sys.exit(0)

backup_dir = state_dir / ".install" / "config-backups"
backup_dir.mkdir(parents=True, exist_ok=True)
# Resolve the referent so publishing does not replace a config symlink.
# mkstemp creates private, exclusive backups and staging files.
target_path = config_path.resolve(strict=True)
mode = stat.S_IMODE(target_path.stat().st_mode)
backup_fd, backup = tempfile.mkstemp(prefix="config.pre-aiwork-config-compat.", suffix=".bak", dir=backup_dir)
with os.fdopen(backup_fd, "wb") as file:
    file.write(target_path.read_bytes())
tmp_fd, tmp_name = tempfile.mkstemp(prefix=f".{target_path.name}.", suffix=".tmp", dir=target_path.parent)
tmp = Path(tmp_name)
try:
    with os.fdopen(tmp_fd, "w", encoding="utf-8") as file:
        file.write(json.dumps(config, ensure_ascii=False, indent=2, allow_nan=False) + "\n")
        file.flush()
        os.fchmod(file.fileno(), mode)
    tmp.replace(target_path)
finally:
    if tmp.exists():
        tmp.unlink()
try:
    receipt_before = before
    if receipt_path:
        after = target_path.read_text(encoding="utf-8")
        if previous and previous["target"] == str(target_path) and previous["after"] == before:
            receipt_before = previous["before"]
        receipt = {"target": str(target_path), "before": receipt_before, "after": after}
        fd, name = tempfile.mkstemp(prefix=".config-receipt.", dir=Path(receipt_path).parent)
        try:
            with os.fdopen(fd, "w", encoding="utf-8") as file:
                json.dump(receipt, file)
                file.flush()
                os.fsync(file.fileno())
            os.replace(name, receipt_path)
        finally:
            if os.path.exists(name):
                os.unlink(name)
except Exception:
    # The config lock is still held; restore only this repair's write.
    fd, name = tempfile.mkstemp(prefix=".config-undo.", dir=target_path.parent)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as file:
            file.write(before)
            file.flush()
            os.fchmod(file.fileno(), mode)
            os.fsync(file.fileno())
        os.replace(name, target_path)
    finally:
        if os.path.exists(name):
            os.unlink(name)
    raise
print("updated")
for rule_id, path in changed:
    print(f"change:config.compat.{rule_id}:{path}")
print(f"backup:{backup}")
PY
}

prepare_config_compat_rules() {
  [[ "$DRY_RUN" == true ]] && return 0
  if private_deployment_source >/dev/null; then
    # The installed version may predate policies and deployment-policy. Let the
    # archive backend resolve and repair with its staged target before activation.
    CONFIG_COMPAT_PRIVATE_DEFERRED=true
    return 0
  fi
  CONFIG_COMPAT_TARGET_VERSION="$(target_config_compat_version)" || return 0
  [[ -f "$DTCLAW_HOME/config.json" ]] || return 0
  mkdir -p "$WORK_DIR" || fail "failed to prepare config compatibility rules directory" 6

  local rules_file result status=0
  rules_file="$WORK_DIR/config-compat-rules.json"
  if ! download_config_compat_rules "$rules_file"; then
    fail "Failed to download config compatibility rules. Check your network connection and retry before installing this historical version." 6
  fi
  CONFIG_COMPAT_RULES_FILE="$rules_file"
  CONFIG_COMPAT_ROLLBACK_RECEIPT="$WORK_DIR/config-rollback.json"

  # Repair before the archive backend changes current. The historical target
  # is never asked to interpret the installation receipt.
  if apply_config_compat_rules_with_binary "$PROGRAM_DIR"; then
    CONFIG_COMPAT_REPAIR_DONE=true
    return 0
  fi

  result="$(apply_config_compat_rules_with_python "$CONFIG_COMPAT_RULES_FILE" "$CONFIG_COMPAT_TARGET_VERSION")" || status=$?
  case "$status" in
    0)
      print_config_compat_result "$result"
      CONFIG_COMPAT_REPAIR_DONE=true
      ;;
    3)
      fail "Config compatibility rules require a newer installer. Update AiWork and retry." 6
      ;;
    127)
      fail "Config compatibility repair requires Python 3. Install Python 3 and retry." 6
      ;;
    *)
      fail "Python config compatibility repair failed; config compatibility could not be established" 6
      ;;
  esac
}

apply_config_compat_rules_with_binary() {
  local repair_program product_cmd product_bin help result capability
  repair_program="$(cd "$1" 2>/dev/null && pwd -P)" || return 1
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$repair_program/bin/$product_cmd"
  [[ -x "$product_bin" ]] || return 1
  help="$(AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$repair_program" AGENTIX_PLUGIN_DIR="$repair_program/plugins" "$product_bin" __install repair-config --help 2>/dev/null)" || return 1
  grep -Fq -- "--compat-rules-only" <<<"$help" || return 1
  grep -Fq -- "--check-compat-rules" <<<"$help" || return 1
  grep -Fq -- "--rollback-receipt" <<<"$help" || return 1
  preserve_config_compat_restore_helper "$repair_program" || return 1

  capability="$(CONFIG_COMPAT_ROLLBACK_RECEIPT="$CONFIG_COMPAT_ROLLBACK_RECEIPT" AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$repair_program" AGENTIX_PLUGIN_DIR="$repair_program/plugins" "$product_bin" __install repair-config --state-dir "$DTCLAW_HOME" --config "$DTCLAW_HOME/config.json" --dist "$DIST" --rollback-receipt "$CONFIG_COMPAT_ROLLBACK_RECEIPT" --compat-rules-only --check-compat-rules --compat-rules "$CONFIG_COMPAT_RULES_FILE" --target-version "$CONFIG_COMPAT_TARGET_VERSION")" || fail "config compatibility check failed using $repair_program" 6
  case "$capability" in
    supported) ;;
    unsupported) return 1 ;;
    *) fail "invalid config compatibility capability response from $repair_program" 6 ;;
  esac

  result="$(CONFIG_COMPAT_ROLLBACK_RECEIPT="$CONFIG_COMPAT_ROLLBACK_RECEIPT" AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$repair_program" AGENTIX_PLUGIN_DIR="$repair_program/plugins" "$product_bin" __install repair-config --state-dir "$DTCLAW_HOME" --config "$DTCLAW_HOME/config.json" --dist "$DIST" --rollback-receipt "$CONFIG_COMPAT_ROLLBACK_RECEIPT" --compat-rules-only --compat-rules "$CONFIG_COMPAT_RULES_FILE" --target-version "$CONFIG_COMPAT_TARGET_VERSION")" || fail "config compatibility repair failed using $repair_program" 6
  print_config_compat_result "$result"
}

print_config_compat_result() {
  local result=$1
  if [[ "$result" == updated* ]]; then
    ok "applied config compatibility rules for target $CONFIG_COMPAT_TARGET_VERSION"
  fi
  printf '%s\n' "$result" | sed -n 's/^change:/  config compat: /p; s/^backup:/  backup: /p; s/^warning:/  warning: /p' | while IFS= read -r line; do
    info "$line"
  done
}

apply_config_compat_rules() {
  return 0
}

final_reconcile_current_bundled_skills_to_state() {
  [[ "$DRY_RUN" == true ]] && return 0
  local current_src_root="$PROGRAM_ROOT/$DIST/current/skills/bundled"
  local src_root="$current_src_root"
  local dst_root="$DTCLAW_HOME/skills/bundled"
  if [[ ! -d "$src_root" && -d "$PROGRAM_DIR/skills/bundled" ]]; then
    src_root="$PROGRAM_DIR/skills/bundled"
  fi
  if [[ ! -d "$src_root" ]]; then
    warn "final bundled skills reconcile skipped; source missing: $src_root"
    return 0
  fi
  local src_real dst_real
  src_real="$(cd "$src_root" 2>/dev/null && pwd -P)" || src_real="$src_root"
  dst_real="$(cd "$dst_root" 2>/dev/null && pwd -P)" || dst_real="$dst_root"
  [[ "$src_real" == "$dst_real" ]] && return 0
  restore_owner_write_for_upgrade "$DTCLAW_HOME/skills"
  local copied
  copied="$(find "$src_root" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l | tr -d '[:space:]')"
  rm -rf "$dst_root"
  mkdir -p "$dst_root"
  cp -R "$src_root"/. "$dst_root"/
  ok "final reconciled $copied bundled skill(s) into $dst_root (source: $src_root)"
}

repair_legacy_global_config_for_coder_validation() {
  local output_file=$1
  local config_json="$DTCLAW_HOME/config.json"
  [[ -f "$config_json" ]] || return 1
  coder_agent_validation_is_global_config_failure "$output_file" || return 1

  local backup_dir backup_base backup status changes_file tmp_file changes suffix remove_metrics migrate_aiwork_router
  backup_dir="$DTCLAW_HOME/.install/config-backups"
  backup_base="$backup_dir/config.pre-aiwork-legacy-compat.$(date -u +%Y%m%dT%H%M%SZ)-$$"
  backup="$backup_base.json"
  changes_file="$WORK_DIR/legacy-global-config-repair.changes"
  mkdir -p "$backup_dir" "$WORK_DIR" 2>/dev/null || return 1
  suffix=0
  while [[ -e "$backup" || -L "$backup" ]]; do
    suffix=$((suffix + 1))
    backup="$backup_base-$suffix.json"
  done
  cp "$config_json" "$backup" || return 1
  LEGACY_GLOBAL_CONFIG_REPAIR_BACKUP="$backup"
  tmp_file="$(mktemp "${config_json}.tmp.XXXXXX")" || return 1
  : >"$changes_file" || { rm -f "$tmp_file"; return 1; }
  remove_metrics=false
  grep -Fq "daemon.hooks.ai_code_metrics_post_commit_enabled" "$output_file" && remove_metrics=true
  migrate_aiwork_router=false
  grep -Fq 'unknown variant `aiwork_router`' "$output_file" && migrate_aiwork_router=true

  status=0
  awk -v changes_file="$changes_file" -v remove_metrics="$remove_metrics" -v migrate_aiwork_router="$migrate_aiwork_router" '
    function leading_indent(value, i, character) {
      for (i = 1; i <= length(value); i++) {
        character = substr(value, i, 1)
        if (character != " " && character != "\t") return i - 1
      }
      return length(value)
    }
    function emit(line) {
      if (pending != "") print pending
      pending = line
    }
    function note(message) {
      print message >> changes_file
      changed = 1
    }
    function unsupported() {
      bad = 1
      emit(line)
    }
    BEGIN {
      in_daemon = 0
      in_hooks = 0
      changed = 0
      bad = 0
      pending = ""
    }
    {
      line = $0
      indent = leading_indent(line)
      if (migrate_aiwork_router == "true" && line ~ /"aiwork_router"/) {
        gsub(/"aiwork_router"/, "\"dtcoder_router\"", line)
        if (!noted_aiwork_router) {
          note("renamed tools.web_search.aiwork_router to legacy dtcoder_router")
          noted_aiwork_router = 1
        }
      }
      if (!in_daemon && line ~ /^[[:space:]]*"daemon"[[:space:]]*:[[:space:]]*\{[[:space:]]*[,]?[[:space:]]*$/) {
        in_daemon = 1
        daemon_indent = indent
      }
      if (in_daemon && !in_hooks && line ~ /^[[:space:]]*"hooks"[[:space:]]*:[[:space:]]*\{[[:space:]]*[,]?[[:space:]]*$/) {
        in_hooks = 1
      }
      if (in_hooks && line ~ /"project_local_enabled"[[:space:]]*:/) {
        if (line ~ /^[[:space:]]*"project_local_enabled"[[:space:]]*:[[:space:]]*(true|false)[[:space:]]*,?[[:space:]]*$/) {
          # Already in the legacy-compatible typed shape; leave it unchanged.
        } else if (line ~ /^[[:space:]]*"project_local_enabled"[[:space:]]*:[[:space:]]*"(true|false)"[[:space:]]*,?[[:space:]]*$/) {
          gsub(/"[Tt][Rr][Uu][Ee]"/, "true", line)
          gsub(/"[Ff][Aa][Ll][Ss][Ee]"/, "false", line)
          note("normalized daemon.hooks.project_local_enabled")
        } else if (line ~ /^[[:space:]]*"project_local_enabled"[[:space:]]*:[[:space:]]*null[[:space:]]*,?[[:space:]]*$/) {
          note("removed null daemon.hooks.project_local_enabled")
          next
        } else {
          unsupported()
          next
        }
      }
      if (in_hooks && line ~ /"ai_code_metrics_post_commit_enabled"[[:space:]]*:/) {
        if (remove_metrics == "true") {
          if (line ~ /^[[:space:]]*"ai_code_metrics_post_commit_enabled"[[:space:]]*:[[:space:]]*("[^"\\]*"|true|false|null)[[:space:]]*,?[[:space:]]*$/) {
            note("removed unsupported daemon.hooks.ai_code_metrics_post_commit_enabled")
            next
          }
          unsupported()
          next
        } else if (line ~ /^[[:space:]]*"ai_code_metrics_post_commit_enabled"[[:space:]]*:[[:space:]]*(true|false)[[:space:]]*,?[[:space:]]*$/) {
          # Already in a typed shape. Keep it unless the requested binary
          # explicitly rejected this key and asked for removal.
        } else if (line ~ /^[[:space:]]*"ai_code_metrics_post_commit_enabled"[[:space:]]*:[[:space:]]*"(true|false)"[[:space:]]*,?[[:space:]]*$/) {
          gsub(/"[Tt][Rr][Uu][Ee]"/, "true", line)
          gsub(/"[Ff][Aa][Ll][Ss][Ee]"/, "false", line)
          note("normalized daemon.hooks.ai_code_metrics_post_commit_enabled")
        } else if (line ~ /^[[:space:]]*"ai_code_metrics_post_commit_enabled"[[:space:]]*:[[:space:]]*null[[:space:]]*,?[[:space:]]*$/) {
          note("removed null daemon.hooks.ai_code_metrics_post_commit_enabled")
          next
        } else {
          unsupported()
          next
        }
      }
      if (in_hooks && line ~ /^[[:space:]]*}[[:space:]]*,?[[:space:]]*$/) {
        sub(/[[:space:]]*,[[:space:]]*$/, "", pending)
        in_hooks = 0
      }
      if (in_daemon && !in_hooks && indent <= daemon_indent && line ~ /^[[:space:]]*}[[:space:]]*,?[[:space:]]*$/) {
        in_daemon = 0
      }
      emit(line)
    }
    END {
      if (pending != "") print pending
      if (bad) exit 2
      if (!changed) exit 3
    }
  ' "$config_json" >"$tmp_file" || status=$?
  if [[ "$status" -ne 0 ]]; then
    rm -f "$tmp_file"
    if [[ "$status" -eq 2 ]]; then
      warn "legacy config compatibility repair needs manual config shape: $config_json"
    else
      warn "failed to repair legacy config compatibility: $config_json"
    fi
    return 1
  fi

  local compact_tmp
  compact_tmp="$(mktemp "${config_json}.tmp.XXXXXX")" || { rm -f "$tmp_file"; return 1; }
  awk -v changes_file="$changes_file" '
    function leading_indent(value, i, character) {
      for (i = 1; i <= length(value); i++) {
        character = substr(value, i, 1)
        if (character != " " && character != "\t") return i - 1
      }
      return length(value)
    }
    function emit(line) {
      if (pending != "") print pending
      pending = line
    }
    function note(message) {
      print message >> changes_file
    }
    BEGIN {
      in_daemon = 0
      holding_hooks = 0
      pending = ""
    }
    {
      line = $0
      indent = leading_indent(line)
    }
    !in_daemon && /^[[:space:]]*"daemon"[[:space:]]*:[[:space:]]*\{[[:space:]]*[,]?[[:space:]]*$/ {
      in_daemon = 1
      daemon_indent = indent
      emit(line)
      next
    }
    in_daemon && !holding_hooks && /^[[:space:]]*"hooks"[[:space:]]*:[[:space:]]*\{[[:space:]]*[,]?[[:space:]]*$/ {
      hooks_line = $0
      holding_hooks = 1
      next
    }
    holding_hooks && /^[[:space:]]*}[[:space:]]*,?[[:space:]]*$/ {
      sub(/[[:space:]]*,[[:space:]]*$/, "", pending)
      note("removed empty daemon.hooks")
      holding_hooks = 0
      next
    }
    holding_hooks {
      emit(hooks_line)
      holding_hooks = 0
    }
    {
      if (line ~ /^[[:space:]]*}[[:space:]]*,?[[:space:]]*$/) {
        sub(/[[:space:]]*,[[:space:]]*$/, "", pending)
      }
      if (in_daemon && indent <= daemon_indent && line ~ /^[[:space:]]*}[[:space:]]*,?[[:space:]]*$/) {
        in_daemon = 0
      }
      emit(line)
    }
    END {
      if (holding_hooks) emit(hooks_line)
      if (pending != "") print pending
    }
  ' "$tmp_file" >"$compact_tmp" || { rm -f "$tmp_file" "$compact_tmp"; return 1; }
  rm -f "$tmp_file"
  tmp_file="$compact_tmp"

  atomic_replace_with_tmp "$tmp_file" "$config_json" || return 1
  changes="$(awk 'NF { text = text ? text "; " $0 : $0 } END { print text }' "$changes_file" 2>/dev/null || true)"
  ok "repaired legacy config compatibility for requested version: $config_json"
  [[ -n "$changes" ]] && info "  changes: $changes"
  [[ -n "$backup" ]] && info "  backup:  $backup"
  return 0
}

restore_legacy_global_config_repair_backup() {
  local backup=$1
  local config_json="$DTCLAW_HOME/config.json"
  [[ -n "$backup" && -f "$backup" ]] || return 1
  local tmp_file
  tmp_file="$(mktemp "${config_json}.tmp.XXXXXX")" || return 1
  cp "$backup" "$tmp_file" || { rm -f "$tmp_file"; return 1; }
  atomic_replace_with_tmp "$tmp_file" "$config_json"
}

run_coder_agent_show_with_legacy_config_repair() {
  local product_bin=$1
  local output_file=$2
  local attempts=0
  local repair_backup=""

  while true; do
    if run_coder_agent_show "$product_bin" "$output_file"; then
      return 0
    fi
    if [[ -n "$repair_backup" ]]; then
      warn "legacy config compatibility repair did not restore coder validation; restoring backup"
      restore_legacy_global_config_repair_backup "$repair_backup" \
        || warn "failed to restore legacy config backup: $repair_backup"
      return 1
    fi
    [[ "$attempts" -lt 2 ]] || return 1
    coder_agent_validation_is_global_config_failure "$output_file" || return 1
    repair_legacy_global_config_for_coder_validation "$output_file" || return 1
    repair_backup="$LEGACY_GLOBAL_CONFIG_REPAIR_BACKUP"
    attempts=$((attempts + 1))
  done
}

print_coder_agent_validation_diagnostics() {
  local product_bin=$1
  local output_file=$2
  local coder_json=$3

  warn "coder agent validation failed."
  print_coder_agent_diagnosis_command "$product_bin"
  warn "  agent config: $coder_json"
  if [[ -s "$output_file" ]]; then
    warn "coder agent validation output:"
    sed -n '1,80p' "$output_file" | sed 's/^/  /' >&2
  else
    warn "coder agent validation produced no diagnostic output"
  fi
}

repair_existing_coder_agent() {
  local product_bin=$1
  local coder_json=$2
  local validation_output=$3
  local coder_dir backup_parent backup_dir backup_base suffix=0 create_output validate_output

  coder_dir="$(dirname "$coder_json")"
  backup_parent="$DTCLAW_HOME/.install/agent-backups"
  backup_base="$backup_parent/coder.bak.$(date -u +%Y%m%dT%H%M%SZ)-$$"
  backup_dir="$backup_base"
  while [[ -e "$backup_dir" || -L "$backup_dir" ]]; do
    suffix=$((suffix + 1))
    backup_dir="$backup_base-$suffix"
  done
  mkdir -p "$WORK_DIR" 2>/dev/null || true
  mkdir -p "$backup_parent" \
    || fail "failed to create coder agent backup directory: $backup_parent" 6

  warn "repairing coder agent by backing up existing state: $backup_dir"
  mv "$coder_dir" "$backup_dir" \
    || fail "failed to back up existing coder agent for repair: $coder_dir -> $backup_dir" 6

  create_output="$WORK_DIR/coder-agent-create.log"
  validate_output="$WORK_DIR/coder-agent-show-after-repair.log"
  if AGENTIX_STATE_DIR="$DTCLAW_HOME" \
      AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" \
      AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" \
      "$product_bin" agent create coder --name Coder >"$create_output" 2>&1 \
      && run_coder_agent_show "$product_bin" "$validate_output"; then
    ok "coder agent recreated; previous state backed up at $backup_dir"
    return 0
  fi

  warn "coder agent repair failed; restoring previous coder agent from backup"
  if [[ -s "$create_output" ]]; then
    warn "coder agent repair create output:"
    sed -n '1,80p' "$create_output" | sed 's/^/  /' >&2
  fi
  if [[ -s "$validate_output" ]]; then
    warn "coder agent repair validation output:"
    sed -n '1,80p' "$validate_output" | sed 's/^/  /' >&2
  fi
  rm -rf "$coder_dir" 2>/dev/null || true
  mv "$backup_dir" "$coder_dir" 2>/dev/null \
    || fail "coder agent repair failed and previous backup could not be restored: $backup_dir -> $coder_dir" 6
  cp "$validation_output" "$WORK_DIR/coder-agent-show-before-repair.log" 2>/dev/null || true
  fail "coder agent exists but could not be repaired; previous state restored: $coder_json" 6
}

bootstrap_tui_default_agent() {
  local product_cmd product_bin agent_json
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$PROGRAM_DIR/bin/$product_cmd"
  agent_json="$DTCLAW_HOME/agents/coder-tui/agent.json"
  if [[ "$DRY_RUN" == true ]]; then
    echo "[dry-run] create coder-tui when $agent_json is absent; do not modify agents/coder"
    return 0
  fi

  [[ -x "$product_bin" ]] || fail "$product_cmd binary is not executable after install: $product_bin" 5
  if [[ -f "$agent_json" ]]; then
    ok "coder-tui agent already exists; leaving its configuration unchanged"
  elif [[ -e "$agent_json" || -L "$agent_json" ]]; then
    fail "coder-tui agent.json exists but is not a regular file: $agent_json" 6
  else
    info "creating coder-tui agent (TUI default; coder is left in place)"
    AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" \
      "$product_bin" agent create coder-tui --name "Coder TUI" \
      || fail "failed to create coder-tui agent" 6
    [[ -f "$agent_json" ]] || fail "coder-tui agent.json was not created: $agent_json" 6
    ok "coder-tui agent created"
  fi
  warn_tui_default_legacy_coder "$product_cmd"
}

warn_tui_default_legacy_coder() {
  local product_cmd=$1
  local coder_dir="$DTCLAW_HOME/agents/coder"
  [[ -d "$coder_dir" ]] || return 0
  if [[ ! -r "$coder_dir" || ! -x "$coder_dir" ]]; then
    warn "could not read $coder_dir; not claiming coder has no history. Existing coder data was not moved. Continue with: $product_cmd tui --agent coder"
    return 0
  fi
  local kind path hit
  for kind in sessions skills; do
    path="$coder_dir/$kind"
    [[ -e "$path" || -L "$path" ]] || continue
    if [[ -L "$path" ]]; then
      warn "TUI default agent is now coder-tui. Existing coder sessions and private skills stay on coder. Use: $product_cmd tui --agent coder"
      return 0
    fi
    if [[ ! -r "$path" ]]; then
      warn "could not read $path; not claiming coder has no history. Existing coder data was not moved."
      return 0
    fi
    [[ -d "$path" ]] || continue
    if ! hit="$(find "$path" \( -type l -o \( -type f ! -name 'catalog*' ! -name 'meta.wal.jsonl' ! -name 'index.json' \) \) -print -quit 2>/dev/null)"; then
      warn "could not scan $path; not claiming coder has no history. Existing coder data was not moved."
      return 0
    fi
    if [[ -n "$hit" ]]; then
      warn "TUI default agent is now coder-tui. Existing coder sessions and private skills stay on coder. Use: $product_cmd tui --agent coder"
      return 0
    fi
  done
}

bootstrap_coder_agent() {
  local product_cmd product_bin
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$PROGRAM_DIR/bin/$product_cmd"
  local coder_json="$DTCLAW_HOME/agents/coder/agent.json"
  if [[ "$DRY_RUN" == true ]]; then
    echo "[dry-run] AGENTIX_STATE_DIR=$DTCLAW_HOME AGENTIX_PROGRAM_DIR=$PROGRAM_DIR AGENTIX_PLUGIN_DIR=$PROGRAM_DIR/plugins $product_bin agent show coder"
    echo "[dry-run] repair missing app-pack referenced by $coder_json when needed"
    echo "[dry-run] AGENTIX_STATE_DIR=$DTCLAW_HOME $product_bin agent create coder --name Coder"
    echo "[dry-run] repair existing coder agent when --repair-coder-agent is set"
    echo "[dry-run] normalize legacy SRT CLI sandbox settings in $coder_json"
    return 0
  fi

  [[ -x "$product_bin" ]] || fail "$product_cmd binary is not executable after install: $product_bin" 5

  if [[ -f "$coder_json" ]]; then
    restore_coder_app_pack_if_release_removed_it
    repair_coder_agent_legacy_config "$coder_json"
    ensure_coder_agent_app_pack "$coder_json"
    local validation_output="$WORK_DIR/coder-agent-show.log"
    if run_coder_agent_show_with_legacy_config_repair "$product_bin" "$validation_output"; then
      ok "coder agent already exists; repaired missing app-pack binding"
      return 0
    fi
    if coder_agent_validation_is_managed_router_env_missing "$validation_output"; then
      print_coder_agent_managed_router_login_hint "$product_bin" "$validation_output"
      warn_managed_router_login_required
      return 0
    fi
    if coder_agent_validation_is_stale_router_auth_failure "$validation_output"; then
      if repair_stale_router_auth_for_coder_validation \
        && run_coder_agent_show "$product_bin" "$validation_output"; then
        ok "coder agent already exists; repaired stale router_auth metadata"
        return 0
      fi
      print_coder_agent_validation_diagnostics "$product_bin" "$validation_output" "$coder_json"
      print_coder_agent_config_failure_hint "$validation_output"
      if allow_requested_version_coder_validation_warning "$validation_output"; then
        warn_requested_version_coder_validation_degraded
        return 0
      fi
      fail "coder agent validation is blocked by incompatible global config: $DTCLAW_HOME/config.json" 6
    fi
    print_coder_agent_validation_diagnostics "$product_bin" "$validation_output" "$coder_json"
    if coder_agent_validation_is_global_config_failure "$validation_output"; then
      print_coder_agent_config_failure_hint "$validation_output"
      if allow_requested_version_coder_validation_warning "$validation_output"; then
        warn_requested_version_coder_validation_degraded
        return 0
      fi
      fail "coder agent validation is blocked by incompatible global config: $DTCLAW_HOME/config.json" 6
    fi
    if allow_requested_version_coder_validation_warning "$validation_output"; then
      warn_requested_version_coder_validation_degraded
      return 0
    fi
    if [[ "$REPAIR_CODER_AGENT" == true ]]; then
      repair_existing_coder_agent "$product_bin" "$coder_json" "$validation_output"
      return 0
    fi
    print_coder_agent_repair_hint
    fail "coder agent exists but could not be validated after app-pack repair: $coder_json" 6
  fi

  local validation_output="$WORK_DIR/coder-agent-show.log"
  if run_coder_agent_show_with_legacy_config_repair "$product_bin" "$validation_output"; then
    ok "coder agent already exists; verified AiWork CLI"
    return 0
  fi
  if coder_agent_validation_is_managed_router_env_missing "$validation_output"; then
    print_coder_agent_managed_router_login_hint "$product_bin" "$validation_output"
    warn_managed_router_login_required
    return 0
  fi

  info "creating coder agent"
  AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" "$product_bin" agent create coder --name Coder \
    || fail "failed to create coder agent" 6
  ok "coder agent created"
}

ensure_coder_agent_app_pack() {
  local coder_json=$1
  [[ -f "$coder_json" ]] || return 0

  local origin status
  status=0
  origin="$(read_coder_app_pack_origin "$coder_json")" || status=$?
  if [[ "$status" -eq 2 ]]; then
    fail "cannot safely read existing coder app-pack origin without python3: $coder_json" 6
  fi
  [[ "$status" -eq 0 ]] || return 0

  local app_pack_id version
  app_pack_id="${origin%%	*}"
  version="${origin#*	}"
  validate_coder_app_pack_origin "$app_pack_id" "$version"

  local manifest="$DTCLAW_HOME/app-packs/$app_pack_id/$version/manifest.json"
  [[ -f "$manifest" ]] && return 0

  info "coder agent references missing app-pack '$app_pack_id@$version'; installing it"
  local archive
  archive="$(resolve_coder_app_pack_archive "$app_pack_id" "$version")" \
    || fail "failed to resolve app-pack archive for $app_pack_id@$version" 6

  local product_cmd product_bin
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$PROGRAM_DIR/bin/$product_cmd"
  [[ -x "$product_bin" ]] || fail "$product_cmd binary is not executable after install: $product_bin" 5
  AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" "$product_bin" app-pack install "$archive" --agent-id coder \
    || fail "failed to install app-pack $app_pack_id@$version for coder" 6
}

validate_coder_app_pack_origin() {
  local app_pack_id=$1 version=$2
  case "$app_pack_id:$version" in
    *'/'*|*'..'*|*':'|':'*|':') fail "invalid coder app-pack origin: $app_pack_id@$version" 5 ;;
  esac
}

read_coder_app_pack_origin_without_python() {
  local coder_json=$1
  local content block app_pack_id version
  content="$(tr -d '\n\r' <"$coder_json" 2>/dev/null || true)"
  case "$content" in
    *'"app_pack_origin"'*) ;;
    *) return 1 ;;
  esac
  block="$(printf '%s' "$content" | sed -n 's/.*"app_pack_origin"[[:space:]]*:[[:space:]]*{\([^}]*\)}.*/\1/p')"
  [[ -n "$block" ]] || return 2
  app_pack_id="$(printf '%s' "$block" | sed -n 's/.*"app_pack_id"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
  version="$(printf '%s' "$block" | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"\\]*\)".*/\1/p')"
  [[ -n "$app_pack_id" && -n "$version" ]] || return 2
  printf '%s\t%s\n' "$app_pack_id" "$version"
}

read_coder_app_pack_origin() {
  local coder_json=$1
  local python3_bin
  python3_bin="$(preferred_python3)"
  if [[ -z "$python3_bin" ]]; then
    read_coder_app_pack_origin_without_python "$coder_json"
    return $?
  fi

  "$python3_bin" - "$coder_json" <<'PY'
import json
import sys

with open(sys.argv[1], encoding="utf-8") as handle:
    value = json.load(handle)

if "app_pack_origin" not in value:
    raise SystemExit(1)
origin = value.get("app_pack_origin")
if not isinstance(origin, dict):
    raise SystemExit(2)

app_pack_id = origin.get("app_pack_id")
version = origin.get("version")
if not isinstance(app_pack_id, str) or not app_pack_id.strip():
    raise SystemExit(2)
if not isinstance(version, str) or not version.strip():
    raise SystemExit(2)

print(f"{app_pack_id.strip()}\t{version.strip()}")
PY
}

resolve_coder_app_pack_archive() {
  local app_pack_id=$1
  local version=$2
  local filename="$app_pack_id-$version.tar.gz"
  local candidate

  local candidates=("$DTCLAW_HOME/app-packs/$filename")
  if [[ -n "${CACHED_UPDATE_DIR:-}" ]]; then
    candidates+=("$CACHED_UPDATE_DIR/app-packs/$filename" "$CACHED_UPDATE_DIR/$filename")
  fi

  for candidate in "${candidates[@]}"; do
    [[ -n "$candidate" && -f "$candidate" ]] || continue
    verify_app_pack_archive_checksum_if_present "$candidate"
    printf '%s\n' "$candidate"
    return 0
  done

  local subdir archive_url sha_url archive sha_file
  subdir="$(remote_subdir)"
  archive_url="${BASE_URL%/}/${subdir}/app-packs/$filename"
  sha_url="$archive_url.sha256"
  mkdir -p "$WORK_DIR/app-packs"
  archive="$WORK_DIR/app-packs/$filename"
  sha_file="$archive.sha256"
  info "downloading app-pack archive: $archive_url" >&2
  download_to "$archive_url" "$archive"
  download_to "$sha_url" "$sha_file"
  verify_app_pack_archive_checksum "$archive" "$sha_file"
  printf '%s\n' "$archive"
}

verify_app_pack_archive_checksum_if_present() {
  local archive=$1
  local sha_file="$archive.sha256"
  [[ -f "$sha_file" ]] || return 0
  verify_app_pack_archive_checksum "$archive" "$sha_file"
}

verify_app_pack_archive_checksum() {
  local archive=$1
  local sha_file=$2
  local expected actual
  expected="$(awk 'NF { print $1; exit }' "$sha_file")"
  [[ -n "$expected" ]] || fail "empty app-pack checksum file: $sha_file" 4
  if command -v sha256sum >/dev/null 2>&1; then
    actual="$(sha256sum "$archive" | awk '{ print $1 }')"
  elif command -v shasum >/dev/null 2>&1; then
    actual="$(shasum -a 256 "$archive" | awk '{ print $1 }')"
  else
    fail "no sha256sum/shasum; cannot verify app-pack checksum" 4
  fi
  [[ "$actual" == "$expected" ]] || fail "app-pack checksum mismatch for $archive" 4
  ok "app-pack sha256 verified: $(basename "$archive")" >&2
}

repair_coder_agent_legacy_config() {
  local coder_json=$1
  [[ -f "$coder_json" ]] || return 0

  local result status=0
  result="$(run_install_config_repair --repair-coder-agent --coder-agent "$coder_json")" || status=$?
  if [[ "$status" -ne 0 ]]; then
    if install_config_repair_failure_is_unsupported "$status"; then
      warn "installed version does not support install config repair; legacy coder config left unchanged: $coder_json"
      return 0
    fi
    fail "failed to repair existing coder agent config: $coder_json" 5
  fi

  if [[ "$result" == updated* ]]; then
    ok "repaired legacy coder SRT CLI sandbox config"
    printf '%s\n' "$result" | sed -n 's/^backup:/  backup:  /p' | while IFS= read -r line; do
      info "$line"
    done
  fi
}

verify_install() {
  [[ "$DRY_RUN" == true ]] && return 0

  local dtclaw_bin="$PROGRAM_DIR/bin/dtclaw"
  local dtcoder_bin="$PROGRAM_DIR/bin/dtcoder"
  local product_cmd product_bin tui_name tui_bin
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$PROGRAM_DIR/bin/$product_cmd"
  tui_name="$(tui_command_for_program_dir "$PROGRAM_DIR")"
  tui_bin="$PROGRAM_DIR/bin/$tui_name"

  [[ -x "$dtclaw_bin" ]] || fail "missing executable: $dtclaw_bin" 5
  [[ -x "$dtcoder_bin" ]] || fail "missing executable: $dtcoder_bin" 5
  [[ -x "$product_bin" ]] || fail "missing executable: $product_bin" 5

  # macOS: clear quarantine on all program bins/plugins (not only launcher).
  # This only removes com.apple.quarantine xattr — it does not strip codesign.
  if [[ "$(uname -s)" == "Darwin" ]] && command -v xattr >/dev/null 2>&1; then
    local f
    if [[ -d "$PROGRAM_DIR/bin" ]]; then
      while IFS= read -r f; do
        [[ -n "$f" ]] || continue
        xattr -d com.apple.quarantine "$f" 2>/dev/null || true
      done < <(find "$PROGRAM_DIR/bin" -type f 2>/dev/null)
    fi
    if [[ -d "$PROGRAM_DIR/plugins" ]]; then
      while IFS= read -r f; do
        [[ -n "$f" ]] || continue
        xattr -d com.apple.quarantine "$f" 2>/dev/null || true
      done < <(find "$PROGRAM_DIR/plugins" -type f 2>/dev/null)
    fi
  fi

  # macOS: reset TCC (Transparency, Consent, and Control) database entries
  # for the installed binaries. Without this, macOS may show dialogs like
  # "macOS隐私与安全性已阻止'DTCoder'修改Mac上的App" even after clearing
  # quarantine. tccutil reset removes any previously cached permission denials
  # so the user gets a fresh prompt on next launch.
  if [[ "$(uname -s)" == "Darwin" ]]; then
    if command -v tccutil >/dev/null 2>&1; then
      # Reset TCC for the Apple Events service (controlling other apps)
      tccutil reset AppleEvents com.agentix.dtcoder 2>/dev/null || true
      tccutil reset AppleEvents "$(basename "$dtcoder_bin")" 2>/dev/null || true
      tccutil reset AppleEvents "$(basename "$dtclaw_bin")" 2>/dev/null || true
      # Reset TCC for System Events (modifying system settings / apps)
      tccutil reset SystemPolicyAllFiles "$(basename "$dtcoder_bin")" 2>/dev/null || true
      tccutil reset SystemPolicyAllFiles "$(basename "$dtclaw_bin")" 2>/dev/null || true
      # Also reset for full path to ensure clean state
      tccutil reset All "$dtcoder_bin" 2>/dev/null || true
      tccutil reset All "$dtclaw_bin" 2>/dev/null || true
    fi
  fi

  if [[ "$SKIP_OPENCODE" != true ]]; then
    [[ -x "$tui_bin" ]] || fail "missing executable: $tui_bin" 5
    AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" "$tui_bin" --version >/dev/null || {
      diagnose_version_failure "$tui_bin"
      fail "$tui_name version check failed" 6
    }
  fi
  AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" "$product_bin" --version >/dev/null || {
    diagnose_version_failure "$product_bin"
    fail "$product_cmd version check failed" 6
  }
  AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" "$dtcoder_bin" --version >/dev/null || {
    diagnose_version_failure "$dtcoder_bin"
    fail "compatibility binary (dtcoder) version check failed" 6
  }
  AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" "$dtclaw_bin" --version >/dev/null || {
    diagnose_version_failure "$dtclaw_bin"
    fail "compatibility binary (dtclaw) version check failed" 6
  }

  ok "AiWork install verified"
}

# ─── PATH configuration ────────────────────────────────────────
# Append the stable user bin dir to the user's shell rc files, idempotently.
# A clearly-delimited marker block lets re-runs and upgrades avoid duplicate
# entries and stay cleanly removable. Honors --no-modify-path.
PATH_MARKER_BEGIN="# >>> agentix aiwork PATH >>>"
PATH_MARKER_END="# <<< agentix aiwork PATH <<<"
LEGACY_PATH_MARKER_BEGIN="# >>> agentix dtcoder PATH >>>"
LEGACY_PATH_MARKER_END="# <<< agentix dtcoder PATH <<<"
PATH_RC_ENTRY=""
PATH_RC_FILE=""
SYMLINKS_MANAGED=false

path_already_has_dir() {
  local dir=$1
  case ":${PATH}:" in
    *":${dir}:"*) return 0 ;;
    *) return 1 ;;
  esac
}

path_marker_has_entry() {
  local rc_file=$1
  local bin_dir=$2
  local expected_entry
  expected_entry="$(path_export_line "$bin_dir")"

  awk \
    -v marker_begin="$PATH_MARKER_BEGIN" \
    -v marker_end="$PATH_MARKER_END" \
    -v legacy_marker_begin="$LEGACY_PATH_MARKER_BEGIN" \
    -v legacy_marker_end="$LEGACY_PATH_MARKER_END" \
    -v expected_entry="$expected_entry" \
    '
      $0 == marker_begin || $0 == legacy_marker_begin { in_marker = 1; entry_in_marker = 0; next }
      in_marker && $0 == expected_entry { entry_in_marker = 1 }
      in_marker && ($0 == marker_end || $0 == legacy_marker_end) {
        if (entry_in_marker) found = 1
        in_marker = 0
      }
      END { exit found ? 0 : 1 }
    ' "$rc_file"
}

path_export_line() {
  local bin_dir=$1
  if [[ "$bin_dir" == "$HOME/.local/bin" ]]; then
    printf '%s\n' 'case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) export PATH="$HOME/.local/bin:$PATH";; esac'
  else
    printf 'case ":$PATH:" in *":%s:"*) ;; *) export PATH="%s:$PATH";; esac\n' "$bin_dir" "$bin_dir"
  fi
}

path_entry_label() {
  local bin_dir=$1
  if [[ "$bin_dir" == "$HOME/.local/bin" ]]; then
    printf '%s\n' '$HOME/.local/bin'
  else
    printf '%s\n' "$bin_dir"
  fi
}

record_path_rc_file() {
  local rc_file=$1
  local label=$2
  PATH_RC_ENTRY="$label"
  case $'\n'"$PATH_RC_FILE"$'\n' in
    *$'\n'"$rc_file"$'\n'*) ;;
    *)
      [[ -z "$PATH_RC_FILE" ]] || PATH_RC_FILE+=$'\n'
      PATH_RC_FILE+="$rc_file"
      ;;
  esac
}

append_path_block_to_rc() {
  local rc_file=$1
  local bin_dir=$2
  local export_line label
  export_line="$(path_export_line "$bin_dir")"
  label="$(path_entry_label "$bin_dir")"

  # Idempotent: never append twice. Replace stale Agentix PATH marker blocks
  # so upgrades move users to the stable ~/.local/bin command entrypoint.
  if [[ -f "$rc_file" ]] && { grep -qF "$PATH_MARKER_BEGIN" "$rc_file" || grep -qF "$LEGACY_PATH_MARKER_BEGIN" "$rc_file"; }; then
    if path_marker_has_entry "$rc_file" "$bin_dir"; then
      ok "PATH block already present in $rc_file"
      record_path_rc_file "$rc_file" "$label"
    else
      if [[ "$DRY_RUN" == true ]]; then
        echo "[dry-run] would update PATH block in $rc_file to $label"
        return 0
      fi
      local tmp_file
      tmp_file="$(mktemp "${TMPDIR:-/tmp}/aiwork-path-rc.XXXXXX")" || {
        warn "PATH rc update failed; skipped: $rc_file"
        return 0
      }
      if awk \
        -v marker_begin="$PATH_MARKER_BEGIN" \
        -v marker_end="$PATH_MARKER_END" \
        -v legacy_marker_begin="$LEGACY_PATH_MARKER_BEGIN" \
        -v legacy_marker_end="$LEGACY_PATH_MARKER_END" \
        -v export_line="$export_line" \
        '
          $0 == marker_begin || $0 == legacy_marker_begin {
            print marker_begin
            print export_line
            print marker_end
            in_marker = 1
            next
          }
          in_marker && ($0 == marker_end || $0 == legacy_marker_end) { in_marker = 0; next }
          !in_marker { print }
        ' "$rc_file" >"$tmp_file" && mv "$tmp_file" "$rc_file"; then
        ok "updated PATH block in $rc_file to $label"
        record_path_rc_file "$rc_file" "$label"
      else
        rm -f "$tmp_file"
        warn "PATH rc update failed; skipped: $rc_file"
      fi
    fi
    return 0
  fi

  if [[ "$DRY_RUN" == true ]]; then
    echo "[dry-run] would append PATH block for $label to $rc_file"
    return 0
  fi

  if ! mkdir -p "$(dirname "$rc_file")" 2>/dev/null; then
    warn "PATH rc directory not writable; skipped: $(dirname "$rc_file")"
    return 0
  fi
  if {
    printf '\n%s\n' "$PATH_MARKER_BEGIN"
    printf '%s\n' "$export_line"
    printf '%s\n' "$PATH_MARKER_END"
  } >>"$rc_file"; then
    ok "added $label to PATH via $rc_file"
    record_path_rc_file "$rc_file" "$label"
  else
    warn "PATH rc append failed; skipped: $rc_file"
  fi
}

repair_existing_path_blocks() {
  local bin_dir=$1
  local rc_file
  for rc_file in "$HOME/.zshrc" "$HOME/.zprofile" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.bash_login" "$HOME/.profile"; do
    if [[ -f "$rc_file" ]] && { grep -qF "$PATH_MARKER_BEGIN" "$rc_file" || grep -qF "$LEGACY_PATH_MARKER_BEGIN" "$rc_file"; }; then
      append_path_block_to_rc "$rc_file" "$bin_dir"
    fi
  done
}

shell_name_from_command() {
  local shell_command=${1:-}
  shell_command="${shell_command%%[[:space:]]*}"
  shell_command="${shell_command##*/}"
  shell_command="${shell_command#-}"
  case "$shell_command" in
    bash|zsh) printf '%s\n' "$shell_command" ;;
    *) return 1 ;;
  esac
}

current_interactive_shell_name() {
  # $SHELL is the login-shell preference and may be inherited through SSH.
  # For a terminal install, the direct parent is the shell currently running
  # the installer. Do not walk further up the process tree: wrappers and
  # non-interactive invocations should retain the $SHELL-only fallback.
  # path_target_shell_names is consumed through process substitution, so its
  # stdout may be a pipe even for an interactive installer. stderr remains
  # attached to the terminal in that case.
  [[ -t 1 || -t 2 ]] || return 1
  command -v ps >/dev/null 2>&1 || return 1

  local parent_command
  parent_command="$(ps -p "$PPID" -o comm= 2>/dev/null)" || return 1
  shell_name_from_command "$parent_command"
}

path_target_shell_names() {
  local login_shell=""
  local current_shell=""

  login_shell="$(shell_name_from_command "${SHELL:-}" 2>/dev/null || true)"
  current_shell="$(current_interactive_shell_name || true)"

  if [[ -n "$login_shell" ]]; then
    printf '%s\n' "$login_shell"
  fi
  if [[ -n "$current_shell" && "$current_shell" != "$login_shell" ]]; then
    printf '%s\n' "$current_shell"
  fi
  if [[ -z "$login_shell" && -z "$current_shell" ]]; then
    printf '%s\n' "unknown"
  fi
}

path_rc_files_for_shell() {
  local shell_name=${1:-}
  if [[ -z "$shell_name" ]]; then
    shell_name="$(shell_name_from_command "${SHELL:-}" 2>/dev/null || printf '%s' unknown)"
  fi
  case "$shell_name" in
    zsh)
      printf '%s\n' "$HOME/.zshrc"
      printf '%s\n' "$HOME/.zprofile"
      ;;
    bash)
      printf '%s\n' "$HOME/.bashrc"
      # Login-shell file: never create ~/.bash_profile over an existing
      # ~/.profile — bash reads only the first of .bash_profile/.bash_login/
      # .profile, so a fresh .bash_profile would silently shadow the user's
      # login environment kept in ~/.profile.
      if [[ -f "$HOME/.bash_profile" ]]; then
        printf '%s\n' "$HOME/.bash_profile"
      elif [[ -f "$HOME/.bash_login" ]]; then
        printf '%s\n' "$HOME/.bash_login"
      elif [[ -f "$HOME/.profile" ]]; then
        printf '%s\n' "$HOME/.profile"
      else
        printf '%s\n' "$HOME/.bash_profile"
      fi
      ;;
    *)
      local found=false
      local rc_file
      for rc_file in "$HOME/.zshrc" "$HOME/.bashrc"; do
        if [[ -f "$rc_file" ]]; then
          printf '%s\n' "$rc_file"
          found=true
        fi
      done
      if [[ "$found" != true ]]; then
        printf '%s\n' "$HOME/.profile"
      fi
      ;;
  esac
}

print_completion_banner() {
  local symlink_status="not created"
  local path_status="not modified"
  local path_rc_files
  local product_cmd
  product_cmd="$(product_command_for_dist "$DIST")"
  local command_path="$HOME/.local/bin/$product_cmd"

  if [[ "$NO_SYMLINK" == true ]]; then
    command_path="$PROGRAM_DIR/bin/$product_cmd"
  fi

  if [[ "${SYMLINKS_MANAGED:-false}" == true && -n "${SYMLINK_TARGET_DIR:-}" ]]; then
    symlink_status="$SYMLINK_TARGET_DIR"
  elif [[ "$DRY_RUN" == true ]]; then
    symlink_status="not created (dry-run)"
  fi
  if [[ "$DRY_RUN" == true ]]; then
    path_status="not modified (dry-run)"
  elif [[ -n "$PATH_RC_ENTRY" && -n "$PATH_RC_FILE" ]]; then
    path_rc_files="${PATH_RC_FILE//$'\n'/, }"
    path_status="$PATH_RC_ENTRY (in $path_rc_files)"
  fi

  cat <<EOF

────────────────────────────────────────────────────────────
  AiWork installed

  State dir:    $DTCLAW_HOME
  Program dir:  $PROGRAM_DIR
  Symlink dir: $symlink_status
  RC PATH entry: $path_status
EOF

  if [[ "$NO_SYMLINK" != true ]]; then
    cat <<EOF
  Use it now — no new terminal required:
    export PATH="\$HOME/.local/bin:\$PATH" && $product_cmd
EOF
  fi

  if [[ -n "$PATH_RC_FILE" ]]; then
    cat <<EOF
  Future shell sessions that read the listed rc file(s) can run: $product_cmd
EOF
  fi

  cat <<EOF
  Try:
    AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" "$command_path" login
    AGENTIX_STATE_DIR="$DTCLAW_HOME" "$command_path"
    "$command_path" --version
────────────────────────────────────────────────────────────
EOF
}

configure_path() {
  local bin_dir="$HOME/.local/bin"
  local rc_file
  local shell_name

  PATH_RC_ENTRY=""
  PATH_RC_FILE=""

  if [[ "$NO_MODIFY_PATH" == true ]]; then
    info "PATH not modified (--no-modify-path). Add it manually:"
    echo '    export PATH="$HOME/.local/bin:$PATH"'
    return 0
  fi

  repair_existing_path_blocks "$bin_dir"

  if [[ "${SYMLINKS_MANAGED:-false}" == true && -n "${SYMLINK_TARGET_DIR:-}" ]] && path_already_has_dir "$SYMLINK_TARGET_DIR"; then
    ok "$SYMLINK_TARGET_DIR already on PATH — commands available immediately"
  elif path_already_has_dir "$bin_dir"; then
    ok "$bin_dir already on PATH — commands available immediately"
  else
    while IFS= read -r shell_name; do
      while IFS= read -r rc_file; do
        [[ -n "$rc_file" ]] || continue
        append_path_block_to_rc "$rc_file" "$bin_dir"
      done < <(path_rc_files_for_shell "$shell_name")
    done < <(path_target_shell_names)
  fi
}

# ─── symlinks (immediate availability) ───────────────────────────
# Symlink shipped user-facing binaries into the stable per-user command
# entrypoint. configure_path() writes this same directory to shell rc files.
SYMLINK_TARGET_DIR=""

remove_stale_managed_dtcoder_tui_symlink() {
  local target_dir=$1
  local bin_dir=$2
  local legacy_link="$target_dir/dtcoder-tui"

  [[ -x "$bin_dir/aiwork-tui" ]] || return 0
  [[ ! -e "$bin_dir/dtcoder-tui" && ! -L "$bin_dir/dtcoder-tui" ]] || return 0
  [[ -L "$legacy_link" ]] || return 0

  local link_target
  link_target="$(readlink "$legacy_link" 2>/dev/null || true)"
  [[ -n "$link_target" ]] || return 0

  local target_path
  case "$link_target" in
    /*) target_path="$link_target" ;;
    *) target_path="$(dirname "$legacy_link")/$link_target" ;;
  esac

  local managed_root="${PROGRAM_ROOT%/}/$DIST"
  local managed_root_real target_real
  managed_root_real="$(canonical_path "$managed_root" 2>/dev/null || true)"
  target_real="$(canonical_path "$target_path" 2>/dev/null || true)"

  [[ -n "$managed_root_real" && -n "$target_real" ]] || return 0
  case "$target_real" in
    "$managed_root_real"|"$managed_root_real"/*)
      rm -f "$legacy_link"
      ok "removed stale legacy TUI symlink: $legacy_link"
      ;;
  esac
}

try_create_symlinks() {
  [[ "$DRY_RUN" == true ]] && return 0
  SYMLINKS_MANAGED=false
  if [[ "$NO_SYMLINK" == true ]]; then
    info "global command symlinks skipped (--no-symlink)"
    return 0
  fi

  SYMLINK_TARGET_DIR="$HOME/.local/bin"
  mkdir -p "$SYMLINK_TARGET_DIR"

  local target_dir="$SYMLINK_TARGET_DIR"

  local bin_dir
  bin_dir="$(cd "$PROGRAM_DIR/bin" 2>/dev/null && pwd -P)" || bin_dir="$PROGRAM_DIR/bin"
  local real_target_dir
  real_target_dir="$(cd "$target_dir" 2>/dev/null && pwd -P)" || real_target_dir="$target_dir"

  if [[ "$bin_dir" == "$real_target_dir" ]]; then
    info "Install dir and symlink target are the same ($bin_dir); skipping symlink creation"
    return 0
  fi

  local name
  local product_cmd
  product_cmd="$(product_command_for_dist "$DIST")"

  for name in aiwork aiworkcn aiworkcli aiwork-tui dtcoder-tui dtcoder dtclaw dtcodercli-internal dtcodercn dtcodercli; do
    local src="$bin_dir/$name"
    local dst="$target_dir/$name"
    is_aiwork_entrypoint_for_dist "$DIST" "$name" || continue
    [[ -x "$src" ]] || continue
    local visible=false
    [[ "$name" == "$product_cmd" ]] && visible=true

    if [[ -e "$dst" || -L "$dst" ]]; then
      local current_target
      current_target="$(readlink "$dst" 2>/dev/null || echo "(not a symlink)")"
      if [[ "$visible" == true ]]; then
        warn "$dst already exists (-> $current_target); overwriting"
      fi
    fi
    ln -sf "$src" "$dst"
    SYMLINKS_MANAGED=true
    if [[ "$visible" == true ]]; then
      ok "symlink: $dst -> $src"
    fi
  done

  remove_stale_managed_dtcoder_tui_symlink "$target_dir" "$bin_dir"
}

# ─── running process detection ─────────────────────────────────
# Before overwriting binaries, detect running AiWork/compatibility/TUI
# processes proven to belong to the target program dir only. Overwriting a
# running binary can cause ETXTBSY or leave orphaned processes that cannot
# connect to the new daemon. State-dir evidence never expands this scope.

canonical_path() {
  local path=$1
  if command -v realpath >/dev/null 2>&1; then
    realpath "$path" 2>/dev/null && return 0
    local probe="$path" suffix="" base resolved
    while [[ ! -e "$probe" && "$probe" != "/" && "$probe" != "." ]]; do
      base="$(basename "$probe")"
      suffix="/$base$suffix"
      probe="$(dirname "$probe")"
    done
    if [[ -e "$probe" ]]; then
      resolved="$(realpath "$probe" 2>/dev/null)" && { printf '%s%s\n' "$resolved" "$suffix"; return 0; }
    fi
  fi
  local python3_bin
  python3_bin="$(preferred_python3)"
  if [[ -n "$python3_bin" ]]; then
    if "$python3_bin" - "$path" <<'PY'
import os, sys
print(os.path.realpath(os.path.abspath(sys.argv[1])))
PY
    then
      return 0
    fi
  fi
  local dir base
  dir="$(dirname "$path")"
  base="$(basename "$path")"
  if [[ -d "$dir" ]]; then
    printf '%s/%s\n' "$(cd "$dir" && pwd -P)" "$base"
  else
    printf '%s\n' "$path"
  fi
}

process_executable_path() {
  local pid=$1
  if [[ -e "/proc/$pid/exe" ]]; then
    readlink "/proc/$pid/exe" 2>/dev/null || true
    return 0
  fi
  # macOS exposes the real executable separately from argv and the truncated
  # process name. Read that identity when Python is available, then keep the
  # existing lsof fallback for installations without Python.
  local kernel_path
  kernel_path="$(process_executable_path_from_kernel "$pid")" || true
  if [[ -n "$kernel_path" ]]; then
    printf '%s\n' "$kernel_path"
    return 0
  fi
  if command -v lsof >/dev/null 2>&1; then
    local lsof_path
    lsof_path="$(process_executable_path_from_lsof "$pid")" || true
    if [[ -n "$lsof_path" ]]; then
      printf '%s\n' "$lsof_path"
      return 0
    fi
  fi
  # `command` is argv rendered with spaces and cannot be split at its first
  # word: the default macOS program root contains "Application Support".
  local comm_path
  comm_path="$(ps -ww -p "$pid" -o comm= 2>/dev/null)" || true
  case "$comm_path" in
    /*) [[ -f "$comm_path" ]] && printf '%s\n' "$comm_path" ;;
  esac
  return 0
}

process_executable_path_from_kernel() {
  [[ "$(uname -s)" == Darwin ]] || return 0
  local python3_bin
  python3_bin="$(preferred_python3)"
  [[ -n "$python3_bin" ]] || return 0
  "$python3_bin" - "$1" <<'PY'
import ctypes
import os
import sys

try:
    libproc = ctypes.CDLL("/usr/lib/libproc.dylib")
    libproc.proc_pidpath.argtypes = (ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32)
    libproc.proc_pidpath.restype = ctypes.c_int
    buffer = ctypes.create_string_buffer(4096)
    if libproc.proc_pidpath(int(sys.argv[1]), buffer, len(buffer)) > 0:
        print(os.fsdecode(buffer.value))
except (OSError, ValueError, AttributeError):
    pass
PY
}

process_executable_path_from_lsof() {
  local pid=$1
  local timeout_ticks=${INSTALL_DTCODER_LSOF_TIMEOUT_TICKS:-10}
  local tick_delay=${INSTALL_DTCODER_LSOF_TICK_DELAY:-0.1}
  local output="${WORK_DIR:-${TMPDIR:-/tmp}}/install-lsof-$pid-$$.out"
  local child tick
  : >"$output" 2>/dev/null || return 0
  lsof -a -p "$pid" -d txt -Fn >"$output" 2>/dev/null &
  child=$!
  for ((tick = 0; tick < timeout_ticks; tick++)); do
    if ! command kill -0 "$child" 2>/dev/null; then
      wait "$child" 2>/dev/null || true
      sed -n 's/^n//p' "$output" 2>/dev/null | head -n 1
      rm -f "$output" 2>/dev/null || true
      return 0
    fi
    sleep "$tick_delay"
  done
  command kill -TERM "$child" 2>/dev/null || true
  sleep "$tick_delay"
  if command kill -0 "$child" 2>/dev/null; then
    command kill -KILL "$child" 2>/dev/null || true
  fi
  wait "$child" 2>/dev/null || true
  rm -f "$output" 2>/dev/null || true
  return 0
}

process_command_line() {
  local pid=$1
  ps -p "$pid" -o command= 2>/dev/null || true
}

protected_install_pids() {
  printf '%s\n' "$$"

  local pid="${PPID:-}"
  local seen=" $$ "
  while [[ "$pid" =~ ^[0-9]+$ && "$pid" -gt 1 ]]; do
    case "$seen" in
      *" $pid "*) break ;;
    esac
    printf '%s\n' "$pid"
    seen="${seen}${pid} "

    local parent
    parent="$(ps -p "$pid" -o ppid= 2>/dev/null | tr -d '[:space:]')" || true
    [[ -n "$parent" ]] || break
    pid="$parent"
  done

  if [[ -n "${INSTALL_DTCODER_PROTECTED_PIDS:-}" ]]; then
    tr ' ,' '\n\n' <<<"$INSTALL_DTCODER_PROTECTED_PIDS" | sed '/^$/d'
  fi
}

is_protected_install_pid() {
  local candidate=$1
  local protected protected_pids
  if [[ $# -ge 2 ]]; then
    protected_pids=$2
  else
    protected_pids="$(protected_install_pids)"
  fi
  while IFS= read -r protected; do
    [[ -n "$protected" ]] || continue
    if [[ "$candidate" == "$protected" ]]; then
      return 0
    fi
  done <<< "$protected_pids"
  return 1
}

dtcoder_process_names_in_stop_order() {
  # Launchers may exec into product bins, so long-lived gateway/agent
  # processes can run under either current AiWork names or legacy aliases.
  printf '%s\n' aiwork-tui dtcoder-tui aiwork aiworkcn aiworkcli dtcoder dtclaw dtcodercli-internal dtcodercn dtcodercli
}

path_points_to_target() {
  local candidate=$1
  local target=$2
  [[ -e "$candidate" && -e "$target" ]] || return 1
  [[ "$(canonical_path "$candidate")" == "$(canonical_path "$target")" ]]
}

command_mentions_path() {
  local command=$1
  local path=$2
  [[ -n "$command" && -n "$path" ]] || return 1
  case " $command " in
    *" $path "*) return 0 ;;
  esac
  return 1
}

command_mentions_option_path() {
  local command=$1
  local option=$2
  local path=$3
  [[ -n "$command" && -n "$option" && -n "$path" ]] || return 1
  case " $command " in
    *" $option $path "*|*" $option=$path "*) return 0 ;;
  esac
  return 1
}

command_mentions_linked_target_bin() {
  local command=$1
  local name=$2
  local target_bin="$PROGRAM_DIR/bin/$name"
  local linked_bin="$HOME/.local/bin/$name"
  [[ -e "$target_bin" ]] || return 1
  command_mentions_path "$command" "$target_bin" && return 0
  command_mentions_option_path "$command" "--dtcoder-bin" "$target_bin" && return 0
  if path_points_to_target "$linked_bin" "$target_bin"; then
    command_mentions_path "$command" "$linked_bin" && return 0
    command_mentions_option_path "$command" "--dtcoder-bin" "$linked_bin" && return 0
  fi
  return 1
}

# A discovery pass snapshots stable target paths, never PID ownership. Signal
# revalidation calls executable_path_matches_target with fresh paths below.
target_program_executable_scope() {
  canonical_path "$PROGRAM_DIR/bin"
  local release_root="" logical_root
  if [[ "$(basename "$PROGRAM_DIR")" == current ]]; then
    logical_root="$(canonical_path "$(dirname "$PROGRAM_DIR")")"
    release_root="$(canonical_path "$logical_root/releases")"
    [[ "$release_root" == "$logical_root/releases" ]] || release_root=""
  fi
  printf '%s\n' "$release_root"
  local name target
  while IFS= read -r name; do
    target="$PROGRAM_DIR/bin/$name"
    [[ -e "$target" ]] || continue
    canonical_path "$target"
  done < <(dtcoder_process_names_in_stop_order)
}

executable_path_matches_scope() {
  local exe=$1 bin_dir=$2 release_root=$3
  shift 3
  [[ "$exe" == "$bin_dir"/* ]] && return 0
  local target
  for target in "$@"; do
    [[ "$exe" == "$target" ]] && return 0
  done
  [[ -n "$release_root" && "$exe" == "$release_root/"* ]] || return 1
  local relative="${exe#"$release_root/"}"
  local release_name="${relative%%/*}"
  [[ -n "$release_name" && "$relative" == "$release_name/bin/"* ]]
}

executable_path_matches_target() {
  local exe=$1
  [[ -n "$exe" ]] || return 1
  exe="$(canonical_path "$exe")"
  local scope=() path
  while IFS= read -r path; do scope+=("$path"); done < <(target_program_executable_scope)
  executable_path_matches_scope "$exe" "${scope[@]}"
}

process_pid_matches_target() {
  local pid=$1
  local exe
  exe="$(process_executable_path "$pid")"
  executable_path_matches_target "$exe" && return 0

  local command
  command="$(process_command_line "$pid")"
  [[ -n "$command" ]] || return 1

  local name
  while IFS= read -r name; do
    command_mentions_linked_target_bin "$command" "$name" && return 0
  done < <(dtcoder_process_names_in_stop_order)
  return 1
}

candidate_tui_related_process_pids() {
  ps -x -o pid=,command= 2>/dev/null | awk '
    /aiwork-tui-stall-watchdog/ ||
    /aiwork-tui[[:space:]]+aiwork/ ||
    /aiwork[[:space:]]+acp[[:space:]]+--agent/ ||
    /aiworkcli[[:space:]]+acp[[:space:]]+--agent/ ||
    /aiworkcn[[:space:]]+acp[[:space:]]+--agent/ ||
    /dtcoder-tui-stall-watchdog/ ||
    /dtcoder-tui[[:space:]]+dtcoder/ ||
    /dtcodercli-internal[[:space:]]+acp[[:space:]]+--agent/ ||
    /dtcodercli[[:space:]]+acp[[:space:]]+--agent/ ||
    /dtcodercn[[:space:]]+acp[[:space:]]+--agent/ ||
    /dtcoder[[:space:]]+acp[[:space:]]+--agent/ ||
    /dtclaw[[:space:]]+acp[[:space:]]+--agent/ {
      print $1
    }
  ' | awk '!seen[$0]++'
}

candidate_pids_for_name() {
  local name=$1
  {
    pgrep -x -u "$(id -u)" "$name" 2>/dev/null || true
    # `comm` has no arguments, so removing only the PID preserves spaces in
    # executable paths even when the platform truncates the pgrep name.
    ps -x -o pid=,comm= 2>/dev/null | awk -v name="$name" '
      {
        pid = $1
        executable = $0
        sub(/^[[:space:]]*[0-9]+[[:space:]]+/, "", executable)
        n = split(executable, parts, "/")
        if (pid ~ /^[0-9]+$/ && parts[n] == name) print pid
      }
    '
    # macOS can truncate comm itself to 16 bytes. Command text supplies only
    # candidates here; the executable identity must confirm the basename.
    ps -ww -x -o pid=,command= 2>/dev/null | awk -v name="$name" '
      $1 ~ /^[0-9]+$/ && $0 ~ "(^|/)" name "([[:space:]]|$)" { print $1 }
    ' | while IFS= read -r pid; do
      local exe
      exe="$(process_executable_path "$pid")"
      [[ -n "$exe" && "$(basename "$exe")" == "$name" ]] && printf '%s\n' "$pid"
    done || true
    ps -x -o pid=,command= 2>/dev/null | awk -v name="$name" '
      {
        pid = $1
        command = $0
        sub(/^[[:space:]]*[0-9]+[[:space:]]+/, "", command)
        first = command
        sub(/[[:space:]].*$/, "", first)
        n = split(first, parts, "/")
        base = parts[n]
        wrapper = (base == "bash" || base == "sh" || base == "zsh" || base == "env" || base == "bun" || base == "node")
        pattern = "(^|/)" name "([[:space:]]|$)"
        if (pid ~ /^[0-9]+$/ && (base == name || (wrapper && command ~ pattern))) {
          print pid
        }
      }
    '
  } | awk '!seen[$0]++'
}

# Enumerate same-user holders by their executable path as well; ownership is
# still proven below against the target logical program directory.
list_same_user_program_bin_pids() {
  [[ -e /proc ]] || return 0
  local scope=() path protected_pids pid exe
  [[ -d "$PROGRAM_DIR/bin" ]] || return 0
  if [[ $# -ge 1 ]]; then
    protected_pids=$1
  else
    protected_pids="$(protected_install_pids)"
  fi
  while IFS= read -r path; do scope+=("$path"); done < <(target_program_executable_scope)
  while IFS= read -r pid; do
    [[ -n "$pid" ]] || continue
    is_protected_install_pid "$pid" "$protected_pids" && continue
    [[ -e "/proc/$pid/exe" ]] || continue
    # The kernel already resolves /proc/<pid>/exe; do not realpath it again.
    exe="$(readlink "/proc/$pid/exe" 2>/dev/null || true)"
    [[ -n "$exe" ]] || continue
    if executable_path_matches_scope "$exe" "${scope[@]}"; then
      printf '%s\n' "$pid"
    fi
  done < <(pgrep -u "$(id -u)" 2>/dev/null || true)
}

list_running_dtcoder_pids() {
  local target_bins=()
  local name
  while IFS= read -r name; do
    local bin_path="$PROGRAM_DIR/bin/$name"
    [[ -e "$bin_path" ]] && target_bins+=("$(canonical_path "$bin_path")")
  done < <(dtcoder_process_names_in_stop_order)
  [[ ${#target_bins[@]} -gt 0 ]] || return 0

  local protected_pids
  protected_pids="$(protected_install_pids)"
  {
    while IFS= read -r name; do
      candidate_pids_for_name "$name" | while IFS= read -r pid; do
        [[ -n "$pid" ]] || continue
        is_protected_install_pid "$pid" "$protected_pids" && continue
        process_pid_matches_target "$pid" && printf '%s\n' "$pid"
      done || true
    done < <(dtcoder_process_names_in_stop_order)

    list_same_user_program_bin_pids "$protected_pids"

    candidate_tui_related_process_pids | while IFS= read -r pid; do
      [[ -n "$pid" ]] || continue
      is_protected_install_pid "$pid" "$protected_pids" && continue
      process_pid_matches_target "$pid" && printf '%s\n' "$pid"
    done || true
  } | awk '!seen[$0]++'
}

wait_for_running_dtcoder_pids_to_exit() {
  local attempts=${1:-25}
  local delay=${2:-0.2}
  local pids=""
  local attempt
  for ((attempt = 0; attempt < attempts; attempt++)); do
    pids="$(list_running_dtcoder_pids)"
    if [[ -z "$pids" ]]; then
      return 0
    fi
    sleep "$delay"
  done
  printf '%s\n' "$pids"
  return 1
}

signal_dtcoder_pids() {
  local pids=$1
  local signal=$2
  local label=$3
  local pid

  # Validate the complete batch before its first destructive action. Individual
  # revalidation below still protects the race between this pass and signal.
  while IFS= read -r pid; do
    [[ -n "$pid" ]] || continue
    is_protected_install_pid "$pid" && continue
    kill -0 "$pid" 2>/dev/null || continue
    if ! process_pid_matches_target "$pid"; then
      warn "skipping PID $pid: target program ownership could not be revalidated"
      continue
    fi
  done <<< "$pids"

  while IFS= read -r pid; do
    [[ -n "$pid" ]] || continue
    is_protected_install_pid "$pid" && continue
    # PID reuse and exec races can change ownership after the discovery scan.
    # A disappeared or no-longer-provable PID is harmless as long as we do not
    # signal it; keep draining the rest of the target-owned batch.
    kill -0 "$pid" 2>/dev/null || continue
    if ! process_pid_matches_target "$pid"; then
      warn "skipping PID $pid: target program ownership could not be revalidated"
      continue
    fi
    info "$label PID $pid (SIG$signal)"
    kill "-$signal" "$pid" 2>/dev/null || true
  done <<< "$pids"
}

describe_running_dtcoder_pids() {
  local pids=$1
  [[ -n "$pids" ]] || return 0
  ps -p "${pids//$'\n'/,}" -o pid=,ppid=,pgid=,stat=,command= 2>/dev/null || echo "$pids"
  local pid exe
  while IFS= read -r pid; do
    [[ -n "$pid" ]] || continue
    exe="$(process_executable_path "$pid")"
    if [[ -n "$exe" ]]; then
      warn "PID $pid executable: $(canonical_path "$exe")"
    fi
  done <<< "$pids"
  return 0
}

warn_reopen_tui_after_versioned_release_upgrade() {
  [[ "$DRY_RUN" == true ]] && return 0
  [[ "$INSTALL_DTCODER_REMAP_FROM_VERSIONED_RELEASE" == true ]] || return 0
  warn "this upgrade was launched from an old versioned release; if the current TUI still shows the old version, exit it and start aiwork again."
}

# Best-effort program-scoped graceful backend stop before destructive signals,
# mirroring the IDE installer intent (dtcoder-installer-internal install.sh):
# a bounded graceful stop gives daemon-held sessions a chance to flush instead
# of dying to SIGTERM/SIGKILL, which is what breaks dtcoder GUI conversations
# when an overwrite install runs while the GUI-owned daemon is live. Unlike a
# state-wide `agent stop --all`, the stop scope is proven per agent: the daemon
# state registry only supplies (agent_id, pid) candidates, and each candidate
# PID must still pass the same target-program ownership proof the signal path
# below uses, so a state dir shared with a foreign install never widens the
# stop scope (PR 3801 CR note_212812016). Every failure mode (missing bin,
# missing python3, list failure, timeout, non-zero exit) keeps the signal
# fallback path; this never aborts the install. Idempotence is per verified
# identity `(agent_id, pid)`: every stop phase re-enumerates the registry, and
# only an identity that already received a successful graceful stop is
# skipped, so a daemon that (re)appears before the overwrite settle pass still
# gets a graceful stop instead of degrading to SIGTERM/SIGKILL (PR 3801 CR
# note_212812065).
GRACEFUL_AGENT_STOP_DONE_KEYS=""

graceful_agent_stop_key_done() {
  case " $GRACEFUL_AGENT_STOP_DONE_KEYS " in
    *" $1 "*) return 0 ;;
    *) return 1 ;;
  esac
}

graceful_agent_stop_mark_key_done() {
  GRACEFUL_AGENT_STOP_DONE_KEYS="${GRACEFUL_AGENT_STOP_DONE_KEYS:+$GRACEFUL_AGENT_STOP_DONE_KEYS }$1"
}

# Classify an `agent stop <id> --expected-pid <pid> --json` payload (stdin) as
# stopped / conflict / failed. `conflict` is the daemon refusing to stop a
# lifecycle owner other than the PID this installer verified, which is the
# identity gate that closes the verify-then-stop race (PR 3801 CR
# note_212812065).
classify_agent_stop_payload() {
  python3 -c '
import json
import sys

raw = sys.stdin.read()
try:
    payload = json.loads(raw)
except Exception:
    print("failed")
    raise SystemExit
if not isinstance(payload, dict):
    print("failed")
    raise SystemExit
if payload.get("ok") is True:
    print("stopped")
    raise SystemExit
code = (payload.get("error") or {}).get("code")
if code == "agent_stop_identity_conflict":
    print("conflict")
    raise SystemExit
print("failed")
'
}

# CLI budget for backend agent commands. The daemon-owned stop state machine
# (crates/daemon/src/admin.rs + admin_lifecycle_control.rs) waits
# STOP_POLL_ATTEMPTS(50) x STOP_POLL_INTERVAL_MS(100ms) = 5s for SIGTERM and
# then KILL_POLL_ATTEMPTS(20) x 100ms = 2s for SIGKILL before finalize, so its
# full contract is ~7s plus reconcile/finalize and CLI startup overhead. The
# installer's outer stop budget must cover that whole contract instead of
# truncating it: a shorter outer timeout kills the CLI mid-statemachine, leaves
# the lifecycle record in Stopping without the canonical Stopped finalize, and
# degrades the slow-stop case right back to the hard-kill signal fallback this
# pass exists to avoid (PR 3801 CR note_212813957). Keep this constant in sync
# with install_aiwork_local.sh.
BACKEND_AGENT_LIST_TIMEOUT_SECONDS=3
BACKEND_AGENT_STOP_TIMEOUT_SECONDS=12

run_backend_agent_command_with_timeout() {
  local timeout_seconds=$1
  local backend_bin=$2
  shift 2
  if command -v timeout >/dev/null 2>&1; then
    AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$PROGRAM_DIR" AGENTIX_PLUGIN_DIR="$PROGRAM_DIR/plugins" \
      timeout "${timeout_seconds}s" "$backend_bin" "$@"
    return $?
  fi
  if command -v python3 >/dev/null 2>&1; then
    python3 - "$DTCLAW_HOME" "$PROGRAM_DIR" "$backend_bin" "$timeout_seconds" "$@" <<'PY'
import os
import subprocess
import sys

state_dir = sys.argv[1]
program_dir = sys.argv[2]
dtcoder_bin = sys.argv[3]
timeout_seconds = float(sys.argv[4])
args = sys.argv[5:]
env = os.environ.copy()
env["AGENTIX_STATE_DIR"] = state_dir
env["AGENTIX_PROGRAM_DIR"] = program_dir
env["AGENTIX_PLUGIN_DIR"] = os.path.join(program_dir, "plugins")
try:
    result = subprocess.run(
        [dtcoder_bin] + args,
        env=env,
        timeout=timeout_seconds,
        check=False,
    )
except subprocess.TimeoutExpired:
    sys.exit(124)
except Exception:
    sys.exit(127)
sys.exit(result.returncode)
PY
    return $?
  fi

  # Fail closed: the first-draft background-poll tier (no `timeout`, no
  # python3) was unreachable dead code — every caller first requires
  # python3, because both the state registry enumeration and the stop
  # envelope classification parse JSON through python3, so the graceful
  # pass has already degraded to the signal fallback by this point
  # (fourth-pass PRReview DEAD-CODE CRITICAL).
  return 1
}

# Enumerate live (agent_id, pid, start_token) triples from the daemon state
# registry via `agent list --json`, printed as tab-separated "id\tpid\ttoken"
# lines (empty token when the platform exposes none). Registry rows are
# candidates only: the caller must still prove every PID belongs to the
# target program before stopping it. The start token is re-committed with the
# stop so a recycled numeric PID cannot pass the daemon identity gate
# (PR 3801 CR note_212814083). Requires python3 to parse the JSON envelope;
# without it the graceful pass degrades to the signal fallback.
state_running_agent_entries() {
  local backend_bin=$1
  command -v python3 >/dev/null 2>&1 || return 1
  local payload
  payload="$(run_backend_agent_command_with_timeout "$BACKEND_AGENT_LIST_TIMEOUT_SECONDS" "$backend_bin" agent list --json 2>/dev/null)" || return 1
  printf '%s\n' "$payload" | python3 -c '
import json
import sys

try:
    payload = json.load(sys.stdin)
except Exception:
    sys.exit(1)
if not isinstance(payload, dict) or payload.get("ok") is not True:
    sys.exit(1)
agents = payload.get("agents")
if not isinstance(agents, list):
    sys.exit(1)
for agent in agents:
    if not isinstance(agent, dict):
        continue
    if agent.get("status") == "stopped":
        continue
    agent_id = agent.get("id")
    pid = agent.get("pid")
    if not isinstance(agent_id, str) or not agent_id:
        continue
    if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
        continue
    start_token = agent.get("start_token")
    if not isinstance(start_token, str) or not start_token:
        start_token = ""
    print(f"{agent_id}\t{pid}\t{start_token}")
'
}

# Canonical readback after a stop call failed or exceeded the outer CLI
# budget: the daemon owns the Stopping -> Stopped state machine, so a CLI that
# was killed by the outer timeout does not prove the stop failed. Re-enumerate
# the registry; if the agent no longer reports running, the daemon completed
# the canonical stop and the installer must treat it as stopped instead of
# falling back to signals (PR 3801 CR note_212813957).
graceful_stop_readback_confirms_stopped() {
  local backend_bin=$1
  local agent_id=$2
  local entries row_id row_pid
  entries="$(state_running_agent_entries "$backend_bin")" || return 1
  while IFS=$'\t' read -r row_id row_pid; do
    [[ -n "$row_id" ]] || continue
    if [[ "$row_id" == "$agent_id" ]]; then
      return 1
    fi
  done <<< "$entries"
  return 0
}

graceful_stop_backend_agents() {
  local product_cmd product_bin
  product_cmd="$(product_command_for_dist "$DIST")"
  product_bin="$PROGRAM_DIR/bin/$product_cmd"
  if [[ ! -x "$product_bin" ]]; then
    # Layouts without dist wrappers still ship the direct product binary.
    product_bin="$PROGRAM_DIR/bin/dtcoder"
    [[ -x "$product_bin" ]] || return 0
  fi
  info "attempting graceful AiWork agent stop (program-scoped, budget ${BACKEND_AGENT_STOP_TIMEOUT_SECONDS}s per agent)"
  # Re-enumerate once after an identity conflict so a takeover daemon can be
  # re-proven and stopped under its new PID instead of retrying a stale
  # identity (PR 3801 CR note_212812065).
  local pass entries conflict_seen agent_id pid key outcome payload
  local stopped_total=0 skipped_total=0
  for ((pass = 1; pass <= 2; pass++)); do
    if ! entries="$(state_running_agent_entries "$product_bin")"; then
      warn "graceful AiWork agent stop unavailable (agent list failed or python3 missing); continuing with signal fallback"
      return 0
    fi
    if [[ -z "$entries" ]]; then
      ok "graceful AiWork agent stop completed (no live agents in state registry)"
      return 0
    fi

    conflict_seen=0
    while IFS=$'\t' read -r agent_id pid start_token; do
      [[ -n "$agent_id" ]] || continue
      key="${agent_id}:${pid}"
      # Per-identity idempotence: only a PID that already received a
      # successful graceful stop is skipped; a re-appeared daemon under a
      # new PID is stopped again below.
      if graceful_agent_stop_key_done "$key"; then
        continue
      fi
      # Program-scope proof, identical to the signal path: installer-owned PIDs
      # never receive a stop, and every daemon PID must still be owned by the
      # target program directory. A shared state dir used by a foreign install
      # only widens the candidate list, never the stop scope.
      if is_protected_install_pid "$pid"; then
        skipped_total=$((skipped_total + 1))
        continue
      fi
      if ! kill -0 "$pid" 2>/dev/null; then
        skipped_total=$((skipped_total + 1))
        continue
      fi
      if ! process_pid_matches_target "$pid"; then
        skipped_total=$((skipped_total + 1))
        warn "skipping graceful stop of agent '$agent_id' (PID $pid): PID is not owned by the target program"
        continue
      fi
      # The expected identity flags make this installer's ownership proof and
      # the daemon's stop decision atomic: if the verified PID was replaced by
      # a foreign takeover of the shared state, the daemon refuses with an
      # identity conflict instead of stopping the new owner; committing the
      # observed start token additionally refuses a takeover that recycled
      # the same numeric PID (PR 3801 CR note_212814083).
      local -a identity_args=(--expected-pid "$pid")
      if [[ -n "$start_token" ]]; then
        identity_args+=(--expected-start-token "$start_token")
      fi
      payload="$(run_backend_agent_command_with_timeout "$BACKEND_AGENT_STOP_TIMEOUT_SECONDS" "$product_bin" agent stop "$agent_id" "${identity_args[@]}" --json 2>/dev/null)" || true
      outcome="$(printf '%s' "$payload" | classify_agent_stop_payload)"
      case "$outcome" in
        stopped)
          graceful_agent_stop_mark_key_done "$key"
          stopped_total=$((stopped_total + 1))
          ;;
        conflict)
          conflict_seen=1
          warn "graceful stop of agent '$agent_id' deferred: the daemon owner changed after PID $pid was verified; re-enumerating"
          ;;
        *)
          # The daemon owns the stop budget and the Stopping -> Stopped
          # state machine; before treating this as a failure, read the
          # registry back through the same CLI so a canonical stop that
          # merely outlived the outer CLI budget is not re-killed by the
          # signal fallback (PR 3801 CR note_212813957).
          if graceful_stop_readback_confirms_stopped "$product_bin" "$agent_id"; then
            graceful_agent_stop_mark_key_done "$key"
            stopped_total=$((stopped_total + 1))
            warn "graceful stop of agent '$agent_id' (PID $pid) exceeded the CLI wait budget; readback confirmed the daemon completed the canonical stop"
            continue
          fi
          # No ungated plain-stop retry, including the legacy-binary case
          # (a pre-fix release rejects the unknown --expected-pid flag with
          # clap's exit code 2 and no stdout envelope): a plain
          # `agent stop <id>` lets an identity-ungated CLI re-select the
          # owner from the shared state at stop time, so a takeover between
          # this installer's PID verification and the stop call would stop
          # the new (possibly foreign-program) owner — the exact race the
          # expected-PID gate exists to close (PR 3801 CR note_212814021).
          # Legacy binaries degrade to the program-scoped signal fallback
          # instead: it re-validates target-program ownership per PID and
          # never lets the CLI choose the owner.
          warn "graceful stop of agent '$agent_id' (PID $pid) failed, timed out, or ran on a legacy binary without --expected-pid; continuing with signal fallback"
          ;;
      esac
    done <<< "$entries"
    [[ "$conflict_seen" == 1 ]] || break
  done
  ok "graceful AiWork agent stop completed (stopped=$stopped_total skipped=$skipped_total)"
  return 0
}

stop_running_processes() {
  local pids=$1
  local max_cycles=${INSTALL_DTCODER_STOP_DRAIN_CYCLES:-8}
  local quiet_scans_required=${INSTALL_DTCODER_STOP_DRAIN_QUIET_SCANS:-5}
  local quiet_delay=${INSTALL_DTCODER_STOP_DRAIN_QUIET_DELAY:-0.2}
  local cycle quiet_scans=0

  # Daemon-held sessions get a bounded graceful flush before destructive
  # signals; failure never blocks the SIGTERM/SIGKILL drain below.
  graceful_stop_backend_agents

  for ((cycle = 1; cycle <= max_cycles; cycle++)); do
    pids="$(list_running_dtcoder_pids)"
    if [[ -z "$pids" ]]; then
      quiet_scans=$((quiet_scans + 1))
      if [[ "$quiet_scans" -ge "$quiet_scans_required" ]]; then
        return 0
      fi
      sleep "$quiet_delay"
      continue
    fi

    quiet_scans=0
    signal_dtcoder_pids "$pids" TERM stopping

    pids="$(wait_for_running_dtcoder_pids_to_exit 10 0.2 || true)"
    if [[ -n "$pids" ]]; then
      signal_dtcoder_pids "$pids" KILL "force killing"
    fi

    pids="$(wait_for_running_dtcoder_pids_to_exit 10 0.2 || true)"
    if [[ -z "$pids" ]]; then
      quiet_scans=1
      sleep "$quiet_delay"
    fi
  done

  pids="$(list_running_dtcoder_pids)"
  if [[ -n "$pids" ]]; then
    warn "AiWork process diagnostics after bounded stop drain:"
    describe_running_dtcoder_pids "$pids"
    pids="$(wait_for_running_dtcoder_pids_to_exit 5 0.2 || true)"
    [[ -z "$pids" ]] && return 0
    fail "AiWork processes still running after bounded stop drain: $pids" 7
  fi
}

read_stop_running_answer() {
  local prompt=$1
  local answer
  local tty_state=""
  local tty_mode_changed=false

  [[ -r /dev/tty ]] || return 1
  tty_state="$(stty -g </dev/tty 2>/dev/null || true)"
  if [[ -n "$tty_state" ]]; then
    stty icanon echo isig icrnl -igncr -inlcr min 1 time 0 </dev/tty 2>/dev/null \
      && tty_mode_changed=true || true
  fi
  if ! { printf "%s" "$prompt" >/dev/tty && IFS= read -r answer </dev/tty; } 2>/dev/null; then
    [[ "$tty_mode_changed" == true ]] && stty "$tty_state" </dev/tty 2>/dev/null || true
    return 1
  fi
  [[ "$tty_mode_changed" == true ]] && stty "$tty_state" </dev/tty 2>/dev/null || true
  while [[ "$answer" == *$'\r' ]]; do
    answer="${answer%$'\r'}"
  done
  printf '%s\n' "$answer"
}

confirm_stop_running_processes() {
  local answer
  while true; do
    if ! answer="$(read_stop_running_answer $'Please choose how to handle running AiWork process(es):\n  1) Stop processes and continue install (recommended)\n  2) Cancel install\nSelect [1/2]: ')"; then
      return 2
    fi

    case "$answer" in
      1|y|Y|yes|YES|Yes) return 0 ;;
      ''|2|n|N|no|NO|No) return 1 ;;
      *) warn "please enter 1 or 2" ;;
    esac
  done
}

handle_running_processes() {
  [[ "$DRY_RUN" == true ]] && return 0

  local pids
  pids="$(list_running_dtcoder_pids)"
  [[ -n "$pids" ]] || return 0

  warn "running AiWork process(es) detected:"
  ps -p "${pids//$'\n'/,}" -o pid=,command= 2>/dev/null || echo "$pids"

  if [[ "$KILL_RUNNING_DTCODER" == true || "$YES" == true ]]; then
    info "auto-stopping running target install-dir processes (--yes / --kill-running-aiwork)"
    stop_running_processes "$pids"
    RUNNING_PROCESSES_STOPPED=true
  elif confirm_stop_running_processes; then
    stop_running_processes "$pids"
    RUNNING_PROCESSES_STOPPED=true
  else
    local confirm_status=$?
    if [[ "$confirm_status" -eq 2 ]]; then
      fail "running AiWork processes detected but no terminal is available for confirmation; rerun with --yes, rerun with --kill-running-aiwork, or stop processes manually first" 7
    fi
    fail "installation aborted: AiWork processes still running; stop them manually or rerun with --yes/--kill-running-aiwork" 7
  fi
}

settle_running_processes_before_overwrite() {
  [[ "$DRY_RUN" == true ]] && return 0

  local pids
  pids="$(list_running_dtcoder_pids)"
  [[ -n "$pids" ]] || return 0

  warn "running AiWork process(es) detected immediately before package overwrite:"
  describe_running_dtcoder_pids "$pids"

  if [[ "$KILL_RUNNING_DTCODER" == true || "$YES" == true || "$RUNNING_PROCESSES_STOPPED" == true ]]; then
    warn "re-stopping target processes before package overwrite"
    stop_running_processes "$pids"
    RUNNING_PROCESSES_STOPPED=true
    return 0
  fi

  if confirm_stop_running_processes; then
    stop_running_processes "$pids"
    RUNNING_PROCESSES_STOPPED=true
    return 0
  fi

  local confirm_status=$?
  if [[ "$confirm_status" -eq 2 ]]; then
    fail "running AiWork processes appeared before package switch but no terminal is available for confirmation; rerun with --yes, rerun with --kill-running-aiwork, or stop processes manually first" 7
  fi
  fail "installation aborted: AiWork processes appeared before package switch; stop them manually or rerun with --yes/--kill-running-aiwork" 7
}

legacy_current_directory_looks_like_release_payload() {
  local current_dir=$1
  [[ -d "$current_dir/bin" ]] || return 1
  [[ -f "$current_dir/VERSION" || -f "$current_dir/README-RELEASE.txt" || -x "$current_dir/run.sh" ]] || return 1
  return 0
}

legacy_current_release_label() {
  local current_dir=$1
  local version="unknown"
  if [[ -f "$current_dir/VERSION" ]]; then
    version="$(awk 'NF { print $1; exit }' "$current_dir/VERSION" 2>/dev/null || true)"
    [[ -n "$version" ]] || version="unknown"
  fi
  version="$(printf '%s' "$version" | tr -c 'A-Za-z0-9._-' '-')"
  printf 'legacy-current-%s-%s-%s\n' "$version" "$(date -u +%Y%m%dT%H%M%SZ)" "$$"
}

normalize_legacy_current_layout() {
  [[ "$DRY_RUN" == true ]] && return 0

  local distribution_program_dir="$PROGRAM_ROOT/$DIST"
  local current_path="$distribution_program_dir/current"
  local releases_dir="$distribution_program_dir/releases"
  [[ -e "$current_path" || -L "$current_path" ]] || return 0
  [[ ! -L "$current_path" ]] || return 0

  if [[ ! -d "$current_path" ]]; then
    fail "cannot normalize legacy current layout because $current_path exists and is not a symlink or directory" 5
  fi
  if ! legacy_current_directory_looks_like_release_payload "$current_path"; then
    fail "cannot normalize legacy current layout because $current_path is a directory but does not look like an AiWork release payload" 5
  fi

  mkdir -p "$releases_dir" || fail "failed to create release directory for legacy current migration: $releases_dir" 5

  local label target suffix=0
  label="$(legacy_current_release_label "$current_path")"
  target="$releases_dir/$label"
  while [[ -e "$target" || -L "$target" ]]; do
    suffix=$((suffix + 1))
    target="$releases_dir/$label-$suffix"
  done

  mv "$current_path" "$target" \
    || fail "failed to move legacy current directory into releases: $current_path -> $target" 5
  if ln -s "$target" "$current_path"; then
    ok "normalized legacy current directory: $current_path -> $target"
    return 0
  fi

  rm -f "$current_path" 2>/dev/null || true
  if mv "$target" "$current_path" 2>/dev/null; then
    fail "failed to create current symlink after legacy migration; restored directory current: $current_path" 5
  fi
  fail "failed to create current symlink after legacy migration and could not restore directory current: $current_path" 5
}

clear_update_ready_marker() {
  [[ "$DRY_RUN" == true ]] && return 0
  rm -f "$DTCLAW_HOME/.update_ready.json" "$DTCLAW_HOME/.update_prefetch_error.json" 2>/dev/null || true
  [[ -n "${CACHED_UPDATE_DIR:-}" ]] || return 0

  local cache_real install_root
  cache_real="$(cd "$CACHED_UPDATE_DIR" 2>/dev/null && pwd -P)" || cache_real="$CACHED_UPDATE_DIR"
  case "$cache_real" in
    */.update-cache/*) install_root="${cache_real%%/.update-cache/*}" ;;
    *) return 0 ;;
  esac
  [[ -n "$install_root" && "$install_root" != "$DTCLAW_HOME" ]] || return 0
  rm -f "$install_root/.update_ready.json" "$install_root/.update_prefetch_error.json" 2>/dev/null || true
}

INSTALL_ACTIVATION_SNAPSHOT_DIR=""
INSTALL_ACTIVATION_SNAPSHOT_MANIFEST=""
INSTALL_ACTIVATION_SNAPSHOT_READY=false
INSTALL_ACTIVATION_COMMITTED=false

snapshot_install_path() {
  local path=$1
  local key=$2
  local snapshot_kind=${3:-link}
  local payload="$INSTALL_ACTIVATION_SNAPSHOT_DIR/$key.payload"
  mkdir -p "$INSTALL_ACTIVATION_SNAPSHOT_DIR" \
    || fail "failed to create install rollback snapshot dir: $INSTALL_ACTIVATION_SNAPSHOT_DIR" 5
  if [[ -L "$path" ]]; then
    if [[ "$snapshot_kind" == "mutable-file" ]]; then
      local link_target referent_path
      readlink "$path" >"$payload.link" \
        || fail "failed to snapshot install rollback symlink: $path" 5
      link_target="$(cat "$payload.link" 2>/dev/null || true)"
      if [[ "$link_target" == /* ]]; then
        referent_path="$link_target"
      else
        referent_path="$(dirname "$path")/$link_target"
      fi
      if [[ -f "$referent_path" ]]; then
        cp -p "$referent_path" "$payload" \
          || fail "failed to snapshot install rollback symlink referent: $referent_path" 5
        printf '%s\t%s\t%s\t%s\n' "$key" "symlink-file" "$path" "$referent_path" >>"$INSTALL_ACTIVATION_SNAPSHOT_MANIFEST"
        return 0
      fi
    fi
    readlink "$path" >"$payload" \
      || fail "failed to snapshot install rollback symlink: $path" 5
    printf '%s\t%s\t%s\n' "$key" "symlink" "$path" >>"$INSTALL_ACTIVATION_SNAPSHOT_MANIFEST"
  elif [[ -f "$path" ]]; then
    cp -p "$path" "$payload" \
      || fail "failed to snapshot install rollback path: $path" 5
    printf '%s\t%s\t%s\n' "$key" "present" "$path" >>"$INSTALL_ACTIVATION_SNAPSHOT_MANIFEST"
  elif [[ -d "$path" ]]; then
    printf '%s\t%s\t%s\n' "$key" "directory" "$path" >>"$INSTALL_ACTIVATION_SNAPSHOT_MANIFEST"
  elif [[ -e "$path" ]]; then
    fail "failed to snapshot install rollback path with unsupported file type: $path" 5
  else
    printf '%s\t%s\t%s\n' "$key" "absent" "$path" >>"$INSTALL_ACTIVATION_SNAPSHOT_MANIFEST"
  fi
}

restore_snapshot_payload_to_path() {
  local payload=$1
  local path=$2
  local parent staging
  parent="$(dirname "$path")" || return 1
  [[ -n "$parent" ]] || return 1
  mkdir -p "$parent" || return 1
  [[ -L "$payload" || ( -f "$payload" && -r "$payload" ) ]] || return 1
  staging="$(mktemp -d "$parent/.install-restore.XXXXXX")" || return 1
  if ! cp -Pp "$payload" "$staging/$(basename "$path")"; then
    rm -rf "$staging"
    return 1
  fi
  if ! mv -f "$staging/$(basename "$path")" "$parent/"; then
    rm -rf "$staging"
    return 1
  fi
  rmdir "$staging" || return 1
}

restore_snapshot_symlink() {
  local link_payload=$1
  local path=$2
  local link_target parent
  link_target="$(cat "$link_payload" 2>/dev/null || true)"
  [[ -n "$link_target" ]] || return 1
  parent="$(dirname "$path")" || return 1
  [[ -n "$parent" ]] || return 1
  mkdir -p "$parent" || return 1
  if [[ -L "$path" || ( -e "$path" && ! -d "$path" ) ]]; then
    rm -f "$path" || return 1
  elif [[ -d "$path" ]]; then
    rmdir "$path" || return 1
  fi
  ln -s "$link_target" "$path" || return 1
}

restore_install_config_if_owned() {
  local receipt="${1:-${CONFIG_COMPAT_ROLLBACK_RECEIPT:-}}"
  local restore_path="${2:-$DTCLAW_HOME/config.json}"
  [[ -f "$receipt" ]] || return 2
  local repair_program python3_bin product_bin result restore_help
  for repair_program in "${CONFIG_COMPAT_RESTORE_PROGRAM_DIR:-}" "${CONFIG_COMPAT_REPAIR_PROGRAM_DIR:-}" "$PROGRAM_DIR"; do
    [[ -n "$repair_program" ]] || continue
    product_bin="$repair_program/bin/$(product_command_for_dist "$DIST")"
    [[ -x "$product_bin" ]] || continue
    if restore_help="$("$product_bin" __install restore-config --help 2>/dev/null)" \
      && { [[ "$restore_path" == "$DTCLAW_HOME/config.json" ]] || grep -Fq -- --rollback-receipt <<<"$restore_help"; }; then
      result="$(AGENTIX_STATE_DIR="$DTCLAW_HOME" AGENTIX_PROGRAM_DIR="$repair_program" \
        "$product_bin" __install restore-config --state-dir "$DTCLAW_HOME" \
        --config "$restore_path" --rollback-receipt "$receipt")" || return 1
      [[ "$result" == restored ]] || warn "Config changed after repair; preserving current config."
      return 0
    fi
  done
  python3_bin="$(preferred_python3)"
  if [[ -z "$python3_bin" ]]; then
    warn "No config rollback helper is available; refusing to preserve a partially repaired config."
    return 1
  fi
  "$python3_bin" - "$DTCLAW_HOME" "$receipt" "$restore_path" <<'PYRESTORE'
import fcntl
import json
import os
from pathlib import Path
import stat
import sys
import tempfile
state, receipt_path, config = map(Path, sys.argv[1:])
lock_path = state / "locks" / "config.lock"
lock_path.parent.mkdir(parents=True, exist_ok=True)
with lock_path.open("a") as lock:
    fcntl.flock(lock, fcntl.LOCK_EX)
    record = json.loads(receipt_path.read_text(encoding="utf-8"))
    if (not config.is_file() or str(config.resolve()) != record["target"]
            or config.read_text(encoding="utf-8") != record["after"]):
        print("warning: Config changed after repair; preserving current config.")
        sys.exit(0)
    target = config.resolve()
    if record["before"] is None:
        target.unlink()
    else:
        fd, name = tempfile.mkstemp(prefix=".config-restore.", dir=target.parent)
        try:
            with os.fdopen(fd, "w", encoding="utf-8") as file:
                file.write(record["before"])
                file.flush()
                os.fchmod(file.fileno(), stat.S_IMODE(target.stat().st_mode))
                os.fsync(file.fileno())
            os.replace(name, target)
        finally:
            if os.path.exists(name):
                os.unlink(name)
PYRESTORE
}

restore_install_markers_if_owned() {
  local receipt_dir="${DTCODER_INSTALL_MARKER_RECEIPT_DIR:-$WORK_DIR/installed-marker-receipts}"
  local key marker source_dir="$receipt_dir" receipt failed=false
  if [[ ! -f "$receipt_dir/handoff-complete" && -f "$receipt_dir/journal-path" ]]; then
    # A child can fail or be killed before exporting receipts. The original
    # journal remains authoritative until the atomic handoff is complete.
    source_dir="$(cat "$receipt_dir/journal-path")" || { failed=true; source_dir=""; }
    [[ -n "$source_dir" && -d "$source_dir" ]] || { failed=true; source_dir=""; }
  fi
  for key in outer state program; do
    if [[ "$key" != outer && -z "$source_dir" ]]; then continue; fi
    receipt="$source_dir/marker-$key.json"
    [[ "$key" != outer ]] || receipt="$receipt_dir/marker-outer.json"
    [[ -e "$receipt" || -L "$receipt" ]] || continue
    if [[ ! -f "$receipt" || -L "$receipt" ]]; then failed=true; continue; fi
    if [[ "$key" == program ]]; then
      if [[ ! -f "$receipt_dir/program-marker-path" ]]; then failed=true; continue; fi
      marker="$(cat "$receipt_dir/program-marker-path")" || { failed=true; continue; }
      [[ -n "$marker" ]] || { failed=true; continue; }
    else marker="$DTCLAW_HOME/.installed_from.json"; fi
    restore_install_config_if_owned "$receipt" "$marker" || failed=true
  done
  [[ "$failed" == false ]]
}

restore_install_snapshot_path() {
  local key=$1
  local state=$2
  local path=$3
  local referent_path=${4:-}
  if [[ "$key" == state-installed-marker && -d "${DTCODER_INSTALL_MARKER_RECEIPT_DIR:-$WORK_DIR/installed-marker-receipts}" ]]; then
    return 0 # Already handled from publication receipts under config.lock.
  fi
  if [[ "$CONNECTOR_SHARED_STATE_PROTECTED" == true ]]; then
    case "$key" in state-*|coder-agent-json|coder-tui-agent-json) return 0 ;; esac
  fi
  local payload="$INSTALL_ACTIVATION_SNAPSHOT_DIR/$key.payload"
  if [[ "$key" == state-config && -n "${CONFIG_COMPAT_ROLLBACK_RECEIPT:-}" ]]; then
    restore_install_config_if_owned
    case $? in
      0) return 0 ;;
      2) ;;
      *) return 1 ;;
    esac
  fi
  case "$state" in
    present)
      restore_snapshot_payload_to_path "$payload" "$path" || return 1
      ;;
    symlink)
      restore_snapshot_symlink "$payload" "$path" || return 1
      ;;
    symlink-file)
      [[ -n "$referent_path" ]] || return 1
      restore_snapshot_payload_to_path "$payload" "$referent_path" || return 1
      restore_snapshot_symlink "$payload.link" "$path" || return 1
      ;;
    directory)
      if [[ -L "$path" || ( -e "$path" && ! -d "$path" ) ]]; then
        rm -f "$path" || return 1
      fi
      [[ -d "$path" ]] || mkdir -p "$path" || return 1
      ;;
    absent)
      rm -f "$path" || return 1
      ;;
    *) return 1 ;;
  esac
}

protect_current_release_for_install_transaction() {
  [[ "$DRY_RUN" == true ]] && return 0
  local current="$PROGRAM_ROOT/$DIST/current" source backup release_root
  [[ -L "$current" ]] || return 0
  source="$(cd "$current" 2>/dev/null && pwd -P)" || return 0
  release_root="$(cd "$PROGRAM_ROOT/$DIST/releases" 2>/dev/null && pwd -P)" || return 0
  case "$source/" in "$release_root"/*) ;; *) return 0 ;; esac
  backup="$WORK_DIR/protected-current-release"
  [[ ! -e "$backup" && ! -L "$backup" ]] || return 1
  # Keep the live release in the archive installer's release set so its normal
  # retention policy still decides successful-install cleanup. The copy is used
  # only if a later parent failure needs to restore a release pruned by child.
  cp -a "$source" "$backup" || return 1
  INSTALL_ACTIVATION_PROTECTED_RELEASE="$source"
  INSTALL_ACTIVATION_PROTECTED_RELEASE_BACKUP="$backup"
}

restore_protected_current_release() {
  local source="${INSTALL_ACTIVATION_PROTECTED_RELEASE:-}" backup="${INSTALL_ACTIVATION_PROTECTED_RELEASE_BACKUP:-}"
  [[ -n "$source" && -n "$backup" && -d "$backup" ]] || return 0
  [[ -e "$source" || -L "$source" ]] && return 0
  mkdir -p "$(dirname "$source")" || return 1
  mv "$backup" "$source"
}

capture_install_activation_snapshot() {
  [[ "$DRY_RUN" == true ]] && return 0
  INSTALL_ACTIVATION_SNAPSHOT_DIR="$WORK_DIR/install-activation-rollback"
  INSTALL_ACTIVATION_SNAPSHOT_MANIFEST="$INSTALL_ACTIVATION_SNAPSHOT_DIR/manifest.tsv"
  rm -rf "$INSTALL_ACTIVATION_SNAPSHOT_DIR"
  mkdir -p "$INSTALL_ACTIVATION_SNAPSHOT_DIR" \
    || fail "failed to create install rollback snapshot dir: $INSTALL_ACTIVATION_SNAPSHOT_DIR" 5
  : >"$INSTALL_ACTIVATION_SNAPSHOT_MANIFEST"

  snapshot_install_path "$PROGRAM_ROOT/$DIST/current" "program-current"
  snapshot_install_path "$DTCLAW_HOME/.installed_from.json" "state-installed-marker" "mutable-file"
  snapshot_install_path "$DTCLAW_HOME/config.json" "state-config" "mutable-file"
  snapshot_install_path "$DTCLAW_HOME/.env" "state-env" "mutable-file"
  snapshot_install_path "$DTCLAW_HOME/agents/coder/agent.json" "coder-agent-json" "mutable-file"
  snapshot_install_path "$DTCLAW_HOME/agents/coder-tui/agent.json" "coder-tui-agent-json" "mutable-file"

  local name
  for name in dtclaw dtcoder aiwork aiworkcn aiworkcli aiwork-tui dtcoder-tui dtcodercli-internal dtcodercn dtcodercli; do
    snapshot_install_path "$HOME/.local/bin/$name" "bin-$name"
  done
  INSTALL_ACTIVATION_SNAPSHOT_READY=true
}

restore_install_activation_snapshot() {
  refresh_connector_rollback_protection "$DTCLAW_HOME"
  [[ "${INSTALL_ACTIVATION_SNAPSHOT_READY:-false}" == true ]] || return 0
  if [[ ! -f "${INSTALL_ACTIVATION_SNAPSHOT_MANIFEST:-}" || ! -r "$INSTALL_ACTIVATION_SNAPSHOT_MANIFEST" ]]; then
    warn "install rollback manifest unavailable: $INSTALL_ACTIVATION_SNAPSHOT_MANIFEST"
    return 1
  fi
  local restore_status=0
  restore_install_markers_if_owned || restore_status=1
  warn "installation did not complete; restoring saved current, bin links, marker, config, .env and coder agent.json"
  local key state path referent_path
  while IFS=$'\t' read -r key state path referent_path; do
    [[ -n "$key" && -n "$path" ]] || continue
    if ! restore_install_snapshot_path "$key" "$state" "$path" "$referent_path"; then
      warn "failed to restore install rollback path: $path"
      restore_status=1
    fi
  done <"$INSTALL_ACTIVATION_SNAPSHOT_MANIFEST"
  return "$restore_status"
}



main() {
  ensure_valid_installer_cwd
  [[ "$DRY_RUN" == true ]] || ensure_state_root_owner_write_for_upgrade "$DTCLAW_HOME"
  WORK_DIR="$(create_installer_work_dir)"
  CONFIG_COMPAT_ROLLBACK_RECEIPT="$WORK_DIR/config-rollback.json"
  maybe_redirect_root_installer

  acquire_install_lock
  handle_running_processes
  PRE_EXISTING_CONFIG=false
  [[ -f "$DTCLAW_HOME/config.json" ]] && PRE_EXISTING_CONFIG=true
  refresh_connector_rollback_protection "$DTCLAW_HOME"
  backup_coder_app_pack_before_release_overlay
  normalize_legacy_current_layout
  capture_install_activation_snapshot
  protect_current_release_for_install_transaction \
    || fail "failed to protect the current release before installation" 5
  prepare_config_compat_rules
  prepare_pre_activation_distribution_defaults
  run_dtclaw_installer
  ensure_aiwork_compat_symlinks
  write_dtcoder_install_marker_distribution
  apply_config_compat_rules
  run_opencode_installer
  bootstrap_coder_agent
  bootstrap_tui_default_agent
  verify_install
  clear_update_ready_marker
  try_create_symlinks
  configure_path
  final_reconcile_current_bundled_skills_to_state
  warn_reopen_tui_after_versioned_release_upgrade
  INSTALL_ACTIVATION_COMMITTED=true

  # Publication is forward-only: no remaining failure may restore old binaries
  # or config. The child was deferred until coder bootstrap and checks finished.
  if [[ "$DRY_RUN" != true ]]; then
    if ! bash "$WORK_DIR/install-aiwork-archive.sh" --dist "$DIST" --finish-install "$PROGRAM_DIR" "$DTCLAW_HOME" 9>&-; then
      warn "Post-install session migration/startup did not complete; see output above. Installation continues."
    fi
  fi

  print_completion_banner
}

if [[ "${INSTALL_DTCODER_SOURCE_ONLY:-false}" == true ]]; then
  if [[ "${BASH_SOURCE[0]-}" == "$0" ]]; then
    fail "INSTALL_DTCODER_SOURCE_ONLY is only supported when sourcing the script in tests" 2
  fi
  return 0 2>/dev/null || exit 0
else
  main "$@"
fi
