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.

327 KB
Raw Blame
#!/usr/bin/env bash
# Install and verify Pixel's host-side ODS integration. Importing this file has
# no side effects. Callers must have already selected ENABLE_PIXEL_RUNTIME=true.

# Model reconciliation also imports this library directly from ods-host-agent.
# Keep the bundle pin and digest verifier available on that path.
# shellcheck source=installers/lib/pixel-integration.sh
source "$(dirname "${BASH_SOURCE[0]}")/pixel-integration.sh"

_ods_pixel_reconcile_workspace_guidance() {
    local owner="$1" home="$2" workspace="$3"
    local -a guidance_options=(--workspace "$workspace")
    [[ "${4:-live}" != generated ]] || guidance_options+=(--generated)
    ods_pixel_run_as_owner "$owner" "$home" /usr/bin/python3 -B \
        "${INSTALL_DIR:?}/installers/lib/pixel-workspace-guidance.py" "${guidance_options[@]}"
}

_ods_pixel_migrate_live_workspace_guidance() {
    local owner="$1" home="$2" pixel_log="$3" workspace_guidance_status
    if ! workspace_guidance_status="$(_ods_pixel_reconcile_workspace_guidance "$owner" "$home" "$home/.openclaw/workspace-pixel" 2>>"$pixel_log")"; then
        # Guidance repair is optional for an existing owner workspace. Preserve
        # unsafe/custom files and keep the verified runtime upgrade available.
        workspace_guidance_status='{"status":"manual-review-required"}'
    fi
    printf '%s\n' "$workspace_guidance_status" >>"$pixel_log"
    if [[ "$workspace_guidance_status" == *'"manual-review-required"'* ]]; then
        ai_warn "Portal preserved custom or unverified workspace guidance. Review AGENTS.md or MEMORY.md against your selected model route."
    fi
}

_ods_pixel_default_output_tokens() {
    # Shared usability default, not an assertion of provider output capacity.
    # Unknown model families remain usable; no model-name or reasoning policy.
    local context max_tokens
    [[ "$#" -eq 1 && "$1" =~ ^[0-9]{4,8}$ ]] || return 1
    context="$((10#$1))"
    (( context >= 4096 && context <= 10000000 )) || return 1
    max_tokens="$((context / 4))"
    (( max_tokens > 8192 )) && max_tokens=8192
    printf '%s\n' "$max_tokens"
}

_ods_pixel_gateway_port() {
    local port="${PIXEL_GATEWAY_PORT:-18789}"
    [[ "$port" =~ ^[1-9][0-9]{0,4}$ ]] || return 1
    (( 10#$port <= 65535 )) || return 1
    printf '%s\n' "$port"
}

# Pixel 4.3.27 renders the gateway port into its privileged systemd unit.
# Its same-release reconciliation transaction can update model/runtime JSON,
# but it cannot safely replace that unit. Refuse a port change before the ODS
# installer writes a new onboarding contract or marks the deployment installing.
_ods_pixel_installed_gateway_port() {
    local owner="$1" home="$2" installed_answers
    installed_answers="$home/.config/pixel-deployment/onboarding.json"
    if [[ ! -e "$installed_answers" && ! -L "$installed_answers" ]]; then
        return 1
    fi
    ods_pixel_run_as_owner "$owner" "$home" python3 - \
        "$installed_answers" <<'PY'
import json, os, pathlib, stat, sys

path = pathlib.Path(sys.argv[1])
info = path.lstat()
parent = path.parent.lstat()
if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
        or info.st_nlink != 1 or info.st_uid != os.getuid()
        or info.st_mode & 0o077 or info.st_size > 2 * 1024 * 1024
        or not stat.S_ISDIR(parent.st_mode) or stat.S_ISLNK(parent.st_mode)
        or parent.st_uid != os.getuid() or parent.st_mode & 0o022):
    raise SystemExit("unsafe installed Pixel onboarding contract")
value = json.loads(path.read_text(encoding="utf-8"))
port = value.get("gatewayPort") if isinstance(value, dict) else None
if type(port) is not int or not 1 <= port <= 65535:
    raise SystemExit("invalid installed Pixel gateway port")
print(port)
PY
}

_ods_pixel_existing_gateway_port_matches() {
    local owner="$1" home="$2" requested="$3" installed_answers existing
    [[ "$requested" =~ ^[1-9][0-9]{0,4}$ ]] || return 1
    (( 10#$requested <= 65535 )) || return 1
    installed_answers="$home/.config/pixel-deployment/onboarding.json"
    if [[ ! -e "$installed_answers" && ! -L "$installed_answers" ]]; then
        return 0
    fi
    existing="$(_ods_pixel_installed_gateway_port "$owner" "$home")" || return 1
    [[ "$existing" == "$requested" ]] || return 2
}

ods_pixel_install_owner() {
    local owner="${INSTALL_USER:-${SUDO_USER:-${USER:-}}}"
    [[ -n "$owner" && "$owner" != root && "$owner" =~ ^[A-Za-z_][A-Za-z0-9_.-]{0,63}$ ]] || {
        printf '%s\n' 'error: Pixel requires a non-root ODS install owner' >&2
        return 1
    }
    id "$owner" >/dev/null 2>&1 || return 1
    printf '%s\n' "$owner"
}

ods_pixel_owner_home() {
    local owner="$1" home
    [[ "$owner" =~ ^[A-Za-z_][A-Za-z0-9_.-]{0,63}$ ]] || return 1
    home="$(python3 - "$owner" <<'PY'
import pwd, sys
try:
    print(pwd.getpwnam(sys.argv[1]).pw_dir)
except KeyError:
    sys.exit(1)
PY
    )" || return 1
    [[ "$home" == /* && "$home" != / && "$home" != *[[:space:]\\]* && -d "$home" && ! -L "$home" ]] || return 1
    printf '%s\n' "$home"
}

ods_pixel_run_as_owner() {
    local owner="$1" home="$2" current_groups account_groups argv_json group refresh_command primary_group
    local -a refresh_groups=() group_order=()
    shift 2
    # The last group listed becomes the command's primary group (see below).
    primary_group="${ODS_PIXEL_OWNER_PRIMARY_GROUP:-docker}"
    case "$primary_group" in
        docker) group_order=(ods-pixel docker) ;;
        ods-pixel) group_order=(docker ods-pixel) ;;
        *)
            printf '%s\n' 'error: unsupported Pixel owner primary group' >&2
            return 1
            ;;
    esac
    # A redundant sudo -u of the already-current owner can allocate a fresh
    # pseudo-terminal (sudoers use_pty). Pixel's child installers then lose
    # the authenticated parent tty and prompt for sudo mid-install/update.
    if [[ "$(id -un)" == "$owner" ]]; then
        current_groups=" $(id -nG) "
        account_groups=" $(id -nG "$owner") "
        for group in "${group_order[@]}"; do
            if [[ "$current_groups" != *" $group "* && "$account_groups" == *" $group "* ]]; then
                refresh_groups+=("$group")
            fi
        done
        if (( ${#refresh_groups[@]} > 0 )); then
            # A requested group already present as the primary group can be
            # lost when sg refreshes another missing group. Reapply it last
            # even when it did not itself need refreshing.
            if [[ "$account_groups" == *" $primary_group "* \
                && "${refresh_groups[${#refresh_groups[@]}-1]}" != "$primary_group" ]]; then
                refresh_groups+=("$primary_group")
            fi
            # A first install may have just granted Docker and Pixel socket
            # access. Refresh each missing runtime group with nested sg rather
            # than another sudo pseudo-terminal. The innermost sg sets the
            # primary group. shadow's sg also keeps the outer groups, but
            # util-linux sg (Ubuntu 26.04) only replaces the primary group, so
            # the innermost one is the only group sure to survive. Owner
            # commands need Docker there; only the root-owned inspection socket
            # needs ods-pixel, and its caller asks for it.
            # Caller arguments remain JSON in the environment, never shell code.
            if ! command -v sg >/dev/null 2>&1 \
                || ! command -v python3 >/dev/null 2>&1; then
                printf '%s\n' 'error: runtime group refresh requires sg and python3' >&2
                return 1
            fi
            argv_json="$(python3 -c 'import json,sys; print(json.dumps(sys.argv[1:]))' "$@")" || return 1
            refresh_command="$(python3 - "${refresh_groups[@]:1}" <<'PY'
import shlex, sys
decoder = 'import json,os; argv=json.loads(os.environ.pop("ODS_PIXEL_OWNER_ARGV_JSON")); os.execvpe(argv[0],argv,os.environ)'
command = 'exec python3 -c ' + shlex.quote(decoder)
for group in reversed(sys.argv[1:]):
    command = 'exec sg ' + shlex.quote(group) + ' -c ' + shlex.quote(command)
print(command)
PY
            )" || return 1
            HOME="$home" USER="$owner" LOGNAME="$owner" PATH="$PATH" \
                ODS_PIXEL_OWNER_ARGV_JSON="$argv_json" sg "${refresh_groups[0]}" -c "$refresh_command"
        else
            env HOME="$home" USER="$owner" LOGNAME="$owner" PATH="$PATH" "$@"
        fi
    elif ods_sudo_available && command -v sudo >/dev/null 2>&1; then
        ods_sudo -u "$owner" -- env HOME="$home" USER="$owner" LOGNAME="$owner" PATH="$PATH" "$@"
    else
        printf '%s\n' 'error: cannot enter the Pixel install owner identity' >&2
        return 1
    fi
}

ods_pixel_check_owner_docker() {
    local owner home status
    owner="${PIXEL_SERVICE_USER:-$(ods_pixel_install_owner)}" || {
        ai_bad "Could not determine the Pixel install owner for the Docker check."
        return 1
    }
    home="$(ods_pixel_owner_home "$owner")" || {
        ai_bad "Could not resolve the home directory for Pixel owner '$owner'."
        return 1
    }
    ai "Checking Docker access as Pixel owner '$owner'..."
    # Pixel bootstrap uses plain Docker as this owner, even when the ODS core
    # can proceed via sudo docker. Reuse its group refresh and environment.
    # Discard info's potentially sensitive stdout, but keep the actual error
    # visible rather than interpreting every failure as a socket permission.
    if ods_pixel_run_as_owner "$owner" "$home" docker info >/dev/null; then
        return 0
    else
        status=$?
    fi
    ai_bad "Pixel's Docker access check failed for '$owner' (exit $status); see the error above."
    ai_warn "As '$owner', run 'docker info >/dev/null' without sudo and resolve the reported error before retrying with the same install options."
    ai_warn "Recovery: https://github.com/Osmantic/ODS/blob/main/ods/docs/TROUBLESHOOTING.md#pixel-cannot-access-docker"
    return "$status"
}

# Resolve Pixel search before phase 03 chooses Compose services. Use the same
# owner-private onboarding selector as phase 11, and the explicit > installed
# .env precedence that phase 06 applies. Never source .env as shell code.
ods_pixel_resolve_search_provider() {
    local requested="${PIXEL_WEB_SEARCH_PROVIDER:-}" raw owner home answers helper resolved
    [[ -n "${INSTALL_DIR:-}" && -n "${SCRIPT_DIR:-}" ]] || return 1
    if [[ -z "$requested" && -f "$INSTALL_DIR/.env" ]]; then
        if ! declare -F safe_env_decode_value >/dev/null 2>&1; then
            # shellcheck source=../../lib/safe-env.sh
            source "$SCRIPT_DIR/lib/safe-env.sh"
        fi
        raw="$(grep -m1 '^PIXEL_WEB_SEARCH_PROVIDER=' "$INSTALL_DIR/.env" 2>/dev/null | cut -d= -f2- || true)"
        requested="$(safe_env_decode_value "$raw")"
    fi
    case "$requested" in
        ""|searxng|parallel-free) ;;
        *) printf '%s\n' 'error: invalid Pixel web search provider' >&2; return 1 ;;
    esac
    owner="${PIXEL_SERVICE_USER:-$(ods_pixel_install_owner)}" || return 1
    home="$(ods_pixel_owner_home "$owner")" || return 1
    answers="$INSTALL_DIR/data/pixel/onboarding.json"
    helper="$SCRIPT_DIR/extensions/services/pixel-agent/host/native_search.py"
    [[ -f "$helper" ]] || return 1
    resolved="$(ods_pixel_run_as_owner "$owner" "$home" python3 "$helper" \
        --answers-file "$answers" --provider "$requested")" || return 1
    case "$resolved" in
        searxng|parallel-free) printf '%s\n' "$resolved" ;;
        *) printf '%s\n' 'error: Pixel search selector returned an invalid provider' >&2; return 1 ;;
    esac
}

ods_pixel_run_as_owner_with_umask() {
    local owner="$1" home="$2" requested_umask="$3"
    shift 3
    [[ "$requested_umask" =~ ^0[0-7]{3}$ && "$#" -gt 0 ]] || return 1

    # Set the mask inside the target owner's process. sudo may apply its own
    # configured umask, so a caller-side subshell is not sufficient.
    ods_pixel_run_as_owner "$owner" "$home" sh -c '
        requested_umask=$1
        shift
        umask "$requested_umask"
        exec "$@"
    ' sh "$requested_umask" "$@"
}

_ods_pixel_prepare_attempt_log() {
    local owner="$1" home="$2" path="$3" parent temporary parent_kind parent_uid
    [[ "$path" == /* && "$path" != / && "$path" != *$'\n'* && "$path" != *$'\r'* ]] || return 1
    parent="${path%/*}"
    if [[ -e "$parent" || -L "$parent" ]]; then
        [[ -d "$parent" && ! -L "$parent" ]] || return 1
        parent_kind="$(stat -c '%F' -- "$parent")" || return 1
        parent_uid="$(stat -c '%u' -- "$parent")" || return 1
        [[ "$parent_kind" == directory && "$parent_uid" == "$(id -u "$owner")" ]] || return 1
    else
        ods_pixel_run_as_owner "$owner" "$home" install -d -m 0700 -- "$parent" || return 1
    fi
    temporary="$(ods_pixel_run_as_owner "$owner" "$home" mktemp "$parent/.pixel-install.XXXXXX")" || return 1
    [[ "$temporary" == "$parent"/.pixel-install.* && -f "$temporary" && ! -L "$temporary" ]] || {
        if [[ -n "$temporary" ]]; then
            ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$temporary" >/dev/null 2>&1 || true
        fi
        return 1
    }
    if ! ods_pixel_run_as_owner "$owner" "$home" chmod 0600 "$temporary" \
        || ! ods_pixel_run_as_owner "$owner" "$home" mv -fT -- "$temporary" "$path"; then
        ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$temporary" >/dev/null 2>&1 || true
        return 1
    fi
    printf '%s\n' "$path"
}

_ods_pixel_assert_managed_state() {
    local owner="$1" home="$2" marker marker_dir pixel_install
    marker="$home/.config/ods/pixel-managed.json"
    marker_dir="${marker%/*}"
    pixel_install="$home/.local/share/pixel"
    local gateway_unit="${ODS_PIXEL_GATEWAY_UNIT_PATH:-/etc/systemd/system/openclaw-gateway.service}"
    local config_dir="${marker_dir%/*}"
    # The access coordinator trusts the marker only when ~/.config is owned by
    # the owner and not writable by others (model-marker-unsafe otherwise).
    # The installer runs as the owner with Ubuntu's default umask 0002, which
    # would create ~/.config as 0775, and other tools may have done the same.
    if [[ -e "$config_dir" || -L "$config_dir" ]]; then
        [[ -d "$config_dir" && ! -L "$config_dir" ]] || return 1
        [[ "$(stat -c '%u' -- "$config_dir")" == "$(id -u "$owner")" ]] || return 1
        if (( (8#$(stat -c '%a' -- "$config_dir") & 0022) != 0 )); then
            ods_pixel_run_as_owner "$owner" "$home" chmod go-w -- "$config_dir" || return 1
        fi
    else
        ods_pixel_run_as_owner "$owner" "$home" install -d -m 0755 -- "$config_dir" || return 1
    fi
    if [[ -e "$marker_dir" || -L "$marker_dir" ]]; then
        [[ -d "$marker_dir" && ! -L "$marker_dir" ]] || return 1
        [[ "$(stat -c '%u' -- "$marker_dir")" == "$(id -u "$owner")" ]] || return 1
        ods_pixel_run_as_owner "$owner" "$home" chmod 0700 "$marker_dir" || return 1
    else
        ods_pixel_run_as_owner "$owner" "$home" install -d -m 0700 -- "$marker_dir" || return 1
    fi
    if [[ -e "$marker" || -L "$marker" ]]; then
        [[ -f "$marker" && ! -L "$marker" ]] || return 1
        [[ "$(stat -c '%u' -- "$marker")" == "$(id -u "$owner")" ]] || return 1
        (( (8#$(stat -c '%a' -- "$marker") & 0077) == 0 )) || return 1
        ods_pixel_run_as_owner "$owner" "$home" python3 - "$marker" "${INSTALL_DIR:?}" <<'PY'
import json, pathlib, sys
value = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8"))
if (value.get("schema_version") not in {1, 2} or value.get("manager") != "ods"
        or value.get("install_dir") != sys.argv[2]):
    raise SystemExit("Pixel management marker does not match this ODS install")
if value.get("schema_version") == 2 and value.get("initial_active_state") != "absent":
    raise SystemExit("Pixel management marker has no safe pre-install state")
PY
        return
    fi

    # Never adopt or rewrite an ambient user-managed Pixel/OpenClaw deployment.
    for existing in \
        "$home/.openclaw/openclaw.json" \
        "$home/.config/pixel-agent/gateway.env" \
        "$home/.config/pixel-deployment/onboarding.json" \
        "$pixel_install/current" \
        "$pixel_install/runtime-attestation.json" \
        "$gateway_unit"; do
        if [[ -e "$existing" || -L "$existing" ]]; then
            ai_bad "An existing non-ODS Pixel/OpenClaw deployment was found. ODS will not overwrite it."
            return 1
        fi
    done

    ods_pixel_run_as_owner "$owner" "$home" python3 - "$marker" "${INSTALL_DIR:?}" "${PIXEL_SOURCE_REF:?}" <<'PY'
import json, os, pathlib, sys, tempfile
path = pathlib.Path(sys.argv[1])
payload = json.dumps({
    "schema_version": 2,
    "manager": "ods",
    "state": "installing",
    "initial_active_state": "absent",
    "install_dir": sys.argv[2],
    "pixel_source_ref": sys.argv[3],
}, indent=2, sort_keys=True) + "\n"
fd, temporary = tempfile.mkstemp(prefix=".pixel-managed.", dir=path.parent)
try:
    with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
        handle.write(payload)
        handle.flush()
        os.fsync(handle.fileno())
    os.chmod(temporary, 0o600)
    os.replace(temporary, path)
finally:
    if os.path.exists(temporary):
        os.unlink(temporary)
PY
}

_ods_pixel_source_transition_state() {
    local owner="$1" home="$2" requested_ref="$3" marker
    marker="$home/.config/ods/pixel-managed.json"
    [[ "$requested_ref" =~ ^[0-9a-f]{40}$ ]] || return 2
    if [[ ! -e "$marker" && ! -L "$marker" ]]; then
        return 1
    fi
    ods_pixel_run_as_owner "$owner" "$home" python3 - \
        "$marker" "${INSTALL_DIR:?}" "$requested_ref" <<'PY'
import json, os, pathlib, re, stat, sys

path = pathlib.Path(sys.argv[1])
info = path.lstat()
if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
        or info.st_nlink != 1 or info.st_uid != os.getuid()
        or info.st_mode & 0o077 or info.st_size > 65536):
    raise SystemExit(2)
value = json.loads(path.read_text(encoding="utf-8"))
source_ref = value.get("pixel_source_ref")
requested_ref = sys.argv[3]
state = value.get("state")
if (value.get("schema_version") != 2 or value.get("manager") != "ods"
        or value.get("initial_active_state") != "absent"
        or value.get("install_dir") != sys.argv[2]
        or state not in {"ready", "installing", "deactivating"}
        or not isinstance(source_ref, str)
        or not re.fullmatch(r"[0-9a-f]{40}", source_ref)
        or value.get("requested_source_ref") not in {None, source_ref, requested_ref}):
    raise SystemExit(2)
print(f"{state}|{source_ref}")
PY
}

# An exact inert initial bootstrap has no deployed authority baseline to hold.
# Recheck the same evidence before reconciling its ordinary source copy.
_ods_pixel_initial_source_copy_allowed() {
    local owner="$1" home="$2" requested_ref="$3" transition
    transition="$(_ods_pixel_source_transition_state "$owner" "$home" "$requested_ref")" || return 1
    [[ "$transition" == "installing|$requested_ref" \
        && ! -e /var/lib/ods-pixel-access && ! -L /var/lib/ods-pixel-access \
        && ! -e /etc/ods/pixel-access.json && ! -L /etc/ods/pixel-access.json \
        && ! -e /usr/local/libexec/ods-pixel-access && ! -L /usr/local/libexec/ods-pixel-access \
        && ! -e /etc/systemd/system/openclaw-gateway.service \
        && ! -L /etc/systemd/system/openclaw-gateway.service ]] \
        && PIXEL_SOURCE_REF="$requested_ref" _ods_pixel_initial_unconfigured_marker "$owner" "$home" \
            "$INSTALL_DIR/data/pixel/source-$requested_ref"
}

# Return 0 when an exact ODS-managed Pixel deployment needs a held transaction
# before the installer copies source over its installed ownership evidence.
# Return 1 when no transition is needed, and 2 for unsafe or ambiguous state.
_ods_pixel_source_transition_required() {
    local owner="$1" home="$2" requested_ref="$3" transition state source_ref
    transition="$(_ods_pixel_source_transition_state "$owner" "$home" "$requested_ref")" || return 2
    IFS='|' read -r state source_ref <<<"$transition"
    [[ "$state" =~ ^(ready|installing|deactivating)$ \
        && "$source_ref" =~ ^[0-9a-f]{40}$ ]] || return 2
    [[ "$state" == deactivating || "$source_ref" != "$requested_ref" ]] && return 0
    # An interrupted bootstrap has not installed a release or access
    # coordinator yet. There is no authority baseline to migrate. Keep the
    # ordinary source-copy path only for the exact inert initial state.
    if [[ "$state" == installing ]] \
        && _ods_pixel_initial_source_copy_allowed "$owner" "$home" "$requested_ref"; then
        return 1
    fi
    # The Pixel pin alone does not identify the ODS host integration. Preserve
    # its installed source until cleanup can validate privileged mirrors, even
    # when an upgrade retains the same developer Pixel checkout.
    local incoming_root="${4:-}" relative comparison
    [[ "${_ODS_PIXEL_FEATURE_SOURCE_CHANGED:-false}" == true ]] && return 0
    [[ -n "$incoming_root" ]] || return 1
    for relative in installers/lib/pixel-host-install.sh bin \
        extensions/services/pixel-agent/host extensions/services/pixel-agent/plugin; do
        [[ -e "${INSTALL_DIR:?}/$relative" && ! -L "$INSTALL_DIR/$relative" \
            && -e "$incoming_root/$relative" && ! -L "$incoming_root/$relative" ]] || return 2
        comparison=0
        diff -qr --exclude=__pycache__ -- "$INSTALL_DIR/$relative" \
            "$incoming_root/$relative" >/dev/null 2>&1 || comparison=$?
        case "$comparison" in
            0) ;;
            1) return 0 ;;
            *) return 2 ;;
        esac
    done
    return 1
}

# Local installer-only custody operations. The root helper validates the real
# install/owner and protected coordinator; the environment handle is merely a
# convenience and never the authority to write files or release admission.
_ods_pixel_source_upgrade() {
    local action="$1" owner="$2"
    shift 2
    # These custody operations are mandatory. ods_sudo intentionally returns
    # success when skipping optional privileged tasks; that is not a valid
    # stage/status/hold response and must never authorize an upgrade step.
    if [[ ${EUID:-$(id -u)} -ne 0 && "${ODS_SUDO_AVAILABLE:-true}" == false ]]; then
        printf '%s\n' 'error: source-upgrade-sudo-required: Pixel source upgrade requires sudo. Preserve the existing installation and any pending upgrade state.' >&2
        return 1
    fi
    local helper="${SCRIPT_DIR:?}/bin/pixel_source_upgrade.py"
    if [[ ! -f "$helper" || -L "$helper" ]]; then
        printf '%s\n' 'error: source-upgrade-helper-unavailable: The reviewed Pixel source upgrade helper is missing or unsafe.' >&2
        return 1
    fi
    ods_sudo python3 -I "$helper" "$action" "${INSTALL_DIR:?}" "$owner" "$@"
}

_ods_pixel_check_source_transaction() {
    local owner="$1" result
    [[ "${ODS_PIXEL_SOURCE_TRANSACTION:-}" =~ ^[a-f0-9]{64}$ ]] || return 1
    result="$(_ods_pixel_source_upgrade status "$owner")" || return 1
    printf '%s' "$result" | python3 -c 'import json,sys; d=json.load(sys.stdin); sys.exit(0 if d.get("pending") is True and d.get("transaction")==sys.argv[1] and d.get("phase")=="applied" and d.get("mode") in ("sandboxed","full-access") else 1)' "$ODS_PIXEL_SOURCE_TRANSACTION"
}

# A failed test or operator cleanup can remove the ODS checkout while leaving
# an interrupted, marker-bound Pixel host deployment. Reconstruct only the
# marker's exact prior commit from the currently authorized source repository
# before the uninstaller uses those bytes to authenticate privileged artifacts.
_ods_pixel_restore_transition_source() {
    local owner="$1" home="$2" requested_ref="$3" transition state source_ref source_root source_url
    transition="$(_ods_pixel_source_transition_state "$owner" "$home" "$requested_ref")" || return 1
    IFS='|' read -r state source_ref <<<"$transition"
    [[ "$state" =~ ^(ready|installing|deactivating)$ \
        && "$source_ref" =~ ^[0-9a-f]{40}$ ]] || return 1
    source_root="${INSTALL_DIR:?}/data/pixel/source-$source_ref"
    # Retirement must verify the source that actually installed the old
    # deployment. Prefer its existing checkout; never fetch a retired private
    # source or try to obtain its ref from the new one-commit ODS bundle.
    if [[ -d "$source_root/.git" && ! -L "$source_root" && ! -L "$source_root/.git" ]]; then
        source_url="$source_root"
    elif [[ "${PIXEL_SOURCE_URL:-}" == /* ]]; then
        # Developer checkouts may still reconstruct an ancestor from a local
        # repository. This path remains file-only inside _source_checkout.
        source_url="$PIXEL_SOURCE_URL"
    elif [[ "${PIXEL_SOURCE_URL:-}" == bundled && "$source_ref" == "$ODS_PIXEL_BUNDLED_REF" ]]; then
        source_url=bundled
    else
        printf '%s\n' 'error: prior Pixel source checkout is missing; restore its local backup before retrying' >&2
        return 1
    fi
    local PIXEL_SOURCE_URL="$source_url" PIXEL_SOURCE_REF="$source_ref"
    _ods_pixel_source_checkout "$owner" "$home" "$source_root" >/dev/null || return 1
    printf '%s\n' "$source_root"
}

_ods_pixel_record_verified_state() {
    local owner="$1" home="$2" contract_sha256="$3" state="$4" pixel_root="$5"
    local marker config manifest sandbox_image sandbox_image_id
    [[ "$contract_sha256" =~ ^[0-9a-f]{64}$ ]] || return 1
    [[ "$state" == installing || "$state" == ready ]] || return 1
    marker="$home/.config/ods/pixel-managed.json"
    config="$home/.openclaw/openclaw.json"
    manifest="$pixel_root/RELEASE-MANIFEST.json"
    sandbox_image="$(ods_pixel_run_as_owner "$owner" "$home" python3 - "$manifest" <<'PY'
import json, pathlib, re, sys
path = pathlib.Path(sys.argv[1])
value = json.loads(path.read_text(encoding="utf-8"))
image = value.get("sandboxImage") if isinstance(value, dict) else None
if not isinstance(image, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._/-]{0,255}:[A-Za-z0-9][A-Za-z0-9._-]{0,127}", image):
    raise SystemExit("invalid Pixel sandbox image reference")
print(image)
PY
)" || return 1
    sandbox_image_id="$(ods_pixel_run_as_owner "$owner" "$home" timeout 30s docker image inspect \
        --format '{{.Id}}' "$sandbox_image")" || return 1
    [[ "$sandbox_image_id" =~ ^sha256:[0-9a-f]{64}$ ]] || return 1
    ods_pixel_run_as_owner "$owner" "$home" python3 - \
        "$marker" "$config" "${INSTALL_DIR:?}" "${PIXEL_SOURCE_REF:?}" \
        "$contract_sha256" "$state" "$home" "$sandbox_image" "$sandbox_image_id" <<'PY'
import hashlib, json, os, pathlib, stat, sys, tempfile

path = pathlib.Path(sys.argv[1])
info = path.lstat()
if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_nlink != 1
        or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_size > 65536):
    raise SystemExit("invalid Pixel management marker")
value = json.loads(path.read_text(encoding="utf-8"))
if (value.get("schema_version") != 2 or value.get("manager") != "ods"
        or value.get("install_dir") != sys.argv[3]
        or value.get("initial_active_state") != "absent"):
    raise SystemExit("Pixel management marker does not match this ODS install")
if value.get("requested_source_ref") not in {None, sys.argv[4]}:
    raise SystemExit("Pixel management marker requested source does not match the verified source")
config_path = pathlib.Path(sys.argv[2])
config_info = config_path.lstat()
if (not stat.S_ISREG(config_info.st_mode) or stat.S_ISLNK(config_info.st_mode)
        or config_info.st_uid != os.getuid() or config_info.st_mode & 0o077
        or config_info.st_size > 2 * 1024 * 1024):
    raise SystemExit("invalid ODS-managed OpenClaw configuration")
config = json.loads(config_path.read_text(encoding="utf-8"))
if not isinstance(config, dict):
    raise SystemExit("invalid ODS-managed OpenClaw configuration")
canonical_config = json.dumps(config, sort_keys=True, separators=(",", ":")).encode()
if sys.argv[6] not in {"installing", "ready"}:
    raise SystemExit("invalid Pixel management state")

home = pathlib.Path(sys.argv[7])
install_root = home / ".local/share/pixel"
releases_root = install_root / "releases"
current = install_root / "current"
current_info = current.lstat()
if not stat.S_ISLNK(current_info.st_mode) or current_info.st_uid != os.getuid():
    raise SystemExit("invalid active Pixel release link")
release = current.resolve(strict=True)
releases_info = releases_root.lstat()
release_info = release.lstat()
if (not stat.S_ISDIR(releases_info.st_mode) or stat.S_ISLNK(releases_info.st_mode)
        or releases_info.st_uid != os.getuid() or releases_info.st_mode & 0o022
        or not stat.S_ISDIR(release_info.st_mode) or stat.S_ISLNK(release_info.st_mode)
        or release_info.st_uid != os.getuid() or release_info.st_mode & 0o022
        or release.parent.resolve(strict=True) != releases_root.resolve(strict=True)):
    raise SystemExit("active Pixel release is outside its release root")

def regular_file(item: pathlib.Path, maximum: int, private: bool = False) -> bytes:
    details = item.lstat()
    if (not stat.S_ISREG(details.st_mode) or stat.S_ISLNK(details.st_mode)
            or details.st_uid != os.getuid() or details.st_nlink != 1
            or details.st_size > maximum or details.st_mode & 0o022
            or (private and details.st_mode & 0o077)):
        raise SystemExit(f"unsafe verified Pixel artifact: {item}")
    return item.read_bytes()

identity_bytes = regular_file(release / "release-identity.json", 65536)
manifest_bytes = regular_file(release / "install-manifest.sha256", 2 * 1024 * 1024)
attestation_bytes = regular_file(install_root / "runtime-attestation.json", 2 * 1024 * 1024, private=True)
identity = json.loads(identity_bytes)
attestation = json.loads(attestation_bytes)
version = identity.get("pixel") if isinstance(identity, dict) else None
source = identity.get("source") if isinstance(identity, dict) else None
if (not isinstance(version, str) or release.name != version
        or not isinstance(source, dict) or source.get("state") != "git-clean"
        or source.get("commit") != sys.argv[4]):
    raise SystemExit("active Pixel release is not bound to the configured source")
identity_sha256 = hashlib.sha256(identity_bytes).hexdigest()
manifest_sha256 = hashlib.sha256(manifest_bytes).hexdigest()
if (not isinstance(attestation, dict) or attestation.get("kind") != "pixel-runtime-attestation"
        or attestation.get("status") not in {"verified", "limited"}
        or attestation.get("pixel") != version or attestation.get("source") != source
        or not isinstance(attestation.get("release"), dict)
        or attestation["release"].get("sourceIdentitySha256") != identity_sha256
        or attestation["release"].get("installManifestSha256") != manifest_sha256):
    raise SystemExit("Pixel runtime attestation does not bind the active release")
if not isinstance(sys.argv[8], str) or not isinstance(sys.argv[9], str):
    raise SystemExit("invalid Pixel sandbox binding")

value["state"] = sys.argv[6]
value["pixel_source_ref"] = sys.argv[4]
value.pop("requested_source_ref", None)
value.pop("requested_contract_sha256", None)
value["contract_sha256"] = sys.argv[5]
value["configuration_sha256"] = hashlib.sha256(b"ods-pixel-openclaw-v1\0" + canonical_config).hexdigest()
value["active_release_version"] = version
value["release_identity_sha256"] = identity_sha256
value["install_manifest_sha256"] = manifest_sha256
value["sandbox_image"] = sys.argv[8]
value["sandbox_image_id"] = sys.argv[9]
fd, temporary = tempfile.mkstemp(prefix=".pixel-managed.", dir=path.parent)
try:
    with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
        json.dump(value, handle, indent=2, sort_keys=True)
        handle.write("\n")
        handle.flush()
        os.fsync(handle.fileno())
    os.chmod(temporary, 0o600)
    os.replace(temporary, path)
finally:
    if os.path.exists(temporary):
        os.unlink(temporary)
PY
}

_ods_pixel_mark_verified_installing() {
    _ods_pixel_record_verified_state "$1" "$2" "$3" installing "$4"
}

_ods_pixel_mark_ready() {
    _ods_pixel_record_verified_state "$1" "$2" "$3" ready "$4"
}

_ods_pixel_contract_sha256() {
    local owner="$1" home="$2" answers="$3"
    local extension_catalog="${INSTALL_DIR:?}/data/pixel/extension-catalog.json"
    local extension_helper="${INSTALL_DIR:?}/extensions/services/pixel-agent/host/extension_search.py"
    local extension_manager="${INSTALL_DIR:?}/extensions/services/pixel-agent/host/extension_manager.py"
    local extension_manager_unit="${INSTALL_DIR:?}/data/pixel/extension-manager.service"
    local artifact_promoter="${INSTALL_DIR:?}/extensions/services/pixel-agent/host/artifact_promoter.py"
    local artifact_promoter_unit="${INSTALL_DIR:?}/data/pixel/artifact-promoter.service"
    local workspace_preview="${INSTALL_DIR:?}/extensions/services/pixel-agent/host/workspace_preview.py"
    local workspace_preview_unit="${INSTALL_DIR:?}/data/pixel/workspace-preview.service"
    local system_observer="${INSTALL_DIR:?}/extensions/services/pixel-agent/host/system_observe.py"
    local operations_service_dropin="${INSTALL_DIR:?}/extensions/services/pixel-agent/host/pixel-ops-broker-ods.conf"
    local approval_helper="${INSTALL_DIR:?}/bin/ods-pixel-approve"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$answers" "$extension_catalog" \
        "$extension_helper" "$extension_manager" "$extension_manager_unit" "$approval_helper" \
        "$artifact_promoter" "$artifact_promoter_unit" "$operations_service_dropin" \
        "$workspace_preview" "$workspace_preview_unit" "$system_observer" <<'PY'
import hashlib, json, os, pathlib, stat, sys

path, catalog_path, helper_path, manager_path, manager_unit_path, approval_path, promoter_path, promoter_unit_path, operations_service_dropin_path, preview_path, preview_unit_path, system_observer_path = map(pathlib.Path, sys.argv[1:13])

def read_private_regular(candidate, label):
    info = candidate.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_uid != os.getuid() or info.st_mode & 0o077
            or info.st_size > 2 * 1024 * 1024):
        raise SystemExit(f"invalid ODS Pixel {label}")
    return candidate.read_bytes()

answers_payload = read_private_regular(path, "onboarding contract")
try:
    answers_value = json.loads(answers_payload)
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
    raise SystemExit("invalid ODS Pixel onboarding contract") from exc
policy_value = answers_value.get("operationsPolicyFile") if isinstance(answers_value, dict) else None
expected_policy = path.parent / "operations-policy.json"
if not isinstance(policy_value, str) or pathlib.Path(policy_value) != expected_policy:
    raise SystemExit("ODS Pixel Operations policy is outside the managed contract")
policy_payload = read_private_regular(expected_policy, "Operations policy")
catalog_payload = read_private_regular(catalog_path, "extension catalog")
helper_payloads = []
inspection_sources = tuple(preview_path.with_name(name) for name in (
    'preview_inspection.py', 'preview_inspection_protocol.py', 'preview_inspection_capsule.py',
    'Dockerfile.inspection', 'preview-inspection.requirements.lock', 'pixel-preview-inspection.service'))
if not any(source.exists() or source.is_symlink() for source in inspection_sources):
    inspection_sources = ()  # Older complete deployments remain removable.
for helper in (helper_path, manager_path, manager_unit_path, approval_path, promoter_path, promoter_unit_path, operations_service_dropin_path, preview_path, preview_unit_path, system_observer_path, preview_path.with_name("unix_peer.py"), *inspection_sources):
    helper_info = helper.lstat()
    if (not stat.S_ISREG(helper_info.st_mode) or stat.S_ISLNK(helper_info.st_mode)
            or helper_info.st_nlink != 1 or helper_info.st_uid != os.getuid()
            or helper_info.st_mode & 0o022 or helper_info.st_size > 2 * 1024 * 1024):
        raise SystemExit("invalid ODS Pixel extension helper")
    helper_payloads.append(helper.read_bytes())
digest = hashlib.sha256()
digest.update(b"ods-pixel-contract-v10\0")
for payload in (answers_payload, policy_payload, catalog_payload, *helper_payloads):
    digest.update(len(payload).to_bytes(8, "big"))
    digest.update(payload)
print(digest.hexdigest())
PY
}

_ods_pixel_verify_operations_policy_custody() {
    local owner="$1" home="$2" source_policy="$3"
    local installed_policy="${4:-/etc/pixel-ops-broker/policy.json}" expected_uid="${5:-0}"
    local metadata kind uid mode size
    [[ "$source_policy" == /* && "$installed_policy" == /* && "$expected_uid" =~ ^[0-9]+$ ]] || return 1
    ods_pixel_run_as_owner "$owner" "$home" test -f "$source_policy" || return 1
    ods_pixel_run_as_owner "$owner" "$home" test ! -L "$source_policy" || return 1
    metadata="$(ods_sudo stat -c '%F|%u|%a|%s' -- "$installed_policy")" || return 1
    IFS='|' read -r kind uid mode size <<<"$metadata"
    [[ "$kind" == "regular file" && "$uid" == "$expected_uid" && "$mode" == 640
        && "$size" =~ ^[0-9]+$ && "$size" -le 2097152 ]] || return 1
    ods_sudo cmp -s -- "$source_policy" "$installed_policy"
}

_ods_pixel_harden_operations_state_profiles() {
    local state_root="${1:-/var/lib/pixel-ops-broker}"
    local broker_user="${2:-pixel-ops-broker}" broker_uid broker_gid
    [[ "$state_root" == /* && "$state_root" != / \
        && "$broker_user" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || return 1
    broker_uid="$(ods_sudo id -u "$broker_user")" || return 1
    broker_gid="$(ods_sudo id -g "$broker_user")" || return 1
    [[ "$broker_uid" =~ ^[0-9]+$ && "$broker_gid" =~ ^[0-9]+$ ]] || return 1
    ods_sudo python3 - "$state_root" "$broker_uid" "$broker_gid" <<'PY'
import os
import pathlib
import stat
import sys

root = pathlib.Path(sys.argv[1])
uid = int(sys.argv[2])
gid = int(sys.argv[3])
root_info = root.lstat()
if (not stat.S_ISDIR(root_info.st_mode) or stat.S_ISLNK(root_info.st_mode)
        or root_info.st_uid != uid or root_info.st_gid != gid
        or stat.S_IMODE(root_info.st_mode) != 0o750):
    raise SystemExit("unsafe Pixel Operations state root")

profiles = [root / name for name in (".bash_logout", ".bashrc", ".profile")]
present = []
for path in profiles:
    if not path.exists() and not path.is_symlink():
        continue
    info = path.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_nlink != 1 or info.st_uid != uid or info.st_gid != gid
            or stat.S_IMODE(info.st_mode) not in {0o600, 0o640, 0o644}
            or info.st_size > 64 * 1024):
        raise SystemExit(f"unsafe Pixel Operations service profile: {path}")
    present.append(path)

# Validate the complete bounded set before changing any mode.
for path in present:
    os.chmod(path, 0o600, follow_symlinks=False)
for path in present:
    if stat.S_IMODE(path.lstat().st_mode) != 0o600:
        raise SystemExit(f"could not harden Pixel Operations service profile: {path}")
PY
}

_ods_pixel_managed_contract_matches() {
    local owner="$1" home="$2" contract_sha256="$3" marker config
    [[ "$contract_sha256" =~ ^[0-9a-f]{64}$ ]] || return 1
    marker="$home/.config/ods/pixel-managed.json"
    config="$home/.openclaw/openclaw.json"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$marker" "$config" "${INSTALL_DIR:?}" "${PIXEL_SOURCE_REF:?}" "$contract_sha256" <<'PY'
import hashlib, json, os, pathlib, stat, sys

path = pathlib.Path(sys.argv[1])
info = path.lstat()
if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_uid != os.getuid()
        or info.st_size > 65536 or info.st_mode & 0o077):
    raise SystemExit(1)
value = json.loads(path.read_text(encoding="utf-8"))
expected = {
    "schema_version": 2,
    "manager": "ods",
    "initial_active_state": "absent",
    "install_dir": sys.argv[3],
    "pixel_source_ref": sys.argv[4],
    "contract_sha256": sys.argv[5],
}
if value.get("state") not in {"ready", "installing"} or any(value.get(key) != item for key, item in expected.items()):
    raise SystemExit(1)
config_path = pathlib.Path(sys.argv[2])
config_info = config_path.lstat()
if (not stat.S_ISREG(config_info.st_mode) or stat.S_ISLNK(config_info.st_mode)
        or config_info.st_uid != os.getuid() or config_info.st_mode & 0o077
        or config_info.st_size > 2 * 1024 * 1024):
    raise SystemExit(1)
config = json.loads(config_path.read_text(encoding="utf-8"))
if not isinstance(config, dict):
    raise SystemExit(1)
canonical_config = json.dumps(config, sort_keys=True, separators=(",", ":")).encode()
observed = hashlib.sha256(b"ods-pixel-openclaw-v1\0" + canonical_config).hexdigest()
if value.get("configuration_sha256") != observed:
    raise SystemExit(1)
for key in ("release_identity_sha256", "install_manifest_sha256"):
    item = value.get(key)
    if not isinstance(item, str) or len(item) != 64 or any(ch not in "0123456789abcdef" for ch in item):
        raise SystemExit(1)
if (not isinstance(value.get("active_release_version"), str)
        or not isinstance(value.get("sandbox_image"), str)
        or not isinstance(value.get("sandbox_image_id"), str)
        or len(value["sandbox_image_id"]) != 71 or not value["sandbox_image_id"].startswith("sha256:")
        or any(ch not in "0123456789abcdef" for ch in value["sandbox_image_id"][7:])):
    raise SystemExit(1)
PY
}

_ods_pixel_verified_source_matches() {
    local owner="$1" home="$2" marker
    marker="$home/.config/ods/pixel-managed.json"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$marker" "${INSTALL_DIR:?}" "${PIXEL_SOURCE_REF:?}" <<'PY'
import json, os, pathlib, stat, sys

path = pathlib.Path(sys.argv[1])
info = path.lstat()
if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
        or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_size > 65536):
    raise SystemExit(1)
value = json.loads(path.read_text(encoding="utf-8"))
if (value.get("schema_version") != 2 or value.get("manager") != "ods"
        or value.get("initial_active_state") != "absent"
        or value.get("install_dir") != sys.argv[2]
        or value.get("pixel_source_ref") != sys.argv[3]
        or value.get("state") not in {"ready", "installing"}):
    raise SystemExit(1)
for key in ("contract_sha256", "configuration_sha256", "release_identity_sha256", "install_manifest_sha256"):
    item = value.get(key)
    if not isinstance(item, str) or len(item) != 64 or any(ch not in "0123456789abcdef" for ch in item):
        raise SystemExit(1)
PY
}

_ods_pixel_candidate_config_matches_live() {
    local owner="$1" home="$2" candidate="$3" live
    live="$home/.openclaw/openclaw.json"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$live" "$candidate" <<'PY'
import json, os, pathlib, stat, sys

values = []
for raw in sys.argv[1:]:
    path = pathlib.Path(raw)
    info = path.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_uid != os.getuid() or info.st_mode & 0o022
            or info.st_size > 2 * 1024 * 1024):
        raise SystemExit(1)
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise SystemExit(1)
    values.append(json.dumps(value, sort_keys=True, separators=(",", ":")))
if values[0] != values[1]:
    raise SystemExit(1)
PY
}

_ods_pixel_uses_stable_model_alias() {
    local owner="$1" home="$2" answers="$3" config
    config="$home/.openclaw/openclaw.json"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$answers" "$config" <<'PY'
import json, os, pathlib, re, stat, sys

documents = []
for raw in sys.argv[1:]:
    path = pathlib.Path(raw)
    info = path.lstat()
    parent = path.parent.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_nlink != 1 or info.st_uid != os.getuid()
            or info.st_mode & 0o077 or info.st_size > 2 * 1024 * 1024
            or not stat.S_ISDIR(parent.st_mode) or stat.S_ISLNK(parent.st_mode)
            or parent.st_uid != os.getuid() or parent.st_mode & 0o022):
        raise SystemExit(1)
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise SystemExit(1)
    documents.append(value)

answers, config = documents
if answers.get("modelProvider") != "ods-gateway" or answers.get("modelId") != "ods/current":
    raise SystemExit(1)
base_url = answers.get("modelBaseUrl")
api_key = answers.get("modelApiKey")
if (not isinstance(base_url, str)
        or not re.fullmatch(r"http://127\.0\.0\.1:[1-9][0-9]{0,4}/v1", base_url)
        or int(base_url.rsplit(":", 1)[1].split("/", 1)[0]) > 65535
        or not isinstance(api_key, str) or not api_key or len(api_key) > 4096
        or any(ord(character) < 32 or ord(character) == 127 for character in api_key)):
    raise SystemExit(1)

providers = config.get("models", {}).get("providers", {})
agents = config.get("agents", {}).get("list", [])
selected = [item for item in agents if isinstance(item, dict) and item.get("id") == "pixel"]
if not isinstance(providers, dict) or set(providers) != {"ods-gateway"} or len(selected) != 1:
    raise SystemExit(1)
provider = providers["ods-gateway"]
models = provider.get("models") if isinstance(provider, dict) else None
if (not isinstance(models, list) or len(models) != 1 or not isinstance(models[0], dict)
        or provider.get("api") != "openai-completions"
        or provider.get("baseUrl") != base_url or provider.get("apiKey") != api_key
        or models[0].get("id") != "ods/current"
        or selected[0].get("model") != "ods-gateway/ods/current"):
    raise SystemExit(1)
PY
}

_ods_pixel_stable_alias_matches_promoted_model() {
    local owner="$1" home="$2" answers="$3" promoted_model="$4"
    local promoted_context="${5:-}" promoted_max_tokens="${6:-}" promoted_reasoning="${7:-}" config
    local route_fingerprint="${8:-}" image_input="${9:-unknown}" thinking_control="${10:-}"
    config="$home/.openclaw/openclaw.json"
    ods_pixel_run_as_owner "$owner" "$home" python3 - \
        "$answers" "$config" "$promoted_model" "$promoted_context" \
        "$promoted_max_tokens" "$promoted_reasoning" "$route_fingerprint" "$image_input" \
        "$thinking_control" <<'PY'
import json, os, pathlib, re, stat, sys

answers_path, config_path = map(pathlib.Path, sys.argv[1:3])
promoted_model, context_raw, max_tokens_raw, reasoning_raw = sys.argv[3:7]
route_fingerprint = sys.argv[7] or None
image_input = sys.argv[8]
thinking_control = sys.argv[9] or None
if image_input not in ("supported", "unsupported", "unknown"):
    raise SystemExit("invalid promoted Pixel image-input contract")
if thinking_control not in (None, "enable_thinking", "always", "none"):
    raise SystemExit("invalid promoted Pixel thinking-control contract")
if route_fingerprint is not None and not re.fullmatch(r"[a-f0-9]{64}", route_fingerprint):
    raise SystemExit(1)
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._+:/ @(),=-]{0,255}", promoted_model):
    raise SystemExit(1)
documents = []
for path in (answers_path, config_path):
    info = path.lstat()
    parent = path.parent.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_nlink != 1 or info.st_uid != os.getuid()
            or info.st_mode & 0o077 or info.st_size > 2 * 1024 * 1024
            or not stat.S_ISDIR(parent.st_mode) or stat.S_ISLNK(parent.st_mode)
            or parent.st_uid != os.getuid() or parent.st_mode & 0o022):
        raise SystemExit(1)
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise SystemExit(1)
    documents.append(value)

answers, config = documents
if (answers.get("modelImageInput", "unknown") != image_input
        or config.get("plugins", {}).get("entries", {}).get("pixel-ods", {}).get("config", {}).get("modelImageInput") != image_input):
    raise SystemExit(1)
if (answers.get("modelRouteFingerprint") != route_fingerprint
        or config.get("plugins", {}).get("entries", {}).get("pixel-ods", {}).get("config", {}).get("modelRouteFingerprint") != route_fingerprint):
    raise SystemExit(1)
# The config never names the control; the answers that rendered it do.
if answers.get("modelThinkingControl") != thinking_control:
    raise SystemExit(1)
if answers.get("modelProvider") != "ods-gateway" or answers.get("modelId") != "ods/current":
    raise SystemExit(1)
expected_name = f"ODS Current ({promoted_model})"
context = answers.get("modelContextWindow")
max_tokens = answers.get("modelMaxTokens")
reasoning = answers.get("modelReasoning")
if context_raw:
    if not context_raw.isdigit():
        raise SystemExit(1)
    context = int(context_raw)
if max_tokens_raw:
    if not max_tokens_raw.isdigit():
        raise SystemExit(1)
    max_tokens = int(max_tokens_raw)
if reasoning_raw:
    if reasoning_raw not in {"true", "false"}:
        raise SystemExit(1)
    reasoning = reasoning_raw == "true"
if (answers.get("modelName") != expected_name
        or type(context) is not int or not 4096 <= context <= 10_000_000
        or type(max_tokens) is not int or not 1 <= max_tokens <= context
        or type(reasoning) is not bool
        or answers.get("modelContextWindow") != context
        or answers.get("modelMaxTokens") != max_tokens
        or answers.get("modelReasoning") is not reasoning):
    raise SystemExit(1)

providers = config.get("models", {}).get("providers", {})
if not isinstance(providers, dict) or set(providers) != {"ods-gateway"}:
    raise SystemExit(1)
provider = providers["ods-gateway"]
models = provider.get("models") if isinstance(provider, dict) else None
if not isinstance(models, list) or len(models) != 1 or not isinstance(models[0], dict):
    raise SystemExit(1)
model = models[0]
if (model.get("id") != "ods/current" or model.get("name") != expected_name
        or model.get("contextWindow") != context or model.get("maxTokens") != max_tokens
        or model.get("reasoning") is not reasoning
        or model.get("input") != (["text"] if image_input == "unsupported" else ["text", "image"])):
    raise SystemExit(1)
PY
}

_ods_pixel_search_provider_matches_contract() {
    local owner="$1" home="$2" answers="$3" live
    live="$home/.openclaw/openclaw.json"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$live" "$answers" "${INSTALL_DIR:?}" <<'PY'
import json, os, pathlib, re, stat, sys

if len(sys.argv) != 4:
    raise SystemExit(1)
documents = []
for raw in sys.argv[1:3]:
    path = pathlib.Path(raw)
    info = path.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_nlink != 1 or info.st_uid != os.getuid()
            or info.st_mode & 0o077 or info.st_size > 2 * 1024 * 1024):
        raise SystemExit(1)
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise SystemExit(1)
    documents.append(value)
live, contract = documents
selected = contract.get("webSearchProvider", "searxng")
search = live.get("tools", {}).get("web", {}).get("search")
plugins = live.get("plugins")
if (selected not in {"searxng", "parallel-free"}
        or search != {"provider": selected} or not isinstance(plugins, dict)):
    raise SystemExit(1)
allow = plugins.get("allow")
entries = plugins.get("entries")
load = plugins.get("load")
paths = load.get("paths") if isinstance(load, dict) else None
if (not isinstance(allow, list) or not isinstance(entries, dict)
        or not isinstance(paths, list) or "pixel-ods" not in allow):
    raise SystemExit(1)
parallel_path = str(pathlib.Path(sys.argv[3]) / "data/pixel/native-search/parallel-2026.6.33")
if selected == "searxng":
    origin = contract.get("searxngBaseUrl")
    if (not isinstance(origin, str)
            or not re.fullmatch(r"http://127\.0\.0\.1:[1-9][0-9]{0,4}", origin)
            or int(origin.rsplit(":", 1)[1]) > 65535
            or "searxng" not in allow or "parallel" in allow
            or entries.get("searxng") != {"enabled": True, "config": {"webSearch": {"baseUrl": origin}}}
            or "parallel" in entries or parallel_path in paths):
        raise SystemExit(1)
else:
    extensions = contract.get("gatewayExtensions")
    parallel = [item for item in extensions if isinstance(item, dict) and item.get("id") == "parallel"] if isinstance(extensions, list) else []
    if (len(parallel) != 1 or parallel[0].get("path") != parallel_path
            or not isinstance(parallel[0].get("sha256"), str)
            or not re.fullmatch(r"[0-9a-f]{64}", parallel[0]["sha256"])
            or "parallel" not in allow or "searxng" in allow
            or entries.get("parallel") != {"enabled": True}
            or "searxng" in entries or parallel_path not in paths):
        raise SystemExit(1)
PY
}

_ods_pixel_stage_stable_alias_candidate() {
    local owner="$1" home="$2" answers="$3" live
    live="$home/.openclaw/openclaw.json"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$live" "$answers" <<'PY'
import copy, json, os, pathlib, re, stat, sys, tempfile

live_path, answers_path = map(pathlib.Path, sys.argv[1:])
documents = []
for path in (live_path, answers_path):
    info = path.lstat()
    parent = path.parent.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_nlink != 1 or info.st_uid != os.getuid()
            or info.st_mode & 0o077 or info.st_size > 2 * 1024 * 1024
            or not stat.S_ISDIR(parent.st_mode) or stat.S_ISLNK(parent.st_mode)
            or parent.st_uid != os.getuid() or parent.st_mode & 0o022):
        raise SystemExit("unsafe stable-alias reconciliation input")
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise SystemExit("invalid stable-alias reconciliation input")
    documents.append(value)

live, contract = documents
if contract.get("modelProvider") != "ods-gateway" or contract.get("modelId") != "ods/current":
    raise SystemExit("stable-alias onboarding contract is invalid")
name = contract.get("modelName")
context = contract.get("modelContextWindow")
max_tokens = contract.get("modelMaxTokens")
reasoning = contract.get("modelReasoning")
if (not isinstance(name, str)
        or not re.fullmatch(r"ODS Current \([A-Za-z0-9][A-Za-z0-9._+:/ @(),=-]{0,255}\)", name)
        or type(context) is not int or not 4096 <= context <= 10_000_000
        or type(max_tokens) is not int or not 1 <= max_tokens <= context
        or type(reasoning) is not bool):
    raise SystemExit("stable-alias model limits are invalid")
providers = live.get("models", {}).get("providers", {})
agents = live.get("agents", {}).get("list", [])
selected = [item for item in agents if isinstance(item, dict) and item.get("id") == "pixel"]
if not isinstance(providers, dict) or set(providers) != {"ods-gateway"} or len(selected) != 1:
    raise SystemExit("live stable-alias route is invalid")
provider = providers["ods-gateway"]
models = provider.get("models") if isinstance(provider, dict) else None
if (not isinstance(models, list) or len(models) != 1 or not isinstance(models[0], dict)
        or models[0].get("id") != "ods/current"
        or selected[0].get("model") != "ods-gateway/ods/current"):
    raise SystemExit("live stable-alias model binding is invalid")
candidate = copy.deepcopy(live)
route_fingerprint = contract.get("modelRouteFingerprint")
if route_fingerprint is not None and (not isinstance(route_fingerprint, str)
        or not re.fullmatch(r"[a-f0-9]{64}", route_fingerprint)):
    raise SystemExit("invalid promoted Pixel route identity")
plugin_config = candidate.setdefault("plugins", {}).setdefault("entries", {}).setdefault("pixel-ods", {}).setdefault("config", {})
if route_fingerprint is None:
    plugin_config.pop("modelRouteFingerprint", None)
else:
    plugin_config["modelRouteFingerprint"] = route_fingerprint
model = candidate["models"]["providers"]["ods-gateway"]["models"][0]
model["name"] = name
model["contextWindow"] = context
model["maxTokens"] = max_tokens
model["reasoning"] = reasoning
image_input = contract.get("modelImageInput", "unknown")
if image_input not in ("supported", "unsupported", "unknown"):
    raise SystemExit("invalid promoted Pixel image-input contract")
plugin_config["modelImageInput"] = image_input
model["input"] = ["text"] if image_input == "unsupported" else ["text", "image"]
agent = next(
    item for item in candidate["agents"]["list"]
    if isinstance(item, dict) and item.get("id") == "pixel"
)
context_limits = agent.setdefault("contextLimits", {})
if not isinstance(context_limits, dict):
    raise SystemExit("live stable-alias context limits are invalid")
context_limits["toolResultMaxChars"] = max(4000, min(16000, context // 4))
defaults = candidate.get("agents", {}).get("defaults", {})
compaction = defaults.setdefault("compaction", {}) if isinstance(defaults, dict) else None
if not isinstance(compaction, dict):
    raise SystemExit("live stable-alias compaction policy is invalid")
compaction["reserveTokens"] = (context + 4 * max_tokens + 4) // 5
compaction["reserveTokensFloor"] = 0
compaction["keepRecentTokens"] = max(512, min(20000, context // 16))
descriptor, temporary = tempfile.mkstemp(prefix=".ods-model-reconcile-", dir=live_path.parent)
try:
    with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle:
        json.dump(candidate, handle, indent=2, sort_keys=True)
        handle.write("\n")
        handle.flush()
        os.fsync(handle.fileno())
    os.chmod(temporary, 0o600)
    print(temporary)
except BaseException:
    try:
        os.unlink(temporary)
    except FileNotFoundError:
        pass
    raise
PY
}

_ods_pixel_managed_source_ref() {
    local owner="$1" home="$2" marker config
    marker="$home/.config/ods/pixel-managed.json"
    config="$home/.openclaw/openclaw.json"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$marker" "$config" "${INSTALL_DIR:?}" <<'PY'
import hashlib, json, os, pathlib, re, stat, sys

marker_path = pathlib.Path(sys.argv[1])
config_path = pathlib.Path(sys.argv[2])
for path, maximum in ((marker_path, 65536), (config_path, 2 * 1024 * 1024)):
    info = path.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_nlink != 1
            or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_size > maximum):
        raise SystemExit("unsafe ODS-managed Pixel state")
marker = json.loads(marker_path.read_text(encoding="utf-8"))
source_ref = marker.get("pixel_source_ref")
if (marker.get("schema_version") != 2 or marker.get("manager") != "ods"
        or marker.get("initial_active_state") != "absent"
        or marker.get("install_dir") != sys.argv[3]
        or marker.get("state") not in {"ready", "installing"}
        or not isinstance(source_ref, str) or not re.fullmatch(r"[0-9a-f]{40}", source_ref)
        or marker.get("requested_source_ref") not in {None, source_ref}):
    raise SystemExit("ODS-managed Pixel marker is not eligible for reconciliation")
config = json.loads(config_path.read_text(encoding="utf-8"))
if not isinstance(config, dict):
    raise SystemExit("invalid ODS-managed OpenClaw configuration")
canonical = json.dumps(config, sort_keys=True, separators=(",", ":")).encode()
observed = hashlib.sha256(b"ods-pixel-openclaw-v1\0" + canonical).hexdigest()
if marker.get("configuration_sha256") != observed:
    raise SystemExit("ODS-managed OpenClaw configuration drifted")
print(source_ref)
PY
}

_ods_pixel_model_reconciliation_snapshot() {
    local owner="$1" home="$2" answers="$3" marker config attestation backup_root installed_answers
    marker="$home/.config/ods/pixel-managed.json"
    config="$home/.openclaw/openclaw.json"
    attestation="$home/.local/share/pixel/runtime-attestation.json"
    backup_root="$home/.openclaw/backups"
    installed_answers="$home/.config/pixel-deployment/onboarding.json"
    ods_pixel_run_as_owner "$owner" "$home" python3 - \
        "$marker" "$config" "$answers" "$attestation" "$backup_root" "$installed_answers" <<'PY'
import json, os, pathlib, re, shutil, stat, sys, tempfile

marker, config, answers, attestation, backup_root, installed_answers = map(pathlib.Path, sys.argv[1:])
required_sources = (
    (marker, 65536),
    (config, 2 * 1024 * 1024),
    (answers, 2 * 1024 * 1024),
    (installed_answers, 2 * 1024 * 1024),
)
for path, maximum in required_sources:
    info = path.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_nlink != 1
            or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_size > maximum):
        raise SystemExit(f"unsafe Pixel reconciliation source: {path}")
attestation_present = False
try:
    attestation_info = attestation.lstat()
except FileNotFoundError:
    pass
else:
    if (not stat.S_ISREG(attestation_info.st_mode) or stat.S_ISLNK(attestation_info.st_mode)
            or attestation_info.st_nlink != 1 or attestation_info.st_uid != os.getuid()
            or attestation_info.st_mode & 0o077 or attestation_info.st_size > 2 * 1024 * 1024):
        raise SystemExit(f"unsafe Pixel reconciliation source: {attestation}")
    attestation_present = True
backup_root.mkdir(mode=0o700, parents=True, exist_ok=True)
root_info = backup_root.lstat()
if (not stat.S_ISDIR(root_info.st_mode) or stat.S_ISLNK(root_info.st_mode)
        or root_info.st_uid != os.getuid() or root_info.st_mode & 0o077):
    raise SystemExit("unsafe Pixel backup root")
backup = pathlib.Path(tempfile.mkdtemp(prefix="ods-model-reconcile-", dir=backup_root))
os.chmod(backup, 0o700)
backup_sources = [
    (marker, "pixel-managed.json"),
    (config, "openclaw.json"),
    (answers, "onboarding.json"),
    (installed_answers, "installed-onboarding.json"),
]
if attestation_present:
    backup_sources.append((attestation, "runtime-attestation.json"))
for source, name in backup_sources:
    target = backup / name
    with source.open("rb") as source_handle, target.open("xb") as target_handle:
        shutil.copyfileobj(source_handle, target_handle)
        target_handle.flush()
        os.fsync(target_handle.fileno())
    os.chmod(target, 0o600)

live = json.loads(config.read_text(encoding="utf-8"))
contract = json.loads(answers.read_text(encoding="utf-8"))
agent_id = contract.get("agentId")
providers = live.get("models", {}).get("providers", {})
if (not isinstance(providers, dict) or len(providers) != 1
        or next(iter(providers), None) not in {"ods-local", "ods-gateway"}):
    raise SystemExit("live Pixel provider is outside the ODS model-only contract")
provider = next(iter(providers))
provider_value = providers[provider]
models = provider_value.get("models", []) if isinstance(provider_value, dict) else []
agents = live.get("agents", {}).get("list", [])
agent = [item for item in agents if isinstance(item, dict) and item.get("id") == agent_id]
extensions = contract.get("gatewayExtensions")
if not isinstance(extensions, list) or not 1 <= len(extensions) <= 32:
    raise SystemExit("invalid ODS Pixel gateway extensions")
extension_ids = set()
for extension in extensions:
    extension_id = extension.get("id") if isinstance(extension, dict) else None
    if (not isinstance(extension_id, str)
            or not re.fullmatch(r"[a-z][a-z0-9-]{1,62}", extension_id)
            or extension_id in extension_ids):
        raise SystemExit("invalid or duplicate ODS Pixel gateway extension")
    extension_ids.add(extension_id)
    # Additional extensions retain Pixel's path/digest binding. Configure and
    # render verify the actual contents; model reconciliation preserves them.
    if extension_id != "pixel-ods":
        location, digest = extension.get("path"), extension.get("sha256")
        if (not isinstance(location, str) or not pathlib.Path(location).is_absolute()
                or pathlib.Path(location) == pathlib.Path("/")
                or ".." in pathlib.Path(location).parts
                or any(ord(c) < 32 or ord(c) == 127 for c in location)
                or not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest)):
            raise SystemExit("unbound ODS Pixel gateway extension")
if (contract.get("deploymentName") != "ods-default" or agent_id != "pixel"
        or "pixel-ods" not in extension_ids
        or len(models) != 1 or len(agent) != 1
        or not isinstance(models[0].get("id"), str) or not isinstance(models[0].get("name"), str)
        or provider_value.get("api") != "openai-completions"
        or agent[0].get("model") != f"{provider}/{models[0]['id']}"):
    raise SystemExit("live Pixel configuration is outside the ODS model-only contract")
model_id = models[0]["id"]
model_name = models[0]["name"]
if provider == "ods-local":
    if (provider_value.get("apiKey") != "local-no-auth"
            or provider_value.get("baseUrl") != "http://127.0.0.1:11434/v1"
            or model_name != f"ODS Local {model_id}"):
        raise SystemExit("live Pixel local route is outside the ODS model-only contract")
else:
    gateway_key = provider_value.get("apiKey")
    gateway_url = provider_value.get("baseUrl")
    alias_label = "Current" if model_id == "ods/current" else "Default"
    if (model_id not in {"default", "ods/current"}
            or not isinstance(gateway_key, str) or not gateway_key or len(gateway_key) > 4096
            or any(ord(character) < 32 or ord(character) == 127 for character in gateway_key)
            or not isinstance(gateway_url, str)
            or not re.fullmatch(r"http://127\.0\.0\.1:[1-9][0-9]{0,4}/v1", gateway_url)
            or int(gateway_url.rsplit(":", 1)[1].split("/", 1)[0]) > 65535
            or not re.fullmatch(
                rf"ODS {alias_label} \([A-Za-z0-9][A-Za-z0-9._+:/ @(),=-]{{0,255}}\)",
                model_name,
            )):
        raise SystemExit("live Pixel gateway route is outside the ODS model-only contract")
context_window = models[0].get("contextWindow")
max_tokens = models[0].get("maxTokens")
reasoning = models[0].get("reasoning")
if (type(context_window) is not int or type(max_tokens) is not int or type(reasoning) is not bool
        or not 4096 <= context_window <= 10_000_000
        or not 1 <= max_tokens <= context_window):
    raise SystemExit("live Pixel model limits are outside the ODS model-only contract")
# The rollback contract describes the live model. A measured thinking control
# saved for another model (the answers can lag a native switch) is dropped.
if contract.get("modelThinkingControl") not in (None, "enable_thinking", "always", "none"):
    raise SystemExit("invalid Pixel thinking-control contract")
if (contract.get("modelProvider"), contract.get("modelId"), contract.get("modelName")) != (provider, model_id, model_name):
    contract.pop("modelThinkingControl", None)
contract["modelProvider"] = provider
contract["modelId"] = models[0]["id"]
contract["modelName"] = models[0]["name"]
contract["modelBaseUrl"] = provider_value.get("baseUrl")
contract["modelApiKey"] = provider_value.get("apiKey")
contract["modelContextWindow"] = context_window
contract["modelMaxTokens"] = max_tokens
contract["modelReasoning"] = reasoning
image_input = live.get("plugins", {}).get("entries", {}).get("pixel-ods", {}).get("config", {}).get("modelImageInput")
if image_input is not None:
    if (image_input not in ("supported", "unsupported", "unknown")
            or models[0].get("input") != (["text"] if image_input == "unsupported" else ["text", "image"])):
        raise SystemExit("invalid live Pixel image-input contract")
    contract["modelImageInput"] = image_input
else:
    contract.pop("modelImageInput", None)
route_fingerprint = live.get("plugins", {}).get("entries", {}).get("pixel-ods", {}).get("config", {}).get("modelRouteFingerprint")
if route_fingerprint is not None and (not isinstance(route_fingerprint, str)
        or not re.fullmatch(r"[a-f0-9]{64}", route_fingerprint)):
    raise SystemExit("invalid live Pixel route identity")
if provider == "ods-gateway" and route_fingerprint is not None:
    contract["modelRouteFingerprint"] = route_fingerprint
else:
    contract.pop("modelRouteFingerprint", None)
rollback = backup / "rollback-onboarding.json"
payload = json.dumps(contract, indent=2, sort_keys=True) + "\n"
with rollback.open("x", encoding="utf-8", newline="\n") as handle:
    handle.write(payload)
    handle.flush()
    os.fsync(handle.fileno())
os.chmod(rollback, 0o600)
print(backup)
PY
}

_ods_pixel_update_onboarding_model() {
    local owner="$1" home="$2" answers="$3" model="$4"
    local context="${5:-}" max_tokens="${6:-}" reasoning="${7:-}"
    local route_fingerprint="${8:-}" image_input="${9:-unknown}" thinking_control="${10:-}"
    ods_pixel_run_as_owner "$owner" "$home" python3 - \
        "$answers" "$model" "$context" "$max_tokens" "$reasoning" "$route_fingerprint" "$image_input" \
        "$thinking_control" <<'PY'
import json, os, pathlib, re, stat, sys, tempfile

path = pathlib.Path(sys.argv[1])
model = sys.argv[2]
context_raw, max_tokens_raw, reasoning_raw = sys.argv[3:6]
route_fingerprint = sys.argv[6] or None
image_input = sys.argv[7]
thinking_control = sys.argv[8] or None
if image_input not in ("supported", "unsupported", "unknown"):
    raise SystemExit("invalid promoted Pixel image-input contract")
if thinking_control not in (None, "enable_thinking", "always", "none"):
    raise SystemExit("invalid promoted Pixel thinking-control contract")
if route_fingerprint is not None and not re.fullmatch(r"[a-f0-9]{64}", route_fingerprint):
    raise SystemExit("invalid promoted Pixel route identity")
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._+:/ @(),=-]{0,255}", model):
    raise SystemExit("invalid promoted Pixel model id")
info = path.lstat()
if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_nlink != 1
        or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_size > 2 * 1024 * 1024):
    raise SystemExit("unsafe ODS Pixel onboarding contract")
parent_info = path.parent.lstat()
if (not stat.S_ISDIR(parent_info.st_mode) or stat.S_ISLNK(parent_info.st_mode)
        or parent_info.st_uid != os.getuid() or parent_info.st_mode & 0o022):
    raise SystemExit("unsafe ODS Pixel onboarding directory")
value = json.loads(path.read_text(encoding="utf-8"))
extensions = value.get("gatewayExtensions")
if not isinstance(extensions, list) or not 1 <= len(extensions) <= 32:
    raise SystemExit("invalid ODS Pixel gateway extensions")
extension_ids = set()
for extension in extensions:
    extension_id = extension.get("id") if isinstance(extension, dict) else None
    if (not isinstance(extension_id, str)
            or not re.fullmatch(r"[a-z][a-z0-9-]{1,62}", extension_id)
            or extension_id in extension_ids):
        raise SystemExit("invalid or duplicate ODS Pixel gateway extension")
    extension_ids.add(extension_id)
    if extension_id != "pixel-ods":
        location, digest = extension.get("path"), extension.get("sha256")
        if (not isinstance(location, str) or not pathlib.Path(location).is_absolute()
                or pathlib.Path(location) == pathlib.Path("/")
                or ".." in pathlib.Path(location).parts
                or any(ord(c) < 32 or ord(c) == 127 for c in location)
                or not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest)):
            raise SystemExit("unbound ODS Pixel gateway extension")
provider = value.get("modelProvider")
model_id = value.get("modelId")
model_name = value.get("modelName")
base_url = value.get("modelBaseUrl")
api_key = value.get("modelApiKey")
if (value.get("deploymentName") != "ods-default" or value.get("agentId") != "pixel"
        or "pixel-ods" not in extension_ids):
    raise SystemExit("onboarding contract is outside the ODS-managed Pixel boundary")
if provider == "ods-local":
    if (api_key != "local-no-auth" or base_url != "http://127.0.0.1:11434/v1"
            or model_name != f"ODS Local {model_id}"):
        raise SystemExit("onboarding local route is outside the ODS-managed Pixel boundary")
elif provider == "ods-gateway":
    alias_label = "Current" if model_id == "ods/current" else "Default"
    if (model_id not in {"default", "ods/current"}
            or not isinstance(model_name, str)
            or not re.fullmatch(
                rf"ODS {alias_label} \([A-Za-z0-9][A-Za-z0-9._+:/ @(),=-]{{0,255}}\)",
                model_name,
            )
            or not isinstance(api_key, str) or not api_key or len(api_key) > 4096
            or any(ord(character) < 32 or ord(character) == 127 for character in api_key)
            or not isinstance(base_url, str)
            or not re.fullmatch(r"http://127\.0\.0\.1:[1-9][0-9]{0,4}/v1", base_url)
            or int(base_url.rsplit(":", 1)[1].split("/", 1)[0]) > 65535):
        raise SystemExit("onboarding gateway route is outside the ODS-managed Pixel boundary")
else:
    raise SystemExit("onboarding provider is outside the ODS-managed Pixel boundary")
if (type(value.get("modelContextWindow")) is not int
        or type(value.get("modelMaxTokens")) is not int
        or type(value.get("modelReasoning")) is not bool
        or not 4096 <= value["modelContextWindow"] <= 10_000_000
        or not 1 <= value["modelMaxTokens"] <= value["modelContextWindow"]):
    raise SystemExit("onboarding model limits are outside the ODS-managed Pixel boundary")
if context_raw:
    if not context_raw.isdigit() or not 4096 <= int(context_raw) <= 10_000_000:
        raise SystemExit("invalid promoted Pixel context window")
    value["modelContextWindow"] = int(context_raw)
if max_tokens_raw:
    if not max_tokens_raw.isdigit() or not 1 <= int(max_tokens_raw) <= value.get("modelContextWindow", 0):
        raise SystemExit("invalid promoted Pixel maximum tokens")
    value["modelMaxTokens"] = int(max_tokens_raw)
elif context_raw and value.get("modelMaxTokens", 0) > value["modelContextWindow"]:
    value["modelMaxTokens"] = value["modelContextWindow"]
if reasoning_raw:
    if reasoning_raw not in {"true", "false"}:
        raise SystemExit("invalid promoted Pixel reasoning capability")
    value["modelReasoning"] = reasoning_raw == "true"
if provider == "ods-local":
    value["modelId"] = model
    value["modelName"] = f"ODS Local {model}"
else:
    # Reconciliation is the safe upgrade boundary for pre-stable-alias ODS
    # installs. Keep accepting the legacy default contract above so it can be
    # rolled forward, then persist only the canonical alias.
    value["modelId"] = "ods/current"
    value["modelName"] = f"ODS Current ({model})"
value["modelImageInput"] = image_input
if provider == "ods-gateway" and route_fingerprint is not None:
    value["modelRouteFingerprint"] = route_fingerprint
else:
    value.pop("modelRouteFingerprint", None)
# The promoted model's own control or none: never another model's.
if thinking_control is None:
    value.pop("modelThinkingControl", None)
else:
    value["modelThinkingControl"] = thinking_control
payload = json.dumps(value, indent=2, sort_keys=True) + "\n"
fd, temporary = tempfile.mkstemp(prefix=".pixel-onboarding.", dir=path.parent)
try:
    with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
        handle.write(payload)
        handle.flush()
        os.fsync(handle.fileno())
    os.chmod(temporary, 0o600)
    os.replace(temporary, path)
finally:
    if os.path.exists(temporary):
        os.unlink(temporary)
PY
}

_ods_pixel_candidate_is_managed_runtime_update() {
    local owner="$1" home="$2" candidate="$3" answers="$4" live
    live="$home/.openclaw/openclaw.json"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$live" "$candidate" "$answers" "${INSTALL_DIR:?}" <<'PY'
import copy, json, os, pathlib, re, stat, sys

values = []
for raw in sys.argv[1:4]:
    path = pathlib.Path(raw)
    info = path.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_nlink != 1
            or info.st_uid != os.getuid() or info.st_mode & 0o077
            or info.st_size > 2 * 1024 * 1024):
        raise SystemExit("unsafe Pixel model-reconciliation input")
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise SystemExit("Pixel model-reconciliation input is not an object")
    values.append(value)
live, candidate, contract = values
provider = contract.get("modelProvider")
model_id = contract.get("modelId")
model_name = contract.get("modelName")
agent_id = contract.get("agentId")
if provider not in {"ods-local", "ods-gateway"} or agent_id != "pixel":
    raise SystemExit("candidate is outside the ODS model contract")
if provider == "ods-local":
    if (model_name != f"ODS Local {model_id}"
            or contract.get("modelApiKey") != "local-no-auth"
            or contract.get("modelBaseUrl") != "http://127.0.0.1:11434/v1"):
        raise SystemExit("candidate local model is outside the ODS model contract")
else:
    gateway_key = contract.get("modelApiKey")
    gateway_url = contract.get("modelBaseUrl")
    alias_label = "Current" if model_id == "ods/current" else "Default"
    if (model_id not in {"default", "ods/current"}
            or not isinstance(model_name, str)
            or not re.fullmatch(
                rf"ODS {alias_label} \([A-Za-z0-9][A-Za-z0-9._+:/ @(),=-]{{0,255}}\)",
                model_name,
            )
            or not isinstance(gateway_key, str) or not gateway_key or len(gateway_key) > 4096
            or any(ord(character) < 32 or ord(character) == 127 for character in gateway_key)
            or not isinstance(gateway_url, str)
            or not re.fullmatch(r"http://127\.0\.0\.1:[1-9][0-9]{0,4}/v1", gateway_url)
            or int(gateway_url.rsplit(":", 1)[1].split("/", 1)[0]) > 65535):
        raise SystemExit("candidate gateway alias is outside the ODS model contract")

def binding(document, expected_provider=None):
    providers = document.get("models", {}).get("providers", {})
    if (not isinstance(providers, dict) or len(providers) != 1
            or next(iter(providers), None) not in {"ods-local", "ods-gateway"}):
        raise SystemExit("unexpected Pixel model providers")
    provider_id = next(iter(providers))
    if expected_provider is not None and provider_id != expected_provider:
        raise SystemExit("unexpected Pixel model provider")
    provider_value = providers[provider_id]
    models = provider_value.get("models") if isinstance(provider_value, dict) else None
    agents = document.get("agents", {}).get("list", [])
    selected = [item for item in agents if isinstance(item, dict) and item.get("id") == agent_id]
    if not isinstance(models, list) or len(models) != 1 or len(selected) != 1:
        raise SystemExit("unexpected Pixel model or agent cardinality")
    return provider_id, provider_value, models[0], selected[0]

def validate_live_route(provider_id, provider_value, model, agent):
    live_id = model.get("id")
    if (provider_value.get("api") != "openai-completions" or not isinstance(live_id, str)
            or agent.get("model") != f"{provider_id}/{live_id}"):
        raise SystemExit("live provider route is outside the ODS model contract")
    if provider_id == "ods-local":
        if (provider_value.get("apiKey") != "local-no-auth"
                or provider_value.get("baseUrl") != "http://127.0.0.1:11434/v1"
                or model.get("name") != f"ODS Local {live_id}"):
            raise SystemExit("live local provider route is outside the ODS model contract")
        return
    live_key = provider_value.get("apiKey")
    live_url = provider_value.get("baseUrl")
    live_label = "Current" if live_id == "ods/current" else "Default"
    live_name = model.get("name")
    if (live_id not in {"default", "ods/current"}
            or not isinstance(live_name, str)
            or not re.fullmatch(
                rf"ODS {live_label} \([A-Za-z0-9][A-Za-z0-9._+:/ @(),=-]{{0,255}}\)",
                live_name,
            )
            or not isinstance(live_key, str) or not live_key or len(live_key) > 4096
            or any(ord(character) < 32 or ord(character) == 127 for character in live_key)
            or not isinstance(live_url, str)
            or not re.fullmatch(r"http://127\.0\.0\.1:[1-9][0-9]{0,4}/v1", live_url)
            or int(live_url.rsplit(":", 1)[1].split("/", 1)[0]) > 65535):
        raise SystemExit("live gateway provider route is outside the ODS model contract")

live_provider_id, live_provider, live_model, live_agent = binding(live)
candidate_provider_id, candidate_provider, candidate_model, candidate_agent = binding(candidate, provider)
validate_live_route(live_provider_id, live_provider, live_model, live_agent)
thinking_control = contract.get("modelThinkingControl")
if thinking_control not in (None, "enable_thinking", "always", "none"):
    raise SystemExit("invalid candidate Pixel thinking-control contract")
# Same rule as pixel-runtime-budget.py: a measured "always" or "none" chat
# template wins over the requested reasoning flag.
model_reasoning = {"always": True, "none": False}.get(thinking_control, contract.get("modelReasoning"))
expected_model = {
    "id": model_id,
    "name": model_name,
    "contextWindow": contract.get("modelContextWindow"),
    "maxTokens": contract.get("modelMaxTokens"),
    "reasoning": model_reasoning,
}
image_input = contract.get("modelImageInput", "unknown")
if image_input not in ("supported", "unsupported", "unknown"):
    raise SystemExit("invalid candidate Pixel image-input contract")
expected_model["input"] = ["text"] if image_input == "unsupported" else ["text", "image"]
for key, expected in expected_model.items():
    if candidate_model.get(key) != expected:
        raise SystemExit(f"candidate model field does not match onboarding: {key}")
if (candidate_provider.get("api") != "openai-completions"
        or candidate_provider.get("apiKey") != contract.get("modelApiKey")
        or candidate_provider.get("baseUrl") != contract.get("modelBaseUrl")
        or candidate_agent.get("model") != f"{provider}/{model_id}"):
    raise SystemExit("candidate provider route does not match onboarding")
normalized = copy.deepcopy(live)
normalized_providers = normalized.get("models", {}).get("providers", {})
if not isinstance(normalized_providers, dict) or set(normalized_providers) != {live_provider_id}:
    raise SystemExit("live provider collection is outside the ODS model contract")
normalized_provider = normalized_providers.pop(live_provider_id)
normalized_providers[provider] = normalized_provider
normalized_provider["api"] = candidate_provider.get("api")
normalized_provider["apiKey"] = candidate_provider.get("apiKey")
normalized_provider["baseUrl"] = candidate_provider.get("baseUrl")
normalized_models = normalized_provider.get("models")
if not isinstance(normalized_models, list) or len(normalized_models) != 1:
    raise SystemExit("live provider models are outside the ODS model contract")
normalized_model = normalized_models[0]
normalized_agents = normalized.get("agents")
normalized_agent_list = normalized_agents.get("list", []) if isinstance(normalized_agents, dict) else []
normalized_selected = [item for item in normalized_agent_list if isinstance(item, dict) and item.get("id") == agent_id]
if len(normalized_selected) != 1:
    raise SystemExit("live Pixel agent is outside the ODS model contract")
normalized_agent = normalized_selected[0]
normalized_agent_experimental = normalized_agent.setdefault("experimental", {})
normalized_model["id"] = model_id
normalized_model["name"] = model_name
normalized_model["contextWindow"] = contract.get("modelContextWindow")
normalized_model["maxTokens"] = contract.get("modelMaxTokens")
normalized_model["reasoning"] = model_reasoning
normalized_model["input"] = expected_model["input"]
normalized_agent["model"] = f"{provider}/{model_id}"
normalized_defaults = normalized_agents.get("defaults") if isinstance(normalized_agents, dict) else None
normalized_session = normalized.get("session")
if not isinstance(normalized_defaults, dict) or not isinstance(normalized_session, dict):
    raise SystemExit("live Pixel runtime policy is outside the ODS contract")

# A promoted route may also carry the current deterministic ODS runtime policy.
# Normalize only those exact fields before the whole-document comparison; any
# other candidate change still fails closed below.
normalized_provider["timeoutSeconds"] = 1800
normalized_defaults["timeoutSeconds"] = 1800
# Preserve Pixel's complete workspace operating and tool contracts. The
# shipped AGENTS.md and TOOLS.md files are both larger than 4,000 characters;
# a smaller ODS override silently removes most of their instructions.
normalized_defaults["bootstrapMaxChars"] = 32000
normalized_defaults["bootstrapTotalMaxChars"] = 96000
normalized_defaults["contextInjection"] = "continuation-skip"
# Full upstream bootstrap documents remain available at 32K and above. Below
# that capability floor they cannot fit beside OpenClaw's core prompt and even
# its compact Tool Search surface, so the ODS plugin supplies a compact safety
# core plus request-specific contracts instead. This changes prompt shape only:
# tools, sandboxing, approvals, and broker authority remain identical.
normalized_context_window = contract.get("modelContextWindow")
normalized_compact_context = normalized_context_window < 32768
model_label = f"{model_id} {model_name}".casefold()
normalized_parameter_markers = re.findall(
    r"(?<![a-z0-9.])(\d+(?:\.\d+)?)\s*b(?![a-z0-9])",
    model_label,
)
# Some published small checkpoints use size classes (Mini, Micro, Tiny)
# instead of a parameter count in their runtime name. Prefer any explicit
# count, so a hypothetical "Micro 70B" cannot be silently compacted.
normalized_small_model = (
    any(float(marker) <= 4 for marker in normalized_parameter_markers)
    or (not normalized_parameter_markers and re.search(
        r"(?<![a-z0-9])(mini|micro|tiny)(?![a-z0-9])", model_label,
    ) is not None)
)
normalized_lean_prompt = normalized_compact_context or normalized_small_model
normalized_agent["bootstrapMaxChars"] = 2000 if normalized_lean_prompt else 14000
normalized_agent["bootstrapTotalMaxChars"] = 6000 if normalized_lean_prompt else 36000
normalized_agent["contextInjection"] = "never" if normalized_lean_prompt else "continuation-skip"
normalized_agent_context_limits = normalized_agent.setdefault("contextLimits", {})
normalized_agent_context_limits["toolResultMaxChars"] = max(
    4000,
    min(16000, contract.get("modelContextWindow") // 4),
)
normalized_compaction = normalized_defaults.setdefault("compaction", {})
normalized_diagnostics = normalized.setdefault("diagnostics", {})
normalized_write_lock = normalized_session.setdefault("writeLock", {})
normalized_tools = normalized.setdefault("tools", {})
normalized_also_allow = normalized_tools.setdefault("alsoAllow", [])
normalized_web = normalized_tools.setdefault("web", {})
normalized_fetch = normalized_web.setdefault("fetch", {})
normalized_plugins = normalized.setdefault("plugins", {})
normalized_plugin_entries = normalized_plugins.setdefault("entries", {}) if isinstance(normalized_plugins, dict) else None
normalized_pixel_plugin = normalized_plugin_entries.setdefault("pixel-ods", {}) if isinstance(normalized_plugin_entries, dict) else None
normalized_pixel_config = normalized_pixel_plugin.setdefault("config", {}) if isinstance(normalized_pixel_plugin, dict) else None
normalized_agent_tools = normalized_agent.setdefault("tools", {})
normalized_agent_deny = normalized_agent_tools.setdefault("deny", [])
normalized_sandbox_tools = normalized_tools.setdefault("sandbox", {}).setdefault("tools", {})
normalized_sandbox_allow = normalized_sandbox_tools.setdefault("allow", [])
normalized_agent_sandbox = normalized_defaults.setdefault("sandbox", {})
normalized_sandbox_docker = normalized_agent_sandbox.setdefault("docker", {})
if (not isinstance(normalized_compaction, dict)
        or not isinstance(normalized_diagnostics, dict)
        or not isinstance(normalized_write_lock, dict)
        or not isinstance(normalized_tools, dict)
        or not isinstance(normalized_also_allow, list)
        or not all(isinstance(item, str) for item in normalized_also_allow)
        or not isinstance(normalized_web, dict)
        or not isinstance(normalized_fetch, dict)
        or not isinstance(normalized_plugins, dict)
        or not isinstance(normalized_plugin_entries, dict)
        or not isinstance(normalized_pixel_plugin, dict)
        or not isinstance(normalized_pixel_config, dict)
        or not isinstance(normalized_agent_tools, dict)
        or not isinstance(normalized_agent_experimental, dict)
        or not isinstance(normalized_agent_deny, list)
        or not all(isinstance(item, str) for item in normalized_agent_deny)
        or not isinstance(normalized_sandbox_tools, dict)
        or not isinstance(normalized_sandbox_allow, list)
        or not all(isinstance(item, str) for item in normalized_sandbox_allow)
        or not isinstance(normalized_agent_sandbox, dict)
        or not isinstance(normalized_sandbox_docker, dict)):
    raise SystemExit("live Pixel runtime policy is outside the ODS contract")
normalized_agent_experimental["localModelLean"] = False
normalized_pixel_config["modelContextWindow"] = normalized_context_window
normalized_pixel_config["modelImageInput"] = image_input
normalized_pixel_config["leanPrompt"] = normalized_lean_prompt
route_fingerprint = contract.get("modelRouteFingerprint")
if route_fingerprint is not None and (provider != "ods-gateway" or not isinstance(route_fingerprint, str)
        or not re.fullmatch(r"[a-f0-9]{64}", route_fingerprint)):
    raise SystemExit("invalid candidate Pixel route identity")
if route_fingerprint is None:
    normalized_pixel_config.pop("modelRouteFingerprint", None)
else:
    normalized_pixel_config["modelRouteFingerprint"] = route_fingerprint
research_port = candidate.get("plugins", {}).get("entries", {}).get("pixel-ods", {}).get("config", {}).get("perplexicaPort", 3004)
if type(research_port) is not int or not 1 <= research_port <= 65535:
    raise SystemExit("invalid Perplexica service port")
normalized_pixel_config["perplexicaPort"] = research_port
# Structured Tool Search keeps the catalog compact for every model. Exact ODS
# routes are injected by the guard when required; otherwise models can search,
# describe, and call the same complete authorized catalog without an allowlist.
normalized_tools["toolSearch"] = {
    "enabled": True,
    "mode": "tools",
    "searchDefaultLimit": 5,
    "maxSearchLimit": 10,
}
exec_control_bind = "{}:/run/pixel-ods-control:ro".format(
    pathlib.Path.home() / ".openclaw" / ".ods-exec-control"
)
existing_binds = normalized_sandbox_docker.get("binds", [])
if existing_binds not in ([], [exec_control_bind]):
    raise SystemExit("live Pixel sandbox binds are outside the ODS contract")
normalized_sandbox_docker["binds"] = [exec_control_bind]
normalized_sandbox_docker["dangerouslyAllowExternalBindSources"] = True
# Docker's nproc ulimit is accounted against the host UID, not only this
# container. On a busy inference host it can therefore prevent even the fixed
# sandbox proof from forking while the independent per-container pidsLimit is
# still almost empty. Keep that cgroup limit and any other ulimits, but remove
# the cross-service nproc ceiling from the ODS-managed Pixel sandbox.
normalized_sandbox_docker["pidsLimit"] = 1024
normalized_sandbox_ulimits = normalized_sandbox_docker.get("ulimits")
if normalized_sandbox_ulimits is not None:
    if not isinstance(normalized_sandbox_ulimits, dict):
        raise SystemExit("live Pixel sandbox ulimits are outside the ODS contract")
    normalized_sandbox_ulimits.pop("nproc", None)
    if not normalized_sandbox_ulimits:
        normalized_sandbox_docker.pop("ulimits", None)
# OpenClaw's OpenAI-compatible transport adds a 1.25 character-based input
# safety margin after its independent pre-prompt compaction estimate. Reserve
# enough headroom that the precheck runs before that transport can silently
# clamp a useful model continuation down to one token. Algebraically this is
# context - ((context - output) / 1.25), rounded up.
normalized_compaction["reserveTokens"] = (
    contract.get("modelContextWindow") + 4 * contract.get("modelMaxTokens") + 4
) // 5
normalized_compaction["reserveTokensFloor"] = 0
# OpenClaw otherwise retains its fixed 20K recent-token default. On compact
# contexts that can select nothing to summarize, create a no-op compaction,
# and then reject the useful retry as already compacted. Keep a context-scaled
# recent tail so every admitted context can actually recover while preserving
# the newest tool evidence and continuation state.
normalized_compaction["keepRecentTokens"] = max(
    512,
    min(20000, normalized_context_window // 16),
)
normalized_diagnostics["stuckSessionAbortMs"] = 1860000
normalized_write_lock["maxHoldMs"] = 1920000
normalized_write_lock["staleMs"] = 3600000
normalized_tools["loopDetection"] = {
    "enabled": True,
    "historySize": 12,
    "warningThreshold": 2,
    "unknownToolThreshold": 2,
    "criticalThreshold": 4,
    "globalCircuitBreakerThreshold": 6,
    "detectors": {
        "genericRepeat": True,
        "knownPollNoProgress": True,
        "pingPong": True,
    },
}
normalized_fetch.update({
    "enabled": True,
    "maxChars": 12000,
    "maxCharsCap": 20000,
    "maxResponseBytes": 1000000,
    "timeoutSeconds": 20,
    "cacheTtlMinutes": 15,
    "maxRedirects": 3,
    "readability": True,
    "useTrustedEnvProxy": False,
    "ssrfPolicy": {
        "allowRfc2544BenchmarkRange": False,
        "allowIpv6UniqueLocalRange": False,
    },
})
normalized_agent_tools["deny"] = [
    item for item in normalized_agent_deny
    if item not in {
        "web_search", "web_fetch", "pixel_ods_status", "pixel_ods_apps_list", "pixel_ods_extensions", "pixel_ods_host_observe", "pixel_ods_host_command_propose",
        "pixel_ods_evidence_report", "pixel_ods_evidence_readback",
        "pixel_ods_research", "pixel_ods_web_extract", "pixel_ods_download_promote", "pixel_ods_workspace_preview", "pixel_ods_workspace_bundle", "pixel_ods_ask_user", "pixel_ods_goal", "pixel_ods_activity", "pixel_ods_history", "pixel_ods_image_read", "pixel_ods_skill", "pixel_ods_extension_proposal", "pixel_ods_source_proposal", "pixel_ods_python_library_proposal", "pixel_ods_extension_request_status", "pixel_ods_extension_request_prepare", "pixel_ods_extension_request_advance", "pixel_ods_extension_request_retry",
        "pixel_web_extract"
    }
]
normalized_also_allow = [item for item in normalized_also_allow if item != "pixel_web_extract"]
normalized_sandbox_allow = [item for item in normalized_sandbox_allow if item != "pixel_web_extract"]
for extension_tool in (
    "cron", "create_goal", "get_goal", "update_goal", "update_plan",
    "pixel_ods_status", "pixel_ods_apps_list", "pixel_ods_extensions", "pixel_ods_host_observe", "pixel_ods_host_command_propose",
    "pixel_ods_evidence_report", "pixel_ods_evidence_readback",
    "pixel_ods_research", "pixel_ods_web_extract", "pixel_ods_download_promote", "pixel_ods_workspace_preview", "pixel_ods_workspace_bundle", "pixel_ods_workspace_artifact", "pixel_ods_ask_user", "pixel_ods_goal", "pixel_ods_activity", "pixel_ods_history", "pixel_ods_image_read", "pixel_ods_skill", "pixel_ods_extension_proposal", "pixel_ods_source_proposal", "pixel_ods_python_library_proposal", "pixel_ods_extension_request_status", "pixel_ods_extension_request_prepare", "pixel_ods_extension_request_advance", "pixel_ods_extension_request_retry"
):
    if extension_tool not in normalized_also_allow:
        normalized_also_allow.append(extension_tool)
for permitted_tool in (
    "cron", "create_goal", "get_goal", "update_goal", "update_plan",
    "web_search", "web_fetch", "pixel_ods_status", "pixel_ods_apps_list", "pixel_ods_extensions", "pixel_ods_host_observe", "pixel_ods_host_command_propose",
    "pixel_ods_evidence_report", "pixel_ods_evidence_readback",
    "pixel_ods_research", "pixel_ods_web_extract", "pixel_ods_download_promote", "pixel_ods_workspace_preview", "pixel_ods_workspace_bundle", "pixel_ods_workspace_artifact", "pixel_ods_ask_user", "pixel_ods_goal", "pixel_ods_activity", "pixel_ods_history", "pixel_ods_image_read", "pixel_ods_skill", "pixel_ods_extension_proposal", "pixel_ods_source_proposal", "pixel_ods_python_library_proposal", "pixel_ods_extension_request_status", "pixel_ods_extension_request_prepare", "pixel_ods_extension_request_advance", "pixel_ods_extension_request_retry"
):
    if permitted_tool not in normalized_sandbox_allow:
        normalized_sandbox_allow.append(permitted_tool)
normalized_tools["alsoAllow"] = sorted(set(normalized_also_allow))
normalized_sandbox_tools["allow"] = sorted(set(normalized_sandbox_allow))
inspection_tool = 'pixel_ods_workspace_preview_inspect'
inspection_enabled = normalized_pixel_config.get('workspacePreviewInspectionTransport') in ('unix', 'native')
for tools in (normalized_tools['alsoAllow'], normalized_sandbox_tools['allow']):
    if inspection_enabled and inspection_tool not in tools:
        tools.append(inspection_tool)
        tools.sort()
    elif not inspection_enabled and inspection_tool in tools:
        tools.remove(inspection_tool)
if inspection_enabled:
    normalized_agent_tools['deny'] = [tool for tool in normalized_agent_tools['deny'] if tool != inspection_tool]
project_socket = normalized_pixel_config.get('projectBuildSocket')
project_enabled = (isinstance(project_socket, str) and project_socket.startswith('/')
                   and '\x00' not in project_socket and 2 <= len(project_socket) <= 100)
project_tool = 'pixel_ods_project_build'
for tools in (normalized_tools['alsoAllow'], normalized_sandbox_tools['allow']):
    if project_enabled and project_tool not in tools:
        tools.append(project_tool)
        tools.sort()
    elif not project_enabled and project_tool in tools:
        tools.remove(project_tool)
if project_enabled:
    normalized_agent_tools['deny'] = [tool for tool in normalized_agent_tools['deny'] if tool != project_tool]
enable_thinking_switch = ("qwen" in model_label if thinking_control is None
                          else thinking_control == "enable_thinking")
if enable_thinking_switch and model_reasoning is True:
    normalized_model["compat"] = {"thinkingFormat": "qwen-chat-template"}
    normalized_agent["thinkingDefault"] = "low"
else:
    normalized_model.pop("compat", None)
    normalized_agent.pop("thinkingDefault", None)
normalized_agent_params = normalized_agent.setdefault("params", {})
if not isinstance(normalized_agent_params, dict):
    raise SystemExit("live Pixel agent parameters are outside the ODS contract")
if enable_thinking_switch:
    template_kwargs = normalized_agent_params.setdefault("chat_template_kwargs", {})
    if not isinstance(template_kwargs, dict):
        raise SystemExit("live Pixel chat-template parameters are outside the ODS contract")
    template_kwargs["enable_thinking"] = model_reasoning is True
else:
    template_kwargs = normalized_agent_params.get("chat_template_kwargs")
    if isinstance(template_kwargs, dict):
        template_kwargs.pop("enable_thinking", None)
        if not template_kwargs:
            normalized_agent_params.pop("chat_template_kwargs", None)
    if not normalized_agent_params:
        normalized_agent.pop("params", None)
normalized_compact_sampling = {
    "temperature": 0.7,
    "topP": 0.8,
    "frequencyPenalty": 0.6,
    "presencePenalty": 0.2,
}
if normalized_lean_prompt:
    normalized_agent["params"] = normalized_agent_params
    normalized_agent_params.update(normalized_compact_sampling)
else:
    for key in normalized_compact_sampling:
        normalized_agent_params.pop(key, None)
if not normalized_agent_params:
    normalized_agent.pop("params", None)
selected_search = contract.get("webSearchProvider")
if selected_search is not None:
    if selected_search not in {"searxng", "parallel-free"}:
        raise SystemExit("invalid selected Pixel search provider")
    live_search = live.get("tools", {}).get("web", {}).get("search")
    candidate_search = candidate.get("tools", {}).get("web", {}).get("search")
    if candidate_search != {"provider": selected_search}:
        raise SystemExit("candidate search provider differs from onboarding")
    if live_search != candidate_search or normalized_plugins != candidate.get("plugins"):
        if live_search not in ({"provider": "searxng"}, {"provider": "parallel-free"}):
            raise SystemExit("live search provider is outside the ODS contract")
        extensions = contract.get("gatewayExtensions")
        if not isinstance(extensions, list):
            raise SystemExit("invalid search extension contract")
        parallel = [item for item in extensions if isinstance(item, dict) and item.get("id") == "parallel"]
        parallel_path = str(pathlib.Path(sys.argv[4]) / "data/pixel/native-search/parallel-2026.6.33")
        if selected_search == "parallel-free":
            if (len(parallel) != 1 or parallel[0].get("path") != parallel_path
                    or not isinstance(parallel[0].get("sha256"), str)
                    or not re.fullmatch(r"[0-9a-f]{64}", parallel[0]["sha256"])):
                raise SystemExit("parallel search extension is not bound to its pinned path and digest")
        elif parallel:
            raise SystemExit("SearXNG selection unexpectedly includes the parallel extension")
        elif (not isinstance(contract.get("searxngBaseUrl"), str)
                or not re.fullmatch(r"http://127\.0\.0\.1:[1-9][0-9]{0,4}", contract["searxngBaseUrl"])
                or int(contract["searxngBaseUrl"].rsplit(":", 1)[1]) > 65535):
            raise SystemExit("SearXNG selection lacks a loopback search origin")

        def without_search(values):
            if (not isinstance(values, list)
                    or any(not isinstance(item, str) for item in values)
                    or len(values) != len(set(values))):
                raise SystemExit("invalid search plugin list")
            return [item for item in values if item not in {"parallel", "searxng"}]

        before_allow = normalized_plugins.get("allow")
        after_allow = candidate.get("plugins", {}).get("allow")
        if without_search(before_allow) != without_search(after_allow):
            raise SystemExit("candidate changes unrelated plugin allowlist")
        expected_plugin = "parallel" if selected_search == "parallel-free" else "searxng"
        if ([item for item in after_allow if item in {"parallel", "searxng"}]
                != [expected_plugin]):
            raise SystemExit("candidate search plugin allowlist is invalid")

        candidate_entries = candidate.get("plugins", {}).get("entries")
        if not isinstance(candidate_entries, dict):
            raise SystemExit("invalid candidate plugin entries")
        for plugin_id in ("parallel", "searxng"):
            normalized_plugin_entries.pop(plugin_id, None)
        unrelated_entries = {key: value for key, value in candidate_entries.items()
                             if key not in {"parallel", "searxng"}}
        if normalized_plugin_entries != unrelated_entries:
            raise SystemExit("candidate changes unrelated plugin entries")
        if selected_search == "parallel-free":
            if candidate_entries.get("parallel") != {"enabled": True} or "searxng" in candidate_entries:
                raise SystemExit("candidate parallel plugin registration is invalid")
        else:
            expected_entry = {"enabled": True, "config": {"webSearch": {
                "baseUrl": contract.get("searxngBaseUrl")}}}
            if (candidate_entries.get("searxng") != expected_entry
                    or "parallel" in candidate_entries):
                raise SystemExit("candidate SearXNG plugin registration is invalid")

        before_load = normalized_plugins.get("load")
        after_load = candidate.get("plugins", {}).get("load")
        if not isinstance(before_load, dict) or not isinstance(after_load, dict):
            raise SystemExit("invalid search plugin load policy")
        before_paths, after_paths = before_load.get("paths"), after_load.get("paths")
        if (not isinstance(before_paths, list) or not isinstance(after_paths, list)
                or any(not isinstance(item, str) for item in before_paths + after_paths)
                or len(before_paths) != len(set(before_paths))
                or len(after_paths) != len(set(after_paths))
                or [path for path in before_paths if path != parallel_path]
                != [path for path in after_paths if path != parallel_path]):
            raise SystemExit("candidate changes unrelated plugin load paths")
        if (parallel_path in after_paths) != (selected_search == "parallel-free"):
            raise SystemExit("candidate search plugin path selection is invalid")

        normalized_web["search"] = copy.deepcopy(candidate_search)
        normalized_plugins["allow"] = copy.deepcopy(after_allow)
        normalized_plugin_entries[expected_plugin] = copy.deepcopy(candidate_entries[expected_plugin])
        normalized_plugins["load"]["paths"] = copy.deepcopy(after_paths)
if normalized != candidate:
    raise SystemExit("candidate changes more than the ODS managed model/runtime fields")
PY
}

_ods_pixel_atomic_replace_managed_file() {
    local owner="$1" home="$2" source="$3" target="$4"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$source" "$target" <<'PY'
import os, pathlib, stat, sys, tempfile

source = pathlib.Path(sys.argv[1])
target = pathlib.Path(sys.argv[2])
for path in (source,):
    info = path.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_nlink != 1
            or info.st_uid != os.getuid() or info.st_mode & 0o077
            or info.st_size > 2 * 1024 * 1024):
        raise SystemExit(f"unsafe managed file: {path}")
if target.exists() or target.is_symlink():
    info = target.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_nlink != 1
            or info.st_uid != os.getuid() or info.st_mode & 0o077
            or info.st_size > 2 * 1024 * 1024):
        raise SystemExit(f"unsafe managed file: {target}")
parent_info = target.parent.lstat()
if (not stat.S_ISDIR(parent_info.st_mode) or stat.S_ISLNK(parent_info.st_mode)
        or parent_info.st_uid != os.getuid() or parent_info.st_mode & 0o022):
    raise SystemExit(f"unsafe managed directory: {target.parent}")
payload = source.read_bytes()
fd, temporary = tempfile.mkstemp(prefix=f".{target.name}.", dir=target.parent)
try:
    with os.fdopen(fd, "wb") as handle:
        handle.write(payload)
        handle.flush()
        os.fsync(handle.fileno())
    os.chmod(temporary, 0o600)
    os.replace(temporary, target)
finally:
    if os.path.exists(temporary):
        os.unlink(temporary)
PY
}

_ods_pixel_install_onboarding_mirror() {
    local owner="$1" home="$2" answers="$3"
    local installed_answers="$home/.config/pixel-deployment/onboarding.json"
    # Pixel configure normally maintains this copy. Stable-alias model changes
    # deliberately skip configure, so they must publish it in the same model
    # transaction. Uninstall verifies these exact bytes against the ready marker.
    _ods_pixel_atomic_replace_managed_file "$owner" "$home" "$answers" "$installed_answers" || return 1
    ods_pixel_run_as_owner "$owner" "$home" cmp -s -- "$answers" "$installed_answers"
}

_ods_pixel_openclaw_bin() {
    local owner="$1" home="$2"
    # Expansion is intentionally performed in the owner shell, not here.
    # shellcheck disable=SC2016
    ods_pixel_run_as_owner "$owner" "$home" bash -c \
        'if [[ -x "$HOME/.npm-global/bin/openclaw" ]]; then printf "%s\\n" "$HOME/.npm-global/bin/openclaw"; else command -v openclaw; fi'
}

_ods_pixel_secure_plugin_tree() {
    local owner="$1" home="$2" plugin_root="$3" expected path
    expected="${INSTALL_DIR:?}/extensions/services/pixel-agent/plugin"
    [[ "$plugin_root" == "$expected" ]] || return 1

    # A source copied from a Windows mount can arrive as mode 0777 even when
    # the Git blob is ordinary read-only code. OpenClaw correctly blocks any
    # plugin below a group/world-writable ancestor, so normalize only this
    # fixed ODS-owned path and fail closed on links, special files, or foreign
    # ownership before calculating the approved extension digest.
    for path in \
        "$INSTALL_DIR" \
        "$INSTALL_DIR/extensions" \
        "$INSTALL_DIR/extensions/services" \
        "$INSTALL_DIR/extensions/services/pixel-agent" \
        "$plugin_root"; do
        [[ -d "$path" && ! -L "$path" ]] || return 1
        [[ "$(stat -c '%u' -- "$path")" == "$(id -u "$owner")" ]] || return 1
        ods_pixel_run_as_owner "$owner" "$home" chmod 0755 "$path" || return 1
    done
    if find -P "$plugin_root" -mindepth 1 \( -type l -o ! -user "$owner" \) -print -quit | grep -q .; then
        return 1
    fi
    if find -P "$plugin_root" -mindepth 1 ! -type d ! -type f -print -quit | grep -q .; then
        return 1
    fi
    ods_pixel_run_as_owner "$owner" "$home" find -P "$plugin_root" -type d -exec chmod 0755 '{}' + || return 1
    ods_pixel_run_as_owner "$owner" "$home" find -P "$plugin_root" -type f -exec chmod 0644 '{}' + || return 1
    if find -P "$plugin_root" -perm /022 -print -quit | grep -q .; then
        return 1
    fi
}

_ods_pixel_refresh_plugin_registry() {
    local owner="$1" home="$2" openclaw_bin="$3" plugin_root="$4" registry
    registry="$(ods_pixel_run_as_owner "$owner" "$home" "$openclaw_bin" \
        plugins registry --refresh --json 2>/dev/null)" || return 1
    jq -e --arg root "$plugin_root" '
        (["pixel_ods_apps_list", "pixel_ods_download_promote", "pixel_ods_evidence_readback", "pixel_ods_evidence_report", "pixel_ods_extensions", "pixel_ods_host_command_propose", "pixel_ods_host_observe", "pixel_ods_status", "pixel_ods_research", "pixel_ods_web_extract", "pixel_ods_workspace_preview", "pixel_ods_project_build", "pixel_ods_workspace_artifact", "pixel_ods_workspace_bundle", "pixel_ods_workspace_preview_inspect", "pixel_ods_ask_user", "pixel_ods_goal", "pixel_ods_activity", "pixel_ods_history", "pixel_ods_image_read", "pixel_ods_skill", "pixel_ods_extension_proposal", "pixel_ods_source_proposal", "pixel_ods_python_library_proposal", "pixel_ods_extension_request_status", "pixel_ods_extension_request_prepare", "pixel_ods_extension_request_advance", "pixel_ods_extension_request_retry"] | sort) as $tools
        | .refreshed == true
        and .registry.version == 1
        and .registry.refreshReason == "manual"
        and ([
            .registry.plugins[]?
            | select(
                .pluginId == "pixel-ods"
                and .enabled == true
                and .rootDir == $root
                and ((.contributions.contracts.tools // []) | sort) == $tools
            )
        ] | length == 1)
    ' <<<"$registry" >/dev/null
}

_ods_pixel_verify_plugin_loaded() {
    local owner="$1" home="$2" openclaw_bin="$3" plugin_root="$4"
    ods_pixel_run_as_owner "$owner" "$home" "$openclaw_bin" plugins list --json 2>/dev/null \
        | jq -e --arg root "$plugin_root" '
            ["pixel_ods_apps_list", "pixel_ods_download_promote", "pixel_ods_evidence_readback", "pixel_ods_evidence_report", "pixel_ods_extensions", "pixel_ods_host_command_propose", "pixel_ods_host_observe", "pixel_ods_status", "pixel_ods_research", "pixel_ods_web_extract", "pixel_ods_workspace_preview", "pixel_ods_project_build", "pixel_ods_workspace_artifact", "pixel_ods_workspace_bundle", "pixel_ods_workspace_preview_inspect", "pixel_ods_ask_user", "pixel_ods_goal", "pixel_ods_activity", "pixel_ods_history", "pixel_ods_image_read", "pixel_ods_skill", "pixel_ods_extension_proposal", "pixel_ods_source_proposal", "pixel_ods_python_library_proposal", "pixel_ods_extension_request_status", "pixel_ods_extension_request_prepare", "pixel_ods_extension_request_advance", "pixel_ods_extension_request_retry"] as $tools
            | [
                .plugins[]?
                | select(
                    .id == "pixel-ods"
                    and .status == "loaded"
                    and .rootDir == $root
                    and ((.contracts.tools // []) | sort) == ($tools | sort)
                )
            ] | length == 1
        ' \
            >/dev/null
}

_ods_pixel_exec_control_stat() {
    local field="$1" path="$2" format
    case "$(uname -s)" in
        Darwin)
            case "$field" in owner) format='%Su' ;; links) format='%l' ;; mode) format='%Lp' ;; *) return 1 ;; esac
            /usr/bin/stat -f "$format" "$path"
            ;;
        Linux)
            case "$field" in owner) format='%U' ;; links) format='%h' ;; mode) format='%a' ;; *) return 1 ;; esac
            stat -c "$format" -- "$path"
            ;;
        *) return 1 ;;
    esac
}

_ods_pixel_install_exec_control() {
    local owner="$1" home="$2" source="$3" sudo_source="$4"
    local parent="$home/.openclaw" root="$home/.openclaw/.ods-exec-control"
    local candidate
    for candidate in "$source" "$sudo_source"; do
        [[ -f "$candidate" && ! -L "$candidate" \
            && "$(_ods_pixel_exec_control_stat owner "$candidate")" == "$owner" \
            && "$(_ods_pixel_exec_control_stat links "$candidate")" == 1 ]] || return 1
        (( (8#$(_ods_pixel_exec_control_stat mode "$candidate") & 0022) == 0 )) || return 1
    done
    # A clean Pixel install has not run OpenClaw bootstrap yet, so its private
    # state directory legitimately does not exist. Create only that exact
    # owner path, then apply the same ownership/symlink/mode checks used for an
    # existing installation. Never follow or replace an ambient path.
    if [[ ! -e "$parent" && ! -L "$parent" ]]; then
        ods_pixel_run_as_owner "$owner" "$home" install -d -m 0700 -- "$parent" || return 1
    fi
    [[ -d "$parent" && ! -L "$parent" \
        && "$(_ods_pixel_exec_control_stat owner "$parent")" == "$owner" ]] || return 1
    (( (8#$(_ods_pixel_exec_control_stat mode "$parent") & 0022) == 0 )) || return 1
    if [[ -e "$root" || -L "$root" ]]; then
        [[ -d "$root" && ! -L "$root" && "$(_ods_pixel_exec_control_stat owner "$root")" == "$owner" \
            && "$(_ods_pixel_exec_control_stat mode "$root")" == 700 ]] || return 1
    fi
    for candidate in "$root/cancellable-exec.sh" "$root/sudo"; do
        if [[ -e "$candidate" || -L "$candidate" ]]; then
            [[ -f "$candidate" && ! -L "$candidate" \
                && "$(_ods_pixel_exec_control_stat owner "$candidate")" == "$owner" \
                && "$(_ods_pixel_exec_control_stat links "$candidate")" == 1 ]] || return 1
        fi
    done
    ods_pixel_run_as_owner "$owner" "$home" install -d -m 0700 -- "$root" || return 1
    ods_pixel_run_as_owner "$owner" "$home" install -m 0500 -- \
        "$source" "$root/cancellable-exec.sh" || return 1
    ods_pixel_run_as_owner "$owner" "$home" install -m 0500 -- \
        "$sudo_source" "$root/sudo" || return 1
    [[ -d "$root" && ! -L "$root" \
        && -f "$root/cancellable-exec.sh" && ! -L "$root/cancellable-exec.sh" \
        && -f "$root/sudo" && ! -L "$root/sudo" \
        && "$(_ods_pixel_exec_control_stat owner "$root")" == "$owner" \
        && "$(_ods_pixel_exec_control_stat owner "$root/cancellable-exec.sh")" == "$owner" \
        && "$(_ods_pixel_exec_control_stat owner "$root/sudo")" == "$owner" \
        && "$(_ods_pixel_exec_control_stat mode "$root")" == 700 \
        && "$(_ods_pixel_exec_control_stat links "$root/cancellable-exec.sh")" == 1 \
        && "$(_ods_pixel_exec_control_stat mode "$root/cancellable-exec.sh")" == 500 \
        && "$(_ods_pixel_exec_control_stat links "$root/sudo")" == 1 \
        && "$(_ods_pixel_exec_control_stat mode "$root/sudo")" == 500 ]]
}

# PIXEL_RESPONSE_LANGUAGE=en fixes Pixel's replies, questions and created
# content to English. The plugin reads this owner file from the OpenClaw state
# folder at start. A plugin config key would break a rollback to a release
# whose config schema rejects it; an older plugin simply ignores this file.
_ods_pixel_install_response_language() {
    local owner="$1" home="$2" language="${PIXEL_RESPONSE_LANGUAGE:-}"
    local parent="$home/.openclaw" target="$home/.openclaw/.ods-response-language"
    case "$language" in
        ""|en) ;;
        *) return 1 ;;
    esac
    [[ -d "$parent" && ! -L "$parent" \
        && "$(_ods_pixel_exec_control_stat owner "$parent")" == "$owner" ]] || return 1
    if [[ -e "$target" || -L "$target" ]]; then
        [[ -f "$target" && ! -L "$target" \
            && "$(_ods_pixel_exec_control_stat owner "$target")" == "$owner" ]] || return 1
    fi
    if [[ -z "$language" ]]; then
        ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$target"
        return
    fi
    ods_pixel_run_as_owner "$owner" "$home" sh -c \
        'umask 077 && printf "en\n" > "$1.new" && mv -f -- "$1.new" "$1"' sh "$target"
}

# Pixel bootstrap ends with this exact message when its sandbox candidate does
# not run the pinned Node.js (vendor/pixel/scripts/bootstrap.sh). Print that
# candidate's tag, so the owner is told which image to remove.
_ods_pixel_failed_sandbox_proof_candidate() {
    local log="$1" line
    line="$(tail -n 5 -- "$log" | grep -F '[pixel] ERROR: Sandbox runtime proof failed: ' | tail -n 1)" || return 1
    [[ "$line" =~ Sandbox\ runtime\ proof\ failed:\ (pixel-sandbox-candidate:[0-9]{1,6}\.[0-9]{1,6}\.[0-9]{1,6}-uid-[1-9][0-9]*)\  ]] \
        || return 1
    printf '%s\n' "${BASH_REMATCH[1]}"
}

# Portal tells the agent its sandbox has node (pixel-agent prompt-contract.mjs).
# The bundled Pixel bootstrap proves that before it succeeds; a developer
# PIXEL_SOURCE_URL checkout older than Pixel 4.3.32 builds a sandbox without
# node and has no such proof. Require the candidate bootstrap just prepared to
# carry the Node.js label, as macOS preparation requires the pinned runtime.
_ods_pixel_sandbox_candidate_has_node() {
    local owner="$1" home="$2" pixel_root="$3" version uid label
    [[ -f "$pixel_root/VERSION" && ! -L "$pixel_root/VERSION" ]] || return 1
    version="$(ods_pixel_run_as_owner "$owner" "$home" sed -n '1p' "$pixel_root/VERSION")" || return 1
    [[ "$version" =~ ^[0-9]{1,6}\.[0-9]{1,6}\.[0-9]{1,6}$ ]] || return 1
    uid="$(id -u "$owner")" || return 1
    [[ "$uid" =~ ^[1-9][0-9]*$ ]] || return 1
    label="$(ods_pixel_run_as_owner "$owner" "$home" docker image inspect \
        --format '{{index .Config.Labels "org.osmantic.pixel.sandbox-node"}}' \
        "pixel-sandbox-candidate:$version-uid-$uid")" || return 1
    [[ "$label" =~ ^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}$ ]]
}

_ods_pixel_recreate_agent_sandbox() {
    local owner="$1" home="$2" openclaw_bin="$3" remaining
    [[ "$openclaw_bin" == /* && -x "$openclaw_bin" ]] || return 1
    ods_pixel_run_as_owner "$owner" "$home" "$openclaw_bin" \
        sandbox recreate --agent pixel --force || return 1
    # OpenClaw retires only sandboxes present in its registry. Independently
    # prove that Docker has no stale agent-scoped container left behind before
    # a gateway restart can accept another tool turn. This catches registry
    # drift as well as a failed runtime removal without broadening the scope to
    # any non-Pixel container.
    remaining="$(ods_pixel_run_as_owner "$owner" "$home" docker ps --all --quiet \
        --filter 'name=^/pixel-sbx-agent-pixel-')" || return 1
    [[ -z "${remaining//[[:space:]]/}" ]]
}

_ods_pixel_apply_runtime_budget() {
    local owner="$1" home="$2" config="$3" openclaw_bin="$4" staged
    local answers="${5:-}" inspection_transport="${6:-}" project_socket="${7:-}"
    # ODS qualifies Pixel on CPU-only hosts. The first local 9B turn can spend
    # more than five minutes loading and prefilling its managed context, while
    # OpenClaw's default session watchdogs assume a responsive remote model.
    # Keep the larger CPU-only budgets deterministic and confined to this
    # ODS-owned Pixel route.
    local budget_writer
    budget_writer="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/pixel-runtime-budget.py"
    staged="$(ods_pixel_run_as_owner "$owner" "$home" python3 "$budget_writer" \
        "$config" "${PERPLEXICA_PORT:-3004}" "$answers" "$home/.openclaw" "$inspection_transport" "$project_socket")" || return 1
    if [[ "$staged" == unchanged ]]; then
        printf '%s\n' unchanged
        return 0
    fi
    [[ "$staged" == "${config%/*}/.ods-pixel-runtime-budget."* && -f "$staged" && ! -L "$staged" ]] || return 1
    if ! ods_pixel_run_as_owner "$owner" "$home" env OPENCLAW_CONFIG_PATH="$staged" \
        "$openclaw_bin" config validate >/dev/null 2>&1; then
        ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$staged"
        return 1
    fi
    if ! _ods_pixel_atomic_replace_managed_file "$owner" "$home" "$staged" "$config"; then
        ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$staged"
        return 1
    fi
    ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$staged" || return 1
    printf '%s\n' changed
}

_ods_pixel_verify_current_runtime() {
    local owner="$1" home="$2" pixel_root="$3" transaction_id="${4:-}"
    local verify_attempt owns_transaction=false openclaw_bin
    local -a verify_arguments=()
    if [[ -z "$transaction_id" && -n "${ODS_PIXEL_SOURCE_TRANSACTION:-}" ]]; then
        _ods_pixel_check_source_transaction "$owner" || return 1
        transaction_id="$ODS_PIXEL_SOURCE_TRANSACTION"
    fi
    if [[ -z "$transaction_id" ]]; then
        # Standalone sandboxed installations retain Pixel's strict verifier.
        # A relaxed boundary is never inferred to be authorized from systemd:
        # acquire a protected transaction and let its fresh runtime proof
        # establish the configured mode before verifying this exact process.
        if [[ "$(systemctl show openclaw-gateway.service -p ProtectHome --value)" != tmpfs \
            || "$(systemctl show openclaw-gateway.service -p ProtectSystem --value)" != strict ]]; then
            openclaw_bin="$(_ods_pixel_openclaw_bin "$owner" "$home")" || return 1
            _ods_pixel_install_access_service "$owner" "$openclaw_bin" || return 1
            transaction_id="$(_ods_pixel_model_transition begin "$owner" "$home")" || return 1
            [[ "$transaction_id" =~ ^[a-f0-9]{64}$ ]] || return 1
            owns_transaction=true
        fi
    fi
    if [[ -n "$transaction_id" ]]; then
        [[ "$transaction_id" =~ ^[a-f0-9]{64}$ ]] || return 1
        verify_arguments=(--ods-model-transaction "$transaction_id")
    fi
    for verify_attempt in 1 2 3; do
        if ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" verify "${verify_arguments[@]}"; then
            if [[ "$owns_transaction" == true ]]; then
                _ods_pixel_model_transition finish "$owner" "$home" "$transaction_id" applied || return 1
            fi
            return 0
        fi
        if (( verify_attempt < 3 )); then
            printf '%s\n' "Pixel verification did not settle after gateway restart (attempt ${verify_attempt}/3); retrying..." >&2
            sleep 2
        fi
    done
    if [[ "$owns_transaction" == true ]]; then
        printf 'Pixel verification failed; admission remains held for transaction %s. Repair the reported verification failure before recovery.\n' "$transaction_id" >&2
    fi
    return 1
}

# Reruns ask the access coordinator for pending state before anything else.
# Only an uninstall stops it (disable --now, first), and a later fail-closed
# uninstall step can return early and leave it stopped across reboots. Start
# it again for a deployment that is still ready or installing; never for one
# an uninstall is deactivating.
_ods_pixel_start_stopped_access_service() {
    local owner="$1" home="$2" requested_ref="$3" transition state attempt
    local unit="${ODS_PIXEL_ACCESS_UNIT_PATH:-/etc/systemd/system/ods-pixel-access.service}"
    local socket="${ODS_PIXEL_ACCESS_SOCKET_PATH:-/run/ods-pixel-access/control.sock}"
    [[ -f "$unit" && ! -L "$unit" ]] || return 0
    systemctl is-active --quiet ods-pixel-access.service && return 0
    transition="$(_ods_pixel_source_transition_state "$owner" "$home" "$requested_ref")" || return 0
    state="${transition%%|*}"
    [[ "$state" == ready || "$state" == installing ]] || return 0
    ods_sudo_available || return 0
    ai "Starting the stopped Pixel access coordinator..."
    ods_sudo systemctl enable --now ods-pixel-access.service || return 1
    for ((attempt = 1; attempt <= 30; attempt++)); do
        [[ -S "$socket" ]] && return 0
        sleep 1
    done
    return 1
}

_ods_pixel_resume_completed_release() {
    local owner="$1" home="$2" pixel_root="$3" contract_sha="$4"
    local status resume transaction_id outcome config_sha observed
    local helper="${ODS_PIXEL_ACCESS_HELPER:-/usr/local/libexec/ods-pixel-access/pixel_model_transition.py}"
    local unit="${ODS_PIXEL_ACCESS_UNIT_PATH:-/etc/systemd/system/ods-pixel-access.service}"
    local state_dir="${ODS_PIXEL_ACCESS_STATE_DIR:-/var/lib/ods-pixel-access}"
    [[ -f "$helper" && ! -L "$helper" ]] || return 0
    # The coordinator's helpers are written before its unit. A first install
    # that stopped between the two never ran a coordinator, so it recorded no
    # transition and there is nothing to resume; the install continues and
    # installs the coordinator. A recorded transition still needs recovery.
    if [[ ! -e "$unit" && ! -L "$unit" ]] && ods_sudo_available \
        && ! ods_sudo test -e "$state_dir/transition.json"; then
        return 0
    fi
    if ! _ods_pixel_start_stopped_access_service "$owner" "$home" "${PIXEL_SOURCE_REF:?}"; then
        printf '%s\n' 'error: the Pixel access coordinator is stopped and did not start; see journalctl -u ods-pixel-access.service' >&2
        return 1
    fi
    status="$(_ods_pixel_model_transition status "$owner" "$home")" || return 1
    if [[ -n "${ODS_PIXEL_SOURCE_TRANSACTION:-}" ]]; then
        _ods_pixel_check_source_transaction "$owner" || return 1
        if printf '%s' "$status" | python3 -c 'import json,sys; d=json.load(sys.stdin); sys.exit(0 if d.get("transaction_id")==sys.argv[1] and "release_completion" not in d else 1)' "$ODS_PIXEL_SOURCE_TRANSACTION"; then
            # This exact source update acquired admission before Phase06 copy.
            # No release has been applied yet; continue the same staged plan.
            return 0
        fi
    fi
    resume="$(printf '%s' "$status" | python3 -c '
import json,re,sys
d=json.load(sys.stdin)
if d == {"pending":False}:
    raise SystemExit(0)
c=d.get("release_completion")
if (d.get("pending") is not True or d.get("kind")!="model"
    or not isinstance(c,dict) or set(c)!={"outcome","config_sha256"}
    or c["outcome"] not in ("apply","rollback")
    or not all(isinstance(v,str) and re.fullmatch("[a-f0-9]{64}",v)
               for v in (d.get("transaction_id"),c["config_sha256"]))):
    raise SystemExit("Pixel has an unfinished transaction without a verified release completion; explicit recovery is required")
print(d["transaction_id"],c["outcome"],c["config_sha256"])
')" || return 1
    [[ -n "$resume" ]] || return 0
    read -r transaction_id outcome config_sha <<< "$resume"
    observed="$(ods_pixel_run_as_owner "$owner" "$home" sha256sum "$home/.openclaw/openclaw.json")" || return 1
    [[ "${observed%% *}" == "$config_sha" ]] || return 1
    # Root finish independently requires the durable release completion and
    # re-proves the process before releasing either admission gate. This also
    # handles a lost reply after native/edge release without applying again.
    if [[ "$outcome" == apply ]]; then
        _ods_pixel_model_transition finish "$owner" "$home" "$transaction_id" applied || return 1
    else
        _ods_pixel_model_transition finish "$owner" "$home" "$transaction_id" rolled-back || return 1
        return 0
    fi
    # Bind this source only after the full vendor verifier accepts it. A later
    # install of different source cannot turn an old receipt into a new pin.
    _ods_pixel_verify_current_runtime "$owner" "$home" "$pixel_root" || return 1
    _ods_pixel_mark_verified_installing "$owner" "$home" "$contract_sha" "$pixel_root"
}

_ods_pixel_begin_release_transition() {
    local owner="$1" home="$2" openclaw_bin transaction_id
    if [[ -n "${ODS_PIXEL_SOURCE_TRANSACTION:-}" ]]; then
        _ods_pixel_check_source_transaction "$owner" || return 1
        printf '%s\n' "$ODS_PIXEL_SOURCE_TRANSACTION"
        return 0
    fi
    # First installation and the ordinary sandboxed boundary need no access
    # migration. A relaxed boundary merely selects the coordinator: only its
    # authenticated begin/verification establishes the actual permission mode.
    [[ -f "$home/.openclaw/openclaw.json" ]] || return 0
    # configure may generate the initial native config before apply installs
    # any gateway. There is no previous access boundary to migrate in that case.
    if [[ ! -e "$home/.local/share/pixel/current" && ! -L "$home/.local/share/pixel/current" \
        && ! -e "$home/.local/share/pixel/runtime-attestation.json" \
        && ! -L "$home/.local/share/pixel/runtime-attestation.json" \
        && "$(systemctl show openclaw-gateway.service -p LoadState --value)" == not-found ]]; then
        return 0
    fi
    if [[ "$(systemctl show openclaw-gateway.service -p ProtectHome --value)" == tmpfs \
        && "$(systemctl show openclaw-gateway.service -p ProtectSystem --value)" == strict ]]; then
        return 0
    fi
    openclaw_bin="$(_ods_pixel_openclaw_bin "$owner" "$home")" || return 1
    _ods_pixel_install_access_service "$owner" "$openclaw_bin" >&2 || return 1
    transaction_id="$(_ods_pixel_model_transition begin "$owner" "$home")" || return 1
    [[ "$transaction_id" =~ ^[a-f0-9]{64}$ ]] || return 1
    printf '%s\n' "$transaction_id"
}

_ods_pixel_finish_release_transition() {
    local owner="$1" home="$2" pixel_root="$3" transaction_id="$4" config_sha attempt proved=false
    [[ "$transaction_id" =~ ^[a-f0-9]{64}$ ]] || return 1
    if [[ "$transaction_id" == "${ODS_PIXEL_SOURCE_TRANSACTION:-}" ]]; then
        _ods_pixel_check_source_transaction "$owner" || return 1
        if _ods_pixel_source_upgrade status "$owner" | jq -e '.mode == "sandboxed"' >/dev/null; then
            # Sandbox has no enabled receipt to migrate. Keep the same hold
            # through the ODS overlay and final runtime verification.
            return 0
        fi
    fi
    config_sha="$(ods_pixel_run_as_owner "$owner" "$home" sha256sum "$home/.openclaw/openclaw.json")" || return 1
    config_sha=${config_sha%% *}
    [[ "$config_sha" =~ ^[a-f0-9]{64}$ ]] || return 1
    # Retirement of the owner journal requires a fresh root runtime proof.
    # If the reply is lost, replay this finish; never start another migration
    # or restore only the JSON file over its associated permission receipt.
    for attempt in 1 2 3; do
        if ods_pixel_run_as_owner "$owner" "$home" python3 -I \
            "$pixel_root/scripts/lib/ods-release-access.py" finish \
            "$transaction_id" "$config_sha" apply >/dev/null; then
            proved=true
            break
        fi
        (( attempt == 3 )) || sleep 2
    done
    [[ "$proved" == true ]] || return 1
    for attempt in 1 2 3; do
        if _ods_pixel_model_transition finish "$owner" "$home" "$transaction_id" applied; then
            return 0
        fi
        (( attempt == 3 )) || sleep 2
    done
    return 1
}

_ods_pixel_restart_gateway_and_verify() {
    local owner="$1" home="$2" pixel_root="$3" attempt ready=false previous_pid current_pid gateway_port
    local transaction_id="${4:-}"
    [[ -z "$transaction_id" || "$transaction_id" =~ ^[a-f0-9]{64}$ ]] || return 1
    # Background model promotion does not inherit Phase 06's gateway-port
    # environment. Verify the installed, owner-validated endpoint rather than
    # probing the default port and leaving the model hold unreleased.
    gateway_port="$(_ods_pixel_installed_gateway_port "$owner" "$home")" || return 1
    previous_pid="$(systemctl show openclaw-gateway.service -p MainPID --value 2>/dev/null || true)"
    if ods_sudo_available; then
        # Writing the final ODS runtime overlay can make OpenClaw begin its own
        # supervised config restart before this helper samples MainPID. A
        # transient MainPID=0 is safe on the privileged systemd path because
        # `systemctl restart` establishes the desired service state directly.
        # Keep the stricter live-PID proof below for the unprivileged signal
        # fallback, where ODS must prove exactly which owner process it kills.
        ods_sudo systemctl restart openclaw-gateway.service || return 1
    else
        # The ODS host agent runs as the same unprivileged install owner. Its
        # non-interactive sudo credential may expire long after installation,
        # so allow one narrow restart path without granting general sudo: the
        # verified system unit must run as this owner with Restart=always, and
        # /proc must prove the current MainPID has that owner's UID. SIGTERM is
        # then enough for systemd to replace the process under the same unit.
        local unit_user restart_policy owner_uid process_uid
        [[ "$previous_pid" =~ ^[1-9][0-9]*$ ]] || return 1
        unit_user="$(systemctl show openclaw-gateway.service -p User --value 2>/dev/null || true)"
        restart_policy="$(systemctl show openclaw-gateway.service -p Restart --value 2>/dev/null || true)"
        owner_uid="$(id -u "$owner" 2>/dev/null || true)"
        process_uid="$(awk '/^Uid:/ { print $2; exit }' "/proc/${previous_pid}/status" 2>/dev/null || true)"
        [[ "$(id -un)" == "$owner" && "$unit_user" == "$owner" \
            && "$restart_policy" == "always" && "$owner_uid" =~ ^[0-9]+$ \
            && "$process_uid" == "$owner_uid" ]] || return 1
        current_pid="$(systemctl show openclaw-gateway.service -p MainPID --value 2>/dev/null || true)"
        [[ "$current_pid" == "$previous_pid" ]] || return 1
        kill -TERM "$previous_pid" || return 1
    fi
    current_pid=""
    for attempt in {1..60}; do
        current_pid="$(systemctl show openclaw-gateway.service -p MainPID --value 2>/dev/null || true)"
        if [[ "$current_pid" =~ ^[1-9][0-9]*$ \
            && ( ! "$previous_pid" =~ ^[1-9][0-9]*$ || "$current_pid" != "$previous_pid" ) ]] \
            && systemctl is-active --quiet openclaw-gateway.service; then
            break
        fi
        sleep 1
    done
    [[ "$current_pid" =~ ^[1-9][0-9]*$ \
        && ( ! "$previous_pid" =~ ^[1-9][0-9]*$ || "$current_pid" != "$previous_pid" ) ]] || return 1
    for attempt in {1..60}; do
        if _ods_pixel_gateway_health "$gateway_port"; then
            ready=true
            break
        fi
        (( attempt < 60 )) && sleep 2
    done
    [[ "$ready" == true ]] || return 1
    # A fresh install can finish the gateway HTTP listener while OpenClaw's
    # separate CLI process is still settling its newly-created plugin registry
    # under first-boot memory and I/O pressure. The gateway itself already
    # reports every required plugin loaded, but the first strict `pixel verify`
    # can transiently fail its independent registry read. Retry only the same
    # complete verification command; every attempt remains fail closed and a
    # persistent version, root, policy, or endpoint mismatch still aborts the
    # model transaction and triggers rollback.
    _ods_pixel_verify_current_runtime "$owner" "$home" "$pixel_root" "$transaction_id"
}

_ods_pixel_wait_access_reconcile() {
    local owner="$1" home="$2" helper="$3" attempts="$4" delay="$5" attempt
    [[ "$attempts" =~ ^[1-9][0-9]*$ && "$delay" =~ ^[0-9]+$ ]] || return 1
    for (( attempt=1; attempt<=attempts; attempt++ )); do
        if ods_pixel_run_as_owner "$owner" "$home" python3 -I "$helper"; then
            return 0
        fi
        (( attempt < attempts )) && sleep "$delay"
    done
    return 1
}

_ods_pixel_reverify_access_after_gateway_restart() {
    local owner="$1" home="$2" required="${3:-false}" attempts=1
    local helper=/usr/local/libexec/ods-pixel-access/pixel_access_reconcile.py
    if [[ ! -f "$helper" || -L "$helper" ]]; then
        # Upgrades from an older access coordinator reach model reconciliation
        # before the new protected bundle is installed. The mandatory final
        # reproof below covers that one compatibility window.
        [[ "$required" == false ]]
        return
    fi
    # systemctl restart is asynchronous. A fresh coordinator can be active
    # before its owner socket and runtime dependencies are simultaneously
    # ready, so the first fail-closed status call can legitimately lose that
    # activation race. Only the mandatory fresh-install proof waits and
    # retries; the protected helper still refuses busy, pending, ambiguous, or
    # mismatched state on every attempt.
    [[ "$required" == true ]] && attempts=30
    _ods_pixel_wait_access_reconcile "$owner" "$home" "$helper" "$attempts" 1
}

_ods_pixel_model_transition() {
    local action="$1" owner="$2" home="$3" transaction_id="${4:-}" outcome="${5:-}"
    local helper=/usr/local/libexec/ods-pixel-access/pixel_model_transition.py
    [[ -f "$helper" && ! -L "$helper" ]] || return 1
    case "$action" in
        begin)
            [[ -z "$transaction_id" && -z "$outcome" ]] || return 1
            ods_pixel_run_as_owner "$owner" "$home" python3 -I "$helper" begin
            ;;
        status)
            [[ -z "$transaction_id" && -z "$outcome" ]] || return 1
            ods_pixel_run_as_owner "$owner" "$home" python3 -I "$helper" status
            ;;
        finish)
            [[ "$transaction_id" =~ ^[0-9a-f]{64}$
                && ( "$outcome" == applied || "$outcome" == rolled-back ) ]] || return 1
            if [[ "$transaction_id" == "${ODS_PIXEL_SOURCE_TRANSACTION:-}" ]]; then
                [[ "$outcome" == applied ]] || return 1
                _ods_pixel_check_source_transaction "$owner"
                return
            fi
            ods_pixel_run_as_owner "$owner" "$home" python3 -I "$helper" \
                finish --transaction "$transaction_id" "$outcome"
            ;;
        *) return 1 ;;
    esac
}

_ods_pixel_reverify_unless_model_held() {
    local owner="$1" home="$2" transaction_id="${3:-}"
    if [[ -n "$transaction_id" ]]; then
        [[ "$transaction_id" =~ ^[0-9a-f]{64}$ ]]
        return
    fi
    _ods_pixel_reverify_access_after_gateway_restart "$owner" "$home"
}

_ods_pixel_restore_model_reconciliation() {
    local owner="$1" home="$2" pixel_root="$3" answers="$4" backup="$5"
    local transaction_id="${6:-}" old_contract openclaw_bin
    openclaw_bin="$(_ods_pixel_openclaw_bin "$owner" "$home")" || return 1
    _ods_pixel_atomic_replace_managed_file "$owner" "$home" "$backup/openclaw.json" "$home/.openclaw/openclaw.json" || return 1
    _ods_pixel_atomic_replace_managed_file "$owner" "$home" "$backup/rollback-onboarding.json" "$answers" || return 1
    _ods_pixel_atomic_replace_managed_file "$owner" "$home" "$backup/pixel-managed.json" "$home/.config/ods/pixel-managed.json" || return 1
    if ! ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" configure --answers "$answers" --force \
        || ! _ods_pixel_reconcile_workspace_guidance "$owner" "$home" "$pixel_root/.generated/workspace" generated \
        || ! _ods_pixel_install_onboarding_mirror "$owner" "$home" "$answers" \
        || ! ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" plan \
        || ! _ods_pixel_recreate_agent_sandbox "$owner" "$home" "$openclaw_bin" \
        || ! _ods_pixel_restart_gateway_and_verify "$owner" "$home" "$pixel_root" "$transaction_id" \
        || ! _ods_pixel_reverify_unless_model_held "$owner" "$home" "$transaction_id" \
        || ! _ods_pixel_restart_ingress_and_verify "$owner" "$home" "$answers"; then
        if [[ -f "$backup/runtime-attestation.json" && ! -L "$backup/runtime-attestation.json" ]]; then
            _ods_pixel_atomic_replace_managed_file "$owner" "$home" "$backup/runtime-attestation.json" \
                "$home/.local/share/pixel/runtime-attestation.json" || true
        else
            ods_pixel_run_as_owner "$owner" "$home" rm -f -- \
                "$home/.local/share/pixel/runtime-attestation.json" || true
        fi
        return 1
    fi
    old_contract="$(_ods_pixel_contract_sha256 "$owner" "$home" "$answers")" || return 1
    _ods_pixel_mark_ready "$owner" "$home" "$old_contract" "$pixel_root"
}

_ods_pixel_reconciliation_source_url() {
    local source_ref="$1"
    [[ "$source_ref" =~ ^[0-9a-f]{40}$ ]] || return 1
    if [[ -n "${PIXEL_SOURCE_URL:-}" ]]; then
        if [[ "$PIXEL_SOURCE_URL" == bundled ]]; then
            if [[ "$source_ref" != "$ODS_PIXEL_BUNDLED_REF" ]]; then
                printf '%s\n' 'error: The installed Pixel source pin differs from the public bundle. Reinstall the managed Pixel runtime before changing models.' >&2
                return 1
            fi
        elif [[ "$PIXEL_SOURCE_URL" != /* || "$PIXEL_SOURCE_URL" == / ]]; then
            printf '%s\n' 'error: Pixel model reconciliation requires the verified ODS bundle or an explicit absolute local source checkout' >&2
            return 1
        fi
        printf '%s\n' "$PIXEL_SOURCE_URL"
    elif [[ "$source_ref" == "$ODS_PIXEL_BUNDLED_REF" ]]; then
        printf '%s\n' bundled
    else
        printf '%s\n' 'error: The installed Pixel source pin is not in the public bundle. Reinstall the managed runtime or configure its exact absolute local source before changing models.' >&2
        return 1
    fi
}

ods_pixel_reconcile_promoted_model() {
    local owner="$1" home="$2" promoted_model="$3" final_state="${4:-ready}"
    local promoted_context="${5:-}" promoted_max_tokens="${6:-}" promoted_reasoning="${7:-}"
    local route_fingerprint="${8:-}" borrowed_transaction="${9:-}" image_input="${10:-unknown}"
    # A measured thinking control for this model; empty keeps the name rule.
    local thinking_control="${11:-}"
    local source_ref source_root source_url pixel_root answers candidate backup contract_sha256 openclaw_bin failed=false
    local model_transaction="" release_failed=false
    local stable_alias=false staged_alias_candidate=""
    local failure_phase="unknown"
    [[ "$final_state" == ready || "$final_state" == installing ]] || return 1
    [[ -z "$thinking_control" || "$thinking_control" =~ ^(enable_thinking|always|none)$ ]] || return 1
    if [[ -n "$borrowed_transaction" ]]; then
        [[ "$borrowed_transaction" =~ ^[0-9a-f]{64}$ ]] || return 1
        local held_status
        held_status="$(_ods_pixel_model_transition status "$owner" "$home")" || return 1
        printf '%s' "$held_status" | python3 -c 'import json,sys; d=json.load(sys.stdin); sys.exit(0 if d.get("pending") is True and d.get("kind")=="model" and d.get("phase")=="held" and d.get("transaction_id")==sys.argv[1] else 1)' "$borrowed_transaction" || return 1
        model_transaction="$borrowed_transaction"
    fi
    source_ref="$(_ods_pixel_managed_source_ref "$owner" "$home")" || return 1
    source_url="$(_ods_pixel_reconciliation_source_url "$source_ref")" || return 1
    local PIXEL_SOURCE_REF="$source_ref"
    local PIXEL_SOURCE_URL="$source_url"
    source_root="${INSTALL_DIR:?}/data/pixel/source-$source_ref"
    pixel_root="$(_ods_pixel_source_checkout "$owner" "$home" "$source_root")" || return 1
    answers="$INSTALL_DIR/data/pixel/onboarding.json"
    candidate="$pixel_root/dist/openclaw.json"
    openclaw_bin="$(_ods_pixel_openclaw_bin "$owner" "$home")" || return 1
    [[ "$openclaw_bin" == /* && -x "$openclaw_bin" ]] || return 1

    # A stable ODS gateway alias separates Pixel from the concrete endpoint but
    # not from the active model limits. Reuse the live gateway only when its
    # concrete display identity, context, output budget, and reasoning contract
    # already match the promoted route. A model or context change must continue
    # through the transactional path below so OpenClaw compacts against the
    # model that LiteLLM actually serves. Model activation already refuses new
    # work and waits for Pixel streams to drain before reaching this boundary.
    if _ods_pixel_uses_stable_model_alias "$owner" "$home" "$answers"; then
        if _ods_pixel_stable_alias_matches_promoted_model "$owner" "$home" "$answers" \
            "$promoted_model" "$promoted_context" "$promoted_max_tokens" \
            "$promoted_reasoning" "$route_fingerprint" "$image_input" "$thinking_control"; then
            contract_sha256="$(_ods_pixel_contract_sha256 "$owner" "$home" "$answers")" || return 1
            # This is a no-op model reconciliation only when the complete
            # ODS-managed contract is already active. A same-model installer
            # upgrade can legitimately change the extension or host-service
            # contract first; continue through the transactional path below
            # so that change is installed instead of requiring its new hash
            # to already exist in the old ready marker.
            if _ods_pixel_managed_contract_matches "$owner" "$home" "$contract_sha256"; then
                # A stale installed mirror needs the transactional path below,
                # even if the active model and the ODS-side answers match.
                if ods_pixel_run_as_owner "$owner" "$home" cmp -s -- \
                    "$answers" "$home/.config/pixel-deployment/onboarding.json"; then
                    _ods_pixel_wait_ingress "$owner" "$home" 6 1 || return 1
                    _ods_pixel_verify_plugin_loaded "$owner" "$home" "$openclaw_bin" \
                        "${INSTALL_DIR:?}/extensions/services/pixel-agent/plugin" || return 1
                    if [[ "$final_state" == ready ]]; then
                        _ods_pixel_mark_ready "$owner" "$home" "$contract_sha256" "$pixel_root" || return 1
                    else
                        _ods_pixel_mark_verified_installing "$owner" "$home" "$contract_sha256" "$pixel_root" || return 1
                    fi
                    printf '%s\n' "Pixel stable model alias remains active for $promoted_model"
                    return 0
                fi
            fi
        fi
        # The stable-alias shortcut copies the live config and only changes
        # model fields. A new search choice needs the same-source renderer so
        # its selected plugin registration can be validated and applied.
        if _ods_pixel_search_provider_matches_contract "$owner" "$home" "$answers"; then
            stable_alias=true
        fi
    fi

    backup="$(_ods_pixel_model_reconciliation_snapshot "$owner" "$home" "$answers")" || return 1
    # Update the root-custodied controller before taking the model hold. This
    # restarts only the access coordinator, not the active Pixel gateway.
    if [[ -z "$borrowed_transaction" ]]; then
        _ods_pixel_install_access_service "$owner" "$openclaw_bin" || return 1
        model_transaction="$(_ods_pixel_model_transition begin "$owner" "$home")" || return 1
        [[ "$model_transaction" =~ ^[0-9a-f]{64}$ ]] || return 1
    fi

    if ! _ods_pixel_update_onboarding_model "$owner" "$home" "$answers" "$promoted_model" \
        "$promoted_context" "$promoted_max_tokens" "$promoted_reasoning" "$route_fingerprint" "$image_input" \
        "$thinking_control"; then
        failed=true
        failure_phase="onboarding-update"
    fi
    if [[ "$failed" == false && "$stable_alias" == true ]]; then
        if ! staged_alias_candidate="$(_ods_pixel_stage_stable_alias_candidate \
            "$owner" "$home" "$answers")"; then
            failed=true
            failure_phase="stable-alias-candidate"
        else
            candidate="$staged_alias_candidate"
        fi
    else
        if [[ "$failed" == false ]] \
            && ! ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" configure --answers "$answers" --force; then
            failed=true
            failure_phase="pixel-configure"
        fi
        if [[ "$failed" == false ]] \
            && ! _ods_pixel_reconcile_workspace_guidance "$owner" "$home" "$pixel_root/.generated/workspace" generated; then
            failed=true
            failure_phase="workspace-guidance"
        fi
        if [[ "$failed" == false ]] \
            && ! ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" plan; then
            failed=true
            failure_phase="pixel-plan"
        fi
    fi
    if [[ "$failed" == false ]] \
        && ! _ods_pixel_apply_runtime_budget "$owner" "$home" "$candidate" "$openclaw_bin" "$answers" >/dev/null; then
        failed=true
        failure_phase="runtime-budget"
    fi
    if [[ "$failed" == false ]] \
        && ! _ods_pixel_candidate_is_managed_runtime_update "$owner" "$home" "$candidate" "$answers"; then
        failed=true
        failure_phase="managed-update-validation"
    fi
    if [[ "$failed" == false ]] && ! _ods_pixel_candidate_config_matches_live "$owner" "$home" "$candidate"; then
        if ! _ods_pixel_atomic_replace_managed_file "$owner" "$home" "$candidate" "$home/.openclaw/openclaw.json"; then
            failed=true
            failure_phase="config-install"
        fi
    fi
    if [[ "$failed" == false ]] \
        && ! _ods_pixel_install_onboarding_mirror "$owner" "$home" "$answers"; then
        failed=true
        failure_phase="onboarding-mirror-install"
    fi
    if [[ "$failed" == false ]] \
        && ! _ods_pixel_recreate_agent_sandbox "$owner" "$home" "$openclaw_bin"; then
        failed=true
        failure_phase="sandbox-recreate"
    fi
    if [[ "$failed" == false ]] \
        && ! _ods_pixel_restart_gateway_and_verify "$owner" "$home" "$pixel_root" "$model_transaction"; then
        failed=true
        failure_phase="gateway-restart-verify"
    fi
    if [[ "$failed" == false ]] \
        && ! _ods_pixel_reverify_unless_model_held "$owner" "$home" "$model_transaction"; then
        failed=true
        failure_phase="access-runtime-reproof"
    fi
    if [[ "$failed" == false ]] \
        && ! _ods_pixel_restart_ingress_and_verify "$owner" "$home" "$answers"; then
        failed=true
        failure_phase="ingress-runtime-refresh"
    fi
    if [[ "$failed" == false ]]; then
        if ! contract_sha256="$(_ods_pixel_contract_sha256 "$owner" "$home" "$answers")"; then
            failed=true
            failure_phase="contract-hash"
        fi
    fi
    if [[ "$failed" == false ]]; then
        if [[ "$final_state" == ready ]]; then
            if ! _ods_pixel_mark_ready "$owner" "$home" "$contract_sha256" "$pixel_root"; then
                failed=true
                failure_phase="ready-marker"
            fi
        else
            if ! _ods_pixel_mark_verified_installing "$owner" "$home" "$contract_sha256" "$pixel_root"; then
                failed=true
                failure_phase="installing-marker"
            fi
        fi
    fi
    if [[ "$failed" == false && -z "$borrowed_transaction" ]] \
        && ! _ods_pixel_model_transition finish "$owner" "$home" \
            "$model_transaction" applied; then
        failed=true
        release_failed=true
        failure_phase="model-transition-finish"
    fi
    if [[ "$failed" == false ]]; then
        if [[ -n "$staged_alias_candidate" ]]; then
            ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$staged_alias_candidate" || true
        fi
        printf '%s\n' "Pixel model route reconciled to $promoted_model"
        return 0
    fi

    if [[ -n "$staged_alias_candidate" ]]; then
        ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$staged_alias_candidate" || true
    fi
    if [[ "$release_failed" == true ]]; then
        # Finish can fail after one gate has released. Never mutate the route
        # again under an uncertain admission boundary; the root journal blocks
        # later transitions until the same transaction is explicitly recovered.
        printf '%s\n' 'error: Pixel model route was verified but transition release failed; recovery-required and automatic rollback suppressed' >&2
        return 1
    fi
    printf 'warning: Pixel model reconciliation failed during phase=%s; restoring the previous verified route\n' \
        "$failure_phase" >&2
    if _ods_pixel_restore_model_reconciliation "$owner" "$home" "$pixel_root" "$answers" "$backup" \
        "$model_transaction" \
        && { [[ -n "$borrowed_transaction" ]] || _ods_pixel_model_transition finish "$owner" "$home" \
            "$model_transaction" rolled-back; }; then
        printf '%s\n' 'warning: previous Pixel model route restored and verified; rollback=verified' >&2
    else
        printf '%s\n' "error: Pixel model reconciliation and verified rollback both failed; rollback=failed evidence=$backup" >&2
    fi
    return 1
}

_ods_pixel_initial_unconfigured_marker() {
    local owner="$1" home="$2"
    [[ -f "$home/.config/ods/pixel-managed.json" && ! -L "$home/.config/ods/pixel-managed.json" ]] || return 1
    ods_pixel_run_as_owner "$owner" "$home" python3 - \
        "$home/.config/ods/pixel-managed.json" "$home/.openclaw/openclaw.json" \
        "${INSTALL_DIR:?}" "$home" "${PIXEL_SOURCE_REF:?}" "${3:-}" <<'PY'
import json, os, pathlib, re, stat, sys
marker = json.load(open(sys.argv[1]))
initial = (
    set(marker) == {"schema_version", "manager", "state", "initial_active_state",
                    "install_dir", "pixel_source_ref"}
    and marker.get("schema_version") == 2 and marker.get("manager") == "ods"
    and marker.get("state") == "installing" and marker.get("initial_active_state") == "absent"
    and marker.get("install_dir") == sys.argv[3]
    and isinstance(marker.get("pixel_source_ref"), str)
    and re.fullmatch(r"[0-9a-f]{40}", marker["pixel_source_ref"])
    and marker["pixel_source_ref"] == sys.argv[5]
)
if not initial or any(
    os.path.lexists(pathlib.Path(sys.argv[4]) / ".local/share/pixel" / name)
    for name in ("current", "runtime-attestation.json", ".ods-uninstall-current",
                 ".ods-uninstall-runtime-attestation")
):
    raise SystemExit(1)
config_path = pathlib.Path(sys.argv[2])
if not os.path.lexists(config_path):
    raise SystemExit(0)
# A cancelled first bootstrap can leave only plugin-enable entries, before
# configure/apply has created any gateway, agent, workspace or access mode.
# Accept this exact inert shape, never an arbitrary partial configuration.
fd = os.open(config_path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
with os.fdopen(fd, 'rb') as handle:
    info = os.fstat(handle.fileno())
    if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()
            or info.st_nlink != 1 or info.st_mode & 0o077 or info.st_size > 65536):
        raise SystemExit(1)
    config = json.load(handle)
if not sys.argv[6]:
    raise SystemExit(1)
manifest = json.loads((pathlib.Path(sys.argv[6]) / 'RELEASE-MANIFEST.json').read_text())
plugins = config.get('plugins') if isinstance(config, dict) else None
meta = config.get('meta') if isinstance(config, dict) else None
if (set(config) != {'plugins', 'meta'} or not isinstance(plugins, dict)
        or set(plugins) != {'entries'} or not isinstance(meta, dict)
        or set(meta) != {'lastTouchedVersion', 'lastTouchedAt'}
        or meta['lastTouchedVersion'] != manifest['openclaw']
        or not isinstance(meta['lastTouchedAt'], str)
        or not re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z', meta['lastTouchedAt'])):
    raise SystemExit(1)
entries = plugins['entries']
if (not isinstance(entries, dict) or not entries
        or not set(entries) <= {'discord', 'searxng', 'llama-cpp'}
        or any(not isinstance(value, dict) or set(value) != {'enabled'}
               or value['enabled'] is not True for value in entries.values())):
    raise SystemExit(1)
raise SystemExit(0)
PY
}

_ods_pixel_reprove_access_marker_if_needed() {
    if [[ -n "${ODS_PIXEL_SOURCE_TRANSACTION:-}" ]]; then
        _ods_pixel_check_source_transaction "$1"
        return
    fi
    local owner="$1" home="$2" openclaw_bin="$3" check
    [[ -e "$home/.config/ods/pixel-managed.json" ]] || return 0
    if ods_pixel_run_as_owner "$owner" "$home" python3 - \
        "$home/.config/ods/pixel-managed.json" "$home/.openclaw/openclaw.json" "${INSTALL_DIR:?}" "$home" <<'PY'
import hashlib, json, os, pathlib, re, sys
marker = json.load(open(sys.argv[1]))
# A new bootstrap has no access mode to reprove. Do not treat a missing config
# on an active/partial release as a fresh install.
initial = (
    set(marker) == {"schema_version", "manager", "state", "initial_active_state",
                    "install_dir", "pixel_source_ref"}
    and marker.get("schema_version") == 2 and marker.get("manager") == "ods"
    and marker.get("state") == "installing" and marker.get("initial_active_state") == "absent"
    and marker.get("install_dir") == sys.argv[3]
    and isinstance(marker.get("pixel_source_ref"), str)
    and re.fullmatch(r"[0-9a-f]{40}", marker["pixel_source_ref"])
)
if initial and not os.path.lexists(sys.argv[2]) and not any(
    os.path.lexists(pathlib.Path(sys.argv[4]) / ".local/share/pixel" / name)
    for name in ("current", "runtime-attestation.json", ".ods-uninstall-current",
                 ".ods-uninstall-runtime-attestation")
):
    raise SystemExit(0)
config = json.load(open(sys.argv[2]))
observed = hashlib.sha256(b"ods-pixel-openclaw-v1\0" + json.dumps(config, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
raise SystemExit(0 if marker.get("configuration_sha256") == observed else 3)
PY
    then
        return 0
    else
        check=$?
    fi
    [[ "$check" == 3 ]] || return 1
    # The protected coordinator distinguishes the exact legacy access change
    # from unrelated drift, obtains fresh runtime proof and retains install state.
    _ods_pixel_install_access_service "$owner" "$openclaw_bin" || return 1
    ods_sudo python3 -I /usr/local/libexec/ods-pixel-access/access_mode_server.py \
        --reprove-installer-access
}

_ods_pixel_install_access_service() {
    local owner="$1" openclaw_bin="$2" adopt_existing="${3:-false}" activate="${4:-true}" home gateway_port
    local code_source="${5:-${INSTALL_DIR:?}}"
    [[ "$adopt_existing" == true || "$adopt_existing" == false ]] || return 1
    [[ "$activate" == true || "$activate" == false ]] || return 1
    home="$(ods_pixel_owner_home "$owner")" || return 1
    # Phase 06 exports PIXEL_GATEWAY_PORT only in its own installer process.
    # Model promotion may run later without that environment. The installed
    # owner's verified onboarding contract is the gateway unit's actual port.
    gateway_port="$(_ods_pixel_installed_gateway_port "$owner" "$home")" || return 1
    # This coordinator is privileged. Never run or import its implementation
    # from the owner's mutable checkout, even when the host agent is unprivileged.
    ods_sudo python3 - "${INSTALL_DIR:?}" "$owner" "$openclaw_bin" "$gateway_port" "$adopt_existing" "$activate" "$code_source" <<'PY'
import fcntl, hashlib, json, os, pathlib, pwd, re, shlex, socket, stat, subprocess, sys, tempfile, time, types
sys.dont_write_bytecode = True
source = pathlib.Path(sys.argv[1])
code_source = pathlib.Path(sys.argv[7])
owner = pwd.getpwnam(sys.argv[2])
if owner.pw_uid == 0:
    raise SystemExit("Pixel access requires a non-root gateway owner")
state = pathlib.Path('/var/lib/ods-pixel-access')
state.mkdir(mode=0o700, exist_ok=True)
info = state.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o077:
    raise SystemExit("Pixel access state directory is unsafe")
lock = os.open(state / 'lock', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
info = os.fstat(lock)
if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_nlink != 1 or info.st_mode & 0o077:
    raise SystemExit("Pixel access state lock is unsafe")
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
source_upgrade = None
completed_source_upgrade = None
if os.path.lexists(state / 'source-upgrade/source-upgrade.json'):
    # The installer itself is already the operator's privileged entry point.
    # Load the exact staged helper, then bind every protected write to that
    # root-custodied plan; no owner socket can select code or paths.
    snapshot_root = state / 'source-upgrade'
    snapshot_info = snapshot_root.lstat()
    if not stat.S_ISDIR(snapshot_info.st_mode) or snapshot_info.st_uid != 0 or snapshot_info.st_mode & 0o077:
        raise SystemExit('Source upgrade snapshot custody changed')
    def snapshot_bytes(name):
        fd = os.open(snapshot_root / name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
        with os.fdopen(fd, 'rb') as handle:
            info = os.fstat(handle.fileno())
            if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != 0
                    or info.st_mode & 0o077 or info.st_size > 64 * 1024 * 1024):
                raise SystemExit('Source upgrade snapshot custody changed')
            value = handle.read(64 * 1024 * 1024 + 1)
            if len(value) > 64 * 1024 * 1024:
                raise SystemExit('Source upgrade snapshot is too large')
            return value
    staged = json.loads(snapshot_bytes('source-upgrade.json'))
    helper_hash = staged['candidate']['bin/pixel_source_upgrade.py']['sha256']
    if not isinstance(helper_hash, str) or not re.fullmatch(r'[a-f0-9]{64}', helper_hash):
        raise SystemExit('Source upgrade helper identity is invalid')
    helper_bytes = snapshot_bytes(helper_hash)
    if hashlib.sha256(helper_bytes).hexdigest() != helper_hash:
        raise SystemExit('Source upgrade helper snapshot changed')
    module = types.ModuleType('ods_source_upgrade')
    # Execute only the previously staged root-private helper, never code read
    # anew from the owner's mutable incoming checkout during bootstrap.
    exec(compile(helper_bytes, str(snapshot_root / helper_hash), 'exec'), module.__dict__)
    source_upgrade = module.SourceUpgrade(state / 'source-upgrade', source, owner.pw_uid)
    plan = source_upgrade.journal()
    if plan['phase'] == 'complete':
        if os.path.lexists(state / 'transition.json'):
            raise SystemExit('Recover the existing Pixel access transition before upgrading its coordinator')
        if code_source != source:
            raise SystemExit('Stage the new source before upgrading its coordinator')
        # A released update does not freeze owner-managed extensions. The
        # retained protected mirror remains authoritative for coordinator
        # rewrites; changes to that code/config require a new staged update.
        source_upgrade.verify_mirror()
        completed_source_upgrade = source_upgrade
        source_upgrade = None
    else:
        expected_source = plan['after'] if code_source == source else plan['candidate']
        if module.inventory(code_source, owner.pw_uid, candidate=code_source != source) != expected_source:
            raise SystemExit('Source upgrade candidate changed before coordinator handoff')
        if os.path.lexists(state / 'transition.json'):
            module._pending(state, plan['hold'])
            if plan['phase'] != 'applied':
                raise SystemExit('Source upgrade code is not fully installed')
elif (state / 'transition.json').exists():
    raise SystemExit("Recover the existing Pixel access transition before upgrading its coordinator")
target = pathlib.Path('/usr/local/libexec/ods-pixel-access')
target.mkdir(mode=0o755, parents=True, exist_ok=True)
for path in (target, *target.parents):
    info = path.lstat()
    if stat.S_ISLNK(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
        raise SystemExit("Pixel access program directory is not root protected")
# These are public programs executed by the unprivileged gateway owner.
# mkdir's requested mode is masked by sudo/the caller's umask, including 0077.
# Normalize only this owned directory after validating its protected custody.
os.chmod(target, 0o755, follow_symlinks=False)

def write(path, content, mode, uid=0, gid=0):
    if completed_source_upgrade is not None:
        completed_source_upgrade.verify_mirror()
        expected = completed_source_upgrade._mirror_record()['after'].get(str(path))
        wanted = dict(sha256=hashlib.sha256(content).hexdigest(), mode=mode, uid=uid, gid=gid)
        if expected != wanted:
            raise SystemExit('Stage a source upgrade before changing its protected coordinator')
    if path.exists() or path.is_symlink():
        info = path.lstat()
        if not stat.S_ISREG(info.st_mode) or info.st_uid != uid or info.st_nlink != 1 or info.st_mode & 0o022:
            raise SystemExit("Refusing an unsafe Pixel access program/configuration path")
    if source_upgrade is not None:
        source_upgrade.record_mirror_write(path, content, mode, uid, gid)
    fd, temporary = tempfile.mkstemp(prefix='.ods-access-install-', dir=path.parent)
    try:
        os.fchmod(fd, mode)
        os.fchown(fd, uid, gid)
        with os.fdopen(fd, 'wb') as handle:
            handle.write(content); handle.flush(); os.fsync(handle.fileno())
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary): os.unlink(temporary)

host = code_source / 'extensions/services/pixel-agent/host'
for name in ('access_mode_server.py', 'unix_peer.py', 'access_mode_worker.py', 'pixel_access_mode.py', 'access_mode_config.py', 'settings_transaction.py', 'provider_transaction.py', 'model_transaction.py', 'access_release_transaction.py'):
    write(target / name, (host / name).read_bytes(), 0o644)
write(target / 'pixel_access_bridge.py', (code_source / 'bin/pixel_access_bridge.py').read_bytes(), 0o644)
write(target / 'pixel_gateway_service.py', (code_source / 'bin/pixel_gateway_service.py').read_bytes(), 0o644)
write(target / 'pixel_access_client.py', (code_source / 'bin/pixel_access_client.py').read_bytes(), 0o644)
write(target / 'pixel_access_reconcile.py', (code_source / 'bin/pixel_access_reconcile.py').read_bytes(), 0o644)
write(target / 'pixel_model_transition.py', (code_source / 'bin/pixel_model_transition.py').read_bytes(), 0o644)
write(target / 'pixel_source_upgrade.py', (code_source / 'bin/pixel_source_upgrade.py').read_bytes(), 0o644)
write(target / 'pixel_access_protocol.py', (code_source / 'bin/pixel_access_protocol.py').read_bytes(), 0o644)
for name in ('pixel_model_contract.py', 'pixel_model_coordinator.py'):
    write(target / name, (code_source / 'bin' / name).read_bytes(), 0o644)
settings_package = target / 'pixel_settings'
settings_package.mkdir(mode=0o755, exist_ok=True)
info = settings_package.lstat()
if not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
    raise SystemExit("Pixel settings program directory is not root protected")
os.chmod(settings_package, 0o755, follow_symlinks=False)
for name in ('__init__.py', 'contract.py', 'projection.py', 'runtime.py', 'coordinator.py'):
    write(settings_package / name, (code_source / 'bin/pixel_settings' / name).read_bytes(), 0o644)
provider_package = target / 'pixel_provider'
provider_package.mkdir(mode=0o755, exist_ok=True)
info = provider_package.lstat()
if not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
    raise SystemExit("Pixel provider program directory is not root protected")
os.chmod(provider_package, 0o755, follow_symlinks=False)
for name in ('__init__.py', 'config.py', 'store.py', 'activation_config.py',
             'managed_deployment.py', 'service_environment.py', 'service_activation.py',
             'runtime_custody.py', 'coordinator.py'):
    write(provider_package / name, (code_source / 'bin/pixel_provider' / name).read_bytes(), 0o644)
config_dir = pathlib.Path('/etc/ods')
config_dir.mkdir(mode=0o755, exist_ok=True)
info = config_dir.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
    raise SystemExit("Pixel access configuration directory is unsafe")
binary = pathlib.Path(sys.argv[3])
if not binary.is_absolute() or not os.access(binary, os.X_OK):
    raise SystemExit("The installed OpenClaw validator is unavailable")
try:
    gateway_port = int(sys.argv[4])
except (TypeError, ValueError):
    raise SystemExit("The installed Pixel gateway port is invalid") from None
if not 1 <= gateway_port <= 65535 or str(gateway_port) != sys.argv[4]:
    raise SystemExit("The installed Pixel gateway port is invalid")
unit_owner = subprocess.check_output(['systemctl', 'show', 'openclaw-gateway.service',
                                      '--property=User', '--value'], text=True).strip()
unit_start = subprocess.check_output(['systemctl', 'show', 'openclaw-gateway.service',
                                      '--property=ExecStart', '--value'], text=True).strip()
if unit_owner != owner.pw_name or unit_start.count('argv[]=') != 1:
    raise SystemExit("The installed Pixel gateway unit does not match its owner")
command = unit_start.split('argv[]=', 1)[1].split(' ; ignore_errors=', 1)[0]
arguments = shlex.split(command)
if (len(arguments) < 2 or arguments[0] != str(binary) or arguments[1] != 'gateway'
        or arguments.count('--port') != 1
        or arguments[arguments.index('--port') + 1:arguments.index('--port') + 2] != [str(gateway_port)]):
    raise SystemExit("The installed Pixel gateway unit port differs from onboarding")
sys.path.insert(0, str(target))  # Import only the freshly root-protected bundle.
from pixel_settings.runtime import settings_data_directory
from pixel_access_bridge import SystemdAccessBridge
binding = None
if sys.argv[5] == 'true':
    # Deliberate legacy migration only. Preserve the actual configuration and
    # mode; no fabricated installer completion or ready marker is created.
    binding = SystemdAccessBridge(source, '', installed_binary=str(binary), gateway_owner=owner.pw_name).gateway_installation_binding(require_running=True)
environment_path = source / '.env'
environment_text = ''
if os.path.lexists(environment_path):
    # The normal installer runs before Compose starts Edge. Read only the
    # qualified installation file, never source it or inherit shell secrets.
    fd = os.open(environment_path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    with os.fdopen(fd, 'rb') as handle:
        info = os.fstat(handle.fileno())
        if (not stat.S_ISREG(info.st_mode) or info.st_uid not in (0, owner.pw_uid)
                or info.st_nlink != 1 or info.st_mode & 0o022 or info.st_size > 1024 * 1024):
            raise SystemExit('The managed installation environment is unsafe')
        environment_raw = handle.read(1024 * 1024 + 1)
    if len(environment_raw) > 1024 * 1024:
        raise SystemExit('The managed installation environment is too large')
    environment_text = environment_raw.decode('utf-8')
    settings_data_dir = settings_data_directory(source.resolve(), environment_text)
elif sys.argv[5] == 'true':
    # An explicitly adopted guest can be access-only while the actual settings
    # store belongs to the Windows/macOS host. Do not invent a guest data path
    # or copy an unrelated host .env (and its secrets) into the guest.
    settings_data_dir = None
else:
    raise SystemExit('The managed installation environment is unavailable')
if settings_data_dir is None:
    print('No qualified local settings store; access control remains separate from Settings Apply', file=sys.stderr)
# The owner-only relay credential is not put in argv, the nonsecret service
# environment, the agent config, or any socket/container bind mount.
if sys.argv[5] == 'true':
    edge = json.loads(subprocess.run(['docker', 'inspect', 'ods-pixel-edge'],
        stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True, timeout=10).stdout)[0]
    if not edge.get('State', {}).get('Running') or edge.get('Config', {}).get('Labels', {}).get('com.docker.compose.service') != 'pixel-edge':
        raise SystemExit('The managed Edge runtime is unavailable')
    values = dict(line.split('=', 1) for line in edge.get('Config', {}).get('Env', []) if '=' in line)
    key = values.get('PIXEL_PREVIEW_PROXY_KEY', '')
else:
    values = {}
    for line in environment_text.splitlines():
        name, separator, value = line.partition('=')
        if separator and name.strip() in ('DASHBOARD_API_KEY', 'PIXEL_OPENWEBUI_KEY'):
            value = value.strip()
            if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
                value = value[1:-1]
            values[name.strip()] = value
    # Compose maps this exact local owner key to PIXEL_PREVIEW_PROXY_KEY.
    key = values.get('DASHBOARD_API_KEY', '')
if not 32 <= len(key) <= 4096 or any(ord(char) < 33 or ord(char) > 126 for char in key) or key == values.get('PIXEL_OPENWEBUI_KEY'):
    raise SystemExit('Distinct Dashboard owner credential required for the access relay')
write(config_dir / 'pixel-access-relay.key', key.encode(), 0o600, owner.pw_uid, owner.pw_gid)
write(config_dir / 'pixel-access.json', json.dumps({'install_dir': str(source.resolve()), 'owner': owner.pw_name,
    'openclaw_bin': str(binary), 'gateway_port': gateway_port,
    'settings_data_dir': settings_data_dir,
    'edge_owner_key_sha256': hashlib.sha256(key.encode()).hexdigest(),
    **({'gateway_binding':binding} if binding is not None else {})}).encode(), 0o600)
write(pathlib.Path('/etc/systemd/system/ods-pixel-access.service'), (host / 'ods-pixel-access.service').read_bytes(), 0o644)
# Hold the same transition lock through activation, so a Settings request cannot
# begin between code replacement and coordinator restart.
if sys.argv[6] == 'true':
    subprocess.run(['systemctl', 'daemon-reload'], check=True)
    subprocess.run(['systemctl', 'enable', 'ods-pixel-access.service'], check=True)
    subprocess.run(['systemctl', 'restart', 'ods-pixel-access.service'], check=True)
    # A spawned service does not yet prove the owner-ready control socket.
    socket_path = pathlib.Path('/run/ods-pixel-access/control.sock')
    for attempt in range(30):
        try:
            directory_info = socket_path.parent.lstat()
            socket_info = socket_path.lstat()
            owner_ready = (
                stat.S_ISDIR(directory_info.st_mode)
                and directory_info.st_uid == 0
                and stat.S_IMODE(directory_info.st_mode) == 0o711
                and stat.S_ISSOCK(socket_info.st_mode)
                and socket_info.st_uid == 0
                and socket_info.st_gid == owner.pw_gid
                and stat.S_IMODE(socket_info.st_mode) == 0o660
            )
            if owner_ready:
                # A stale but correctly owned socket must not count as ready.
                with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
                    probe.settimeout(2)
                    probe.connect(str(socket_path))
                    probe.sendall(b'{"operation":"status"}\n')
                    with probe.makefile('rb') as stream:
                        response = json.loads(stream.readline(65537))
                owner_ready = (
                    set(response) == {'status', 'body'}
                    and response['status'] in (200, 400, 403, 409, 503)
                    and isinstance(response['body'], dict)
                )
        except (FileNotFoundError, ConnectionError, TimeoutError, OSError,
                ValueError, TypeError, json.JSONDecodeError):
            owner_ready = False
        if owner_ready:
            break
        if attempt < 29:
            time.sleep(1)
    else:
        raise SystemExit('Pixel access coordinator socket did not become owner-ready')
PY
    [[ $? -eq 0 ]] || return 1
}

_ods_pixel_mark_installing() {
    local owner="$1" home="$2" requested_contract_sha256="${3:-}" marker
    [[ -z "$requested_contract_sha256" || "$requested_contract_sha256" =~ ^[0-9a-f]{64}$ ]] || return 1
    marker="$home/.config/ods/pixel-managed.json"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$marker" "${INSTALL_DIR:?}" \
        "${PIXEL_SOURCE_REF:?}" "$requested_contract_sha256" <<'PY'
import json, os, pathlib, stat, sys, tempfile

path = pathlib.Path(sys.argv[1])
info = path.lstat()
if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_nlink != 1
        or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_size > 65536):
    raise SystemExit("invalid Pixel management marker")
value = json.loads(path.read_text(encoding="utf-8"))
if (value.get("schema_version") != 2 or value.get("manager") != "ods"
        or value.get("initial_active_state") != "absent" or value.get("install_dir") != sys.argv[2]):
    raise SystemExit("Pixel management marker does not match this ODS install")
value["state"] = "installing"
if all(key in value for key in (
        "active_release_version", "release_identity_sha256", "install_manifest_sha256",
        "sandbox_image", "sandbox_image_id")):
    if len(sys.argv[4]) != 64 or any(character not in "0123456789abcdef" for character in sys.argv[4]):
        raise SystemExit("active Pixel transition requires the exact requested contract")
    value["requested_source_ref"] = sys.argv[3]
    value["requested_contract_sha256"] = sys.argv[4]
else:
    value["pixel_source_ref"] = sys.argv[3]
fd, temporary = tempfile.mkstemp(prefix=".pixel-managed.", dir=path.parent)
try:
    with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
        json.dump(value, handle, indent=2, sort_keys=True)
        handle.write("\n")
        handle.flush()
        os.fsync(handle.fileno())
    os.chmod(temporary, 0o600)
    os.replace(temporary, path)
finally:
    if os.path.exists(temporary):
        os.unlink(temporary)
PY
}

# Docker Desktop can retain this shared tag after its Ubuntu distribution was
# removed. This is distinct from an inactive release directory on this host.
# Never reinterpret another UID's image as our candidate or retire its tag.
_ods_pixel_shared_sandbox_conflict() {
    local owner="$1" home="$2" apply_log="$3"
    ods_pixel_run_as_owner "$owner" "$home" grep -Fxq \
        -e '[pixel] ERROR: Shared live sandbox tag exists without an active Pixel release and is not valid for the reviewed candidate' \
        -e '[pixel] ERROR: Shared live sandbox tag exists without an active Pixel release and does not match the reviewed candidate' \
        -- "$apply_log"
}

# Pixel deliberately preserves a release that was rolled back after live
# mutation as audit evidence.  A later ODS retry can render a different plan
# for the same Pixel version (for example after an ODS-managed route change),
# and Pixel correctly refuses to overwrite that non-identical release.  When
# this is the first ODS-managed deployment, archive only the exact inactive,
# internally verified release that the failed apply named, then allow one
# clean retry.  The archive remains owner-private evidence; nothing is deleted.
_ods_pixel_retire_inactive_conflicting_release() {
    local owner="$1" home="$2" pixel_root="$3" apply_log="$4"
    local marker install_root version gateway_unit retired_release
    marker="$home/.config/ods/pixel-managed.json"
    install_root="$home/.local/share/pixel"
    gateway_unit="${ODS_PIXEL_GATEWAY_UNIT_PATH:-/etc/systemd/system/openclaw-gateway.service}"

    [[ -f "$pixel_root/VERSION" && ! -L "$pixel_root/VERSION" ]] || return 1
    version="$(ods_pixel_run_as_owner "$owner" "$home" sed -n '1p' "$pixel_root/VERSION")" || return 1
    [[ "$version" =~ ^[0-9]{1,6}\.[0-9]{1,6}\.[0-9]{1,6}$ ]] || return 1
    if [[ -e "$gateway_unit" || -L "$gateway_unit" ]] \
        || { [[ "$gateway_unit" == /etc/systemd/system/openclaw-gateway.service ]] \
            && systemctl is-active --quiet openclaw-gateway.service 2>/dev/null; }; then
        return 1
    fi

    retired_release="$(ods_pixel_run_as_owner "$owner" "$home" python3 - \
        "$marker" "${INSTALL_DIR:?}" "${PIXEL_SOURCE_REF:?}" "$install_root" \
        "$version" "$apply_log" "$home" <<'PY'
import hashlib
import json
import os
import pathlib
import re
import stat
import sys
import tempfile

marker, install_dir, source_ref, install_root, version, apply_log, home = sys.argv[1:]
marker = pathlib.Path(marker)
install_dir = pathlib.Path(install_dir)
install_root = pathlib.Path(install_root)
apply_log = pathlib.Path(apply_log)
home = pathlib.Path(home)
uid = os.getuid()

def regular(path, maximum, private=False):
    info = path.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_nlink != 1 or info.st_uid != uid
            or info.st_size > maximum or info.st_mode & 0o022
            or (private and info.st_mode & 0o077)):
        raise SystemExit(f"unsafe inactive Pixel recovery file: {path}")
    return info

def directory(path, private=False):
    info = path.lstat()
    if (not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_uid != uid or info.st_mode & 0o022
            or (private and info.st_mode & 0o077)):
        raise SystemExit(f"unsafe inactive Pixel recovery directory: {path}")
    return info

regular(marker, 65536, private=True)
value = json.loads(marker.read_text(encoding="utf-8"))
if (value.get("schema_version") != 2 or value.get("manager") != "ods"
        or value.get("state") != "installing"
        or value.get("initial_active_state") != "absent"
        or value.get("install_dir") != str(install_dir)
        or value.get("pixel_source_ref") != source_ref
        or value.get("requested_source_ref") not in {None, source_ref}):
    raise SystemExit("inactive Pixel recovery marker is not bound to this ODS install")
for key in (
    "active_release_version", "release_identity_sha256", "install_manifest_sha256",
    "sandbox_image", "sandbox_image_id", "retired_release_path",
):
    if key in value:
        raise SystemExit("verified or deactivating Pixel state cannot use inactive recovery")

regular(apply_log, 2 * 1024 * 1024, private=True)
release = install_root / "releases" / version
expected_error = (
    "[pixel] ERROR: Release already exists but is not byte-exact to the reviewed plan: "
    + str(release)
)
if expected_error not in apply_log.read_text(encoding="utf-8", errors="strict").splitlines():
    raise SystemExit("Pixel apply did not report the exact inactive-release conflict")

for path in (
    install_root / "current",
    install_root / "runtime-attestation.json",
    install_root / ".ods-uninstall-current",
    install_root / ".ods-uninstall-runtime-attestation",
    home / ".config/systemd/user/openclaw-gateway.service",
    home / ".config/systemd/system/openclaw-gateway.service",
    home / ".config/systemd/user/pixel-web-courier.service",
):
    if path.exists() or path.is_symlink():
        raise SystemExit("inactive Pixel recovery found live or staged deployment state")

directory(install_root, private=True)
releases = install_root / "releases"
directory(releases, private=True)
directory(release)
identity_path = release / "release-identity.json"
manifest_path = release / "install-manifest.sha256"
regular(identity_path, 65536)
regular(manifest_path, 2 * 1024 * 1024)
identity_bytes = identity_path.read_bytes()
identity = json.loads(identity_bytes)
source = identity.get("source") if isinstance(identity, dict) else None
if (identity.get("pixel") != version or not isinstance(source, dict)
        or source.get("state") != "git-clean" or source.get("commit") != source_ref
        or not isinstance(source.get("tree"), str)
        or not re.fullmatch(r"[0-9a-f]{40}", source["tree"])):
    raise SystemExit("inactive Pixel release identity is not bound to the requested source")

manifest_entries = {}
for line in manifest_path.read_text(encoding="utf-8").splitlines():
    match = re.fullmatch(r"([0-9a-f]{64})  (\./[^\r\n]+)", line)
    if not match:
        raise SystemExit("inactive Pixel release manifest is malformed")
    digest, relative = match.groups()
    relative_path = pathlib.PurePosixPath(relative[2:])
    if (not relative_path.parts or relative_path.is_absolute()
            or any(part in {"", ".", ".."} for part in relative_path.parts)
            or relative in manifest_entries):
        raise SystemExit("inactive Pixel release manifest has an unsafe path")
    manifest_entries[relative] = digest

actual_files = set()
for root, directories, files in os.walk(release, topdown=True, followlinks=False):
    root_path = pathlib.Path(root)
    directory(root_path)
    for name in directories:
        directory(root_path / name)
    for name in files:
        path = root_path / name
        regular(path, 64 * 1024 * 1024)
        relative = "./" + path.relative_to(release).as_posix()
        actual_files.add(relative)
        if relative == "./install-manifest.sha256":
            continue
        expected = manifest_entries.get(relative)
        if expected is None or hashlib.sha256(path.read_bytes()).hexdigest() != expected:
            raise SystemExit("inactive Pixel release bytes do not match their manifest")
if actual_files != set(manifest_entries) | {"./install-manifest.sha256"}:
    raise SystemExit("inactive Pixel release manifest does not cover the exact file set")
if "./release-identity.json" not in manifest_entries or "./VERSION" not in manifest_entries:
    raise SystemExit("inactive Pixel release manifest lacks identity evidence")

identity_sha256 = hashlib.sha256(identity_bytes).hexdigest()
archive_root = install_root / "retired-ods-releases"
if archive_root.exists() or archive_root.is_symlink():
    directory(archive_root, private=True)
else:
    archive_root.mkdir(mode=0o700)
container = pathlib.Path(tempfile.mkdtemp(
    prefix=f"{version}-{identity_sha256[:12]}.", dir=archive_root,
))
os.chmod(container, 0o700, follow_symlinks=False)
destination = container / "release"
try:
    os.rename(release, destination)
except BaseException:
    container.rmdir()
    raise
for path in (releases, archive_root, container):
    descriptor = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
    try:
        os.fsync(descriptor)
    finally:
        os.close(descriptor)
print(destination)
PY
    )" || return 1
    [[ "$retired_release" == "$install_root/retired-ods-releases/$version-"*.????????/release ]] || return 1
    printf '%s\n' "$retired_release"
}

_ods_pixel_ensure_runtime_group_tools() {
    # Fresh Ubuntu 26.04 no longer ships sg in login. Install the qualified
    # distro's package before adding groups that this shell must refresh.
    local -a packages=()
    local sg_package
    if command -v sg >/dev/null 2>&1 && command -v python3 >/dev/null 2>&1; then
        return 0
    fi
    _ods_pixel_parse_os_release || return 1
    case "$_ODS_PIXEL_OS_ID:$_ODS_PIXEL_OS_VERSION_ID" in
        ubuntu:26.04) sg_package=util-linux-extra ;;
        ubuntu:24.04|debian:12) sg_package=login ;;
        *) ai_bad "Pixel runtime group tools require a qualified Linux distribution."; return 1 ;;
    esac
    command -v sg >/dev/null 2>&1 || packages+=("$sg_package")
    command -v python3 >/dev/null 2>&1 || packages+=(python3)
    if [[ "${PKG_MANAGER:-}" != apt ]] || ! declare -f pkg_install >/dev/null 2>&1; then
        ai_bad "Pixel runtime group tools are missing. Install: ${packages[*]}"
        return 1
    fi
    pkg_install "${packages[@]}" || return 1
    if ! command -v sg >/dev/null 2>&1 || ! command -v python3 >/dev/null 2>&1; then
        ai_bad "Pixel runtime group tools are still unavailable after package installation."
        return 1
    fi
}

ods_pixel_prepare_runtime_identity() {
    [[ "${ENABLE_PIXEL_RUNTIME:-false}" == true ]] || return 0
    [[ "${DRY_RUN:-false}" != true ]] || return 0
    ods_sudo_available || {
        ai_bad "Pixel requires privileged systemd and group setup on this host."
        return 1
    }

    local owner gid
    owner="$(ods_pixel_install_owner)" || return 1
    if ! _ods_pixel_ensure_runtime_group_tools; then
        ai_bad "Could not prepare Pixel's runtime group tools before identity setup."
        return 1
    fi
    if ! getent group ods-pixel >/dev/null 2>&1; then
        ods_sudo groupadd --system ods-pixel
    fi
    ods_sudo usermod -aG ods-pixel "$owner"
    gid="$(getent group ods-pixel | awk -F: 'NR == 1 { print $3 }')"
    [[ "$gid" =~ ^[1-9][0-9]*$ ]] || {
        ai_bad "Could not resolve the ods-pixel group GID."
        return 1
    }
    PIXEL_SERVICE_USER="$owner"
    PIXEL_INGRESS_GID="$gid"
    export PIXEL_SERVICE_USER PIXEL_INGRESS_GID
    if declare -f _phase11_env_set >/dev/null 2>&1; then
        _phase11_env_set PIXEL_INGRESS_GID "$gid"
    fi
    if ! _ods_pixel_prepare_wsl_runtime_bridge "$owner"; then
        ai_bad "Could not prepare Pixel's shared WSL runtime before container startup."
        return 1
    fi
    ai_ok "Prepared the unprivileged Pixel runtime identity"
}

# Docker Desktop translates bind sources from the WSL client's namespace.
# Establish the shared projection before Compose starts Pixel Edge, including
# on a fresh install where the persistent bridge unit is not installed yet.
_ods_pixel_prepare_wsl_runtime_bridge() {
    local owner="$1" env_file="${INSTALL_DIR:?}/.env"
    grep -Fxq 'PIXEL_RUNTIME_BIND_PROPAGATION=rshared' "$env_file" || return 0
    grep -Fxq 'PIXEL_INGRESS_RUNTIME_DIR=/mnt/wsl/ods-portal-runtime/ingress' "$env_file" || return 1
    grep -Fxq 'PIXEL_PREVIEW_RUNTIME_DIR=/mnt/wsl/ods-portal-runtime/preview' "$env_file" || return 1
    local bridge="$INSTALL_DIR/extensions/services/pixel-agent/host/pixel-wsl-runtime-bridge.sh"
    [[ -f "$bridge" && ! -L "$bridge" ]] || return 1
    [[ ! -L /run/ods-pixel && ! -L /run/ods-pixel-preview ]] || return 1
    ods_sudo install -d -o "$owner" -g ods-pixel -m 0710 /run/ods-pixel || return 1
    ods_sudo install -d -o "$owner" -g ods-pixel -m 0750 /run/ods-pixel-preview || return 1
    ods_sudo /bin/bash "$bridge" ensure
}

_ods_pixel_source_checkout() {
    local owner="$1" home="$2" source_root="$3"
    local source="${PIXEL_SOURCE_URL:?}" ref="${PIXEL_SOURCE_REF:?}"
    local source_timeout="${ODS_PIXEL_SOURCE_TIMEOUT_SECONDS:-180}"
    local -a git_env=(env -i PATH="$PATH" HOME="$home" USER="$owner" LOGNAME="$owner"
        GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null GIT_TERMINAL_PROMPT=0
        GIT_ALLOW_PROTOCOL=file GIT_NO_REPLACE_OBJECTS=1)
    [[ "$ref" =~ ^[0-9a-f]{40}$ ]] || return 1
    if [[ "$source" == bundled ]]; then
        if [[ "$ref" != "$ODS_PIXEL_BUNDLED_REF" ]]; then
            printf '%s\n' 'error: The requested Pixel pin is not in the verified public bundle' >&2
            return 1
        fi
    elif [[ "$source" != /* || "$source" == / || "$source" == *$'\n'* || "$source" == *$'\r'* ]]; then
        printf '%s\n' 'error: Pixel checkout requires the verified ODS bundle or an absolute local source' >&2
        return 1
    fi
    [[ "$source_root" == /* && "$source_root" != / && ! -L "$source_root" ]] || return 1
    [[ "$source_timeout" =~ ^[0-9]+$ && "$source_timeout" -ge 1 && "$source_timeout" -le 900 ]] || return 1
    if [[ "$source" == bundled ]]; then
        [[ "$ref" == "$ODS_PIXEL_BUNDLED_REF" ]] && ods_pixel_bundled_source || return 1
    fi

    if [[ ! -e "$source_root" ]]; then
        local parent="${source_root%/*}" stage checkout
        ods_pixel_run_as_owner "$owner" "$home" mkdir -p -- "$parent"
        stage="$(ods_pixel_run_as_owner "$owner" "$home" mktemp -d "$parent/.pixel-source.XXXXXX")" || return 1
        checkout="$stage/checkout"
        if [[ "$source" == bundled ]]; then
            if ! ods_pixel_run_as_owner_with_umask "$owner" "$home" 0022 timeout "${source_timeout}s" \
                "${git_env[@]}" git -c credential.interactive=never \
                clone --no-local --no-checkout -- "${INSTALL_DIR:?}/vendor/pixel.bundle" "$checkout" >/dev/null; then
                ods_pixel_run_as_owner "$owner" "$home" rm -rf -- "$stage"
                return 1
            fi
        else
            if ! ods_pixel_run_as_owner_with_umask "$owner" "$home" 0022 timeout "${source_timeout}s" \
                "${git_env[@]}" git -c credential.interactive=never \
                clone --no-local --no-checkout -- "$source" "$checkout" >/dev/null; then
                ods_pixel_run_as_owner "$owner" "$home" rm -rf -- "$stage"
                return 1
            fi
        fi
        if ! ods_pixel_run_as_owner_with_umask "$owner" "$home" 0022 timeout 60s \
            "${git_env[@]}" git -C "$checkout" -c advice.detachedHead=false checkout --detach "$ref" >/dev/null \
            || ! ods_pixel_run_as_owner "$owner" "$home" mv -T -- "$checkout" "$source_root"; then
            ods_pixel_run_as_owner "$owner" "$home" rm -rf -- "$stage"
            return 1
        fi
        ods_pixel_run_as_owner "$owner" "$home" rmdir -- "$stage" || return 1
    fi

    # Re-check the destination after the atomic move. The initial guard runs
    # before cloning; this closes the narrow replacement window between mv and
    # the exact-commit/clean-tree verification below.
    [[ ! -L "$source_root" && -d "$source_root/.git" && ! -L "$source_root/.git" ]] || return 1
    [[ "$(ods_pixel_run_as_owner "$owner" "$home" "${git_env[@]}" git -C "$source_root" rev-parse HEAD)" == "$ref" ]] || return 1
    ods_pixel_run_as_owner "$owner" "$home" "${git_env[@]}" git -C "$source_root" diff --quiet --ignore-submodules --
    ods_pixel_run_as_owner "$owner" "$home" "${git_env[@]}" git -C "$source_root" diff --cached --quiet --ignore-submodules --
    printf '%s\n' "$source_root"
}

_ods_pixel_gateway_health() {
    # Read-only discovery: prefer direct IPv6 loopback; retain IPv4-only hosts.
    # Split the existing five-second probe budget across the two candidates.
    local port="${1:-18789}" host body
    [[ "$port" =~ ^[1-9][0-9]{0,4}$ ]] && (( port <= 65535 )) || return 1
    for host in '[::1]' '127.0.0.1'; do
        if body="$(curl --noproxy '*' --fail --silent --show-error --max-time 2.5 \
            "http://${host}:${port}/health" 2>/dev/null)" \
            && jq -e '.ok == true and .status == "live"' >/dev/null 2>&1 <<<"$body"; then
            return 0
        fi
    done
    return 1
}

_ods_pixel_wait_gateway() {
    local attempts="${1:-60}" port="${2:-18789}" attempt
    for ((attempt = 1; attempt <= attempts; attempt++)); do
        _ods_pixel_gateway_health "$port" && return 0
        (( attempt == attempts )) || sleep 2
    done
    ai_bad "Pixel gateway did not become ready at its loopback endpoint."
    return 1
}

_ods_pixel_wait_http() {
    local label="$1" url="$2" attempts="${3:-120}" jq_filter="${4:-}"
    local body attempt
    for ((attempt = 1; attempt <= attempts; attempt++)); do
        if body="$(curl --fail --silent --show-error --max-time 8 "$url" 2>/dev/null)"; then
            if [[ -z "$jq_filter" ]] || jq -e "$jq_filter" >/dev/null 2>&1 <<<"$body"; then
                return 0
            fi
        fi
        sleep 2
    done
    ai_bad "$label did not become ready at its loopback endpoint."
    return 1
}

_ods_pixel_gateway_model_alias() {
    case "${ODS_MODEL_SWITCHBOARD:-enabled}" in
        legacy|observe|enabled|"") printf '%s\n' 'ods/current' ;;
        *) return 1 ;;
    esac
}

_ods_pixel_runtime_model_identity() {
    # Pixel must bind to the concrete identity served behind ods/current, not
    # the friendlier catalog alias. Otherwise ingress truth and the OpenClaw
    # contract diverge as soon as a model has a distinct GGUF/runtime name.
    local model=""
    if [[ -n "${EXTERNAL_LLM_URL:-}" ]]; then
        model="${EXTERNAL_LLM_MODEL:-}"
        [[ -n "$model" ]] || return 1
    elif [[ "${LLM_BACKEND:-}" == "vllm" ]]; then
        # The vLLM engine serves its --served-model-name, VLLM_SERVED_MODEL.
        model="${VLLM_SERVED_MODEL:-}"
        [[ -n "$model" ]] || return 1
    fi
    # llama-server serves the GGUF file name (its --alias) on every other
    # runtime, the Windows Portal's host-native server included.
    [[ -n "$model" ]] || model="${GGUF_FILE:-${LLM_MODEL:-default}}"
    printf '%s\n' "$model"
}

# The onboarding renderer's unspecified reasoning setting for the vLLM model
# LLM_MODEL: model-router gives it its catalog entry's thinking level
# ("reasoning": off, low, medium or high) in its own template arguments, so
# the Portal starts from the same default. "bootstrap" is the renderer's
# default-on value and "default" its default-off one; both keep a validated
# preference for the same route.
_ods_pixel_vllm_reasoning_default() {
    local level
    level="$(jq -r --arg model "${LLM_MODEL:-}" '
        [.models[]? | select(.runtime == "vllm" and (.llm_model_name == $model or .id == $model)) | .reasoning]
        | if length == 1 and (.[0] | type) == "string" then .[0] else "" end' \
        "${SCRIPT_DIR:?}/config/model-library.json")" || return 1
    case "$level" in
        off) printf '%s\n' default ;;
        low|medium|high) printf '%s\n' bootstrap ;;
        *) return 1 ;;
    esac
}

_ods_pixel_wait_model_gateway() {
    local label="$1" port="$2" api_key="$3" model="$4" attempts="${5:-120}"
    local body attempt
    [[ "$port" =~ ^[0-9]+$ ]] && (( port >= 1 && port <= 65535 )) || return 1
    [[ -n "$api_key" && ${#api_key} -le 4096 && "$api_key" != *[[:cntrl:]]* \
        && "$model" =~ ^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$ ]] || return 1
    for ((attempt = 1; attempt <= attempts; attempt++)); do
        if body="$(curl --fail --silent --show-error --max-time 8 \
            -H @<(printf 'Authorization: Bearer %s\n' "$api_key") \
            "http://127.0.0.1:${port}/v1/models" 2>/dev/null)" \
            && jq -e --arg model "$model" \
                '.data | type == "array" and any(.[]?; .id == $model)' \
                >/dev/null 2>&1 <<<"$body"; then
            return 0
        fi
        sleep 2
    done
    ai_bad "$label did not publish the required model alias at its authenticated loopback endpoint."
    return 1
}

_ods_pixel_enable_chat_endpoint() {
    local owner="$1" home="$2" config
    config="$home/.openclaw/openclaw.json"
    ods_pixel_run_as_owner "$owner" "$home" mkdir -p -- "$home/.openclaw"
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$config" <<'PY'
import json, os, pathlib, stat, sys, tempfile

path = pathlib.Path(sys.argv[1])
if path.is_symlink():
    raise SystemExit("OpenClaw config cannot be a symlink")
value = {}
if path.exists():
    info = path.stat()
    if not stat.S_ISREG(info.st_mode) or info.st_size > 2 * 1024 * 1024:
        raise SystemExit("OpenClaw config is not a bounded regular file")
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise SystemExit("OpenClaw config must be an object")
gateway = value.setdefault("gateway", {})
http = gateway.setdefault("http", {})
endpoints = http.setdefault("endpoints", {})
if endpoints.get("chatCompletions") == {"enabled": True}:
    # Nothing to change. A rewrite would only reorder keys, and a held source
    # upgrade compares the exact config bytes it recorded before this step.
    raise SystemExit(0)
endpoints["chatCompletions"] = {"enabled": True}
fd, temporary = tempfile.mkstemp(prefix=".openclaw.", dir=path.parent)
try:
    with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
        json.dump(value, handle, indent=2, sort_keys=True)
        handle.write("\n")
        handle.flush()
        os.fsync(handle.fileno())
    os.chmod(temporary, 0o600)
    os.replace(temporary, path)
finally:
    if os.path.exists(temporary):
        os.unlink(temporary)
PY
}

_ods_pixel_write_extension_catalog() {
    local owner="$1" home="$2" output="$3" install_root="${INSTALL_DIR:?}"
    local source_catalog="$install_root/config/extensions-catalog.json"
    local services_root="$install_root/extensions/library/services"

    ods_pixel_run_as_owner "$owner" "$home" install -d -m 0700 -- "${output%/*}" || return 1
    ods_pixel_run_as_owner "$owner" "$home" python3 - \
        "$source_catalog" "$services_root" "$output" <<'PY'
import hashlib, json, os, pathlib, re, stat, sys, tempfile

source_path, services_path, output_path = map(pathlib.Path, sys.argv[1:4])
builtin_services_path = services_path.parent.parent / "services"
owner_uid = os.getuid()


def owned_regular(path, label, maximum):
    info = path.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_nlink != 1 or info.st_uid != owner_uid
            or info.st_mode & 0o022 or info.st_size > maximum):
        raise SystemExit(f"unsafe ODS {label}")
    return path.read_bytes()


def clean_text(value, label, maximum):
    if not isinstance(value, str):
        raise SystemExit(f"invalid ODS extension {label}")
    result = " ".join(value.split())
    if not result or len(result) > maximum or any(ord(character) < 32 for character in result):
        raise SystemExit(f"invalid ODS extension {label}")
    return result


def token_list(value, label, pattern, maximum_items=64, maximum_length=128):
    if not isinstance(value, list) or len(value) > maximum_items:
        raise SystemExit(f"invalid ODS extension {label}")
    result = []
    for item in value:
        if not isinstance(item, str) or len(item) > maximum_length or re.fullmatch(pattern, item) is None:
            raise SystemExit(f"invalid ODS extension {label}")
        if item not in result:
            result.append(item)
    return sorted(result)


source_payload = owned_regular(source_path, "extension source catalog", 8 * 1024 * 1024)
services_info = services_path.lstat()
if (not stat.S_ISDIR(services_info.st_mode) or stat.S_ISLNK(services_info.st_mode)
        or services_info.st_uid != owner_uid or services_info.st_mode & 0o022):
    raise SystemExit("unsafe ODS extension services directory")
try:
    source = json.loads(source_payload)
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
    raise SystemExit("invalid ODS extension source catalog") from exc
raw_extensions = source.get("extensions") if isinstance(source, dict) else None
if not isinstance(raw_extensions, list) or not 1 <= len(raw_extensions) <= 256:
    raise SystemExit("invalid ODS extension source catalog")

extensions = []
seen = set()
for item in raw_extensions:
    if not isinstance(item, dict):
        raise SystemExit("invalid ODS extension catalog entry")
    extension_id = item.get("id")
    if (not isinstance(extension_id, str)
            or re.fullmatch(r"[a-z0-9](?:[a-z0-9_-]|\.(?=[a-z0-9])){0,63}", extension_id) is None
            or extension_id in seen):
        raise SystemExit("invalid or duplicate ODS extension id")
    seen.add(extension_id)
    catalog_source = item.get("catalog_source", "library")
    if catalog_source not in {"library", "builtin"}:
        raise SystemExit("invalid ODS extension catalog source")
    source_root = builtin_services_path if catalog_source == "builtin" else services_path
    source_info = source_root.lstat()
    if (not stat.S_ISDIR(source_info.st_mode) or stat.S_ISLNK(source_info.st_mode)
            or source_info.st_uid != owner_uid or source_info.st_mode & 0o022):
        raise SystemExit("unsafe ODS extension source directory")
    service_dir = source_root / extension_id
    try:
        directory_info = service_dir.lstat()
    except FileNotFoundError:
        continue
    if (not stat.S_ISDIR(directory_info.st_mode) or stat.S_ISLNK(directory_info.st_mode)
            or directory_info.st_uid != owner_uid or directory_info.st_mode & 0o022):
        raise SystemExit("unsafe ODS extension directory")
    compose_name = item.get("compose_file")
    if compose_name in {None, ""}:
        if catalog_source != "builtin":
            continue
        owned_regular(service_dir / "manifest.yaml", f"service manifest {extension_id}", 2 * 1024 * 1024)
    else:
        if not isinstance(compose_name, str) or re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}", compose_name) is None:
            raise SystemExit(f"invalid compose file for ODS extension {extension_id}")
        compose_path = service_dir / compose_name
        try:
            owned_regular(compose_path, f"extension compose file {extension_id}", 2 * 1024 * 1024)
        except FileNotFoundError:
            if catalog_source == "builtin":
                # Disabled services remain discoverable without authorizing a start.
                try:
                    owned_regular(compose_path.with_name(compose_name + ".disabled"),
                                  f"disabled extension compose file {extension_id}", 2 * 1024 * 1024)
                except FileNotFoundError:
                    continue
            else:
                continue

    env_vars = item.get("env_vars", [])
    if not isinstance(env_vars, list) or len(env_vars) > 128:
        raise SystemExit(f"invalid environment metadata for ODS extension {extension_id}")
    required_configuration = []
    optional_configuration = []
    for env_item in env_vars:
        if not isinstance(env_item, dict) or not isinstance(env_item.get("required", False), bool):
            raise SystemExit(f"invalid environment metadata for ODS extension {extension_id}")
        key = env_item.get("key")
        if not isinstance(key, str) or re.fullmatch(r"[A-Z][A-Z0-9_]{0,127}", key) is None:
            raise SystemExit(f"invalid configuration key for ODS extension {extension_id}")
        destination = required_configuration if env_item.get("required", False) else optional_configuration
        if key not in destination:
            destination.append(key)

    feature_names = []
    features = item.get("features", [])
    if not isinstance(features, list) or len(features) > 64:
        raise SystemExit(f"invalid feature metadata for ODS extension {extension_id}")
    for feature in features:
        if not isinstance(feature, dict):
            raise SystemExit(f"invalid feature metadata for ODS extension {extension_id}")
        name = clean_text(feature.get("name"), "feature name", 256)
        if name not in feature_names:
            feature_names.append(name)

    extensions.append({
        "id": extension_id,
        "name": clean_text(item.get("name"), "name", 128),
        "description": clean_text(item.get("description"), "description", 1000),
        "category": clean_text(item.get("category"), "category", 64),
        "catalogSource": catalog_source,
        "configurationScope": "declared-environment-keys",
        "gpuBackends": token_list(item.get("gpu_backends", []), "GPU backends", r"[a-z0-9][a-z0-9._-]{0,31}", 16, 32),
        "dependsOn": token_list(item.get("depends_on", []), "dependencies", r"[a-z0-9][a-z0-9._-]{0,63}"),
        "requiredConfiguration": sorted(required_configuration),
        "optionalConfiguration": sorted(optional_configuration),
        "tags": token_list(item.get("tags", []), "tags", r"[A-Za-z0-9][A-Za-z0-9._+-]{0,63}"),
        "featureNames": sorted(feature_names),
    })

if not extensions:
    raise SystemExit("ODS extension catalog has no available entries")
extensions.sort(key=lambda entry: entry["id"])
payload = {
    "schemaVersion": 1,
    "kind": "ods-pixel-extension-catalog",
    "sourceSha256": hashlib.sha256(source_payload).hexdigest(),
    "extensions": extensions,
}
serialized = (json.dumps(payload, sort_keys=True, separators=(",", ":")) + "\n").encode()
parent_info = output_path.parent.lstat()
if (not stat.S_ISDIR(parent_info.st_mode) or stat.S_ISLNK(parent_info.st_mode)
        or parent_info.st_uid != owner_uid or parent_info.st_mode & 0o077):
    raise SystemExit("unsafe ODS Pixel extension catalog directory")
if output_path.is_symlink():
    raise SystemExit("ODS Pixel extension catalog cannot be a symlink")
if output_path.exists():
    existing = output_path.lstat()
    if (not stat.S_ISREG(existing.st_mode) or existing.st_nlink != 1
            or existing.st_uid != owner_uid or existing.st_mode & 0o077
            or existing.st_size > 2 * 1024 * 1024):
        raise SystemExit("unsafe existing ODS Pixel extension catalog")

descriptor, temporary = tempfile.mkstemp(prefix=".extension-catalog.", dir=output_path.parent)
try:
    os.fchmod(descriptor, 0o600)
    with os.fdopen(descriptor, "wb") as stream:
        stream.write(serialized)
        stream.flush()
        os.fsync(stream.fileno())
    os.replace(temporary, output_path)
    directory = os.open(output_path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
    try:
        os.fsync(directory)
    finally:
        os.close(directory)
finally:
    if os.path.exists(temporary):
        os.unlink(temporary)
PY
}

_ods_pixel_write_extension_manager_unit() {
    local owner="$1" home="$2" output="$3"
    local source="${INSTALL_DIR:?}/extensions/services/pixel-agent/host/pixel-extension-manager.service"
    local dashboard_port="${DASHBOARD_API_PORT:-3002}"

    ods_pixel_run_as_owner "$owner" "$home" install -d -m 0700 -- "${output%/*}" || return 1
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$source" "$output" \
        "$owner" "${INSTALL_DIR:?}" "$dashboard_port" <<'PY'
import os, pathlib, re, stat, sys, tempfile

source_path, output_path = map(pathlib.Path, sys.argv[1:3])
owner, install_dir, port = sys.argv[3:6]
if re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", owner) is None:
    raise SystemExit("unsafe Pixel manager service user")
if not port.isdigit() or not 1 <= int(port) <= 65535:
    raise SystemExit("unsafe ODS dashboard port")
if (not install_dir.startswith("/") or len(install_dir) > 1024
        or any(character in install_dir for character in '\n\r\0"\\%')):
    raise SystemExit("unsafe ODS install directory for systemd")
source_info = source_path.lstat()
if (not stat.S_ISREG(source_info.st_mode) or stat.S_ISLNK(source_info.st_mode)
        or source_info.st_nlink != 1 or source_info.st_uid != os.getuid()
        or source_info.st_mode & 0o022 or source_info.st_size > 1024 * 1024):
    raise SystemExit("unsafe Pixel manager service template")
parent_info = output_path.parent.lstat()
if (not stat.S_ISDIR(parent_info.st_mode) or stat.S_ISLNK(parent_info.st_mode)
        or parent_info.st_uid != os.getuid() or parent_info.st_mode & 0o077):
    raise SystemExit("unsafe Pixel manager service output directory")
if output_path.is_symlink():
    raise SystemExit("Pixel manager service output cannot be a symlink")
if output_path.exists():
    output_info = output_path.lstat()
    if (not stat.S_ISREG(output_info.st_mode) or output_info.st_nlink != 1
            or output_info.st_uid != os.getuid() or output_info.st_mode & 0o077
            or output_info.st_size > 1024 * 1024):
        raise SystemExit("unsafe existing Pixel manager service output")
text = source_path.read_text(encoding="utf-8")
text = (text.replace("__PIXEL_SERVICE_USER__", owner)
            .replace("__ODS_INSTALL_DIR__", install_dir)
            .replace("__ODS_DASHBOARD_PORT__", port))
if "__PIXEL_" in text or "__ODS_" in text:
    raise SystemExit("unresolved Pixel manager systemd placeholder")
descriptor, temporary = tempfile.mkstemp(prefix=".extension-manager.", dir=output_path.parent)
try:
    os.fchmod(descriptor, 0o600)
    with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
        stream.write(text)
        stream.flush()
        os.fsync(stream.fileno())
    os.replace(temporary, output_path)
    directory = os.open(output_path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
    try:
        os.fsync(directory)
    finally:
        os.close(directory)
finally:
    if os.path.exists(temporary):
        os.unlink(temporary)
PY
}

_ods_pixel_write_artifact_promoter_unit() {
    local owner="$1" home="$2" output="$3"
    local source="${INSTALL_DIR:?}/extensions/services/pixel-agent/host/pixel-artifact-promoter.service"
    local workspace="$home/.openclaw/workspace-pixel"

    ods_pixel_run_as_owner "$owner" "$home" install -d -m 0700 -- "${output%/*}" || return 1
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$source" "$output" \
        "$owner" "$workspace" <<'PY'
import os, pathlib, re, stat, sys, tempfile

source_path, output_path = map(pathlib.Path, sys.argv[1:3])
owner, workspace = sys.argv[3:5]
if re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", owner) is None:
    raise SystemExit("unsafe Pixel artifact promoter owner")
if (not workspace.startswith("/") or workspace == "/" or len(workspace) > 1024
        or any(character in workspace for character in '\n\r\0"\\%')):
    raise SystemExit("unsafe Pixel workspace for artifact promotion")
source_info = source_path.lstat()
if (not stat.S_ISREG(source_info.st_mode) or stat.S_ISLNK(source_info.st_mode)
        or source_info.st_nlink != 1 or source_info.st_uid != os.getuid()
        or source_info.st_mode & 0o022 or source_info.st_size > 1024 * 1024):
    raise SystemExit("unsafe Pixel artifact promoter service template")
parent_info = output_path.parent.lstat()
if (not stat.S_ISDIR(parent_info.st_mode) or stat.S_ISLNK(parent_info.st_mode)
        or parent_info.st_uid != os.getuid() or parent_info.st_mode & 0o077):
    raise SystemExit("unsafe Pixel artifact promoter output directory")
if output_path.is_symlink():
    raise SystemExit("Pixel artifact promoter output cannot be a symlink")
if output_path.exists():
    output_info = output_path.lstat()
    if (not stat.S_ISREG(output_info.st_mode) or output_info.st_nlink != 1
            or output_info.st_uid != os.getuid() or output_info.st_mode & 0o077
            or output_info.st_size > 1024 * 1024):
        raise SystemExit("unsafe existing Pixel artifact promoter output")
text = (source_path.read_text(encoding="utf-8")
        .replace("__PIXEL_SERVICE_USER__", owner)
        .replace("__PIXEL_WORKSPACE__", workspace))
if "__PIXEL_" in text:
    raise SystemExit("unresolved Pixel artifact promoter systemd placeholder")
descriptor, temporary = tempfile.mkstemp(prefix=".artifact-promoter.", dir=output_path.parent)
try:
    os.fchmod(descriptor, 0o600)
    with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
        stream.write(text)
        stream.flush()
        os.fsync(stream.fileno())
    os.replace(temporary, output_path)
    directory = os.open(output_path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
    try:
        os.fsync(directory)
    finally:
        os.close(directory)
finally:
    if os.path.exists(temporary):
        os.unlink(temporary)
PY
}

_ods_pixel_write_workspace_preview_unit() {
    local owner="$1" home="$2" output="$3" port="${4:-9437}"
    local source="${INSTALL_DIR:?}/extensions/services/pixel-agent/host/pixel-workspace-preview.service"
    local workspace="$home/.openclaw/workspace-pixel"
    [[ "$port" =~ ^[0-9]+$ ]] && (( port >= 1 && port <= 65535 )) || return 1

    ods_pixel_run_as_owner "$owner" "$home" install -d -m 0700 -- "${output%/*}" || return 1
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$source" "$output" \
        "$owner" "$workspace" "$port" <<'PY'
import os, pathlib, re, stat, sys, tempfile

source_path, output_path = map(pathlib.Path, sys.argv[1:3])
owner, workspace, port = sys.argv[3:6]
if re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", owner) is None:
    raise SystemExit("unsafe Pixel workspace preview owner")
if (not workspace.startswith("/") or workspace == "/" or len(workspace) > 1024
        or any(character in workspace for character in '\n\r\0"\\%')):
    raise SystemExit("unsafe Pixel workspace for preview")
if not port.isdigit() or not 1 <= int(port) <= 65535:
    raise SystemExit("unsafe Pixel workspace preview port")
source_info = source_path.lstat()
if (not stat.S_ISREG(source_info.st_mode) or stat.S_ISLNK(source_info.st_mode)
        or source_info.st_nlink != 1 or source_info.st_uid != os.getuid()
        or source_info.st_mode & 0o022 or source_info.st_size > 1024 * 1024):
    raise SystemExit("unsafe Pixel workspace preview service template")
parent_info = output_path.parent.lstat()
if (not stat.S_ISDIR(parent_info.st_mode) or stat.S_ISLNK(parent_info.st_mode)
        or parent_info.st_uid != os.getuid() or parent_info.st_mode & 0o077):
    raise SystemExit("unsafe Pixel workspace preview output directory")
if output_path.is_symlink():
    raise SystemExit("Pixel workspace preview output cannot be a symlink")
if output_path.exists():
    output_info = output_path.lstat()
    if (not stat.S_ISREG(output_info.st_mode) or output_info.st_nlink != 1
            or output_info.st_uid != os.getuid() or output_info.st_mode & 0o077
            or output_info.st_size > 1024 * 1024):
        raise SystemExit("unsafe existing Pixel workspace preview output")
text = (source_path.read_text(encoding="utf-8")
        .replace("__PIXEL_SERVICE_USER__", owner)
        .replace("__PIXEL_WORKSPACE__", workspace)
        .replace("__PIXEL_PREVIEW_PORT__", port))
if "__PIXEL_" in text:
    raise SystemExit("unresolved Pixel workspace preview systemd placeholder")
descriptor, temporary = tempfile.mkstemp(prefix=".workspace-preview.", dir=output_path.parent)
try:
    os.fchmod(descriptor, 0o600)
    with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
        stream.write(text)
        stream.flush()
        os.fsync(stream.fileno())
    os.replace(temporary, output_path)
    directory = os.open(output_path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
    try:
        os.fsync(directory)
    finally:
        os.close(directory)
finally:
    if os.path.exists(temporary):
        os.unlink(temporary)
PY
}

_ods_pixel_write_operations_policy() {
    local owner="$1" home="$2" policy="$3" install_root="${INSTALL_DIR:?}"
    local workspace="${4:-$home/.openclaw/workspace-pixel}"
    local system_observer_source="$install_root/extensions/services/pixel-agent/host/system_observe.py"

    ods_pixel_run_as_owner "$owner" "$home" install -d -m 0700 -- "${policy%/*}" || return 1
    ods_pixel_run_as_owner "$owner" "$home" python3 - "$policy" "$install_root" "$workspace" \
        "$system_observer_source" <<'PY'
import json, os, pathlib, re, shutil, socket, stat, subprocess, sys, tempfile

out, install_root, workspace, system_observer_source_raw = sys.argv[1:]
path = pathlib.Path(out)
if not path.is_absolute() or path == pathlib.Path("/"):
    raise SystemExit("ODS Pixel Operations policy path must be absolute and non-root")
parent_info = path.parent.lstat()
if (not stat.S_ISDIR(parent_info.st_mode) or stat.S_ISLNK(parent_info.st_mode)
        or parent_info.st_uid != os.getuid() or parent_info.st_mode & 0o077):
    raise SystemExit("unsafe ODS Pixel Operations policy directory")
if path.is_symlink():
    raise SystemExit("ODS Pixel Operations policy cannot be a symlink")
if path.exists():
    info = path.stat()
    if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1
            or info.st_uid != os.getuid() or info.st_mode & 0o077
            or info.st_size > 2 * 1024 * 1024):
        raise SystemExit("unsafe existing ODS Pixel Operations policy")

hostname = socket.gethostname()
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,254}", hostname):
    raise SystemExit("unsafe ODS host name for Pixel Operations policy")

def normalized_root(value, label):
    candidate = pathlib.Path(value)
    if not candidate.is_absolute() or candidate == pathlib.Path("/"):
        raise SystemExit(f"{label} must be an absolute non-root path")
    return os.path.normpath(str(candidate))

install_root = normalized_root(install_root, "ODS install root")
workspace = normalized_root(workspace, "Pixel workspace")
native_macos = sys.platform == "darwin"
broker_state = "/private/var/lib/pixel-ops-broker" if native_macos else "/var/lib/pixel-ops-broker"
manager_socket_root = "/private/var/lib/ods-pixel-manager" if native_macos else "/run/ods-pixel-manager"
manager_socket = manager_socket_root + "/extension-manager.sock"
manager_program = "/usr/local/libexec/ods-pixel-services/manager/extension_manager.py" if native_macos else "/opt/pixel-ops-broker/ods-extension-manager.py"
extension_search = "/usr/local/libexec/ods-pixel-services/helpers/extension_search.py" if native_macos else "/opt/pixel-ops-broker/ods-extension-search.py"
extension_catalog = "/usr/local/libexec/ods-pixel-services/helpers/extension-catalog.json" if native_macos else "/opt/pixel-ops-broker/ods-extension-catalog.json"
system_observer = "/usr/local/libexec/ods-pixel-services/helpers/system_observe.py" if native_macos else "/usr/local/libexec/ods-pixel-system-observe.py"
system_observer_source = pathlib.Path(system_observer_source_raw)

def required_binary(name):
    candidate = shutil.which(name)
    if not candidate:
        raise SystemExit(f"required Pixel Operations executable is unavailable: {name}")
    return str(pathlib.Path(candidate).resolve(strict=True))

python_binary = str(pathlib.Path("/usr/bin/python3").resolve(strict=True))
if native_macos:
    probe = "import ctypes,os; b=ctypes.create_string_buffer(4096); assert ctypes.CDLL(None).proc_pidpath(os.getpid(),b,len(b))>0; print(b.value.decode())"
    res = subprocess.run(["/usr/bin/python3", "-I", "-B", "-c", probe], cwd="/", env={"PATH": "/usr/bin:/bin", "HOME": "/var/empty", "TMPDIR": "/private/tmp"}, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15)
    if not res.returncode and len(res.stdout.splitlines()) == 1:
        cand = pathlib.Path(res.stdout.strip())
        st = cand.lstat() if cand.exists() else None
        if st and stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode) and st.st_uid == 0 and not (st.st_mode & 0o022) and os.access(cand, os.X_OK):
            python_binary = str(cand.resolve(strict=True))
hostname_binary = required_binary("hostname")
uname_binary = required_binary("uname")
cat_binary = required_binary("cat")
uptime_binary = required_binary("uptime")
ps_binary = required_binary("ps")
systemctl_binary = None if native_macos else required_binary("systemctl")
lscpu_binary = None if native_macos else required_binary("lscpu")
free_binary = None if native_macos else required_binary("free")
df_binary = required_binary("df")
ip_binary = None if native_macos else required_binary("ip")
ss_binary = None if native_macos else required_binary("ss")
for binary in (
    python_binary, hostname_binary, uname_binary, cat_binary, uptime_binary, ps_binary,
    systemctl_binary, lscpu_binary, free_binary, df_binary, ip_binary, ss_binary,
):
    if binary is None:
        continue
    info = pathlib.Path(binary).lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_uid != 0 or info.st_mode & 0o022
            or not os.access(binary, os.X_OK)):
        raise SystemExit(f"unsafe Pixel Operations executable: {binary}")
observer_info = system_observer_source.lstat()
if (not stat.S_ISREG(observer_info.st_mode) or stat.S_ISLNK(observer_info.st_mode)
        or observer_info.st_nlink != 1 or observer_info.st_uid != os.getuid()
        or observer_info.st_mode & 0o022 or observer_info.st_size > 2 * 1024 * 1024):
    raise SystemExit("unsafe ODS Pixel system observer source")

payload = {
    "schemaVersion": 2,
    "deployment": "ods-default",
    "maxWorkers": 4,
    "workflowWorkers": 4,
    "maxWorkflowSteps": 32,
    "defaultTimeoutSeconds": 60,
    "maxTimeoutSeconds": 3600,
    "maxOutputBytes": 262144,
    "planTtlMinutes": 30,
    "identityCacheSeconds": 30,
    "sshBinary": "/usr/bin/ssh",
    "download": {
        "stagingRoot": broker_state + "/artifacts",
        "maxBytes": 536870912,
        "maxRedirects": 5,
        "allowedDomains": [
            "example.com",
            "github.com",
            "githubusercontent.com",
            "hf.co",
            "huggingface.co",
            "nodejs.org",
            "npmjs.org",
            "pypi.org",
            "pythonhosted.org",
        ],
    },
    "targets": {
        "ods-host": {
            "enabled": True,
            "backend": "local",
            "environment": "unclassified",
            "expectedHostname": hostname,
            # The broker service intentionally uses ProtectHome=true. Fixed
            # host observations do not need an owner-home cwd, so start them
            # inside the broker's root-custodied state tree instead of making
            # /home visible to the privileged execution service.
            "defaultCwd": broker_state,
            "allowedRoots": [
                install_root, workspace, broker_state, manager_socket_root,
            ],
            "writableRoots": [workspace],
            "shell": "/bin/bash",
            # Raw host commands remain a proposal-only break-glass path in the
            # external broker: every immutable plan requires a separate owner
            # approval, and the broker service itself is unprivileged and
            # systemd-confined. This enables useful host work for every model
            # without granting any model ambient execution authority.
            "allowRaw": True,
            "labels": ["ods-host"],
            "capabilities": ["inspect", "manage-extensions", "stage-download", "approved-host-command"],
        },
        "broker": {
            "enabled": True,
            "backend": "local",
            "environment": "lab",
            "expectedHostname": hostname,
            "defaultCwd": broker_state,
            "allowedRoots": [broker_state],
            "writableRoots": [broker_state + "/artifacts"],
            "shell": "/bin/sh",
            "allowRaw": False,
            "labels": ["broker-quarantine"],
            "capabilities": ["stage-download"],
        },
    },
    "actions": {
        "host.identity": {
            "description": "Verify and report the ODS host name.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [hostname_binary],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.platform": {
            "description": "Report the ODS host kernel and architecture.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [uname_binary, "-a"],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.kernel": {
            "description": "Report the ODS host kernel name and release.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [uname_binary, "-sr"],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.architecture": {
            "description": "Report the ODS host machine architecture.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [uname_binary, "-m"],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.os-release": {
            "description": "Report the ODS host operating-system release metadata.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [cat_binary, "/etc/os-release"],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.uptime": {
            "description": "Report host uptime and the one, five, and fifteen minute load averages.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [uptime_binary],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.processes": {
            "description": "List bounded process identity and resource fields without command arguments or environment values.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [
                ps_binary, "-eo", "pid=,ppid=,user=,stat=,%cpu=,%mem=,comm=", "--sort=-%cpu",
            ],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.services": {
            "description": "List running and failed system services without reading service environments or credentials.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [
                systemctl_binary, "--no-pager", "--plain", "--legend=no", "list-units",
                "--type=service", "--state=running,failed",
            ],
            "timeoutSeconds": 15,
            "exclusiveTarget": False,
        },
        "host.cpu": {
            "description": "Report bounded CPU and virtualization inventory as JSON.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [lscpu_binary, "--json"],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.gpu": {
            "description": "Report a bounded GPU name, memory capacity, and driver projection without UUIDs or serial numbers.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [python_binary, system_observer, "gpu"],
            "timeoutSeconds": 15,
            "exclusiveTarget": False,
        },
        "host.memory": {
            "description": "Report host memory and swap capacity in bytes.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [free_binary, "--bytes"],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.storage": {
            "description": "Report mounted filesystem capacity without reading filesystem contents.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [
                df_binary, "--block-size=1", "--output=fstype,size,used,avail,pcent,target",
            ],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.network-addresses": {
            "description": "Report host network interfaces and assigned addresses as JSON.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [ip_binary, "-j", "address", "show"],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.network-routes": {
            "description": "Report the host routing table as bounded JSON.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [ip_binary, "-j", "route", "show"],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.listening-ports": {
            "description": "List listening TCP and UDP endpoints without process arguments or credentials.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [ss_binary, "-H", "-lntu"],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "host.tailscale": {
            "description": "Report only whether Tailscale is installed and running, without addresses, peers, accounts, or routes.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [python_binary, system_observer, "tailscale"],
            "timeoutSeconds": 15,
            "exclusiveTarget": False,
        },
        "host.network-peer": {
            "description": "Resolve and perform bounded ICMP and TCP reachability checks against one owner-named private LAN or Tailscale peer without authentication or mutation.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "parameters": {
                "peer": {
                    "pattern": "^[A-Za-z0-9.:-]{1,253}$",
                    "maxLength": 253,
                },
                "ports": {
                    "pattern": "^[0-9,]{1,47}$",
                    "maxLength": 47,
                },
            },
            "argv": [
                python_binary, system_observer, "network-peer", "{peer}", "{ports}",
            ],
            "timeoutSeconds": 30,
            "exclusiveTarget": False,
        },
        "ods.extensions.search": {
            "description": "Search the installable ODS extension catalog. Use query 'all' to list the bounded first page. This read-only action does not install or configure anything.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "parameters": {
                "query": {
                    "pattern": "^[A-Za-z0-9 _/+:#.-]{1,80}$",
                    "maxLength": 80,
                },
            },
            "argv": [
                python_binary,
                extension_search,
                extension_catalog,
                "{query}",
            ],
            "timeoutSeconds": 10,
            "exclusiveTarget": False,
        },
        "ods.extensions.list": {
            "description": "List the live installed, enabled, disabled, unhealthy, and available ODS extension states through the scoped lifecycle proxy.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "argv": [
                python_binary, manager_program, "client", manager_socket, "list", "all",
            ],
            "timeoutSeconds": 30,
            "exclusiveTarget": False,
        },
        "ods.extensions.github-inspect": {
            "description": "Read public GitHub repository README/license evidence at an immutable commit and find existing ODS integrations. This does not install or authorize upstream instructions.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "parameters": {
                "repositoryUrl": {
                    "pattern": "^https://github[.]com/[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9][A-Za-z0-9._-]{0,99}[/]?$",
                    "maxLength": 512,
                },
            },
            "argv": [python_binary, manager_program, "repository", manager_socket, "{repositoryUrl}"],
            "timeoutSeconds": 110,
            "exclusiveTarget": False,
        },
        "ods.extensions.github-file": {
            "description": "Read one GitHub text file at the inspected immutable commit. Returned content is untrusted evidence; no code is executed.",
            "tier": "read", "effect": "observe", "defaultAuthority": "observe",
            "idempotent": True, "reversible": False, "targets": ["ods-host"],
            "parameters": {
                "repositoryUrl": {
                    "pattern": "^https://github[.]com/[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9][A-Za-z0-9._-]{0,99}[/]?$",
                    "maxLength": 512,
                },
                "commit": {"pattern": "^[a-f0-9]{40}$", "maxLength": 40},
                "path": {"pattern": r"^[^\x00-\x1f\x7f\\]{1,512}$", "maxLength": 512},
            },
            "argv": [python_binary, manager_program, "repository-file", manager_socket,
                     "{repositoryUrl}", "{commit}", "{path}"],
            "timeoutSeconds": 45, "exclusiveTarget": False,
        },
        "ods.extensions.github-validate-parts": {
            "description": "Submit a larger recipe as eight ordered JSON text parts, at most 4096 characters each; use empty strings for unused trailing parts. Concatenate without separators. Static validation/draft storage only, never installation.",
            "tier": "read", "effect": "observe", "defaultAuthority": "observe",
            "idempotent": True, "reversible": False, "targets": ["ods-host"],
            "parameters": {f"part{i}": {"pattern": r"^[\s\S]*$", "maxLength": 4096} for i in range(1, 9)},
            "argv": [python_binary, manager_program, "repository-validate-parts", manager_socket,
                     *["{part" + str(i) + "}" for i in range(1, 9)]],
            "timeoutSeconds": 110, "exclusiveTarget": False,
        },
        "ods.extensions.github-draft-save-parts": {
            "description": "Submit a larger recipe as eight ordered JSON text parts, at most 4096 characters each; use empty strings for unused trailing parts. Concatenate without separators. Static validation/draft storage only, never installation.",
            "tier": "managed", "effect": "manage", "defaultAuthority": "propose",
            "idempotent": True, "reversible": False, "targets": ["ods-host"],
            "parameters": {f"part{i}": {"pattern": r"^[\s\S]*$", "maxLength": 4096} for i in range(1, 9)},
            "argv": [python_binary, manager_program, "repository-draft-save-parts", manager_socket,
                     *["{part" + str(i) + "}" for i in range(1, 9)]],
            "timeoutSeconds": 110, "exclusiveTarget": True,
        },
        "ods.extensions.github-draft-prepare": {
            "description": "Prepare an exact saved GitHub recipe as an available extension configuration. Does not download, start or mark the application installed.",
            "tier": "managed", "effect": "manage", "defaultAuthority": "propose",
            "idempotent": True, "reversible": False, "targets": ["ods-host"],
            "parameters": {"draftId": {"pattern": "^[a-f0-9]{64}$", "maxLength": 64}},
            "argv": [python_binary, manager_program, "repository-draft-prepare", manager_socket, "{draftId}"],
            "timeoutSeconds": 150, "exclusiveTarget": True,
        },
        "ods.extensions.github-draft-read": {
            "description": "Recover a saved extension recipe by its exact draft ID. Recovered proposals require fresh validation and do not prove installation.",
            "tier": "read", "effect": "observe", "defaultAuthority": "observe",
            "idempotent": True, "reversible": False, "targets": ["ods-host"],
            "parameters": {"draftId": {"pattern": "^[a-f0-9]{64}$", "maxLength": 64}},
            "argv": [python_binary, manager_program, "repository-draft-read", manager_socket, "{draftId}"],
            "timeoutSeconds": 45, "exclusiveTarget": False,
        },
        "ods.extensions.github-draft-save": {
            "description": "Save an immutable, statically validated extension recipe for recovery. This stores a draft only; it does not install or register an extension.",
            "tier": "managed", "effect": "manage", "defaultAuthority": "propose",
            "idempotent": True, "reversible": False, "targets": ["ods-host"],
            "parameters": {"recipeJson": {"pattern": r"^[\s\S]+$", "maxLength": 4096}},
            "argv": [python_binary, manager_program, "repository-draft-save", manager_socket, "{recipeJson}"],
            "timeoutSeconds": 110, "exclusiveTarget": True,
        },
        "ods.extensions.github-validate": {
            "description": "Validate a proposed GitHub extension manifest and Compose recipe; returns static diagnostics only, without installation or registration.",
            "tier": "read", "effect": "observe", "defaultAuthority": "observe",
            "idempotent": True, "reversible": False, "targets": ["ods-host"],
            "parameters": {
                "recipeJson": {"pattern": r"^[\s\S]+$", "maxLength": 4096},
            },
            "argv": [python_binary, manager_program, "repository-validate", manager_socket, "{recipeJson}"],
            "timeoutSeconds": 110, "exclusiveTarget": False,
        },
        "ods.extensions.inspect": {
            "description": "Inspect one ODS extension's installed state and configuration prerequisites through the scoped lifecycle proxy.",
            "tier": "read",
            "effect": "observe",
            "defaultAuthority": "observe",
            "idempotent": True,
            "reversible": False,
            "targets": ["ods-host"],
            "parameters": {
                "serviceId": {
                    "pattern": "^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,62}[a-z0-9])$",
                    "maxLength": 64,
                },
            },
            "argv": [
                python_binary, manager_program, "client", manager_socket, "inspect", "{serviceId}",
            ],
            "timeoutSeconds": 90,
            "exclusiveTarget": False,
        },
        "ods.extensions.install": {
            "description": "Install and verify one cataloged ODS extension through the scoped lifecycle proxy. Exact-plan owner approval is required.",
            "tier": "managed",
            "effect": "manage",
            "defaultAuthority": "propose",
            "idempotent": True,
            "reversible": True,
            "rollbackAction": "ods.extensions.remove",
            "verificationAction": "ods.extensions.inspect",
            "targets": ["ods-host"],
            "parameters": {
                "serviceId": {
                    "pattern": "^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,62}[a-z0-9])$",
                    "maxLength": 64,
                },
            },
            "argv": [
                python_binary, manager_program, "client", manager_socket, "install", "{serviceId}",
            ],
            "timeoutSeconds": 900,
            "exclusiveTarget": True,
        },
        "ods.extensions.install-next": {
            "description": "Advance one installation step for a cataloged ODS extension and its declared dependencies. Retains uncertain effects; acceptance is not readiness.",
            "tier": "managed",
            "effect": "manage",
            "defaultAuthority": "propose",
            "idempotent": True,
            "reversible": False,
            "verificationAction": "ods.extensions.inspect",
            "targets": ["ods-host"],
            "parameters": {
                "serviceId": {
                    "pattern": "^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,62}[a-z0-9])$",
                    "maxLength": 64,
                },
            },
            "argv": [
                python_binary, manager_program, "client", manager_socket, "install-next", "{serviceId}",
            ],
            "timeoutSeconds": 240,
            "exclusiveTarget": True,
        },
        "ods.extensions.enable": {
            "description": "Enable and verify one installed ODS extension through the scoped lifecycle proxy. Exact-plan owner approval is required.",
            "tier": "managed",
            "effect": "manage",
            "defaultAuthority": "propose",
            "idempotent": True,
            "reversible": True,
            "rollbackAction": "ods.extensions.disable",
            "verificationAction": "ods.extensions.inspect",
            "targets": ["ods-host"],
            "parameters": {
                "serviceId": {
                    "pattern": "^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,62}[a-z0-9])$",
                    "maxLength": 64,
                },
            },
            "argv": [
                python_binary, manager_program, "client", manager_socket, "enable", "{serviceId}",
            ],
            "timeoutSeconds": 300,
            "exclusiveTarget": True,
        },
        "ods.extensions.disable": {
            "description": "Disable and verify one ODS extension while preserving its data. Exact-plan owner approval is required.",
            "tier": "managed",
            "effect": "manage",
            "defaultAuthority": "propose",
            "idempotent": True,
            "reversible": True,
            "rollbackAction": "ods.extensions.enable",
            "verificationAction": "ods.extensions.inspect",
            "targets": ["ods-host"],
            "parameters": {
                "serviceId": {
                    "pattern": "^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,62}[a-z0-9])$",
                    "maxLength": 64,
                },
            },
            "argv": [
                python_binary, manager_program, "client", manager_socket, "disable", "{serviceId}",
            ],
            "timeoutSeconds": 300,
            "exclusiveTarget": True,
        },
        "ods.extensions.remove": {
            "description": "Remove one disabled user-installed ODS extension definition while preserving its data. Exact-plan owner approval is required.",
            "tier": "change",
            "effect": "change",
            "defaultAuthority": "propose",
            "idempotent": True,
            "reversible": False,
            "verificationAction": "ods.extensions.inspect",
            "targets": ["ods-host"],
            "parameters": {
                "serviceId": {
                    "pattern": "^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,62}[a-z0-9])$",
                    "maxLength": 64,
                },
            },
            "argv": [
                python_binary, manager_program, "client", manager_socket, "remove", "{serviceId}",
            ],
            "timeoutSeconds": 300,
            "exclusiveTarget": True,
        },
    },
    "authority": {
        "defaultLevel": "propose",
        "grants": [{
            "id": "ods-approved-downloads",
            "level": "bounded-auto",
            "actions": ["download.stage"],
            "targets": ["broker"],
            "tiers": ["staging"],
            "environments": ["lab"],
            "maxExecutions": 100,
            "windowSeconds": 86400,
            "maxConcurrent": 2,
            "maxRuntimeSeconds": 600,
            "maxFailures": 10,
            "maxArtifactBytes": 536870912,
        }],
    },
}
if native_macos:
    for observation in ("os-release", "cpu", "memory", "processes", "services", "storage",
                        "network-addresses", "network-routes", "listening-ports"):
        payload["actions"]["host." + observation]["argv"] = [python_binary, system_observer, observation]
content = json.dumps(payload, indent=2, sort_keys=True) + "\n"
descriptor, temporary = tempfile.mkstemp(prefix=".pixel-ops-policy.", dir=path.parent)
try:
    with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle:
        handle.write(content)
        handle.flush()
        os.fsync(handle.fileno())
    os.chmod(temporary, 0o600)
    os.replace(temporary, path)
    directory = os.open(path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
    try:
        os.fsync(directory)
    finally:
        os.close(directory)
finally:
    if os.path.exists(temporary):
        os.unlink(temporary)
PY
}

_ods_pixel_write_onboarding() {
    local owner="$1" home="$2" answers="$3" openclaw_bin="$4" plugin_path="$5" plugin_digest="$6"
    local web_search_provider="${7:-searxng}" parallel_path="${8:-}" parallel_digest="${9:-}"
    local context="${MAX_CONTEXT:-16384}" max_tokens reasoning=default
    local gateway_alias gateway_label runtime_model model_gateway_port="${PIXEL_MODEL_RELAY_PORT:-4006}" pixel_gateway_port gateway_key="${PIXEL_MODEL_RELAY_KEY:-}"
    local gateway_key_file write_status=0
    if [[ "$context" =~ ^[0-9]+$ && "$context" -ge 4096 ]]; then
        :
    else
        ai_bad "Pixel requires a model context of at least 4096 tokens."
        return 1
    fi
    max_tokens="$(_ods_pixel_default_output_tokens "$context")" || {
        ai_bad "Pixel received an invalid model context budget."
        return 1
    }
    gateway_alias="$(_ods_pixel_gateway_model_alias)" || {
        ai_bad "Pixel received an unsupported ODS model Switchboard mode."
        return 1
    }
    gateway_label="Default"
    [[ "$gateway_alias" == "ods/current" ]] && gateway_label="Current"
    runtime_model="$(_ods_pixel_runtime_model_identity)" || return 1
    # This field controls the active OpenClaw reasoning path, not merely the
    # model family's theoretical capability. An explicit operator setting
    # (including an empty value) always wins. When unset, the renderer decides:
    # a local built-in Qwen3.5-2B bootstrap route defaults to reasoning on so
    # the Portal can complete simple tasks without tool loops; every other
    # route keeps the historical no-think default. The renderer preserves a
    # previously validated reasoning preference for the same model route. On
    # the vLLM engine the catalog entry's thinking default decides, which
    # model-router applies; LLAMA_REASONING is llama-server's setting.
    if [[ -z "${EXTERNAL_LLM_URL:-}" && "${LLM_BACKEND:-}" == "vllm" ]]; then
        reasoning="$(_ods_pixel_vllm_reasoning_default)" || {
            ai_bad "Pixel could not read the thinking default of ${LLM_MODEL:-the vLLM model} from config/model-library.json. The ODS files may be incomplete: download ODS again and rerun the installer. Need help? Ask on the ODS Discord: ${ODS_HELP_DISCORD_URL:-https://discord.gg/4ntNp9MAwC}"
            return 1
        }
    elif [[ -n "${LLAMA_REASONING+x}" ]]; then
        # Case-insensitive, as ods-host-agent.py reads LLAMA_REASONING.
        if [[ "$(printf '%s' "${LLAMA_REASONING:-off}" | tr '[:upper:]' '[:lower:]')" =~ ^(off|none|false|0)$ ]]; then
            reasoning=false
        else
            reasoning=true
        fi
    elif [[ -z "${EXTERNAL_LLM_URL:-}" ]]; then
        case "$(printf '%s' "$runtime_model" | tr '[:upper:]' '[:lower:]')" in
            qwen3.5-2b|qwen3.5-2b-q4_k_m.gguf) reasoning=bootstrap ;;
        esac
    fi
    if [[ ! "$model_gateway_port" =~ ^[0-9]+$ ]] || (( model_gateway_port < 1 || model_gateway_port > 65535 )); then
        ai_bad "Pixel requires a valid loopback model relay port."
        return 1
    fi
    pixel_gateway_port="$(_ods_pixel_gateway_port)" || {
        ai_bad "Pixel requires a valid loopback gateway port."
        return 1
    }
    [[ -n "$gateway_key" && ${#gateway_key} -le 4096 ]] || {
        ai_bad "Pixel requires the generated model relay key."
        return 1
    }

    local renderer
    renderer="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/pixel-onboarding.py" || return 1
    [[ -f "$renderer" ]] || return 1
    ods_pixel_run_as_owner "$owner" "$home" install -d -m 0700 -- "${answers%/*}" || return 1
    gateway_key_file="$(ods_pixel_run_as_owner "$owner" "$home" \
        mktemp "${answers%/*}/.pixel-gateway-key.XXXXXX")" || return 1
    if ! printf '%s' "$gateway_key" \
        | ods_pixel_run_as_owner "$owner" "$home" tee -- "$gateway_key_file" >/dev/null \
        || ! ods_pixel_run_as_owner "$owner" "$home" chmod 0600 "$gateway_key_file"; then
        ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$gateway_key_file" || true
        return 1
    fi
    ods_pixel_run_as_owner "$owner" "$home" python3 "$renderer" "$answers" \
        "$openclaw_bin" "$home" "$runtime_model" "$context" "$max_tokens" "$reasoning" \
        "$gateway_alias" "$gateway_label" "$model_gateway_port" "$pixel_gateway_port" "$gateway_key_file" \
        "${SEARXNG_PORT:-8888}" "$plugin_path" "$plugin_digest" \
        "$web_search_provider" "$parallel_path" "$parallel_digest" || write_status=$?
    ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$gateway_key_file" || write_status=1
    return "$write_status"
}

_ods_pixel_wait_extension_manager_probe() {
    local program="$1" extension_id="$2" attempts="${3:-30}" delay="${4:-1}"
    local manager_probe attempt
    [[ "$program" == /* && -f "$program" && ! -L "$program" \
        && "$extension_id" =~ ^[a-z0-9][a-z0-9._-]{0,63}$ \
        && "$extension_id" != *. \
        && "$attempts" =~ ^[0-9]+$ && "$attempts" -ge 1 && "$attempts" -le 60 \
        && "$delay" =~ ^[0-9]+$ && "$delay" -le 5 ]] || return 1
    for ((attempt = 1; attempt <= attempts; attempt++)); do
        if manager_probe="$(ods_sudo -u pixel-ops-broker /usr/bin/python3 \
            "$program" client /run/ods-pixel-manager/extension-manager.sock \
            inspect "$extension_id" 2>/dev/null)" \
            && jq -e --arg id "$extension_id" '.schemaVersion == 1
                and .kind == "ods-pixel-extension-lifecycle"
                and .action == "inspect" and .extensionId == $id
                and (.outcome == "inspected" or .outcome == "blocked")
                and .changed == false and .externalEffectOccurred == false
                and (.requiredConfiguration | type == "array")
                and (.optionalConfiguration | type == "array")
                and (.missingConfiguration | type == "array")
                and .rollback == {"attempted": false, "succeeded": null}
                and .boundary == "Scoped ODS extension lifecycle proxy; it grants no Docker, shell, credential, arbitrary HTTP, or data-purge authority."' \
                <<<"$manager_probe" >/dev/null; then
            return 0
        fi
        if (( attempt < attempts && delay > 0 )); then
            sleep "$delay"
        fi
    done
    return 1
}

_ods_pixel_wait_artifact_promoter_probe() {
    local owner="$1" home="$2" program="$3" attempts="${4:-30}" delay="${5:-1}"
    local response attempt
    [[ "$program" == /* && -f "$program" && ! -L "$program" \
        && "$attempts" =~ ^[0-9]+$ && "$attempts" -ge 1 && "$attempts" -le 60 \
        && "$delay" =~ ^[0-9]+$ && "$delay" -le 5 ]] || return 1
    for ((attempt = 1; attempt <= attempts; attempt++)); do
        if response="$(ods_pixel_run_as_owner "$owner" "$home" /usr/bin/python3 \
            "$program" health /run/ods-pixel-artifact-promoter/promoter.sock 2>/dev/null)" \
            && jq -e '.schemaVersion == 1
                and .kind == "ods-pixel-download-promotion"
                and .status == "ok"
                and .boundary == "Verified create-only promotion from Pixel Operations quarantine into the configured owner workspace; no arbitrary source, overwrite, execution, or path traversal authority."' \
                <<<"$response" >/dev/null; then
            return 0
        fi
        if (( attempt < attempts && delay > 0 )); then
            sleep "$delay"
        fi
    done
    return 1
}

_ods_pixel_wait_workspace_preview_probe() {
    local owner="$1" home="$2" program="$3" port="${4:-9437}" attempts="${5:-30}" delay="${6:-1}"
    local response attempt
    [[ "$program" == /* && -f "$program" && ! -L "$program" \
        && "$port" =~ ^[0-9]+$ && "$port" -ge 1 && "$port" -le 65535 \
        && "$attempts" =~ ^[0-9]+$ && "$attempts" -ge 1 && "$attempts" -le 60 \
        && "$delay" =~ ^[0-9]+$ && "$delay" -le 5 ]] || return 1
    for ((attempt = 1; attempt <= attempts; attempt++)); do
        if response="$(ods_pixel_run_as_owner "$owner" "$home" /usr/bin/python3 \
            "$program" health /run/ods-pixel-preview/control.sock 2>/dev/null)" \
            && jq -e --argjson port "$port" '.schemaVersion == 1
                and .kind == "ods-pixel-workspace-preview"
                and .status == "ok" and .port == $port
                and .boundary == "Create-only static-site snapshot from the configured Pixel workspace to a dedicated loopback preview origin; no arbitrary host path, network destination, server process, overwrite, or execution authority."' \
                <<<"$response" >/dev/null; then
            return 0
        fi
        if (( attempt < attempts && delay > 0 )); then
            sleep "$delay"
        fi
    done
    return 1
}

_ods_pixel_install_ingress() {
    local owner="$1" home="$2" plugin_root="$3" extension_catalog="$4"
    local rendered_extension_manager_unit="$5" rendered_artifact_promoter_unit="$6"
    local rendered_workspace_preview_unit="$7" preview_port="${PIXEL_PREVIEW_PORT:-9437}" gateway_port
    local token_file="$home/.openclaw/openclaw.json"
    local runtime_token_file="/run/ods-pixel/openclaw.json"
    local extension_helper="$plugin_root/host/extension_search.py"
    local installed_extension_helper="/opt/pixel-ops-broker/ods-extension-search.py"
    local installed_extension_catalog="/opt/pixel-ops-broker/ods-extension-catalog.json"
    local extension_manager="$plugin_root/host/extension_manager.py"
    local installed_extension_manager="/opt/pixel-ops-broker/ods-extension-manager.py"
    local system_extension_manager="/usr/local/libexec/ods-pixel-extension-manager.py"
    local artifact_promoter="$plugin_root/host/artifact_promoter.py"
    local system_artifact_promoter="/usr/local/libexec/ods-pixel-artifact-promoter.py"
    local workspace_preview="$plugin_root/host/workspace_preview.py"
    local system_workspace_preview="/usr/local/libexec/ods-pixel-workspace-preview.py"
    local unix_peer="$plugin_root/host/unix_peer.py"
    local system_observer="$plugin_root/host/system_observe.py"
    local installed_system_observer="/usr/local/libexec/ods-pixel-system-observe.py"
    local operations_service_dropin="$plugin_root/host/pixel-ops-broker-ods.conf"
    local operations_service_dropin_dir="/etc/systemd/system/pixel-ops-broker.service.d"
    local installed_operations_service_dropin="$operations_service_dropin_dir/10-ods-host-observation.conf"
    local wsl_bridge=false
    local wsl_bridge_source="$plugin_root/host/pixel-wsl-runtime-bridge.sh"
    local wsl_bridge_unit="$plugin_root/host/pixel-wsl-runtime-bridge.service"
    local ods_version="${VERSION:-3.0.0}"
    if grep -Fxq 'PIXEL_RUNTIME_BIND_PROPAGATION=rshared' "${INSTALL_DIR:?}/.env"; then
        grep -Fxq 'PIXEL_INGRESS_RUNTIME_DIR=/mnt/wsl/ods-portal-runtime/ingress' "$INSTALL_DIR/.env" || return 1
        grep -Fxq 'PIXEL_PREVIEW_RUNTIME_DIR=/mnt/wsl/ods-portal-runtime/preview' "$INSTALL_DIR/.env" || return 1
        grep -qi microsoft /proc/sys/kernel/osrelease || return 1
        wsl_bridge=true
    fi
    [[ "$ods_version" =~ ^[0-9]+(\.[0-9]+){1,3}([-+][A-Za-z0-9.-]+)?$ ]] || return 1
    [[ -f "$token_file" && ! -L "$token_file" ]] || return 1
    [[ "$(stat -c '%u' -- "$token_file")" == "$(id -u "$owner")" ]] || return 1
    (( (8#$(stat -c '%a' -- "$token_file") & 0077) == 0 )) || return 1
    local projection_source kind uid mode size
    for projection_source in "$extension_helper" "$extension_catalog" \
        "$extension_manager" "$rendered_extension_manager_unit" \
        "$artifact_promoter" "$rendered_artifact_promoter_unit" \
        "$workspace_preview" "$rendered_workspace_preview_unit" \
        "$system_observer" "$unix_peer" \
        "$operations_service_dropin"; do
        [[ -f "$projection_source" && ! -L "$projection_source" ]] || return 1
        IFS='|' read -r kind uid mode size < <(stat -c '%F|%u|%a|%s' -- "$projection_source")
        [[ "$kind" == "regular file" && "$uid" == "$(id -u "$owner")" \
            && "$size" =~ ^[0-9]+$ && "$size" -le 2097152 ]] || return 1
        (( (8#$mode & 0022) == 0 )) || return 1
    done
    (( (8#$(stat -c '%a' -- "$extension_catalog") & 0077) == 0 )) || return 1
    if "$wsl_bridge"; then
        for projection_source in "$wsl_bridge_source" "$wsl_bridge_unit"; do
            [[ -f "$projection_source" && ! -L "$projection_source" ]] || return 1
            IFS='|' read -r kind uid mode size < <(stat -c '%F|%u|%a|%s' -- "$projection_source")
            [[ "$kind" == "regular file" && "$uid" == "$(id -u "$owner")" \
                && "$size" =~ ^[0-9]+$ && "$size" -le 2097152 ]] || return 1
            (( (8#$mode & 0022) == 0 )) || return 1
        done
    fi

    gateway_port="$(_ods_pixel_gateway_port)" || return 1
    [[ "$preview_port" =~ ^[0-9]+$ ]] || return 1
    (( preview_port >= 1 && preview_port <= 65535 )) || return 1
    (( preview_port != gateway_port )) || return 1
    local app_port
    for app_port in \
        "${DASHBOARD_PORT:-3001}" "${WEBUI_PORT:-3000}" "${SEARXNG_PORT:-8888}" \
        "${PERPLEXICA_PORT:-3004}" "${WHISPER_PORT:-9000}" "${TTS_PORT:-8880}" \
        "${N8N_PORT:-5678}" "${QDRANT_PORT:-6333}" "${EMBEDDINGS_PORT:-8090}" \
        "${LITELLM_PORT:-4000}" "${OLLAMA_PORT:-11434}" "${SHIELD_PORT:-8085}" \
        "${TOKEN_SPY_PORT:-3005}" "${APE_PORT:-7890}" "${HERMES_PROXY_PORT:-9120}"; do
        [[ "$app_port" =~ ^[0-9]+$ ]] || return 1
        (( app_port >= 1 && app_port <= 65535 )) || return 1
        (( preview_port != app_port )) || return 1
    done

    local stage extension_probe
    stage="$(mktemp -d)" || return 1
    python3 - "$plugin_root/host/pixel-ingress.service" "$stage/pixel-ingress.service" "$owner" "$token_file" "$runtime_token_file" <<'PY'
import pathlib, pwd, sys

source, target, owner, token_source, token_file = sys.argv[1:6]
text = pathlib.Path(source).read_text(encoding="utf-8")
if any(c in owner + token_source + token_file for c in "\n\r\0"):
    raise SystemExit("unsafe systemd substitution")
text = (text.replace("__PIXEL_SERVICE_USER__", owner)
            .replace("__PIXEL_SERVICE_GID__", str(pwd.getpwnam(owner).pw_gid))
            .replace("__PIXEL_GATEWAY_TOKEN_SOURCE__", token_source)
            .replace("__PIXEL_GATEWAY_TOKEN_FILE__", token_file))
if "__PIXEL_" in text:
    raise SystemExit("unresolved Pixel systemd placeholder")
pathlib.Path(target).write_text(text, encoding="utf-8", newline="\n")
PY
    cat > "$stage/pixel-agent.env" <<EOF
PIXEL_INGRESS_SOCKET=/run/ods-pixel/pixel-ingress.sock
PIXEL_CHAT_STATE_DIR=/var/lib/ods-pixel-chat
PIXEL_ACCESS_OWNER_KEY_FILE=/etc/ods/pixel-access-relay.key
PIXEL_INGRESS_GID=${PIXEL_INGRESS_GID:?}
PIXEL_GATEWAY_TOKEN_FILE=$runtime_token_file
PIXEL_GATEWAY_PORT=$gateway_port
PIXEL_STATUS_FILE=/run/ods-pixel/ods-status.json
PIXEL_STATUS_INTERVAL_MS=30000
PIXEL_ODS_VERSION=$ods_version
PIXEL_ODS_DASHBOARD_PORT=${DASHBOARD_PORT:-3001}
PIXEL_ODS_WEBUI_PORT=${WEBUI_PORT:-3000}
PIXEL_ODS_SEARXNG_PORT=${SEARXNG_PORT:-8888}
PIXEL_ODS_PERPLEXICA_PORT=${PERPLEXICA_PORT:-3004}
PIXEL_ODS_WHISPER_PORT=${WHISPER_PORT:-9000}
PIXEL_ODS_TTS_PORT=${TTS_PORT:-8880}
PIXEL_ODS_N8N_PORT=${N8N_PORT:-5678}
PIXEL_ODS_QDRANT_PORT=${QDRANT_PORT:-6333}
PIXEL_ODS_EMBEDDINGS_PORT=${EMBEDDINGS_PORT:-8090}
PIXEL_ODS_LITELLM_PORT=${LITELLM_PORT:-4000}
PIXEL_ODS_LLAMA_PORT=${OLLAMA_PORT:-11434}
PIXEL_ODS_PRIVACY_SHIELD_PORT=${SHIELD_PORT:-8085}
PIXEL_ODS_TOKEN_SPY_PORT=${TOKEN_SPY_PORT:-3005}
PIXEL_ODS_APE_PORT=${APE_PORT:-7890}
PIXEL_ODS_HERMES_PROXY_PORT=${HERMES_PROXY_PORT:-9120}
EOF
    chmod 0640 "$stage/pixel-agent.env"
    ods_sudo install -d -m 0755 /usr/local/libexec /etc/ods
    ods_sudo test -d /opt/pixel-ops-broker
    ods_sudo test ! -L /opt/pixel-ops-broker
    ods_sudo install -o root -g root -m 0755 "$extension_helper" "$installed_extension_helper"
    ods_sudo install -o root -g pixel-ops -m 0640 "$extension_catalog" "$installed_extension_catalog"
    ods_sudo install -o root -g root -m 0755 "$extension_manager" "$installed_extension_manager"
    ods_sudo install -o root -g root -m 0755 "$extension_manager" "$system_extension_manager"
    ods_sudo install -o root -g root -m 0755 "$artifact_promoter" "$system_artifact_promoter"
    ods_sudo install -o root -g root -m 0755 "$workspace_preview" "$system_workspace_preview"
    ods_sudo install -o root -g root -m 0755 "$system_observer" "$installed_system_observer"
    ods_sudo install -o root -g root -m 0644 "$unix_peer" /usr/local/libexec/unix_peer.py
    ods_sudo install -o root -g root -m 0644 "$unix_peer" /opt/pixel-ops-broker/unix_peer.py
    if ods_sudo test -e "$operations_service_dropin_dir" \
        || ods_sudo test -L "$operations_service_dropin_dir"; then
        ods_sudo test -d "$operations_service_dropin_dir" || return 1
        ods_sudo test ! -L "$operations_service_dropin_dir" || return 1
    else
        ods_sudo install -d -o root -g root -m 0755 "$operations_service_dropin_dir" || return 1
    fi
    [[ "$(ods_sudo stat -c '%U:%G:%a' -- "$operations_service_dropin_dir")" == "root:root:755" ]] \
        || return 1
    ods_sudo install -o root -g root -m 0644 "$operations_service_dropin" \
        "$installed_operations_service_dropin" || return 1
    ods_sudo cmp -s -- "$extension_helper" "$installed_extension_helper"
    ods_sudo cmp -s -- "$extension_catalog" "$installed_extension_catalog"
    ods_sudo cmp -s -- "$extension_manager" "$installed_extension_manager"
    ods_sudo cmp -s -- "$extension_manager" "$system_extension_manager"
    ods_sudo cmp -s -- "$artifact_promoter" "$system_artifact_promoter"
    ods_sudo cmp -s -- "$workspace_preview" "$system_workspace_preview"
    ods_sudo cmp -s -- "$system_observer" "$installed_system_observer"
    ods_sudo cmp -s -- "$unix_peer" /usr/local/libexec/unix_peer.py
    ods_sudo cmp -s -- "$unix_peer" /opt/pixel-ops-broker/unix_peer.py
    ods_sudo cmp -s -- "$operations_service_dropin" "$installed_operations_service_dropin" \
        || return 1
    extension_probe="$(ods_sudo -u pixel-ops-broker /usr/bin/python3 \
        "$installed_extension_helper" "$installed_extension_catalog" all)" || return 1
    jq -e '.schemaVersion == 1 and .kind == "ods-pixel-extension-search"
        and .query == "all" and (.totalCatalog | type == "number") and .totalCatalog > 0
        and (.matches | type == "array") and (.matches | length) <= 10
        and (.boundary | type == "string")' <<<"$extension_probe" >/dev/null || return 1
    ods_sudo install -o root -g root -m 0755 "$plugin_root/host/pixel_ingress.mjs" /usr/local/libexec/ods-pixel-ingress.mjs
    ods_sudo install -o root -g root -m 0644 "$plugin_root/host/chat_history_ledger.mjs" /usr/local/libexec/chat_history_ledger.mjs
    ods_sudo install -o root -g root -m 0644 "$plugin_root/host/chat_image_store.mjs" /usr/local/libexec/chat_image_store.mjs
    ods_sudo install -o root -g root -m 0644 "$plugin_root/host/chat_image_transport.mjs" /usr/local/libexec/chat_image_transport.mjs
    ods_sudo install -o root -g root -m 0644 "$plugin_root/host/access_mode_relay.mjs" /usr/local/libexec/access_mode_relay.mjs
    ods_sudo install -o root -g root -m 0644 "$plugin_root/host/task_activity_schema.mjs" /usr/local/libexec/task_activity_schema.mjs
    ods_sudo install -o root -g root -m 0644 "$plugin_root/host/questions_schema.mjs" /usr/local/libexec/questions_schema.mjs
    ods_sudo install -o root -g root -m 0644 "$plugin_root/host/owner_tool_policy.mjs" /usr/local/libexec/owner_tool_policy.mjs
    ods_sudo install -o root -g ods-pixel -m 0640 "$stage/pixel-agent.env" /etc/ods/pixel-agent.env
    ods_sudo install -o root -g root -m 0644 "$stage/pixel-ingress.service" /etc/systemd/system/pixel-ingress.service
    ods_sudo install -o root -g root -m 0644 "$rendered_extension_manager_unit" \
        /etc/systemd/system/pixel-extension-manager.service
    ods_sudo cmp -s -- "$rendered_extension_manager_unit" \
        /etc/systemd/system/pixel-extension-manager.service
    ods_sudo install -o root -g root -m 0644 "$rendered_artifact_promoter_unit" \
        /etc/systemd/system/pixel-artifact-promoter.service
    ods_sudo cmp -s -- "$rendered_artifact_promoter_unit" \
        /etc/systemd/system/pixel-artifact-promoter.service
    ods_sudo install -o root -g root -m 0644 "$rendered_workspace_preview_unit" \
        /etc/systemd/system/pixel-workspace-preview.service
    ods_sudo cmp -s -- "$rendered_workspace_preview_unit" \
        /etc/systemd/system/pixel-workspace-preview.service
    if "$wsl_bridge"; then
        ods_sudo install -o root -g root -m 0755 "$wsl_bridge_source" \
            /usr/local/libexec/ods-pixel-wsl-runtime-bridge || return 1
        ods_sudo install -o root -g root -m 0644 "$wsl_bridge_unit" \
            /etc/systemd/system/ods-pixel-wsl-runtime-bridge.service || return 1
        ods_sudo cmp -s -- "$wsl_bridge_source" /usr/local/libexec/ods-pixel-wsl-runtime-bridge || return 1
        ods_sudo cmp -s -- "$wsl_bridge_unit" /etc/systemd/system/ods-pixel-wsl-runtime-bridge.service || return 1
    fi
    rm -f -- "$stage/pixel-agent.env" "$stage/pixel-ingress.service"
    rmdir -- "$stage"
    ods_sudo systemctl daemon-reload || return 1
    ods_sudo systemctl restart pixel-ops-broker.service || return 1
    local operations_address_families operations_capabilities operations_device_policy
    local operations_private_devices
    operations_address_families="$(ods_sudo systemctl show pixel-ops-broker.service \
        --property=RestrictAddressFamilies --value)" || return 1
    operations_capabilities="$(ods_sudo systemctl show pixel-ops-broker.service \
        --property=CapabilityBoundingSet --value)" || return 1
    operations_private_devices="$(ods_sudo systemctl show pixel-ops-broker.service \
        --property=PrivateDevices --value)" || return 1
    operations_device_policy="$(ods_sudo systemctl show pixel-ops-broker.service \
        --property=DevicePolicy --value)" || return 1
    python3 - "$operations_address_families" "$operations_capabilities" \
        "$operations_private_devices" "$operations_device_policy" <<'PY'
import sys

if set(sys.argv[1].split()) != {"AF_UNIX", "AF_INET", "AF_INET6", "AF_NETLINK", "AF_VSOCK"}:
    raise SystemExit("unexpected Pixel Operations address-family boundary")
if sys.argv[2]:
    raise SystemExit("Pixel Operations capability boundary is not empty")
if sys.argv[3] != "no" or sys.argv[4] != "closed":
    raise SystemExit("Pixel Operations device boundary is not closed")
PY
    ods_sudo systemctl enable openclaw-gateway.service pixel-ingress.service \
        pixel-extension-manager.service pixel-artifact-promoter.service \
        pixel-workspace-preview.service || return 1
    ods_sudo systemctl start openclaw-gateway.service || return 1
    ods_sudo systemctl restart pixel-extension-manager.service || return 1
    ods_sudo systemctl restart pixel-artifact-promoter.service || return 1
    ods_sudo systemctl restart pixel-workspace-preview.service || return 1
    # `enable --now` does not refresh an already-running ingress after its
    # reviewed program or environment changes. Restart only the ingress here;
    # the Pixel gateway was already verified above and need not be disturbed.
    ods_sudo systemctl restart pixel-ingress.service || return 1
    if "$wsl_bridge"; then
        ods_sudo systemctl enable ods-pixel-wsl-runtime-bridge.service || return 1
        if ! ods_sudo systemctl start ods-pixel-wsl-runtime-bridge.service \
            || ! ods_sudo systemctl is-active --quiet ods-pixel-wsl-runtime-bridge.service; then
            ai_bad "The WSL runtime bridge for Pixel Edge did not start. Its journal:"
            ods_sudo journalctl -u ods-pixel-wsl-runtime-bridge.service -n 20 --no-pager -o cat \
                || ai_warn "journalctl could not read the bridge journal (non-fatal)"
            return 1
        fi
    fi
    ods_sudo systemctl is-active --quiet openclaw-gateway.service pixel-ingress.service \
        pixel-extension-manager.service pixel-artifact-promoter.service \
        pixel-workspace-preview.service || return 1
    local extension_id
    extension_id="$(jq -er '.matches[0].id | select(type == "string")' \
        <<<"$extension_probe")" || return 1
    [[ "$extension_id" =~ ^[a-z0-9][a-z0-9._-]{0,63}$ && "$extension_id" != *. ]] || return 1
    _ods_pixel_wait_extension_manager_probe "$installed_extension_manager" "$extension_id" || return 1
    _ods_pixel_wait_artifact_promoter_probe "$owner" "$home" "$system_artifact_promoter" || return 1
    _ods_pixel_wait_workspace_preview_probe "$owner" "$home" "$system_workspace_preview" \
        "$preview_port" || return 1
    _ods_pixel_install_preview_inspection "$owner" "$home" "$plugin_root/host"
}

_ods_pixel_install_preview_inspection() {
    local owner="$1" home="$2" source="$3" config
    local installer="${INSTALL_DIR:?}/installers/lib/pixel-preview-inspection.py"
    config="$(ods_pixel_run_as_owner "$owner" "$home" /usr/bin/python3 "$installer" build \
        --source "$source" --owner-uid "$(id -u "$owner")" --transport local)" || return 1
    printf '%s\n' "$config" | ods_sudo /usr/bin/python3 "$installer" install-linux --source "$source" || return 1
    ods_sudo systemctl daemon-reload || return 1
    ods_sudo systemctl enable pixel-preview-inspection.service || return 1
    ods_sudo systemctl restart pixel-preview-inspection.service || return 1
    ods_sudo systemctl is-active --quiet pixel-preview-inspection.service || return 1
    # Type=simple becomes active before Python imports finish and the broker
    # binds its socket. Slow WSL startup can exceed the former five-second wait.
    # The socket directory is root:ods-pixel, so this probe needs that group.
    ODS_PIXEL_OWNER_PRIMARY_GROUP=ods-pixel \
        ods_pixel_run_as_owner "$owner" "$home" /usr/bin/python3 "$installer" wait-owner-socket \
        || return 1
    ods_sudo /usr/bin/python3 -B /usr/local/libexec/ods-pixel-inspection/preview_inspection.py health \
        | jq -e '.schemaVersion == 1 and .kind == "ods-pixel-preview-inspection" and .status == "ready"' >/dev/null
}

_ods_pixel_install_project_runtime() {
    local owner="$1" home="$2" source="$3" config
    local installer="${INSTALL_DIR:?}/installers/lib/pixel-project-runtime.py"
    config="$(ods_pixel_run_as_owner "$owner" "$home" /usr/bin/python3 "$installer" build \
        --source "$source" --owner-uid "$(id -u "$owner")")" || return 1
    printf '%s\n' "$config" | ods_sudo /usr/bin/python3 -B "$installer" check-install --source "$source" || return 1
    if [[ -e /etc/systemd/system/ods-pixel-project.service ]]; then
        ods_sudo systemctl stop ods-pixel-project.service || return 1
    fi
    printf '%s\n' "$config" | ods_sudo /usr/bin/python3 -B "$installer" install-linux --source "$source" || return 1
    ods_sudo systemctl daemon-reload || return 1
    ods_sudo systemctl start ods-pixel-project.service || return 1
    ods_pixel_run_as_owner "$owner" "$home" /usr/bin/python3 - "$config" <<'PY' || return 1
import json, socket, sys, time
expected = json.loads(sys.argv[1])
for attempt in range(30):
    try:
        with socket.socket(socket.AF_UNIX) as client:
            client.settimeout(20)
            client.connect('/var/lib/ods-pixel-project/control.sock')
            client.sendall(b'{"schemaVersion":1,"action":"health"}\n')
            with client.makefile('rb') as stream:
                result = json.loads(stream.readline(8192))
        if (result.get('kind') == 'ods-project-runtime' and result.get('status') == 'ready'
                and result.get('image') == expected['imageId']
                and result.get('runtimes') == {'npm': expected['imageId'], 'python': expected['pythonImageId']}
                and result.get('executionPolicy') == 'runtime-verified-full-access'):
            break
    except (OSError, ValueError):
        pass
    if attempt == 29:
        raise SystemExit('Project executor did not pass installation health')
    time.sleep(.2)
PY
    ods_sudo systemctl enable ods-pixel-project.service || return 1
}

_ods_pixel_wait_ingress() {
    local owner="$1" home="$2" attempts="${3:-60}" delay="${4:-1}" response
    [[ "$attempts" =~ ^[0-9]+$ && "$attempts" -ge 1 && "$attempts" -le 300 ]] || return 1
    [[ "$delay" =~ ^[0-9]+$ && "$delay" -le 5 ]] || return 1
    local attempt
    for ((attempt = 1; attempt <= attempts; attempt++)); do
        if response="$(ods_pixel_run_as_owner "$owner" "$home" curl --fail --silent --show-error --max-time 10 \
            --unix-socket /run/ods-pixel/pixel-ingress.sock http://localhost/health 2>/dev/null)" \
            && jq -e '.status == "ok"' <<<"$response" >/dev/null 2>&1; then
            return 0
        fi
        if (( attempt < attempts && delay > 0 )); then
            sleep "$delay"
        fi
    done
    return 1
}

_ods_pixel_restart_ingress_and_verify() {
    local owner="$1" home="$2" answers="$3"
    local previous_pid current_pid unit_user restart_policy restart_force owner_uid process_uid attempt
    [[ "$answers" == /* && -f "$answers" && ! -L "$answers" ]] || return 1
    if ! systemctl is-active --quiet pixel-ingress.service; then
        # First installation reconciles the model before it installs ingress.
        return 0
    fi
    previous_pid="$(systemctl show pixel-ingress.service -p MainPID --value 2>/dev/null || true)"
    [[ "$previous_pid" =~ ^[1-9][0-9]*$ ]] || return 1
    if ods_sudo_available; then
        ods_sudo systemctl restart pixel-ingress.service || return 1
    else
        unit_user="$(systemctl show pixel-ingress.service -p User --value 2>/dev/null || true)"
        restart_policy="$(systemctl show pixel-ingress.service -p Restart --value 2>/dev/null || true)"
        restart_force="$(systemctl show pixel-ingress.service -p RestartForceExitStatus --value 2>/dev/null || true)"
        owner_uid="$(id -u "$owner" 2>/dev/null || true)"
        process_uid="$(awk '/^Uid:/ { print $2; exit }' "/proc/${previous_pid}/status" 2>/dev/null || true)"
        [[ "$(id -un)" == "$owner" && "$unit_user" == "$owner" \
            && "$restart_policy" == "on-failure" \
            && "$restart_force" =~ (^|[[:space:]])HUP($|[[:space:]]) \
            && "$owner_uid" =~ ^[0-9]+$ \
            && "$process_uid" == "$owner_uid" ]] || return 1
        current_pid="$(systemctl show pixel-ingress.service -p MainPID --value 2>/dev/null || true)"
        [[ "$current_pid" == "$previous_pid" ]] || return 1
        kill -HUP "$previous_pid" || return 1
    fi
    current_pid=""
    for attempt in {1..60}; do
        current_pid="$(systemctl show pixel-ingress.service -p MainPID --value 2>/dev/null || true)"
        if [[ "$current_pid" =~ ^[1-9][0-9]*$ && "$current_pid" != "$previous_pid" ]] \
            && systemctl is-active --quiet pixel-ingress.service; then
            break
        fi
        sleep 1
    done
    [[ "$current_pid" =~ ^[1-9][0-9]*$ && "$current_pid" != "$previous_pid" ]] || return 1
    _ods_pixel_wait_ingress "$owner" "$home" || return 1
    for attempt in {1..30}; do
        if ods_pixel_run_as_owner "$owner" "$home" python3 - "$answers" \
            /run/ods-pixel/ods-status.json <<'PY'
import json, os, pathlib, re, stat, sys

answers_path = pathlib.Path(sys.argv[1])
status_path = pathlib.Path(sys.argv[2])
for path, private in ((answers_path, True), (status_path, False)):
    info = path.lstat()
    if (not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)
            or info.st_uid != os.getuid() or info.st_size > 2 * 1024 * 1024
            or info.st_mode & 0o022 or (private and info.st_mode & 0o077)):
        raise SystemExit(1)
answers = json.loads(answers_path.read_text(encoding="utf-8"))
status = json.loads(status_path.read_text(encoding="utf-8"))
provider = answers.get("modelProvider")
model_id = answers.get("modelId")
model_name = answers.get("modelName")
if provider == "ods-local" and model_name == f"ODS Local {model_id}":
    concrete = model_id
elif provider == "ods-gateway" and model_id in {"default", "ods/current"}:
    label = "Current" if model_id == "ods/current" else "Default"
    match = re.fullmatch(
        rf"ODS {label} \(([A-Za-z0-9][A-Za-z0-9._+:/ @(),=-]{{0,255}})\)",
        model_name if isinstance(model_name, str) else "",
    )
    concrete = match.group(1) if match else None
else:
    concrete = None
context = answers.get("modelContextWindow")
runtime = status.get("runtime") if isinstance(status, dict) else None
if (not isinstance(concrete, str) or not 1 <= len(concrete) <= 256
        or type(context) is not int or not 4096 <= context <= 10_000_000
        or runtime != {"model": concrete, "context_length": context}):
    raise SystemExit(1)
PY
        then
            return 0
        fi
        (( attempt < 30 )) && sleep 1
    done
    return 1
}

_ods_pixel_prepare_wsl_runtime_targets() {
    local base="${1:-/mnt/wsl/ods-portal-runtime}" target
    for target in "$base" "$base/ingress" "$base/preview"; do
        # Existing targets may be bind mounts of the live Pixel directories.
        # install -d would chown/chmod the source through those mounts and
        # prevent the unprivileged services from recreating their sockets.
        if [[ -L "$target" || ( -e "$target" && ! -d "$target" ) ]]; then
            ai_bad "Pixel runtime target is not a regular directory: $target"
            return 1
        fi
        if [[ ! -d "$target" ]]; then
            ods_sudo install -d -o root -g root -m 0755 -- "$target" || return 1
        fi
    done
}

ods_pixel_install_default_agent() {
    [[ "${ENABLE_PIXEL_RUNTIME:-false}" == true ]] || return 0
    local owner home source_root pixel_root plugin_root answers operations_policy extension_catalog extension_manager_unit artifact_promoter_unit workspace_preview_unit openclaw_bin plugin_digest contract_sha256 runtime_budget_status gateway_alias pixel_log
    local candidate_runtime_status reuse_active=false same_verified_source=false same_source_resume=false pixel_gateway_port gateway_port_status
    local web_search_provider parallel_path="" parallel_digest="" apply_attempt="" initial_access_reproved=false stale_sandbox=""
    # The access coordinator's proof ceremony inspects Pixel Edge's durable
    # transition gate. Start the edge before the host ingress is installed;
    # its transition endpoint is independent of upstream chat readiness, and
    # the final access reproof below still runs only after ingress is healthy.
    local -a pixel_prerequisites=(litellm dashboard-api pixel-edge pixel-model-relay)
    # Managed inference needs the router before the relay's real model probe.
    # Cloud/external installs instead bind the relay to authenticated LiteLLM;
    # their Compose overlays intentionally profile model-router out.
    if [[ "${ODS_MODE:-local}" != cloud && -z "${EXTERNAL_LLM_URL:-}" ]]; then
        pixel_prerequisites+=(model-router)
    fi
    owner="${PIXEL_SERVICE_USER:-$(ods_pixel_install_owner)}" || return 1
    home="$(ods_pixel_owner_home "$owner")" || return 1
    pixel_gateway_port="$(_ods_pixel_gateway_port)" || {
        ai_bad "Pixel requires a valid loopback gateway port."
        return 1
    }
    if [[ -n "${ODS_PIXEL_SOURCE_TRANSACTION:-}" ]]; then
        _ods_pixel_check_source_transaction "$owner" || return 1
        # From here generated config, native package repairs and auxiliary
        # services may change. Failure is resume-only under the durable hold;
        # restoring just the checkout would not restore the whole runtime.
        _ods_pixel_source_upgrade downstream "$owner" || return 1
    fi
    _ods_pixel_assert_managed_state "$owner" "$home" || return 1
    gateway_port_status=0
    _ods_pixel_existing_gateway_port_matches "$owner" "$home" "$pixel_gateway_port" \
        || gateway_port_status=$?
    case "$gateway_port_status" in
        0) ;;
        2)
            ai_bad "An installed ODS-managed Pixel uses a different gateway port. Keep its existing PIXEL_GATEWAY_PORT value or uninstall that managed Pixel before choosing a new port."
            return 1
            ;;
        *)
            ai_bad "The installed ODS-managed Pixel gateway-port contract is unsafe or invalid."
            return 1
            ;;
    esac
    pixel_log="$(_ods_pixel_prepare_attempt_log "$owner" "$home" "$INSTALL_DIR/logs/pixel-install.log")" || {
        ai_bad "Could not create Pixel's owner-private persistent install log."
        return 1
    }
    source_root="${INSTALL_DIR:?}/data/pixel/source-${PIXEL_SOURCE_REF:?}"
    pixel_root="$(_ods_pixel_source_checkout "$owner" "$home" "$source_root")" || {
        ai_bad "Pixel source checkout is absent, changed, or not at the configured exact commit."
        return 1
    }
    plugin_root="${INSTALL_DIR:?}/extensions/services/pixel-agent"
    [[ -f "$plugin_root/plugin/openclaw.plugin.json" \
        && -f "$plugin_root/plugin/playground-projects.mjs" \
        && -f "$plugin_root/plugin/workspace-projects.mjs" \
        && -f "$plugin_root/plugin/context-compaction.mjs" \
        && -f "$plugin_root/plugin/model-runtime-readback.mjs" \
        && -f "$plugin_root/plugin/history-context.mjs" \
        && -f "$plugin_root/host/pixel_ingress.mjs" \
        && -f "$plugin_root/host/chat_history_ledger.mjs" \
        && -f "$plugin_root/host/chat_image_store.mjs" \
        && -f "$plugin_root/host/chat_image_transport.mjs" \
        && -f "$plugin_root/host/access_mode_relay.mjs" \
        && -f "$plugin_root/host/task_activity_schema.mjs" \
        && -f "$plugin_root/host/questions_schema.mjs" \
        && -f "$plugin_root/host/owner_tool_policy.mjs" \
        && -f "$plugin_root/host/extension_search.py" \
        && -f "$plugin_root/host/extension_manager.py" \
        && -f "$plugin_root/host/pixel-extension-manager.service" \
        && -f "$plugin_root/host/artifact_promoter.py" \
        && -f "$plugin_root/host/pixel-artifact-promoter.service" \
        && -f "$plugin_root/host/workspace_preview.py" \
        && -f "$plugin_root/host/unix_peer.py" \
        && -f "$plugin_root/host/pixel-workspace-preview.service" \
        && -f "$plugin_root/host/system_observe.py" \
        && -f "$plugin_root/host/preview_inspection.py" \
        && -f "$plugin_root/host/preview_inspection_protocol.py" \
        && -f "$plugin_root/host/preview_inspection_capsule.py" \
        && -f "$plugin_root/host/Dockerfile.inspection" \
        && -f "$plugin_root/host/preview-inspection.requirements.lock" \
        && -f "$plugin_root/host/pixel-preview-inspection.service" \
        && -f "$plugin_root/host/openclaw_tool_recovery.py" \
        && -f "$plugin_root/host/native_search.py" \
        && -f "$plugin_root/host/openclaw-tool-recovery.json" \
        && -f "$plugin_root/host/openclaw-completion-recovery.json" \
        && -f "$plugin_root/host/openclaw-compaction-export.json" \
        && -f "$plugin_root/host/openclaw-compaction-idle.json" \
        && -f "$plugin_root/host/openclaw-compaction-resume.json" \
        && -f "$plugin_root/host/openclaw-read-range.json" \
        && -f "$plugin_root/host/openclaw-sandbox-mkdir-bridge.json" \
        && -f "$plugin_root/host/openclaw-sandbox-mkdir-secure.json" \
        && -f "$plugin_root/host/openclaw-tool-result-projection.json" \
        && -f "$plugin_root/host/openclaw-diagnostic-stream-writes.json" \
        && -f "$plugin_root/host/openclaw-command-attempt-warning.json" \
        && -f "$plugin_root/host/openclaw-utf8-output.json" \
        && -f "$plugin_root/host/openclaw-image-envelope.json" \
        && -f "$plugin_root/host/openclaw-context-usage.json" \
        && -f "$plugin_root/host/openclaw-no-tools-ingress.json" \
        && -f "$plugin_root/host/openclaw-yield-usage.json" \
        && -f "$plugin_root/host/openclaw-compaction-empty.json" \
        && -f "$plugin_root/host/openclaw-compaction-no-work.json" \
        && -f "$plugin_root/host/openclaw-subagent-admission.json" \
        && -f "$plugin_root/host/openclaw-subagent-session.json" \
        && -f "$plugin_root/host/openclaw-hook-provenance.json" \
        && -f "$plugin_root/host/openclaw-run-id-redaction.json" \
        && -f "$plugin_root/host/pixel-ops-broker-ods.conf" \
        && -f "$plugin_root/host/cancellable-exec.sh" \
        && -f "$plugin_root/host/noninteractive-sudo.sh" ]] || return 1
    if ! _ods_pixel_secure_plugin_tree "$owner" "$home" "$plugin_root/plugin"; then
        ai_bad "The ODS Pixel plugin path is not a safe owner-controlled code tree."
        return 1
    fi
    if ! _ods_pixel_install_exec_control "$owner" "$home" \
        "$plugin_root/host/cancellable-exec.sh" "$plugin_root/host/noninteractive-sudo.sh"; then
        ai_bad "Could not install Pixel's owner-private cancellable execution control."
        return 1
    fi
    if ! _ods_pixel_install_response_language "$owner" "$home"; then
        case "${PIXEL_RESPONSE_LANGUAGE:-}" in
            ""|en) ai_bad "Could not apply PIXEL_RESPONSE_LANGUAGE: $home/.openclaw/.ods-response-language must be a regular file owned by $owner, not a link, in a $home/.openclaw folder owned by $owner. Remove that file, then rerun the installer." ;;
            *) ai_bad "PIXEL_RESPONSE_LANGUAGE=${PIXEL_RESPONSE_LANGUAGE} in .env is not supported. Set it to en, or remove the line to match the owner's language, then rerun the installer." ;;
        esac
        # Phase 11 stops with exit 1 here, which the installer's ERR trap does not see.
        ai_bad "Need help? Ask on the ODS Discord: ${ODS_HELP_DISCORD_URL:-https://discord.gg/4ntNp9MAwC}"
        return 1
    fi
    gateway_alias="$(_ods_pixel_gateway_model_alias)" || {
        ai_bad "Pixel received an unsupported ODS model Switchboard mode."
        return 1
    }
    answers="$INSTALL_DIR/data/pixel/onboarding.json"
    web_search_provider="$(ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/native_search.py" --answers-file "$answers" \
        --provider "${PIXEL_WEB_SEARCH_PROVIDER:-}")" || return 1
    case "$web_search_provider" in
        searxng|parallel-free) ;;
        *) ai_bad "Pixel returned an invalid native search provider."; return 1 ;;
    esac
    if [[ -n "${PIXEL_RESOLVED_WEB_SEARCH_PROVIDER:-}" &&
          "$web_search_provider" != "$PIXEL_RESOLVED_WEB_SEARCH_PROVIDER" ]]; then
        ai_bad "Pixel's web search choice changed after Compose services were selected. Retry without altering the onboarding contract."
        return 1
    fi
    if [[ "$web_search_provider" == searxng ]]; then
        pixel_prerequisites+=(searxng)
    fi
    if grep -Fxq 'PIXEL_RUNTIME_BIND_PROPAGATION=rshared' "${INSTALL_DIR:?}/.env"; then
        # Pixel Edge starts here, before the WSL runtime bridge is installed.
        # Create the fixed empty targets on WSL's shared tmpfs so its rshared
        # binds exist now and receive the bridge mounts when they arrive.
        _ods_pixel_prepare_wsl_runtime_targets || return 1
    fi
    ai "Starting the ODS model gateway, control API, and search prerequisites for Pixel review..."
    # The scoped extension manager validates its contract against dashboard-api
    # while Pixel is installed below. The access coordinator also requires the
    # exact Pixel Edge transition gate before the later whole-stack launch.
    # Start both from this exact Compose project before those probes. Otherwise
    # a fresh install has no endpoint, and a migration can accidentally probe a
    # stale related install on the same port. Treat Compose startup failure as
    # authoritative instead of allowing later checks to accept unrelated
    # containers.
    if ! $DOCKER_COMPOSE_CMD "${COMPOSE_FLAGS_ARR[@]}" up -d --no-build --pull never \
        "${pixel_prerequisites[@]}" >>"$LOG_FILE" 2>&1; then
        ai_bad "Could not start Pixel's exact ODS prerequisite services. See $LOG_FILE."
        return 1
    fi
    _ods_pixel_wait_model_gateway "ODS Pixel model relay" "${PIXEL_MODEL_RELAY_PORT:-4006}" \
        "${PIXEL_MODEL_RELAY_KEY:-}" "$gateway_alias" 180
    if [[ "$web_search_provider" == searxng ]]; then
        _ods_pixel_wait_http "ODS local search" \
            "http://127.0.0.1:${SEARXNG_PORT:-8888}/search?q=pixel-preflight&format=json" \
            90 '.results | type == "array"'
    fi
    _ods_pixel_wait_http "ODS control API" \
        "http://127.0.0.1:${DASHBOARD_API_PORT:-3002}/health" 90

    ai "Bootstrapping the exact Pixel source and pinned runtime..."
    if ! declare -f ods_linux_node_tools_available >/dev/null 2>&1 \
        || ! ods_linux_node_tools_available; then
        ai_bad "Pixel requires Linux Node.js 20+ and Linux npm; Windows-mounted WSL tools are not accepted."
        return 1
    fi
    if [[ "$web_search_provider" == parallel-free ]]; then
        parallel_path="$INSTALL_DIR/data/pixel/native-search/parallel-2026.6.33"
        # Pixel bootstrap validates an existing OpenClaw configuration before
        # replacing it. Reinstalls can therefore still reference the pinned
        # ODS-managed Parallel path; provision that path before bootstrap so
        # the fail-closed validator sees the exact extension it was bound to.
        if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
            "$plugin_root/host/native_search.py" \
            --base-dir "$INSTALL_DIR/data/pixel/native-search" >>"$pixel_log" 2>&1; then
            ai_bad "Pixel could not provision its pinned native search plugin. See $pixel_log."
            return 1
        fi
    fi
    # Only a proven first bootstrap (empty or plugin-only) has no access mode
    # to reprove. Retained and partial releases must resume their durable
    # transition below before access-mode reproof, as they did previously.
    if [[ -z "${ODS_PIXEL_SOURCE_TRANSACTION:-}" ]] \
        && _ods_pixel_initial_unconfigured_marker "$owner" "$home" "$pixel_root" >>"$pixel_log" 2>&1; then
        initial_access_reproved=true
    fi
    # This fixed, noninteractive file entrypoint needs no terminal input.
    # Nested sudo/NodeSource/apt must inherit EOF without changing sudoers.
    if ! ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" bootstrap --apply </dev/null >>"$pixel_log" 2>&1; then
        # Phase 11 can stop here without reaching the installer's help trap,
        # so these messages carry the cause, recovery and help link themselves.
        # A failed check of an existing candidate is not a download problem.
        stale_sandbox="$(_ods_pixel_failed_sandbox_proof_candidate "$pixel_log")" || stale_sandbox=""
        if [[ -n "$stale_sandbox" ]]; then
            ai_bad "Pixel stopped before applying its new release: the agent sandbox image $stale_sandbox did not pass the offline check for the pinned Node.js runtime without npm, npx or corepack. The image holds no projects or settings. Remove it with docker image rm $stale_sandbox, then run the ODS install or update again so Pixel rebuilds it. The exact Pixel error is in $pixel_log. Need help? ${ODS_HELP_DISCORD_URL:-https://discord.gg/4ntNp9MAwC}"
        else
            ai_bad "Pixel could not finish preparing its runtime and agent sandbox. It downloads pinned packages, including Debian packages from deb.debian.org and the sandbox's Node.js runtime from nodejs.org. Check this machine's internet access and free disk space, then run the ODS install or update again. The exact Pixel error is in $pixel_log. Need help? ${ODS_HELP_DISCORD_URL:-https://discord.gg/4ntNp9MAwC}"
        fi
        return 1
    fi
    if ! _ods_pixel_sandbox_candidate_has_node "$owner" "$home" "$pixel_root" >>"$pixel_log" 2>&1; then
        ai_bad "The selected Pixel source builds an agent sandbox without the Node.js runtime that Portal's agent is told it has, so ODS stopped before applying it. Use the Pixel source bundled with ODS (leave PIXEL_SOURCE_URL and PIXEL_SOURCE_REF unset), then run the ODS install or update again. Need help? ${ODS_HELP_DISCORD_URL:-https://discord.gg/4ntNp9MAwC}"
        return 1
    fi
    openclaw_bin="$(_ods_pixel_openclaw_bin "$owner" "$home")"
    [[ "$openclaw_bin" == /* && -x "$openclaw_bin" ]] || return 1
    plugin_digest="$(ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" extension-hash "$plugin_root/plugin")"
    [[ "$plugin_digest" =~ ^[0-9a-f]{64}$ ]] || return 1
    if [[ "$web_search_provider" == parallel-free ]]; then
        parallel_digest="$(ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" extension-hash "$parallel_path")" || return 1
        [[ "$parallel_digest" =~ ^[0-9a-f]{64}$ ]] || return 1
    fi

    answers="$INSTALL_DIR/data/pixel/onboarding.json"
    operations_policy="$INSTALL_DIR/data/pixel/operations-policy.json"
    extension_catalog="$INSTALL_DIR/data/pixel/extension-catalog.json"
    extension_manager_unit="$INSTALL_DIR/data/pixel/extension-manager.service"
    artifact_promoter_unit="$INSTALL_DIR/data/pixel/artifact-promoter.service"
    workspace_preview_unit="$INSTALL_DIR/data/pixel/workspace-preview.service"
    if ! _ods_pixel_write_extension_catalog "$owner" "$home" "$extension_catalog"; then
        ai_bad "Could not write Pixel's secret-free ODS extension catalog."
        return 1
    fi
    if ! _ods_pixel_write_operations_policy "$owner" "$home" "$operations_policy"; then
        ai_bad "Could not write the owner-private ODS Pixel Operations policy."
        return 1
    fi
    if ! _ods_pixel_write_extension_manager_unit "$owner" "$home" "$extension_manager_unit"; then
        ai_bad "Could not write the owner-private ODS Pixel extension manager service."
        return 1
    fi
    if ! _ods_pixel_write_artifact_promoter_unit "$owner" "$home" "$artifact_promoter_unit"; then
        ai_bad "Could not write the owner-private ODS Pixel artifact promoter service."
        return 1
    fi
    if ! _ods_pixel_write_workspace_preview_unit "$owner" "$home" "$workspace_preview_unit" \
        "${PIXEL_PREVIEW_PORT:-9437}"; then
        ai_bad "Could not write the owner-private ODS Pixel workspace preview service."
        return 1
    fi
    if ! _ods_pixel_write_onboarding "$owner" "$home" "$answers" "$openclaw_bin" "$plugin_root/plugin" "$plugin_digest" \
        "$web_search_provider" "$parallel_path" "$parallel_digest"; then
        ai_bad "Could not write the ODS-managed Pixel onboarding contract."
        return 1
    fi
    contract_sha256="$(_ods_pixel_contract_sha256 "$owner" "$home" "$answers")" || {
        ai_bad "Could not hash the ODS-managed Pixel onboarding contract."
        return 1
    }
    [[ "$contract_sha256" =~ ^[0-9a-f]{64}$ ]] || return 1
    if ! _ods_pixel_resume_completed_release "$owner" "$home" "$pixel_root" "$contract_sha256" >>"$pixel_log" 2>&1; then
        ai_bad "Pixel has a pending update that could not be reverified safely. See $pixel_log before retrying."
        return 1
    fi
    if [[ "$initial_access_reproved" != true ]]; then
        if ! _ods_pixel_reprove_access_marker_if_needed "$owner" "$home" "$openclaw_bin" >>"$pixel_log" 2>&1; then
            ai_bad "Pixel's existing access mode could not be reverified before upgrade. See $pixel_log."
            return 1
        fi
    fi
    # A completed model transaction rebinds the live configuration digest but
    # can leave the install contract describing the previous model. Reuse is
    # safe only when the live route also agrees with the new onboarding record.
    if _ods_pixel_managed_contract_matches "$owner" "$home" "$contract_sha256" \
        && _ods_pixel_stable_alias_matches_promoted_model "$owner" "$home" "$answers" \
            "$(_ods_pixel_runtime_model_identity)" "" "" "" \
            "$(jq -r '.modelRouteFingerprint // ""' "$answers")" \
            "$(jq -r '.modelImageInput // "unknown"' "$answers")" \
            "$(jq -r '.modelThinkingControl // ""' "$answers")"; then
        reuse_active=true
    fi
    if _ods_pixel_verified_source_matches "$owner" "$home"; then
        same_verified_source=true
    fi
    _ods_pixel_mark_installing "$owner" "$home" "$contract_sha256" || return 1
    if ! _ods_pixel_enable_chat_endpoint "$owner" "$home"; then
        ai_bad "Could not enable Pixel's loopback chat endpoint."
        return 1
    fi
    if [[ "$reuse_active" == true ]]; then
        ai "The exact ODS-managed Pixel contract is already active; verifying it without reapplying the same release..."
        if ! ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" ops-broker --confirm >>"$pixel_log" 2>&1; then
            ai_bad "Pixel could not install and verify the isolated Operations Broker. See $pixel_log."
            return 1
        fi
        if ! _ods_pixel_harden_operations_state_profiles; then
            ai_bad "Pixel's Operations Broker service profiles could not be hardened safely."
            return 1
        fi
        if ! _ods_pixel_verify_operations_policy_custody "$owner" "$home" "$operations_policy"; then
            ai_bad "Pixel's root-custodied Operations policy does not match the ODS-managed policy."
            return 1
        fi
        if [[ "${FORCE:-false}" == true ]]; then
            # Forced reinstall retires an interrupted agent sandbox while
            # the gateway is stopped, then runs the unchanged verifier.
            if ! ods_sudo systemctl stop openclaw-gateway.service >>"$pixel_log" 2>&1; then
                ai_bad "The ODS-managed Pixel gateway could not enter maintenance mode. See $pixel_log."
                return 1
            fi
            if ! _ods_pixel_recreate_agent_sandbox "$owner" "$home" "$openclaw_bin" \
                >>"$pixel_log" 2>&1; then
                # Restore the previously configured service when cleanup
                # fails; the installer still fails closed and does not claim
                # the sandbox boundary was refreshed.
                ods_sudo systemctl start openclaw-gateway.service >>"$pixel_log" 2>&1 || true
                ai_bad "Pixel could not retire its stale agent sandbox during forced recovery. See $pixel_log."
                return 1
            fi
            if ! ods_sudo systemctl start openclaw-gateway.service >>"$pixel_log" 2>&1; then
                ai_bad "The ODS-managed Pixel gateway could not restart after forced sandbox recovery. See $pixel_log."
                return 1
            fi
            if ! _ods_pixel_wait_gateway 60 "$pixel_gateway_port"; then
                ai_bad "The ODS-managed Pixel gateway did not become healthy after forced sandbox recovery. See $pixel_log."
                return 1
            fi
        fi
        if ! _ods_pixel_verify_current_runtime "$owner" "$home" "$pixel_root" >>"$pixel_log" 2>&1; then
            ai_bad "The existing ODS-managed Pixel contract failed exact-source verification. See $pixel_log."
            return 1
        fi
    else
        if ! ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" configure --answers "$answers" --force >>"$pixel_log" 2>&1; then
            ai_bad "Pixel configure failed. See $pixel_log for the exact Pixel error."
            return 1
        fi
        if ! _ods_pixel_reconcile_workspace_guidance "$owner" "$home" "$pixel_root/.generated/workspace" generated >>"$pixel_log" 2>&1; then
            ai_bad "Could not safely prepare Portal workspace guidance. See $pixel_log."
            return 1
        fi
        if ! ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" plan >>"$pixel_log" 2>&1; then
            ai_bad "Pixel plan failed. See $pixel_log for the exact Pixel error."
            return 1
        fi
        if ! ods_pixel_run_as_owner "$owner" "$home" "$pixel_root/pixel" ops-broker --confirm >>"$pixel_log" 2>&1; then
            ai_bad "Pixel could not install and verify the isolated Operations Broker. See $pixel_log."
            return 1
        fi
        if ! _ods_pixel_harden_operations_state_profiles; then
            ai_bad "Pixel's Operations Broker service profiles could not be hardened safely."
            return 1
        fi
        if ! _ods_pixel_verify_operations_policy_custody "$owner" "$home" "$operations_policy"; then
            ai_bad "Pixel's root-custodied Operations policy does not match the ODS-managed policy."
            return 1
        fi
        if [[ "$same_verified_source" == true ]]; then
            if _ods_pixel_candidate_config_matches_live "$owner" "$home" "$pixel_root/dist/openclaw.json"; then
                same_source_resume=true
                ai "The exact Pixel release and runtime configuration are unchanged; refreshing the verified ODS extension without reapplying the release..."
            else
                # A run from an older installer may have atomically written the
                # deterministic ODS overlay before it could bind the updated
                # marker. Recreate that overlay on the reviewed candidate and
                # require whole-document equality before accepting this narrow
                # recovery path. Unrelated live changes still fail closed into
                # the transactional model-reconciliation path below.
                candidate_runtime_status="$(_ods_pixel_apply_runtime_budget "$owner" "$home" \
                    "$pixel_root/dist/openclaw.json" "$openclaw_bin" "$answers")" || {
                    ai_bad "Could not validate the exact-source Pixel runtime candidate for safe recovery."
                    return 1
                }
                case "$candidate_runtime_status" in
                    changed|unchanged) ;;
                    *)
                        ai_bad "Pixel returned an invalid exact-source runtime recovery result."
                        return 1
                        ;;
                esac
                if _ods_pixel_candidate_config_matches_live "$owner" "$home" "$pixel_root/dist/openclaw.json"; then
                    same_source_resume=true
                    ai "The exact Pixel release and deterministic ODS runtime policy are already active; repairing the interrupted ownership checkpoint..."
                fi
            fi
            if [[ "$same_source_resume" == true ]]; then
                # Quiesce the gateway so a concurrent tool turn cannot create
                # a sandbox between retirement and the Docker postcondition.
                if ! ods_sudo systemctl stop openclaw-gateway.service >>"$pixel_log" 2>&1; then
                    ai_bad "The ODS-managed Pixel gateway could not enter maintenance mode. See $pixel_log."
                    return 1
                fi
                if ! _ods_pixel_recreate_agent_sandbox "$owner" "$home" "$openclaw_bin" \
                    >>"$pixel_log" 2>&1; then
                    # Restore the previously configured service when cleanup
                    # fails; the installer still fails closed and does not
                    # claim that the sandbox boundary was refreshed.
                    ods_sudo systemctl start openclaw-gateway.service >>"$pixel_log" 2>&1 || true
                    ai_bad "Pixel could not retire its stale agent sandbox during recovery. See $pixel_log."
                    return 1
                fi
                if ! ods_sudo systemctl start openclaw-gateway.service >>"$pixel_log" 2>&1; then
                    ai_bad "The ODS-managed Pixel gateway could not restart after sandbox recovery. See $pixel_log."
                    return 1
                fi
                if ! _ods_pixel_wait_gateway 60 "$pixel_gateway_port"; then
                    ai_bad "The ODS-managed Pixel gateway did not become healthy after sandbox recovery. See $pixel_log."
                    return 1
                fi
                if ! _ods_pixel_verify_current_runtime "$owner" "$home" "$pixel_root" \
                    >>"$pixel_log" 2>&1; then
                    ai_bad "The recovered ODS-managed Pixel contract failed verification. See $pixel_log."
                    return 1
                fi
            else
                ai "The exact Pixel release is active with an older ODS route; reconciling the reviewed model/runtime policy..."
                if ! ods_pixel_reconcile_promoted_model "$owner" "$home" \
                    "$(_ods_pixel_runtime_model_identity)" installing "" "" "" \
                    "$(jq -r '.modelRouteFingerprint // ""' "$answers")" "${ODS_PIXEL_SOURCE_TRANSACTION:-}" \
                    "$(jq -r '.modelImageInput // "unknown"' "$answers")" \
                    "$(jq -r '.modelThinkingControl // ""' "$answers")" >>"$pixel_log" 2>&1; then
                    ai_bad "The ODS-managed Pixel model route could not be reconciled safely. See $pixel_log."
                    return 1
                fi
            fi
        else
            local release_transaction='' prove_after_apply=true
            local -a release_arguments=()
            release_transaction="$(_ods_pixel_begin_release_transition "$owner" "$home")" || {
                ai_bad "Could not acquire the existing Pixel access state for release update; resolve any pending transaction before retrying."
                return 1
            }
            if [[ -n "$release_transaction" ]]; then
                release_arguments=(--ods-release-transaction "$release_transaction")
                if [[ "$release_transaction" == "${ODS_PIXEL_SOURCE_TRANSACTION:-}" ]] \
                    && _ods_pixel_source_upgrade status "$owner" | jq -e '.mode == "sandboxed"' >/dev/null; then
                    # Pixel's raw candidate lacks the ODS runtime overlay, including
                    # the exec-control bind the access proof runs through, so a proof
                    # here always fails. Apply it under Pixel's strict Sandbox
                    # verifier, as a first install does. The held source transaction
                    # is proved after the overlay (_ods_pixel_restart_gateway_and_verify)
                    # and again before release (_ods_pixel_source_upgrade finish).
                    release_arguments=()
                    prove_after_apply=false
                fi
            fi
            apply_attempt="$(ods_pixel_run_as_owner "$owner" "$home" \
                mktemp "$INSTALL_DIR/logs/.pixel-apply.XXXXXXXX")" || return 1
            ods_pixel_run_as_owner "$owner" "$home" chmod 0600 "$apply_attempt" || return 1
            if {
                ods_pixel_run_as_owner "$owner" "$home" env \
                    PATH="$home/.openclaw/.ods-exec-control:$PATH" \
                    "$pixel_root/pixel" apply --confirm "${release_arguments[@]}" </dev/null &&
                { [[ "$prove_after_apply" == false ]] \
                    || _ods_pixel_verify_current_runtime "$owner" "$home" "$pixel_root" "$release_transaction"; }
            } >"$apply_attempt" 2>&1; then
                ods_pixel_run_as_owner "$owner" "$home" cat "$apply_attempt" >>"$pixel_log" 2>&1 || return 1
            else
                ods_pixel_run_as_owner "$owner" "$home" cat "$apply_attempt" >>"$pixel_log" 2>&1 || return 1
                if _ods_pixel_shared_sandbox_conflict "$owner" "$home" "$apply_attempt"; then
                    ai_bad "Pixel found a shared Docker sandbox image that does not match this installation. Recreating Ubuntu does not clear Docker Desktop images; the Linux UID may have changed."
                    ai "No shared image tag was changed. Check the exact image and every installation using this Docker engine before recovery."
                    ai "After retiring the old installation, run in Ubuntu: bash \"$INSTALL_DIR/scripts/recover-retired-pixel-sandbox.sh\". It preserves the old image and requires your confirmation. Apply evidence: $apply_attempt"
                    return 1
                fi
                if _ods_pixel_retire_inactive_conflicting_release \
                    "$owner" "$home" "$pixel_root" "$apply_attempt" >>"$pixel_log" 2>&1; then
                    ai "Archived an exact, inactive ODS-owned Pixel release that conflicted with the current reviewed plan; retrying once..."
                    ods_pixel_run_as_owner "$owner" "$home" truncate -s 0 "$apply_attempt" || return 1
                    if ! {
                        ods_pixel_run_as_owner "$owner" "$home" env \
                            PATH="$home/.openclaw/.ods-exec-control:$PATH" \
                            "$pixel_root/pixel" apply --confirm "${release_arguments[@]}" </dev/null &&
                        { [[ "$prove_after_apply" == false ]] \
                            || _ods_pixel_verify_current_runtime "$owner" "$home" "$pixel_root" "$release_transaction"; }
                    } >"$apply_attempt" 2>&1; then
                        ods_pixel_run_as_owner "$owner" "$home" cat "$apply_attempt" >>"$pixel_log" 2>&1 || true
                        ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$apply_attempt" || true
                        ai_bad "Pixel apply or verify failed after the single inactive-release recovery retry. See $pixel_log for the exact Pixel error."
                        return 1
                    fi
                    ods_pixel_run_as_owner "$owner" "$home" cat "$apply_attempt" >>"$pixel_log" 2>&1 || return 1
                else
                    ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$apply_attempt" || true
                    ai_bad "Pixel apply or verify failed. See $pixel_log for the exact Pixel error."
                    return 1
                fi
            fi
            if [[ -n "$release_transaction" ]] && ! _ods_pixel_finish_release_transition \
                "$owner" "$home" "$pixel_root" "$release_transaction" >>"$pixel_log" 2>&1; then
                ai_bad "Pixel release verification could not finish its access transaction; admission remains held for recovery. See $pixel_log."
                return 1
            fi
            ods_pixel_run_as_owner "$owner" "$home" rm -f -- "$apply_attempt" || return 1
        fi
    fi
    # Both a fresh apply and the already-active-contract path reach this owner
    # migration. It leaves custom text intact and precedes the gateway restart.
    _ods_pixel_migrate_live_workspace_guidance "$owner" "$home" "$pixel_log"
    # Record the verified Pixel release before applying the ODS-owned runtime
    # overlay. If power is lost between the atomic config update and gateway
    # verification, the next installer run can safely enter the exact-source
    # reconciliation path instead of attempting to reapply an active release.
    if ! _ods_pixel_mark_verified_installing "$owner" "$home" "$contract_sha256" "$pixel_root"; then
        ai_bad "Could not bind the verified Pixel release before managed-runtime configuration."
        return 1
    fi
    runtime_budget_status="$(_ods_pixel_apply_runtime_budget "$owner" "$home" \
        "$home/.openclaw/openclaw.json" "$openclaw_bin" "$answers")" || {
        ai_bad "Could not validate and apply Pixel's ODS managed-runtime policy."
        return 1
    }
    case "$runtime_budget_status" in
        changed) ai "Applying Pixel's bounded ODS managed-runtime policy..." ;;
        unchanged) ;;
        *)
            ai_bad "Pixel returned an invalid ODS managed-runtime policy result."
            return 1
            ;;
    esac
    # The runtime overlay above replaces the live configuration atomically.
    # Bind that exact canonical file before any fallible runtime repair,
    # registry or service operation. If a later step is interrupted, the next
    # installer or uninstaller run can prove the managed contract without
    # misclassifying ODS's own runtime policy as unmanaged drift.
    if ! _ods_pixel_mark_verified_installing "$owner" "$home" "$contract_sha256" "$pixel_root"; then
        ai_bad "Could not bind the verified Pixel ODS managed-runtime configuration."
        return 1
    fi
    # Another ODS build can leave OpenClaw runtime patch sets that this
    # version does not manage. Restore only sets whose private receipt records
    # the live bytes and a verified original, then archive their state, so
    # this ODS version never runs on another build's runtime patches.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" \
        --restore-foreign "$home/.openclaw/ods-runtime-patches" \
        --known tool-recovery completion-recovery image-envelope compaction-export \
            compaction-idle compaction-resume read-range tool-result-projection \
            diagnostic-stream-writes command-attempt-warning utf8-output compaction-budget context-usage no-tools-ingress yield-usage compaction-empty compaction-no-work subagent-admission subagent-session hook-provenance run-id-redaction sandbox-mkdir-bridge sandbox-mkdir-secure \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel could not restore OpenClaw runtime patches left by another ODS build. See $pixel_log."
        return 1
    fi
    # OpenClaw 2026.6.33 mistakes "Unknown tool id: name" for a missing tool
    # named "id", then vetoes every later tool_call. Repair only the reviewed
    # package bytes; preserve its other detectors and retain rollback custody.
    # This ODS-owned runtime overlay follows Pixel release verification and is
    # loaded by the gateway restart below, including same-release reinstalls.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" \
        --state-dir "$home/.openclaw/ods-runtime-patches/tool-recovery" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's runtime recovery repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Embedded model runs already own context compaction. Do not run the CLI
    # post-turn compactor on their persisted final reply: a redundant timeout
    # there discarded a completed task and its verified preview.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --completion-recovery \
        --state-dir "$home/.openclaw/ods-runtime-patches/completion-recovery" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's completion recovery repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Keep screenshot bytes in native image blocks. JSON-encoding them as text
    # exhausts small model contexts before the provider can handle the image.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --image-envelope \
        --state-dir "$home/.openclaw/ods-runtime-patches/image-envelope" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's image result repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # The pinned runtime's compaction facade omits its chunk's default export.
    # Preserve successful compaction counts using the reviewed implementation;
    # do not hide reconciliation failures or alter conversation roles.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --compaction-export \
        --state-dir "$home/.openclaw/ods-runtime-patches/compaction-export" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's compaction export repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Manual compaction must reject an active run instead of interrupting it.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --compaction-idle \
        --state-dir "$home/.openclaw/ods-runtime-patches/compaction-idle" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's compaction admission repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Resume a truncated tool turn after compaction without replaying its prompt.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --compaction-resume \
        --state-dir "$home/.openclaw/ods-runtime-patches/compaction-resume" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's compaction continuation repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Parallel writes may create the same parent directory. Reopen it with the
    # pinned no-follow directory flags after EEXIST; never accept a symlink.
    local mkdir_module
    for mkdir_module in bridge secure; do
        if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
            "$plugin_root/host/openclaw_tool_recovery.py" \
            --openclaw-bin "$openclaw_bin" --sandbox-mkdir "$mkdir_module" \
            --state-dir "$home/.openclaw/ods-runtime-patches/sandbox-mkdir-$mkdir_module" \
            >>"$pixel_log" 2>&1; then
            ai_bad "Pixel's concurrent workspace directory repair could not verify its package bytes. See $pixel_log."
            return 1
        fi
    done
    # Preserve the real line count when a read starts beyond EOF. A silent
    # empty success makes the model keep requesting higher invalid offsets.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --read-range \
        --state-dir "$home/.openclaw/ods-runtime-patches/read-range" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's file read range repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Deliver every new tool result to the model. The pinned live prompt
    # projection otherwise sends new results empty once the tool output in the
    # model context exceeds its aggregate budget; reduce older results instead.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --tool-result-projection \
        --state-dir "$home/.openclaw/ods-runtime-patches/tool-result-projection" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's tool result delivery repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # The model-call diagnostic observer's stream proxy ignores iterator and
    # result replacements made by wrappers applied outside it. It is outermost
    # here, so this changes nothing today; the native macOS bundle runs it
    # inside the tool-call argument repair and composes the same recipe.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --diagnostic-stream-writes \
        --state-dir "$home/.openclaw/ods-runtime-patches/diagnostic-stream-writes" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's model stream wrapper repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Preserve failed command evidence while distinguishing the attempt from
    # the final answer; do not infer recovery from a different successful command.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --command-attempt-warning \
        --state-dir "$home/.openclaw/ods-runtime-patches/command-attempt-warning" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's command attempt warning repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Preserve UTF-8 characters split across subprocess stdout/stderr events.
    # The runtime keeps each stream's pending bytes until its final flush.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --utf8-output \
        --state-dir "$home/.openclaw/ods-runtime-patches/utf8-output" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's UTF-8 output repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Honor the configured compaction budget on slow local providers.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --compaction-budget \
        --state-dir "$home/.openclaw/ods-runtime-patches/compaction-budget" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's compaction budget repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Keep opaque UUIDs intact without disabling credential redaction.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --run-id-redaction \
        --state-dir "$home/.openclaw/ods-runtime-patches/run-id-redaction" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's run identity redaction repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Child announcements must enter admission even while an owner turn is active.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --subagent-admission \
        --state-dir "$home/.openclaw/ods-runtime-patches/subagent-admission" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's subagent admission repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Native child completion keeps its owner session across automatic expiration.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --subagent-session \
        --state-dir "$home/.openclaw/ods-runtime-patches/subagent-session" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's subagent session repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Preserve trusted inter-session provenance in native prompt-hook contexts.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --hook-provenance \
        --state-dir "$home/.openclaw/ods-runtime-patches/hook-provenance" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's hook provenance repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # Keep billing totals out of context accounting and skip empty checkpoints.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --context-usage \
        --state-dir "$home/.openclaw/ods-runtime-patches/context-usage" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's context-usage repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # An explicit no-tools turn must reach the provider with no callable tools
    # while the next normal turn in the same session regains them.
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --no-tools-ingress \
        --state-dir "$home/.openclaw/ods-runtime-patches/no-tools-ingress" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's no-tools ingress repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --yield-usage \
        --state-dir "$home/.openclaw/ods-runtime-patches/yield-usage" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's yield-usage repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --compaction-empty \
        --state-dir "$home/.openclaw/ods-runtime-patches/compaction-empty" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's compaction-empty repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    if ! ods_pixel_run_as_owner "$owner" "$home" python3 \
        "$plugin_root/host/openclaw_tool_recovery.py" \
        --openclaw-bin "$openclaw_bin" --compaction-no-work \
        --state-dir "$home/.openclaw/ods-runtime-patches/compaction-no-work" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel's compaction-no-work repair could not verify its package bytes. See $pixel_log."
        return 1
    fi
    # OpenClaw persists plugin descriptors separately from its live config.
    # Rebuild that registry after any reviewed extension/config update, then
    # restart once so the gateway loads both the exact descriptor contract and
    # the final ODS runtime policy. A plain service restart can otherwise keep
    # stale tool descriptors across same-release extension refreshes.
    if ! _ods_pixel_refresh_plugin_registry "$owner" "$home" "$openclaw_bin" "$plugin_root/plugin" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel could not refresh the exact ODS plugin registry. See $pixel_log."
        return 1
    fi
    if ! _ods_pixel_recreate_agent_sandbox "$owner" "$home" "$openclaw_bin" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel could not recreate its agent sandbox for the reviewed ODS runtime. See $pixel_log."
        return 1
    fi
    if ! _ods_pixel_restart_gateway_and_verify "$owner" "$home" "$pixel_root" \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel could not restart and verify its gateway after the ODS runtime update. See $pixel_log."
        return 1
    fi
    # Reconfirm the exact verified contract and canonical live config after the
    # gateway has loaded them while the marker remains non-ready. If ingress
    # setup is interrupted, a rerun can verify and reuse this same release.
    if ! _ods_pixel_mark_verified_installing "$owner" "$home" "$contract_sha256" "$pixel_root"; then
        ai_bad "Could not bind the verified Pixel contract for retry-safe ingress setup."
        return 1
    fi
    if ! _ods_pixel_install_ingress "$owner" "$home" "$plugin_root" \
        "$extension_catalog" "$extension_manager_unit" "$artifact_promoter_unit" \
        "$workspace_preview_unit"; then
        ai_bad "Could not install and start the private Pixel ingress."
        return 1
    fi
    # Enable the deferred inspector only after its exact image, broker and
    # owner transport have passed installation health. Existing model-budget
    # reconciliation never grants this capability to an older installation.
    _ods_pixel_install_project_runtime "$owner" "$home" "$plugin_root/host" || return 1
    runtime_budget_status="$(_ods_pixel_apply_runtime_budget "$owner" "$home" \
        "$home/.openclaw/openclaw.json" "$openclaw_bin" "$answers" unix /var/lib/ods-pixel-project/control.sock)" || return 1
    case "$runtime_budget_status" in
        changed) _ods_pixel_restart_gateway_and_verify "$owner" "$home" "$pixel_root" || return 1 ;;
        unchanged) ;;
        *) return 1 ;;
    esac
    # sudo -u starts a fresh owner session with the newly assigned ods-pixel
    # supplementary group; the original installer shell may not see that group
    # until the next login.
    if ! _ods_pixel_wait_ingress "$owner" "$home"; then
        ai_bad "Pixel ingress did not pass its authenticated loopback health check."
        return 1
    fi
    if ! _ods_pixel_verify_plugin_loaded "$owner" "$home" "$openclaw_bin" "$plugin_root/plugin"; then
        ai_bad "The reviewed ODS Pixel plugin and exact tool contract are not loaded by the active gateway."
        return 1
    fi
    if ! _ods_pixel_mark_ready "$owner" "$home" "$contract_sha256" "$pixel_root"; then
        ai_bad "Could not record the verified Pixel runtime as ready."
        return 1
    fi
    if ! _ods_pixel_install_access_service "$owner" "$openclaw_bin"; then
        ai_bad "Pixel access coordinator installation failed; access mode changes remain unavailable."
        return 1
    fi
    if [[ -n "${ODS_PIXEL_SOURCE_TRANSACTION:-}" ]]; then
        _ods_pixel_source_upgrade finish "$owner" || {
            ai_bad "Pixel source update requires recovery; admission remains protected until its exact runtime is proved."
            return 1
        }
        unset ODS_PIXEL_SOURCE_TRANSACTION
    fi
    if ! _ods_pixel_reverify_access_after_gateway_restart "$owner" "$home" true \
        >>"$pixel_log" 2>&1; then
        ai_bad "Pixel access coordinator could not verify the live gateway after installation. See $pixel_log."
        return 1
    fi
    ai_ok "Pixel is installed, verified, and ready on the private ODS ingress"
}