#!/bin/bash -p

if [[ "${BASH_SOURCE[0]}" != "$0" || "$-" == *p* ]]; then
  set -euo pipefail
  umask 077
  export PATH="/opt/homebrew/opt/openssl@3/bin:/usr/local/opt/openssl@3/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:${PATH}"
fi

VERSION="v113-macos"
# 环境注入使用 REALM_AGENT_REPO_ZIP_URL / REALM_AGENT_REPO_FALLBACK_ZIP_URL
# （见 fetch_repo_zip）；REPO_ZIP_URL_DEFAULT / REPO_ZIP_URL_FALLBACK 为
# 与 Linux 端一致的空默认值声明，仅作文档化默认。
REPO_ZIP_URL_DEFAULT=""
REPO_ZIP_URL_FALLBACK=""
REPO_RELEASE_METADATA_URL_DEFAULT="https://nexus.infpro.me/release-manifest.json"
# 与 Linux 端一致的默认值：仓库文件根与签名文件清单 URL。
REPO_BASE_URL_DEFAULT="https://nexus.infpro.me/nexus"
REPO_MANIFEST_URL_DEFAULT="https://nexus.infpro.me/release-manifest.json"
DEFAULT_PORT="18700"
DEFAULT_HOST="127.0.0.1"
AGENT_INSTALL_LOCK_PATH_DEFAULT="/private/var/run/realm-agent/install.lock"
BASE_DIR="/usr/local/realm-agent"
MACOS_RECOVERY_DIR="/usr/local/libexec/realm-agent"
MACOS_RECOVERY_SCRIPT="${MACOS_RECOVERY_DIR}/realm_agent_macos_recovery.sh"
MACOS_STARTUP_WRAPPER="${MACOS_RECOVERY_DIR}/start_with_recovery.sh"
MACOS_RECOVERY_LABEL="com.realm.agent.install-recovery"
MACOS_RECOVERY_PLIST="/Library/LaunchDaemons/${MACOS_RECOVERY_LABEL}.plist"
AGENT_LABEL="com.realm.agent"
REVTUNNEL_LABEL="com.realm.agent.revtunnel"
MPTCP_SIDECAR_LABEL="com.realm.agent.mptcp-sidecar"
REMOTE_COMPANION_LABEL="com.realm.remote-mac-agent"
REMOTE_COMPANION_APP_PATH="${BASE_DIR}/RemoteMacAgent.app"
REMOTE_COMPANION_CONFIG="/etc/realm-agent/remote-companion.json"
REMOTE_COMPANION_API_KEY_PATH="/etc/realm-agent/remote-companion.api.key"
REMOTE_COMPANION_STATUS_LEGACY="/var/lib/realm-agent/remote-mac-agent/status.json"
REMOTE_COMPANION_ARTIFACT_SHA_PATH="/var/lib/realm-agent/remote-mac-agent/installed-artifact.sha256"
REMOTE_COMPANION_KEYCHAIN_SERVICE="com.realm.remote-mac-agent"
REMOTE_COMPANION_KEYCHAIN_ACCOUNT="api_key"
SSHD_LOOPBACK_PENALTY_CONFIG="/etc/ssh/sshd_config.d/010-realm-agent-loopback.conf"
# REMOTE_COMPANION_STATUS 在 setup_remote_companion 中根据桌面用户家目录重算；
# 全局占位以满足 set -u；当无法识别桌面用户时（极端情况）回落到旧路径。
REMOTE_COMPANION_STATUS="${REMOTE_COMPANION_STATUS:-${REMOTE_COMPANION_STATUS_LEGACY}}"
REMOTE_COMPANION_CODESIGN_IDENTITY="${REALM_REMOTE_CODESIGN_IDENTITY:-Realm RemoteMacAgent Local Code Signing}"
REMOTE_COMPANION_CODESIGN_KEYCHAIN="${REALM_REMOTE_CODESIGN_KEYCHAIN:-}"
REMOTE_COMPANION_CODESIGN_KEYCHAIN_PASSWORD_FILE="${REALM_REMOTE_CODESIGN_KEYCHAIN_PASSWORD_FILE:-}"
REMOTE_COMPANION_ALLOW_ADHOC_CODESIGN="${REALM_REMOTE_ALLOW_ADHOC_CODESIGN:-0}"
AGENT_BOOTSTRAP_MODE="launchd"
REMOTE_CONTROL_ENABLED="${REALM_REMOTE_CONTROL_ENABLED:-1}"
REMOTE_CONTROL_PRESERVE="${REALM_REMOTE_CONTROL_PRESERVE:-0}"
REMOTE_COMPANION_STATUS_RESET_OK="0"
REMOTE_COMPANION_LEGACY_KEY_EXPOSED="0"
REMOTE_COMPANION_UPDATE_PENDING="0"
REMOTE_COMPANION_UPDATE_BACKUP=""
REMOTE_COMPANION_TRANSACTION_DIR=""
REMOTE_COMPANION_PENDING_ARTIFACT_SHA=""
REMOTE_COMPANION_DESKTOP_USER=""
REMOTE_COMPANION_DESKTOP_UID=""
REMOTE_COMPANION_DESKTOP_GID=""
REMOTE_COMPANION_DESKTOP_GROUP=""
REMOTE_COMPANION_DESKTOP_HOME=""
REMOTE_COMPANION_DESKTOP_PLIST=""
REMOTE_COMPANION_RELEASE_VERSION=""
REMOTE_COMPANION_RELEASE_SHA256=""
REMOTE_COMPANION_RELEASE_ZIP=""
REMOTE_COMPANION_LOGS_RETIRE_ALLOWED="0"
REALM_MAC_DEPLOY_ROLLBACK_ACTIVE="0"
REALM_MAC_TRANSACTION_DIR="${BASE_DIR}/.install-transaction"
REALM_MAC_DEPLOY_ROLLBACK_DIR="${REALM_MAC_TRANSACTION_DIR}/rollback"
REALM_MAC_DEPLOY_REPLACE_VENV="0"
REALM_MAC_AGENT_WAS_LOADED="0"
REALM_MAC_STAGE_DIR=""
REALM_MAC_PREV_AGENT="${BASE_DIR}/.agent-prev"
REALM_MAC_PREV_SHARED="${BASE_DIR}/.shared-prev"
REALM_MAC_PREV_VENV="${BASE_DIR}/.venv-prev"
REALM_MAC_CONTINUITY_INSTALL_REQUESTED="0"
REALM_MAC_CONTINUITY_PACKAGE_SHA=""
REALM_MAC_CONTINUITY_RELEASE_DIR=""
REALM_MAC_CONTINUITY_RELEASE_ROOT=""
REALM_MAC_CONTINUITY_RELEASE_CREATED="0"
REALM_AGENT_INSTALL_LOCK_HELD="0"
REALM_AGENT_INSTALL_LOCK_PATH_HELD=""
REALM_AGENT_INSTALL_LOCK_BUSY="0"
__REALM_MAC_CLEANUP_PATHS=()
REALM_MAC_RECOVER_ONLY="0"
MAC_TRUSTED_PYTHON_BIN=""

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

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

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
}

register_cleanup_path(){
  local path="${1:-}"
  [[ -n "${path}" ]] || return 0
  __REALM_MAC_CLEANUP_PATHS+=("${path}")
}

fsync_path_and_parent(){
  local path="${1:-}"
  [[ -f "${path}" && ! -L "${path}" ]] || return 1
  ensure_trusted_macos_agent_python || {
    err "缺少 python3，无法持久化事务文件：${path}"
    return 1
  }
  run_trusted_macos_python - "${path}" <<'PY'
import os
import stat
import sys

path = os.fsencode(sys.argv[1])
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
fd = os.open(path, flags)
try:
    if not stat.S_ISREG(os.fstat(fd).st_mode):
        raise OSError("transaction path is not a regular file")
    os.fsync(fd)
finally:
    os.close(fd)
parent = os.path.dirname(path) or b"."
parent_fd = os.open(parent, os.O_RDONLY)
try:
    os.fsync(parent_fd)
finally:
    os.close(parent_fd)
PY
}

fsync_directory_and_parent(){
  local path="${1:-}"
  [[ -d "${path}" && ! -L "${path}" ]] || return 1
  ensure_trusted_macos_agent_python || {
    err "缺少 python3，无法持久化目录：${path}"
    return 1
  }
  run_trusted_macos_python - "${path}" <<'PY'
import os
import stat
import sys

path = os.fsencode(sys.argv[1])
flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
fd = os.open(path, flags)
try:
    if not stat.S_ISDIR(os.fstat(fd).st_mode):
        raise OSError("path is not a directory")
    os.fsync(fd)
finally:
    os.close(fd)
parent = os.path.dirname(path) or b"."
parent_fd = os.open(parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
try:
    os.fsync(parent_fd)
finally:
    os.close(parent_fd)
PY
}

fsync_tree_and_parent(){
  local path="${1:-}"
  [[ -d "${path}" && ! -L "${path}" ]] || return 1
  ensure_trusted_macos_agent_python || {
    err "缺少 python3，无法持久化目录树：${path}"
    return 1
  }
  run_trusted_macos_python - "${path}" <<'PY'
import os
import stat
import sys

root = os.fsencode(sys.argv[1])
nofollow = getattr(os, "O_NOFOLLOW", 0)
for current, directories, files in os.walk(root, topdown=False, followlinks=False):
    for name in files:
        path = os.path.join(current, os.fsencode(name))
        mode = os.lstat(path).st_mode
        if stat.S_ISLNK(mode):
            continue
        if not stat.S_ISREG(mode):
            raise OSError(f"runtime entry is not regular: {path!r}")
        fd = os.open(path, os.O_RDONLY | nofollow)
        try:
            os.fsync(fd)
        finally:
            os.close(fd)
    for name in directories:
        path = os.path.join(current, os.fsencode(name))
        if stat.S_ISLNK(os.lstat(path).st_mode):
            continue
        fd = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | nofollow)
        try:
            os.fsync(fd)
        finally:
            os.close(fd)
    current_fd = os.open(
        current,
        os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | nofollow,
    )
    try:
        os.fsync(current_fd)
    finally:
        os.close(current_fd)
parent_fd = os.open(
    os.path.dirname(root) or b".",
    os.O_RDONLY | getattr(os, "O_DIRECTORY", 0),
)
try:
    os.fsync(parent_fd)
finally:
    os.close(parent_fd)
PY
}

persist_transaction_value(){
  local path="${1:-}"
  local value="${2-}"
  local parent=""
  local temp_path=""
  [[ -n "${path}" ]] || return 1
  parent="$(dirname "${path}")"
  install -d -m 700 "${parent}" || return 1
  temp_path="$(mktemp "${path}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${temp_path}"
  printf '%s\n' "${value}" > "${temp_path}" || return 1
  chmod 600 "${temp_path}" || return 1
  fsync_path_and_parent "${temp_path}" || return 1
  mv -f "${temp_path}" "${path}" || return 1
  fsync_path_and_parent "${path}"
}

read_transaction_value(){
  local path="${1:-}"
  [[ -f "${path}" && ! -L "${path}" ]] || return 1
  head -n 1 "${path}" 2>/dev/null | tr -d '\r\n'
}

agent_install_lock_path(){
  local 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_device_inode(){
  local path="$1"
  if [[ "$(uname -s)" == "Darwin" ]]; then
    stat -f '%d:%i' "${path}" 2>/dev/null
  else
    stat -c '%d:%i' "${path}" 2>/dev/null
  fi
}

agent_lock_fd_stat_value(){
  local index="$1"
  if [[ -x /usr/bin/perl ]]; then
    /usr/bin/perl -e '
      open(my $fh, "<&=202") or exit 1;
      my @stat = stat($fh);
      print $stat[$ARGV[0]];
    ' "${index}"
    return
  fi
  if ensure_trusted_macos_agent_python; then
    run_trusted_macos_python - "${index}" <<'PY'
import os
import sys

value = os.fstat(202)
fields = (value.st_dev, value.st_ino, value.st_mode, value.st_nlink, value.st_uid)
print(fields[int(sys.argv[1])], end="")
PY
    return
  fi
  return 1
}

agent_lock_fd_device_inode(){
  local device=""
  local inode=""
  device="$(agent_lock_fd_stat_value 0)" || return 1
  inode="$(agent_lock_fd_stat_value 1)" || return 1
  printf '%s:%s' "${device}" "${inode}"
}

agent_lock_fd_uid(){
  agent_lock_fd_stat_value 4
}

agent_lock_file_uid(){
  local path="$1"
  if [[ "$(uname -s)" == "Darwin" ]]; then
    stat -f '%u' "${path}" 2>/dev/null
  else
    stat -c '%u' "${path}" 2>/dev/null
  fi
}

agent_lock_file_mode(){
  local path="$1"
  if [[ "$(uname -s)" == "Darwin" ]]; then
    stat -f '%Lp' "${path}" 2>/dev/null
  else
    stat -c '%a' "${path}" 2>/dev/null
  fi
}

verify_agent_lock_parent(){
  local lock_parent="$1"
  local current="/"
  local component=""
  local remainder="${lock_parent#/}"
  while [[ -n "${remainder}" ]]; do
    if [[ "${remainder}" == */* ]]; then
      component="${remainder%%/*}"
      remainder="${remainder#*/}"
    else
      component="${remainder}"
      remainder=""
    fi
    [[ -n "${component}" ]] || continue
    current="${current%/}/${component}"
    if [[ -L "${current}" ]]; then
      err "Agent 安装锁目录包含符号链接：${current}"
      return 1
    fi
  done
  [[ -d "${lock_parent}" && ! -L "${lock_parent}" ]] || {
    err "Agent 安装锁目录不是可信普通目录：${lock_parent}"
    return 1
  }
  local expected_uid="${REALM_AGENT_INSTALL_LOCK_EXPECTED_UID:-0}"
  if [[ "$(agent_lock_file_uid "${lock_parent}" || true)" != "${expected_uid}" ]]; then
    err "Agent 安装锁目录必须属于 uid ${expected_uid}：${lock_parent}"
    return 1
  fi
  local mode=""
  mode="$(agent_lock_file_mode "${lock_parent}" || true)"
  if [[ ! "${mode}" =~ ^[0-7]{3,4}$ ]] \
    || (( (8#${mode} & 0022) != 0 )); then
    err "Agent 安装锁目录不得由 group/other 写入：${lock_parent}"
    return 1
  fi
}

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}" ]] \
    && ! install -d -m 0700 "${lock_parent}"; then
    err "无法创建 Agent 安装锁目录：${lock_parent}"
    return 1
  fi
  verify_agent_lock_parent "${lock_parent}" || return 1
  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
  chmod 0600 "${lock_path}" || {
    err "无法收紧 Agent 安装锁权限：${lock_path}"
    return 1
  }
}

verify_agent_install_lock_inode(){
  local lock_path="$1"
  local expected_uid="${REALM_AGENT_INSTALL_LOCK_EXPECTED_UID:-0}"
  if [[ ! -f "${lock_path}" || -L "${lock_path}" ]]; then
    err "Agent 安装锁在打开时被替换：${lock_path}"
    return 1
  fi
  if [[ "$(agent_lock_file_device_inode "${lock_path}" || true)" \
    != "$(agent_lock_fd_device_inode || true)" ]]; then
    err "Agent 安装锁 device+inode 校验失败：${lock_path}"
    return 1
  fi
  if [[ "$(agent_lock_file_uid "${lock_path}" || true)" != "${expected_uid}" ]] \
    || [[ "$(agent_lock_fd_uid || true)" != "${expected_uid}" ]]; then
    err "Agent 安装锁 inode 所有权不可信：${lock_path}"
    return 1
  fi
}

acquire_nonblocking_agent_install_lock(){
  local lock_path="${1:-}"
  local lock_status="0"
  if command_exists flock; then
    flock -n -E 75 202 || lock_status="$?"
  else
    lockf -s -t 0 202 || lock_status="$?"
  fi
  if [[ "${lock_status}" == "75" ]]; then
    REALM_AGENT_INSTALL_LOCK_BUSY="1"
    exec 202>&-
    return 1
  fi
  if [[ "${lock_status}" != "0" ]]; then
    exec 202>&-
    err "非阻塞 Agent 安装锁失败（rc=${lock_status}）：${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
    [[ "${lock_path}" == "${REALM_AGENT_INSTALL_LOCK_PATH_HELD}" ]] || {
      err "同一进程不能切换 Agent 安装锁路径"
      return 1
    }
    verify_agent_install_lock_inode "${lock_path}"
    return
  fi
  if ! command_exists flock && ! command_exists lockf; then
    err "需要 flock/lockf 防止并发 Agent 安装或更新"
    return 1
  fi
  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
    acquire_nonblocking_agent_install_lock "${lock_path}" || return 1
  elif command_exists flock; then
    if ! flock 202; then
      exec 202>&-
      err "无法获取 Agent 安装/更新事务锁：${lock_path}"
      return 1
    fi
  else
    if ! lockf -s 202; then
      exec 202>&-
      err "无法获取 Agent 安装/更新事务锁：${lock_path}"
      return 1
    fi
  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(){
  [[ "${REALM_AGENT_INSTALL_LOCK_HELD:-0}" == "1" ]] || return 0
  REALM_AGENT_INSTALL_LOCK_HELD="0"
  REALM_AGENT_INSTALL_LOCK_PATH_HELD=""
  exec 202>&-
}

cleanup(){
  local exit_status=$?
  local path
  local cleanup_failed="0"
  local joint_commit_cleanup="0"
  local main_cleanup_failed="0"
  local remote_cleanup_failed="0"
  if declare -F should_recover_macos_joint_commit >/dev/null 2>&1 \
    && should_recover_macos_joint_commit; then
    joint_commit_cleanup="1"
    if ! complete_macos_joint_commit; then
      cleanup_failed="1"
      err "macOS Agent 联合提交清理未完成，已保留双方事务证据"
    fi
  fi
  if [[ "${joint_commit_cleanup}" == "0" \
      && "${REALM_MAC_DEPLOY_ROLLBACK_ACTIVE:-0}" == "1" ]] \
    && declare -F restore_macos_agent_rollback >/dev/null 2>&1; then
    if ! restore_macos_agent_rollback; then
      main_cleanup_failed="1"
      cleanup_failed="1"
      err "主 macOS Agent 恢复/提交清理未完成，已保留事务证据"
    fi
  fi
  if [[ "${joint_commit_cleanup}" == "0" \
      && "${REMOTE_COMPANION_UPDATE_PENDING:-0}" == "1" ]] \
    && declare -F rollback_remote_companion_update >/dev/null 2>&1; then
    if [[ "${main_cleanup_failed}" == "1" ]]; then
      if declare -F quiesce_remote_companion_launchagent >/dev/null 2>&1 \
        && ! quiesce_remote_companion_launchagent; then
        err "主 Agent 恢复失败后，RemoteMacAgent 也未能保持静止"
      fi
      remote_cleanup_failed="1"
      cleanup_failed="1"
      warn "主 Agent 尚未恢复，保留静止的 RemoteMacAgent 联合事务"
    else
      if ! rollback_remote_companion_update; then
        remote_cleanup_failed="1"
        cleanup_failed="1"
        err "RemoteMacAgent 恢复/提交清理未完成，保留联合事务证据"
      fi
    fi
  fi
  if [[ "${REMOTE_COMPANION_LEGACY_KEY_EXPOSED:-0}" == "1" ]] \
    && declare -F restrict_remote_companion_legacy_key >/dev/null 2>&1; then
    if ! restrict_remote_companion_legacy_key; then
      cleanup_failed="1"
      err "RemoteMacAgent legacy API key 权限收紧未完成"
    fi
  fi
  for path in "${__REALM_MAC_CLEANUP_PATHS[@]:-}"; do
    [[ -n "${path}" && ( -e "${path}" || -L "${path}" ) ]] || continue
    if [[ -n "${REALM_MAC_STAGE_DIR:-}" \
      && "${path}" == "${REALM_MAC_STAGE_DIR}" \
      && -d "${REALM_MAC_TRANSACTION_DIR:-}" ]]; then
      continue
    fi
    rm -rf "${path}" >/dev/null 2>&1 || true
  done
  release_agent_install_lock || true
  if [[ "${exit_status}" != "0" ]]; then
    return "${exit_status}"
  fi
  [[ "${cleanup_failed}" == "0" ]]
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM

usage(){
  cat <<EOF_USAGE
Usage: sudo /bin/bash -p realm_agent_macos.sh [--without-remote-control|--preserve-remote-control]

Options:
  --without-remote-control   跳过 macOS RemoteMacAgent companion 安装和启动
  --preserve-remote-control  更新主 Agent，保留现有 companion 状态不变
  --recover-only             仅恢复中断的 Agent 安装事务，不执行升级
  -h, --help                 显示帮助
EOF_USAGE
}

parse_args(){
  local arg
  for arg in "$@"; do
    case "${arg}" in
      --without-remote-control)
        REMOTE_CONTROL_ENABLED="0"
        ;;
      --preserve-remote-control)
        REMOTE_CONTROL_PRESERVE="1"
        ;;
      --recover-only)
        REALM_MAC_RECOVER_ONLY="1"
        ;;
      -h|--help)
        usage
        exit 0
        ;;
      *)
        warn "忽略未知参数：${arg}"
        ;;
    esac
  done
}

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

# compute_remote_companion_status_path <desktop_user> <desktop_home>
# 当能解析到桌面用户家目录时，返回 ~/Library/Application Support/com.realm.remote-mac-agent/status.json，
# 否则回落到 /var/lib/realm-agent/remote-mac-agent/status.json（旧路径）。
compute_remote_companion_status_path(){
  local user="${1:-}"
  local home="${2:-}"
  if [[ -n "${home}" ]]; then
    echo "${home}/Library/Application Support/com.realm.remote-mac-agent/status.json"
  else
    echo "${REMOTE_COMPANION_STATUS_LEGACY}"
  fi
}

fix_owner_mode(){
  local path="$1"
  local mode="${2:-}"
  [[ -n "${path}" ]] || return 0
  if [[ -n "${mode}" ]]; then
    chmod "${mode}" "${path}" >/dev/null 2>&1 || true
  fi
  chown root:wheel "${path}" >/dev/null 2>&1 || true
}

fix_owner_mode_strict(){
  local path="${1:-}"
  local mode="${2:-}"
  local actual=""
  [[ -n "${path}" && -e "${path}" && ! -L "${path}" ]] || return 1
  [[ -z "${mode}" ]] || chmod "${mode}" "${path}" || return 1
  chown root:wheel "${path}" || return 1
  actual="$(stat -f '%u:%g:%Lp' "${path}" 2>/dev/null || true)"
  if [[ -n "${mode}" && "${actual}" != "0:0:${mode}" ]]; then
    err "root:wheel 权限校验失败：${path}（${actual:-missing}）"
    return 1
  fi
}

publish_root_owned_regular_file(){
  local source="${1:-}"
  local target="${2:-}"
  local mode="${3:-}"
  local parent=""
  [[ -f "${source}" && ! -L "${source}" && -n "${target}" ]] || return 1
  parent="$(dirname "${target}")"
  if [[ ! -d "${parent}" || -L "${parent}" \
    || -L "${target}" || ( -e "${target}" && ! -f "${target}" ) ]]; then
    err "受管文件目标不可信：${target}"
    return 1
  fi
  fix_owner_mode_strict "${source}" "${mode}" || return 1
  fsync_path_and_parent "${source}" || return 1
  mv -f "${source}" "${target}" || return 1
  if [[ ! -f "${target}" || -L "${target}" ]]; then
    err "受管文件原子发布后状态异常：${target}"
    return 1
  fi
  fsync_path_and_parent "${target}"
}

validate_realm_env_file(){
  local path="${1:-}"
  [[ -f "${path}" && ! -L "${path}" ]] || return 1
  run_trusted_macos_python -I -S - "${path}" <<'PY'
import pathlib
import re
import shlex
import sys

path = pathlib.Path(sys.argv[1])
raw = path.read_bytes()
if len(raw) > 1024 * 1024:
    raise SystemExit("env file is too large")
text = raw.decode("utf-8", errors="strict")
key_pattern = re.compile(r"(?:REALM|AGENT)_[A-Z0-9_]+")
seen = set()
for number, raw_line in enumerate(text.splitlines(), 1):
    line = raw_line.rstrip("\r\n")
    if not line or line.lstrip().startswith("#"):
        continue
    if any(ord(char) < 32 or ord(char) == 127 for char in line):
        raise SystemExit(f"env file contains control characters at line {number}")
    if "=" not in line:
        raise SystemExit(f"env file line {number} is not KEY=VALUE")
    key, raw_value = line.split("=", 1)
    if not key_pattern.fullmatch(key) or key in seen:
        raise SystemExit(f"env file key is invalid or duplicated at line {number}")
    seen.add(key)
    if raw_value:
        values = shlex.split(raw_value, comments=False, posix=True)
        if len(values) != 1:
            raise SystemExit(f"env file value must be one value at line {number}")
PY
}

configure_macos_sshd_loopback_penalty_exemption(){
  local main_config="${1:-/etc/ssh/sshd_config}"
  local config_path="${2:-${SSHD_LOOPBACK_PENALTY_CONFIG}}"
  local sshd_bin="${3:-/usr/sbin/sshd}"
  local config_dir=""
  local tmp=""
  local previous=""
  local had_previous="0"
  local effective=""

  [[ -x "${sshd_bin}" && -f "${main_config}" ]] || return 0
  effective="$("${sshd_bin}" -T -f "${main_config}" 2>/dev/null || true)"
  if ! grep -q '^persourcepenalties ' <<< "${effective}"; then
    return 0
  fi

  config_dir="$(dirname "${config_path}")"
  if [[ -L "${config_dir}" || -L "${config_path}" ]]; then
    err "拒绝通过符号链接更新 sshd loopback 豁免：${config_path}"
    return 1
  fi
  install -d -m 755 "${config_dir}" || return 1
  if [[ -e "${config_path}" ]]; then
    previous="$(mktemp "${TMPDIR:-/private/tmp}/realm-sshd-loopback.XXXXXX")" \
      || return 1
    register_cleanup_path "${previous}"
    cp -p "${config_path}" "${previous}" || return 1
    had_previous="1"
  fi

  tmp="$(mktemp "${config_dir}/.realm-agent-loopback.XXXXXX")" || return 1
  register_cleanup_path "${tmp}"
  {
    printf '%s\n' "# Realm tunnel targets connect to sshd over loopback."
    printf '%s\n' \
      "# Do not let unauthenticated public tunnel probes penalize valid relay opens."
    printf '%s\n' "PerSourcePenaltyExemptList 127.0.0.1,::1"
  } > "${tmp}"
  fix_owner_mode "${tmp}" 644
  mv -f "${tmp}" "${config_path}" || return 1

  effective="$("${sshd_bin}" -T -f "${main_config}" 2>/dev/null || true)"
  if ! "${sshd_bin}" -t -f "${main_config}" >/dev/null 2>&1 \
    || ! grep -Eq \
      '^persourcepenaltyexemptlist .*127\.0\.0\.1.*::1' \
      <<< "${effective}"; then
    if [[ "${had_previous}" == "1" ]]; then
      cp -p "${previous}" "${config_path}" || true
    else
      rm -f "${config_path}" >/dev/null 2>&1 || true
    fi
    err "sshd loopback 豁免校验失败，已恢复原配置"
    return 1
  fi

  ok "已豁免 sshd loopback 源处罚，避免公网隧道探测误伤正常登录"
}

prepare_log_path(){
  local path="${1:-}"
  local parent=""
  [[ -n "${path}" ]] || return 0
  parent="$(dirname "${path}")"
  [[ -d "${parent}" && ! -L "${parent}" ]] || {
    err "日志目录不是可信普通目录：${parent}"
    return 1
  }
  if [[ -L "${path}" || ( -e "${path}" && ! -f "${path}" ) ]]; then
    err "日志路径不是可信普通文件：${path}"
    return 1
  fi
  : >> "${path}" || {
    err "无法创建或写入日志文件：${path}"
    return 1
  }
  chmod 600 "${path}" || return 1
  chown root:wheel "${path}" || return 1
}

prepare_log_paths(){
  local path=""
  for path in "$@"; do
    prepare_log_path "${path}" || return 1
  done
}

retire_legacy_macos_log_file(){
  local path="${1:-}"
  [[ -n "${path}" ]] || return 0
  [[ -e "${path}" || -L "${path}" ]] || return 0
  if [[ -L "${path}" || ! -f "${path}" ]]; then
    err "拒绝删除非普通 legacy 日志：${path}"
    return 1
  fi
  rm -f -- "${path}" || return 1
  [[ ! -e "${path}" && ! -L "${path}" ]] || return 1
}

retire_legacy_macos_logs(){
  local desktop_user=""
  local desktop_home=""
  local path=""
  local -a paths=(
    /var/log/realm-agent.log
    /var/log/realm-agent.error.log
    /var/log/realm-agent-mptcp-sidecar.log
    /var/log/realm-agent-mptcp-sidecar.error.log
  )
  desktop_user="$(console_user || true)"
  desktop_home="$(console_home "${desktop_user}" || true)"
  if [[ -n "${desktop_home}" ]]; then
    if [[ "${REMOTE_COMPANION_LOGS_RETIRE_ALLOWED:-0}" == "1" ]]; then
      paths+=(
        "${desktop_home}/Library/Logs/realm-remote-mac-agent.log"
        "${desktop_home}/Library/Logs/realm-remote-mac-agent.error.log"
      )
    fi
  fi
  for path in "${paths[@]}"; do
    retire_legacy_macos_log_file "${path}" || return 1
  done
}

clear_quarantine_flag(){
  local path="$1"
  [[ -n "${path}" ]] || return 0
  if ! command_exists xattr; then
    return 0
  fi
  if [[ -e "${path}" ]]; then
    xattr -d com.apple.quarantine "${path}" >/dev/null 2>&1 || true
  fi
}

normalize_remote_companion_bundle_permissions(){
  local bundle="${1:-}"
  local executable=""
  [[ -d "${bundle}" && ! -L "${bundle}" ]] || {
    err "RemoteMacAgent bundle 不是可信普通目录：${bundle}"
    return 1
  }
  # Make copied app bundles traversable and executable for the logged-in user.
  chmod -R a+rX "${bundle}" || return 1
  chmod -R go-w "${bundle}" || return 1
  executable="$(remote_companion_app_executable "${bundle}" || true)"
  if [[ -z "${executable}" || ! -f "${executable}" \
        || -L "${executable}" || ! -x "${executable}" ]]; then
    err "RemoteMacAgent 主程序权限无效：${executable:-missing}"
    return 1
  fi
}

verify_remote_companion_executable_for_user(){
  local desktop_user="${1:-}"
  local executable="${2:-}"
  local desktop_uid="${3:-}"
  local desktop_gid="${4:-}"
  local desktop_group="${5:-}"
  local quoted=""
  [[ -n "${desktop_user}" && -f "${executable}" \
      && ! -L "${executable}" ]] || return 1
  remote_companion_desktop_identity_matches \
    "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
    "${desktop_group}" || return 1
  if [[ -x /usr/bin/sudo ]]; then
    /usr/bin/sudo -u "#${desktop_uid}" -H /bin/test -x "${executable}" \
      || return 1
    remote_companion_desktop_identity_matches \
      "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
      "${desktop_group}"
    return
  fi
  if [[ -x /usr/bin/su ]]; then
    printf -v quoted '%q' "${executable}"
    /usr/bin/su -m "${desktop_user}" \
      -c "/bin/test -x ${quoted}" || return 1
    remote_companion_desktop_identity_matches \
      "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
      "${desktop_group}"
    return
  fi
  err "缺少 sudo/su，无法以桌面用户验证 RemoteMacAgent 执行权限"
  return 1
}

verify_remote_companion_path_for_user(){
  local desktop_user="${1:-}"
  local operator="${2:-}"
  local path="${3:-}"
  local desktop_uid="${4:-}"
  local desktop_gid="${5:-}"
  local desktop_group="${6:-}"
  local quoted=""
  [[ -n "${desktop_user}" \
    && ( "${operator}" == "-r" || "${operator}" == "-x" ) \
    && -n "${path}" ]] || return 1
  remote_companion_desktop_identity_matches \
    "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
    "${desktop_group}" || return 1
  if [[ -x /usr/bin/sudo ]]; then
    /usr/bin/sudo -u "#${desktop_uid}" -H /bin/test \
      "${operator}" "${path}" || return 1
    remote_companion_desktop_identity_matches \
      "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
      "${desktop_group}"
    return
  fi
  if [[ -x /usr/bin/su ]]; then
    printf -v quoted '%q' "${path}"
    /usr/bin/su -m "${desktop_user}" \
      -c "/bin/test ${operator} ${quoted}" || return 1
    remote_companion_desktop_identity_matches \
      "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
      "${desktop_group}"
    return
  fi
  err "缺少 sudo/su，无法验证 RemoteMacAgent 用户路径权限"
  return 1
}

remote_companion_app_path_allowed(){
  local app_path="${1:-}"
  local desktop_home="${2:-}"
  canonical_remote_companion_app_path \
    "${app_path}" "${desktop_home}" >/dev/null
}

canonical_remote_companion_app_path(){
  local app_path="${1:-}"
  local desktop_home="${2:-}"
  local default_path=""
  local canonical=""
  [[ -n "${app_path}" && "${app_path}" == */RemoteMacAgent.app ]] || return 1
  default_path="$(
    canonical_macos_transaction_path \
      "${BASE_DIR}/RemoteMacAgent.app" "${BASE_DIR}" "strict" || true
  )"
  if [[ -n "${default_path}" \
    && ( "${app_path}" == "${BASE_DIR}/RemoteMacAgent.app" \
      || "${app_path}" == "${default_path}" ) ]]; then
    printf '%s\n' "${default_path}"
    return 0
  fi
  [[ -n "${desktop_home}" ]] || return 1
  canonical="$(
    canonical_macos_transaction_path \
      "${app_path}" "${desktop_home}/Applications" "strict" || true
  )"
  [[ -n "${canonical}" \
    && "$(basename "${canonical}")" == "RemoteMacAgent.app" ]] || return 1
  printf '%s\n' "${canonical}"
}

remote_companion_app_path_is_user_owned(){
  [[ "$(remote_companion_app_owner_kind "${1:-}" "${2:-}" || true)" == "user" ]]
}

remote_companion_app_owner_kind(){
  local app_path="${1:-}"
  local desktop_home="${2:-}"
  local canonical=""
  local default_path=""
  default_path="$(
    canonical_macos_transaction_path \
      "${BASE_DIR}/RemoteMacAgent.app" "${BASE_DIR}" "strict" || true
  )"
  if [[ -n "${default_path}" && "${app_path}" == "${default_path}" ]]; then
    printf 'root\n'
    return 0
  fi
  [[ -n "${desktop_home}" ]] || return 1
  canonical="$(
    canonical_remote_companion_app_path \
      "${app_path}" "${desktop_home}" || true
  )"
  [[ -n "${canonical}" \
    && "${canonical}" == "${app_path}" ]] || return 1
  printf 'user\n'
}

existing_remote_companion_launchagent_app_path(){
  local desktop_home="${1:-}"
  local plist="${desktop_home}/Library/LaunchAgents/${REMOTE_COMPANION_LABEL}.plist"
  local found=""
  [[ -n "${desktop_home}" && -f "${plist}" ]] || return 1
  if [[ -x /usr/libexec/PlistBuddy ]]; then
    found="$(/usr/libexec/PlistBuddy -c "Print :ProgramArguments" "${plist}" 2>/dev/null | awk -F'= ' '/RemoteMacAgent\.app(\/Contents\/MacOS\/RemoteMacAgent)?[[:space:]]*$/ {print $2; exit}' || true)"
  fi
  if [[ -z "${found}" ]]; then
    found="$(awk '/<string>.*RemoteMacAgent\.app(\/Contents\/MacOS\/RemoteMacAgent)?<\/string>/ {gsub(/^.*<string>|<\/string>.*$/, ""); print; exit}' "${plist}" 2>/dev/null || true)"
  fi
  found="${found%/Contents/MacOS/RemoteMacAgent}"
  [[ -n "${found}" ]] || return 1
  printf '%s\n' "${found}"
}

select_remote_companion_app_path(){
  local desktop_home="${1:-}"
  local existing=""
  local canonical=""
  existing="$(existing_remote_companion_launchagent_app_path "${desktop_home}" || true)"
  canonical="$(
    canonical_remote_companion_app_path \
      "${existing}" "${desktop_home}" || true
  )"
  if [[ -z "${canonical}" ]]; then
    canonical="$(
      canonical_remote_companion_app_path \
        "${BASE_DIR}/RemoteMacAgent.app" "${desktop_home}" || true
    )"
  fi
  [[ -n "${canonical}" ]] || return 1
  printf '%s\n' "${canonical}"
}

retire_stale_remote_companion_status_files(){
  local active="${1:-}"
  local desktop_home="${2:-}"
  local candidate
  for candidate in \
    "${REMOTE_COMPANION_STATUS_LEGACY}" \
    "${desktop_home}/Library/Application Support/com.realm.remote-mac-agent/status.json"; do
    [[ "${candidate}" != "${active}" ]] || continue
    [[ -n "${candidate}" && ( -f "${candidate}" || -L "${candidate}" ) ]] || continue
    mv -f "${candidate}" "${candidate}.stale" >/dev/null 2>&1 || true
  done
}

prepare_remote_companion_status_dir(){
  local desktop_user="${1:-}"
  local desktop_group="${2:-}"
  local status_path="${3:-${REMOTE_COMPANION_STATUS}}"
  local desktop_uid="${4:-}"
  local desktop_gid="${5:-}"
  local status_dir

  remote_companion_desktop_identity_matches \
    "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
    "${desktop_group}" || return 1
  status_dir="$(dirname "${status_path}")"
  install -d -m 700 "${status_dir}" || return 1
  fix_user_mode_strict \
    "${status_dir}" 700 "${desktop_user}" "${desktop_group}" \
    "${desktop_uid}" "${desktop_gid}"
}

prepare_remote_companion_status_file(){
  local status_path="${1:-${REMOTE_COMPANION_STATUS}}"
  local status_dir status_tmp stale_path
  [[ -n "${status_path}" ]] || return 1

  status_dir="$(dirname "${status_path}")"
  status_tmp="${status_dir}/.$(basename "${status_path}").tmp"
  stale_path="${status_path}.stale"

  if [[ -e "${status_path}" || -L "${status_path}" ]]; then
    if [[ -e "${stale_path}" || -L "${stale_path}" ]]; then
      stale_path="${stale_path}.$(date +%s).$$"
    fi
    if ! mv "${status_path}" "${stale_path}" >/dev/null 2>&1; then
      warn "无法归档旧 RemoteMacAgent 状态文件：${status_path}"
      return 1
    fi
    info "已归档旧 RemoteMacAgent 状态文件：${stale_path}"
  fi

  if [[ -e "${status_tmp}" || -L "${status_tmp}" ]]; then
    if ! rm -f -- "${status_tmp}" >/dev/null 2>&1; then
      warn "无法清理 RemoteMacAgent 临时状态文件：${status_tmp}"
      return 1
    fi
  fi
  return 0
}

sanitize_launchdaemon_payload(){
  local plist="$1"
  local program_path="${2:-}"
  install -d -m 755 /Library/LaunchDaemons >/dev/null 2>&1 || true
  [[ -n "${plist}" ]] || return 0
  if [[ -f "${plist}" ]]; then
    fix_owner_mode "${plist}" 644
    clear_quarantine_flag "${plist}"
    local plist_dir
    plist_dir="$(dirname "${plist}")"
    chmod 755 "${plist_dir}" >/dev/null 2>&1 || true
    chown root:wheel "${plist_dir}" >/dev/null 2>&1 || true
  fi
  if [[ -n "${program_path}" && -e "${program_path}" ]]; then
    chmod 755 "${program_path}" >/dev/null 2>&1 || true
    chown root:wheel "${program_path}" >/dev/null 2>&1 || true
    clear_quarantine_flag "${program_path}"
  fi
}

validate_plist_file(){
  local plist="$1"
  [[ -f "${plist}" ]] || { err "找不到 launchd plist：${plist}"; return 1; }
  if command_exists plutil; then
    if ! plutil -lint "${plist}" >/dev/null 2>&1; then
      err "launchd plist 格式错误：${plist}"
      plutil -lint "${plist}" >&2 || true
      return 1
    fi
  fi
  return 0
}

console_uid(){
  local uid=""
  uid="$(stat -f %u /dev/console 2>/dev/null || true)"
  if [[ "${uid}" =~ ^[0-9]+$ ]]; then
    echo "${uid}"
    return 0
  fi
  return 1
}

console_user(){
  local name=""
  name="$(stat -f %Su /dev/console 2>/dev/null || true)"
  name="${name//[[:space:]]/}"
  if [[ -n "${name}" && "${name}" != "root" && "${name}" != "loginwindow" && "${name}" != "_mbsetupuser" ]]; then
    echo "${name}"
    return 0
  fi
  if command_exists scutil; then
    name="$(scutil show State:/Users/ConsoleUser 2>/dev/null | awk -F': *' '/Name[[:space:]]*:/ {print $2; exit}' || true)"
    name="${name//[[:space:]]/}"
    if [[ -n "${name}" && "${name}" != "root" && "${name}" != "loginwindow" && "${name}" != "_mbsetupuser" ]]; then
      echo "${name}"
      return 0
    fi
  fi
  if command_exists who; then
    name="$(who 2>/dev/null | awk '$2=="console"{print $1; exit}' || true)"
    name="${name//[[:space:]]/}"
    if [[ -n "${name}" && "${name}" != "root" ]]; then
      echo "${name}"
      return 0
    fi
  fi
  return 1
}

console_home(){
  local user="${1:-}"
  local home=""
  if [[ -n "${user}" && -d "/Users/${user}" ]]; then
    echo "/Users/${user}"
    return 0
  fi
  if [[ -n "${user}" ]]; then
    home="$(dscl . -read "/Users/${user}" NFSHomeDirectory 2>/dev/null | awk '{print $2; exit}' || true)"
    if [[ -n "${home}" && -d "${home}" ]]; then
      echo "${home}"
      return 0
    fi
  fi
  return 1
}

user_primary_group(){
  local user="${1:-}"
  local group=""
  if [[ -n "${user}" ]]; then
    group="$(id -gn "${user}" 2>/dev/null || true)"
  fi
  if [[ -n "${group}" ]]; then
    echo "${group}"
  else
    echo "staff"
  fi
}

fix_user_mode(){
  local path="$1"
  local mode="${2:-}"
  local user="${3:-}"
  local group="${4:-}"
  [[ -n "${path}" ]] || return 0
  if [[ -n "${mode}" ]]; then
    chmod "${mode}" "${path}" >/dev/null 2>&1 || true
  fi
  if [[ -n "${user}" ]]; then
    if [[ -n "${group}" ]]; then
      chown "${user}:${group}" "${path}" >/dev/null 2>&1 || true
    else
      chown "${user}" "${path}" >/dev/null 2>&1 || true
    fi
  fi
}

fix_user_mode_strict(){
  local path="${1:-}"
  local mode="${2:-}"
  local user="${3:-}"
  local group="${4:-}"
  local expected_uid="${5:-}"
  local expected_gid="${6:-}"
  local current_uid=""
  local current_gid=""
  local current_group=""
  local actual=""
  [[ -n "${path}" && -n "${user}" && -e "${path}" && ! -L "${path}" ]] \
    || return 1
  current_uid="$(id -u "${user}" 2>/dev/null)" || return 1
  current_gid="$(id -g "${user}" 2>/dev/null)" || return 1
  current_group="$(id -gn "${user}" 2>/dev/null)" || return 1
  [[ -n "${expected_uid}" ]] || expected_uid="${current_uid}"
  [[ -n "${expected_gid}" ]] || expected_gid="${current_gid}"
  [[ "${expected_uid}" =~ ^[0-9]+$ \
    && "${expected_gid}" =~ ^[0-9]+$ \
    && "${current_uid}" == "${expected_uid}" \
    && "${current_gid}" == "${expected_gid}" \
    && ( -z "${group}" || "${current_group}" == "${group}" ) ]] || return 1
  [[ -z "${mode}" ]] || chmod "${mode}" "${path}" || return 1
  chown "${expected_uid}:${expected_gid}" "${path}" || return 1
  actual="$(stat -f '%u:%g:%Lp' "${path}" 2>/dev/null || true)"
  if [[ -n "${mode}" \
    && "${actual}" != "${expected_uid}:${expected_gid}:${mode}" ]]; then
    err "用户路径权限校验失败：${path}（${actual:-missing}）"
    return 1
  fi
}

verify_path_owner(){
  local path="${1:-}"
  local user="${2:-}"
  local expected_uid="${3:-}"
  local expected_gid="${4:-}"
  local current_uid=""
  local current_gid=""
  local actual=""
  [[ -n "${path}" && -n "${user}" && -e "${path}" && ! -L "${path}" ]] \
    || return 1
  current_uid="$(id -u "${user}" 2>/dev/null)" || return 1
  current_gid="$(id -g "${user}" 2>/dev/null)" || return 1
  [[ -n "${expected_uid}" ]] || expected_uid="${current_uid}"
  [[ -n "${expected_gid}" ]] || expected_gid="${current_gid}"
  [[ "${current_uid}" == "${expected_uid}" \
    && "${current_gid}" == "${expected_gid}" ]] || return 1
  actual="$(stat -f '%u:%g' "${path}" 2>/dev/null || true)"
  [[ "${actual}" == "${expected_uid}:${expected_gid}" ]] || {
    err "路径所有者校验失败：${path}（uid:gid=${actual:-missing}）"
    return 1
  }
}
bootstrap_launchdaemon(){
  local label="$1"
  local plist="$2"
  local program_path="${3:-}"

  [[ -n "${label}" ]] || { err "launchd label 不能为空"; return 1; }
  [[ -n "${plist}" ]] || { err "launchd plist 路径不能为空"; return 1; }
  if ! command_exists launchctl; then
    err "系统缺少 launchctl，无法托管服务"
    return 1
  fi

  sanitize_launchdaemon_payload "${plist}" "${program_path}"
  validate_plist_file "${plist}" || return 1
  if [[ -n "${program_path}" && ! -x "${program_path}" ]]; then
    err "启动程序不可执行：${program_path}"
    return 1
  fi

  local targets=("system/${label}" "${label}")
  local cuid=""
  cuid="$(console_uid || true)"
  if [[ -n "${cuid}" ]]; then
    targets+=("gui/${cuid}/${label}" "user/${cuid}/${label}")
  fi

  local t out="" boot_ok=0
  local attempt=1
  while (( attempt <= 4 )); do
    for t in "${targets[@]}"; do
      launchctl bootout "${t}" >/dev/null 2>&1 || true
    done
    launchctl bootout system "${plist}" >/dev/null 2>&1 || true
    launchctl remove "${label}" >/dev/null 2>&1 || true
    if launchctl print "system/${label}" >/dev/null 2>&1; then
      sleep 1
      attempt=$((attempt + 1))
      continue
    fi
    sanitize_launchdaemon_payload "${plist}" "${program_path}"
    if out="$(launchctl bootstrap system "${plist}" 2>&1)"; then
      boot_ok=1
      break
    fi
    if (( attempt >= 3 )); then
      if out="$(launchctl load -w "${plist}" 2>&1)"; then
        boot_ok=1
        break
      fi
    fi
    sleep 1
    attempt=$((attempt + 1))
  done
  if [[ "${boot_ok}" != "1" ]]; then
    err "launchctl bootstrap 失败（${label}）：${out}"
    launchctl print "system/${label}" >/dev/null 2>&1 || true
    return 1
  fi

  if ! out="$(launchctl enable "system/${label}" 2>&1)"; then
    err "launchctl enable 失败（${label}）：${out}"
    return 1
  fi
  # bootstrap + RunAtLoad may already be starting the service. Avoid -k here,
  # which can race the fresh listener teardown against its replacement.
  if ! out="$(launchctl kickstart "system/${label}" 2>&1)"; then
    if launchctl print "system/${label}" >/dev/null 2>&1; then
      warn "launchctl kickstart 返回失败但服务已 loaded（${label}）：${out}"
    else
      err "launchctl kickstart 失败（${label}）：${out}"
      return 1
    fi
  fi
  if ! launchctl print "system/${label}" >/dev/null 2>&1; then
    err "launchd bootstrap 后服务未 loaded：${label}"
    return 1
  fi
  return 0
}

macos_launchd_job_pid(){
  local target="${1:-}"
  local output=""
  local pid=""
  [[ -n "${target}" ]] || return 1
  output="$(launchctl print "${target}" 2>/dev/null)" || return 1
  pid="$(
    printf '%s\n' "${output}" \
      | awk '$1 == "pid" && $2 == "=" && $3 ~ /^[0-9]+$/ {
          print $3
          exit
        }'
  )"
  [[ "${pid}" =~ ^[0-9]+$ ]] || return 1
  printf '%s\n' "${pid}"
}

macos_process_command_line(){
  local pid="${1:-}"
  local command_line=""
  [[ "${pid}" =~ ^[0-9]+$ ]] || return 1
  command_line="$(ps -ww -p "${pid}" -o command= 2>/dev/null || true)"
  command_line="${command_line#"${command_line%%[![:space:]]*}"}"
  command_line="${command_line%"${command_line##*[![:space:]]}"}"
  [[ -n "${command_line}" ]] || return 1
  printf '%s\n' "${command_line}"
}

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

ensure_macos(){
  if [[ "$(uname -s)" != "Darwin" ]]; then
    err "该安装脚本仅支持 macOS"
    exit 1
  fi
}

find_brew(){
  if command_exists brew; then
    command -v brew
    return 0
  fi
  if [[ -x /opt/homebrew/bin/brew ]]; then
    echo "/opt/homebrew/bin/brew"
    return 0
  fi
  if [[ -x /usr/local/bin/brew ]]; then
    echo "/usr/local/bin/brew"
    return 0
  fi
  return 1
}

run_brew(){
  local brew_bin
  brew_bin="$(find_brew || true)"
  if [[ -z "${brew_bin}" ]]; then
    return 127
  fi
  local run_user="${SUDO_USER:-}"
  if [[ "$(id -u)" -eq 0 ]]; then
    if [[ -z "${run_user}" || "${run_user}" == "root" ]]; then
      run_user="$(stat -f %Su "${brew_bin}" 2>/dev/null || true)"
    fi
    if [[ -n "${run_user}" && "${run_user}" != "root" ]]; then
      if [[ -x /usr/bin/sudo ]]; then
        /usr/bin/sudo -u "${run_user}" -H "${brew_bin}" "$@"
        return $?
      fi
      err "当前为 root，且缺少 sudo，无法以普通用户执行 brew"
      return 126
    fi
    err "当前为 root，无法确定可用的 brew 用户（可设置 SUDO_USER）"
    return 126
  fi
  "${brew_bin}" "$@"
}

validate_root_owned_macos_python(){
  local candidate="${1:-}"
  local current=""
  local component=""
  local remainder=""
  local metadata=""
  local uid=""
  local mode=""
  local kind=""
  [[ "${candidate}" == /* && -x "${candidate}" && ! -L "${candidate}" ]] \
    || return 1
  remainder="${candidate#/}"
  while [[ -n "${remainder}" ]]; do
    if [[ "${remainder}" == */* ]]; then
      component="${remainder%%/*}"
      remainder="${remainder#*/}"
    else
      component="${remainder}"
      remainder=""
    fi
    case "${component}" in
      ""|"."|"..") return 1 ;;
    esac
    current="${current}/${component}"
    metadata="$(/usr/bin/stat -f '%u:%Lp:%HT' "${current}" 2>/dev/null)" \
      || return 1
    IFS=: read -r uid mode kind <<< "${metadata}"
    [[ "${uid}" == "0" && "${mode}" =~ ^[0-7]{3,4}$ ]] || return 1
    (( (8#${mode} & 0022) == 0 )) || return 1
    if [[ -n "${remainder}" ]]; then
      [[ "${kind}" == "Directory" && ! -L "${current}" ]] || return 1
    else
      [[ "${kind}" == "Regular File" && -x "${current}" \
        && ! -L "${current}" ]] || return 1
    fi
  done
}

probe_macos_python_candidate(){
  local candidate="${1:-}"
  local nonce=""
  local output=""
  local output_file=""
  [[ -n "${candidate}" ]] || return 1
  nonce="${BASHPID:-$$}-${RANDOM}-${RANDOM}-${SECONDS}"
  output_file="$(
    /usr/bin/mktemp /private/tmp/realm-agent-python-probe.XXXXXX
  )" || return 1
  if ! /usr/bin/env -i \
    PATH=/usr/bin:/bin:/usr/sbin:/sbin \
    HOME=/var/root \
    /bin/bash -p -c '
      set -euo pipefail
      output_file="$1"
      shift
      ulimit -f 1
      "$@" > "${output_file}" 2>/dev/null &
      candidate_pid=$!
      waited=0
      while /bin/kill -0 "${candidate_pid}" >/dev/null 2>&1; do
        if (( waited >= 50 )); then
          /bin/kill -TERM "${candidate_pid}" >/dev/null 2>&1 || true
          /bin/sleep 1
          /bin/kill -KILL "${candidate_pid}" >/dev/null 2>&1 || true
          wait "${candidate_pid}" >/dev/null 2>&1 || true
          exit 124
        fi
        /bin/sleep 0.1
        waited=$((waited + 1))
      done
      wait "${candidate_pid}"
    ' realm-agent-python-probe \
      "${output_file}" \
      "${candidate}" -I -S -B -c \
      'import platform, ssl, sys, venv
if platform.python_implementation() != "CPython" or sys.version_info < (3, 9):
    raise SystemExit(1)
sys.stdout.write(f"NEXUS_MAC_PYTHON_PROBE:{sys.argv[1]}:CPython")' \
      "${nonce}"; then
    /bin/rm -f "${output_file}"
    return 1
  fi
  output="$(<"${output_file}")"
  /bin/rm -f "${output_file}"
  [[ "${output}" == "NEXUS_MAC_PYTHON_PROBE:${nonce}:CPython" ]]
}

trusted_macos_agent_python(){
  local candidate=""
  for candidate in \
    "${REALM_AGENT_PYTHON_BIN:-}" \
    /usr/bin/python3 \
    /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.13/bin/python3.13 \
    /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.12/bin/python3.12 \
    /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.11/bin/python3.11 \
    /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.10/bin/python3.10 \
    /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/bin/python3.9; do
    [[ -n "${candidate}" ]] || continue
    validate_root_owned_macos_python "${candidate}" || continue
    if probe_macos_python_candidate "${candidate}"; then
      printf '%s\n' "${candidate}"
      return 0
    fi
  done
  return 1
}

ensure_trusted_macos_agent_python(){
  local selected=""
  if [[ -n "${MAC_TRUSTED_PYTHON_BIN:-}" ]] \
    && validate_root_owned_macos_python "${MAC_TRUSTED_PYTHON_BIN}"; then
    return 0
  fi
  MAC_TRUSTED_PYTHON_BIN=""
  selected="$(trusted_macos_agent_python || true)"
  [[ -n "${selected}" ]] || return 1
  MAC_TRUSTED_PYTHON_BIN="${selected}"
}

run_isolated_macos_python(){
  local python_bin="${1:-}"
  [[ -x "${python_bin}" ]] || return 127
  /usr/bin/env -i \
    PATH=/usr/bin:/bin:/usr/sbin:/sbin \
    HOME=/var/root \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONNOUSERSITE=1 \
    "${python_bin}" -I -S -B "${@:2}"
}

run_trusted_macos_python(){
  if ! ensure_trusted_macos_agent_python; then
    err "缺少受信任且由 root 管理的 macOS Python 3.9+"
    return 127
  fi
  run_isolated_macos_python "${MAC_TRUSTED_PYTHON_BIN}" "$@"
}

ensure_python_runtime(){
  ensure_trusted_macos_agent_python
}

ensure_deps(){
  local missing=()
  command_exists curl || missing+=("curl")
  command_exists unzip || missing+=("unzip")
  command_exists jq || missing+=("jq")
  command_exists rsync || missing+=("rsync")
  command_exists openssl || missing+=("openssl")
  if ! ensure_python_runtime; then
    missing+=("python")
    err "需要 Apple/CommandLineTools 的 root-owned CPython 3.9+，或显式设置 REALM_AGENT_PYTHON_BIN 为 root-owned 非符号链接解释器"
  fi

  if [[ ${#missing[@]} -eq 0 ]]; then
    ok "依赖已满足，跳过安装"
    return 0
  fi

  err "缺少安装依赖：${missing[*]}"
  err "安装器不会自动执行 Homebrew latest 安装；请由受管部署预先固定并安装依赖"
  exit 1
}

normalize_port(){
  local p="${1:-}"
  if [[ "$p" =~ ^[0-9]+$ ]] && (( p >= 1 && p <= 65535 )); then
    echo "$p"
  else
    echo "$DEFAULT_PORT"
  fi
}

# 仅当进程命令行属于 realm agent 安装目录时才视为受管进程；
# 防止端口冲突或更新重启时误杀同端口/同路径的用户进程。
# 同时匹配直接执行与经解释器启动（如 /usr/bin/env bash start.sh）的进程：
# ps 输出的 command 可能以解释器路径/参数开头。
macos_process_cwd(){
  local pid="${1:-}"
  local cwd=""
  [[ "${pid}" =~ ^[0-9]+$ ]] || return 1
  command_exists lsof || return 1
  cwd="$(
    lsof -a -p "${pid}" -d cwd -Fn 2>/dev/null \
      | awk '/^n/ {sub(/^n/, ""); print; exit}' || true
  )"
  [[ -n "${cwd}" ]] || return 1
  printf '%s\n' "${cwd}"
}

is_realm_agent_process(){
  local pid="$1"
  local command_line=""
  local base_dir_regex=""
  local process_cwd=""
  [[ "${pid}" =~ ^[0-9]+$ ]] || return 1
  command_line="$(ps -p "${pid}" -o command= 2>/dev/null || true)"
  [[ -n "${command_line}" ]] || return 1
  base_dir_regex="$(escape_ere_literal "${BASE_DIR}")"
  if [[ "${command_line}" =~ ^${base_dir_regex}/(start\.sh|mptcp_sidecar\.sh|revtunnel\.sh)([[:space:]]|$) ]]; then
    return 0
  fi
  if [[ "${command_line}" =~ ^${base_dir_regex}/venv/bin/[^[:space:]]+([[:space:]]|$) ]]; then
    return 0
  fi
  if [[ "${command_line}" =~ ^(/usr/bin/env[[:space:]]+)?((/usr)?/bin/)?(bash|sh)[[:space:]]+${base_dir_regex}/(start\.sh|mptcp_sidecar\.sh|revtunnel\.sh)([[:space:]]|$) ]]; then
    return 0
  fi
  if [[ "${command_line}" =~ (^|[[:space:]])-m[[:space:]]+uvicorn[[:space:]]+agent\.app\.main:app([[:space:]]|$) ]]; then
    process_cwd="$(macos_process_cwd "${pid}" || true)"
    if [[ "${process_cwd}" == "${BASE_DIR}/agent" ]]; then
      return 0
    fi
  fi
  return 1
}

# 将路径转义为 ERE 字面量（pkill -f 使用 ERE），
# 避免 BASE_DIR 含正则元字符时匹配失效或误匹配。
escape_ere_literal(){
  local s="${1:-}"
  local out=""
  local ch=""
  local i=""
  for ((i = 0; i < ${#s}; i++)); do
    ch="${s:i:1}"
    case "${ch}" in
      ']'|'[') out+="\\${ch}" ;;
      '.'|'^'|'$'|'*'|'+'|'?'|'('|')'|'{'|'}'|'|'|'\') out+="\\${ch}" ;;
      *) out+="${ch}" ;;
    esac
  done
  printf '%s' "${out}"
}

# 将字符串转义为 XML 文本安全形式（launchd plist 是 XML 文档，
# 路径/标签含 & < > " ' 时 plutil 会拒绝解析）。
# 注意 ${s//pat/repl} 会把替换串中的 & 替换为匹配文本，必须写 \& 取字面。
xml_escape(){
  local s="${1:-}"
  s="${s//&/\&amp;}"
  s="${s//</\&lt;}"
  s="${s//>/\&gt;}"
  s="${s//\"/\&quot;}"
  s="${s//\'/\&apos;}"
  printf '%s' "${s}"
}

kill_agent_listener_on_port(){
  local port="$1"
  local pids=""
  local pid=""
  local pid_to_kill=""
  local -a candidate_pids=()
  [[ "${port}" =~ ^[0-9]+$ ]] || return 0
  if command_exists lsof; then
    pids="$(lsof -tiTCP:"${port}" -sTCP:LISTEN 2>/dev/null | awk '!seen[$0]++' || true)"
  fi
  if [[ -z "${pids}" ]] && command_exists netstat; then
    pids="$(netstat -anv -p tcp 2>/dev/null | awk -v port="${port}" '
      function local_port_matches(addr) {
        return addr ~ ("(^|[.:])" port "$")
      }
      {
        is_listen = 0
        for (i = 1; i <= NF; i++) {
          if ($i == "LISTEN") {
            is_listen = 1
            break
          }
        }
        if (!is_listen) {
          next
        }
        local_idx = 0
        for (i = 1; i <= NF; i++) {
          if (local_port_matches($i)) {
            local_idx = i
            break
          }
        }
        if (!local_idx) {
          next
        }
        # process:pid 单元格自描述（形如 "name:123"），
        # 不依赖列偏移或表头对齐（表头多词列会破坏列号映射）。
        for (i = 1; i <= NF; i++) {
          if ($i ~ /^[^:[:space:]]+:[0-9]+$/ && !seen[$i]++) {
            sub(/^.*:/, "", $i)
            if ($i > 0) {
              print $i
            }
          }
        }
      }
    ' || true)"
  fi
  while IFS= read -r pid; do
    [[ "${pid}" =~ ^[0-9]+$ ]] || continue
    if [[ "${pid}" == "$$" ]]; then
      continue
    fi
    if ! is_realm_agent_process "${pid}"; then
      warn "端口 ${port} 被非 realm agent 进程占用，已跳过：pid=${pid}"
      continue
    fi
    candidate_pids+=("${pid}")
  done <<< "${pids}"
  if (( ${#candidate_pids[@]} == 0 )); then
    return 0
  fi
  for pid_to_kill in "${candidate_pids[@]}"; do
    kill "${pid_to_kill}" >/dev/null 2>&1 || true
  done
  sleep 1
  for pid_to_kill in "${candidate_pids[@]}"; do
    if kill -0 "${pid_to_kill}" >/dev/null 2>&1; then
      kill -9 "${pid_to_kill}" >/dev/null 2>&1 || true
    fi
  done
}

managed_macos_agent_pids(){
  local port="${1:-}"
  local base_dir_regex=""
  local candidates=""
  local pid=""
  local pid_file="/var/run/realm-agent.pid"
  if [[ -f "${pid_file}" && ! -L "${pid_file}" ]]; then
    candidates+="$(head -n 1 "${pid_file}" 2>/dev/null || true)"$'\n'
  fi
  if [[ "${port}" =~ ^[0-9]+$ ]] && command_exists lsof; then
    candidates+="$(lsof -tiTCP:"${port}" -sTCP:LISTEN 2>/dev/null \
      || true)"$'\n'
  fi
  if command_exists pgrep; then
    base_dir_regex="$(escape_ere_literal "${BASE_DIR}")"
    candidates+="$(pgrep -f \
      "^(${base_dir_regex}/(start\\.sh|venv/bin/[^[:space:]]+)|(/usr/bin/env[[:space:]]+)?((/usr)?/bin/)?(bash|sh)[[:space:]]+${base_dir_regex}/start\\.sh)([[:space:]]|$)" \
      2>/dev/null || true)"$'\n'
  fi
  while IFS= read -r pid; do
    [[ "${pid}" =~ ^[0-9]+$ && "${pid}" != "$$" ]] || continue
    if is_realm_agent_process "${pid}"; then
      printf '%s\n' "${pid}"
    fi
  done <<< "${candidates}" | awk '!seen[$0]++'
}

terminate_macos_agent_processes(){
  local port="${1:-}"
  local pid=""
  local agent_user="root"
  local base_dir_regex=""
  local start_command_regex=""
  local -a pids=()
  if command_exists id && id -u -n >/dev/null 2>&1; then
    agent_user="$(id -u -n 2>/dev/null || printf 'root')"
  fi
  # Keep the command-line fallback anchored and ERE-escaped. PID discovery
  # remains the primary path; this covers launchd processes that do not expose
  # a stable pidfile or listener while preserving the prior kill contract.
  base_dir_regex="$(escape_ere_literal "${BASE_DIR}")"
  start_command_regex="^(${base_dir_regex}/start\\.sh|(/usr/bin/env[[:space:]]+)?((/usr)?/bin/)?(bash|sh)[[:space:]]+${base_dir_regex}/start\\.sh)([[:space:]]|$)"
  pkill -TERM -u "${agent_user}" -f "${start_command_regex}" >/dev/null 2>&1 || true
  pkill -TERM -u "${agent_user}" -f "^${base_dir_regex}/venv/bin/python[[:space:]]+-m uvicorn agent\\.app\\.main" >/dev/null 2>&1 || true
  while IFS= read -r pid; do
    [[ "${pid}" =~ ^[0-9]+$ ]] || continue
    pids+=("${pid}")
  done < <(managed_macos_agent_pids "${port}")
  for pid in "${pids[@]:-}"; do
    kill -TERM "${pid}" >/dev/null 2>&1 || true
  done
  kill_agent_listener_on_port "${port}"
  if (( ${#pids[@]} > 0 )); then
    sleep 1
  fi
  while IFS= read -r pid; do
    [[ "${pid}" =~ ^[0-9]+$ ]] || continue
    kill -KILL "${pid}" >/dev/null 2>&1 || true
  done < <(managed_macos_agent_pids "${port}")
}

wait_for_macos_agent_quiesced(){
  local port="${1:-}"
  local attempts="${REALM_AGENT_QUIESCE_ATTEMPTS:-15}"
  local attempt=""
  local listeners=""
  local managed=""
  local label=""
  local launchd_stopped=""
  [[ "${port}" =~ ^[0-9]+$ ]] || return 1
  if [[ ! "${attempts}" =~ ^[0-9]+$ ]] \
    || (( 10#${attempts} < 1 || 10#${attempts} > 120 )); then
    attempts=15
  else
    attempts="$((10#${attempts}))"
  fi
  command_exists lsof || {
    err "Agent 静止校验需要 lsof"
    return 1
  }
  for ((attempt = 1; attempt <= attempts; attempt++)); do
    launchd_stopped="1"
    for label in \
      "${AGENT_LABEL}" "${MPTCP_SIDECAR_LABEL}" "${REVTUNNEL_LABEL}"; do
      if launchctl print "system/${label}" >/dev/null 2>&1; then
        launchd_stopped="0"
      fi
    done
    managed="$(managed_macos_agent_pids "${port}" || true)"
    listeners="$(lsof -tiTCP:"${port}" -sTCP:LISTEN 2>/dev/null || true)"
    if [[ "${launchd_stopped}" == "1" \
      && -z "${managed}" \
      && -z "${listeners}" ]]; then
      return 0
    fi
    sleep 1
  done
  err "macOS Agent 未能在目录切换前完全静止"
  return 1
}

quiesce_macos_agent_stack(){
  local port="${1:-}"
  persist_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" "main-quiescing" || return 1
  bootout_macos_launchd_stack || return 1
  terminate_macos_agent_processes "${port}"
  wait_for_macos_agent_quiesced "${port}" || return 1
  persist_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" "main-quiesced"
}

wait_for_macos_agent_process_and_listener(){
  local port="${1:-}"
  local attempts="${REALM_AGENT_STARTUP_HEALTH_ATTEMPTS:-30}"
  local pids=""
  local pid=""
  local healthy="0"
  local attempt=1
  [[ "${port}" =~ ^[0-9]+$ ]] || return 1
  if [[ ! "${attempts}" =~ ^[0-9]+$ ]] \
    || (( 10#${attempts} < 1 || 10#${attempts} > 120 )); then
    attempts=30
  else
    attempts="$((10#${attempts}))"
  fi
  if ! command_exists lsof; then
    err "Agent 启动健康检查需要 lsof 证明监听进程归属"
    return 1
  fi
  for ((attempt = 1; attempt <= attempts; attempt++)); do
    pids="$(lsof -tiTCP:"${port}" -sTCP:LISTEN 2>/dev/null \
      | awk '!seen[$0]++' || true)"
    healthy="1"
    if [[ -z "${pids}" ]]; then
      healthy="0"
    else
      while IFS= read -r pid; do
        [[ "${pid}" =~ ^[0-9]+$ ]] || {
          healthy="0"
          continue
        }
        if ! is_realm_agent_process "${pid}"; then
          healthy="0"
        fi
      done <<< "${pids}"
    fi
    if [[ "${healthy}" == "1" ]]; then
      return 0
    fi
    sleep 1
  done
  err "Agent 进程/监听端口健康检查超时：${port}"
  return 1
}

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 | tail -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_shell_env_value(){
  local raw="${1:-}"
  local parser=""
  local decoded=""
  if [[ -n "${base_dir:-}" && -x "${base_dir}/venv/bin/python" ]]; then
    parser="${base_dir}/venv/bin/python"
  elif ensure_trusted_macos_agent_python; then
    parser="${MAC_TRUSTED_PYTHON_BIN}"
  else
    [[ "${raw}" != b64:* ]] || return 1
    printf '%s' "${raw}"
    return 0
  fi
  if decoded="$(run_isolated_macos_python "${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
    [[ "${raw}" != b64:* ]] || return 1
    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 0
  decode_shell_env_value "${value}"
}

resolve_mptcp_sidecar_cmd_value(){
  local explicit="${1:-}"
  local fallback="${2:-}"
  local value="${explicit:-${fallback}}"
  [[ -n "${value}" ]] || return 0
  decode_shell_env_value "${value}"
}

wait_for_macos_launchd_process(){
  local label="${1:-}"
  local kind="${2:-generic}"
  local attempts="${REALM_MACOS_SERVICE_HEALTH_ATTEMPTS:-15}"
  local stable_required="${REALM_MACOS_SERVICE_HEALTH_STABLE_SAMPLES:-2}"
  local stable_pid=""
  local stable_samples=0
  local attempt=""
  local pid=""
  local command_line=""
  if [[ ! "${attempts}" =~ ^[0-9]+$ ]] \
    || (( 10#${attempts} < 1 || 10#${attempts} > 120 )); then
    attempts=15
  else
    attempts="$((10#${attempts}))"
  fi
  if [[ ! "${stable_required}" =~ ^[0-9]+$ ]] \
    || (( 10#${stable_required} < 1 || 10#${stable_required} > 10 )); then
    stable_required=2
  else
    stable_required="$((10#${stable_required}))"
  fi
  for ((attempt = 1; attempt <= attempts; attempt++)); do
    pid="$(macos_launchd_job_pid "system/${label}" || true)"
    command_line=""
    if [[ "${pid}" =~ ^[0-9]+$ ]] \
      && kill -0 "${pid}" >/dev/null 2>&1; then
      command_line="$(macos_process_command_line "${pid}" || true)"
    fi
    case "${kind}" in
      revtunnel)
        if [[ ! "${command_line}" =~ ^/usr/bin/ssh[[:space:]]+-NT([[:space:]]|$) \
          || "${command_line}" != *"ExitOnForwardFailure=yes"* \
          || "${command_line}" != *" -R "* ]]; then
          pid=""
        fi
        ;;
      mptcp)
        [[ -n "${command_line}" ]] || pid=""
        ;;
    esac
    if [[ -n "${pid}" && "${stable_pid}" == "${pid}" ]]; then
      stable_samples=$((stable_samples + 1))
    elif [[ -n "${pid}" ]]; then
      stable_pid="${pid}"
      stable_samples=1
    else
      stable_pid=""
      stable_samples=0
    fi
    if (( stable_samples >= stable_required )); then
      return 0
    fi
    sleep 1
  done
  err "launchd 服务未形成稳定运行进程：${label}"
  return 1
}

probe_macos_mptcp_endpoint(){
  local uds="${1:-}"
  local host="${2:-127.0.0.1}"
  local port="${3:-29443}"
  local python_bin=""
  if [[ -x "${BASE_DIR}/venv/bin/python" ]]; then
    python_bin="${BASE_DIR}/venv/bin/python"
  elif ensure_trusted_macos_agent_python; then
    python_bin="${MAC_TRUSTED_PYTHON_BIN}"
  else
    return 1
  fi
  run_isolated_macos_python \
    "${python_bin}" - "${uds}" "${host}" "${port}" <<'PY' >/dev/null 2>&1
import socket
import sys

uds, host, raw_port = sys.argv[1:4]
candidates = []
if uds:
    candidates.append((socket.AF_UNIX, uds))
try:
    port = int(raw_port)
except ValueError:
    port = 0
if host and 0 < port <= 65535:
    candidates.append((socket.AF_INET6 if ":" in host else socket.AF_INET, (host, port)))
for family, address in candidates:
    sock = socket.socket(family, socket.SOCK_STREAM)
    sock.settimeout(1.0)
    try:
        sock.connect(address)
    except OSError:
        continue
    finally:
        sock.close()
    raise SystemExit(0)
raise SystemExit(1)
PY
}

verify_macos_mptcp_launchd_runtime(){
  local enabled=""
  local sidecar_cmd=""
  local uds=""
  local host=""
  local port=""
  local attempts="${REALM_MACOS_SERVICE_HEALTH_ATTEMPTS:-15}"
  local attempt=""
  enabled="$(read_env_value /etc/realm-agent/agent.env \
    REALM_MPTCP_ENABLED || true)"
  sidecar_cmd="$(read_mptcp_sidecar_cmd_value \
    /etc/realm-agent/agent.env || true)"
  [[ "${enabled}" == "1" && -n "${sidecar_cmd}" ]] || return 1
  wait_for_macos_launchd_process \
    "${MPTCP_SIDECAR_LABEL}" mptcp || return 1
  uds="$(read_env_value /etc/realm-agent/agent.env \
    REALM_MPTCP_SIDECAR_UDS || true)"
  host="$(read_env_value /etc/realm-agent/agent.env \
    REALM_MPTCP_SIDECAR_HOST || true)"
  port="$(read_env_value /etc/realm-agent/agent.env \
    REALM_MPTCP_SIDECAR_PORT || true)"
  if [[ ! "${attempts}" =~ ^[0-9]+$ ]] \
    || (( 10#${attempts} < 1 || 10#${attempts} > 120 )); then
    attempts=15
  else
    attempts="$((10#${attempts}))"
  fi
  for ((attempt = 1; attempt <= attempts; attempt++)); do
    if probe_macos_mptcp_endpoint \
      "${uds:-/var/run/realm-mptcp-sidecar.sock}" \
      "${host:-127.0.0.1}" "${port:-29443}"; then
      return 0
    fi
    sleep 1
  done
  err "MPTCP sidecar 进程存在但 UDS/TCP 端点不可用"
  return 1
}

verify_macos_revtunnel_launchd_runtime(){
  wait_for_macos_launchd_process "${REVTUNNEL_LABEL}" revtunnel
}

verify_macos_launchd_label_runtime(){
  local label="${1:-}"
  local restored_port=""
  case "${label}" in
    "${AGENT_LABEL}")
      restored_port="$(read_env_value /etc/realm-agent/agent.env \
        REALM_AGENT_PORT || true)"
      restored_port="$(normalize_port "${restored_port:-${DEFAULT_PORT}}")"
      wait_for_macos_agent_process_and_listener "${restored_port}"
      ;;
    "${MPTCP_SIDECAR_LABEL}")
      verify_macos_mptcp_launchd_runtime
      ;;
    "${REVTUNNEL_LABEL}")
      verify_macos_revtunnel_launchd_runtime
      ;;
    *)
      return 1
      ;;
  esac
}

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(){
  printf '%s' "${1:-}" | run_trusted_macos_python -c '
import sys

value = sys.stdin.read()
if len(value) > 2048 or any(
    ord(character) < 32 or ord(character) == 127
    for character in value
):
    raise SystemExit(1)
if any(ord(character) in (34, 39, 92, 96, 36) for character in value):
    raise SystemExit(1)
sys.stdout.write(value)
'
}

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 parsed_env=""
  local value=""
  if ! parsed_env="$(run_trusted_macos_python - "${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
  )"; then
    err "无法安全解析既有 Agent 更新环境"
    return 1
  fi
  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 <<< "${parsed_env}"
}

# update_env_file_var <file> <key> <value>
# 若 file 已含 ^<key>= 行，原地替换；否则追加一行。
# value 始终用双引号包裹，供固定的数据解析器读取。env 文件绝不作为
# shell 程序 source；含空格的路径仍需要完整保留为单个值。
update_env_file_var(){
  local file="$1"
  local key="$2"
  local value="$3"
  [[ -n "${file}" && -n "${key}" ]] || return 0
  [[ -f "${file}" ]] || return 0
  local tmp
  tmp="$(mktemp "$(dirname "${file}")/.$(basename "${file}").tmp.XXXXXX")" || return 0
  register_cleanup_path "${tmp}"
  # 转义 value 中可能存在的双引号/反斜杠，避免破坏 quote。
  local escaped
  escaped="${value//\\/\\\\}"
  escaped="${escaped//\"/\\\"}"
  if grep -Eq "^${key}=" "${file}"; then
    awk -v k="${key}" -v v="${escaped}" 'BEGIN{FS=OFS="="} $1==k {print k"=\""v"\""; next} {print}' "${file}" > "${tmp}"
  else
    cat "${file}" > "${tmp}"
    printf '%s="%s"\n' "${key}" "${escaped}" >> "${tmp}"
  fi
  mv "${tmp}" "${file}"
  chmod 600 "${file}" 2>/dev/null || true
}

managed_mptcp_sidecar_cmd(){
  local python_bin="${BASE_DIR}/venv/bin/python"
  local module_path="${BASE_DIR}/agent/app/services/mptcp_sidecar_server.py"
  if [[ -x "${python_bin}" \
    && -f "${module_path}" \
    && ! -L "${module_path}" ]]; then
    printf '%s -m agent.app.services.mptcp_sidecar_server' "${python_bin}"
  fi
}

resolve_mptcp_sidecar_cmd(){
  local cmd="${REALM_MPTCP_SIDECAR_CMD:-}"
  if [[ -n "${cmd}" ]]; then
    echo "${cmd}"
    return 0
  fi
  managed_mptcp_sidecar_cmd
}

validate_mptcp_sidecar_cmd(){
  local cmd="${1:-}"
  [[ -n "${cmd}" ]] || return 1
  run_trusted_macos_python - "${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)
if text.startswith("b64:"):
    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(){
  run_trusted_macos_python - "${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
}

shell_quote_env_value(){
  printf '%q' "${1:-}"
}

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://}"
    src="${src%%\?*}"
    if [[ ! -f "$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 shasum; then
    shasum -a 256 "${path}" | awk '{print tolower($1)}'
  elif command_exists sha256sum; then
    sha256sum "${path}" | awk '{print tolower($1)}'
  else
    err "缺少 shasum/sha256sum，无法校验：${path}"
    return 1
  fi
}

verify_file_sha256(){
  local path="$1"
  local expected=""
  local actual=""
  expected="$(normalize_sha256 "${2:-}" || true)"
  if [[ -z "${expected}" ]]; then
    err "缺少有效 SHA256，拒绝使用文件：${path}"
    return 1
  fi
  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 ! run_trusted_macos_python - \
    "${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 ! run_trusted_macos_python - \
    "${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.get("mode", "-")
    if schema == 2 and (
        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"
  local symlink_policy="${2:-reject-symlinks}"
  [[ -f "${archive}" ]] || return 1
  run_trusted_macos_python - "${archive}" "${symlink_policy}" <<'PY'
import pathlib
import stat
import sys
import zipfile

archive_path = pathlib.Path(sys.argv[1])
allow_safe_symlinks = sys.argv[2] == "allow-safe-symlinks"

def symlink_stays_inside(member, target):
    target_path = pathlib.PurePosixPath(target)
    if (
        not target
        or target_path.is_absolute()
        or "\\" in target
        or "\x00" in target
    ):
        return False
    stack = list(member.parent.parts)
    for part in target_path.parts:
        if part in {"", "."}:
            continue
        if part == "..":
            if not stack:
                return False
            stack.pop()
        else:
            stack.append(part)
    return bool(stack)

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_paths = set()
        seen_casefold = set()
        seen_dirs = set()
        seen_casefold_dirs = set()
        members = []
        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)
                or path.as_posix() != raw.rstrip("/")
            ):
                raise SystemExit(f"unsafe zip path: {raw!r}")
            is_dir = raw.endswith("/")
            normalized = raw.rstrip("/")
            case_key = normalized.casefold()
            if normalized in seen_paths or case_key in seen_casefold:
                raise SystemExit(f"duplicate zip member: {raw!r}")
            mode = (info.external_attr >> 16) & 0xFFFF
            if stat.S_ISLNK(mode):
                if not allow_safe_symlinks:
                    raise SystemExit(f"zip symlink is not allowed: {raw}")
                target = archive.read(info).decode("utf-8", errors="strict")
                if not symlink_stays_inside(path, target):
                    raise SystemExit(f"unsafe zip symlink: {raw} -> {target!r}")
            total += max(0, int(info.file_size))
            if total > 4 * 1024 * 1024 * 1024:
                raise SystemExit("zip expands beyond the safety limit")
            members.append((normalized, is_dir, case_key))
            seen_paths.add(normalized)
            seen_casefold.add(case_key)
            if is_dir:
                seen_dirs.add(normalized)
                seen_casefold_dirs.add(case_key)
        for normalized, is_dir, case_key in members:
            if is_dir:
                continue
            path = pathlib.PurePosixPath(normalized)
            for idx in range(len(path.parts) - 1):
                prefix = "/".join(path.parts[: idx + 1])
                prefix_case = prefix.casefold()
                if (prefix in seen_paths and prefix not in seen_dirs) or (
                    prefix_case in seen_casefold
                    and prefix_case not in seen_casefold_dirs
                ):
                    raise SystemExit(
                        f"zip file/directory collision: {normalized!r}"
                    )
        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
}

validate_remote_companion_app_tree(){
  local app_root="${1:-}"
  [[ -d "${app_root}" && ! -L "${app_root}" ]] || return 1
  run_trusted_macos_python - "${app_root}" <<'PY'
import os
import pathlib
import sys

root_path = pathlib.Path(sys.argv[1])
if root_path.is_symlink() or not root_path.is_dir():
    raise SystemExit("RemoteMacAgent.app root must be a real directory")
root = pathlib.Path(os.path.realpath(str(root_path)))

for directory, dirnames, filenames in os.walk(str(root), followlinks=False):
    for name in list(dirnames) + filenames:
        path = pathlib.Path(directory) / name
        if not path.is_symlink():
            continue
        target = os.readlink(str(path))
        if not target or os.path.isabs(target):
            raise SystemExit(f"unsafe app symlink: {path} -> {target!r}")
        stack = list(path.parent.relative_to(root).parts)
        for part in pathlib.PurePosixPath(target).parts:
            if part in {"", "."}:
                continue
            if part == "..":
                if not stack:
                    raise SystemExit(
                        f"app symlink escapes bundle: {path} -> {target!r}"
                    )
                stack.pop()
            else:
                stack.append(part)
        resolved = pathlib.Path(
            os.path.realpath(os.path.join(directory, target))
        )
        try:
            resolved.relative_to(root)
        except ValueError as exc:
            raise SystemExit(
                f"app symlink escapes bundle: {path} -> {target!r}"
            ) from exc
PY
}

verify_remote_companion_bundle_signature(){
  local app_root="${1:-}"
  local requirement="${REALM_REMOTE_CODESIGN_REQUIREMENT:-}"
  if ! command_exists codesign; then
    err "系统缺少 codesign，拒绝安装未验证的 RemoteMacAgent.app"
    return 1
  fi
  if [[ -z "${requirement}" ]]; then
    err "缺少 REALM_REMOTE_CODESIGN_REQUIREMENT，无法固定 RemoteMacAgent 签名身份"
    return 1
  fi
  if ! codesign --verify --deep --strict --verbose=2 \
    -R="${requirement}" "${app_root}"; then
    err "RemoteMacAgent.app 签名或固定 requirement 校验失败"
    return 1
  fi
}

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
}

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 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
    return 1
  fi
  if ! verify_file_sha256 "${verified_tmp}" "${expected_sha}"; then
    err "${label} SHA256 校验失败：${url}"
    rm -f "${verified_tmp}" >/dev/null 2>&1 || true
    return 1
  fi
  mv -f "${verified_tmp}" "${out}"
}

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

  # Remote sidecars share the origin's trust and do not authenticate content.
  # Require an explicit digest or a digest from verified release metadata.
  return 1
}

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 "${TMPDIR:-/private/tmp}/realm-agent-macos-release.XXXXXX"
  )" || return 1
  register_cleanup_path "${metadata_file}"
  if ! download_signed_release_manifest \
    "${metadata_url}" "${metadata_file}" "macos-agent-install"; then
    return 1
  fi

  fields="$(
    run_trusted_macos_python - "${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}"
}

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
}

download_fresh_file(){
  local url="$1"
  local out="$2"
  local cache_busted_url
  cache_busted_url="$(append_cache_bust_url "${url}")"
  if download_file "${cache_busted_url}" "${out}"; then
    return 0
  fi
  if [[ "${cache_busted_url}" != "${url}" ]]; then
    download_file "${url}" "${out}"
    return $?
  fi
  return 1
}

fetch_repo_zip(){
  local out="$1"
  local explicit="${REALM_AGENT_REPO_ZIP_URL:-}"
  local panel_url="${REALM_PANEL_URL:-}"
  local explicit_sha="${REALM_AGENT_REPO_ZIP_SHA256:-${ACTUAL_ZIP_SHA256:-${TARGET_ZIP_SHA256:-}}}"
  local candidate cache_busted_candidate expected_sha expected_size actual_size
  local release_fields="" release_git_sha="" release_url="" release_sha="" release_size=""
  local fallback_zip_url="" fallback_zip_sha=""
  local seen="|"
  local -a candidates=()
  local -a candidate_hashes=()
  local -a candidate_sizes=()

  if [[ -z "${panel_url}" && -f /etc/realm-agent/panel.env ]]; then
    panel_url="$(read_env_value /etc/realm-agent/panel.env REALM_PANEL_URL || true)"
  fi
  panel_url="$(panel_url_without_trailing_slash "${panel_url}")"

  if [[ -n "${explicit}" ]]; then
    candidates+=("${explicit}")
    candidate_hashes+=("$(expected_sha256_for_url \
      "${explicit}" "${explicit_sha}" "$(basename "${explicit%%\?*}")" || true)")
    candidate_sizes+=("")
  elif [[ -n "${panel_url}" ]]; then
    candidates+=("${panel_url}/static/realm-agent.zip")
    candidate_hashes+=("$(expected_sha256_for_url \
      "${panel_url}/static/realm-agent.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
  # 与 Linux 端统一：优先 REALM_AGENT_REPO_FALLBACK_ZIP_URL，
  # 同时保留 REPO_ZIP_URL_FALLBACK 兼容。
  fallback_zip_url="${REALM_AGENT_REPO_FALLBACK_ZIP_URL:-${REPO_ZIP_URL_FALLBACK:-}}"
  fallback_zip_sha="${REALM_AGENT_REPO_FALLBACK_ZIP_SHA256:-}"
  if [[ -n "${fallback_zip_url}" ]]; then
    if [[ -n "${fallback_zip_sha}" ]]; then
      candidates+=("${fallback_zip_url}")
      candidate_hashes+=("$(normalize_sha256 \
        "${fallback_zip_sha}" || true)")
      candidate_sizes+=("")
    else
      warn "备用 ZIP 源未绑定 SHA256，已拒绝：${fallback_zip_url}"
    fi
  fi

  local candidate_index=0
  for candidate in "${candidates[@]}"; do
    [[ -n "${candidate}" ]] || continue
    expected_sha="${candidate_hashes[$candidate_index]:-}"
    expected_size="${candidate_sizes[$candidate_index]:-}"
    candidate_index=$((candidate_index + 1))
    if [[ "${seen}" == *"|${candidate}|"* ]]; then
      continue
    fi
    seen="${seen}${candidate}|"
    if [[ -z "${expected_sha}" ]]; then
      warn "来源未绑定 SHA256，已拒绝：${candidate}"
      continue
    fi
    info "下载并校验仓库 ZIP：${candidate}"
    cache_busted_candidate="$(append_cache_bust_url "${candidate}")"
    if ! download_verified_file \
      "${cache_busted_candidate}" "${out}" "${expected_sha}" "仓库 ZIP"; then
      if [[ "${cache_busted_candidate}" == "${candidate}" ]] \
        || ! download_verified_file \
          "${candidate}" "${out}" "${expected_sha}" "仓库 ZIP"; then
        rm -f "${out}" || true
        warn "仓库 ZIP 下载或 SHA256 校验失败，尝试下一个源：${candidate}"
        continue
      fi
    fi
    if [[ -n "${expected_size}" ]]; then
      actual_size="$(wc -c < "${out}" | tr -d '[:space:]')"
      if [[ "${actual_size}" != "${expected_size}" ]]; then
        rm -f "${out}" || true
        warn "仓库 ZIP 大小与 release 元数据不一致：${candidate}"
        continue
      fi
    fi
    if validate_zip_archive "${out}" \
      && unzip -tq "${out}" >/dev/null 2>&1; then
      return 0
    fi
    rm -f "${out}" || true
    warn "仓库 ZIP 结构或完整性检查失败，尝试下一个源：${candidate}"
  done

  # 全部 ZIP 源失败时，与 Linux 端对齐：尝试签名 manifest 逐文件拉取。
  info "全部 ZIP 源失败，尝试签名 manifest 逐文件拉取仓库..."
  local manifest_dir="" raw_dir="" rebuilt_zip=""
  local repo_base="" manifest_url=""
  manifest_dir="$(mktemp -d "${TMPDIR:-/private/tmp}/realm-agent-macos-manifest.XXXXXX")" \
    || return 1
  register_cleanup_path "${manifest_dir}"
  raw_dir="${manifest_dir}/raw"
  repo_base="$(macos_repo_base_url || true)"
  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
  if [[ -n "${repo_base}" ]] \
    && macos_download_repo_from_manifest_with_fallback \
      "${repo_base}" "${manifest_url}" "${raw_dir}"; then
    rebuilt_zip="${manifest_dir}/repo-rebuilt.zip"
    if macos_zip_repo_tree "${raw_dir}" "${rebuilt_zip}" \
      && validate_zip_archive "${rebuilt_zip}" \
      && unzip -tq "${rebuilt_zip}" >/dev/null 2>&1; then
      mv -f "${rebuilt_zip}" "${out}"
      ok "已通过签名 manifest 逐文件拉取并重建仓库 ZIP"
      return 0
    fi
    warn "签名 manifest 逐文件拉取结果无法重建有效 ZIP"
  fi
  return 1
}

# 仓库文件基址：与 Linux 端 REPO_BASE_URL_DEFAULT 语义一致，可用
# REALM_AGENT_REPO_BASE_URL 覆盖（manifest 文件清单中的路径以此为根）。
macos_repo_base_url(){
  local override="${REALM_AGENT_REPO_BASE_URL:-}"
  if [[ -n "${override}" ]]; then
    printf '%s\n' "${override%/}"
    return 0
  fi
  printf '%s\n' "${REPO_BASE_URL_DEFAULT}"
}

macos_repo_fallback_manifest_url(){
  if [[ -n "${REALM_AGENT_REPO_FALLBACK_MANIFEST_URL:-}" ]]; then
    printf '%s\n' "${REALM_AGENT_REPO_FALLBACK_MANIFEST_URL}"
    return 0
  fi
  local fallback_base="${REALM_AGENT_REPO_FALLBACK_BASE_URL:-}"
  if [[ -n "${fallback_base}" ]]; then
    printf '%s\n' "${fallback_base%/}/release-manifest.json"
    return 0
  fi
  return 1
}

macos_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}" != "-" ]] \
    && ! run_trusted_macos_python - "${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
}

macos_download_repo_from_manifest(){
  local base_url="${1%/}"
  local manifest_url="$2"
  local out_dir="$3"
  local manifest_file="${out_dir}/manifest.json"
  local records_file="${out_dir}/manifest.paths"
  local bust=""
  local hash="" size="" mode="" path=""
  local failed="0"
  local index="0"
  local -a paths=() hashes=() sizes=() modes=()

  install -d -m 700 "${out_dir}"
  bust="ts=$(date +%s)"
  info "拉取并验证签名 release manifest..."
  if ! download_signed_release_manifest \
    "${manifest_url}" "${manifest_file}" "macos-agent-install" "${records_file}"; then
    err "签名 release manifest 下载或验证失败"
    return 1
  fi

  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}" == "-" || "${mode}" =~ ^0[0-7]{3}$ ]] || {
      err "签名 manifest mode 记录无效：${path}"
      return 1
    }
    hashes+=("${hash}")
    sizes+=("${size}")
    modes+=("${mode}")
    paths+=("${path}")
  done < "${records_file}"

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

  info "开始逐文件拉取仓库内容（共 ${#paths[@]} 个）..."
  for path in "${paths[@]}"; do
    if ! macos_download_repo_manifest_path \
      "${base_url}" "${out_dir}" "${path}" "${bust}" \
      "${hashes[$index]}" "${sizes[$index]}" "${modes[$index]}"; then
      failed="1"
    fi
    index=$((index + 1))
  done
  if [[ "${failed}" != "0" ]]; then
    return 1
  fi
  ok "仓库文件拉取完成（共 ${#paths[@]} 个）"
}

macos_download_repo_from_manifest_with_fallback(){
  local base_url="$1"
  local manifest_url="$2"
  local out_dir="$3"
  local fallback_base="" fallback_manifest=""

  if macos_download_repo_from_manifest "${base_url}" "${manifest_url}" "${out_dir}"; then
    return 0
  fi
  fallback_base="${REALM_AGENT_REPO_FALLBACK_BASE_URL:-}"
  fallback_manifest="$(macos_repo_fallback_manifest_url || true)"
  if [[ -z "${fallback_base}" || -z "${fallback_manifest}" ]]; then
    return 1
  fi
  if [[ "${base_url}" == "${fallback_base%/}" \
        && "${manifest_url}" == "${fallback_manifest}" ]]; then
    return 1
  fi
  info "主源清单拉取失败，切换显式固定的备用源..."
  rm -rf "${out_dir}" || true
  install -d -m 700 "${out_dir}"
  if macos_download_repo_from_manifest \
    "${fallback_base%/}" "${fallback_manifest}" "${out_dir}"; then
    ok "已从显式固定的备用源拉取仓库文件"
    return 0
  fi
  return 1
}

macos_zip_repo_tree(){
  local raw_dir="$1"
  local out_zip="$2"
  run_trusted_macos_python - "${raw_dir}" "${out_zip}" <<'PY'
import os
import pathlib
import stat
import sys
import zipfile

raw_dir = pathlib.Path(sys.argv[1])
out_zip = pathlib.Path(sys.argv[2])
count = 0
with zipfile.ZipFile(out_zip, "w", compression=zipfile.ZIP_DEFLATED) as archive:
    for root, dirs, files in os.walk(raw_dir):
        dirs.sort()
        for name in sorted(files):
            full = pathlib.Path(root) / name
            if full.is_symlink():
                continue
            relative = full.relative_to(raw_dir).as_posix()
            mode = stat.S_IMODE(full.stat().st_mode)
            info = zipfile.ZipInfo(relative)
            info.external_attr = (mode & 0o7777) << 16
            info.compress_type = zipfile.ZIP_DEFLATED
            archive.writestr(info, full.read_bytes())
            count += 1
            if count > 20000:
                raise SystemExit("repo tree exceeds zip entry limit")
if count == 0:
    raise SystemExit("repo tree is empty")
PY
}

find_agent_dir(){
  local base="$1"
  local agent_dir
  agent_dir="$(find "$base" -maxdepth 6 -type d -name agent -print -quit 2>/dev/null || true)"
  if [[ -z "$agent_dir" ]]; then
    err "找不到 agent 目录，请确认 ZIP 内容正确"
    exit 1
  fi
  echo "$agent_dir"
}

write_env_files(){
  local host="$1"
  local port="$2"
  local transport="${3:-http}"
  local ssl_cert="${4:-/etc/realm-agent/certs/server.crt}"
  local ssl_key="${5:-/etc/realm-agent/certs/server.key}"
  local tls_server_name="${6:-}"
  local tls_ca_cert="${7:-}"
  local insecure_non_loopback="${8:-0}"
  local desktop_user=""
  local desktop_home=""
  local desktop_uid=""
  local agent_env_file="/etc/realm-agent/agent.env"
  local agent_env_tmp=""
  local panel_env_file="/etc/realm-agent/panel.env"
  local panel_env_tmp=""
  local api_key_file="/etc/realm-agent/api.key"
  local api_key_tmp=""
  local existing_enabled=""
  local existing_uds=""
  local existing_sidecar_host=""
  local existing_sidecar_port=""
  local existing_sidecar_timeout_ms=""
  local existing_sidecar_cmd=""
  local mptcp_enabled=""
  local mptcp_sidecar_uds=""
  local mptcp_sidecar_host=""
  local mptcp_sidecar_port=""
  local mptcp_sidecar_timeout_ms=""
  local mptcp_sidecar_cmd=""
  local realm_node_id=""
  local npp_hub_enabled=""
  local npp_hub_apply_enabled=""
  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=""
  local allow_shell=""
  local enable_custom_nginx_templates=""
  local continuity_enabled=""
  local continuity_protocol_v1_enabled=""
  local continuity_route_open_enabled=""
  local continuity_anchor_enabled=""
  local continuity_ingress_enabled=""
  local continuity_release_root=""
  local continuity_runtime_dir=""
  local continuity_package_sha=""
  local tunnel_runtime_mode=""
  local tunnel_runtime_require_owner_lease=""
  local tunnel_runtime_socket=""
  local tunnel_runtime_owner_lease=""
  local tunnel_runtime_owner_state=""
  local tunnel_runtime_status_path=""

  install -d -m 700 /etc/realm-agent || return 1
  install -d -m 755 /etc/realm || return 1

  if [[ -L "${api_key_file}" \
    || ( -e "${api_key_file}" && ! -f "${api_key_file}" ) ]]; then
    err "Agent API key 路径不是可信普通文件：${api_key_file}"
    return 1
  fi
  if [[ ! -s "${api_key_file}" ]]; then
    if ! command_exists openssl; then
      err "生成 API key 需要 openssl，安装中止"
      return 1
    fi
    api_key_tmp="$(mktemp "${api_key_file}.tmp.XXXXXX")" || return 1
    register_cleanup_path "${api_key_tmp}"
    if ! openssl rand -hex 32 > "${api_key_tmp}" \
      || ! grep -Eq '^[0-9a-f]{64}$' "${api_key_tmp}" \
      || ! chmod -N "${api_key_tmp}" \
      || ! publish_root_owned_regular_file \
        "${api_key_tmp}" "${api_key_file}" 600; then
      err "Agent API key 无法安全生成或持久化"
      return 1
    fi
  else
    chmod -N "${api_key_file}" || return 1
    fix_owner_mode_strict "${api_key_file}" 600 || return 1
    fsync_path_and_parent "${api_key_file}" || return 1
  fi

  desktop_user="$(console_user || true)"
  if [[ -n "${desktop_user}" && -d "/Users/${desktop_user}" ]]; then
    desktop_home="/Users/${desktop_user}"
    desktop_uid="$(id -u "${desktop_user}" 2>/dev/null || true)"
  fi
  if [[ -z "${desktop_uid}" ]]; then
    desktop_uid="$(console_uid || true)"
  fi

  # RemoteMacAgent LaunchAgent plist 通过 EnvironmentVariables 注入若干 REALM_REMOTE_COMPANION_*
  # 变量；这里必须把同名变量同步写入 /etc/realm-agent/agent.env，让 root 持有的 Python agent
  # 与桌面会话里的 companion 共享同一份配置（plist/env 对称导出，杜绝路径或 label 漂移）。
  local companion_status_path
  companion_status_path="$(compute_remote_companion_status_path "${desktop_user}" "${desktop_home}")"
  update_tmp_parent="$(resolve_preserved_env_value "${agent_env_file}" "REALM_AGENT_UPDATE_TMP_PARENT" "${REALM_AGENT_UPDATE_TMP_PARENT:-}" "/private/tmp")"
  if [[ "${update_tmp_parent}" != /* || -L "${update_tmp_parent}" || ! -d "${update_tmp_parent}" ]]; then
    warn "REALM_AGENT_UPDATE_TMP_PARENT 不是可用的真实目录，已修复为 /private/tmp"
    update_tmp_parent="/private/tmp"
  fi
  update_log_dir="$(resolve_preserved_env_value "${agent_env_file}" "REALM_AGENT_UPDATE_LOG_DIR" "${REALM_AGENT_UPDATE_LOG_DIR:-}" "")"
  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
  update_tmp_retention_days="$(resolve_preserved_uint_env_value "${agent_env_file}" "REALM_AGENT_UPDATE_TMP_RETENTION_DAYS" "${REALM_AGENT_UPDATE_TMP_RETENTION_DAYS:-}" 1 0 3650)"
  update_log_retention_days="$(resolve_preserved_uint_env_value "${agent_env_file}" "REALM_AGENT_UPDATE_LOG_RETENTION_DAYS" "${REALM_AGENT_UPDATE_LOG_RETENTION_DAYS:-}" 7 0 3650)"
  update_curl_connect_timeout="$(resolve_preserved_uint_env_value "${agent_env_file}" "REALM_AGENT_UPDATE_CURL_CONNECT_TIMEOUT" "${REALM_AGENT_UPDATE_CURL_CONNECT_TIMEOUT:-}" 20 1 300)"
  update_curl_max_time="$(resolve_preserved_uint_env_value "${agent_env_file}" "REALM_AGENT_UPDATE_CURL_MAX_TIME" "${REALM_AGENT_UPDATE_CURL_MAX_TIME:-}" 300 1 3600)"
  update_curl_retry="$(resolve_preserved_uint_env_value "${agent_env_file}" "REALM_AGENT_UPDATE_CURL_RETRY" "${REALM_AGENT_UPDATE_CURL_RETRY:-}" 1 0 8)"
  update_curl_retry_delay="$(resolve_preserved_uint_env_value "${agent_env_file}" "REALM_AGENT_UPDATE_CURL_RETRY_DELAY" "${REALM_AGENT_UPDATE_CURL_RETRY_DELAY:-}" 3 0 60)"
  update_curl_speed_time="$(resolve_preserved_uint_env_value "${agent_env_file}" "REALM_AGENT_UPDATE_CURL_SPEED_TIME" "${REALM_AGENT_UPDATE_CURL_SPEED_TIME:-}" 20 1 300)"
  update_curl_speed_limit="$(resolve_preserved_uint_env_value "${agent_env_file}" "REALM_AGENT_UPDATE_CURL_SPEED_LIMIT" "${REALM_AGENT_UPDATE_CURL_SPEED_LIMIT:-}" 32768 1 104857600)"
  pip_install_timeout="$(resolve_preserved_uint_env_value "${agent_env_file}" "REALM_AGENT_PIP_INSTALL_TIMEOUT" "${REALM_AGENT_PIP_INSTALL_TIMEOUT:-}" 900 60 3600)"
  pip_disable_fallback="$(resolve_preserved_bool_env_value "${agent_env_file}" "REALM_AGENT_PIP_DISABLE_FALLBACK" "${REALM_AGENT_PIP_DISABLE_FALLBACK:-}" 0)"
  pip_enable_legacy_resolver_fallback="$(resolve_preserved_bool_env_value "${agent_env_file}" "REALM_AGENT_PIP_ENABLE_LEGACY_RESOLVER_FALLBACK" "${REALM_AGENT_PIP_ENABLE_LEGACY_RESOLVER_FALLBACK:-}" 1)"
  pip_force_legacy_resolver="$(resolve_preserved_bool_env_value "${agent_env_file}" "REALM_AGENT_PIP_FORCE_LEGACY_RESOLVER" "${REALM_AGENT_PIP_FORCE_LEGACY_RESOLVER:-}" 0)"
  pip_index_url="$(resolve_preserved_update_text_env_value "${agent_env_file}" "REALM_AGENT_PIP_INDEX_URL" "${REALM_AGENT_PIP_INDEX_URL:-}")" || return 1
  pip_extra_index_url="$(resolve_preserved_update_text_env_value "${agent_env_file}" "REALM_AGENT_PIP_EXTRA_INDEX_URL" "${REALM_AGENT_PIP_EXTRA_INDEX_URL:-}")" || return 1
  pip_fallback_indexes="$(resolve_preserved_update_text_env_value "${agent_env_file}" "REALM_AGENT_PIP_FALLBACK_INDEXES" "${REALM_AGENT_PIP_FALLBACK_INDEXES:-}")" || return 1
  pip_trusted_host="$(resolve_preserved_update_text_env_value "${agent_env_file}" "REALM_AGENT_PIP_TRUSTED_HOST" "${REALM_AGENT_PIP_TRUSTED_HOST:-}")" || return 1
  allow_shell="$(resolve_preserved_env_value "${agent_env_file}" "REALM_AGENT_ALLOW_SHELL" "${REALM_AGENT_ALLOW_SHELL:-}" "0")"
  if macos_agent_bool_enabled "${allow_shell}"; then
    allow_shell="1"
  else
    allow_shell="0"
  fi
  enable_custom_nginx_templates="$(
    resolve_preserved_env_value \
      "${agent_env_file}" \
      "REALM_AGENT_ENABLE_CUSTOM_NGINX_TEMPLATES" \
      "${REALM_AGENT_ENABLE_CUSTOM_NGINX_TEMPLATES:-}" \
      "1"
  )"
  if macos_agent_bool_enabled "${enable_custom_nginx_templates}"; then
    enable_custom_nginx_templates="1"
  else
    enable_custom_nginx_templates="0"
  fi

  existing_enabled="$(read_env_value "${agent_env_file}" "REALM_MPTCP_ENABLED" || true)"
  existing_uds="$(read_env_value "${agent_env_file}" "REALM_MPTCP_SIDECAR_UDS" || true)"
  existing_sidecar_host="$(read_env_value "${agent_env_file}" "REALM_MPTCP_SIDECAR_HOST" || true)"
  existing_sidecar_port="$(read_env_value "${agent_env_file}" "REALM_MPTCP_SIDECAR_PORT" || true)"
  existing_sidecar_timeout_ms="$(read_env_value "${agent_env_file}" "REALM_MPTCP_SIDECAR_TIMEOUT_MS" || true)"
  if ! existing_sidecar_cmd="$(
    read_mptcp_sidecar_cmd_value "${agent_env_file}"
  )"; then
    err "既有 REALM_MPTCP_SIDECAR_CMD 编码无效，拒绝覆盖"
    return 1
  fi

  mptcp_enabled="${REALM_MPTCP_ENABLED:-${existing_enabled}}"
  mptcp_sidecar_uds="${REALM_MPTCP_SIDECAR_UDS:-${existing_uds}}"
  mptcp_sidecar_host="${REALM_MPTCP_SIDECAR_HOST:-${existing_sidecar_host}}"
  mptcp_sidecar_port="${REALM_MPTCP_SIDECAR_PORT:-${existing_sidecar_port}}"
  mptcp_sidecar_timeout_ms="${REALM_MPTCP_SIDECAR_TIMEOUT_MS:-${existing_sidecar_timeout_ms}}"
  if ! mptcp_sidecar_cmd="$(
    resolve_mptcp_sidecar_cmd_value \
      "${REALM_MPTCP_SIDECAR_CMD:-}" \
      "${existing_sidecar_cmd}"
  )"; then
    err "REALM_MPTCP_SIDECAR_CMD 编码无效，拒绝写入"
    return 1
  fi
  realm_node_id="$(resolve_preserved_env_value "${agent_env_file}" "REALM_NODE_ID" "${REALM_NODE_ID:-}" "${REALM_AGENT_ID:-}")"
  local npp_feature_defaults_version="2"
  local installed_npp_feature_defaults_version=""
  installed_npp_feature_defaults_version="$(read_env_value "${agent_env_file}" "REALM_NPP_FEATURE_DEFAULTS_VERSION" || true)"
  npp_hub_enabled="$(resolve_migrated_default_env_value "${agent_env_file}" "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 "${agent_env_file}" "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 "${agent_env_file}" "REALM_NPP_DECOY_ENABLED" "${REALM_NPP_DECOY_ENABLED:-}" "1")"
  npp_endpoint_failover_enabled="$(resolve_migrated_default_env_value "${agent_env_file}" "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 "${agent_env_file}" "REALM_NPP_TRAFFIC_SHAPE_ENABLED" "${REALM_NPP_TRAFFIC_SHAPE_ENABLED:-}" "1")"
  npp_stealth_path_enabled="$(resolve_preserved_env_value "${agent_env_file}" "REALM_NPP_STEALTH_PATH_ENABLED" "${REALM_NPP_STEALTH_PATH_ENABLED:-}" "1")"
  npp_mux_randomize_connections="$(resolve_migrated_default_env_value "${agent_env_file}" "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 "${agent_env_file}" "REALM_NPP_ROUTE_OPEN_ENABLED" "${REALM_NPP_ROUTE_OPEN_ENABLED:-}" "${installed_npp_feature_defaults_version}" "${npp_feature_defaults_version}" "1")"
  continuity_enabled="$(resolve_preserved_env_value "${agent_env_file}" "REALM_CONTINUITY_ENABLED" "${REALM_CONTINUITY_ENABLED:-}" "false")"
  continuity_protocol_v1_enabled="$(resolve_preserved_env_value "${agent_env_file}" "REALM_CONTINUITY_PROTOCOL_V1_ENABLED" "${REALM_CONTINUITY_PROTOCOL_V1_ENABLED:-}" "false")"
  continuity_route_open_enabled="$(resolve_preserved_env_value "${agent_env_file}" "REALM_CONTINUITY_ROUTE_OPEN_ENABLED" "${REALM_CONTINUITY_ROUTE_OPEN_ENABLED:-}" "false")"
  continuity_anchor_enabled="$(resolve_preserved_env_value "${agent_env_file}" "REALM_CONTINUITY_ANCHOR_ENABLED" "${REALM_CONTINUITY_ANCHOR_ENABLED:-}" "false")"
  continuity_ingress_enabled="$(resolve_preserved_env_value "${agent_env_file}" "REALM_CONTINUITY_INGRESS_ENABLED" "${REALM_CONTINUITY_INGRESS_ENABLED:-}" "false")"
  continuity_enabled="$(macos_continuity_env_bool "${continuity_enabled}")" || {
    err "REALM_CONTINUITY_ENABLED 必须是布尔值"
    return 1
  }
  continuity_protocol_v1_enabled="$(macos_continuity_env_bool "${continuity_protocol_v1_enabled}")" || {
    err "REALM_CONTINUITY_PROTOCOL_V1_ENABLED 必须是布尔值"
    return 1
  }
  continuity_route_open_enabled="$(macos_continuity_env_bool "${continuity_route_open_enabled}")" || {
    err "REALM_CONTINUITY_ROUTE_OPEN_ENABLED 必须是布尔值"
    return 1
  }
  continuity_anchor_enabled="$(macos_continuity_env_bool "${continuity_anchor_enabled}")" || {
    err "REALM_CONTINUITY_ANCHOR_ENABLED 必须是布尔值"
    return 1
  }
  continuity_ingress_enabled="$(macos_continuity_env_bool "${continuity_ingress_enabled}")" || {
    err "REALM_CONTINUITY_INGRESS_ENABLED 必须是布尔值"
    return 1
  }
  continuity_release_root="${REALM_MAC_CONTINUITY_RELEASE_ROOT:-}"
  if [[ -z "${continuity_release_root}" ]]; then
    continuity_release_root="$(resolve_preserved_env_value \
      "${agent_env_file}" \
      "REALM_CONTINUITY_RELEASE_ROOT" \
      "${REALM_CONTINUITY_RELEASE_ROOT:-}" \
      "/opt/realm/continuity/releases")"
  fi
  continuity_release_root="${continuity_release_root%/}"
  if ! valid_macos_continuity_release_root "${continuity_release_root}"; then
    err "REALM_CONTINUITY_RELEASE_ROOT 无效：${continuity_release_root:-<empty>}"
    return 1
  fi
  continuity_runtime_dir="$(resolve_preserved_env_value \
    "${agent_env_file}" \
    "REALM_CONTINUITY_RUNTIME_DIR" \
    "${REALM_CONTINUITY_RUNTIME_DIR:-}" \
    "/var/run/realm-agent/continuity")"
  if [[ "${continuity_runtime_dir}" == "/run/realm-agent/continuity" ]]; then
    continuity_runtime_dir="/var/run/realm-agent/continuity"
  fi
  if [[ "${continuity_runtime_dir}" != /* \
    || "${continuity_runtime_dir}" == *$'\n'* \
    || "${continuity_runtime_dir}" == *$'\r'* ]]; then
    err "REALM_CONTINUITY_RUNTIME_DIR 必须是绝对路径"
    return 1
  fi
  continuity_package_sha="${REALM_MAC_CONTINUITY_PACKAGE_SHA:-}"
  if [[ -z "${continuity_package_sha}" ]]; then
    continuity_package_sha="$(resolve_preserved_env_value \
      "${agent_env_file}" \
      "REALM_CONTINUITY_PACKAGE_SHA" \
      "${REALM_CONTINUITY_PACKAGE_SHA:-}" "")"
  fi
  if [[ "${REALM_MAC_CONTINUITY_INSTALL_REQUESTED}" == "1" \
    && ! "${continuity_package_sha}" =~ ^[0-9a-f]{64}$ ]]; then
    err "continuity 已请求安装但 package SHA 无效"
    return 1
  fi
  tunnel_runtime_mode="$(resolve_preserved_env_value \
    "${agent_env_file}" \
    "REALM_TUNNEL_RUNTIME_MODE" \
    "${REALM_TUNNEL_RUNTIME_MODE:-}" \
    "compat")"
  tunnel_runtime_require_owner_lease="$(resolve_preserved_env_value \
    "${agent_env_file}" \
    "REALM_TUNNEL_RUNTIME_REQUIRE_OWNER_LEASE" \
    "${REALM_TUNNEL_RUNTIME_REQUIRE_OWNER_LEASE:-}" \
    "false")"
  if [[ "${REALM_MAC_CONTINUITY_INSTALL_REQUESTED}" == "1" ]]; then
    tunnel_runtime_mode="owner"
    tunnel_runtime_require_owner_lease="true"
  fi
  tunnel_runtime_socket="$(resolve_preserved_env_value \
    "${agent_env_file}" \
    "REALM_TUNNEL_RUNTIME_SOCKET" \
    "${REALM_TUNNEL_RUNTIME_SOCKET:-}" \
    "/var/run/realm-agent/tunnel-runtime.sock")"
  if [[ "${tunnel_runtime_socket}" == "/run/realm-agent/tunnel-runtime.sock" ]]; then
    tunnel_runtime_socket="/var/run/realm-agent/tunnel-runtime.sock"
  fi
  tunnel_runtime_owner_lease="$(resolve_preserved_env_value \
    "${agent_env_file}" \
    "REALM_TUNNEL_RUNTIME_OWNER_LEASE" \
    "${REALM_TUNNEL_RUNTIME_OWNER_LEASE:-}" \
    "/var/run/realm-agent/tunnel-runtime.owner")"
  if [[ "${tunnel_runtime_owner_lease}" == "/run/realm-agent/tunnel-runtime.owner" ]]; then
    tunnel_runtime_owner_lease="/var/run/realm-agent/tunnel-runtime.owner"
  fi
  tunnel_runtime_owner_state="$(resolve_preserved_env_value \
    "${agent_env_file}" \
    "REALM_TUNNEL_RUNTIME_OWNER_STATE" \
    "${REALM_TUNNEL_RUNTIME_OWNER_STATE:-}" \
    "/var/lib/realm-agent/processes/tunnel-runtime/owner-activation.json")"
  tunnel_runtime_status_path="$(resolve_preserved_env_value \
    "${agent_env_file}" \
    "REALM_TUNNEL_RUNTIME_STATUS_PATH" \
    "${REALM_TUNNEL_RUNTIME_STATUS_PATH:-}" \
    "/var/lib/realm-agent/processes/tunnel-runtime/status.json")"
  if [[ "${REALM_MAC_CONTINUITY_INSTALL_REQUESTED}" == "1" ]]; then
    install -d -m 700 /var/run/realm-agent || return 1
    install -d -m 700 "${continuity_runtime_dir}" || return 1
    install -d -m 700 /var/lib/realm-agent/processes/tunnel-runtime \
      || 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="$(managed_mptcp_sidecar_cmd)"
  fi
  if [[ -n "${mptcp_sidecar_cmd}" ]] \
    && ! validate_mptcp_sidecar_cmd "${mptcp_sidecar_cmd}"; then
    err "REALM_MPTCP_SIDECAR_CMD 含 shell 元字符或无效 argv，拒绝写入"
    return 1
  fi
  if macos_agent_bool_enabled "${insecure_non_loopback}"; then
    insecure_non_loopback="1"
  else
    insecure_non_loopback="0"
  fi

  agent_env_tmp="$(mktemp "${agent_env_file}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${agent_env_tmp}"
  if ! {
    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_SSL_CERT=%s\n' \
      "$(shell_quote_env_value "$(strip_env_value "${ssl_cert}")")"
    printf 'REALM_AGENT_SSL_KEY=%s\n' \
      "$(shell_quote_env_value "$(strip_env_value "${ssl_key}")")"
    printf 'REALM_AGENT_TLS_SERVER_NAME=%s\n' \
      "$(shell_quote_env_value "$(strip_env_value "${tls_server_name}")")"
    printf 'REALM_AGENT_TLS_CA_CERT=%s\n' \
      "$(shell_quote_env_value "$(strip_env_value "${tls_ca_cert}")")"
    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_AGENT_SERVICE=%s\n' "$(strip_env_value "${AGENT_LABEL}")"
    printf 'REALM_AGENT_LAUNCHD_LABEL=%s\n' "$(strip_env_value "${AGENT_LABEL}")"
    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_NODE_ID=%s\n' "$(strip_env_value "${realm_node_id}")"
    printf 'REALM_AGENT_DESKTOP_USER=%s\n' "$(strip_env_value "${desktop_user}")"
    printf 'REALM_AGENT_DESKTOP_HOME=%s\n' "$(strip_env_value "${desktop_home}")"
    printf 'REALM_REMOTE_COMPANION_STATUS_PATH="%s"\n' "$(strip_env_value "${companion_status_path}")"
    printf 'REALM_REMOTE_COMPANION_LAUNCHD_LABEL="%s"\n' "$(strip_env_value "${REMOTE_COMPANION_LABEL}")"
    printf 'REALM_REMOTE_COMPANION_LAUNCHD_TARGET="%s"\n' "$(strip_env_value "gui/${desktop_uid}/${REMOTE_COMPANION_LABEL}")"
    printf 'REALM_REMOTE_COMPANION_EXECUTABLE="%s"\n' "$(strip_env_value "${REMOTE_COMPANION_APP_PATH}/Contents/MacOS/RemoteMacAgent")"
    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_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}")"
    printf 'REALM_CONTINUITY_ENABLED=%s\n' "$(strip_env_value "${continuity_enabled}")"
    printf 'REALM_CONTINUITY_PROTOCOL_V1_ENABLED=%s\n' "$(strip_env_value "${continuity_protocol_v1_enabled}")"
    printf 'REALM_CONTINUITY_ROUTE_OPEN_ENABLED=%s\n' "$(strip_env_value "${continuity_route_open_enabled}")"
    printf 'REALM_CONTINUITY_ANCHOR_ENABLED=%s\n' "$(strip_env_value "${continuity_anchor_enabled}")"
    printf 'REALM_CONTINUITY_INGRESS_ENABLED=%s\n' "$(strip_env_value "${continuity_ingress_enabled}")"
    printf 'REALM_CONTINUITY_RUNTIME_DIR="%s"\n' "$(strip_env_value "${continuity_runtime_dir}")"
    printf 'REALM_CONTINUITY_RELEASE_ROOT="%s"\n' "$(strip_env_value "${continuity_release_root}")"
    printf 'REALM_CONTINUITY_PACKAGE_SHA=%s\n' "$(strip_env_value "${continuity_package_sha}")"
    printf 'REALM_CONTINUITY_INGRESS_PACKAGE_SHA=%s\n' "$(strip_env_value "${continuity_package_sha}")"
    printf 'REALM_TUNNEL_RUNTIME_MODE=%s\n' "$(strip_env_value "${tunnel_runtime_mode}")"
    printf 'REALM_TUNNEL_RUNTIME_REQUIRE_OWNER_LEASE=%s\n' "$(strip_env_value "${tunnel_runtime_require_owner_lease}")"
    printf 'REALM_TUNNEL_RUNTIME_SOCKET="%s"\n' "$(strip_env_value "${tunnel_runtime_socket}")"
    printf 'REALM_TUNNEL_RUNTIME_OWNER_LEASE="%s"\n' "$(strip_env_value "${tunnel_runtime_owner_lease}")"
    printf 'REALM_TUNNEL_RUNTIME_OWNER_STATE="%s"\n' "$(strip_env_value "${tunnel_runtime_owner_state}")"
    printf 'REALM_TUNNEL_RUNTIME_STATUS_PATH="%s"\n' "$(strip_env_value "${tunnel_runtime_status_path}")"
  } > "${agent_env_tmp}"; then
    err "Agent 环境文件写入失败"
    return 1
  fi
  if ! validate_realm_env_file "${agent_env_tmp}" \
    || ! publish_root_owned_regular_file \
      "${agent_env_tmp}" "${agent_env_file}" 600; then
    err "Agent 环境文件校验或持久化失败"
    return 1
  fi
  if [[ "${mptcp_enabled}" == "1" && -z "${mptcp_sidecar_cmd}" ]]; then
    info "REALM_MPTCP_ENABLED=1 但未探测到 sidecar 命令，可手动设置 REALM_MPTCP_SIDECAR_CMD"
  fi

  if [[ -n "${REALM_PANEL_URL:-}" || -n "${REALM_AGENT_ID:-}" ]]; then
    panel_env_tmp="$(mktemp "${panel_env_file}.tmp.XXXXXX")" || return 1
    register_cleanup_path "${panel_env_tmp}"
    if ! {
      printf 'REALM_PANEL_URL=%s\n' "$(strip_env_value "${REALM_PANEL_URL:-}")"
      printf 'REALM_AGENT_ID=%s\n' "$(strip_env_value "${REALM_AGENT_ID:-0}")"
      printf 'REALM_AGENT_HEARTBEAT_INTERVAL=%s\n' "$(strip_env_value "${REALM_AGENT_HEARTBEAT_INTERVAL:-3}")"
      printf 'REALM_AGENT_REPORT_INSECURE_TLS=%s\n' "$(strip_env_value "${REALM_AGENT_REPORT_INSECURE_TLS:-0}")"
      printf 'REALM_AGENT_REPORT_CA_FILE=%s\n' "$(strip_env_value "${REALM_AGENT_REPORT_CA_FILE:-}")"
    } > "${panel_env_tmp}"; then
      err "Panel 环境文件写入失败"
      return 1
    fi
    if ! validate_realm_env_file "${panel_env_tmp}" \
      || ! publish_root_owned_regular_file \
        "${panel_env_tmp}" "${panel_env_file}" 600; then
      err "Panel 环境文件校验或持久化失败"
      return 1
    fi
  fi
}

write_start_script(){
  local start_path="${BASE_DIR}/start.sh"
  local start_tmp=""
  install -d -m 755 "${BASE_DIR}" || return 1
  start_tmp="$(mktemp "${start_path}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${start_tmp}"
  if ! cat > "${start_tmp}" <<'EOF_START'
#!/usr/bin/env bash
set -euo pipefail

BASE="/usr/local/realm-agent"
AGENT_DIR="$BASE/agent"
export SETUPTOOLS_USE_DISTUTILS=stdlib

load_realm_env_file(){
  local file="$1"
  local parsed=""
  local key=""
  local value=""
  [[ -e "$file" ]] || return 0
  parsed="$(mktemp "${TMPDIR:-/private/tmp}/realm-env.XXXXXX")"
  chmod 600 "$parsed"
  cleanup_parsed_env(){
    rm -f "$parsed" >/dev/null 2>&1 || true
  }
  trap cleanup_parsed_env RETURN
  if ! "$BASE/venv/bin/python" -I -S -B - "$file" > "$parsed" <<'PY'
import base64
import os
import re
import shlex
import stat
import sys

path = sys.argv[1]
metadata = os.lstat(path)
if not stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode):
    raise SystemExit(f"env file is not a regular file: {path}")
if metadata.st_uid != 0 or stat.S_IMODE(metadata.st_mode) & 0o077:
    raise SystemExit(f"env file ownership or mode is unsafe: {path}")

key_pattern = re.compile(r"(?:REALM|AGENT)_[A-Z0-9_]+")
seen = set()
with open(path, "r", encoding="utf-8", errors="strict") as handle:
    for number, raw_line in enumerate(handle, 1):
        line = raw_line.rstrip("\r\n")
        if not line or line.lstrip().startswith("#"):
            continue
        if any(ord(char) < 32 or ord(char) == 127 for char in line):
            raise SystemExit(f"env file contains control characters at line {number}")
        if "=" not in line:
            raise SystemExit(f"env file line {number} is not KEY=VALUE")
        key, raw_value = line.split("=", 1)
        if not key_pattern.fullmatch(key) or key in seen:
            raise SystemExit(f"env file key is invalid or duplicated at line {number}")
        seen.add(key)
        if raw_value == "":
            value = ""
        else:
            try:
                values = shlex.split(raw_value, comments=False, posix=True)
            except ValueError as exc:
                raise SystemExit(f"env file value is invalid at line {number}: {exc}") from exc
            if len(values) != 1:
                raise SystemExit(f"env file value must be one data value at line {number}")
            value = values[0]
        if key == "REALM_MPTCP_SIDECAR_CMD" and value.startswith("b64:"):
            encoded = value[4:]
            try:
                data = base64.b64decode(
                    encoded,
                    altchars=b"-_",
                    validate=True,
                )
                value = data.decode("utf-8")
            except (ValueError, UnicodeDecodeError) as exc:
                raise SystemExit(
                    "literal agent env encoding is invalid "
                    f"at line {number}"
                ) from exc
            if base64.urlsafe_b64encode(data).decode("ascii") != encoded:
                raise SystemExit(
                    "literal agent env encoding is not canonical "
                    f"at line {number}"
                )
            if any(ord(char) < 32 or ord(char) == 127 for char in value):
                raise SystemExit(
                    "literal agent env contains control characters "
                    f"at line {number}"
                )
        if any(char in value for char in ("\0", "\r", "\n")):
            raise SystemExit(f"env file value contains control characters at line {number}")
        sys.stdout.buffer.write(key.encode("ascii") + b"\0")
        sys.stdout.buffer.write(value.encode("utf-8") + b"\0")
PY
  then
    cleanup_parsed_env
    trap - RETURN
    return 1
  fi
  while IFS= read -r -d '' key && IFS= read -r -d '' value; do
    printf -v "$key" '%s' "$value"
    export "$key"
  done < "$parsed"
  cleanup_parsed_env
  trap - RETURN
}

load_realm_env_file /etc/realm-agent/panel.env
load_realm_env_file /etc/realm-agent/agent.env

HOST="${REALM_AGENT_HOST:-127.0.0.1}"
PORT="${REALM_AGENT_PORT:-18700}"
TRANSPORT="${REALM_AGENT_TRANSPORT:-http}"
SSL_CERT="${REALM_AGENT_SSL_CERT:-/etc/realm-agent/certs/server.crt}"
SSL_KEY="${REALM_AGENT_SSL_KEY:-/etc/realm-agent/certs/server.key}"

cd "$AGENT_DIR"
if [[ -n "${PYTHONPATH:-}" ]]; then
  export PYTHONPATH="$BASE:${PYTHONPATH}"
else
  export PYTHONPATH="$BASE"
fi
# Avoid stale bytecode when reproducible ZIP mtimes keep Python sources at
# fixed timestamps across agent updates.
agent_cache_version="$(
  awk -F'"' '/^AGENT_VERSION = "[0-9]+"$/{print $2; exit}' \
    "$AGENT_DIR/app/version.py"
)"
if [[ ! "$agent_cache_version" =~ ^[0-9]+$ ]]; then
  echo "Agent release version is invalid" >&2
  exit 1
fi
export PYTHONPYCACHEPREFIX="$BASE/.runtime-pycache/v${agent_cache_version}"
export PYTHONDONTWRITEBYTECODE=1
startup_preflight="$AGENT_DIR/app/services/venv_startup_preflight.py"
if [[ ! -f "$startup_preflight" || -L "$startup_preflight" ]]; then
  echo "Agent venv startup preflight is unavailable" >&2
  exit 1
fi
"$BASE/venv/bin/python" -I -S -B "$startup_preflight" \
  --venv-root "$BASE/venv" \
  --python-executable "$BASE/venv/bin/python" >/dev/null
ulimit -n 65536 >/dev/null 2>&1 || true
uvicorn_args=(
  -m uvicorn agent.app.main:app
  --host "$HOST"
  --port "$PORT"
  --workers 1
)
case "$TRANSPORT" in
  http)
    ;;
  https)
    [[ -r "$SSL_CERT" && -r "$SSL_KEY" ]] || {
      echo "HTTPS cert/key 不可读" >&2
      exit 1
    }
    uvicorn_args+=(--ssl-certfile "$SSL_CERT" --ssl-keyfile "$SSL_KEY")
    ;;
  *)
    echo "REALM_AGENT_TRANSPORT 仅支持 http 或 https" >&2
    exit 1
    ;;
esac
exec "$BASE/venv/bin/python" -B "${uvicorn_args[@]}" \
  > >(/usr/bin/logger -p daemon.notice -t realm-agent) \
  2> >(/usr/bin/logger -p daemon.err -t realm-agent)
EOF_START
  then
    err "Agent start.sh 写入失败"
    return 1
  fi
  if ! bash -n "${start_tmp}" \
    || ! publish_root_owned_regular_file \
      "${start_tmp}" "${start_path}" 755; then
    err "Agent start.sh 校验或持久化失败"
    return 1
  fi
}

install_macos_startup_recovery_support(){
  local source="${REALM_MAC_INSTALLER_SOURCE:-${BASH_SOURCE[0]}}"
  local source_tmp=""
  local wrapper_tmp=""
  [[ -f "${source}" && ! -L "${source}" ]] || {
    err "无法定位当前 macOS Agent 安装器，拒绝安装启动恢复支持：${source}"
    return 1
  }
  install -d -m 755 "${MACOS_RECOVERY_DIR}" || return 1
  fix_owner_mode_strict "${MACOS_RECOVERY_DIR}" 755 || return 1
  fsync_directory_and_parent "${MACOS_RECOVERY_DIR}" || return 1
  source_tmp="$(mktemp "${MACOS_RECOVERY_SCRIPT}.tmp.XXXXXX")" || return 1
  wrapper_tmp="$(mktemp "${MACOS_STARTUP_WRAPPER}.tmp.XXXXXX")" || {
    rm -f "${source_tmp}" >/dev/null 2>&1 || true
    return 1
  }
  register_cleanup_path "${source_tmp}"
  register_cleanup_path "${wrapper_tmp}"
  if ! install -m 0755 "${source}" "${source_tmp}" \
    || ! fix_owner_mode_strict "${source_tmp}" 755 \
    || ! fsync_path_and_parent "${source_tmp}" \
    || ! mv -f "${source_tmp}" "${MACOS_RECOVERY_SCRIPT}" \
    || ! fsync_path_and_parent "${MACOS_RECOVERY_SCRIPT}"; then
    err "无法持久化 macOS Agent 启动恢复安装器"
    return 1
  fi
  if ! cat > "${wrapper_tmp}" <<EOF_WRAPPER
#!/usr/bin/env bash
set -euo pipefail
BASE=$(shell_quote_env_value "${BASE_DIR}")
TRANSACTION="\${BASE}/.install-transaction"
STATE_FILE="\${TRANSACTION}/state"
RECOVERY_LABEL=$(shell_quote_env_value "${MACOS_RECOVERY_LABEL}")
if [[ -d "\${TRANSACTION}" ]]; then
  if [[ ! -f "\${STATE_FILE}" || -L "\${STATE_FILE}" ]]; then
    echo "macOS Agent transaction state is unavailable" >&2
    exit 75
  fi
  state="\$(/usr/bin/head -n 1 "\${STATE_FILE}" | /usr/bin/tr -d '\\r\\n')"
  case "\${state}" in
    committed|rolled-back)
      ;;
    main-start-allowed|main-restored)
      if ! /bin/launchctl print "system/\${RECOVERY_LABEL}" >/dev/null 2>&1; then
        echo "macOS Agent recovery service is unavailable" >&2
        exit 1
      fi
      ;;
    *)
      echo "macOS Agent start is blocked by transaction state: \${state:-missing}" >&2
      exit 75
      ;;
  esac
fi
if [[ ! -x "\${BASE}/start.sh" ]]; then
  echo "macOS Agent start script is missing: \${BASE}/start.sh" >&2
  exit 1
fi
exec "\${BASE}/start.sh"
EOF_WRAPPER
  then
    err "macOS Agent 启动 wrapper 写入失败"
    return 1
  fi
  if ! bash -n "${wrapper_tmp}" \
    || ! publish_root_owned_regular_file \
      "${wrapper_tmp}" "${MACOS_STARTUP_WRAPPER}" 755; then
    err "无法校验或持久化 macOS Agent 启动 wrapper"
    return 1
  fi
}

write_macos_recovery_launchd(){
  local label=""
  local python_bin=""
  local program=""
  local transaction=""
  local plist_tmp=""
  if ! ensure_trusted_macos_agent_python; then
    err "无法为 macOS recovery 持久化受信任 Python"
    return 1
  fi
  label="$(xml_escape "${MACOS_RECOVERY_LABEL}")"
  python_bin="$(xml_escape "${MAC_TRUSTED_PYTHON_BIN}")"
  program="$(xml_escape "${MACOS_RECOVERY_SCRIPT}")"
  transaction="$(xml_escape "${REALM_MAC_TRANSACTION_DIR}")"
  plist_tmp="$(mktemp "${MACOS_RECOVERY_PLIST}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${plist_tmp}"
  cat > "${plist_tmp}" <<EOF_RECOVERY_PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>${label}</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/bash</string>
    <string>-p</string>
    <string>${program}</string>
    <string>--recover-only</string>
  </array>
  <key>EnvironmentVariables</key>
  <dict>
    <key>REALM_AGENT_INSTALL_LOCK_NONBLOCK</key>
    <string>1</string>
    <key>REALM_AGENT_PYTHON_BIN</key>
    <string>${python_bin}</string>
  </dict>
  <key>KeepAlive</key>
  <dict>
    <key>PathState</key>
    <dict>
      <key>${transaction}</key>
      <true/>
    </dict>
  </dict>
  <key>ProcessType</key>
  <string>Background</string>
  <key>ThrottleInterval</key>
  <integer>5</integer>
</dict>
</plist>
EOF_RECOVERY_PLIST
  validate_plist_file "${plist_tmp}" || return 1
  fix_owner_mode_strict "${plist_tmp}" 644 || return 1
  fsync_path_and_parent "${plist_tmp}" || return 1
  mv -f "${plist_tmp}" "${MACOS_RECOVERY_PLIST}" || return 1
  fsync_path_and_parent "${MACOS_RECOVERY_PLIST}"
}

install_macos_recovery_launchd(){
  write_macos_recovery_launchd || return 1
  if ! bootstrap_launchdaemon \
    "${MACOS_RECOVERY_LABEL}" \
    "${MACOS_RECOVERY_PLIST}" \
    "${MACOS_RECOVERY_SCRIPT}"; then
    err "独立 macOS Agent 恢复服务安装失败"
    return 1
  fi
}

write_agent_launchd(){
  local python_bin=""
  local plist_label=""
  local startup_wrapper=""
  local recovery_dir=""
  local plist_path="/Library/LaunchDaemons/${AGENT_LABEL}.plist"
  local plist_tmp=""
  if ! ensure_trusted_macos_agent_python; then
    err "无法为 macOS Agent launchd 持久化受信任 Python"
    return 1
  fi
  # plist 是 XML 文档：插值内容必须先做 XML 转义，
  # 否则路径/标签含 & < > 时 plutil 拒绝加载。
  python_bin="$(xml_escape "${MAC_TRUSTED_PYTHON_BIN}")"
  plist_label="$(xml_escape "${AGENT_LABEL}")"
  startup_wrapper="$(xml_escape "${MACOS_STARTUP_WRAPPER}")"
  recovery_dir="$(xml_escape "${MACOS_RECOVERY_DIR}")"
  plist_tmp="$(mktemp "${plist_path}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${plist_tmp}"
  if ! cat > "${plist_tmp}" <<EOF_PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>${plist_label}</string>
  <key>ProgramArguments</key>
  <array>
    <string>${startup_wrapper}</string>
  </array>
  <key>WorkingDirectory</key>
  <string>${recovery_dir}</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>REALM_AGENT_PYTHON_BIN</key>
    <string>${python_bin}</string>
  </dict>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>SoftResourceLimits</key>
  <dict>
    <key>NumberOfFiles</key>
    <integer>65536</integer>
  </dict>
  <key>HardResourceLimits</key>
  <dict>
    <key>NumberOfFiles</key>
    <integer>65536</integer>
  </dict>
</dict>
</plist>
EOF_PLIST
  then
    err "Agent launchd plist 写入失败"
    return 1
  fi
  if ! validate_plist_file "${plist_tmp}" \
    || ! publish_root_owned_regular_file \
      "${plist_tmp}" "${plist_path}" 644; then
    err "Agent launchd plist 校验或持久化失败"
    return 1
  fi
}

start_agent_standalone(){
  local pid_file="/var/run/realm-agent.pid"

  if [[ -f "${pid_file}" ]]; then
    local old_pid=""
    old_pid="$(cat "${pid_file}" 2>/dev/null || true)"
    if [[ "${old_pid}" =~ ^[0-9]+$ ]]; then
      kill "${old_pid}" >/dev/null 2>&1 || true
    fi
  fi

  nohup "${BASE_DIR}/start.sh" >/dev/null 2>&1 &
  local new_pid=$!
  echo "${new_pid}" > "${pid_file}"
  chmod 600 "${pid_file}" >/dev/null 2>&1 || true
  chown root:wheel "${pid_file}" >/dev/null 2>&1 || true
  sleep 1
  if ! kill -0 "${new_pid}" >/dev/null 2>&1; then
    err "独立模式启动 Agent 失败，请使用 log show 查询 realm-agent"
    return 1
  fi
  AGENT_BOOTSTRAP_MODE="standalone"
  warn "已切换到独立模式启动 Agent（非 launchd 托管）"
  return 0
}

restart_agent_launchd(){
  local port="${1:-$DEFAULT_PORT}"
  terminate_macos_agent_processes "${port}"
  if bootstrap_launchdaemon "${AGENT_LABEL}" "/Library/LaunchDaemons/${AGENT_LABEL}.plist" "${MACOS_STARTUP_WRAPPER}"; then
    if ! wait_for_macos_agent_process_and_listener "${port}"; then
      err "launchd 已 loaded，但 Agent 进程或监听端口未健康：${port}"
      return 1
    fi
    AGENT_BOOTSTRAP_MODE="launchd"
    return 0
  fi
  err "launchd 托管启动失败；拒绝使用无法跨重启恢复的独立进程伪装安装成功"
  return 1
}

setup_mptcp_sidecar_launchd(){
  local mptcp_enabled="0"
  local sidecar_cmd=""
  local plist_label=""
  local plist_base_dir=""
  local script_path="${BASE_DIR}/mptcp_sidecar.sh"
  local script_tmp=""
  local plist_path="/Library/LaunchDaemons/${MPTCP_SIDECAR_LABEL}.plist"
  local plist_tmp=""
  if ! ensure_trusted_macos_agent_python; then
    err "无法为 MPTCP sidecar 固定受信任 Python"
    return 1
  fi
  if [[ -f /etc/realm-agent/agent.env ]]; then
    mptcp_enabled="$(read_env_value /etc/realm-agent/agent.env REALM_MPTCP_ENABLED || true)"
    if ! sidecar_cmd="$(
      read_mptcp_sidecar_cmd_value /etc/realm-agent/agent.env
    )"; then
      err "既有 REALM_MPTCP_SIDECAR_CMD 编码无效，拒绝启动 sidecar"
      return 1
    fi
  fi
  mptcp_enabled="${REALM_MPTCP_ENABLED:-${mptcp_enabled:-0}}"
  if ! sidecar_cmd="$(
    resolve_mptcp_sidecar_cmd_value \
      "${REALM_MPTCP_SIDECAR_CMD:-}" \
      "${sidecar_cmd}"
  )"; then
    err "REALM_MPTCP_SIDECAR_CMD 编码无效，拒绝启动 sidecar"
    return 1
  fi
  if [[ -n "${sidecar_cmd}" ]] && ! validate_mptcp_sidecar_cmd "${sidecar_cmd}"; then
    err "REALM_MPTCP_SIDECAR_CMD 含 shell 元字符或无效 argv，拒绝启动 sidecar"
    return 1
  fi

  script_tmp="$(mktemp "${script_path}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${script_tmp}"
  if ! cat > "${script_tmp}" <<'EOF_MPTCP'
#!/usr/bin/env bash
set -euo pipefail
umask 077
MANAGED_PYTHON=__NEXUS_MANAGED_PYTHON__

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}"
}

run_sidecar_python(){
  local parser="${1:-}"
  [[ -x "${parser}" ]] || return 127
  /usr/bin/env -i \
    PATH=/usr/bin:/bin:/usr/sbin:/sbin \
    HOME=/var/root \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONNOUSERSITE=1 \
    "${parser}" -I -S -B "${@:2}"
}

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 [[ -n "${MANAGED_PYTHON}" && -x "${MANAGED_PYTHON}" ]]; then
    parser="${MANAGED_PYTHON}"
  elif [[ -x /usr/bin/python3 && ! -L /usr/bin/python3 ]]; then
    parser="/usr/bin/python3"
  else
    [[ "${raw}" != b64:* ]] || return 1
    printf '%s' "${raw}"
    return 0
  fi
  if decoded="$(run_sidecar_python "${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
    [[ "${raw}" != b64:* ]] || return 1
    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 [[ -n "${MANAGED_PYTHON}" && -x "${MANAGED_PYTHON}" ]]; then
    parser_python="${MANAGED_PYTHON}"
  elif [[ -x /usr/bin/python3 && ! -L /usr/bin/python3 ]]; then
    parser_python="/usr/bin/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 ! run_sidecar_python \
    "${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")
if text.startswith("b64:"):
    raise SystemExit("encoded sidecar command was not decoded")
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}"
cd "${base_dir}"
parse_mptcp_argv "${cmd}"
exec "${MPTCP_ARGV[@]}" \
  > >(/usr/bin/logger -p daemon.notice -t realm-agent-mptcp-sidecar) \
  2> >(/usr/bin/logger -p daemon.err -t realm-agent-mptcp-sidecar)
EOF_MPTCP
  then
    err "MPTCP sidecar 启动脚本写入失败"
    return 1
  fi
  if ! run_trusted_macos_python - \
    "${script_tmp}" "${MAC_TRUSTED_PYTHON_BIN}" <<'PY'
import pathlib
import shlex
import sys

path = pathlib.Path(sys.argv[1])
raw = path.read_text(encoding="utf-8")
placeholder = "__NEXUS_MANAGED_PYTHON__"
if raw.count(placeholder) != 1:
    raise SystemExit("managed Python placeholder is invalid")
path.write_text(
    raw.replace(placeholder, shlex.quote(sys.argv[2]), 1),
    encoding="utf-8",
)
PY
  then
    err "MPTCP sidecar 受信任 Python 写入失败"
    return 1
  fi
  if ! bash -n "${script_tmp}" \
    || ! publish_root_owned_regular_file \
      "${script_tmp}" "${script_path}" 700; then
    err "MPTCP sidecar 启动脚本校验或持久化失败"
    return 1
  fi

  plist_label="$(xml_escape "${MPTCP_SIDECAR_LABEL}")"
  plist_base_dir="$(xml_escape "${BASE_DIR}")"
  plist_tmp="$(mktemp "${plist_path}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${plist_tmp}"
  if ! cat > "${plist_tmp}" <<EOF_MPTCP_PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>${plist_label}</string>
  <key>ProgramArguments</key>
  <array>
    <string>${plist_base_dir}/mptcp_sidecar.sh</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
</dict>
</plist>
EOF_MPTCP_PLIST
  then
    err "MPTCP sidecar launchd plist 写入失败"
    return 1
  fi
  if ! validate_plist_file "${plist_tmp}" \
    || ! publish_root_owned_regular_file \
      "${plist_tmp}" "${plist_path}" 644; then
    err "MPTCP sidecar launchd plist 校验或持久化失败"
    return 1
  fi

  if [[ "${mptcp_enabled}" == "1" && -n "${sidecar_cmd}" ]]; then
    if bootstrap_launchdaemon \
      "${MPTCP_SIDECAR_LABEL}" "${plist_path}" "${script_path}" \
      && verify_macos_mptcp_launchd_runtime; then
      ok "已启用 MPTCP sidecar 服务托管（${MPTCP_SIDECAR_LABEL}）"
    else
      err "MPTCP sidecar 启动失败"
      return 1
    fi
    return 0
  fi
  if ! bootout_macos_launchd_label "${MPTCP_SIDECAR_LABEL}"; then
    return 1
  fi
  if ! launchctl disable "system/${MPTCP_SIDECAR_LABEL}" >/dev/null 2>&1; then
    err "无法禁用 MPTCP sidecar launchd label"
    return 1
  fi
  if [[ "$(macos_launchd_label_disabled_state \
    "${MPTCP_SIDECAR_LABEL}" || true)" != "1" ]]; then
    err "MPTCP sidecar launchd label 禁用后状态不一致"
    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
}

setup_revtunnel_launchd(){
  local plist_label=""
  local plist_base_dir=""
  local script_path="${BASE_DIR}/revtunnel.sh"
  local script_tmp=""
  local plist_path="/Library/LaunchDaemons/${REVTUNNEL_LABEL}.plist"
  local plist_tmp=""
  if [[ "${REALM_AGENT_SETUP_REVTUNNEL:-1}" != "1" ]]; then
    return 0
  fi
  if [[ ! -f /private/etc/realm-agent/revtunnel.env ]]; then
    return 0
  fi
  if ! "${BASE_DIR}/venv/bin/python" -I -B \
    "${BASE_DIR}/agent/app/services/revtunnel_config.py" \
    --environment-file /private/etc/realm-agent/revtunnel.env \
    --canonicalize-macos-paths; then
    err "反向隧道配置中的旧 macOS /etc 路径无法安全迁移"
    return 1
  fi

  script_tmp="$(mktemp "${script_path}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${script_tmp}"
  if ! cat > "${script_tmp}" <<'EOF_RT'
#!/usr/bin/env bash
set -euo pipefail

BASE="/usr/local/realm-agent"
ENV_FILE="/private/etc/realm-agent/revtunnel.env"
PARSED_ENV="$(mktemp "${TMPDIR:-/private/tmp}/realm-revtunnel-env.XXXXXX")"
chmod 600 "$PARSED_ENV"
cleanup_parsed_env(){
  rm -f "$PARSED_ENV" >/dev/null 2>&1 || true
}
trap cleanup_parsed_env EXIT HUP INT TERM
"$BASE/venv/bin/python" -I -B \
  "$BASE/agent/app/services/revtunnel_config.py" \
  --environment-file "$ENV_FILE" \
  --emit-env0 > "$PARSED_ENV"
while IFS= read -r -d '' key && IFS= read -r -d '' value; do
  printf -v "$key" '%s' "$value"
  export "$key"
done < "$PARSED_ENV"

PANEL_SSH_HOST="${PANEL_SSH_HOST:-}"
PANEL_SSH_PORT="${PANEL_SSH_PORT:-22}"
PANEL_SSH_USER="${PANEL_SSH_USER:-nexus-tunnel}"
REMOTE_BIND="${REMOTE_BIND:-127.0.0.1}"
REMOTE_PORT="${REMOTE_PORT:-28700}"
LOCAL_HOST="${LOCAL_HOST:-127.0.0.1}"
LOCAL_PORT="${LOCAL_PORT:-18700}"
SSH_KEY_FILE="${SSH_KEY_FILE:-/private/etc/realm-agent/tunnel/id_ed25519}"
KNOWN_HOSTS_FILE="${KNOWN_HOSTS_FILE:-/private/etc/realm-agent/tunnel/known_hosts}"
STRICT_HOST_KEY_CHECKING="${STRICT_HOST_KEY_CHECKING:-yes}"

exec /usr/bin/ssh -NT \
  -o BatchMode=yes \
  -o ExitOnForwardFailure=yes \
  -o ServerAliveInterval=15 \
  -o ServerAliveCountMax=3 \
  -o StrictHostKeyChecking="${STRICT_HOST_KEY_CHECKING}" \
  -o UserKnownHostsFile="${KNOWN_HOSTS_FILE}" \
  -i "${SSH_KEY_FILE}" \
  -p "${PANEL_SSH_PORT}" \
  -R "${REMOTE_BIND}:${REMOTE_PORT}:${LOCAL_HOST}:${LOCAL_PORT}" \
  "${PANEL_SSH_USER}@${PANEL_SSH_HOST}" \
  > >(/usr/bin/logger -p daemon.notice -t realm-agent-revtunnel) \
  2> >(/usr/bin/logger -p daemon.err -t realm-agent-revtunnel)
EOF_RT
  then
    err "反向隧道启动脚本写入失败"
    return 1
  fi
  if ! bash -n "${script_tmp}" \
    || ! publish_root_owned_regular_file \
      "${script_tmp}" "${script_path}" 700; then
    err "反向隧道启动脚本校验或持久化失败"
    return 1
  fi

  plist_label="$(xml_escape "${REVTUNNEL_LABEL}")"
  plist_base_dir="$(xml_escape "${BASE_DIR}")"
  plist_tmp="$(mktemp "${plist_path}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${plist_tmp}"
  if ! cat > "${plist_tmp}" <<EOF_RT_PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>${plist_label}</string>
  <key>ProgramArguments</key>
  <array>
    <string>${plist_base_dir}/revtunnel.sh</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
</dict>
</plist>
EOF_RT_PLIST
  then
    err "反向隧道 launchd plist 写入失败"
    return 1
  fi
  if ! validate_plist_file "${plist_tmp}" \
    || ! publish_root_owned_regular_file \
      "${plist_tmp}" "${plist_path}" 644; then
    err "反向隧道 launchd plist 校验或持久化失败"
    return 1
  fi

  if activate_macos_revtunnel_launchd; then
    return 0
  fi
  return 1
}

macos_revtunnel_upgrade_state_available(){
  local transaction_root="${REALM_MAC_TRANSACTION_DIR:-}"
  local rollback_root="${REALM_MAC_DEPLOY_ROLLBACK_DIR:-}"
  local plist_snapshot=""
  local script_snapshot=""
  local loaded=""
  local disabled=""
  [[ "${REALM_MAC_DEPLOY_ROLLBACK_ACTIVE:-0}" == "1" \
    && -n "${transaction_root}" \
    && -d "${transaction_root}/launchd" \
    && -n "${rollback_root}" \
    && -d "${rollback_root}" ]] || return 2
  if [[ -f "${rollback_root}/revtunnel.plist" \
    && ! -L "${rollback_root}/revtunnel.plist" \
    && ! -e "${rollback_root}/revtunnel.plist.absent" \
    && ! -L "${rollback_root}/revtunnel.plist.absent" ]]; then
    plist_snapshot="present"
  elif [[ -f "${rollback_root}/revtunnel.plist.absent" \
    && ! -L "${rollback_root}/revtunnel.plist.absent" \
    && ! -e "${rollback_root}/revtunnel.plist" \
    && ! -L "${rollback_root}/revtunnel.plist" ]]; then
    plist_snapshot="absent"
  else
    return 2
  fi
  if [[ -f "${rollback_root}/revtunnel.sh" \
    && ! -L "${rollback_root}/revtunnel.sh" \
    && ! -e "${rollback_root}/revtunnel.sh.absent" \
    && ! -L "${rollback_root}/revtunnel.sh.absent" ]]; then
    script_snapshot="present"
  elif [[ -f "${rollback_root}/revtunnel.sh.absent" \
    && ! -L "${rollback_root}/revtunnel.sh.absent" \
    && ! -e "${rollback_root}/revtunnel.sh" \
    && ! -L "${rollback_root}/revtunnel.sh" ]]; then
    script_snapshot="absent"
  else
    return 2
  fi
  loaded="$(
    read_transaction_value \
      "${transaction_root}/launchd/${REVTUNNEL_LABEL}.loaded" || true
  )"
  disabled="$(
    read_transaction_value \
      "${transaction_root}/launchd/${REVTUNNEL_LABEL}.disabled" || true
  )"
  [[ "${loaded}" == "0" || "${loaded}" == "1" ]] || return 2
  [[ "${disabled}" == "0" || "${disabled}" == "1" ]] || return 2
  if [[ "${plist_snapshot}" == "absent" \
    && "${script_snapshot}" == "absent" \
    && "${loaded}" == "0" \
    && "${disabled}" == "0" ]]; then
    return 1
  fi
  return 0
}

activate_macos_revtunnel_launchd(){
  local plist="/Library/LaunchDaemons/${REVTUNNEL_LABEL}.plist"
  local program="${BASE_DIR}/revtunnel.sh"
  local upgrade_state_status="0"
  if macos_revtunnel_upgrade_state_available; then
    if restore_macos_launchd_label_state \
      "${REALM_MAC_TRANSACTION_DIR}" "${REVTUNNEL_LABEL}"; then
      ok "已更新反向隧道服务并保留升级前 loaded/disabled 状态（${REVTUNNEL_LABEL}）"
      return 0
    fi
    err "反向隧道服务升级后状态恢复失败"
    return 1
  else
    upgrade_state_status="$?"
    if [[ "${upgrade_state_status}" != "1" ]]; then
      err "反向隧道升级快照缺失或无效，拒绝改变 launchd 状态"
      return 1
    fi
  fi
  if bootstrap_launchdaemon "${REVTUNNEL_LABEL}" "${plist}" "${program}"; then
    if verify_macos_revtunnel_launchd_runtime; then
      ok "已启用反向隧道服务（${REVTUNNEL_LABEL}）"
      return 0
    fi
    err "反向隧道 launchd 已 loaded 但受管 SSH 转发未稳定运行"
    return 1
  fi
  err "反向隧道服务启动失败"
  return 1
}

probe_base_urls(){
  local host="$1"
  local port="$2"
  local transport="${3:-http}"
  local tls_server_name="${4:-}"
  local out=()
  if [[ "${transport}" == "https" && -n "${tls_server_name}" ]]; then
    if [[ "${tls_server_name}" == *:* \
      && "${tls_server_name}" != \[*\] ]]; then
      out+=("${transport}://[${tls_server_name}]:${port}")
    else
      out+=("${transport}://${tls_server_name}:${port}")
    fi
  fi
  out+=("${transport}://127.0.0.1:${port}")
  out+=("${transport}://localhost:${port}")
  out+=("${transport}://[::1]:${port}")

  if [[ -n "${host}" && "${host}" != "0.0.0.0" && "${host}" != "::" ]]; then
    if [[ "${host}" == \[*\] ]]; then
      out+=("${transport}://${host}:${port}")
    elif [[ "${host}" == *:* ]]; then
      out+=("${transport}://[${host}]:${port}")
    else
      out+=("${transport}://${host}:${port}")
    fi
  fi

  printf '%s\n' "${out[@]}"
}

agent_api_get(){
  local host="$1"
  local port="$2"
  local api_key="$3"
  local path="$4"
  local out_file="$5"
  local connect_timeout="${6:-2}"
  local max_time="${7:-5}"
  local transport="${8:-http}"
  local ca_cert="${9:-}"
  local tls_server_name="${10:-}"

  local base_url=""
  local header_file=""
  local -a curl_args=()
  header_file="$(mktemp "${TMPDIR:-/tmp}/realm-agent-header.XXXXXX" 2>/dev/null)" \
    || return 1
  chmod 600 "${header_file}" >/dev/null 2>&1 || true
  printf 'x-api-key: %s\n' "${api_key}" > "${header_file}" || {
    rm -f "${header_file}" >/dev/null 2>&1 || true
    return 1
  }
  curl_args=(
    -fsS
    --connect-timeout "${connect_timeout}"
    --max-time "${max_time}"
    --max-redirs 0
    -H "@${header_file}"
  )
  if [[ "${transport}" == "https" && -n "${ca_cert}" ]]; then
    curl_args+=(--cacert "${ca_cert}")
  fi
  while IFS= read -r base_url; do
    [[ -n "${base_url}" ]] || continue
    local -a request_args=("${curl_args[@]}")
    if [[ "${transport}" == "https" && -n "${tls_server_name}" \
      && "${tls_server_name}" != *:* && "${base_url}" == *"${tls_server_name}"* ]]; then
      request_args+=(--resolve "${tls_server_name}:${port}:127.0.0.1")
    fi
    if curl "${request_args[@]}" "${base_url}${path}" -o "${out_file}" \
      >/dev/null 2>&1; then
      rm -f "${header_file}" >/dev/null 2>&1 || true
      return 0
    fi
  done < <(
    probe_base_urls \
      "${host}" "${port}" "${transport}" "${tls_server_name}"
  )
  rm -f "${header_file}" >/dev/null 2>&1 || true
  return 1
}

json_escape(){
  local value="${1:-}"
  run_trusted_macos_python - "${value}" <<'PY'
import json
import sys
print(json.dumps(sys.argv[1]), end="")
PY
}

normalize_bool(){
  local value="${1:-}"
  value="$(printf '%s' "${value}" | tr '[:upper:]' '[:lower:]')"
  case "${value}" in
    1|true|yes|on|y) echo "true" ;;
    *) echo "false" ;;
  esac
}

normalize_macos_agent_host(){
  local raw="${1:-}"
  local host=""
  host="$(strip_env_value "${raw}")"
  [[ "${host}" == "${raw}" ]] || return 1
  if [[ -z "${host}" ]]; then
    printf '%s\n' "${DEFAULT_HOST}"
    return 0
  fi
  if [[ "${host}" == "*" ]]; then
    printf '%s\n' "0.0.0.0"
    return 0
  fi
  case "${host}" in
    *[!A-Za-z0-9._:%\[\]-]*)
      return 1
      ;;
  esac
  printf '%s\n' "${host}"
}

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

is_macos_agent_loopback_host(){
  local host="${1:-}"
  local normalized=""
  normalized="$(printf '%s' "${host}" | tr '[:upper:]' '[:lower:]')"
  normalized="${normalized#[}"
  normalized="${normalized%]}"
  normalized="${normalized%%\%*}"
  if [[ "${normalized}" == "localhost" ]]; then
    return 0
  fi
  if ensure_trusted_macos_agent_python; then
    run_trusted_macos_python - "${normalized}" <<'PY' >/dev/null
import ipaddress
import sys

try:
    address = ipaddress.ip_address(sys.argv[1])
except ValueError:
    raise SystemExit(1)
raise SystemExit(0 if address.is_loopback else 1)
PY
    return
  fi
  case "${normalized}" in
    127.0.0.1|::1)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

legacy_macos_insecure_override(){
  local existing_host="${1:-}"
  local existing_transport="${2:-}"
  local existing_override="${3:-}"
  local host="${4:-}"
  local transport="${5:-}"
  local normalized_existing_host=""
  local normalized_existing_transport=""

  if [[ -n "${existing_override}" ]]; then
    printf '%s\n' "${existing_override}"
    return 0
  fi
  normalized_existing_host="$(normalize_macos_agent_host \
    "${existing_host}" || true)"
  [[ -n "${normalized_existing_host}" ]] || {
    printf '%s\n' "0"
    return 0
  }
  normalized_existing_transport="$(
    normalize_macos_agent_transport "${existing_transport:-http}" || true
  )"
  if [[ "${normalized_existing_transport}" != "http" \
    || "${transport}" != "http" ]] \
    || is_macos_agent_loopback_host "${normalized_existing_host}" \
    || is_macos_agent_loopback_host "${host}"; then
    printf '%s\n' "0"
    return 0
  fi
  printf '%s\n' "1"
}

MACOS_AGENT_CONTRACT_FIELDS=()

parse_macos_agent_contract_fields(){
  local payload="${1-}"
  local value=""
  MACOS_AGENT_CONTRACT_FIELDS=()
  while IFS= read -r value; do
    MACOS_AGENT_CONTRACT_FIELDS[${#MACOS_AGENT_CONTRACT_FIELDS[@]}]="${value}"
  done <<< "${payload}"
  if [[ "${#MACOS_AGENT_CONTRACT_FIELDS[@]}" -ne 8 ]]; then
    err "macOS Agent 契约字段数量无效"
    return 1
  fi
}

macos_agent_bool_enabled(){
  local value="${1:-}"
  value="$(printf '%s' "${value}" | tr '[:upper:]' '[:lower:]')"
  case "${value}" in
    1|true|yes|on|y)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

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

macos_continuity_env_bool(){
  local normalized=""
  normalized="$(macos_continuity_bool_value "${1:-}")" || return 1
  if [[ "${normalized}" == "1" ]]; then
    printf '%s' "true"
  else
    printf '%s' "false"
  fi
}

macos_continuity_flag_value(){
  local env_file="$1"
  local key="$2"
  local explicit="${!key:-}"
  local value=""
  if [[ -n "${explicit}" ]]; then
    macos_continuity_bool_value "${explicit}"
    return
  fi
  value="$(read_env_value "${env_file}" "${key}" || true)"
  macos_continuity_bool_value "${value}"
}

resolve_macos_continuity_install_request(){
  local explicit="${REALM_CONTINUITY_INSTALL:-}"
  local flag=""
  local value=""
  if [[ -n "${explicit}" ]]; then
    REALM_MAC_CONTINUITY_INSTALL_REQUESTED="$(
      macos_continuity_bool_value "${explicit}"
    )" || {
      err "REALM_CONTINUITY_INSTALL 必须是布尔值"
      return 1
    }
    return 0
  fi
  for flag in \
    REALM_CONTINUITY_ENABLED \
    REALM_CONTINUITY_PROTOCOL_V1_ENABLED \
    REALM_CONTINUITY_ROUTE_OPEN_ENABLED \
    REALM_CONTINUITY_INGRESS_ENABLED \
    REALM_CONTINUITY_ANCHOR_ENABLED
  do
    value="$(macos_continuity_flag_value \
      /etc/realm-agent/agent.env "${flag}")" || {
      err "${flag} 必须是布尔值"
      return 1
    }
    if [[ "${value}" == "1" ]]; then
      REALM_MAC_CONTINUITY_INSTALL_REQUESTED="1"
      return 0
    fi
  done
  REALM_MAC_CONTINUITY_INSTALL_REQUESTED="0"
}

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

resolve_macos_continuity_release_root(){
  local root=""
  root="$(resolve_preserved_env_value \
    /etc/realm-agent/agent.env \
    REALM_CONTINUITY_RELEASE_ROOT \
    "${REALM_CONTINUITY_RELEASE_ROOT:-}" \
    "/opt/realm/continuity/releases")"
  root="${root%/}"
  if ! valid_macos_continuity_release_root "${root}"; then
    err "REALM_CONTINUITY_RELEASE_ROOT 必须是安全的绝对 releases 路径：${root:-<empty>}"
    return 1
  fi
  REALM_MAC_CONTINUITY_RELEASE_ROOT="${root}"
}

macos_continuity_platform_suffix(){
  local os_name=""
  local architecture=""
  os_name="$(uname -s 2>/dev/null || true)"
  architecture="$(uname -m 2>/dev/null || true)"
  case "${os_name}:${architecture}" in
    Darwin:x86_64|Darwin:amd64)
      printf '%s\n' "darwin-amd64"
      ;;
    Darwin:arm64|Darwin:aarch64)
      printf '%s\n' "darwin-arm64"
      ;;
    *)
      err "不支持的 continuity 平台：${os_name}/${architecture}"
      return 1
      ;;
  esac
}

macos_continuity_artifact_relative_path(){
  local name="$1"
  local suffix="$2"
  printf 'agent/npp-go/dist/%s-%s\n' "${name}" "${suffix}"
}

find_macos_continuity_artifact(){
  local agent_dir="$1"
  local name="$2"
  local suffix="$3"
  local artifact="${agent_dir}/npp-go/dist/${name}-${suffix}"
  if [[ -f "${artifact}" && ! -L "${artifact}" && -x "${artifact}" ]]; then
    printf '%s\n' "${artifact}"
    return 0
  fi
  err "缺少 continuity ${name} 的 ${suffix} 制品：${artifact}"
  return 1
}

macos_continuity_manifest_sha256(){
  local manifest="$1"
  local relative="$2"
  [[ -f "${manifest}" && ! -L "${manifest}" ]] || {
    err "continuity manifest 缺失或不安全：${manifest}"
    return 1
  }
  run_trusted_macos_python - "${manifest}" "${relative}" <<'PY'
import json
import re
import sys
from pathlib import Path

manifest_path = Path(sys.argv[1])
relative = sys.argv[2]
try:
    payload = json.loads(manifest_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
    raise SystemExit(f"invalid continuity manifest {manifest_path}: {exc}")
files = payload.get("files") if isinstance(payload, dict) else None
hashes = payload.get("sha256") if isinstance(payload, dict) else None
if not isinstance(files, list) or files.count(relative) != 1:
    raise SystemExit(f"continuity artifact is not declared exactly once: {relative}")
expected = hashes.get(relative) if isinstance(hashes, dict) else None
if not isinstance(expected, str) or re.fullmatch(r"[0-9a-f]{64}", expected) is None:
    raise SystemExit(f"continuity artifact has no valid manifest SHA-256: {relative}")
print(expected)
PY
}

macos_continuity_sha256(){
  local path="$1"
  shasum -a 256 "${path}" | awk '{print $1}'
}

verify_macos_continuity_artifact_sha256(){
  local path="$1"
  local expected="$2"
  local actual=""
  actual="$(macos_continuity_sha256 "${path}")" || return 1
  [[ "${actual}" == "${expected}" ]] || {
    err "continuity 制品 SHA-256 不匹配：${path}"
    return 1
  }
}

verify_macos_continuity_artifact_architecture(){
  local path="$1"
  local suffix="$2"
  run_trusted_macos_python - "${path}" "${suffix}" <<'PY'
import sys
from pathlib import Path

path = Path(sys.argv[1])
target = sys.argv[2]
machine = {
    "darwin-amd64": 0x01000007,
    "darwin-arm64": 0x0100000C,
}.get(target)
if machine is None:
    raise SystemExit(f"unsupported continuity artifact target: {target}")
data = path.read_bytes()[:32]
if (
    len(data) < 8
    or data[:4] != b"\xcf\xfa\xed\xfe"
    or int.from_bytes(data[4:8], "little") != machine
):
    raise SystemExit(
        f"continuity artifact architecture mismatch for {target}: {path}"
    )
PY
}

verify_macos_continuity_artifact(){
  local manifest="$1"
  local path="$2"
  local name="$3"
  local suffix="$4"
  local relative=""
  local expected=""
  relative="$(macos_continuity_artifact_relative_path \
    "${name}" "${suffix}")"
  expected="$(macos_continuity_manifest_sha256 \
    "${manifest}" "${relative}")" || return 1
  verify_macos_continuity_artifact_sha256 "${path}" "${expected}" || return 1
  verify_macos_continuity_artifact_architecture "${path}" "${suffix}" || return 1
  printf '%s\n' "${expected}"
}

macos_continuity_package_identity(){
  local runtime_path="$1"
  local ingress_path="$2"
  run_trusted_macos_python - "${runtime_path}" "${ingress_path}" <<'PY'
import hashlib
import pathlib
import sys

digest = hashlib.sha256()
for name, raw_path in (
    ("realm-continuity", sys.argv[1]),
    ("realm-continuity-ingress", sys.argv[2]),
):
    path = pathlib.Path(raw_path)
    digest.update(name.encode("ascii"))
    digest.update(hashlib.sha256(path.read_bytes()).digest())
print(digest.hexdigest())
PY
}

macos_continuity_release_path_safe(){
  local path="${1:-}"
  local root="${2:-}"
  local base=""
  [[ "${path}" == "${root}/"* ]] || return 1
  base="$(basename "${path}")"
  [[ "${base}" =~ ^[0-9a-f]{64}$ ]]
}

verify_macos_installed_continuity_package(){
  local release_dir="$1"
  local runtime_sha="$2"
  local ingress_sha="$3"
  local suffix="$4"
  [[ -d "${release_dir}" && ! -L "${release_dir}" ]] || return 1
  shasum -a 256 -c \
    "${release_dir}/realm-continuity.sha256" >/dev/null 2>&1 \
    && shasum -a 256 -c \
      "${release_dir}/realm-continuity-ingress.sha256" >/dev/null 2>&1 \
    && verify_macos_continuity_artifact_sha256 \
      "${release_dir}/realm-continuity" "${runtime_sha}" \
    && verify_macos_continuity_artifact_sha256 \
      "${release_dir}/realm-continuity-ingress" "${ingress_sha}" \
    && verify_macos_continuity_artifact_architecture \
      "${release_dir}/realm-continuity" "${suffix}" \
    && verify_macos_continuity_artifact_architecture \
      "${release_dir}/realm-continuity-ingress" "${suffix}"
}

install_macos_continuity_package(){
  local agent_dir="$1"
  local repo_root=""
  local manifest=""
  local suffix=""
  local runtime_source=""
  local ingress_source=""
  local runtime_sha=""
  local ingress_sha=""
  local configured_sha=""
  local stage=""

  resolve_macos_continuity_install_request || return 1
  [[ "${REALM_MAC_CONTINUITY_INSTALL_REQUESTED}" == "1" ]] || return 0
  resolve_macos_continuity_release_root || return 1
  repo_root="$(cd "${agent_dir}/.." && pwd -P)"
  manifest="${repo_root}/manifest.json"
  suffix="$(macos_continuity_platform_suffix)" || return 1
  runtime_source="$(find_macos_continuity_artifact \
    "${agent_dir}" realm-continuity "${suffix}")" || return 1
  ingress_source="$(find_macos_continuity_artifact \
    "${agent_dir}" realm-continuity-ingress "${suffix}")" || return 1
  runtime_sha="$(verify_macos_continuity_artifact \
    "${manifest}" "${runtime_source}" realm-continuity "${suffix}")" || return 1
  ingress_sha="$(verify_macos_continuity_artifact \
    "${manifest}" "${ingress_source}" realm-continuity-ingress "${suffix}")" || return 1
  REALM_MAC_CONTINUITY_PACKAGE_SHA="$(macos_continuity_package_identity \
    "${runtime_source}" "${ingress_source}")" || return 1
  configured_sha="${REALM_CONTINUITY_PACKAGE_SHA:-}"
  if [[ -n "${configured_sha}" \
    && "${configured_sha}" != "${REALM_MAC_CONTINUITY_PACKAGE_SHA}" ]]; then
    err "配置的 continuity package SHA 与制品不匹配"
    return 1
  fi
  install -d -m 755 "${REALM_MAC_CONTINUITY_RELEASE_ROOT}" || return 1
  [[ ! -L "${REALM_MAC_CONTINUITY_RELEASE_ROOT}" ]] || {
    err "continuity releases 路径不能是符号链接"
    return 1
  }
  REALM_MAC_CONTINUITY_RELEASE_DIR="${REALM_MAC_CONTINUITY_RELEASE_ROOT}/${REALM_MAC_CONTINUITY_PACKAGE_SHA}"
  if [[ -e "${REALM_MAC_CONTINUITY_RELEASE_DIR}" \
    || -L "${REALM_MAC_CONTINUITY_RELEASE_DIR}" ]]; then
    if ! verify_macos_installed_continuity_package \
      "${REALM_MAC_CONTINUITY_RELEASE_DIR}" \
      "${runtime_sha}" "${ingress_sha}" "${suffix}"; then
      err "现有 continuity package 校验失败：${REALM_MAC_CONTINUITY_RELEASE_DIR}"
      return 1
    fi
  else
    stage="$(mktemp -d "${REALM_MAC_CONTINUITY_RELEASE_ROOT}/.package.XXXXXX")" || return 1
    if ! install -m 755 "${runtime_source}" "${stage}/realm-continuity" \
      || ! install -m 755 "${ingress_source}" "${stage}/realm-continuity-ingress" \
      || ! printf '%s  %s\n' "${runtime_sha}" \
        "${REALM_MAC_CONTINUITY_RELEASE_DIR}/realm-continuity" \
        > "${stage}/realm-continuity.sha256" \
      || ! printf '%s  %s\n' "${ingress_sha}" \
        "${REALM_MAC_CONTINUITY_RELEASE_DIR}/realm-continuity-ingress" \
        > "${stage}/realm-continuity-ingress.sha256"; then
      rm -rf "${stage}" >/dev/null 2>&1 || true
      return 1
    fi
    chmod 444 "${stage}"/*.sha256 || {
      rm -rf "${stage}" >/dev/null 2>&1 || true
      return 1
    }
    if ! mv "${stage}" "${REALM_MAC_CONTINUITY_RELEASE_DIR}"; then
      rm -rf "${stage}" >/dev/null 2>&1 || true
      return 1
    fi
    REALM_MAC_CONTINUITY_RELEASE_CREATED="1"
    persist_transaction_value \
      "${REALM_MAC_TRANSACTION_DIR}/continuity-release-created" \
      "${REALM_MAC_CONTINUITY_RELEASE_DIR}" || return 1
    if ! verify_macos_installed_continuity_package \
      "${REALM_MAC_CONTINUITY_RELEASE_DIR}" \
      "${runtime_sha}" "${ingress_sha}" "${suffix}"; then
      err "安装后的 continuity package 校验失败"
      return 1
    fi
  fi
  chmod 755 "${REALM_MAC_CONTINUITY_RELEASE_DIR}" \
    "${REALM_MAC_CONTINUITY_RELEASE_DIR}/realm-continuity" \
    "${REALM_MAC_CONTINUITY_RELEASE_DIR}/realm-continuity-ingress" || return 1
  info "已安装 continuity package ${REALM_MAC_CONTINUITY_PACKAGE_SHA}（${suffix}）"
}

rollback_macos_continuity_package(){
  [[ "${REALM_MAC_CONTINUITY_RELEASE_CREATED:-0}" == "1" ]] || return 0
  macos_continuity_release_path_safe \
    "${REALM_MAC_CONTINUITY_RELEASE_DIR}" \
    "${REALM_MAC_CONTINUITY_RELEASE_ROOT}" || return 1
  [[ -d "${REALM_MAC_CONTINUITY_RELEASE_DIR}" \
    && ! -L "${REALM_MAC_CONTINUITY_RELEASE_DIR}" ]] || return 1
  rm -rf "${REALM_MAC_CONTINUITY_RELEASE_DIR}" || return 1
  REALM_MAC_CONTINUITY_RELEASE_CREATED="0"
}

rollback_macos_continuity_package_from_transaction(){
  local release_dir=""
  local release_root=""
  release_dir="$(read_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/continuity-release-created" || true)"
  [[ -n "${release_dir}" ]] || return 0
  release_root="$(dirname "${release_dir}")"
  valid_macos_continuity_release_root "${release_root}" || return 1
  macos_continuity_release_path_safe "${release_dir}" "${release_root}" || return 1
  [[ -e "${release_dir}" || -L "${release_dir}" ]] || return 0
  [[ -d "${release_dir}" && ! -L "${release_dir}" ]] || return 1
  rm -rf "${release_dir}"
}

macos_agent_file_mode(){
  local path="$1"
  if [[ "$(uname -s)" == "Darwin" ]]; then
    stat -f '%Lp' "${path}" 2>/dev/null
  else
    stat -c '%a' "${path}" 2>/dev/null
  fi
}

macos_agent_file_uid(){
  local path="$1"
  if [[ "$(uname -s)" == "Darwin" ]]; then
    stat -f '%u' "${path}" 2>/dev/null
  else
    stat -c '%u' "${path}" 2>/dev/null
  fi
}

validate_macos_agent_tls_path(){
  local path="${1:-}"
  local secret="${2:-0}"
  local expected_uid="${REALM_AGENT_TLS_EXPECTED_UID:-0}"
  local mode=""
  [[ "${path}" == /* && "${path}" != *$'\n'* && "${path}" != *$'\r'* ]] || return 1
  [[ -f "${path}" && ! -L "${path}" && -r "${path}" ]] || return 1
  [[ "$(macos_agent_file_uid "${path}" || true)" == "${expected_uid}" ]] || return 1
  mode="$(macos_agent_file_mode "${path}" || true)"
  [[ "${mode}" =~ ^[0-7]{3,4}$ ]] || return 1
  if [[ "${secret}" == "1" ]]; then
    (( (8#${mode} & 0077) == 0 ))
  else
    (( (8#${mode} & 0022) == 0 ))
  fi
}

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

validate_macos_agent_tls_directory(){
  local path="${1:-}"
  local expected_uid="${REALM_AGENT_TLS_EXPECTED_UID:-0}"
  local mode=""
  local uid=""
  [[ "${path}" == /* && -d "${path}" && ! -L "${path}" ]] || return 1
  uid="$(macos_agent_file_uid "${path}" || true)"
  [[ "${uid}" == "0" || "${uid}" == "${expected_uid}" ]] || return 1
  mode="$(macos_agent_file_mode "${path}" || true)"
  [[ "${mode}" =~ ^[0-7]{3,4}$ ]] || return 1
  (( (8#${mode} & 0022) == 0 ))
}

ensure_macos_agent_tls_directory(){
  local target="${1:-}"
  local current="${target}"
  local parent=""
  local -a missing=()
  local index=0
  [[ "${target}" == /* && "${target}" != "/" ]] || return 1
  while [[ ! -e "${current}" && ! -L "${current}" ]]; do
    missing[${#missing[@]}]="${current}"
    parent="$(dirname "${current}")"
    [[ "${parent}" != "${current}" ]] || return 1
    current="${parent}"
  done
  while :; do
    validate_macos_agent_tls_directory "${current}" || return 1
    [[ "${current}" == "/" ]] && break
    current="$(dirname "${current}")"
  done
  for (( index=${#missing[@]} - 1; index >= 0; index-- )); do
    current="${missing[${index}]}"
    mkdir -m 700 "${current}" || return 1
    validate_macos_agent_tls_directory "${current}" || return 1
  done
}

validate_macos_agent_tls_target_path(){
  local path="${1:-}"
  local parent=""
  [[ "${path}" == /* && "${path}" != *$'\n'* && "${path}" != *$'\r'* ]] || return 1
  [[ "${path}" != *"/../"* && "${path}" != */.. && "${path}" != *"/./"* ]] || return 1
  [[ "${path}" != */ && "$(basename "${path}")" != "." ]] || return 1
  parent="$(dirname "${path}")"
  ensure_macos_agent_tls_directory "${parent}" || return 1
  [[ ! -L "${path}" ]]
}

macos_agent_tls_san_entry(){
  local server_name="${1:-}"
  if [[ "${server_name}" == \[*\] ]]; then
    server_name="${server_name#[}"
    server_name="${server_name%]}"
  fi
  [[ -n "${server_name}" && "${server_name}" =~ ^[A-Za-z0-9*._:-]+$ ]] || return 1
  if [[ "${server_name}" == *:* \
    || "${server_name}" =~ ^[0-9]+(\.[0-9]+){3}$ ]]; then
    printf 'IP:%s' "${server_name}"
  else
    printf 'DNS:%s' "${server_name}"
  fi
}

prepare_macos_agent_https_material(){
  local transport="${1:-}"
  local cert="${2:-}"
  local key="${3:-}"
  local server_name="${4:-}"
  local ca_cert="${5:-}"
  local auto_generate="${6:-0}"
  local verify_peer="${7:-0}"
  local cert_exists="0"
  local key_exists="0"
  local cert_parent=""
  local key_parent=""
  local stage=""
  local openssl_config=""
  local san_entry=""
  local staged_cert=""
  local staged_key=""
  local target_cert=""
  local target_key=""

  [[ "${transport}" == "https" ]] || return 0
  auto_generate="$(normalize_macos_agent_tls_flag "${auto_generate}")" || {
    err "REALM_AGENT_TLS_AUTO_GENERATE 仅支持 0/1 或布尔值"
    return 1
  }
  verify_peer="$(normalize_macos_agent_tls_flag "${verify_peer}")" || {
    err "REALM_AGENT_TLS_VERIFY_PEER 仅支持 0/1 或布尔值"
    return 1
  }
  [[ -e "${cert}" || -L "${cert}" ]] && cert_exists="1"
  [[ -e "${key}" || -L "${key}" ]] && key_exists="1"
  if [[ "${cert_exists}" != "${key_exists}" ]]; then
    err "HTTPS cert/key 仅存在一个，拒绝自动生成或覆盖"
    return 1
  fi
  [[ "${cert_exists}" == "0" ]] || return 0
  if [[ "${auto_generate}" != "1" ]]; then
    err "HTTPS cert/key 缺失，且 REALM_AGENT_TLS_AUTO_GENERATE 未明确启用"
    return 1
  fi
  if [[ -n "${ca_cert}" || "${verify_peer}" == "1" ]]; then
    err "HTTPS CA/严格验证模式禁止自动生成不受信任的自签证书"
    return 1
  fi
  [[ -n "${server_name}" ]] || {
    err "自动生成 HTTPS 证书必须提供 REALM_AGENT_TLS_SERVER_NAME"
    return 1
  }
  validate_macos_agent_tls_target_path "${cert}" || {
    err "HTTPS 证书目标路径或父目录不安全：${cert}"
    return 1
  }
  validate_macos_agent_tls_target_path "${key}" || {
    err "HTTPS 私钥目标路径或父目录不安全：${key}"
    return 1
  }
  cert_parent="$(dirname "${cert}")"
  key_parent="$(dirname "${key}")"
  if [[ "${cert_parent}" != "${key_parent}" ]]; then
    err "自动生成 HTTPS cert/key 必须位于同一安全目录"
    return 1
  fi
  command_exists openssl || {
    err "缺少 openssl，无法生成 HTTPS 自签证书"
    return 1
  }
  san_entry="$(macos_agent_tls_san_entry "${server_name}" || true)"
  [[ -n "${san_entry}" ]] || {
    err "TLS server name 无法安全写入证书 SAN：${server_name}"
    return 1
  }
  stage="$(mktemp -d "${cert_parent}/.realm-agent-tls.XXXXXX")" || return 1
  register_cleanup_path "${stage}"
  chmod 700 "${stage}" || return 1
  openssl_config="${stage}/openssl.cnf"
  staged_cert="${stage}/server.crt"
  staged_key="${stage}/server.key"
  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_entry}
EOF
  chmod 600 "${openssl_config}" || return 1
  if ! openssl req -x509 -nodes -newkey rsa:3072 -sha256 -days 825 \
    -keyout "${staged_key}" -out "${staged_cert}" \
    -config "${openssl_config}" >/dev/null 2>&1; then
    err "生成 Agent 自签 HTTPS 证书失败"
    return 1
  fi
  chmod 600 "${staged_key}" || return 1
  chmod 644 "${staged_cert}" || return 1
  validate_macos_agent_https_config \
    "${staged_cert}" "${staged_key}" "${server_name}" "" || {
    err "新生成的 Agent HTTPS cert/key 未通过现有校验"
    return 1
  }
  target_cert="$(mktemp "${cert_parent}/.realm-agent-cert.XXXXXX")" || return 1
  target_key="$(mktemp "${key_parent}/.realm-agent-key.XXXXXX")" || return 1
  register_cleanup_path "${target_cert}"
  register_cleanup_path "${target_key}"
  install -m 0644 "${staged_cert}" "${target_cert}" || return 1
  install -m 0600 "${staged_key}" "${target_key}" || return 1
  if [[ -e "${cert}" || -L "${cert}" || -e "${key}" || -L "${key}" ]]; then
    err "HTTPS cert/key 目标在安装期间发生变化，拒绝覆盖"
    return 1
  fi
  mv "${target_key}" "${key}" || return 1
  if ! mv "${target_cert}" "${cert}"; then
    rm -f "${key}"
    return 1
  fi
  chmod 600 "${key}" || return 1
  chmod 644 "${cert}" || return 1
  rm -rf "${stage}" || return 1
  info "已安全生成并安装 Agent 自签 HTTPS 证书：${cert}" >&2
}

validate_macos_agent_https_config(){
  local cert="${1:-}"
  local key="${2:-}"
  local server_name="${3:-}"
  local ca_cert="${4:-}"
  local cert_pub=""
  local key_pub=""
  local cert_pub_file=""
  local key_pub_file=""
  validate_macos_agent_tls_path "${cert}" || {
    err "HTTPS 证书路径无效或所有权/权限不安全：${cert}"
    return 1
  }
  validate_macos_agent_tls_path "${key}" "1" || {
    err "HTTPS 私钥路径无效或所有权/权限不安全：${key}"
    return 1
  }
  if [[ -n "${ca_cert}" ]] \
    && ! validate_macos_agent_tls_path "${ca_cert}"; then
    err "HTTPS CA 证书路径无效或所有权/权限不安全：${ca_cert}"
    return 1
  fi
  command_exists openssl || {
    err "缺少 openssl，无法验证 HTTPS 证书/私钥"
    return 1
  }
  if ! openssl x509 -in "${cert}" -noout >/dev/null 2>&1 \
    || ! openssl x509 -checkend 0 -in "${cert}" -noout >/dev/null 2>&1; then
    err "HTTPS 证书无法解析或已过期：${cert}"
    return 1
  fi
  if ! openssl pkey -in "${key}" -noout >/dev/null 2>&1; then
    err "HTTPS 私钥无法解析：${key}"
    return 1
  fi
  cert_pub_file="$(mktemp -t realm-agent-macos-cert-pub.XXXXXX)" || return 1
  key_pub_file="$(mktemp -t realm-agent-macos-key-pub.XXXXXX)" || return 1
  register_cleanup_path "${cert_pub_file}"
  register_cleanup_path "${key_pub_file}"
  if ! openssl x509 -in "${cert}" -pubkey -noout > "${cert_pub_file}" \
    || ! openssl pkey -in "${key}" -pubout > "${key_pub_file}"; then
    err "HTTPS cert/key 公钥无法提取"
    return 1
  fi
  cert_pub="$(cat "${cert_pub_file}")"
  key_pub="$(cat "${key_pub_file}")"
  if [[ "${cert_pub}" != "${key_pub}" ]]; then
    err "HTTPS cert 与 key 公钥不匹配"
    return 1
  fi
  if [[ -n "${server_name}" ]]; then
    if ! openssl x509 -in "${cert}" -checkhost "${server_name}" -noout \
      >/dev/null 2>&1 \
      && ! openssl x509 -in "${cert}" -checkip "${server_name}" -noout \
        >/dev/null 2>&1; then
      err "HTTPS 证书不匹配 TLS server name：${server_name}"
      return 1
    fi
  fi
  if [[ -n "${ca_cert}" ]] \
    && ! openssl verify -purpose sslserver -CAfile "${ca_cert}" "${cert}" \
      >/dev/null 2>&1; then
    err "HTTPS 证书无法通过指定 CA 校验：${ca_cert}"
    return 1
  fi
}

validate_macos_agent_bind_contract(){
  local host="${1:-}"
  local port="${2:-}"
  local transport="${3:-}"
  local cert="${4:-}"
  local key="${5:-}"
  local server_name="${6:-}"
  local ca_cert="${7:-}"
  local insecure_override="${8:-0}"
  local normalized_host=""
  local normalized_transport=""

  normalized_host="$(normalize_macos_agent_host "${host}" || true)"
  if [[ -z "${normalized_host}" || "${normalized_host}" != "${host}" ]]; then
    err "Agent 监听地址非法或未规范化：${host}"
    return 1
  fi
  if [[ ! "${port}" =~ ^[0-9]+$ ]] \
    || (( 10#${port} < 1 || 10#${port} > 65535 )); then
    err "Agent 端口无效：${port}"
    return 1
  fi
  normalized_transport="$(normalize_macos_agent_transport "${transport}" || true)"
  [[ -n "${normalized_transport}" ]] || {
    err "Agent 传输类型仅支持 http 或 https：${transport}"
    return 1
  }
  if [[ "${normalized_transport}" == "https" ]]; then
    if [[ "${normalized_host}" == "0.0.0.0" || "${normalized_host}" == "::" ]] \
      && [[ -z "${server_name}" ]]; then
      err "HTTPS wildcard 监听必须提供 REALM_AGENT_TLS_SERVER_NAME"
      return 1
    fi
    validate_macos_agent_https_config \
      "${cert}" "${key}" "${server_name}" "${ca_cert}" || return 1
    return 0
  fi
  if is_macos_agent_loopback_host "${normalized_host}"; then
    return 0
  fi
  if macos_agent_bool_enabled "${insecure_override}"; then
    warn "已启用高风险 REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK=1：" >&2
    warn "Agent 将以明文 HTTP 绑定非 loopback 地址 ${normalized_host}:${port}" >&2
    return 0
  fi
  err "拒绝非 loopback 明文 HTTP Agent：${normalized_host}:${port}"
  err "请改用 HTTPS（REALM_AGENT_TRANSPORT=https）并提供证书/私钥，或显式设置 REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK=1"
  return 1
}

resolve_macos_agent_contract(){
  local agent_env_file="/etc/realm-agent/agent.env"
  local existing_host=""
  local existing_port=""
  local existing_transport=""
  local existing_cert=""
  local existing_key=""
  local existing_server_name=""
  local existing_ca_cert=""
  local existing_auto_generate=""
  local existing_verify_peer=""
  local existing_override=""
  local host=""
  local port=""
  local transport=""
  local cert=""
  local key=""
  local server_name=""
  local ca_cert=""
  local auto_generate=""
  local verify_peer=""
  local insecure_override=""

  existing_host="$(read_env_value "${agent_env_file}" REALM_AGENT_HOST || true)"
  existing_port="$(read_env_value "${agent_env_file}" REALM_AGENT_PORT || true)"
  existing_transport="$(read_env_value "${agent_env_file}" REALM_AGENT_TRANSPORT || true)"
  existing_cert="$(read_env_value "${agent_env_file}" REALM_AGENT_SSL_CERT || true)"
  existing_key="$(read_env_value "${agent_env_file}" REALM_AGENT_SSL_KEY || true)"
  existing_server_name="$(read_env_value \
    "${agent_env_file}" REALM_AGENT_TLS_SERVER_NAME || true)"
  existing_ca_cert="$(read_env_value \
    "${agent_env_file}" REALM_AGENT_TLS_CA_CERT || true)"
  existing_auto_generate="$(read_env_value \
    "${agent_env_file}" REALM_AGENT_TLS_AUTO_GENERATE || true)"
  existing_verify_peer="$(read_env_value \
    "${agent_env_file}" REALM_AGENT_TLS_VERIFY_PEER || true)"
  existing_override="$(read_env_value \
    "${agent_env_file}" REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK || true)"

  host="$(normalize_macos_agent_host \
    "${REALM_AGENT_HOST:-${existing_host:-${DEFAULT_HOST}}}" || true)"
  port="${REALM_AGENT_PORT:-${existing_port:-${DEFAULT_PORT}}}"
  transport="${REALM_AGENT_TRANSPORT:-${existing_transport:-http}}"
  cert="${REALM_AGENT_SSL_CERT:-${existing_cert:-/etc/realm-agent/certs/server.crt}}"
  key="${REALM_AGENT_SSL_KEY:-${existing_key:-/etc/realm-agent/certs/server.key}}"
  server_name="${REALM_AGENT_TLS_SERVER_NAME:-${existing_server_name:-}}"
  ca_cert="${REALM_AGENT_TLS_CA_CERT:-${existing_ca_cert:-}}"
  auto_generate="${REALM_AGENT_TLS_AUTO_GENERATE:-${existing_auto_generate:-0}}"
  verify_peer="${REALM_AGENT_TLS_VERIFY_PEER:-${existing_verify_peer:-0}}"
  insecure_override="${REALM_AGENT_ALLOW_INSECURE_NON_LOOPBACK:-${existing_override:-}}"
  [[ -n "${host}" ]] || {
    err "REALM_AGENT_HOST 非法"
    return 1
  }
  if [[ ! "${port}" =~ ^[0-9]+$ ]] \
    || (( 10#${port} < 1 || 10#${port} > 65535 )); then
    err "REALM_AGENT_PORT 无效：${port}"
    return 1
  fi
  port="$((10#${port}))"
  transport="$(normalize_macos_agent_transport "${transport}" || true)"
  [[ -n "${transport}" ]] || {
    err "REALM_AGENT_TRANSPORT 仅支持 http 或 https"
    return 1
  }
  if [[ -z "${insecure_override}" ]]; then
    insecure_override="$(legacy_macos_insecure_override \
      "${existing_host}" "${existing_transport}" "${existing_override}" \
      "${host}" "${transport}")"
    if [[ "${insecure_override}" == "1" ]]; then
      warn "检测到既有非 loopback HTTP Agent，更新时保留兼容 override"
    fi
  fi
  [[ -n "${insecure_override}" ]] || insecure_override="0"
  if [[ "${transport}" == "https" && -z "${server_name}" \
    && "${host}" != "0.0.0.0" && "${host}" != "::" ]]; then
    server_name="${host}"
  fi
  prepare_macos_agent_https_material \
    "${transport}" "${cert}" "${key}" "${server_name}" "${ca_cert}" \
    "${auto_generate}" "${verify_peer}" || return 1
  validate_macos_agent_bind_contract \
    "${host}" "${port}" "${transport}" "${cert}" "${key}" \
    "${server_name}" "${ca_cert}" "${insecure_override}" || return 1
  printf '%s\n' \
    "${host}" "${port}" "${transport}" "${cert}" "${key}" \
    "${server_name}" "${ca_cert}" "${insecure_override}"
}

remote_control_enabled(){
  local value="${REMOTE_CONTROL_ENABLED:-1}"
  value="$(printf '%s' "${value}" | tr '[:upper:]' '[:lower:]')"
  case "${value}" in
    0|false|no|off|n) return 1 ;;
    *) return 0 ;;
  esac
}

remote_control_preserve_enabled(){
  local value="${REMOTE_CONTROL_PRESERVE:-0}"
  value="$(printf '%s' "${value}" | tr '[:upper:]' '[:lower:]')"
  case "${value}" in
    1|true|yes|on|y) return 0 ;;
    *) return 1 ;;
  esac
}

panel_url_without_trailing_slash(){
  local value="${1:-}"
  value="$(printf '%s' "${value}" | tr -d '\r' | sed 's/[[:space:]]*$//' | sed 's#/*$##')"
  printf '%s' "${value}"
}

remote_companion_panel_url_allowed(){
  local panel_url=""
  local authority=""
  local host=""
  local port=""
  panel_url="$(panel_url_without_trailing_slash "${1:-}")"
  [[ -n "${panel_url}" ]] || return 1
  [[ "${panel_url}" != *[\?\#]* ]] || return 1

  case "${panel_url}" in
    https://*)
      authority="${panel_url#https://}"
      authority="${authority%%/*}"
      [[ -n "${authority}" \
        && "${authority}" != *@* \
        && "${authority}" != *[[:space:]]* ]]
      ;;
    http://*)
      authority="${panel_url#http://}"
      authority="${authority%%/*}"
      [[ -n "${authority}" \
        && "${authority}" != *@* \
        && "${authority}" != *[[:space:]]* ]] || return 1
      if [[ "${authority}" == \[* ]]; then
        [[ "${authority}" =~ ^\[::1\](:[0-9]+)?$ ]] || return 1
        port="${authority#\[::1\]}"
        port="${port#:}"
      else
        host="${authority%%:*}"
        if [[ "${authority}" == *:* ]]; then
          port="${authority#*:}"
          [[ "${port}" != *:* ]] || return 1
        fi
        host="$(printf '%s' "${host}" | tr '[:upper:]' '[:lower:]')"
        [[ "${host}" == "localhost" || "${host}" == "127.0.0.1" ]] || return 1
      fi
      if [[ -n "${port}" ]]; then
        [[ "${port}" =~ ^[0-9]+$ ]] || return 1
        ((10#${port} >= 1 && 10#${port} <= 65535)) || return 1
      fi
      ;;
    *)
      return 1
      ;;
  esac
}

preflight_remote_companion_panel_transport(){
  remote_control_preserve_enabled && return 0
  remote_control_enabled || return 0
  local panel_url=""
  panel_url="$(resolve_remote_companion_panel_url)"
  if remote_companion_panel_url_allowed "${panel_url}"; then
    return 0
  fi
  err "RemoteMacAgent 拒绝不安全的 panel URL：${panel_url:-missing}"
  err "远程 panel 必须使用 HTTPS；明文 HTTP 仅允许 localhost、127.0.0.1 或 [::1]"
  return 1
}

remote_companion_app_executable(){
  local app_path="${1:-$REMOTE_COMPANION_APP_PATH}"
  local exe=""
  if [[ ! -d "${app_path}" ]]; then
    return 1
  fi
  exe="$(find "${app_path}/Contents/MacOS" -maxdepth 1 -type f -perm -100 -print 2>/dev/null | head -n 1 || true)"
  if [[ -n "${exe}" ]]; then
    echo "${exe}"
    return 0
  fi
  return 1
}

remote_companion_current_arch(){
  local raw="${1:-}"
  if [[ -z "${raw}" ]]; then
    raw="$(uname -m)"
  fi
  case "${raw}" in
    arm64|aarch64)
      printf 'arm64\n'
      ;;
    x86_64|amd64)
      printf 'x86_64\n'
      ;;
    *)
      return 1
      ;;
  esac
}

remote_companion_binary_arches(){
  local binary="${1:-}"
  local output=""
  [[ -n "${binary}" && -f "${binary}" ]] || return 1
  if [[ -x /usr/bin/lipo ]]; then
    output="$(/usr/bin/lipo -archs "${binary}" 2>/dev/null || true)"
    if [[ -n "${output}" ]]; then
      printf '%s\n' "${output}"
      return 0
    fi
  fi
  if command_exists file; then
    output="$(file -b "${binary}" 2>/dev/null || true)"
    local arches=""
    if [[ "${output}" == *arm64* ]]; then
      arches="arm64"
    fi
    if [[ "${output}" == *x86_64* ]]; then
      arches="${arches:+${arches} }x86_64"
    fi
    if [[ -n "${arches}" ]]; then
      printf '%s\n' "${arches}"
      return 0
    fi
  fi
  return 1
}

remote_companion_artifact_architecture_matches(){
  local artifact="${1:-}"
  local executable=""
  local expected=""
  local arches=""
  # Staged upgrades use a trusted directory such as RemoteMacAgent.app.new.
  # Validate the bundle contents instead of requiring the temporary path to
  # end in .app, otherwise every atomic replacement is rejected before lipo.
  if [[ -d "${artifact}" ]]; then
    executable="$(remote_companion_app_executable "${artifact}" || true)"
  elif [[ -f "${artifact}" ]]; then
    executable="${artifact}"
  fi
  [[ -n "${executable}" ]] || return 1
  expected="$(remote_companion_current_arch || true)"
  [[ -n "${expected}" ]] || return 1
  arches="$(remote_companion_binary_arches "${executable}" || true)"
  [[ -n "${arches}" ]] || return 1
  case " ${arches} " in
    *" ${expected} "*) return 0 ;;
    *) return 1 ;;
  esac
}

set_remote_companion_transaction_paths(){
  REMOTE_COMPANION_TRANSACTION_DIR="${REMOTE_COMPANION_APP_PATH}.transaction"
  REMOTE_COMPANION_UPDATE_BACKUP="${REMOTE_COMPANION_APP_PATH}.previous"
}

canonical_macos_transaction_path(){
  local path="${1:-}"
  local allowed_root="${2:-}"
  local containment="${3:-allow-root}"
  [[ "${path}" == /* \
    && "${path}" != *$'\n'* \
    && "${path}" != *$'\r'* ]] || return 1
  ensure_trusted_macos_agent_python || return 1
  run_trusted_macos_python - \
    "${path}" "${allowed_root}" "${containment}" <<'PY'
import os
import sys

path, allowed_root, containment = sys.argv[1:]


def validate_absolute_lexical_path(value: str) -> None:
    if not value.startswith("/") or "\n" in value or "\r" in value:
        raise SystemExit("path is not a clean absolute path")
    components = value[1:].split("/")
    if not components or any(
        component in {"", ".", ".."} for component in components
    ):
        raise SystemExit("path contains an unsafe component")


validate_absolute_lexical_path(path)
canonical = os.path.realpath(path)
if allowed_root:
    validate_absolute_lexical_path(allowed_root)
    canonical_root = os.path.realpath(allowed_root)
    if os.path.commonpath((canonical, canonical_root)) != canonical_root:
        raise SystemExit("path escapes its allowed root")
    if containment == "strict" and canonical == canonical_root:
        raise SystemExit("path must be below its allowed root")

    lexical_root = os.path.normpath(allowed_root)
    lexical_path = os.path.normpath(path)
    if os.path.commonpath((lexical_path, lexical_root)) != lexical_root:
        raise SystemExit("lexical path escapes its allowed root")
    relative = os.path.relpath(lexical_path, lexical_root)
    current = lexical_root
    paths_to_check = [current]
    if relative != ".":
        for component in relative.split(os.sep):
            current = os.path.join(current, component)
            paths_to_check.append(current)
    if any(os.path.lexists(item) and os.path.islink(item) for item in paths_to_check):
        raise SystemExit("path contains a symlink ancestor")

print(canonical)
PY
}

reset_remote_companion_desktop_context(){
  REMOTE_COMPANION_DESKTOP_USER=""
  REMOTE_COMPANION_DESKTOP_UID=""
  REMOTE_COMPANION_DESKTOP_GID=""
  REMOTE_COMPANION_DESKTOP_GROUP=""
  REMOTE_COMPANION_DESKTOP_HOME=""
  REMOTE_COMPANION_DESKTOP_PLIST=""
}

remote_companion_desktop_identity_matches(){
  local user="${1:-}"
  local uid="${2:-}"
  local gid="${3:-}"
  local group="${4:-}"
  [[ -n "${user}" \
    && "${uid}" =~ ^[0-9]+$ \
    && "${gid}" =~ ^[0-9]+$ \
    && -n "${group}" \
    && "$(id -u "${user}" 2>/dev/null || true)" == "${uid}" \
    && "$(id -g "${user}" 2>/dev/null || true)" == "${gid}" \
    && "$(id -gn "${user}" 2>/dev/null || true)" == "${group}" ]]
}

resolve_remote_companion_desktop_context(){
  local user=""
  local uid=""
  local actual_uid=""
  local gid=""
  local group=""
  local home=""
  reset_remote_companion_desktop_context
  user="$(console_user || true)"
  uid="$(console_uid || true)"
  if [[ -z "${user}" && -z "${uid}" ]]; then
    return 0
  fi
  if [[ -z "${user}" || ! "${uid}" =~ ^[0-9]+$ ]]; then
    err "Aqua 桌面用户身份不完整，拒绝继续 RemoteMacAgent 更新"
    return 1
  fi
  actual_uid="$(id -u "${user}" 2>/dev/null || true)"
  gid="$(id -g "${user}" 2>/dev/null || true)"
  group="$(id -gn "${user}" 2>/dev/null || true)"
  home="$(console_home "${user}" || true)"
  home="$(canonical_macos_transaction_path "${home}" || true)"
  if [[ "${actual_uid}" != "${uid}" \
    || ! "${gid}" =~ ^[0-9]+$ \
    || -z "${group}" \
    || -z "${home}" \
    || ! -d "${home}" \
    || -L "${home}" ]]; then
    err "Aqua 桌面用户身份在解析期间发生变化，拒绝继续 RemoteMacAgent 更新"
    return 1
  fi
  REMOTE_COMPANION_DESKTOP_USER="${user}"
  REMOTE_COMPANION_DESKTOP_UID="${uid}"
  REMOTE_COMPANION_DESKTOP_GID="${gid}"
  REMOTE_COMPANION_DESKTOP_GROUP="${group}"
  REMOTE_COMPANION_DESKTOP_HOME="${home}"
  REMOTE_COMPANION_DESKTOP_PLIST="${home}/Library/LaunchAgents/${REMOTE_COMPANION_LABEL}.plist"
}

new_macos_transaction_id(){
  local value=""
  if command_exists openssl; then
    value="$(openssl rand -hex 32 2>/dev/null || true)"
  fi
  if [[ -z "${value}" ]] && ensure_trusted_macos_agent_python; then
    value="$(run_trusted_macos_python - <<'PY' 2>/dev/null || true
import secrets

print(secrets.token_hex(32))
PY
)"
  fi
  normalize_sha256 "${value}"
}

remote_companion_joint_transaction_matches(){
  local schema=""
  local remote_state=""
  local remote_main_path=""
  local remote_main_id=""
  local remote_app_path=""
  local snapshot_home=""
  local current_main_path=""
  local expected_main_path=""
  local current_main_id=""
  local current_app_path=""
  local canonical_remote_app_path=""
  set_remote_companion_transaction_paths
  [[ -d "${REMOTE_COMPANION_TRANSACTION_DIR}" \
    && ! -L "${REMOTE_COMPANION_TRANSACTION_DIR}" \
    && -d "${REALM_MAC_TRANSACTION_DIR}" \
    && ! -L "${REALM_MAC_TRANSACTION_DIR}" ]] || return 1
  schema="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/transaction-schema" || true)"
  remote_state="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/state" || true)"
  [[ "${schema}" == "2" ]] || return 1
  case "${remote_state}" in
    prepared|quiescing|quiesced|old-moved|new-active|commit-prepared|committed) ;;
    *) return 1 ;;
  esac
  remote_main_path="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/main-transaction-path" || true)"
  remote_main_id="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/main-transaction-id" || true)"
  remote_app_path="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/companion-app-path" || true)"
  snapshot_home="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/launchagent/home" || true)"
  current_main_path="$(
    canonical_macos_transaction_path \
      "${REALM_MAC_TRANSACTION_DIR}" "${BASE_DIR}" "strict" || true
  )"
  expected_main_path="$(
    canonical_macos_transaction_path \
      "${BASE_DIR}/.install-transaction" "${BASE_DIR}" "strict" || true
  )"
  current_main_id="$(read_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/transaction-id" || true)"
  current_app_path="$(
    canonical_remote_companion_app_path \
      "${REMOTE_COMPANION_APP_PATH}" "${snapshot_home}" || true
  )"
  canonical_remote_app_path="$(
    canonical_remote_companion_app_path \
      "${remote_app_path}" "${snapshot_home}" || true
  )"
  [[ -n "${current_main_path}" \
    && "${current_main_path}" == "${expected_main_path}" \
    && -n "${current_app_path}" \
    && "${remote_main_path}" == "${current_main_path}" \
    && "${remote_main_id}" == "${current_main_id}" \
    && "${remote_main_id}" =~ ^[0-9a-f]{64}$ \
    && "${canonical_remote_app_path}" == "${current_app_path}" \
    && "${REMOTE_COMPANION_APP_PATH}" == "${current_app_path}" ]] \
    || return 1
  remote_companion_launchagent_snapshot >/dev/null
}

remote_companion_verification_matches(){
  local verified_id=""
  local remote_main_id=""
  set_remote_companion_transaction_paths
  remote_companion_joint_transaction_matches || return 1
  verified_id="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/companion-verified" || true)"
  remote_main_id="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/main-transaction-id" || true)"
  [[ "${verified_id}" =~ ^[0-9a-f]{64}$ \
    && "${verified_id}" == "${remote_main_id}" ]]
}

remote_companion_requires_main_commit_evidence(){
  local remote_state=""
  local main_state=""
  set_remote_companion_transaction_paths
  remote_state="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/state" || true)"
  case "${remote_state}" in
    new-active|commit-prepared|committed) ;;
    *) return 1 ;;
  esac
  remote_companion_verification_matches || return 1
  main_state="$(read_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" || true)"
  [[ "${main_state}" == "commit-prepared" \
    || "${main_state}" == "committed" ]]
}

macos_joint_commit_decided(){
  local state=""
  [[ -d "${REALM_MAC_TRANSACTION_DIR}" \
    && ! -L "${REALM_MAC_TRANSACTION_DIR}" ]] || return 1
  state="$(read_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" || true)"
  [[ "${state}" == "commit-prepared" || "${state}" == "committed" ]]
}

macos_joint_commit_recovery_context_valid(){
  macos_joint_commit_decided || return 1
  [[ -d "${REALM_MAC_DEPLOY_ROLLBACK_DIR}" \
    && ! -L "${REALM_MAC_DEPLOY_ROLLBACK_DIR}" ]] || return 1
  macos_agent_transaction_stage_path >/dev/null
}

should_recover_macos_joint_commit(){
  local state=""
  macos_joint_commit_decided || return 1
  state="$(read_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" || true)"
  [[ "${state}" == "commit-prepared" ]] \
    || macos_joint_commit_recovery_context_valid
}

remote_companion_launchagent_snapshot(){
  local snapshot_dir=""
  local schema=""
  local available=""
  local uid=""
  local gid=""
  local user=""
  local group=""
  local home=""
  local plist=""
  local loaded=""
  local disabled=""
  set_remote_companion_transaction_paths
  snapshot_dir="${REMOTE_COMPANION_TRANSACTION_DIR}/launchagent"
  schema="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/transaction-schema" || true)"
  [[ -z "${schema}" || "${schema}" == "2" ]] || return 1
  if [[ ! -e "${snapshot_dir}" && ! -L "${snapshot_dir}" ]]; then
    [[ -z "${schema}" ]] || return 1
    printf 'legacy\n'
    return 0
  fi
  [[ -d "${snapshot_dir}" && ! -L "${snapshot_dir}" ]] || return 1
  available="$(read_transaction_value "${snapshot_dir}/available" || true)"
  if [[ -z "${available}" ]]; then
    [[ -z "${schema}" ]] || return 1
    printf 'legacy\n'
    return 0
  fi
  [[ "${available}" == "0" || "${available}" == "1" ]] || return 1
  if [[ "${available}" == "0" ]]; then
    printf '0\n'
    return 0
  fi
  uid="$(read_transaction_value "${snapshot_dir}/uid" || true)"
  gid="$(read_transaction_value "${snapshot_dir}/gid" || true)"
  user="$(read_transaction_value "${snapshot_dir}/user" || true)"
  group="$(read_transaction_value "${snapshot_dir}/group" || true)"
  home="$(read_transaction_value "${snapshot_dir}/home" || true)"
  plist="$(read_transaction_value "${snapshot_dir}/plist-path" || true)"
  loaded="$(read_transaction_value "${snapshot_dir}/loaded" || true)"
  disabled="$(read_transaction_value "${snapshot_dir}/disabled" || true)"
  [[ "${uid}" =~ ^[0-9]+$ \
    && "${gid}" =~ ^[0-9]+$ \
    && -n "${user}" \
    && -n "${group}" \
    && "${home}" == /* \
    && "${plist}" == "${home}/Library/LaunchAgents/${REMOTE_COMPANION_LABEL}.plist" \
    && ( "${loaded}" == "0" || "${loaded}" == "1" ) \
    && ( "${disabled}" == "0" || "${disabled}" == "1" ) ]] || return 1
  remote_companion_desktop_identity_matches \
    "${user}" "${uid}" "${gid}" "${group}" || return 1
  printf '1\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
    "${uid}" "${gid}" "${user}" "${group}" "${home}" "${plist}" \
    "${loaded}" "${disabled}"
}

snapshot_remote_companion_launchagent_state(){
  local transaction_root="${1:-}"
  local user="${2:-}"
  local uid="${3:-}"
  local gid="${4:-}"
  local group="${5:-}"
  local home="${6:-}"
  local plist="${7:-}"
  local snapshot_dir="${transaction_root}/launchagent"
  local target=""
  local loaded="0"
  local disabled=""
  local disabled_output=""
  install -d -m 700 "${snapshot_dir}" || return 1
  if [[ -z "${user}" && -z "${uid}" && -z "${gid}" \
    && -z "${group}" && -z "${home}" && -z "${plist}" ]]; then
    persist_transaction_value "${snapshot_dir}/available" "0"
    return
  fi
  [[ -n "${user}" \
    && "${uid}" =~ ^[0-9]+$ \
    && "${gid}" =~ ^[0-9]+$ \
    && -n "${group}" \
    && "${home}" == /* \
    && "${plist}" == "${home}/Library/LaunchAgents/${REMOTE_COMPANION_LABEL}.plist" \
    && "$(id -u "${user}" 2>/dev/null || true)" == "${uid}" \
    && "$(id -g "${user}" 2>/dev/null || true)" == "${gid}" \
    && "$(id -gn "${user}" 2>/dev/null || true)" == "${group}" \
    && "$(canonical_macos_transaction_path "${home}" || true)" == "${home}" \
    && -d "${home}" \
    && ! -L "${home}" ]] || return 1
  command_exists launchctl || return 1
  target="gui/${uid}/${REMOTE_COMPANION_LABEL}"
  disabled_output="$(launchctl print-disabled "gui/${uid}" 2>&1)" \
    || return 1
  disabled="$(
    macos_launchd_disabled_state_from_output \
      "${REMOTE_COMPANION_LABEL}" "${disabled_output}" || true
  )"
  [[ "${disabled}" == "0" || "${disabled}" == "1" ]] || return 1
  if launchctl print "${target}" >/dev/null 2>&1; then
    loaded="1"
  fi
  persist_transaction_value "${snapshot_dir}/available" "1" || return 1
  persist_transaction_value "${snapshot_dir}/uid" "${uid}" || return 1
  persist_transaction_value "${snapshot_dir}/gid" "${gid}" || return 1
  persist_transaction_value "${snapshot_dir}/user" "${user}" || return 1
  persist_transaction_value "${snapshot_dir}/group" "${group}" || return 1
  persist_transaction_value "${snapshot_dir}/home" "${home}" || return 1
  persist_transaction_value "${snapshot_dir}/plist-path" "${plist}" || return 1
  persist_transaction_value "${snapshot_dir}/loaded" "${loaded}" || return 1
  persist_transaction_value "${snapshot_dir}/disabled" "${disabled}" || return 1
  if [[ -L "${plist}" || ( -e "${plist}" && ! -f "${plist}" ) ]]; then
    return 1
  fi
  if [[ -f "${plist}" ]]; then
    cp -p "${plist}" "${snapshot_dir}/plist" || return 1
    fsync_path_and_parent "${snapshot_dir}/plist" || return 1
  else
    : > "${snapshot_dir}/plist.absent" || return 1
    fsync_path_and_parent "${snapshot_dir}/plist.absent" || return 1
  fi
  fsync_directory_and_parent "${snapshot_dir}"
}

remote_companion_process_pids(){
  local uid="${1:-}"
  local program=""
  local program_regex=""
  [[ "${uid}" =~ ^[0-9]+$ ]] || return 1
  command_exists pgrep || return 1
  program="$(remote_companion_app_executable \
    "${REMOTE_COMPANION_APP_PATH}" || true)"
  [[ -n "${program}" ]] || return 0
  program_regex="$(escape_ere_literal "${program}")"
  pgrep -u "${uid}" -f "^${program_regex}([[:space:]]|$)" \
    2>/dev/null || true
}

remote_companion_process_matches(){
  local uid="${1:-}"
  local pid="${2:-}"
  local expected_program=""
  local command_line=""
  local process_uid=""
  [[ "${uid}" =~ ^[0-9]+$ && "${pid}" =~ ^[0-9]+$ ]] || return 1
  kill -0 "${pid}" >/dev/null 2>&1 || return 1
  process_uid="$(ps -p "${pid}" -o uid= 2>/dev/null \
    | tr -d '[:space:]' || true)"
  [[ "${process_uid}" == "${uid}" ]] || return 1
  expected_program="$(remote_companion_app_executable \
    "${REMOTE_COMPANION_APP_PATH}" || true)"
  [[ -n "${expected_program}" ]] || return 1
  command_line="$(ps -ww -p "${pid}" -o command= 2>/dev/null || true)"
  [[ "${command_line}" == "${expected_program}" \
    || "${command_line}" == "${expected_program} "* ]]
}

terminate_remote_companion_processes(){
  local uid="${1:-}"
  local pid=""
  local -a pids=()
  while IFS= read -r pid; do
    [[ "${pid}" =~ ^[0-9]+$ ]] || continue
    pids+=("${pid}")
  done < <(remote_companion_process_pids "${uid}")
  for pid in "${pids[@]:-}"; do
    kill -TERM "${pid}" >/dev/null 2>&1 || true
  done
  if (( ${#pids[@]} > 0 )); then
    sleep 1
  fi
  while IFS= read -r pid; do
    [[ "${pid}" =~ ^[0-9]+$ ]] || continue
    kill -KILL "${pid}" >/dev/null 2>&1 || true
  done < <(remote_companion_process_pids "${uid}")
}

wait_for_remote_companion_quiesced(){
  local uid="${1:-}"
  local target="gui/${uid}/${REMOTE_COMPANION_LABEL}"
  local attempts="${REALM_REMOTE_COMPANION_QUIESCE_ATTEMPTS:-15}"
  local attempt=""
  local pids=""
  if [[ ! "${attempts}" =~ ^[0-9]+$ ]] \
    || (( 10#${attempts} < 1 || 10#${attempts} > 120 )); then
    attempts=15
  else
    attempts="$((10#${attempts}))"
  fi
  for ((attempt = 1; attempt <= attempts; attempt++)); do
    pids="$(remote_companion_process_pids "${uid}" || true)"
    if ! launchctl print "${target}" >/dev/null 2>&1 \
      && [[ -z "${pids}" ]]; then
      return 0
    fi
    sleep 1
  done
  err "RemoteMacAgent 未能在 app 切换前完全静止：${target}"
  return 1
}

quiesce_remote_companion_launchagent(){
  local snapshot=""
  local available=""
  local uid=""
  local gid=""
  local user=""
  local group=""
  local home=""
  local plist=""
  local loaded=""
  local disabled=""
  local target=""
  snapshot="$(remote_companion_launchagent_snapshot)" || return 1
  IFS=$'\t' read -r \
    available uid gid user group home plist loaded disabled <<< "${snapshot}"
  [[ "${available}" == "1" ]] || return 0
  target="gui/${uid}/${REMOTE_COMPANION_LABEL}"
  if ! launchctl bootout "${target}" >/dev/null 2>&1 \
    && launchctl print "${target}" >/dev/null 2>&1; then
    err "无法停止 RemoteMacAgent LaunchAgent：${target}"
    return 1
  fi
  terminate_remote_companion_processes "${uid}"
  wait_for_remote_companion_quiesced "${uid}"
}

restore_remote_companion_launchagent_plist(){
  local user="${1:-}"
  local uid="${2:-}"
  local gid="${3:-}"
  local group="${4:-}"
  local plist="${5:-}"
  local snapshot_dir="${REMOTE_COMPANION_TRANSACTION_DIR}/launchagent"
  local plist_dir=""
  local temp_path=""
  plist_dir="$(dirname "${plist}")"
  if [[ -f "${snapshot_dir}/plist" \
    && ! -L "${snapshot_dir}/plist" \
    && ! -e "${snapshot_dir}/plist.absent" ]]; then
    install -d -m 755 "${plist_dir}" || return 1
    fix_user_mode_strict \
      "${plist_dir}" 755 "${user}" "${group}" "${uid}" "${gid}" \
      || return 1
    temp_path="$(mktemp "${plist_dir}/.${REMOTE_COMPANION_LABEL}.restore.XXXXXX")" \
      || return 1
    register_cleanup_path "${temp_path}"
    cp -f "${snapshot_dir}/plist" "${temp_path}" || return 1
    validate_plist_file "${temp_path}" || return 1
    fix_user_mode_strict \
      "${temp_path}" 644 "${user}" "${group}" "${uid}" "${gid}" \
      || return 1
    fsync_path_and_parent "${temp_path}" || return 1
    mv -f "${temp_path}" "${plist}" || return 1
    fix_user_mode_strict \
      "${plist}" 644 "${user}" "${group}" "${uid}" "${gid}" \
      || return 1
    fsync_path_and_parent "${plist}"
    return
  fi
  if [[ -f "${snapshot_dir}/plist.absent" \
    && ! -L "${snapshot_dir}/plist.absent" \
    && ! -e "${snapshot_dir}/plist" ]]; then
    if [[ -e "${plist}" || -L "${plist}" ]]; then
      remove_macos_rollback_file "${plist}" || return 1
    fi
    return 0
  fi
  err "RemoteMacAgent LaunchAgent plist 回滚证据缺失或冲突"
  return 1
}

restore_remote_companion_launchagent_state(){
  local snapshot=""
  local available=""
  local uid=""
  local gid=""
  local user=""
  local group=""
  local home=""
  local plist=""
  local loaded=""
  local disabled=""
  local target=""
  local actual_disabled=""
  local disabled_output=""
  snapshot="$(remote_companion_launchagent_snapshot)" || return 1
  IFS=$'\t' read -r \
    available uid gid user group home plist loaded disabled <<< "${snapshot}"
  [[ "${available}" == "1" ]] || return 0
  restore_remote_companion_launchagent_plist \
    "${user}" "${uid}" "${gid}" "${group}" "${plist}" || return 1
  target="gui/${uid}/${REMOTE_COMPANION_LABEL}"
  if [[ "${loaded}" == "1" ]]; then
    [[ -f "${plist}" && ! -L "${plist}" ]] || return 1
    REMOTE_COMPANION_STATUS="$(
      compute_remote_companion_status_path "${user}" "${home}"
    )"
    REMOTE_COMPANION_STATUS_RESET_OK="0"
    if ! prepare_remote_companion_status_file \
      "${REMOTE_COMPANION_STATUS}"; then
      err "无法重置 RemoteMacAgent 回滚健康状态"
      return 1
    fi
    REMOTE_COMPANION_STATUS_RESET_OK="1"
    launchctl enable "${target}" >/dev/null 2>&1 || return 1
    launchctl bootstrap "gui/${uid}" "${plist}" >/dev/null 2>&1 || return 1
    launchctl kickstart "${target}" >/dev/null 2>&1 || return 1
    launchctl print "${target}" >/dev/null 2>&1 || return 1
    if ! remote_companion_health_check "${uid}"; then
      err "RemoteMacAgent 回滚后未通过进程/版本/launchd 健康校验"
      return 1
    fi
  elif launchctl print "${target}" >/dev/null 2>&1; then
    err "RemoteMacAgent LaunchAgent loaded 状态恢复后不一致"
    return 1
  fi
  if [[ "${disabled}" == "1" ]]; then
    launchctl disable "${target}" >/dev/null 2>&1 || return 1
  else
    launchctl enable "${target}" >/dev/null 2>&1 || return 1
  fi
  disabled_output="$(launchctl print-disabled "gui/${uid}" 2>&1)" || return 1
  actual_disabled="$(
    macos_launchd_disabled_state_from_output \
      "${REMOTE_COMPANION_LABEL}" "${disabled_output}" || true
  )"
  if [[ "${actual_disabled}" != "${disabled}" ]]; then
    err "RemoteMacAgent LaunchAgent disabled 状态恢复后不一致"
    return 1
  fi
}

remote_companion_transaction_staging_path(){
  local staging=""
  set_remote_companion_transaction_paths
  staging="$(
    read_transaction_value \
      "${REMOTE_COMPANION_TRANSACTION_DIR}/staging-path" || true
  )"
  case "${staging}" in
    "${REMOTE_COMPANION_APP_PATH}.new."*)
      printf '%s\n' "${staging}"
      ;;
    *)
      return 1
      ;;
  esac
}

remote_companion_commit_approved(){
  local state=""
  local main_state=""
  set_remote_companion_transaction_paths
  state="$(
    read_transaction_value \
      "${REMOTE_COMPANION_TRANSACTION_DIR}/state" || true
  )"
  [[ "${state}" == "committed" ]] || return 1
  remote_companion_requires_main_commit_evidence || return 1
  main_state="$(read_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" || true)"
  [[ "${main_state}" == "committed" ]]
}

atomic_publish_directory(){
  local source="${1:-}"
  local target="${2:-}"
  local source_parent=""
  local target_parent=""
  [[ -d "${source}" && ! -L "${source}" ]] || {
    err "事务 staging 不是可信目录：${source}"
    return 1
  }
  source_parent="$(dirname "${source}")"
  target_parent="$(dirname "${target}")"
  if [[ "${source_parent}" != "${target_parent}" \
    || ! -d "${target_parent}" || -L "${target_parent}" ]]; then
    err "事务 staging/目标必须位于同一可信目录"
    return 1
  fi
  if [[ -e "${target}" || -L "${target}" ]]; then
    err "事务目标已存在，拒绝覆盖或落入已有目录：${target}"
    return 1
  fi
  ensure_trusted_macos_agent_python || {
    err "缺少 python3，无法执行原子 no-replace 事务发布"
    return 1
  }
  if ! run_trusted_macos_python - "${source}" "${target}" <<'PY'
import ctypes
import errno
import os
import platform
import stat
import sys

source = os.fsencode(sys.argv[1])
target = os.fsencode(sys.argv[2])
libc = ctypes.CDLL(None, use_errno=True)
system = platform.system()

for root, directories, files in os.walk(source, topdown=False):
    for name in files:
        path = os.path.join(root, os.fsencode(name))
        fd = os.open(
            path,
            os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0),
        )
        try:
            if not stat.S_ISREG(os.fstat(fd).st_mode):
                raise OSError(f"transaction entry is not regular: {path!r}")
            os.fsync(fd)
        finally:
            os.close(fd)
    for name in directories:
        path = os.path.join(root, os.fsencode(name))
        if os.path.islink(path):
            raise OSError(f"transaction directory is a symlink: {path!r}")
        fd = os.open(path, os.O_RDONLY)
        try:
            os.fsync(fd)
        finally:
            os.close(fd)
source_fd = os.open(source, os.O_RDONLY)
try:
    os.fsync(source_fd)
finally:
    os.close(source_fd)

if system == "Darwin":
    rename = getattr(libc, "renameatx_np", None)
    if rename is None:
        raise SystemExit("renameatx_np is unavailable")
    rename.argtypes = (
        ctypes.c_int,
        ctypes.c_char_p,
        ctypes.c_int,
        ctypes.c_char_p,
        ctypes.c_uint,
    )
    rename.restype = ctypes.c_int
    result = rename(-2, source, -2, target, 0x00000004)
elif system == "Linux":
    rename = getattr(libc, "renameat2", None)
    if rename is None:
        raise SystemExit("renameat2 is unavailable")
    rename.argtypes = (
        ctypes.c_int,
        ctypes.c_char_p,
        ctypes.c_int,
        ctypes.c_char_p,
        ctypes.c_uint,
    )
    rename.restype = ctypes.c_int
    result = rename(-100, source, -100, target, 0x00000001)
else:
    raise SystemExit(f"no atomic no-replace rename for {system}")

if result != 0:
    error = ctypes.get_errno()
    if error == errno.EEXIST:
        raise SystemExit("transaction target already exists")
    raise OSError(error, os.strerror(error), os.fsdecode(target))
parent_fd = os.open(os.path.dirname(target) or b".", os.O_RDONLY)
try:
    os.fsync(parent_fd)
finally:
    os.close(parent_fd)
PY
  then
    err "无法原子发布事务目录：${target}"
    return 1
  fi
  if [[ -e "${source}" || -L "${source}" \
    || ! -d "${target}" || -L "${target}" ]]; then
    err "事务目录原子发布后状态异常：${target}"
    return 1
  fi
}

restore_remote_companion_artifact_sha(){
  local saved=""
  local absent=""
  local artifact_dir=""
  local temp_path=""
  set_remote_companion_transaction_paths
  saved="${REMOTE_COMPANION_TRANSACTION_DIR}/installed-artifact.sha256"
  absent="${saved}.absent"
  artifact_dir="$(dirname "${REMOTE_COMPANION_ARTIFACT_SHA_PATH}")"
  if [[ -L "${saved}" || -L "${absent}" \
    || ( -e "${saved}" && ! -f "${saved}" ) \
    || ( -e "${absent}" && ! -f "${absent}" ) ]]; then
    err "RemoteMacAgent artifact SHA 回滚证据不可信"
    return 1
  fi
  if [[ -f "${saved}" && -f "${absent}" ]]; then
    err "RemoteMacAgent artifact SHA 回滚证据冲突"
    return 1
  fi
  if [[ -f "${saved}" ]]; then
    install -d -m 700 "${artifact_dir}" || return 1
    fix_owner_mode_strict "${artifact_dir}" 700 || return 1
    fsync_directory_and_parent "${artifact_dir}" || return 1
    temp_path="$(
      mktemp "${artifact_dir}/.installed-artifact.sha256.restore.XXXXXX"
    )" || return 1
    register_cleanup_path "${temp_path}"
    cp -f "${saved}" "${temp_path}" || return 1
    publish_root_owned_regular_file \
      "${temp_path}" "${REMOTE_COMPANION_ARTIFACT_SHA_PATH}" 600 || return 1
  elif [[ -f "${absent}" ]]; then
    remove_macos_rollback_file \
      "${REMOTE_COMPANION_ARTIFACT_SHA_PATH}" || return 1
  else
    err "RemoteMacAgent artifact SHA 回滚证据缺失"
    return 1
  fi
}

publish_remote_companion_path_index(){
  local main_transaction_path="${1:-}"
  local companion_app_path="${2:-}"
  local companion_home="${3-}"
  local index_dir="${main_transaction_path}/remote-companion-index"
  local index_tmp=""
  if [[ -e "${index_dir}" || -L "${index_dir}" ]]; then
    err "RemoteMacAgent 主事务已存在 companion 路径索引"
    return 1
  fi
  index_tmp="$(mktemp -d "${index_dir}.new.XXXXXX")" || return 1
  chmod 700 "${index_tmp}" || return 1
  register_cleanup_path "${index_tmp}"
  persist_transaction_value \
    "${index_tmp}/app-path" "${companion_app_path}" || return 1
  persist_transaction_value \
    "${index_tmp}/home" "${companion_home}" || return 1
  if ! atomic_publish_directory "${index_tmp}" "${index_dir}"; then
    err "无法原子发布 RemoteMacAgent 主事务路径索引"
    return 1
  fi
}

begin_remote_companion_transaction(){
  local staging="${1:-}"
  local pending_sha="${2:-}"
  local normalized_sha=""
  local transaction_tmp=""
  local main_transaction_path=""
  local main_transaction_id=""
  local companion_app_path=""
  set_remote_companion_transaction_paths
  if [[ -L "${REMOTE_COMPANION_TRANSACTION_DIR}" \
        || -e "${REMOTE_COMPANION_TRANSACTION_DIR}" ]]; then
    err "RemoteMacAgent 事务目录已存在，拒绝开始新的切换：${REMOTE_COMPANION_TRANSACTION_DIR}"
    return 1
  fi
  if [[ -e "${REMOTE_COMPANION_UPDATE_BACKUP}" \
        || -L "${REMOTE_COMPANION_UPDATE_BACKUP}" ]]; then
    err "RemoteMacAgent previous app 未恢复，拒绝开始新的切换"
    return 1
  fi
  if [[ -L "${REMOTE_COMPANION_APP_PATH}" \
        || ( -e "${REMOTE_COMPANION_APP_PATH}" \
          && ! -d "${REMOTE_COMPANION_APP_PATH}" ) ]]; then
    err "RemoteMacAgent 目标路径不是受管 app 目录：${REMOTE_COMPANION_APP_PATH}"
    return 1
  fi

  main_transaction_path="$(
    canonical_macos_transaction_path \
      "${REALM_MAC_TRANSACTION_DIR}" "${BASE_DIR}" "strict" || true
  )"
  main_transaction_id="$(read_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/transaction-id" || true)"
  companion_app_path="$(
    canonical_remote_companion_app_path \
      "${REMOTE_COMPANION_APP_PATH}" \
      "${REMOTE_COMPANION_DESKTOP_HOME}" || true
  )"
  if [[ -z "${main_transaction_path}" \
    || ! "${main_transaction_id}" =~ ^[0-9a-f]{64}$ \
    || -z "${companion_app_path}" \
    || "${companion_app_path}" != "${REMOTE_COMPANION_APP_PATH}" ]]; then
    err "RemoteMacAgent 缺少可信的主安装事务绑定"
    return 1
  fi
  publish_remote_companion_path_index \
    "${main_transaction_path}" \
    "${companion_app_path}" \
    "${REMOTE_COMPANION_DESKTOP_HOME}" || return 1
  transaction_tmp="$(
    mktemp -d "${REMOTE_COMPANION_TRANSACTION_DIR}.new.XXXXXX"
  )" || return 1
  chmod 700 "${transaction_tmp}" || return 1
  register_cleanup_path "${transaction_tmp}"
  persist_transaction_value \
    "${transaction_tmp}/main-transaction-path" \
    "${main_transaction_path}" || return 1
  persist_transaction_value \
    "${transaction_tmp}/main-transaction-id" \
    "${main_transaction_id}" || return 1
  persist_transaction_value \
    "${transaction_tmp}/companion-app-path" \
    "${companion_app_path}" || return 1
  persist_transaction_value \
    "${transaction_tmp}/transaction-schema" "2" || return 1
  snapshot_remote_companion_launchagent_state \
    "${transaction_tmp}" \
    "${REMOTE_COMPANION_DESKTOP_USER}" \
    "${REMOTE_COMPANION_DESKTOP_UID}" \
    "${REMOTE_COMPANION_DESKTOP_GID}" \
    "${REMOTE_COMPANION_DESKTOP_GROUP}" \
    "${REMOTE_COMPANION_DESKTOP_HOME}" \
    "${REMOTE_COMPANION_DESKTOP_PLIST}" || {
    err "无法快照 RemoteMacAgent LaunchAgent 状态"
    return 1
  }
  if [[ -d "${REMOTE_COMPANION_APP_PATH}" ]]; then
    : > "${transaction_tmp}/had-current" || return 1
  fi
  if [[ -L "${REMOTE_COMPANION_ARTIFACT_SHA_PATH}" ]]; then
    err "拒绝通过符号链接更新 RemoteMacAgent artifact SHA"
    return 1
  elif [[ -f "${REMOTE_COMPANION_ARTIFACT_SHA_PATH}" ]]; then
    cp -f \
      "${REMOTE_COMPANION_ARTIFACT_SHA_PATH}" \
      "${transaction_tmp}/installed-artifact.sha256" || return 1
  elif [[ -e "${REMOTE_COMPANION_ARTIFACT_SHA_PATH}" ]]; then
    err "RemoteMacAgent artifact SHA 路径不是普通文件"
    return 1
  else
    : > "${transaction_tmp}/installed-artifact.sha256.absent" || return 1
  fi
  persist_transaction_value \
    "${transaction_tmp}/staging-path" "${staging}" || return 1
  if [[ -n "${pending_sha}" ]]; then
    normalized_sha="$(normalize_sha256 "${pending_sha}" || true)"
    if [[ -z "${normalized_sha}" ]]; then
      err "RemoteMacAgent 待提交 artifact SHA 无效"
      return 1
    fi
    persist_transaction_value \
      "${transaction_tmp}/pending-artifact.sha256" "${normalized_sha}" \
      || return 1
  fi
  persist_transaction_value \
    "${transaction_tmp}/state" "prepared" || return 1
  if ! atomic_publish_directory \
    "${transaction_tmp}" "${REMOTE_COMPANION_TRANSACTION_DIR}"; then
    err "无法持久化 RemoteMacAgent 切换事务"
    return 1
  fi
  REMOTE_COMPANION_PENDING_ARTIFACT_SHA="${normalized_sha}"
  REMOTE_COMPANION_UPDATE_PENDING="1"
}

finalize_remote_companion_update(){
  local staging=""
  set_remote_companion_transaction_paths
  if [[ -d "${REMOTE_COMPANION_TRANSACTION_DIR}" ]] \
    && ! remote_companion_commit_approved; then
    err "RemoteMacAgent 联合提交尚未完成，拒绝清理回滚证据"
    return 1
  fi
  staging="$(remote_companion_transaction_staging_path || true)"
  if [[ -e "${REMOTE_COMPANION_UPDATE_BACKUP}" \
    || -L "${REMOTE_COMPANION_UPDATE_BACKUP}" ]]; then
    if ! remove_macos_rollback_directory \
      "${REMOTE_COMPANION_UPDATE_BACKUP}"; then
      err "无法清理 RemoteMacAgent previous app，已保留提交事务"
      return 1
    fi
  fi
  if [[ -n "${staging}" && ( -e "${staging}" || -L "${staging}" ) ]]; then
    if ! remove_macos_rollback_directory "${staging}"; then
      err "无法清理 RemoteMacAgent staging，已保留提交事务"
      return 1
    fi
  fi
  if [[ -e "${REMOTE_COMPANION_TRANSACTION_DIR}" \
    || -L "${REMOTE_COMPANION_TRANSACTION_DIR}" ]]; then
    if ! remove_macos_rollback_directory \
      "${REMOTE_COMPANION_TRANSACTION_DIR}"; then
      err "无法清理 RemoteMacAgent 提交事务"
      return 1
    fi
  fi
  REMOTE_COMPANION_PENDING_ARTIFACT_SHA=""
  REMOTE_COMPANION_UPDATE_BACKUP=""
  REMOTE_COMPANION_TRANSACTION_DIR=""
  REMOTE_COMPANION_UPDATE_PENDING="0"
  return 0
}

rollback_remote_companion_update(){
  local reason="${1:-RemoteMacAgent 未通过运行确认}"
  local failed="${REMOTE_COMPANION_APP_PATH}.failed-update"
  local staging=""
  local had_current="0"
  local transaction_present="0"
  set_remote_companion_transaction_paths

  if remote_companion_commit_approved; then
    finalize_remote_companion_update || return 1
    return 0
  fi
  if [[ -L "${REMOTE_COMPANION_TRANSACTION_DIR}" ]]; then
    err "RemoteMacAgent 事务路径是符号链接，拒绝自动恢复"
    return 1
  fi
  if [[ -d "${REMOTE_COMPANION_TRANSACTION_DIR}" ]]; then
    transaction_present="1"
    if [[ -f "${REMOTE_COMPANION_TRANSACTION_DIR}/had-current" ]]; then
      had_current="1"
    fi
    if ! staging="$(remote_companion_transaction_staging_path)"; then
      err "RemoteMacAgent 事务缺少可信 staging 路径"
      return 1
    fi
    REMOTE_COMPANION_PENDING_ARTIFACT_SHA="$(
      read_transaction_value \
        "${REMOTE_COMPANION_TRANSACTION_DIR}/pending-artifact.sha256" \
        || true
    )"
  elif [[ "${REMOTE_COMPANION_UPDATE_PENDING:-0}" == "1" \
          && ( -e "${REMOTE_COMPANION_UPDATE_BACKUP}" \
            || -L "${REMOTE_COMPANION_UPDATE_BACKUP}" ) ]]; then
    had_current="1"
  else
    REMOTE_COMPANION_PENDING_ARTIFACT_SHA=""
    return 1
  fi

  if [[ "${transaction_present}" == "1" ]] \
    && ! quiesce_remote_companion_launchagent; then
    err "RemoteMacAgent LaunchAgent 未能进入可回滚静止状态"
    return 1
  fi
  if [[ -e "${failed}" || -L "${failed}" ]]; then
    remove_macos_rollback_directory "${failed}" || return 1
  fi
  if [[ "${had_current}" == "1" ]]; then
    if [[ -e "${REMOTE_COMPANION_UPDATE_BACKUP}" \
          || -L "${REMOTE_COMPANION_UPDATE_BACKUP}" ]]; then
      if [[ -e "${REMOTE_COMPANION_APP_PATH}" \
            || -L "${REMOTE_COMPANION_APP_PATH}" ]]; then
        if ! mv "${REMOTE_COMPANION_APP_PATH}" "${failed}"; then
          err "无法隔离未提交的 RemoteMacAgent.app"
          return 1
        fi
      fi
      if ! mv \
        "${REMOTE_COMPANION_UPDATE_BACKUP}" \
        "${REMOTE_COMPANION_APP_PATH}"; then
        if [[ -e "${failed}" || -L "${failed}" ]]; then
          if ! mv "${failed}" "${REMOTE_COMPANION_APP_PATH}" \
            || ! fsync_tree_and_parent \
              "${REMOTE_COMPANION_APP_PATH}"; then
            err "previous app 恢复失败，且无法恢复未提交的 RemoteMacAgent.app"
          fi
        fi
        err "无法恢复 previous RemoteMacAgent.app"
        return 1
      fi
    elif [[ ! -e "${REMOTE_COMPANION_APP_PATH}" \
            && ! -L "${REMOTE_COMPANION_APP_PATH}" ]]; then
      err "RemoteMacAgent 事务缺少当前 app 与 previous app"
      return 1
    fi
    fsync_tree_and_parent "${REMOTE_COMPANION_APP_PATH}" || return 1
  else
    if [[ -e "${REMOTE_COMPANION_APP_PATH}" \
      || -L "${REMOTE_COMPANION_APP_PATH}" ]]; then
      remove_macos_rollback_directory \
        "${REMOTE_COMPANION_APP_PATH}" || return 1
    fi
    if [[ -e "${REMOTE_COMPANION_UPDATE_BACKUP}" \
      || -L "${REMOTE_COMPANION_UPDATE_BACKUP}" ]]; then
      remove_macos_rollback_directory \
        "${REMOTE_COMPANION_UPDATE_BACKUP}" || return 1
    fi
  fi
  if [[ -e "${failed}" || -L "${failed}" ]]; then
    remove_macos_rollback_directory "${failed}" || return 1
  fi

  if [[ "${transaction_present}" == "1" ]]; then
    if ! restore_remote_companion_artifact_sha; then
      err "RemoteMacAgent app 已恢复，但 artifact SHA 回滚失败"
      return 1
    fi
    if ! restore_remote_companion_launchagent_state; then
      err "RemoteMacAgent app 已恢复，但 LaunchAgent 状态回滚失败"
      return 1
    fi
    if [[ -e "${staging}" || -L "${staging}" ]]; then
      remove_macos_rollback_directory "${staging}" || return 1
    fi
    remove_macos_rollback_directory \
      "${REMOTE_COMPANION_TRANSACTION_DIR}" || return 1
  fi
  REMOTE_COMPANION_UPDATE_PENDING="0"
  REMOTE_COMPANION_UPDATE_BACKUP=""
  REMOTE_COMPANION_TRANSACTION_DIR=""
  REMOTE_COMPANION_PENDING_ARTIFACT_SHA=""
  warn "${reason}，已恢复 previous app"
  return 0
}

recover_remote_companion_transaction(){
  local orphan=""
  local state=""
  set_remote_companion_transaction_paths
  for orphan in "${REMOTE_COMPANION_TRANSACTION_DIR}.new."*; do
    [[ -e "${orphan}" || -L "${orphan}" ]] || continue
    remove_macos_rollback_directory "${orphan}" || return 1
  done
  if [[ -L "${REMOTE_COMPANION_TRANSACTION_DIR}" ]]; then
    err "RemoteMacAgent 事务路径是符号链接，拒绝继续安装"
    return 1
  fi
  if [[ -d "${REMOTE_COMPANION_TRANSACTION_DIR}" ]]; then
    state="$(
      read_transaction_value \
        "${REMOTE_COMPANION_TRANSACTION_DIR}/state" || true
    )"
    REMOTE_COMPANION_UPDATE_PENDING="1"
    if remote_companion_commit_approved; then
      warn "检测到已批准但未清理的 RemoteMacAgent 提交，继续完成提交"
      finalize_remote_companion_update || return 1
      return 0
    fi
    if [[ "${state}" != "prepared" \
          && "${state}" != "quiescing" \
          && "${state}" != "quiesced" \
          && "${state}" != "old-moved" \
          && "${state}" != "new-active" \
          && "${state}" != "commit-prepared" ]]; then
      err "RemoteMacAgent 事务状态无效：${state:-missing}"
      return 1
    fi
    warn "检测到中断的 RemoteMacAgent 切换，启动前执行回滚"
    rollback_remote_companion_update "中断的 RemoteMacAgent 切换"
    return
  fi
  if [[ -e "${REMOTE_COMPANION_UPDATE_BACKUP}" \
        || -L "${REMOTE_COMPANION_UPDATE_BACKUP}" ]]; then
    REMOTE_COMPANION_UPDATE_PENDING="1"
    warn "检测到旧版安装器遗留的 previous app，启动前执行回滚"
    rollback_remote_companion_update "旧版中断的 RemoteMacAgent 切换"
  fi
}

commit_remote_companion_staging(){
  local staging="${1:-}"
  local pending_sha="${2:-}"
  local expected=""
  [[ -d "${staging}" ]] || return 1
  expected="$(remote_companion_current_arch || true)"
  if [[ -z "${expected}" ]]; then
    err "不支持的 Mac CPU 架构：$(uname -m)"
    rm -rf "${staging}"
    return 1
  fi
  if ! remote_companion_artifact_architecture_matches "${staging}"; then
    err "RemoteMacAgent.app 架构不匹配，当前系统需要 ${expected}"
    rm -rf "${staging}"
    return 1
  fi
  if ! validate_remote_companion_app_tree "${staging}" \
    || ! verify_remote_companion_bundle_signature "${staging}"; then
    rm -rf "${staging}"
    return 1
  fi
  if ! recover_remote_companion_transaction; then
    rm -rf "${staging}"
    return 1
  fi
  if ! begin_remote_companion_transaction "${staging}" "${pending_sha}"; then
    rm -rf "${staging}"
    return 1
  fi
  if ! persist_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/state" "quiescing" \
    || ! quiesce_remote_companion_launchagent \
    || ! persist_transaction_value \
      "${REMOTE_COMPANION_TRANSACTION_DIR}/state" "quiesced"; then
    err "RemoteMacAgent 未能在 app 切换前持久进入静止状态"
    if ! rollback_remote_companion_update \
      "RemoteMacAgent 切换前静止失败"; then
      err "RemoteMacAgent 静止失败后的回滚未完成"
    fi
    return 1
  fi

  if [[ -d "${REMOTE_COMPANION_APP_PATH}" ]]; then
    if ! mv \
      "${REMOTE_COMPANION_APP_PATH}" \
      "${REMOTE_COMPANION_UPDATE_BACKUP}"; then
      err "无法暂存现有 RemoteMacAgent.app"
      if ! rollback_remote_companion_update; then
        err "RemoteMacAgent app 暂存失败后的回滚未完成"
      fi
      return 1
    fi
    if ! fsync_directory_and_parent \
      "$(dirname "${REMOTE_COMPANION_APP_PATH}")"; then
      if ! rollback_remote_companion_update; then
        err "RemoteMacAgent app 暂存持久化失败后的回滚未完成"
      fi
      return 1
    fi
    if ! persist_transaction_value \
      "${REMOTE_COMPANION_TRANSACTION_DIR}/state" "old-moved"; then
      if ! rollback_remote_companion_update; then
        err "RemoteMacAgent old-moved 状态失败后的回滚未完成"
      fi
      return 1
    fi
  fi
  if ! mv "${staging}" "${REMOTE_COMPANION_APP_PATH}"; then
    err "无法安装新的 RemoteMacAgent.app"
    if ! rollback_remote_companion_update; then
      err "RemoteMacAgent 新 app 安装失败后的回滚未完成"
    fi
    return 1
  fi
  if ! fsync_tree_and_parent "${REMOTE_COMPANION_APP_PATH}"; then
    if ! rollback_remote_companion_update; then
      err "RemoteMacAgent 新 app 持久化失败后的回滚未完成"
    fi
    return 1
  fi
  if ! persist_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/state" "new-active"; then
    if ! rollback_remote_companion_update; then
      err "RemoteMacAgent new-active 状态失败后的回滚未完成"
    fi
    return 1
  fi
  if ! remote_companion_artifact_architecture_matches \
      "${REMOTE_COMPANION_APP_PATH}" \
    || ! validate_remote_companion_app_tree "${REMOTE_COMPANION_APP_PATH}" \
    || ! verify_remote_companion_bundle_signature \
      "${REMOTE_COMPANION_APP_PATH}"; then
    err "安装后的 RemoteMacAgent.app 复核失败，正在恢复旧版本"
    if ! rollback_remote_companion_update; then
      err "RemoteMacAgent 安装后复核失败且回滚未完成"
    fi
    return 1
  fi
  REMOTE_COMPANION_UPDATE_PENDING="1"
  return 0
}

persist_remote_companion_artifact_sha(){
  local artifact_sha=""
  local artifact_dir=""
  local temp_path=""
  artifact_sha="$(
    normalize_sha256 "${1:-}" || true
  )"
  [[ -n "${artifact_sha}" ]] || return 1
  artifact_dir="$(dirname "${REMOTE_COMPANION_ARTIFACT_SHA_PATH}")"
  install -d -m 700 "${artifact_dir}" || return 1
  fix_owner_mode_strict "${artifact_dir}" 700 || return 1
  fsync_directory_and_parent "${artifact_dir}" || return 1
  temp_path="$(
    mktemp "${artifact_dir}/.installed-artifact.sha256.XXXXXX"
  )" || return 1
  register_cleanup_path "${temp_path}"
  printf '%s\n' "${artifact_sha}" > "${temp_path}" || return 1
  publish_root_owned_regular_file \
    "${temp_path}" "${REMOTE_COMPANION_ARTIFACT_SHA_PATH}" 600
}

prepare_remote_companion_commit(){
  local state=""
  set_remote_companion_transaction_paths
  if [[ ! -d "${REMOTE_COMPANION_TRANSACTION_DIR}" \
    && "${REMOTE_COMPANION_UPDATE_PENDING:-0}" == "1" ]]; then
    err "RemoteMacAgent 待提交标记存在但事务目录缺失"
    return 1
  fi
  if [[ -d "${REMOTE_COMPANION_TRANSACTION_DIR}" ]]; then
    state="$(read_transaction_value \
      "${REMOTE_COMPANION_TRANSACTION_DIR}/state" || true)"
    if [[ "${state}" != "new-active" \
        && "${state}" != "commit-prepared" ]] \
      || ! remote_companion_verification_matches; then
      err "RemoteMacAgent 缺少与主事务绑定的运行确认"
      return 1
    fi
    REMOTE_COMPANION_PENDING_ARTIFACT_SHA="$(
      read_transaction_value \
        "${REMOTE_COMPANION_TRANSACTION_DIR}/pending-artifact.sha256" \
        || true
    )"
  fi
  if [[ -n "${REMOTE_COMPANION_PENDING_ARTIFACT_SHA}" ]] \
    && ! persist_remote_companion_artifact_sha \
      "${REMOTE_COMPANION_PENDING_ARTIFACT_SHA}"; then
    err "无法提交 RemoteMacAgent 已安装 artifact SHA，保留 previous app 以便回滚"
    return 1
  fi
  if [[ "${state}" == "new-active" ]]; then
    persist_transaction_value \
      "${REMOTE_COMPANION_TRANSACTION_DIR}/state" "commit-prepared" \
      || return 1
  fi
}

mark_remote_companion_verified(){
  local state=""
  local main_transaction_id=""
  set_remote_companion_transaction_paths
  if [[ ! -d "${REMOTE_COMPANION_TRANSACTION_DIR}" ]]; then
    [[ "${REMOTE_COMPANION_UPDATE_PENDING:-0}" != "1" ]]
    return
  fi
  state="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/state" || true)"
  [[ "${state}" == "new-active" ]] || return 1
  remote_companion_joint_transaction_matches || return 1
  main_transaction_id="$(read_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/main-transaction-id" || true)"
  [[ "${main_transaction_id}" =~ ^[0-9a-f]{64}$ ]] || return 1
  persist_transaction_value \
    "${REMOTE_COMPANION_TRANSACTION_DIR}/companion-verified" \
    "${main_transaction_id}"
}

mark_remote_companion_commit(){
  local state=""
  set_remote_companion_transaction_paths
  if [[ -d "${REMOTE_COMPANION_TRANSACTION_DIR}" ]]; then
    state="$(read_transaction_value \
      "${REMOTE_COMPANION_TRANSACTION_DIR}/state" || true)"
    case "${state}" in
      new-active|commit-prepared|committed) ;;
      *) return 1 ;;
    esac
    remote_companion_requires_main_commit_evidence || return 1
    [[ "${state}" != "committed" ]] || return 0
    persist_transaction_value \
      "${REMOTE_COMPANION_TRANSACTION_DIR}/state" "committed" \
      || return 1
  fi
}

commit_remote_companion_update(){
  prepare_remote_companion_commit || return 1
  mark_remote_companion_commit || return 1
  finalize_remote_companion_update
}

remote_companion_signature_authority(){
  local app_path="${1:-$REMOTE_COMPANION_APP_PATH}"
  command_exists codesign || return 1
  codesign -dv --verbose=2 "${app_path}" 2>&1 | awk -F= '/^Authority=/{print substr($0, index($0, "=") + 1); exit}'
}

remote_companion_signature_is_adhoc(){
  local app_path="${1:-$REMOTE_COMPANION_APP_PATH}"
  command_exists codesign || return 1
  codesign -dv "${app_path}" 2>&1 | grep -q '^Signature=adhoc'
}

remote_companion_allow_adhoc_codesign(){
  local value="${REMOTE_COMPANION_ALLOW_ADHOC_CODESIGN:-0}"
  value="$(printf '%s' "${value}" | tr '[:upper:]' '[:lower:]')"
  case "${value}" in
    1|true|yes|on|y) return 0 ;;
    *) return 1 ;;
  esac
}

remote_companion_candidate_homes(){
  local desktop_user="" home="" sudo_home=""
  desktop_user="$(console_user || true)"
  if [[ -n "${desktop_user}" ]]; then
    home="$(console_home "${desktop_user}" || true)"
    [[ -n "${home}" ]] && printf '%s\n' "${home}"
  fi
  if [[ -n "${SUDO_USER:-}" && "${SUDO_USER}" != "root" ]]; then
    sudo_home="$(dscl . -read "/Users/${SUDO_USER}" NFSHomeDirectory 2>/dev/null | awk '{print $2; exit}' || true)"
    [[ -n "${sudo_home}" && -d "${sudo_home}" ]] && printf '%s\n' "${sudo_home}"
  fi
  [[ -n "${HOME:-}" && -d "${HOME}" ]] && printf '%s\n' "${HOME}"
}

resolve_remote_companion_codesign_keychain(){
  local home="" keychain="" passfile=""
  if [[ -n "${REMOTE_COMPANION_CODESIGN_KEYCHAIN}" && -f "${REMOTE_COMPANION_CODESIGN_KEYCHAIN}" ]]; then
    return 0
  fi
  while IFS= read -r home; do
    [[ -n "${home}" ]] || continue
    keychain="${home}/.realm-remote-agent/codesign/realm-remote-agent-signing.keychain-db"
    passfile="${home}/.realm-remote-agent/codesign/keychain.pass"
    if [[ -f "${keychain}" ]]; then
      REMOTE_COMPANION_CODESIGN_KEYCHAIN="${keychain}"
      if [[ -z "${REMOTE_COMPANION_CODESIGN_KEYCHAIN_PASSWORD_FILE}" && -f "${passfile}" ]]; then
        REMOTE_COMPANION_CODESIGN_KEYCHAIN_PASSWORD_FILE="${passfile}"
      fi
      return 0
    fi
  done < <(remote_companion_candidate_homes | awk '!seen[$0]++')
  return 1
}

sign_remote_companion_app(){
  local app_path="${1:-$REMOTE_COMPANION_APP_PATH}"
  command_exists codesign || return 0
  [[ -d "${app_path}" ]] || return 0

  local current_authority=""
  current_authority="$(remote_companion_signature_authority "${app_path}" || true)"
  if [[ -n "${current_authority}" && "${current_authority}" != "adhoc" ]]; then
    ok "RemoteMacAgent 已保留稳定 codesign：${current_authority}"
    return 0
  fi

  local args=(--force --deep)
  resolve_remote_companion_codesign_keychain || true
  if [[ -n "${REMOTE_COMPANION_CODESIGN_KEYCHAIN}" && -f "${REMOTE_COMPANION_CODESIGN_KEYCHAIN}" ]]; then
    if [[ -n "${REMOTE_COMPANION_CODESIGN_KEYCHAIN_PASSWORD_FILE}" && -f "${REMOTE_COMPANION_CODESIGN_KEYCHAIN_PASSWORD_FILE}" ]]; then
      security unlock-keychain -p "$(cat "${REMOTE_COMPANION_CODESIGN_KEYCHAIN_PASSWORD_FILE}")" "${REMOTE_COMPANION_CODESIGN_KEYCHAIN}" >/dev/null 2>&1 || true
    fi
    args+=(--keychain "${REMOTE_COMPANION_CODESIGN_KEYCHAIN}")
  fi
  if [[ -n "${REMOTE_COMPANION_CODESIGN_IDENTITY}" ]] && codesign "${args[@]}" --sign "${REMOTE_COMPANION_CODESIGN_IDENTITY}" "${app_path}" >/dev/null 2>&1; then
    ok "RemoteMacAgent 已使用稳定 codesign：${REMOTE_COMPANION_CODESIGN_IDENTITY}"
    return 0
  fi

  if remote_companion_signature_is_adhoc "${app_path}"; then
    warn "RemoteMacAgent 未找到稳定 codesign 身份，保留 ad-hoc 签名；更新后可能需要重新授权隐私权限"
    return 0
  fi
  if ! remote_companion_allow_adhoc_codesign; then
    warn "RemoteMacAgent 未找到稳定 codesign 身份，已跳过 ad-hoc 重签；请配置 REALM_REMOTE_CODESIGN_KEYCHAIN 后再更新以避免重复授权"
    return 0
  fi
  if codesign --force --deep --sign - "${app_path}" >/dev/null 2>&1; then
    warn "RemoteMacAgent 已回退 ad-hoc codesign；更新后可能需要重新授权隐私权限"
  else
    warn "RemoteMacAgent codesign 失败，继续安装；首次启动可能需要手动允许"
  fi
}

read_remote_companion_app_version(){
  local app_path="${1:-${REMOTE_COMPANION_APP_PATH}}"
  local plist="${app_path}/Contents/Info.plist"
  local version=""
  [[ -f "${plist}" && ! -L "${plist}" ]] || return 1
  if [[ -x /usr/libexec/PlistBuddy ]]; then
    version="$(
      /usr/libexec/PlistBuddy \
        -c "Print :CFBundleShortVersionString" "${plist}" 2>/dev/null \
        || true
    )"
  elif ensure_trusted_macos_agent_python; then
    version="$(
      run_trusted_macos_python - "${plist}" <<'PY' 2>/dev/null || true
import pathlib
import plistlib
import sys

payload = plistlib.loads(pathlib.Path(sys.argv[1]).read_bytes())
print(payload.get("CFBundleShortVersionString") or "")
PY
    )"
  fi
  version="${version//$'\r'/}"
  version="${version//$'\n'/}"
  [[ "${version}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
  printf '%s\n' "${version}"
}

read_local_remote_companion_version(){
  read_remote_companion_app_version "${REMOTE_COMPANION_APP_PATH}" || echo ""
}

resolve_remote_companion_panel_url(){
  local url="${REALM_PANEL_URL:-}"
  if [[ -z "${url}" && -f /etc/realm-agent/panel.env ]]; then
    url="$(read_env_value /etc/realm-agent/panel.env REALM_PANEL_URL || true)"
  fi
  url="${url:-https://realm.infpro.me}"
  panel_url_without_trailing_slash "${url}"
}

read_remote_companion_version_sidecar(){
  local sidecar="$1"
  local version=""
  [[ -f "${sidecar}" && ! -L "${sidecar}" ]] || return 1
  version="$(cat "${sidecar}" 2>/dev/null || true)"
  version="${version%$'\n'}"
  version="${version%$'\r'}"
  [[ "${version}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
  printf '%s\n' "${version}"
}

remote_companion_file_size(){
  local path="$1"
  local size=""
  size="$(stat -f '%z' "${path}" 2>/dev/null || true)"
  if [[ ! "${size}" =~ ^[0-9]+$ ]]; then
    size="$(stat -c '%s' "${path}" 2>/dev/null || true)"
  fi
  [[ "${size}" =~ ^[0-9]+$ ]] || return 1
  printf '%s\n' "${size}"
}

parse_remote_companion_release_manifest(){
  local manifest_path="$1"
  local expected_arch="$2"
  run_trusted_macos_python - "${manifest_path}" "${expected_arch}" <<'PY'
import json
import pathlib
import re
import sys

manifest_path = pathlib.Path(sys.argv[1])
expected_arch = sys.argv[2]
if manifest_path.stat().st_size > 65536:
    raise SystemExit("manifest is too large")
payload = json.loads(manifest_path.read_text(encoding="utf-8"))
if not isinstance(payload, dict) or payload.get("schema") != 1:
    raise SystemExit("unsupported manifest schema")

architecture = payload.get("architecture")
version = payload.get("version")
archive_sha = payload.get("archive_sha256")
archive_size = payload.get("archive_size")
release_id = payload.get("release_id")
artifacts = payload.get("artifacts")
if architecture != expected_arch:
    raise SystemExit("manifest architecture mismatch")
if not isinstance(version, str) or not re.fullmatch(
    r"[0-9]+\.[0-9]+\.[0-9]+",
    version,
):
    raise SystemExit("manifest version is invalid")
if not isinstance(archive_sha, str) or not re.fullmatch(
    r"[0-9a-f]{64}",
    archive_sha,
):
    raise SystemExit("manifest sha256 is invalid")
if not isinstance(archive_size, int) or not 0 < archive_size <= 4 * 1024**3:
    raise SystemExit("manifest archive_size is invalid")
if release_id != f"{version}-{archive_sha}":
    raise SystemExit("manifest release_id is invalid")
if not isinstance(artifacts, dict):
    raise SystemExit("manifest artifacts are missing")

archive_name = f"RemoteMacAgent-{expected_arch}.zip"
release_root = pathlib.PurePosixPath(
    "remote-mac-agent",
    "releases",
    expected_arch,
    release_id,
)
expected = {
    "archive": str(release_root / archive_name),
    "sha256": str(release_root / f"{archive_name}.sha256"),
    "version": str(release_root / f"{archive_name}.version"),
    }
if artifacts != expected:
    raise SystemExit("manifest artifact paths are invalid")
print(
    "\t".join(
        (
            release_id,
            version,
            archive_sha,
            str(archive_size),
            expected["archive"],
            expected["sha256"],
            expected["version"],
        )
    )
)
PY
}

remote_companion_sha_override_matches(){
  local published_sha="$1"
  local raw_override="${REALM_REMOTE_COMPANION_SHA256:-}"
  local override=""
  [[ -n "${raw_override}" ]] || return 0
  override="$(normalize_sha256 "${raw_override}" || true)"
  if [[ -z "${override}" ]]; then
    err "REALM_REMOTE_COMPANION_SHA256 不是有效的 SHA256"
    return 1
  fi
  if [[ "${override}" != "${published_sha}" ]]; then
    err "REALM_REMOTE_COMPANION_SHA256 与 panel 当前发布不一致"
    return 1
  fi
}

remote_companion_installed_release_matches(){
  local local_version="$1"
  local remote_version="$2"
  local installed_sha="$3"
  local expected_sha="$4"
  [[ -n "${local_version}" \
    && "${local_version}" == "${remote_version}" \
    && "${installed_sha}" == "${expected_sha}" \
    && -d "${REMOTE_COMPANION_APP_PATH}" ]] \
    && remote_companion_artifact_architecture_matches \
      "${REMOTE_COMPANION_APP_PATH}"
}

fetch_remote_companion_manifest_release(){
  local panel_url="$1"
  local arch="$2"
  local tmp_dir="$3"
  local local_version="$4"
  local installed_sha="$5"
  local manifest_url="${panel_url}/static/remote-mac-agent/current-${arch}.json"
  local attempt=""
  local manifest_before=""
  local manifest_after=""
  local manifest_final=""
  local fields=""
  local release_id=""
  local remote_version=""
  local expected_sha=""
  local archive_size=""
  local archive_path=""
  local sha_path=""
  local version_path=""
  local sha_file=""
  local version_file=""
  local zip_file="${tmp_dir}/RemoteMacAgent.zip"
  local sidecar_sha=""
  local sidecar_version=""
  local actual_size=""

  for attempt in 1 2 3; do
    manifest_before="${tmp_dir}/manifest-${attempt}-before.json"
    manifest_after="${tmp_dir}/manifest-${attempt}-after.json"
    manifest_final="${tmp_dir}/manifest-${attempt}-final.json"
    sha_file="${tmp_dir}/manifest-${attempt}.sha256"
    version_file="${tmp_dir}/manifest-${attempt}.version"

    if ! REALM_AGENT_UPDATE_CURL_MAX_TIME=30 \
      REALM_AGENT_UPDATE_CURL_RETRY=1 \
      download_fresh_file "${manifest_url}" "${manifest_before}"; then
      return 2
    fi
    fields="$(
      parse_remote_companion_release_manifest \
        "${manifest_before}" "${arch}" 2>/dev/null
    )" || {
      err "RemoteMacAgent current manifest 格式无效，拒绝回退到可变三件套"
      return 1
    }
    IFS=$'\t' read -r \
      release_id remote_version expected_sha archive_size \
      archive_path sha_path version_path <<< "${fields}"
    if ! remote_companion_sha_override_matches "${expected_sha}"; then
      return 1
    fi
    if ! download_fresh_file \
      "${panel_url}/static/${sha_path}" "${sha_file}" \
      || ! download_fresh_file \
        "${panel_url}/static/${version_path}" "${version_file}"; then
      warn "RemoteMacAgent manifest 三件套尚不可完整读取，重试 ${attempt}/3"
      continue
    fi
    sidecar_sha="$(
      read_sha256_sidecar \
        "${sha_file}" "RemoteMacAgent-${arch}.zip" \
        || true
    )"
    sidecar_version="$(
      read_remote_companion_version_sidecar "${version_file}" || true
    )"
    if [[ "${sidecar_sha}" != "${expected_sha}" \
      || "${sidecar_version}" != "${remote_version}" ]]; then
      err "RemoteMacAgent manifest 与不可变三件套元数据不一致"
      return 1
    fi
    if ! download_fresh_file "${manifest_url}" "${manifest_after}"; then
      warn "RemoteMacAgent current manifest 复读失败，重试 ${attempt}/3"
      continue
    fi
    if ! cmp -s "${manifest_before}" "${manifest_after}"; then
      warn "检测到 RemoteMacAgent 发布切换，丢弃本轮读取并重试 ${attempt}/3"
      continue
    fi

    REMOTE_COMPANION_RELEASE_VERSION="${remote_version}"
    REMOTE_COMPANION_RELEASE_SHA256="${expected_sha}"
    REMOTE_COMPANION_RELEASE_ZIP=""
    if remote_companion_installed_release_matches \
      "${local_version}" "${remote_version}" \
      "${installed_sha}" "${expected_sha}"; then
      info "RemoteMacAgent.app 版本与 current manifest 均匹配（v${local_version}），跳过下载"
      return 10
    fi

    if ! download_fresh_file \
      "${panel_url}/static/${archive_path}" "${zip_file}"; then
      warn "RemoteMacAgent 不可变 archive 下载失败，重试 ${attempt}/3"
      continue
    fi
    if ! download_fresh_file "${manifest_url}" "${manifest_final}" \
      || ! cmp -s "${manifest_before}" "${manifest_final}"; then
      warn "RemoteMacAgent archive 下载期间发生发布切换，重试 ${attempt}/3"
      continue
    fi
    actual_size="$(remote_companion_file_size "${zip_file}" || true)"
    if [[ "${actual_size}" != "${archive_size}" ]]; then
      err "RemoteMacAgent archive 大小与 current manifest 不一致"
      return 1
    fi
    if ! verify_file_sha256 "${zip_file}" "${expected_sha}"; then
      err "RemoteMacAgent archive 与 current manifest 的 SHA256 不一致"
      return 1
    fi
    REMOTE_COMPANION_RELEASE_ZIP="${zip_file}"
    info "已锁定 RemoteMacAgent release：${release_id}"
    return 0
  done

  err "RemoteMacAgent current manifest 持续切换或读取不完整，拒绝安装"
  return 1
}

fetch_remote_companion_legacy_release(){
  local panel_url="$1"
  local arch="$2"
  local tmp_dir="$3"
  local local_version="$4"
  local installed_sha="$5"
  local zip_url="${panel_url}/static/RemoteMacAgent-${arch}.zip"
  local sha_url="${zip_url}.sha256"
  local version_url="${zip_url}.version"
  local zip_file="${tmp_dir}/RemoteMacAgent.zip"
  local sha_before="${tmp_dir}/legacy-before.sha256"
  local sha_after="${tmp_dir}/legacy-after.sha256"
  local version_before="${tmp_dir}/legacy-before.version"
  local version_after="${tmp_dir}/legacy-after.version"
  local attempt=""
  local expected_sha=""
  local remote_version=""

  for attempt in 1 2 3; do
    if ! download_fresh_file "${sha_url}" "${sha_before}" \
      || ! download_fresh_file "${version_url}" "${version_before}"; then
      err "旧 RemoteMacAgent 三件套缺少 .sha256 或 .version，拒绝安装"
      return 1
    fi
    expected_sha="$(
      read_sha256_sidecar \
        "${sha_before}" "RemoteMacAgent-${arch}.zip" \
        || true
    )"
    remote_version="$(
      read_remote_companion_version_sidecar "${version_before}" || true
    )"
    if [[ -z "${expected_sha}" || -z "${remote_version}" ]]; then
      err "旧 RemoteMacAgent 三件套元数据无效，拒绝安装"
      return 1
    fi
    if ! remote_companion_sha_override_matches "${expected_sha}"; then
      return 1
    fi
    if ! download_fresh_file "${sha_url}" "${sha_after}" \
      || ! download_fresh_file "${version_url}" "${version_after}"; then
      warn "旧 RemoteMacAgent 三件套复读失败，重试 ${attempt}/3"
      continue
    fi
    if ! cmp -s "${sha_before}" "${sha_after}" \
      || ! cmp -s "${version_before}" "${version_after}"; then
      warn "检测到旧 RemoteMacAgent 三件套发布切换，重试 ${attempt}/3"
      continue
    fi

    REMOTE_COMPANION_RELEASE_VERSION="${remote_version}"
    REMOTE_COMPANION_RELEASE_SHA256="${expected_sha}"
    REMOTE_COMPANION_RELEASE_ZIP=""
    if remote_companion_installed_release_matches \
      "${local_version}" "${remote_version}" \
      "${installed_sha}" "${expected_sha}"; then
      info "RemoteMacAgent.app 版本与旧三件套 SHA 均匹配（v${local_version}），跳过下载"
      return 10
    fi

    if ! download_fresh_file "${zip_url}" "${zip_file}" \
      || ! download_fresh_file "${sha_url}" "${sha_after}" \
      || ! download_fresh_file "${version_url}" "${version_after}"; then
      warn "旧 RemoteMacAgent 三件套读取不完整，重试 ${attempt}/3"
      continue
    fi
    if ! cmp -s "${sha_before}" "${sha_after}" \
      || ! cmp -s "${version_before}" "${version_after}"; then
      warn "旧 RemoteMacAgent archive 下载期间发生发布切换，重试 ${attempt}/3"
      continue
    fi
    if ! verify_file_sha256 "${zip_file}" "${expected_sha}"; then
      err "旧 RemoteMacAgent 三件套 SHA256 不匹配，拒绝安装"
      return 1
    fi
    REMOTE_COMPANION_RELEASE_ZIP="${zip_file}"
    return 0
  done

  err "旧 RemoteMacAgent 三件套持续变化，拒绝安装"
  return 1
}

# 优先读取 /static/remote-mac-agent/current-${arch}.json，再按 manifest 指向的
# 不可变目录读取 zip/sha256/version。旧 panel 没有 manifest 时，兼容固定三件套，
# 但必须前后复读 sidecar 并拒绝任何发布切换或跨版本混合。
download_and_install_remote_companion_artifact(){
  command -v curl >/dev/null 2>&1 || return 1
  command -v unzip >/dev/null 2>&1 || return 1
  command -v shasum >/dev/null 2>&1 || return 1

  local arch
  arch="$(remote_companion_current_arch || true)"
  if [[ -z "${arch}" ]]; then
    err "不支持的 Mac CPU 架构：$(uname -m)"
    return 1
  fi
  local panel_url
  panel_url="$(resolve_remote_companion_panel_url)"
  if ! remote_companion_panel_url_allowed "${panel_url}"; then
    err "RemoteMacAgent 拒绝从不安全的 panel URL 下载：${panel_url}"
    return 1
  fi
  local tmp_dir
  tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/realm-mac-app.XXXXXX")" || return 1
  chmod 700 "${tmp_dir}" >/dev/null 2>&1 || true
  register_cleanup_path "${tmp_dir}"

  local local_version=""
  local installed_sha=""
  local fetch_status="0"
  local_version="$(read_local_remote_companion_version || true)"
  if [[ -f "${REMOTE_COMPANION_ARTIFACT_SHA_PATH}" ]]; then
    installed_sha="$(
      head -n 1 "${REMOTE_COMPANION_ARTIFACT_SHA_PATH}" 2>/dev/null \
        | tr -d '\r\n ' \
        | tr '[:upper:]' '[:lower:]' \
        || true
    )"
  fi

  if fetch_remote_companion_manifest_release \
    "${panel_url}" "${arch}" "${tmp_dir}" \
    "${local_version}" "${installed_sha}"; then
    fetch_status="0"
  else
    fetch_status="$?"
  fi
  if [[ "${fetch_status}" == "10" ]]; then
    rm -rf "${tmp_dir}"
    return 0
  fi
  if [[ "${fetch_status}" == "2" ]]; then
    info "panel 尚无 RemoteMacAgent current manifest，使用旧三件套 fail-closed 兼容读取"
    if fetch_remote_companion_legacy_release \
      "${panel_url}" "${arch}" "${tmp_dir}" \
      "${local_version}" "${installed_sha}"; then
      fetch_status="0"
    else
      fetch_status="$?"
    fi
  fi
  if [[ "${fetch_status}" == "10" ]]; then
    rm -rf "${tmp_dir}"
    return 0
  fi
  if [[ "${fetch_status}" != "0" \
    || -z "${REMOTE_COMPANION_RELEASE_ZIP}" \
    || ! -f "${REMOTE_COMPANION_RELEASE_ZIP}" ]]; then
    rm -rf "${tmp_dir}"
    return 1
  fi

  info "下载 RemoteMacAgent.app（${arch}, v${REMOTE_COMPANION_RELEASE_VERSION}）..."
  ok "RemoteMacAgent.app sha256 校验通过"
  if ! validate_zip_archive \
    "${REMOTE_COMPANION_RELEASE_ZIP}" allow-safe-symlinks; then
    err "RemoteMacAgent zip 结构或内容不安全"
    rm -rf "${tmp_dir}"
    return 1
  fi

  local extract_dir="${tmp_dir}/extract"
  install -d -m 700 "${extract_dir}"
  if ! unzip -q "${REMOTE_COMPANION_RELEASE_ZIP}" -d "${extract_dir}"; then
    err "解压 RemoteMacAgent zip 失败"
    rm -rf "${tmp_dir}"
    return 1
  fi
  local extracted_app
  extracted_app="$(find "${extract_dir}" -maxdepth 4 -type d -name 'RemoteMacAgent.app' -print -quit 2>/dev/null || true)"
  if [[ -z "${extracted_app}" || ! -d "${extracted_app}" ]]; then
    err "下载的 zip 中找不到 RemoteMacAgent.app"
    rm -rf "${tmp_dir}"
    return 1
  fi
  if ! validate_remote_companion_app_tree "${extracted_app}"; then
    err "RemoteMacAgent.app 含有指向 bundle 外部的符号链接"
    rm -rf "${tmp_dir}"
    return 1
  fi
  if ! verify_remote_companion_bundle_signature "${extracted_app}"; then
    rm -rf "${tmp_dir}"
    return 1
  fi
  local extracted_version=""
  extracted_version="$(
    read_remote_companion_app_version "${extracted_app}" || true
  )"
  if [[ "${extracted_version}" != "${REMOTE_COMPANION_RELEASE_VERSION}" ]]; then
    err "RemoteMacAgent zip 内版本与发布 version 不一致，拒绝安装"
    rm -rf "${tmp_dir}"
    return 1
  fi

  install -d -m 755 "$(dirname "${REMOTE_COMPANION_APP_PATH}")"
  local staging="${REMOTE_COMPANION_APP_PATH}.new"
  staging="$(mktemp -d "${REMOTE_COMPANION_APP_PATH}.new.XXXXXX")"
  rmdir "${staging}"
  register_cleanup_path "${staging}"
  cp -R "${extracted_app}" "${staging}"
  normalize_remote_companion_bundle_permissions "${staging}" || return 1
  if ! commit_remote_companion_staging \
    "${staging}" "${REMOTE_COMPANION_RELEASE_SHA256}"; then
    rm -rf "${tmp_dir}"
    return 1
  fi
  normalize_remote_companion_bundle_permissions \
    "${REMOTE_COMPANION_APP_PATH}" || return 1
  rm -rf "${tmp_dir}"
  ok "RemoteMacAgent.app 已下载安装到 ${REMOTE_COMPANION_APP_PATH}"
  return 0
}

find_remote_companion_artifact(){
  local root="${1:-}"
  [[ -n "${root}" && -d "${root}" ]] || return 1

  local arch=""
  local found=""
  local candidate=""
  arch="$(remote_companion_current_arch || true)"
  [[ -n "${arch}" ]] || return 1

  found="$(find "${root}" -maxdepth 8 -type f -name "RemoteMacAgent-${arch}.zip" -print -quit 2>/dev/null || true)"
  if [[ -n "${found}" ]]; then
    echo "${found}"
    return 0
  fi

  while IFS= read -r candidate; do
    [[ -n "${candidate}" ]] || continue
    if remote_companion_artifact_architecture_matches "${candidate}"; then
      echo "${candidate}"
      return 0
    fi
  done < <(find "${root}" -maxdepth 8 -type d -name "RemoteMacAgent.app" -print 2>/dev/null)

  found="$(find "${root}" -maxdepth 8 -type f \( -name "RemoteMacAgent.zip" -o -name "remote-mac-agent.zip" -o -name "realm-remote-mac-agent.zip" \) -print -quit 2>/dev/null || true)"
  if [[ -n "${found}" ]]; then
    echo "${found}"
    return 0
  fi

  while IFS= read -r candidate; do
    [[ -n "${candidate}" ]] || continue
    if remote_companion_artifact_architecture_matches "${candidate}"; then
      echo "${candidate}"
      return 0
    fi
  done < <(
    find "${root}" -maxdepth 8 -type f \
      \( -name "RemoteMacAgent" -o -name "realm-remote-mac-agent" -o -name "remote-mac-agent" \) \
      -perm -111 -print 2>/dev/null
  )
  return 1
}

install_remote_companion_artifact(){
  local artifact="${1:-}"
  local tmpdir="${2:-}"
  [[ -n "${artifact}" && -e "${artifact}" ]] || return 1

  install -d -m 755 "${BASE_DIR}"
  local staging="${REMOTE_COMPANION_APP_PATH}.new"
  staging="$(mktemp -d "${REMOTE_COMPANION_APP_PATH}.new.XXXXXX")"
  rmdir "${staging}"
  register_cleanup_path "${staging}"
  if [[ -d "${artifact}" && "${artifact}" == *.app ]]; then
    if ! validate_remote_companion_app_tree "${artifact}" \
      || ! verify_remote_companion_bundle_signature "${artifact}"; then
      warn "RemoteMacAgent.app bundle 安全复核失败：${artifact}"
      return 1
    fi
    cp -R "${artifact}" "${staging}"
  elif [[ -f "${artifact}" && "${artifact}" == *.zip ]]; then
    if ! validate_zip_archive "${artifact}" allow-safe-symlinks; then
      warn "RemoteMacAgent zip 结构或内容不安全：${artifact}"
      return 1
    fi
    local unzip_dir="${tmpdir}/remote-companion-unzip"
    rm -rf "${unzip_dir}"
    mkdir -p "${unzip_dir}"
    unzip -q "${artifact}" -d "${unzip_dir}"
    local app_in_zip=""
    app_in_zip="$(find_remote_companion_artifact "${unzip_dir}" || true)"
    if [[ -n "${app_in_zip}" ]]; then
      install_remote_companion_artifact "${app_in_zip}" "${unzip_dir}" || return 1
      return 0
    else
      warn "RemoteMacAgent zip 中未找到 .app bundle 或可执行文件：${artifact}"
      return 1
    fi
  elif [[ -f "${artifact}" ]]; then
    local app_contents="${staging}/Contents"
    install -d -m 755 "${app_contents}/MacOS"
    cp -f "${artifact}" "${app_contents}/MacOS/RemoteMacAgent"
    chmod 755 "${app_contents}/MacOS/RemoteMacAgent" >/dev/null 2>&1 || true
    cat > "${app_contents}/Info.plist" <<EOF_INFO_PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleExecutable</key>
  <string>RemoteMacAgent</string>
  <key>CFBundleIdentifier</key>
  <string>${REMOTE_COMPANION_LABEL}</string>
  <key>CFBundleName</key>
  <string>RemoteMacAgent</string>
  <key>CFBundlePackageType</key>
  <string>APPL</string>
  <key>CFBundleVersion</key>
  <string>0.1.0</string>
</dict>
</plist>
EOF_INFO_PLIST
  else
    return 1
  fi

  normalize_remote_companion_bundle_permissions "${staging}" || return 1
  chmod -R go-w "${staging}" || return 1
  sign_remote_companion_app "${staging}"
  if ! validate_remote_companion_app_tree "${staging}" \
    || ! verify_remote_companion_bundle_signature "${staging}" \
    || ! commit_remote_companion_staging "${staging}" ""; then
    return 1
  fi
  normalize_remote_companion_bundle_permissions \
    "${REMOTE_COMPANION_APP_PATH}" || return 1
  clear_quarantine_flag "${REMOTE_COMPANION_APP_PATH}"
  if command_exists xattr; then
    xattr -dr com.apple.quarantine "${REMOTE_COMPANION_APP_PATH}" >/dev/null 2>&1 || true
  fi
  sign_remote_companion_app "${REMOTE_COMPANION_APP_PATH}"
  return 0
}

log_remote_companion_key_event(){
  local level="$1"
  shift
  local message="$*"
  case "${level}" in
    error) err "${message}" ;;
    *) warn "${message}" ;;
  esac
  if [[ -x /usr/bin/logger ]]; then
    /usr/bin/logger -t realm-agent-installer -- "${message}" >/dev/null 2>&1 || true
  fi
}

restrict_remote_companion_key_file(){
  local path="${1:-}"
  [[ -e "${path}" || -L "${path}" ]] || return 0
  if [[ ! -f "${path}" || -L "${path}" ]]; then
    err "RemoteMacAgent API key 路径不是可信普通文件：${path}"
    return 1
  fi
  chmod -N "${path}" || return 1
  fix_owner_mode_strict "${path}" 600 || return 1
  fsync_path_and_parent "${path}"
}

restrict_remote_companion_legacy_key(){
  local failed="0"
  restrict_remote_companion_key_file \
    "${REMOTE_COMPANION_API_KEY_PATH}" || failed="1"
  restrict_remote_companion_key_file \
    /etc/realm-agent/api.key || failed="1"
  [[ "${failed}" == "0" ]] || return 1
  REMOTE_COMPANION_LEGACY_KEY_EXPOSED="0"
}

secure_and_rollback_remote_companion_update(){
  local reason="${1:-RemoteMacAgent 更新未完成}"
  local failed="0"
  set_remote_companion_transaction_paths
  restrict_remote_companion_legacy_key || failed="1"
  if remote_companion_update_material_present; then
    rollback_remote_companion_update "${reason}" || failed="1"
  fi
  [[ "${failed}" == "0" ]]
}

remote_companion_update_material_present(){
  [[ "${REMOTE_COMPANION_UPDATE_PENDING:-0}" == "1" ]] \
    || remote_companion_durable_update_material_present
}

remote_companion_durable_update_material_present(){
  set_remote_companion_transaction_paths
  [[ -e "${REMOTE_COMPANION_TRANSACTION_DIR}" \
    || -L "${REMOTE_COMPANION_TRANSACTION_DIR}" \
    || -e "${REMOTE_COMPANION_UPDATE_BACKUP}" \
    || -L "${REMOTE_COMPANION_UPDATE_BACKUP}" \
    || -e "${REALM_MAC_TRANSACTION_DIR}/remote-companion-index" \
    || -L "${REALM_MAC_TRANSACTION_DIR}/remote-companion-index" \
    || -e "${REALM_MAC_TRANSACTION_DIR}/remote-companion-app-path" \
    || -L "${REALM_MAC_TRANSACTION_DIR}/remote-companion-app-path" \
    || -e "${REALM_MAC_TRANSACTION_DIR}/remote-companion-home" \
    || -L "${REALM_MAC_TRANSACTION_DIR}/remote-companion-home" ]]
}

retain_remote_companion_legacy_key_fallback(){
  local desktop_user="${1:-}"
  local desktop_uid="${2:-}"
  local desktop_gid="${3:-}"
  local desktop_group="${4:-}"
  remote_companion_desktop_identity_matches \
    "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
    "${desktop_group}" || return 1
  [[ -f "${REMOTE_COMPANION_API_KEY_PATH}" \
    && ! -L "${REMOTE_COMPANION_API_KEY_PATH}" ]] || return 1
  chmod -N "${REMOTE_COMPANION_API_KEY_PATH}" || return 1
  fix_owner_mode_strict \
    "${REMOTE_COMPANION_API_KEY_PATH}" 600 || return 1
  REMOTE_COMPANION_LEGACY_KEY_EXPOSED="1"
  chmod +a "${desktop_user} allow read,readattr" \
    "${REMOTE_COMPANION_API_KEY_PATH}" || return 1
  fsync_path_and_parent "${REMOTE_COMPANION_API_KEY_PATH}" || return 1
  verify_remote_companion_path_for_user \
    "${desktop_user}" -r "${REMOTE_COMPANION_API_KEY_PATH}" \
    "${desktop_uid}" "${desktop_gid}" "${desktop_group}" || return 1
  REMOTE_COMPANION_LEGACY_KEY_EXPOSED="0"
}

read_remote_companion_keychain_key(){
  local desktop_uid="${1:-}"
  local desktop_user="${2:-}"
  local desktop_gid="${3:-}"
  local desktop_group="${4:-}"
  local timeout="${REALM_REMOTE_KEYCHAIN_TIMEOUT_SECONDS:-8}"
  remote_companion_desktop_identity_matches \
    "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
    "${desktop_group}" || return 1
  [[ "${timeout}" =~ ^[0-9]+$ ]] || timeout="8"
  if (( timeout < 1 || timeout > 30 )); then
    timeout="8"
  fi
  [[ -x /bin/launchctl && -x /usr/bin/sudo && -x /usr/bin/security ]] \
    || return 1
  ensure_trusted_macos_agent_python || return 1
  run_trusted_macos_python - \
    "${desktop_uid}" \
    "${desktop_user}" \
    "${REMOTE_COMPANION_KEYCHAIN_SERVICE}" \
    "${REMOTE_COMPANION_KEYCHAIN_ACCOUNT}" \
    "${timeout}" <<'PY'
import os
import signal
import subprocess
import sys

uid, user, service, account, timeout_raw = sys.argv[1:]
command = [
    "/bin/launchctl",
    "asuser",
    uid,
    "/usr/bin/sudo",
    "-u",
    f"#{uid}",
    "-H",
    "/usr/bin/security",
    "find-generic-password",
    "-s",
    service,
    "-a",
    account,
    "-w",
]
process = subprocess.Popen(
    command,
    stdout=subprocess.PIPE,
    stderr=subprocess.DEVNULL,
    start_new_session=True,
)
try:
    stdout, _ = process.communicate(timeout=int(timeout_raw))
except subprocess.TimeoutExpired:
    os.killpg(process.pid, signal.SIGKILL)
    process.communicate()
    raise SystemExit(124)
if process.returncode != 0:
    raise SystemExit(process.returncode)
sys.stdout.buffer.write(stdout)
PY
}

finalize_remote_companion_legacy_key(){
  local desktop_uid="${1:-}"
  local desktop_user="${2:-}"
  local desktop_gid="${3:-}"
  local desktop_group="${4:-}"
  local expected_key=""
  local keychain_key=""
  local legacy_key=""
  expected_key="$(cat /etc/realm-agent/api.key 2>/dev/null || true)"
  if [[ -z "${expected_key}" ]]; then
    log_remote_companion_key_event error \
      "RemoteMacAgent Keychain 迁移无法确认：root API key 缺失；legacy 明文已收紧"
    restrict_remote_companion_legacy_key
    return 1
  fi
  keychain_key="$(read_remote_companion_keychain_key \
    "${desktop_uid}" "${desktop_user}" \
    "${desktop_gid}" "${desktop_group}" || true)"
  if [[ -n "${keychain_key}" && "${keychain_key}" == "${expected_key}" ]]; then
    if chmod -N "${REMOTE_COMPANION_API_KEY_PATH}" \
      && remove_macos_rollback_file "${REMOTE_COMPANION_API_KEY_PATH}"; then
      REMOTE_COMPANION_LEGACY_KEY_EXPOSED="0"
      ok "已确认 RemoteMacAgent Keychain 写入并删除 legacy API key 文件"
      return 0
    fi
    log_remote_companion_key_event error \
      "RemoteMacAgent Keychain 已确认，但 legacy API key 删除失败；已撤销用户 ACL 并收紧为 root:wheel 0600"
    restrict_remote_companion_legacy_key
    return 1
  fi
  legacy_key="$(cat "${REMOTE_COMPANION_API_KEY_PATH}" 2>/dev/null || true)"
  if [[ -n "${legacy_key}" && "${legacy_key}" == "${expected_key}" ]] \
    && retain_remote_companion_legacy_key_fallback \
      "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
      "${desktop_group}"; then
    log_remote_companion_key_event warning \
      "RemoteMacAgent Keychain 写入未确认；保留 root:wheel 0600 且仅桌面用户可读的兼容凭据"
    return 0
  fi
  log_remote_companion_key_event error \
    "RemoteMacAgent Keychain 写入未确认且受限兼容凭据不可用；已禁用 legacy 明文权威源"
  restrict_remote_companion_legacy_key
  return 1
}

write_remote_companion_legacy_key(){
  local api_key="${1:-}"
  local parent=""
  local temp_path=""
  [[ -n "${api_key}" ]] || return 1
  parent="$(dirname "${REMOTE_COMPANION_API_KEY_PATH}")"
  if [[ ! -d "${parent}" || -L "${parent}" \
    || -L "${REMOTE_COMPANION_API_KEY_PATH}" \
    || ( -e "${REMOTE_COMPANION_API_KEY_PATH}" \
      && ! -f "${REMOTE_COMPANION_API_KEY_PATH}" ) ]]; then
    err "RemoteMacAgent legacy API key 目标不可信"
    return 1
  fi
  temp_path="$(mktemp "${REMOTE_COMPANION_API_KEY_PATH}.tmp.XXXXXX")" \
    || return 1
  register_cleanup_path "${temp_path}"
  printf '%s\n' "${api_key}" > "${temp_path}" || return 1
  chmod -N "${temp_path}" || return 1
  publish_root_owned_regular_file \
    "${temp_path}" "${REMOTE_COMPANION_API_KEY_PATH}" 600
}

validate_remote_companion_config(){
  local path="${1:-}"
  [[ -f "${path}" && ! -L "${path}" ]] || return 1
  ensure_trusted_macos_agent_python || return 1
  run_trusted_macos_python - "${path}" <<'PY'
import json
import pathlib
import sys

payload = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8"))
if not isinstance(payload, dict):
    raise SystemExit("remote companion config must be an object")
PY
}

write_remote_companion_config(){
  local remote_enabled="$1"
  local desktop_user="${2:-}"
  local desktop_uid="${3:-}"
  local desktop_gid="${4:-}"
  local desktop_group="${5:-}"
  local panel_url=""
  local node_id="0"
  local clipboard_enabled=""
  local unattended=""
  local local_approval_required=""
  local quality_default=""
  local api_key=""
  local config_tmp=""

  panel_url="$(panel_url_without_trailing_slash "${REALM_PANEL_URL:-}")"
  node_id="${REALM_AGENT_ID:-0}"
  if [[ -f /etc/realm-agent/panel.env ]]; then
    if [[ -z "${panel_url}" ]]; then
      panel_url="$(panel_url_without_trailing_slash "$(read_env_value /etc/realm-agent/panel.env REALM_PANEL_URL || true)")"
    fi
    if [[ "${node_id}" == "0" || -z "${node_id}" ]]; then
      node_id="$(read_env_value /etc/realm-agent/panel.env REALM_AGENT_ID || true)"
    fi
  fi
  if [[ ! "${node_id}" =~ ^[0-9]+$ ]]; then
    node_id="0"
  fi

  install -d -m 700 /etc/realm-agent || return 1
  fix_owner_mode_strict /etc/realm-agent 700 || return 1
  fsync_directory_and_parent /etc/realm-agent || return 1
  if [[ -f /etc/realm-agent/api.key ]]; then
    api_key="$(cat /etc/realm-agent/api.key 2>/dev/null || true)"
  fi
  if [[ -n "${api_key}" ]]; then
    write_remote_companion_legacy_key "${api_key}" || return 1
  fi

  clipboard_enabled="$(normalize_bool "${REALM_REMOTE_CLIPBOARD_ENABLED:-1}")"
  unattended="$(normalize_bool "${REALM_REMOTE_UNATTENDED:-1}")"
  if [[ "${unattended}" == "true" ]]; then
    local_approval_required="false"
  else
    local_approval_required="true"
  fi
  if [[ -n "${REALM_REMOTE_LOCAL_APPROVAL_REQUIRED:-}" ]]; then
    local_approval_required="$(normalize_bool "${REALM_REMOTE_LOCAL_APPROVAL_REQUIRED}")"
  fi
  quality_default="${REALM_REMOTE_QUALITY_DEFAULT:-balanced}"
  case "${quality_default}" in
    low|balanced|sharp_text|smooth|4k) ;;
    *) quality_default="balanced" ;;
  esac

  if [[ -L "${REMOTE_COMPANION_CONFIG}" \
    || ( -e "${REMOTE_COMPANION_CONFIG}" \
      && ! -f "${REMOTE_COMPANION_CONFIG}" ) ]]; then
    err "RemoteMacAgent config 目标不可信"
    return 1
  fi
  config_tmp="$(mktemp "${REMOTE_COMPANION_CONFIG}.tmp.XXXXXX")" || return 1
  register_cleanup_path "${config_tmp}"
  if ! cat > "${config_tmp}" <<EOF_REMOTE_CONFIG
{
  "node_id": ${node_id},
  "panel_url": $(json_escape "${panel_url}"),
  "api_key_path": $(json_escape "${REMOTE_COMPANION_API_KEY_PATH}"),
  "remote_enabled": ${remote_enabled},
  "unattended": ${unattended},
  "local_approval_required": ${local_approval_required},
  "clipboard_enabled": ${clipboard_enabled},
  "quality_default": $(json_escape "${quality_default}")
}
EOF_REMOTE_CONFIG
  then
    return 1
  fi
  validate_remote_companion_config "${config_tmp}" || return 1
  publish_root_owned_regular_file \
    "${config_tmp}" "${REMOTE_COMPANION_CONFIG}" 600 || return 1
  if [[ -n "${desktop_user}" ]]; then
    if ! remote_companion_desktop_identity_matches \
        "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
        "${desktop_group}" \
      || ! chmod +a "${desktop_user} allow search,readattr" \
        /etc/realm-agent \
      || ! remote_companion_desktop_identity_matches \
        "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
        "${desktop_group}" \
      || ! chmod +a "${desktop_user} allow read,readattr" \
        "${REMOTE_COMPANION_CONFIG}" \
      || ! fsync_directory_and_parent /etc/realm-agent \
      || ! fsync_path_and_parent "${REMOTE_COMPANION_CONFIG}" \
      || ! verify_remote_companion_path_for_user \
        "${desktop_user}" -x /etc/realm-agent \
        "${desktop_uid}" "${desktop_gid}" "${desktop_group}" \
      || ! verify_remote_companion_path_for_user \
        "${desktop_user}" -r "${REMOTE_COMPANION_CONFIG}" \
        "${desktop_uid}" "${desktop_gid}" "${desktop_group}"; then
      if ! restrict_remote_companion_legacy_key; then
        err "RemoteMacAgent config ACL 失败后无法收紧 legacy API key"
      fi
      err "RemoteMacAgent config ACL 或桌面用户读取校验失败"
      return 1
    fi
    if [[ "${remote_enabled}" == "true" \
          && -n "${api_key}" \
          && -f "${REMOTE_COMPANION_API_KEY_PATH}" ]]; then
      REMOTE_COMPANION_LEGACY_KEY_EXPOSED="1"
      if ! remote_companion_desktop_identity_matches \
          "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
          "${desktop_group}" \
        || ! chmod +a "${desktop_user} allow read,readattr" \
          "${REMOTE_COMPANION_API_KEY_PATH}" \
        || ! remote_companion_desktop_identity_matches \
          "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
          "${desktop_group}" \
        || ! fsync_path_and_parent "${REMOTE_COMPANION_API_KEY_PATH}" \
        || ! verify_remote_companion_path_for_user \
          "${desktop_user}" -r "${REMOTE_COMPANION_API_KEY_PATH}" \
          "${desktop_uid}" "${desktop_gid}" "${desktop_group}"; then
        if ! restrict_remote_companion_legacy_key; then
          err "RemoteMacAgent key ACL 失败后无法收紧 legacy API key"
        fi
        return 1
      fi
    fi
  fi
  if [[ "${remote_enabled}" != "true" || -z "${api_key}" ]]; then
    restrict_remote_companion_legacy_key || return 1
  fi
}

write_remote_companion_placeholder(){
  cat > "${BASE_DIR}/RemoteMacAgent.README.txt" <<'EOF_REMOTE_PLACEHOLDER'
RemoteMacAgent.app was not bundled with this installer archive.

The main Realm Python agent was installed normally. Remote control remains
inactive until a macOS companion artifact is placed at:

  /usr/local/realm-agent/RemoteMacAgent.app

After copying the app, run:

  sudo REALM_REMOTE_CODESIGN_KEYCHAIN=/Users/YOUR_USER/.realm-remote-agent/codesign/realm-remote-agent-signing.keychain-db \\
    REALM_REMOTE_CODESIGN_KEYCHAIN_PASSWORD_FILE=/Users/YOUR_USER/.realm-remote-agent/codesign/keychain.pass \\
    /bin/bash -p realm_agent_macos.sh
  sudo xattr -dr com.apple.quarantine /usr/local/realm-agent/RemoteMacAgent.app
  launchctl load -w ~/Library/LaunchAgents/com.realm.remote-mac-agent.plist

The companion writes its runtime status to:

  ~/Library/Application Support/com.realm.remote-mac-agent/status.json

(legacy installs may keep using /var/lib/realm-agent/remote-mac-agent/status.json
until the new LaunchAgent recreates the file under the desktop user's home.)
EOF_REMOTE_PLACEHOLDER
  chmod 644 "${BASE_DIR}/RemoteMacAgent.README.txt" >/dev/null 2>&1 || true
  chown root:wheel "${BASE_DIR}/RemoteMacAgent.README.txt" >/dev/null 2>&1 || true
}

write_remote_companion_launchagent(){
  # 此函数生成的 plist 与 agent/launchd/com.realm.remote-mac-agent.plist.example
  # 保持一致；example 模板使用 __INSTALL_DIR__ / __CONFIG_FILE__
  # 占位符，本函数等价地通过 heredoc 内插具体值（root 持有 config，ACL 授权
  # 桌面用户读取）。
  local desktop_user="$1"
  local desktop_home="$2"
  local desktop_group="$3"
  local desktop_uid="$4"
  local desktop_gid="$5"
  local launchagents_dir="${desktop_home}/Library/LaunchAgents"
  local plist="${launchagents_dir}/${REMOTE_COMPANION_LABEL}.plist"
  local plist_tmp=""
  local companion_program=""
  local plist_label=""
  local plist_config=""
  local plist_status=""

  remote_companion_desktop_identity_matches \
    "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
    "${desktop_group}" || return 1
  companion_program="$(remote_companion_app_executable "${REMOTE_COMPANION_APP_PATH}" || true)"
  if [[ -z "${companion_program}" ]]; then
    warn "RemoteMacAgent.app 中未找到可执行文件"
    return 1
  fi
  plist_label="$(xml_escape "${REMOTE_COMPANION_LABEL}")"
  companion_program="$(xml_escape "${companion_program}")"
  plist_config="$(xml_escape "${REMOTE_COMPANION_CONFIG}")"
  plist_status="$(xml_escape "${REMOTE_COMPANION_STATUS}")"

  install -d -m 755 "${launchagents_dir}" || return 1
  fix_user_mode_strict \
    "${launchagents_dir}" 755 "${desktop_user}" "${desktop_group}" \
    "${desktop_uid}" "${desktop_gid}" || return 1
  plist_tmp="$(mktemp "${launchagents_dir}/.${REMOTE_COMPANION_LABEL}.plist.XXXXXX")" \
    || return 1
  register_cleanup_path "${plist_tmp}"
  cat > "${plist_tmp}" <<EOF_REMOTE_LAUNCHAGENT
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>${plist_label}</string>
  <key>ProgramArguments</key>
  <array>
    <string>${companion_program}</string>
  </array>
  <key>EnvironmentVariables</key>
  <dict>
    <key>REALM_REMOTE_COMPANION_CONFIG</key>
    <string>${plist_config}</string>
    <key>REALM_REMOTE_COMPANION_STATUS_PATH</key>
    <string>${plist_status}</string>
  </dict>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>ProcessType</key>
  <string>Interactive</string>
  <key>LimitLoadToSessionType</key>
  <string>Aqua</string>
  <key>ThrottleInterval</key>
  <integer>10</integer>
  <key>SoftResourceLimits</key>
  <dict>
    <key>NumberOfFiles</key>
    <integer>1024</integer>
    <key>ResidentSetSize</key>
    <integer>314572800</integer>
  </dict>
  <key>HardResourceLimits</key>
  <dict>
    <key>NumberOfFiles</key>
    <integer>2048</integer>
    <key>ResidentSetSize</key>
    <integer>536870912</integer>
  </dict>
</dict>
</plist>
EOF_REMOTE_LAUNCHAGENT
  validate_plist_file "${plist_tmp}" || return 1
  fix_user_mode_strict \
    "${plist_tmp}" 644 "${desktop_user}" "${desktop_group}" \
    "${desktop_uid}" "${desktop_gid}" || return 1
  fsync_path_and_parent "${plist_tmp}" || return 1
  mv -f "${plist_tmp}" "${plist}" || return 1
  fix_user_mode_strict \
    "${plist}" 644 "${desktop_user}" "${desktop_group}" \
    "${desktop_uid}" "${desktop_gid}" || return 1
  fsync_path_and_parent "${plist}" || return 1
  remote_companion_desktop_identity_matches \
    "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
    "${desktop_group}" || return 1
  echo "${plist}"
}

print_remote_companion_gatekeeper_hints(){
  cat <<EOF_REMOTE_HINTS
RemoteMacAgent Gatekeeper 检查与逃生步骤：
- 检查：spctl --assess --verbose ${REMOTE_COMPANION_APP_PATH}
- 若提示无法验证开发者，请在已登录桌面用户的终端执行：
    open ${REMOTE_COMPANION_APP_PATH}
  然后打开 系统设置 -> 隐私与安全性 -> 仍要打开 RemoteMacAgent.app
- 远控还需要在 系统设置 -> 隐私与安全性 中授予 Screen Recording 和 Accessibility 权限。
EOF_REMOTE_HINTS
}

load_remote_companion_launchagent(){
  local desktop_uid="$1"
  local desktop_user="$2"
  local desktop_home="$3"
  local plist="$4"
  local desktop_gid="$5"
  local desktop_group="$6"
  local launchctl_output=""
  REMOTE_COMPANION_STATUS_RESET_OK="0"

  remote_companion_desktop_identity_matches \
    "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
    "${desktop_group}" || return 1
  if ! command_exists launchctl; then
    warn "系统缺少 launchctl，无法自动加载 RemoteMacAgent LaunchAgent"
    return 1
  fi

  launchctl bootout "gui/${desktop_uid}/${REMOTE_COMPANION_LABEL}" >/dev/null 2>&1 || true
  launchctl remove "${REMOTE_COMPANION_LABEL}" >/dev/null 2>&1 || true
  # Terminate a detached process from an older open(1)-based LaunchAgent before
  # bootstrapping the direct executable service.
  if pkill -TERM -u "${desktop_uid}" -f "RemoteMacAgent.app/Contents/MacOS/RemoteMacAgent" >/dev/null 2>&1; then
    sleep 1
    pkill -KILL -u "${desktop_uid}" -f "RemoteMacAgent.app/Contents/MacOS/RemoteMacAgent" >/dev/null 2>&1 || true
  fi
  if ! prepare_remote_companion_status_file "${REMOTE_COMPANION_STATUS}"; then
    warn "旧 RemoteMacAgent 状态清理失败，继续尝试启动并等待新状态"
  else
    REMOTE_COMPANION_STATUS_RESET_OK="1"
  fi

  launchctl enable "gui/${desktop_uid}/${REMOTE_COMPANION_LABEL}" >/dev/null 2>&1 || true
  if launchctl_output="$(launchctl bootstrap "gui/${desktop_uid}" "${plist}" 2>&1)"; then
    launchctl kickstart -k "gui/${desktop_uid}/${REMOTE_COMPANION_LABEL}" >/dev/null 2>&1 || true
    remote_companion_desktop_identity_matches \
      "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
      "${desktop_group}"
    return
  fi
  warn "launchctl bootstrap RemoteMacAgent 失败：${launchctl_output}"

  if [[ -x /usr/bin/sudo ]] \
    && launchctl_output="$(/usr/bin/sudo -u "#${desktop_uid}" -H launchctl load -w "${plist}" 2>&1)"; then
    remote_companion_desktop_identity_matches \
      "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
      "${desktop_group}"
    return
  fi
  warn "launchctl load -w RemoteMacAgent 失败：${launchctl_output}"

  if command_exists open && launchctl asuser "${desktop_uid}" \
    /usr/bin/open -g -a "${REMOTE_COMPANION_APP_PATH}" >/dev/null 2>&1; then
    warn "RemoteMacAgent 已在 Aqua 会话临时启动，但 LaunchAgent 未托管；安装仍判定失败"
    return 1
  fi

  local companion_program=""
  companion_program="$(remote_companion_app_executable "${REMOTE_COMPANION_APP_PATH}" || true)"
  if [[ -n "${companion_program}" ]]; then
    if [[ -x /usr/bin/sudo ]]; then
      /usr/bin/sudo -u "#${desktop_uid}" -H "${companion_program}" >/dev/null 2>&1 &
    else
      "${companion_program}" >/dev/null 2>&1 &
    fi
  fi
  return 1
}

remote_companion_health_check(){
  local desktop_uid="$1"
  local timeout_sec="${2:-30}"
  local stable_required="${REALM_REMOTE_COMPANION_HEALTH_STABLE_SAMPLES:-3}"
  local stable_samples=0
  local stable_pid=""
  local stable_instance=""
  local launchd_ready=0
  local runtime_ready=0
  local launchd_pid=""
  local status_pid=""
  local status_instance=""
  local expected_version=""
  local i=1
  if [[ ! "${timeout_sec}" =~ ^[0-9]+$ ]] || (( timeout_sec < 1 )); then
    timeout_sec=30
  fi
  if [[ ! "${stable_required}" =~ ^[0-9]+$ ]] \
    || (( 10#${stable_required} < 1 || 10#${stable_required} > 10 )); then
    stable_required=3
  else
    stable_required="$((10#${stable_required}))"
  fi
  expected_version="$(
    read_remote_companion_app_version \
      "${REMOTE_COMPANION_APP_PATH}" || true
  )"
  if [[ -z "${expected_version}" ]]; then
    warn "RemoteMacAgent 当前 app 缺少可信版本，拒绝运行确认"
    return 1
  fi
  info "状态文件路径：${REMOTE_COMPANION_STATUS}"
  if [[ "${REMOTE_COMPANION_STATUS_RESET_OK:-0}" != "1" ]]; then
    warn "RemoteMacAgent 状态基线未成功重置，拒绝使用可能过期的健康状态"
    return 1
  fi
  while (( i <= timeout_sec )); do
    launchd_ready=0
    runtime_ready=0
    launchd_pid="$(
      macos_launchd_job_pid \
        "gui/${desktop_uid}/${REMOTE_COMPANION_LABEL}" || true
    )"
    if [[ "${launchd_pid}" =~ ^[0-9]+$ ]] \
      && kill -0 "${launchd_pid}" >/dev/null 2>&1; then
      launchd_ready=1
    fi
    if [[ -f "${REMOTE_COMPANION_STATUS}" && ! -L "${REMOTE_COMPANION_STATUS}" ]] \
      && jq -e \
        --arg version "${expected_version}" \
        --arg status_path "${REMOTE_COMPANION_STATUS}" \
        'type == "object"
          and .installed == true
          and .running == true
          and .version == $version
          and .build_version == $version
          and (.pid | type == "number" and . > 0 and floor == .)
          and (.process_instance_id | type == "string" and length > 0)
          and .status_path == $status_path
          and .ws_state == "connected"
          and (.last_ws_connected_at | type == "string" and length > 0)' \
        "${REMOTE_COMPANION_STATUS}" >/dev/null 2>&1; then
      status_pid="$(
        jq -r '.pid | tostring' \
          "${REMOTE_COMPANION_STATUS}" 2>/dev/null || true
      )"
      status_instance="$(
        jq -r '.process_instance_id' \
          "${REMOTE_COMPANION_STATUS}" 2>/dev/null || true
      )"
      if [[ "${status_pid}" == "${launchd_pid}" ]] \
        && remote_companion_process_matches \
          "${desktop_uid}" "${status_pid}"; then
        if [[ "${stable_pid}" == "${status_pid}" \
          && "${stable_instance}" == "${status_instance}" ]]; then
          stable_samples=$((stable_samples + 1))
        else
          stable_pid="${status_pid}"
          stable_instance="${status_instance}"
          stable_samples=1
        fi
        if (( stable_samples >= stable_required )); then
          runtime_ready=1
        fi
      else
        stable_samples=0
        stable_pid=""
        stable_instance=""
      fi
    else
      stable_samples=0
      stable_pid=""
      stable_instance=""
    fi
    if [[ "${launchd_ready}" == "1" && "${runtime_ready}" == "1" ]]; then
      break
    fi
    sleep 1
    i=$((i + 1))
  done

  if [[ "${launchd_ready}" == "1" && "${runtime_ready}" == "1" ]]; then
    ok "RemoteMacAgent 运行正常，已生成状态并建立 WS 连接"
    return 0
  fi

  if [[ "${launchd_ready}" == "1" ]]; then
    warn "RemoteMacAgent LaunchAgent 已加载，但 ${timeout_sec} 秒内未生成有效运行状态"
  else
    warn "RemoteMacAgent ${timeout_sec} 秒内未确认 LaunchAgent 与运行状态"
  fi
  warn "排查：launchctl print gui/${desktop_uid}/${REMOTE_COMPANION_LABEL}"
  warn "日志：log show --predicate 'process == \"RemoteMacAgent\"' --last 10m"
  warn "状态：${REMOTE_COMPANION_STATUS}"
  warn "如果 Screen Recording 仍未出现，请先在桌面会话里运行：open ${REMOTE_COMPANION_APP_PATH}"
  warn "请检查 Screen Recording / Accessibility 权限以及 Gatekeeper 是否拦截"
  return 1
}

setup_remote_companion(){
  local extracted_root="${1:-}"
  local desktop_user="" desktop_home="" desktop_group=""
  local desktop_uid="" desktop_gid="" plist=""
  local app_owner_kind=""
  local current_owner_kind=""
  local selected_app_path=""
  if remote_control_preserve_enabled; then
    info "主 Agent 自更新保留现有 RemoteMacAgent companion 状态"
    return 0
  fi
  resolve_remote_companion_desktop_context || return 1
  desktop_user="${REMOTE_COMPANION_DESKTOP_USER}"
  desktop_uid="${REMOTE_COMPANION_DESKTOP_UID}"
  desktop_gid="${REMOTE_COMPANION_DESKTOP_GID}"
  desktop_group="${REMOTE_COMPANION_DESKTOP_GROUP}"
  desktop_home="${REMOTE_COMPANION_DESKTOP_HOME}"
  plist="${REMOTE_COMPANION_DESKTOP_PLIST}"
  if ! remote_control_enabled; then
    write_remote_companion_config \
      "false" "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
      "${desktop_group}" || return 1
    info "已按 --without-remote-control 跳过 RemoteMacAgent companion"
    return 0
  fi
  if ! preflight_remote_companion_panel_transport; then
    return 1
  fi

  write_remote_companion_config \
    "true" "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
    "${desktop_group}" || return 1

  selected_app_path="$(
    select_remote_companion_app_path "${desktop_home}" || true
  )"
  if [[ -z "${selected_app_path}" ]]; then
    err "无法确定可信的 RemoteMacAgent.app 安装路径"
    return 1
  fi
  if [[ "${selected_app_path}" != "${REMOTE_COMPANION_APP_PATH}" ]]; then
    info "沿用当前 RemoteMacAgent LaunchAgent app 路径：${selected_app_path}"
  fi
  REMOTE_COMPANION_APP_PATH="${selected_app_path}"
  if ! recover_remote_companion_transaction; then
    return 1
  fi

  # 优先从 panel 静态目录拉取最新 .app（自动更新）。失败时退回到 zip 内
  # 搜索 / 本地保留 / placeholder 三段式逻辑，保持对老安装包/离线场景兼容。
  local installed_via_download="0"
  if download_and_install_remote_companion_artifact; then
    installed_via_download="1"
  elif remote_companion_update_material_present; then
    err "RemoteMacAgent 下载安装失败且事务仍未收敛"
    if ! secure_and_rollback_remote_companion_update \
      "RemoteMacAgent 下载安装失败"; then
      err "RemoteMacAgent 下载安装失败后的安全回滚未完成"
    fi
    return 1
  fi

  if [[ "${installed_via_download}" == "0" ]]; then
    local artifact=""
    artifact="$(find_remote_companion_artifact "${extracted_root}" || true)"
    if [[ -n "${artifact}" ]]; then
      if install_remote_companion_artifact "${artifact}" "${extracted_root}"; then
        ok "RemoteMacAgent companion 已安装到 ${REMOTE_COMPANION_APP_PATH}"
      else
        if remote_companion_update_material_present; then
          err "RemoteMacAgent 本地 artifact 安装失败且事务仍未收敛"
          if ! secure_and_rollback_remote_companion_update \
            "RemoteMacAgent 本地 artifact 安装失败"; then
            err "RemoteMacAgent 本地 artifact 失败后的安全回滚未完成"
          fi
          return 1
        fi
        warn "RemoteMacAgent companion 安装失败，主 Agent 继续安装"
      fi
    elif [[ -d "${REMOTE_COMPANION_APP_PATH}" ]]; then
      info "未在安装包发现 RemoteMacAgent.app，保留已安装 companion"
    else
      warn "安装包未包含 RemoteMacAgent.app；已写入占位说明，主 Agent 继续安装"
      write_remote_companion_placeholder
      print_remote_companion_gatekeeper_hints
      log_remote_companion_key_event warning \
        "RemoteMacAgent 不可用，legacy API key 已收紧，等待后续 Keychain 迁移"
      secure_and_rollback_remote_companion_update \
        "安装包未包含 RemoteMacAgent.app" || return 1
      return 0
    fi
  fi

  if [[ ! -d "${REMOTE_COMPANION_APP_PATH}" ]]; then
    print_remote_companion_gatekeeper_hints
    secure_and_rollback_remote_companion_update \
      "RemoteMacAgent.app 安装结果缺失" || return 1
    return 0
  fi
  if ! remote_companion_artifact_architecture_matches "${REMOTE_COMPANION_APP_PATH}"; then
    local incompatible_path="${REMOTE_COMPANION_APP_PATH}.incompatible"
    rm -rf "${incompatible_path}"
    mv "${REMOTE_COMPANION_APP_PATH}" "${incompatible_path}" >/dev/null 2>&1 || true
    warn "RemoteMacAgent.app 与当前 CPU 架构不兼容，已停止加载 companion"
    write_remote_companion_placeholder
    print_remote_companion_gatekeeper_hints
    log_remote_companion_key_event error \
      "RemoteMacAgent 架构不兼容，legacy API key 已收紧且不会作为明文权威源"
    secure_and_rollback_remote_companion_update \
      "RemoteMacAgent 架构不兼容" || return 1
    return 0
  fi

  if ! normalize_remote_companion_bundle_permissions \
    "${REMOTE_COMPANION_APP_PATH}"; then
    if ! secure_and_rollback_remote_companion_update \
      "RemoteMacAgent bundle 权限修复失败"; then
      err "RemoteMacAgent bundle 权限失败后的安全回滚未完成"
    fi
    return 1
  fi
  app_owner_kind="$(
    remote_companion_app_owner_kind \
      "${REMOTE_COMPANION_APP_PATH}" "${desktop_home}" || true
  )"
  if [[ "${app_owner_kind}" != "root" && "${app_owner_kind}" != "user" ]]; then
    err "RemoteMacAgent.app 路径归属在安装期间变得不可信"
    if ! secure_and_rollback_remote_companion_update \
      "RemoteMacAgent.app 路径归属不可信"; then
      err "RemoteMacAgent 路径归属异常后的安全回滚未完成"
    fi
    return 1
  fi
  if [[ "${app_owner_kind}" == "user" ]]; then
    remote_companion_desktop_identity_matches \
      "${desktop_user}" "${desktop_uid}" "${desktop_gid}" \
      "${desktop_group}" || return 1
    chown -R "${desktop_uid}:${desktop_gid}" \
      "${REMOTE_COMPANION_APP_PATH}" || return 1
    verify_path_owner \
      "${REMOTE_COMPANION_APP_PATH}" "${desktop_user}" \
      "${desktop_uid}" "${desktop_gid}" || return 1
  else
    chown -R root:wheel "${REMOTE_COMPANION_APP_PATH}" || return 1
    verify_path_owner "${REMOTE_COMPANION_APP_PATH}" root 0 0 || return 1
  fi
  clear_quarantine_flag "${REMOTE_COMPANION_APP_PATH}"
  if command_exists xattr; then
    xattr -dr com.apple.quarantine "${REMOTE_COMPANION_APP_PATH}" >/dev/null 2>&1 || true
  fi
  sign_remote_companion_app "${REMOTE_COMPANION_APP_PATH}"
  if [[ "${REMOTE_COMPANION_UPDATE_PENDING:-0}" == "1" ]] \
    && ! verify_remote_companion_bundle_signature \
      "${REMOTE_COMPANION_APP_PATH}"; then
    warn "RemoteMacAgent 重签后严格校验失败，恢复 previous app"
    secure_and_rollback_remote_companion_update \
      "RemoteMacAgent 重签后严格校验失败" || return 1
    return 0
  fi
  if command_exists spctl; then
    spctl --assess --verbose "${REMOTE_COMPANION_APP_PATH}" >/dev/null 2>&1 || true
  fi
  print_remote_companion_gatekeeper_hints

  if [[ -z "${desktop_user}" || -z "${desktop_uid}" ]]; then
    warn "未检测到已登录 Aqua 桌面用户，跳过 RemoteMacAgent LaunchAgent 加载"
    # 没有桌面用户时回落到旧路径，避免 status_path 为空
    REMOTE_COMPANION_STATUS="$(compute_remote_companion_status_path "" "")"
    warn "无桌面用户上下文，状态文件将回落到旧路径：${REMOTE_COMPANION_STATUS}"
    log_remote_companion_key_event warning \
      "无桌面用户上下文，无法确认 Keychain 写入；legacy API key 已收紧"
    secure_and_rollback_remote_companion_update \
      "无已登录 Aqua 用户，无法确认 RemoteMacAgent 升级" || return 1
    warn "请先登录目标 macOS 桌面用户，再重新运行本安装器/升级流程"
    return 0
  fi
  if [[ -z "${desktop_home}" ]]; then
    warn "无法确定桌面用户 ${desktop_user} 的 HOME，跳过 RemoteMacAgent LaunchAgent"
    REMOTE_COMPANION_STATUS="$(compute_remote_companion_status_path "${desktop_user}" "")"
    warn "回落状态路径：${REMOTE_COMPANION_STATUS}"
    log_remote_companion_key_event warning \
      "无法确定桌面用户 HOME，无法确认 Keychain 写入；legacy API key 已收紧"
    secure_and_rollback_remote_companion_update \
      "无法确定桌面用户 HOME" || return 1
    return 0
  fi
  local companion_program=""
  companion_program="$(
    remote_companion_app_executable "${REMOTE_COMPANION_APP_PATH}" || true
  )"
  current_owner_kind="$(
    remote_companion_app_owner_kind \
      "${REMOTE_COMPANION_APP_PATH}" "${desktop_home}" || true
  )"
  if [[ "${current_owner_kind}" != "${app_owner_kind}" ]]; then
    err "RemoteMacAgent.app 路径归属在权限校验前发生变化"
    if ! secure_and_rollback_remote_companion_update \
      "RemoteMacAgent.app 路径归属发生变化"; then
      err "RemoteMacAgent 路径归属变化后的安全回滚未完成"
    fi
    return 1
  fi
  if [[ "${app_owner_kind}" == "user" ]]; then
    verify_path_owner \
      "${companion_program}" "${desktop_user}" \
      "${desktop_uid}" "${desktop_gid}" || return 1
  else
    verify_path_owner "${companion_program}" root 0 0 || return 1
  fi
  if ! verify_remote_companion_executable_for_user \
    "${desktop_user}" "${companion_program}" \
    "${desktop_uid}" "${desktop_gid}" "${desktop_group}"; then
    err "桌面用户无法执行 RemoteMacAgent：${companion_program:-missing}"
    if ! secure_and_rollback_remote_companion_update \
      "RemoteMacAgent 桌面用户执行权限校验失败"; then
      err "RemoteMacAgent 执行权限失败后的安全回滚未完成"
    fi
    return 1
  fi

  # 重算 REMOTE_COMPANION_STATUS：用桌面用户家目录下的 Application Support 路径
  REMOTE_COMPANION_STATUS="$(compute_remote_companion_status_path "${desktop_user}" "${desktop_home}")"
  info "RemoteMacAgent 状态文件路径：${REMOTE_COMPANION_STATUS}"

  # 当 write_env_files 与本函数解析的 desktop_user 不一致（极少见，但
  # 在 console session 切换时确实会发生）会让 agent.env 里的 STATUS_PATH
  # 和 plist 漂移；此处用最终值回写 agent.env，保持二者同步。
  if [[ -f /etc/realm-agent/agent.env ]]; then
    update_env_file_var /etc/realm-agent/agent.env REALM_REMOTE_COMPANION_STATUS_PATH "${REMOTE_COMPANION_STATUS}"
    update_env_file_var /etc/realm-agent/agent.env REALM_REMOTE_COMPANION_EXECUTABLE "${REMOTE_COMPANION_APP_PATH}/Contents/MacOS/RemoteMacAgent"
    update_env_file_var /etc/realm-agent/agent.env REALM_REMOTE_COMPANION_LAUNCHD_TARGET "gui/${desktop_uid}/${REMOTE_COMPANION_LABEL}"
  fi

  if ! plist="$(
    write_remote_companion_launchagent \
      "${desktop_user}" "${desktop_home}" "${desktop_group}" \
      "${desktop_uid}" "${desktop_gid}"
  )" || [[ -z "${plist}" ]]; then
    warn "RemoteMacAgent LaunchAgent plist 写入失败"
    log_remote_companion_key_event error \
      "RemoteMacAgent LaunchAgent 未写入，无法确认 Keychain 迁移；legacy API key 已收紧"
    if ! secure_and_rollback_remote_companion_update \
      "RemoteMacAgent LaunchAgent plist 写入失败"; then
      err "RemoteMacAgent LaunchAgent 写入失败后的安全回滚未完成"
    fi
    return 1
  fi
  if [[ "${plist}" != "${REMOTE_COMPANION_DESKTOP_PLIST}" ]]; then
    err "RemoteMacAgent LaunchAgent 路径与冻结桌面身份不一致"
    if ! secure_and_rollback_remote_companion_update \
      "RemoteMacAgent LaunchAgent 路径不一致"; then
      err "RemoteMacAgent LaunchAgent 路径异常后的安全回滚未完成"
    fi
    return 1
  fi

  if ! prepare_remote_companion_status_dir \
    "${desktop_user}" "${desktop_group}" "${REMOTE_COMPANION_STATUS}" \
    "${desktop_uid}" "${desktop_gid}"; then
    err "RemoteMacAgent 状态目录权限与冻结桌面身份不一致"
    secure_and_rollback_remote_companion_update \
      "RemoteMacAgent 状态目录准备失败" || return 1
    return 1
  fi
  retire_stale_remote_companion_status_files "${REMOTE_COMPANION_STATUS}" "${desktop_home}"
  if load_remote_companion_launchagent \
    "${desktop_uid}" "${desktop_user}" "${desktop_home}" "${plist}" \
    "${desktop_gid}" "${desktop_group}"; then
    ok "RemoteMacAgent LaunchAgent 已加载（${plist}）"
  else
    warn "RemoteMacAgent LaunchAgent 自动加载失败，已保留 plist：${plist}"
  fi
  if ! remote_companion_health_check "${desktop_uid}"; then
    err "RemoteMacAgent 运行探针失败"
    if ! secure_and_rollback_remote_companion_update \
      "RemoteMacAgent 运行探针失败"; then
      err "RemoteMacAgent 运行探针失败后的安全回滚未完成"
    fi
    return 1
  fi
  if ! finalize_remote_companion_legacy_key \
    "${desktop_uid}" "${desktop_user}" "${desktop_gid}" \
    "${desktop_group}"; then
    err "RemoteMacAgent Keychain 迁移失败，legacy 明文 key 已禁用"
    if ! secure_and_rollback_remote_companion_update \
      "RemoteMacAgent Keychain 迁移失败"; then
      err "RemoteMacAgent Keychain 失败后的安全回滚未完成"
    fi
    return 1
  fi
  if ! mark_remote_companion_verified; then
    err "RemoteMacAgent 运行确认无法持久绑定到主安装事务"
    if ! secure_and_rollback_remote_companion_update \
      "RemoteMacAgent 运行确认持久化失败"; then
      err "RemoteMacAgent 运行确认失败后的安全回滚未完成"
    fi
    return 1
  fi
  REMOTE_COMPANION_LOGS_RETIRE_ALLOWED="1"
}

verify_agent_runtime(){
  local host="$1"
  local port="$2"
  local transport="${3:-http}"
  local tls_ca_cert="${4:-}"
  local tls_server_name="${5:-}"

  local api_key
  api_key="$(cat /etc/realm-agent/api.key 2>/dev/null || true)"
  if [[ -z "${api_key}" ]]; then
    err "安装后检查失败：缺少 /etc/realm-agent/api.key"
    return 1
  fi

  local tmp_sys tmp_cert tmp_status tmp_report
  local header_file body_file key_file response_header_file
  tmp_sys="$(mktemp)" || { err "无法创建临时文件"; return 1; }
  tmp_cert="$(mktemp)" || { err "无法创建临时文件"; rm -f "${tmp_sys}" >/dev/null 2>&1 || true; return 1; }
  tmp_status="$(mktemp)" || { err "无法创建临时文件"; rm -f "${tmp_sys}" "${tmp_cert}" >/dev/null 2>&1 || true; return 1; }
  tmp_report="$(mktemp)" || { err "无法创建临时文件"; rm -f "${tmp_sys}" "${tmp_cert}" "${tmp_status}" >/dev/null 2>&1 || true; return 1; }
  register_cleanup_path "${tmp_sys}"
  register_cleanup_path "${tmp_cert}"
  register_cleanup_path "${tmp_status}"
  register_cleanup_path "${tmp_report}"
  header_file=""
  body_file=""
  key_file=""
  response_header_file=""

  cleanup_verify(){
    rm -f "${tmp_sys}" "${tmp_cert}" "${tmp_status}" "${tmp_report}" \
      "${header_file}" "${body_file}" "${key_file}" \
      "${response_header_file}" >/dev/null 2>&1 || true
  }

  local ready=0
  local ready_attempts="${REALM_AGENT_VERIFY_READY_ATTEMPTS:-90}"
  if [[ ! "${ready_attempts}" =~ ^[0-9]+$ ]] \
    || (( 10#${ready_attempts} < 30 || 10#${ready_attempts} > 300 )); then
    ready_attempts=90
  else
    ready_attempts="$((10#${ready_attempts}))"
  fi
  local i=1
  while (( i <= ready_attempts )); do
    if agent_api_get \
      "${host}" "${port}" "${api_key}" "/api/v1/sys" "${tmp_sys}" \
      "2" "5" "${transport}" "${tls_ca_cert}" "${tls_server_name}"; then
      ready=1
      break
    fi
    sleep 1
    i=$((i + 1))
  done
  if [[ "${ready}" != "1" ]]; then
    cleanup_verify
    err "安装后检查失败：Agent API 未就绪（/api/v1/sys）"
    return 1
  fi

  if ! jq -e '.ok == true and (.cpu | type == "object") and (.mem | type == "object") and (.net | type == "object")' "${tmp_sys}" >/dev/null 2>&1; then
    cat "${tmp_sys}" >&2 || true
    cleanup_verify
    err "安装后检查失败：节点监控数据异常（/api/v1/sys）"
    return 1
  fi

  if ! agent_api_get \
    "${host}" "${port}" "${api_key}" "/api/v1/intranet/cert" "${tmp_cert}" \
    "2" "5" "${transport}" "${tls_ca_cert}" "${tls_server_name}"; then
    cleanup_verify
    err "安装后检查失败：内网穿透证书接口不可用（/api/v1/intranet/cert）"
    return 1
  fi
  if ! jq -e '.ok == true and (.cert_pem | type == "string") and ((.cert_pem | length) > 0)' "${tmp_cert}" >/dev/null 2>&1; then
    cat "${tmp_cert}" >&2 || true
    cleanup_verify
    err "安装后检查失败：内网穿透 TLS 证书未就绪"
    return 1
  fi

  local intranet_status_ready=0
  local intranet_status_error=""
  local status_try=1
  while (( status_try <= 3 )); do
    if agent_api_get \
      "${host}" "${port}" "${api_key}" "/api/v1/intranet/status" "${tmp_status}" \
      "3" "8" "${transport}" "${tls_ca_cert}" "${tls_server_name}"; then
      if jq -e '.ok == true and (.status.summary | type == "object")' "${tmp_status}" >/dev/null 2>&1; then
        intranet_status_ready=1
        break
      fi
      intranet_status_error="内网穿透状态结构异常"
      cat "${tmp_status}" >&2 || true
    else
      intranet_status_error="内网穿透状态接口不可用（/api/v1/intranet/status）"
    fi
    sleep 1
    status_try=$((status_try + 1))
  done
  if [[ "${intranet_status_ready}" != "1" ]]; then
    cleanup_verify
    err "安装后检查失败：${intranet_status_error:-内网穿透状态检查失败}"
    return 1
  fi

  local panel_url="" panel_id="0" report_insecure="0"
  local allow_no_panel="${REALM_AGENT_ALLOW_NO_PANEL:-0}"
  if [[ -f /etc/realm-agent/panel.env ]]; then
    panel_url="$(grep -E '^REALM_PANEL_URL=' /etc/realm-agent/panel.env 2>/dev/null | tail -n1 | cut -d= -f2-)"
    panel_id="$(grep -E '^REALM_AGENT_ID=' /etc/realm-agent/panel.env 2>/dev/null | tail -n1 | cut -d= -f2-)"
    report_insecure="$(grep -E '^REALM_AGENT_REPORT_INSECURE_TLS=' /etc/realm-agent/panel.env 2>/dev/null | tail -n1 | cut -d= -f2-)"
  fi
  panel_url="$(echo "${panel_url:-}" | tr -d '\r' | sed 's/[[:space:]]*$//' | sed 's#/*$##')"
  panel_id="$(echo "${panel_id:-0}" | tr -d '\r' | sed 's/[[:space:]]*$//')"
  report_insecure="$(echo "${report_insecure:-0}" | tr -d '\r' | sed 's/[[:space:]]*$//' | tr '[:upper:]' '[:lower:]')"

  if [[ -z "${panel_url}" || ! "${panel_id}" =~ ^[0-9]+$ || "${panel_id}" -le 0 ]]; then
    if [[ "${allow_no_panel}" != "1" ]]; then
      cleanup_verify
      err "安装后检查失败：未绑定面板（REALM_PANEL_URL / REALM_AGENT_ID 缺失）"
      err "请使用面板 Join 命令安装，或在 /etc/realm-agent/panel.env 正确填写后重试"
      return 1
    fi
  else
    local payload now_s agent_sig
    now_s="$(date '+%Y-%m-%d %H:%M:%S')"
    payload="$(printf '{"node_id":%s,"ack_version":0,"agent_version":"bootstrap-check","report":{"ok":true,"time":"%s","info":{"ok":true}}}' "${panel_id}" "${now_s}")"
    header_file="$(mktemp "${TMPDIR:-/tmp}/realm-report-header.XXXXXX" 2>/dev/null)" || {
      cleanup_verify
      err "安装后检查失败：无法创建上报临时文件"
      return 1
    }
    body_file="$(mktemp "${TMPDIR:-/tmp}/realm-report-body.XXXXXX" 2>/dev/null)" || {
      cleanup_verify
      err "安装后检查失败：无法创建上报临时文件"
      return 1
    }
    key_file="$(mktemp "${TMPDIR:-/tmp}/realm-report-key.XXXXXX" 2>/dev/null)" || {
      cleanup_verify
      err "安装后检查失败：无法创建上报临时文件"
      return 1
    }
    response_header_file="$(mktemp "${TMPDIR:-/tmp}/realm-report-response-header.XXXXXX" 2>/dev/null)" || {
      cleanup_verify
      err "安装后检查失败：无法创建上报响应头临时文件"
      return 1
    }
    chmod 600 "${header_file}" "${body_file}" "${key_file}" \
      "${response_header_file}" >/dev/null 2>&1 || true
    printf '%s' "${api_key}" > "${key_file}" || {
      cleanup_verify
      err "安装后检查失败：无法写入上报签名密钥"
      return 1
    }
    printf '%s' "${payload}" > "${body_file}" || {
      cleanup_verify
      err "安装后检查失败：无法写入上报内容"
      return 1
    }
    if ! ensure_trusted_macos_agent_python; then
      cleanup_verify
      err "安装后检查失败：缺少 python3，无法计算上报签名"
      return 1
    fi
    if ! agent_sig="$(
      printf '%s' "${payload}" | run_trusted_macos_python -c 'import hashlib
import hmac
import sys

key_path = sys.argv[1]
payload_bytes = sys.stdin.buffer.read()
with open(key_path, "rb") as key_fh:
    key_bytes = key_fh.read()
print("sha256=" + hmac.new(key_bytes, payload_bytes, hashlib.sha256).hexdigest(), end="")' \
        "${key_file}"
    )"; then
      cleanup_verify
      err "安装后检查失败：上报签名计算失败"
      return 1
    fi
    printf 'x-api-key: %s\nX-Agent-Signature: %s\nContent-Type: application/json\n' \
      "${api_key}" "${agent_sig}" > "${header_file}" || {
      cleanup_verify
      err "安装后检查失败：无法写入上报头"
      return 1
    }
    local report_try=1
    local report_ok=0
    local status_code=""
    local retry_after=""
    local retry_delay=10
    while (( report_try <= 5 )); do
      : > "${response_header_file}"
      if [[ "${report_insecure}" == "1" || "${report_insecure}" == "true" || "${report_insecure}" == "yes" || "${report_insecure}" == "on" || "${report_insecure}" == "y" ]]; then
        status_code="$(curl -k -sS --max-redirs 0 --connect-timeout 3 --max-time 10 -D "${response_header_file}" -H "@${header_file}" --data "@${body_file}" "${panel_url}/api/agent/report" -o "${tmp_report}" -w '%{http_code}' || true)"
      else
        status_code="$(curl -sS --max-redirs 0 --connect-timeout 3 --max-time 10 -D "${response_header_file}" -H "@${header_file}" --data "@${body_file}" "${panel_url}/api/agent/report" -o "${tmp_report}" -w '%{http_code}' || true)"
      fi
      if [[ "${status_code}" == "200" ]] && jq -e '.ok == true' "${tmp_report}" >/dev/null 2>&1; then
        report_ok=1
        break
      fi
      if [[ "${status_code}" == "429" && "${report_try}" -lt 5 ]]; then
        retry_after="$(
          awk 'tolower($0) ~ /^retry-after:[[:space:]]*/ {
              gsub(/\r/, "", $0)
              sub(/^[^:]*:[[:space:]]*/, "", $0)
              sub(/[[:space:]]+$/, "", $0)
              value=$0
            }
            END { print value }' "${response_header_file}" 2>/dev/null || true
        )"
        retry_delay=10
        if [[ "${retry_after}" =~ ^[0-9]{1,2}$ ]] \
          && (( 10#${retry_after} >= 1 && 10#${retry_after} <= 30 )); then
          retry_delay="$((10#${retry_after}))"
        fi
        info "上报频率过高，请稍后：面板返回 HTTP 429，${retry_delay} 秒后重试（${report_try}/5）"
        sleep "${retry_delay}"
        report_try=$((report_try + 1))
        continue
      fi
      break
    done
    if [[ "${report_ok}" != "1" ]]; then
      cat "${tmp_report}" >&2 || true
      cleanup_verify
      err "安装后检查失败：无法上报面板（${panel_url}/api/agent/report）"
      if [[ "${report_insecure}" != "1" && "${report_insecure}" != "true" && "${report_insecure}" != "yes" && "${report_insecure}" != "on" && "${report_insecure}" != "y" ]]; then
        err "若面板为自签证书，请在 panel.env 设置 REALM_AGENT_REPORT_INSECURE_TLS=1"
      fi
      return 1
    fi
  fi

  cleanup_verify
  ok "安装后检查通过：节点监控、内网穿透、面板上报可用"
  return 0
}

compute_requirements_sha256(){
  local file="$1"
  [[ -f "${file}" ]] || return 1
  sha256_file "${file}"
}

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

repair_macos_venv_script_shebangs(){
  local venv_dir="${1:-}"
  local old_venv_dir="${2:-}"
  local new_venv_dir="${3:-${venv_dir}}"
  local repaired=""
  [[ -n "${venv_dir}" && -d "${venv_dir}/bin" \
    && -n "${old_venv_dir}" && -n "${new_venv_dir}" ]] || return 0
  repaired="$(run_trusted_macos_python -I -S -B - \
    "${venv_dir}" "${old_venv_dir}" "${new_venv_dir}" <<'PY'
import base64
import csv
import hashlib
import io
import os
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()


def fail(message):
    raise SystemExit(message)


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 metadata(path, directory=False):
    try:
        value = path.lstat()
    except OSError:
        fail(f"missing venv repair path: {path}")
    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 validate_directory_chain(path):
    candidate = lexical(path)
    if not within(candidate, root):
        fail(f"venv repair path escapes root: {candidate}")
    metadata(root, directory=True)
    current = root
    for part in candidate.relative_to(root).parts:
        current = current / part
        metadata(current, directory=True)
    return candidate


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)
    ):
        fail(f"invalid venv RECORD path: {name!r}")
    target = lexical(site_root.joinpath(*relative.parts))
    if not within(target, root):
        fail(f"venv RECORD path escapes root: {name!r}")
    return target


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 owner_uid == 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


validate_directory_chain(scripts)
record_states = {}
owners = {}
site_roots = []
seen_site_root_ids = set()
for site_root in sorted(
    {
        *root.glob("lib/python*/site-packages"),
        *root.glob("lib64/python*/site-packages"),
    }
):
    site_root = validate_directory_chain(site_root)
    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
    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")):
        validate_directory_chain(dist_info)
        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 venv RECORD: {record}")
        if not rows or any(len(row) != 3 for row in rows):
            fail(f"invalid venv RECORD: {record}")
        record_states[record] = [rows, raw, record_meta]
        for index, row in enumerate(rows):
            target = record_target(site_root, row[0])
            if 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()
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 exactly one RECORD owner: {script}")
    record, index = bindings[0]
    row = record_states[record][0][index]
    if (
        not row[1].startswith("sha256=")
        or not row[2].isdigit()
        or row[1] != record_hash(raw)
        or int(row[2]) != len(raw)
    ):
        fail(f"repaired script RECORD proof mismatch: {script}")
    updated = new_prefix + first[len(old_prefix) :] + separator + rest
    if updated == raw:
        continue
    row[1] = record_hash(updated)
    row[2] = str(len(updated))
    script_updates.append((script, updated, script_meta))
    changed_records.add(record)

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):
    rows, raw, record_meta = record_states[record]
    newline = "\r\n" if b"\r\n" in raw else "\n"
    output = io.StringIO(newline="")
    csv.writer(output, lineterminator=newline).writerows(rows)
    encoded = output.getvalue().encode("utf-8")
    sequence += 1
    atomic_write(record, encoded, record_meta, sequence)

print(len(script_updates))
PY
  )" || return 1
  if [[ "${repaired}" =~ ^[1-9][0-9]*$ ]]; then
    info "已修复 ${repaired} 个 venv 脚本 shebang 并重绑 RECORD"
  fi
}

snapshot_macos_rollback_file(){
  local path="$1"
  local name="$2"
  if [[ -L "${path}" ]]; then
    err "拒绝通过符号链接更新受管文件：${path}"
    return 1
  fi
  if [[ -e "${path}" ]]; then
    cp -a "${path}" "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/${name}"
  else
    : > "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/${name}.absent"
  fi
}

snapshot_macos_rollback_directory_metadata(){
  local path="${1:-}"
  local name="${2:-}"
  local metadata=""
  [[ -n "${path}" && -n "${name}" ]] || return 1
  if [[ -L "${path}" || ( -e "${path}" && ! -d "${path}" ) ]]; then
    err "macOS Agent 受管目录不是可信普通目录：${path}"
    return 1
  fi
  if [[ -d "${path}" ]]; then
    metadata="$(stat -f '%u:%g:%Lp' "${path}" 2>/dev/null)" || return 1
    printf '%s\n' "${metadata}" \
      > "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/${name}.metadata" || return 1
    : > "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/${name}.present"
  else
    : > "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/${name}.absent"
  fi
}

restore_macos_rollback_file(){
  local path="$1"
  local name="$2"
  local saved="${REALM_MAC_DEPLOY_ROLLBACK_DIR}/${name}"
  local absent="${saved}.absent"
  local parent tmp
  parent="$(dirname "${path}")"
  if [[ -L "${parent}" || ( -e "${parent}" && ! -d "${parent}" ) ]]; then
    err "macOS Agent 回滚目标父目录不可信：${parent}"
    return 1
  fi
  if [[ -d "${path}" && ! -L "${path}" ]]; then
    err "拒绝把目录当作回滚文件覆盖：${path}"
    return 1
  fi
  if [[ -f "${saved}" && ! -L "${saved}" ]]; then
    mkdir -p "${parent}" || return 1
    tmp="$(mktemp "${parent}/.$(basename "${path}").restore.XXXXXX")" \
      || return 1
    register_cleanup_path "${tmp}"
    cp -a "${saved}" "${tmp}" || return 1
    mv -f "${tmp}" "${path}" || return 1
    fsync_path_and_parent "${path}" || return 1
  elif [[ -e "${saved}" || -L "${saved}" ]]; then
    err "macOS Agent 回滚快照不是可信普通文件：${name}"
    return 1
  elif [[ -f "${absent}" && ! -L "${absent}" ]]; then
    if [[ ! -e "${path}" && ! -L "${path}" \
      && ! -e "${parent}" && ! -L "${parent}" ]]; then
      return 0
    fi
    remove_macos_rollback_file "${path}" || return 1
  else
    err "macOS Agent 回滚快照缺失：${name}"
    return 1
  fi
}

restore_macos_rollback_directory_metadata(){
  local path="${1:-}"
  local name="${2:-}"
  local metadata=""
  local uid=""
  local gid=""
  local mode=""
  if [[ -f "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/${name}.present" ]]; then
    metadata="$(cat "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/${name}.metadata")" \
      || return 1
    IFS=: read -r uid gid mode <<< "${metadata}"
    [[ -d "${path}" && ! -L "${path}" ]] || return 1
    chmod "${mode}" "${path}" || return 1
    chown "${uid}:${gid}" "${path}" || return 1
    fsync_directory_and_parent "${path}" || return 1
  elif [[ -f "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/${name}.absent" \
    && -d "${path}" ]]; then
    rmdir "${path}" 2>/dev/null || {
      err "回滚后新建 macOS Agent 目录仍含残留：${path}"
      return 1
    }
    fsync_directory_and_parent "$(dirname "${path}")" || return 1
  fi
}

macos_launchd_state_file(){
  local transaction_root="${1:-}"
  local label="${2:-}"
  local state_name="${3:-}"
  printf '%s/launchd/%s.%s\n' \
    "${transaction_root}" "${label}" "${state_name}"
}

macos_launchd_disabled_state_from_output(){
  local label="${1:-}"
  local output="${2:-}"
  local state=""
  state="$(
    printf '%s\n' "${output}" | awk -v needle="\"${label}\"" '
      index($0, needle) {
        if ($0 ~ /=>[[:space:]]*(disabled|true)([[:space:]]|$)/) {
          print "1"
          found = 1
          exit
        }
        if ($0 ~ /=>[[:space:]]*(enabled|false)([[:space:]]|$)/) {
          print "0"
          found = 1
          exit
        }
      }
      END {
        if (!found) {
          print "0"
        }
      }
    '
  )"
  [[ "${state}" == "0" || "${state}" == "1" ]] || return 1
  printf '%s\n' "${state}"
}

macos_launchd_label_disabled_state(){
  local label="${1:-}"
  local output=""
  output="$(launchctl print-disabled system 2>&1)" || {
    err "无法读取 launchd disabled 状态：${label}"
    return 1
  }
  if ! macos_launchd_disabled_state_from_output "${label}" "${output}"; then
    err "launchd disabled 状态无法解析：${label}"
    return 1
  fi
}

snapshot_macos_launchd_states(){
  local transaction_root="${1:-}"
  local disabled_output=""
  local label=""
  local loaded="0"
  local disabled="0"
  [[ -n "${transaction_root}" && -d "${transaction_root}" \
    && ! -L "${transaction_root}" ]] || return 1
  install -d -m 700 "${transaction_root}/launchd" || return 1
  disabled_output="$(launchctl print-disabled system 2>&1)" || {
    err "无法快照 launchd disabled 状态"
    return 1
  }
  for label in "${AGENT_LABEL}" "${MPTCP_SIDECAR_LABEL}" "${REVTUNNEL_LABEL}"; do
    loaded="0"
    if launchctl print "system/${label}" >/dev/null 2>&1; then
      loaded="1"
    fi
    disabled="$(
      macos_launchd_disabled_state_from_output "${label}" "${disabled_output}" \
        || true
    )"
    if [[ "${disabled}" != "0" && "${disabled}" != "1" ]]; then
      err "无法解析 launchd disabled 快照：${label}"
      return 1
    fi
    persist_transaction_value \
      "$(macos_launchd_state_file "${transaction_root}" "${label}" loaded)" \
      "${loaded}" || return 1
    persist_transaction_value \
      "$(macos_launchd_state_file "${transaction_root}" "${label}" disabled)" \
      "${disabled}" || return 1
    if [[ "${label}" == "${AGENT_LABEL}" && "${loaded}" == "1" ]]; then
      : > "${transaction_root}/agent-was-loaded" || return 1
    fi
  done
}

macos_launchd_label_paths(){
  local label="${1:-}"
  case "${label}" in
    "${AGENT_LABEL}")
      printf '%s\t%s\n' \
        "/Library/LaunchDaemons/${AGENT_LABEL}.plist" \
        "${MACOS_STARTUP_WRAPPER}"
      ;;
    "${MPTCP_SIDECAR_LABEL}")
      printf '%s\t%s\n' \
        "/Library/LaunchDaemons/${MPTCP_SIDECAR_LABEL}.plist" \
        "${BASE_DIR}/mptcp_sidecar.sh"
      ;;
    "${REVTUNNEL_LABEL}")
      printf '%s\t%s\n' \
        "/Library/LaunchDaemons/${REVTUNNEL_LABEL}.plist" \
        "${BASE_DIR}/revtunnel.sh"
      ;;
    *)
      return 1
      ;;
  esac
}

macos_launchd_program_from_plist(){
  local plist="${1:-}"
  local program=""
  [[ -f "${plist}" && ! -L "${plist}" ]] || {
    err "无法读取受信任的 launchd plist 启动程序：${plist}"
    return 1
  }
  if command_exists plutil; then
    program="$(
      plutil -extract ProgramArguments.0 raw -o - "${plist}" 2>/dev/null \
        || true
    )"
  fi
  if [[ -z "${program}" && -x /usr/libexec/PlistBuddy ]]; then
    program="$(
      /usr/libexec/PlistBuddy \
        -c "Print :ProgramArguments:0" "${plist}" 2>/dev/null || true
    )"
  fi
  program="${program%$'\r'}"
  if [[ "${program}" != /* \
        || "${program}" == *$'\n'* \
        || "${program}" == *$'\r'* ]]; then
    err "launchd plist 缺少可信绝对启动程序：${plist}"
    return 1
  fi
  printf '%s\n' "${program}"
}

macos_launchd_restore_program_path(){
  local label="${1:-}"
  local plist="${2:-}"
  local program=""
  program="$(macos_launchd_program_from_plist "${plist}")" || return 1
  case "${label}:${program}" in
    "${AGENT_LABEL}:${BASE_DIR}/start.sh" \
      |"${AGENT_LABEL}:${MACOS_STARTUP_WRAPPER}" \
      |"${MPTCP_SIDECAR_LABEL}:${BASE_DIR}/mptcp_sidecar.sh" \
      |"${REVTUNNEL_LABEL}:${BASE_DIR}/revtunnel.sh")
      printf '%s\n' "${program}"
      ;;
    *)
      err "拒绝恢复未受管的 launchd 启动程序（${label}）：${program}"
      return 1
      ;;
  esac
}

bootout_macos_launchd_label(){
  local label="${1:-}"
  local output=""
  if output="$(launchctl bootout "system/${label}" 2>&1)"; then
    return 0
  fi
  if ! launchctl print "system/${label}" >/dev/null 2>&1; then
    return 0
  fi
  err "launchd bootout 失败（${label}）：${output}"
  return 1
}

bootout_macos_launchd_stack(){
  local label=""
  local failed="0"
  for label in "${AGENT_LABEL}" "${MPTCP_SIDECAR_LABEL}" "${REVTUNNEL_LABEL}"; do
    if ! bootout_macos_launchd_label "${label}"; then
      failed="1"
    fi
  done
  [[ "${failed}" == "0" ]]
}

restore_macos_launchd_label_state(){
  local transaction_root="${1:-}"
  local label="${2:-}"
  local paths=""
  local plist=""
  local program=""
  local loaded=""
  local disabled=""
  local output=""
  local actual_disabled=""
  paths="$(macos_launchd_label_paths "${label}")" || return 1
  IFS=$'\t' read -r plist program <<< "${paths}"
  loaded="$(
    read_transaction_value \
      "$(macos_launchd_state_file "${transaction_root}" "${label}" loaded)" \
      || true
  )"
  disabled="$(
    read_transaction_value \
      "$(macos_launchd_state_file "${transaction_root}" "${label}" disabled)" \
      || true
  )"
  [[ "${loaded}" == "0" || "${loaded}" == "1" ]] || {
    err "launchd loaded 快照缺失或无效：${label}"
    return 1
  }
  [[ "${disabled}" == "0" || "${disabled}" == "1" ]] || {
    err "launchd disabled 快照缺失或无效：${label}"
    return 1
  }

  if [[ "${loaded}" == "1" ]]; then
    program="$(macos_launchd_restore_program_path "${label}" "${plist}")" \
      || return 1
    if ! bootstrap_launchdaemon "${label}" "${plist}" "${program}"; then
      err "恢复 launchd 服务失败：${label}"
      return 1
    fi
    if ! launchctl print "system/${label}" >/dev/null 2>&1; then
      err "恢复后 launchd 服务未 loaded：${label}"
      return 1
    fi
    if ! verify_macos_launchd_label_runtime "${label}"; then
      err "恢复后 launchd 服务仅 loaded 但未通过运行健康校验：${label}"
      return 1
    fi
  fi

  if [[ "${disabled}" == "1" ]]; then
    launchctl disable "system/${label}" >/dev/null 2>&1 || {
      err "无法恢复 launchd disabled 状态（${label}）"
      return 1
    }
  else
    launchctl enable "system/${label}" >/dev/null 2>&1 || {
      err "无法恢复 launchd enabled 状态（${label}）"
      return 1
    }
  fi
  actual_disabled="$(macos_launchd_label_disabled_state "${label}" || true)"
  if [[ "${actual_disabled}" != "${disabled}" ]]; then
    err "launchd disabled 状态恢复后不一致（${label}）"
    return 1
  fi
  if [[ "${loaded}" == "0" ]] \
    && launchctl print "system/${label}" >/dev/null 2>&1; then
    err "launchd loaded 状态恢复后不一致（${label}）"
    return 1
  fi
}

restore_macos_launchd_states(){
  local transaction_root="${1:-}"
  local label=""
  local failed="0"
  for label in "${AGENT_LABEL}" "${MPTCP_SIDECAR_LABEL}" "${REVTUNNEL_LABEL}"; do
    if ! restore_macos_launchd_label_state "${transaction_root}" "${label}"; then
      failed="1"
    fi
  done
  [[ "${failed}" == "0" ]]
}

macos_agent_transaction_stage_path(){
  local stage=""
  stage="$(
    read_transaction_value "${REALM_MAC_TRANSACTION_DIR}/stage-path" || true
  )"
  case "${stage}" in
    "${BASE_DIR}/.staging."*)
      printf '%s\n' "${stage}"
      ;;
    *)
      return 1
      ;;
  esac
}

begin_macos_agent_rollback(){
  local transaction_tmp=""
  local transaction_id=""
  REALM_MAC_TRANSACTION_DIR="${BASE_DIR}/.install-transaction"
  REALM_MAC_DEPLOY_ROLLBACK_DIR="${REALM_MAC_TRANSACTION_DIR}/rollback"
  install -d -m 755 "${BASE_DIR}" || return 1
  if [[ -L "${REALM_MAC_TRANSACTION_DIR}" \
        || -e "${REALM_MAC_TRANSACTION_DIR}" ]]; then
    err "macOS Agent 事务目录已存在，拒绝开始新的切换"
    return 1
  fi
  if [[ -e "${REALM_MAC_PREV_AGENT}" \
        || -L "${REALM_MAC_PREV_AGENT}" \
        || -e "${REALM_MAC_PREV_SHARED}" \
        || -L "${REALM_MAC_PREV_SHARED}" \
        || -e "${REALM_MAC_PREV_VENV}" \
        || -L "${REALM_MAC_PREV_VENV}" ]]; then
    err "macOS Agent previous 目录尚未恢复，拒绝开始新的切换"
    return 1
  fi

  transaction_tmp="$(
    mktemp -d "${BASE_DIR}/.install-transaction.new.XXXXXX"
  )" || return 1
  chmod 700 "${transaction_tmp}" || return 1
  register_cleanup_path "${transaction_tmp}"
  REALM_MAC_DEPLOY_ROLLBACK_DIR="${transaction_tmp}/rollback"
  install -d -m 700 "${REALM_MAC_DEPLOY_ROLLBACK_DIR}" || return 1
  transaction_id="$(new_macos_transaction_id || true)"
  if [[ ! "${transaction_id}" =~ ^[0-9a-f]{64}$ ]]; then
    err "无法生成 macOS Agent 安装事务 ID"
    return 1
  fi
  persist_transaction_value \
    "${transaction_tmp}/transaction-id" "${transaction_id}" || return 1

  snapshot_macos_launchd_states "${transaction_tmp}" || return 1
  REALM_MAC_AGENT_WAS_LOADED="$(
    read_transaction_value \
      "$(macos_launchd_state_file \
        "${transaction_tmp}" "${AGENT_LABEL}" loaded)" || true
  )"
  [[ "${REALM_MAC_AGENT_WAS_LOADED}" == "1" ]] \
    || REALM_MAC_AGENT_WAS_LOADED="0"
  if [[ -d "${BASE_DIR}/agent" ]]; then
    : > "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/agent.present" || return 1
  fi
  if [[ -d "${BASE_DIR}/shared" ]]; then
    : > "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/shared.present" || return 1
  fi
  if [[ -d "${BASE_DIR}/venv" ]]; then
    : > "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/venv.present" || return 1
  fi
  snapshot_macos_rollback_file \
    /etc/realm-agent/api.key api.key || return 1
  snapshot_macos_rollback_file \
    /etc/realm-agent/agent.env agent.env || return 1
  snapshot_macos_rollback_file \
    /etc/realm-agent/panel.env panel.env || return 1
  snapshot_macos_rollback_file \
    /etc/realm-agent/requirements.sha256 requirements.sha256 || return 1
  snapshot_macos_rollback_file \
    /etc/realm-agent/remote-companion.json remote-companion.json \
    || return 1
  snapshot_macos_rollback_file \
    "${SSHD_LOOPBACK_PENALTY_CONFIG}" sshd-loopback.conf || return 1
  snapshot_macos_rollback_file \
    /etc/realm/pool_to_run.jq pool_to_run.jq || return 1
  snapshot_macos_rollback_file \
    "${BASE_DIR}/start.sh" start.sh || return 1
  snapshot_macos_rollback_file \
    "${BASE_DIR}/mptcp_sidecar.sh" mptcp_sidecar.sh || return 1
  snapshot_macos_rollback_file \
    "${BASE_DIR}/revtunnel.sh" revtunnel.sh || return 1
  snapshot_macos_rollback_directory_metadata \
    /private/etc/realm-agent/tunnel revtunnel-tunnel-dir || return 1
  snapshot_macos_rollback_file \
    /private/etc/realm-agent/revtunnel.env revtunnel.env || return 1
  snapshot_macos_rollback_file \
    /private/etc/realm-agent/tunnel/id_ed25519 revtunnel-key || return 1
  snapshot_macos_rollback_file \
    /private/etc/realm-agent/tunnel/known_hosts revtunnel-known-hosts \
    || return 1
  snapshot_macos_rollback_directory_metadata \
    /etc/realm-agent/certs tls-certs-dir || return 1
  snapshot_macos_rollback_file \
    /etc/realm-agent/certs/server.crt tls-cert || return 1
  snapshot_macos_rollback_file \
    /etc/realm-agent/certs/server.key tls-key || return 1
  snapshot_macos_rollback_file \
    "/Library/LaunchDaemons/${AGENT_LABEL}.plist" agent.plist || return 1
  snapshot_macos_rollback_file \
    "/Library/LaunchDaemons/${MPTCP_SIDECAR_LABEL}.plist" mptcp.plist \
    || return 1
  snapshot_macos_rollback_file \
    "/Library/LaunchDaemons/${REVTUNNEL_LABEL}.plist" revtunnel.plist \
    || return 1
  persist_transaction_value \
    "${transaction_tmp}/stage-path" "${REALM_MAC_STAGE_DIR}" || return 1
  persist_transaction_value \
    "${transaction_tmp}/state" "prepared" || return 1
  if ! atomic_publish_directory \
    "${transaction_tmp}" "${REALM_MAC_TRANSACTION_DIR}"; then
    err "无法持久化 macOS Agent 安装事务"
    return 1
  fi
  REALM_MAC_DEPLOY_ROLLBACK_DIR="${REALM_MAC_TRANSACTION_DIR}/rollback"
  REALM_MAC_DEPLOY_ROLLBACK_ACTIVE="1"
}

remove_macos_rollback_file(){
  local path="${1:-}"
  local parent=""
  parent="$(dirname "${path}")"
  if [[ -d "${path}" && ! -L "${path}" ]]; then
    err "拒绝把目录当作回滚文件删除：${path}"
    return 1
  fi
  rm -f -- "${path}" || {
    err "无法删除回滚目标文件：${path}"
    return 1
  }
  if [[ -e "${path}" || -L "${path}" ]]; then
    err "回滚目标文件删除后仍存在：${path}"
    return 1
  fi
  fsync_directory_and_parent "${parent}"
}

remove_macos_rollback_directory(){
  local path="${1:-}"
  local parent=""
  parent="$(dirname "${path}")"
  if [[ -L "${path}" ]]; then
    err "拒绝递归删除符号链接目录：${path}"
    return 1
  fi
  rm -rf -- "${path}" || {
    err "无法删除回滚目标目录：${path}"
    return 1
  }
  if [[ -e "${path}" || -L "${path}" ]]; then
    err "回滚目标目录删除后仍存在：${path}"
    return 1
  fi
  fsync_directory_and_parent "${parent}"
}

restore_macos_switched_directory(){
  local current="$1"
  local previous="$2"
  local original_marker="$3"
  local failed="${previous}.failed-new"
  if [[ -L "${previous}" ]]; then
    err "previous 路径是符号链接，拒绝恢复：${previous}"
    return 1
  fi

  if [[ -f "${original_marker}" ]]; then
    if [[ -d "${previous}" ]]; then
      remove_macos_rollback_directory "${failed}" || return 1
      if [[ -e "${current}" || -L "${current}" ]]; then
        if ! mv "${current}" "${failed}"; then
          err "无法隔离失败的新目录：${current}"
          return 1
        fi
      fi
      if ! mv "${previous}" "${current}"; then
        if [[ -e "${failed}" || -L "${failed}" ]]; then
          mv "${failed}" "${current}" >/dev/null 2>&1 || true
        fi
        err "旧目录恢复失败，已保留回滚副本：${previous}"
        return 1
      fi
      remove_macos_rollback_directory "${failed}" || return 1
      fsync_tree_and_parent "${current}" || return 1
      return 0
    fi
    if [[ -d "${current}" && ! -L "${current}" ]]; then
      remove_macos_rollback_directory "${failed}" || return 1
      fsync_tree_and_parent "${current}" || return 1
      return 0
    fi
    err "事务记录原目录存在，但 current/previous 均不可恢复：${current}"
    return 1
  fi

  remove_macos_rollback_directory "${current}" || return 1
  remove_macos_rollback_directory "${previous}" || return 1
  remove_macos_rollback_directory "${failed}"
}

restore_macos_switched_directories(){
  local restore_failed="0"
  if ! restore_macos_switched_directory \
    "${BASE_DIR}/venv" "${REALM_MAC_PREV_VENV}" \
    "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/venv.present"; then
    restore_failed="1"
  fi
  if ! restore_macos_switched_directory \
    "${BASE_DIR}/shared" "${REALM_MAC_PREV_SHARED}" \
    "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/shared.present"; then
    restore_failed="1"
  fi
  if ! restore_macos_switched_directory \
    "${BASE_DIR}/agent" "${REALM_MAC_PREV_AGENT}" \
    "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/agent.present"; then
    restore_failed="1"
  fi
  [[ "${restore_failed}" == "0" ]]
}

activate_macos_agent_stage(){
  local state=""
  [[ -d "${REALM_MAC_STAGE_DIR}/agent" \
      && -d "${REALM_MAC_STAGE_DIR}/shared" ]] || {
    err "Agent staging 不完整，拒绝切换"
    return 1
  }
  state="$(read_transaction_value "${REALM_MAC_TRANSACTION_DIR}/state" || true)"
  if [[ "${state}" != "main-quiesced" ]]; then
    err "macOS Agent 未在目录切换前持久进入静止状态"
    return 1
  fi
  if [[ -e "${REALM_MAC_PREV_AGENT}" \
        || -L "${REALM_MAC_PREV_AGENT}" \
        || -e "${REALM_MAC_PREV_SHARED}" \
        || -L "${REALM_MAC_PREV_SHARED}" \
        || -e "${REALM_MAC_PREV_VENV}" \
        || -L "${REALM_MAC_PREV_VENV}" ]]; then
    err "检测到未恢复的 macOS Agent previous 目录"
    return 1
  fi

  if [[ -d "${BASE_DIR}/agent" ]]; then
    mv "${BASE_DIR}/agent" "${REALM_MAC_PREV_AGENT}" || return 1
  fi
  if ! mv "${REALM_MAC_STAGE_DIR}/agent" "${BASE_DIR}/agent"; then
    restore_macos_switched_directories
    return 1
  fi
  if ! fsync_tree_and_parent "${BASE_DIR}/agent"; then
    restore_macos_switched_directories
    return 1
  fi
  if ! persist_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" "agent-active"; then
    restore_macos_switched_directories
    return 1
  fi

  if [[ -d "${BASE_DIR}/shared" ]]; then
    if ! mv "${BASE_DIR}/shared" "${REALM_MAC_PREV_SHARED}"; then
      restore_macos_switched_directories
      return 1
    fi
  fi
  if ! mv "${REALM_MAC_STAGE_DIR}/shared" "${BASE_DIR}/shared"; then
    restore_macos_switched_directories
    return 1
  fi
  if ! fsync_tree_and_parent "${BASE_DIR}/shared"; then
    restore_macos_switched_directories
    return 1
  fi
  if ! persist_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" "shared-active"; then
    restore_macos_switched_directories
    return 1
  fi

  if [[ "${REALM_MAC_DEPLOY_REPLACE_VENV}" == "1" ]]; then
    [[ -x "${REALM_MAC_STAGE_DIR}/venv/bin/python" ]] || {
      restore_macos_switched_directories
      return 1
    }
    if [[ -d "${BASE_DIR}/venv" ]]; then
      if ! mv "${BASE_DIR}/venv" "${REALM_MAC_PREV_VENV}"; then
        restore_macos_switched_directories
        return 1
      fi
    fi
    if ! mv "${REALM_MAC_STAGE_DIR}/venv" "${BASE_DIR}/venv"; then
      restore_macos_switched_directories
      return 1
    fi
    if ! repair_macos_venv_script_shebangs \
      "${BASE_DIR}/venv" "${REALM_MAC_STAGE_DIR}/venv" \
      "${BASE_DIR}/venv"; then
      restore_macos_switched_directories
      return 1
    fi
    if ! fsync_tree_and_parent "${BASE_DIR}/venv" \
      || ! persist_transaction_value \
        "${REALM_MAC_TRANSACTION_DIR}/state" "venv-active"; then
      restore_macos_switched_directories
      return 1
    fi
  fi
  if ! persist_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" "new-active"; then
    restore_macos_switched_directories
    return 1
  fi
}

finalize_macos_agent_update(){
  local stage=""
  local cleanup_failed="0"
  local path=""
  if [[ -d "${REALM_MAC_TRANSACTION_DIR}" ]] \
    && ! macos_joint_companion_cleanup_complete; then
    err "RemoteMacAgent 联合事务尚未清理，拒绝删除主 Agent 回滚证据"
    return 1
  fi
  stage="$(macos_agent_transaction_stage_path || true)"
  REALM_MAC_DEPLOY_ROLLBACK_ACTIVE="0"
  for path in \
    "${REALM_MAC_PREV_AGENT}" \
    "${REALM_MAC_PREV_SHARED}" \
    "${REALM_MAC_PREV_VENV}"; do
    [[ -e "${path}" || -L "${path}" ]] || continue
    remove_macos_rollback_directory "${path}" || cleanup_failed="1"
  done
  if [[ -n "${stage}" ]]; then
    remove_macos_rollback_directory "${stage}" || cleanup_failed="1"
  fi
  if [[ "${cleanup_failed}" != "0" ]]; then
    err "无法清理 macOS Agent previous/staging，已保留事务材料：${REALM_MAC_TRANSACTION_DIR}"
    return 1
  fi
  if [[ -e "${REALM_MAC_TRANSACTION_DIR}" \
    || -L "${REALM_MAC_TRANSACTION_DIR}" ]]; then
    if ! remove_macos_rollback_directory "${REALM_MAC_TRANSACTION_DIR}"; then
      err "无法清理 macOS Agent 事务目录：${REALM_MAC_TRANSACTION_DIR}"
      return 1
    fi
  fi
  REALM_MAC_DEPLOY_ROLLBACK_DIR=""
  REALM_MAC_STAGE_DIR=""
  return 0
}

fsync_macos_runtime_path(){
  local path="${1:-}"
  if [[ -f "${path}" && ! -L "${path}" ]]; then
    fsync_path_and_parent "${path}"
    return
  fi
  if [[ -d "${path}" && ! -L "${path}" ]]; then
    fsync_tree_and_parent "${path}"
    return
  fi
  if [[ ! -e "${path}" && ! -L "${path}" ]]; then
    return 0
  fi
  err "macOS Agent 运行路径不可持久化：${path}"
  return 1
}

sync_macos_agent_runtime_state(){
  local path=""
  local failed="0"
  for path in \
    "${BASE_DIR}/agent" \
    "${BASE_DIR}/shared" \
    "${BASE_DIR}/venv" \
    "${BASE_DIR}/start.sh" \
    /etc/realm-agent \
    /etc/realm/pool_to_run.jq \
    "/Library/LaunchDaemons/${AGENT_LABEL}.plist"; do
    fsync_macos_runtime_path "${path}" || failed="1"
  done
  [[ "${failed}" == "0" ]]
}

restore_macos_agent_runtime_files(){
  local failed="0"
  restore_macos_switched_directories || failed="1"
  restore_macos_rollback_file /etc/realm-agent/api.key api.key \
    || failed="1"
  restore_macos_rollback_file /etc/realm-agent/agent.env agent.env \
    || failed="1"
  restore_macos_rollback_file /etc/realm-agent/panel.env panel.env \
    || failed="1"
  restore_macos_rollback_file \
    /etc/realm-agent/requirements.sha256 requirements.sha256 \
    || failed="1"
  restore_macos_rollback_file \
    /etc/realm-agent/remote-companion.json remote-companion.json \
    || failed="1"
  restore_macos_rollback_file /etc/realm/pool_to_run.jq pool_to_run.jq \
    || failed="1"
  restore_macos_rollback_file "${BASE_DIR}/start.sh" start.sh \
    || failed="1"
  restore_macos_rollback_file \
    /etc/realm-agent/certs/server.crt tls-cert || failed="1"
  restore_macos_rollback_file \
    /etc/realm-agent/certs/server.key tls-key || failed="1"
  restore_macos_rollback_directory_metadata \
    /etc/realm-agent/certs tls-certs-dir || failed="1"
  restore_macos_rollback_file \
    "/Library/LaunchDaemons/${AGENT_LABEL}.plist" agent.plist \
    || failed="1"
  [[ "${failed}" == "0" ]]
}

restore_macos_sshd_runtime_file(){
  if [[ -e "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/sshd-loopback.conf" \
        || -f "${REALM_MAC_DEPLOY_ROLLBACK_DIR}/sshd-loopback.conf.absent" ]]; then
    restore_macos_rollback_file \
      "${SSHD_LOOPBACK_PENALTY_CONFIG}" sshd-loopback.conf || return 1
  fi
  if [[ -x /usr/sbin/sshd && -f /etc/ssh/sshd_config ]] \
    && ! /usr/sbin/sshd -t -f /etc/ssh/sshd_config >/dev/null 2>&1; then
    err "回滚后的 sshd 配置校验失败"
    return 1
  fi
}

restore_macos_mptcp_runtime_files(){
  local failed="0"
  restore_macos_rollback_file \
    "${BASE_DIR}/mptcp_sidecar.sh" mptcp_sidecar.sh || failed="1"
  restore_macos_rollback_file \
    "/Library/LaunchDaemons/${MPTCP_SIDECAR_LABEL}.plist" mptcp.plist \
    || failed="1"
  [[ "${failed}" == "0" ]]
}

restore_macos_revtunnel_runtime_files(){
  local failed="0"
  restore_macos_rollback_file \
    "${BASE_DIR}/revtunnel.sh" revtunnel.sh || failed="1"
  restore_macos_rollback_file \
    "/Library/LaunchDaemons/${REVTUNNEL_LABEL}.plist" revtunnel.plist \
    || failed="1"
  restore_macos_rollback_file \
    /private/etc/realm-agent/revtunnel.env revtunnel.env || failed="1"
  restore_macos_rollback_file \
    /private/etc/realm-agent/tunnel/id_ed25519 revtunnel-key || failed="1"
  restore_macos_rollback_file \
    /private/etc/realm-agent/tunnel/known_hosts revtunnel-known-hosts \
    || failed="1"
  restore_macos_rollback_directory_metadata \
    /private/etc/realm-agent/tunnel revtunnel-tunnel-dir || failed="1"
  [[ "${failed}" == "0" ]]
}

macos_restored_agent_is_healthy(){
  local loaded=""
  local restored_port=""
  loaded="$(
    read_transaction_value \
      "$(macos_launchd_state_file \
        "${REALM_MAC_TRANSACTION_DIR}" "${AGENT_LABEL}" loaded)" || true
  )"
  if [[ "${loaded}" == "0" ]]; then
    ! launchctl print "system/${AGENT_LABEL}" >/dev/null 2>&1
    return
  fi
  [[ "${loaded}" == "1" ]] || return 1
  launchctl print "system/${AGENT_LABEL}" >/dev/null 2>&1 || return 1
  restored_port="$(read_env_value /etc/realm-agent/agent.env \
    REALM_AGENT_PORT || true)"
  restored_port="$(normalize_port "${restored_port:-${DEFAULT_PORT}}")"
  wait_for_macos_agent_process_and_listener "${restored_port}"
}

retry_macos_auxiliary_rollback(){
  local failed="0"
  rollback_macos_continuity_package_from_transaction || failed="1"
  restore_macos_sshd_runtime_file || failed="1"
  if restore_macos_mptcp_runtime_files; then
    restore_macos_launchd_label_state \
      "${REALM_MAC_TRANSACTION_DIR}" "${MPTCP_SIDECAR_LABEL}" || failed="1"
  else
    failed="1"
  fi
  if restore_macos_revtunnel_runtime_files; then
    restore_macos_launchd_label_state \
      "${REALM_MAC_TRANSACTION_DIR}" "${REVTUNNEL_LABEL}" || failed="1"
  else
    failed="1"
  fi
  restrict_remote_companion_legacy_key || failed="1"
  [[ "${failed}" == "0" ]]
}

finish_macos_agent_rollback(){
  local preserve_materials="${1:-1}"
  if ! retry_macos_auxiliary_rollback; then
    err "辅助组件回滚未完成；主 Agent 保持在线并保留恢复材料：${REALM_MAC_TRANSACTION_DIR}"
    return 1
  fi
  if [[ "${preserve_materials}" == "1" ]]; then
    persist_transaction_value \
      "${REALM_MAC_TRANSACTION_DIR}/state" "rolled-back" || return 1
    REALM_MAC_DEPLOY_ROLLBACK_ACTIVE="0"
    warn "macOS Agent 已回滚；恢复材料保留至下一次安装启动：${REALM_MAC_TRANSACTION_DIR}"
    return 0
  fi
  finalize_macos_agent_update
}

restore_macos_agent_rollback(){
  [[ "${REALM_MAC_DEPLOY_ROLLBACK_ACTIVE:-0}" == "1" ]] || return 0
  local preserve_materials="${1:-1}"
  local retain_terminal="${2:-0}"
  local state=""
  state="$(read_transaction_value "${REALM_MAC_TRANSACTION_DIR}/state" || true)"
  if [[ "${state}" == "commit-prepared" ]]; then
    if [[ "${retain_terminal}" == "1" ]]; then
      return 0
    fi
    err "主 Agent 已持久化联合提交决策，必须由联合恢复流程处理"
    return 1
  fi
  if [[ "${state}" == "committed" || "${state}" == "rolled-back" ]]; then
    if [[ "${retain_terminal}" == "1" ]]; then
      REALM_MAC_DEPLOY_ROLLBACK_ACTIVE="0"
      return 0
    fi
    finalize_macos_agent_update
    return
  fi
  if [[ "${state}" == "main-restored" ]] \
    && macos_restored_agent_is_healthy; then
    finish_macos_agent_rollback "${preserve_materials}"
    return
  fi
  err "安装/升级未完成，正在恢复上一个可用 macOS Agent..."
  if ! persist_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" "recovering-main"; then
    err "无法持久化主 Agent 恢复中状态：${REALM_MAC_TRANSACTION_DIR}"
    return 1
  fi
  if ! bootout_macos_launchd_stack; then
    err "无法完整 bootout macOS Agent launchd 服务，已保留恢复材料：${REALM_MAC_TRANSACTION_DIR}"
    return 1
  fi
  if ! restore_macos_agent_runtime_files \
    || ! sync_macos_agent_runtime_state; then
    err "主 macOS Agent 回滚未完成，已保留恢复材料：${REALM_MAC_TRANSACTION_DIR}"
    return 1
  fi
  if ! persist_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" "main-start-allowed"; then
    err "无法持久化主 Agent 启动许可：${REALM_MAC_TRANSACTION_DIR}"
    return 1
  fi
  if ! restore_macos_launchd_label_state \
    "${REALM_MAC_TRANSACTION_DIR}" "${AGENT_LABEL}"; then
    err "主 macOS Agent launchd 恢复未完成，已保留恢复材料：${REALM_MAC_TRANSACTION_DIR}"
    return 1
  fi
  if ! persist_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" "main-restored"; then
    err "无法持久化主 Agent 已恢复状态：${REALM_MAC_TRANSACTION_DIR}"
    return 1
  fi
  finish_macos_agent_rollback "${preserve_materials}"
}

recover_orphan_macos_previous_directory(){
  local current="$1"
  local previous="$2"
  local failed="${previous}.failed-new"
  [[ -e "${previous}" || -L "${previous}" ]] || return 0
  if [[ -L "${previous}" || ! -d "${previous}" ]]; then
    err "previous 路径无效，拒绝自动恢复：${previous}"
    return 1
  fi
  remove_macos_rollback_directory "${failed}" || return 1
  if [[ -e "${current}" || -L "${current}" ]]; then
    mv "${current}" "${failed}" || return 1
  fi
  if mv "${previous}" "${current}"; then
    remove_macos_rollback_directory "${failed}" || return 1
    return 0
  fi
  if [[ -e "${failed}" || -L "${failed}" ]]; then
    mv "${failed}" "${current}" >/dev/null 2>&1 || true
  fi
  return 1
}

recover_macos_agent_transaction(){
  local orphan=""
  local preserve_materials="${1:-0}"
  local state=""
  REALM_MAC_TRANSACTION_DIR="${BASE_DIR}/.install-transaction"
  REALM_MAC_DEPLOY_ROLLBACK_DIR="${REALM_MAC_TRANSACTION_DIR}/rollback"
  for orphan in "${BASE_DIR}/.install-transaction.new."*; do
    [[ -e "${orphan}" || -L "${orphan}" ]] || continue
    remove_macos_rollback_directory "${orphan}" || return 1
  done
  if [[ -L "${REALM_MAC_TRANSACTION_DIR}" ]]; then
    err "macOS Agent 事务路径是符号链接，拒绝继续安装"
    return 1
  fi
  if [[ -e "${REALM_MAC_TRANSACTION_DIR}" \
    && ! -d "${REALM_MAC_TRANSACTION_DIR}" ]]; then
    err "macOS Agent 事务路径不是可信目录，拒绝继续安装"
    return 1
  fi
  if [[ -d "${REALM_MAC_TRANSACTION_DIR}" ]]; then
    if [[ ! -d "${REALM_MAC_DEPLOY_ROLLBACK_DIR}" \
          || -L "${REALM_MAC_DEPLOY_ROLLBACK_DIR}" ]]; then
      err "macOS Agent 事务缺少可信回滚快照"
      return 1
    fi
    state="$(read_transaction_value "${REALM_MAC_TRANSACTION_DIR}/state" || true)"
    case "${state}" in
      prepared|main-quiescing|main-quiesced|agent-active|shared-active|venv-active|new-active|commit-prepared|recovering-main|main-start-allowed|main-restored|committed|rolled-back)
        ;;
      *)
        err "macOS Agent 事务状态无效：${state:-missing}"
        return 1
        ;;
    esac
    REALM_MAC_STAGE_DIR="$(macos_agent_transaction_stage_path || true)"
    REALM_MAC_AGENT_WAS_LOADED="0"
    if [[ "$(read_transaction_value \
      "$(macos_launchd_state_file \
        "${REALM_MAC_TRANSACTION_DIR}" "${AGENT_LABEL}" loaded)" \
        || true)" == "1" \
      || -f "${REALM_MAC_TRANSACTION_DIR}/agent-was-loaded" ]]; then
      REALM_MAC_AGENT_WAS_LOADED="1"
    fi
    REALM_MAC_DEPLOY_ROLLBACK_ACTIVE="1"
    if [[ "${state}" == "commit-prepared" \
      || "${state}" == "committed" \
      || "${state}" == "rolled-back" ]]; then
      warn "检测到已批准但未清理的 macOS Agent 提交，继续完成提交"
    else
      warn "检测到中断的 macOS Agent 安装事务，启动前执行回滚"
    fi
    restore_macos_agent_rollback "${preserve_materials}" "1"
    return
  fi

  recover_orphan_macos_previous_directory \
    "${BASE_DIR}/venv" "${REALM_MAC_PREV_VENV}" || return 1
  recover_orphan_macos_previous_directory \
    "${BASE_DIR}/shared" "${REALM_MAC_PREV_SHARED}" || return 1
  recover_orphan_macos_previous_directory \
    "${BASE_DIR}/agent" "${REALM_MAC_PREV_AGENT}" || return 1
  for orphan in "${BASE_DIR}/.staging."*; do
    [[ -e "${orphan}" || -L "${orphan}" ]] || continue
    remove_macos_rollback_directory "${orphan}" || return 1
  done
}

commit_macos_agent_rollback(){
  if [[ -d "${REALM_MAC_TRANSACTION_DIR}" ]]; then
    persist_transaction_value \
      "${REALM_MAC_TRANSACTION_DIR}/state" "committed" || return 1
  fi
  finalize_macos_agent_update
}

indexed_remote_companion_app_path(){
  local index_dir="${REALM_MAC_TRANSACTION_DIR}/remote-companion-index"
  local app_index="${index_dir}/app-path"
  local home_index="${index_dir}/home"
  local current_main_path=""
  local expected_main_path=""
  local indexed_app_path=""
  local indexed_home=""
  local canonical_app_path=""
  if [[ ! -e "${index_dir}" && ! -L "${index_dir}" ]]; then
    return 2
  fi
  if [[ ! -d "${index_dir}" || -L "${index_dir}" \
    || ! -f "${app_index}" || -L "${app_index}" \
    || ! -f "${home_index}" || -L "${home_index}" ]]; then
    err "RemoteMacAgent 主事务路径索引不可信"
    return 1
  fi
  current_main_path="$(
    canonical_macos_transaction_path \
      "${REALM_MAC_TRANSACTION_DIR}" "${BASE_DIR}" "strict" || true
  )"
  expected_main_path="$(
    canonical_macos_transaction_path \
      "${BASE_DIR}/.install-transaction" "${BASE_DIR}" "strict" || true
  )"
  if [[ -z "${current_main_path}" \
    || "${current_main_path}" != "${expected_main_path}" ]]; then
    err "RemoteMacAgent 主事务路径索引不属于当前安装事务"
    return 1
  fi
  indexed_app_path="$(read_transaction_value "${app_index}" || true)"
  indexed_home="$(read_transaction_value "${home_index}" || true)"
  canonical_app_path="$(
    canonical_remote_companion_app_path \
      "${indexed_app_path}" "${indexed_home}" || true
  )"
  if [[ -z "${canonical_app_path}" \
    || "${canonical_app_path}" != "${indexed_app_path}" ]]; then
    err "RemoteMacAgent 主事务中的 companion 路径索引无效"
    return 1
  fi
  printf '%s\n' "${canonical_app_path}"
}

macos_joint_companion_cleanup_complete(){
  local indexed_app_path=""
  local indexed_status="0"
  if indexed_app_path="$(indexed_remote_companion_app_path)"; then
    REMOTE_COMPANION_APP_PATH="${indexed_app_path}"
    set_remote_companion_transaction_paths
    [[ ! -e "${REMOTE_COMPANION_TRANSACTION_DIR}" \
      && ! -L "${REMOTE_COMPANION_TRANSACTION_DIR}" ]]
  else
    indexed_status=$?
    [[ "${indexed_status}" == "2" ]]
  fi
}

complete_macos_joint_commit(){
  local indexed_app_path=""
  local indexed_status="0"
  local main_state=""
  local remote_transaction_present="0"
  macos_joint_commit_recovery_context_valid || return 1
  main_state="$(read_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/state" || true)"
  REALM_MAC_STAGE_DIR="$(macos_agent_transaction_stage_path)" || return 1
  REALM_MAC_DEPLOY_ROLLBACK_ACTIVE="1"
  if indexed_app_path="$(indexed_remote_companion_app_path)"; then
    REMOTE_COMPANION_APP_PATH="${indexed_app_path}"
    set_remote_companion_transaction_paths
    if [[ -d "${REMOTE_COMPANION_TRANSACTION_DIR}" \
      && ! -L "${REMOTE_COMPANION_TRANSACTION_DIR}" ]]; then
      remote_transaction_present="1"
      REMOTE_COMPANION_UPDATE_PENDING="1"
      remote_companion_verification_matches || return 1
      mark_remote_companion_commit || return 1
    elif [[ -e "${REMOTE_COMPANION_TRANSACTION_DIR}" \
      || -L "${REMOTE_COMPANION_TRANSACTION_DIR}" \
      || "${main_state}" != "committed" ]]; then
      err "RemoteMacAgent 联合提交事务缺失或不可信"
      return 1
    fi
  else
    indexed_status=$?
    [[ "${indexed_status}" == "2" ]] || return 1
  fi
  if [[ "${main_state}" != "committed" ]]; then
    persist_transaction_value \
      "${REALM_MAC_TRANSACTION_DIR}/state" "committed" || return 1
  fi
  if [[ "${remote_transaction_present}" == "1" ]]; then
    remote_companion_commit_approved || return 1
    finalize_remote_companion_update || return 1
  fi
  finalize_macos_agent_update
}

recover_legacy_remote_companion_transactions(){
  local default_app_path="${1:-}"
  local preferred_app_path="${2:-}"
  local launchagent=""
  local candidate_home=""
  local candidate_app_path=""
  for launchagent in \
    /Users/*/Library/LaunchAgents/"${REMOTE_COMPANION_LABEL}.plist"; do
    [[ -f "${launchagent}" ]] || continue
    candidate_home="$(
      dirname "$(dirname "$(dirname "${launchagent}")")"
    )"
    candidate_app_path="$(
      existing_remote_companion_launchagent_app_path \
        "${candidate_home}" || true
    )"
    candidate_app_path="$(
      canonical_remote_companion_app_path \
        "${candidate_app_path}" "${candidate_home}" || true
    )"
    if [[ -z "${candidate_app_path}" ]]; then
      continue
    fi
    if [[ "${candidate_app_path}" == "${default_app_path}" \
          || "${candidate_app_path}" == "${preferred_app_path}" ]]; then
      continue
    fi
    REMOTE_COMPANION_APP_PATH="${candidate_app_path}"
    recover_remote_companion_transaction || return 1
  done
}

recover_known_remote_companion_transactions(){
  local default_app_path=""
  local desktop_user=""
  local desktop_home=""
  local indexed_app_path=""
  local indexed_status="0"
  local preferred_app_path=""
  local selected_app_path=""
  if indexed_app_path="$(indexed_remote_companion_app_path)"; then
    preferred_app_path="${indexed_app_path}"
    REMOTE_COMPANION_APP_PATH="${indexed_app_path}"
    recover_remote_companion_transaction || return 1
  else
    indexed_status=$?
    [[ "${indexed_status}" == "2" ]] || return 1
    default_app_path="$(
      canonical_remote_companion_app_path \
        "${BASE_DIR}/RemoteMacAgent.app" "" || true
    )"
    [[ -n "${default_app_path}" ]] || return 1
    preferred_app_path="${default_app_path}"
    REMOTE_COMPANION_APP_PATH="${default_app_path}"
    recover_remote_companion_transaction || return 1
    desktop_user="$(console_user || true)"
    if [[ -n "${desktop_user}" ]]; then
      desktop_home="$(console_home "${desktop_user}" || true)"
    fi
    if [[ -n "${desktop_home}" ]]; then
      selected_app_path="$(
        select_remote_companion_app_path "${desktop_home}" || true
      )"
      if [[ -n "${selected_app_path}" \
            && "${selected_app_path}" != "${REMOTE_COMPANION_APP_PATH}" ]]; then
        REMOTE_COMPANION_APP_PATH="${selected_app_path}"
        recover_remote_companion_transaction || return 1
        preferred_app_path="${selected_app_path}"
      fi
    fi
    recover_legacy_remote_companion_transactions \
      "${default_app_path}" "${preferred_app_path}" || return 1
  fi
  REMOTE_COMPANION_APP_PATH="${preferred_app_path}"
  set_remote_companion_transaction_paths
}

recover_interrupted_macos_install(){
  local state=""
  recover_macos_agent_transaction "1" || return 1
  if [[ -d "${REALM_MAC_TRANSACTION_DIR}" \
    && ! -L "${REALM_MAC_TRANSACTION_DIR}" ]]; then
    state="$(
      read_transaction_value "${REALM_MAC_TRANSACTION_DIR}/state" || true
    )"
    if [[ "${state}" == "commit-prepared" \
      || "${state}" == "committed" ]]; then
      complete_macos_joint_commit
      return
    fi
  fi
  recover_known_remote_companion_transactions || return 1
  if [[ -d "${REALM_MAC_TRANSACTION_DIR}" \
    && ! -L "${REALM_MAC_TRANSACTION_DIR}" ]]; then
    state="$(
      read_transaction_value "${REALM_MAC_TRANSACTION_DIR}/state" || true
    )"
    case "${state}" in
      committed|rolled-back)
        finalize_macos_agent_update || return 1
        ;;
      *)
        err "联合恢复后主 Agent 事务未进入可清理状态：${state:-missing}"
        return 1
        ;;
    esac
  fi
}

commit_macos_install_transaction(){
  prepare_remote_companion_commit || return 1
  if [[ -d "${REALM_MAC_TRANSACTION_DIR}" ]]; then
    persist_transaction_value \
      "${REALM_MAC_TRANSACTION_DIR}/state" "commit-prepared" || return 1
  fi
  if ! mark_remote_companion_commit; then
    err "RemoteMacAgent 提交标记写入失败，保留主事务授权证据"
    return 1
  fi
  if [[ -d "${REALM_MAC_TRANSACTION_DIR}" ]]; then
    persist_transaction_value \
      "${REALM_MAC_TRANSACTION_DIR}/state" "committed" || return 1
  fi
  finalize_remote_companion_update || return 1
  finalize_macos_agent_update
}

sync_macos_shared_stage(){
  local src_shared_dir="$1"
  local BASE_DIR="$2"
  rsync -a --checksum --delete "${src_shared_dir%/}/" "$BASE_DIR/shared/"
}

# —— 以下为 Linux 端 run_with_timeout / pip 镜像回退 / venv 严格证明的 macOS 移植 ——

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

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

  (
    set -m
    "$@" &
    local cmd_pid=$!
    local waited=0
    local rc=0
    while /bin/kill -0 "${cmd_pid}" >/dev/null 2>&1; do
      if (( waited >= timeout_seconds )); then
        err "${label} 超时（${timeout_seconds}s）"
        /bin/kill -TERM -- "-${cmd_pid}" >/dev/null 2>&1 \
          || /bin/kill -TERM "${cmd_pid}" >/dev/null 2>&1 \
          || true
        /bin/sleep 2
        /bin/kill -KILL -- "-${cmd_pid}" >/dev/null 2>&1 \
          || /bin/kill -KILL "${cmd_pid}" >/dev/null 2>&1 \
          || true
        wait "${cmd_pid}" >/dev/null 2>&1 || true
        exit 124
      fi
      /bin/sleep 1
      waited=$((waited + 1))
    done
    if wait "${cmd_pid}"; then
      rc=0
    else
      rc=$?
    fi
    exit "${rc}"
  )
}

create_isolated_macos_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)
  [[ -x "${python_bin}" && -n "${target}" ]] || return 1
  if [[ "${use_copies}" == "1" ]]; then
    venv_args+=(--copies)
  fi
  run_with_timeout "${timeout_seconds}" "创建隔离虚拟环境（staging）" \
    /usr/bin/env -i \
      PATH=/usr/bin:/bin:/usr/sbin:/sbin \
      HOME=/var/root \
      PYTHONDONTWRITEBYTECODE=1 \
      PYTHONNOUSERSITE=1 \
      SETUPTOOLS_USE_DISTUTILS=stdlib \
      "${python_bin}" "${venv_args[@]}" "${target}"
}

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(){
  run_trusted_macos_python - "${1:-}" <<'PY'
import re
import sys

value = sys.argv[1]
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_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
  local -a fallback_indexes=()
  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//,/ }"
    read -r -a fallback_indexes <<< "${fallback_raw}" || true
    if (( ${#fallback_indexes[@]} > 0 )); then
      for idx in "${fallback_indexes[@]}"; 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
  fi
  return 1
}

run_macos_venv_pip(){
  local pip_bin="$1"
  local python_bin=""
  local venv_root=""
  local runtime_root=""
  local pip_home=""
  local pip_tmp=""
  local safe_index_url="${MAC_PIP_SAFE_INDEX_URL:-}"
  local safe_extra_index_url="${MAC_PIP_SAFE_EXTRA_INDEX_URL:-}"
  local safe_use_deprecated="${MAC_PIP_SAFE_USE_DEPRECATED:-}"
  local -a clean_env=()
  shift
  [[ -x "${pip_bin}" ]] || return 1
  python_bin="${pip_bin%/*}/python"
  [[ -x "${python_bin}" ]] || return 1
  venv_root="${pip_bin%/bin/pip}"
  runtime_root="${REALM_MAC_STAGE_DIR:-${venv_root}}/.pip-runtime"
  pip_home="${runtime_root}/home"
  pip_tmp="${runtime_root}/tmp"
  if [[ -L "${runtime_root}" \
        || ( -e "${runtime_root}" && ! -d "${runtime_root}" ) ]]; then
    return 1
  fi
  /usr/bin/install -d -m 700 "${pip_home}" "${pip_tmp}" || return 1
  clean_env=(
    PATH=/usr/bin:/bin:/usr/sbin:/sbin
    "HOME=${pip_home}"
    "TMPDIR=${pip_tmp}"
    PIP_CONFIG_FILE=/dev/null
    PIP_DISABLE_PIP_VERSION_CHECK=1
    PIP_NO_INPUT=1
    SETUPTOOLS_USE_DISTUTILS=stdlib
    PYTHONDONTWRITEBYTECODE=1
    PYTHONNOUSERSITE=1
  )
  if [[ -n "${safe_index_url}" ]]; then
    clean_env+=("PIP_INDEX_URL=${safe_index_url}")
  fi
  if [[ -n "${safe_extra_index_url}" ]]; then
    clean_env+=("PIP_EXTRA_INDEX_URL=${safe_extra_index_url}")
  fi
  if [[ -n "${safe_use_deprecated}" ]]; then
    clean_env+=("PIP_USE_DEPRECATED=${safe_use_deprecated}")
  fi
  exec /usr/bin/env -i "${clean_env[@]}" \
    "${python_bin}" -I -B -m pip "$@"
}

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}" \
    run_macos_venv_pip "${pip_bin}" install --no-input --no-index \
    --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 ]]
}

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:-/private/tmp}/realm-agent-wheels.XXXXXX" 2>/dev/null || true)"
  [[ -n "${tmp}" && -d "${tmp}" ]] || return 1
  register_cleanup_path "${tmp}"
  if ( run_macos_venv_pip "${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_macos_agent_requirements_file "${agent_dir}" || true)"
  [[ -n "${req_file}" ]] || return 1
  wheelhouse_satisfies_requirements "${existing_pip}" "${req_file}" "${wheel_dir}"
}

pip_supports_legacy_resolver(){
  local pip_bin="${1:-}"
  [[ -n "${pip_bin}" && -x "${pip_bin}" ]] || return 1
  run_macos_venv_pip "${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_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
  local MAC_PIP_SAFE_INDEX_URL="${index_url}"
  local MAC_PIP_SAFE_EXTRA_INDEX_URL="${extra_index_url}"
  local MAC_PIP_SAFE_USE_DEPRECATED=""
  (
    if [[ -n "${index_url}" ]]; then
      export PIP_INDEX_URL="${index_url}"
    else
      unset PIP_INDEX_URL >/dev/null 2>&1 || true
    fi
    if [[ -n "${extra_index_url}" ]]; then
      export PIP_EXTRA_INDEX_URL="${extra_index_url}"
    else
      unset PIP_EXTRA_INDEX_URL >/dev/null 2>&1 || true
    fi
    if [[ "${resolver_mode}" == "legacy" ]]; then
      MAC_PIP_SAFE_USE_DEPRECATED=legacy-resolver
      export PIP_USE_DEPRECATED=legacy-resolver
    else
      unset PIP_USE_DEPRECATED >/dev/null 2>&1 || true
    fi
    run_with_timeout "${timeout_seconds}" "${label}" \
      run_macos_venv_pip "${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 --prefer-binary --timeout 60 --retries 2
  )

  local host
  local -a trusted_hosts=()
  trusted_host_raw="${trusted_host_raw//,/ }"
  read -r -a trusted_hosts <<< "${trusted_host_raw}" || true
  if (( ${#trusted_hosts[@]} > 0 )); then
    for host in "${trusted_hosts[@]}"; do
      [[ -n "${host}" ]] || continue
      pip_args+=(--trusted-host "${host}")
    done
  fi

  local -a candidates=()
  local -a fallback_indexes=()
  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//,/ }"
    read -r -a fallback_indexes <<< "${fallback_raw}" || true
    if (( ${#fallback_indexes[@]} > 0 )); then
      for idx in "${fallback_indexes[@]}"; do
        [[ -n "${idx}" ]] || continue
        if [[ "${seen}" == *"|${idx}|"* ]]; then
          continue
        fi
        candidates+=("${idx}")
        seen="${seen}${idx}|"
      done
    fi
  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
}

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="$(bounded_uint_or_default "${REALM_AGENT_VENV_VERIFY_TIMEOUT:-240}" 240 30 1800)"
  output="$(mktemp "${TMPDIR:-/private/tmp}/realm-agent-venv-preflight.XXXXXX")" \
    || return 1
  register_cleanup_path "${output}"
  if ! run_with_timeout \
    "${timeout_seconds}" "隔离预检 Agent venv 启动边界" \
    env -i \
      PATH=/usr/bin:/bin:/usr/sbin:/sbin \
      HOME="${HOME:-/var/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
}

bootstrap_macos_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 引导输入不完整"
    return 1
  fi
  if ! run_with_timeout \
    "${timeout_seconds}" "无字节码引导 Agent venv pip" \
    env -i \
      PATH=/usr/bin:/bin:/usr/sbin:/sbin \
      HOME="${HOME:-/var/root}" \
      PYTHONDONTWRITEBYTECODE=1 \
      PYTHONNOUSERSITE=1 \
      SETUPTOOLS_USE_DISTUTILS=stdlib \
      "${py}" -I -S -B "${bootstrap}"; then
    err "Agent venv pip 无字节码引导失败"
    return 1
  fi
}

agent_venv_attestation_reason(){
  local path="$1"
  run_trusted_macos_python -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
}

verify_agent_venv_attestation_file(){
  local path="$1"
  local expected_kind="${2:-either}"
  run_trusted_macos_python -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
}

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_macos_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="$(bounded_uint_or_default "${REALM_AGENT_VENV_VERIFY_TIMEOUT:-240}" 240 30 1800)"
  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/bin:/bin:/usr/sbin:/sbin \
      HOME="${HOME:-/var/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
  mv -f "${temp_output}" "${output}"
}

build_macos_agent_stage(){
  local agent_dir="$1"
  local bootstrap_python=""
  local src_shared_dir=""
  local req_file=""
  local req_sha=""
  local old_req_sha=""
  local stage_python=""
  local stage_python_version=""
  local venv_timeout=""
  local pip_timeout=""
  local wheelhouse_dir=""
  local has_local_wheels="0"
  local venv_attestation_stage=""
  local req_installed="0"
  local -a req_hash_args=()

  unset PYTHONPYCACHEPREFIX PYTHONPATH PYTHONHOME PYTHONSTARTUP
  bootstrap_python="$(trusted_macos_agent_python || true)"
  if [[ -z "${bootstrap_python}" ]]; then
    err "缺少 root-owned 且权限可信的 Python 3.9+，拒绝创建 Agent venv"
    return 1
  fi
  venv_timeout="$(bounded_uint_or_default "${REALM_AGENT_VENV_CREATE_TIMEOUT:-240}" 240 30 3600)"
  pip_timeout="$(bounded_uint_or_default "${REALM_AGENT_PIP_INSTALL_TIMEOUT:-900}" 900 60 3600)"

  install -d -m 755 "${BASE_DIR}"
  REALM_MAC_STAGE_DIR="$(mktemp -d "${BASE_DIR}/.staging.XXXXXX")"
  chmod 700 "${REALM_MAC_STAGE_DIR}" >/dev/null 2>&1 || true
  register_cleanup_path "${REALM_MAC_STAGE_DIR}"
  rsync -a --checksum --delete "${agent_dir%/}/" "${REALM_MAC_STAGE_DIR}/agent/"
  find "${REALM_MAC_STAGE_DIR}/agent" -type d -name __pycache__ -prune -exec rm -rf {} + >/dev/null 2>&1 || true
  find "${REALM_MAC_STAGE_DIR}/agent" -type f \( -name '*.pyc' -o -name '*.pyo' \) -delete >/dev/null 2>&1 || true

  src_shared_dir="$(cd "${agent_dir}/.." && pwd)/shared"
  if [[ ! -d "${src_shared_dir}" ]]; then
    err "仓库 ZIP 未包含 shared 包，拒绝切换到不完整 Agent"
    return 1
  fi
  sync_macos_shared_stage "${src_shared_dir}" "${REALM_MAC_STAGE_DIR}"

  req_file="$(select_macos_agent_requirements_file \
    "${REALM_MAC_STAGE_DIR}/agent" || true)"
  if [[ -z "${req_file}" ]]; then
    err "Agent staging 缺少 requirements.lock"
    return 1
  fi
  req_sha="$(compute_requirements_sha256 "${req_file}" || true)"
  old_req_sha="$(tr -d '[:space:]' < /etc/realm-agent/requirements.sha256 2>/dev/null || true)"
  venv_attestation_stage="${REALM_MAC_STAGE_DIR}/venv-attestation.json"
  wheelhouse_dir="${REALM_MAC_STAGE_DIR}/agent/wheels"
  if wheelhouse_has_wheels "${wheelhouse_dir}"; then
    has_local_wheels="1"
    info "检测到包内离线依赖包：${wheelhouse_dir}"
  fi

  REALM_MAC_DEPLOY_REPLACE_VENV="1"
  # 复用前必须通过严格 lock/RECORD/ABI 证明（对齐 Linux verify_agent_venv_lock），
  # 防止 venv 包文件被篡改后仍被静默复用。
  if [[ "${REALM_AGENT_FORCE_VENV_REBUILD:-0}" != "1" \
        && -x "${BASE_DIR}/venv/bin/python" \
        && -n "${req_sha}" \
        && "${req_sha}" == "${old_req_sha}" ]]; then
    if verify_agent_venv_lock \
      "${BASE_DIR}/venv/bin/python" "${REALM_MAC_STAGE_DIR}" "${venv_attestation_stage}"; then
      REALM_MAC_DEPLOY_REPLACE_VENV="0"
      stage_python="${BASE_DIR}/venv/bin/python"
      info "依赖锁未变化且现有 venv 通过严格证明（sha256: ${req_sha:0:12}...），保留当前 venv"
    else
      info "requirements hash 相同但现有 venv 证明失败；继续 staging 重建"
    fi
  fi

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

  if [[ "${REALM_MAC_DEPLOY_REPLACE_VENV}" == "1" ]]; then
    info "在 staging 中创建并验证新 venv（超时 ${venv_timeout}s）..."
    if ! create_isolated_macos_agent_venv \
      "${bootstrap_python}" "${REALM_MAC_STAGE_DIR}/venv" \
      "${venv_timeout}" 0; then
      err "创建虚拟环境失败，尝试使用 --copies 重试一次..."
      rm -rf "${REALM_MAC_STAGE_DIR}/venv" || true
      if ! create_isolated_macos_agent_venv \
        "${bootstrap_python}" "${REALM_MAC_STAGE_DIR}/venv" \
        "${venv_timeout}" 1; then
        err "创建虚拟环境失败：请检查磁盘空间/系统 Python 后重试（可调 REALM_AGENT_VENV_CREATE_TIMEOUT）"
        return 1
      fi
    fi
    stage_python="${REALM_MAC_STAGE_DIR}/venv/bin/python"
    if ! preflight_agent_venv_startup \
      "${stage_python}" "${REALM_MAC_STAGE_DIR}"; then
      err "新建 Agent venv 在执行 pip 前未通过隔离启动预检"
      return 1
    fi
    if ! bootstrap_macos_venv_pip \
      "${stage_python}" "${REALM_MAC_STAGE_DIR}" "${venv_timeout}"; then
      return 1
    fi
    if ! preflight_agent_venv_startup \
      "${stage_python}" "${REALM_MAC_STAGE_DIR}"; then
      err "Agent venv 在 pip 引导后未通过隔离启动预检"
      return 1
    fi
    stage_python_version="$(
      run_isolated_macos_python "${stage_python}" -c \
        'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")' \
        2>/dev/null || true
    )"
    # 先尝试包内 wheelhouse；不完整或平台不兼容时回退在线索引（保持同一带哈希 lock）。
    if [[ "${has_local_wheels}" == "1" ]]; then
      if ! wheelhouse_satisfies_requirements \
        "${REALM_MAC_STAGE_DIR}/venv/bin/pip" "${req_file}" "${wheelhouse_dir}"; then
        warn "本地离线包不完整或与当前 macOS/CPython ${stage_python_version:-unknown} 不兼容，跳过离线包并回退在线索引（保持当前哈希策略）"
        has_local_wheels="0"
      fi
    fi
    req_hash_args=(--require-hashes --no-deps --no-compile)
    req_installed="0"
    if [[ "${has_local_wheels}" == "1" ]]; then
      info "安装依赖（staging，本地离线包，超时 ${pip_timeout}s）..."
      if pip_install_from_wheels \
        "${REALM_MAC_STAGE_DIR}/venv/bin/pip" "${pip_timeout}" \
        "安装依赖（staging，本地离线包）" \
        "${wheelhouse_dir}" "${req_hash_args[@]}" -r "${req_file}"; then
        req_installed="1"
      else
        err "本地离线包安装 requirements 失败，回退在线索引（保持当前哈希策略）"
      fi
    fi
    if [[ "${req_installed}" != "1" ]]; then
      # 本地 wheelhouse 不可用时，明确使用在线索引安装，仍强制 --require-hashes。
      info "安装依赖（staging，超时 ${pip_timeout}s）..."
      if ! pip_install_with_fallback \
        "${REALM_MAC_STAGE_DIR}/venv/bin/pip" "${pip_timeout}" \
        "安装依赖（staging）" "${req_hash_args[@]}" -r "${req_file}"; then
        err "requirements.lock 哈希校验安装失败，拒绝无哈希重试"
        return 1
      fi
    fi
    if ! verify_agent_venv_lock \
      "${stage_python}" "${REALM_MAC_STAGE_DIR}" "${venv_attestation_stage}"; then
      err "新建 Agent venv 未通过严格 lock/RECORD/ABI 校验"
      return 1
    fi
    "${stage_python}" -B -c "import fastapi, uvicorn" >/dev/null
    "${stage_python}" -I -B -m pip check >/dev/null
  fi

  (
    cd "${REALM_MAC_STAGE_DIR}/agent" || exit 1
    PYTHONPATH="${REALM_MAC_STAGE_DIR}" PYTHONDONTWRITEBYTECODE=1 \
      "${stage_python}" -B -c "import agent.app.main"
  )
  "${stage_python}" -I -B -m pip check >/dev/null
  printf '%s\n' "${req_sha}" > "${REALM_MAC_STAGE_DIR}/requirements.sha256"
}

install_agent_files(){
  local host="$1"
  local port="$2"
  local transport="${3:-http}"
  local ssl_cert="${4:-/etc/realm-agent/certs/server.crt}"
  local ssl_key="${5:-/etc/realm-agent/certs/server.key}"
  local tls_server_name="${6:-}"
  local tls_ca_cert="${7:-}"
  local insecure_non_loopback="${8:-0}"
  local tmpdir
  tmpdir="$(mktemp -d "${TMPDIR:-/tmp}/realm-agent-macos.XXXXXX")" \
    || return 1
  chmod 700 "${tmpdir}" || return 1
  register_cleanup_path "${tmpdir}"

  local repo_zip="$tmpdir/repo.zip"
  if ! fetch_repo_zip "$repo_zip"; then
    err "仓库 ZIP 下载失败"
    return 1
  fi

  install -d -m 700 "$tmpdir/extract" || return 1
  unzip -q "$repo_zip" -d "$tmpdir/extract" || return 1

  local agent_dir
  agent_dir="$(find_agent_dir "$tmpdir/extract")" || return 1
  [[ -n "${agent_dir}" ]] || return 1
  info "发现 agent 目录：$agent_dir"

  build_macos_agent_stage "${agent_dir}" || return 1
  if [[ "${REALM_MAC_DEPLOY_ROLLBACK_ACTIVE:-0}" != "1" ]]; then
    begin_macos_agent_rollback || return 1
  fi
  if ! persist_transaction_value \
    "${REALM_MAC_TRANSACTION_DIR}/stage-path" "${REALM_MAC_STAGE_DIR}"; then
    err "无法把 macOS Agent staging 路径绑定到持久化事务"
    return 1
  fi
  if ! write_agent_launchd; then
    err "无法在 macOS Agent 切换前持久化 launchd 配置"
    return 1
  fi
  if ! configure_macos_sshd_loopback_penalty_exemption; then
    err "sshd loopback 源处罚豁免配置失败"
    return 1
  fi
  if ! install_macos_continuity_package "${agent_dir}"; then
    err "continuity package 安装或完整性校验失败"
    return 1
  fi
  if ! quiesce_macos_agent_stack "${port}"; then
    err "主 Agent 未能在目录切换前进入静止状态"
    return 1
  fi
  if ! activate_macos_agent_stage; then
    err "Agent staging 原子切换失败"
    return 1
  fi
  if [[ "${REALM_MAC_DEPLOY_REPLACE_VENV}" == "1" ]]; then
    local final_venv_attestation="${REALM_MAC_STAGE_DIR}/venv-attestation.final.json"
    if ! verify_agent_venv_lock \
      "${BASE_DIR}/venv/bin/python" "${BASE_DIR}" \
      "${final_venv_attestation}"; then
      err "最终路径 Agent venv 未通过 shebang/RECORD 重绑定后的严格证明"
      return 1
    fi
  fi

  install -d -m 755 /etc/realm || return 1
  if [[ -f "$BASE_DIR/agent/pool_to_run.jq" ]]; then
    cp -f "$BASE_DIR/agent/pool_to_run.jq" /etc/realm/pool_to_run.jq \
      || return 1
  fi
  install -d -m 700 /etc/realm-agent || return 1
  cp -f "${REALM_MAC_STAGE_DIR}/requirements.sha256" \
    /etc/realm-agent/requirements.sha256 || return 1
  chmod 600 /etc/realm-agent/requirements.sha256 || return 1

  write_env_files \
    "$host" "$port" "$transport" "$ssl_cert" "$ssl_key" \
    "$tls_server_name" "$tls_ca_cert" "$insecure_non_loopback" || return 1
  write_start_script || return 1
  write_agent_launchd || return 1
  if ! sync_macos_agent_runtime_state \
    || ! persist_transaction_value \
      "${REALM_MAC_TRANSACTION_DIR}/state" "main-start-allowed"; then
    err "Agent 运行文件未持久化，拒绝授予 launchd 启动许可"
    return 1
  fi
  if ! restart_agent_launchd "$port"; then
    err "主 Agent launchd bootstrap/启动失败"
    return 1
  fi
  if ! setup_mptcp_sidecar_launchd; then
    err "MPTCP sidecar launchd bootstrap/状态恢复失败"
    return 1
  fi
  if ! setup_revtunnel_launchd; then
    err "反向隧道 launchd bootstrap/启动失败"
    return 1
  fi
  if ! setup_remote_companion "$tmpdir/extract"; then
    err "RemoteMacAgent companion 安装/运行探针失败"
    return 1
  fi
}

get_ipv4(){
  run_trusted_macos_python - <<'PY' 2>/dev/null || true
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
    s.connect(("8.8.8.8", 80))
    print(s.getsockname()[0])
except Exception:
    pass
finally:
    s.close()
PY
}

format_macos_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_macos_agent_access_endpoints(){
  local transport="$1"
  local host="$2"
  local port="$3"
  local tls_server_name="${4:-}"
  local ip=""
  if [[ "${transport}" == "https" && -n "${tls_server_name}" ]]; then
    echo "- Agent URL:   $(format_macos_agent_url \
      "${transport}" "${tls_server_name}" "${port}")"
  fi
  case "${host}" in
    0.0.0.0)
      echo "- Listen:      $(format_macos_agent_url \
        "${transport}" "${host}" "${port}")"
      ip="$(get_ipv4)"
      if [[ -n "${ip}" && -z "${tls_server_name}" ]]; then
        echo "- Agent URL:   $(format_macos_agent_url \
          "${transport}" "${ip}" "${port}")"
      fi
      ;;
    ::)
      echo "- Listen:      $(format_macos_agent_url \
        "${transport}" "${host}" "${port}")"
      ;;
    *)
      if [[ -z "${tls_server_name}" || "${tls_server_name}" == "${host}" ]]; then
        echo "- Agent URL:   $(format_macos_agent_url \
          "${transport}" "${host}" "${port}")"
      fi
      ;;
  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:     已安全保存（默认隐藏；文件：/etc/realm-agent/api.key）"
  fi
}

main(){
  parse_args "$@"
  ensure_macos
  need_root
  if [[ "${REALM_MAC_RECOVER_ONLY:-0}" == "1" ]]; then
    REALM_AGENT_INSTALL_LOCK_NONBLOCK="1"
  fi
  if ! acquire_agent_install_lock; then
    if [[ "${REALM_MAC_RECOVER_ONLY:-0}" == "1" \
      && "${REALM_AGENT_INSTALL_LOCK_BUSY:-0}" == "1" \
      && "${REALM_AGENT_INSTALL_LOCK_NONBLOCK:-0}" == "1" ]]; then
      exit 75
    fi
    exit 1
  fi
  if [[ "${REALM_MAC_RECOVER_ONLY:-0}" == "1" ]]; then
    if ! recover_interrupted_macos_install; then
      exit 1
    fi
    ok "macOS Agent 启动前事务恢复检查完成"
    exit 0
  fi
  if ! recover_interrupted_macos_install; then
    exit 1
  fi
  hydrate_update_runtime_env
  local contract_fields=""
  local host=""
  local port=""
  local transport=""
  local ssl_cert=""
  local ssl_key=""
  local tls_server_name=""
  local tls_ca_cert=""
  local insecure_non_loopback=""
  contract_fields="$(resolve_macos_agent_contract)" || exit 1
  parse_macos_agent_contract_fields "${contract_fields}" || exit 1
  host="${MACOS_AGENT_CONTRACT_FIELDS[0]}"
  port="${MACOS_AGENT_CONTRACT_FIELDS[1]}"
  transport="${MACOS_AGENT_CONTRACT_FIELDS[2]}"
  ssl_cert="${MACOS_AGENT_CONTRACT_FIELDS[3]}"
  ssl_key="${MACOS_AGENT_CONTRACT_FIELDS[4]}"
  tls_server_name="${MACOS_AGENT_CONTRACT_FIELDS[5]}"
  tls_ca_cert="${MACOS_AGENT_CONTRACT_FIELDS[6]}"
  insecure_non_loopback="${MACOS_AGENT_CONTRACT_FIELDS[7]}"
  if ! preflight_remote_companion_panel_transport; then
    exit 1
  fi
  info "检查依赖..."
  ensure_deps
  if ! install_macos_startup_recovery_support \
    || ! install_macos_recovery_launchd; then
    exit 1
  fi
  REALM_MAC_STAGE_DIR="${BASE_DIR}/.staging.pending"
  if ! begin_macos_agent_rollback; then
    exit 1
  fi
  if ! write_agent_launchd; then
    exit 1
  fi
  local api_key_existed_before="0"
  if [[ -s /etc/realm-agent/api.key ]]; then
    api_key_existed_before="1"
  fi

  echo "Realm Agent Installer (macOS) ${VERSION}"
  echo "------------------------------------------------------------"

  info "安装/更新 Agent（macOS launchd 模式）..."
  install_agent_files \
    "$host" "$port" "$transport" "$ssl_cert" "$ssl_key" \
    "$tls_server_name" "$tls_ca_cert" "$insecure_non_loopback"
  info "执行安装后检查（节点监控 + 内网穿透）..."
  if ! verify_agent_runtime \
    "$host" "$port" "$transport" "$tls_ca_cert" "$tls_server_name"; then
    exit 1
  fi
  if ! commit_macos_install_transaction; then
    err "macOS Agent 事务提交失败"
    exit 1
  fi
  if ! retire_legacy_macos_logs; then
    warn "Agent 已提交，但 legacy macOS 日志清理失败；保留服务在线"
  fi

  local api_key
  api_key="$(cat /etc/realm-agent/api.key 2>/dev/null || true)"

  ok "Agent 已安装并启动"
  print_macos_agent_access_endpoints \
    "${transport}" "${host}" "${port}" "${tls_server_name}"
  print_agent_api_key "${api_key}" "${api_key_existed_before}"
  if [[ "${AGENT_BOOTSTRAP_MODE}" == "launchd" ]]; then
    echo "- Service:     launchctl print system/${AGENT_LABEL}"
  else
    echo "- Service:     standalone（PID: /var/run/realm-agent.pid）"
  fi
}

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