Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

23.5 KB
Raw Blame
#!/usr/bin/env bash
set -euo pipefail
export PYTHONDONTWRITEBYTECODE=1

PIXEL_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)

pixel_log() { printf '[pixel] %s\n' "$*"; }
pixel_warn() { printf '[pixel] WARNING: %s\n' "$*" >&2; }
pixel_die() { printf '[pixel] ERROR: %s\n' "$*" >&2; exit 1; }

pixel_load_env() {
  local env_file=${1:-$PIXEL_ROOT/.env}
  [[ -f "$env_file" ]] || pixel_die "Missing $env_file. Run ./pixel configure first."
  bash -n "$env_file" || pixel_die "Invalid shell syntax in $env_file"
  set -a
  # The file is generated by Pixel and is trusted operator configuration.
  # shellcheck disable=SC1090
  source "$env_file"
  set +a
  # OPENCLAW_HOME is Pixel's operator-facing state directory setting. OpenClaw's
  # native variables must be explicit so custom state paths work consistently.
  export OPENCLAW_STATE_DIR="$OPENCLAW_HOME"
  export OPENCLAW_CONFIG_PATH="$OPENCLAW_HOME/openclaw.json"
  export PIXEL_ROOT
}

pixel_require_command() {
  command -v "$1" >/dev/null 2>&1 || pixel_die "Missing command: $1"
}

pixel_end_human_approval_session() {
  if [[ ${PIXEL_HUMAN_APPROVAL_SESSION_ACTIVE:-0} == 1 ]]; then
    "$PIXEL_HUMAN_APPROVAL_SUDO" -K >/dev/null 2>&1 || true
    PIXEL_HUMAN_APPROVAL_SESSION_ACTIVE=0
  fi
}

pixel_require_interactive_terminal() {
  [[ -t 0 && -t 1 && -t 2 && -c /dev/tty && -r /dev/tty && -w /dev/tty ]] ||
    pixel_die "Human approval requires a real interactive terminal on standard input, output, and error"
}

pixel_begin_human_approval_session() {
  local purpose=$1
  pixel_require_interactive_terminal
  [[ $EUID -ne 0 ]] || pixel_die "Human approval must run as the non-root deployment owner"
  PATH=/usr/sbin:/usr/bin:/sbin:/bin
  export PATH
  PIXEL_HUMAN_APPROVAL_SUDO=/usr/bin/sudo
  [[ -f "$PIXEL_HUMAN_APPROVAL_SUDO" && ! -L "$PIXEL_HUMAN_APPROVAL_SUDO" && -x "$PIXEL_HUMAN_APPROVAL_SUDO" ]] ||
    pixel_die "Pixel requires the trusted system administrator tool at /usr/bin/sudo"
  pixel_log "$purpose requires fresh administrator authentication and a one-time terminal confirmation."
  "$PIXEL_HUMAN_APPROVAL_SUDO" -K
  PIXEL_HUMAN_APPROVAL_SESSION_ACTIVE=1
  trap pixel_end_human_approval_session EXIT
  if "$PIXEL_HUMAN_APPROVAL_SUDO" -n -v >/dev/null 2>&1; then
    pixel_die "Passwordless administrator access cannot establish Pixel's human-authenticated approval boundary"
  fi
  "$PIXEL_HUMAN_APPROVAL_SUDO" -v </dev/tty
}

pixel_confirm_human_approval() {
  local purpose=$1 object_id=$2 object_hash=$3 challenge expected response
  [[ -f /usr/bin/od && ! -L /usr/bin/od && -x /usr/bin/od ]] ||
    pixel_die "Pixel requires the trusted system random-byte renderer at /usr/bin/od"
  challenge=$(LC_ALL=C /usr/bin/od -An -N8 -tx1 /dev/urandom)
  challenge=${challenge// /}
  [[ "$challenge" =~ ^[a-f0-9]{16}$ ]] || pixel_die "Could not create a safe one-time approval challenge"
  expected="APPROVE ${object_hash:0:12} $challenge"
  printf '\nPixel will perform: %s\nObject: %s\nSHA-256: %s\nType exactly: %s\n> ' \
    "$purpose" "$object_id" "$object_hash" "$expected" >/dev/tty
  IFS= read -r response </dev/tty || pixel_die "Human approval confirmation was interrupted"
  [[ "$response" == "$expected" ]] || pixel_die "Human approval confirmation did not match; nothing was approved"
  pixel_log "Human approval confirmed for $object_id."
}

pixel_require_linux() {
  [[ $(uname -s) == Linux ]] || pixel_die "Pixel deployment currently supports Linux hosts; found $(uname -s)"
  [[ -r /etc/os-release ]] || pixel_die "Cannot identify Linux distribution"
  # shellcheck disable=SC1091
  source /etc/os-release
  case "${ID:-}" in ubuntu|debian) ;; *) pixel_die "Supported distributions are Ubuntu and Debian; found ${ID:-unknown}" ;; esac
}

pixel_json_bool() {
  [[ ${1:-0} == 1 || ${1:-false} == true ]] && printf true || printf false
}

# Check the target user's effective access with Bash's syscall-backed file
# predicates. Some supported distributions provide a Rust coreutils `test`
# whose -r/-w predicates inspect only mode bits and ignore effective POSIX ACLs.
# Keep the expression static and pass the path as data so this remains safe for
# configured paths containing shell metacharacters.
pixel_user_can_access() {
  local user=$1 mode=$2 path=$3 expression
  [[ "$user" =~ ^[A-Za-z_][A-Za-z0-9_.-]{0,63}[$]?$ ]] || pixel_die "Access probe user is unsafe"
  [[ -n "$path" && "$path" != *$'\n'* && "$path" != *$'\r'* ]] || pixel_die "Access probe path is unsafe"
  # The literal expressions are deliberately evaluated only by the target
  # user's Bash; the configured path is supplied separately as argv data.
  # shellcheck disable=SC2016
  case "$mode" in
    r) expression='[[ -r "$1" ]]' ;;
    w) expression='[[ -w "$1" ]]' ;;
    x) expression='[[ -x "$1" ]]' ;;
    *) pixel_die "Access probe mode is unsafe" ;;
  esac
  sudo -u "$user" /bin/bash -c "$expression" pixel-access-probe "$path"
}

pixel_safe_absolute_dir() {
  local value=$1 label=$2
  [[ "$value" == /* && "$value" != / ]] || pixel_die "$label must be an absolute, non-root path: $value"
}

pixel_openclaw_version() {
  "$OPENCLAW_BIN" --version 2>/dev/null | grep -Eo '[0-9]{4}\.[0-9]+\.[0-9]+(-[0-9]+)?' | head -n1
}

pixel_plugin_loaded() {
  local plugin_id=$1
  "$OPENCLAW_BIN" plugins inspect "$plugin_id" >/dev/null 2>&1
}

pixel_custom_plugin_release_matches() {
  local plugin_id=$1 relative=$2 expected_version=${3:-} details expected_root
  [[ "$relative" == plugin || "$relative" == plugin-ops ]] || return 1
  expected_root=$(realpath -e "$PIXEL_INSTALL_DIR/current/$relative") || return 1
  if [[ -z "$expected_version" ]]; then
    [[ -f "$PIXEL_INSTALL_DIR/current/VERSION" && ! -L "$PIXEL_INSTALL_DIR/current/VERSION" ]] || return 1
    IFS= read -r expected_version < "$PIXEL_INSTALL_DIR/current/VERSION" || return 1
  fi
  [[ "$expected_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([+~-][A-Za-z0-9._-]+)?$ ]] || return 1
  details=$("$OPENCLAW_BIN" plugins inspect "$plugin_id" --json 2>/dev/null) || return 1
  jq -e --arg version "$expected_version" --arg root "$expected_root" '
    .plugin.status == "loaded" and
    .plugin.version == $version and
    .plugin.rootDir == $root
  ' <<<"$details" >/dev/null
}

pixel_refresh_custom_plugin_registry() {
  "$OPENCLAW_BIN" plugins registry --refresh --json >/dev/null
  if [[ ${PIXEL_SOURCE_BROKER_ENABLED:-1} == 1 ]]; then
    pixel_custom_plugin_release_matches pixel-source-broker plugin || pixel_die "Pixel Source Broker registry root does not match the active release"
  fi
  if [[ ${PIXEL_OPS_BROKER_ENABLED:-0} == 1 ]]; then
    pixel_custom_plugin_release_matches pixel-operations-broker plugin-ops || pixel_die "Pixel Operations Broker registry root does not match the active release"
  fi
}

pixel_plugin_release_matches() {
  local plugin_id=$1 expected_version=$2 expected_integrity=$3 expected_archive_sha256=$4 archive=$5 details root observed openclaw_root peer_version receipt receipt_mode
  local -a receipt_args
  [[ -f "$archive" && ! -L "$archive" ]] || return 1
  observed=$(sha256sum "$archive" | awk '{print $1}')
  [[ "$observed" == "$expected_archive_sha256" ]] || return 1
  details=$("$OPENCLAW_BIN" plugins inspect "$plugin_id" --json 2>/dev/null) || return 1
  jq -e --arg version "$expected_version" --arg integrity "$expected_integrity" '
    .plugin.status == "loaded" and
    .plugin.version == $version and
    (
      (.install.source == "archive" and .install.version == $version) or
      (.install.resolvedVersion == $version and .install.integrity == $integrity)
    )
  ' <<<"$details" >/dev/null
  root=$(jq -er '.plugin.rootDir' <<<"$details") || return 1
  openclaw_root=$(dirname "$(realpath -e "$OPENCLAW_BIN")") || return 1
  peer_version=${PIXEL_OPENCLAW_VERSION:-${openclaw_version:-}}
  [[ -n "$peer_version" ]] || return 1
  receipt=${archive%.tgz}.installed.json
  receipt_mode=${PIXEL_PLUGIN_RECEIPT_MODE:-verify}
  case "$receipt_mode" in
    verify) receipt_args=(--receipt "$receipt") ;;
    record) receipt_args=(--write-receipt "$receipt") ;;
    *) return 1 ;;
  esac
  python3 "$PIXEL_ROOT/scripts/verify-plugin-archive.py" \
    --allowed-peer "openclaw@$peer_version=$openclaw_root" "${receipt_args[@]}" "$archive" "$root" >/dev/null
}

pixel_release_operator_enabled() {
  [[ ${PIXEL_RELEASE_OPERATOR_ENABLED:-0} == 1 ]]
}

pixel_release_operator_client() {
  python3 "$PIXEL_ROOT/deploy/release-operator/client.py" "$@"
}

pixel_release_operator_preflight() {
  pixel_release_operator_enabled || return 0
  [[ -n ${PIXEL_RELEASE_OPERATOR_USER:-} && -n ${PIXEL_RELEASE_OPERATOR_KEY:-} ]] ||
    pixel_die "Enabled release operator is missing its transport user or private key path"
  pixel_release_operator_client status >/dev/null ||
    pixel_die "Enabled release operator failed its pinned localhost status probe"
}

pixel_release_operator_unit() {
  local op=$1 which=$2 source=$3 requested
  [[ -f "$source" && ! -L "$source" ]] || pixel_die "Operator unit source is missing or a link: $source"
  requested=$(sha256sum "$source" | awk '{print $1}')
  [[ "$requested" =~ ^[a-f0-9]{64}$ ]] || pixel_die "Unable to compute a safe unit SHA-256"
  pixel_release_operator_client unit "$op" "$which" "$requested"
}

pixel_release_operator_systemctl() {
  local which=$1 verb=$2 extra=() unit expected
  shift 2
  if [[ $verb == daemon-reload ]]; then
    [[ $# == 0 ]] || pixel_die "daemon-reload takes no unit argument"
    pixel_release_operator_client systemctl daemon-reload
    return $?
  fi
  case "$verb" in
    enable|disable|restart|stop|is-active|is-enabled) ;;
    *) pixel_die "unsupported release-operator systemctl verb: $verb" ;;
  esac
  if [[ $# -ge 1 && $1 == --now ]]; then extra=(--now); shift; fi
  [[ $# == 1 ]] || pixel_die "release-operator systemctl expects exactly one unit"
  unit=$1
  if [[ $which == gateway ]]; then expected=${PIXEL_SYSTEMD_UNIT:-}; else expected=${PIXEL_WEB_COURIER_UNIT:-pixel-web-courier.service}; fi
  [[ -n "$expected" && "$unit" == "$expected" ]] || pixel_die "release-operator systemctl unit does not match the configured $which unit"
  pixel_release_operator_client systemctl "$verb" "$which" "${extra[@]}"
}

pixel_release_operator_probe() {
  local reader=$1 message=$2
  if ! pixel_release_operator_client probe "$reader"; then
    pixel_die "$message"
  fi
}

pixel_systemctl() {
  if pixel_release_operator_enabled; then
    pixel_release_operator_systemctl gateway "$@"
    return $?
  fi
  if [[ -n ${PIXEL_SYSTEMCTL_BIN:-} ]]; then
    "$PIXEL_SYSTEMCTL_BIN" "$@"
  else
    sudo systemctl "$@"
  fi
}

pixel_systemctl_read() {
  if [[ -n ${PIXEL_SYSTEMCTL_BIN:-} ]]; then
    "$PIXEL_SYSTEMCTL_BIN" "$@"
  else
    systemctl "$@"
  fi
}

pixel_gateway_install_unit() {
  local source=$1 target=$2
  if pixel_release_operator_enabled; then
    pixel_release_operator_unit install gateway "$source"
    return $?
  fi
  if [[ -n ${PIXEL_SYSTEMCTL_BIN:-} ]]; then
    install -m 644 "$source" "$target"
  else
    sudo install -o root -g root -m 644 "$source" "$target"
  fi
}

pixel_gateway_remove_unit() {
  local target=$1
  if pixel_release_operator_enabled; then
    pixel_release_operator_client unit remove gateway
    return $?
  fi
  if [[ -n ${PIXEL_SYSTEMCTL_BIN:-} ]]; then
    rm -f -- "$target"
  else
    sudo rm -f -- "$target"
  fi
}

pixel_legacy_systemctl() {
  "${PIXEL_LEGACY_SYSTEMCTL_BIN:-systemctl}" --user "$@"
}

pixel_courier_systemctl() {
  if pixel_release_operator_enabled; then
    pixel_release_operator_systemctl courier "$@"
    return $?
  fi
  if [[ -n ${PIXEL_COURIER_SYSTEMCTL_BIN:-} ]]; then
    "$PIXEL_COURIER_SYSTEMCTL_BIN" "$@"
  else
    sudo systemctl "$@"
  fi
}

pixel_courier_systemctl_read() {
  if [[ -n ${PIXEL_COURIER_SYSTEMCTL_BIN:-} ]]; then
    "$PIXEL_COURIER_SYSTEMCTL_BIN" "$@"
  else
    systemctl "$@"
  fi
}

pixel_courier_install_unit() {
  local source=$1 target=$2
  if pixel_release_operator_enabled; then
    pixel_release_operator_unit install courier "$source"
    return $?
  fi
  if [[ -n ${PIXEL_COURIER_SYSTEMCTL_BIN:-} ]]; then
    install -m 644 "$source" "$target"
  else
    sudo install -m 644 "$source" "$target"
  fi
}

pixel_courier_remove_unit() {
  local target=$1
  if pixel_release_operator_enabled; then
    pixel_release_operator_client unit remove courier
    return $?
  fi
  if [[ -n ${PIXEL_COURIER_SYSTEMCTL_BIN:-} ]]; then
    rm -f -- "$target"
  else
    sudo rm -f -- "$target"
  fi
}

pixel_atomic_symlink() {
  local target=$1 link=$2 temporary
  temporary="${link}.new.$$"
  ln -s "$target" "$temporary"
  mv -Tf "$temporary" "$link"
}

# pixel_invalidate_runtime_attestation PATH
# Atomically invalidate the runtime attestation so a changed active release can never
# retain a false positive receipt. Removal alone satisfies the safe invariant: an absent
# attestation reads as "unavailable", never as a fabricated verified state. Removes only a
# regular single-link file or a symlink; fails closed (nonzero, so the caller aborts) when
# the path is a directory, a multi-link regular file, or any unsafe special object. The
# caller must run this immediately after flipping the active-release symlink, and must treat
# a nonzero return as a failed reconciliation (no success receipt may be recorded).
pixel_invalidate_runtime_attestation() {
  local path=$1 nlink
  [[ ! -e "$path" && ! -L "$path" ]] && return 0
  [[ -d "$path" ]] && pixel_die "Runtime attestation path is an unsafe directory: $path"
  [[ -f "$path" || -L "$path" ]] || pixel_die "Runtime attestation path is unsafe: $path"
  if [[ ! -L "$path" ]]; then
    nlink=$(stat -c '%h' -- "$path" 2>/dev/null) || \
      pixel_die "Runtime attestation link count cannot be read safely: $path"
    [[ "$nlink" == "1" ]] || pixel_die "Runtime attestation is unsafely hard-linked: $path"
  fi
  rm -f -- "$path" || pixel_die "Runtime attestation could not be invalidated: $path"
}

pixel_sandbox_preserve_tag() {
  local version=$1 uid=${2:-$(id -u)}
  [[ "$version" =~ ^[0-9]{1,6}\.[0-9]{1,6}\.[0-9]{1,6}$ ]] || pixel_die "Unsafe sandbox preserve version: $version"
  [[ "$uid" =~ ^[1-9][0-9]*$ ]] || pixel_die "Unsafe sandbox preserve uid: $uid"
  printf 'pixel-sandbox-preserve:%s-uid-%s\n' "$version" "$uid"
}

pixel_sandbox_candidate_tag() {
  local version=$1 uid=${2:-$(id -u)}
  [[ "$version" =~ ^[0-9]{1,6}\.[0-9]{1,6}\.[0-9]{1,6}$ ]] || pixel_die "Unsafe sandbox candidate version: $version"
  [[ "$uid" =~ ^[1-9][0-9]*$ ]] || pixel_die "Unsafe sandbox candidate uid: $uid"
  printf 'pixel-sandbox-candidate:%s-uid-%s\n' "$version" "$uid"
}

pixel_validate_sandbox_image() {
  local reference=$1 expected_version=$2 expected_uid=$3 image_id observed_version observed_uid observed_user
  image_id=$(docker image inspect --format '{{.Id}}' "$reference" 2>/dev/null) || return 1
  observed_version=$(docker image inspect --format '{{ index .Config.Labels "org.osmantic.pixel.sandbox-version" }}' "$reference" 2>/dev/null) || return 1
  observed_uid=$(docker image inspect --format '{{ index .Config.Labels "org.osmantic.pixel.sandbox-uid" }}' "$reference" 2>/dev/null) || return 1
  observed_user=$(docker image inspect --format '{{.Config.User}}' "$reference" 2>/dev/null) || return 1
  [[ "$image_id" =~ ^sha256:[a-f0-9]{64}$ && "$observed_version" == "$expected_version" && "$observed_uid" == "$expected_uid" && "$observed_user" == sandbox ]] || return 1
  printf '%s\n' "$image_id"
}

# Labels name the release that built a sandbox image, not what it contains.
# Run the image's own node once, offline and read-only like the agent sandbox:
# it must be the pinned version for this host's architecture, and npm, npx and
# corepack must be absent. Returns nonzero, without live changes, otherwise.
pixel_prove_sandbox_runtime() {
  local image_id=$1 expected_version=$2 expected_arch observed program name
  [[ "$image_id" =~ ^sha256:[a-f0-9]{64}$ ]] || return 1
  [[ "$expected_version" =~ ^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}$ ]] || return 1
  case "$(uname -m)" in
    x86_64) expected_arch=x64 ;;
    aarch64|arm64) expected_arch=arm64 ;;
    *) return 1 ;;
  esac
  program='const {accessSync, constants} = require("fs"), {join} = require("path");
const found = ["npm", "npx", "corepack"].filter((name) => (process.env.PATH || "").split(":").some((dir) => {
  try { accessSync(join(dir, name), constants.X_OK); return true; } catch { return false; }
}));
console.log(process.version + " " + process.arch + " " + (found.join(",") || "none"));'
  # A wedged Docker daemon must not hang bootstrap. A timed-out client does not
  # stop its container, so the proof names its own and removes it on failure.
  name="ods-pixel-sandbox-proof-$(od -An -N8 -tx1 /dev/urandom | tr -d ' \n')"
  [[ "$name" =~ ^ods-pixel-sandbox-proof-[a-f0-9]{16}$ ]] || return 1
  if ! observed=$(timeout 120 docker run --rm --name "$name" --network none --read-only --cap-drop ALL \
    --security-opt no-new-privileges:true --pids-limit 128 --memory 512m \
    --tmpfs /tmp:rw,nosuid,nodev,size=16m --user sandbox \
    --entrypoint /usr/local/bin/node "$image_id" -e "$program"); then
    # --rm normally removed it already; a missing container is the expected case.
    docker rm -f -- "$name" >/dev/null 2>&1 || true
    return 1
  fi
  [[ "$observed" == "v$expected_version $expected_arch none" ]]
}

pixel_preserve_sandbox_image() {
  local source=$1 version=$2 uid=$3 preserve image_id preserved_id
  preserve=$(pixel_sandbox_preserve_tag "$version" "$uid")
  image_id=$(pixel_validate_sandbox_image "$source" "$version" "$uid") || pixel_die "Existing sandbox image is unsafe and cannot be preserved for rollback"
  docker image tag "$image_id" "$preserve"
  preserved_id=$(pixel_validate_sandbox_image "$preserve" "$version" "$uid") || pixel_die "Preserved rollback sandbox image failed identity verification"
  [[ "$preserved_id" == "$image_id" ]] || pixel_die "Preserved rollback sandbox image changed identity"
  printf '%s\n' "$preserved_id"
}

pixel_restore_sandbox_image() {
  local target=$1 version=$2 uid=$3 expected_id=$4 preserve observed_id restored_id
  [[ "$expected_id" =~ ^sha256:[a-f0-9]{64}$ ]] || return 1
  preserve=$(pixel_sandbox_preserve_tag "$version" "$uid") || return 1
  observed_id=$(pixel_validate_sandbox_image "$preserve" "$version" "$uid") || return 1
  [[ "$observed_id" == "$expected_id" ]] || return 1
  docker image tag "$expected_id" "$target" || return 1
  restored_id=$(pixel_validate_sandbox_image "$target" "$version" "$uid") || return 1
  [[ "$restored_id" == "$expected_id" ]]
}

pixel_remove_sandbox_tag_exact() {
  local reference=$1 expected_version=$2 expected_uid=$3 expected_id=$4 observed_id
  docker image inspect "$reference" >/dev/null 2>&1 || return 1
  observed_id=$(pixel_validate_sandbox_image "$reference" "$expected_version" "$expected_uid") || return 1
  [[ "$observed_id" == "$expected_id" ]] || return 1
  docker image rm -- "$reference" >/dev/null 2>&1 || return 1
  ! docker image inspect "$reference" >/dev/null 2>&1
}

pixel_timestamp() { date -u +%Y%m%dT%H%M%SZ; }

pixel_acquire_deployment_lock() {
  local mode=${1:-exclusive} option=-n
  if [[ ${PIXEL_DEPLOYMENT_LOCK_HELD:-0} == 1 ]]; then
    [[ ${PIXEL_DEPLOYMENT_LOCK_FD:-} =~ ^[0-9]+$ && -e /proc/$$/fd/$PIXEL_DEPLOYMENT_LOCK_FD ]] || pixel_die "Invalid inherited deployment-lock context"
    return 0
  fi
  pixel_require_command flock
  [[ -n ${PIXEL_INSTALL_DIR:-} ]] || pixel_die "PIXEL_INSTALL_DIR is required for the deployment lock"
  pixel_safe_absolute_dir "$PIXEL_INSTALL_DIR" PIXEL_INSTALL_DIR
  install -d -m 700 "$PIXEL_INSTALL_DIR"
  PIXEL_DEPLOYMENT_LOCK_PATH="$PIXEL_INSTALL_DIR/.deployment.lock"
  exec {PIXEL_DEPLOYMENT_LOCK_FD}>"$PIXEL_DEPLOYMENT_LOCK_PATH"
  chmod 600 "$PIXEL_DEPLOYMENT_LOCK_PATH"
  case "$mode" in
    exclusive) option=-n ;;
    shared) option=-ns ;;
    *) pixel_die "Unknown deployment lock mode: $mode" ;;
  esac
  flock "$option" "$PIXEL_DEPLOYMENT_LOCK_FD" || pixel_die "Another Pixel deployment, backup, restore, rollback, or rotation is active"
  export PIXEL_DEPLOYMENT_LOCK_HELD=1 PIXEL_DEPLOYMENT_LOCK_FD PIXEL_DEPLOYMENT_LOCK_PATH
}

pixel_agent_sandbox_container_ids() {
  [[ ${PIXEL_AGENT_ID:-} =~ ^[a-z][a-z0-9_-]{1,63}$ ]] || pixel_die "PIXEL_AGENT_ID is unsafe for sandbox discovery"
  docker ps -aq --filter "name=^/pixel-sbx-agent-${PIXEL_AGENT_ID}-"
}

pixel_validate_agent_sandbox_identity() {
  local container=$1
  [[ "$container" =~ ^[a-f0-9]{12,64}$ ]] || pixel_die "Docker returned an unsafe sandbox container ID"
  docker inspect "$container" | jq -e \
    --arg prefix "/pixel-sbx-agent-${PIXEL_AGENT_ID}-" \
    --arg session "agent:${PIXEL_AGENT_ID}" '
      length == 1 and
      (.[0].Name | startswith($prefix)) and
      .[0].Config.Labels["openclaw.sandbox"] == "1" and
      .[0].Config.Labels["openclaw.sessionKey"] == $session
    ' >/dev/null || pixel_die "Container in Pixel's reserved sandbox namespace has an invalid identity"
}

pixel_retire_agent_sandboxes() {
  local container
  local -a containers=()
  mapfile -t containers < <(pixel_agent_sandbox_container_ids)
  for container in "${containers[@]}"; do pixel_validate_agent_sandbox_identity "$container"; done
  if [[ ${#containers[@]} -gt 0 ]]; then
    docker rm -f -- "${containers[@]}" >/dev/null
    pixel_log "Retired ${#containers[@]} agent sandbox container(s) before the gateway transition"
  fi
}

# pixel_read_release_version ROOT
# Bounded dependency-free no-follow stable read of $ROOT/VERSION for the exact-version
# release-identity gate. Opens with O_NOFOLLOW|O_CLOEXEC, fstats a regular single-link
# bounded file, loops os.read until exactly the pre-read st_size bytes are captured
# (rejecting early EOF and any growth), fstats the open descriptor again, then lstat-verifies
# the path: pre fstat, post fstat, and path lstat must all agree on the same device/inode/
# regular file type/single-link/size/mtime/ctime identity, so a linked, swapped, or in-place
# mutated VERSION cannot pass. Prints the ASCII-whitespace-trimmed content on stdout and
# returns 0; fails closed (nonzero) on any unsafe or changed identity. This proves only
# bounded single-link regular-file identity/coherence - ownership and directory custody come
# from the exact-source/release-tree gates, not this read.
pixel_read_release_version() {
  local root=$1
  python3 - "$root" <<'PY'
import os, re, stat, sys
root = sys.argv[1]
name = "VERSION"
maximum = 64
path = os.path.join(root, name)
version_re = re.compile(r"^[0-9]{1,6}\.[0-9]{1,6}\.[0-9]{1,6}$")
if not (hasattr(os, "O_NOFOLLOW") and hasattr(os, "O_CLOEXEC")):
    sys.exit("platform lacks O_NOFOLLOW/O_CLOEXEC release-identity guarantees")
flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC
def identity(st):
    return (st.st_dev, st.st_ino, stat.S_ISREG(st.st_mode), st.st_nlink,
            st.st_size, st.st_mtime_ns, st.st_ctime_ns)
try:
    fd = os.open(path, flags)
except OSError:
    sys.exit("release VERSION is unavailable or unsafe")
try:
    pre = os.fstat(fd)
    if not stat.S_ISREG(pre.st_mode) or pre.st_nlink != 1 or not 0 <= pre.st_size <= maximum:
        sys.exit("release VERSION is not a bounded single-link regular file")
    payload = bytearray()
    while len(payload) < pre.st_size:
        chunk = os.read(fd, pre.st_size - len(payload))
        if not chunk:
            sys.exit("release VERSION ended early during read")
        payload += chunk
    if os.read(fd, 1):
        sys.exit("release VERSION grew during read")
    post = os.fstat(fd)
    if identity(pre) != identity(post):
        sys.exit("release VERSION changed during read")
    current = os.lstat(path)
    if identity(post) != identity(current):
        sys.exit("release VERSION changed during read")
except OSError:
    sys.exit("release VERSION is unavailable or unsafe")
finally:
    os.close(fd)
try:
    text = bytes(payload).decode("ascii")
except UnicodeDecodeError:
    sys.exit("release VERSION is not ascii")
value = text.strip()
if not version_re.match(value):
    sys.exit("release VERSION is not a bounded semver")
print(value)
PY
}