#!/bin/bash -p

if [[ "${BASH_SOURCE[0]}" != "$0" || "$-" == *p* ]]; then
  set -euo pipefail
  set +x
  umask 077
else
  exec /bin/bash -p "$0" "$@"
fi

VERSION="v113"
REPO_BASE_URL_DEFAULT="https://nexus.infpro.me/nexus"
REPO_MANIFEST_URL_DEFAULT="https://nexus.infpro.me/release-manifest.json"
REPO_RELEASE_METADATA_URL_DEFAULT="https://nexus.infpro.me/release-manifest.json"
REPO_ZIP_URL_DEFAULT=""
REPO_FALLBACK_BASE_URL_DEFAULT=""
REPO_FALLBACK_ZIP_URL_DEFAULT=""
REPO_MANIFEST_CONCURRENCY_DEFAULT="8"
REALM_RELEASE_TAG_DEFAULT="v2.9.3"
DEFAULT_MODE="1"
DEFAULT_PORT="18700"
DEFAULT_HOST="127.0.0.1"
AGENT_INSTALL_LOCK_PATH_DEFAULT="/run/lock/nexus-agent-install.lock"

info(){ printf "[提示] %s\n" "$*"; }
ok(){ printf "[OK] %s\n" "$*"; }
warn(){ printf "[警告] %s\n" "$*" >&2; }
err(){ printf "[错误] %s\n" "$*" >&2; }

require_secure_asset_url(){
  local url="${1:-}"
  local label="${2:-远程资产}"
  case "${url}" in
    https://*|file://*) return 0 ;;
    *)
      err "${label} 必须使用 https:// 或 file://：${url:-<empty>}"
      return 1
      ;;
  esac
}

# Whitelist for values interpolated into systemd unit files. Rejects
# anything outside [A-Za-z0-9_./-], which is enough for absolute paths and
# command names but excludes whitespace, shell metacharacters, and the
# newline injection that would let an attacker append extra unit fields.
is_safe_systemd_value(){
  local value="${1:-}"
  [[ -n "${value}" ]] || return 1
  case "${value}" in
    *[!A-Za-z0-9_./-]*) return 1 ;;
  esac
  return 0
}

__REALM_AGENT_CLEANUP_PATHS=()
REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE="0"
REALM_AGENT_DEPLOY_ROLLBACK_BASE=""
REALM_AGENT_DEPLOY_ROLLBACK_DIR=""
AGENT_DEPLOY_JOURNAL_STATE=""
REALM_AGENT_DEPLOY_REPLACE_VENV="0"
REALM_AGENT_ROLLBACK_TLS_CERT=""
REALM_AGENT_ROLLBACK_TLS_KEY=""
REALM_AGENT_ROLLBACK_TLS_CERT_SNAPSHOTTED="0"
REALM_AGENT_ROLLBACK_TLS_KEY_SNAPSHOTTED="0"
AGENT_CONTRACT_PYTHON=""
AGENT_PHASE1_CONTRACT_COMPLETE="0"
REALM_AGENT_PENDING_TARGET_API_KEY=""
REALM_AGENT_PENDING_TARGET_API_KEY_SET="0"
REALM_AGENT_PENDING_TARGET_API_KEY_VERSION=""
REALM_AGENT_TARGET_API_KEY_ADOPTED="0"
REALM_AGENT_ADOPTED_API_KEY_VERSION=""
REALM_AGENT_API_KEY_EXPECTED_UID="0"
REALM_AGENT_API_KEY_EXPECTED_GID="0"
REALM_AGENT_INSTALL_LOCK_HELD="0"
REALM_AGENT_INSTALL_LOCK_PATH_HELD=""
REALM_AGENT_INSTALL_LOCK_BUSY="0"
REALM_AGENT_RECOVERY_READY_SENT="0"
export -n REALM_AGENT_PENDING_TARGET_API_KEY \
  REALM_AGENT_PENDING_TARGET_API_KEY_SET \
  REALM_AGENT_PENDING_TARGET_API_KEY_VERSION 2>/dev/null || true
AGENT_INSTALL_HOST=""
AGENT_INSTALL_PORT=""
AGENT_INSTALL_TRANSPORT=""
AGENT_INSTALL_SERVICE=""
AGENT_INSTALL_ADDRESS_FAMILY=""
AGENT_INSTALL_SSL_CERT=""
AGENT_INSTALL_SSL_KEY=""
AGENT_INSTALL_TLS_SERVER_NAME=""
AGENT_INSTALL_TLS_AUTO_GENERATE="0"
AGENT_INSTALL_TLS_VERIFY_PEER="0"
AGENT_INSTALL_TLS_CA_CERT=""
AGENT_INSTALL_TLS_CERT_SHA256=""
AGENT_INSTALL_ALLOW_INSECURE_NON_LOOPBACK="0"
AGENT_TLS_PREPARED_CERT=""
AGENT_TLS_PREPARED_KEY=""
AGENT_MPTCP_SIDECAR_SHOULD_RUN="0"
AGENT_SYSTEMD_PROTECT_SYSTEM_MODE="strict"
AGENT_SERVICE_USER="realm-agent"
AGENT_SERVICE_GROUP="realm-agent"
AGENT_SERVICE_UID=""
AGENT_SERVICE_GID=""
AGENT_SERVICE_USER_CREATED_THIS_RUN="0"
AGENT_SERVICE_GROUP_CREATED_THIS_RUN="0"
AGENT_SERVICE_USER_CREATE_INTENT="0"
AGENT_SERVICE_GROUP_CREATE_INTENT="0"
AGENT_SERVICE_USER_MANAGED="0"
AGENT_SERVICE_GROUP_MANAGED="0"
AGENT_RUNTIME_UNITS=(
  realm-agent-install-recovery.service
  realm-agent.target
  realm-agent-privileged.socket
  realm-agent-privileged.service
  realm-tunnel-runtime.socket
  realm-netops.socket
  realm-panel-reporter.socket
  realm-v2-control.socket
  realm-agent-revtunnel.service
  realm-mptcp-sidecar.service
  realm-agent.service
  realm-agent-https.service
  realm-tunnel-runtime.service
  realm-netops.service
  realm-panel-reporter.service
  realm-v2-control.service
)
AGENT_CUTOVER_UNITS=("${AGENT_RUNTIME_UNITS[@]}" realm.service)
AGENT_MANAGED_UNITS=("${AGENT_CUTOVER_UNITS[@]}" nftables.service)
AGENT_ROLLBACK_STOP_UNITS=(
  realm-agent-install-recovery.service
  realm-agent.target
  realm-agent.service
  realm-agent-https.service
  realm-agent-revtunnel.service
  realm-mptcp-sidecar.service
  realm-tunnel-runtime.service
  realm-netops.service
  realm-panel-reporter.service
  realm-v2-control.service
  realm-agent-privileged.service
  realm-tunnel-runtime.socket
  realm-netops.socket
  realm-panel-reporter.socket
  realm-v2-control.socket
  realm-agent-privileged.socket
  realm.service
  nftables.service
)
AGENT_ROLLBACK_REQUIRED_ACTIVE_PAIRS=(
  "realm-agent-privileged.service realm-agent-privileged.socket"
)

agent_skip_recovery_unit_during_self_restore(){
  [[ "${REALM_AGENT_RECOVERY_SERVICE_MODE:-0}" == "1" \
    && "${1:-}" == "realm-agent-install-recovery.service" ]]
}

notify_agent_recovery_ready(){
  [[ "${REALM_AGENT_RECOVERY_SERVICE_MODE:-0}" == "1" ]] || return 0
  [[ "${REALM_AGENT_RECOVERY_READY_SENT:-0}" != "1" ]] || return 0
  command_exists systemd-notify || {
    err "启动恢复缺少 systemd-notify，拒绝释放 Agent runtime"
    return 1
  }
  if ! systemd-notify --ready --status="Realm Agent recovery state restored"; then
    err "无法向 systemd 确认 Agent 恢复状态已可启动"
    return 1
  fi
  REALM_AGENT_RECOVERY_READY_SENT="1"
}

agent_install_lock_path(){
  local lock_path=""
  lock_path="${REALM_AGENT_INSTALL_LOCK_PATH:-${NEXUS_AGENT_INSTALL_LOCK_PATH:-${AGENT_INSTALL_LOCK_PATH_DEFAULT}}}"
  if [[ -z "${lock_path}" || "${lock_path}" != /* ]]; then
    err "Agent 安装锁必须是绝对路径：${lock_path:-<empty>}"
    return 1
  fi
  printf '%s' "${lock_path}"
}

agent_lock_file_uid(){
  local path="$1"
  stat -Lc '%u' "${path}" 2>/dev/null \
    || stat -f '%u' "${path}" 2>/dev/null
}

agent_lock_file_inode(){
  local path="$1"
  stat -Lc '%i' "${path}" 2>/dev/null \
    || stat -f '%i' "${path}" 2>/dev/null
}

prepare_agent_install_lock_file(){
  local lock_path="$1"
  local lock_parent=""
  local expected_uid="${REALM_AGENT_INSTALL_LOCK_EXPECTED_UID:-0}"
  lock_parent="$(dirname "${lock_path}")"
  if [[ -L "${lock_parent}" || ( -e "${lock_parent}" && ! -d "${lock_parent}" ) ]]; then
    err "Agent 安装锁目录不是可信普通目录：${lock_parent}"
    return 1
  fi
  if [[ ! -d "${lock_parent}" ]] && ! mkdir -p "${lock_parent}"; then
    err "无法创建 Agent 安装锁目录：${lock_parent}"
    return 1
  fi
  if [[ -L "${lock_path}" || ( -e "${lock_path}" && ! -f "${lock_path}" ) ]]; then
    err "Agent 安装锁必须是非符号链接普通文件：${lock_path}"
    return 1
  fi
  if [[ ! -e "${lock_path}" ]]; then
    if ! (umask 077; set -o noclobber; : > "${lock_path}") 2>/dev/null; then
      if [[ -L "${lock_path}" || ! -f "${lock_path}" ]]; then
        err "无法安全创建 Agent 安装锁：${lock_path}"
        return 1
      fi
    fi
  fi
  if [[ "$(agent_lock_file_uid "${lock_path}" || true)" != "${expected_uid}" ]]; then
    err "Agent 安装锁必须属于 uid ${expected_uid}：${lock_path}"
    return 1
  fi
  if ! chmod 0600 "${lock_path}"; then
    err "无法收紧 Agent 安装锁权限：${lock_path}"
    return 1
  fi
}

verify_agent_install_lock_inode(){
  local lock_path="$1"
  local expected_uid="${REALM_AGENT_INSTALL_LOCK_EXPECTED_UID:-0}"
  local descriptor_path="/proc/self/fd/202"
  if [[ ! -e "${descriptor_path}" ]]; then
    descriptor_path="/dev/fd/202"
  fi
  if [[ ! -f "${lock_path}" || -L "${lock_path}" || ! -e "${descriptor_path}" ]]; then
    err "Agent 安装锁在打开时被替换：${lock_path}"
    return 1
  fi
  if [[ "${descriptor_path}" == /proc/* ]] \
    && [[ ! "${lock_path}" -ef "${descriptor_path}" ]]; then
    err "Agent 安装锁路径与已锁 inode 不一致：${lock_path}"
    return 1
  fi
  if [[ "$(agent_lock_file_inode "${lock_path}" || true)" \
    != "$(agent_lock_file_inode "${descriptor_path}" || true)" ]]; then
    err "Agent 安装锁 inode 校验失败：${lock_path}"
    return 1
  fi
  if [[ "$(agent_lock_file_uid "${lock_path}" || true)" != "${expected_uid}" ]] \
    || [[ "$(agent_lock_file_uid "${descriptor_path}" || true)" != "${expected_uid}" ]]; then
    err "Agent 安装锁 inode 所有权不可信：${lock_path}"
    return 1
  fi
}

acquire_agent_install_lock(){
  local lock_path=""
  REALM_AGENT_INSTALL_LOCK_BUSY="0"
  if [[ "${REALM_AGENT_INSTALL_LOCK_HELD:-0}" == "1" ]]; then
    lock_path="$(agent_install_lock_path)" || return 1
    if [[ "${lock_path}" != "${REALM_AGENT_INSTALL_LOCK_PATH_HELD}" ]]; then
      err "同一进程不能切换 Agent 安装锁路径"
      return 1
    fi
    return 0
  fi
  command_exists flock || {
    err "需要 flock 防止并发 Agent 安装或更新"
    return 1
  }
  lock_path="$(agent_install_lock_path)" || return 1
  prepare_agent_install_lock_file "${lock_path}" || return 1
  if ! exec 202<> "${lock_path}"; then
    err "无法打开 Agent 安装锁：${lock_path}"
    return 1
  fi
  if ! verify_agent_install_lock_inode "${lock_path}"; then
    exec 202>&-
    return 1
  fi
  info "等待 Agent 安装/更新事务锁：${lock_path}"
  if [[ "${REALM_AGENT_INSTALL_LOCK_NONBLOCK:-0}" == "1" ]]; then
    if ! flock -n 202; then
      REALM_AGENT_INSTALL_LOCK_BUSY="1"
      exec 202>&-
      return 1
    fi
  elif ! flock 202; then
    exec 202>&-
    err "无法获取 Agent 安装/更新事务锁：${lock_path}"
    return 1
  fi
  if ! verify_agent_install_lock_inode "${lock_path}"; then
    exec 202>&-
    return 1
  fi
  REALM_AGENT_INSTALL_LOCK_HELD="1"
  REALM_AGENT_INSTALL_LOCK_PATH_HELD="${lock_path}"
}

release_agent_install_lock(){
  if [[ "${REALM_AGENT_INSTALL_LOCK_HELD:-0}" != "1" ]]; then
    return 0
  fi
  REALM_AGENT_INSTALL_LOCK_HELD="0"
  REALM_AGENT_INSTALL_LOCK_PATH_HELD=""
  exec 202>&-
}

register_cleanup_path(){
  local path="${1:-}"
  [[ -n "${path}" ]] || return 0
  __REALM_AGENT_CLEANUP_PATHS+=("${path}")
}
cleanup(){
  local path
  if [[ "${REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE:-0}" == "1" ]] \
    && declare -F restore_agent_deploy_rollback >/dev/null 2>&1; then
    restore_agent_deploy_rollback || true
  fi
  for path in "${__REALM_AGENT_CLEANUP_PATHS[@]:-}"; do
    [[ -n "${path}" && -e "${path}" ]] || continue
    rm -rf "${path}" >/dev/null 2>&1 || true
  done
  release_agent_install_lock
}
trap cleanup EXIT INT TERM
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM

need_root(){
  if [[ "$(id -u)" -ne 0 ]]; then
    err "请使用 root 运行（sudo -i / su -）"
    exit 1
  fi
}

probe_python_runtime(){
  local py="$1"
  if [[ -z "${py}" ]]; then
    return 1
  fi
  if [[ "${py}" == */* ]]; then
    [[ -x "${py}" ]] || return 1
  else
    command_exists "${py}" || return 1
  fi
  "${py}" -I -S -c "import venv, ssl, json" >/dev/null 2>&1
}

python_version_at_least(){
  local py="$1"
  local min_major="${2:-3}"
  local min_minor="${3:-9}"
  if [[ -z "${py}" ]]; then
    return 1
  fi
  "${py}" -I -S - <<PY >/dev/null 2>&1
import sys
raise SystemExit(0 if sys.version_info >= (${min_major}, ${min_minor}) else 1)
PY
}

trusted_agent_bootstrap_python(){
  local candidate=""
  for candidate in \
    /usr/bin/python3.13 /usr/bin/python3.12 /usr/bin/python3.11 \
    /usr/bin/python3.10 /usr/bin/python3.9 /usr/bin/python3 \
    /usr/local/bin/python3.13 /usr/local/bin/python3.12 \
    /usr/local/bin/python3.11 /usr/local/bin/python3.10 \
    /usr/local/bin/python3.9 /usr/local/bin/python3; do
    [[ -x "${candidate}" && ! -L "${candidate}" ]] || continue
    if "${candidate}" -I -S -c \
      'import sys; raise SystemExit(0 if sys.version_info >= (3, 9) else 1)' \
      >/dev/null 2>&1; then
      printf '%s' "${candidate}"
      return 0
    fi
  done
  return 1
}

managed_python_root(){
  printf '%s\n' "${REALM_AGENT_MANAGED_PYTHON_ROOT:-/opt/realm-agent/python}"
}

find_managed_python_runtime(){
  local root
  local candidate
  root="$(managed_python_root)"
  for candidate in \
    "${root}/bin/python3.12" "${root}/bin/python3.11" "${root}/bin/python3.10" "${root}/bin/python3.9" \
    "${root}"/*/bin/python3.12 "${root}"/*/bin/python3.11 "${root}"/*/bin/python3.10 "${root}"/*/bin/python3.9; do
    [[ -e "${candidate}" ]] || continue
    if probe_python_runtime "${candidate}" && python_version_at_least "${candidate}" 3 9; then
      printf '%s\n' "${candidate}"
      return 0
    fi
  done
  return 1
}

select_supported_python_runtime(){
  local candidate=""
  local managed_py=""
  local -a candidates=()

  if [[ -n "${REALM_AGENT_PYTHON_BIN:-}" ]]; then
    candidates+=("${REALM_AGENT_PYTHON_BIN}")
  fi
  managed_py="$(find_managed_python_runtime || true)"
  if [[ -n "${managed_py}" ]]; then
    candidates+=("${managed_py}")
  fi
  candidates+=(python3.12 python3.11 python3.10 python3.9 python3)

  for candidate in "${candidates[@]}"; do
    [[ -n "${candidate}" ]] || continue
    if ! probe_python_runtime "${candidate}"; then
      continue
    fi
    if ! python_version_at_least "${candidate}" 3 9; then
      continue
    fi
    if [[ "${candidate}" == */* ]]; then
      printf '%s\n' "${candidate}"
    else
      command -v "${candidate}"
    fi
    return 0
  done
  return 1
}

probe_existing_agent_venv(){
  local py="${1:-}"
  if [[ -z "${py}" ]]; then
    py="$(agent_base_dir)/venv/bin/python"
  fi
  if [[ ! -x "${py}" ]]; then
    return 1
  fi
  if ! python_version_at_least "${py}" 3 9; then
    return 1
  fi
  "${py}" -c "import ssl, json, fastapi, uvicorn, requests, httpx, h2, hypercorn, websockets" >/dev/null 2>&1 \
    && "${py}" -m pip check >/dev/null 2>&1
}

apt_has_candidate(){
  local pkg="${1:-}"
  local candidate=""
  [[ -n "${pkg}" ]] || return 1
  command_exists apt-cache || return 1
  candidate="$(apt-cache policy "${pkg}" 2>/dev/null | sed -n 's/^  Candidate: //p' | head -n 1 || true)"
  [[ -n "${candidate}" && "${candidate}" != "(none)" ]]
}

install_apt_supported_python_runtime(){
  local ver
  local pkg
  local selected_py=""
  for ver in 3.12 3.11 3.10 3.9; do
    pkg="python${ver}"
    if ! apt_has_candidate "${pkg}"; then
      continue
    fi
    info "尝试通过 apt 安装 Python ${ver} 运行时..."
    if ! apt-get install -y --no-install-recommends \
      "${pkg}" "${pkg}-venv" "${pkg}-distutils"; then
      if ! apt-get install -y --no-install-recommends "${pkg}" "${pkg}-venv"; then
        err "安装 ${pkg} 运行时失败"
        continue
      fi
    fi
    selected_py="$(select_supported_python_runtime || true)"
    if [[ -n "${selected_py}" ]]; then
      export REALM_AGENT_PYTHON_BIN="${selected_py}"
      ok "已安装可用 Python：${selected_py}"
      return 0
    fi
  done
  return 1
}

uv_tool_path(){
  local candidate
  if [[ -n "${REALM_AGENT_UV_BIN:-}" && -x "${REALM_AGENT_UV_BIN}" ]]; then
    printf '%s\n' "${REALM_AGENT_UV_BIN}"
    return 0
  fi
  if command_exists uv; then
    command -v uv
    return 0
  fi
  for candidate in \
    "${REALM_AGENT_UV_INSTALL_DIR:-/opt/realm-agent/bin}/uv" \
    "/opt/realm-agent/bin/uv" \
    "/root/.local/bin/uv"; do
    [[ -x "${candidate}" ]] || continue
    printf '%s\n' "${candidate}"
    return 0
  done
  return 1
}

install_uv_tool(){
  local uv_bin=""
  local uv_dir="${REALM_AGENT_UV_INSTALL_DIR:-/opt/realm-agent/bin}"
  local uv_url="${REALM_AGENT_UV_INSTALL_URL:-}"
  local uv_sha256="${REALM_AGENT_UV_INSTALL_SHA256:-}"
  local timeout_seconds="${REALM_AGENT_UV_INSTALL_TIMEOUT:-300}"
  local tmp=""

  uv_bin="$(uv_tool_path || true)"
  if [[ -n "${uv_bin}" ]]; then
    return 0
  fi
  if [[ "${REALM_AGENT_INSTALL_UV:-1}" != "1" ]]; then
    return 1
  fi
  if [[ -z "${uv_url}" || -z "${uv_sha256}" ]]; then
    err "自动安装 uv 已禁用：必须同时设置不可变 REALM_AGENT_UV_INSTALL_URL 与 REALM_AGENT_UV_INSTALL_SHA256"
    return 1
  fi
  command_exists curl || return 1
  mkdir -p "${uv_dir}"
  tmp="$(mktemp -t realm-uv-install.XXXXXX)"
  register_cleanup_path "${tmp}"
  info "系统仓库未提供可用 Python，尝试安装已固定 SHA256 的 uv..."
  if ! run_with_timeout "${timeout_seconds}" "下载 uv 安装器" \
    download_verified_file "${uv_url}" "${tmp}" "${uv_sha256}" "uv 安装器"; then
    err "uv 安装器下载或 SHA256 校验失败"
    return 1
  fi
  if ! sh -n "${tmp}"; then
    err "uv 安装器 shell 语法无效"
    return 1
  fi
  if ! run_with_timeout "${timeout_seconds}" "安装 uv" env UV_INSTALL_DIR="${uv_dir}" sh "${tmp}"; then
    err "uv 安装失败"
    return 1
  fi
  uv_bin="$(uv_tool_path || true)"
  [[ -n "${uv_bin}" ]]
}

install_managed_python_runtime(){
  local uv_bin=""
  local root=""
  local target="${REALM_AGENT_MANAGED_PYTHON_VERSION:-}"
  local timeout_seconds="${REALM_AGENT_MANAGED_PYTHON_INSTALL_TIMEOUT:-600}"
  local selected_py=""

  if [[ "${REALM_AGENT_MANAGED_PYTHON:-0}" != "1" ]]; then
    return 1
  fi
  if [[ ! "${target}" =~ ^3\.(9|10|11|12)\.[0-9]+$ ]]; then
    err "独立 Python 安装必须显式固定完整补丁版本，例如 3.11.9"
    return 1
  fi
  selected_py="$(find_managed_python_runtime || true)"
  if [[ -n "${selected_py}" ]]; then
    export REALM_AGENT_PYTHON_BIN="${selected_py}"
    return 0
  fi
  install_uv_tool || return 1
  uv_bin="$(uv_tool_path || true)"
  [[ -n "${uv_bin}" ]] || return 1

  root="$(managed_python_root)"
  mkdir -p "${root}"
  info "尝试安装独立 Python ${target} 运行时..."
  if ! run_with_timeout "${timeout_seconds}" "安装独立 Python ${target}" \
    "${uv_bin}" python install "${target}" --install-dir "${root}" --no-progress; then
    err "独立 Python ${target} 安装失败"
    return 1
  fi
  selected_py="$(find_managed_python_runtime || true)"
  if [[ -z "${selected_py}" ]]; then
    err "独立 Python 已安装但未找到可用解释器"
    return 1
  fi
  export REALM_AGENT_PYTHON_BIN="${selected_py}"
  ok "已准备独立 Python：${selected_py}"
  return 0
}

apt_update_with_repair(){
  local i
  for i in 1 2; do
    if apt-get -o Acquire::Languages=none update -y; then
      return 0
    fi
    err "apt 索引更新失败（${i}/2）"
    sleep 1
  done
  return 1
}

apt_install(){
  local deps_ok="1"
  local py_ok="0"
  local selected_py=""
  local managed_root=""

  command_exists curl || deps_ok="0"
  command_exists unzip || deps_ok="0"
  command_exists jq || deps_ok="0"
  command_exists openssl || deps_ok="0"
  command_exists rsync || deps_ok="0"

  selected_py="$(select_supported_python_runtime || true)"
  if [[ -n "${selected_py}" ]]; then
    py_ok="1"
    managed_root="$(managed_python_root)"
  fi
  if [[ "${py_ok}" != "1" || "${selected_py}" != "${managed_root%/}/"* ]]; then
    command_exists python3 || deps_ok="0"
    dpkg-query -W -f='${Status}' python3-venv 2>/dev/null | grep -q "install ok installed" || deps_ok="0"
    dpkg-query -W -f='${Status}' python3-pip 2>/dev/null | grep -q "install ok installed" || deps_ok="0"
  fi
  if [[ "${deps_ok}" == "1" && "${py_ok}" == "1" ]]; then
    unset REALM_AGENT_REUSE_VENV || true
    export REALM_AGENT_PYTHON_BIN="${selected_py}"
    ok "依赖已满足，跳过 apt 安装"
    return
  fi

  export DEBIAN_FRONTEND=noninteractive
  export APT_LISTCHANGES_FRONTEND=none
  if ! apt_update_with_repair; then
    err "apt 索引更新失败；安装事务保持未提交"
    exit 1
  fi
  # rsync 用于更稳的覆盖更新（避免部分文件未更新）
  # cifs-utils / nfs-common 提前装好常见远程挂载 helper，避免 mount.cifs / mount.nfs 缺失。
  if ! apt-get install -y --no-install-recommends \
    curl ca-certificates unzip jq openssl python3 python3-venv python3-pip rsync \
    cifs-utils nfs-common; then
    err "依赖安装失败；拒绝吞错或补装未锁定的 latest 运行时"
    exit 1
  fi

  if [[ "${py_ok}" != "1" ]]; then
    info "检测到系统缺少 Python 3.9+ 运行时，尝试安装发行版明确版本包..."
    selected_py="$(select_supported_python_runtime || true)"
    if [[ -z "${selected_py}" ]]; then
      install_apt_supported_python_runtime || {
        err "发行版仓库没有可用的 Python 3.9+ 运行时"
        exit 1
      }
    fi
  fi

  selected_py="$(select_supported_python_runtime || true)"
  if [[ -n "${selected_py}" ]]; then
    unset REALM_AGENT_REUSE_VENV || true
    export REALM_AGENT_PYTHON_BIN="${selected_py}"
    return
  fi
  err "系统缺少 Python 3.9+ 运行时；拒绝以旧 venv 掩盖依赖安装失败"
  exit 1
}

command_exists(){
  command -v "$1" >/dev/null 2>&1
}

detect_timeout_cmd(){
  if command_exists timeout; then
    echo "timeout"
    return 0
  fi
  if command_exists gtimeout; then
    echo "gtimeout"
    return 0
  fi
  return 1
}

run_with_timeout(){
  local timeout_seconds="$1"
  local label="$2"
  shift 2

  if [[ ! "${timeout_seconds}" =~ ^[0-9]+$ ]] || (( timeout_seconds <= 0 )); then
    "$@"
    return $?
  fi

  local timeout_bin=""
  timeout_bin="$(detect_timeout_cmd || true)"
  if [[ -z "${timeout_bin}" ]]; then
    "$@" &
    local cmd_pid=$!
    local waited=0
    while kill -0 "${cmd_pid}" >/dev/null 2>&1; do
      if (( waited >= timeout_seconds )); then
        err "${label} 超时（${timeout_seconds}s）"
        kill -TERM "${cmd_pid}" >/dev/null 2>&1 || true
        sleep 2
        kill -KILL "${cmd_pid}" >/dev/null 2>&1 || true
        wait "${cmd_pid}" >/dev/null 2>&1 || true
        return 124
      fi
      sleep 1
      waited=$((waited + 1))
    done
    wait "${cmd_pid}"
    return $?
  fi

  local timeout_with_kill_after="0"
  if "${timeout_bin}" --help 2>&1 | grep -q -- '--kill-after'; then
    timeout_with_kill_after="1"
  fi

  local rc=0
  if [[ "${timeout_with_kill_after}" == "1" ]]; then
    if "${timeout_bin}" --signal=TERM --kill-after=15 "${timeout_seconds}" "$@"; then
      return 0
    else
      rc=$?
    fi
  else
    if "${timeout_bin}" "${timeout_seconds}" "$@"; then
      return 0
    else
      rc=$?
    fi
  fi

  if (( rc == 124 || rc == 137 )); then
    err "${label} 超时（${timeout_seconds}s）"
  fi
  return "${rc}"
}

detect_pkg_manager(){
  if command_exists apt-get; then
    echo "apt"
    return
  fi
  if command_exists dnf; then
    echo "dnf"
    return
  fi
  if command_exists yum; then
    echo "yum"
    return
  fi
  if command_exists zypper; then
    echo "zypper"
    return
  fi
  if command_exists pacman; then
    echo "pacman"
    return
  fi
  if command_exists apk; then
    echo "apk"
    return
  fi
  echo ""
}

detect_nft_cmd(){
  local override="${REALM_NFT_BIN:-}"
  if [[ -n "${override}" ]]; then
    if [[ "${override}" == */* ]]; then
      if [[ -x "${override}" ]]; then
        echo "${override}"
        return 0
      fi
    elif command_exists "${override}"; then
      command -v "${override}"
      return 0
    fi
  fi

  if command_exists nft; then
    command -v nft
    return 0
  fi
  return 1
}

install_nftables_with_pkg_manager(){
  local pm="$1"
  case "${pm}" in
    apt)
      apt_update_with_repair || return 1
      if ! apt-get install -y --no-install-recommends nftables iproute2 >/dev/null 2>&1; then
        return 1
      fi
      ;;
    dnf)
      if ! dnf -y install nftables iproute >/dev/null 2>&1; then
        return 1
      fi
      ;;
    yum)
      if ! yum -y install nftables iproute >/dev/null 2>&1; then
        return 1
      fi
      ;;
    zypper)
      if ! zypper --non-interactive install --no-recommends nftables iproute2 >/dev/null 2>&1; then
        return 1
      fi
      ;;
    pacman)
      if ! pacman --noconfirm -Sy nftables iproute2 >/dev/null 2>&1; then
        return 1
      fi
      ;;
    apk)
      if ! apk add --no-cache nftables >/dev/null 2>&1; then
        return 1
      fi
      ;;
    *)
      return 1
      ;;
  esac
}

ensure_ipv4_forwarding(){
  if [[ "${REALM_AGENT_APPLY_HOST_NETWORK_CHANGES:-0}" != "1" ]]; then
    err "启用 IPv4 forwarding 需要显式设置 REALM_AGENT_APPLY_HOST_NETWORK_CHANGES=1"
    return 1
  fi
  local f=""
  f="$(agent_sysctl_dir)/99-realm-ipforward.conf"
  install -d -m 0755 "$(dirname "${f}")"
  sysctl -w net.ipv4.ip_forward=1 >/dev/null
  if [[ -f "${f}" ]]; then
    if grep -Eq '^[[:space:]]*net\.ipv4\.ip_forward[[:space:]]*=' "${f}"; then
      sed -i 's/^[[:space:]]*net\.ipv4\.ip_forward[[:space:]]*=.*/net.ipv4.ip_forward=1/' "${f}"
    else
      echo "net.ipv4.ip_forward=1" >> "${f}"
    fi
  else
    echo "net.ipv4.ip_forward=1" > "${f}"
  fi
  sysctl -p "${f}" >/dev/null
}

install_nftables_stack(){
  local nft_bin pm
  nft_bin="$(detect_nft_cmd || true)"
  if [[ -z "${nft_bin}" ]]; then
    pm="$(detect_pkg_manager)"
    if [[ -n "${pm}" ]]; then
      info "未检测到 nftables，尝试使用 ${pm} 安装系统防火墙组件..."
      install_nftables_with_pkg_manager "${pm}" || return 1
      nft_bin="$(detect_nft_cmd || true)"
    fi
  fi

  if [[ -z "${nft_bin}" ]]; then
    err "未检测到可用 nft 命令"
    return 1
  fi

  export REALM_NFT_BIN="${nft_bin}"
  ok "nftables 命令：${REALM_NFT_BIN}"
  ensure_ipv4_forwarding || return 1
  if command_exists systemctl; then
    systemctl enable nftables >/dev/null
  fi
}

download_file(){
  local url="$1"
  local out="$2"
  local tmp
  local connect_timeout max_time retry retry_delay speed_time speed_limit
  local -a curl_args=()
  local -a protocol_args=(--proto '=http,https' --proto-redir '=https')
  require_secure_asset_url "${url}" "下载资产" || return 1
  tmp="$(mktemp "${out}.tmp.XXXXXX")" || return 1
  if declare -F register_cleanup_path >/dev/null 2>&1; then
    register_cleanup_path "${tmp}"
  fi
  connect_timeout="$(bounded_uint_or_default "${REALM_AGENT_UPDATE_CURL_CONNECT_TIMEOUT:-20}" 20 1 300)"
  max_time="$(bounded_uint_or_default "${REALM_AGENT_UPDATE_CURL_MAX_TIME:-900}" 900 1 3600)"
  retry="$(bounded_uint_or_default "${REALM_AGENT_UPDATE_CURL_RETRY:-2}" 2 0 8)"
  retry_delay="$(bounded_uint_or_default "${REALM_AGENT_UPDATE_CURL_RETRY_DELAY:-2}" 2 0 60)"
  speed_time="$(bounded_uint_or_default "${REALM_AGENT_UPDATE_CURL_SPEED_TIME:-30}" 30 1 300)"
  speed_limit="$(bounded_uint_or_default "${REALM_AGENT_UPDATE_CURL_SPEED_LIMIT:-16384}" 16384 1 104857600)"

  if [[ "${url}" == file://* ]]; then
    local src="${url#file://}"
    # file:// 只允许复制普通文件本体；符号链接与特殊文件一律拒绝，
    # 避免把任意本地路径当作“下载资产”吞入安装流程。
    if [[ ! -f "${src}" || -L "${src}" ]]; then
      rm -f "${tmp}" || true
      return 1
    fi
    if cp -f "${src}" "${tmp}"; then
      mv -f "${tmp}" "${out}"
      return 0
    fi
    rm -f "${tmp}" || true
    return 1
  fi

  if [[ "${url}" == https://* ]]; then
    protocol_args=(--proto '=https' --proto-redir '=https')
  fi

  curl_args=(
    -fL
    --max-redirs 8 \
    "${protocol_args[@]}" \
    --silent \
    --show-error \
    --retry "${retry}" \
    --retry-delay "${retry_delay}" \
    --connect-timeout "${connect_timeout}" \
    --max-time "${max_time}" \
    --speed-time "${speed_time}" \
    --speed-limit "${speed_limit}" \
    -H "Cache-Control: no-cache" \
    -H "Pragma: no-cache"
  )
  if curl --help all 2>/dev/null | grep -q -- "--retry-connrefused"; then
    curl_args=(--retry-connrefused "${curl_args[@]}")
  fi
  if curl --help all 2>/dev/null | grep -q -- "--retry-all-errors"; then
    curl_args=(--retry-all-errors "${curl_args[@]}")
  fi
  if curl "${curl_args[@]}" "${url}" -o "${tmp}"; then
    mv -f "$tmp" "$out"
    return 0
  fi
  rm -f "$tmp" || true
  return 1
}

normalize_sha256(){
  local raw="${1:-}"
  raw="${raw%$'\r'}"
  raw="${raw%$'\n'}"
  raw="${raw#"${raw%%[![:space:]]*}"}"
  raw="${raw%"${raw##*[![:space:]]}"}"
  raw="$(printf '%s' "${raw}" | tr 'A-F' 'a-f')"
  [[ "${raw}" =~ ^[0-9a-f]{64}$ ]] || return 1
  printf '%s\n' "${raw}"
}

sha256_file(){
  local path="$1"
  [[ -f "${path}" ]] || return 1
  if command_exists sha256sum; then
    sha256sum "${path}" | awk '{print tolower($1)}'
  elif command_exists shasum; then
    shasum -a 256 "${path}" | awk '{print tolower($1)}'
  else
    err "缺少 sha256sum/shasum，无法校验：${path}"
    return 1
  fi
}

verify_file_sha256(){
  local path="$1"
  local expected
  local actual
  expected="$(normalize_sha256 "${2:-}" || true)"
  [[ -n "${expected}" ]] || {
    err "缺少有效 SHA256，拒绝使用文件：${path}"
    return 1
  }
  actual="$(sha256_file "${path}" || true)"
  if [[ -z "${actual}" || "${actual}" != "${expected}" ]]; then
    err "SHA256 不匹配：${path}（期望 ${expected}，实际 ${actual:-unknown}）"
    return 1
  fi
}

release_public_key_bits(){
  local public_key="$1"
  local key_text=""
  local bits=""
  command -v openssl >/dev/null 2>&1 || return 1
  key_text="$(openssl pkey -pubin -in "${public_key}" -text_pub -noout 2>/dev/null)" \
    || return 1
  printf '%s\n' "${key_text}" | grep -q '^[[:space:]]*Modulus:' || return 1
  bits="$(
    printf '%s\n' "${key_text}" \
      | sed -n \
        -e 's/^[[:space:]]*Public-Key: (\([0-9][0-9]*\) bit)[[:space:]]*$/\1/p' \
        -e 's/^[[:space:]]*RSA[[:space:]][[:space:]]*Public-Key: (\([0-9][0-9]*\) bit)[[:space:]]*$/\1/p' \
      | head -n 1
  )"
  [[ "${bits}" =~ ^[0-9]+$ ]] || return 1
  (( bits >= 3072 )) || return 1
  printf '%s\n' "${bits}"
}

verify_signed_release_manifest(){
  local manifest_file="$1"
  local signature_file="$2"
  local required_capability="$3"
  local records_file="${4:-}"
  local public_key="${REALM_RELEASE_PUBLIC_KEY_FILE:-}"
  local public_key_bits=""
  local signature_size=""

  if [[ -z "${public_key}" || "${public_key}" != /* \
        || ! -f "${public_key}" || -L "${public_key}" ]]; then
    err "缺少本机受信 release 公钥文件 REALM_RELEASE_PUBLIC_KEY_FILE"
    return 1
  fi
  if ! python3 - "${public_key}" "${manifest_file}" "${signature_file}" <<'PY'
import os
import pathlib
import stat
import sys

trusted_uids = {0, os.geteuid()}
for raw in sys.argv[1:]:
    path = pathlib.Path(raw)
    if not path.is_absolute():
        raise SystemExit(f"trusted release path is not absolute: {path}")
    metadata = path.lstat()
    if (
        stat.S_ISLNK(metadata.st_mode)
        or not stat.S_ISREG(metadata.st_mode)
        or metadata.st_nlink != 1
        or metadata.st_uid not in trusted_uids
        or stat.S_IMODE(metadata.st_mode) & 0o022
    ):
        raise SystemExit(f"trusted release file is unsafe: {path}")
    current = path.parent
    while True:
        parent = current.lstat()
        sticky_root = (
            parent.st_uid == 0
            and bool(stat.S_IMODE(parent.st_mode) & stat.S_ISVTX)
        )
        if (
            stat.S_ISLNK(parent.st_mode)
            or not stat.S_ISDIR(parent.st_mode)
            or parent.st_uid not in trusted_uids
            or (
                stat.S_IMODE(parent.st_mode) & 0o022
                and not sticky_root
            )
        ):
            raise SystemExit(f"trusted release parent is unsafe: {current}")
        if current == current.parent:
            break
        current = current.parent
PY
  then
    err "受信 release 公钥权限不安全"
    return 1
  fi
  public_key_bits="$(release_public_key_bits "${public_key}" || true)"
  if [[ -z "${public_key_bits}" ]]; then
    err "受信 release 公钥必须是 RSA 3072-bit 或更强"
    return 1
  fi
  signature_size="$(wc -c < "${signature_file}" 2>/dev/null | tr -d '[:space:]')"
  if [[ "${signature_size}" != "$((public_key_bits / 8))" ]]; then
    err "release manifest 签名长度与 RSA 公钥不匹配"
    return 1
  fi
  if ! openssl dgst -sha256 -verify "${public_key}" \
    -signature "${signature_file}" "${manifest_file}" >/dev/null 2>&1; then
    err "release manifest 公钥签名校验失败"
    return 1
  fi
  if ! python3 - "${manifest_file}" "${required_capability}" "${records_file}" \
    "${REALM_RELEASE_EXPECTED_VERSION:-}" \
    "${REALM_RELEASE_EXPECTED_COMMIT:-}" \
    "${REALM_RELEASE_EXPECTED_BUILD_ID:-}" <<'PY'
import json
import pathlib
import re
import sys

manifest_path = pathlib.Path(sys.argv[1])
required_capability = sys.argv[2]
records_path = pathlib.Path(sys.argv[3]) if sys.argv[3] else None
expected_version, expected_commit, expected_build_id = sys.argv[4:7]
raw = manifest_path.read_bytes()
payload = json.loads(raw)
expected_fields = {
    "schema", "version", "commit", "build_id", "capabilities",
    "source_files", "files", "release_metadata",
}
if not isinstance(payload, dict) or set(payload) != expected_fields:
    raise SystemExit("release manifest fields are invalid")
schema = payload["schema"]
if schema not in {1, 2}:
    raise SystemExit("unsupported release manifest schema")
if not re.fullmatch(r"[0-9][0-9A-Za-z._+-]{0,63}", payload["version"]):
    raise SystemExit("release version is invalid")
if not re.fullmatch(r"[0-9a-f]{40}([0-9a-f]{24})?", payload["commit"]):
    raise SystemExit("release commit is invalid")
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}", payload["build_id"]):
    raise SystemExit("release build_id is invalid")
release_metadata = payload["release_metadata"]
if release_metadata is not None and (
    not isinstance(release_metadata, dict)
    or set(release_metadata) != {"path", "projection", "sha256", "size"}
    or release_metadata.get("path") != "release.json"
    or release_metadata.get("projection") != "identity-archive-site-v1"
    or not re.fullmatch(r"[0-9a-f]{64}", str(release_metadata.get("sha256", "")))
    or isinstance(release_metadata.get("size"), bool)
    or not isinstance(release_metadata.get("size"), int)
    or release_metadata["size"] < 0
):
    raise SystemExit("release metadata binding is invalid")
capabilities = payload["capabilities"]
if (
    not isinstance(capabilities, list)
    or capabilities != sorted(set(capabilities))
    or required_capability not in capabilities
    or not all(
        isinstance(item, str)
        and re.fullmatch(r"[a-z0-9][a-z0-9._-]{0,63}", item)
        for item in capabilities
    )
):
    raise SystemExit("release capabilities are invalid")
for label, actual, expected in (
    ("version", payload["version"], expected_version),
    ("commit", payload["commit"], expected_commit.lower()),
    ("build_id", payload["build_id"], expected_build_id),
):
    if expected and actual != expected:
        raise SystemExit(f"release {label} drift detected")
files = payload["files"]
if not isinstance(files, dict) or not files or list(files) != sorted(files):
    raise SystemExit("release files are invalid")
source_files = payload["source_files"]
if (
    not isinstance(source_files, list)
    or not source_files
    or source_files != sorted(set(source_files))
    or any(path not in files for path in source_files)
):
    raise SystemExit("release source_files are invalid")
records = []
for path, entry in files.items():
    parts = pathlib.PurePosixPath(path)
    if (
        not isinstance(path, str)
        or not path
        or parts.is_absolute()
        or "\\" in path
        or any(ord(character) < 32 or ord(character) == 127 for character in path)
        or any(part in {"", ".", ".."} for part in parts.parts)
        or not isinstance(entry, dict)
    ):
        raise SystemExit("release file entry is invalid")
    allowed = (
        ({"sha256", "size"}, {"sha256", "size", "url"})
        if schema == 1
        else (
            {"sha256", "size", "mode"},
            {"sha256", "size", "mode", "url"},
        )
    )
    if set(entry) not in allowed:
        raise SystemExit("release file entry is invalid")
    digest = entry.get("sha256")
    size = entry.get("size")
    if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):
        raise SystemExit("release file digest is invalid")
    if isinstance(size, bool) or not isinstance(size, int) or size < 0:
        raise SystemExit("release file size is invalid")
    mode = entry["mode"] if schema == 2 else "0644"
    if (
        not isinstance(mode, str)
        or re.fullmatch(r"0[0-7]{3}", mode) is None
    ):
        raise SystemExit("release file mode is invalid")
    if path in source_files:
        records.append((digest, str(size), str(mode), path))
canonical = (
    json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(",", ":"))
    + "\n"
).encode()
if raw != canonical:
    raise SystemExit("release manifest is not canonical JSON")
if records_path is not None:
    records_path.write_text(
        "".join("\t".join(row) + "\n" for row in records),
        encoding="utf-8",
    )
PY
  then
    err "release manifest 字段、能力或期望值校验失败"
    return 1
  fi
}

download_signed_release_manifest(){
  local manifest_url="$1"
  local manifest_file="$2"
  local required_capability="$3"
  local records_file="${4:-}"
  local signature_url="${REALM_RELEASE_MANIFEST_SIGNATURE_URL:-${manifest_url%%\?*}.sig}"
  local signature_file="${manifest_file}.sig"
  local manifest_sha=""

  require_secure_asset_url "${manifest_url}" "release manifest" || return 1
  require_secure_asset_url "${signature_url}" "release manifest signature" || return 1
  manifest_sha="$(normalize_sha256 "${REALM_RELEASE_MANIFEST_SHA256:-}" || true)"
  if [[ -n "${manifest_sha}" ]]; then
    download_verified_file \
      "${manifest_url}" "${manifest_file}" "${manifest_sha}" "release manifest" \
      || return 1
  else
    download_file "${manifest_url}" "${manifest_file}" || return 1
  fi
  download_file "${signature_url}" "${signature_file}" || return 1
  verify_signed_release_manifest \
    "${manifest_file}" "${signature_file}" "${required_capability}" "${records_file}"
}

validate_zip_archive(){
  local archive="$1"
  [[ -f "${archive}" ]] || return 1
  python3 - "${archive}" <<'PY'
import pathlib
import stat
import sys
import zipfile

archive_path = pathlib.Path(sys.argv[1])
try:
    with zipfile.ZipFile(archive_path) as archive:
        entries = archive.infolist()
        if not entries or len(entries) > 20000:
            raise SystemExit("zip entry count is invalid")
        total = 0
        seen_exact = set()
        seen_casefold = set()
        seen_files = set()
        seen_dirs = set()
        for info in entries:
            raw = info.filename
            path = pathlib.PurePosixPath(raw)
            if (
                not raw
                or path.is_absolute()
                or "\\" in raw
                or any(part in {"", ".", ".."} for part in path.parts)
            ):
                raise SystemExit(f"unsafe zip path: {raw!r}")
            mode = (info.external_attr >> 16) & 0xFFFF
            if stat.S_ISLNK(mode):
                raise SystemExit(f"zip symlink is not allowed: {raw}")
            normalized = raw.rstrip("/")
            folded = normalized.casefold()
            if normalized in seen_exact or folded in seen_casefold:
                raise SystemExit(f"duplicate zip member: {raw!r}")
            if info.is_dir():
                if normalized in seen_files or normalized in seen_dirs:
                    raise SystemExit(f"duplicate zip directory member: {raw!r}")
                seen_dirs.add(normalized)
            else:
                parts = normalized.split("/")
                for index in range(1, len(parts)):
                    prefix = "/".join(parts[:index])
                    if prefix in seen_files:
                        raise SystemExit(f"zip file/directory collision: {raw!r}")
                if normalized in seen_files or normalized in seen_dirs:
                    raise SystemExit(f"duplicate zip member: {raw!r}")
                seen_files.add(normalized)
                for index in range(1, len(parts)):
                    seen_dirs.add("/".join(parts[:index]))
            seen_exact.add(normalized)
            seen_casefold.add(folded)
            total += max(0, int(info.file_size))
            if total > 4 * 1024 * 1024 * 1024:
                raise SystemExit("zip expands beyond the safety limit")
        bad = archive.testzip()
        if bad:
            raise SystemExit(f"corrupt zip member: {bad}")
except (OSError, zipfile.BadZipFile) as exc:
    raise SystemExit(f"invalid zip archive: {exc}") from exc
PY
}

read_sha256_sidecar(){
  local sidecar="$1"
  local asset_name="${2:-}"
  local text=""
  [[ -f "${sidecar}" ]] || return 1
  text="$(cat "${sidecar}" 2>/dev/null || true)"
  find_sha256_in_text "${text}" "${asset_name}"
}

download_verified_file(){
  local url="$1"
  local out="$2"
  local expected_sha="$3"
  local label="${4:-文件}"
  local actual=""
  local verified_tmp=""
  expected_sha="$(normalize_sha256 "${expected_sha}" || true)"
  if [[ -z "${expected_sha}" ]]; then
    err "${label} 缺少有效 SHA256，拒绝下载执行内容：${url}"
    return 1
  fi
  verified_tmp="$(mktemp "${out}.verified.XXXXXX")" || return 1
  register_cleanup_path "${verified_tmp}"
  if ! download_file "${url}" "${verified_tmp}"; then
    rm -f "${verified_tmp}" >/dev/null 2>&1 || true
    return 1
  fi
  actual="$(sha256_file "${verified_tmp}" || true)"
  if [[ -z "${actual}" || "${actual}" != "${expected_sha}" ]]; then
    err "${label} SHA256 校验失败：${url}"
    rm -f "${verified_tmp}" >/dev/null 2>&1 || true
    return 1
  fi
  if ! mv -f "${verified_tmp}" "${out}"; then
    rm -f "${verified_tmp}" >/dev/null 2>&1 || true
    return 1
  fi
}

append_cache_bust_url(){
  local url="$1"
  local bust
  bust="ts=$(date +%s)"
  if [[ "${url}" != http://* && "${url}" != https://* ]]; then
    printf '%s\n' "${url}"
  elif [[ "${url}" == *\?* ]]; then
    printf '%s\n' "${url}&${bust}"
  else
    printf '%s\n' "${url}?${bust}"
  fi
}

realm_release_tag(){
  local raw="${REALM_AGENT_REALM_RELEASE_TAG:-${REALM_RELEASE_TAG:-${REALM_RELEASE_TAG_DEFAULT}}}"
  raw="${raw##*/}"
  raw="${raw#v}"
  if [[ -z "${raw}" || ! "${raw}" =~ ^[0-9][0-9A-Za-z._-]*$ ]]; then
    raw="${REALM_RELEASE_TAG_DEFAULT#v}"
  fi
  printf 'v%s\n' "${raw}"
}

find_sha256_in_text(){
  local text="$1"
  local asset_name="${2:-}"
  local line hash
  while IFS= read -r line || [[ -n "${line}" ]]; do
    line="${line%$'\r'}"
    [[ -z "${line}" ]] && continue
    if [[ -n "${asset_name}" && "${line}" != *"${asset_name}"* ]]; then
      if ! [[ "${line}" =~ ^[[:space:]]*[0-9a-fA-F]{64}[[:space:]]*$ ]]; then
        continue
      fi
    fi
    hash="$(printf '%s' "${line}" | grep -Eo '[0-9a-fA-F]{64}' | head -n1 | tr 'A-F' 'a-f')"
    if [[ "${hash}" =~ ^[0-9a-f]{64}$ ]]; then
      printf '%s\n' "${hash}"
      return 0
    fi
  done <<< "${text}"
  return 1
}

expected_sha256_for_url(){
  local url="$1"
  local explicit="${2:-}"
  local asset_name="${3:-${url%%\?*}}"
  local expected=""
  local checksum_file=""

  expected="$(normalize_sha256 "${explicit}" || true)"
  if [[ -z "${expected}" && "${url}" == *\?* ]]; then
    local query="${url#*\?}"
    local pair=""
    local -a query_parts=()
    query="${query%%#*}"
    IFS='&' read -r -a query_parts <<< "${query}"
    for pair in "${query_parts[@]}"; do
      if [[ "${pair}" == sha256=* ]]; then
        expected="$(normalize_sha256 "${pair#sha256=}" || true)"
        break
      fi
    done
  fi
  if [[ -n "${expected}" ]]; then
    printf '%s\n' "${expected}"
    return 0
  fi

  asset_name="$(basename "${asset_name}")"
  if [[ "${url}" == file://* ]]; then
    local source_path="${url#file://}"
    source_path="${source_path%%\?*}"
    for checksum_file in "${source_path}.sha256" "${source_path}.sha256sum"; do
      expected="$(read_sha256_sidecar "${checksum_file}" "${asset_name}" || true)"
      if [[ -n "${expected}" ]]; then
        printf '%s\n' "${expected}"
        return 0
      fi
    done
    return 1
  fi

  # A checksum fetched from the same mutable remote origin is not an
  # independent trust anchor. Remote assets therefore require an explicit
  # digest or a digest from already-verified release metadata.
  return 1
}

trusted_offline_archive_sha256(){
  local archive="$1"
  local manifest_file="${REALM_RELEASE_MANIFEST_FILE:-}"
  local signature_file="${REALM_RELEASE_MANIFEST_SIGNATURE_FILE:-}"
  local artifact_path="${REALM_AGENT_RELEASE_ARTIFACT_PATH:-}"

  if [[ -z "${manifest_file}" ]]; then
    manifest_file="$(dirname "${REALM_AGENT_ZIP_PATH:-${archive}}")/release-manifest.json"
  fi
  if [[ -z "${signature_file}" ]]; then
    signature_file="${manifest_file}.sig"
  fi
  if [[ -z "${manifest_file}" || "${manifest_file}" != /* \
        || ! -f "${manifest_file}" || -L "${manifest_file}" \
        || -z "${signature_file}" || "${signature_file}" != /* \
        || ! -f "${signature_file}" || -L "${signature_file}" ]]; then
    err "离线 ZIP 必须附带绝对路径的签名 release manifest 与签名文件"
    return 1
  fi
  if ! verify_signed_release_manifest \
    "${manifest_file}" "${signature_file}" "agent-install"; then
    return 1
  fi
  python3 - "${manifest_file}" "${archive}" "${artifact_path}" <<'PY'
import hashlib
import json
import pathlib
import re
import sys

manifest_path = pathlib.Path(sys.argv[1])
archive_path = pathlib.Path(sys.argv[2])
requested_path = sys.argv[3].strip()
payload = json.loads(manifest_path.read_text(encoding="utf-8"))
files = payload.get("files", {})
commit = str(payload.get("commit") or "").strip().lower()
archive_bytes = archive_path.read_bytes()
archive_sha = hashlib.sha256(archive_bytes).hexdigest()
archive_size = len(archive_bytes)


def allowed(path: str) -> bool:
    return path == "panel/static/realm-agent.zip" or bool(
        re.fullmatch(
            rf"nexus/archive/releases/{re.escape(commit)}\.zip",
            path,
        )
    )


matches = []
for path, entry in files.items():
    if (
        isinstance(path, str)
        and isinstance(entry, dict)
        and allowed(path)
        and entry.get("sha256") == archive_sha
        and entry.get("size") == archive_size
    ):
        matches.append(path)
if requested_path:
    if requested_path not in matches:
        raise SystemExit("offline archive does not match the requested signed artifact")
elif len(matches) != 1:
    raise SystemExit("offline archive is missing or ambiguous in the signed release")
print(archive_sha)
PY
}

release_metadata_url_for_artifact(){
  local artifact_url="${1:-}"
  if [[ -n "${REALM_AGENT_RELEASE_METADATA_URL:-}" ]]; then
    printf '%s\n' "${REALM_AGENT_RELEASE_METADATA_URL}"
    return 0
  fi
  case "${artifact_url}" in
    https://*)
      printf '%s\n' "${artifact_url}" \
        | sed -E 's#^(https://[^/]+).*$#\1/release-manifest.json#'
      ;;
    file://*)
      local path="${artifact_url#file://}"
      printf 'file://%s/release-manifest.json\n' "$(dirname "${path%%\?*}")"
      ;;
    *)
      printf '%s\n' "${REPO_RELEASE_METADATA_URL_DEFAULT}"
      ;;
  esac
}

resolve_release_archive(){
  local metadata_url="${1:-${REALM_AGENT_RELEASE_METADATA_URL:-${REPO_RELEASE_METADATA_URL_DEFAULT}}}"
  local expected_git_sha="${REALM_AGENT_RELEASE_GIT_SHA:-}"
  local metadata_file=""
  local fields=""
  local git_sha=""
  local archive_url=""
  local archive_sha=""
  local archive_size=""

  metadata_file="$(mktemp -t realm-agent-release.XXXXXX)" || return 1
  register_cleanup_path "${metadata_file}"
  if ! download_signed_release_manifest \
    "${metadata_url}" "${metadata_file}" "agent-install"; then
    return 1
  fi

  fields="$(
    python3 - "${metadata_file}" "${metadata_url}" <<'PY'
import json
import pathlib
import re
import sys
import urllib.parse

metadata_path = pathlib.Path(sys.argv[1])
metadata_url = sys.argv[2]
payload = json.loads(metadata_path.read_text(encoding="utf-8"))
git_sha = str(payload.get("commit") or "").strip().lower()
archive_path = f"nexus/archive/releases/{git_sha}.zip"
entry = payload.get("files", {}).get(archive_path, {})
archive_sha = str(entry.get("sha256") or "").strip().lower()
archive_size = entry.get("size")

if not re.fullmatch(r"[0-9a-f]{40}([0-9a-f]{24})?", git_sha):
    raise SystemExit("release metadata git_sha is invalid")
if not re.fullmatch(r"[0-9a-f]{64}", archive_sha):
    raise SystemExit("release metadata archive_sha256 is invalid")
try:
    archive_size = int(archive_size)
except (TypeError, ValueError, OverflowError) as exc:
    raise SystemExit("release metadata archive_size is invalid") from exc
if archive_size <= 0:
    raise SystemExit("release metadata archive_size must be positive")

parts = pathlib.PurePosixPath(archive_path)
if (
    not archive_path
    or parts.is_absolute()
    or "\\" in archive_path
    or any(part in {"", ".", ".."} for part in parts.parts)
):
    raise SystemExit("release metadata archive_path is unsafe")
if parts.as_posix() != f"nexus/archive/releases/{git_sha}.zip":
    raise SystemExit("release metadata archive_path is not content-addressed")

parsed = urllib.parse.urlsplit(metadata_url)
if parsed.scheme == "file":
    base = pathlib.Path(urllib.parse.unquote(parsed.path)).parent
    archive_url = (base.joinpath(*parts.parts)).resolve().as_uri()
elif parsed.scheme == "https" and parsed.netloc:
    archive_url = urllib.parse.urlunsplit(
        ("https", parsed.netloc, "/" + "/".join(parts.parts), "", "")
    )
else:
    raise SystemExit("unsupported release metadata URL")

print("\t".join((git_sha, archive_url, archive_sha, str(archive_size))))
PY
  )" || {
    err "release 元数据格式或不可变来源字段无效：${metadata_url}"
    return 1
  }

  IFS=$'\t' read -r git_sha archive_url archive_sha archive_size <<< "${fields}"
  if [[ -n "${expected_git_sha}" \
        && "$(printf '%s' "${expected_git_sha}" | tr 'A-F' 'a-f')" != "${git_sha}" ]]; then
    err "release git_sha 与 REALM_AGENT_RELEASE_GIT_SHA 不一致"
    return 1
  fi
  [[ -n "${archive_url}" && -n "${archive_sha}" && "${archive_size}" =~ ^[0-9]+$ ]] || return 1
  printf '%s\t%s\t%s\t%s\n' "${git_sha}" "${archive_url}" "${archive_sha}" "${archive_size}"
}

embedded_realm_asset_sha256(){
  local asset_name="$1"
  local release_ref="${2:-${REALM_RELEASE_TAG_DEFAULT}}"
  local tag="${release_ref##*/}"
  tag="${tag#v}"
  tag="v${tag}"
  [[ "${tag}" == "v2.9.3" ]] || return 1
  case "${asset_name}" in
    realm-aarch64-unknown-linux-gnu.tar.gz) printf '%s\n' "9937daacdcdfcac9fd78d25819f2de0a5c3357c2c49e686679d812343ab8661e" ;;
    realm-aarch64-unknown-linux-musl.tar.gz) printf '%s\n' "1e5065ae147423647a63ed2dd27b6faee9800b7882eec8656946cbda54ee796f" ;;
    realm-x86_64-unknown-linux-gnu.tar.gz) printf '%s\n' "2eba86f1a1e47c1bfe9d6fd682ef8667bd05e57c3aeb0ec37806aabe2ce74a0c" ;;
    realm-x86_64-unknown-linux-musl.tar.gz) printf '%s\n' "622932d21eb74d1683dc71bf596227038ce8f72b01aa77906e899be548bb3792" ;;
    *) return 1 ;;
  esac
}

find_sha256_in_release_page(){
  local text="$1"
  local asset_name="$2"
  [[ -z "${text}" || -z "${asset_name}" ]] && return 1

  local flat escaped pair hash
  flat="$(printf '%s' "${text}" | tr '\n' ' ' | sed 's/\\"/"/g; s#\\/#/#g; s#\\u002F#/#g; s/&quot;/"/g')"
  escaped="$(printf '%s' "${asset_name}" | sed -e 's/[][(){}.^$+*?|\\/]/\\&/g')"

  pair="$(printf '%s' "${flat}" | grep -Eo "\"name\"[[:space:]]*:[[:space:]]*\"${escaped}\".{0,1400}\"digest\"[[:space:]]*:[[:space:]]*\"sha256:[0-9a-fA-F]{64}\"" 2>/dev/null | head -n1 || true)"
  if [[ -n "${pair}" ]]; then
    hash="$(printf '%s' "${pair}" | grep -Eo "sha256:[0-9a-fA-F]{64}" | head -n1 | cut -d: -f2 | tr 'A-F' 'a-f')"
    if [[ "${hash}" =~ ^[0-9a-f]{64}$ ]]; then
      printf '%s\n' "${hash}"
      return 0
    fi
  fi

  hash="$(
    printf '%s' "${flat}" | awk -v asset="${asset_name}" '
      BEGIN { IGNORECASE=1 }
      {
        s=$0
        pos=index(tolower(s), tolower(asset))
        while (pos > 0) {
          seg=substr(s, pos, 1800)
          if (match(seg, /sha256:[0-9a-fA-F]{64}/)) {
            print tolower(substr(seg, RSTART + 7, 64))
            exit
          }
          tail=substr(s, pos + length(asset))
          nxt=index(tolower(tail), tolower(asset))
          if (nxt <= 0) break
          pos=pos + length(asset) + nxt - 1
        }
      }
    ' | head -n1
  )"
  if [[ "${hash}" =~ ^[0-9a-f]{64}$ ]]; then
    printf '%s\n' "${hash}"
    return 0
  fi
  return 1
}

fetch_release_asset_sha256(){
  local release_url="$1"
  local asset_name="$2"
  local key configured=""
  key="$(
    printf 'REALM_AGENT_REALM_ASSET_SHA256_%s' "${asset_name}" \
      | tr '[:lower:].-' '[:upper:]__'
  )"
  configured="${!key:-}"
  configured="$(normalize_sha256 "${configured}" || true)"
  if [[ -n "${configured}" ]]; then
    printf '%s\n' "${configured}"
    return 0
  fi
  embedded_realm_asset_sha256 "${asset_name}" "${release_url}"
}

# REALM_AGENT_REALM_RELEASE_SHA256 pins the SHA256 of the realm asset
# manifest (realm-assets.json) published by the panel. When set, the
# installer fetches that manifest from the panel static realm directory,
# verifies it against the pinned digest, and uses its per-asset digests for
# any explicitly declared release tag. The pinned manifest digest is the
# trust anchor: sources that carry no bound digest are still refused.
fetch_realm_manifest_asset_sha256(){
  local asset_name="$1"
  local panel_base="${2:-}"
  local cache_dir="${3:-}"
  local manifest_sha="${REALM_AGENT_REALM_RELEASE_SHA256:-}"
  local manifest_url=""
  local manifest_file=""
  local asset_sha=""
  local expected_tag=""
  manifest_sha="$(normalize_sha256 "${manifest_sha}" || true)"
  [[ -n "${manifest_sha}" ]] || return 1
  panel_base="$(normalize_panel_url "${panel_base}" || true)"
  [[ -n "${panel_base}" ]] || return 1
  manifest_url="${panel_base}/static/realm/realm-assets.json"
  if [[ -z "${cache_dir}" ]]; then
    cache_dir="$(mktemp -d "${TMPDIR:-/tmp}/realm-assets.XXXXXX")" || return 1
    if declare -F register_cleanup_path >/dev/null 2>&1; then
      register_cleanup_path "${cache_dir}"
    fi
  fi
  if [[ "${cache_dir}" != /* || ! -d "${cache_dir}" || -L "${cache_dir}" ]]; then
    return 1
  fi
  chmod 0700 "${cache_dir}" >/dev/null 2>&1 || return 1
  manifest_file="${cache_dir}/realm-assets.${manifest_sha}.json"
  if [[ -e "${manifest_file}" || -L "${manifest_file}" ]]; then
    # 缓存必须是当前私有目录中的普通文件，并在每次使用前重验摘要。
    if [[ ! -f "${manifest_file}" || -L "${manifest_file}" \
      || "$(sha256_file "${manifest_file}" || true)" != "${manifest_sha}" ]]; then
      rm -f "${manifest_file}" >/dev/null 2>&1 || true
    fi
  fi
  if [[ ! -s "${manifest_file}" ]]; then
    if ! download_verified_file \
      "${manifest_url}" "${manifest_file}" "${manifest_sha}" "realm 资产清单"; then
      err "无法从面板拉取并校验 realm 资产清单（REALM_AGENT_REALM_RELEASE_SHA256）"
      return 1
    fi
    chmod 0600 "${manifest_file}" >/dev/null 2>&1 || true
    if declare -F register_cleanup_path >/dev/null 2>&1; then
      register_cleanup_path "${manifest_file}"
    fi
  fi
  # 清单 tag 与请求的 release tag 交叉校验，防止运维钉错 tag 时静默安装旧版。
  expected_tag="$(realm_release_tag || true)"
  [[ -n "${expected_tag}" ]] || return 1
  asset_sha="$(python3 - \
    "${manifest_file}" "${asset_name}" "${expected_tag}" "${manifest_sha}" <<'PY' || true
import hashlib
import json
import os
import re
import stat
import sys

manifest_path, asset_name, expected_tag, expected_sha = sys.argv[1:5]
maximum_bytes = 1 << 20
flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
fd = os.open(manifest_path, flags)
try:
    info = os.fstat(fd)
    if not stat.S_ISREG(info.st_mode) or info.st_size <= 0 or info.st_size > maximum_bytes:
        raise SystemExit(1)
    chunks = []
    remaining = info.st_size
    while remaining:
        chunk = os.read(fd, min(remaining, 65536))
        if not chunk:
            raise SystemExit(1)
        chunks.append(chunk)
        remaining -= len(chunk)
    if os.read(fd, 1):
        raise SystemExit(1)
finally:
    os.close(fd)
raw = b"".join(chunks)
if hashlib.sha256(raw).hexdigest() != expected_sha:
    raise SystemExit(1)
payload = json.loads(raw.decode("utf-8"))
manifest_tag = payload.get("tag")
if not isinstance(manifest_tag, str) or manifest_tag != expected_tag:
    raise SystemExit(1)
assets = payload.get("assets")
if not isinstance(assets, dict):
    raise SystemExit(1)
value = assets.get(asset_name)
if not isinstance(value, str):
    raise SystemExit(1)
value = value.strip().lower()
if not re.fullmatch(r"[0-9a-f]{64}", value):
    raise SystemExit(1)
print(value)
PY
  )"
  [[ "${asset_sha}" =~ ^[0-9a-f]{64}$ ]] || return 1
  printf '%s\n' "${asset_sha}"
}

strip_env_value(){
  local value="$1"
  value="${value//$'\r'/}"
  value="${value//$'\n'/}"
  printf '%s' "${value}"
}

normalize_agent_bind_host(){
  local raw="${1:-}"
  local host
  host="$(strip_env_value "${raw}")"
  if [[ "${host}" != "${raw}" ]]; then
    return 1
  fi
  if [[ -z "${host}" ]]; then
    printf '%s' "127.0.0.1"
    return 0
  fi
  if [[ "${host}" == "*" ]]; then
    printf '%s' "0.0.0.0"
    return 0
  fi
  if [[ ! "${host}" =~ ^[A-Za-z0-9._:%-]+$ ]]; then
    return 1
  fi
  printf '%s' "${host}"
}

normalize_agent_transport(){
  local transport
  transport="$(
    printf '%s' "${1:-}" \
      | tr '[:upper:]' '[:lower:]' \
      | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'
  )"
  case "${transport}" in
    http|https)
      printf '%s' "${transport}"
      ;;
    *)
      return 1
      ;;
  esac
}

agent_systemd_dir(){
  printf '%s' "${REALM_AGENT_SYSTEMD_DIR:-/etc/systemd/system}"
}

agent_config_dir(){
  printf '%s' "${REALM_AGENT_CONFIG_DIR:-/etc/realm-agent}"
}

agent_api_key_path(){
  printf '%s' "$(agent_config_dir)/api.key"
}

agent_gateway_env_path(){
  printf '%s' "$(agent_config_dir)/gateway.env"
}

agent_service_account_marker_path(){
  printf '%s' "$(agent_config_dir)/service-account.env"
}

agent_service_account_marker_value(){
  local path="$1"
  local key="$2"
  awk -F= -v wanted="${key}" '$1 == wanted { print substr($0, length($1) + 2); exit }' \
    "${path}" 2>/dev/null
}

agent_service_account_marker_metadata_valid(){
  local path="$1"
  local expected_uid="0"
  local expected_gid="0"
  local actual=""
  if ! agent_sandbox_is_host_unit_dir; then
    expected_uid="$(id -u)"
    expected_gid="$(id -g)"
  fi
  [[ -f "${path}" && ! -L "${path}" ]] || return 1
  actual="$(
    stat -Lc '%u:%g:%a' "${path}" 2>/dev/null \
      || stat -f '%u:%g:%Lp' "${path}" 2>/dev/null
  )"
  [[ "${actual}" == "${expected_uid}:${expected_gid}:600" ]]
}

record_agent_service_account_transaction_marker(){
  local path=""
  local tmp=""
  local marker_uid="0"
  local marker_gid="0"
  [[ "${REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE:-0}" == "1" ]] || return 0
  path="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state/service-account-created.env"
  if ! agent_sandbox_is_host_unit_dir; then
    marker_uid="$(id -u)"
    marker_gid="$(id -g)"
  fi
  tmp="$(mktemp "${path}.XXXXXX")" || return 1
  if ! {
    printf 'VERSION=1\n'
    printf 'USER=%s\n' "${AGENT_SERVICE_USER}"
    printf 'GROUP=%s\n' "${AGENT_SERVICE_GROUP}"
    printf 'UID=%s\n' "${AGENT_SERVICE_UID:-0}"
    printf 'GID=%s\n' "${AGENT_SERVICE_GID:-0}"
    printf 'USER_CREATED=%s\n' "${AGENT_SERVICE_USER_CREATED_THIS_RUN}"
    printf 'GROUP_CREATED=%s\n' "${AGENT_SERVICE_GROUP_CREATED_THIS_RUN}"
    printf 'USER_INTENT=%s\n' "${AGENT_SERVICE_USER_CREATE_INTENT:-0}"
    printf 'GROUP_INTENT=%s\n' "${AGENT_SERVICE_GROUP_CREATE_INTENT:-0}"
  } > "${tmp}" \
    || ! chmod 0600 "${tmp}" \
    || ! chown "${marker_uid}:${marker_gid}" "${tmp}" \
    || ! durable_sync_agent_path "${tmp}" \
    || ! mv -f "${tmp}" "${path}" \
    || ! durable_sync_agent_path "$(dirname "${path}")"; then
    rm -f "${tmp}" >/dev/null 2>&1 || true
    return 1
  fi
}

agent_local_group_file(){
  printf '%s' /etc/group
}

agent_local_passwd_file(){
  printf '%s' /etc/passwd
}

agent_local_identity_name_absent(){
  local kind="$1"
  local name="$2"
  local source=""
  case "${kind}" in
    group) source="$(agent_local_group_file)" ;;
    user) source="$(agent_local_passwd_file)" ;;
    *) return 1 ;;
  esac
  [[ -r "${source}" ]] || return 1
  ! awk -F: -v wanted="${name}" '$1 == wanted { found = 1 } END { exit found ? 0 : 1 }' \
    "${source}"
}

agent_resolve_created_group_gid(){
  local entry=""
  local gid=""
  entry="$(getent group "${AGENT_SERVICE_GROUP}" 2>/dev/null || true)"
  gid="$(
    printf '%s\n' "${entry}" | awk -F: -v wanted="${AGENT_SERVICE_GROUP}" \
      '$1 == wanted && $3 ~ /^[1-9][0-9]*$/ { if (found++) exit 2; value = $3 }
       END { if (found == 1) print value; else exit 1 }'
  )" || gid=""
  if [[ -z "${gid}" ]]; then
    gid="$(
      awk -F: -v wanted="${AGENT_SERVICE_GROUP}" \
        '$1 == wanted && $3 ~ /^[1-9][0-9]*$/ { if (found++) exit 2; value = $3 }
         END { if (found == 1) print value; else exit 1 }' \
        "$(agent_local_group_file)"
    )" || gid=""
  fi
  [[ "${gid}" =~ ^[1-9][0-9]*$ ]] || return 1
  printf '%s' "${gid}"
}

agent_resolve_created_user_ids(){
  local uid=""
  local gid=""
  local entry=""
  uid="$(id -u "${AGENT_SERVICE_USER}" 2>/dev/null || true)"
  gid="$(id -g "${AGENT_SERVICE_USER}" 2>/dev/null || true)"
  if [[ ! "${uid}" =~ ^[1-9][0-9]*$ || ! "${gid}" =~ ^[1-9][0-9]*$ ]]; then
    entry="$(getent passwd "${AGENT_SERVICE_USER}" 2>/dev/null || true)"
    read -r uid gid < <(
      printf '%s\n' "${entry}" | awk -F: -v wanted="${AGENT_SERVICE_USER}" \
        '$1 == wanted && $3 ~ /^[1-9][0-9]*$/ && $4 ~ /^[1-9][0-9]*$/ {
           if (found++) exit 2; uid = $3; gid = $4
         }
         END { if (found == 1) print uid, gid; else exit 1 }'
    ) || {
      uid=""
      gid=""
    }
  fi
  if [[ -z "${uid}" || -z "${gid}" ]]; then
    read -r uid gid < <(
      awk -F: -v wanted="${AGENT_SERVICE_USER}" \
        '$1 == wanted && $3 ~ /^[1-9][0-9]*$/ && $4 ~ /^[1-9][0-9]*$/ {
           if (found++) exit 2; uid = $3; gid = $4
         }
         END { if (found == 1) print uid, gid; else exit 1 }' \
        "$(agent_local_passwd_file)"
    ) || return 1
  fi
  [[ "${uid}" =~ ^[1-9][0-9]*$ && "${gid}" =~ ^[1-9][0-9]*$ ]] || return 1
  printf '%s:%s' "${uid}" "${gid}"
}

clear_failed_agent_create_intent(){
  local kind="$1"
  local marker="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state/service-account-created.env"
  case "${kind}" in
    group) AGENT_SERVICE_GROUP_CREATE_INTENT="0" ;;
    user) AGENT_SERVICE_USER_CREATE_INTENT="0" ;;
    *) return 1 ;;
  esac
  if [[ "${AGENT_SERVICE_USER_CREATED_THIS_RUN}" == "0" \
    && "${AGENT_SERVICE_GROUP_CREATED_THIS_RUN}" == "0" ]]; then
    rm -f "${marker}" >/dev/null 2>&1 || true
    return 0
  fi
  record_agent_service_account_transaction_marker || {
    rm -f "${marker}" >/dev/null 2>&1 || true
    return 1
  }
}

compensate_unresolved_agent_create(){
  local kind="$1"
  local marker="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state/service-account-created.env"
  local intent_key=""
  local expected_uid="${AGENT_SERVICE_UID:-}"
  local expected_gid="${AGENT_SERVICE_GID:-}"
  local current_ids=""
  local current_gid=""
  [[ -f "${marker}" && ! -L "${marker}" ]] || return 1
  [[ "$(agent_service_account_marker_value "${marker}" USER)" \
      == "${AGENT_SERVICE_USER}" \
    && "$(agent_service_account_marker_value "${marker}" GROUP)" \
      == "${AGENT_SERVICE_GROUP}" ]] || return 1
  [[ "${expected_gid}" =~ ^[1-9][0-9]*$ ]] || return 1
  case "${kind}" in
    group)
      intent_key="GROUP_INTENT"
      [[ "$(agent_service_account_marker_value "${marker}" "${intent_key}")" == "1" ]] \
        || return 1
      current_gid="$(agent_resolve_created_group_gid || true)"
      [[ "${current_gid}" == "${expected_gid}" ]] || return 1
      agent_service_group_primary_gid_exclusive "${expected_gid}" || return 1
      groupdel "${AGENT_SERVICE_GROUP}" || return 1
      ;;
    user)
      intent_key="USER_INTENT"
      [[ "$(agent_service_account_marker_value "${marker}" "${intent_key}")" == "1" ]] \
        || return 1
      [[ "${expected_uid}" =~ ^[1-9][0-9]*$ ]] || return 1
      current_ids="$(agent_resolve_created_user_ids || true)"
      [[ "${current_ids}" == "${expected_uid}:${expected_gid}" ]] || return 1
      remove_created_agent_service_identity \
        "1" "${AGENT_SERVICE_GROUP_CREATED_THIS_RUN}" \
        "${expected_uid}" "${expected_gid}" || return 1
      ;;
    *) return 1 ;;
  esac
  rm -f "${marker}" >/dev/null 2>&1 || true
  AGENT_SERVICE_USER_CREATED_THIS_RUN="0"
  AGENT_SERVICE_GROUP_CREATED_THIS_RUN="0"
  AGENT_SERVICE_USER_CREATE_INTENT="0"
  AGENT_SERVICE_GROUP_CREATE_INTENT="0"
}

agent_service_group_primary_gid_exclusive(){
  local expected_gid="$1"
  local passwd_inventory=""
  local primary_name=""
  local _primary_password=""
  local primary_uid=""
  local primary_gid=""
  local _primary_gecos=""
  local _primary_home=""
  local _primary_shell=""
  passwd_inventory="$(getent passwd)" || return 1
  while IFS=: read -r primary_name _primary_password primary_uid primary_gid \
    _primary_gecos _primary_home _primary_shell; do
    [[ -n "${primary_name}" ]] || continue
    [[ "${primary_uid}" =~ ^[0-9]+$ && "${primary_gid}" =~ ^[0-9]+$ ]] \
      || return 1
    if [[ "${primary_gid}" == "${expected_gid}" \
      && "${primary_name}" != "${AGENT_SERVICE_USER}" ]]; then
      return 1
    fi
  done <<< "${passwd_inventory}"
}

validate_agent_service_account_identity(){
  local passwd_entry=""
  local group_entry=""
  local account_name=""
  local _password_field=""
  local uid=""
  local gid=""
  local _gecos=""
  local home=""
  local shell_path=""
  local group_name=""
  local _group_password=""
  local group_gid=""
  local group_members=""
  local password_status=""
  local uid_min="1000"
  local member_gid=""
  passwd_entry="$(getent passwd "${AGENT_SERVICE_USER}")" || return 1
  group_entry="$(getent group "${AGENT_SERVICE_GROUP}")" || return 1
  IFS=: read -r account_name _password_field uid gid _gecos home shell_path \
    <<< "${passwd_entry}"
  IFS=: read -r group_name _group_password group_gid group_members \
    <<< "${group_entry}"
  [[ "${account_name}" == "${AGENT_SERVICE_USER}" \
    && "${group_name}" == "${AGENT_SERVICE_GROUP}" \
    && "${uid}" =~ ^[1-9][0-9]*$ \
    && "${gid}" =~ ^[1-9][0-9]*$ \
    && "${gid}" == "${group_gid}" \
    && "${home}" == "/nonexistent" \
    && ! -e "${home}" \
    && -z "${group_members}" ]] || return 1
  agent_service_group_primary_gid_exclusive "${gid}" || return 1
  case "${shell_path}" in
    */nologin|/bin/false) ;;
    *) return 1 ;;
  esac
  if [[ -r /etc/login.defs ]]; then
    uid_min="$(
      awk '$1 == "UID_MIN" && $2 ~ /^[0-9]+$/ { print $2; exit }' \
        /etc/login.defs
    )"
    [[ "${uid_min}" =~ ^[1-9][0-9]*$ ]] || uid_min="1000"
  fi
  (( uid < uid_min )) || return 1
  password_status="$(passwd -S "${AGENT_SERVICE_USER}" 2>/dev/null | awk '{print $2}')"
  case "${password_status}" in
    L|LK) ;;
    *) return 1 ;;
  esac
  while IFS= read -r member_gid; do
    [[ -z "${member_gid}" || "${member_gid}" == "${gid}" ]] || return 1
  done < <(id -G "${AGENT_SERVICE_USER}" | tr ' ' '\n')
  AGENT_SERVICE_UID="${uid}"
  AGENT_SERVICE_GID="${gid}"
}

remove_created_agent_service_identity(){
  local user_created="$1"
  local group_created="$2"
  local expected_uid="$3"
  local expected_gid="$4"
  local current_uid=""
  local current_gid=""
  local group_entry=""
  local group_inventory=""
  local passwd_inventory=""
  local group_members=""
  if [[ "${group_created}" == "1" ]]; then
    group_entry="$(getent group "${AGENT_SERVICE_GROUP}" 2>/dev/null || true)"
    if [[ -z "${group_entry}" ]]; then
      group_inventory="$(getent group)" || return 1
      if awk -F: -v wanted="${expected_gid}" \
        '$3 == wanted { found = 1 } END { exit found ? 0 : 1 }' \
        <<< "${group_inventory}" \
        || ! agent_service_group_primary_gid_exclusive "${expected_gid}"; then
        err "拒绝接受 GID 已被重新占用的 realm-agent 私有组删除"
        return 1
      fi
      group_created="0"
    fi
    current_gid="$(printf '%s' "${group_entry}" | awk -F: '{print $3}')"
    if [[ "${group_created}" == "1" ]]; then
      group_members="$(printf '%s' "${group_entry}" | awk -F: '{print $4}')"
      if [[ "${current_gid}" != "${expected_gid}" \
        || -n "${group_members}" ]] \
        || ! agent_service_group_primary_gid_exclusive "${expected_gid}"; then
        err "拒绝删除 GID 或成员已变化的 realm-agent 组"
        return 1
      fi
    fi
  fi
  if [[ "${user_created}" == "1" ]]; then
    current_uid="$(id -u "${AGENT_SERVICE_USER}" 2>/dev/null || true)"
    current_gid="$(id -g "${AGENT_SERVICE_USER}" 2>/dev/null || true)"
    if [[ -z "${current_uid}" && -z "${current_gid}" ]]; then
      passwd_inventory="$(getent passwd)" || return 1
      if awk -F: -v wanted="${expected_uid}" \
        '$3 == wanted { found = 1 } END { exit found ? 0 : 1 }' \
        <<< "${passwd_inventory}"; then
        err "拒绝接受 UID 已被重新占用的 realm-agent 用户删除"
        return 1
      fi
      user_created="0"
    elif [[ "${current_uid}" != "${expected_uid}" \
      || "${current_gid}" != "${expected_gid}" ]]; then
      err "拒绝删除 UID/GID 已变化的 realm-agent 用户"
      return 1
    fi
    if [[ "${user_created}" == "1" ]]; then
      userdel "${AGENT_SERVICE_USER}" || return 1
    fi
  fi
  if [[ "${group_created}" == "1" ]]; then
    group_entry="$(getent group "${AGENT_SERVICE_GROUP}" 2>/dev/null || true)"
    if [[ -z "${group_entry}" ]]; then
      group_inventory="$(getent group)" || {
        err "无法确认 userdel 后 realm-agent 私有组状态"
        return 1
      }
      if awk -F: -v wanted="${expected_gid}" \
        '$3 == wanted { found = 1 } END { exit found ? 0 : 1 }' \
        <<< "${group_inventory}" \
        || ! agent_service_group_primary_gid_exclusive "${expected_gid}"; then
        err "拒绝接受 GID 已被重新占用的 realm-agent 私有组删除"
        return 1
      fi
      return 0
    fi
    current_gid="$(printf '%s' "${group_entry}" | awk -F: '{print $3}')"
    group_members="$(printf '%s' "${group_entry}" | awk -F: '{print $4}')"
    if [[ "${current_gid}" != "${expected_gid}" \
      || -n "${group_members}" ]] \
      || ! agent_service_group_primary_gid_exclusive "${expected_gid}"; then
      err "拒绝删除 GID 或成员已变化的 realm-agent 组"
      return 1
    fi
    groupdel "${AGENT_SERVICE_GROUP}" || return 1
  fi
}

fail_agent_service_account_creation(){
  local marker="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state/service-account-created.env"
  if [[ "${AGENT_SERVICE_USER_CREATED_THIS_RUN}" == "1" \
    || "${AGENT_SERVICE_GROUP_CREATED_THIS_RUN}" == "1" ]]; then
    if ! remove_created_agent_service_identity \
      "${AGENT_SERVICE_USER_CREATED_THIS_RUN}" \
      "${AGENT_SERVICE_GROUP_CREATED_THIS_RUN}" \
      "${AGENT_SERVICE_UID:-0}" "${AGENT_SERVICE_GID:-0}"; then
      err "realm-agent 服务账户创建失败后的补偿未完成"
      return 1
    fi
    rm -f "${marker}" >/dev/null 2>&1 || true
    AGENT_SERVICE_USER_CREATED_THIS_RUN="0"
    AGENT_SERVICE_GROUP_CREATED_THIS_RUN="0"
    AGENT_SERVICE_USER_CREATE_INTENT="0"
    AGENT_SERVICE_GROUP_CREATE_INTENT="0"
  fi
  return 1
}

load_agent_service_account_marker(){
  local path=""
  local state=""
  local marker_uid=""
  local marker_gid=""
  local user_created=""
  local group_created=""
  path="$(agent_service_account_marker_path)"
  AGENT_SERVICE_USER_MANAGED="0"
  AGENT_SERVICE_GROUP_MANAGED="0"
  [[ -e "${path}" ]] || return 0
  agent_service_account_marker_metadata_valid "${path}" || {
    err "realm-agent 服务账户 marker 元数据不安全"
    return 1
  }
  [[ "$(agent_service_account_marker_value "${path}" VERSION)" == "1" \
    && "$(agent_service_account_marker_value "${path}" USER)" == "${AGENT_SERVICE_USER}" \
    && "$(agent_service_account_marker_value "${path}" GROUP)" == "${AGENT_SERVICE_GROUP}" ]] || {
    err "realm-agent 服务账户 marker 格式无效"
    return 1
  }
  state="$(agent_service_account_marker_value "${path}" STATE)"
  marker_uid="$(agent_service_account_marker_value "${path}" UID)"
  marker_gid="$(agent_service_account_marker_value "${path}" GID)"
  user_created="$(agent_service_account_marker_value "${path}" USER_CREATED)"
  group_created="$(agent_service_account_marker_value "${path}" GROUP_CREATED)"
  [[ "${marker_uid}" == "${AGENT_SERVICE_UID}" \
    && "${marker_gid}" == "${AGENT_SERVICE_GID}" \
    && "${user_created}" =~ ^[01]$ \
    && "${group_created}" =~ ^[01]$ ]] || {
    err "realm-agent 服务账户 marker 与当前 UID/GID 不匹配"
    return 1
  }
  if [[ "${user_created}" == "1" || "${group_created}" == "1" ]]; then
    [[ "${state}" == "created" ]] || return 1
  else
    [[ "${state}" == "adopted" ]] || return 1
  fi
  AGENT_SERVICE_USER_MANAGED="${user_created}"
  AGENT_SERVICE_GROUP_MANAGED="${group_created}"
}

ensure_agent_service_account(){
  local nologin_shell=""
  local marker_path=""
  local resolved_user_ids=""
  local resolved_user_gid=""
  local user_exists="0"
  local group_exists="0"
  AGENT_SERVICE_USER_CREATED_THIS_RUN="0"
  AGENT_SERVICE_GROUP_CREATED_THIS_RUN="0"
  AGENT_SERVICE_USER_CREATE_INTENT="0"
  AGENT_SERVICE_GROUP_CREATE_INTENT="0"
  if ! agent_sandbox_is_host_unit_dir; then
    AGENT_SERVICE_UID="$(id -u)"
    AGENT_SERVICE_GID="$(id -g)"
    AGENT_SERVICE_USER_MANAGED="0"
    AGENT_SERVICE_GROUP_MANAGED="0"
    return 0
  fi
  [[ "$(id -u)" == "0" ]] || {
    err "创建 Agent 特权边界账户需要 root"
    return 1
  }
  if ! command_exists getent \
    || ! command_exists groupadd \
    || ! command_exists useradd \
    || ! command_exists userdel \
    || ! command_exists groupdel \
    || ! command_exists passwd; then
    err "创建 realm-agent 服务账户需要 getent/groupadd/useradd/userdel/groupdel/passwd"
    return 1
  fi
  marker_path="$(agent_service_account_marker_path)"
  getent group "${AGENT_SERVICE_GROUP}" >/dev/null 2>&1 && group_exists="1"
  if id -u "${AGENT_SERVICE_USER}" >/dev/null 2>&1 \
    || getent passwd "${AGENT_SERVICE_USER}" >/dev/null 2>&1; then
    user_exists="1"
  fi
  if [[ -e "${marker_path}" \
    && ( "${group_exists}" != "1" || "${user_exists}" != "1" ) ]]; then
    err "realm-agent marker 存在但服务账户不完整，拒绝自动重建"
    return 1
  fi
  if [[ ( "${group_exists}" != "1" || "${user_exists}" != "1" ) \
    && "${REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE:-0}" != "1" ]]; then
    err "realm-agent 服务账户只能在已激活的 rollback 事务中创建"
    return 1
  fi
  if [[ "${group_exists}" == "1" ]]; then
    AGENT_SERVICE_GID="$(
      getent group "${AGENT_SERVICE_GROUP}" | awk -F: '{print $3}'
    )"
  fi
  if [[ "${user_exists}" == "1" ]]; then
    AGENT_SERVICE_UID="$(id -u "${AGENT_SERVICE_USER}")" || return 1
  fi
  if [[ "${group_exists}" != "1" ]]; then
    agent_local_identity_name_absent group "${AGENT_SERVICE_GROUP}" || return 1
    AGENT_SERVICE_GROUP_CREATE_INTENT="1"
    record_agent_service_account_transaction_marker || return 1
    if ! groupadd --system "${AGENT_SERVICE_GROUP}"; then
      clear_failed_agent_create_intent group || true
      return 1
    fi
    AGENT_SERVICE_GROUP_CREATED_THIS_RUN="1"
    AGENT_SERVICE_GID="$(agent_resolve_created_group_gid || true)"
    if [[ ! "${AGENT_SERVICE_GID}" =~ ^[1-9][0-9]*$ ]]; then
      compensate_unresolved_agent_create group || true
      return 1
    fi
    if ! record_agent_service_account_transaction_marker; then
      compensate_unresolved_agent_create group || true
      return 1
    fi
    AGENT_SERVICE_GROUP_CREATE_INTENT="0"
    if ! record_agent_service_account_transaction_marker; then
      AGENT_SERVICE_GROUP_CREATE_INTENT="1"
      compensate_unresolved_agent_create group || true
      return 1
    fi
  fi
  if [[ "${user_exists}" != "1" ]]; then
    agent_local_identity_name_absent user "${AGENT_SERVICE_USER}" || {
      fail_agent_service_account_creation
      return 1
    }
    nologin_shell="$(command -v nologin 2>/dev/null || true)"
    [[ -n "${nologin_shell}" ]] || nologin_shell="/usr/sbin/nologin"
    AGENT_SERVICE_USER_CREATE_INTENT="1"
    if ! record_agent_service_account_transaction_marker; then
      AGENT_SERVICE_USER_CREATE_INTENT="0"
      fail_agent_service_account_creation
      return 1
    fi
    if ! useradd --system --gid "${AGENT_SERVICE_GROUP}" \
      --home-dir /nonexistent --no-create-home --shell "${nologin_shell}" \
      "${AGENT_SERVICE_USER}"; then
      clear_failed_agent_create_intent user || true
      fail_agent_service_account_creation
      return 1
    fi
    AGENT_SERVICE_USER_CREATED_THIS_RUN="1"
    resolved_user_ids="$(agent_resolve_created_user_ids || true)"
    AGENT_SERVICE_UID="${resolved_user_ids%%:*}"
    resolved_user_gid="${resolved_user_ids##*:}"
    if [[ ! "${AGENT_SERVICE_UID}" =~ ^[1-9][0-9]*$ \
      || ! "${resolved_user_gid}" =~ ^[1-9][0-9]*$ \
      || "${resolved_user_gid}" != "${AGENT_SERVICE_GID}" ]]; then
      compensate_unresolved_agent_create user || true
      return 1
    fi
    if ! record_agent_service_account_transaction_marker; then
      compensate_unresolved_agent_create user || true
      return 1
    fi
    AGENT_SERVICE_USER_CREATE_INTENT="0"
    if ! record_agent_service_account_transaction_marker; then
      AGENT_SERVICE_USER_CREATE_INTENT="1"
      compensate_unresolved_agent_create user || true
      return 1
    fi
    if ! passwd -l "${AGENT_SERVICE_USER}" >/dev/null 2>&1; then
      fail_agent_service_account_creation
      return 1
    fi
  fi
  if ! validate_agent_service_account_identity; then
    err "realm-agent 服务账户不是严格 locked system identity"
    fail_agent_service_account_creation
    return 1
  fi
  if ! record_agent_service_account_transaction_marker; then
    fail_agent_service_account_creation
    return 1
  fi
  if [[ -e "${marker_path}" ]]; then
    if ! load_agent_service_account_marker; then
      fail_agent_service_account_creation
      return 1
    fi
  else
    AGENT_SERVICE_USER_MANAGED="${AGENT_SERVICE_USER_CREATED_THIS_RUN}"
    AGENT_SERVICE_GROUP_MANAGED="${AGENT_SERVICE_GROUP_CREATED_THIS_RUN}"
  fi
}

prepare_agent_config_boundary(){
  local config_dir=""
  local owner_uid="0"
  config_dir="$(agent_config_dir)"
  [[ -n "${AGENT_SERVICE_GID}" ]] || return 1
  if ! agent_sandbox_is_host_unit_dir; then
    owner_uid="$(id -u)"
  fi
  install -d -m 0750 "${config_dir}" || return 1
  chmod 0750 "${config_dir}" || return 1
  chown "${owner_uid}:${AGENT_SERVICE_GID}" "${config_dir}" || return 1
}

write_agent_service_account_marker(){
  local path=""
  local tmp=""
  local state="adopted"
  local owner_uid="0"
  local owner_gid="0"
  path="$(agent_service_account_marker_path)"
  if [[ "${AGENT_SERVICE_USER_MANAGED}" == "1" \
    || "${AGENT_SERVICE_GROUP_MANAGED}" == "1" ]]; then
    state="created"
  fi
  if ! agent_sandbox_is_host_unit_dir; then
    owner_uid="$(id -u)"
    owner_gid="$(id -g)"
  fi
  tmp="$(mktemp "$(dirname "${path}")/.service-account.XXXXXX")" || return 1
  register_cleanup_path "${tmp}"
  {
    printf 'VERSION=1\n'
    printf 'STATE=%s\n' "${state}"
    printf 'USER=%s\n' "${AGENT_SERVICE_USER}"
    printf 'GROUP=%s\n' "${AGENT_SERVICE_GROUP}"
    printf 'UID=%s\n' "${AGENT_SERVICE_UID}"
    printf 'GID=%s\n' "${AGENT_SERVICE_GID}"
    printf 'USER_CREATED=%s\n' "${AGENT_SERVICE_USER_MANAGED}"
    printf 'GROUP_CREATED=%s\n' "${AGENT_SERVICE_GROUP_MANAGED}"
  } > "${tmp}" || return 1
  chmod 0600 "${tmp}" || return 1
  chown "${owner_uid}:${owner_gid}" "${tmp}" || return 1
  mv -f "${tmp}" "${path}" || return 1
}

rollback_agent_service_account(){
  local marker="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state/service-account-created.env"
  local expected_uid=""
  local expected_gid=""
  local user_created=""
  local group_created=""
  [[ -f "${marker}" && ! -L "${marker}" ]] || return 0
  user_created="$(agent_service_account_marker_value "${marker}" USER_CREATED)"
  group_created="$(agent_service_account_marker_value "${marker}" GROUP_CREATED)"
  [[ "${user_created}" == "1" || "${group_created}" == "1" ]] || return 0
  expected_uid="$(agent_service_account_marker_value "${marker}" UID)"
  expected_gid="$(agent_service_account_marker_value "${marker}" GID)"
  remove_created_agent_service_identity \
    "${user_created}" "${group_created}" "${expected_uid}" "${expected_gid}"
}

agent_service_account_rollback_required(){
  local marker="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state/service-account-created.env"
  local user_created=""
  local group_created=""
  [[ -f "${marker}" && ! -L "${marker}" ]] || return 1
  user_created="$(agent_service_account_marker_value "${marker}" USER_CREATED)"
  group_created="$(agent_service_account_marker_value "${marker}" GROUP_CREATED)"
  [[ "${user_created}" == "1" || "${group_created}" == "1" ]]
}

secure_agent_secret_file(){
  local path="$1"
  local owner_uid="0"
  local owner_gid="0"
  [[ -f "${path}" && ! -L "${path}" ]] || return 0
  if ! agent_sandbox_is_host_unit_dir; then
    owner_uid="$(id -u)"
    owner_gid="$(id -g)"
  fi
  chmod 0600 "${path}" || return 1
  chown "${owner_uid}:${owner_gid}" "${path}" || return 1
}

agent_service_file_uid(){
  if agent_sandbox_is_host_unit_dir; then
    printf '%s' 0
  else
    id -u
  fi
}

agent_default_tls_dir(){
  printf '%s' "$(agent_config_dir)/certs"
}

validate_agent_tls_gateway_access(){
  local cert="$1"
  local key="$2"
  local python_bin=""
  python_bin="$(agent_contract_python || true)"
  [[ -n "${python_bin}" && -n "${AGENT_SERVICE_UID}" \
    && -n "${AGENT_SERVICE_GID}" ]] || return 1
  "${python_bin}" - "${cert}" "${key}" \
    "${AGENT_SERVICE_UID}" "${AGENT_SERVICE_GID}" <<'PY'
import os
import stat
import sys
from pathlib import Path

cert = Path(sys.argv[1])
key = Path(sys.argv[2])
uid = int(sys.argv[3])
gid = int(sys.argv[4])


def permission_bits(metadata):
    mode = stat.S_IMODE(metadata.st_mode)
    if metadata.st_uid == uid:
        return (mode >> 6) & 0o7
    if metadata.st_gid == gid:
        return (mode >> 3) & 0o7
    return mode & 0o7


def require_traverse(path):
    resolved_path = path.parent.resolve(strict=True) / path.name
    current = Path("/")
    for component in resolved_path.parent.parts[1:]:
        current /= component
        metadata = os.lstat(current)
        if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode):
            raise SystemExit(1)
        if not permission_bits(metadata) & 0o1:
            raise SystemExit(1)
    return resolved_path


for path in (cert, key):
    resolved_path = require_traverse(path)
    metadata = os.lstat(resolved_path)
    if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode):
        raise SystemExit(1)
    if not permission_bits(metadata) & 0o4:
        raise SystemExit(1)
PY
}

prepare_agent_tls_gateway_permissions(){
  local cert="$1"
  local key="$2"
  local owner_uid=""
  local parent=""
  local default_dir=""
  [[ -n "${AGENT_SERVICE_GID}" ]] || return 1
  owner_uid="$(agent_service_file_uid)"
  default_dir="$(agent_default_tls_dir)"
  for parent in "$(dirname "${cert}")" "$(dirname "${key}")"; do
    [[ ! -L "${parent}" && -d "${parent}" ]] || return 1
    if [[ "${parent}" == "${default_dir}" ]]; then
      chmod 0750 "${parent}" || return 1
      chown "${owner_uid}:${AGENT_SERVICE_GID}" "${parent}" || return 1
    fi
  done
  chmod 0644 "${cert}" || return 1
  chmod 0640 "${key}" || return 1
  chown "${owner_uid}:${AGENT_SERVICE_GID}" "${cert}" "${key}" || return 1
  validate_agent_tls_gateway_access "${cert}" "${key}"
}

write_agent_gateway_env(){
  local host="$1"
  local port="$2"
  local transport="$3"
  local cert="$4"
  local key="$5"
  local server_name="$6"
  local verify_peer="$7"
  local ca_cert="$8"
  local cert_sha256="$9"
  local insecure_non_loopback="${10:-0}"
  local target=""
  local tmp=""
  local owner_uid="0"
  target="$(agent_gateway_env_path)"
  [[ -n "${AGENT_SERVICE_GID}" ]] || return 1
  if ! agent_sandbox_is_host_unit_dir; then
    owner_uid="$(id -u)"
  fi
  tmp="$(mktemp "$(dirname "${target}")/.gateway.env.XXXXXX")" || return 1
  register_cleanup_path "${tmp}"
  {
    printf 'REALM_AGENT_HOST=%s\n' "$(strip_env_value "${host}")"
    printf 'REALM_AGENT_PORT=%s\n' "$(strip_env_value "${port}")"
    printf 'REALM_AGENT_TRANSPORT=%s\n' "$(strip_env_value "${transport}")"
    printf 'REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK=%s\n' \
      "$(strip_env_value "${insecure_non_loopback}")"
    printf 'REALM_AGENT_PRIVILEGED_SOCKET=/run/realm-agent-privileged.sock\n'
    printf 'REALM_AGENT_GATEWAY_MAX_REQUEST_BODY_BYTES=%s\n' \
      "$(strip_env_value "${REALM_AGENT_GATEWAY_MAX_REQUEST_BODY_BYTES:-67108864}")"
    printf 'REALM_AGENT_GATEWAY_UPSTREAM_TIMEOUT_SECONDS=%s\n' \
      "$(strip_env_value "${REALM_AGENT_GATEWAY_UPSTREAM_TIMEOUT_SECONDS:-300}")"
    printf 'REALM_AGENT_SSL_CERT=%s\n' "$(strip_env_value "${cert}")"
    printf 'REALM_AGENT_SSL_KEY=%s\n' "$(strip_env_value "${key}")"
    printf 'REALM_AGENT_TLS_SERVER_NAME=%s\n' "$(strip_env_value "${server_name}")"
    printf 'REALM_AGENT_TLS_VERIFY_PEER=%s\n' "$(strip_env_value "${verify_peer}")"
    printf 'REALM_AGENT_TLS_CA_CERT=%s\n' "$(strip_env_value "${ca_cert}")"
    printf 'REALM_AGENT_TLS_CERT_SHA256=%s\n' "$(strip_env_value "${cert_sha256}")"
  } > "${tmp}" || return 1
  chmod 0640 "${tmp}" || return 1
  chown "${owner_uid}:${AGENT_SERVICE_GID}" "${tmp}" || return 1
  mv -f "${tmp}" "${target}" || return 1
}

realm_config_dir(){
  printf '%s' "${REALM_AGENT_REALM_CONFIG_DIR:-/etc/realm}"
}

agent_sysctl_dir(){
  printf '%s' "${REALM_AGENT_SYSCTL_DIR:-/etc/sysctl.d}"
}

agent_apt_config_dir(){
  printf '%s' "${REALM_AGENT_APT_CONFIG_DIR:-/etc/apt/apt.conf.d}"
}

agent_local_bin_dir(){
  printf '%s' "${REALM_AGENT_LOCAL_BIN_DIR:-/usr/local/bin}"
}

agent_libexec_dir(){
  if [[ -n "${REALM_AGENT_LIBEXEC_DIR:-}" ]]; then
    printf '%s' "${REALM_AGENT_LIBEXEC_DIR}"
  elif declare -F agent_sandbox_is_host_unit_dir >/dev/null 2>&1 \
    && ! agent_sandbox_is_host_unit_dir; then
    printf '%s/.realm-agent-libexec' "$(dirname "$(agent_systemd_dir)")"
  else
    printf '%s' /usr/local/libexec
  fi
}

agent_base_dir(){
  printf '%s' "${REALM_AGENT_BASE_DIR:-/opt/realm-agent}"
}

agent_recovery_installer_path(){
  local version="${VERSION:-}"
  is_safe_systemd_value "${version}" || return 1
  printf '%s/realm-agent-installer-%s.sh' "$(agent_libexec_dir)" "${version}"
}

agent_recovery_unit_path(){
  printf '%s/%s' "$(agent_systemd_dir)" \
    "realm-agent-install-recovery.service"
}

agent_recovery_systemd_path_valid(){
  local path="${1:-}"
  [[ "${path}" =~ ^/[A-Za-z0-9_./:@%+-]+$ ]] || return 1
  [[ "${path}" != *"//"* \
    && "${path}" != *"/../"* && "${path}" != */.. \
    && "${path}" != *"/./"* && "${path}" != */. ]]
}

agent_escape_systemd_path(){
  local path="${1:-}"
  agent_recovery_systemd_path_valid "${path}" || return 1
  printf '%s' "${path//%/%%}"
}

install_agent_recovery_support(){
  local stage="${1:-}"
  local tls_cert="${2:-${AGENT_INSTALL_SSL_CERT:-}}"
  local tls_key="${3:-${AGENT_INSTALL_SSL_KEY:-}}"
  local source=""
  local recovery_path=""
  local recovery_dir=""
  local unit_source=""
  local unit_path=""
  local unit_tmp=""
  local recovery_tmp=""
  local rollback_parent=""
  local lock_path=""
  local config_dir=""
  local realm_dir=""
  local systemd_dir=""
  local sysctl_dir=""
  local local_bin_dir=""
  local base_dir=""
  local pool_version_state_file=""
  local tls_path=""
  local writable_path=""
  local rendered_writable_path=""
  local writable_paths=""
  local rendered_recovery_path=""
  local rendered_rollback_parent=""
  local rendered_lock_path=""
  local rendered_config_dir=""
  local -a writable_path_candidates=()

  source="${REALM_AGENT_INSTALLER_SOURCE:-${BASH_SOURCE[0]}}"
  recovery_path="$(agent_recovery_installer_path)"
  recovery_dir="$(dirname "${recovery_path}")"
  unit_path="$(agent_recovery_unit_path)"
  unit_source="${stage}/agent/systemd/realm-agent-install-recovery.service"
  rollback_parent="$(agent_deploy_transaction_parent)" || return 1
  lock_path="$(agent_install_lock_path)" || return 1
  config_dir="$(agent_config_dir)"
  realm_dir="$(realm_config_dir)"
  systemd_dir="$(agent_systemd_dir)"
  sysctl_dir="$(agent_sysctl_dir)"
  local_bin_dir="$(agent_local_bin_dir)"
  base_dir="$(agent_base_dir)"
  pool_version_state_file="$(agent_pool_version_state_file)" || return 1
  [[ -f "${source}" && ! -L "${source}" ]] || {
    err "无法定位当前 Agent 安装器，拒绝安装启动恢复支持：${source}"
    return 1
  }
  [[ -f "${unit_source}" && ! -L "${unit_source}" ]] || {
    err "更新包缺少启动恢复 systemd unit：${unit_source}"
    return 1
  }
  agent_recovery_systemd_path_valid "${recovery_path}" || {
    err "启动恢复安装器路径含非法 systemd 字符：${recovery_path}"
    return 1
  }
  agent_recovery_systemd_path_valid "${rollback_parent}" || {
    err "Agent rollback parent 含非法 systemd 字符：${rollback_parent}"
    return 1
  }
  agent_recovery_systemd_path_valid "${lock_path}" || {
    err "Agent 安装锁路径含非法 systemd 字符：${lock_path}"
    return 1
  }
  agent_recovery_systemd_path_valid "${config_dir}" || {
    err "Agent 配置目录含非法 systemd 字符：${config_dir}"
    return 1
  }
  rendered_recovery_path="$(agent_escape_systemd_path "${recovery_path}")" \
    || return 1
  rendered_rollback_parent="$(agent_escape_systemd_path "${rollback_parent}")" \
    || return 1
  rendered_lock_path="$(agent_escape_systemd_path "${lock_path}")" || return 1
  rendered_config_dir="$(agent_escape_systemd_path "${config_dir}")" || return 1
  writable_path_candidates=(
    "$(dirname "${lock_path}")"
    "${rollback_parent}"
    "${config_dir}"
    "${realm_dir}"
    "${systemd_dir}"
    "${sysctl_dir}"
    "${local_bin_dir}"
    "${recovery_dir}"
    "${base_dir}"
    "$(dirname "${pool_version_state_file}")"
  )
  for tls_path in "${tls_cert}" "${tls_key}"; do
    [[ -n "${tls_path}" ]] || continue
    writable_path_candidates+=("$(dirname "${tls_path}")")
  done
  for writable_path in "${writable_path_candidates[@]}"; do
    [[ "${writable_path}" != "/" ]] || continue
    if ! agent_recovery_systemd_path_valid "${writable_path}"; then
      err "Agent 启动恢复可写路径无效：${writable_path}"
      return 1
    fi
    rendered_writable_path="$(agent_escape_systemd_path "${writable_path}")" \
      || return 1
    case " ${writable_paths} " in
      *" -${rendered_writable_path} "*) ;;
      *)
        writable_paths="${writable_paths:+${writable_paths} }-${rendered_writable_path}"
        ;;
    esac
  done
  install -d -m 755 "${recovery_dir}" "$(dirname "${unit_path}")" || return 1
  [[ -d "${recovery_dir}" && ! -L "${recovery_dir}" ]] || {
    err "启动恢复安装器目录不可信：${recovery_dir}"
    return 1
  }
  recovery_tmp="$(mktemp "${recovery_path}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${recovery_tmp}"
  unit_tmp="$(mktemp "${unit_path}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${unit_tmp}"
  if ! install -m 0755 "${source}" "${recovery_tmp}" \
    || ! mv -f "${recovery_tmp}" "${recovery_path}" \
    || ! sed \
      -e "s|/usr/local/libexec/realm-agent-installer.sh|${rendered_recovery_path}|g" \
      -e "s|/var/lib/nexus/agent-update|${rendered_rollback_parent}|g" \
      -e "s|/run/lock/nexus-agent-install.lock|${rendered_lock_path}|g" \
      -e "s|/etc/realm-agent|${rendered_config_dir}|g" \
      -e "s|^ReadWritePaths=.*$|ReadWritePaths=${writable_paths}|g" \
      "${unit_source}" > "${unit_tmp}" \
    || ! chmod 0644 "${unit_tmp}" \
    || ! mv -f "${unit_tmp}" "${unit_path}"; then
    rm -f "${recovery_tmp}" "${unit_tmp}" >/dev/null 2>&1 || true
    err "无法持久化 Agent 启动恢复支持"
    return 1
  fi
  if command_exists systemctl; then
    systemctl daemon-reload || return 1
    systemctl enable realm-agent-install-recovery.service >/dev/null 2>&1 \
      || {
        err "无法启用 Agent 启动恢复 systemd unit"
        return 1
      }
  fi
}

validate_agent_transaction_tls_extension(){
  local requested_cert="${1:-}"
  local requested_key="${2:-}"
  local recorded_cert="${REALM_AGENT_ROLLBACK_TLS_CERT:-}"
  local recorded_key="${REALM_AGENT_ROLLBACK_TLS_KEY:-}"
  local cert_snapshotted="${REALM_AGENT_ROLLBACK_TLS_CERT_SNAPSHOTTED:-0}"
  local key_snapshotted="${REALM_AGENT_ROLLBACK_TLS_KEY_SNAPSHOTTED:-0}"
  if [[ "${cert_snapshotted}" == "1" ]]; then
    if [[ -z "${recorded_cert}" \
      || ( -n "${requested_cert}" && "${requested_cert}" != "${recorded_cert}" ) ]]; then
      err "active transaction 的 TLS certificate 路径发生漂移"
      return 1
    fi
  elif [[ "${cert_snapshotted}" != "0" || -n "${recorded_cert}" ]]; then
    err "active transaction 的 TLS certificate 快照状态不一致"
    return 1
  fi
  if [[ "${key_snapshotted}" == "1" ]]; then
    if [[ -z "${recorded_key}" \
      || ( -n "${requested_key}" && "${requested_key}" != "${recorded_key}" ) ]]; then
      err "active transaction 的 TLS key 路径发生漂移"
      return 1
    fi
  elif [[ "${key_snapshotted}" != "0" || -n "${recorded_key}" ]]; then
    err "active transaction 的 TLS key 快照状态不一致"
    return 1
  fi
}

prepare_agent_recovery_support_for_transaction(){
  local stage="$1"
  local base="$2"
  local requested_cert="${3:-}"
  local requested_key="${4:-}"
  local recovery_cert="${requested_cert}"
  local recovery_key="${requested_key}"
  if [[ "${REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE:-0}" == "1" ]]; then
    if [[ "${REALM_AGENT_DEPLOY_ROLLBACK_BASE:-}" != "${base}" ]]; then
      err "Agent transaction base 与更新目标不一致"
      return 1
    fi
    validate_agent_transaction_tls_extension \
      "${requested_cert}" "${requested_key}" || return 1
    recovery_cert="${REALM_AGENT_ROLLBACK_TLS_CERT:-${requested_cert}}"
    recovery_key="${REALM_AGENT_ROLLBACK_TLS_KEY:-${requested_key}}"
  fi
  install_agent_recovery_support \
    "${stage}" "${recovery_cert}" "${recovery_key}"
}

verify_installed_agent_release_version(){
  local base=""
  local version_file=""
  local expected="${VERSION#v}"
  local actual=""
  base="$(agent_base_dir)"
  version_file="${base}/agent/app/version.py"
  if [[ ! -f "${version_file}" ]]; then
    err "Agent 版本文件不存在：${version_file}"
    return 1
  fi
  actual="$(
    sed -n \
      's/^AGENT_VERSION = "\([0-9][0-9]*\)"$/\1/p' \
      "${version_file}" \
      | head -n 1
  )"
  if [[ -z "${actual}" || "${actual}" != "${expected}" ]]; then
    err "Agent 安装后版本不匹配：期望 ${expected}，实际 ${actual:-unknown}"
    return 1
  fi
}

find_phase1_contract_python(){
  trusted_agent_bootstrap_python
}

agent_contract_python(){
  local selected="${AGENT_CONTRACT_PYTHON:-}"
  if [[ -n "${selected}" ]] && probe_python_runtime "${selected}"; then
    printf '%s' "${selected}"
    return 0
  fi
  find_phase1_contract_python
}

is_agent_loopback_host(){
  local host="${1:-}"
  local python_bin=""
  python_bin="$(agent_contract_python || true)"
  [[ -n "${python_bin}" ]] || return 1
  "${python_bin}" - "${host}" <<'PY' >/dev/null
import ipaddress
import sys

host = str(sys.argv[1] or "").strip().lower().rstrip(".")
if host == "localhost":
    raise SystemExit(0)
if host.startswith("[") and host.endswith("]"):
    host = host[1:-1].strip()
try:
    address = ipaddress.ip_address(host.split("%", 1)[0])
except ValueError:
    raise SystemExit(1)
raise SystemExit(0 if address.is_loopback else 1)
PY
}

validate_agent_bind_contract(){
  local host="${1:-}"
  local port="${2:-}"
  local transport="${3:-}"
  local insecure_override="${4:-0}"
  local normalized_host=""
  local normalized_transport=""
  local normalized_insecure_override=""

  if ! normalized_host="$(normalize_agent_bind_host "${host}")"; then
    err "Agent 监听地址含非法字符：${host}"
    return 1
  fi
  if [[ "${normalized_host}" != "${host}" ]]; then
    err "Agent 监听地址未规范化：${host}"
    return 1
  fi
  if [[ ! "${port}" =~ ^[0-9]+$ || ${#port} -gt 5 ]] \
    || (( 10#${port} < 1 || 10#${port} > 65535 )); then
    err "Agent 端口无效：${port}"
    return 1
  fi
  if ! normalized_transport="$(normalize_agent_transport "${transport}")"; then
    err "Agent 传输类型仅支持 http 或 https：${transport}"
    return 1
  fi
  if ! normalized_insecure_override="$(
    normalize_tls_auto_generate "${insecure_override}"
  )"; then
    err "REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK 仅支持 0/1 或布尔值"
    return 1
  fi
  if [[ "${normalized_transport}" == "http" ]] \
    && ! is_agent_loopback_host "${normalized_host}"; then
    if [[ "${normalized_insecure_override}" == "1" ]]; then
      warn "已启用高风险 REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK=1："
      warn "Agent 将以明文 HTTP 绑定非 loopback 地址 ${normalized_host}:${port}"
      return 0
    fi
    err "拒绝非 loopback 明文 HTTP Agent：${normalized_host}:${port}"
    err "请改用 HTTPS、通过反向通道访问 loopback Agent，或显式设置 REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK=1"
    return 1
  fi
}

read_agent_unit_contract(){
  local unit_path="$1"
  local parsed=""
  local python_bin=""
  local transport=""
  local host=""
  local port=""
  local cert=""
  local key=""

  [[ -f "${unit_path}" && ! -L "${unit_path}" ]] || return 1
  python_bin="$(agent_contract_python || true)"
  if [[ -z "${python_bin}" ]]; then
    err "缺少 Python 3.9+，暂时无法完整解析旧 Agent unit：${unit_path}"
    return 1
  fi
  if ! parsed="$("${python_bin}" - "${unit_path}" <<'PY'
import re
import shlex
import sys
from pathlib import Path

path = Path(sys.argv[1])
try:
    text = path.read_text(encoding="utf-8", errors="strict")
except Exception as exc:
    raise SystemExit(f"cannot read legacy Agent unit {path}: {exc}")


def logical_lines(value):
    output = []
    pending = ""
    for physical in value.splitlines():
        line = physical.rstrip()
        continued = line.endswith("\\")
        fragment = line[:-1] if continued else line
        pending = f"{pending}{fragment}" if pending else fragment
        if continued:
            pending += " "
            continue
        output.append(pending)
        pending = ""
    if pending:
        output.append(pending)
    return output


def words(value):
    try:
        return shlex.split(value, posix=True)
    except ValueError as exc:
        raise SystemExit(f"invalid quoting in legacy Agent unit {path}: {exc}")


def assignment(token):
    if "=" not in token:
        return None
    name, value = token.split("=", 1)
    if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
        return None
    return name, value


env = {}
exec_lines = []
for line in logical_lines(text):
    raw = line.strip()
    if not raw or raw.startswith("#"):
        continue
    if raw.startswith("Environment="):
        value = raw.split("=", 1)[1].strip()
        if not value:
            env.clear()
            continue
        for token in words(value):
            item = assignment(token)
            if item is not None:
                env[item[0]] = item[1]
    elif raw.startswith("ExecStart="):
        value = raw.split("=", 1)[1].strip()
        if not value:
            exec_lines.clear()
            continue
        exec_lines.append(value)


var_re = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)")


def expand(value):
    def replace(match):
        name = match.group(1) or match.group(2) or ""
        return env.get(name, match.group(0))

    return var_re.sub(replace, value)


def option(argv, name):
    result = ""
    index = 0
    prefix = f"{name}="
    while index < len(argv):
        token = argv[index]
        if token.startswith(prefix):
            result = token[len(prefix):].strip()
            index += 1
            continue
        if token == name:
            if index + 1 < len(argv) and not argv[index + 1].startswith("--"):
                result = argv[index + 1].strip()
                index += 2
                continue
        index += 1
    return result


host = str(env.get("REALM_AGENT_HOST") or "").strip()
port = str(env.get("REALM_AGENT_PORT") or "").strip()
cert = str(env.get("REALM_AGENT_SSL_CERT") or "").strip()
key = str(env.get("REALM_AGENT_SSL_KEY") or "").strip()
has_ssl_cert_option = False
has_ssl_key_option = False

for command in exec_lines:
    argv = words(expand(command))
    value = option(argv, "--host")
    if value:
        host = value
    value = option(argv, "--port")
    if value:
        port = value
    value = option(argv, "--ssl-certfile")
    if value:
        cert = value
        has_ssl_cert_option = True
    value = option(argv, "--ssl-keyfile")
    if value:
        key = value
        has_ssl_key_option = True

if has_ssl_cert_option != has_ssl_key_option:
    raise SystemExit(f"legacy Agent unit {path} has an incomplete TLS ExecStart")

transport = "https" if (
    has_ssl_cert_option
    or has_ssl_key_option
    or path.name == "realm-agent-https.service"
) else "http"

if "$" in host or "$" in port or "$" in cert or "$" in key:
    raise SystemExit(f"legacy Agent unit {path} contains unresolved variables")
if port and (not port.isdigit() or not 1 <= int(port) <= 65535):
    raise SystemExit(f"legacy Agent unit {path} contains an invalid port")
for value in (transport, host, port, cert, key):
    if "|" in value or any(ord(char) < 32 or ord(char) == 127 for char in value):
        raise SystemExit(f"legacy Agent unit {path} contains unsafe values")

print("|".join((transport, host, port, cert, key)))
PY
  )"; then
    err "无法安全解析旧 Agent systemd unit：${unit_path}"
    return 1
  fi
  IFS='|' read -r transport host port cert key <<< "${parsed}"
  AGENT_UNIT_TRANSPORT="${transport}"
  AGENT_UNIT_HOST="${host}"
  AGENT_UNIT_PORT="${port}"
  AGENT_UNIT_SSL_CERT="${cert}"
  AGENT_UNIT_SSL_KEY="${key}"
}

discover_legacy_agent_contract(){
  local preferred_transport="${1:-}"
  local systemd_dir=""
  local http_unit=""
  local https_unit=""
  local chosen=""
  local http_active="0"
  local https_active="0"
  local http_enabled="0"
  local https_enabled="0"

  LEGACY_AGENT_SERVICE=""
  LEGACY_AGENT_TRANSPORT=""
  LEGACY_AGENT_HOST=""
  LEGACY_AGENT_PORT=""
  LEGACY_AGENT_SSL_CERT=""
  LEGACY_AGENT_SSL_KEY=""

  systemd_dir="$(agent_systemd_dir)"
  http_unit="${systemd_dir}/realm-agent.service"
  https_unit="${systemd_dir}/realm-agent-https.service"
  if [[ ! -f "${http_unit}" && ! -f "${https_unit}" ]]; then
    return 0
  fi

  if command_exists systemctl; then
    if [[ -f "${http_unit}" ]] \
      && systemctl is-active --quiet realm-agent.service 2>/dev/null; then
      http_active="1"
    fi
    if [[ -f "${https_unit}" ]] \
      && systemctl is-active --quiet realm-agent-https.service 2>/dev/null; then
      https_active="1"
    fi
    if [[ "${http_active}" == "1" && "${https_active}" == "1" ]]; then
      err "检测到 HTTP/HTTPS Agent 服务同时运行，无法安全判断旧监听契约"
      return 1
    fi
    if [[ "${http_active}" == "1" ]]; then
      chosen="${http_unit}"
    elif [[ "${https_active}" == "1" ]]; then
      chosen="${https_unit}"
    fi
  fi

  if [[ -z "${chosen}" && -n "${preferred_transport}" ]]; then
    if [[ "${preferred_transport}" == "https" && -f "${https_unit}" ]]; then
      chosen="${https_unit}"
    elif [[ "${preferred_transport}" == "http" && -f "${http_unit}" ]]; then
      chosen="${http_unit}"
    fi
  fi

  if [[ -z "${chosen}" && -f "${http_unit}" && ! -f "${https_unit}" ]]; then
    chosen="${http_unit}"
  elif [[ -z "${chosen}" && -f "${https_unit}" && ! -f "${http_unit}" ]]; then
    chosen="${https_unit}"
  fi

  if [[ -z "${chosen}" ]] && command_exists systemctl; then
    if [[ -f "${http_unit}" ]] \
      && systemctl is-enabled --quiet realm-agent.service 2>/dev/null; then
      http_enabled="1"
    fi
    if [[ -f "${https_unit}" ]] \
      && systemctl is-enabled --quiet realm-agent-https.service 2>/dev/null; then
      https_enabled="1"
    fi
    if [[ "${http_enabled}" == "1" && "${https_enabled}" == "1" ]]; then
      err "HTTP/HTTPS Agent 服务均已启用，无法安全判断旧服务类型"
      return 1
    fi
    if [[ "${http_enabled}" == "1" ]]; then
      chosen="${http_unit}"
    elif [[ "${https_enabled}" == "1" ]]; then
      chosen="${https_unit}"
    fi
  fi

  if [[ -z "${chosen}" ]]; then
    err "同时发现 realm-agent.service 与 realm-agent-https.service，但无法确定旧服务类型"
    err "请显式设置 REALM_AGENT_TRANSPORT=http 或 https 后重试"
    return 1
  fi

  if ! read_agent_unit_contract "${chosen}"; then
    return 1
  fi
  LEGACY_AGENT_SERVICE="$(basename "${chosen}")"
  LEGACY_AGENT_TRANSPORT="${AGENT_UNIT_TRANSPORT}"
  LEGACY_AGENT_HOST="${AGENT_UNIT_HOST}"
  LEGACY_AGENT_PORT="${AGENT_UNIT_PORT}"
  LEGACY_AGENT_SSL_CERT="${AGENT_UNIT_SSL_CERT}"
  LEGACY_AGENT_SSL_KEY="${AGENT_UNIT_SSL_KEY}"
}

validate_agent_tls_path(){
  local path="${1:-}"
  [[ "${path}" =~ ^/[A-Za-z0-9_./:@%+-]+$ ]] || return 1
  [[ "${path}" != *"/../"* && "${path}" != */.. ]] || return 1
}

normalize_tls_auto_generate(){
  local raw
  raw="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')"
  case "${raw}" in
    1|true|yes|on)
      printf '1'
      ;;
    0|false|no|off|"")
      printf '0'
      ;;
    *)
      return 1
      ;;
  esac
}

normalize_agent_address_family(){
  local raw
  raw="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')"
  case "${raw}" in
    ""|explicit|ipv4|ipv6|dual)
      printf '%s' "${raw}"
      ;;
    *)
      return 1
      ;;
  esac
}

validate_agent_tls_cert_sha256(){
  local value="${1:-}"
  [[ -z "${value}" || "${value}" =~ ^[0-9a-f]{64}$ ]]
}

normalize_agent_tls_server_name(){
  local raw="${1:-}"
  local name=""
  name="$(strip_env_value "${raw}")"
  [[ "${name}" == "${raw}" ]] || return 1
  name="${name%.}"
  [[ -n "${name}" ]] || return 1
  case "${name}" in
    "*"|"0.0.0.0"|"::"|"[::]")
      return 1
      ;;
  esac
  [[ "${name}" =~ ^[A-Za-z0-9._:-]+$ ]] || return 1
  printf '%s' "${name}"
}

validate_agent_dual_stack_bind_policy(){
  local bind_host="${1:-}"
  local address_family="${2:-}"
  local bindv6only=""
  [[ "${address_family}" == "dual" ]] || return 0
  if [[ "${bind_host}" != "::" ]]; then
    err "双栈地址族策略仅支持显式 :: wildcard 监听"
    return 1
  fi
  bindv6only="$(get_bindv6only)"
  if [[ "${bindv6only}" == "1" ]]; then
    err "节点同时使用 A/AAAA，但本机 bindv6only=1；单个 :: socket 会丢失 IPv4"
    err "请改为单地址族 DNS/明确 IPv4 或 IPv6 监听后重试"
    return 1
  fi
}

validate_agent_target_api_key(){
  local value="${1:-}"
  (( ${#value} >= 8 && ${#value} <= 256 )) \
    && [[ "${value}" =~ ^[A-Za-z0-9._~:/+=-]+$ ]]
}

validate_agent_api_key_version(){
  local value="${1:-}"
  [[ "${value}" =~ ^[0-9a-f]{64}$ ]]
}

compute_agent_api_key_version(){
  local value="${1:-}"
  if command_exists sha256sum; then
    printf '%s' "${value}" | sha256sum | awk '{print $1}'
  elif command_exists shasum; then
    printf '%s' "${value}" | shasum -a 256 | awk '{print $1}'
  elif command_exists openssl; then
    printf '%s' "${value}" \
      | openssl dgst -sha256 -r 2>/dev/null \
      | awk '{print $1}'
  else
    return 1
  fi
}

agent_api_key_file_version(){
  local path="${1:-$(agent_api_key_path)}"
  local expected_uid="${2:-0}"
  local expected_gid="${3:-0}"
  local value=""
  if ! validate_agent_api_key_file \
    "${path}" "${expected_uid}" "${expected_gid}" >/dev/null 2>&1; then
    return 1
  fi
  IFS= read -r value < "${path}" || return 1
  compute_agent_api_key_version "${value}"
}

capture_agent_target_api_key(){
  local value=""
  local version=""
  if [[ "${REALM_AGENT_TARGET_API_KEY+x}" != "x" ]]; then
    return 0
  fi
  value="${REALM_AGENT_TARGET_API_KEY:-}"
  if ! validate_agent_target_api_key "${value}"; then
    err "join 目标 API key 必须是 8-256 位安全 ASCII 字符"
    return 1
  fi
  version="${REALM_AGENT_TARGET_API_KEY_VERSION:-}"
  if [[ -n "${version}" ]] && ! validate_agent_api_key_version "${version}"; then
    err "join 目标 API key version 必须是 64 位小写十六进制 SHA-256"
    return 1
  fi
  REALM_AGENT_PENDING_TARGET_API_KEY="${value}"
  REALM_AGENT_PENDING_TARGET_API_KEY_SET="1"
  REALM_AGENT_PENDING_TARGET_API_KEY_VERSION="${version}"
  unset REALM_AGENT_TARGET_API_KEY REALM_AGENT_TARGET_API_KEY_VERSION
}

agent_target_api_key_is_set(){
  [[ "${REALM_AGENT_PENDING_TARGET_API_KEY_SET:-0}" == "1" \
    || "${REALM_AGENT_TARGET_API_KEY+x}" == "x" ]]
}

agent_target_api_key_value(){
  if [[ "${REALM_AGENT_PENDING_TARGET_API_KEY_SET:-0}" == "1" ]]; then
    printf '%s' "${REALM_AGENT_PENDING_TARGET_API_KEY}"
  else
    printf '%s' "${REALM_AGENT_TARGET_API_KEY:-}"
  fi
}

agent_target_api_key_version(){
  if [[ "${REALM_AGENT_PENDING_TARGET_API_KEY_SET:-0}" == "1" ]]; then
    printf '%s' "${REALM_AGENT_PENDING_TARGET_API_KEY_VERSION:-}"
  else
    printf '%s' "${REALM_AGENT_TARGET_API_KEY_VERSION:-}"
  fi
}

phase1_known_loopback_host(){
  local host="${1:-}"
  host="$(printf '%s' "${host}" | tr '[:upper:]' '[:lower:]')"
  case "${host}" in
    localhost|127.0.0.1|::1)
      return 0
      ;;
  esac
  return 1
}

phase1_reject_ambiguous_legacy_units(){
  local preferred_transport="${1:-}"
  local systemd_dir=""
  local http_unit=""
  local https_unit=""
  local http_active="0"
  local https_active="0"
  local http_enabled="0"
  local https_enabled="0"

  systemd_dir="$(agent_systemd_dir)"
  http_unit="${systemd_dir}/realm-agent.service"
  https_unit="${systemd_dir}/realm-agent-https.service"
  [[ -f "${http_unit}" && -f "${https_unit}" ]] || return 0

  if command_exists systemctl; then
    systemctl is-active --quiet realm-agent.service 2>/dev/null \
      && http_active="1"
    systemctl is-active --quiet realm-agent-https.service 2>/dev/null \
      && https_active="1"
  fi
  if [[ "${http_active}" == "1" && "${https_active}" == "1" ]]; then
    err "检测到 HTTP/HTTPS Agent 服务同时运行，拒绝在依赖安装前修改系统"
    return 1
  fi
  if [[ "${http_active}" == "1" || "${https_active}" == "1" ]]; then
    return 0
  fi
  if [[ "${preferred_transport}" == "http" || "${preferred_transport}" == "https" ]]; then
    return 0
  fi

  if command_exists systemctl; then
    systemctl is-enabled --quiet realm-agent.service 2>/dev/null \
      && http_enabled="1"
    systemctl is-enabled --quiet realm-agent-https.service 2>/dev/null \
      && https_enabled="1"
  fi
  if [[ "${http_enabled}" == "1" && "${https_enabled}" == "1" ]]; then
    err "HTTP/HTTPS Agent 服务均已启用，拒绝在依赖安装前修改系统"
    return 1
  fi
  if [[ "${http_enabled}" == "1" || "${https_enabled}" == "1" ]]; then
    return 0
  fi
  err "同时发现 HTTP/HTTPS Agent unit，但没有明确 transport/active/enabled 选择"
  return 1
}

phase1_validate_explicit_agent_contract(){
  local explicit_host="${1:-}"
  local explicit_port="${2:-}"
  local explicit_transport="${3:-}"
  local normalized_host=""
  local normalized_transport=""
  local normalized_auto=""
  local normalized_verify_peer=""
  local address_family=""
  local cert=""
  local key=""
  local ca_cert=""
  local cert_sha256=""
  local existing_insecure_override=""
  local insecure_override=""

  existing_insecure_override="$(
    read_env_value \
      "$(agent_config_dir)/agent.env" \
      "REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK" || true
  )"
  if ! insecure_override="$(
    normalize_tls_auto_generate \
      "${REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK:-${existing_insecure_override:-0}}"
  )"; then
    err "REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK 仅支持 0/1 或布尔值"
    return 1
  fi

  if [[ -n "${explicit_host}" ]]; then
    if ! normalized_host="$(normalize_agent_bind_host "${explicit_host}")" \
      || [[ "${normalized_host}" != "${explicit_host}" ]]; then
      err "显式 REALM_AGENT_HOST 非法：${explicit_host}"
      return 1
    fi
  fi
  if [[ -n "${explicit_port}" ]] \
    && { [[ ! "${explicit_port}" =~ ^[0-9]+$ || ${#explicit_port} -gt 5 ]] \
      || (( 10#${explicit_port} < 1 || 10#${explicit_port} > 65535 )); }; then
    err "显式 REALM_AGENT_PORT 无效：${explicit_port}"
    return 1
  fi
  if [[ -n "${explicit_transport}" ]]; then
    if ! normalized_transport="$(normalize_agent_transport "${explicit_transport}")"; then
      err "显式 REALM_AGENT_TRANSPORT 仅支持 http 或 https"
      return 1
    fi
  fi
  if [[ "${normalized_transport}" == "http" && -n "${normalized_host}" ]]; then
    if [[ -n "${AGENT_CONTRACT_PYTHON:-}" ]]; then
      if ! is_agent_loopback_host "${normalized_host}" \
        && [[ "${insecure_override}" != "1" ]]; then
        err "拒绝显式非 loopback 明文 HTTP Agent：${normalized_host}:${explicit_port:-${DEFAULT_PORT}}"
        err "如确需承担风险，请显式设置 REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK=1"
        return 1
      fi
    elif ! phase1_known_loopback_host "${normalized_host}" \
      && [[ "${insecure_override}" != "1" ]]; then
      err "缺少 Python 时仅接受 localhost/127.0.0.1/::1 的显式明文 HTTP 监听"
      err "如确需承担风险，请显式设置 REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK=1"
      return 1
    fi
  fi
  if ! address_family="$(
    normalize_agent_address_family "${REALM_AGENT_ADDRESS_FAMILY:-}"
  )"; then
    err "REALM_AGENT_ADDRESS_FAMILY 仅支持 explicit/ipv4/ipv6/dual"
    return 1
  fi
  if [[ -n "${normalized_host}" ]] \
    && ! validate_agent_dual_stack_bind_policy \
      "${normalized_host}" "${address_family}"; then
    return 1
  fi
  if [[ "${normalized_transport}" == "https" ]]; then
    cert="${REALM_AGENT_SSL_CERT:-$(agent_config_dir)/certs/server.crt}"
    key="${REALM_AGENT_SSL_KEY:-$(agent_config_dir)/certs/server.key}"
    if [[ -n "${REALM_AGENT_TLS_SERVER_NAME:-}" ]]; then
      if ! normalize_agent_tls_server_name \
        "${REALM_AGENT_TLS_SERVER_NAME}" >/dev/null; then
        err "REALM_AGENT_TLS_SERVER_NAME 为空、unspecified 或含非法字符"
        return 1
      fi
    elif [[ -z "${normalized_host}" \
      || "${normalized_host}" == "0.0.0.0" || "${normalized_host}" == "::" ]]; then
      err "显式 HTTPS wildcard 监听必须提供非 unspecified TLS server name"
      return 1
    fi
    if ! normalized_auto="$(
      normalize_tls_auto_generate "${REALM_AGENT_TLS_AUTO_GENERATE:-0}"
    )"; then
      err "REALM_AGENT_TLS_AUTO_GENERATE 仅支持 0/1 或布尔值"
      return 1
    fi
    if ! normalized_verify_peer="$(
      normalize_tls_auto_generate "${REALM_AGENT_TLS_VERIFY_PEER:-0}"
    )"; then
      err "REALM_AGENT_TLS_VERIFY_PEER 仅支持 0/1 或布尔值"
      return 1
    fi
    ca_cert="${REALM_AGENT_TLS_CA_CERT:-}"
    cert_sha256="${REALM_AGENT_TLS_CERT_SHA256:-}"
    if ! validate_agent_tls_cert_sha256 "${cert_sha256}"; then
      err "REALM_AGENT_TLS_CERT_SHA256 必须是 64 位小写十六进制"
      return 1
    fi
    if [[ "${normalized_verify_peer}" == "1" ]]; then
      if [[ "${normalized_auto}" != "0" ]]; then
        err "HTTPS verify_tls=true 禁止自动生成自签证书"
        return 1
      fi
      if [[ -z "${ca_cert}" ]] || ! validate_agent_tls_path "${ca_cert}" \
        || [[ ! -f "${ca_cert}" || -L "${ca_cert}" ]]; then
        err "HTTPS verify_tls=true 必须显式提供可信 REALM_AGENT_TLS_CA_CERT"
        return 1
      fi
    fi
    if [[ "${normalized_auto}" == "0" ]]; then
      if [[ ! -f "${cert}" || -L "${cert}" || ! -f "${key}" || -L "${key}" ]]; then
        err "HTTPS verify/fail-closed 模式要求预先配置可信 cert/key"
        return 1
      fi
    fi
    if [[ -e "${cert}" || -e "${key}" ]]; then
      if [[ ! -f "${cert}" || -L "${cert}" || ! -f "${key}" || -L "${key}" ]]; then
        err "显式 HTTPS cert/key 必须同时存在且不得为符号链接"
        return 1
      fi
      if [[ -n "${AGENT_CONTRACT_PYTHON:-}" ]] \
        && ! command_exists openssl; then
        err "phase-1 已有 Python，但缺少 openssl，无法无副作用完整校验 HTTPS 材料"
        return 1
      fi
    fi
  fi
  if agent_target_api_key_is_set; then
    if ! validate_agent_target_api_key "$(agent_target_api_key_value)"; then
      err "join 目标 API key 必须是 8-256 位安全 ASCII 字符"
      return 1
    fi
    if [[ -n "$(agent_target_api_key_version)" ]] \
      && ! validate_agent_api_key_version "$(agent_target_api_key_version)"; then
      err "join 目标 API key version 必须是 64 位小写十六进制 SHA-256"
      return 1
    fi
  fi
}

phase1_agent_install_contract_preflight(){
  local explicit_host="${1:-}"
  local explicit_port="${2:-}"
  local explicit_transport="${3:-}"
  local existing_transport=""
  local preferred_transport=""

  AGENT_PHASE1_CONTRACT_COMPLETE="0"
  AGENT_CONTRACT_PYTHON="$(find_phase1_contract_python || true)"
  if ! phase1_validate_explicit_agent_contract \
    "${explicit_host}" "${explicit_port}" "${explicit_transport}"; then
    return 1
  fi
  if [[ -z "${explicit_transport}" ]]; then
    existing_transport="$(
      read_env_value \
        "$(agent_config_dir)/agent.env" \
        "REALM_AGENT_TRANSPORT" || true
    )"
  fi
  preferred_transport="${explicit_transport:-${existing_transport}}"
  if [[ -n "${preferred_transport}" ]]; then
    if ! preferred_transport="$(
      normalize_agent_transport "${preferred_transport}"
    )"; then
      err "Agent 传输类型仅支持 http 或 https：${preferred_transport}"
      return 1
    fi
  fi
  if ! phase1_reject_ambiguous_legacy_units "${preferred_transport}"; then
    return 1
  fi

  if [[ -z "${AGENT_CONTRACT_PYTHON}" ]]; then
    warn "phase-1 未找到 Python 3.9+；已完成显式契约/歧义检查，依赖阶段后将补做旧 unit 完整解析"
    return 0
  fi
  if ! resolve_agent_install_contract \
    "${explicit_host}" "${explicit_port}" "${explicit_transport}"; then
    return 1
  fi
  AGENT_PHASE1_CONTRACT_COMPLETE="1"
}

resolve_agent_install_contract(){
  local explicit_host="${1:-}"
  local explicit_port="${2:-}"
  local explicit_transport="${3:-}"
  local config_dir=""
  local existing_env=""
  local existing_host=""
  local existing_port=""
  local existing_transport=""
  local existing_cert=""
  local existing_key=""
  local existing_server_name=""
  local existing_auto_generate=""
  local existing_verify_peer=""
  local existing_ca_cert=""
  local existing_cert_sha256=""
  local existing_address_family=""
  local existing_insecure_override=""
  local preferred_transport=""
  local host=""
  local port=""
  local transport=""
  local cert=""
  local key=""
  local server_name=""
  local auto_generate=""
  local verify_peer=""
  local ca_cert=""
  local cert_sha256=""
  local address_family=""
  local insecure_override=""
  local tls_expected_gid=""
  local normalized_host=""
  local normalized_transport=""

  config_dir="$(agent_config_dir)"
  existing_env="${config_dir}/agent.env"
  existing_host="$(read_env_value "${existing_env}" "REALM_AGENT_HOST" || true)"
  existing_port="$(read_env_value "${existing_env}" "REALM_AGENT_PORT" || true)"
  existing_transport="$(read_env_value "${existing_env}" "REALM_AGENT_TRANSPORT" || true)"
  existing_cert="$(read_env_value "${existing_env}" "REALM_AGENT_SSL_CERT" || true)"
  existing_key="$(read_env_value "${existing_env}" "REALM_AGENT_SSL_KEY" || true)"
  existing_server_name="$(read_env_value "${existing_env}" "REALM_AGENT_TLS_SERVER_NAME" || true)"
  existing_auto_generate="$(read_env_value "${existing_env}" "REALM_AGENT_TLS_AUTO_GENERATE" || true)"
  existing_verify_peer="$(read_env_value "${existing_env}" "REALM_AGENT_TLS_VERIFY_PEER" || true)"
  existing_ca_cert="$(read_env_value "${existing_env}" "REALM_AGENT_TLS_CA_CERT" || true)"
  existing_cert_sha256="$(read_env_value "${existing_env}" "REALM_AGENT_TLS_CERT_SHA256" || true)"
  existing_address_family="$(read_env_value "${existing_env}" "REALM_AGENT_ADDRESS_FAMILY" || true)"
  existing_insecure_override="$(
    read_env_value \
      "${existing_env}" "REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK" || true
  )"

  preferred_transport="${explicit_transport:-${existing_transport}}"
  if [[ -n "${preferred_transport}" ]]; then
    if ! preferred_transport="$(normalize_agent_transport "${preferred_transport}")"; then
      err "Agent 传输类型仅支持 http 或 https：${preferred_transport}"
      return 1
    fi
  fi
  if ! discover_legacy_agent_contract "${preferred_transport}"; then
    return 1
  fi

  if [[ -n "${LEGACY_AGENT_SERVICE:-}" ]]; then
    if [[ -z "${explicit_host}" && -z "${existing_host}" && -z "${LEGACY_AGENT_HOST}" ]]; then
      err "旧 Agent unit 未声明可迁移的 REALM_AGENT_HOST/--host"
      return 1
    fi
    if [[ -z "${explicit_port}" && -z "${existing_port}" && -z "${LEGACY_AGENT_PORT}" ]]; then
      err "旧 Agent unit 未声明可迁移的 REALM_AGENT_PORT/--port"
      return 1
    fi
  fi

  host="${explicit_host:-${existing_host:-${LEGACY_AGENT_HOST:-${DEFAULT_HOST}}}}"
  port="${explicit_port:-${existing_port:-${LEGACY_AGENT_PORT:-${DEFAULT_PORT}}}}"
  transport="${preferred_transport:-${LEGACY_AGENT_TRANSPORT:-http}}"
  cert="${REALM_AGENT_SSL_CERT:-${existing_cert:-${LEGACY_AGENT_SSL_CERT:-${config_dir}/certs/server.crt}}}"
  key="${REALM_AGENT_SSL_KEY:-${existing_key:-${LEGACY_AGENT_SSL_KEY:-${config_dir}/certs/server.key}}}"
  server_name="${REALM_AGENT_TLS_SERVER_NAME:-${existing_server_name}}"
  auto_generate="${REALM_AGENT_TLS_AUTO_GENERATE:-${existing_auto_generate}}"
  verify_peer="${REALM_AGENT_TLS_VERIFY_PEER:-${existing_verify_peer:-0}}"
  ca_cert="${REALM_AGENT_TLS_CA_CERT:-${existing_ca_cert}}"
  cert_sha256="${REALM_AGENT_TLS_CERT_SHA256:-${existing_cert_sha256}}"
  address_family="${REALM_AGENT_ADDRESS_FAMILY:-${existing_address_family:-explicit}}"
  insecure_override="$(
    normalize_tls_auto_generate \
      "${REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK:-${existing_insecure_override:-0}}"
  )" || {
    err "REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK 仅支持 0/1 或布尔值"
    return 1
  }

  if ! normalized_host="$(normalize_agent_bind_host "${host}")"; then
    err "旧 Agent 监听地址无法安全迁移：${host}"
    return 1
  fi
  host="${normalized_host}"
  if ! address_family="$(normalize_agent_address_family "${address_family}")"; then
    err "Agent 地址族策略无法安全迁移：${address_family}"
    return 1
  fi
  if [[ -z "${address_family}" ]]; then
    address_family="explicit"
  fi
  if ! validate_agent_dual_stack_bind_policy "${host}" "${address_family}"; then
    return 1
  fi
  if [[ ! "${port}" =~ ^[0-9]+$ || ${#port} -gt 5 ]] \
    || (( 10#${port} < 1 || 10#${port} > 65535 )); then
    err "旧 Agent 端口无法安全迁移：${port}"
    return 1
  fi
  port="$((10#${port}))"
  if ! normalized_transport="$(normalize_agent_transport "${transport}")"; then
    err "旧 Agent 服务类型无法安全迁移：${transport}"
    return 1
  fi
  transport="${normalized_transport}"
  if ! validate_agent_bind_contract \
    "${host}" "${port}" "${transport}" "${insecure_override}"; then
    return 1
  fi

  if [[ "${transport}" == "https" ]]; then
    if ! validate_agent_tls_path "${cert}" || ! validate_agent_tls_path "${key}"; then
      err "HTTPS 证书路径无效，拒绝切换服务"
      return 1
    fi
    if [[ -z "${auto_generate}" ]]; then
      auto_generate="0"
    fi
    if ! auto_generate="$(normalize_tls_auto_generate "${auto_generate}")"; then
      err "REALM_AGENT_TLS_AUTO_GENERATE 仅支持 0/1 或布尔值"
      return 1
    fi
    if ! verify_peer="$(normalize_tls_auto_generate "${verify_peer}")"; then
      err "REALM_AGENT_TLS_VERIFY_PEER 仅支持 0/1 或布尔值"
      return 1
    fi
    if ! validate_agent_tls_cert_sha256 "${cert_sha256}"; then
      err "REALM_AGENT_TLS_CERT_SHA256 必须是 64 位小写十六进制"
      return 1
    fi
    if [[ -z "${server_name}" \
      && "${host}" != "0.0.0.0" && "${host}" != "::" && "${host}" != "*" ]]; then
      server_name="${host}"
    fi
    if ! server_name="$(normalize_agent_tls_server_name "${server_name}")"; then
      err "HTTPS 必须提供非 unspecified 的 REALM_AGENT_TLS_SERVER_NAME"
      return 1
    fi
    if [[ "${auto_generate}" == "0" ]] \
      && { [[ ! -f "${cert}" || -L "${cert}" ]] \
        || [[ ! -f "${key}" || -L "${key}" ]]; }; then
      err "HTTPS verify/fail-closed 模式要求预先配置可信 cert/key"
      return 1
    fi
    if [[ "${verify_peer}" == "1" ]]; then
      if [[ "${auto_generate}" != "0" ]]; then
        err "HTTPS verify_tls=true 禁止自动生成自签证书"
        return 1
      fi
      if [[ -z "${ca_cert}" ]] || ! validate_agent_tls_path "${ca_cert}" \
        || [[ ! -f "${ca_cert}" || -L "${ca_cert}" ]]; then
        err "HTTPS verify_tls=true 必须显式提供可信 REALM_AGENT_TLS_CA_CERT"
        return 1
      fi
    fi
    if [[ -e "${cert}" || -e "${key}" ]]; then
      if [[ ! -f "${cert}" || -L "${cert}" || ! -f "${key}" || -L "${key}" ]]; then
        err "HTTPS cert/key 必须同时存在且不得为符号链接"
        return 1
      fi
      if ! command_exists openssl || [[ -z "$(agent_contract_python || true)" ]]; then
        err "完整 HTTPS cert/key/trust contract 校验需要 Python 3.9+ 与 openssl"
        return 1
      fi
      if ! tls_expected_gid="$(existing_agent_tls_expected_gid)"; then
        return 1
      fi
      if ! validate_agent_tls_material \
        "${cert}" "${key}" "${server_name}" "${host}" \
        "$(agent_service_file_uid)" "${tls_expected_gid}" 86400 \
        "${verify_peer}" "${ca_cert}" "${cert_sha256}"; then
        err "HTTPS cert/key/CA trust contract 校验失败"
        return 1
      fi
    fi
  else
    auto_generate="0"
    verify_peer="0"
    ca_cert=""
    cert_sha256=""
  fi

  AGENT_INSTALL_HOST="${host}"
  AGENT_INSTALL_PORT="${port}"
  AGENT_INSTALL_TRANSPORT="${transport}"
  if [[ "${transport}" == "https" ]]; then
    AGENT_INSTALL_SERVICE="realm-agent-https.service"
  else
  AGENT_INSTALL_SERVICE="realm-agent.service"
  fi
  AGENT_INSTALL_ADDRESS_FAMILY="${address_family}"
  AGENT_INSTALL_SSL_CERT="${cert}"
  AGENT_INSTALL_SSL_KEY="${key}"
  AGENT_INSTALL_TLS_SERVER_NAME="${server_name}"
  AGENT_INSTALL_TLS_AUTO_GENERATE="${auto_generate}"
  AGENT_INSTALL_TLS_VERIFY_PEER="${verify_peer}"
  AGENT_INSTALL_TLS_CA_CERT="${ca_cert}"
  AGENT_INSTALL_TLS_CERT_SHA256="${cert_sha256}"
  AGENT_INSTALL_ALLOW_INSECURE_NON_LOOPBACK="${insecure_override}"

  if [[ -n "${LEGACY_AGENT_SERVICE:-}" ]]; then
    info "旧 Agent 契约：${LEGACY_AGENT_SERVICE} ${LEGACY_AGENT_TRANSPORT}://${LEGACY_AGENT_HOST:-未声明}:${LEGACY_AGENT_PORT:-未声明}"
    info "迁移后契约：${AGENT_INSTALL_SERVICE} ${AGENT_INSTALL_TRANSPORT}://${AGENT_INSTALL_HOST}:${AGENT_INSTALL_PORT}"
  fi
}

existing_agent_tls_expected_gid(){
  local group_exists="0"
  local user_exists="0"
  if ! agent_sandbox_is_host_unit_dir; then
    id -g
    return
  fi
  getent group "${AGENT_SERVICE_GROUP}" >/dev/null 2>&1 && group_exists="1"
  if id -u "${AGENT_SERVICE_USER}" >/dev/null 2>&1 \
    || getent passwd "${AGENT_SERVICE_USER}" >/dev/null 2>&1; then
    user_exists="1"
  fi
  if [[ "${group_exists}" == "0" && "${user_exists}" == "0" ]]; then
    printf '0'
    return
  fi
  if [[ "${group_exists}" != "1" || "${user_exists}" != "1" ]] \
    || ! validate_agent_service_account_identity; then
    err "现有 realm-agent 服务账户不完整或不可信，拒绝复用 TLS 私钥组"
    return 1
  fi
  printf '%s' "${AGENT_SERVICE_GID}"
}

# See realm_panel.sh::append_env_default for rationale (SH-001 / SH-013).
# All env writes derived from caller-supplied or environment values must
# go through this helper so a value with embedded "\nMALICIOUS_KEY=..."
# cannot inject a second line.
append_env_default(){
  local target="$1" key="$2" value="$3"
  local sanitized
  sanitized="$(strip_env_value "${value}")"
  if [[ "${key}" =~ [^A-Za-z0-9_] ]]; then
    err "拒绝写入非法 env 键：${key}"
    return 1
  fi
  if grep -q "^${key}=" "${target}" 2>/dev/null; then
    return 0
  fi
  printf '%s=%s\n' "${key}" "${sanitized}" >> "${target}"
}

manifest_concurrency(){
  local raw="${REPO_MANIFEST_CONCURRENCY:-${REPO_MANIFEST_CONCURRENCY_DEFAULT}}"
  if [[ ! "${raw}" =~ ^[0-9]+$ ]]; then
    echo "${REPO_MANIFEST_CONCURRENCY_DEFAULT}"
    return
  fi
  if (( raw < 1 )); then
    raw=1
  fi
  if (( raw > 32 )); then
    raw=32
  fi
  echo "${raw}"
}

download_repo_manifest_path(){
  local base_url="${1%/}"
  local out_dir="$2"
  local path="$3"
  local bust="$4"
  local expected_sha="$5"
  local expected_size="$6"
  local expected_mode="$7"
  local src="${base_url}/${path}"
  local dest="${out_dir}/${path}"
  local actual_size=""
  mkdir -p "$(dirname "${dest}")"
  if ! download_verified_file "${src}?${bust}" "${dest}" "${expected_sha}" "manifest 文件 ${path}"; then
    if ! download_verified_file "${src}" "${dest}" "${expected_sha}" "manifest 文件 ${path}"; then
      err "下载文件失败：${src}"
      return 1
    fi
  fi
  actual_size="$(wc -c < "${dest}" | tr -d '[:space:]')" || return 1
  if [[ "${actual_size}" != "${expected_size}" ]]; then
    err "manifest 文件大小校验失败：${path}"
    rm -f "${dest}" || true
    return 1
  fi
  if [[ ! "${expected_mode}" =~ ^0[0-7]{3}$ ]] \
    || ! python3 - "${dest}" "${expected_mode}" <<'PY'
import os
import pathlib
import stat
import sys

path = pathlib.Path(sys.argv[1])
expected = int(sys.argv[2], 8)
os.chmod(path, expected)
metadata = path.lstat()
if (
    stat.S_ISLNK(metadata.st_mode)
    or not stat.S_ISREG(metadata.st_mode)
    or metadata.st_nlink != 1
    or stat.S_IMODE(metadata.st_mode) != expected
):
    raise SystemExit("downloaded manifest file mode mismatch")
PY
  then
    err "manifest 文件模式校验失败：${path}"
    rm -f "${dest}" || true
    return 1
  fi
}

parse_manifest_paths(){
  local manifest_file="$1"
  local paths_file="$2"
  : > "${paths_file}"

  if command_exists python3; then
    if python3 - "${manifest_file}" "${paths_file}" <<'PY'
import json
import pathlib
import sys

manifest_file = pathlib.Path(sys.argv[1])
paths_file = pathlib.Path(sys.argv[2])
text = manifest_file.read_text(encoding="utf-8", errors="ignore")
entries = None
hashes = {}
try:
    data = json.loads(text)
except Exception:
    data = None

if isinstance(data, dict):
    entries = data.get("files")
    raw_hashes = data.get("sha256", data.get("hashes", {}))
    if isinstance(raw_hashes, dict):
        hashes = raw_hashes

seen = set()
records = []

def add_path(raw, raw_sha=None):
    if isinstance(raw, dict):
        raw_sha = raw.get("sha256")
        raw = raw.get("path")
    if not isinstance(raw, str) or not isinstance(raw_sha, str):
        raise SystemExit(4)
    p = raw.strip().replace("\r", "")
    sha = raw_sha.strip().lower()
    parts = pathlib.PurePosixPath(p)
    if (
        not p
        or p.startswith("#")
        or parts.is_absolute()
        or "\\" in p
        or any(part in {"", ".", ".."} for part in parts.parts)
    ):
        raise SystemExit(4)
    if len(sha) != 64 or any(char not in "0123456789abcdef" for char in sha):
        raise SystemExit(4)
    if p in seen:
        raise SystemExit(4)
    seen.add(p)
    records.append((sha, p))

if isinstance(entries, list):
    for item in entries:
        if isinstance(item, str):
            add_path(item, hashes.get(item))
        else:
            add_path(item)

if not records:
    raise SystemExit(3)

paths_file.write_text(
    "".join(f"{sha}\t{path}\n" for sha, path in records),
    encoding="utf-8",
)
PY
    then
      return 0
    fi
  fi

  err "manifest 必须是 JSON，且每个 files 条目必须绑定 SHA256"
  return 1
}

render_manifest_progress(){
  local done="$1"
  local total="$2"
  local width=28
  local percent filled i
  local bar=""
  if (( total <= 0 )); then
    return
  fi
  if (( done < 0 )); then
    done=0
  fi
  if (( done > total )); then
    done="${total}"
  fi
  percent=$(( done * 100 / total ))
  filled=$(( done * width / total ))
  for ((i=0; i<filled; i++)); do
    bar="${bar}#"
  done
  for ((i=filled; i<width; i++)); do
    bar="${bar}-"
  done
  printf "\r[提示] 文件拉取进度 [%s] %3d%% (%d/%d)" "${bar}" "${percent}" "${done}" "${total}"
  if (( done >= total )); then
    printf "\n"
  fi
}

guess_repo_base_from_zip_url(){
  local zip_url="$1"
  case "$zip_url" in
    */archive/refs/heads/*.zip) echo "${zip_url%/archive/refs/heads/*.zip}" ;;
    */archive/*.zip) echo "${zip_url%/archive/*.zip}" ;;
    */static/realm-agent.zip) echo "${zip_url%/static/realm-agent.zip}" ;;
    *) echo "${REPO_BASE_URL_DEFAULT}" ;;
  esac
}

repo_fallback_base_url(){
  local url="${REALM_AGENT_REPO_FALLBACK_BASE_URL:-${REPO_FALLBACK_BASE_URL_DEFAULT}}"
  echo "${url%/}"
}

# 回退端点支持空格分隔列表（REALM_AGENT_REPO_FALLBACK_BASE_URLS），
# 同时保留单个 REALM_AGENT_REPO_FALLBACK_BASE_URL 的旧配置；逐行输出。
# 用 read -a 按 IFS 拆分（不展开 glob），URL 含 * ? [ 等通配符时不被
# 文件系统展开。
repo_fallback_base_urls(){
  local urls="${REALM_AGENT_REPO_FALLBACK_BASE_URLS:-${REALM_AGENT_REPO_FALLBACK_BASE_URL:-}}"
  local -a url_list=()
  local url=""
  read -r -a url_list <<< "${urls}" || true
  for url in "${url_list[@]}"; do
    [[ -n "${url}" ]] || continue
    printf '%s\n' "${url%/}"
  done
}

repo_fallback_manifest_url(){
  if [[ -n "${REALM_AGENT_REPO_FALLBACK_MANIFEST_URL:-}" ]]; then
    echo "${REALM_AGENT_REPO_FALLBACK_MANIFEST_URL}"
    return
  fi
  local base=""
  base="$(repo_fallback_base_url)"
  [[ -n "${base}" ]] || return 1
  echo "${base}/release-manifest.json"
}

repo_fallback_zip_url(){
  echo "${REALM_AGENT_REPO_FALLBACK_ZIP_URL:-${REPO_FALLBACK_ZIP_URL_DEFAULT}}"
}

download_repo_from_manifest(){
  local base_url="${1%/}"
  local manifest_url="$2"
  local out_dir="$3"
  local manifest_file="${out_dir}/manifest.json"
  local paths_file="${out_dir}/manifest.paths"
  local downloaded=0
  local -a paths=()
  local -a hashes=()
  local -a sizes=()
  local -a modes=()
  local -a worker_pids=()
  local bust concurrency running failed completed
  mkdir -p "${out_dir}"
  bust="ts=$(date +%s)"

  info "拉取并验证签名 release manifest..."
  if ! download_signed_release_manifest \
    "${manifest_url}" "${manifest_file}" "agent-install" "${paths_file}"; then
    err "签名 release manifest 下载或验证失败"
    return 1
  fi

  local hash size mode path
  while IFS=$'\t' read -r hash size mode path \
    || [[ -n "${hash}${size}${mode}${path}" ]]; do
    [[ -z "${path}" ]] && continue
    [[ "${size}" =~ ^[0-9]+$ ]] || {
      err "签名 manifest size 记录无效：${path}"
      return 1
    }
    [[ "${mode}" =~ ^0[0-7]{3}$ ]] || {
      err "签名 manifest mode 记录无效：${path}"
      return 1
    }
    hashes+=("${hash}")
    sizes+=("${size}")
    modes+=("${mode}")
    paths+=("${path}")
  done < "${paths_file}"

  downloaded="${#paths[@]}"
  if [[ "${downloaded}" -eq 0 ]]; then
    err "仓库文件清单为空"
    return 1
  fi

  concurrency="$(manifest_concurrency)"
  info "开始拉取文件（并发 ${concurrency}，共 ${downloaded} 个）"
  running=0
  failed=0
  completed=0
  render_manifest_progress "${completed}" "${downloaded}"
  local index=0
  local next_wait_index=0
  for path in "${paths[@]}"; do
    while (( running >= concurrency )); do
      if ! wait "${worker_pids[$next_wait_index]}"; then
        failed=1
      fi
      next_wait_index=$((next_wait_index+1))
      running=$((running-1))
      completed=$((completed+1))
      render_manifest_progress "${completed}" "${downloaded}"
    done
    (
      download_repo_manifest_path \
        "${base_url}" "${out_dir}" "${path}" "${bust}" \
        "${hashes[$index]}" "${sizes[$index]}" "${modes[$index]}"
    ) &
    worker_pids+=("$!")
    running=$((running+1))
    index=$((index+1))
  done
  while (( running > 0 )); do
    if ! wait "${worker_pids[$next_wait_index]}"; then
      failed=1
    fi
    next_wait_index=$((next_wait_index+1))
    running=$((running-1))
    completed=$((completed+1))
    render_manifest_progress "${completed}" "${downloaded}"
  done
  if [[ "${failed}" -ne 0 ]]; then
    return 1
  fi
  ok "仓库文件拉取完成（共 ${downloaded} 个）"
}

download_repo_from_manifest_with_fallback(){
  local base_url="${1%/}"
  local manifest_url="$2"
  local out_dir="$3"
  local fallback_base fallback_manifest
  local -a fallback_pairs=()

  if download_repo_from_manifest "${base_url}" "${manifest_url}" "${out_dir}"; then
    return 0
  fi

  # 显式 manifest URL 与单个 base 配对（旧配置）；列表形式则逐 base
  # 使用其 /release-manifest.json。不猜测任何新端点。
  if [[ -n "${REALM_AGENT_REPO_FALLBACK_MANIFEST_URL:-}" ]]; then
    fallback_base="$(repo_fallback_base_url)"
    if [[ -n "${fallback_base}" ]]; then
      fallback_pairs+=("${fallback_base}|${REALM_AGENT_REPO_FALLBACK_MANIFEST_URL}")
    fi
  else
    while IFS= read -r fallback_base; do
      [[ -n "${fallback_base}" ]] || continue
      fallback_pairs+=("${fallback_base}|${fallback_base}/release-manifest.json")
    done < <(repo_fallback_base_urls)
  fi
  if [[ "${#fallback_pairs[@]}" -eq 0 ]]; then
    return 1
  fi

  local pair=""
  for pair in "${fallback_pairs[@]}"; do
    fallback_base="${pair%%|*}"
    fallback_manifest="${pair#*|}"
    if [[ "${base_url}" == "${fallback_base}" \
      && "${manifest_url}" == "${fallback_manifest}" ]]; then
      continue
    fi
    info "主源清单拉取失败，切换显式固定的备用源：${fallback_base}"
    rm -rf "${out_dir}" || true
    mkdir -p "${out_dir}"
    if download_repo_from_manifest \
      "${fallback_base}" "${fallback_manifest}" "${out_dir}"; then
      ok "已从显式固定的备用源拉取仓库文件：${fallback_base}"
      return 0
    fi
    err "备用源拉取失败，继续尝试下一个：${fallback_base}"
  done
  err "全部备用源均拉取失败（共 ${#fallback_pairs[@]} 个）"
  return 1
}

install_tcping(){
  local tcping_path=""
  if command_exists tcping; then
    ok "检测到 tcping 已安装：$(command -v tcping)"
    return
  fi
  tcping_path="$(agent_local_bin_dir)/tcping"
  install -d -m 0755 "$(dirname "${tcping_path}")"
  info "未检测到 tcping，开始安装..."
  cat > "${tcping_path}" <<'EOF_TCPING'
#!/usr/bin/env python3
import argparse
import socket
import sys
import time


def main() -> int:
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("-c", dest="count", type=int, default=1)
    parser.add_argument("-t", dest="timeout", type=int, default=5)
    parser.add_argument("host")
    parser.add_argument("port", type=int)
    args, _extra = parser.parse_known_args()

    count = max(1, int(args.count))
    timeout = max(1, int(args.timeout))
    host = args.host
    port = int(args.port)

    for _ in range(count):
        start = time.monotonic()
        try:
            with socket.create_connection((host, port), timeout=timeout):
                latency = (time.monotonic() - start) * 1000.0
                print(f"open {host}:{port} time={latency:.2f} ms")
                return 0
        except Exception as exc:
            print(f"tcping failed: {exc}", file=sys.stderr)
            return 1
    return 1


if __name__ == "__main__":
    raise SystemExit(main())
EOF_TCPING
  chmod 755 "${tcping_path}"
  if [[ -x "${tcping_path}" ]]; then
    ok "tcping 安装完成"
  else
    err "tcping 安装失败，请检查网络或脚本"
  fi
}

normalize_panel_url(){
  local url="$1"
  local host_port host scheme rest
  if [[ -z "${url}" ]]; then
    echo ""
    return
  fi
  if [[ "${url}" == http://* || "${url}" == https://* ]]; then
    scheme="${url%%://*}"
    rest="${url#*://}"
    host_port="${rest%%/*}"
    host_port="${host_port%%\?*}"
    host_port="${host_port%%\#*}"
    host="${host_port}"
    if [[ "${host_port}" == \[*\]:* ]]; then
      host="${host_port%%]:*}"
      host="${host#\[}"
    elif [[ "${host_port}" == *:* ]]; then
      host="${host_port%%:*}"
    fi
    if [[ "${scheme}" == "http" && "$(printf '%s' "${host}" | tr '[:upper:]' '[:lower:]')" == "realm.infpro.me" ]]; then
      url="https://${rest}"
    fi
  else
    host_port="${url%%/*}"
    host_port="${host_port%%\?*}"
    host_port="${host_port%%\#*}"
    host="${host_port}"
    if [[ "${host_port}" == \[*\]:* ]]; then
      host="${host_port%%]:*}"
      host="${host#\[}"
    elif [[ "${host_port}" == *:* ]]; then
      host="${host_port%%:*}"
    fi
    if [[ -n "${host}" && "${host}" != *[!0-9.]* ]]; then
      url="http://${url}"
    elif [[ "${host}" == *:* ]]; then
      url="http://${url}"
    else
      url="https://${url}"
    fi
  fi
  echo "${url%/}"
}

default_nats_url_from_panel(){
  local panel_url host_port host
  panel_url="$(normalize_panel_url "${1:-}")"
  if [[ -z "${panel_url}" ]]; then
    printf 'nats://127.0.0.1:4222'
    return
  fi
  host_port="${panel_url#http://}"
  host_port="${host_port#https://}"
  host_port="${host_port%%/*}"
  if [[ -z "${host_port}" ]]; then
    printf 'nats://127.0.0.1:4222'
    return
  fi
  if [[ "${host_port}" == \[*\]:* ]]; then
    host="${host_port%%]:*}"
    host="${host#\[}"
    printf 'tls://[%s]:4222' "${host}"
    return
  fi
  if [[ "${host_port}" == \[*\] ]]; then
    host="${host_port#\[}"
    host="${host%\]}"
    printf 'tls://[%s]:4222' "${host}"
    return
  fi
  if [[ "${host_port}" == *:* ]]; then
    host="${host_port%%:*}"
  else
    host="${host_port}"
  fi
  printf 'tls://%s:4222' "${host}"
}

nats_url_needs_derivation(){
  local raw host_port host
  raw="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')"
  if [[ -z "${raw}" ]]; then
    return 0
  fi
  if [[ "${raw}" != nats://* && "${raw}" != tls://* ]]; then
    return 1
  fi
  host_port="${raw#nats://}"
  host_port="${host_port#tls://}"
  host_port="${host_port%%/*}"
  if [[ -z "${host_port}" ]]; then
    return 0
  fi
  if [[ "${host_port}" == \[*\]:* ]]; then
    host="${host_port%%]:*}"
    host="${host#\[}"
  elif [[ "${host_port}" == *:* ]]; then
    host="${host_port%%:*}"
  else
    host="${host_port}"
  fi
  case "${host}" in
    ""|127.0.0.1|localhost|::1|0.0.0.0) return 0 ;;
    *) return 1 ;;
  esac
}

resolve_agent_nats_url(){
  local explicit existing panel_url resolved expected
  explicit="$(printf '%s' "${1:-}")"
  existing="$(printf '%s' "${2:-}")"
  panel_url="$(printf '%s' "${3:-}")"
  resolved="${explicit}"
  if [[ -n "${resolved}" ]]; then
    printf '%s' "${resolved}"
    return
  fi
  resolved="${existing}"
  expected="$(default_nats_url_from_panel "${panel_url}")"
  if nats_url_needs_derivation "${resolved}"; then
    resolved="${expected}"
  fi
  printf '%s' "${resolved}"
}

read_env_value(){
  local file="$1"
  local key="$2"
  local line value
  if [[ ! -f "${file}" ]]; then
    return 1
  fi
  line="$(grep -E "^(export[[:space:]]+)?${key}=" "${file}" 2>/dev/null | head -n 1 || true)"
  if [[ -z "${line}" ]]; then
    return 1
  fi
  if [[ "${line}" == export* ]]; then
    line="${line#export }"
  fi
  value="${line#"${key}"=}"
  value="${value%$'\r'}"
  # trim leading/trailing spaces
  value="${value#"${value%%[![:space:]]*}"}"
  value="${value%"${value##*[![:space:]]}"}"
  if [[ "${value}" == \"*\" ]]; then
    value="${value#\"}"
    value="${value%\"}"
  fi
  if [[ "${value}" == \'*\' ]]; then
    value="${value#\'}"
    value="${value%\'}"
  fi
  printf "%s" "${value}"
}

decode_shell_env_value(){
  local raw="${1:-}"
  local parser=""
  local decoded=""
  parser="$(trusted_agent_bootstrap_python || true)"
  if [[ -z "${parser}" ]]; then
    printf '%s' "${raw}"
    return 0
  fi
  if decoded="$("${parser}" - "${raw}" <<'PY'
import base64
import shlex
import sys

text = sys.argv[1]
if text.startswith("b64:"):
    encoded = text[4:]
    try:
        data = base64.b64decode(encoded, altchars=b"-_", validate=True)
        decoded = data.decode("utf-8")
    except (ValueError, UnicodeDecodeError):
        raise SystemExit(1)
    if base64.urlsafe_b64encode(data).decode("ascii") != encoded:
        raise SystemExit(1)
    if any(ord(char) < 32 or ord(char) == 127 for char in decoded):
        raise SystemExit(1)
    sys.stdout.write(decoded)
    raise SystemExit(0)
try:
    values = shlex.split(text, posix=True)
except ValueError:
    raise SystemExit(1)
if len(values) != 1:
    raise SystemExit(1)
sys.stdout.write(values[0])
PY
  )"; then
    printf '%s' "${decoded}"
  else
    printf '%s' "${raw}"
  fi
}

read_mptcp_sidecar_cmd_value(){
  local file="$1"
  local value=""
  value="$(read_env_value "${file}" "REALM_MPTCP_SIDECAR_CMD" || true)"
  [[ -n "${value}" ]] || return 1
  decode_shell_env_value "${value}"
}

resolve_preserved_env_value(){
  local file="$1"
  local key="$2"
  local explicit="${3:-}"
  local default_value="${4:-}"
  local existing=""

  if [[ -n "${explicit}" ]]; then
    printf '%s' "${explicit}"
    return 0
  fi
  existing="$(read_env_value "${file}" "${key}" || true)"
  if [[ -n "${existing}" ]]; then
    printf '%s' "${existing}"
  else
    printf '%s' "${default_value}"
  fi
}

resolve_migrated_default_env_value(){
  local file="$1"
  local key="$2"
  local explicit="${3:-}"
  local installed_version="${4:-}"
  local current_version="$5"
  local default_value="${6:-}"
  local existing=""

  if [[ -n "${explicit}" ]]; then
    printf '%s' "${explicit}"
    return 0
  fi
  if [[ "${installed_version}" == "${current_version}" ]]; then
    existing="$(read_env_value "${file}" "${key}" || true)"
    if [[ -n "${existing}" ]]; then
      printf '%s' "${existing}"
      return 0
    fi
  fi
  printf '%s' "${default_value}"
}

bounded_uint_or_default(){
  local raw="${1:-}"
  local default_value="$2"
  local min_value="$3"
  local max_value="$4"
  local number
  if [[ ! "${raw}" =~ ^[0-9]+$ || ${#raw} -gt 10 ]]; then
    printf '%s' "${default_value}"
    return 0
  fi
  number=$((10#${raw}))
  if (( number < min_value || number > max_value )); then
    printf '%s' "${default_value}"
  else
    printf '%s' "${number}"
  fi
}

resolve_preserved_uint_env_value(){
  local file="$1"
  local key="$2"
  local explicit="${3:-}"
  local default_value="$4"
  local min_value="$5"
  local max_value="$6"
  local value
  value="$(resolve_preserved_env_value "${file}" "${key}" "${explicit}" "${default_value}")"
  bounded_uint_or_default "${value}" "${default_value}" "${min_value}" "${max_value}"
}

normalize_bool_or_default(){
  local raw="${1:-}"
  local default_value="$2"
  raw="$(printf '%s' "${raw}" | tr '[:upper:]' '[:lower:]')"
  case "${raw}" in
    1|true|yes|on|y)
      printf '1'
      ;;
    0|false|no|off|n)
      printf '0'
      ;;
    *)
      printf '%s' "${default_value}"
      ;;
  esac
}

resolve_preserved_bool_env_value(){
  local file="$1"
  local key="$2"
  local explicit="${3:-}"
  local default_value="$4"
  local value=""
  value="$(
    resolve_preserved_env_value \
      "${file}" "${key}" "${explicit}" "${default_value}"
  )"
  normalize_bool_or_default "${value}" "${default_value}"
}

normalize_update_text_env_value(){
  REALM_AGENT_NORMALIZE_UPDATE_TEXT_INPUT="${1:-}" python3 - <<'PY'
import os
import sys

value = os.environ.get("REALM_AGENT_NORMALIZE_UPDATE_TEXT_INPUT", "")
if len(value) > 2048 or any(
    ord(character) < 32 or ord(character) == 127
    for character in value
):
    raise SystemExit(1)
if any(character in value for character in ('"', "'", "\\", "`", "$")):
    raise SystemExit(1)
sys.stdout.write(value)
PY
}

resolve_preserved_update_text_env_value(){
  local file="$1"
  local key="$2"
  local explicit="${3:-}"
  local value=""
  value="$(resolve_preserved_env_value "${file}" "${key}" "${explicit}" "")"
  if ! normalize_update_text_env_value "${value}"; then
    err "${key} 含不安全字符，拒绝写入 agent.env"
    return 1
  fi
}

hydrate_update_runtime_env(){
  local env_file="${REALM_AGENT_ENV_FILE:-/etc/realm-agent/agent.env}"
  local key=""
  local value=""
  while IFS=$'\t' read -r key value; do
    [[ -n "${key}" ]] || continue
    if [[ -n "${!key+x}" ]]; then
      continue
    fi
    printf -v "${key}" '%s' "${value}"
    export "${key}"
  done < <(python3 - "${env_file}" <<'PY'
import os
import re
import shlex
import stat
import sys

path = sys.argv[1]
kinds = {
    "REALM_AGENT_PIP_DISABLE_FALLBACK": "boolean",
    "REALM_AGENT_PIP_ENABLE_LEGACY_RESOLVER_FALLBACK": "boolean",
    "REALM_AGENT_PIP_EXTRA_INDEX_URL": "text",
    "REALM_AGENT_PIP_FALLBACK_INDEXES": "text",
    "REALM_AGENT_PIP_FORCE_LEGACY_RESOLVER": "boolean",
    "REALM_AGENT_PIP_INDEX_URL": "text",
    "REALM_AGENT_PIP_INSTALL_TIMEOUT": "numeric",
    "REALM_AGENT_PIP_TRUSTED_HOST": "text",
    "REALM_AGENT_UPDATE_CURL_CONNECT_TIMEOUT": "numeric",
    "REALM_AGENT_UPDATE_CURL_MAX_TIME": "numeric",
    "REALM_AGENT_UPDATE_CURL_RETRY": "numeric",
    "REALM_AGENT_UPDATE_CURL_RETRY_DELAY": "numeric",
    "REALM_AGENT_UPDATE_CURL_SPEED_LIMIT": "numeric",
    "REALM_AGENT_UPDATE_CURL_SPEED_TIME": "numeric",
    "REALM_AGENT_UPDATE_LOG_RETENTION_DAYS": "numeric",
}
boolean_values = {
    "0": "0",
    "1": "1",
    "false": "0",
    "n": "0",
    "no": "0",
    "off": "0",
    "on": "1",
    "true": "1",
    "y": "1",
    "yes": "1",
}
flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
try:
    descriptor = os.open(path, flags)
except OSError:
    raise SystemExit(0)
try:
    metadata = os.fstat(descriptor)
    if (
        not stat.S_ISREG(metadata.st_mode)
        or metadata.st_uid != os.geteuid()
        or stat.S_IMODE(metadata.st_mode) & 0o022
    ):
        raise SystemExit(0)
    with os.fdopen(descriptor, "r", encoding="utf-8", errors="strict") as handle:
        descriptor = -1
        values = {}
        for raw_line in handle:
            line = raw_line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            key, raw_value = line.split("=", 1)
            key = key.strip()
            kind = kinds.get(key)
            if kind is None:
                continue
            try:
                parsed = shlex.split(raw_value.strip(), posix=True)
            except ValueError:
                continue
            if len(parsed) != 1:
                continue
            value = parsed[0]
            if (
                not value
                or len(value) > 2048
                or any(ord(char) < 32 or ord(char) == 127 for char in value)
            ):
                continue
            if kind == "numeric" and not re.fullmatch(r"[0-9]+", value):
                continue
            if kind == "boolean":
                value = boolean_values.get(value.lower(), "")
                if not value:
                    continue
            values[key] = value
        for key in sorted(values):
            print(f"{key}\t{values[key]}")
finally:
    if descriptor >= 0:
        os.close(descriptor)
PY
)
}

resolve_preserved_outer_tcp_mss(){
  local file="$1"
  local key="$2"
  local explicit="${3:-}"
  local min_value="$4"
  local max_value="$5"
  local value=""
  local number=0

  value="$(resolve_preserved_env_value "${file}" "${key}" "${explicit}" "0")"
  if [[ "${value}" == "0" ]]; then
    printf '0'
    return 0
  fi
  if [[ ! "${value}" =~ ^[0-9]+$ || ${#value} -gt 10 ]]; then
    err "${key} 只能是 0 或十进制 TCP MSS"
    return 1
  fi
  number=$((10#${value}))
  if (( number < min_value || number > max_value )); then
    err "${key} 必须为 0 或 ${min_value}-${max_value}"
    return 1
  fi
  printf '%s' "${number}"
}

hydrate_panel_context(){
  local v env_file
  local -a env_files=(/etc/realm-agent/panel.env /etc/realm-agent/agent.env)
  for env_file in "${env_files[@]}"; do
    if [[ ! -f "${env_file}" ]]; then
      continue
    fi
    if [[ -z "${REALM_PANEL_URL:-}" ]]; then
      v="$(read_env_value "${env_file}" "REALM_PANEL_URL" || true)"
      if [[ -n "${v}" ]]; then
        export REALM_PANEL_URL="${v}"
        info "未显式指定 REALM_PANEL_URL，已从 Agent 记录读取（${env_file}）：${REALM_PANEL_URL}"
      fi
    fi
    if [[ -z "${REALM_AGENT_ID:-}" ]]; then
      v="$(read_env_value "${env_file}" "REALM_AGENT_ID" || true)"
      if [[ -n "${v}" ]]; then
        export REALM_AGENT_ID="${v}"
      fi
    fi
    if [[ -z "${REALM_AGENT_HEARTBEAT_INTERVAL:-}" ]]; then
      v="$(read_env_value "${env_file}" "REALM_AGENT_HEARTBEAT_INTERVAL" || true)"
      if [[ -n "${v}" ]]; then
        export REALM_AGENT_HEARTBEAT_INTERVAL="${v}"
      fi
    fi
    if [[ -n "${REALM_PANEL_URL:-}" && -n "${REALM_AGENT_ID:-}" ]]; then
      break
    fi
  done

  # 兼容老版本：如果 panel.env 不在，但 systemd runtime env 中有值，也尝试提取。
  if [[ -z "${REALM_PANEL_URL:-}" && -z "${REALM_AGENT_ID:-}" ]] && command_exists systemctl; then
    local env_blob service
    for service in realm-agent.service realm-agent-https.service; do
      env_blob="$(systemctl show -p Environment --value "${service}" 2>/dev/null || true)"
      if [[ -n "${env_blob}" ]]; then
        if [[ -z "${REALM_PANEL_URL:-}" ]]; then
          v="$(printf "%s\n" "${env_blob}" | tr ' ' '\n' | grep -E '^REALM_PANEL_URL=' | head -n 1 | cut -d= -f2- || true)"
          if [[ -n "${v}" ]]; then
            export REALM_PANEL_URL="${v}"
            info "已从 ${service} 运行环境读取面板地址：${REALM_PANEL_URL}"
          fi
        fi
        if [[ -z "${REALM_AGENT_ID:-}" ]]; then
          v="$(printf "%s\n" "${env_blob}" | tr ' ' '\n' | grep -E '^REALM_AGENT_ID=' | head -n 1 | cut -d= -f2- || true)"
          if [[ -n "${v}" ]]; then
            export REALM_AGENT_ID="${v}"
          fi
        fi
        if [[ -z "${REALM_AGENT_HEARTBEAT_INTERVAL:-}" ]]; then
          v="$(printf "%s\n" "${env_blob}" | tr ' ' '\n' | grep -E '^REALM_AGENT_HEARTBEAT_INTERVAL=' | head -n 1 | cut -d= -f2- || true)"
          if [[ -n "${v}" ]]; then
            export REALM_AGENT_HEARTBEAT_INTERVAL="${v}"
          fi
        fi
      fi
      if [[ -n "${REALM_PANEL_URL:-}" && -n "${REALM_AGENT_ID:-}" ]]; then
        break
      fi
    done
  fi

  # 再兜底：从正在运行的 realm-agent 主进程环境变量读取（/proc/<pid>/environ）。
  if [[ -z "${REALM_PANEL_URL:-}" ]] && command_exists systemctl; then
    local pid proc_env
    for service in realm-agent.service realm-agent-https.service; do
      pid="$(systemctl show -p MainPID --value "${service}" 2>/dev/null | tr -d '[:space:]' || true)"
      if [[ "${pid}" =~ ^[0-9]+$ ]] && [[ "${pid}" -gt 1 ]] && [[ -r "/proc/${pid}/environ" ]]; then
        proc_env="$(tr '\0' '\n' < "/proc/${pid}/environ" 2>/dev/null || true)"
        if [[ -n "${proc_env}" ]]; then
          if [[ -z "${REALM_PANEL_URL:-}" ]]; then
            v="$(printf "%s\n" "${proc_env}" | grep -E '^REALM_PANEL_URL=' | head -n 1 | cut -d= -f2- || true)"
            if [[ -n "${v}" ]]; then
              export REALM_PANEL_URL="${v}"
              info "已从 ${service} 进程环境读取面板地址：${REALM_PANEL_URL}"
            fi
          fi
          if [[ -z "${REALM_AGENT_ID:-}" ]]; then
            v="$(printf "%s\n" "${proc_env}" | grep -E '^REALM_AGENT_ID=' | head -n 1 | cut -d= -f2- || true)"
            if [[ -n "${v}" ]]; then
              export REALM_AGENT_ID="${v}"
            fi
          fi
          if [[ -z "${REALM_AGENT_HEARTBEAT_INTERVAL:-}" ]]; then
            v="$(printf "%s\n" "${proc_env}" | grep -E '^REALM_AGENT_HEARTBEAT_INTERVAL=' | head -n 1 | cut -d= -f2- || true)"
            if [[ -n "${v}" ]]; then
              export REALM_AGENT_HEARTBEAT_INTERVAL="${v}"
            fi
          fi
        fi
      fi
      if [[ -n "${REALM_PANEL_URL:-}" ]]; then
        break
      fi
    done
  fi
}

validate_mptcp_sidecar_cmd(){
  local cmd="${1:-}"
  [[ -n "${cmd}" ]] || return 1
  python3 - "${cmd}" <<'PY' >/dev/null
import re
import shlex
import sys

text = sys.argv[1]
if not text or any(ord(char) < 32 or ord(char) == 127 for char in text):
    raise SystemExit(1)
lexer = shlex.shlex(
    text,
    posix=True,
    punctuation_chars=";&|<>`$()*?[]{}!~",
)
lexer.whitespace_split = True
lexer.commenters = ""
try:
    argv = list(lexer)
except ValueError:
    raise SystemExit(1)
if not argv or len(argv) > 128:
    raise SystemExit(1)
operators = set(";&|<>`$()*?[]{}!~")
if any(token and all(char in operators for char in token) for token in argv):
    raise SystemExit(1)
if any("\x00" in token or "\n" in token or "\r" in token for token in argv):
    raise SystemExit(1)
program = argv[0]
if "/" not in program and not re.fullmatch(r"[A-Za-z0-9_.+-]+", program):
    raise SystemExit(1)
PY
}

encode_literal_env_value(){
  python3 - "${1:-}" <<'PY'
import base64
import sys

value = sys.argv[1]
if any(ord(char) < 32 or ord(char) == 127 for char in value):
    raise SystemExit("literal env value contains control characters")
encoded = base64.urlsafe_b64encode(value.encode("utf-8")).decode("ascii")
sys.stdout.write("b64:" + encoded)
PY
}

resolve_mptcp_sidecar_cmd(){
  local cmd="${REALM_MPTCP_SIDECAR_CMD:-}"
  local found=""
  local c
  if [[ -n "${cmd}" ]]; then
    echo "${cmd}"
    return 0
  fi
  for c in "realm-mptcp-sidecar" "/usr/local/bin/realm-mptcp-sidecar" "/usr/bin/realm-mptcp-sidecar" "/opt/realm-agent/bin/realm-mptcp-sidecar" "mptcp-sidecar"; do
    if [[ "${c}" == */* ]]; then
      if [[ -x "${c}" ]]; then
        found="${c}"
        break
      fi
      continue
    fi
    if command_exists "${c}"; then
      found="$(command -v "${c}")"
      break
    fi
  done
  echo "${found}"
}

# 预检 realm tar 包成员：拒绝绝对路径、..、反斜杠、symlink/hardlink、重复成员、
# file/directory collision，并把成员限制为期望集合（realm 二进制及说明文档）。
# 返回码：0 = 有效且安全；1 = 不是 tar 归档（裸二进制，由调用方走旧路径）；
# 2 = 是 tar 但包含不安全成员，调用方必须拒绝解压。
validate_realm_tar_archive(){
  local archive="$1"
  [[ -f "${archive}" ]] || return 1
  python3 - "${archive}" <<'PY'
import pathlib
import sys
import tarfile

archive_path = pathlib.Path(sys.argv[1])
try:
    with tarfile.open(archive_path, "r:*") as archive:
        members = archive.getmembers()
        if not members:
            print("realm tar has no members", file=sys.stderr)
            raise SystemExit(2)
        total = 0
        seen_exact = set()
        seen_casefold = set()
        seen_files = set()
        seen_dirs = set()
        for member in members:
            raw = member.name
            path = pathlib.PurePosixPath(raw)
            if (
                not raw
                or path.is_absolute()
                or "\\" in raw
                or any(part in {"", ".", ".."} for part in path.parts)
            ):
                print(f"unsafe realm tar member: {raw!r}", file=sys.stderr)
                raise SystemExit(2)
            if member.issym() or member.islnk():
                print(f"realm tar link member is not allowed: {raw}", file=sys.stderr)
                raise SystemExit(2)
            if not (member.isfile() or member.isdir()):
                print(f"realm tar special member is not allowed: {raw}", file=sys.stderr)
                raise SystemExit(2)
            normalized = raw.rstrip("/")
            parts = normalized.split("/")
            if len(parts) > 2 or parts[-1] not in {"realm", "README.md", "README"}:
                print(f"realm tar member outside the expected set: {raw!r}", file=sys.stderr)
                raise SystemExit(2)
            folded = normalized.casefold()
            if normalized in seen_exact or folded in seen_casefold:
                print(f"duplicate realm tar member: {raw!r}", file=sys.stderr)
                raise SystemExit(2)
            if member.isdir():
                if normalized in seen_files or normalized in seen_dirs:
                    print(f"duplicate realm tar directory member: {raw!r}", file=sys.stderr)
                    raise SystemExit(2)
                seen_dirs.add(normalized)
            else:
                for index in range(1, len(parts)):
                    prefix = "/".join(parts[:index])
                    if prefix in seen_files:
                        print(f"realm tar file/directory collision: {raw!r}", file=sys.stderr)
                        raise SystemExit(2)
                if normalized in seen_files or normalized in seen_dirs:
                    print(f"duplicate realm tar member: {raw!r}", file=sys.stderr)
                    raise SystemExit(2)
                seen_files.add(normalized)
                for index in range(1, len(parts)):
                    seen_dirs.add("/".join(parts[:index]))
            seen_exact.add(normalized)
            seen_casefold.add(folded)
            total += max(0, int(member.size))
            if total > 1024 * 1024 * 1024:
                print("realm tar expands beyond the safety limit", file=sys.stderr)
                raise SystemExit(2)
except tarfile.ReadError:
    # 不是 tar 归档（例如直接发布的裸 realm 二进制），由调用方走旧路径
    raise SystemExit(1)
except (OSError, tarfile.TarError, EOFError) as exc:
    print(f"invalid realm tar archive: {exc}", file=sys.stderr)
    raise SystemExit(2)
PY
}

install_realm(){
  local realm_target=""
  if command_exists realm; then
    ok "检测到 realm 已安装：$(command -v realm)"
    return
  fi

  realm_target="$(agent_local_bin_dir)/realm"
  install -d -m 0755 "$(dirname "${realm_target}")"
  info "未检测到 realm，开始安装..."
  local arch
  arch=$(uname -m)
  case "${arch}" in
    x86_64|amd64) arch="x86_64" ;;
    aarch64|arm64) arch="aarch64" ;;
    *) err "不支持的架构：${arch}，请手动安装 realm"; exit 1 ;;
  esac

  local urls=()
  local release_urls=()
  local panel_base
  panel_base="$(normalize_panel_url "${REALM_PANEL_URL:-}")"
  local realm_tag release_url download_base
  realm_tag="$(realm_release_tag)"
  release_url="https://github.com/zhboner/realm/releases/tag/${realm_tag}"
  download_base="https://github.com/zhboner/realm/releases/download/${realm_tag}"
  # 当面板机器非公网可达时，可通过 REALM_AGENT_GITHUB_ONLY=1 强制所有安装资产走 GitHub，
  # 避免依赖面板提供 /static 下载（例如 realm 二进制）。
  if [[ -n "${panel_base}" && "${REALM_AGENT_GITHUB_ONLY:-}" != "1" ]]; then
    urls+=(
      "${panel_base}/static/realm/realm-${arch}-unknown-linux-gnu.tar.gz"
      "${panel_base}/static/realm/realm-${arch}-unknown-linux-musl.tar.gz"
    )
    release_urls+=("${release_url}" "${release_url}")
  fi
  urls+=(
    "${download_base}/realm-${arch}-unknown-linux-gnu.tar.gz"
    "${download_base}/realm-${arch}-unknown-linux-musl.tar.gz"
  )
  release_urls+=("${release_url}" "${release_url}")

  local tmpdir bin_path downloaded="0"
  tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/realm-agent-realm.XXXXXX")
  register_cleanup_path "${tmpdir}"
  local idx url
  for idx in "${!urls[@]}"; do
    url="${urls[$idx]}"
    local asset_name expected_sha
    asset_name="$(basename "${url}")"
    expected_sha="$(fetch_release_asset_sha256 \
      "${release_urls[$idx]:-${release_url}}" "${asset_name}" || true)"
    if [[ -z "${expected_sha}" ]]; then
      # 显式声明的非内置 tag（如 REALM_AGENT_REALM_RELEASE_TAG=v2.9.4）：
      # 允许经 REALM_AGENT_REALM_RELEASE_SHA256 钉住的资产清单提供各资产哈希，
      # 安全性不变——没有绑定哈希的来源仍然拒绝。
      expected_sha="$(fetch_realm_manifest_asset_sha256 \
        "${asset_name}" "${panel_base}" "${tmpdir}" || true)"
    fi
    if [[ -z "${expected_sha}" ]]; then
      info "未配置 ${asset_name} 的固定 SHA256，拒绝安装"
      continue
    fi
    if download_verified_file \
      "${url}" "${tmpdir}/realm.pkg" "${expected_sha}" "realm ${asset_name}"; then
      downloaded="1"
      local tar_rc=0
      local tar_stage=""
      validate_realm_tar_archive "${tmpdir}/realm.pkg" || tar_rc=$?
      if [[ "${tar_rc}" -eq 2 ]]; then
        err "realm tar 预检拒绝解压：${asset_name}"
        rm -f "${tmpdir}/realm.pkg"
        continue
      fi
      if [[ "${tar_rc}" -eq 0 ]]; then
        tar_stage="$(mktemp -d "${tmpdir}/realm-extract.XXXXXX")" || {
          rm -f "${tmpdir}/realm.pkg"
          continue
        }
        register_cleanup_path "${tar_stage}"
        chmod 0700 "${tar_stage}"
        if ! tar -xzf "${tmpdir}/realm.pkg" -C "${tar_stage}"; then
          info "realm 压缩包解压失败，跳过 ${asset_name}"
          rm -f "${tmpdir}/realm.pkg"
          continue
        fi
        bin_path="$(find "${tar_stage}" -maxdepth 2 -type f -name realm -print -quit 2>/dev/null || true)"
        if [[ -z "${bin_path}" ]]; then
          info "realm 压缩包中未找到可执行文件，跳过 ${asset_name}"
          rm -f "${tmpdir}/realm.pkg"
          continue
        fi
      else
        bin_path="${tmpdir}/realm.pkg"
      fi
      if [[ -n "${bin_path}" ]]; then
        local realm_stage
        realm_stage="$(mktemp "$(dirname "${realm_target}")/.realm.new.XXXXXX")"
        register_cleanup_path "${realm_stage}"
        install -m 0755 "${bin_path}" "${realm_stage}"
        mv -f "${realm_stage}" "${realm_target}"
        ok "realm 已安装至 ${realm_target}"
        rm -rf "${tmpdir}"
        return
      fi
    fi
  done
  rm -rf "${tmpdir}"
  if [[ "${downloaded}" != "1" ]]; then
    err "realm 下载失败，请检查网络或手动安装"
  else
    err "realm 安装失败，请手动安装"
  fi
  exit 1
}


realm_config_has_endpoints(){
  local config_path="${1:-/etc/realm/config.json}"
  [[ -r "${config_path}" ]] || return 1
  if command_exists jq; then
    if jq -e '
      (.endpoints | type == "array")
      and ((.endpoints | length) > 0)
      and all(
        .endpoints[];
        (type == "object")
        and ((.listen // "") | (type == "string" and test("\\S")))
        and ((.remote // "") | (type == "string" and test("\\S")))
      )
    ' "${config_path}" >/dev/null 2>&1; then
      return 0
    fi
    return 1
  fi
  if command_exists python3; then
    if python3 - "${config_path}" <<'PY' >/dev/null 2>&1
import json
import sys

with open(sys.argv[1], "r", encoding="utf-8") as handle:
    payload = json.load(handle)
endpoints = payload.get("endpoints") if isinstance(payload, dict) else None
valid = bool(isinstance(endpoints, list) and endpoints)
if valid:
    valid = all(
        isinstance(endpoint, dict)
        and isinstance(endpoint.get("listen"), str)
        and bool(endpoint["listen"].strip())
        and isinstance(endpoint.get("remote"), str)
        and bool(endpoint["remote"].strip())
        for endpoint in endpoints
    )
raise SystemExit(0 if valid else 1)
PY
    then
      return 0
    fi
    return 1
  fi
  return 1
}

preflight_active_managed_realm_config(){
  local config_path="${1:-/etc/realm/config.json}"
  command_exists systemctl || return 0
  systemctl is-active --quiet realm.service 2>/dev/null || return 0
  realm_service_uses_managed_config || return 0
  if realm_config_has_endpoints "${config_path}"; then
    return 0
  fi
  err "active realm.service 的磁盘配置缺少可运行的 listen/remote；拒绝在重启前切换 Agent"
  err "请先用当前 pool_to_run.jq 从 pool_full.json 重建 /etc/realm/config.json"
  return 1
}

realm_service_uses_managed_config(){
  local exec_start="${1:-}"
  if [[ -z "${exec_start}" ]]; then
    exec_start="$(systemctl show realm.service -p ExecStart --value 2>/dev/null || true)"
  elif [[ -f "${exec_start}" ]]; then
    exec_start="$(sed -n 's/^[[:space:]]*ExecStart=//p' "${exec_start}" \
      | tail -n 1)"
  fi
  [[ -n "${exec_start}" ]] || return 1
  grep -Eq \
    '(^|[[:space:];])(-c|--config)(=|[[:space:]]+)/etc/realm/config\.json([[:space:];}]|$)' \
    <<< "${exec_start}"
}

install_realm_service_guard(){
  if ! command_exists systemctl; then
    info "未检测到 systemd，跳过 realm.service 配置保护"
    return
  fi

  local systemd_dir=""
  local guard_dir=""
  local guard_file="${guard_dir}/10-nexus-config-guard.conf"
  local helper_dir=""
  local helper_path="${helper_dir}/nexus-realm-config-ready"
  systemd_dir="$(agent_systemd_dir)"
  guard_dir="${systemd_dir}/realm.service.d"
  guard_file="${guard_dir}/10-nexus-config-guard.conf"
  helper_dir="$(agent_libexec_dir)"
  helper_path="${helper_dir}/nexus-realm-config-ready"
  # ExecCondition 里的 helper 路径来自 env，必须过 unit 值白名单。
  if ! is_safe_systemd_value "${systemd_dir}" \
    || ! is_safe_systemd_value "${helper_path}"; then
    err "拒绝写入 realm.service 配置保护：路径含非法字符"
    return 1
  fi
  if ! realm_service_uses_managed_config; then
    rm -f "${guard_file}"
    systemctl daemon-reload
    info "realm.service 使用自定义配置路径，跳过 Nexus 配置保护"
    return
  fi

  install -d -m 0755 "${helper_dir}"
  cat > "${helper_path}" <<'EOF'
#!/bin/sh
set -eu

config_path="${1:-/etc/realm/config.json}"
[ -r "${config_path}" ] || exit 1

if command -v jq >/dev/null 2>&1; then
  exec jq -e '
    (.endpoints | type == "array")
    and ((.endpoints | length) > 0)
    and all(
      .endpoints[];
      (type == "object")
      and ((.listen // "") | (type == "string" and test("\\S")))
      and ((.remote // "") | (type == "string" and test("\\S")))
    )
  ' "${config_path}" >/dev/null 2>&1
fi
if command -v python3 >/dev/null 2>&1; then
  exec python3 - "${config_path}" <<'PY' >/dev/null 2>&1
import json
import sys

with open(sys.argv[1], "r", encoding="utf-8") as handle:
    payload = json.load(handle)
endpoints = payload.get("endpoints") if isinstance(payload, dict) else None
valid = bool(isinstance(endpoints, list) and endpoints)
if valid:
    valid = all(
        isinstance(endpoint, dict)
        and isinstance(endpoint.get("listen"), str)
        and bool(endpoint["listen"].strip())
        and isinstance(endpoint.get("remote"), str)
        and bool(endpoint["remote"].strip())
        for endpoint in endpoints
    )
raise SystemExit(0 if valid else 1)
PY
fi
exit 1
EOF
  chmod 0755 "${helper_path}"

  mkdir -p "${guard_dir}"
  cat > "${guard_file}" <<EOF
[Service]
ExecCondition=${helper_path} /etc/realm/config.json
EOF

  systemctl daemon-reload
  if ! realm_config_has_endpoints /etc/realm/config.json; then
    systemctl stop realm.service >/dev/null 2>&1 || true
    systemctl reset-failed realm.service >/dev/null 2>&1 || true
  fi
}

install_realm_service(){
  if ! command_exists systemctl; then
    info "未检测到 systemd，跳过 realm.service 生成"
    return
  fi

  local systemd_dir=""
  local realm_unit=""
  local realm_bin=""
  systemd_dir="$(agent_systemd_dir)"
  realm_unit="${systemd_dir}/realm.service"
  realm_bin="$(agent_local_bin_dir)/realm"
  # 进入 unit 文件的所有 env 派生值必须通过白名单校验（含换行注入防护）。
  if ! is_safe_systemd_value "${systemd_dir}" \
    || ! is_safe_systemd_value "${realm_bin}"; then
    err "拒绝写入 realm.service：安装路径含非法字符（systemd_dir=${systemd_dir} realm_bin=${realm_bin}）"
    return 1
  fi
  install -d -m 0755 "${systemd_dir}"

  # 主 unit：不存在则创建；已存在则保留用户自定义
  if [[ ! -f "${realm_unit}" ]]; then
    info "创建 realm.service..."
    cat > "${realm_unit}" <<EOF
[Unit]
Description=Realm Proxy Service
After=network.target

[Service]
Type=simple
ExecStart=${realm_bin} -c /etc/realm/config.json -n 1048576
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target
EOF
  else
    ok "检测到 realm.service 已存在"
  fi

  # Drop-in：尽量不覆盖用户的 ExecStart，仅补充性能/稳定性参数
  mkdir -p "${systemd_dir}/realm.service.d"
  cat > "${systemd_dir}/realm.service.d/override.conf" <<'EOF'
[Service]
LimitNOFILE=1048576
TasksMax=infinity
Restart=on-failure
EOF

  install_realm_service_guard
}

apply_sysctl_tuning(){
  if [[ "${REALM_AGENT_APPLY_HOST_NETWORK_CHANGES:-0}" != "1" ]]; then
    info "默认不修改全局 sysctl/BBR；需要时显式设置 REALM_AGENT_APPLY_HOST_NETWORK_CHANGES=1"
    return 0
  fi
  # 只写入一次，避免覆盖用户已有调优
  local f=""
  f="$(agent_sysctl_dir)/99-realm.conf"
  if [[ -f "${f}" ]]; then
    ok "检测到 ${f} 已存在，跳过 sysctl 调优写入"
    return
  fi
  install -d -m 0755 "$(dirname "${f}")"
  info "写入内核网络调优（/etc/sysctl.d/99-realm.conf）..."
  cat > "${f}" <<'EOF'
# Realm forwarding tuning (TCP为主、少量UDP、含ws/wss)
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.core.netdev_max_backlog = 250000

net.core.rmem_max = 33554432
net.core.wmem_max = 33554432
net.core.rmem_default = 262144
net.core.wmem_default = 262144
net.ipv4.tcp_rmem = 4096 87380 33554432
net.ipv4.tcp_wmem = 4096 65536 33554432
net.ipv4.udp_rmem_min = 16384
net.ipv4.udp_wmem_min = 16384

net.ipv4.ip_local_port_range = 10240 65535

# Keepalive（结合 realm 的 tcp_keepalive/tcp_keepalive_probe 使用更佳）
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 5

  # Queue + CC. Any unsupported setting fails this explicit change plan.
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
EOF

  # Apply only the managed file; replaying every third-party sysctl file would
  # mutate runtime state outside this transaction's rollback inventory.
  if ! sysctl -p "${f}" >/dev/null; then
    err "内核调优应用失败"
    return 1
  fi
}

# 离线 ZIP 先以 no-follow 语义复制到私有 0700 staging，之后 SHA256、结构校验与
# 解压全部针对同一 staging 对象，避免校验与解压之间源路径被原子替换（TOCTOU）。
stage_verified_offline_archive(){
  local source_path="$1"
  local stage_dir=""
  local stage_file=""
  [[ -n "${source_path}" ]] || return 1
  if [[ -L "${source_path}" ]]; then
    err "离线归档是符号链接，拒绝：${source_path}"
    return 1
  fi
  [[ -f "${source_path}" ]] || {
    err "离线归档不是普通文件：${source_path}"
    return 1
  }
  stage_dir="$(mktemp -d "${TMPDIR:-/tmp}/realm-agent-offline.XXXXXX")" || return 1
  chmod 0700 "${stage_dir}"
  register_cleanup_path "${stage_dir}"
  stage_file="${stage_dir}/offline.zip"
  if ! cat < "${source_path}" > "${stage_file}" 2>/dev/null; then
    err "无法复制离线归档到私有 staging：${source_path}"
    rm -rf "${stage_dir}" >/dev/null 2>&1 || true
    return 1
  fi
  chmod 0600 "${stage_file}"
  printf '%s\n' "${stage_file}"
}

fetch_repo(){
  local mode="$1"
  local tmpdir="$2"
  local zip_path=""
  ACTUAL_ZIP_SHA256=""

  # download_verified_file wraps download_file and rejects content before use
  # unless its expected SHA256 is available from trusted metadata or config.
  if [[ "${mode}" == "2" ]]; then
    zip_path="${REALM_AGENT_ZIP_PATH:-}"
    if [[ -z "${zip_path}" || ! -f "${zip_path}" ]]; then
      err "离线模式需要设置 REALM_AGENT_ZIP_PATH=/path/to/Realm-main.zip"
      exit 1
    fi
    local offline_sha=""
    local offline_stage=""
    offline_stage="$(stage_verified_offline_archive "${zip_path}" || true)"
    if [[ -z "${offline_stage}" ]]; then
      err "离线 ZIP 无法安全复制到私有 staging"
      exit 1
    fi
    offline_sha="$(trusted_offline_archive_sha256 "${offline_stage}" || true)"
    local explicit_offline_sha=""
    explicit_offline_sha="$(normalize_sha256 \
      "${REALM_AGENT_ZIP_SHA256:-${REALM_AGENT_REPO_ZIP_SHA256:-${ACTUAL_ZIP_SHA256:-${TARGET_ZIP_SHA256:-}}}}" \
      || true)"
    if [[ -n "${explicit_offline_sha}" && -n "${offline_sha}" \
      && "${explicit_offline_sha}" != "${offline_sha}" ]]; then
      err "离线 ZIP 显式 SHA256 与签名 release manifest 不一致"
      exit 1
    fi
    if [[ -z "${offline_sha}" ]] || ! verify_file_sha256 "${offline_stage}" "${offline_sha}"; then
      err "离线 ZIP 必须是已验证签名 release manifest 中的唯一受信制品"
      exit 1
    fi
    ACTUAL_ZIP_SHA256="${offline_sha}"
    if ! validate_zip_archive "${offline_stage}" \
      || ! unzip -tq "${offline_stage}" >/dev/null 2>&1; then
      err "离线 ZIP 结构或内容校验失败"
      exit 1
    fi
    info "使用离线 ZIP：${zip_path}"
    unzip -q "${offline_stage}" -d "${tmpdir}"
  else
    local url panel_base panel_zip repo_base manifest_url fallback_zip
    local -a candidates=()
    local -a candidate_hashes=()
    local -a candidate_sizes=()
    local fetched="0"
    local release_fields=""
    local release_git_sha=""
    local release_url=""
    local release_sha=""
    local release_size=""
    local explicit_sha="${REALM_AGENT_REPO_ZIP_SHA256:-${ACTUAL_ZIP_SHA256:-${TARGET_ZIP_SHA256:-}}}"

    url="${REALM_AGENT_REPO_ZIP_URL:-}"
    if [[ -n "${url}" ]]; then
      candidates+=("${url}")
      candidate_hashes+=("$(expected_sha256_for_url \
        "${url}" "${explicit_sha}" "$(basename "${url%%\?*}")" || true)")
      candidate_sizes+=("")
      fallback_zip="$(repo_fallback_zip_url)"
      if [[ -n "${fallback_zip}" && "${fallback_zip}" != "${url}" ]]; then
        candidates+=("${fallback_zip}")
        candidate_hashes+=("$(expected_sha256_for_url \
          "${fallback_zip}" "${REALM_AGENT_REPO_FALLBACK_ZIP_SHA256:-}" \
          "$(basename "${fallback_zip%%\?*}")" || true)")
        candidate_sizes+=("")
      fi
      info "使用自定义仓库 ZIP 地址：${url}"
    else
      panel_base="$(normalize_panel_url "${REALM_PANEL_URL:-}")"
      if [[ -n "${panel_base}" && "${REALM_AGENT_GITHUB_ONLY:-}" != "1" ]]; then
        panel_zip="${panel_base}/static/realm-agent.zip"
        candidates+=("${panel_zip}")
        candidate_hashes+=("$(expected_sha256_for_url \
          "${panel_zip}" "${explicit_sha}" "realm-agent.zip" || true)")
        candidate_sizes+=("")
      fi

      release_fields="$(resolve_release_archive \
        "${REALM_AGENT_RELEASE_METADATA_URL:-${REPO_RELEASE_METADATA_URL_DEFAULT}}" || true)"
      if [[ -n "${release_fields}" ]]; then
        IFS=$'\t' read -r release_git_sha release_url release_sha release_size \
          <<< "${release_fields}"
        candidates+=("${release_url}")
        candidate_hashes+=("${release_sha}")
        candidate_sizes+=("${release_size}")
        info "已锁定 release：git=${release_git_sha} sha256=${release_sha:0:12}..."
      fi

      if [[ -n "${REPO_ZIP_URL_DEFAULT}" ]]; then
        candidates+=("${REPO_ZIP_URL_DEFAULT}")
        candidate_hashes+=("$(expected_sha256_for_url \
          "${REPO_ZIP_URL_DEFAULT}" "${explicit_sha}" \
          "$(basename "${REPO_ZIP_URL_DEFAULT}")" || true)")
        candidate_sizes+=("")
      fi
      fallback_zip="$(repo_fallback_zip_url)"
      if [[ -n "${fallback_zip}" && -n "${REALM_AGENT_REPO_FALLBACK_ZIP_SHA256:-}" ]]; then
        candidates+=("${fallback_zip}")
        candidate_hashes+=("$(normalize_sha256 \
          "${REALM_AGENT_REPO_FALLBACK_ZIP_SHA256}" || true)")
        candidate_sizes+=("")
      fi
      info "未指定仓库 ZIP 地址，按面板 sidecar / release 元数据优先级尝试"
    fi

    local candidate cache_busted_candidate expected_sha expected_size actual_size
    local candidate_index=0
    info "正在下载并校验仓库归档..."
    for candidate in "${candidates[@]}"; do
      expected_sha="${candidate_hashes[$candidate_index]:-}"
      expected_size="${candidate_sizes[$candidate_index]:-}"
      candidate_index=$((candidate_index + 1))
      if [[ -z "${expected_sha}" ]]; then
        err "来源未绑定 SHA256，已拒绝：${candidate}"
        continue
      fi
      cache_busted_candidate="$(append_cache_bust_url "${candidate}")"
      if ! download_verified_file \
        "${cache_busted_candidate}" "${tmpdir}/repo.zip" "${expected_sha}" "仓库 ZIP"; then
        if [[ "${cache_busted_candidate}" == "${candidate}" ]] \
          || ! download_verified_file \
            "${candidate}" "${tmpdir}/repo.zip" "${expected_sha}" "仓库 ZIP"; then
          err "下载或 SHA256 校验失败，尝试下一个源：${candidate}"
          continue
        fi
      fi
      if [[ -n "${expected_size}" ]]; then
        actual_size="$(wc -c < "${tmpdir}/repo.zip" | tr -d '[:space:]')"
        if [[ "${actual_size}" != "${expected_size}" ]]; then
          err "仓库 ZIP 大小与 release 元数据不一致：${candidate}"
          rm -f "${tmpdir}/repo.zip" || true
          continue
        fi
      fi
      if ! validate_zip_archive "${tmpdir}/repo.zip" \
        || ! unzip -tq "${tmpdir}/repo.zip" >/dev/null 2>&1; then
        err "仓库 ZIP 结构或内容校验失败：${candidate}"
        rm -f "${tmpdir}/repo.zip" || true
        continue
      fi
      fetched="1"
      ACTUAL_ZIP_SHA256="${expected_sha}"
      info "下载与校验成功：${candidate}"
      break
    done
    if [[ "${fetched}" != "1" ]]; then
      repo_base="${REALM_AGENT_REPO_BASE_URL:-}"
      if [[ -z "${repo_base}" ]]; then
        if [[ ${#candidates[@]} -gt 0 ]]; then
          repo_base="$(guess_repo_base_from_zip_url "${candidates[0]}")"
        else
          repo_base="${REPO_BASE_URL_DEFAULT}"
        fi
      fi
      manifest_url="${REALM_AGENT_REPO_MANIFEST_URL:-}"
      if [[ -z "${manifest_url}" ]]; then
        if [[ "${repo_base}" == "${REPO_BASE_URL_DEFAULT}" ]]; then
          manifest_url="${REPO_MANIFEST_URL_DEFAULT}"
        else
          manifest_url="${repo_base%/}/release-manifest.json"
        fi
      fi
      info "已验证 ZIP 不可用，尝试签名 manifest 与逐文件 SHA256 清单拉取..."
      if ! download_repo_from_manifest_with_fallback "${repo_base}" "${manifest_url}" "${tmpdir}/raw"; then
        if [[ -z "${REALM_AGENT_REPO_BASE_URL:-}" && -z "${REALM_AGENT_REPO_MANIFEST_URL:-}" && "${repo_base}" != "${REPO_BASE_URL_DEFAULT}" ]]; then
          info "文件清单拉取失败，回退默认源重试..."
          if ! download_repo_from_manifest_with_fallback "${REPO_BASE_URL_DEFAULT}" "${REPO_MANIFEST_URL_DEFAULT}" "${tmpdir}/raw"; then
            err "仓库下载失败（ZIP 与清单模式均不可用）"
            exit 1
          fi
        else
          err "仓库下载失败（ZIP 与清单模式均不可用）"
          exit 1
        fi
      fi
      return 0
    fi
    info "解压中..."
    unzip -q "${tmpdir}/repo.zip" -d "${tmpdir}"
  fi
}

stop_agent_api_services(){
  if command_exists systemctl; then
    local service
    for service in realm-agent.service realm-agent-https.service; do
      if systemctl is-active --quiet "${service}" 2>/dev/null; then
        info "停止旧 Agent 服务：${service}"
        if ! systemctl stop "${service}" >/dev/null 2>&1; then
          err "无法停止旧 Agent 服务：${service}"
          return 1
        fi
        if systemctl is-active --quiet "${service}" 2>/dev/null; then
          err "旧 Agent 服务停止后仍处于 active：${service}"
          return 1
        fi
      fi
    done
  fi
}

probe_agent_protect_system_mode(){
  local mode="$1"
  local unit="realm-agent-protect-system-${mode}-$$-${RANDOM}"
  local -a args=(
    --wait
    --quiet
    --unit "${unit}"
    --property "ProtectSystem=${mode}"
  )
  if systemd-run --help 2>/dev/null | grep -q -- '--collect'; then
    args+=(--collect)
  fi
  if systemd-run "${args[@]}" /bin/true >/dev/null 2>&1; then
    return 0
  fi
  systemctl reset-failed "${unit}.service" >/dev/null 2>&1 || true
  return 1
}

prepare_agent_systemd_sandbox_compatibility(){
  local systemd_dir="${1:-}"
  local unit_file=""
  local temp_file=""
  AGENT_SYSTEMD_PROTECT_SYSTEM_MODE="strict"
  [[ -d "${systemd_dir}" ]] || {
    err "Agent staging 缺少 systemd unit 目录：${systemd_dir}"
    return 1
  }
  if ! command -v systemd-run >/dev/null 2>&1; then
    warn "缺少 systemd-run，保留 ProtectSystem=strict 交由启动门禁验证"
    return 0
  fi
  if probe_agent_protect_system_mode strict; then
    return 0
  fi
  if ! probe_agent_protect_system_mode full; then
    err "当前 systemd 无法提供 ProtectSystem=strict/full 隔离"
    return 1
  fi
  AGENT_SYSTEMD_PROTECT_SYSTEM_MODE="full"
  warn "当前 systemd 不兼容 ProtectSystem=strict；新 Agent unit 降级为 full"
  while IFS= read -r unit_file; do
    [[ -n "${unit_file}" ]] || continue
    temp_file="${unit_file}.sandbox.$$"
    if ! sed 's/^ProtectSystem=strict$/ProtectSystem=full/' \
      "${unit_file}" > "${temp_file}" \
      || ! mv -f "${temp_file}" "${unit_file}"; then
      rm -f "${temp_file}" >/dev/null 2>&1 || true
      err "无法写入 Agent systemd sandbox 兼容配置：${unit_file}"
      return 1
    fi
  done < <(
    grep -rl \
      --include='*.service' \
      '^ProtectSystem=strict$' \
      "${systemd_dir}" 2>/dev/null || true
  )
}

stop_agent_runtime_stack_for_cutover(){
  local unit=""
  local unit_kind=""
  local state=""
  command_exists systemctl || return 0
  # The second pass converges services that were reactivated by live sockets.
  for unit_kind in service socket service socket; do
    for unit in "${AGENT_CUTOVER_UNITS[@]}"; do
      [[ -n "${unit}" ]] || continue
      if [[ "${unit_kind}" == "service" && "${unit}" == *.socket ]]; then
        continue
      fi
      if [[ "${unit_kind}" == "socket" && "${unit}" != *.socket ]]; then
        continue
      fi
      state="$(agent_unit_active_state "${unit}")" || return 1
      [[ "${state}" == "active" ]] || continue
      info "切换前停止 Agent runtime：${unit}"
      if ! systemctl stop "${unit}" >/dev/null 2>&1; then
        warn "Agent runtime 首轮停止未收敛，将在 socket 关闭后重试：${unit}"
      fi
    done
  done
  for unit in "${AGENT_CUTOVER_UNITS[@]}"; do
    [[ -n "${unit}" ]] || continue
    state="$(agent_unit_active_state "${unit}")" || return 1
    if [[ "${state}" != "inactive" ]]; then
      err "Agent runtime 最终停机复核失败：${unit}"
      return 1
    fi
  done
}

stop_service_if_running(){
  stop_agent_api_services
}

activate_agent_api_service(){
  local selected_service="$1"
  local opposite_service="$2"
  systemctl daemon-reload
  if ! systemctl disable --now "${opposite_service}" >/dev/null 2>&1; then
    err "无法禁用旧 Agent 服务：${opposite_service}"
    return 1
  fi
  if systemctl is-active --quiet "${opposite_service}" 2>/dev/null \
    || systemctl is-enabled --quiet "${opposite_service}" 2>/dev/null; then
    err "旧 Agent 服务仍处于 active/enabled：${opposite_service}"
    return 1
  fi
  if ! systemctl start realm-agent-privileged.socket >/dev/null 2>&1 \
    || ! systemctl is-active --quiet realm-agent-privileged.socket 2>/dev/null; then
    err "privileged Agent UDS socket 未先进入 active"
    return 1
  fi
  if ! systemctl start realm-agent-privileged.service >/dev/null 2>&1 \
    || ! systemctl is-active --quiet realm-agent-privileged.service 2>/dev/null; then
    err "privileged Agent helper 未在 gateway 前进入 active"
    return 1
  fi
  if ! systemctl enable --now "${selected_service}" >/dev/null 2>&1; then
    err "无法启用目标 Agent 服务：${selected_service}"
    return 1
  fi
  if ! systemctl is-active --quiet "${selected_service}" 2>/dev/null; then
    err "目标 Agent 服务未进入 active：${selected_service}"
    return 1
  fi
  if ! systemctl is-enabled --quiet "${selected_service}" 2>/dev/null; then
    err "目标 Agent 服务未设为开机启用：${selected_service}"
    return 1
  fi
  if ! systemctl enable --now realm-agent.target >/dev/null 2>&1; then
    err "无法启用目标 Agent runtime stack：realm-agent.target"
    return 1
  fi
  if ! systemctl is-active --quiet realm-agent.target 2>/dev/null \
    || ! systemctl is-enabled --quiet realm-agent.target 2>/dev/null; then
    err "realm-agent.target 未达到 active/enabled"
    return 1
  fi
  local unit=""
  while IFS= read -r unit; do
    [[ -n "${unit}" && "${unit}" != "realm-agent.target" ]] || continue
    if ! systemctl is-active --quiet "${unit}" 2>/dev/null; then
      err "目标 Agent runtime member 未进入 active：${unit}"
      return 1
    fi
  done < <(agent_isolated_runtime_unit_names)
}

agent_listener_snapshot_has_pid(){
  local snapshot="${1:-}"
  local owner_pid="${2:-}"
  [[ "${owner_pid}" =~ ^[1-9][0-9]*$ ]] || return 1
  case "${snapshot}" in
    *"pid=${owner_pid},"*|*"pid=${owner_pid})"*) return 0 ;;
  esac
  return 1
}

verify_agent_privilege_boundary(){
  local selected_service="$1"
  local gateway_pid=""
  local helper_pid=""
  local runtime_pid=""
  local gateway_uid=""
  local helper_uid=""
  local runtime_uid=""
  local socket_path="/run/realm-agent-privileged.sock"
  local socket_uid=""
  local socket_gid=""
  local socket_mode=""
  local runtime_status=""
  local runtime_proof=""
  local expected_listeners=""
  local continuity_ready=""
  local python_bin=""
  local listening_sockets=""
  agent_sandbox_is_host_unit_dir || return 0
  runtime_status="$(
    read_env_value \
      "$(agent_config_dir)/agent.env" \
      "REALM_TUNNEL_RUNTIME_STATUS_PATH" || true
  )"
  [[ -n "${runtime_status}" ]] \
    || runtime_status="/var/lib/realm-agent/processes/tunnel-runtime/status.json"
  if ! command_exists ps || ! command_exists ss; then
    err "Agent 特权边界健康检查需要 ps 与 ss"
    return 1
  fi
  gateway_pid="$(systemctl show "${selected_service}" -p MainPID --value 2>/dev/null)"
  helper_pid="$(
    systemctl show realm-agent-privileged.service -p MainPID --value 2>/dev/null
  )"
  [[ "${gateway_pid}" =~ ^[1-9][0-9]*$ \
    && "${helper_pid}" =~ ^[1-9][0-9]*$ ]] || {
    err "无法读取 gateway/helper MainPID"
    return 1
  }
  gateway_uid="$(ps -o uid= -p "${gateway_pid}" | tr -d '[:space:]')"
  helper_uid="$(ps -o uid= -p "${helper_pid}" | tr -d '[:space:]')"
  [[ "${gateway_uid}" == "${AGENT_SERVICE_UID}" && "${helper_uid}" == "0" ]] || {
    err "gateway/helper UID 不符合非特权/root 边界"
    return 1
  }
  [[ -S "${socket_path}" && ! -L "${socket_path}" ]] || {
    err "privileged Agent UDS 缺失或类型不安全"
    return 1
  }
  socket_uid="$(agent_sandbox_stat_field "${socket_path}" '%u' '%u')"
  socket_gid="$(agent_sandbox_stat_field "${socket_path}" '%g' '%g')"
  socket_mode="$(agent_sandbox_stat_field "${socket_path}" '%a' '%Lp')"
  [[ "${socket_uid}" == "0" && "${socket_gid}" == "${AGENT_SERVICE_GID}" \
    && ( "${socket_mode}" == "660" || "${socket_mode}" == "0660" ) ]] || {
    err "privileged Agent UDS owner/group/mode 不符合 0:realm-agent 0660"
    return 1
  }
  listening_sockets="$(ss -H -lntup 2>/dev/null)" || {
    err "无法读取 TCP/UDP listener ownership"
    return 1
  }
  if agent_listener_snapshot_has_pid "${listening_sockets}" "${helper_pid}"; then
    err "privileged Agent helper 存在 TCP/UDP listening socket"
    return 1
  fi
  runtime_pid="$(
    systemctl show realm-tunnel-runtime.service -p MainPID --value 2>/dev/null
  )"
  [[ "${runtime_pid}" =~ ^[1-9][0-9]*$ \
    && "${runtime_pid}" != "${helper_pid}" ]] || {
    err "无法确认 isolated tunnel runtime owner PID"
    return 1
  }
  runtime_uid="$(ps -o uid= -p "${runtime_pid}" | tr -d '[:space:]')"
  [[ "${runtime_uid}" == "0" ]] || {
    err "isolated tunnel runtime owner UID 异常"
    return 1
  }
  python_bin="$(agent_contract_python || true)"
  [[ -n "${python_bin}" ]] || return 1
  runtime_proof="$(
    "${python_bin}" - "${runtime_status}" "${runtime_pid}" <<'PY'
import json
import sys
from pathlib import Path

path = Path(sys.argv[1])
expected_pid = int(sys.argv[2])
try:
    payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
    raise SystemExit(1)
manager = payload.get("manager_status")
if not isinstance(manager, dict):
    raise SystemExit(1)
required = (
    payload.get("pid") == expected_pid
    and payload.get("mode") == "active"
    and payload.get("manager_started") is True
    and payload.get("active_owner") is True
    and payload.get("data_plane_ready") is True
    and manager.get("active_owner") is True
    and manager.get("data_plane_ready") is True
)
if not required:
    raise SystemExit(1)
keys = (
    "servers",
    "tcp_rules",
    "udp_rules",
    "client_tcp_rules",
    "client_udp_rules",
    "npp_proxies",
    "npp_servers",
    "npp_bridges",
    "ssh_proxies",
    "ssh_servers",
    "ssh_bridges",
)
expected = sum(len(manager.get(key) or ()) for key in keys)
continuity = manager.get("continuity")
continuity_ready = (
    isinstance(continuity, dict)
    and continuity.get("active_owner") is True
    and continuity.get("data_plane_ready") is True
)
print(f"{expected}:{int(continuity_ready)}")
PY
  )" || {
    err "isolated tunnel runtime 未证明 active data-plane ownership"
    return 1
  }
  expected_listeners="${runtime_proof%%:*}"
  continuity_ready="${runtime_proof##*:}"
  if (( expected_listeners > 0 )) && [[ "${continuity_ready}" != "1" ]]; then
    listening_sockets="$(ss -H -lntup 2>/dev/null)" || {
      err "无法读取 TCP/UDP listener ownership"
      return 1
    }
    if ! agent_listener_snapshot_has_pid \
      "${listening_sockets}" "${runtime_pid}"; then
      err "期望的数据面 listener 不属于 isolated tunnel runtime owner"
      return 1
    fi
  fi
}

activate_agent_auxiliary_runtime(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local revtunnel="realm-agent-revtunnel.service"
  local sidecar="realm-mptcp-sidecar.service"
  local preserved_runtime=""
  if [[ "${AGENT_MPTCP_SIDECAR_SHOULD_RUN:-0}" == "1" ]]; then
    if ! systemctl enable --now "${sidecar}" >/dev/null 2>&1 \
      || ! systemctl is-enabled --quiet "${sidecar}" 2>/dev/null \
      || ! systemctl is-active --quiet "${sidecar}" 2>/dev/null; then
      err "MPTCP sidecar 未达到目标 active/enabled 状态"
      return 1
    fi
  else
    if ! systemctl disable --now "${sidecar}" >/dev/null 2>&1; then
      err "无法按目标禁用 MPTCP sidecar"
      return 1
    fi
    if systemctl is-enabled --quiet "${sidecar}" 2>/dev/null \
      || systemctl is-active --quiet "${sidecar}" 2>/dev/null; then
      err "MPTCP sidecar 目标 disabled/inactive 状态未生效"
      return 1
    fi
  fi
  for preserved_runtime in "${revtunnel}" realm.service; do
    if [[ -f "${state_dir}/${preserved_runtime}.was-active" ]]; then
      if ! systemctl start "${preserved_runtime}" >/dev/null 2>&1 \
        || ! systemctl is-active --quiet "${preserved_runtime}" 2>/dev/null; then
        err "无法恢复原 active runtime：${preserved_runtime}"
        return 1
      fi
    fi
  done
}

agent_service_restart_count(){
  local unit="$1"
  local value=""
  value="$(systemctl show "${unit}" -p NRestarts --value 2>/dev/null || true)"
  if [[ ! "${value}" =~ ^[0-9]+$ ]]; then
    err "无法读取 systemd NRestarts：${unit}"
    return 1
  fi
  printf '%s' "${value}"
}

agent_health_service_names(){
  local selected_service="$1"
  local unit=""
  printf '%s\n' "${selected_service}"
  while IFS= read -r unit; do
    [[ -n "${unit}" ]] || continue
    printf '%s\n' "${unit}"
  done < <(agent_isolated_runtime_unit_names)
  for unit in \
    realm-mptcp-sidecar.service \
    realm-agent-revtunnel.service \
    realm.service; do
    if systemctl is-active --quiet "${unit}" 2>/dev/null; then
      printf '%s\n' "${unit}"
    fi
  done
}

snapshot_agent_restart_counts(){
  local selected_service="$1"
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local unit_list="${state_dir}/health-units"
  local unit=""
  local count=""
  : > "${unit_list}" || return 1
  while IFS= read -r unit; do
    [[ -n "${unit}" ]] || continue
    printf '%s\n' "${unit}" >> "${unit_list}" || return 1
    if [[ "${unit}" == *.service ]]; then
      count="$(agent_service_restart_count "${unit}")" || return 1
      printf '%s\n' "${count}" > "${state_dir}/${unit}.health-nrestarts"
    fi
  done < <(agent_health_service_names "${selected_service}")
}

verify_agent_restart_counts(){
  local _selected_service="$1"
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local unit_list="${state_dir}/health-units"
  local unit=""
  local baseline=""
  local current=""
  if [[ ! -s "${unit_list}" ]]; then
    err "健康稳定窗口缺少冻结的 service 清单"
    return 1
  fi
  while IFS= read -r unit; do
    [[ -n "${unit}" ]] || continue
    if ! systemctl is-active --quiet "${unit}" 2>/dev/null; then
      err "健康稳定窗口内 unit 非 active：${unit}"
      return 1
    fi
    [[ "${unit}" == *.service ]] || continue
    baseline="$(cat "${state_dir}/${unit}.health-nrestarts" 2>/dev/null || true)"
    current="$(agent_service_restart_count "${unit}")" || return 1
    if [[ "${baseline}" != "${current}" ]]; then
      err "健康稳定窗口内 NRestarts 增加：${unit}"
      return 1
    fi
  done < "${unit_list}"
}

agent_probe_connect_host(){
  local bind_host="$1"
  local normalized=""
  case "${bind_host}" in
    0.0.0.0|"*")
      printf '%s' 127.0.0.1
      ;;
    ::|"[::]")
      printf '%s' ::1
      ;;
    *)
      normalized="${bind_host#[}"
      printf '%s' "${normalized%]}"
      ;;
  esac
}

probe_agent_api_with_target_key(){
  local transport="$1"
  local bind_host="$2"
  local port="$3"
  local tls_server_name="$4"
  local verify_peer="$5"
  local ca_cert="$6"
  local quiet="${7:-0}"
  local python_bin=""
  local connect_host=""
  local expected_version=""
  local current_version=""
  python_bin="$(agent_contract_python || true)"
  [[ -n "${python_bin}" ]] || {
    err "Agent 健康探测缺少 Python 3.9+"
    return 1
  }
  if [[ "${REALM_AGENT_PENDING_TARGET_API_KEY_SET:-0}" == "1" ]]; then
    expected_version="${REALM_AGENT_PENDING_TARGET_API_KEY_VERSION:-}"
    current_version="$(agent_api_key_file_version "$(agent_api_key_path)" 0 0 || true)"
    if [[ -z "${expected_version}" || "${current_version}" != "${expected_version}" ]]; then
      err "健康探测前目标 API key version/CAS 不匹配"
      return 1
    fi
  fi
  connect_host="$(agent_probe_connect_host "${bind_host}")"
  if ! (
    if [[ "${quiet}" == "1" ]]; then
      exec 2>/dev/null
    fi
    "${python_bin}" - \
      "${transport}" "${connect_host}" "${port}" "${tls_server_name}" \
      "${verify_peer}" "${ca_cert}" "$(agent_api_key_path)" <<'PY'
import json
import socket
import ssl
import sys

transport, connect_host, raw_port, server_name, verify_peer, ca_cert, key_path = (
    sys.argv[1:8]
)
port = int(raw_port)
with open(key_path, "r", encoding="utf-8") as handle:
    api_key = handle.read().strip()
if not api_key:
    raise SystemExit(1)
host_header = server_name if transport == "https" else connect_host
if ":" in host_header and not host_header.startswith("["):
    host_header = f"[{host_header}]"
request = (
    "GET /api/v1/info HTTP/1.1\r\n"
    f"Host: {host_header}:{port}\r\n"
    f"X-API-Key: {api_key}\r\n"
    "Accept: application/json\r\n"
    "Connection: close\r\n\r\n"
).encode("utf-8")
with socket.create_connection((connect_host, port), timeout=5.0) as raw_socket:
    stream = raw_socket
    if transport == "https":
        if verify_peer == "1":
            context = ssl.create_default_context(cafile=ca_cert)
        else:
            context = ssl._create_unverified_context()
        stream = context.wrap_socket(raw_socket, server_hostname=server_name)
    stream.sendall(request)
    chunks = []
    total = 0
    while True:
        chunk = stream.recv(65536)
        if not chunk:
            break
        total += len(chunk)
        if total > 4 * 1024 * 1024:
            raise SystemExit(1)
        chunks.append(chunk)
response = b"".join(chunks)
head, separator, body = response.partition(b"\r\n\r\n")
if not separator:
    raise SystemExit(1)
status_line = head.splitlines()[0].decode("ascii", errors="replace")
parts = status_line.split()
if len(parts) < 2 or not parts[1].isdigit() or not 200 <= int(parts[1]) < 300:
    raise SystemExit(1)
payload = json.loads(body.decode("utf-8"))
if not isinstance(payload, dict) or payload.get("ok") is not True:
    raise SystemExit(1)
PY
  ); then
    if [[ "${quiet}" != "1" ]]; then
      err "Agent 带目标 API key/TLS trust 的健康探测失败"
    fi
    return 1
  fi
}

wait_agent_api_ready_with_target_key(){
  local selected_service="$1"
  local transport="$2"
  local bind_host="$3"
  local port="$4"
  local tls_server_name="$5"
  local verify_peer="$6"
  local ca_cert="$7"
  local ready_timeout=""
  local ready_interval=""
  local divisor=""
  local attempts=""
  local attempt=""
  ready_timeout="$(
    parse_nonneg_int "${REALM_AGENT_HEALTH_READY_TIMEOUT:-30}" 30
  )"
  ready_interval="$(
    parse_nonneg_int "${REALM_AGENT_HEALTH_READY_INTERVAL:-1}" 1
  )"
  if (( ready_timeout > 300 || ready_interval > 30 )); then
    err "Agent 启动就绪等待参数超出安全范围"
    return 1
  fi
  divisor="${ready_interval}"
  (( divisor > 0 )) || divisor=1
  attempts=$((ready_timeout / divisor + 1))
  (( attempts >= 1 )) || attempts=1
  for ((attempt=1; attempt<=attempts; attempt++)); do
    verify_agent_restart_counts "${selected_service}" || return 1
    if probe_agent_api_with_target_key \
      "${transport}" "${bind_host}" "${port}" "${tls_server_name}" \
      "${verify_peer}" "${ca_cert}" 1 \
      && verify_agent_privilege_boundary "${selected_service}"; then
      return 0
    fi
    if (( attempt < attempts && ready_interval > 0 )); then
      sleep "${ready_interval}"
    fi
  done
  err "Agent 在 ${ready_timeout}s 内未完成带目标 key/TLS trust 的启动就绪探测"
  return 1
}

verify_agent_deploy_health(){
  local selected_service="$1"
  local transport="$2"
  local bind_host="$3"
  local port="$4"
  local tls_server_name="$5"
  local verify_peer="$6"
  local ca_cert="$7"
  local stability_seconds=""
  local sample_interval=""
  local sample_count=""
  local sample=""
  stability_seconds="$(
    parse_nonneg_int "${REALM_AGENT_HEALTH_STABILITY_SECONDS:-6}" 6
  )"
  sample_interval="$(
    parse_nonneg_int "${REALM_AGENT_HEALTH_SAMPLE_INTERVAL:-2}" 2
  )"
  if (( sample_interval > 30 || stability_seconds > 300 )); then
    err "Agent 健康稳定窗口参数超出安全范围"
    return 1
  fi
  if (( sample_interval == 0 )); then
    sample_count=2
  else
    sample_count=$((stability_seconds / sample_interval + 1))
    (( sample_count >= 2 )) || sample_count=2
  fi
  snapshot_agent_restart_counts "${selected_service}" || return 1
  wait_agent_api_ready_with_target_key \
    "${selected_service}" "${transport}" "${bind_host}" "${port}" \
    "${tls_server_name}" "${verify_peer}" "${ca_cert}" || return 1
  for ((sample=1; sample<=sample_count; sample++)); do
    verify_agent_restart_counts "${selected_service}" || return 1
    verify_agent_privilege_boundary "${selected_service}" || return 1
    if (( sample > 1 )); then
      probe_agent_api_with_target_key \
        "${transport}" "${bind_host}" "${port}" "${tls_server_name}" \
        "${verify_peer}" "${ca_cert}" || return 1
    fi
    if (( sample < sample_count && sample_interval > 0 )); then
      sleep "${sample_interval}"
    fi
  done
  ok "Agent 通过目标 key/TLS 健康探测与 NRestarts 稳定窗口"
}

parse_nonneg_int(){
  local raw="$1"
  local def="$2"
  if [[ "${raw}" =~ ^[0-9]+$ ]]; then
    printf "%s" "${raw}"
  else
    printf "%s" "${def}"
  fi
}

linux_disk_headroom_admission(){
  local required_raw="${1:-}"
  local available_raw="${2:-}"
  local label="${3:-Agent staging}"
  local reserve_raw="${REALM_AGENT_DISK_RESERVE_MIB:-256}"
  if [[ ! "${required_raw}" =~ ^[0-9]+$ \
    || ! "${available_raw}" =~ ^[0-9]+$ \
    || ! "${reserve_raw}" =~ ^[0-9]+$ \
    || ${#required_raw} -gt 15 || ${#available_raw} -gt 15 \
    || ${#reserve_raw} -gt 6 \
    || 10#${reserve_raw} -lt 128 || 10#${reserve_raw} -gt 8192 ]]; then
    err "${label} disk admission measurement is invalid"
    return 1
  fi
  local required_kib="$((10#${required_raw} + 10#${reserve_raw} * 1024))"
  if (( 10#${available_raw} < required_kib )); then
    err "${label} requires $((required_kib / 1024)) MiB available including reserve; measured $((10#${available_raw} / 1024)) MiB"
    return 1
  fi
  info "${label} disk admission: $((10#${available_raw} / 1024)) MiB available"
}

linux_path_size_kib(){
  local path="${1:-}"
  local measured=""
  [[ -n "${path}" && -e "${path}" && ! -L "${path}" ]] || return 1
  measured="$(du -sk -- "${path}" 2>/dev/null | awk 'NR == 1 {print $1}')" \
    || return 1
  [[ "${measured}" =~ ^[0-9]+$ ]] || return 1
  printf '%s\n' "${measured}"
}

linux_available_kib(){
  local path="${1:-}"
  local target="${path}"
  [[ -n "${target}" ]] || return 1
  while [[ ! -e "${target}" && "${target}" != "/" ]]; do
    target="$(dirname "${target}")"
  done
  [[ -e "${target}" && ! -L "${target}" ]] || return 1
  df -Pk -- "${target}" 2>/dev/null | awk 'NR == 2 && $4 ~ /^[0-9]+$/ {print $4}'
}

linux_stage_copy_disk_admission(){
  local source_agent="${1:-}"
  local base="${2:-}"
  local source_root=""
  local required_kib=""
  local available_kib=""
  source_root="$(dirname "${source_agent}")"
  required_kib="$(linux_path_size_kib "${source_root}" || true)"
  available_kib="$(linux_available_kib "${base}" || true)"
  linux_disk_headroom_admission \
    "${required_kib}" "${available_kib}" "Agent source staging"
}

linux_venv_rebuild_disk_admission(){
  local base="${1:-}"
  local estimate_raw="${REALM_AGENT_VENV_REBUILD_ESTIMATED_MIB:-512}"
  local existing_kib="0"
  local estimated_kib=""
  local available_kib=""
  if [[ ! "${estimate_raw}" =~ ^[0-9]+$ \
    || 10#${estimate_raw} -lt 256 || 10#${estimate_raw} -gt 8192 ]]; then
    err "REALM_AGENT_VENV_REBUILD_ESTIMATED_MIB must be 256-8192"
    return 1
  fi
  if [[ -d "${base}/venv" && ! -L "${base}/venv" ]]; then
    existing_kib="$(linux_path_size_kib "${base}/venv" || true)"
    [[ "${existing_kib}" =~ ^[0-9]+$ ]] || {
      err "Agent venv rebuild disk measurement failed"
      return 1
    }
  fi
  estimated_kib="$((10#${estimate_raw} * 1024))"
  if (( 10#${existing_kib} > estimated_kib )); then
    estimated_kib="$((10#${existing_kib}))"
  fi
  available_kib="$(linux_available_kib "${base}" || true)"
  linux_disk_headroom_admission \
    "${estimated_kib}" "${available_kib}" "Agent venv rebuild"
}

linux_venv_rebuild_admission(){
  local meminfo="${1:-/proc/meminfo}"
  local minimum_raw="${REALM_AGENT_VENV_REBUILD_MIN_AVAILABLE_MIB:-384}"
  local minimum_mib=""
  local measured=""
  local mem_available_kib=""
  local swap_total_kib=""
  local swap_free_kib=""
  local available_kib=0
  if [[ ! "${minimum_raw}" =~ ^[0-9]+$ ]] \
    || (( 10#${minimum_raw} < 256 || 10#${minimum_raw} > 4096 )); then
    err "REALM_AGENT_VENV_REBUILD_MIN_AVAILABLE_MIB must be 256-4096"
    return 1
  fi
  minimum_mib="$((10#${minimum_raw}))"
  if [[ ! -f "${meminfo}" || -L "${meminfo}" ]]; then
    err "memory admission data is unavailable: ${meminfo}"
    return 1
  fi
  measured="$({
    awk '
      $1 == "MemAvailable:" {
        if ($2 !~ /^[0-9]+$/ || $3 != "kB") exit 2
        available = $2; have_available = 1
      }
      $1 == "SwapTotal:" {
        if ($2 !~ /^[0-9]+$/ || $3 != "kB") exit 2
        swap_total = $2; have_swap_total = 1
      }
      $1 == "SwapFree:" {
        if ($2 !~ /^[0-9]+$/ || $3 != "kB") exit 2
        swap_free = $2; have_swap_free = 1
      }
      END {
        if (!have_available || !have_swap_total || !have_swap_free) exit 3
        printf "%s %s %s\n", available, swap_total, swap_free
      }
    ' "${meminfo}"
  } 2>/dev/null)" || {
    err "memory admission measurement is invalid: ${meminfo}"
    return 1
  }
  IFS=' ' read -r mem_available_kib swap_total_kib swap_free_kib \
    <<< "${measured}"
  if [[ ! "${mem_available_kib}" =~ ^[0-9]+$ \
    || ! "${swap_total_kib}" =~ ^[0-9]+$ \
    || ! "${swap_free_kib}" =~ ^[0-9]+$ ]]; then
    err "memory admission measurement is invalid: ${meminfo}"
    return 1
  fi
  available_kib="$((10#${mem_available_kib}))"
  if (( 10#${swap_total_kib} > 0 )); then
    available_kib="$((available_kib + 10#${swap_free_kib}))"
  fi
  if (( available_kib < minimum_mib * 1024 )); then
    err "Agent venv rebuild requires at least ${minimum_mib} MiB available memory plus active swap; measured $((available_kib / 1024)) MiB"
    return 1
  fi
  info "Agent venv rebuild memory admission: $((available_kib / 1024)) MiB available (minimum ${minimum_mib} MiB)"
}

create_isolated_linux_agent_venv(){
  local python_bin="$1"
  local target="$2"
  local timeout_seconds="$3"
  local use_copies="${4:-0}"
  local -a venv_args=(-I -S -B -m venv --without-pip)
  [[ -n "${python_bin}" && -n "${target}" ]] || return 1
  if [[ "${use_copies}" == "1" ]]; then
    venv_args+=(--copies)
  fi
  run_with_timeout "${timeout_seconds}" "创建隔离虚拟环境（staging）" \
    env -i \
      PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
      HOME=/root \
      PYTHONDONTWRITEBYTECODE=1 \
      PYTHONNOUSERSITE=1 \
      SETUPTOOLS_USE_DISTUTILS=stdlib \
      "${python_bin}" "${venv_args[@]}" "${target}"
}

bootstrap_linux_venv_pip(){
  local py="$1"
  local stage="$2"
  local timeout_seconds="$3"
  local bootstrap="${stage}/agent/app/services/venv_pip_bootstrap.py"
  if [[ -z "${py}" || ! -x "${py}" \
        || ! -f "${bootstrap}" || -L "${bootstrap}" ]]; then
    err "Agent venv pip bootstrap input is incomplete"
    return 1
  fi
  if ! run_with_timeout \
    "${timeout_seconds}" "无字节码引导 Agent venv pip" \
    env -i \
      PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
      HOME=/root \
      PYTHONDONTWRITEBYTECODE=1 \
      PYTHONNOUSERSITE=1 \
      SETUPTOOLS_USE_DISTUTILS=stdlib \
      "${py}" -I -B "${bootstrap}"; then
    err "Agent venv pip no-bytecode bootstrap failed"
    return 1
  fi
}

resolve_agent_v2_wal_root(){
  local path="${REALM_AGENT_V2_WAL_ROOT:-/var/lib/realm-agent/control-plane/wal}"
  case "${path}" in
    /var/lib/realm-agent/*)
      if [[ "${path}" == *"/../"* \
        || "${path}" == */.. \
        || "${path}" == *"/./"* \
        || "${path}" == */. \
        || "${path}" == *"//"* ]]; then
        err "REALM_AGENT_V2_WAL_ROOT 必须是规范化的 /var/lib/realm-agent 子目录"
        return 1
      fi
      ;;
    *)
      err "REALM_AGENT_V2_WAL_ROOT 必须位于 /var/lib/realm-agent 下"
      return 1
      ;;
  esac
  printf '%s' "${path}"
}

default_pip_fallback_indexes(){
  printf '%s\n' "https://mirrors.aliyun.com/pypi/simple,https://pypi.tuna.tsinghua.edu.cn/simple,https://pypi.org/simple"
}

pip_fallback_indexes_raw(){
  printf '%s\n' "${REALM_AGENT_PIP_FALLBACK_INDEXES:-$(default_pip_fallback_indexes)}"
}

redact_url_for_log(){
  REALM_AGENT_REDACT_URL_INPUT="${1:-}" python3 - <<'PY'
import os
import re
import sys

value = os.environ.get("REALM_AGENT_REDACT_URL_INPUT", "")
userinfo = re.compile(r"(?i)\b(https?://)[^/\s]*@")
query_value = re.compile(r"([?&][^=&#\s]+=)[^&#\s]*")
value = userinfo.sub(r"\1***@", value)
sys.stdout.write(query_value.sub(r"\1***", value))
PY
}

pip_supports_legacy_resolver(){
  local pip_bin="${1:-}"
  [[ -n "${pip_bin}" && -x "${pip_bin}" ]] || return 1
  env \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONNOUSERSITE=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    PIP_NO_INPUT=1 \
    "${pip_bin}" help install 2>/dev/null | grep -q 'legacy-resolver'
}

pip_resolver_modes(){
  local pip_bin="${1:-}"
  local force_legacy_raw="${REALM_AGENT_PIP_FORCE_LEGACY_RESOLVER:-0}"
  local enable_legacy_fallback_raw="${REALM_AGENT_PIP_ENABLE_LEGACY_RESOLVER_FALLBACK:-1}"
  local force_legacy
  local enable_legacy_fallback
  force_legacy="$(normalize_bool_or_default "${force_legacy_raw}" 0)"
  enable_legacy_fallback="$(
    normalize_bool_or_default "${enable_legacy_fallback_raw}" 1
  )"

  if [[ "${force_legacy}" == "1" ]]; then
    printf 'legacy\n'
    return 0
  fi

  printf 'modern\n'
  if [[ "${enable_legacy_fallback}" == "1" ]]; then
    if pip_supports_legacy_resolver "${pip_bin}"; then
      printf 'legacy\n'
    fi
  fi
}

pip_index_probe_one(){
  local idx="${1:-}"
  [[ -n "${idx}" ]] || return 1
  command_exists curl || return 1
  case "${idx}" in
    *$'\n'*|*$'\r'*|*'"'*|*'\\'*) return 1 ;;
  esac
  if printf 'url = "%s"\n' "${idx}" \
    | curl -fsSIL --connect-timeout 2 --max-time 5 --retry 0 \
      --config - >/dev/null 2>&1; then
    return 0
  fi
  printf 'url = "%s"\n' "${idx}" \
    | curl -fsSL --connect-timeout 2 --max-time 5 --retry 0 \
      -o /dev/null --config - >/dev/null 2>&1
}

pip_index_any_reachable(){
  local primary_index="${REALM_AGENT_PIP_INDEX_URL:-}"
  local fallback_raw
  fallback_raw="$(pip_fallback_indexes_raw)"
  local disable_fallback=""
  disable_fallback="$(
    normalize_bool_or_default "${REALM_AGENT_PIP_DISABLE_FALLBACK:-0}" 0
  )"

  local seen="|"
  local idx
  if [[ -n "${primary_index}" ]]; then
    if pip_index_probe_one "${primary_index}"; then
      return 0
    fi
    seen="${seen}${primary_index}|"
  fi
  if [[ "${disable_fallback}" != "1" ]]; then
    fallback_raw="${fallback_raw//,/ }"
    for idx in ${fallback_raw}; do
      [[ -n "${idx}" ]] || continue
      if [[ "${seen}" == *"|${idx}|"* ]]; then
        continue
      fi
      if pip_index_probe_one "${idx}"; then
        return 0
      fi
      seen="${seen}${idx}|"
    done
  fi
  return 1
}

pip_install_from_wheels(){
  local pip_bin="$1"
  local timeout_seconds="$2"
  local label="$3"
  local wheel_dir="$4"
  shift 4
  local -a install_args=("$@")
  if [[ -z "${wheel_dir}" || ! -d "${wheel_dir}" ]]; then
    return 1
  fi
  run_with_timeout "${timeout_seconds}" "${label}" \
    "${pip_bin}" install --no-input --no-index \
    --no-cache-dir --no-compile \
    --find-links "${wheel_dir}" "${install_args[@]}"
}

wheelhouse_has_wheels(){
  local wheel_dir="${1:-}"
  [[ -n "${wheel_dir}" && -d "${wheel_dir}" ]] || return 1
  find "${wheel_dir}" -maxdepth 1 -type f \( -name '*.whl' -o -name '*.tar.gz' -o -name '*.zip' \) -print -quit | grep -q .
}

requirements_file_uses_hashes(){
  local req_file="${1:-}"
  [[ -n "${req_file}" && "${req_file}" == *.lock ]]
}

select_agent_requirements_file(){
  local agent_dir="${1:-}"
  local req_lock="${agent_dir}/requirements.lock"
  if [[ -s "${req_lock}" ]]; then
    printf '%s\n' "${req_lock}"
    return 0
  fi
  return 1
}

wheelhouse_satisfies_requirements(){
  local pip_bin="$1"
  local req_file="$2"
  local wheel_dir="$3"
  [[ -x "${pip_bin}" && -f "${req_file}" && -d "${wheel_dir}" ]] || return 1
  local tmp=""
  local -a hash_args=()
  if requirements_file_uses_hashes "${req_file}"; then
    hash_args=(--require-hashes)
  fi
  tmp="$(mktemp -d "${TMPDIR:-/tmp}/realm-agent-wheels.XXXXXX" 2>/dev/null || true)"
  [[ -n "${tmp}" && -d "${tmp}" ]] || return 1
  register_cleanup_path "${tmp}"
  if "${pip_bin}" download --disable-pip-version-check --no-cache-dir \
    --no-deps --no-index \
    --find-links "${wheel_dir}" "${hash_args[@]}" -r "${req_file}" \
    -d "${tmp}" >/dev/null 2>&1; then
    rm -rf "${tmp}" || true
    return 0
  fi
  rm -rf "${tmp}" || true
  return 1
}

# 返回 0 表示包内 wheelhouse 可在离线环境下重建出满足 lock 的依赖；
# 返回 1 表示 wheelhouse 缺失或无法满足 requirements（正谓词语义）。
offline_wheelhouse_can_rebuild(){
  local agent_dir="$1"
  local wheel_dir="$2"
  local has_local_wheels="$3"
  local existing_pip="$4"
  local req_file=""
  [[ "${has_local_wheels}" == "1" ]] || return 1
  req_file="$(select_agent_requirements_file "${agent_dir}" || true)"
  [[ -n "${req_file}" ]] || return 1
  wheelhouse_satisfies_requirements "${existing_pip}" "${req_file}" "${wheel_dir}"
}

pip_install_attempt(){
  local pip_bin="$1"
  local timeout_seconds="$2"
  local label="$3"
  local index_url="$4"
  local extra_index_url="$5"
  local resolver_mode="$6"
  shift 6
  (
    export PYTHONDONTWRITEBYTECODE=1
    export PYTHONNOUSERSITE=1
    export PIP_DISABLE_PIP_VERSION_CHECK=1
    export PIP_NO_INPUT=1
    if [[ -n "${index_url}" ]]; then
      export PIP_INDEX_URL="${index_url}"
    fi
    if [[ -n "${extra_index_url}" ]]; then
      export PIP_EXTRA_INDEX_URL="${extra_index_url}"
    fi
    if [[ "${resolver_mode}" == "legacy" ]]; then
      export PIP_USE_DEPRECATED=legacy-resolver
    fi
    run_with_timeout "${timeout_seconds}" "${label}" "${pip_bin}" "$@"
  )
}

pip_install_with_fallback(){
  local pip_bin="$1"
  local timeout_seconds="$2"
  local label="$3"
  shift 3
  local -a install_args=("$@")

  local primary_index="${REALM_AGENT_PIP_INDEX_URL:-}"
  local extra_index="${REALM_AGENT_PIP_EXTRA_INDEX_URL:-}"
  local trusted_host_raw="${REALM_AGENT_PIP_TRUSTED_HOST:-}"
  local fallback_raw
  fallback_raw="$(pip_fallback_indexes_raw)"
  local disable_fallback=""
  disable_fallback="$(
    normalize_bool_or_default "${REALM_AGENT_PIP_DISABLE_FALLBACK:-0}" 0
  )"

  local -a pip_args=(
    install
    --no-input --no-cache-dir --no-compile
    --prefer-binary --timeout 60 --retries 2
  )

  local host
  trusted_host_raw="${trusted_host_raw//,/ }"
  for host in ${trusted_host_raw}; do
    [[ -n "${host}" ]] || continue
    pip_args+=(--trusted-host "${host}")
  done

  local -a candidates=()
  local seen="|"
  local idx
  if [[ -n "${primary_index}" ]]; then
    candidates+=("${primary_index}")
    seen="${seen}${primary_index}|"
  fi
  if [[ "${disable_fallback}" != "1" ]]; then
    fallback_raw="${fallback_raw//,/ }"
    for idx in ${fallback_raw}; do
      [[ -n "${idx}" ]] || continue
      if [[ "${seen}" == *"|${idx}|"* ]]; then
        continue
      fi
      candidates+=("${idx}")
      seen="${seen}${idx}|"
    done
  fi

  local candidate candidate_log resolver_mode
  local legacy_announced="0"
  for resolver_mode in $(pip_resolver_modes "${pip_bin}"); do
    local resolver_label="${label}"
    if [[ "${resolver_mode}" == "legacy" ]]; then
      resolver_label="${label}（legacy resolver）"
      if [[ "${legacy_announced}" != "1" ]]; then
        info "${label}：常规 resolver 失败或解析过慢，尝试 legacy resolver"
        legacy_announced="1"
      fi
    fi

    if (( ${#candidates[@]} == 0 )); then
      if pip_install_attempt \
        "${pip_bin}" "${timeout_seconds}" "${resolver_label}" \
        "" "${extra_index}" "${resolver_mode}" \
        "${pip_args[@]}" "${install_args[@]}"; then
        return 0
      fi
      continue
    fi

    for candidate in "${candidates[@]}"; do
      candidate_log="$(redact_url_for_log "${candidate}")"
      info "${resolver_label}：尝试索引 ${candidate_log}"
      if pip_install_attempt \
        "${pip_bin}" "${timeout_seconds}" \
        "${resolver_label}（索引 ${candidate_log}）" \
        "${candidate}" "${extra_index}" "${resolver_mode}" \
        "${pip_args[@]}" "${install_args[@]}"; then
        return 0
      fi
      err "${resolver_label} 失败：${candidate_log}"
      if [[ "${disable_fallback}" == "1" ]]; then
        break
      fi
    done
  done
  return 1
}

compute_requirements_sha256(){
  local file="$1"
  [[ -f "${file}" ]] || return 1
  if command_exists sha256sum; then
    sha256sum "${file}" | awk '{print $1}'
  elif command_exists shasum; then
    shasum -a 256 "${file}" | awk '{print $1}'
  else
    return 1
  fi
}

durable_replace_agent_state_file(){
  local source="$1"
  local target="$2"
  python3 - "${source}" "${target}" <<'PY'
import os
import pathlib
import stat
import sys

source = pathlib.Path(sys.argv[1])
target = pathlib.Path(sys.argv[2])
if not source.is_absolute() or not target.is_absolute():
    raise SystemExit("durable replace paths must be absolute")
if source.parent != target.parent:
    raise SystemExit("durable replace requires a same-directory source")
flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
descriptor = os.open(source, flags)
try:
    if not stat.S_ISREG(os.fstat(descriptor).st_mode):
        raise SystemExit("durable replace source must be a regular file")
    os.fsync(descriptor)
finally:
    os.close(descriptor)
os.replace(source, target)
directory_flags = (
    os.O_RDONLY
    | getattr(os, "O_CLOEXEC", 0)
    | getattr(os, "O_DIRECTORY", 0)
    | getattr(os, "O_NOFOLLOW", 0)
)
directory_descriptor = os.open(target.parent, directory_flags)
try:
    os.fsync(directory_descriptor)
finally:
    os.close(directory_descriptor)
PY
}

verify_agent_venv_attestation_file(){
  local path="$1"
  local expected_kind="${2:-either}"
  local bootstrap=""
  bootstrap="$(trusted_agent_bootstrap_python || true)"
  [[ -n "${bootstrap}" ]] || return 1
  "${bootstrap}" -I -S - "${path}" "${expected_kind}" <<'PY'
import json
import pathlib
import re
import sys

path = pathlib.Path(sys.argv[1])
expected_kind = sys.argv[2]
raw = path.read_bytes()
if len(raw) > 128 * 1024:
    raise SystemExit("venv attestation is too large")
payload = json.loads(raw)
required = {
    "allowed_extras",
    "distribution_count",
    "distribution_map_sha256",
    "lock_sha256",
    "python",
    "record_proof_sha256",
    "schema_version",
    "status",
}
binding = {"agent_release_zip_sha256", "agent_version"}
fields = frozenset(payload) if isinstance(payload, dict) else frozenset()
base_fields = frozenset(required)
final_fields = frozenset(required | binding)
if fields not in {base_fields, final_fields}:
    raise SystemExit("venv attestation fields are invalid")
if expected_kind not in {"base", "final", "either"}:
    raise SystemExit("venv attestation expected kind is invalid")
if expected_kind == "base" and fields != base_fields:
    raise SystemExit("venv attestation base fields are invalid")
if expected_kind == "final" and fields != final_fields:
    raise SystemExit("venv attestation final fields are invalid")
if payload.get("schema_version") != 1 or payload.get("status") != "ok":
    raise SystemExit("venv attestation status is invalid")
for field in ("lock_sha256", "distribution_map_sha256", "record_proof_sha256"):
    if re.fullmatch(r"[0-9a-f]{64}", str(payload.get(field) or "")) is None:
        raise SystemExit(f"venv attestation {field} is invalid")
python_identity = payload.get("python")
if not isinstance(python_identity, dict) or set(python_identity) != {
    "implementation",
    "machine",
    "platform_tag",
    "soabi",
    "sys_platform",
    "version",
}:
    raise SystemExit("venv attestation Python identity is invalid")
if (
    isinstance(payload.get("distribution_count"), bool)
    or not isinstance(payload.get("distribution_count"), int)
    or payload["distribution_count"] <= 0
    or not isinstance(payload.get("allowed_extras"), list)
    or not all(isinstance(item, str) for item in payload["allowed_extras"])
):
    raise SystemExit("venv attestation distribution inventory is invalid")
if fields == final_fields:
    release_zip_sha = payload.get("agent_release_zip_sha256")
    agent_version = payload.get("agent_version")
    if not isinstance(release_zip_sha, str) or (
        release_zip_sha
        and re.fullmatch(r"[0-9a-f]{64}", release_zip_sha) is None
    ):
        raise SystemExit("venv attestation release ZIP SHA is invalid")
    if not isinstance(agent_version, str) or re.fullmatch(
        r"[0-9][0-9A-Za-z._+-]{0,63}",
        agent_version,
    ) is None:
        raise SystemExit("venv attestation Agent version is invalid")
canonical = (
    json.dumps(payload, ensure_ascii=True, separators=(",", ":"), sort_keys=True)
    + "\n"
).encode("utf-8")
if raw != canonical:
    raise SystemExit("venv attestation is not canonical JSON")
PY
}

agent_venv_attestation_reason(){
  local path="$1"
  local bootstrap=""
  bootstrap="$(trusted_agent_bootstrap_python || true)"
  [[ -n "${bootstrap}" ]] || return 0
  "${bootstrap}" -I -S - "${path}" <<'PY'
import json
import pathlib
import re
import sys

try:
    payload = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8"))
except Exception:
    raise SystemExit(0)
reason = str(payload.get("reason_code") or "")
if re.fullmatch(r"[a-z0-9_]{1,80}", reason):
    print(reason)
PY
}

preflight_agent_venv_startup(){
  local py="$1"
  local stage="$2"
  local preflight="${stage}/agent/app/services/venv_startup_preflight.py"
  local venv_root=""
  local timeout_seconds=""
  local output=""
  local reason=""
  if [[ -z "${py}" || ! -x "${py}" || ! -f "${preflight}" \
    || -L "${preflight}" ]]; then
    err "Agent venv 启动预检输入不完整"
    return 1
  fi
  venv_root="$(dirname "$(dirname "${py}")")"
  timeout_seconds="$(
    parse_nonneg_int "${REALM_AGENT_VENV_VERIFY_TIMEOUT:-240}" 240
  )"
  if (( timeout_seconds < 30 || timeout_seconds > 1800 )); then
    err "REALM_AGENT_VENV_VERIFY_TIMEOUT 必须为 30-1800 秒"
    return 1
  fi
  output="$(mktemp "${TMPDIR:-/tmp}/realm-agent-venv-preflight.XXXXXX")" \
    || return 1
  register_cleanup_path "${output}"
  if ! run_with_timeout \
    "${timeout_seconds}" "隔离预检 Agent venv 启动边界" \
    env -i \
      PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
      HOME="${HOME:-/root}" \
      PYTHONDONTWRITEBYTECODE=1 \
      PYTHONNOUSERSITE=1 \
      SETUPTOOLS_USE_DISTUTILS=stdlib \
      "${py}" -I -S -B "${preflight}" \
        --venv-root "${venv_root}" \
        --python-executable "${py}" > "${output}"; then
    reason="$(agent_venv_attestation_reason "${output}" || true)"
    err "Agent venv 未通过隔离启动预检${reason:+：${reason}}"
    return 1
  fi
}

verify_agent_venv_lock(){
  local py="$1"
  local stage="$2"
  local output="$3"
  local verifier="${stage}/agent/app/services/venv_lock_verifier.py"
  local verifier_bootstrap="${stage}/agent/app/services/venv_lock_verifier_bootstrap.py"
  local req_file=""
  local venv_root=""
  local timeout_seconds=""
  local temp_output=""
  local reason=""

  rm -f "${output}" >/dev/null 2>&1 || true
  if [[ -z "${py}" || ! -x "${py}" \
        || -z "${stage}" || ! -d "${stage}/agent" \
        || ! -f "${verifier}" || -L "${verifier}" \
        || ! -f "${verifier_bootstrap}" || -L "${verifier_bootstrap}" ]]; then
    err "Agent venv lock 验证输入不完整"
    return 1
  fi
  preflight_agent_venv_startup "${py}" "${stage}" || return 1
  req_file="$(select_agent_requirements_file "${stage}/agent" || true)"
  if [[ -z "${req_file}" ]]; then
    err "Agent venv lock 验证缺少 requirements.lock"
    return 1
  fi
  venv_root="$(dirname "$(dirname "${py}")")"
  timeout_seconds="$(
    parse_nonneg_int "${REALM_AGENT_VENV_VERIFY_TIMEOUT:-240}" 240
  )"
  if (( timeout_seconds < 30 || timeout_seconds > 1800 )); then
    err "REALM_AGENT_VENV_VERIFY_TIMEOUT 必须为 30-1800 秒"
    return 1
  fi
  temp_output="$(mktemp "${output}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${temp_output}"
  if ! run_with_timeout \
    "${timeout_seconds}" "验证 Agent venv 与 requirements.lock 等价性" \
    env -i \
      PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
      HOME="${HOME:-/root}" \
      PYTHONDONTWRITEBYTECODE=1 \
      PYTHONNOUSERSITE=1 \
      PIP_DISABLE_PIP_VERSION_CHECK=1 \
      PIP_NO_INPUT=1 \
      SETUPTOOLS_USE_DISTUTILS=stdlib \
    "${py}" -I -S -B "${verifier_bootstrap}" \
      --requirements-lock "${req_file}" \
      --venv-root "${venv_root}" \
      --source-root "${stage}" > "${temp_output}"; then
    reason="$(agent_venv_attestation_reason "${temp_output}" || true)"
    err "Agent venv 未通过严格 lock/RECORD/ABI 校验${reason:+：${reason}}"
    rm -f "${temp_output}" >/dev/null 2>&1 || true
    return 1
  fi
  if ! verify_agent_venv_attestation_file "${temp_output}" base; then
    err "Agent venv 验证器未返回有效证明"
    rm -f "${temp_output}" >/dev/null 2>&1 || true
    return 1
  fi
  chmod 0600 "${temp_output}" || return 1
  durable_replace_agent_state_file "${temp_output}" "${output}"
}

write_agent_venv_attestation(){
  local source="$1"
  local target="$2"
  local expected_lock_sha="$3"
  local release_zip_sha="${4:-}"
  local version="${VERSION#v}"
  local temp=""
  local bootstrap=""

  verify_agent_venv_attestation_file "${source}" base || return 1
  release_zip_sha="$(normalize_sha256 "${release_zip_sha}" || true)"
  bootstrap="$(trusted_agent_bootstrap_python || true)"
  [[ -n "${bootstrap}" ]] || return 1
  temp="$(mktemp "${target}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${temp}"
  "${bootstrap}" -I -S - \
    "${source}" "${temp}" "${expected_lock_sha}" \
    "${release_zip_sha}" "${version}" <<'PY'
import json
import os
import pathlib
import re
import sys

source, target = map(pathlib.Path, sys.argv[1:3])
expected_lock_sha, release_zip_sha, version = sys.argv[3:6]
payload = json.loads(source.read_text(encoding="utf-8"))
if payload.get("lock_sha256") != expected_lock_sha:
    raise SystemExit("venv attestation lock SHA does not match installed source")
if release_zip_sha and re.fullmatch(r"[0-9a-f]{64}", release_zip_sha) is None:
    raise SystemExit("venv attestation release ZIP SHA is invalid")
if re.fullmatch(r"[0-9][0-9A-Za-z._+-]{0,63}", version) is None:
    raise SystemExit("venv attestation Agent version is invalid")
payload["agent_release_zip_sha256"] = release_zip_sha
payload["agent_version"] = version
encoded = (
    json.dumps(payload, ensure_ascii=True, separators=(",", ":"), sort_keys=True)
    + "\n"
).encode("utf-8")
with target.open("wb") as handle:
    handle.write(encoded)
    handle.flush()
    os.fsync(handle.fileno())
PY
  chmod 0600 "${temp}" || return 1
  durable_replace_agent_state_file "${temp}" "${target}" || return 1
  verify_agent_venv_attestation_file "${target}" final
}

repair_venv_script_shebangs(){
  local venv_dir="${1:-}"
  local old_venv_dir="${2:-}"
  local new_venv_dir="${3:-${venv_dir}}"
  local bootstrap=""
  local repaired=""
  [[ -n "${venv_dir}" && -d "${venv_dir}/bin" \
    && -n "${old_venv_dir}" && -n "${new_venv_dir}" ]] || return 0
  bootstrap="$(trusted_agent_bootstrap_python || true)"
  [[ -n "${bootstrap}" ]] || {
    err "修复 venv shebang 缺少可信系统 Python"
    return 1
  }
  repaired="$("${bootstrap}" -I -S - \
    "${venv_dir}" "${old_venv_dir}" "${new_venv_dir}" <<'PY'
import base64
import configparser
import csv
import hashlib
import io
import os
import re
import stat
import sys
from pathlib import Path, PurePosixPath

root = Path(os.path.abspath(sys.argv[1]))
old_root = Path(os.path.abspath(sys.argv[2]))
new_root = Path(os.path.abspath(sys.argv[3]))
scripts = root / "bin"
owner_uid = os.geteuid()
entry_point_pattern = re.compile(
    r"^\s*([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*:"
    r"\s*([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)"
    r"(?:\s*\[[A-Za-z0-9_.-]+(?:\s*,\s*[A-Za-z0-9_.-]+)*\])?\s*$"
)


def fail(message):
    raise SystemExit(message)


def metadata(path, directory=False):
    value = path.lstat()
    expected = stat.S_ISDIR if directory else stat.S_ISREG
    if (
        stat.S_ISLNK(value.st_mode)
        or not expected(value.st_mode)
        or value.st_uid != owner_uid
        or value.st_mode & 0o022
        or (not directory and value.st_nlink != 1)
    ):
        fail(f"unsafe venv repair path: {path}")
    return value


def lexical(path):
    return Path(os.path.abspath(os.fspath(path)))


def within(path, parent):
    try:
        path.relative_to(parent)
    except ValueError:
        return False
    return True


def file_bytes(path, before):
    flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0)
    flags |= getattr(os, "O_NOFOLLOW", 0)
    descriptor = os.open(path, flags)
    try:
        opened = os.fstat(descriptor)
        if (opened.st_dev, opened.st_ino) != (before.st_dev, before.st_ino):
            fail(f"venv repair path changed: {path}")
        with os.fdopen(descriptor, "rb", closefd=True) as handle:
            descriptor = -1
            data = handle.read()
            finished = os.fstat(handle.fileno())
        if (
            opened.st_size,
            opened.st_mtime_ns,
            opened.st_ctime_ns,
            opened.st_mode,
            opened.st_nlink,
        ) != (
            finished.st_size,
            finished.st_mtime_ns,
            finished.st_ctime_ns,
            finished.st_mode,
            finished.st_nlink,
        ):
            fail(f"venv repair path changed while reading: {path}")
        return data
    finally:
        if descriptor >= 0:
            os.close(descriptor)


def record_hash(data):
    encoded = base64.urlsafe_b64encode(hashlib.sha256(data).digest())
    return "sha256=" + encoded.rstrip(b"=").decode("ascii")


def record_target(site_root, name):
    relative = PurePosixPath(name)
    if (
        not name
        or "\\" in name
        or "\x00" in name
        or relative.is_absolute()
        or relative.as_posix() != name
        or any(part in {"", "."} for part in relative.parts)
    ):
        return None
    return lexical(site_root.joinpath(*relative.parts))


def verified_record_binding(record, target):
    rows, _, _, site_root, _ = record_states[record]
    matches = []
    for index, row in enumerate(rows):
        if record_target(site_root, row[0]) == target:
            matches.append((index, row))
    if len(matches) != 1:
        return None
    index, row = matches[0]
    before = metadata(target)
    raw = file_bytes(target, before)
    if (
        not row[1].startswith("sha256=")
        or not row[2].isdigit()
        or row[1] != record_hash(raw)
        or int(row[2]) != len(raw)
    ):
        return None
    return index, raw


def console_entry_points(record):
    rows, _, _, _, dist_info = record_states[record]
    entry_points = dist_info / "entry_points.txt"
    try:
        entry_points.lstat()
    except FileNotFoundError:
        return {}
    binding = verified_record_binding(record, entry_points)
    if binding is None:
        fail(f"untrusted console entry point metadata: {entry_points}")
    _, raw = binding
    try:
        text = raw.decode("utf-8")
        parser = configparser.ConfigParser(interpolation=None, strict=True)
        parser.optionxform = str
        parser.read_string(text)
    except (UnicodeDecodeError, configparser.Error):
        fail(f"invalid console entry point metadata: {entry_points}")
    if not parser.has_section("console_scripts"):
        return {}
    result = {}
    for name, value in parser.items("console_scripts"):
        name = name.strip()
        match = entry_point_pattern.fullmatch(value)
        if (
            not name
            or "/" in name
            or "\\" in name
            or "\x00" in name
            or match is None
        ):
            fail(f"invalid console entry point metadata: {entry_points}")
        result[name] = (match.group(1), match.group(2))
    return result


def canonical_console_script_body(module, attribute):
    imported = attribute.split(".", 1)[0]
    call = attribute
    common = (
        f"import re\n"
        f"import sys\n"
        f"from {module} import {imported}\n"
        f"if __name__ == '__main__':\n"
        f"    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n"
        f"    sys.exit({call}())\n"
    ).encode("utf-8")
    return {
        b"# -*- coding: utf-8 -*-\n" + common,
        common,
        (
            f"import sys\n"
            f"from {module} import {imported}\n"
            f"if __name__ == '__main__':\n"
            f"    sys.exit({call}())\n"
        ).encode("utf-8"),
    }


def legacy_console_owner(script, body):
    claims = []
    for record in sorted(record_states):
        target = console_entry_points(record).get(script.name)
        if target is not None:
            claims.append((record, target))
    if len(claims) != 1:
        fail(f"repaired script lacks one RECORD owner: {script}")
    record, (module, attribute) = claims[0]
    if body not in canonical_console_script_body(module, attribute):
        fail(f"historical console script does not match its entry point: {script}")
    return record


def atomic_write(path, data, before, sequence):
    temporary = path.parent / f".{path.name}.repair.{os.getpid()}.{sequence}"
    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
    flags |= getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
    descriptor = os.open(temporary, flags, 0o600)
    try:
        with os.fdopen(descriptor, "wb", closefd=True) as handle:
            descriptor = -1
            handle.write(data)
            handle.flush()
            os.fchmod(handle.fileno(), stat.S_IMODE(before.st_mode))
            if os.geteuid() == 0:
                os.fchown(handle.fileno(), before.st_uid, before.st_gid)
            os.fsync(handle.fileno())
        os.replace(temporary, path)
        directory = os.open(
            path.parent,
            os.O_RDONLY
            | getattr(os, "O_CLOEXEC", 0)
            | getattr(os, "O_DIRECTORY", 0)
            | getattr(os, "O_NOFOLLOW", 0),
        )
        try:
            os.fsync(directory)
        finally:
            os.close(directory)
    finally:
        if descriptor >= 0:
            os.close(descriptor)
        try:
            temporary.unlink()
        except FileNotFoundError:
            pass


metadata(root, directory=True)
metadata(scripts, directory=True)
record_states = {}
owners = {}
candidate_site_roots = sorted(
    {
        *root.glob("lib/python*/site-packages"),
        *root.glob("lib64/python*/site-packages"),
    }
)
site_roots = []
seen_site_root_ids = set()
for site_root in candidate_site_roots:
    site_metadata = metadata(site_root, directory=True)
    site_root_id = (site_metadata.st_dev, site_metadata.st_ino)
    if site_root_id in seen_site_root_ids:
        continue
    # Some Linux venvs expose the same site-packages directory through both
    # lib and lib64. Scan one inode once so a shared RECORD cannot gain two
    # owners solely from equivalent lexical paths.
    seen_site_root_ids.add(site_root_id)
    site_roots.append(site_root)
for site_root in site_roots:
    for dist_info in sorted(site_root.glob("*.dist-info")):
        metadata(dist_info, directory=True)
        record = dist_info / "RECORD"
        record_meta = metadata(record)
        raw = file_bytes(record, record_meta)
        try:
            rows = list(csv.reader(io.StringIO(raw.decode("utf-8"), newline="")))
        except (UnicodeDecodeError, csv.Error):
            fail(f"unreadable RECORD: {record}")
        if not rows or any(len(row) != 3 for row in rows):
            fail(f"invalid RECORD: {record}")
        record_states[record] = [rows, raw, record_meta, site_root, dist_info]
        for index, row in enumerate(rows):
            target = record_target(site_root, row[0])
            if target is None:
                continue
            if within(target, root) and target.parent == scripts:
                owners.setdefault(target, []).append((record, index))

old_prefix = os.fsencode(f"#!{old_root}/bin/")
new_prefix = os.fsencode(f"#!{new_root}/bin/")
script_updates = []
changed_records = set()
repaired_scripts = set()
for script in sorted(scripts.iterdir()):
    if script.is_symlink() or not script.is_file():
        continue
    script_meta = metadata(script)
    raw = file_bytes(script, script_meta)
    first, separator, rest = raw.partition(b"\n")
    if not first.startswith(old_prefix):
        continue
    bindings = owners.get(lexical(script), [])
    if len(bindings) > 1:
        fail(f"repaired script lacks one RECORD owner: {script}")
    if not bindings:
        record = legacy_console_owner(script, rest)
        rows, _, _, site_root, _ = record_states[record]
        relative_name = os.path.relpath(script, site_root).replace(os.sep, "/")
        if record_target(site_root, relative_name) != lexical(script):
            fail(f"invalid historical console script RECORD path: {script}")
        row = [relative_name, record_hash(raw), str(len(raw))]
        self_indexes = [
            index
            for index, candidate in enumerate(rows)
            if record_target(site_root, candidate[0]) == record
        ]
        if len(self_indexes) != 1:
            fail(f"invalid RECORD self ownership: {record}")
        rows.append(row)
        index = len(rows) - 1
        owners.setdefault(lexical(script), []).append((record, index))
        changed_records.add(record)
        repaired_scripts.add(script)
    else:
        record, index = bindings[0]
        row = record_states[record][0][index]
    record_mismatch = (
        not row[1].startswith("sha256=")
        or not row[2].isdigit()
        or row[1] != record_hash(raw)
        or int(row[2]) != len(raw)
    )
    if record_mismatch:
        legacy_record = legacy_console_owner(script, rest)
        if legacy_record != record:
            fail(f"repaired script RECORD owner mismatch: {script}")
        repaired_scripts.add(script)
    updated = new_prefix + first[len(old_prefix) :] + separator + rest
    row[1] = record_hash(updated)
    row[2] = str(len(updated))
    if record_mismatch or updated != raw:
        changed_records.add(record)
    if updated != raw:
        script_updates.append((script, updated, script_meta))
        repaired_scripts.add(script)

sequence = 0
for script, data, script_meta in script_updates:
    sequence += 1
    atomic_write(script, data, script_meta, sequence)
for record in sorted(changed_records):
    state = record_states[record]
    rows, raw, record_meta, _, _ = state
    newline = "\r\n" if b"\r\n" in raw else "\n"
    output = io.StringIO(newline="")
    writer = csv.writer(output, lineterminator=newline)
    writer.writerows(rows)
    encoded = output.getvalue().encode("utf-8")
    if encoded == raw:
        continue
    sequence += 1
    atomic_write(record, encoded, record_meta, sequence)
print(len(repaired_scripts))
PY
  )" || return 1
  if [[ "${repaired}" =~ ^[1-9][0-9]*$ ]] \
    && declare -F info >/dev/null 2>&1; then
    info "已修复 ${repaired} 个 venv 脚本 shebang 并重绑 RECORD"
  fi
}

prune_agent_artifacts(){
  local base="/opt/realm-agent"
  local keep_bak log_days tmp_days
  keep_bak="$(parse_nonneg_int "${REALM_AGENT_KEEP_BAK:-1}" "1")"
  log_days="$(parse_nonneg_int "${REALM_AGENT_UPDATE_LOG_RETENTION_DAYS:-7}" "7")"
  tmp_days="$(parse_nonneg_int "${REALM_AGENT_UPDATE_TMP_RETENTION_DAYS:-1}" "1")"

  # Keep the newest N backups only to avoid disk growth on small nodes.
  local -a bak_dirs=()
  local d
  while IFS= read -r d; do
    bak_dirs+=("${d}")
  done < <(find "${base}" -maxdepth 1 -mindepth 1 -type d -name '.bak.*' -print 2>/dev/null | sort -r)

  if (( ${#bak_dirs[@]} > keep_bak )); then
    local i removed=0
    for ((i=keep_bak; i<${#bak_dirs[@]}; i++)); do
      rm -rf "${bak_dirs[$i]}" || true
      removed=$((removed + 1))
    done
    if (( removed > 0 )); then
      info "已清理旧 Agent 备份目录：${removed} 个（保留 ${keep_bak} 个）"
    fi
  fi

  find /var/log -maxdepth 1 -type f -name 'realm-agent-update-*.log' -mtime +"${log_days}" -delete 2>/dev/null || true
  find /tmp -maxdepth 1 -type f -name 'realm-agent-update-*.sh' -mtime +"${tmp_days}" -delete 2>/dev/null || true
  find /tmp -maxdepth 1 -type f -name 'realm-agent-repo-*.zip' -mtime +"${tmp_days}" -delete 2>/dev/null || true
}

validate_agent_api_key_file(){
  local path="${1:-$(agent_api_key_path)}"
  local expected_uid="${2:-0}"
  local expected_gid="${3:-0}"
  local python_bin=""
  python_bin="$(agent_contract_python || true)"
  if [[ -z "${python_bin}" ]]; then
    err "无法验证 API key 文件：缺少 Python 3.9+"
    return 1
  fi
  if ! "${python_bin}" - "${path}" "${expected_uid}" "${expected_gid}" <<'PY'
import os
import stat
import sys

path, expected_uid, expected_gid = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
try:
    metadata = os.lstat(path)
    with open(path, "rb") as handle:
        data = handle.read(4097)
except OSError:
    raise SystemExit(1)
value = data.rstrip(b"\r\n")
valid = (
    stat.S_ISREG(metadata.st_mode)
    and metadata.st_uid == expected_uid
    and metadata.st_gid == expected_gid
    and stat.S_IMODE(metadata.st_mode) == 0o600
    and 0 < len(value) <= 4096
    and b"\x00" not in value
    and b"\n" not in value
    and b"\r" not in value
)
raise SystemExit(0 if valid else 1)
PY
  then
    err "API key 文件必须是 nonempty、root:root、0600 的普通文件"
    return 1
  fi
}

write_agent_api_key_atomically(){
  local path="$1"
  local value="$2"
  local owner_uid="${3:-0}"
  local owner_gid="${4:-0}"
  local parent=""
  local tmp=""

  parent="$(dirname "${path}")"
  if [[ -L "${parent}" || ( -e "${parent}" && ! -d "${parent}" ) ]]; then
    err "API key 目录不是可信普通目录"
    return 1
  fi
  if [[ -L "${path}" ]]; then
    err "拒绝通过符号链接替换 API key"
    return 1
  fi
  if [[ "${parent}" == "$(agent_config_dir)" \
    && -n "${AGENT_SERVICE_GID:-}" ]]; then
    if ! prepare_agent_config_boundary; then
      err "无法保持 Agent 配置目录权限边界"
      return 1
    fi
  else
    if ! install -d -m 700 "${parent}" || ! chmod 700 "${parent}"; then
      err "无法创建或收紧 API key 目录"
      return 1
    fi
    if [[ "$(id -u)" != "${owner_uid}" || "$(id -g)" != "${owner_gid}" ]] \
      && ! chown "${owner_uid}:${owner_gid}" "${parent}"; then
      err "无法设置 API key 目录所有权"
      return 1
    fi
  fi
  tmp="$(mktemp "${parent}/.api.key.XXXXXX")" || return 1
  register_cleanup_path "${tmp}"
  if ! printf '%s\n' "${value}" > "${tmp}"; then
    return 1
  fi
  if ! chmod 600 "${tmp}"; then
    err "无法收紧临时 API key 文件权限"
    return 1
  fi
  if [[ "$(id -u)" != "${owner_uid}" || "$(id -g)" != "${owner_gid}" ]] \
    && ! chown "${owner_uid}:${owner_gid}" "${tmp}"; then
    err "无法设置临时 API key 文件所有权"
    return 1
  fi
  if ! mv -f "${tmp}" "${path}"; then
    err "无法原子替换 API key 文件"
    return 1
  fi
}

agent_api_key_file_matches_target_bytes(){
  local path="$1"
  local target="$2"
  local actual_size=""
  local written_value=""
  [[ -f "${path}" && ! -L "${path}" ]] || return 1
  actual_size="$(wc -c < "${path}" | tr -d '[:space:]')" || return 1
  IFS= read -r written_value < "${path}" || [[ -n "${written_value}" ]] \
    || return 1
  [[ ( "${actual_size}" == "${#target}" \
      || "${actual_size}" == "$(( ${#target} + 1 ))" ) \
    && "${written_value}" == "${target}" ]]
}

validate_written_agent_target_key(){
  local path="$1"
  local target="$2"
  local expected_uid="${3:-0}"
  local expected_gid="${4:-0}"
  local actual_uid=""
  local actual_gid=""
  local actual_mode=""
  agent_api_key_file_matches_target_bytes "${path}" "${target}" || return 1
  actual_uid="$(
    stat -Lc '%u' "${path}" 2>/dev/null \
      || stat -f '%u' "${path}" 2>/dev/null
  )" || return 1
  actual_gid="$(
    stat -Lc '%g' "${path}" 2>/dev/null \
      || stat -f '%g' "${path}" 2>/dev/null
  )" || return 1
  actual_mode="$(
    stat -Lc '%a' "${path}" 2>/dev/null \
      || stat -f '%Lp' "${path}" 2>/dev/null
  )" || return 1
  [[ "${actual_uid}" == "${expected_uid}" \
    && "${actual_gid}" == "${expected_gid}" \
    && "${actual_mode}" == "600" ]]
}

adopted_agent_api_key_file_version(){
  local path="$1"
  local expected_uid="${2:-0}"
  local expected_gid="${3:-0}"
  if [[ "${REALM_AGENT_PENDING_TARGET_API_KEY_SET:-0}" == "1" ]] \
    && validate_written_agent_target_key \
      "${path}" "${REALM_AGENT_PENDING_TARGET_API_KEY}" \
      "${expected_uid}" "${expected_gid}"; then
    compute_agent_api_key_version "${REALM_AGENT_PENDING_TARGET_API_KEY}"
    return $?
  fi
  agent_api_key_file_version "${path}" "${expected_uid}" "${expected_gid}"
}

generate_agent_api_key(){
  local value=""
  if ! command_exists openssl; then
    err "生成 API key 需要 openssl"
    return 1
  fi
  value="$(openssl rand -hex 32 2>/dev/null || true)"
  if ! validate_agent_target_api_key "${value}"; then
    err "openssl 未能生成有效 API key"
    return 1
  fi
  printf '%s' "${value}"
}

prepare_agent_api_key(){
  local expected_uid="${1:-0}"
  local expected_gid="${2:-0}"
  local path=""
  local target=""
  local expected_version=""
  local actual_version=""
  local file_version=""
  local generated=""

  path="$(agent_api_key_path)"
  REALM_AGENT_API_KEY_EXPECTED_UID="${expected_uid}"
  REALM_AGENT_API_KEY_EXPECTED_GID="${expected_gid}"
  if agent_target_api_key_is_set; then
    target="$(agent_target_api_key_value)"
    if ! validate_agent_target_api_key "${target}"; then
      err "join 目标 API key 必须是 8-256 位安全 ASCII 字符"
      return 1
    fi
    expected_version="$(agent_target_api_key_version)"
    actual_version="$(compute_agent_api_key_version "${target}")" || {
      err "无法计算 join 目标 API key version"
      return 1
    }
    if [[ -n "${expected_version}" \
      && "${expected_version}" != "${actual_version}" ]]; then
      err "join 目标 API key version 与目标值不匹配"
      return 1
    fi
    expected_version="${actual_version}"
    if [[ "${REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE:-0}" == "1" ]] \
      && ! durable_write_agent_transaction_file \
        "${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state/api-key.target-version" \
        "${expected_version}"; then
      err "无法在采用 join 目标 API key 前持久化 CAS version"
      return 1
    fi
    if ! write_agent_api_key_atomically \
      "${path}" "${target}" "${expected_uid}" "${expected_gid}"; then
      return 1
    fi
    REALM_AGENT_PENDING_TARGET_API_KEY="${target}"
    REALM_AGENT_PENDING_TARGET_API_KEY_SET="1"
    REALM_AGENT_PENDING_TARGET_API_KEY_VERSION="${expected_version}"
    REALM_AGENT_TARGET_API_KEY_ADOPTED="1"
    REALM_AGENT_ADOPTED_API_KEY_VERSION="${expected_version}"
    unset REALM_AGENT_TARGET_API_KEY REALM_AGENT_TARGET_API_KEY_VERSION
    if ! validate_written_agent_target_key \
      "${path}" "${target}" "${expected_uid}" "${expected_gid}"; then
      err "join 目标 API key 原子写入后的内容或权限不匹配"
      return 1
    fi
    file_version="$(
      adopted_agent_api_key_file_version \
        "${path}" "${expected_uid}" "${expected_gid}"
    )" || return 1
    if [[ "${file_version}" != "${expected_version}" ]]; then
      err "join 目标 API key 原子写入后 CAS version 不匹配"
      return 1
    fi
    info "已在 rollback 快照后按 version/CAS 原子应用 join 目标 API key"
    return 0
  elif validate_agent_api_key_file "${path}" "${expected_uid}" "${expected_gid}" \
    >/dev/null 2>&1; then
    info "保留现有 API key"
  else
    if [[ -L "${path}" ]]; then
      err "现有 API key 是符号链接，拒绝自动重建"
      return 1
    fi
    warn "现有 API key 缺失、为空或权限/所有权不安全，正在安全重建"
    generated="$(generate_agent_api_key)" || return 1
    if ! write_agent_api_key_atomically \
      "${path}" "${generated}" "${expected_uid}" "${expected_gid}"; then
      return 1
    fi
  fi
  validate_agent_api_key_file "${path}" "${expected_uid}" "${expected_gid}"
}

adopt_join_target_api_key_after_snapshot(){
  local expected_uid="${1:-0}"
  local expected_gid="${2:-0}"
  agent_target_api_key_is_set || return 0
  if [[ "${REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE:-0}" != "1" ]]; then
    err "join 目标 API key 只能在 rollback 快照后采用"
    return 1
  fi
  prepare_agent_api_key "${expected_uid}" "${expected_gid}"
}

ensure_agent_api_key_for_activation(){
  local expected_uid="${1:-0}"
  local expected_gid="${2:-0}"
  local path=""
  local expected_version=""
  local current_version=""
  path="$(agent_api_key_path)"
  if [[ "${REALM_AGENT_TARGET_API_KEY_ADOPTED:-0}" != "1" ]]; then
    prepare_agent_api_key "${expected_uid}" "${expected_gid}"
    return $?
  fi
  expected_version="${REALM_AGENT_ADOPTED_API_KEY_VERSION:-}"
  if ! validate_agent_api_key_version "${expected_version}"; then
    err "启动前目标 API key CAS version 丢失"
    return 1
  fi
  current_version="$(
    agent_api_key_file_version "${path}" "${expected_uid}" "${expected_gid}" \
      || true
  )"
  if [[ "${current_version}" != "${expected_version}" ]]; then
    err "启动前目标 API key CAS 冲突；拒绝覆盖并发轮换结果"
    return 1
  fi
  return 0
}

restore_agent_api_key_transaction(){
  local path=""
  local current_version=""
  local expected_version="${REALM_AGENT_ADOPTED_API_KEY_VERSION:-}"
  local expected_uid="${REALM_AGENT_API_KEY_EXPECTED_UID:-0}"
  local expected_gid="${REALM_AGENT_API_KEY_EXPECTED_GID:-0}"
  path="$(agent_api_key_path)"
  if [[ "${REALM_AGENT_TARGET_API_KEY_ADOPTED:-0}" != "1" ]]; then
    restore_agent_rollback_file "${path}" api-key
    return $?
  fi
  if ! validate_agent_api_key_version "${expected_version}"; then
    err "已采用目标 API key，但 rollback CAS version 丢失"
    return 1
  fi
  current_version="$(
    adopted_agent_api_key_file_version \
      "${path}" "${expected_uid}" "${expected_gid}" \
      || true
  )"
  if [[ "${current_version}" == "${expected_version}" ]]; then
    info "rollback 保留 panel 已采用的目标 API key version"
    return 0
  fi
  if [[ "${REALM_AGENT_PENDING_TARGET_API_KEY_SET:-0}" == "1" ]] \
    && { [[ ! -e "${path}" ]] \
      || agent_api_key_file_matches_target_bytes \
        "${path}" "${REALM_AGENT_PENDING_TARGET_API_KEY}"; }; then
    if ! write_agent_api_key_atomically \
      "${path}" "${REALM_AGENT_PENDING_TARGET_API_KEY}" \
      "${expected_uid}" "${expected_gid}"; then
      err "rollback 无法重建已采用的目标 API key"
      return 1
    fi
    current_version="$(
      agent_api_key_file_version "${path}" "${expected_uid}" "${expected_gid}" \
        || true
    )"
    if [[ "${current_version}" == "${expected_version}" ]]; then
      info "rollback 已重建并保留 panel 采用的目标 API key version"
      return 0
    fi
  fi
  err "API key rollback CAS 冲突；拒绝覆盖可能的并发轮换结果"
  return 1
}

agent_tls_san_value(){
  local server_name="${1:-}"
  local bind_host="${2:-}"
  local python_bin=""
  python_bin="$(agent_contract_python || true)"
  [[ -n "${python_bin}" ]] || return 1
  "${python_bin}" - "${server_name}" "${bind_host}" <<'PY'
import ipaddress
import sys

server_name = str(sys.argv[1] or "").strip().rstrip(".")
bind_host = str(sys.argv[2] or "").strip()
if bind_host.startswith("[") and bind_host.endswith("]"):
    bind_host = bind_host[1:-1].strip()

entries = []


def add(value):
    if not value or value in entries:
        return
    entries.append(value)


def add_host(value):
    value = str(value or "").strip().rstrip(".")
    if not value or value in {"0.0.0.0", "::", "*"}:
        return
    try:
        address = ipaddress.ip_address(value.split("%", 1)[0])
    except ValueError:
        add(f"DNS:{value}")
    else:
        add(f"IP:{address.compressed}")


add_host(server_name)
add_host(bind_host)
add("DNS:localhost")
add("IP:127.0.0.1")
add("IP:::1")
print(",".join(entries))
PY
}

validate_agent_tls_material(){
  local cert="$1"
  local key="$2"
  local server_name="$3"
  local bind_host="$4"
  local expected_uid="${5:-0}"
  local expected_gid="${6:-0}"
  local min_validity_seconds="${7:-86400}"
  local verify_peer="${8:-0}"
  local ca_cert="${9:-}"
  local cert_sha256="${10:-}"
  local python_bin=""
  local cert_public_sha=""
  local key_public_sha=""
  local actual_cert_sha256=""

  if [[ ! "${min_validity_seconds}" =~ ^[0-9]+$ ]] \
    || (( min_validity_seconds < 0 || min_validity_seconds > 31536000 )); then
    err "TLS checkend 秒数无效"
    return 1
  fi
  if ! server_name="$(normalize_agent_tls_server_name "${server_name}")"; then
    err "TLS server name 为空、unspecified 或含非法字符"
    return 1
  fi
  if ! verify_peer="$(normalize_tls_auto_generate "${verify_peer}")"; then
    err "TLS verify peer 仅支持 0/1 或布尔值"
    return 1
  fi
  if ! validate_agent_tls_cert_sha256 "${cert_sha256}"; then
    err "TLS cert SHA-256 pin 必须是 64 位小写十六进制"
    return 1
  fi
  python_bin="$(agent_contract_python || true)"
  if [[ -z "${python_bin}" ]] || ! command_exists openssl; then
    err "完整 TLS 校验需要 Python 3.9+ 与 openssl"
    return 1
  fi
  if ! openssl x509 -in "${cert}" -noout >/dev/null 2>&1 \
    || ! openssl pkey -in "${key}" -noout >/dev/null 2>&1; then
    err "TLS cert/key 无法解析"
    return 1
  fi
  if ! openssl x509 -in "${cert}" -checkend "${min_validity_seconds}" \
    -noout >/dev/null 2>&1; then
    err "TLS 证书已过期或有效期不足 ${min_validity_seconds} 秒"
    return 1
  fi
  if ! cert_public_sha="$(
    openssl x509 -in "${cert}" -pubkey -noout 2>/dev/null \
      | openssl pkey -pubin -outform DER 2>/dev/null \
      | openssl dgst -sha256 2>/dev/null
  )"; then
    err "无法提取 TLS 证书公钥"
    return 1
  fi
  if ! key_public_sha="$(
    openssl pkey -in "${key}" -pubout -outform DER 2>/dev/null \
      | openssl dgst -sha256 2>/dev/null
  )"; then
    err "无法提取 TLS 私钥公钥"
    return 1
  fi
  if [[ -z "${cert_public_sha}" || "${cert_public_sha}" != "${key_public_sha}" ]]; then
    err "TLS cert 与 key 公钥不匹配"
    return 1
  fi
  if [[ -n "${cert_sha256}" ]]; then
    actual_cert_sha256="$(
      openssl x509 -in "${cert}" -outform DER 2>/dev/null \
        | openssl dgst -sha256 -r 2>/dev/null \
        | awk '{print $1}'
    )"
    if [[ -z "${actual_cert_sha256}" \
      || "${actual_cert_sha256}" != "${cert_sha256}" ]]; then
      err "TLS cert SHA-256 pin 不匹配"
      return 1
    fi
  fi
  if [[ "${verify_peer}" == "1" ]]; then
    if [[ -z "${ca_cert}" ]] || ! validate_agent_tls_path "${ca_cert}" \
      || [[ ! -f "${ca_cert}" || -L "${ca_cert}" ]]; then
      err "TLS verify peer 模式要求显式可信 CA 文件"
      return 1
    fi
    if ! openssl verify -purpose sslserver -CAfile "${ca_cert}" \
      "${cert}" >/dev/null 2>&1; then
      err "TLS cert 未通过 openssl sslserver 信任链校验"
      return 1
    fi
  fi
  if ! "${python_bin}" - \
    "${cert}" "${key}" "${server_name}" "${bind_host}" \
    "${expected_uid}" "${expected_gid}" "${min_validity_seconds}" \
    "${verify_peer}" "${ca_cert}" >/dev/null 2>&1 <<'PY'
import os
import ssl
import stat
import sys
import time

cert, key, server_name, bind_host = sys.argv[1:5]
expected_uid, expected_gid = int(sys.argv[5]), int(sys.argv[6])
min_validity_seconds = int(sys.argv[7])
verify_peer = sys.argv[8] == "1"
ca_cert = sys.argv[9]
try:
    cert_stat = os.lstat(cert)
    key_stat = os.lstat(key)
    decoded = ssl._ssl._test_decode_cert(cert)
except (OSError, ValueError, ssl.SSLError):
    raise SystemExit(1)
cert_mode = stat.S_IMODE(cert_stat.st_mode)
key_mode = stat.S_IMODE(key_stat.st_mode)
trusted_key_gids = {0, expected_gid}
files_valid = (
    stat.S_ISREG(cert_stat.st_mode)
    and stat.S_ISREG(key_stat.st_mode)
    and cert_stat.st_uid == expected_uid
    and key_stat.st_uid == expected_uid
    and key_stat.st_gid in trusted_key_gids
    and not bool(cert_mode & 0o022)
    and bool(key_mode & stat.S_IRUSR)
    and key_mode in {0o600, 0o640}
)
if not files_valid or not decoded.get("subjectAltName"):
    raise SystemExit(1)
try:
    not_before = ssl.cert_time_to_seconds(decoded["notBefore"])
    not_after = ssl.cert_time_to_seconds(decoded["notAfter"])
except (KeyError, TypeError, ValueError):
    raise SystemExit(1)
now = time.time()
if now < not_before or not_after - now < min_validity_seconds:
    raise SystemExit(1)
if verify_peer:
    try:
        ca_stat = os.lstat(ca_cert)
    except OSError:
        raise SystemExit(1)
    ca_mode = stat.S_IMODE(ca_stat.st_mode)
    if not (
        stat.S_ISREG(ca_stat.st_mode)
        and ca_stat.st_uid == expected_uid
        and ca_stat.st_gid in {0, expected_gid}
        and not bool(ca_mode & 0o022)
    ):
        raise SystemExit(1)
try:
    ssl.match_hostname(decoded, server_name)
except (ssl.CertificateError, ValueError):
    raise SystemExit(1)
PY
  then
    err "TLS SAN/有效期/所有权/cert-key-CA 权限校验失败"
    return 1
  fi
}

prepare_agent_tls_material(){
  local transport="$1"
  local cert="$2"
  local key="$3"
  local server_name="$4"
  local bind_host="$5"
  local stage="$6"
  local auto_generate="$7"
  local verify_peer="${8:-0}"
  local ca_cert="${9:-}"
  local cert_sha256="${10:-}"
  local config_dir=""
  local default_cert=""
  local default_key=""
  local tls_stage=""
  local openssl_config=""
  local san_value=""
  local tls_expected_gid=""

  AGENT_TLS_PREPARED_CERT=""
  AGENT_TLS_PREPARED_KEY=""
  [[ "${transport}" == "https" ]] || return 0

  if [[ -e "${cert}" || -e "${key}" ]]; then
    if ! tls_expected_gid="$(existing_agent_tls_expected_gid)"; then
      return 1
    fi
    if ! validate_agent_tls_material \
      "${cert}" "${key}" "${server_name}" "${bind_host}" \
      "$(agent_service_file_uid)" "${tls_expected_gid}" 86400 \
      "${verify_peer}" "${ca_cert}" "${cert_sha256}"; then
      err "现有 HTTPS cert/key 未通过完整校验，拒绝切换服务"
      return 1
    fi
    info "现有 HTTPS cert/key 已通过解析、checkend、公钥、SAN 与权限校验"
    return 0
  fi

  if [[ "${auto_generate}" != "1" ]]; then
    err "HTTPS 证书不存在，且 REALM_AGENT_TLS_AUTO_GENERATE=0"
    return 1
  fi
  if [[ "$(normalize_tls_auto_generate "${verify_peer}")" == "1" ]]; then
    err "TLS verify peer 模式禁止生成自签证书"
    return 1
  fi
  if [[ ( "${bind_host}" == "0.0.0.0" || "${bind_host}" == "::" ) \
    && -z "${server_name}" ]]; then
    err "wildcard HTTPS 监听自动生成证书时必须提供 REALM_AGENT_TLS_SERVER_NAME"
    return 1
  fi
  config_dir="$(agent_config_dir)"
  default_cert="${config_dir}/certs/server.crt"
  default_key="${config_dir}/certs/server.key"
  if [[ "${cert}" != "${default_cert}" || "${key}" != "${default_key}" ]]; then
    err "拒绝在自定义路径自动生成证书；请先提供可读证书与私钥"
    return 1
  fi
  if [[ -L "${config_dir}" || -L "$(dirname "${cert}")" || -L "$(dirname "${key}")" ]]; then
    err "拒绝通过符号链接目录自动生成 Agent HTTPS 证书"
    return 1
  fi
  if ! command_exists openssl; then
    err "HTTPS 安装需要 openssl 生成自签证书"
    return 1
  fi

  tls_stage="${stage}/tls"
  mkdir -p "${tls_stage}"
  chmod 700 "${tls_stage}" >/dev/null 2>&1 || true
  openssl_config="${tls_stage}/openssl.cnf"
  san_value="$(agent_tls_san_value "${server_name}" "${bind_host}")"
  if [[ -z "${san_value}" ]]; then
    err "无法为 HTTPS Agent 生成有效证书 SAN"
    return 1
  fi
  cat > "${openssl_config}" <<EOF
[req]
distinguished_name = subject
x509_extensions = server
prompt = no

[subject]
CN = Realm Agent

[server]
basicConstraints = critical,CA:FALSE
keyUsage = critical,digitalSignature,keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = ${san_value}
EOF
  if ! openssl req -x509 -nodes -newkey rsa:3072 -sha256 -days 825 \
    -keyout "${tls_stage}/server.key" \
    -out "${tls_stage}/server.crt" \
    -config "${openssl_config}" >/dev/null 2>&1; then
    err "生成 Agent 自签 HTTPS 证书失败"
    return 1
  fi
  chmod 644 "${tls_stage}/server.crt"
  chmod 600 "${tls_stage}/server.key"
  if ! validate_agent_tls_material \
    "${tls_stage}/server.crt" "${tls_stage}/server.key" \
    "${server_name}" "${bind_host}" "$(id -u)" "$(id -g)" \
    86400 0 "" ""; then
    err "新生成的 Agent HTTPS cert/key 未通过完整校验"
    return 1
  fi
  AGENT_TLS_PREPARED_CERT="${tls_stage}/server.crt"
  AGENT_TLS_PREPARED_KEY="${tls_stage}/server.key"
  info "已在 staging 中准备 Agent 自签 HTTPS 证书"
}

install_prepared_agent_tls_material(){
  local cert="$1"
  local key="$2"
  local server_name="$3"
  local bind_host="$4"
  local verify_peer="${5:-0}"
  local ca_cert="${6:-}"
  local cert_sha256="${7:-}"
  local cert_parent=""
  local key_parent=""
  local default_dir=""

  default_dir="$(agent_default_tls_dir)"
  if [[ -n "${AGENT_TLS_PREPARED_CERT:-}" ]]; then
    cert_parent="$(dirname "${cert}")"
    key_parent="$(dirname "${key}")"
    if [[ "${cert_parent}" == "${default_dir}" ]]; then
      install -d -m 0750 "${cert_parent}"
    elif [[ ! -d "${cert_parent}" || -L "${cert_parent}" ]]; then
      err "custom TLS certificate parent must already be a real directory"
      return 1
    fi
    if [[ "${key_parent}" == "${default_dir}" ]]; then
      install -d -m 0750 "${key_parent}"
    elif [[ ! -d "${key_parent}" || -L "${key_parent}" ]]; then
      err "custom TLS key parent must already be a real directory"
      return 1
    fi
    if [[ -L "${cert}" || -L "${key}" ]]; then
      err "拒绝通过符号链接写入 Agent HTTPS 证书"
      return 1
    fi
    install -m 0644 "${AGENT_TLS_PREPARED_CERT}" "${cert}"
    install -m 0640 "${AGENT_TLS_PREPARED_KEY}" "${key}"
    ok "Agent HTTPS 证书已安装：${cert}"
  fi
  prepare_agent_tls_gateway_permissions "${cert}" "${key}" || return 1
  validate_agent_tls_material \
    "${cert}" "${key}" "${server_name}" "${bind_host}" \
    "$(agent_service_file_uid)" "${AGENT_SERVICE_GID}" 86400 \
    "${verify_peer}" "${ca_cert}" "${cert_sha256}"
}

agent_isolated_runtime_unit_names(){
  cat <<'EOF'
realm-agent-privileged.socket
realm-agent-privileged.service
realm-tunnel-runtime.service
realm-netops.service
realm-panel-reporter.service
realm-v2-control.service
realm-tunnel-runtime.socket
realm-netops.socket
realm-panel-reporter.socket
realm-v2-control.socket
realm-agent.target
EOF
}

agent_runtime_unit_names(){
  printf '%s\n' "${AGENT_RUNTIME_UNITS[@]}"
}

agent_cutover_unit_names(){
  printf '%s\n' "${AGENT_CUTOVER_UNITS[@]}"
}

agent_overwritten_unit_names(){
  printf '%s\n' "${AGENT_CUTOVER_UNITS[@]}"
}

agent_managed_unit_names(){
  printf '%s\n' "${AGENT_MANAGED_UNITS[@]}"
}

valid_agent_pool_version_state_file(){
  local path="$1"
  [[ "${path}" == /* \
    && "${path}" != "/" \
    && "${path}" != *"/../"* \
    && "${path}" != */.. \
    && "${path}" != *"/./"* \
    && "${path}" != */. \
    && "${path}" != *[[:space:]]* \
    && "${path}" != *[[:cntrl:]]* ]]
}

agent_pool_version_state_file(){
  local config_dir=""
  local existing_env=""
  local path="${REALM_AGENT_POOL_VERSION_STATE_FILE:-}"
  config_dir="$(agent_config_dir)"
  existing_env="${config_dir}/agent.env"
  if [[ -z "${path}" ]]; then
    path="$(read_env_value "${existing_env}" \
      "REALM_AGENT_POOL_VERSION_STATE_FILE" || true)"
  fi
  [[ -n "${path}" ]] || path="${config_dir}/pool_apply_state.json"
  if ! valid_agent_pool_version_state_file "${path}"; then
    err "Agent pool version state 路径无效：${path}"
    return 1
  fi
  printf '%s' "${path}"
}

agent_managed_file_entries(){
  local base="$1"
  local config_dir=""
  local realm_dir=""
  local systemd_dir=""
  local sysctl_dir=""
  local local_bin_dir=""
  local libexec_dir=""
  local pool_version_state_file=""
  local unit=""
  config_dir="$(agent_config_dir)"
  realm_dir="$(realm_config_dir)"
  systemd_dir="$(agent_systemd_dir)"
  sysctl_dir="$(agent_sysctl_dir)"
  local_bin_dir="$(agent_local_bin_dir)"
  libexec_dir="$(agent_libexec_dir)"
  pool_version_state_file="$(agent_pool_version_state_file)" || return 1
  printf '%s\t%s\n' agent.env "${config_dir}/agent.env"
  printf '%s\t%s\n' gateway.env "${config_dir}/gateway.env"
  printf '%s\t%s\n' service-account "${config_dir}/service-account.env"
  printf '%s\t%s\n' panel.env "${config_dir}/panel.env"
  printf '%s\t%s\n' panel-ack-version "${config_dir}/panel_ack.version"
  printf '%s\t%s\n' pool-applied-signature "${config_dir}/pool_applied.sig"
  printf '%s\t%s\n' pool-apply-state "${config_dir}/pool_apply_state.json"
  if [[ "${pool_version_state_file}" != "${config_dir}/pool_apply_state.json" ]]; then
    printf '%s\t%s\n' pool-apply-state-custom "${pool_version_state_file}"
  fi
  printf '%s\t%s\n' requirements.sha256 "${config_dir}/requirements.sha256"
  printf '%s\t%s\n' venv-attestation.json "${config_dir}/venv-attestation.json"
  printf '%s\t%s\n' realm-config "${realm_dir}/config.json"
  printf '%s\t%s\n' realm-pool-full "${realm_dir}/pool_full.json"
  printf '%s\t%s\n' realm-pool-active "${realm_dir}/pool.json"
  printf '%s\t%s\n' pool_to_run.jq "${realm_dir}/pool_to_run.jq"
  printf '%s\t%s\n' 90-realm-mptcp.conf "${sysctl_dir}/90-realm-mptcp.conf"
  printf '%s\t%s\n' 99-realm.conf "${sysctl_dir}/99-realm.conf"
  printf '%s\t%s\n' 99-realm-ipforward.conf "${sysctl_dir}/99-realm-ipforward.conf"
  printf '%s\t%s\n' realm-bin "${local_bin_dir}/realm"
  printf '%s\t%s\n' tcping-bin "${local_bin_dir}/tcping"
  printf '%s\t%s\n' realm-service-override \
    "${systemd_dir}/realm.service.d/override.conf"
  printf '%s\t%s\n' realm-service-guard \
    "${systemd_dir}/realm.service.d/10-nexus-config-guard.conf"
  printf '%s\t%s\n' realm-config-ready \
    "${libexec_dir}/nexus-realm-config-ready"
  printf '%s\t%s\n' mptcp_sidecar_start.sh "${base}/mptcp_sidecar_start.sh"
  for unit in "${AGENT_CUTOVER_UNITS[@]}"; do
    [[ -n "${unit}" ]] || continue
    [[ "${unit}" != "realm-agent-install-recovery.service" ]] || continue
    printf '%s\t%s\n' "${unit}" "${systemd_dir}/${unit}"
  done
}

snapshot_agent_rollback_file(){
  local source="$1"
  local name="$2"
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  if [[ -L "${source}" ]]; then
    err "拒绝通过符号链接更新受管文件：${source}"
    return 1
  fi
  if [[ -e "${source}" ]]; then
    if ! cp -a "${source}" "${state_dir}/${name}" \
      || ! : > "${state_dir}/${name}.present"; then
      err "无法快照受管文件：${source}"
      return 1
    fi
  else
    if ! : > "${state_dir}/${name}.absent"; then
      err "无法记录受管文件缺失状态：${source}"
      return 1
    fi
  fi
}

restore_agent_rollback_file(){
  local target="$1"
  local name="$2"
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local parent tmp
  if [[ -f "${state_dir}/${name}.present" ]]; then
    parent="$(dirname "${target}")"
    if ! mkdir -p "${parent}"; then
      err "无法创建回滚目标目录：${parent}"
      return 1
    fi
    tmp="$(mktemp "${parent}/.$(basename "${target}").restore.XXXXXX")" \
      || return 1
    register_cleanup_path "${tmp}"
    if ! cp -a "${state_dir}/${name}" "${tmp}" \
      || ! mv -f "${tmp}" "${target}"; then
      err "无法恢复受管文件：${target}"
      return 1
    fi
  elif [[ -f "${state_dir}/${name}.absent" ]]; then
    if ! rm -f "${target}" >/dev/null 2>&1; then
      err "无法删除更新中新建的受管文件：${target}"
      return 1
    fi
  else
    err "缺少受管文件回滚状态：${name}"
    return 1
  fi
}

snapshot_agent_managed_files(){
  local base="$1"
  local name=""
  local path=""
  local inventory="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state/managed-files.entries"
  if ! agent_managed_file_entries "${base}" > "${inventory}"; then
    err "无法冻结受管文件 rollback inventory"
    return 1
  fi
  while IFS=$'\t' read -r name path; do
    [[ -n "${name}" && -n "${path}" ]] || continue
    if ! snapshot_agent_rollback_file "${path}" "${name}"; then
      return 1
    fi
  done < "${inventory}"
}

restore_agent_managed_files(){
  local base="$1"
  local name=""
  local path=""
  local failed="0"
  local inventory="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state/managed-files.entries"
  if [[ ! -s "${inventory}" ]]; then
    err "缺少冻结的受管文件 rollback inventory：${base}"
    return 1
  fi
  while IFS=$'\t' read -r name path; do
    [[ -n "${name}" && -n "${path}" ]] || continue
    if ! restore_agent_rollback_file "${path}" "${name}"; then
      failed="1"
    fi
  done < "${inventory}"
  [[ "${failed}" == "0" ]]
}

agent_managed_sysctl_names(){
  cat <<'EOF'
net.ipv4.ip_forward
net.core.somaxconn
net.ipv4.tcp_max_syn_backlog
net.core.netdev_max_backlog
net.core.rmem_max
net.core.wmem_max
net.core.rmem_default
net.core.wmem_default
net.ipv4.tcp_rmem
net.ipv4.tcp_wmem
net.ipv4.udp_rmem_min
net.ipv4.udp_wmem_min
net.ipv4.ip_local_port_range
net.ipv4.tcp_keepalive_time
net.ipv4.tcp_keepalive_intvl
net.ipv4.tcp_keepalive_probes
net.core.default_qdisc
net.ipv4.tcp_congestion_control
net.mptcp.enabled
EOF
}

snapshot_agent_sysctl_state(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local name=""
  local value=""
  if [[ "${REALM_AGENT_TEST_SKIP_RUNTIME_STATE_SNAPSHOT:-0}" == "1" ]]; then
    : > "${state_dir}/sysctl.snapshot-skipped"
    return 0
  fi
  command_exists sysctl || return 0
  while IFS= read -r name; do
    [[ -n "${name}" ]] || continue
    if value="$(sysctl -n "${name}" 2>/dev/null)"; then
      if ! printf '%s\n' "${value}" > "${state_dir}/sysctl.${name}.value" \
        || ! : > "${state_dir}/sysctl.${name}.present"; then
        err "无法快照 sysctl：${name}"
        return 1
      fi
    elif ! : > "${state_dir}/sysctl.${name}.absent"; then
      err "无法记录 sysctl 缺失状态：${name}"
      return 1
    fi
  done < <(agent_managed_sysctl_names)
}

restore_agent_sysctl_state(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local name=""
  local value=""
  local current=""
  local failed="0"
  [[ ! -f "${state_dir}/sysctl.snapshot-skipped" ]] || return 0
  command_exists sysctl || return 0
  while IFS= read -r name; do
    [[ -n "${name}" ]] || continue
    if [[ -f "${state_dir}/sysctl.${name}.present" ]]; then
      value="$(cat "${state_dir}/sysctl.${name}.value")"
      if ! sysctl -w "${name}=${value}" >/dev/null 2>&1; then
        err "无法恢复 sysctl：${name}"
        failed="1"
        continue
      fi
      current="$(sysctl -n "${name}" 2>/dev/null || true)"
      if [[ "${current}" != "${value}" ]]; then
        err "sysctl rollback 最终值不匹配：${name}"
        failed="1"
      fi
    elif [[ ! -f "${state_dir}/sysctl.${name}.absent" ]]; then
      err "缺少 sysctl rollback 状态：${name}"
      failed="1"
    fi
  done < <(agent_managed_sysctl_names)
  [[ "${failed}" == "0" ]]
}

snapshot_agent_mptcp_limits_state(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local output=""
  if [[ "${REALM_AGENT_TEST_SKIP_RUNTIME_STATE_SNAPSHOT:-0}" == "1" ]]; then
    : > "${state_dir}/mptcp-limits.absent"
    return 0
  fi
  if command_exists ip \
    && output="$(ip mptcp limits show 2>/dev/null)"; then
    printf '%s\n' "${output}" > "${state_dir}/mptcp-limits.value"
    : > "${state_dir}/mptcp-limits.present"
  else
    : > "${state_dir}/mptcp-limits.absent"
  fi
}

restore_agent_mptcp_limits_state(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local output=""
  local subflows=""
  local accepted=""
  [[ -f "${state_dir}/mptcp-limits.present" ]] || return 0
  command_exists ip || {
    err "无法恢复 MPTCP limits：缺少 ip 命令"
    return 1
  }
  output="$(cat "${state_dir}/mptcp-limits.value")"
  subflows="$(
    printf '%s\n' "${output}" \
      | awk '{for (i=1;i<=NF;i++) if ($i=="subflows") {print $(i+1); exit}}'
  )"
  accepted="$(
    printf '%s\n' "${output}" \
      | awk '{for (i=1;i<=NF;i++) if ($i=="add_addr_accepted") {print $(i+1); exit}}'
  )"
  if [[ ! "${subflows}" =~ ^[0-9]+$ || ! "${accepted}" =~ ^[0-9]+$ ]]; then
    err "无法解析 MPTCP limits rollback 快照"
    return 1
  fi
  if ! ip mptcp limits set \
    subflows "${subflows}" add_addr_accepted "${accepted}" >/dev/null 2>&1; then
    err "无法恢复 MPTCP limits"
    return 1
  fi
}

snapshot_agent_managed_directory(){
  local path="$1"
  local name="$2"
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  if [[ -L "${path}" || ( -e "${path}" && ! -d "${path}" ) ]]; then
    err "受管目录不是可信真实目录：${path}"
    return 1
  fi
  if [[ -d "${path}" ]]; then
    if ! cp -a "${path}" "${state_dir}/${name}.directory" \
      || ! : > "${state_dir}/${name}.directory-present"; then
      err "无法快照受管目录：${path}"
      return 1
    fi
  elif ! : > "${state_dir}/${name}.directory-absent"; then
    err "无法记录受管目录缺失状态：${path}"
    return 1
  fi
}

restore_agent_managed_directory(){
  local path="$1"
  local name="$2"
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local failed_path="${state_dir}/${name}.failed-current"
  rm -rf "${failed_path}" >/dev/null 2>&1 || true
  if [[ -e "${path}" || -L "${path}" ]]; then
    if ! mv "${path}" "${failed_path}"; then
      err "无法隔离失败的受管目录：${path}"
      return 1
    fi
  fi
  if [[ -f "${state_dir}/${name}.directory-present" ]]; then
    if ! mkdir -p "$(dirname "${path}")" \
      || ! cp -a "${state_dir}/${name}.directory" "${path}"; then
      if [[ -e "${failed_path}" || -L "${failed_path}" ]]; then
        mv "${failed_path}" "${path}" >/dev/null 2>&1 || true
      fi
      err "无法恢复受管目录：${path}"
      return 1
    fi
  elif [[ ! -f "${state_dir}/${name}.directory-absent" ]]; then
    if [[ -e "${failed_path}" || -L "${failed_path}" ]]; then
      mv "${failed_path}" "${path}" >/dev/null 2>&1 || true
    fi
    err "缺少受管目录 rollback 状态：${name}"
    return 1
  fi
  rm -rf "${failed_path}" >/dev/null 2>&1 || true
}

agent_sandbox_is_host_unit_dir(){
  local raw=""
  local normalized=""
  raw="$(agent_systemd_dir)" || return 1
  normalized="${raw%/}"
  [[ -n "${normalized}" ]] || normalized="/"
  case "${normalized}" in
    /etc/systemd/system|/usr/local/lib/systemd/system|\
    /usr/lib/systemd/system|/lib/systemd/system)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

agent_sandbox_expected_uid(){
  printf '%s' 0
}

agent_sandbox_expected_gid(){
  printf '%s' 0
}

agent_sandbox_trust_root(){
  local path="$1"
  case "${path}" in
    /etc|/etc/*) printf '%s' /etc ;;
    /var|/var/*) printf '%s' /var ;;
    /root|/root/*) printf '%s' /root ;;
    *) printf '%s' / ;;
  esac
}

agent_sandbox_path_within_trust_root(){
  local path="$1"
  local trust_root="$2"
  if [[ "${trust_root}" == "/" ]]; then
    [[ "${path}" == /* ]]
    return
  fi
  [[ "${path}" == "${trust_root}" || "${path}" == "${trust_root}/"* ]]
}

agent_sandbox_stat_field(){
  local path="$1"
  local linux_format="$2"
  local bsd_format="$3"
  stat -c "${linux_format}" "${path}" 2>/dev/null \
    || stat -f "${bsd_format}" "${path}" 2>/dev/null
}

agent_sandbox_acl_is_write_safe(){
  local acl="$1"
  awk -F: '
    function valid_permissions(value) {
      return value ~ /^[r-][w-][x-]$/
    }
    BEGIN {
      mask = ""
      named_count = 0
      unsafe = 0
      owner_count = 0
      group_count = 0
      other_count = 0
      mask_count = 0
    }
    /^$/ {
      next
    }
    /^default:/ {
      unsafe = 1
      next
    }
    NF == 3 && $1 == "user" && $2 == "" {
      owner_count += 1
      owner_permissions = $3
      if (!valid_permissions($3)) {
        unsafe = 1
      }
      next
    }
    NF == 3 && $1 == "group" && $2 == "" {
      group_count += 1
      group_permissions = $3
      if (!valid_permissions($3)) {
        unsafe = 1
      }
      next
    }
    NF == 3 && $1 == "other" && $2 == "" {
      other_count += 1
      other_permissions = $3
      if (!valid_permissions($3)) {
        unsafe = 1
      }
      next
    }
    NF == 3 && $1 == "mask" && $2 == "" {
      mask_count += 1
      mask = $3
      if (!valid_permissions($3)) {
        unsafe = 1
      }
      next
    }
    NF == 3 && ($1 == "user" || $1 == "group") && $2 ~ /^[0-9]+$/ {
      entry_key = $1 ":" $2
      if (seen_named[entry_key] || !valid_permissions($3)) {
        unsafe = 1
        next
      }
      seen_named[entry_key] = 1
      named_count += 1
      named_permissions[named_count] = $3
      next
    }
    {
      unsafe = 1
    }
    END {
      if (unsafe) {
        exit 1
      }
      if (owner_count != 1 || group_count != 1 || other_count != 1) {
        exit 1
      }
      if (mask_count > 1 || (named_count > 0 && mask_count != 1)) {
        exit 1
      }
      if (other_permissions ~ /w/) {
        exit 1
      }
      if (group_permissions ~ /w/ && (mask_count == 0 || mask ~ /w/)) {
        exit 1
      }
      for (entry_index = 1; entry_index <= named_count; entry_index += 1) {
        if (named_permissions[entry_index] ~ /w/ && mask ~ /w/) {
          exit 1
        }
      }
      exit 0
    }
  ' <<< "${acl}"
}

agent_sandbox_acl_xattrs_absent(){
  local path="$1"
  local python_bin=""
  python_bin="$(trusted_agent_bootstrap_python || true)"
  [[ -n "${python_bin}" ]] || return 1
  "${python_bin}" - "${path}" <<'PY' >/dev/null 2>&1
import errno
import os
import sys

path = sys.argv[1]
if not hasattr(os, "getxattr"):
    raise SystemExit(0 if sys.platform != "linux" else 1)
missing = {
    value
    for value in (
        getattr(errno, "ENODATA", None),
        getattr(errno, "ENOATTR", None),
    )
    if value is not None
}
unsupported = {
    value
    for value in (
        getattr(errno, "ENOTSUP", None),
        getattr(errno, "EOPNOTSUPP", None),
    )
    if value is not None
}
for attribute in ("system.posix_acl_access", "system.posix_acl_default"):
    try:
        os.getxattr(path, attribute)
    except OSError as exc:
        if exc.errno in missing or exc.errno in unsupported:
            continue
        raise
    raise SystemExit(1)
PY
}

agent_sandbox_validate_directory(){
  local path="$1"
  local expected_uid="$2"
  local expected_gid="$3"
  local allowed_mode="$4"
  local actual_uid=""
  local actual_gid=""
  local actual_mode=""
  local actual_value=0
  local allowed_value=0
  [[ -d "${path}" && ! -L "${path}" ]] || return 1
  actual_uid="$(agent_sandbox_stat_field "${path}" '%u' '%u' || true)"
  actual_gid="$(agent_sandbox_stat_field "${path}" '%g' '%g' || true)"
  actual_mode="$(agent_sandbox_stat_field "${path}" '%a' '%Lp' || true)"
  [[ "${actual_uid}" == "${expected_uid}" \
    && "${actual_gid}" == "${expected_gid}" \
    && "${actual_mode}" =~ ^[0-7]{3,4}$ ]] || return 1
  actual_value=$((8#${actual_mode}))
  allowed_value=$((8#${allowed_mode#0}))
  if (( (actual_value & ~allowed_value) != 0 \
    || (actual_value & 0700) != 0700 )); then
    return 1
  fi
  if command_exists getfacl; then
    local acl=""
    if ! acl="$(LC_ALL=C getfacl -c -E -p -n -- "${path}" 2>/dev/null)"; then
      err "无法读取 Agent sandbox ACL：${path}"
      return 1
    fi
    if ! agent_sandbox_acl_is_write_safe "${acl}"; then
      err "Agent sandbox ACL 含默认规则或允许非所有者写入：${path}"
      return 1
    fi
  elif ! agent_sandbox_acl_xattrs_absent "${path}"; then
    err "缺少 getfacl，且无法证明 Agent sandbox 目录不存在 POSIX ACL：${path}"
    return 1
  fi
}

agent_sandbox_validate_path_chain(){
  local path="$1"
  local final_mode="${2:-0755}"
  local expected_uid=""
  local expected_gid=""
  local trust_root=""
  local current=""
  local remaining=""
  local component=""
  local allowed_mode=""
  expected_uid="$(agent_sandbox_expected_uid)" || return 1
  expected_gid="$(agent_sandbox_expected_gid)" || return 1
  trust_root="$(agent_sandbox_trust_root "${path}")"
  if ! agent_sandbox_validate_directory \
    "${trust_root}" "${expected_uid}" "${expected_gid}" 0755; then
    err "Agent sandbox 可信根不是安全 root-owned 目录：${trust_root}"
    return 1
  fi
  current="${trust_root}"
  remaining="${path#"${trust_root}"}"
  while [[ -n "${remaining}" ]]; do
    remaining="${remaining#/}"
    component="${remaining%%/*}"
    if [[ "${component}" == "${remaining}" ]]; then
      remaining=""
    else
      remaining="${remaining#*/}"
    fi
    current="${current%/}/${component}"
    [[ -e "${current}" || -L "${current}" ]] || return 0
    allowed_mode="0755"
    [[ -n "${remaining}" ]] || allowed_mode="${final_mode}"
    if ! agent_sandbox_validate_directory \
      "${current}" "${expected_uid}" "${expected_gid}" "${allowed_mode}"; then
      err "Agent sandbox 路径链含不可信目录：${current}"
      return 1
    fi
  done
}

agent_sandbox_validate_systemd_dir(){
  local systemd_dir=""
  systemd_dir="$(agent_systemd_dir)" || return 1
  while [[ "${systemd_dir}" != "/" && "${systemd_dir}" == */ ]]; do
    systemd_dir="${systemd_dir%/}"
  done
  if ! agent_sandbox_is_host_unit_dir; then
    err "Agent systemd 目录仅支持固定持久路径，拒绝别名或自定义目录：${systemd_dir}"
    return 1
  fi
  if ! agent_sandbox_validate_path_chain "${systemd_dir}" 0755 \
    || ! agent_sandbox_validate_directory \
      "${systemd_dir}" \
      "$(agent_sandbox_expected_uid)" \
      "$(agent_sandbox_expected_gid)" \
      0755; then
    err "Agent systemd 目录链不可信或不是安全普通目录：${systemd_dir}"
    return 1
  fi
}

agent_sandbox_prepare_path(){
  local mode="$1"
  local path="$2"
  local created_file="$3"
  local expected_uid=""
  local expected_gid=""
  local trust_root=""
  local current=""
  local remaining=""
  local component=""
  local create_mode=""
  expected_uid="$(agent_sandbox_expected_uid)" || return 1
  expected_gid="$(agent_sandbox_expected_gid)" || return 1
  while [[ "${path}" != "/" && "${path}" == */ ]]; do
    path="${path%/}"
  done
  trust_root="$(agent_sandbox_trust_root "${path}")"
  agent_sandbox_path_within_trust_root "${path}" "${trust_root}" || {
    err "Agent sandbox 路径不在可信根下：${path}"
    return 1
  }
  if ! agent_sandbox_validate_directory \
    "${trust_root}" "${expected_uid}" "${expected_gid}" 0755; then
    err "Agent sandbox 可信根不是 root-owned 且不可被低权限写入：${trust_root}"
    return 1
  fi
  current="${trust_root}"
  remaining="${path#"${trust_root}"}"
  while [[ -n "${remaining}" ]]; do
    remaining="${remaining#/}"
    component="${remaining%%/*}"
    if [[ "${component}" == "${remaining}" ]]; then
      remaining=""
    else
      remaining="${remaining#*/}"
    fi
    [[ -n "${component}" && "${component}" != "." && "${component}" != ".." ]] || {
      err "Agent sandbox 路径组件无效：${path}"
      return 1
    }
    current="${current%/}/${component}"
    create_mode="0755"
    [[ -z "${remaining}" ]] && create_mode="${mode}"
    if [[ -L "${current}" || -e "${current}" ]]; then
      if [[ -L "${current}" || ! -d "${current}" ]] \
        || ! agent_sandbox_validate_directory \
          "${current}" "${expected_uid}" "${expected_gid}" "${create_mode}"; then
        err "Agent sandbox 目录不是可信 root-owned 普通目录：${current}"
        return 1
      fi
      continue
    fi
    # Record before mkdir so a signal or partial mkdir cannot escape rollback.
    printf '%s\n' "${current}" >> "${created_file}" || return 1
    durable_sync_agent_path "${created_file}" || return 1
    if ! install -d -m "${create_mode}" "${current}" \
      || ! chmod "${create_mode}" "${current}" \
      || ! agent_sandbox_validate_directory \
        "${current}" "${expected_uid}" "${expected_gid}" "${create_mode}"; then
      err "无法创建可信 Agent sandbox 目录：${current}"
      return 1
    fi
  done
}

agent_sandbox_path_entries(){
  cat <<'EOF'
0755	/etc/realm
0755	/etc/nginx
0755	/etc/ssl/nexus
0755	/etc/letsencrypt
0755	/var/lib/realm-agent
0700	/root/.acme.sh
0755	/www
EOF
}

preflight_agent_sandbox_paths(){
  local mode=""
  local path=""
  agent_sandbox_validate_systemd_dir || return 1
  while IFS=$'\t' read -r mode path; do
    [[ -n "${mode}" && -n "${path}" ]] || continue
    agent_sandbox_validate_path_chain "${path}" "${mode}" || return 1
  done < <(agent_sandbox_path_entries)
}

prepare_agent_sandbox_paths(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local created_file="${state_dir}/sandbox-created.paths"
  local mode=""
  local path=""
  preflight_agent_sandbox_paths || return 1
  [[ -f "${created_file}" ]] || : > "${created_file}" || return 1
  while IFS=$'\t' read -r mode path; do
    [[ -n "${mode}" && -n "${path}" ]] || continue
    agent_sandbox_prepare_path "${mode}" "${path}" "${created_file}" || return 1
  done < <(agent_sandbox_path_entries)
}

restore_agent_sandbox_paths(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local created_file="${state_dir}/sandbox-created.paths"
  local reverse_file="${created_file}.reverse"
  local path=""
  local failed="0"
  [[ -f "${created_file}" ]] || return 0
  if ! awk '{ paths[NR] = $0 } END { for (i = NR; i > 0; i--) print paths[i] }' \
    "${created_file}" > "${reverse_file}"; then
    err "无法读取 Agent sandbox rollback 清单：${created_file}"
    return 1
  fi
  while IFS= read -r path; do
    [[ -n "${path}" ]] || continue
    if ! agent_sandbox_validate_path_chain "${path}"; then
      err "Agent sandbox rollback 路径链不可信：${path}"
      failed="1"
      continue
    fi
    [[ -e "${path}" ]] || continue
    if ! rmdir "${path}" >/dev/null 2>&1; then
      err "Agent sandbox rollback 目录非空或无法删除：${path}"
      failed="1"
    fi
  done < "${reverse_file}"
  rm -f "${reverse_file}" >/dev/null 2>&1 || true
  [[ "${failed}" == "0" ]]
}

agent_unit_active_state(){
  local unit="$1"
  local state=""
  state="$(systemctl is-active "${unit}" 2>/dev/null || true)"
  case "${state}" in
    active|activating|reloading|deactivating)
      printf '%s' active
      ;;
    inactive|failed|unknown)
      printf '%s' inactive
      ;;
    *)
      err "无法读取 unit active 状态：${unit}"
      return 1
      ;;
  esac
}

agent_unit_snapshot_active_state(){
  local unit="$1"
  local state=""
  state="$(systemctl is-active "${unit}" 2>/dev/null || true)"
  case "${state}" in
    active|activating|reloading)
      printf '%s' active
      ;;
    deactivating|inactive|failed|unknown)
      printf '%s' inactive
      ;;
    *)
      err "无法读取 unit 快照状态：${unit}"
      return 1
      ;;
  esac
}

normalize_agent_snapshot_required_active_units(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local pair=""
  local requiring_unit=""
  local required_unit=""
  for pair in "${AGENT_ROLLBACK_REQUIRED_ACTIVE_PAIRS[@]}"; do
    requiring_unit="${pair%% *}"
    required_unit="${pair#* }"
    [[ -n "${requiring_unit}" && -n "${required_unit}" \
      && "${requiring_unit}" != "${required_unit}" ]] || return 1
    [[ -f "${state_dir}/${requiring_unit}.was-active" ]] || continue
    if [[ ! -f "${state_dir}/${required_unit}.state-snapshotted" ]]; then
      err "active unit 的必需依赖缺少 rollback 快照：${required_unit}"
      return 1
    fi
    if ! : > "${state_dir}/${required_unit}.was-active" \
      || ! rm -f "${state_dir}/${required_unit}.was-inactive"; then
      err "无法规范化 rollback 必需依赖状态：${required_unit}"
      return 1
    fi
  done
}

agent_unit_enabled_state(){
  local unit="$1"
  local state=""
  local load_state=""
  state="$(systemctl is-enabled "${unit}" 2>/dev/null || true)"
  if [[ -z "${state}" ]]; then
    load_state="$(
      systemctl show --property=LoadState --value "${unit}" 2>/dev/null || true
    )"
    if [[ "${load_state}" == "not-found" ]]; then
      printf '%s' disabled
      return 0
    fi
  fi
  case "${state}" in
    enabled|enabled-runtime|linked|linked-runtime|alias)
      printf '%s' enabled
      ;;
    disabled|static|indirect|masked|masked-runtime|generated|transient|bad|not-found)
      printf '%s' disabled
      ;;
    *)
      err "无法读取 unit enabled 状态：${unit}"
      return 1
      ;;
  esac
}

snapshot_agent_unit_states(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local unit=""
  local active_state=""
  local enabled_state=""
  command_exists systemctl || return 0
  for unit in "${AGENT_MANAGED_UNITS[@]}"; do
    [[ -n "${unit}" ]] || continue
    # The recovery bootstrap is monotonic safety infrastructure. A failed
    # Agent rollout keeps the newest trusted recovery entrypoint installed.
    [[ "${unit}" != "realm-agent-install-recovery.service" ]] || continue
    if ! : > "${state_dir}/${unit}.state-snapshotted"; then
      err "无法记录 unit rollback 状态：${unit}"
      return 1
    fi
    active_state="$(agent_unit_snapshot_active_state "${unit}")" || return 1
    if [[ "${active_state}" == "active" ]]; then
      if ! : > "${state_dir}/${unit}.was-active"; then
        return 1
      fi
    else
      if ! : > "${state_dir}/${unit}.was-inactive"; then
        return 1
      fi
    fi
    enabled_state="$(agent_unit_enabled_state "${unit}")" || return 1
    if [[ "${enabled_state}" == "enabled" ]]; then
      if ! : > "${state_dir}/${unit}.was-enabled"; then
        return 1
      fi
    else
      if ! : > "${state_dir}/${unit}.was-disabled"; then
        return 1
      fi
    fi
  done
  normalize_agent_snapshot_required_active_units
}

rollback_systemctl(){
  local label="$1"
  shift
  if ! systemctl "$@" >/dev/null 2>&1; then
    err "回滚 systemctl 失败（${label}）：systemctl $*"
    return 1
  fi
}

wait_agent_unit_inactive(){
  local unit="$1"
  local max_attempts="${2:-50}"
  local attempt=""
  local active_state=""
  if [[ ! "${max_attempts}" =~ ^[0-9]+$ ]] || (( max_attempts < 1 )); then
    max_attempts=50
  fi
  for ((attempt = 1; attempt <= max_attempts; attempt++)); do
    active_state="$(agent_unit_active_state "${unit}")" || return 1
    if [[ "${active_state}" == "inactive" ]]; then
      return 0
    fi
    sleep 0.1
  done
  err "回滚等待 unit inactive 超时：${unit}"
  return 1
}

prepare_agent_units_for_restore(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local unit=""
  local stop_pass=""
  local failed="0"
  local active_state=""
  local enabled_state=""
  command_exists systemctl || return 0
  for stop_pass in 1 2; do
    for unit in "${AGENT_ROLLBACK_STOP_UNITS[@]}"; do
      [[ -f "${state_dir}/${unit}.state-snapshotted" ]] || continue
      agent_skip_recovery_unit_during_self_restore "${unit}" && continue
      if ! active_state="$(agent_unit_active_state "${unit}")"; then
        failed="1"
        continue
      fi
      if [[ "${active_state}" == "active" ]]; then
        rollback_systemctl "stop ${unit}" stop "${unit}" || true
      fi
    done
  done
  for unit in "${AGENT_ROLLBACK_STOP_UNITS[@]}"; do
    [[ -f "${state_dir}/${unit}.state-snapshotted" ]] || continue
    agent_skip_recovery_unit_during_self_restore "${unit}" && continue
    if ! wait_agent_unit_inactive "${unit}"; then
      err "回滚停止后 unit 仍 active：${unit}"
      failed="1"
    fi
  done
  for unit in "${AGENT_MANAGED_UNITS[@]}"; do
    [[ -f "${state_dir}/${unit}.state-snapshotted" ]] || continue
    agent_skip_recovery_unit_during_self_restore "${unit}" && continue
    if ! enabled_state="$(agent_unit_enabled_state "${unit}")"; then
      failed="1"
      continue
    fi
    if [[ "${enabled_state}" == "enabled" ]]; then
      if ! rollback_systemctl "disable ${unit}" disable "${unit}"; then
        failed="1"
      elif ! enabled_state="$(agent_unit_enabled_state "${unit}")" \
        || [[ "${enabled_state}" != "disabled" ]]; then
        err "回滚禁用后 unit 仍 enabled：${unit}"
        failed="1"
      fi
    fi
    systemctl reset-failed "${unit}" >/dev/null 2>&1 || true
  done
  for unit in "${AGENT_MANAGED_UNITS[@]}"; do
    [[ -f "${state_dir}/${unit}.state-snapshotted" ]] || continue
    agent_skip_recovery_unit_during_self_restore "${unit}" && continue
    if ! wait_agent_unit_inactive "${unit}" 1; then
      err "回滚最终停机复核失败：${unit}"
      failed="1"
    fi
  done
  [[ "${failed}" == "0" ]]
}

force_quiesce_agent_units_after_failed_restore(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local unit=""
  command_exists systemctl || return 1
  if prepare_agent_units_for_restore; then
    return 0
  fi
  for unit in "${AGENT_ROLLBACK_STOP_UNITS[@]}"; do
    [[ -f "${state_dir}/${unit}.state-snapshotted" ]] || continue
    agent_skip_recovery_unit_during_self_restore "${unit}" && continue
    systemctl stop "${unit}" >/dev/null 2>&1 || true
    systemctl kill --kill-who=all --signal=SIGKILL "${unit}" \
      >/dev/null 2>&1 || true
    systemctl stop "${unit}" >/dev/null 2>&1 || true
  done
  prepare_agent_units_for_restore
}

agent_units_inactive_for_identity_rollback(){
  local unit=""
  command_exists systemctl || return 1
  for unit in "${AGENT_CUTOVER_UNITS[@]}"; do
    [[ -n "${unit}" ]] || continue
    agent_skip_recovery_unit_during_self_restore "${unit}" && continue
    if ! wait_agent_unit_inactive "${unit}" 1; then
      err "realm-agent 身份回滚前 unit 仍在运行：${unit}"
      return 1
    fi
  done
}

restore_agent_unit_states(){
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local unit=""
  local failed="0"
  local active_state=""
  local enabled_state=""
  local restore_pass=0
  command_exists systemctl || return 0
  normalize_agent_snapshot_required_active_units || return 1
  for unit in "${AGENT_MANAGED_UNITS[@]}"; do
    [[ -f "${state_dir}/${unit}.state-snapshotted" ]] || continue
    agent_skip_recovery_unit_during_self_restore "${unit}" && continue
    if [[ -f "${state_dir}/${unit}.was-enabled" ]]; then
      if ! rollback_systemctl "enable ${unit}" enable "${unit}"; then
        failed="1"
        break
      fi
    fi
  done
  [[ "${failed}" == "0" ]] || return 1

  # Starting one unit can activate a recorded-inactive soft dependency, while
  # stopping a recorded-inactive PartOf parent can stop recorded-active
  # children. Two convergence passes restore both dependency directions.
  for ((restore_pass = 1; restore_pass <= 2; restore_pass++)); do
    for unit in "${AGENT_MANAGED_UNITS[@]}"; do
      [[ -f "${state_dir}/${unit}.state-snapshotted" ]] || continue
      agent_skip_recovery_unit_during_self_restore "${unit}" && continue
      [[ -f "${state_dir}/${unit}.was-active" ]] || continue
      if ! active_state="$(agent_unit_active_state "${unit}")"; then
        failed="1"
        continue
      fi
      if [[ "${active_state}" != "active" ]] \
        && ! rollback_systemctl "start ${unit}" start "${unit}"; then
        failed="1"
      fi
    done
    [[ "${failed}" == "0" ]] || return 1

    for unit in "${AGENT_ROLLBACK_STOP_UNITS[@]}"; do
      [[ -f "${state_dir}/${unit}.state-snapshotted" ]] || continue
      agent_skip_recovery_unit_during_self_restore "${unit}" && continue
      [[ ! -f "${state_dir}/${unit}.was-active" ]] || continue
      if ! active_state="$(agent_unit_active_state "${unit}")"; then
        failed="1"
        continue
      fi
      if [[ "${active_state}" == "active" ]] \
        && ! rollback_systemctl \
          "stop dependency-reactivated ${unit}" stop "${unit}"; then
        failed="1"
      fi
    done
    [[ "${failed}" == "0" ]] || return 1
  done

  for unit in "${AGENT_ROLLBACK_STOP_UNITS[@]}"; do
    [[ -f "${state_dir}/${unit}.state-snapshotted" ]] || continue
    agent_skip_recovery_unit_during_self_restore "${unit}" && continue
    [[ ! -f "${state_dir}/${unit}.was-active" ]] || continue
    if ! wait_agent_unit_inactive "${unit}"; then
      failed="1"
    fi
  done
  [[ "${failed}" == "0" ]] || return 1

  for unit in "${AGENT_MANAGED_UNITS[@]}"; do
    [[ -f "${state_dir}/${unit}.state-snapshotted" ]] || continue
    agent_skip_recovery_unit_during_self_restore "${unit}" && continue
    if ! enabled_state="$(agent_unit_enabled_state "${unit}")" \
      || ! active_state="$(agent_unit_active_state "${unit}")"; then
      failed="1"
      continue
    fi
    if [[ -f "${state_dir}/${unit}.was-enabled" ]]; then
      if [[ "${enabled_state}" != "enabled" ]]; then
        err "回滚最终 enabled 状态不匹配：${unit}"
        failed="1"
      fi
    elif [[ "${enabled_state}" != "disabled" ]]; then
      err "回滚最终 disabled 状态不匹配：${unit}"
      failed="1"
    fi
    if [[ -f "${state_dir}/${unit}.was-active" ]]; then
      if [[ "${active_state}" != "active" ]]; then
        err "回滚最终 active 状态不匹配：${unit}"
        failed="1"
      fi
    elif [[ "${active_state}" != "inactive" ]]; then
      err "回滚最终 inactive 状态不匹配：${unit}"
      failed="1"
    fi
  done
  [[ "${failed}" == "0" ]]
}

begin_agent_deploy_rollback(){
  local base="$1"
  local rollback_dir="$2"
  local replace_venv="$3"
  local tls_cert="${4:-}"
  local tls_key="${5:-}"
  local config_dir=""
  config_dir="$(agent_config_dir)"
  if [[ -L "${config_dir}" || ( -e "${config_dir}" && ! -d "${config_dir}" ) ]]; then
    err "Agent 配置目录不是可信普通目录：${config_dir}"
    return 1
  fi
  if ! install -d -m 700 "${rollback_dir}" "${rollback_dir}/state"; then
    err "无法创建 Agent rollback 目录：${rollback_dir}"
    return 1
  fi
  REALM_AGENT_DEPLOY_ROLLBACK_BASE="${base}"
  REALM_AGENT_DEPLOY_ROLLBACK_DIR="${rollback_dir}"
  REALM_AGENT_DEPLOY_REPLACE_VENV="${replace_venv}"
  REALM_AGENT_ROLLBACK_TLS_CERT="${tls_cert}"
  REALM_AGENT_ROLLBACK_TLS_KEY="${tls_key}"
  REALM_AGENT_ROLLBACK_TLS_CERT_SNAPSHOTTED="0"
  REALM_AGENT_ROLLBACK_TLS_KEY_SNAPSHOTTED="0"
  REALM_AGENT_TARGET_API_KEY_ADOPTED="0"
  REALM_AGENT_ADOPTED_API_KEY_VERSION=""
  if [[ -d "${base}" ]]; then
    : > "${rollback_dir}/state/base.directory-present"
  else
    : > "${rollback_dir}/state/base.directory-absent"
  fi
  if ! snapshot_agent_managed_files "${base}" \
    || ! snapshot_agent_rollback_file "$(agent_api_key_path)" api-key \
    || ! snapshot_agent_managed_directory "${base}/python" managed-python \
    || ! snapshot_agent_managed_directory "${base}/bin" managed-bin \
    || ! snapshot_agent_tls_directory_metadata "${tls_cert}" "${tls_key}" \
    || ! snapshot_agent_sysctl_state \
    || ! snapshot_agent_mptcp_limits_state \
    || ! snapshot_agent_unit_states; then
    err "Agent rollback 快照不完整，拒绝开始更新事务"
    rm -rf "${rollback_dir}" >/dev/null 2>&1 || true
    return 1
  fi
  if [[ -n "${tls_cert}" ]]; then
    if ! snapshot_agent_rollback_file "${tls_cert}" tls-cert; then
      return 1
    fi
    REALM_AGENT_ROLLBACK_TLS_CERT_SNAPSHOTTED="1"
  fi
  if [[ -n "${tls_key}" ]]; then
    if ! snapshot_agent_rollback_file "${tls_key}" tls-key; then
      return 1
    fi
    REALM_AGENT_ROLLBACK_TLS_KEY_SNAPSHOTTED="1"
  fi
  REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE="1"
}

agent_deploy_transaction_path_safe(){
  local path="${1:-}"
  [[ "${path}" == /* && "${path}" != "/" ]] || return 1
  case "${path}" in
    *[!A-Za-z0-9_./:@%+-]*|*//*|*/../*|*/..|*/./*|*/.) return 1 ;;
  esac
}

agent_deploy_transaction_parent(){
  local parent="${REALM_AGENT_ROLLBACK_PARENT:-/var/lib/nexus/agent-update}"
  while [[ "${parent}" != "/" && "${parent}" == */ ]]; do
    parent="${parent%/}"
  done
  agent_deploy_transaction_path_safe "${parent}" || {
    err "Agent rollback 持久目录路径无效：${parent}"
    return 1
  }
  printf '%s' "${parent}"
}

agent_deploy_transaction_journal_path(){
  local parent=""
  parent="$(agent_deploy_transaction_parent)" || return 1
  printf '%s/active.env' "${parent}"
}

agent_deploy_transaction_directory_valid(){
  local path="$1"
  local metadata=""
  metadata="$(
    stat -Lc '%u:%g:%a' "${path}" 2>/dev/null \
      || stat -f '%u:%g:%Lp' "${path}" 2>/dev/null
  )" || return 1
  [[ -d "${path}" && ! -L "${path}" \
    && "${metadata}" == "$(id -u):$(id -g):700" ]]
}

agent_deploy_transaction_journal_valid(){
  local path="$1"
  local metadata=""
  local size=""
  metadata="$(
    stat -Lc '%u:%g:%a:%h' "${path}" 2>/dev/null \
      || stat -f '%u:%g:%Lp:%l' "${path}" 2>/dev/null
  )" || return 1
  size="$(wc -c < "${path}" 2>/dev/null | tr -d '[:space:]')" || return 1
  [[ -f "${path}" && ! -L "${path}" \
    && "${metadata}" == "$(id -u):$(id -g):600:1" \
    && "${size}" =~ ^[0-9]+$ && "${size}" -le 4096 ]]
}

ensure_agent_deploy_transaction_parent(){
  local parent=""
  parent="$(agent_deploy_transaction_parent)" || return 1
  if [[ -L "${parent}" || ( -e "${parent}" && ! -d "${parent}" ) ]]; then
    err "Agent rollback 持久目录不是可信普通目录：${parent}"
    return 1
  fi
  if [[ ! -d "${parent}" ]] \
    && ! install -d -m 0700 "${parent}"; then
    err "无法创建 Agent rollback 持久目录：${parent}"
    return 1
  fi
  chmod 0700 "${parent}" >/dev/null 2>&1 || return 1
  if ! agent_deploy_transaction_directory_valid "${parent}"; then
    err "Agent rollback 持久目录所有权或权限不可信：${parent}"
    return 1
  fi
}

durable_sync_agent_path(){
  local path="$1"
  if sync -f "${path}" >/dev/null 2>&1; then
    return 0
  fi
  sync >/dev/null 2>&1
}

durable_write_agent_transaction_file(){
  local path="$1"
  local value="${2:-}"
  local parent=""
  local tmp=""
  parent="$(dirname "${path}")"
  [[ -d "${parent}" && ! -L "${parent}" ]] || return 1
  if [[ -L "${path}" || ( -e "${path}" && ! -f "${path}" ) ]]; then
    return 1
  fi
  tmp="$(mktemp "${parent}/.$(basename "${path}").XXXXXX")" || return 1
  if ! printf '%s\n' "${value}" > "${tmp}" \
    || ! chmod 0600 "${tmp}" \
    || ! durable_sync_agent_path "${tmp}" \
    || ! mv -f "${tmp}" "${path}" \
    || ! durable_sync_agent_path "${parent}"; then
    rm -f "${tmp}" >/dev/null 2>&1 || true
    return 1
  fi
}

persist_agent_deploy_transaction_journal(){
  local state="$1"
  local parent=""
  local journal=""
  local tmp=""
  local rollback_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR:-}"
  local base="${REALM_AGENT_DEPLOY_ROLLBACK_BASE:-}"
  case "${state}" in prepared|committed|restored) ;; *) return 1 ;; esac
  ensure_agent_deploy_transaction_parent || return 1
  parent="$(agent_deploy_transaction_parent)" || return 1
  journal="${parent}/active.env"
  agent_deploy_transaction_path_safe "${base}" || return 1
  agent_deploy_transaction_path_safe "${rollback_dir}" || return 1
  [[ "${rollback_dir}" == "${parent}/realm-agent-rollback."* ]] || return 1
  if [[ -L "${rollback_dir}" || ! -d "${rollback_dir}" ]] \
    || ! agent_deploy_transaction_directory_valid "${rollback_dir}"; then
    return 1
  fi
  if [[ -n "${REALM_AGENT_ROLLBACK_TLS_CERT:-}" ]] \
    && ! agent_deploy_transaction_path_safe "${REALM_AGENT_ROLLBACK_TLS_CERT}"; then
    return 1
  fi
  if [[ -n "${REALM_AGENT_ROLLBACK_TLS_KEY:-}" ]] \
    && ! agent_deploy_transaction_path_safe "${REALM_AGENT_ROLLBACK_TLS_KEY}"; then
    return 1
  fi
  if [[ -L "${journal}" ]] \
    || { [[ -e "${journal}" ]] \
      && ! agent_deploy_transaction_journal_valid "${journal}"; }; then
    err "Agent rollback journal 元数据不可信：${journal}"
    return 1
  fi
  tmp="$(mktemp "${parent}/.active.XXXXXX")" || return 1
  if ! {
    printf 'SCHEMA=1\n'
    printf 'STATE=%s\n' "${state}"
    printf 'BASE=%s\n' "${base}"
    printf 'ROLLBACK_DIR=%s\n' "${rollback_dir}"
    printf 'REPLACE_VENV=%s\n' "${REALM_AGENT_DEPLOY_REPLACE_VENV:-0}"
    printf 'TLS_CERT=%s\n' "${REALM_AGENT_ROLLBACK_TLS_CERT:-}"
    printf 'TLS_KEY=%s\n' "${REALM_AGENT_ROLLBACK_TLS_KEY:-}"
    printf 'TLS_CERT_SNAPSHOTTED=%s\n' \
      "${REALM_AGENT_ROLLBACK_TLS_CERT_SNAPSHOTTED:-0}"
    printf 'TLS_KEY_SNAPSHOTTED=%s\n' \
      "${REALM_AGENT_ROLLBACK_TLS_KEY_SNAPSHOTTED:-0}"
  } > "${tmp}" \
    || ! chmod 0600 "${tmp}" \
    || ! durable_sync_agent_path "${tmp}" \
    || ! mv -f "${tmp}" "${journal}" \
    || ! durable_sync_agent_path "${parent}"; then
    rm -f "${tmp}" >/dev/null 2>&1 || true
    return 1
  fi
  AGENT_DEPLOY_JOURNAL_STATE="${state}"
}

load_agent_deploy_transaction_journal(){
  local parent=""
  local journal=""
  local key=""
  local value=""
  local schema="" state="" base="" rollback_dir=""
  local replace_venv="" tls_cert="" tls_key=""
  local cert_snapshotted="" key_snapshotted=""
  local seen=""
  parent="$(agent_deploy_transaction_parent)" || return 1
  journal="${parent}/active.env"
  agent_deploy_transaction_journal_valid "${journal}" || return 1
  while IFS='=' read -r key value; do
    case "${key}" in
      SCHEMA|STATE|BASE|ROLLBACK_DIR|REPLACE_VENV|TLS_CERT|TLS_KEY|\
TLS_CERT_SNAPSHOTTED|TLS_KEY_SNAPSHOTTED)
        [[ "${seen}" != *"|${key}|"* ]] || return 1
        seen="${seen}|${key}|"
        ;;
      *) return 1 ;;
    esac
    case "${key}" in
      SCHEMA) schema="${value}" ;;
      STATE) state="${value}" ;;
      BASE) base="${value}" ;;
      ROLLBACK_DIR) rollback_dir="${value}" ;;
      REPLACE_VENV) replace_venv="${value}" ;;
      TLS_CERT) tls_cert="${value}" ;;
      TLS_KEY) tls_key="${value}" ;;
      TLS_CERT_SNAPSHOTTED) cert_snapshotted="${value}" ;;
      TLS_KEY_SNAPSHOTTED) key_snapshotted="${value}" ;;
    esac
  done < "${journal}"
  for key in \
    SCHEMA STATE BASE ROLLBACK_DIR REPLACE_VENV TLS_CERT TLS_KEY \
    TLS_CERT_SNAPSHOTTED TLS_KEY_SNAPSHOTTED; do
    [[ "${seen}" == *"|${key}|"* ]] || return 1
  done
  [[ "${schema}" == "1" ]] || return 1
  case "${state}" in prepared|committed|restored) ;; *) return 1 ;; esac
  [[ "${replace_venv}" == "0" || "${replace_venv}" == "1" ]] || return 1
  [[ "${cert_snapshotted}" == "0" || "${cert_snapshotted}" == "1" ]] || return 1
  [[ "${key_snapshotted}" == "0" || "${key_snapshotted}" == "1" ]] || return 1
  agent_deploy_transaction_path_safe "${base}" || return 1
  agent_deploy_transaction_path_safe "${rollback_dir}" || return 1
  [[ "${rollback_dir}" == "${parent}/realm-agent-rollback."* ]] || return 1
  if [[ -e "${rollback_dir}" || -L "${rollback_dir}" ]]; then
    agent_deploy_transaction_directory_valid "${rollback_dir}" || return 1
  elif [[ "${state}" == "prepared" ]]; then
    return 1
  fi
  [[ -z "${tls_cert}" ]] || agent_deploy_transaction_path_safe "${tls_cert}" \
    || return 1
  [[ -z "${tls_key}" ]] || agent_deploy_transaction_path_safe "${tls_key}" \
    || return 1
  AGENT_DEPLOY_JOURNAL_STATE="${state}"
  REALM_AGENT_DEPLOY_ROLLBACK_BASE="${base}"
  REALM_AGENT_DEPLOY_ROLLBACK_DIR="${rollback_dir}"
  REALM_AGENT_DEPLOY_REPLACE_VENV="${replace_venv}"
  REALM_AGENT_ROLLBACK_TLS_CERT="${tls_cert}"
  REALM_AGENT_ROLLBACK_TLS_KEY="${tls_key}"
  REALM_AGENT_ROLLBACK_TLS_CERT_SNAPSHOTTED="${cert_snapshotted}"
  REALM_AGENT_ROLLBACK_TLS_KEY_SNAPSHOTTED="${key_snapshotted}"
}

clear_agent_deploy_transaction_journal(){
  local parent=""
  local journal=""
  parent="$(agent_deploy_transaction_parent)" || return 1
  journal="${parent}/active.env"
  if [[ -L "${journal}" ]] \
    || { [[ -e "${journal}" ]] \
      && ! agent_deploy_transaction_journal_valid "${journal}"; }; then
    return 1
  fi
  rm -f "${journal}" || return 1
  durable_sync_agent_path "${parent}"
}

recover_pending_agent_deploy_transaction(){
  local parent=""
  local journal=""
  local expected_version=""
  local current_version=""
  ensure_agent_deploy_transaction_parent || return 1
  parent="$(agent_deploy_transaction_parent)" || return 1
  journal="${parent}/active.env"
  [[ -e "${journal}" || -L "${journal}" ]] || return 0
  if ! load_agent_deploy_transaction_journal; then
    err "Agent rollback journal 无效；拒绝继续覆盖半完成事务：${journal}"
    return 1
  fi
  if [[ "${AGENT_DEPLOY_JOURNAL_STATE}" != "prepared" ]]; then
    rm -rf "${REALM_AGENT_DEPLOY_ROLLBACK_DIR}" >/dev/null 2>&1 || return 1
    clear_agent_deploy_transaction_journal || return 1
    info "已清理完成态 Agent rollback transaction"
    return 0
  fi
  expected_version="$(
    cat "${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state/api-key.target-version" \
      2>/dev/null || true
  )"
  if validate_agent_api_key_version "${expected_version}"; then
    current_version="$(agent_api_key_file_version "$(agent_api_key_path)" 0 0 || true)"
    if [[ "${current_version}" == "${expected_version}" ]]; then
      REALM_AGENT_TARGET_API_KEY_ADOPTED="1"
      REALM_AGENT_ADOPTED_API_KEY_VERSION="${expected_version}"
    fi
  fi
  REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE="1"
  err "检测到未提交的 Agent 更新事务，先恢复上一个可用版本"
  restore_agent_deploy_rollback
}

begin_root_agent_install_transaction(){
  local base="$1"
  local tls_cert="${2:-}"
  local tls_key="${3:-}"
  local rollback_parent=""
  local rollback_dir=""
  ensure_agent_deploy_transaction_parent || return 1
  rollback_parent="$(agent_deploy_transaction_parent)" || return 1
  if [[ -e "${rollback_parent}/active.env" \
    || -L "${rollback_parent}/active.env" ]]; then
    err "已有 Agent rollback journal，必须先完成恢复"
    return 1
  fi
  rollback_dir="$(mktemp -d "${rollback_parent%/}/realm-agent-rollback.XXXXXX")" \
    || return 1
  chmod 0700 "${rollback_dir}" >/dev/null 2>&1 || true
  if ! begin_agent_deploy_rollback \
    "${base}" "${rollback_dir}" 0 "${tls_cert}" "${tls_key}"; then
    rm -rf "${rollback_dir}" >/dev/null 2>&1 || true
    return 1
  fi
  if ! sync >/dev/null 2>&1 \
    || ! persist_agent_deploy_transaction_journal prepared; then
    REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE="0"
    rm -rf "${rollback_dir}" >/dev/null 2>&1 || true
    err "Agent rollback 快照无法持久化，拒绝开始更新事务"
    return 1
  fi
  info "已在任何 Agent/Realm/sysctl 受管写入前创建完整 rollback 快照"
}

snapshot_agent_tls_paths_for_transaction(){
  local cert="${1:-}"
  local key="${2:-}"
  [[ "${REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE:-0}" == "1" ]] || {
    err "TLS rollback 扩展必须在 active transaction 内执行"
    return 1
  }
  validate_agent_transaction_tls_extension "${cert}" "${key}" || return 1
  snapshot_agent_tls_directory_metadata "${cert}" "${key}" || return 1
  if [[ -n "${cert}" \
    && "${REALM_AGENT_ROLLBACK_TLS_CERT_SNAPSHOTTED:-0}" != "1" ]]; then
    if ! snapshot_agent_rollback_file "${cert}" tls-cert; then
      return 1
    fi
    REALM_AGENT_ROLLBACK_TLS_CERT="${cert}"
    REALM_AGENT_ROLLBACK_TLS_CERT_SNAPSHOTTED="1"
  fi
  if [[ -n "${key}" \
    && "${REALM_AGENT_ROLLBACK_TLS_KEY_SNAPSHOTTED:-0}" != "1" ]]; then
    if ! snapshot_agent_rollback_file "${key}" tls-key; then
      return 1
    fi
    REALM_AGENT_ROLLBACK_TLS_KEY="${key}"
    REALM_AGENT_ROLLBACK_TLS_KEY_SNAPSHOTTED="1"
  fi
  sync >/dev/null 2>&1 \
    && persist_agent_deploy_transaction_journal prepared
}

snapshot_agent_tls_directory_metadata(){
  local cert="${1:-}"
  local key="${2:-}"
  local default_dir=""
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local metadata=""
  default_dir="$(agent_default_tls_dir)"
  if [[ "$(dirname "${cert:-/}")" != "${default_dir}" \
    && "$(dirname "${key:-/}")" != "${default_dir}" ]]; then
    return 0
  fi
  if [[ -f "${state_dir}/tls-default-dir.present" \
    || -f "${state_dir}/tls-default-dir.absent" ]]; then
    return 0
  fi
  if [[ -e "${default_dir}" || -L "${default_dir}" ]]; then
    [[ -d "${default_dir}" && ! -L "${default_dir}" ]] || return 1
    metadata="$(
      stat -Lc '%u:%g:%a' "${default_dir}" 2>/dev/null \
        || stat -f '%u:%g:%Lp' "${default_dir}" 2>/dev/null
    )" || return 1
    printf '%s\n' "${metadata}" > "${state_dir}/tls-default-dir.metadata" \
      || return 1
    : > "${state_dir}/tls-default-dir.present"
  else
    : > "${state_dir}/tls-default-dir.absent"
  fi
}

restore_agent_tls_directory_metadata(){
  local default_dir=""
  local state_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}/state"
  local metadata=""
  local uid=""
  local gid=""
  local mode=""
  default_dir="$(agent_default_tls_dir)"
  if [[ -f "${state_dir}/tls-default-dir.present" ]]; then
    metadata="$(cat "${state_dir}/tls-default-dir.metadata")" || return 1
    IFS=: read -r uid gid mode <<< "${metadata}"
    [[ -d "${default_dir}" && ! -L "${default_dir}" ]] || return 1
    chmod "${mode}" "${default_dir}" || return 1
    chown "${uid}:${gid}" "${default_dir}" || return 1
  elif [[ -f "${state_dir}/tls-default-dir.absent" \
    && -d "${default_dir}" ]]; then
    rmdir "${default_dir}" 2>/dev/null || {
      err "rollback 后新建 TLS 目录仍含残留：${default_dir}"
      return 1
    }
  fi
}

prepare_agent_runtime_permissions(){
  local base="$1"
  local path=""
  local owner_uid="0"
  local owner_gid="0"
  if ! agent_sandbox_is_host_unit_dir; then
    owner_uid="$(id -u)"
    owner_gid="$(id -g)"
  fi
  if [[ -L "${base}" || ! -d "${base}" ]]; then
    err "Agent 运行根目录不是可信普通目录：${base}"
    return 1
  fi
  chown "${owner_uid}:${owner_gid}" "${base}" || return 1
  chmod 0755 "${base}" || return 1
  for path in "${base}/agent" "${base}/shared" "${base}/venv"; do
    [[ -e "${path}" || -L "${path}" ]] || continue
    if [[ -L "${path}" || ! -d "${path}" ]]; then
      err "Agent 运行路径不是可信普通目录：${path}"
      return 1
    fi
    chown -hR "${owner_uid}:${owner_gid}" "${path}" || {
      err "无法收紧 Agent 运行路径所有权：${path}"
      return 1
    }
    chmod -R u=rX,go=rX "${path}" || {
      err "无法设置 Agent 运行路径只读权限：${path}"
      return 1
    }
  done
  [[ -r "${base}/agent/app/gateway.py" ]] || {
    err "Agent gateway 源码不可读"
    return 1
  }
  [[ -x "${base}/venv/bin/python" ]] || {
    err "Agent venv Python 不可执行"
    return 1
  }
}

activate_agent_stage(){
  local stage="$1"
  local base="$2"
  local rollback_dir="$3"
  local replace_venv="$4"
  local name

  if [[ ! -d "${stage}/agent" || ! -d "${stage}/shared" ]]; then
    err "Agent staging 缺少 agent/shared，拒绝切换"
    return 1
  fi
  if [[ "${replace_venv}" == "1" && ! -x "${stage}/venv/bin/python" ]]; then
    err "Agent staging 缺少可执行 venv，拒绝切换"
    return 1
  fi
  if [[ "${replace_venv}" == "1" ]] \
    && ! repair_venv_script_shebangs \
      "${stage}/venv" "${stage}/venv" "${base}/venv"; then
    err "Agent staging venv 未通过最终路径 shebang/RECORD 预绑定"
    return 1
  fi

  for name in agent shared; do
    if [[ -e "${base}/${name}" || -L "${base}/${name}" ]]; then
      [[ ! -L "${base}/${name}" ]] || {
        err "拒绝替换符号链接目录：${base}/${name}"
        restore_agent_deploy_rollback
        return 1
      }
      if ! durable_write_agent_transaction_file \
        "${rollback_dir}/${name}.old-moved" ""; then
        restore_agent_deploy_rollback
        return 1
      fi
      if ! mv "${base}/${name}" "${rollback_dir}/${name}" \
        || ! durable_sync_agent_path "${base}" \
        || ! durable_sync_agent_path "${rollback_dir}"; then
        restore_agent_deploy_rollback
        return 1
      fi
    else
      durable_write_agent_transaction_file \
        "${rollback_dir}/${name}.absent" "" || return 1
    fi
  done
  if [[ "${replace_venv}" == "1" ]]; then
    if [[ -e "${base}/venv" || -L "${base}/venv" ]]; then
      [[ ! -L "${base}/venv" ]] || {
        err "拒绝替换符号链接 venv：${base}/venv"
        restore_agent_deploy_rollback
        return 1
      }
      if ! durable_write_agent_transaction_file \
        "${rollback_dir}/venv.old-moved" ""; then
        restore_agent_deploy_rollback
        return 1
      fi
      if ! mv "${base}/venv" "${rollback_dir}/venv" \
        || ! durable_sync_agent_path "${base}" \
        || ! durable_sync_agent_path "${rollback_dir}"; then
        restore_agent_deploy_rollback
        return 1
      fi
    else
      durable_write_agent_transaction_file \
        "${rollback_dir}/venv.absent" "" || return 1
    fi
  fi

  if ! durable_write_agent_transaction_file \
    "${rollback_dir}/agent.switched" "" \
    || ! mv "${stage}/agent" "${base}/agent" \
    || ! durable_sync_agent_path "${base}"; then
    restore_agent_deploy_rollback
    return 1
  fi
  if ! durable_write_agent_transaction_file \
    "${rollback_dir}/shared.switched" "" \
    || ! mv "${stage}/shared" "${base}/shared" \
    || ! durable_sync_agent_path "${base}"; then
    restore_agent_deploy_rollback
    return 1
  fi
  if [[ "${replace_venv}" == "1" ]]; then
    if ! durable_write_agent_transaction_file \
      "${rollback_dir}/venv.switched" "" \
      || ! mv "${stage}/venv" "${base}/venv" \
      || ! durable_sync_agent_path "${base}"; then
      restore_agent_deploy_rollback
      return 1
    fi
  fi
  if ! prepare_agent_runtime_permissions "${base}"; then
    restore_agent_deploy_rollback
    return 1
  fi
}

restore_agent_switched_directory(){
  local base="$1"
  local rollback_dir="$2"
  local name="$3"
  local current="${base}/${name}"
  local old="${rollback_dir}/${name}"
  local failed="${rollback_dir}/${name}.failed-new"
  local switched="${rollback_dir}/${name}.switched"
  local old_moved="${rollback_dir}/${name}.old-moved"
  local absent="${rollback_dir}/${name}.absent"
  local restore_intent="${rollback_dir}/${name}.restore-old-intent"
  local restored="${rollback_dir}/${name}.restored"

  [[ ! -f "${restored}" ]] || return 0
  if [[ ! -f "${switched}" && ! -f "${old_moved}" ]]; then
    return 0
  fi
  if [[ -f "${old_moved}" && ! -e "${old}" && ! -L "${old}" \
    && ! -f "${switched}" && -d "${current}" && ! -L "${current}" ]]; then
    durable_write_agent_transaction_file "${restored}" "" || return 1
    return 0
  fi
  if [[ -f "${old_moved}" && -f "${restore_intent}" \
    && ! -e "${old}" && ! -L "${old}" \
    && -d "${current}" && ! -L "${current}" ]]; then
    rm -rf "${failed}" >/dev/null 2>&1 || return 1
    durable_sync_agent_path "${rollback_dir}" || return 1
    durable_write_agent_transaction_file "${restored}" "" || return 1
    return 0
  fi
  rm -rf "${failed}" >/dev/null 2>&1 || true
  if [[ -f "${switched}" && ( -e "${current}" || -L "${current}" ) ]]; then
    if ! mv "${current}" "${failed}" \
      || ! durable_sync_agent_path "${base}" \
      || ! durable_sync_agent_path "${rollback_dir}"; then
      err "无法隔离失败的新目录：${current}"
      return 1
    fi
  fi
  if [[ -f "${old_moved}" ]]; then
    if [[ -d "${old}" && ! -L "${old}" ]]; then
      durable_write_agent_transaction_file "${restore_intent}" "" || return 1
      if ! mv "${old}" "${current}" \
        || ! durable_sync_agent_path "${base}" \
        || ! durable_sync_agent_path "${rollback_dir}"; then
        if [[ -e "${failed}" || -L "${failed}" ]]; then
          mv "${failed}" "${current}" >/dev/null 2>&1 || true
        fi
        err "旧目录恢复失败，已保留回滚副本：${old}"
        return 1
      fi
    elif [[ ! -f "${restore_intent}" \
      || ! -d "${current}" || -L "${current}" ]]; then
      if [[ -e "${failed}" || -L "${failed}" ]]; then
        mv "${failed}" "${current}" >/dev/null 2>&1 || true
      fi
      return 1
    fi
    rm -rf "${failed}" >/dev/null 2>&1 || return 1
    durable_sync_agent_path "${rollback_dir}" || return 1
    durable_write_agent_transaction_file "${restored}" "" || return 1
    return 0
  fi
  if [[ -f "${absent}" ]]; then
    rm -rf "${failed}" >/dev/null 2>&1 || return 1
    durable_sync_agent_path "${base}" || return 1
    durable_write_agent_transaction_file "${restored}" "" || return 1
    return 0
  fi
  if [[ -e "${failed}" || -L "${failed}" ]]; then
    mv "${failed}" "${current}" >/dev/null 2>&1 || true
  fi
  return 1
}

restore_agent_deploy_rollback(){
  [[ "${REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE:-0}" == "1" ]] || return 0
  local base="${REALM_AGENT_DEPLOY_ROLLBACK_BASE}"
  local rollback_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}"
  local name restore_failed="0"
  local managed_files_restored="1"
  local identity_rollback_safe="1"
  local identity_rollback_required="0"
  local journal=""
  local unit=""
  REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE="0"
  if [[ -z "${base}" || ! -d "${rollback_dir}" ]]; then
    err "Agent rollback 状态丢失，无法确认恢复成功"
    return 1
  fi

  err "Agent 更新未完成，正在恢复上一个可用版本..."
  if agent_service_account_rollback_required; then
    identity_rollback_required="1"
  fi
  if ! prepare_agent_units_for_restore; then
    restore_failed="1"
  fi
  for name in agent shared; do
    if ! restore_agent_switched_directory "${base}" "${rollback_dir}" "${name}"; then
      restore_failed="1"
    fi
  done
  if [[ "${REALM_AGENT_DEPLOY_REPLACE_VENV:-0}" == "1" ]]; then
    if ! restore_agent_switched_directory "${base}" "${rollback_dir}" venv; then
      restore_failed="1"
    fi
  fi
  if ! restore_agent_managed_directory "${base}/python" managed-python; then
    restore_failed="1"
  fi
  if ! restore_agent_managed_directory "${base}/bin" managed-bin; then
    restore_failed="1"
  fi

  if ! restore_agent_managed_files "${base}"; then
    restore_failed="1"
    managed_files_restored="0"
  fi
  if ! restore_agent_api_key_transaction; then
    restore_failed="1"
  fi
  if [[ "${REALM_AGENT_ROLLBACK_TLS_CERT_SNAPSHOTTED:-0}" == "1" ]]; then
    restore_agent_rollback_file \
      "${REALM_AGENT_ROLLBACK_TLS_CERT}" tls-cert \
      || restore_failed="1"
  fi
  if [[ "${REALM_AGENT_ROLLBACK_TLS_KEY_SNAPSHOTTED:-0}" == "1" ]]; then
    restore_agent_rollback_file \
      "${REALM_AGENT_ROLLBACK_TLS_KEY}" tls-key \
      || restore_failed="1"
  fi
  if ! restore_agent_tls_directory_metadata; then
    restore_failed="1"
  fi
  # Restore files before removing directories created solely for the new
  # deployment; TLS material may live inside /etc/letsencrypt or /etc/ssl/nexus.
  if ! restore_agent_sandbox_paths; then
    restore_failed="1"
  fi
  if ! restore_agent_sysctl_state; then
    restore_failed="1"
  fi
  if ! restore_agent_mptcp_limits_state; then
    restore_failed="1"
  fi
  if command_exists systemctl; then
    if ! rollback_systemctl "daemon-reload" daemon-reload; then
      restore_failed="1"
      identity_rollback_safe="0"
    fi
    for unit in "${AGENT_CUTOVER_UNITS[@]}"; do
      [[ -n "${unit}" ]] || continue
      systemctl reset-failed "${unit}" >/dev/null 2>&1 || true
    done
    if [[ "${identity_rollback_required}" == "1" ]]; then
      if [[ "${managed_files_restored}" != "1" ]] \
        || ! agent_units_inactive_for_identity_rollback; then
        identity_rollback_safe="0"
        restore_failed="1"
      fi
    fi
  elif [[ "${identity_rollback_required}" == "1" ]]; then
    identity_rollback_safe="0"
    restore_failed="1"
  fi
  if [[ "${identity_rollback_safe}" == "1" ]]; then
    if ! rollback_agent_service_account; then
      restore_failed="1"
    fi
  else
    err "Agent unit 未安全静止，保留 realm-agent 服务账户"
  fi
  if [[ "${restore_failed}" == "0" ]] && command_exists systemctl; then
    if [[ "${REALM_AGENT_RECOVERY_SERVICE_MODE:-0}" == "1" ]] \
      && ! notify_agent_recovery_ready; then
      restore_failed="1"
    fi
  fi
  if [[ "${restore_failed}" == "0" ]] && command_exists systemctl; then
    if ! restore_agent_unit_states; then
      restore_failed="1"
      if ! force_quiesce_agent_units_after_failed_restore; then
        err "恢复 unit 状态失败后无法重新静止全部 Agent runtime"
      fi
    fi
  fi
  if [[ "${restore_failed}" == "0" ]]; then
    if [[ -f "${rollback_dir}/state/base.directory-absent" \
      && -d "${base}" ]] \
      && ! rmdir "${base}" >/dev/null 2>&1; then
      if find "${base}" -mindepth 1 -maxdepth 1 -print -quit \
        | grep -q .; then
        err "rollback 后原本缺失的 Agent base 仍含残留：${base}"
        restore_failed="1"
      fi
    fi
  fi
  if [[ "${restore_failed}" == "0" ]]; then
    journal="$(agent_deploy_transaction_journal_path 2>/dev/null || true)"
    if [[ -n "${journal}" && ( -e "${journal}" || -L "${journal}" ) ]] \
      && { ! sync >/dev/null 2>&1 \
        || ! persist_agent_deploy_transaction_journal restored; }; then
      err "rollback 已恢复状态，但无法持久化 restored journal"
      restore_failed="1"
    fi
  fi
  if [[ "${restore_failed}" != "0" ]]; then
    err "部分回滚未完成，已保留恢复材料：${rollback_dir}"
    return 1
  fi
  if ! rm -rf "${rollback_dir}" >/dev/null 2>&1; then
    err "回滚已恢复状态，但无法删除恢复材料：${rollback_dir}"
    return 1
  fi
  if [[ -n "${journal}" && ( -e "${journal}" || -L "${journal}" ) ]] \
    && ! clear_agent_deploy_transaction_journal; then
    err "rollback 已恢复，但无法清理完成态 journal"
    return 1
  fi
  REALM_AGENT_DEPLOY_ROLLBACK_BASE=""
  REALM_AGENT_DEPLOY_ROLLBACK_DIR=""
  AGENT_DEPLOY_JOURNAL_STATE=""
  REALM_AGENT_DEPLOY_REPLACE_VENV="0"
  REALM_AGENT_ROLLBACK_TLS_CERT=""
  REALM_AGENT_ROLLBACK_TLS_KEY=""
  REALM_AGENT_ROLLBACK_TLS_CERT_SNAPSHOTTED="0"
  REALM_AGENT_ROLLBACK_TLS_KEY_SNAPSHOTTED="0"
  REALM_AGENT_TARGET_API_KEY_ADOPTED="0"
  REALM_AGENT_ADOPTED_API_KEY_VERSION=""
  AGENT_SERVICE_USER_CREATED_THIS_RUN="0"
  AGENT_SERVICE_GROUP_CREATED_THIS_RUN="0"
  AGENT_SERVICE_USER_MANAGED="0"
  AGENT_SERVICE_GROUP_MANAGED="0"
  return 0
}

commit_agent_deploy_rollback(){
  local rollback_dir="${REALM_AGENT_DEPLOY_ROLLBACK_DIR:-}"
  local journal=""
  local cleanup_failed="0"
  journal="$(agent_deploy_transaction_journal_path 2>/dev/null || true)"
  if [[ -n "${journal}" && ( -e "${journal}" || -L "${journal}" ) ]] \
    && { ! sync >/dev/null 2>&1 \
      || ! persist_agent_deploy_transaction_journal committed; }; then
    err "Agent commit journal 无法持久化"
    return 1
  fi
  if [[ -n "${rollback_dir}" && -d "${rollback_dir}" ]] \
    && ! rm -rf "${rollback_dir}" >/dev/null 2>&1; then
    err "Agent 已提交，但 rollback 材料将留待下次清理：${rollback_dir}"
    cleanup_failed="1"
  fi
  if [[ "${cleanup_failed}" == "0" \
    && -n "${journal}" && ( -e "${journal}" || -L "${journal}" ) ]] \
    && ! clear_agent_deploy_transaction_journal; then
    err "Agent 已提交，但完成态 journal 将留待下次清理"
  fi
  REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE="0"
  REALM_AGENT_DEPLOY_ROLLBACK_BASE=""
  REALM_AGENT_DEPLOY_ROLLBACK_DIR=""
  AGENT_DEPLOY_JOURNAL_STATE=""
  REALM_AGENT_DEPLOY_REPLACE_VENV="0"
  REALM_AGENT_ROLLBACK_TLS_CERT=""
  REALM_AGENT_ROLLBACK_TLS_KEY=""
  REALM_AGENT_ROLLBACK_TLS_CERT_SNAPSHOTTED="0"
  REALM_AGENT_ROLLBACK_TLS_KEY_SNAPSHOTTED="0"
  REALM_AGENT_TARGET_API_KEY_ADOPTED="0"
  REALM_AGENT_ADOPTED_API_KEY_VERSION=""
  REALM_AGENT_PENDING_TARGET_API_KEY=""
  REALM_AGENT_PENDING_TARGET_API_KEY_SET="0"
  REALM_AGENT_PENDING_TARGET_API_KEY_VERSION=""
  AGENT_SERVICE_USER_CREATED_THIS_RUN="0"
  AGENT_SERVICE_GROUP_CREATED_THIS_RUN="0"
}

verify_agent_stage_import(){
  local stage="${1:-}"
  local py="${2:-}"
  local host="${3:-127.0.0.1}"
  local transport="${4:-http}"
  local ssl_cert="${5:-}"
  local ssl_key="${6:-}"
  local insecure_non_loopback="${7:-0}"
  if [[ -z "${stage}" || ! -d "${stage}/agent" || ! -d "${stage}/shared" ]]; then
    err "Agent staging 源码不完整，拒绝切换"
    return 1
  fi
  if [[ -z "${py}" || ! -x "${py}" ]]; then
    err "Agent staging 缺少可执行 Python，拒绝切换"
    return 1
  fi
  if ! (
    cd "${stage}/agent" || exit 1
    export REALM_AGENT_HOST="${host}"
    export REALM_AGENT_TRANSPORT="${transport}"
    export REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK="${insecure_non_loopback}"
    if [[ "${transport}" == "https" ]]; then
      export REALM_AGENT_SSL_CERT="${ssl_cert}"
      export REALM_AGENT_SSL_KEY="${ssl_key}"
    else
      unset REALM_AGENT_SSL_CERT REALM_AGENT_SSL_KEY
    fi
    PYTHONPATH="${stage}" PYTHONDONTWRITEBYTECODE=1 \
      "${py}" -c "import agent.app.main"
  ); then
    err "Agent staging 主模块导入失败，拒绝切换"
    return 1
  fi
}

verify_agent_staged_revtunnel_unit(){
  local unit_path="${1:-}"
  local required=""
  [[ -n "${unit_path}" && -f "${unit_path}" && ! -L "${unit_path}" ]] || return 1
  for required in \
    'Environment="REMOTE_BIND=127.0.0.1"' \
    'Environment="LOCAL_HOST=127.0.0.1"' \
    'Environment="STRICT_HOST_KEY_CHECKING=yes"' \
    '  -o BatchMode=yes \' \
    '  -o ExitOnForwardFailure=yes \' \
    '  -o StrictHostKeyChecking=${STRICT_HOST_KEY_CHECKING} \' \
    '  -o UserKnownHostsFile=${KNOWN_HOSTS_FILE} \' \
    '  -R ${REMOTE_BIND}:${REMOTE_PORT}:${LOCAL_HOST}:${LOCAL_PORT} \'; do
    if ! grep -Fqx -- "${required}" "${unit_path}"; then
      err "Agent reverse tunnel unit 缺少安全约束：${required}"
      return 1
    fi
  done
  if grep -Eq \
    'StrictHostKeyChecking=(no|accept-new)|UserKnownHostsFile=/dev/null|ProxyCommand|LocalCommand' \
    "${unit_path}"; then
    err "Agent reverse tunnel unit 包含不安全 SSH 选项"
    return 1
  fi
}

verify_agent_staged_service_units(){
  local systemd_dir="${1:-}"
  local unit=""
  local unit_path=""
  for unit in \
    realm-agent-install-recovery.service \
    realm-agent.service \
    realm-agent-https.service \
    realm-agent-privileged.service \
    realm-agent-privileged.socket \
    realm-agent-revtunnel.service; do
    unit_path="${systemd_dir}/${unit}"
    if [[ -L "${unit_path}" || ! -f "${unit_path}" ]]; then
      err "更新包缺少可信 Agent systemd unit：${unit}"
      return 1
    fi
  done
  verify_agent_staged_revtunnel_unit \
    "${systemd_dir}/realm-agent-revtunnel.service"
}

atomic_update_agent(){
  # 将新版本先部署到 staging，成功后再整体替换，避免“更新不到位 / 半更新”
  local src_agent_dir="$1"
  local host="$2"
  local port="$3"
  local transport="${4:-http}"
  local ssl_cert="${5:-$(agent_config_dir)/certs/server.crt}"
  local ssl_key="${6:-$(agent_config_dir)/certs/server.key}"
  local tls_server_name="${7:-}"
  local tls_auto_generate="${8:-0}"
  local tls_verify_peer="${9:-${AGENT_INSTALL_TLS_VERIFY_PEER:-0}}"
  local tls_ca_cert="${10:-${AGENT_INSTALL_TLS_CA_CERT:-}}"
  local tls_cert_sha256="${11:-${AGENT_INSTALL_TLS_CERT_SHA256:-}}"
  local address_family="${12:-${AGENT_INSTALL_ADDRESS_FAMILY:-explicit}}"
  local insecure_non_loopback="${13:-${AGENT_INSTALL_ALLOW_INSECURE_NON_LOOPBACK:-0}}"
  local agent_host="${host}"
  local agent_port="${port}"
  local selected_service=""
  local opposite_service=""
  local systemd_dir=""
  local config_dir=""
  local realm_dir=""

  if ! insecure_non_loopback="$(
    normalize_tls_auto_generate "${insecure_non_loopback}"
  )"; then
    err "REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK 仅支持 0/1 或布尔值"
    return 1
  fi
  if ! validate_agent_bind_contract \
    "${agent_host}" "${agent_port}" "${transport}" \
    "${insecure_non_loopback}"; then
    return 1
  fi
  if ! address_family="$(normalize_agent_address_family "${address_family}")"; then
    err "Agent 地址族策略无效"
    return 1
  fi
  if [[ -z "${address_family}" ]]; then
    address_family="explicit"
  fi
  if ! validate_agent_dual_stack_bind_policy \
    "${agent_host}" "${address_family}"; then
    return 1
  fi
  if ! tls_verify_peer="$(normalize_tls_auto_generate "${tls_verify_peer}")"; then
    err "REALM_AGENT_TLS_VERIFY_PEER 仅支持 0/1 或布尔值"
    return 1
  fi
  if [[ "${transport}" == "https" ]]; then
    selected_service="realm-agent-https.service"
    opposite_service="realm-agent.service"
    if ! validate_agent_tls_path "${ssl_cert}" || ! validate_agent_tls_path "${ssl_key}"; then
      err "HTTPS 证书路径无效，拒绝更新"
      return 1
    fi
    if [[ "${tls_verify_peer}" == "1" \
      && ( -z "${tls_ca_cert}" || "${tls_auto_generate}" != "0" ) ]]; then
      err "HTTPS verify peer 需要显式 CA 且禁止自动生成自签证书"
      return 1
    fi
  else
    selected_service="realm-agent.service"
    opposite_service="realm-agent-https.service"
  fi
  systemd_dir="$(agent_systemd_dir)"
  config_dir="$(agent_config_dir)"
  realm_dir="$(realm_config_dir)"
  if ! preflight_agent_sandbox_paths; then
    return 1
  fi

  local base=""
  local stage=""
  local bak=""
  base="$(agent_base_dir)"
  bak="${REALM_AGENT_DEPLOY_ROLLBACK_DIR:-${base}/.bak.$(date +%s).$$}"
  local reuse_venv="${REALM_AGENT_REUSE_VENV:-0}"
  local force_venv_rebuild="${REALM_AGENT_FORCE_VENV_REBUILD:-0}"
  local stage_python=""
  local venv_attestation_stage=""
  local venv_attestation_pending=""
  local existing_venv_verified="0"
  local wheelhouse_dir=""
  local has_local_wheels="0"
  local venv_timeout
  local pip_timeout
  local python_bin="${REALM_AGENT_PYTHON_BIN:-python3}"
  venv_timeout="$(parse_nonneg_int "${REALM_AGENT_VENV_CREATE_TIMEOUT:-240}" "240")"
  pip_timeout="$(parse_nonneg_int "${REALM_AGENT_PIP_INSTALL_TIMEOUT:-900}" "900")"
  if (( venv_timeout < 30 )); then venv_timeout=30; fi
  if (( pip_timeout < 60 )); then pip_timeout=60; fi

  if ! linux_stage_copy_disk_admission "${src_agent_dir}" "${base}"; then
    return 1
  fi
  install -d -m 755 "${base}"
  stage="$(mktemp -d "${base}/.staging.XXXXXX")"
  register_cleanup_path "${stage}"
  chmod 700 "${stage}" >/dev/null 2>&1 || true

  info "准备更新包（staging）..."
  mkdir -p "${stage}/agent"
  # 用 rsync 强制覆盖 + 删除旧文件，保证“全量更新到最新”
  rsync -a --delete "${src_agent_dir%/}/" "${stage}/agent/"
  local src_shared_dir
  src_shared_dir="$(cd "${src_agent_dir}/.." && pwd)/shared"
  if [[ -d "${src_shared_dir}" ]]; then
    mkdir -p "${stage}/shared"
    rsync -a --delete "${src_shared_dir%/}/" "${stage}/shared/"
  else
    err "更新包缺少 shared/，拒绝切换到不完整 Agent"
    return 1
  fi
  if ! verify_agent_staged_service_units "${stage}/agent/systemd"; then
    return 1
  fi
  if ! prepare_agent_tls_material \
    "${transport}" "${ssl_cert}" "${ssl_key}" "${tls_server_name}" \
    "${agent_host}" "${stage}" "${tls_auto_generate}" \
    "${tls_verify_peer}" "${tls_ca_cert}" "${tls_cert_sha256}"; then
    return 1
  fi
  wheelhouse_dir="${stage}/agent/wheels"
  if wheelhouse_has_wheels "${wheelhouse_dir}"; then
    has_local_wheels="1"
    info "检测到离线依赖包：${wheelhouse_dir}"
  fi

  local req_target=""
  local new_req_sha=""
  local old_req_sha=""
  local req_sha_file="${config_dir}/requirements.sha256"
  req_target="$(select_agent_requirements_file "${stage}/agent" || true)"
  if [[ -z "${req_target}" ]]; then
    err "Agent 依赖文件缺失：必须提供 requirements.lock"
    return 1
  fi
  new_req_sha="$(compute_requirements_sha256 "${req_target}" || true)"
  if [[ -z "${new_req_sha}" ]]; then
    err "无法计算 Agent requirements.lock SHA256"
    return 1
  fi
  if [[ -f "${req_sha_file}" ]]; then
    old_req_sha="$(cat "${req_sha_file}" 2>/dev/null | tr -d '[:space:]' || true)"
  fi
  venv_attestation_stage="${stage}/venv-attestation.json"

  # 智能 venv 复用：hash 相同仍必须重新证明 lock/RECORD/ABI 等价。
  if [[ "${force_venv_rebuild}" == "1" ]]; then
    reuse_venv="0"
  fi
  if [[ "${reuse_venv}" != "1" && "${force_venv_rebuild}" != "1" \
    && -x "${base}/venv/bin/python" \
    && "${new_req_sha}" == "${old_req_sha}" ]]; then
    if verify_agent_venv_lock \
      "${base}/venv/bin/python" "${stage}" "${venv_attestation_stage}"; then
      info "$(basename "${req_target}") hash 相同且严格证明通过（sha256: ${new_req_sha:0:12}...），复用现有 venv"
      reuse_venv="1"
      existing_venv_verified="1"
    else
      info "requirements hash 相同但现有 venv 证明失败；继续 staging 重建"
    fi
  fi

  # 离线环境只允许复用严格证明等价的 venv；证明失败时若包内 wheelhouse
  # 可离线重建则继续 staging 重建，否则离线安装无法完成依赖安装。
  if [[ "${reuse_venv}" != "1" && "${force_venv_rebuild}" != "1" \
    && "${REALM_AGENT_AUTO_REUSE_VENV_WHEN_OFFLINE:-1}" == "1" ]]; then
    if [[ -x "${base}/venv/bin/python" ]]; then
      if ! pip_index_any_reachable; then
        if verify_agent_venv_lock \
          "${base}/venv/bin/python" "${stage}" "${venv_attestation_stage}"; then
          existing_venv_verified="1"
          if offline_wheelhouse_can_rebuild \
            "${stage}/agent" "${wheelhouse_dir}" "${has_local_wheels}" \
            "${base}/venv/bin/pip"; then
            info "检测到 pip 索引不可达，但本地 wheelhouse 可用；继续 staging 依赖安装"
          else
            if [[ "${has_local_wheels}" == "1" ]]; then
              info "pip 索引不可达且本地 wheelhouse 不可用；现有 venv 严格证明通过，允许代码更新"
            else
              info "pip 索引不可达且没有本地 wheelhouse；现有 venv 严格证明通过，允许代码更新"
            fi
            reuse_venv="1"
          fi
        else
          if offline_wheelhouse_can_rebuild \
            "${stage}/agent" "${wheelhouse_dir}" "${has_local_wheels}" \
            "${base}/venv/bin/pip"; then
            info "pip 索引不可达且现有 venv 不符合当前 lock；本地 wheelhouse 可离线重建，继续 staging 依赖安装"
          else
            err "pip 索引不可达且现有 venv 不符合当前 lock，且本地 wheelhouse 不可用；无法离线安装依赖"
            return 1
          fi
        fi
      fi
    fi
  fi

  if [[ "${reuse_venv}" != "1" ]]; then
    if ! linux_venv_rebuild_disk_admission "${base}"; then
      err "Agent venv rebuild disk admission failed"
      return 1
    fi
    if ! linux_venv_rebuild_admission; then
      err "Agent venv rebuild admission failed; installer does not create or enable swap"
      return 1
    fi
    info "创建虚拟环境（staging，超时 ${venv_timeout}s）..."
    if ! create_isolated_linux_agent_venv \
      "${python_bin}" "${stage}/venv" "${venv_timeout}" 0; then
      err "创建虚拟环境失败，尝试使用 --copies 重试一次..."
      rm -rf "${stage}/venv" || true
      if ! create_isolated_linux_agent_venv \
        "${python_bin}" "${stage}/venv" "${venv_timeout}" 1; then
        err "创建虚拟环境失败：请检查磁盘空间/系统 Python 后重试（可调 REALM_AGENT_VENV_CREATE_TIMEOUT）"
        exit 1
      fi
    fi
    if ! preflight_agent_venv_startup \
      "${stage}/venv/bin/python" "${stage}"; then
      err "新建 Agent venv 在执行 pip 前未通过隔离启动预检"
      exit 1
    fi
    if ! bootstrap_linux_venv_pip \
      "${stage}/venv/bin/python" "${stage}" "${venv_timeout}"; then
      exit 1
    fi
    if ! preflight_agent_venv_startup \
      "${stage}/venv/bin/python" "${stage}"; then
      err "Agent venv 在 pip 引导后未通过隔离启动预检"
      exit 1
    fi

    if [[ "${reuse_venv}" != "1" ]]; then
      local req_installed="0"
      local -a req_hash_args=(--require-hashes --no-deps)
      export PIP_DISABLE_PIP_VERSION_CHECK=1
      export PIP_ROOT_USER_ACTION=ignore
      if [[ "${REALM_AGENT_UPGRADE_PIP:-0}" == "1" ]]; then
        err "禁止安装器在线升级未锁定的 pip/wheel/setuptools"
        exit 1
      fi
      # 先尝试包内 wheelhouse；在线回退仍必须满足同一带哈希 lock。
      if [[ "${has_local_wheels}" == "1" ]]; then
        if ! wheelhouse_satisfies_requirements "${stage}/venv/bin/pip" "${req_target}" "${wheelhouse_dir}"; then
          err "本地离线包不完整（缺少 requirements 依赖），跳过离线包并回退在线索引（保持当前哈希策略）"
          has_local_wheels="0"
        fi
      fi
      if [[ "${has_local_wheels}" == "1" ]]; then
        info "安装依赖（staging，本地离线包，超时 ${pip_timeout}s）..."
        if pip_install_from_wheels "${stage}/venv/bin/pip" "${pip_timeout}" "安装依赖（staging，本地离线包）" \
          "${wheelhouse_dir}" "${req_hash_args[@]}" -r "${req_target}"; then
          req_installed="1"
        else
          err "本地离线包安装 requirements 失败，回退在线索引（保持当前哈希策略）"
        fi
      fi
      if [[ "${req_installed}" != "1" ]]; then
        info "安装依赖（staging，超时 ${pip_timeout}s）..."
        if pip_install_with_fallback "${stage}/venv/bin/pip" "${pip_timeout}" "安装依赖（staging）" \
          "${req_hash_args[@]}" -r "${req_target}"; then
          req_installed="1"
        else
          err "requirements.lock 哈希校验安装失败，拒绝无哈希重试"
          exit 1
        fi
      fi
      if ! repair_venv_script_shebangs \
        "${stage}/venv" "${stage}/venv" "${stage}/venv"; then
        err "新建 Agent venv 的历史 console script 无法安全补证"
        exit 1
      fi
      if ! verify_agent_venv_lock \
        "${stage}/venv/bin/python" "${stage}" "${venv_attestation_stage}"; then
        err "新建 Agent venv 未通过严格 lock/RECORD/ABI 校验"
        exit 1
      fi
    fi
  fi

  if [[ "${reuse_venv}" == "1" ]]; then
    if ! probe_existing_agent_venv; then
      err "现有 Agent venv 未通过 Python 3.9+ 与核心依赖检查，拒绝复用"
      return 1
    fi
    if [[ "${existing_venv_verified}" != "1" ]] \
      && ! verify_agent_venv_lock \
        "${base}/venv/bin/python" "${stage}" "${venv_attestation_stage}"; then
      err "显式复用的 Agent venv 未通过严格 lock/RECORD/ABI 校验"
      return 1
    fi
    existing_venv_verified="1"
    stage_python="${base}/venv/bin/python"
    info "复用已严格证明等价的现有 venv，仅更新 Agent 代码"
  else
    stage_python="${stage}/venv/bin/python"
  fi
  if [[ ! -s "${venv_attestation_stage}" ]]; then
    err "Agent venv 证明缺失，拒绝进入切换事务"
    return 1
  fi
  if ! prepare_agent_systemd_sandbox_compatibility \
    "${stage}/agent/systemd"; then
    return 1
  fi
  if ! verify_agent_stage_import \
    "${stage}" "${stage_python}" "${agent_host}" "${transport}" \
    "${ssl_cert}" "${ssl_key}" "${insecure_non_loopback}"; then
    return 1
  fi

  local replace_venv="1"
  if [[ "${reuse_venv}" == "1" ]]; then
    replace_venv="0"
  fi
  if ! prepare_agent_recovery_support_for_transaction \
    "${stage}" "${base}" "${ssl_cert}" "${ssl_key}"; then
    return 1
  fi
  if [[ "${REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE:-0}" == "1" ]]; then
    if [[ "${transport}" == "https" ]] \
      && ! snapshot_agent_tls_paths_for_transaction \
        "${ssl_cert}" "${ssl_key}"; then
      return 1
    fi
    REALM_AGENT_DEPLOY_REPLACE_VENV="${replace_venv}"
    if ! persist_agent_deploy_transaction_journal prepared; then
      err "无法把 venv 切换决策绑定到 rollback journal"
      return 1
    fi
    bak="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}"
  else
    if ! begin_root_agent_install_transaction \
      "${base}" "${ssl_cert}" "${ssl_key}"; then
      return 1
    fi
    REALM_AGENT_DEPLOY_REPLACE_VENV="${replace_venv}"
    persist_agent_deploy_transaction_journal prepared || return 1
    bak="${REALM_AGENT_DEPLOY_ROLLBACK_DIR}"
  fi
  if ! prepare_agent_sandbox_paths; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  if ! adopt_join_target_api_key_after_snapshot 0 0; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  if ! install_agent_managed_prerequisites; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  if ! ensure_agent_service_account \
    || ! prepare_agent_config_boundary \
    || ! write_agent_service_account_marker; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  if [[ "${transport}" == "https" ]] \
    && ! install_prepared_agent_tls_material \
      "${ssl_cert}" "${ssl_key}" "${tls_server_name}" "${agent_host}" \
      "${tls_verify_peer}" "${tls_ca_cert}" "${tls_cert_sha256}"; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  if ! ensure_agent_api_key_for_activation 0 0; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  # jq filter
  mkdir -p "${realm_dir}"
  if [[ -f "${stage}/agent/pool_to_run.jq" ]]; then
    cp -a "${stage}/agent/pool_to_run.jq" "${realm_dir}/pool_to_run.jq"
  fi

  # Push-report 配置（Agent -> Panel）
  # 通过面板一键安装时，会注入这些环境变量；这里持久化到文件供 systemd 读取。
  mkdir -p "${config_dir}"
  local existing_agent_env="${config_dir}/agent.env"
  local existing_nft_bin=""
  local existing_iptables_bin=""
  local existing_sidecar_uds=""
  local existing_sidecar_host=""
  local existing_sidecar_port=""
  local existing_sidecar_timeout_ms=""
  local existing_sidecar_cmd=""
  local existing_mptcp_feature_defaults_version=""
  local existing_nats_url=""
  local existing_agent_v2_enable_jetstream=""
  local existing_pool_version_state_file=""
  local existing_outer_tcp_mss_ipv4=""
  local existing_outer_tcp_mss_ipv6=""
  local existing_panel_url=""
  local existing_node_id=""
  local allow_shell=""
  local enable_custom_nginx_templates=""
  existing_nft_bin="$(read_env_value "${existing_agent_env}" "REALM_NFT_BIN" || true)"
  existing_iptables_bin="$(read_env_value "${existing_agent_env}" "REALM_IPTABLES_BIN" || true)"
  existing_sidecar_uds="$(read_env_value "${existing_agent_env}" "REALM_MPTCP_SIDECAR_UDS" || true)"
  existing_sidecar_host="$(read_env_value "${existing_agent_env}" "REALM_MPTCP_SIDECAR_HOST" || true)"
  existing_sidecar_port="$(read_env_value "${existing_agent_env}" "REALM_MPTCP_SIDECAR_PORT" || true)"
  existing_sidecar_timeout_ms="$(read_env_value "${existing_agent_env}" "REALM_MPTCP_SIDECAR_TIMEOUT_MS" || true)"
  existing_sidecar_cmd="$(read_mptcp_sidecar_cmd_value "${existing_agent_env}" || true)"
  existing_mptcp_feature_defaults_version="$(read_env_value "${existing_agent_env}" "REALM_MPTCP_FEATURE_DEFAULTS_VERSION" || true)"
  existing_nats_url="$(read_env_value "${existing_agent_env}" "REALM_NATS_URL" || true)"
  existing_agent_v2_enable_jetstream="$(read_env_value "${existing_agent_env}" "REALM_AGENT_V2_ENABLE_JETSTREAM" || true)"
  existing_pool_version_state_file="$(read_env_value "${existing_agent_env}" "REALM_AGENT_POOL_VERSION_STATE_FILE" || true)"
  existing_outer_tcp_mss_ipv4="$(read_env_value "${existing_agent_env}" "REALM_INTRANET_OUTER_TCP_MSS_IPV4" || true)"
  existing_outer_tcp_mss_ipv6="$(read_env_value "${existing_agent_env}" "REALM_INTRANET_OUTER_TCP_MSS_IPV6" || true)"
  existing_panel_url="$(read_env_value "${config_dir}/panel.env" "REALM_PANEL_URL" || true)"
  existing_node_id="$(read_env_value "${existing_agent_env}" "REALM_NODE_ID" || true)"

  local nft_bin="${REALM_NFT_BIN:-${existing_nft_bin}}"
  local iptables_bin="${REALM_IPTABLES_BIN:-${existing_iptables_bin}}"
  local mptcp_enabled=""
  local mptcp_sidecar_uds="${REALM_MPTCP_SIDECAR_UDS:-${existing_sidecar_uds}}"
  local mptcp_sidecar_host="${REALM_MPTCP_SIDECAR_HOST:-${existing_sidecar_host}}"
  local mptcp_sidecar_port="${REALM_MPTCP_SIDECAR_PORT:-${existing_sidecar_port}}"
  local mptcp_sidecar_timeout_ms="${REALM_MPTCP_SIDECAR_TIMEOUT_MS:-${existing_sidecar_timeout_ms}}"
  local mptcp_sidecar_cmd="${REALM_MPTCP_SIDECAR_CMD:-${existing_sidecar_cmd}}"
  local realm_node_id="${REALM_NODE_ID:-${REALM_AGENT_ID:-${existing_node_id}}}"
  local panel_url_for_nats="${REALM_PANEL_URL:-${existing_panel_url}}"
  local realm_nats_url
  realm_nats_url="$(resolve_agent_nats_url "${REALM_NATS_URL:-}" "${existing_nats_url}" "${panel_url_for_nats}")"
  local agent_v2_wal_root=""
  agent_v2_wal_root="$(resolve_agent_v2_wal_root)" || return 1
  local agent_v2_enable_jetstream="${REALM_AGENT_V2_ENABLE_JETSTREAM:-${existing_agent_v2_enable_jetstream:-1}}"
  local pool_version_state_file="${REALM_AGENT_POOL_VERSION_STATE_FILE:-${existing_pool_version_state_file:-${config_dir}/pool_apply_state.json}}"
  local outer_tcp_mss_ipv4=""
  local outer_tcp_mss_ipv6=""
  local npp_hub_enabled=""
  local npp_hub_apply_enabled=""
  local mptcp_feature_defaults_version="1"
  local npp_feature_defaults_version="2"
  local installed_npp_feature_defaults_version=""
  local npp_decoy_enabled=""
  local npp_endpoint_failover_enabled=""
  local npp_traffic_shape_enabled=""
  local npp_stealth_path_enabled=""
  local npp_mux_randomize_connections=""
  local npp_route_open_enabled=""
  local update_tmp_parent=""
  local update_log_dir=""
  local update_tmp_retention_days=""
  local update_log_retention_days=""
  local update_curl_connect_timeout=""
  local update_curl_max_time=""
  local update_curl_retry=""
  local update_curl_retry_delay=""
  local update_curl_speed_time=""
  local update_curl_speed_limit=""
  local pip_install_timeout=""
  local pip_disable_fallback=""
  local pip_enable_legacy_resolver_fallback=""
  local pip_force_legacy_resolver=""
  local pip_index_url=""
  local pip_extra_index_url=""
  local pip_fallback_indexes=""
  local pip_trusted_host=""
  installed_npp_feature_defaults_version="$(read_env_value "${existing_agent_env}" "REALM_NPP_FEATURE_DEFAULTS_VERSION" || true)"
  mptcp_enabled="$(resolve_migrated_default_env_value "${existing_agent_env}" "REALM_MPTCP_ENABLED" "${REALM_MPTCP_ENABLED:-}" "${existing_mptcp_feature_defaults_version}" "${mptcp_feature_defaults_version}" "1")"
  npp_hub_enabled="$(resolve_migrated_default_env_value "${existing_agent_env}" "REALM_NPP_HUB_ENABLED" "${REALM_NPP_HUB_ENABLED:-}" "${installed_npp_feature_defaults_version}" "${npp_feature_defaults_version}" "1")"
  npp_hub_apply_enabled="$(resolve_migrated_default_env_value "${existing_agent_env}" "REALM_NPP_HUB_APPLY_ENABLED" "${REALM_NPP_HUB_APPLY_ENABLED:-}" "${installed_npp_feature_defaults_version}" "${npp_feature_defaults_version}" "1")"
  npp_decoy_enabled="$(resolve_preserved_env_value "${existing_agent_env}" "REALM_NPP_DECOY_ENABLED" "${REALM_NPP_DECOY_ENABLED:-}" "1")"
  npp_endpoint_failover_enabled="$(resolve_migrated_default_env_value "${existing_agent_env}" "REALM_NPP_ENDPOINT_FAILOVER_ENABLED" "${REALM_NPP_ENDPOINT_FAILOVER_ENABLED:-}" "${installed_npp_feature_defaults_version}" "${npp_feature_defaults_version}" "1")"
  npp_traffic_shape_enabled="$(resolve_preserved_env_value "${existing_agent_env}" "REALM_NPP_TRAFFIC_SHAPE_ENABLED" "${REALM_NPP_TRAFFIC_SHAPE_ENABLED:-}" "1")"
  npp_stealth_path_enabled="$(resolve_preserved_env_value "${existing_agent_env}" "REALM_NPP_STEALTH_PATH_ENABLED" "${REALM_NPP_STEALTH_PATH_ENABLED:-}" "1")"
  npp_mux_randomize_connections="$(resolve_migrated_default_env_value "${existing_agent_env}" "REALM_NPP_MUX_RANDOMIZE_CONNECTIONS" "${REALM_NPP_MUX_RANDOMIZE_CONNECTIONS:-}" "${installed_npp_feature_defaults_version}" "${npp_feature_defaults_version}" "1")"
  npp_route_open_enabled="$(resolve_migrated_default_env_value "${existing_agent_env}" "REALM_NPP_ROUTE_OPEN_ENABLED" "${REALM_NPP_ROUTE_OPEN_ENABLED:-}" "${installed_npp_feature_defaults_version}" "${npp_feature_defaults_version}" "1")"
  update_tmp_parent="$(resolve_preserved_env_value "${existing_agent_env}" "REALM_AGENT_UPDATE_TMP_PARENT" "${REALM_AGENT_UPDATE_TMP_PARENT:-}" "")"
  update_log_dir="$(resolve_preserved_env_value "${existing_agent_env}" "REALM_AGENT_UPDATE_LOG_DIR" "${REALM_AGENT_UPDATE_LOG_DIR:-}" "")"
  update_tmp_retention_days="$(resolve_preserved_uint_env_value "${existing_agent_env}" "REALM_AGENT_UPDATE_TMP_RETENTION_DAYS" "${REALM_AGENT_UPDATE_TMP_RETENTION_DAYS:-}" 1 0 3650)"
  update_log_retention_days="$(resolve_preserved_uint_env_value "${existing_agent_env}" "REALM_AGENT_UPDATE_LOG_RETENTION_DAYS" "${REALM_AGENT_UPDATE_LOG_RETENTION_DAYS:-}" 7 0 3650)"
  update_curl_connect_timeout="$(resolve_preserved_uint_env_value "${existing_agent_env}" "REALM_AGENT_UPDATE_CURL_CONNECT_TIMEOUT" "${REALM_AGENT_UPDATE_CURL_CONNECT_TIMEOUT:-}" 20 1 300)"
  update_curl_max_time="$(resolve_preserved_uint_env_value "${existing_agent_env}" "REALM_AGENT_UPDATE_CURL_MAX_TIME" "${REALM_AGENT_UPDATE_CURL_MAX_TIME:-}" 300 1 3600)"
  update_curl_retry="$(resolve_preserved_uint_env_value "${existing_agent_env}" "REALM_AGENT_UPDATE_CURL_RETRY" "${REALM_AGENT_UPDATE_CURL_RETRY:-}" 1 0 8)"
  update_curl_retry_delay="$(resolve_preserved_uint_env_value "${existing_agent_env}" "REALM_AGENT_UPDATE_CURL_RETRY_DELAY" "${REALM_AGENT_UPDATE_CURL_RETRY_DELAY:-}" 3 0 60)"
  update_curl_speed_time="$(resolve_preserved_uint_env_value "${existing_agent_env}" "REALM_AGENT_UPDATE_CURL_SPEED_TIME" "${REALM_AGENT_UPDATE_CURL_SPEED_TIME:-}" 20 1 300)"
  update_curl_speed_limit="$(resolve_preserved_uint_env_value "${existing_agent_env}" "REALM_AGENT_UPDATE_CURL_SPEED_LIMIT" "${REALM_AGENT_UPDATE_CURL_SPEED_LIMIT:-}" 32768 1 104857600)"
  pip_install_timeout="$(resolve_preserved_uint_env_value "${existing_agent_env}" "REALM_AGENT_PIP_INSTALL_TIMEOUT" "${REALM_AGENT_PIP_INSTALL_TIMEOUT:-}" 900 60 3600)"
  pip_disable_fallback="$(resolve_preserved_bool_env_value "${existing_agent_env}" "REALM_AGENT_PIP_DISABLE_FALLBACK" "${REALM_AGENT_PIP_DISABLE_FALLBACK:-}" 0)"
  pip_enable_legacy_resolver_fallback="$(resolve_preserved_bool_env_value "${existing_agent_env}" "REALM_AGENT_PIP_ENABLE_LEGACY_RESOLVER_FALLBACK" "${REALM_AGENT_PIP_ENABLE_LEGACY_RESOLVER_FALLBACK:-}" 1)"
  pip_force_legacy_resolver="$(resolve_preserved_bool_env_value "${existing_agent_env}" "REALM_AGENT_PIP_FORCE_LEGACY_RESOLVER" "${REALM_AGENT_PIP_FORCE_LEGACY_RESOLVER:-}" 0)"
  pip_index_url="$(resolve_preserved_update_text_env_value "${existing_agent_env}" "REALM_AGENT_PIP_INDEX_URL" "${REALM_AGENT_PIP_INDEX_URL:-}")" || return 1
  pip_extra_index_url="$(resolve_preserved_update_text_env_value "${existing_agent_env}" "REALM_AGENT_PIP_EXTRA_INDEX_URL" "${REALM_AGENT_PIP_EXTRA_INDEX_URL:-}")" || return 1
  pip_fallback_indexes="$(resolve_preserved_update_text_env_value "${existing_agent_env}" "REALM_AGENT_PIP_FALLBACK_INDEXES" "${REALM_AGENT_PIP_FALLBACK_INDEXES:-}")" || return 1
  pip_trusted_host="$(resolve_preserved_update_text_env_value "${existing_agent_env}" "REALM_AGENT_PIP_TRUSTED_HOST" "${REALM_AGENT_PIP_TRUSTED_HOST:-}")" || return 1
  outer_tcp_mss_ipv4="$(
    resolve_preserved_outer_tcp_mss \
      "${existing_agent_env}" "REALM_INTRANET_OUTER_TCP_MSS_IPV4" \
      "${REALM_INTRANET_OUTER_TCP_MSS_IPV4:-${existing_outer_tcp_mss_ipv4}}" \
      536 65495
  )" || return 1
  outer_tcp_mss_ipv6="$(
    resolve_preserved_outer_tcp_mss \
      "${existing_agent_env}" "REALM_INTRANET_OUTER_TCP_MSS_IPV6" \
      "${REALM_INTRANET_OUTER_TCP_MSS_IPV6:-${existing_outer_tcp_mss_ipv6}}" \
      1220 65475
  )" || return 1
  allow_shell="$(resolve_preserved_env_value "${existing_agent_env}" "REALM_AGENT_ALLOW_SHELL" "${REALM_AGENT_ALLOW_SHELL:-}" "0")"
  case "${allow_shell}" in
    1|true|TRUE|yes|YES|on|ON) allow_shell="1" ;;
    *) allow_shell="0" ;;
  esac
  enable_custom_nginx_templates="$(
    resolve_preserved_env_value \
      "${existing_agent_env}" \
      "REALM_AGENT_ENABLE_CUSTOM_NGINX_TEMPLATES" \
      "${REALM_AGENT_ENABLE_CUSTOM_NGINX_TEMPLATES:-}" \
      "1"
  )"
  case "${enable_custom_nginx_templates}" in
    1|true|TRUE|yes|YES|on|ON) enable_custom_nginx_templates="1" ;;
    *) enable_custom_nginx_templates="0" ;;
  esac

  if [[ -n "${update_tmp_parent}" && ( "${update_tmp_parent}" != /* || -L "${update_tmp_parent}" || ! -d "${update_tmp_parent}" ) ]]; then
    warn "REALM_AGENT_UPDATE_TMP_PARENT 不是可用的真实目录，已恢复为系统临时目录"
    update_tmp_parent=""
  fi
  if [[ -n "${update_log_dir}" && ( "${update_log_dir}" != /* || -L "${update_log_dir}" || ! -d "${update_log_dir}" ) ]]; then
    warn "REALM_AGENT_UPDATE_LOG_DIR 不是可用的真实目录，已恢复为默认日志目录"
    update_log_dir=""
  fi
  if ! valid_agent_pool_version_state_file "${pool_version_state_file}"; then
    err "REALM_AGENT_POOL_VERSION_STATE_FILE 不是安全绝对路径"
    return 1
  fi

  if [[ "${mptcp_enabled}" == "1" || "${mptcp_enabled}" == "true" || "${mptcp_enabled}" == "TRUE" ]]; then
    mptcp_enabled="1"
  else
    mptcp_enabled="0"
  fi
  if [[ -z "${mptcp_sidecar_uds}" ]]; then
    mptcp_sidecar_uds="/var/run/realm-mptcp-sidecar.sock"
  fi
  if [[ -z "${mptcp_sidecar_host}" ]]; then
    mptcp_sidecar_host="127.0.0.1"
  fi
  if [[ ! "${mptcp_sidecar_port}" =~ ^[0-9]+$ ]] || (( mptcp_sidecar_port < 1 || mptcp_sidecar_port > 65535 )); then
    mptcp_sidecar_port="29443"
  fi
  if [[ ! "${mptcp_sidecar_timeout_ms}" =~ ^[0-9]+$ ]] || (( mptcp_sidecar_timeout_ms < 100 || mptcp_sidecar_timeout_ms > 20000 )); then
    mptcp_sidecar_timeout_ms="1800"
  fi
  if [[ -z "${mptcp_sidecar_cmd}" ]]; then
    mptcp_sidecar_cmd="$(resolve_mptcp_sidecar_cmd)"
  fi
  if [[ -z "${mptcp_sidecar_cmd}" && -f "${stage}/agent/app/services/mptcp_sidecar_server.py" ]]; then
    mptcp_sidecar_cmd="${base}/venv/bin/python -m agent.app.services.mptcp_sidecar_server"
  fi
  if [[ -n "${mptcp_sidecar_cmd}" ]] \
    && ! validate_mptcp_sidecar_cmd "${mptcp_sidecar_cmd}"; then
    err "REALM_MPTCP_SIDECAR_CMD 含未引用 shell 元字符或无效 argv，拒绝安装"
    return 1
  fi

  local panel_env_url panel_env_agent_id panel_env_heartbeat
  panel_env_url="$(strip_env_value "${REALM_PANEL_URL:-}")"
  panel_env_agent_id="$(strip_env_value "${REALM_AGENT_ID:-}")"
  panel_env_heartbeat="$(strip_env_value "${REALM_AGENT_HEARTBEAT_INTERVAL:-3}")"
  if [[ -n "${panel_env_url}" && -n "${panel_env_agent_id}" ]]; then
    {
      printf 'REALM_PANEL_URL=%s\n' "${panel_env_url}"
      printf 'REALM_AGENT_ID=%s\n' "${panel_env_agent_id}"
      printf 'REALM_AGENT_HEARTBEAT_INTERVAL=%s\n' "${panel_env_heartbeat}"
    } > "${config_dir}/panel.env"
  fi
  secure_agent_secret_file "${config_dir}/panel.env" || return 1
  {
    printf 'REALM_AGENT_HOST=%s\n' "$(strip_env_value "${agent_host}")"
    printf 'REALM_AGENT_PORT=%s\n' "$(strip_env_value "${agent_port}")"
    printf 'REALM_AGENT_TRANSPORT=%s\n' "$(strip_env_value "${transport}")"
    printf 'REALM_AGENT_SSL_CERT=%s\n' "$(strip_env_value "${ssl_cert}")"
    printf 'REALM_AGENT_SSL_KEY=%s\n' "$(strip_env_value "${ssl_key}")"
    printf 'REALM_AGENT_TLS_SERVER_NAME=%s\n' "$(strip_env_value "${tls_server_name}")"
    printf 'REALM_AGENT_TLS_AUTO_GENERATE=%s\n' "$(strip_env_value "${tls_auto_generate}")"
    printf 'REALM_AGENT_TLS_VERIFY_PEER=%s\n' "$(strip_env_value "${tls_verify_peer}")"
    printf 'REALM_AGENT_TLS_CA_CERT=%s\n' "$(strip_env_value "${tls_ca_cert}")"
    printf 'REALM_AGENT_TLS_CERT_SHA256=%s\n' "$(strip_env_value "${tls_cert_sha256}")"
    printf 'REALM_AGENT_ADDRESS_FAMILY=%s\n' "$(strip_env_value "${address_family}")"
    printf 'REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK=%s\n' \
      "$(strip_env_value "${insecure_non_loopback}")"
    printf 'REALM_AGENT_ALLOW_SHELL=%s\n' "$(strip_env_value "${allow_shell}")"
    printf 'REALM_AGENT_ENABLE_CUSTOM_NGINX_TEMPLATES=%s\n' \
      "$(strip_env_value "${enable_custom_nginx_templates}")"
    printf 'REALM_NFT_BIN=%s\n' "$(strip_env_value "${nft_bin}")"
    printf 'REALM_IPTABLES_BIN=%s\n' "$(strip_env_value "${iptables_bin}")"
    printf 'REALM_MPTCP_ENABLED=%s\n' "$(strip_env_value "${mptcp_enabled}")"
    printf 'REALM_MPTCP_SIDECAR_UDS=%s\n' "$(strip_env_value "${mptcp_sidecar_uds}")"
    printf 'REALM_MPTCP_SIDECAR_HOST=%s\n' "$(strip_env_value "${mptcp_sidecar_host}")"
    printf 'REALM_MPTCP_SIDECAR_PORT=%s\n' "$(strip_env_value "${mptcp_sidecar_port}")"
    printf 'REALM_MPTCP_SIDECAR_TIMEOUT_MS=%s\n' "$(strip_env_value "${mptcp_sidecar_timeout_ms}")"
    printf 'REALM_MPTCP_SIDECAR_CMD=%s\n' \
      "$(encode_literal_env_value "$(strip_env_value "${mptcp_sidecar_cmd}")")"
    printf 'REALM_MPTCP_FEATURE_DEFAULTS_VERSION=%s\n' "$(strip_env_value "${mptcp_feature_defaults_version}")"
    printf 'REALM_NODE_ID=%s\n' "$(strip_env_value "${realm_node_id}")"
    printf 'REALM_NATS_URL=%s\n' "$(strip_env_value "${realm_nats_url}")"
    printf 'REALM_AGENT_V2_WAL_ROOT=%s\n' "$(strip_env_value "${agent_v2_wal_root}")"
    printf 'REALM_AGENT_V2_ENABLE_JETSTREAM=%s\n' "$(strip_env_value "${agent_v2_enable_jetstream}")"
    printf 'REALM_AGENT_POOL_VERSION_STATE_FILE=%s\n' \
      "$(strip_env_value "${pool_version_state_file}")"
    printf 'REALM_TUNNEL_RUNTIME_MODE=active\n'
    printf 'REALM_PANEL_REPORTER_MODE=active\n'
    printf 'REALM_V2_CONTROL_MODE=active\n'
    printf 'REALM_AGENT_UPDATE_TMP_PARENT="%s"\n' "$(strip_env_value "${update_tmp_parent}")"
    printf 'REALM_AGENT_UPDATE_LOG_DIR="%s"\n' "$(strip_env_value "${update_log_dir}")"
    printf 'REALM_AGENT_UPDATE_TMP_RETENTION_DAYS=%s\n' "$(strip_env_value "${update_tmp_retention_days}")"
    printf 'REALM_AGENT_UPDATE_LOG_RETENTION_DAYS=%s\n' "$(strip_env_value "${update_log_retention_days}")"
    printf 'REALM_AGENT_UPDATE_CURL_CONNECT_TIMEOUT=%s\n' "$(strip_env_value "${update_curl_connect_timeout}")"
    printf 'REALM_AGENT_UPDATE_CURL_MAX_TIME=%s\n' "$(strip_env_value "${update_curl_max_time}")"
    printf 'REALM_AGENT_UPDATE_CURL_RETRY=%s\n' "$(strip_env_value "${update_curl_retry}")"
    printf 'REALM_AGENT_UPDATE_CURL_RETRY_DELAY=%s\n' "$(strip_env_value "${update_curl_retry_delay}")"
    printf 'REALM_AGENT_UPDATE_CURL_SPEED_TIME=%s\n' "$(strip_env_value "${update_curl_speed_time}")"
    printf 'REALM_AGENT_UPDATE_CURL_SPEED_LIMIT=%s\n' "$(strip_env_value "${update_curl_speed_limit}")"
    printf 'REALM_AGENT_PIP_INSTALL_TIMEOUT=%s\n' "$(strip_env_value "${pip_install_timeout}")"
    printf 'REALM_AGENT_PIP_DISABLE_FALLBACK=%s\n' "$(strip_env_value "${pip_disable_fallback}")"
    printf 'REALM_AGENT_PIP_ENABLE_LEGACY_RESOLVER_FALLBACK=%s\n' "$(strip_env_value "${pip_enable_legacy_resolver_fallback}")"
    printf 'REALM_AGENT_PIP_FORCE_LEGACY_RESOLVER=%s\n' "$(strip_env_value "${pip_force_legacy_resolver}")"
    printf 'REALM_AGENT_PIP_INDEX_URL="%s"\n' "$(strip_env_value "${pip_index_url}")"
    printf 'REALM_AGENT_PIP_EXTRA_INDEX_URL="%s"\n' "$(strip_env_value "${pip_extra_index_url}")"
    printf 'REALM_AGENT_PIP_FALLBACK_INDEXES="%s"\n' "$(strip_env_value "${pip_fallback_indexes}")"
    printf 'REALM_AGENT_PIP_TRUSTED_HOST="%s"\n' "$(strip_env_value "${pip_trusted_host}")"
    printf 'REALM_INTRANET_OUTER_TCP_MSS_IPV4=%s\n' \
      "$(strip_env_value "${outer_tcp_mss_ipv4}")"
    printf 'REALM_INTRANET_OUTER_TCP_MSS_IPV6=%s\n' \
      "$(strip_env_value "${outer_tcp_mss_ipv6}")"
    printf 'REALM_NPP_FEATURE_DEFAULTS_VERSION=%s\n' "$(strip_env_value "${npp_feature_defaults_version}")"
    printf 'REALM_NPP_HUB_ENABLED=%s\n' "$(strip_env_value "${npp_hub_enabled}")"
    printf 'REALM_NPP_HUB_APPLY_ENABLED=%s\n' "$(strip_env_value "${npp_hub_apply_enabled}")"
    printf 'REALM_NPP_DECOY_ENABLED=%s\n' "$(strip_env_value "${npp_decoy_enabled}")"
    printf 'REALM_NPP_ENDPOINT_FAILOVER_ENABLED=%s\n' "$(strip_env_value "${npp_endpoint_failover_enabled}")"
    printf 'REALM_NPP_TRAFFIC_SHAPE_ENABLED=%s\n' "$(strip_env_value "${npp_traffic_shape_enabled}")"
    printf 'REALM_NPP_STEALTH_PATH_ENABLED=%s\n' "$(strip_env_value "${npp_stealth_path_enabled}")"
    printf 'REALM_NPP_MUX_RANDOMIZE_CONNECTIONS=%s\n' "$(strip_env_value "${npp_mux_randomize_connections}")"
    printf 'REALM_NPP_ROUTE_OPEN_ENABLED=%s\n' "$(strip_env_value "${npp_route_open_enabled}")"
  } > "${config_dir}/agent.env"
  secure_agent_secret_file "${config_dir}/agent.env" || return 1
  write_agent_gateway_env \
    "${agent_host}" "${agent_port}" "${transport}" \
    "${ssl_cert}" "${ssl_key}" "${tls_server_name}" \
    "${tls_verify_peer}" "${tls_ca_cert}" "${tls_cert_sha256}" \
    "${insecure_non_loopback}" || return 1
  if [[ "${mptcp_enabled}" == "1" && -z "${mptcp_sidecar_cmd}" ]]; then
    info "REALM_MPTCP_ENABLED=1 但未探测到 sidecar 命令，可手动设置 REALM_MPTCP_SIDECAR_CMD"
  fi

  if ! preflight_active_managed_realm_config; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  if ! stop_agent_runtime_stack_for_cutover; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  info "写入/更新 Agent systemd 服务..."
  install -d -m 755 "${systemd_dir}"
  install -m 0644 \
    "${stage}/agent/systemd/realm-agent.service" \
    "${systemd_dir}/realm-agent.service"
  install -m 0644 \
    "${stage}/agent/systemd/realm-agent-https.service" \
    "${systemd_dir}/realm-agent-https.service"
  install -m 0644 \
    "${stage}/agent/systemd/realm-agent-revtunnel.service" \
    "${systemd_dir}/realm-agent-revtunnel.service"
  if ! systemctl daemon-reload >/dev/null 2>&1; then
    err "写入 Agent unit 后 systemctl daemon-reload 失败"
    restore_agent_deploy_rollback || true
    return 1
  fi

  info "切换到最新版本（staging + rename，可失败回滚）..."
  if ! activate_agent_stage "${stage}" "${base}" "${bak}" "${replace_venv}"; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  if [[ "${replace_venv}" == "1" ]]; then
    local final_venv_attestation="${stage}/venv-attestation.final.json"
    if ! verify_agent_venv_lock \
      "${base}/venv/bin/python" "${base}" "${final_venv_attestation}"; then
      err "最终路径 Agent venv 未通过 shebang/RECORD 重绑定后的严格证明"
      restore_agent_deploy_rollback || true
      return 1
    fi
    venv_attestation_stage="${final_venv_attestation}"
  fi
  venv_attestation_pending="${bak}/state/venv-attestation.pending.json"
  if ! install -m 0600 \
    "${venv_attestation_stage}" "${venv_attestation_pending}"; then
    err "无法把 Agent venv 证明绑定到 rollback transaction"
    restore_agent_deploy_rollback || true
    return 1
  fi
  chmod 755 "${base}/agent/start.sh" >/dev/null 2>&1 || true
  rm -rf "${stage}" || true

  # 写入标记，方便你一眼知道“是否已更新到这次执行”
  date -u +"%Y-%m-%dT%H:%M:%SZ" > "${base}/agent/.installed_at" || true
  echo "${VERSION}" > "${base}/agent/.installer_version" || true

  setup_mptcp_kernel_runtime
  setup_mptcp_sidecar_systemd "${base}" 1
  install_isolated_runtime_units "${base}" "${selected_service}"
  if ! validate_agent_api_key_file "$(agent_api_key_path)" 0 0; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  if [[ "${transport}" == "https" ]] \
    && ! validate_agent_tls_material \
      "${ssl_cert}" "${ssl_key}" "${tls_server_name}" "${agent_host}" \
      "$(agent_service_file_uid)" "${AGENT_SERVICE_GID}" 86400 \
      "${tls_verify_peer}" "${tls_ca_cert}" "${tls_cert_sha256}"; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  if ! activate_agent_api_service "${selected_service}" "${opposite_service}"; then
    restore_agent_deploy_rollback
    return 1
  fi
  if ! activate_agent_auxiliary_runtime; then
    restore_agent_deploy_rollback
    return 1
  fi

  if ! verify_agent_deploy_health \
    "${selected_service}" "${transport}" "${agent_host}" "${agent_port}" \
    "${tls_server_name}" "${tls_verify_peer}" "${tls_ca_cert}"; then
    err "Agent 新版本未通过 commit 前稳定健康门禁"
    restore_agent_deploy_rollback
    return 1
  fi

  # 只有新版本完成健康稳定窗口后，才持久化 lock/ABI/RECORD 证明。
  local final_req_file=""
  local final_req_sha=""
  local release_zip_sha=""
  final_req_file="$(select_agent_requirements_file "${base}/agent" || true)"
  final_req_sha="$(compute_requirements_sha256 "${final_req_file}" || true)"
  release_zip_sha="$(normalize_sha256 \
    "${ACTUAL_ZIP_SHA256:-${TARGET_ZIP_SHA256:-${REALM_AGENT_ZIP_SHA256:-}}}" \
    || true)"
  if [[ "${REALM_AGENT_MODE:-${DEFAULT_MODE}}" == "2" \
    && -z "${release_zip_sha}" ]]; then
    err "离线 Agent 更新未绑定实际签名 ZIP SHA256"
    restore_agent_deploy_rollback || true
    return 1
  fi
  if [[ -z "${final_req_sha}" || "${final_req_sha}" != "${new_req_sha}" ]]; then
    err "健康门禁后 Agent requirements.lock SHA 漂移"
    restore_agent_deploy_rollback || true
    return 1
  fi
  if ! write_agent_venv_attestation \
    "${venv_attestation_pending}" \
    "${config_dir}/venv-attestation.json" \
    "${final_req_sha}" "${release_zip_sha}"; then
    err "Agent venv 证明写入失败"
    restore_agent_deploy_rollback || true
    return 1
  fi
  local req_sha_temp=""
  req_sha_temp="$(mktemp "${req_sha_file}.tmp.XXXXXX")" || {
    restore_agent_deploy_rollback || true
    return 1
  }
  register_cleanup_path "${req_sha_temp}"
  if ! printf '%s\n' "${final_req_sha}" > "${req_sha_temp}" \
    || ! chmod 0600 "${req_sha_temp}" \
    || ! durable_replace_agent_state_file \
      "${req_sha_temp}" "${req_sha_file}"; then
    err "Agent requirements SHA 写入失败"
    restore_agent_deploy_rollback || true
    return 1
  fi
  ok "Agent venv lock/ABI/RECORD 证明已在健康门禁后持久化"

  # 版本校验必须在 commit 之前：失败时事务尚未提交、回滚材料仍在，
  # 可以安全恢复到上一个版本。commit 之后只做确认（main 中的复核）。
  if ! verify_installed_agent_release_version; then
    err "Agent 已切换版本与安装器声明不一致，拒绝提交事务"
    restore_agent_deploy_rollback || true
    return 1
  fi

  if ! commit_agent_deploy_rollback; then
    restore_agent_deploy_rollback || true
    return 1
  fi
  prune_agent_artifacts
}

find_agent_dir(){
  local base="$1"
  local p
  p=$(find "${base}" -maxdepth 5 -type d -name agent -print | head -n 1 || true)
  if [[ -z "${p}" ]]; then
    err "找不到 agent 目录。请确认仓库里包含 agent/ 或 realm-pro-suite-vXX/agent/"
    err "建议仓库结构：仓库根目录/agent  或  仓库根目录/realm-pro-suite-v31/agent"
    exit 1
  fi
  echo "${p}"
}

restart_service(){
  local svc="$1"
  if ! systemctl daemon-reload >/dev/null 2>&1 \
    || ! systemctl enable --now "${svc}" >/dev/null 2>&1; then
    err "无法启用 systemd 服务：${svc}"
    return 1
  fi
  if ! systemctl is-enabled --quiet "${svc}" 2>/dev/null \
    || ! systemctl is-active --quiet "${svc}" 2>/dev/null; then
    err "systemd 服务未达到 active/enabled：${svc}"
    return 1
  fi
}

install_isolated_runtime_units(){
  local base="$1"
  local selected_service="${2:-realm-agent.service}"
  local unit_source="${base}/agent/systemd"
  local systemd_dir=""
  local unit
  local target_tmp=""
  local -a units=()
  systemd_dir="$(agent_systemd_dir)"
  install -d -m 755 "${systemd_dir}"
  while IFS= read -r unit; do
    [[ -n "${unit}" ]] || continue
    units+=("${unit}")
  done < <(agent_isolated_runtime_unit_names)
  if [[ ! -d "${unit_source}" ]]; then
    err "缺少隔离运行时 systemd 目录：${unit_source}"
    return 1
  fi
  for unit in "${units[@]}"; do
    if [[ ! -f "${unit_source}/${unit}" ]]; then
      err "缺少隔离运行时 unit：${unit_source}/${unit}"
      return 1
    fi
    if [[ "${unit}" == "realm-agent.target" ]]; then
      target_tmp="$(mktemp "${systemd_dir}/.realm-agent.target.XXXXXX")"
      register_cleanup_path "${target_tmp}"
      if ! sed \
        "s/^Wants=realm-agent\\.service$/Wants=${selected_service}/" \
        "${unit_source}/${unit}" > "${target_tmp}"; then
        return 1
      fi
      if ! grep -q "^Wants=${selected_service}$" "${target_tmp}"; then
        err "无法把 realm-agent.target 对齐到 ${selected_service}"
        return 1
      fi
      chmod 0644 "${target_tmp}"
      mv -f "${target_tmp}" "${systemd_dir}/${unit}"
      target_tmp=""
    else
      install -m 0644 "${unit_source}/${unit}" "${systemd_dir}/${unit}"
    fi
  done
  systemctl daemon-reload
  ok "隔离运行时 systemd 单元已安装（保持未启用，等待灰度切换）"
}

setup_mptcp_kernel_runtime(){
  if [[ "${REALM_AGENT_APPLY_HOST_NETWORK_CHANGES:-0}" != "1" ]]; then
    info "默认不写入 MPTCP sysctl；需要时显式设置 REALM_AGENT_APPLY_HOST_NETWORK_CHANGES=1"
    return 0
  fi
  local sysctl_dir=""
  sysctl_dir="$(agent_sysctl_dir)"
  install -d -m 755 "${sysctl_dir}"
  cat > "${sysctl_dir}/90-realm-mptcp.conf" <<'EOF'
# Ignore old kernels that do not expose this key. A supported kernel will
# enable MPTCP automatically during boot.
-net.mptcp.enabled = 1
EOF
  chmod 644 "${sysctl_dir}/90-realm-mptcp.conf"

  if [[ -e /proc/sys/net/mptcp/enabled ]]; then
    sysctl -w net.mptcp.enabled=1 >/dev/null
    if command_exists ip && ip mptcp limits show >/dev/null 2>&1; then
      ip mptcp limits set subflows 4 add_addr_accepted 4 >/dev/null
    fi
    ok "已启用内核 MPTCP 与路径管理上限"
  else
    info "当前内核不支持 MPTCP；已预置 sysctl，升级内核并重启后自动生效"
  fi
}

setup_mptcp_sidecar_systemd(){
  local base="$1"
  local defer_start="${2:-0}"
  local systemd_dir=""
  local unit_path=""
  local protect_system_mode="${AGENT_SYSTEMD_PROTECT_SYSTEM_MODE:-strict}"
  AGENT_MPTCP_SIDECAR_SHOULD_RUN="0"
  if ! command_exists systemctl; then
    return 0
  fi
  systemd_dir="$(agent_systemd_dir)"
  unit_path="${systemd_dir}/realm-mptcp-sidecar.service"
  case "${protect_system_mode}" in
    strict | full) ;;
    *)
      err "非法 ProtectSystem 兼容模式：${protect_system_mode}"
      return 1
      ;;
  esac
  install -d -m 755 "${systemd_dir}"
  mkdir -p "${base}"
  cat > "${base}/mptcp_sidecar_start.sh" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
umask 077

read_sidecar_env_value(){
  local key="$1"
  local line value
  line="$(grep -E "^(export[[:space:]]+)?${key}=" /etc/realm-agent/agent.env 2>/dev/null | head -n 1 || true)"
  if [[ -z "${line}" ]]; then
    return 1
  fi
  if [[ "${line}" == export* ]]; then
    line="${line#export }"
  fi
  value="${line#"${key}"=}"
  value="${value%$'\r'}"
  value="${value#"${value%%[![:space:]]*}"}"
  value="${value%"${value##*[![:space:]]}"}"
  if [[ "${value}" == \"*\" ]]; then
    value="${value#\"}"
    value="${value%\"}"
  fi
  if [[ "${value}" == \'*\' ]]; then
    value="${value#\'}"
    value="${value%\'}"
  fi
  printf '%s' "${value}"
}

decode_sidecar_command_value(){
  local raw="${1:-}"
  local launcher_dir=""
  local parser=""
  local decoded=""
  launcher_dir="$(cd -- "$(dirname -- "$0")" && pwd -P)"
  if [[ -x "${launcher_dir}/venv/bin/python" ]]; then
    parser="${launcher_dir}/venv/bin/python"
  elif command -v python3 >/dev/null 2>&1; then
    parser="$(command -v python3)"
  else
    printf '%s' "${raw}"
    return 0
  fi
  if decoded="$("${parser}" - "${raw}" <<'PY'
import base64
import shlex
import sys

text = sys.argv[1]
if text.startswith("b64:"):
    encoded = text[4:]
    try:
        data = base64.b64decode(encoded, altchars=b"-_", validate=True)
        decoded = data.decode("utf-8")
    except (ValueError, UnicodeDecodeError):
        raise SystemExit(1)
    if base64.urlsafe_b64encode(data).decode("ascii") != encoded:
        raise SystemExit(1)
    if any(ord(char) < 32 or ord(char) == 127 for char in decoded):
        raise SystemExit(1)
    sys.stdout.write(decoded)
    raise SystemExit(0)
try:
    values = shlex.split(text, posix=True)
except ValueError:
    raise SystemExit(1)
if len(values) != 1:
    raise SystemExit(1)
sys.stdout.write(values[0])
PY
  )"; then
    printf '%s' "${decoded}"
  else
    printf '%s' "${raw}"
  fi
}

parse_mptcp_argv(){
  local command_text="$1"
  local parser_python=""
  local argv_file=""
  local item=""
  MPTCP_ARGV=()
  if [[ -x "${base_dir}/venv/bin/python" ]]; then
    parser_python="${base_dir}/venv/bin/python"
  elif command -v python3 >/dev/null 2>&1; then
    parser_python="$(command -v python3)"
  else
    echo "python3 unavailable for safe sidecar argv parsing" >&2
    return 1
  fi
  argv_file="$(mktemp "${TMPDIR:-/tmp}/realm-mptcp-argv.XXXXXX")" || return 1
  cleanup_argv_file(){
    rm -f "${argv_file}" >/dev/null 2>&1 || true
  }
  trap cleanup_argv_file EXIT HUP INT TERM
  if ! "${parser_python}" - "${command_text}" > "${argv_file}" <<'PY'
import re
import shlex
import sys

text = sys.argv[1]
if not text or any(ord(char) < 32 or ord(char) == 127 for char in text):
    raise SystemExit("invalid sidecar command")
lexer = shlex.shlex(
    text,
    posix=True,
    punctuation_chars=";&|<>`$()*?[]{}!~",
)
lexer.whitespace_split = True
lexer.commenters = ""
try:
    argv = list(lexer)
except ValueError as exc:
    raise SystemExit(f"invalid sidecar quoting: {exc}") from exc
if not argv or len(argv) > 128:
    raise SystemExit("invalid sidecar argv length")
operators = set(";&|<>`$()*?[]{}!~")
if any(token and all(char in operators for char in token) for token in argv):
    raise SystemExit("shell operators are not allowed")
if any("\x00" in token or "\n" in token or "\r" in token for token in argv):
    raise SystemExit("control characters are not allowed")
program = argv[0]
if "/" not in program and not re.fullmatch(r"[A-Za-z0-9_.+-]+", program):
    raise SystemExit("invalid sidecar executable")
for token in argv:
    sys.stdout.buffer.write(token.encode("utf-8") + b"\0")
PY
  then
    cleanup_argv_file
    trap - EXIT HUP INT TERM
    return 1
  fi
  while IFS= read -r -d '' item; do
    MPTCP_ARGV+=("${item}")
  done < "${argv_file}"
  cleanup_argv_file
  trap - EXIT HUP INT TERM
  (( ${#MPTCP_ARGV[@]} > 0 ))
}

mptcp_enabled="${REALM_MPTCP_ENABLED:-}"
if [[ -z "${mptcp_enabled}" ]]; then
  mptcp_enabled="$(read_sidecar_env_value REALM_MPTCP_ENABLED || true)"
fi
if [[ "${mptcp_enabled:-0}" != "1" ]]; then
  echo "REALM_MPTCP_ENABLED!=1, skip sidecar startup"
  exit 0
fi
cmd="${REALM_MPTCP_SIDECAR_CMD:-}"
if [[ -n "${cmd}" ]]; then
  cmd="$(decode_sidecar_command_value "${cmd}")"
else
  cmd="$(read_sidecar_env_value REALM_MPTCP_SIDECAR_CMD || true)"
  cmd="$(decode_sidecar_command_value "${cmd}")"
fi
if [[ -z "${cmd}" ]]; then
  echo "REALM_MPTCP_SIDECAR_CMD empty"
  exit 1
fi
base_dir="$(cd -- "$(dirname -- "$0")" && pwd -P)"
export PYTHONPATH="${base_dir}${PYTHONPATH:+:${PYTHONPATH}}"
cd "${base_dir}"
parse_mptcp_argv "${cmd}"
exec "${MPTCP_ARGV[@]}"
EOF
  chmod 700 "${base}/mptcp_sidecar_start.sh" >/dev/null 2>&1 || true

  if ! is_safe_systemd_value "${base}"; then
    err "拒绝写入 systemd 单元：sidecar 安装路径含非法字符（${base}）"
    return 1
  fi
  cat > "${unit_path}" <<'UNIT_EOF'
[Unit]
Description=Realm MPTCP Sidecar
Wants=network-online.target
After=network-online.target
StartLimitIntervalSec=60
StartLimitBurst=5

[Service]
Type=simple
WorkingDirectory=__BASE__
EnvironmentFile=-/etc/realm-agent/agent.env
Environment=PYTHONDONTWRITEBYTECODE=1
Environment=PYTHONPATH=__BASE__
ExecStart=__BASE__/mptcp_sidecar_start.sh
Restart=always
RestartSec=2
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=read-only
ProtectSystem=__PROTECT_SYSTEM_MODE__
ReadWritePaths=/run /var/run
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
LockPersonality=true
LimitNOFILE=1048576

[Install]
WantedBy=multi-user.target
UNIT_EOF
  sed -i \
    -e "s|__BASE__|${base}|g" \
    -e "s|__PROTECT_SYSTEM_MODE__|${protect_system_mode}|g" \
    "${unit_path}"

  local mptcp_enabled sidecar_cmd
  mptcp_enabled="$(read_env_value /etc/realm-agent/agent.env REALM_MPTCP_ENABLED || true)"
  sidecar_cmd="$(read_env_value /etc/realm-agent/agent.env REALM_MPTCP_SIDECAR_CMD || true)"
  if [[ -z "${mptcp_enabled}" ]]; then
    mptcp_enabled="0"
  fi
  if [[ "${mptcp_enabled}" == "1" && -n "${sidecar_cmd}" ]]; then
    AGENT_MPTCP_SIDECAR_SHOULD_RUN="1"
  fi
  if [[ "${defer_start}" == "1" ]]; then
    if ! systemctl daemon-reload >/dev/null 2>&1; then
      err "无法 reload MPTCP sidecar unit"
      return 1
    fi
    info "MPTCP sidecar unit 已写入，将随目标 runtime stack 激活"
    return 0
  fi
  if [[ "${mptcp_enabled}" == "1" && -n "${sidecar_cmd}" ]]; then
    restart_service realm-mptcp-sidecar.service
    ok "已启用 MPTCP sidecar 服务托管（realm-mptcp-sidecar）"
    return 0
  fi
  if ! systemctl daemon-reload >/dev/null 2>&1 \
    || ! systemctl disable --now realm-mptcp-sidecar.service >/dev/null 2>&1; then
    err "无法禁用 MPTCP sidecar 服务"
    return 1
  fi
  if systemctl is-active --quiet realm-mptcp-sidecar.service 2>/dev/null \
    || systemctl is-enabled --quiet realm-mptcp-sidecar.service 2>/dev/null; then
    err "MPTCP sidecar 禁用后仍处于 active/enabled"
    return 1
  fi
  if [[ "${mptcp_enabled}" == "1" && -z "${sidecar_cmd}" ]]; then
    info "REALM_MPTCP_ENABLED=1 但未设置 REALM_MPTCP_SIDECAR_CMD，sidecar 服务未启动"
  else
    info "MPTCP sidecar 服务默认不启用（REALM_MPTCP_ENABLED=0）"
  fi
}

get_bindv6only(){
  local path="${REALM_AGENT_BINDV6ONLY_PATH:-/proc/sys/net/ipv6/bindv6only}"
  if [[ -f "${path}" ]]; then
    tr -d '[:space:]' < "${path}" 2>/dev/null || echo "0"
  else
    echo "0"
  fi
}

get_ipv4(){
  local ip
  ip=$(ip -o -4 addr show scope global 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -n 1 || true)
  if [[ -z "${ip}" ]]; then
    ip=$(hostname -I 2>/dev/null | awk '{for (i=1;i<=NF;i++) if ($i ~ /^[0-9.]+$/) {print $i; exit}}' || true)
  fi
  echo "${ip}"
}

get_ipv6(){
  local ip
  ip=$(ip -o -6 addr show scope global 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -n 1 || true)
  if [[ -z "${ip}" ]]; then
    ip=$(hostname -I 2>/dev/null | awk '{for (i=1;i<=NF;i++) if ($i ~ /:/) {print $i; exit}}' || true)
  fi
  echo "${ip}"
}

format_agent_url(){
  local transport="$1"
  local host="$2"
  local port="$3"
  if [[ "${host}" == *:* && "${host}" != \[*\] ]]; then
    printf '%s://[%s]:%s' "${transport}" "${host}" "${port}"
  else
    printf '%s://%s:%s' "${transport}" "${host}" "${port}"
  fi
}

print_agent_access_endpoints(){
  local transport="$1"
  local host="$2"
  local port="$3"
  local ipv4=""
  local ipv6=""

  case "${host}" in
    0.0.0.0)
      echo "- Listen:      $(format_agent_url "${transport}" "${host}" "${port}")"
      ipv4="$(get_ipv4)"
      if [[ -n "${ipv4}" ]]; then
        echo "- Agent URL:   $(format_agent_url "${transport}" "${ipv4}" "${port}")"
      fi
      ;;
    ::)
      echo "- Listen:      $(format_agent_url "${transport}" "${host}" "${port}")"
      ipv6="$(get_ipv6)"
      if [[ -n "${ipv6}" ]]; then
        echo "- Agent URL:   $(format_agent_url "${transport}" "${ipv6}" "${port}")"
      fi
      if [[ "$(get_bindv6only)" != "1" ]]; then
        ipv4="$(get_ipv4)"
        if [[ -n "${ipv4}" ]]; then
          echo "- Agent URL:   $(format_agent_url "${transport}" "${ipv4}" "${port}")"
        fi
      fi
      ;;
    *)
      echo "- Agent URL:   $(format_agent_url "${transport}" "${host}" "${port}")"
      ;;
  esac
}

print_agent_api_key(){
  local api_key="$1"
  : "${2:-}"
  if [[ "${REALM_AGENT_SHOW_API_KEY:-0}" == "1" ]]; then
    echo "- API Key:     ${api_key}"
  else
    echo "- API Key:     已安全保存（默认隐藏；文件：$(agent_api_key_path)）"
  fi
}

install_agent_managed_prerequisites(){
  if [[ "${REALM_AGENT_DEPLOY_ROLLBACK_ACTIVE:-0}" != "1" ]]; then
    err "拒绝在 rollback transaction 外写入 Agent/Realm 受管状态"
    return 1
  fi
  if [[ "${REALM_AGENT_SETUP_NFTABLES:-${REALM_AGENT_SETUP_IPTABLES:-0}}" == "1" ]]; then
    install_nftables_stack || return 1
  else
    info "跳过 nftables 系统初始化（REALM_AGENT_SETUP_NFTABLES=0）"
  fi
  if [[ "${REALM_AGENT_INSTALL_TCPING:-0}" == "1" ]]; then
    install_tcping
  else
    info "跳过 tcping 安装（设置 REALM_AGENT_INSTALL_TCPING=1 可启用）"
  fi
  if [[ "${REALM_AGENT_ONLY:-0}" != "1" ]]; then
    install_realm
    install_realm_service
    apply_sysctl_tuning
  else
    install_realm_service_guard
  fi
}

main(){
  need_root
  hydrate_update_runtime_env
  if ! acquire_agent_install_lock; then
    if [[ "${1:-}" == "--recover-only" \
      && "${REALM_AGENT_INSTALL_LOCK_BUSY:-0}" == "1" \
      && "${REALM_AGENT_INSTALL_LOCK_NONBLOCK:-0}" == "1" ]]; then
      notify_agent_recovery_ready || exit 1
      ok "Agent 更新事务仍由安装器持有，启动恢复本轮跳过"
      exit 0
    fi
    exit 1
  fi
  if [[ "${1:-}" == "--recover-only" ]]; then
    if ! recover_pending_agent_deploy_transaction; then
      exit 1
    fi
    notify_agent_recovery_ready || exit 1
    ok "Agent 启动前事务恢复检查完成"
    exit 0
  fi
  if ! recover_pending_agent_deploy_transaction; then
    exit 1
  fi
  if ! capture_agent_target_api_key; then
    exit 1
  fi
  local api_key_path=""
  api_key_path="$(agent_api_key_path)"

  echo "Realm Pro Agent Installer ${VERSION}"
  echo "------------------------------------------------------------"
  local mode
  mode="${REALM_AGENT_MODE:-${DEFAULT_MODE}}"
  if [[ "${mode}" != "1" && "${mode}" != "2" ]]; then
    err "安装模式仅支持 1(在线) 或 2(离线)"
    exit 1
  fi

  hydrate_panel_context
  local panel_base_for_log
  panel_base_for_log="$(normalize_panel_url "${REALM_PANEL_URL:-}")"
  if [[ -n "${panel_base_for_log}" && -z "${REALM_AGENT_REPO_ZIP_URL:-}" && "${REALM_AGENT_GITHUB_ONLY:-}" != "1" ]]; then
    info "仓库 ZIP 将优先使用面板地址：${panel_base_for_log}/static/realm-agent.zip"
  fi

  if ! phase1_agent_install_contract_preflight \
    "${REALM_AGENT_HOST:-}" \
    "${REALM_AGENT_PORT:-}" \
    "${REALM_AGENT_TRANSPORT:-}"; then
    err "Agent phase-1 契约预检失败；尚未修改 apt/apt-listchanges"
    exit 1
  fi
  if ! resolve_agent_v2_wal_root >/dev/null; then
    exit 1
  fi
  if ! preflight_agent_sandbox_paths; then
    exit 1
  fi
  if ! preflight_active_managed_realm_config; then
    exit 1
  fi
  info "安装依赖..."
  apt_install
  AGENT_CONTRACT_PYTHON="$(find_phase1_contract_python || true)"
  if [[ "${AGENT_PHASE1_CONTRACT_COMPLETE}" != "1" ]]; then
    info "依赖阶段完成，正在补做旧 Agent unit 完整契约解析"
  fi
  if ! resolve_agent_install_contract \
    "${REALM_AGENT_HOST:-}" \
    "${REALM_AGENT_PORT:-}" \
    "${REALM_AGENT_TRANSPORT:-}"; then
    err "Agent 监听/传输契约预检失败；旧服务未切换"
    exit 1
  fi
  local host="${AGENT_INSTALL_HOST}"
  local port="${AGENT_INSTALL_PORT}"
  local transport="${AGENT_INSTALL_TRANSPORT}"
  local service="${AGENT_INSTALL_SERVICE}"

  local tmpdir
  tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/realm-agent-repo.XXXXXX")
  register_cleanup_path "${tmpdir}"

  fetch_repo "${mode}" "${tmpdir}"

  local agent_dir
  agent_dir=$(find_agent_dir "${tmpdir}")
  ok "agent 目录：${agent_dir}"

  # ✅ 再次执行脚本时，自动全量更新到最新（无需卸载重装）
  # - staging + 原子替换，避免“半更新/更新不到位”
  # - 自动 cache-bust，避免下载到旧包
  atomic_update_agent \
    "${agent_dir}" \
    "${host}" \
    "${port}" \
    "${transport}" \
    "${AGENT_INSTALL_SSL_CERT}" \
    "${AGENT_INSTALL_SSL_KEY}" \
    "${AGENT_INSTALL_TLS_SERVER_NAME}" \
    "${AGENT_INSTALL_TLS_AUTO_GENERATE}" \
    "${AGENT_INSTALL_TLS_VERIFY_PEER}" \
    "${AGENT_INSTALL_TLS_CA_CERT}" \
    "${AGENT_INSTALL_TLS_CERT_SHA256}" \
    "${AGENT_INSTALL_ADDRESS_FAMILY}" \
    "${AGENT_INSTALL_ALLOW_INSECURE_NON_LOOPBACK}"
  if ! verify_installed_agent_release_version; then
    err "Agent 原子更新未落地目标版本"
    return 1
  fi

  local api_key
  api_key=""
  if [[ "${REALM_AGENT_SHOW_API_KEY:-0}" == "1" ]]; then
    api_key=$(cat "${api_key_path}")
  fi

  ok "Agent 已安装并启动"
  print_agent_access_endpoints "${transport}" "${host}" "${port}"
  print_agent_api_key "${api_key}" 1
  echo "- Service:     systemctl status ${service} --no-pager"
  if [[ "${transport}" == "https" ]]; then
    echo "- TLS cert:    ${AGENT_INSTALL_SSL_CERT}"
  fi
}

if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then
  return 0
fi
if [[ "$-" != *p* ]]; then
  exec /bin/bash -p "$0" "$@"
fi
main "$@"
