"""Lifecycle wiring for cameras, telemetry, OTA, and compute offload."""

from __future__ import annotations

import base64
import copy
import hashlib
import ipaddress
import json
import logging
import math
import os
import re
import secrets
import socket
import stat
import threading
import time
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple

from .datahub import DataHubPublisher
from .offload import RemoteJobError, ShortcutJobClient
from .ota import (
    OTA_ADMISSION_REVALIDATION_PHASES,
    OTAAdmissionChanged,
    OTAError,
    OTAResult,
    PrivilegedOTAClient,
    SecureOTAUpdater,
)
from .readiness import DeviceReadinessClient
from .settings import IntegrationSettings, parse_camera_source

try:
    from main.ota_commissioning import (
        OTACommissioningGate,
        evaluate_auto_apply_commissioning,
    )
    from main.motion_permit import (
        MotionBindings,
        MotionIntent,
        MotionPermitGrant,
    )
except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
    from ota_commissioning import (  # type: ignore[no-redef]
        OTACommissioningGate,
        evaluate_auto_apply_commissioning,
    )
    from motion_permit import (  # type: ignore[no-redef]
        MotionBindings,
        MotionIntent,
        MotionPermitGrant,
    )

LOGGER = logging.getLogger("labcobot.workcell")

_CAPTURE_CONFIRMATION_SECONDS = 5.0
_MOTION_SEARCH_CONFIRMATION_SECONDS = 5.0
_SAFETY_CONFIGURATION_CONFIRMATION_SECONDS = 5.0
_PETRI_CONFIRMATION_SECONDS = 5.0
_RECOVERY_CONFIRMATION_SECONDS = 5.0
_MANUAL_REVIEW_CONFIRMATION_SECONDS = 30.0
_WORKSPACE_TEACH_CONFIRMATION_SECONDS = 5.0
_MANUAL_REVIEW_PREVIEW_MAX_BYTES = 512 * 1024
_OTA_HEALTH_REPORT_RETRY_DELAYS_SECONDS = (0.0, 1.0, 5.0, 30.0, 120.0)
_CAPTURE_STATES = frozenset(
    (
        "idle",
        "starting",
        "running",
        "stopping",
        "completed",
        "cancelled",
        "failed",
        "interrupted",
        "fault_locked",
    )
)
_CAPTURE_ACTIVE_STATES = frozenset(("starting", "running", "stopping"))
_CAPTURE_TIMEPOINTS = 15
_CAPTURE_IMAGES = 30
_XARM_STATUS_SCHEMA_VERSION = 1
_XARM_METRICS_SCHEMA_VERSION = 1
_RUNTIME_STATUS_SCHEMA_VERSION = 2
_OPERATOR_DIAGNOSTICS_SCHEMA_VERSION = 1
_XARM_STATUS_MAX_AGE_SECONDS = 3.0
_DEPLOYMENT_MODES = frozenset(
    ("development", "production", "gateway", "operator", "workcell")
)
_LITE6_JOINT_LOWER_RADIANS = tuple(
    math.radians(value) for value in (-360, -150, -3.5, -360, -124, -360)
)
_LITE6_JOINT_UPPER_RADIANS = tuple(
    math.radians(value) for value in (360, 150, 300, 360, 124, 360)
)
_MAX_REDUCED_TCP_SPEED_MM_PER_SECOND = 250.0
_MAX_REDUCED_JOINT_SPEED_RADIANS_PER_SECOND = math.radians(60.0)
_REDUCED_CONFIGURATION_RECHECK_SECONDS = 0.05
_XARM_FAULT_NONE = ("none", "")
_XARM_CONTROLLER_FAULT = (
    "controller_error",
    "A controller error is active; onsite inspection through the approved "
    "controller workflow is required.",
)
_XARM_EXTERNAL_EMERGENCY_IO_FAULT = (
    "external_emergency_io",
    "External Control Box Emergency-I/O is triggered; onsite safety-circuit "
    "inspection is required.",
)
_MOTION_RELEASE_BLOCKER = "motion_release_incomplete"
_MOTION_PERMIT_BLOCKER = "motion_permit_not_ready"
_MOTION_AUTHORIZATION_WATCHDOG_SECONDS = 0.05
_LITE6_DEVICE_TYPE = 9
_MAX_REVIEWED_TRAJECTORY_WAYPOINTS = 4096


class XArmControllerFault(RuntimeError):
    """A normalized fault at the canonical Lite6 controller boundary."""

    def __init__(self, code: str, operation: str) -> None:
        self.code = str(code)
        self.operation = str(operation)
        super().__init__("xArm {} failed ({})".format(operation, code))


class _XArmStopRequested(RuntimeError):
    """Internal control-flow marker used to keep STOP out of the fault latch."""


@dataclass(frozen=True)
class ReviewedJointTrajectory:
    """A digest-bound, finite joint trajectory accepted by the sole owner.

    Construction is deliberately local and typed; possession of an instance
    is not motion authority.  The canonical SHA-256 must still match the
    independently signed motion permit consumed at the motor-enable boundary.
    """

    operation_scope: str
    action: str
    waypoints_radians: Tuple[Tuple[float, ...], ...]
    profile_sha256: str

    @classmethod
    def from_waypoints(
        cls,
        *,
        operation_scope: str,
        action: str,
        waypoints_radians: Sequence[Sequence[float]],
        expected_sha256: str,
    ) -> "ReviewedJointTrajectory":
        if operation_scope not in {"reviewed_home", "reviewed_trajectory"}:
            raise RuntimeError("Reviewed trajectory operation scope is invalid")
        if action not in {"home", "execute"}:
            raise RuntimeError("Reviewed trajectory action is invalid")
        if (operation_scope, action) not in {
            ("reviewed_home", "home"),
            ("reviewed_trajectory", "execute"),
        }:
            raise RuntimeError("Reviewed trajectory scope/action does not match")
        if (
            not isinstance(expected_sha256, str)
            or re.fullmatch(r"[0-9a-f]{64}", expected_sha256) is None
        ):
            raise RuntimeError("Reviewed trajectory SHA-256 is invalid")
        if not isinstance(waypoints_radians, (tuple, list)) or not (
            1 <= len(waypoints_radians) <= _MAX_REVIEWED_TRAJECTORY_WAYPOINTS
        ):
            raise RuntimeError("Reviewed trajectory waypoint count is invalid")
        normalized = []
        for waypoint in waypoints_radians:
            values = XArmMotionAdapter._finite_vector(
                waypoint,
                6,
                "reviewed trajectory waypoint",
            )
            if any(
                not _LITE6_JOINT_LOWER_RADIANS[index]
                <= value
                <= _LITE6_JOINT_UPPER_RADIANS[index]
                for index, value in enumerate(values)
            ):
                raise RuntimeError(
                    "Reviewed trajectory exceeds the Lite6 joint envelope"
                )
            normalized.append(values)
        canonical = json.dumps(
            {
                "action": action,
                "operation_scope": operation_scope,
                "schema": "labcobot.reviewed-joint-trajectory.v1",
                "waypoints_radians": normalized,
            },
            allow_nan=False,
            ensure_ascii=True,
            separators=(",", ":"),
            sort_keys=True,
        ).encode("ascii")
        actual_sha256 = hashlib.sha256(canonical).hexdigest()
        if not secrets.compare_digest(actual_sha256, expected_sha256):
            raise RuntimeError("Reviewed trajectory SHA-256 does not match")
        return cls(
            operation_scope=operation_scope,
            action=action,
            waypoints_radians=tuple(normalized),
            profile_sha256=actual_sha256,
        )


@dataclass(frozen=True)
class _ReviewedJointCommand:
    joints: Tuple[float, ...]
    gripper: None = None


@dataclass(frozen=True)
class _OTAAdmissionLease:
    """Immutable, veto-only evidence captured for one automatic update."""

    generation: int
    captured_at_monotonic_s: float
    maximum_age_seconds: float
    stop_generation: int
    authorization_generation: int
    telemetry_sequence: int
    controller_state: int
    controller_mode: int
    camera_identities: Tuple[Tuple[str, str, str, str], ...]
    camera_sequences: Tuple[Tuple[str, int], ...]
    owner_snapshot: Tuple[Tuple[str, Any], ...]
    workspace_teach_generation: int
    workspace_teach_owner_active: bool
    workspace_teach_invalidation_pending: bool
    safety_configuration_generation: int
    safety_configuration_state: str
    runtime_fatal_generation: int
    evidence_sha256: str


def _empty_safety_preflight() -> Mapping[str, bool]:
    """Return the complete fail-closed safety-preflight wire schema."""

    return {
        "ready": False,
        "connected": False,
        "healthy": False,
        "stopped": False,
        "motors_disabled": False,
        "stationary": False,
        "identity_verified": False,
        "mode_locked": False,
        "brakes_engaged": False,
        "pose_inside_profile": False,
        "controller_binding_verified": False,
    }


def _empty_safety_readback() -> Mapping[str, Any]:
    """Return the complete fail-closed pinned-profile readback wire schema."""

    return {
        "verified": False,
        "tcp_boundary_mm": None,
        "max_tcp_speed_mm_per_second": None,
        "max_joint_speed_radians_per_second": None,
        "joint_ranges_radians": None,
        "safety_boundary_enabled": False,
        "collision_rebound_enabled": False,
        "reduced_mode_enabled": False,
    }


_OTA_ERROR_CODES = frozenset(
    ("", "admission_changed", "metadata_service_unavailable", "update_check_failed")
)
_OTA_MANIFEST_VERIFICATION_STATES = frozenset(
    ("not_checked", "not_available", "checking", "verified", "failed")
)
_OTA_ARCHIVE_VERIFICATION_STATES = frozenset(
    ("not_checked", "not_required", "checking", "verified", "failed")
)
_CAMERA_STATES = frozenset(("stopped", "starting", "running", "degraded"))
_CAMERA_BACKENDS = frozenset(("depthai", "opencv"))
_CAPTURE_MANIFEST_STATES = frozenset(
    (
        "none",
        "starting",
        "running",
        "stopping",
        "completed",
        "cancelled",
        "failed",
        "interrupted",
        "fault_locked",
        "invalid",
    )
)
_PETRI_OBSERVATION_STATES = frozenset(
    ("accepted_auto", "requires_review", "accepted_manual")
)
_VALVE_CYCLE_STATES = frozenset(
    (
        "authorization_invalid",
        "busy",
        "cartesian_plan_only",
        "clearance_blocked",
        "duplicate_frame",
        "duplicate_observation",
        "confirmation_required",
        "dry_run_controller",
        "dry_run_executor",
        "dry_run_not_live",
        "dry_run_unarmed",
        "executed",
        "execution_error",
        "frame_error",
        "inference_error",
        "motion_fault_latched",
        "no_frame",
        "no_safe_target",
        "planning_error",
        "stopped",
        "target_already_executed",
        "target_gate_error",
        "tool_calibration_not_ready",
        "unknown",
    )
)
_SAFE_PUBLIC_IDENTIFIER = re.compile(r"[A-Za-z0-9_.:+-]{1,255}\Z")
_SAFE_REGISTRY_IDENTIFIER = re.compile(r"[A-Z0-9][A-Z0-9._-]{2,63}\Z")
_SAFE_XARM_FIRMWARE_VERSION = re.compile(
    r"[vV]?[0-9]{1,4}(?:\.[0-9A-Za-z]{1,16}){1,5}" r"(?:[-+][0-9A-Za-z.]{1,24})?\Z"
)
_WORKER_KINDS = {
    "device-registry": "persistent",
    "xarm-pose-history": "persistent",
    "dynamic-valve-imitation": "persistent",
    "datahub-uploader": "persistent",
    "capture-dataset-exporter": "persistent",
    "robot-telemetry": "persistent",
    "motion-authorization-watchdog": "persistent",
    "ota-poller": "persistent",
    "ota-health-reporter": "persistent",
    "ota-health-commit": "finite",
    "ota-manual-check": "on_demand",
    "capture-run-watch": "on_demand",
}


def _bounded_public_identifier(value: Any, *, limit: int = 255) -> str:
    """Return a bounded display identifier, never an arbitrary remote string."""

    if not isinstance(value, str) or not value or len(value) > limit:
        return ""
    return value if _SAFE_PUBLIC_IDENTIFIER.fullmatch(value) else ""


def _bounded_status_text(value: Any, *, limit: int = 160) -> str:
    """Return one printable single-line status without paths or exceptions."""

    if not isinstance(value, str):
        return ""
    result = " ".join(value.replace("\x00", "").split())
    lowered = result.lower()
    if (
        "/" in result
        or "\\" in result
        or "://" in lowered
        or any(
            marker in lowered
            for marker in (
                "secret",
                "password",
                "authorization",
                "bearer ",
                "api_key",
                "signing_key",
            )
        )
    ):
        return ""
    if not result or len(result) > limit:
        return result[:limit]
    return result


def _bounded_error_code(value: Any) -> str:
    if not isinstance(value, str):
        return ""
    result = re.sub(r"[^a-z0-9_]+", "_", value.lower()).strip("_")[:48]
    return result


def _validated_optional_challenge(value: Any) -> Optional[str]:
    """Normalize a first-step empty value or exact one-use token."""

    if value is None or value == "":
        return ""
    if isinstance(value, str) and re.fullmatch(r"[0-9a-f]{32}", value):
        return value
    return None


def _bounded_nonnegative_integer(value: Any, *, maximum: int) -> Optional[int]:
    if isinstance(value, bool):
        return None
    try:
        result = int(value)
    except (TypeError, ValueError, OverflowError):
        return None
    if not 0 <= result <= maximum:
        return None
    return result


def _bounded_finite_number(
    value: Any,
    *,
    minimum: float = 0.0,
    maximum: float = 100_000_000_000.0,
) -> Optional[float]:
    if isinstance(value, bool):
        return None
    try:
        result = float(value)
    except (TypeError, ValueError, OverflowError):
        return None
    if not math.isfinite(result) or not minimum <= result <= maximum:
        return None
    return result


def _bounded_metric_vector(
    value: Any,
    *,
    length: int,
    minimum: float,
    maximum: float,
    allow_lite6_dummy: bool = False,
) -> Optional[List[float]]:
    """Normalize one finite fixed-size telemetry vector.

    Some xArm SDK reads return a seventh dummy axis for six-axis arms.  It is
    accepted only when it is an exact numeric zero; arbitrary extra values
    are never truncated into the public health contract.
    """

    if not isinstance(value, (tuple, list)):
        return None
    values = list(value)
    if allow_lite6_dummy and len(values) == length + 1:
        dummy = values[-1]
        if (
            isinstance(dummy, bool)
            or not isinstance(dummy, (int, float))
            or not math.isfinite(float(dummy))
            or float(dummy) != 0.0
        ):
            return None
        values = values[:-1]
    if len(values) != length:
        return None
    result: List[float] = []
    for item in values:
        number = _bounded_finite_number(
            item,
            minimum=minimum,
            maximum=maximum,
        )
        if number is None:
            return None
        result.append(number)
    return result


def _bounded_binary_metric_vector(
    value: Any,
    *,
    length: int = 6,
) -> Optional[List[int]]:
    """Normalize one exact per-axis binary controller-state vector."""

    if not isinstance(value, (tuple, list)):
        return None
    values = list(value)
    if len(values) in (length + 1, length + 2):
        # SDK 1.18.4 exposes J1..J7 plus one reserved bit for motor state.
        # Lite6 may discard only exact integer-zero unused fields.
        if any(type(item) is not int or item != 0 for item in values[length:]):
            return None
        values = values[:length]
    if len(values) != length:
        return None
    result: List[int] = []
    for item in values:
        if isinstance(item, bool):
            item = int(item)
        if type(item) is not int or item not in (0, 1):
            return None
        result.append(item)
    return result


def _bounded_metric_integer(value: Any, *, maximum: int) -> Optional[int]:
    """Accept only a real bounded SDK integer, never a coercible string."""

    if type(value) is not int or not 0 <= value <= maximum:
        return None
    return value


def _bounded_xarm_firmware_version(value: Any) -> str:
    """Expose only a version-shaped controller identifier."""

    if not isinstance(value, str) or len(value) > 255:
        return ""
    # XArmAPI.version normally returns a composite string such as
    # ``6,9,LI1006,DL1000,v1.12.2``.  Keep only its final version-shaped
    # component; serial numbers and controller identifiers never leave this
    # normalization boundary.
    candidate = value.rsplit(",", 1)[-1].strip()
    if len(candidate) > 64:
        return ""
    if not _SAFE_XARM_FIRMWARE_VERSION.fullmatch(candidate):
        return ""
    return candidate[1:] if candidate[:1] in ("v", "V") else candidate


def _empty_xarm_metrics() -> Mapping[str, Any]:
    """Return the stable, secret-free robot metrics dashboard contract."""

    return {
        "schema_version": _XARM_METRICS_SCHEMA_VERSION,
        "sample_age_seconds": 86400.0,
        "fresh": False,
        "command_queue_depth": None,
        "joint_angles_deg": None,
        "joint_angles_rad": None,
        "joint_velocity_rad_s": None,
        "joint_effort": None,
        "joint_effort_unit": "sdk_native",
        "tcp_position_mm": None,
        "tcp_orientation_deg": None,
        "tcp_orientation_rad": None,
        "controller": {
            "axis_count": None,
            "device_type": None,
            "firmware_version": "",
            "temperatures_c": None,
            "joint_voltages_v": None,
            "joint_currents_a": None,
            "joint_torque_or_current_sdk": None,
            "motor_brake_states": None,
            "motor_enable_states": None,
            "tcp_load_kg": None,
            "tcp_center_of_gravity_mm": None,
            "collision_sensitivity": None,
            "teach_sensitivity": None,
        },
        "safety": {
            "tcp_boundary_min_mm": None,
            "tcp_boundary_max_mm": None,
            "max_tcp_speed_mm_s": None,
            "max_joint_speed_rad_s": None,
            "joint_lower_rad": None,
            "joint_upper_rad": None,
            "safety_boundary_enabled": None,
            "collision_rebound_enabled": None,
        },
    }


def _bounded_xarm_metrics(metrics: Mapping[str, Any]) -> Mapping[str, Any]:
    """Build a bounded read-only dashboard snapshot from raw SDK telemetry."""

    result = dict(_empty_xarm_metrics())
    joint_states = metrics.get("joint_states")
    joint_states = joint_states if isinstance(joint_states, Mapping) else {}
    tcp_pose = metrics.get("tcp_pose")
    tcp_pose = tcp_pose if isinstance(tcp_pose, Mapping) else {}
    tcp_pose_mm_deg = _bounded_metric_vector(
        metrics.get("tcp_pose_mm_deg"),
        length=6,
        minimum=-1_000_000.0,
        maximum=1_000_000.0,
    )
    controller = metrics.get("controller")
    controller = controller if isinstance(controller, Mapping) else {}

    result["command_queue_depth"] = _bounded_metric_integer(
        metrics.get("command_queue_depth"),
        maximum=1_000_000,
    )
    result["joint_angles_deg"] = _bounded_metric_vector(
        metrics.get("joint_angles_deg"),
        length=6,
        minimum=-36_000.0,
        maximum=36_000.0,
        allow_lite6_dummy=True,
    )
    result["joint_angles_rad"] = _bounded_metric_vector(
        metrics.get("joint_angles_rad"),
        length=6,
        minimum=-1_000.0,
        maximum=1_000.0,
        allow_lite6_dummy=True,
    )
    result["joint_velocity_rad_s"] = _bounded_metric_vector(
        joint_states.get("velocity_rad_s"),
        length=6,
        minimum=-1_000.0,
        maximum=1_000.0,
        allow_lite6_dummy=True,
    )
    result["joint_effort"] = _bounded_metric_vector(
        joint_states.get("effort"),
        length=6,
        minimum=-1_000_000.0,
        maximum=1_000_000.0,
        allow_lite6_dummy=True,
    )
    tcp_position_mm = _bounded_metric_vector(
        tcp_pose.get("position_mm"),
        length=3,
        minimum=-1_000_000.0,
        maximum=1_000_000.0,
    )
    result["tcp_position_mm"] = (
        tcp_position_mm
        if tcp_position_mm is not None
        else (tcp_pose_mm_deg[:3] if tcp_pose_mm_deg is not None else None)
    )
    result["tcp_orientation_deg"] = (
        tcp_pose_mm_deg[3:] if tcp_pose_mm_deg is not None else None
    )
    result["tcp_orientation_rad"] = _bounded_metric_vector(
        tcp_pose.get("orientation_rad"),
        length=3,
        minimum=-1_000.0,
        maximum=1_000.0,
    )
    result["controller"] = {
        "axis_count": _bounded_metric_integer(controller.get("axis_count"), maximum=32),
        "device_type": _bounded_metric_integer(
            controller.get("device_type"), maximum=65535
        ),
        "firmware_version": _bounded_xarm_firmware_version(
            controller.get("firmware_version")
        ),
        "temperatures_c": _bounded_metric_vector(
            controller.get("temperatures_c"),
            length=6,
            minimum=-100.0,
            maximum=250.0,
            allow_lite6_dummy=True,
        ),
        "joint_voltages_v": _bounded_metric_vector(
            controller.get("joint_voltages"),
            length=6,
            minimum=0.0,
            maximum=1_000.0,
            allow_lite6_dummy=True,
        ),
        "joint_currents_a": _bounded_metric_vector(
            controller.get("joint_currents"),
            length=6,
            minimum=-1_000.0,
            maximum=1_000.0,
            allow_lite6_dummy=True,
        ),
        # XArmAPI can switch this report channel between estimated torque and
        # current.  The property carries no stable unit discriminator, so the
        # public contract deliberately keeps its SDK-native provenance.
        "joint_torque_or_current_sdk": _bounded_metric_vector(
            controller.get("joint_torque"),
            length=6,
            minimum=-10_000.0,
            maximum=10_000.0,
            allow_lite6_dummy=True,
        ),
        "motor_brake_states": _bounded_binary_metric_vector(
            controller.get("motor_brake_states")
        ),
        "motor_enable_states": _bounded_binary_metric_vector(
            controller.get("motor_enable_states")
        ),
        "tcp_load_kg": None,
        "tcp_center_of_gravity_mm": None,
        "collision_sensitivity": _bounded_metric_integer(
            controller.get("collision_sensitivity"), maximum=5
        ),
        "teach_sensitivity": _bounded_metric_integer(
            controller.get("teach_sensitivity"), maximum=5
        ),
    }
    tcp_load = controller.get("tcp_load")
    if isinstance(tcp_load, (tuple, list)) and len(tcp_load) == 2:
        result["controller"]["tcp_load_kg"] = _bounded_finite_number(
            tcp_load[0],
            minimum=0.0,
            maximum=10_000.0,
        )
        result["controller"]["tcp_center_of_gravity_mm"] = _bounded_metric_vector(
            tcp_load[1],
            length=3,
            minimum=-1_000_000.0,
            maximum=1_000_000.0,
        )
    reduced_states = metrics.get("reduced_states")
    if isinstance(reduced_states, (tuple, list)) and len(reduced_states) == 7:
        boundary = _bounded_metric_vector(
            reduced_states[1],
            length=6,
            minimum=-1_000_000.0,
            maximum=1_000_000.0,
        )
        if boundary is not None and all(
            boundary[index * 2] >= boundary[index * 2 + 1] for index in range(3)
        ):
            result["safety"]["tcp_boundary_min_mm"] = [
                boundary[1],
                boundary[3],
                boundary[5],
            ]
            result["safety"]["tcp_boundary_max_mm"] = [
                boundary[0],
                boundary[2],
                boundary[4],
            ]
        result["safety"]["max_tcp_speed_mm_s"] = _bounded_finite_number(
            reduced_states[2], minimum=0.0, maximum=1_000_000.0
        )
        result["safety"]["max_joint_speed_rad_s"] = _bounded_finite_number(
            reduced_states[3], minimum=0.0, maximum=1_000.0
        )
        ranges = _bounded_metric_vector(
            reduced_states[4],
            length=14,
            minimum=-1_000.0,
            maximum=1_000.0,
        )
        if (
            ranges is not None
            and ranges[12:] == [0.0, 0.0]
            and all(ranges[index * 2] <= ranges[index * 2 + 1] for index in range(6))
        ):
            result["safety"]["joint_lower_rad"] = [
                ranges[index * 2] for index in range(6)
            ]
            result["safety"]["joint_upper_rad"] = [
                ranges[index * 2 + 1] for index in range(6)
            ]
        if type(reduced_states[5]) is int and reduced_states[5] in (0, 1):
            result["safety"]["safety_boundary_enabled"] = bool(reduced_states[5])
        if type(reduced_states[6]) is int and reduced_states[6] in (0, 1):
            result["safety"]["collision_rebound_enabled"] = bool(reduced_states[6])
    return result


def _private_network_address(value: Any) -> str:
    """Expose only a literal non-global controller address."""

    if not isinstance(value, str) or not value or len(value) > 64:
        return ""
    try:
        address = ipaddress.ip_address(value)
    except ValueError:
        return ""
    if address.is_global or address.is_multicast or address.is_unspecified:
        return ""
    return str(address)


def _safe_hostname() -> str:
    try:
        return _bounded_public_identifier(socket.gethostname())
    except OSError:
        return ""


def _xarm_fault_diagnostic(error_code: Optional[int]) -> Tuple[str, str]:
    """Map controller alarms to a closed, secret-free operator diagnostic."""

    if error_code == 2:
        return _XARM_EXTERNAL_EMERGENCY_IO_FAULT
    if isinstance(error_code, int) and not isinstance(error_code, bool):
        if error_code > 0:
            return _XARM_CONTROLLER_FAULT
    return _XARM_FAULT_NONE


def _strict_xarm_payload(result: Any, name: str) -> Any:
    """Unwrap one exact SDK ``(code, payload)`` result.

    Motion safety reads deliberately use a stricter contract than optional
    telemetry.  A raw value, boolean return code, extra tuple field, or any
    non-zero code is rejected before a motor command can be issued.
    """

    if not isinstance(result, (tuple, list)) or len(result) != 2:
        raise RuntimeError("{} response is invalid".format(name))
    code = result[0]
    if type(code) is not int or code != 0:
        raise RuntimeError("{} returned invalid code {!r}".format(name, code))
    return result[1]


def _strict_xarm_boolean(result: Any, name: str) -> bool:
    """Accept the SDK's documented raw bool or exact code/payload bool."""

    value = (
        _strict_xarm_payload(result, name)
        if isinstance(result, (tuple, list))
        else result
    )
    if not isinstance(value, bool):
        raise XArmControllerFault("invalid_boolean_response", name)
    return value


def _finite_control_vector(value: Any, length: int, name: str) -> Tuple[float, ...]:
    if not isinstance(value, (tuple, list)) or len(value) != length:
        raise RuntimeError("{} must contain exactly {} values".format(name, length))
    result = []
    for item in value:
        if isinstance(item, bool):
            raise RuntimeError("{} contains invalid values".format(name))
        try:
            number = float(item)
        except (TypeError, ValueError, OverflowError) as exc:
            raise RuntimeError("{} contains invalid values".format(name)) from exc
        if not math.isfinite(number):
            raise RuntimeError("{} contains invalid values".format(name))
        result.append(number)
    return tuple(result)


def _lite6_control_vector(value: Any, name: str) -> Tuple[float, ...]:
    if isinstance(value, (tuple, list)) and len(value) == 7:
        dummy = value[-1]
        if (
            isinstance(dummy, bool)
            or not isinstance(dummy, (int, float))
            or not math.isfinite(float(dummy))
            or abs(float(dummy)) > XArmMotionAdapter.sdk_dummy_joint_tolerance
        ):
            raise RuntimeError("{} has a nonzero Lite6 SDK dummy joint".format(name))
        value = value[:6]
    return _finite_control_vector(value, 6, name)


def _parse_reduced_configuration(
    mode_value: Any,
    states_value: Any,
    *,
    workspace_lower_xyz_mm: Sequence[float],
    workspace_upper_xyz_mm: Sequence[float],
) -> Mapping[str, Any]:
    """Validate the exact xArm 1.18.x reduced-state contract.

    This function only accepts an active, bounded Lite6 configuration.  It
    never enables reduced mode or changes controller limits; those remain a
    witnessed commissioning operation on the physical controller.
    """

    if type(mode_value) is not int or mode_value not in (0, 1):
        raise RuntimeError("xArm reduced-mode response is invalid")
    if not isinstance(states_value, (tuple, list)) or len(states_value) != 7:
        raise RuntimeError("xArm reduced-state response lacks required limits")
    mode_from_states = states_value[0]
    if type(mode_from_states) is not int or mode_from_states not in (0, 1):
        raise RuntimeError("xArm reduced-state mode is invalid")
    if mode_value != mode_from_states:
        raise RuntimeError("xArm reduced-mode queries disagree")
    if mode_value != 1:
        raise RuntimeError("xArm reduced mode is not active")

    lower = _finite_control_vector(
        workspace_lower_xyz_mm,
        3,
        "commissioned workspace lower bound",
    )
    upper = _finite_control_vector(
        workspace_upper_xyz_mm,
        3,
        "commissioned workspace upper bound",
    )
    if any(low >= high for low, high in zip(lower, upper)):
        raise RuntimeError("commissioned workspace bounds are invalid")

    boundary = _finite_control_vector(
        states_value[1],
        6,
        "xArm reduced TCP boundary",
    )
    for axis in range(3):
        maximum = boundary[axis * 2]
        minimum = boundary[axis * 2 + 1]
        if maximum <= minimum:
            raise RuntimeError("xArm reduced TCP boundary is invalid")
        if minimum < lower[axis] or maximum > upper[axis]:
            raise RuntimeError(
                "xArm reduced TCP boundary exceeds commissioned workspace"
            )

    speeds = _finite_control_vector(
        (states_value[2], states_value[3]),
        2,
        "xArm reduced speeds",
    )
    if not 0.0 < speeds[0] <= _MAX_REDUCED_TCP_SPEED_MM_PER_SECOND:
        raise RuntimeError("xArm reduced TCP speed exceeds the safety ceiling")
    if not 0.0 < speeds[1] <= _MAX_REDUCED_JOINT_SPEED_RADIANS_PER_SECOND:
        raise RuntimeError("xArm reduced joint speed exceeds the safety ceiling")

    ranges = _finite_control_vector(
        states_value[4],
        14,
        "xArm reduced joint ranges",
    )
    for index in range(6):
        joint_lower = ranges[index * 2]
        joint_upper = ranges[index * 2 + 1]
        if (
            joint_lower >= joint_upper
            or joint_lower < _LITE6_JOINT_LOWER_RADIANS[index]
            or joint_upper > _LITE6_JOINT_UPPER_RADIANS[index]
        ):
            raise RuntimeError(
                "xArm reduced joint ranges exceed the conservative Lite6 envelope"
            )
    if ranges[12:] != (0.0, 0.0):
        raise RuntimeError("xArm Lite6 dummy seventh-joint range is invalid")
    if type(states_value[5]) is not int or states_value[5] != 1:
        raise RuntimeError("xArm reduced safety boundary is not active")
    if type(states_value[6]) is not int or states_value[6] != 0:
        raise RuntimeError("xArm collision rebound must be disabled")

    return {
        "tcp_boundary_mm": boundary,
        "max_tcp_speed_mm_per_second": speeds[0],
        "max_joint_speed_radians_per_second": speeds[1],
        "joint_ranges_radians": ranges,
        "workspace_lower_xyz_mm": lower,
        "workspace_upper_xyz_mm": upper,
        "signature": (
            boundary,
            speeds[0],
            speeds[1],
            ranges,
            1,
            0,
        ),
    }


def _bounded_reduced_telemetry(
    mode_value: Any,
    states_value: Any,
    *,
    workspace_lower_xyz_mm: Sequence[float],
    workspace_upper_xyz_mm: Sequence[float],
    joints_value: Any,
    tcp_pose_value: Any,
) -> Mapping[str, bool]:
    """Return only closed safety booleans for health/LVGL display."""

    result = {
        "reduced_mode_enabled": False,
        "reduced_configuration_valid": False,
        "reduced_safety_boundary_enabled": False,
        "collision_rebound_disabled": False,
        "conservative_joint_envelope": False,
        "control_envelope_ready": False,
    }
    result["reduced_mode_enabled"] = type(mode_value) is int and mode_value == 1
    if isinstance(states_value, (tuple, list)) and len(states_value) == 7:
        result["reduced_safety_boundary_enabled"] = (
            type(states_value[5]) is int and states_value[5] == 1
        )
        result["collision_rebound_disabled"] = (
            type(states_value[6]) is int and states_value[6] == 0
        )
    try:
        joints = _lite6_control_vector(
            joints_value,
            "xArm telemetry joint angles",
        )
    except RuntimeError:
        joints = None
    if joints is not None:
        result["conservative_joint_envelope"] = all(
            _LITE6_JOINT_LOWER_RADIANS[index]
            <= value
            <= _LITE6_JOINT_UPPER_RADIANS[index]
            for index, value in enumerate(joints)
        )
    try:
        configuration = _parse_reduced_configuration(
            mode_value,
            states_value,
            workspace_lower_xyz_mm=workspace_lower_xyz_mm,
            workspace_upper_xyz_mm=workspace_upper_xyz_mm,
        )
    except RuntimeError:
        configuration = None
    else:
        result["reduced_configuration_valid"] = True
    if (
        configuration is not None
        and joints is not None
        and isinstance(tcp_pose_value, Mapping)
    ):
        position = tcp_pose_value.get("position_mm")
        orientation = tcp_pose_value.get("orientation_rad")
        if isinstance(position, (tuple, list)) and isinstance(
            orientation, (tuple, list)
        ):
            try:
                _require_pose_in_control_envelope(
                    joints,
                    tuple(position) + tuple(orientation),
                    configuration,
                )
            except RuntimeError:
                pass
            else:
                result["control_envelope_ready"] = True
    return result


def _require_pose_in_control_envelope(
    joints: Sequence[float],
    tcp_pose: Sequence[float],
    configuration: Mapping[str, Any],
) -> None:
    joint_values = _finite_control_vector(joints, 6, "xArm joint angles")
    tcp_values = _finite_control_vector(tcp_pose, 6, "xArm TCP pose")
    ranges = configuration["joint_ranges_radians"]
    for index, value in enumerate(joint_values):
        if not (
            _LITE6_JOINT_LOWER_RADIANS[index]
            <= value
            <= _LITE6_JOINT_UPPER_RADIANS[index]
            and ranges[index * 2] <= value <= ranges[index * 2 + 1]
        ):
            raise RuntimeError(
                "xArm joint {} is outside the commissioned safety envelope".format(
                    index + 1
                )
            )
    boundary = configuration["tcp_boundary_mm"]
    lower = configuration["workspace_lower_xyz_mm"]
    upper = configuration["workspace_upper_xyz_mm"]
    for axis, value in enumerate(tcp_values[:3]):
        if not (
            lower[axis] <= value <= upper[axis]
            and boundary[axis * 2 + 1] <= value <= boundary[axis * 2]
        ):
            raise RuntimeError("xArm TCP pose is outside the commissioned workspace")


class _CooldownTrackingAdapter:
    """Bound remote inference frequency without changing tracker semantics."""

    def __init__(
        self,
        tracking_service: Any,
        *,
        minimum_interval_seconds: float,
        clock: Callable[[], float] = time.monotonic,
    ) -> None:
        self.tracking_service = tracking_service
        self.minimum_interval_seconds = float(minimum_interval_seconds)
        self.clock = clock
        self._lock = threading.Lock()
        self._last_attempt_at: Optional[float] = None

    def process(self, frame: Any) -> Any:
        now = float(self.clock())
        with self._lock:
            if (
                self._last_attempt_at is not None
                and now - self._last_attempt_at < self.minimum_interval_seconds
            ):
                return ()
            self._last_attempt_at = now
        return self.tracking_service.process(frame)


class XArmMetricSource:
    """Read a bounded snapshot from an injected xArm SDK client."""

    def __init__(self, arm: Any) -> None:
        self.arm = arm
        self._lock = threading.Lock()
        self._motion_owner: Any = None

    def claim_motion_owner(self, owner: Any) -> None:
        """Permanently bind the one process-local production motion owner."""

        if owner is None:
            raise RuntimeError("xArm motion owner is invalid")
        with self._lock:
            if self._motion_owner is not None:
                raise RuntimeError("xArm already has a production motion owner")
            self._motion_owner = owner

    def is_motion_owner(self, owner: Any) -> bool:
        with self._lock:
            return owner is not None and self._motion_owner is owner

    def __call__(self) -> Mapping[str, Any]:
        with self._lock:
            metrics = {
                "connected": bool(getattr(self.arm, "connected", True)),
                "state": _optional_xarm_call(self.arm, "get_state"),
                "mode": getattr(self.arm, "mode", None),
                "moving": _optional_xarm_call(
                    self.arm,
                    "get_is_moving",
                ),
                "command_queue_depth": _optional_xarm_call(
                    self.arm,
                    "get_cmdnum",
                ),
                "joint_angles_deg": _optional_xarm_call(
                    self.arm,
                    "get_servo_angle",
                    is_radian=False,
                ),
                "joint_angles_rad": _optional_xarm_call(
                    self.arm,
                    "get_servo_angle",
                    is_radian=True,
                ),
                "tcp_pose_mm_deg": _optional_xarm_call(
                    self.arm,
                    "get_position",
                    is_radian=False,
                ),
                "reduced_mode": _optional_xarm_call(
                    self.arm,
                    "get_reduced_mode",
                ),
                "reduced_states": _optional_xarm_call(
                    self.arm,
                    "get_reduced_states",
                    is_radian=True,
                ),
                "error_warning": _optional_xarm_call(
                    self.arm,
                    "get_err_warn_code",
                ),
            }
            joint_states = _optional_xarm_call(
                self.arm,
                "get_joint_states",
                is_radian=True,
                num=3,
            )
            if isinstance(joint_states, (tuple, list)) and len(joint_states) >= 3:
                metrics["joint_states"] = {
                    "position_rad": joint_states[0],
                    "velocity_rad_s": joint_states[1],
                    "effort": joint_states[2],
                }
            else:
                metrics["joint_states"] = joint_states

            tcp_pose_rad = _optional_xarm_call(
                self.arm,
                "get_position",
                is_radian=True,
            )
            if isinstance(tcp_pose_rad, (tuple, list)) and len(tcp_pose_rad) >= 6:
                metrics["tcp_pose"] = {
                    "position_mm": list(tcp_pose_rad[:3]),
                    "orientation_rad": list(tcp_pose_rad[3:6]),
                }
            else:
                metrics["tcp_pose"] = tcp_pose_rad

            metrics["controller"] = {
                "axis_count": getattr(self.arm, "axis", None),
                "device_type": getattr(self.arm, "device_type", None),
                "firmware_version": getattr(self.arm, "version", None),
                "temperatures_c": getattr(self.arm, "temperatures", None),
                "joint_voltages": getattr(self.arm, "voltages", None),
                "joint_currents": getattr(self.arm, "currents", None),
                "joint_torque": getattr(self.arm, "joints_torque", None),
                "motor_brake_states": getattr(
                    self.arm,
                    "motor_brake_states",
                    None,
                ),
                "motor_enable_states": getattr(
                    self.arm,
                    "motor_enable_states",
                    None,
                ),
                "tcp_load": getattr(self.arm, "tcp_load", None),
                "collision_sensitivity": getattr(
                    self.arm,
                    "collision_sensitivity",
                    None,
                ),
                "teach_sensitivity": getattr(
                    self.arm,
                    "teach_sensitivity",
                    None,
                ),
            }
            return metrics

    def read_timed_tool_pose(self) -> Any:
        """Read one base-to-tool transform with a midpoint wall-clock stamp."""

        try:
            from main.vision.eye_in_hand import (
                TimedToolPose,
                xarm_pose_to_base_T_tool,
            )
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from vision.eye_in_hand import (  # type: ignore[no-redef]
                TimedToolPose,
                xarm_pose_to_base_T_tool,
            )

        with self._lock:
            started_at = time.time()
            try:
                raw_pose = self.arm.get_position(is_radian=False)
            except TypeError:
                raw_pose = self.arm.get_position()
            finished_at = time.time()
        return TimedToolPose(
            base_T_tool=xarm_pose_to_base_T_tool(raw_pose),
            timestamp_s=(started_at + finished_at) / 2.0,
        )

    def close(self) -> None:
        disconnect = getattr(self.arm, "disconnect", None)
        if callable(disconnect):
            disconnect()


def open_xarm_metric_source(xarm_ip: str) -> XArmMetricSource:
    """Create the repository's only supported xArm SDK connection.

    UI, workflows and compatibility modules receive typed workcell services;
    they never instantiate ``XArmAPI`` themselves.  Commissioning may use the
    returned source for bounded read-only capture, while production motion is
    owned exactly once by :class:`XArmMotionAdapter`.
    """

    if not isinstance(xarm_ip, str) or not xarm_ip.strip():
        raise RuntimeError("xArm controller address is invalid")
    try:
        from xarm.wrapper import XArmAPI
    except ImportError as exc:
        raise RuntimeError("xArm SDK is unavailable") from exc
    return XArmMetricSource(XArmAPI(xarm_ip.strip(), is_radian=True))


def _xarm_value(result: Any) -> Any:
    """Normalize the SDK's common ``(return_code, payload)`` shape."""

    if (
        isinstance(result, (tuple, list))
        and len(result) >= 2
        and isinstance(result[0], bool)
    ):
        raise RuntimeError("xArm call returned a boolean return code")
    if (
        isinstance(result, (tuple, list))
        and len(result) >= 2
        and isinstance(result[0], int)
    ):
        if result[0] != 0:
            raise RuntimeError("xArm metric call returned code {}".format(result[0]))
        if len(result) == 2:
            return result[1]
        return list(result[1:])
    return result


def _optional_xarm_call(
    arm: Any,
    method_name: str,
    **kwargs: Any,
) -> Any:
    """Read an optional firmware metric without losing the core snapshot."""

    callback = getattr(arm, method_name, None)
    if not callable(callback):
        return {"available": False, "reason": "unsupported"}
    try:
        return _xarm_value(callback(**kwargs))
    except Exception as exc:
        return {
            "available": False,
            "reason": type(exc).__name__,
        }


def _require_xarm_command(result: Any, operation: str) -> None:
    """Require the SDK's integer success code for a state-changing command."""

    code = result[0] if isinstance(result, (tuple, list)) and result else result
    if isinstance(code, bool) or not isinstance(code, int) or code != 0:
        normalized = "invalid_return_code"
        if isinstance(code, int) and not isinstance(code, bool):
            normalized = "sdk_code_{}".format(code)
        raise XArmControllerFault(normalized, operation)


class XArmMotionAdapter:
    """Fail-closed Lite6 IK and servo-stream adapter.

    The adapter shares the metric source's lock so telemetry, pose sampling,
    inverse kinematics, and commands cannot interleave SDK calls. Controller
    errors are never cleared automatically.
    """

    axis_count = 6
    sdk_dummy_joint_tolerance = 1e-9

    def __init__(
        self,
        metric_source: XArmMetricSource,
        *,
        workspace_lower_xyz_mm: Sequence[float] = (),
        workspace_upper_xyz_mm: Sequence[float] = (),
        pinned_safety_required: bool = False,
        monotonic: Callable[[], float] = time.monotonic,
    ) -> None:
        self.metric_source = metric_source
        self.arm = metric_source.arm
        self._lock = metric_source._lock
        self._command_dispatch_lock = threading.Lock()
        self._prepared = False
        self._commands_revoked = threading.Event()
        self._commands_revoked.set()
        self._workspace_lower_xyz_mm = tuple(workspace_lower_xyz_mm)
        self._workspace_upper_xyz_mm = tuple(workspace_upper_xyz_mm)
        self._monotonic = monotonic
        self._reduced_configuration: Optional[Mapping[str, Any]] = None
        self._reduced_configuration_checked_at = 0.0
        self._pinned_safety_verifier_locked: Optional[
            Callable[[], Mapping[str, Any]]
        ] = None
        self._pinned_safety_required = bool(pinned_safety_required)
        self._motion_permit_authority: Any = None
        self._motion_binding_provider: Optional[Callable[[], MotionBindings]] = None
        self._permit_stop_generation = 0
        self._permit_stop_fence = threading.Event()
        self._permit_stop_fence.set()
        self._permit_deadline_monotonic = 0.0
        self._permit_epoch_fault = threading.Event()
        self._fault_latched = False
        self._fault_code = ""
        self._fault_operation = ""
        self._fault_sequence = 0
        self._sampling_tool_adapter: Any = None
        metric_source.claim_motion_owner(self)

    def bind_sampling_tool_adapter(self, adapter: Any) -> None:
        """Bind one typed tool to this canonical motion owner exactly once."""

        if (
            adapter is None
            or getattr(adapter, "motion_owner", None) is not self
            or getattr(adapter, "metric_source", None) is not self.metric_source
            or not callable(getattr(adapter, "require_motion_allowed_locked", None))
            or not callable(getattr(adapter, "emergency_safe_idle", None))
        ):
            raise RuntimeError("Sampling tool does not share the motion owner")
        with self._lock:
            if self._sampling_tool_adapter not in (None, adapter):
                raise RuntimeError("A sampling tool is already bound")
            self._sampling_tool_adapter = adapter

    def fault_status(self) -> Mapping[str, Any]:
        """Return a bounded auditable controller-fault projection."""

        with self._lock:
            return {
                "schema_version": 1,
                "latched": self._fault_latched,
                "code": self._fault_code,
                "operation": self._fault_operation,
                "sequence": self._fault_sequence,
                "motion_owner": self.metric_source._motion_owner is self,
            }

    def _latch_fault_locked(self, code: str, operation: str) -> None:
        self._fault_latched = True
        self._fault_code = str(code)[:48]
        self._fault_operation = str(operation)[:64]
        self._fault_sequence += 1

    def _require_controller_identity_locked(self) -> None:
        if not bool(getattr(self.arm, "connected", False)):
            raise XArmControllerFault("disconnected", "identity")
        reported_axis = getattr(self.arm, "axis", None)
        if type(reported_axis) is not int or reported_axis != self.axis_count:
            raise XArmControllerFault("identity_mismatch", "axis count")
        device_type = getattr(self.arm, "device_type", None)
        if type(device_type) is not int or device_type != _LITE6_DEVICE_TYPE:
            raise XArmControllerFault("identity_mismatch", "device type")

    def acknowledge_supervised_recovery(self) -> Mapping[str, Any]:
        """Clear only the software latch after an onsite controller recovery.

        This operation never clears controller errors/warnings and never
        enables motors.  It first issues the fail-safe stop/disable pair, then
        requires an exact healthy, stationary, state-4 Lite6 readback.  Motion
        remains locked and a new signed one-use permit is still mandatory.
        """

        self._commands_revoked.set()
        self._permit_stop_fence.set()
        self._request_sampling_tool_stop()
        self._invalidate_motion_permits("supervised_recovery")
        with self._lock:
            self._prepared = False
            self._permit_deadline_monotonic = 0.0
            failures = self._safe_sampling_tool_locked()
            failures.extend(self._halt_locked())
            if failures:
                self._latch_fault_locked("fail_safe_stop_failed", "supervised_recovery")
                raise XArmControllerFault(
                    "fail_safe_stop_failed", "supervised_recovery"
                )
            try:
                self._require_controller_identity_locked()
                self._require_healthy_locked()
                state = _strict_xarm_payload(
                    self.arm.get_state(), "xArm supervised-recovery state"
                )
                if type(state) is not int or state != 4:
                    raise XArmControllerFault("state_not_locked", "supervised_recovery")
                moving = _strict_xarm_boolean(
                    self.arm.get_is_moving(), "xArm supervised-recovery moving state"
                )
                if moving:
                    raise XArmControllerFault(
                        "motion_not_stopped", "supervised_recovery"
                    )
                motor_states = getattr(self.arm, "motor_enable_states", None)
                if (
                    not isinstance(motor_states, (tuple, list))
                    or len(motor_states) < self.axis_count
                    or any(
                        type(value) is not int or value != 0
                        for value in motor_states[: self.axis_count]
                    )
                ):
                    raise XArmControllerFault(
                        "motors_not_disabled", "supervised_recovery"
                    )
                self._read_reduced_configuration_locked()
            except Exception as exc:
                if isinstance(exc, XArmControllerFault):
                    fault = exc
                else:
                    fault = XArmControllerFault(
                        "recovery_readback_failed", "supervised_recovery"
                    )
                self._latch_fault_locked(fault.code, fault.operation)
                raise fault from exc
            self._fault_latched = False
            self._fault_code = ""
            self._fault_operation = ""
            return {
                "schema_version": 1,
                "latched": False,
                "code": "",
                "operation": "",
                "sequence": self._fault_sequence,
                "motion_owner": self.metric_source._motion_owner is self,
            }

    def bind_motion_permit_authority(
        self,
        authority: Any,
        bindings_provider: Callable[[], MotionBindings],
    ) -> None:
        """Bind the verifier-only permit boundary during trusted assembly.

        The adapter accepts no signer and exposes no permit acquisition API.
        The authority must provide durable verification/consumption and
        invalidation; immutable release, robot and safety identities are read
        afresh by ``bindings_provider`` inside the final controller lock.
        """

        if any(
            not callable(getattr(authority, name, None))
            for name in ("verify_and_consume", "invalidate", "runtime_context")
        ) or not callable(bindings_provider):
            raise RuntimeError("Motion permit authority is invalid")
        with self._lock:
            if self._motion_permit_authority is not None:
                raise RuntimeError("Motion permit authority is already bound")
            self._motion_permit_authority = authority
            self._motion_binding_provider = bindings_provider
            self._permit_deadline_monotonic = 0.0
            self._permit_epoch_fault.clear()

    def motion_permit_context_status(self) -> Mapping[str, Any]:
        """Expose only the non-secret runtime/epoch replay boundary."""

        authority = self._motion_permit_authority
        if authority is None:
            return {
                "configured": False,
                "ready": False,
                "runtime_instance_id": "",
                "authorization_epoch": 0,
            }
        try:
            context = authority.runtime_context()
        except Exception:
            return {
                "configured": True,
                "ready": False,
                "runtime_instance_id": "",
                "authorization_epoch": 0,
            }
        if (
            not isinstance(context, tuple)
            or len(context) != 2
            or not isinstance(context[0], str)
            or re.fullmatch(r"[0-9a-f]{32}", context[0]) is None
            or isinstance(context[1], bool)
            or not isinstance(context[1], int)
            or context[1] < 0
        ):
            return {
                "configured": True,
                "ready": False,
                "runtime_instance_id": "",
                "authorization_epoch": 0,
            }
        return {
            "configured": True,
            "ready": not self._permit_epoch_fault.is_set(),
            "runtime_instance_id": context[0],
            "authorization_epoch": context[1],
        }

    def bind_pinned_safety_configurator(self, configurator: Any) -> None:
        """Bind an exact-profile verifier sharing this adapter's SDK lock.

        Production Search arming requires one non-reentrant critical section
        from the last pinned-profile verification through motor-enable.  A
        configurator using any other lock cannot provide that invariant.
        """

        verifier = getattr(configurator, "verify_for_motion_locked", None)
        if (
            not callable(verifier)
            or getattr(configurator, "lock", None) is not self._lock
        ):
            raise RuntimeError(
                "Pinned Lite6 safety verifier must share the xArm SDK lock"
            )
        self._pinned_safety_verifier_locked = verifier
        self._pinned_safety_required = True

    @property
    def prepared(self) -> bool:
        with self._lock:
            return self._prepared

    def read_joint_angles_radians(self) -> Tuple[float, ...]:
        with self._lock:
            return self._read_joint_angles_locked()

    def inverse_kinematics(
        self,
        tcp_pose: Sequence[float],
        seed_joints: Optional[Sequence[float]],
    ) -> Tuple[float, ...]:
        pose = self._finite_vector(tcp_pose, 6, "TCP pose")
        reference = (
            self._finite_vector(seed_joints, self.axis_count, "IK seed")
            if seed_joints is not None
            else None
        )
        with self._lock:
            kwargs = {
                "input_is_radian": True,
                "return_is_radian": True,
                "limited": True,
            }
            if reference is not None:
                kwargs["ref_angles"] = list(reference)
            try:
                result = self.arm.get_inverse_kinematics(list(pose), **kwargs)
            except TypeError:
                # Older firmware/SDK combinations do not expose ref_angles.
                kwargs.pop("ref_angles", None)
                result = self.arm.get_inverse_kinematics(list(pose), **kwargs)
            angles = self._lite6_sdk_vector(
                _xarm_value(result),
                "inverse-kinematics result",
            )
            limit_result = self.arm.is_joint_limit(
                list(angles),
                is_radian=True,
            )
            outside_limit = _xarm_value(limit_result)
            if not isinstance(outside_limit, bool):
                raise RuntimeError("xArm joint-limit check returned invalid data")
            if outside_limit:
                raise RuntimeError("xArm inverse kinematics exceeded controller limits")
            return angles

    def forward_kinematics(
        self,
        joints: Sequence[float],
    ) -> Tuple[float, ...]:
        """Resolve reviewed radian joints to a finite TCP pose for validation."""

        angles = self._finite_vector(joints, self.axis_count, "FK joints")
        with self._lock:
            result = self.arm.get_forward_kinematics(
                list(angles),
                input_is_radian=True,
                return_is_radian=True,
            )
            return self._finite_vector(
                _xarm_value(result),
                6,
                "forward-kinematics result",
            )

    def prepare_motion(
        self,
        *,
        stop_requested: Optional[Callable[[], bool]] = None,
        permit: Any = None,
        intent: Any = None,
        expected_motion_profile_sha256: Optional[str] = None,
    ) -> None:
        """Consume one signed permit atomically at the motor-enable boundary."""

        with self._lock:
            if self._prepared:
                raise RuntimeError("xArm motion is already prepared")
            if self._fault_latched:
                raise XArmControllerFault(
                    "fault_latched", self._fault_operation or "prepare_motion"
                )
        self._commands_revoked.set()
        authority = self._motion_permit_authority
        bindings_provider = self._motion_binding_provider
        if authority is None or bindings_provider is None:
            with self._lock:
                self._prepared = False
                self._reduced_configuration = None
                self._reduced_configuration_checked_at = 0.0
            raise RuntimeError(_MOTION_RELEASE_BLOCKER)
        if not isinstance(intent, MotionIntent):
            raise RuntimeError("A typed motion intent is required")
        if self._permit_epoch_fault.is_set():
            raise RuntimeError("Motion permit state is fault-locked")

        with self._command_dispatch_lock:
            stop_generation = self._permit_stop_generation
            self._permit_stop_fence.clear()

        def require_not_stopped() -> None:
            if (
                self._permit_epoch_fault.is_set()
                or self._permit_stop_fence.is_set()
                or (stop_requested is not None and stop_requested())
            ):
                raise _XArmStopRequested("xArm motion preparation was stopped")

        with self._lock:
            self._prepared = False
            self._permit_deadline_monotonic = 0.0
            controller_mutation_started = False
            controller_phase = True
            try:
                reduced = self._final_motion_safety_readback_locked()
                self._require_sampling_tool_motion_allowed_locked()
                # STOP, durable consume and the first controller mutation share
                # this dispatch gate.  The surrounding SDK lock also covers
                # the final health/profile readback above.
                with self._command_dispatch_lock:
                    controller_phase = False
                    require_not_stopped()
                    if stop_generation != self._permit_stop_generation:
                        raise _XArmStopRequested("xArm motion preparation was stopped")
                    bindings = bindings_provider()
                    if not isinstance(bindings, MotionBindings):
                        raise RuntimeError("Motion permit bindings are invalid")
                    if expected_motion_profile_sha256 is not None and not (
                        isinstance(expected_motion_profile_sha256, str)
                        and secrets.compare_digest(
                            bindings.motion_primitive_sha256,
                            expected_motion_profile_sha256,
                        )
                    ):
                        raise RuntimeError(
                            "Reviewed motion profile does not match permit bindings"
                        )
                    grant = authority.verify_and_consume(
                        permit,
                        intent=intent,
                        bindings=bindings,
                    )
                    if not isinstance(grant, MotionPermitGrant):
                        raise RuntimeError("Motion permit grant is invalid")
                    require_not_stopped()
                    if stop_generation != self._permit_stop_generation:
                        raise _XArmStopRequested("xArm motion preparation was stopped")
                    controller_mutation_started = True
                    controller_phase = True
                    _require_xarm_command(
                        self.arm.motion_enable(enable=True),
                        "motion_enable",
                    )
                    require_not_stopped()
                    _require_xarm_command(self.arm.set_mode(1), "set_mode(1)")
                    require_not_stopped()
                    _require_xarm_command(self.arm.set_state(0), "set_state(0)")
                    require_not_stopped()
                    state = _strict_xarm_payload(
                        self.arm.get_state(), "xArm ready state"
                    )
                    if state != 0:
                        raise RuntimeError(
                            "xArm did not enter ready state 0 "
                            "(reported {!r})".format(state)
                        )
                    self._require_healthy_locked()
                    confirmed_reduced = self._read_reduced_configuration_locked()
                    if confirmed_reduced["signature"] != reduced["signature"]:
                        raise RuntimeError(
                            "xArm reduced safety configuration changed while arming"
                        )
                    deadline = min(
                        float(grant.deadline_monotonic),
                        float(self._monotonic())
                        + (float(grant.maximum_duration_ms) / 1000.0),
                    )
                    if deadline <= float(self._monotonic()):
                        raise RuntimeError("Motion permit expired before motor enable")
                    self._permit_deadline_monotonic = deadline
            except Exception as exc:
                self._prepared = False
                self._commands_revoked.set()
                self._permit_stop_fence.set()
                self._permit_deadline_monotonic = 0.0
                self._invalidate_motion_permits("prepare_failed")
                failures = self._safe_sampling_tool_locked()
                if controller_mutation_started:
                    failures.extend(self._halt_locked())
                if failures:
                    self._latch_fault_locked("fail_safe_stop_failed", "prepare_motion")
                elif controller_phase and not isinstance(exc, _XArmStopRequested):
                    if isinstance(exc, XArmControllerFault):
                        self._latch_fault_locked(exc.code, exc.operation)
                    else:
                        self._latch_fault_locked(
                            "controller_readback_failed", "prepare_motion"
                        )
                if failures:
                    LOGGER.error(
                        "Could not fully lock xArm after prepare failure: %s",
                        "; ".join(failures),
                    )
                raise
            self._reduced_configuration = confirmed_reduced
            self._reduced_configuration_checked_at = float(self._monotonic())
            try:
                require_not_stopped()
                self._commands_revoked.clear()
                require_not_stopped()
                if float(self._monotonic()) >= self._permit_deadline_monotonic:
                    raise RuntimeError("Motion permit expired before command release")
            except Exception:
                self._commands_revoked.set()
                self._permit_stop_fence.set()
                self._permit_deadline_monotonic = 0.0
                self._invalidate_motion_permits("prepare_stopped")
                failures = self._halt_locked()
                if failures:
                    LOGGER.error(
                        "Could not fully lock xArm after concurrent STOP: %s",
                        "; ".join(failures),
                    )
                raise
            self._prepared = True

    def execute_reviewed_trajectory(
        self,
        trajectory: ReviewedJointTrajectory,
        *,
        permit: Any,
        intent: MotionIntent,
        stop_requested: Optional[Callable[[], bool]] = None,
    ) -> None:
        """Execute one digest-bound profile and always return to LOCKED.

        This is the only bounded batch operation exposed by the canonical
        controller.  It accepts no Cartesian target, speed, mode or arbitrary
        SDK method name.  Home uses the same function with the separately
        reviewed ``reviewed_home`` scope.
        """

        if not isinstance(trajectory, ReviewedJointTrajectory):
            raise RuntimeError("A typed reviewed trajectory is required")
        if not isinstance(intent, MotionIntent) or (
            intent.operation_scope != trajectory.operation_scope
            or intent.action != trajectory.action
        ):
            raise RuntimeError("Motion intent does not match reviewed trajectory")
        try:
            self.prepare_motion(
                stop_requested=stop_requested,
                permit=permit,
                intent=intent,
                expected_motion_profile_sha256=trajectory.profile_sha256,
            )
            for joints in trajectory.waypoints_radians:
                if stop_requested is not None and stop_requested():
                    raise _XArmStopRequested("Reviewed trajectory was stopped")
                self.send_joint_command(_ReviewedJointCommand(joints=joints))
        finally:
            try:
                self.halt()
            except Exception:
                with self._lock:
                    self._latch_fault_locked(
                        "fail_safe_stop_failed", "reviewed_trajectory"
                    )
                raise

    def _final_motion_safety_readback_locked(self) -> Mapping[str, Any]:
        """Perform the final read-only controller/profile checks under lock."""

        self._require_controller_identity_locked()
        self._require_healthy_locked()
        current_joints = self._read_joint_angles_locked()
        reduced = self._read_reduced_configuration_locked()
        current_pose = _finite_control_vector(
            _strict_xarm_payload(
                self.arm.get_position(is_radian=True),
                "xArm TCP pose",
            ),
            6,
            "xArm TCP pose",
        )
        _require_pose_in_control_envelope(current_joints, current_pose, reduced)
        get_is_moving = getattr(self.arm, "get_is_moving", None)
        if callable(get_is_moving):
            moving = _strict_xarm_boolean(get_is_moving(), "xArm moving state")
            if moving:
                raise RuntimeError(
                    "xArm is still moving; wait for a complete stop before arming"
                )
        verifier = self._pinned_safety_verifier_locked
        if self._pinned_safety_required and verifier is None:
            raise RuntimeError(
                "Pinned Lite6 safety verifier is required before motor enable"
            )
        if verifier is not None:
            verification = verifier()
            if (
                not isinstance(verification, Mapping)
                or verification.get("verified") is not True
                or verification.get("preflight", {}).get("ready") is not True
                or verification.get("readback", {}).get("verified") is not True
            ):
                raise RuntimeError(
                    "Pinned Lite6 safety verification failed before motor enable"
                )
        return reduced

    def send_joint_command(self, command: Any) -> None:
        """Send one already safety-validated radian command."""

        joints = self._finite_vector(
            getattr(command, "joints", None),
            self.axis_count,
            "joint command",
        )
        if getattr(command, "gripper", None) is not None:
            raise RuntimeError(
                "Live primitive contains gripper commands but no reviewed "
                "gripper adapter is configured"
            )
        with self._lock:
            if not self._prepared or self._commands_revoked.is_set():
                raise RuntimeError("xArm command path is locked")
            try:
                if float(self._monotonic()) >= self._permit_deadline_monotonic:
                    raise RuntimeError("Motion permit expired")
                self._require_stream_healthy_locked()
                self._require_sampling_tool_motion_allowed_locked()
                reduced = self._require_reduced_stream_gate_locked()
                self._require_joint_command_envelope(joints, reduced)
                # STOP and the final SDK write share one linearization gate.
                # A STOP that wins this gate prevents the write; a command
                # already inside it is an in-flight write which STOP waits to
                # retire before returning from ``revoke_commands``.
                with self._command_dispatch_lock:
                    if self._commands_revoked.is_set():
                        raise RuntimeError("xArm command path was stopped")
                    if float(self._monotonic()) >= self._permit_deadline_monotonic:
                        raise RuntimeError("Motion permit expired")
                    _require_xarm_command(
                        self.arm.set_servo_angle_j(
                            list(joints),
                            is_radian=True,
                        ),
                        "set_servo_angle_j",
                    )
            except Exception:
                self._prepared = False
                self._commands_revoked.set()
                self._permit_stop_fence.set()
                self._permit_deadline_monotonic = 0.0
                self._invalidate_motion_permits("command_failed")
                failures = self._safe_sampling_tool_locked()
                failures.extend(self._halt_locked())
                if failures:
                    self._latch_fault_locked(
                        "fail_safe_stop_failed", "send_joint_command"
                    )
                else:
                    self._latch_fault_locked(
                        "controller_command_failed", "send_joint_command"
                    )
                if failures:
                    LOGGER.error(
                        "Could not fully halt xArm after command failure: %s",
                        "; ".join(failures),
                    )
                raise

    def lock_commands(self) -> None:
        """Close the software command gate without changing controller state."""

        self._commands_revoked.set()
        self._permit_stop_fence.set()
        self._request_sampling_tool_stop()
        self._invalidate_motion_permits("command_locked")
        with self._lock:
            self._prepared = False
            self._reduced_configuration = None
            self._permit_deadline_monotonic = 0.0
            failures = self._safe_sampling_tool_locked()
            if failures:
                self._latch_fault_locked("tool_safe_state_failed", "lock_commands")
                raise RuntimeError("; ".join(failures))

    def halt(self) -> None:
        """Stop the controller and disable motion; try both calls on failure."""

        self._commands_revoked.set()
        self._permit_stop_fence.set()
        self._request_sampling_tool_stop()
        self._invalidate_motion_permits("controller_halt")
        with self._lock:
            self._prepared = False
            self._reduced_configuration = None
            self._permit_deadline_monotonic = 0.0
            failures = self._safe_sampling_tool_locked()
            failures.extend(self._halt_locked())
            if failures:
                self._latch_fault_locked("fail_safe_stop_failed", "halt")
                raise RuntimeError("; ".join(failures))

    def revoke_commands(self) -> None:
        """Linearize command revocation before the blocking controller halt.

        The Event closes queued/future writes immediately.  Crossing the
        dispatch gate then proves that no pre-existing SDK write can begin
        after this method returns.  The subsequent controller halt remains the
        physical backstop for a write that had already entered the SDK.
        """

        self._commands_revoked.set()
        self._permit_stop_fence.set()
        self._request_sampling_tool_stop()
        self._invalidate_motion_permits("software_stop")
        with self._command_dispatch_lock:
            self._permit_stop_generation += 1

    def _request_sampling_tool_stop(self) -> None:
        adapter = self._sampling_tool_adapter
        request_stop = getattr(adapter, "request_stop", None)
        if callable(request_stop):
            request_stop()

    def _require_sampling_tool_motion_allowed_locked(self) -> None:
        adapter = self._sampling_tool_adapter
        if adapter is not None:
            adapter.require_motion_allowed_locked()

    def _safe_sampling_tool_locked(self) -> List[str]:
        """De-energize the bound tool while the shared SDK lock is held."""

        adapter = self._sampling_tool_adapter
        safe_idle = getattr(adapter, "_safe_idle_from_owner_locked", None)
        if not callable(safe_idle):
            return []
        try:
            safe_idle()
            return []
        except Exception as exc:
            return ["sampling tool safe state: {}".format(exc)]

    def _invalidate_motion_permits(self, reason: str) -> None:
        """Invalidate all outstanding permits, fault-locking on ledger loss."""

        authority = self._motion_permit_authority
        if authority is None:
            return
        try:
            authority.invalidate(reason)
        except Exception:
            # STOP/halt must continue to the physical controller even when
            # durable replay state is unavailable.  Future arming remains
            # fault-locked until a fresh runtime rebuilds the authority.
            self._permit_epoch_fault.set()
            LOGGER.error(
                "Could not durably invalidate outstanding motion permits",
                exc_info=True,
            )

    def _read_joint_angles_locked(self) -> Tuple[float, ...]:
        result = self.arm.get_servo_angle(is_radian=True)
        return self._lite6_sdk_vector(
            _xarm_value(result),
            "xArm joint angles",
        )

    def _require_healthy_locked(self) -> None:
        errors = _strict_xarm_payload(
            self.arm.get_err_warn_code(), "xArm error/warning"
        )
        if (
            not isinstance(errors, (tuple, list))
            or len(errors) < 2
            or isinstance(errors[0], bool)
            or isinstance(errors[1], bool)
            or not isinstance(errors[0], int)
            or not isinstance(errors[1], int)
        ):
            raise XArmControllerFault(
                "invalid_health_response", "error_warning_readback"
            )
        if errors[0] != 0 or errors[1] != 0:
            raise XArmControllerFault(
                "controller_error_{}_warning_{}".format(errors[0], errors[1]),
                "error {} warning {} readback".format(errors[0], errors[1]),
            )

    def _require_stream_healthy_locked(self) -> None:
        self._require_controller_identity_locked()
        state = _strict_xarm_payload(self.arm.get_state(), "xArm command state")
        if type(state) is not int or state != 0:
            raise XArmControllerFault("state_invalid", "command state")
        mode = getattr(self.arm, "mode", None)
        if type(mode) is not int or mode != 1:
            raise XArmControllerFault("mode_invalid", "command mode")
        has_error = getattr(self.arm, "has_error", None)
        has_warning = getattr(self.arm, "has_warn", None)
        if has_error is None or has_warning is None:
            self._require_healthy_locked()
            return
        if bool(has_error) or bool(has_warning):
            self._require_healthy_locked()

    def _read_reduced_configuration_locked(self) -> Mapping[str, Any]:
        mode = _strict_xarm_payload(
            self.arm.get_reduced_mode(),
            "xArm reduced mode",
        )
        states = _strict_xarm_payload(
            self.arm.get_reduced_states(is_radian=True),
            "xArm reduced states",
        )
        return _parse_reduced_configuration(
            mode,
            states,
            workspace_lower_xyz_mm=self._workspace_lower_xyz_mm,
            workspace_upper_xyz_mm=self._workspace_upper_xyz_mm,
        )

    def _require_reduced_stream_gate_locked(self) -> Mapping[str, Any]:
        configuration = self._reduced_configuration
        if not isinstance(configuration, Mapping):
            raise RuntimeError("xArm reduced safety configuration is not commissioned")
        mode = _strict_xarm_payload(
            self.arm.get_reduced_mode(),
            "xArm reduced mode",
        )
        if type(mode) is not int or mode != 1:
            raise RuntimeError("xArm reduced mode is not active")
        now = float(self._monotonic())
        if (
            now - self._reduced_configuration_checked_at
            >= _REDUCED_CONFIGURATION_RECHECK_SECONDS
        ):
            current = self._read_reduced_configuration_locked()
            if current["signature"] != configuration["signature"]:
                raise RuntimeError(
                    "xArm reduced safety configuration changed during motion"
                )
            configuration = current
            self._reduced_configuration = current
            self._reduced_configuration_checked_at = now
        return configuration

    @staticmethod
    def _require_joint_command_envelope(
        joints: Sequence[float],
        configuration: Mapping[str, Any],
    ) -> None:
        ranges = configuration["joint_ranges_radians"]
        for index, value in enumerate(joints):
            if not (
                _LITE6_JOINT_LOWER_RADIANS[index]
                <= value
                <= _LITE6_JOINT_UPPER_RADIANS[index]
                and ranges[index * 2] <= value <= ranges[index * 2 + 1]
            ):
                raise RuntimeError(
                    "xArm command joint {} exceeds the commissioned safety "
                    "envelope".format(index + 1)
                )

    def _halt_locked(self) -> List[str]:
        failures = []
        for operation, callback in (
            ("set_state(4)", lambda: self.arm.set_state(4)),
            (
                "motion_enable(false)",
                lambda: self.arm.motion_enable(enable=False),
            ),
        ):
            try:
                _require_xarm_command(callback(), operation)
            except Exception as exc:
                failures.append("{}: {}".format(operation, exc))
        return failures

    @staticmethod
    def _finite_vector(
        values: Any,
        expected_length: int,
        name: str,
    ) -> Tuple[float, ...]:
        try:
            result = tuple(float(value) for value in values)
        except (TypeError, ValueError) as exc:
            raise RuntimeError("{} must be numeric".format(name)) from exc
        if len(result) != expected_length or not all(
            math.isfinite(value) for value in result
        ):
            raise RuntimeError(
                "{} must contain {} finite values".format(name, expected_length)
            )
        return result

    @classmethod
    def _lite6_sdk_vector(
        cls,
        values: Any,
        name: str,
    ) -> Tuple[float, ...]:
        """Normalize the SDK's six axes plus optional zero dummy slot.

        xarm-python-sdk 1.18.4 returns seven-element joint and IK arrays for
        the physical Lite6, with a finite zero placeholder in the final slot.
        Accept only that precisely bounded compatibility shape; command and
        caller-provided vectors still require exactly six values.
        """

        try:
            result = tuple(float(value) for value in values)
        except (TypeError, ValueError) as exc:
            raise RuntimeError("{} must be numeric".format(name)) from exc
        if len(result) == cls.axis_count and all(
            math.isfinite(value) for value in result
        ):
            return result
        if (
            len(result) == cls.axis_count + 1
            and all(math.isfinite(value) for value in result)
            and math.isclose(
                result[-1],
                0.0,
                rel_tol=0.0,
                abs_tol=cls.sdk_dummy_joint_tolerance,
            )
        ):
            return result[: cls.axis_count]
        raise RuntimeError(
            "{} must contain {} finite values or those values plus a "
            "near-zero SDK dummy slot".format(name, cls.axis_count)
        )


class ReviewedHomeController:
    """Bounded home operation sharing the canonical production owner.

    The provider supplies only an opaque signed permit and typed intent.  The
    reviewed joint values are fixed in the digest-bound profile and no caller
    can pass coordinates, speed, controller mode or an SDK method name.
    """

    def __init__(
        self,
        motion_owner: XArmMotionAdapter,
        trajectory: ReviewedJointTrajectory,
        permit_provider: Callable[[], Tuple[Any, MotionIntent]],
    ) -> None:
        if (
            not isinstance(motion_owner, XArmMotionAdapter)
            or not (
                isinstance(trajectory, ReviewedJointTrajectory)
                and trajectory.operation_scope == "reviewed_home"
                and trajectory.action == "home"
            )
            or not callable(permit_provider)
        ):
            raise RuntimeError("Reviewed home controller configuration is invalid")
        if not motion_owner.metric_source.is_motion_owner(motion_owner):
            raise RuntimeError("Reviewed home controller does not own the xArm")
        self.motion_owner = motion_owner
        self.trajectory = trajectory
        self.permit_provider = permit_provider

    def verify_recovery_ready(self) -> bool:
        return (
            self.motion_owner.metric_source.is_motion_owner(self.motion_owner)
            and self.motion_owner.prepared is False
        )

    def return_home(self, motion_stop_requested: Callable[[], bool]) -> str:
        if not callable(motion_stop_requested) or motion_stop_requested():
            raise RuntimeError("Reviewed home was stopped")
        authorization = self.permit_provider()
        if not isinstance(authorization, tuple) or len(authorization) != 2:
            raise RuntimeError("Reviewed home authorization is invalid")
        permit, intent = authorization
        self.motion_owner.execute_reviewed_trajectory(
            self.trajectory,
            permit=permit,
            intent=intent,
            stop_requested=motion_stop_requested,
        )
        return "Reviewed home reached; motion remains LOCKED"


class WorkcellServices:
    """Own optional hardware/cloud services as one runtime lifecycle."""

    def __init__(
        self,
        *,
        settings: IntegrationSettings,
        datahub: Optional[DataHubPublisher] = None,
        camera_rig: Any = None,
        metric_source: Optional[Callable[[], Mapping[str, Any]]] = None,
        ota_updater: Optional[SecureOTAUpdater | PrivilegedOTAClient] = None,
        offload_client: Optional[ShortcutJobClient] = None,
        tenant_auth_client: Any = None,
        readiness_client: Optional[DeviceReadinessClient] = None,
        mjpeg_server: Any = None,
        jpeg_encoder: Optional[Callable[[Any], bytes]] = None,
        tool_pose_buffer: Any = None,
        tool_workspace_mapper: Any = None,
        local_valve_confirmation_detector: Any = None,
        valve_controller: Any = None,
        xarm_motion_adapter: Optional[XArmMotionAdapter] = None,
        sampling_tool_adapter: Any = None,
        motion_permit_authority: Any = None,
        motion_binding_provider: Optional[Callable[[], MotionBindings]] = None,
        recovery_controller: Any = None,
        petri_process_controller: Any = None,
        petri_registry: Any = None,
        petri_artifact_root: Optional[Path] = None,
        capture_run_controller: Any = None,
        capture_dataset_exporter: Any = None,
        hand_training_controller: Any = None,
        safety_configurator: Any = None,
        site_safety_gate: Any = None,
        digital_twin_provider: Any = None,
        trajectory_preflight: Any = None,
        workspace_teach_recorder: Any = None,
        workspace_teach_store: Any = None,
        workspace_boundary_validator: Any = None,
        ota_commissioning_evaluator: Optional[
            Callable[[IntegrationSettings], OTACommissioningGate]
        ] = None,
        monotonic: Callable[[], float] = time.monotonic,
    ) -> None:
        self.settings = settings
        self.datahub = datahub
        self.camera_rig = camera_rig
        self.metric_source = metric_source
        self.ota_updater = ota_updater
        self.offload_client = offload_client
        self.tenant_auth_client = tenant_auth_client
        self.readiness_client = readiness_client
        self.mjpeg_server = mjpeg_server
        self.jpeg_encoder = jpeg_encoder
        self.tool_pose_buffer = tool_pose_buffer
        self.tool_workspace_mapper = tool_workspace_mapper
        self.local_valve_confirmation_detector = local_valve_confirmation_detector
        self.valve_controller = valve_controller
        self.xarm_motion_adapter = xarm_motion_adapter
        self.sampling_tool_adapter = sampling_tool_adapter
        if sampling_tool_adapter is not None:
            if not getattr(settings, "sampling_tool_enabled", False):
                raise RuntimeError(
                    "Sampling-tool injection requires explicit trusted configuration"
                )
            if (
                not isinstance(xarm_motion_adapter, XArmMotionAdapter)
                or getattr(sampling_tool_adapter, "motion_owner", None)
                is not xarm_motion_adapter
            ):
                raise RuntimeError(
                    "Sampling tool must share the canonical xArm motion owner"
                )
            xarm_motion_adapter.bind_sampling_tool_adapter(sampling_tool_adapter)
        if (motion_permit_authority is None) != (motion_binding_provider is None):
            raise RuntimeError(
                "Motion permit authority and immutable bindings must be supplied together"
            )
        if motion_permit_authority is not None:
            if not isinstance(xarm_motion_adapter, XArmMotionAdapter):
                raise RuntimeError(
                    "Motion permit authority requires the concrete xArm adapter"
                )
            xarm_motion_adapter.bind_motion_permit_authority(
                motion_permit_authority,
                motion_binding_provider,
            )
        if isinstance(xarm_motion_adapter, XArmMotionAdapter) and (
            recovery_controller is not None
            and not (
                isinstance(recovery_controller, ReviewedHomeController)
                and recovery_controller.motion_owner is xarm_motion_adapter
            )
        ):
            raise RuntimeError(
                "Production xArm recovery must share the canonical motion owner"
            )
        self.recovery_controller = recovery_controller
        self.petri_process_controller = petri_process_controller
        self.hand_training_controller = hand_training_controller
        if sampling_tool_adapter is not None and (
            petri_process_controller is not None or hand_training_controller is not None
        ):
            claim_control = getattr(
                sampling_tool_adapter,
                "claim_process_control",
                None,
            )
            if not callable(claim_control):
                raise RuntimeError(
                    "Production sampling tool lacks typed process control"
                )
            shared_tool_control = claim_control(self)
            if petri_process_controller is not None:
                bind_tool = getattr(
                    petri_process_controller,
                    "bind_sampling_tool_control",
                    None,
                )
                if not callable(bind_tool):
                    raise RuntimeError(
                        "Production Petri controller lacks typed sampling-tool control"
                    )
                bind_tool(shared_tool_control)
            if hand_training_controller is not None:
                bind_training_tool = getattr(
                    hand_training_controller,
                    "bind_tool_control",
                    None,
                )
                if not callable(bind_training_tool):
                    raise RuntimeError(
                        "Hand-training controller lacks typed sampling-tool control"
                    )
                bind_training_tool(shared_tool_control)
        self.petri_registry = petri_registry
        self.petri_artifact_root = (
            Path(petri_artifact_root) if petri_artifact_root is not None else None
        )
        self.capture_run_controller = capture_run_controller
        self.capture_dataset_exporter = capture_dataset_exporter
        self.safety_configurator = safety_configurator
        self.site_safety_gate = site_safety_gate
        if digital_twin_provider is None:
            try:
                from main.digital_twin import DigitalTwinSnapshotProvider
            except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                from digital_twin import (  # type: ignore[no-redef]
                    DigitalTwinSnapshotProvider,
                )

            digital_twin_provider = DigitalTwinSnapshotProvider(
                required_clearance_mm=float(
                    getattr(settings, "dual_depth_required_clearance_mm", 0.0)
                ),
                geometry_profile_sha256=getattr(
                    settings,
                    "dual_depth_geometry_profile_sha256",
                    "",
                ),
            )
        self.digital_twin_provider = digital_twin_provider
        self.trajectory_preflight = trajectory_preflight
        self.workspace_teach_recorder = workspace_teach_recorder
        self.workspace_teach_store = workspace_teach_store
        self.workspace_boundary_validator = workspace_boundary_validator
        self._ota_commissioning_evaluator = (
            ota_commissioning_evaluator or evaluate_auto_apply_commissioning
        )
        if settings.xarm_motion_enabled and isinstance(
            xarm_motion_adapter, XArmMotionAdapter
        ):
            xarm_motion_adapter.bind_pinned_safety_configurator(safety_configurator)
        self.last_valve_cycle: Any = None
        self._stop_event = threading.Event()
        self._ota_health_report_event = threading.Event()
        self._threads: List[threading.Thread] = []
        self._supervised_threads: List[threading.Thread] = []
        self._fatal_lock = threading.Lock()
        self._fatal_event = threading.Event()
        self._fatal_error_code = ""
        self._runtime_fatal_generation = 0
        self._started = False
        self._lock = threading.Lock()
        self._ota_lock = threading.Lock()
        self._ota_status_lock = threading.Lock()
        requested_auto_apply = bool(getattr(settings, "ota_auto_apply", False))
        self._ota_commissioning = OTACommissioningGate(
            requested=requested_auto_apply,
            permitted=False,
            blockers=(
                ("commissioning_artifact_invalid",) if requested_auto_apply else ()
            ),
        )
        self._ota_status: Mapping[str, Any] = {
            "configured": ota_updater is not None,
            "status": "idle" if ota_updater is not None else "unavailable",
            "current_version": str(getattr(settings, "current_version", "")),
            "available_version": "",
            "message": "",
            "error_code": "",
            "manifest_verification": "not_checked",
            "archive_digest_verification": "not_checked",
        }
        self._ota_admission_lock = threading.Lock()
        self._ota_admission_generation = 0
        self._ota_admission_lease: Optional[_OTAAdmissionLease] = None
        self._ota_admission_last_telemetry_sequence = 0
        self._ota_admission_last_camera_sequences: Mapping[str, int] = {}
        self._ota_admission_latched_reason = ""
        self._ota_admission_status: Mapping[str, Any] = {
            "schema_version": 1,
            "status": "inactive",
            "phase": "",
            "reason": "",
            "generation": 0,
            "validation_count": 0,
            "age_seconds": 0.0,
            "maximum_age_seconds": float(
                getattr(settings, "ota_admission_lease_seconds", 120.0)
            ),
            "evidence_sha256": "",
            "motion_authority": "none",
        }
        self._ota_history_sequence = 1
        self._ota_history: List[Mapping[str, Any]] = [
            {
                "sequence": 1,
                "status": self._ota_status["status"],
                "current_version": self._ota_status["current_version"],
                "available_version": "",
                "error_code": "",
            }
        ]
        self._registry_lock = threading.Lock()
        self._registry_status: Mapping[str, Any] = {
            "configured": readiness_client is not None,
            "verified": False,
            "ready": readiness_client is None,
            "status": "pending" if readiness_client is not None else "off",
        }
        self._xarm_status_lock = threading.Lock()
        self._xarm_status: Mapping[str, Any] = {
            "schema_version": _XARM_STATUS_SCHEMA_VERSION,
            "configured": metric_source is not None,
            "available": False,
            "connected": False,
            "healthy": False,
            "state": None,
            "mode": None,
            "moving": None,
            "error_code": None,
            "warning_code": None,
            "reduced_mode_enabled": False,
            "reduced_configuration_valid": False,
            "reduced_safety_boundary_enabled": False,
            "collision_rebound_disabled": False,
            "conservative_joint_envelope": False,
            "control_envelope_ready": False,
            "fault_category": "none",
            "fault_guidance": "",
            "axis_count": None,
            "device_type": None,
            "metrics": _empty_xarm_metrics(),
            "sampled_at_monotonic_s": 0.0,
            "sample_error": "awaiting_sample" if metric_source is not None else "",
        }
        self._xarm_pose_sequence = 0
        self._motion_lock = threading.Lock()
        self._motion_abort_event = threading.Event()
        self._motion_stop_generation = 0
        self._motion_authorization_generation = 0
        self._motion_authorization_expires_at = 0.0
        self._motion_armed = False
        self._motion_live = False
        self._motion_fault_reason = ""
        self._motion_search_confirmation_lock = threading.Lock()
        self._motion_search_challenge = ""
        self._motion_search_confirmation_expires_at = 0.0
        self._motion_search_stop_generation = -1
        self._motion_search_authorization_generation = -1
        self._safety_configuration_lock = threading.Lock()
        self._safety_configuration_challenge = ""
        self._safety_configuration_expires_at = 0.0
        self._safety_configuration_stop_generation = -1
        self._safety_configuration_state = (
            "requires_configuration"
            if safety_configurator is not None
            else "unavailable"
        )
        self._safety_configuration_generation = 0
        self._safety_configuration_error = ""
        self._safety_configuration_fault_latched = False
        safety_journal = (
            Path(getattr(settings, "state_dir", "/var/lib/labcobot"))
            / "safety-configuration.json"
        )
        if safety_configurator is not None and safety_journal.exists():
            try:
                persisted = json.loads(safety_journal.read_text(encoding="utf-8"))
            except Exception:
                persisted = {"state": "fault", "error": "journal_invalid"}
            if (
                not isinstance(persisted, Mapping)
                or persisted.get("state")
                in {
                    "applying",
                    "aborted_partial",
                    "fault",
                }
                or persisted.get("profile_sha256")
                != safety_configurator.profile.profile_sha256
            ):
                self._set_safety_configuration_state_locked("error")
                self._safety_configuration_fault_latched = True
                self._safety_configuration_error = str(
                    persisted.get("error")
                    if isinstance(persisted, Mapping)
                    else "journal_invalid"
                )[:48]
        self._monotonic = monotonic
        self._petri_cancel_event = threading.Event()
        self._petri_run_lock = threading.Lock()
        self._operations_lock = threading.Lock()
        self._petri_confirmation_challenge = ""
        self._petri_confirmation_expires_at = 0.0
        self._petri_confirmation_stop_generation = -1
        self._petri_confirmation_context: Tuple[Any, ...] = ()
        self._petri_status: Mapping[str, Any] = {
            "state": "ready" if self.petri_process_configured else "unavailable",
            "completed_steps": 0,
            "total_steps": 0,
            "estimated_seconds": 0.0,
            "started_at": 0.0,
            "message": "",
            "error_code": "",
        }
        self._recovery_confirmation_challenge = ""
        self._recovery_confirmation_expires_at = 0.0
        self._recovery_confirmation_stop_generation = -1
        self._recovery_confirmation_context: Tuple[Any, ...] = ()
        self._recovery_status: Mapping[str, Any] = {
            "state": "idle" if recovery_controller is not None else "unavailable",
            "message": "",
            "error_code": "",
        }
        self._manual_review_lock = threading.Lock()
        self._manual_review_challenge = ""
        self._manual_review_expires_at = 0.0
        self._manual_review_stop_generation = -1
        self._manual_review_observation_id = ""
        self._manual_review_candidate: Mapping[str, Any] = {}
        self._manual_review_previewed = False
        self._capture_control_lock = threading.Lock()
        self._capture_operation_lock = threading.Lock()
        self._hand_training_operation_lock = threading.Lock()
        self._operation_transition_lock = threading.Lock()
        self._software_stop_lock = threading.Lock()
        self._capture_confirmation_expires_at = 0.0
        self._capture_confirmation_challenge = ""
        self._capture_confirmation_stop_generation = -1
        self._capture_confirmation_fingerprint: Tuple[Any, ...] = ()
        self._workspace_teach_lock = threading.RLock()
        self._workspace_teach_finalize_challenge = ""
        self._workspace_teach_finalize_expires_at = 0.0
        self._workspace_teach_finalize_session_id = ""
        self._workspace_teach_finalize_proposal_sha256 = ""
        self._workspace_teach_finalize_stop_generation = -1
        self._workspace_teach_persisting_token = ""
        self._workspace_teach_persisting_session_id = ""
        self._workspace_teach_persisting_proposal_sha256 = ""
        self._workspace_teach_persisting_stop_generation = -1
        self._workspace_teach_invalidation_pending = threading.Event()
        self._workspace_teach_generation = 0
        # Protected by ``_operation_transition_lock``.  This reserves the
        # physical-operation lane while the operator can move the arm by hand
        # in controller mode 2; it never enables or commands robot motion.
        self._workspace_teach_owner_active = workspace_teach_recorder is not None
        initial_teach_snapshot = getattr(workspace_teach_recorder, "snapshot", None)
        if callable(initial_teach_snapshot):
            try:
                initial_teach_state = initial_teach_snapshot().get("state")
            except Exception:
                initial_teach_state = None
            if initial_teach_state in {
                "idle",
                "cancelled",
                "invalidated",
                "proposed",
            }:
                self._workspace_teach_owner_active = False
        self._restart_callback: Optional[Callable[[], None]] = None
        self._restart_pending = False
        self._ota_startup_update_id: Optional[str] = None
        self._ota_boot_health_lock = threading.Lock()
        self._ota_boot_health_generation = 0
        self._ota_boot_health_fingerprint = ""
        self._ota_runtime_tick_failure_events = 0
        self._ota_runtime_max_consecutive_errors = 0
        self._ota_boot_health_last: Mapping[str, Any] = {
            "schema_version": 1,
            "status": "not_pending" if ota_updater is not None else "unavailable",
            "pending": False,
            "ready": False,
            "generation": 0,
            "update_id_sha256": "",
            "target_version": "",
            "target_source_revision": "",
            "motion_release_required": self.motion_release_required,
            "motion_release_gate_ignored": True,
            "checks": {},
            "problems": [],
        }
        set_status_provider = getattr(
            self.mjpeg_server,
            "set_status_provider",
            None,
        )
        if callable(set_status_provider):
            set_status_provider(self.runtime_status)
        set_update_requester = getattr(
            self.mjpeg_server,
            "set_update_requester",
            None,
        )
        if callable(set_update_requester):
            set_update_requester(
                self.request_update_check if self.ota_updater is not None else None
            )
        set_capture_controls = getattr(
            self.mjpeg_server,
            "set_capture_controls",
            None,
        )
        if callable(set_capture_controls):
            set_capture_controls(
                self.request_capture_start,
                self.request_capture_stop,
            )
        set_hand_training_controls = getattr(
            self.mjpeg_server,
            "set_hand_training_controls",
            None,
        )
        if callable(set_hand_training_controls):
            set_hand_training_controls(
                starter=self.request_hand_training_start,
                tool=self.request_hand_training_tool,
                ender=self.request_hand_training_end,
            )
        set_software_stop = getattr(
            self.mjpeg_server,
            "set_software_stop",
            None,
        )
        if callable(set_software_stop):
            set_software_stop(self.request_software_stop)
        set_motion_search_control = getattr(
            self.mjpeg_server,
            "set_motion_search_control",
            None,
        )
        if callable(set_motion_search_control):
            set_motion_search_control(self.request_dynamic_valve_search)
        set_safety_configuration_control = getattr(
            self.mjpeg_server,
            "set_safety_configuration_control",
            None,
        )
        if callable(set_safety_configuration_control):
            set_safety_configuration_control(self.request_safety_configuration)
        set_operator_controls = getattr(
            self.mjpeg_server,
            "set_operator_controls",
            None,
        )
        if callable(set_operator_controls):
            set_operator_controls(
                petri_starter=self.request_petri_start,
                registration_verifier=self.request_registration_verification,
                recovery_starter=self.request_reviewed_recovery,
                manual_reviewer=self.request_manual_review,
                manual_review_previewer=self.manual_review_preview,
            )
        set_workspace_teach_controls = getattr(
            self.mjpeg_server,
            "set_workspace_teach_controls",
            None,
        )
        if callable(set_workspace_teach_controls):
            set_workspace_teach_controls(
                starter=self.request_workspace_teach_start,
                capturer=self.request_workspace_teach_capture,
                canceller=self.request_workspace_teach_cancel,
                finalizer=self.request_workspace_teach_finalize,
            )
        set_tenant_auth_controls = getattr(
            self.mjpeg_server,
            "set_tenant_auth_controls",
            None,
        )
        if callable(set_tenant_auth_controls):
            set_tenant_auth_controls(
                login=self.request_tenant_login,
                logout=self.request_tenant_logout,
            )
        if self.trajectory_preflight is not None and hasattr(
            self.trajectory_preflight,
            "evidence_sink",
        ):
            # Bind producer evidence to the exact cached robot sample before
            # the digital-twin provider stores it.  The callback remains
            # visualization-only and cannot grant motion authority.
            self.trajectory_preflight.evidence_sink = (
                self._record_bound_clearance_evidence
            )

    @property
    def ota_configured(self) -> bool:
        return self.ota_updater is not None

    @property
    def offload_configured(self) -> bool:
        return self.offload_client is not None

    @property
    def tenant_login_configured(self) -> bool:
        return self.tenant_auth_client is not None

    @property
    def eye_in_hand_configured(self) -> bool:
        return self.tool_workspace_mapper is not None

    @property
    def dynamic_valve_configured(self) -> bool:
        return self.valve_controller is not None

    @property
    def petri_process_configured(self) -> bool:
        return callable(getattr(self.petri_process_controller, "start", None))

    def _petri_process_durable_status(self) -> Mapping[str, Any]:
        """Read a bounded durable-controller projection, when provided.

        Legacy/injected test controllers without a ``status`` method remain
        supported.  A malformed or failing durable status is fail-closed and
        blocks every subsequent physical admission.
        """

        reader = getattr(self.petri_process_controller, "status", None)
        if not callable(reader):
            return {
                "state": "IDLE",
                "run_id": "",
                "active": False,
                "recovery_required": False,
                "local_evidence_committed": False,
                "upload_queued": False,
                "current_plate_id": "",
                "transition_sequence": 0,
                "error_code": "",
            }
        try:
            raw = reader()
        except Exception:
            LOGGER.error("Could not read durable Petri process state", exc_info=True)
            raw = {}
        allowed_states = {
            "IDLE",
            "PREFLIGHT",
            "AUTHORIZED",
            "HOME",
            "LOCATE_TRAY",
            "IDENTIFY_PLATES",
            "APPROACH",
            "PICK_LID",
            "VERIFY_GRASP",
            "CAPTURE",
            "RETURN_LID",
            "VERIFY_RELEASE",
            "NEXT_PLATE",
            "RETURN_HOME",
            "LOCAL_COMMIT",
            "QUEUE_UPLOAD",
            "COMPLETE",
            "STOPPING",
            "CANCELLED",
            "FAULT_LOCKED",
            "RECOVERY_REQUIRED",
        }
        if not isinstance(raw, Mapping) or raw.get("state") not in allowed_states:
            return {
                "state": "FAULT_LOCKED",
                "run_id": "",
                "active": True,
                "recovery_required": True,
                "local_evidence_committed": False,
                "upload_queued": False,
                "current_plate_id": "",
                "transition_sequence": 0,
                "error_code": "petri_state_unavailable",
            }
        run_id = _bounded_public_identifier(raw.get("run_id"), limit=32)
        plate_id = _bounded_public_identifier(raw.get("current_plate_id"), limit=64)
        sequence = _bounded_nonnegative_integer(
            raw.get("transition_sequence"), maximum=1_000_000
        )
        return {
            "state": raw["state"],
            "run_id": run_id,
            "active": raw.get("active") is True,
            "recovery_required": raw.get("recovery_required") is True,
            "local_evidence_committed": raw.get("local_evidence_committed") is True,
            "upload_queued": raw.get("upload_queued") is True,
            "current_plate_id": plate_id,
            "transition_sequence": sequence or 0,
            "error_code": _bounded_error_code(raw.get("error_code")),
        }

    def _petri_durable_owner_blocks_physical_operation(self) -> bool:
        status = self._petri_process_durable_status()
        return bool(status["active"] or status["recovery_required"])

    @property
    def motion_live_capable(self) -> bool:
        # Deliberately false until a root-owned/asymmetric trust chain can issue
        # and the concrete adapter can atomically consume a typed one-use permit.
        return False

    @property
    def motion_release_required(self) -> bool:
        """Return whether this deployment contains a concrete motor owner."""

        return bool(
            getattr(self.settings, "xarm_motion_enabled", False)
            or getattr(self.settings, "capture_run_enabled", False)
        )

    def motion_is_armed(self) -> bool:
        self._expire_motion_authorization_if_needed()
        with self._motion_lock:
            return self._motion_armed

    def motion_is_live(self) -> bool:
        self._expire_motion_authorization_if_needed()
        with self._motion_lock:
            return self._motion_live

    def _formal_motion_release(self) -> Mapping[str, Any]:
        """Return the sanitized Device Manager handover cached by readiness."""

        with self._registry_lock:
            registry = dict(self._registry_status)
        registry_features = registry.get("features")
        registry_features = (
            registry_features if isinstance(registry_features, Mapping) else {}
        )
        formal_release = registry_features.get("motion_release")
        return dict(formal_release) if isinstance(formal_release, Mapping) else {}

    def motion_status(
        self,
        *,
        xarm_snapshot: Optional[Mapping[str, Any]] = None,
        safety_snapshot: Optional[Mapping[str, Any]] = None,
    ) -> Mapping[str, Any]:
        self._expire_motion_authorization_if_needed()
        now = float(self._monotonic())
        last_cycle = self.last_valve_cycle
        release_required = self.motion_release_required
        formal_release = self._formal_motion_release()
        release_valid = formal_release.get("ready") is True
        with self._motion_lock:
            if self._motion_fault_reason:
                state = "FAULT_LOCKED"
            elif self._motion_armed and self._motion_live:
                state = "ARMED_LIVE"
            else:
                state = "LOCKED"
            result = {
                "state": state,
                "capable": self.motion_live_capable,
                "search_configured": self.dynamic_valve_configured,
                "release_required": release_required,
                "release_gate": (
                    _MOTION_RELEASE_BLOCKER
                    if release_required and not release_valid
                    else ""
                ),
                "release_valid": release_valid,
                "release_source": ("device_manager_handover" if release_valid else ""),
                "release_id": str(formal_release.get("release_id") or ""),
                "release_evidence_sha256": str(
                    formal_release.get("evidence_sha256") or ""
                ),
                "armed": self._motion_armed,
                "live": self._motion_live,
                "fault": self._motion_fault_reason,
                "authorization_expires_in_seconds": max(
                    0.0,
                    self._motion_authorization_expires_at - now,
                ),
                "stop_generation": self._motion_stop_generation,
                "authorization_watchdog_interval_seconds": (
                    _MOTION_AUTHORIZATION_WATCHDOG_SECONDS
                ),
                "recovery_commissioned": self.recovery_controller is not None,
                "last_valve_cycle": self._bounded_valve_cycle_status(last_cycle),
                "last_target_review": self._last_target_review(last_cycle),
            }
        permit_context = getattr(
            self.xarm_motion_adapter,
            "motion_permit_context_status",
            None,
        )
        result["permit_context"] = (
            dict(permit_context())
            if callable(permit_context)
            else {
                "configured": False,
                "ready": False,
                "runtime_instance_id": "",
                "authorization_epoch": 0,
            }
        )
        result["action_allowed"] = self._motion_search_action_allowed(
            motion=result,
            xarm_snapshot=xarm_snapshot,
            safety_snapshot=safety_snapshot,
        )
        return result

    @staticmethod
    def _bounded_valve_cycle_status(result: Any) -> Optional[str]:
        if result is None:
            return None
        value = getattr(result, "status", None)
        return (
            value
            if isinstance(value, str) and value in _VALVE_CYCLE_STATES
            else "unknown"
        )

    def _motion_search_action_allowed(
        self,
        *,
        motion: Optional[Mapping[str, Any]] = None,
        xarm_snapshot: Optional[Mapping[str, Any]] = None,
        safety_snapshot: Optional[Mapping[str, Any]] = None,
    ) -> bool:
        """Keep Search locked until the typed release permit exists."""

        # This gate is intentionally unconditional.  Positive branding,
        # settings, telemetry, safety readback, and artifacts are necessary but
        # cannot replace the missing signed, measured one-use release permit.
        del motion, xarm_snapshot, safety_snapshot
        return False

    def safety_configuration_status(
        self,
        *,
        xarm_snapshot: Optional[Mapping[str, Any]] = None,
    ) -> Mapping[str, Any]:
        """Return the bounded pinned-profile/readback configuration state."""

        configurator = self.safety_configurator
        profile = getattr(configurator, "profile", None)
        digest = _bounded_public_identifier(
            getattr(profile, "profile_sha256", ""), limit=64
        )
        if configurator is None or profile is None:
            return {
                "schema_version": 1,
                "capable": False,
                "profile_loaded": False,
                "profile_sha256": "",
                "state": "unavailable",
                "preflight": dict(_empty_safety_preflight()),
                "profile": {},
                "readback": dict(_empty_safety_readback()),
                "configured": False,
                "search_admission_ready": False,
                "remaining_search_gates": self._remaining_search_gates(
                    safety_configured=False,
                    xarm_snapshot=xarm_snapshot,
                ),
                "last_error": "",
            }
        with self._motion_lock:
            motion_active = self._motion_armed or self._motion_live
        safety_configuring = self._safety_configuration_state == "configuring"
        if (
            motion_active
            or self._capture_operation_lock.locked()
            or self._petri_run_lock.locked()
            or self._petri_durable_owner_blocks_physical_operation()
            or safety_configuring
        ):
            # Do not wait behind configuration SDK I/O merely to render health.
            # STOP generation independently invalidates an in-flight challenge.
            error = self._safety_configuration_error
            fault_latched = self._safety_configuration_fault_latched
            return {
                "schema_version": 1,
                "capable": True,
                "profile_loaded": True,
                "profile_sha256": digest,
                "state": "error" if fault_latched else "unsafe",
                "preflight": dict(_empty_safety_preflight()),
                "profile": dict(profile.public_profile()),
                "readback": dict(_empty_safety_readback()),
                "configured": False,
                "search_admission_ready": False,
                "remaining_search_gates": ["physical_operation_active"],
                "last_error": error,
            }
        try:
            preflight = dict(configurator.preflight())
        except Exception:
            LOGGER.warning("Lite6 safety preflight failed", exc_info=True)
            preflight = dict(_empty_safety_preflight())
        try:
            readback = dict(configurator.readback())
        except Exception:
            readback = dict(_empty_safety_readback())
        configured = readback.get("verified") is True
        with self._safety_configuration_lock:
            state = self._safety_configuration_state
            error = self._safety_configuration_error
            fault_latched = self._safety_configuration_fault_latched
        if fault_latched:
            configured = False
            state = "error"
        elif configured and state != "configuring":
            state = "configured"
        elif state == "requires_configuration" and preflight.get("ready") is True:
            state = "ready_to_configure"
        elif (
            state not in {"configuring", "error"} and preflight.get("ready") is not True
        ):
            state = "unsafe"
        remaining = self._remaining_search_gates(
            safety_configured=configured,
            xarm_snapshot=xarm_snapshot,
        )
        return {
            "schema_version": 1,
            "capable": True,
            "profile_loaded": True,
            "profile_sha256": digest,
            "state": state,
            "preflight": preflight,
            "profile": dict(profile.public_profile()),
            "readback": readback,
            "configured": configured,
            "search_admission_ready": configured and not remaining,
            "remaining_search_gates": remaining,
            "last_error": error,
        }

    def controller_firmware_status(
        self,
        *,
        xarm_snapshot: Optional[Mapping[str, Any]] = None,
    ) -> Mapping[str, Any]:
        """Expose commissioned-versus-observed controller firmware.

        The commissioned value comes only from the root-owned, hash-pinned
        Lite6 safety profile.  The observed value comes from bounded cached
        telemetry.  This path never calls the xArm SDK or grants motion.
        """

        try:
            from main.controller_firmware import controller_firmware_status
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from controller_firmware import (  # type: ignore[no-redef]
                controller_firmware_status,
            )

        profile = getattr(self.safety_configurator, "profile", None)
        expected = getattr(profile, "expected_firmware_version", "")
        xarm = (
            dict(xarm_snapshot)
            if isinstance(xarm_snapshot, Mapping)
            else dict(self.xarm_status())
        )
        try:
            return dict(controller_firmware_status(expected, xarm))
        except Exception:
            LOGGER.error("Controller firmware status evaluation failed", exc_info=True)
            return {
                "schema": "labcobot.xarm-controller-firmware-status.v1",
                "configured": False,
                "ready": False,
                "commissioned_version": "",
                "observed_version": "",
                "matches": False,
                "maintenance_required": False,
                "maintenance_action": "",
                "motion_authority": "none",
                "blockers": ["controller_firmware_unavailable"],
            }

    def _remaining_search_gates(
        self,
        *,
        safety_configured: bool,
        xarm_snapshot: Optional[Mapping[str, Any]] = None,
    ) -> List[str]:
        gates: List[str] = []
        if self._formal_motion_release().get("ready") is not True:
            gates.append(_MOTION_RELEASE_BLOCKER)
        if not safety_configured:
            gates.append("safety_boundary_configuration")
        if (
            self.settings.workspace_boundary_validation_enabled
            and not self._workspace_boundary_valid_for_current_proposal()
        ):
            gates.append("workspace_boundary_validation")
        if self._runtime_deployment_mode() not in {"production", "operator"}:
            gates.append("operator_deployment")
        if not self.motion_live_capable:
            gates.append("reviewed_motion_owner")
        with self._lock:
            if not self._started:
                gates.append("services_started")
        xarm = dict(xarm_snapshot) if xarm_snapshot is not None else self.xarm_status()
        checks = (
            ("xarm_healthy", xarm.get("healthy") is True),
            ("xarm_telemetry_fresh", xarm.get("fresh") is True),
            ("xarm_stationary", xarm.get("moving") is False),
            ("reduced_mode", xarm.get("reduced_mode_enabled") is True),
            (
                "reduced_configuration",
                xarm.get("reduced_configuration_valid") is True,
            ),
            (
                "joint_envelope",
                xarm.get("conservative_joint_envelope") is True,
            ),
            ("control_envelope", xarm.get("control_envelope_ready") is True),
        )
        gates.extend(name for name, passed in checks if not passed)
        return gates

    def request_safety_configuration(
        self,
        challenge: Optional[str] = None,
    ) -> Mapping[str, Any]:
        """Two-step, one-use admission to the pinned safety-only setter seam."""

        configurator = self.safety_configurator
        if configurator is None:
            return {"status": "unavailable"}
        supplied = challenge if isinstance(challenge, str) else ""
        if supplied and not re.fullmatch(r"[0-9a-f]{32}", supplied):
            return {"status": "confirmation_required"}
        with self._safety_configuration_lock:
            now = float(self._monotonic())
            if not supplied:
                self._clear_safety_configuration_challenge_locked()
                if self._safety_configuration_busy_or_unsafe(configurator):
                    return {"status": "unsafe"}
                with self._motion_lock:
                    stop_generation = self._motion_stop_generation
                token = secrets.token_hex(16)
                self._safety_configuration_challenge = token
                self._safety_configuration_expires_at = (
                    now + _SAFETY_CONFIGURATION_CONFIRMATION_SECONDS
                )
                self._safety_configuration_stop_generation = stop_generation
                return {
                    "status": "confirm",
                    "challenge": token,
                    "expires_in_seconds": int(
                        _SAFETY_CONFIGURATION_CONFIRMATION_SECONDS
                    ),
                    "profile_sha256": configurator.profile.profile_sha256,
                }
            with self._motion_lock:
                generation_matches = (
                    self._safety_configuration_stop_generation
                    == self._motion_stop_generation
                )
            confirmed = bool(
                self._safety_configuration_challenge
                and self._safety_configuration_expires_at >= now
                and generation_matches
                and secrets.compare_digest(
                    self._safety_configuration_challenge,
                    supplied,
                )
            )
            confirmed_generation = self._safety_configuration_stop_generation
            self._clear_safety_configuration_challenge_locked()
            if not confirmed:
                return {"status": "confirmation_required"}
            if self._safety_configuration_busy_or_unsafe(configurator):
                return {"status": "unsafe"}
            with self._motion_lock:
                if confirmed_generation != self._motion_stop_generation:
                    return {"status": "confirmation_required"}
            self._set_safety_configuration_state_locked("configuring")
            self._safety_configuration_error = ""
            if not self._operation_transition_lock.acquire(blocking=False):
                self._set_safety_configuration_state_locked("requires_configuration")
                return {"status": "busy"}
            try:
                if self._workspace_teach_invalidation_pending.is_set():
                    self._invalidate_workspace_teach_locked()
                if (
                    self._workspace_teach_blocks_physical_operation()
                    or self._ota_lock.locked()
                    or self._capture_operation_lock.locked()
                ):
                    self._set_safety_configuration_state_locked(
                        "requires_configuration"
                    )
                    return {"status": "busy"}
                with self._motion_lock:
                    generation_matches = (
                        confirmed_generation == self._motion_stop_generation
                        and not self._motion_armed
                        and not self._motion_live
                    )
                if not generation_matches:
                    self._set_safety_configuration_state_locked(
                        "requires_configuration"
                    )
                    return {"status": "confirmation_required"}
                configurator.before_write = lambda: (
                    confirmed_generation == self._motion_stop_generation
                )
                # This is the final generation check before the durable
                # applying marker.  A STOP after this point is classified in
                # the exception/success paths below and can never strand an
                # applying record.
                with self._motion_lock:
                    generation_matches = (
                        confirmed_generation == self._motion_stop_generation
                        and not self._motion_armed
                        and not self._motion_live
                    )
                if not generation_matches:
                    self._set_safety_configuration_state_locked(
                        "requires_configuration"
                    )
                    return {"status": "confirmation_required"}
                if self.xarm_motion_adapter is not None:
                    # A controller-configuration transaction retires every
                    # outstanding motion permit even when it reapplies the
                    # same reviewed profile.
                    self.xarm_motion_adapter.lock_commands()
                self._write_safety_configuration_journal("applying")
                configurator.configure()
                with self._motion_lock:
                    generation_matches = (
                        confirmed_generation == self._motion_stop_generation
                        and not self._motion_armed
                        and not self._motion_live
                    )
                if not generation_matches:
                    partial = bool(
                        getattr(
                            configurator,
                            "last_transaction_writes_started",
                            False,
                        )
                    )
                    self._safety_configuration_fault_latched = partial
                    self._set_safety_configuration_state_locked(
                        "error" if partial else "requires_configuration"
                    )
                    self._safety_configuration_error = (
                        "stop_during_configuration" if partial else ""
                    )
                    self._write_safety_configuration_journal(
                        "aborted_partial" if partial else "aborted",
                        error=self._safety_configuration_error,
                    )
                    return {"status": "aborted"}
            except Exception as exc:
                with self._motion_lock:
                    stopped_during_configuration = (
                        confirmed_generation != self._motion_stop_generation
                    )
                partial = bool(
                    getattr(
                        configurator,
                        "last_transaction_writes_started",
                        False,
                    )
                )
                if stopped_during_configuration:
                    LOGGER.info("Lite6 safety configuration aborted by software STOP")
                    self._safety_configuration_fault_latched = partial
                    self._set_safety_configuration_state_locked(
                        "error" if partial else "requires_configuration"
                    )
                    self._safety_configuration_error = (
                        "stop_during_configuration" if partial else ""
                    )
                    self._write_safety_configuration_journal(
                        "aborted_partial" if partial else "aborted",
                        error=self._safety_configuration_error,
                    )
                    return {"status": "aborted"}
                LOGGER.error("Lite6 safety configuration failed", exc_info=True)
                self._set_safety_configuration_state_locked("error")
                self._safety_configuration_fault_latched = True
                self._safety_configuration_error = type(exc).__name__[:48]
                self._write_safety_configuration_journal(
                    "fault",
                    error=self._safety_configuration_error,
                )
                return {"status": "error"}
            finally:
                configurator.before_write = lambda: True
                self._operation_transition_lock.release()
                if self._workspace_teach_invalidation_pending.is_set():
                    self._invalidate_workspace_teach(
                        blocking=False,
                        request=False,
                    )
            self._set_safety_configuration_state_locked("configured")
            self._safety_configuration_fault_latched = False
            self._write_safety_configuration_journal("configured")
            return {
                "status": "configured",
                "profile_sha256": configurator.profile.profile_sha256,
            }

    def _set_safety_configuration_state_locked(self, state: str) -> None:
        """Advance the OTA-visible generation on each real safety transition."""

        safe_state = str(state)[:48]
        if safe_state == self._safety_configuration_state:
            return
        self._safety_configuration_state = safe_state
        self._safety_configuration_generation = min(
            self._safety_configuration_generation + 1,
            1_000_000_000,
        )

    def _safety_configuration_busy_or_unsafe(self, configurator: Any) -> bool:
        if (
            self.settings.workspace_boundary_validation_enabled
            and not self._workspace_boundary_valid_for_current_proposal()
        ):
            return True
        if (
            self._restart_pending
            or self._fatal_event.is_set()
            or self._capture_operation_lock.locked()
            or self._operation_transition_lock.locked()
            or self._ota_lock.locked()
            or self._petri_run_lock.locked()
            or self._petri_durable_owner_blocks_physical_operation()
            or self._workspace_teach_blocks_physical_operation()
        ):
            return True
        with self._motion_lock:
            if self._motion_armed or self._motion_live or self._motion_fault_reason:
                return True
        try:
            return configurator.preflight().get("ready") is not True
        except Exception:
            return True

    def _clear_safety_configuration_challenge_locked(self) -> None:
        self._safety_configuration_challenge = ""
        self._safety_configuration_expires_at = 0.0
        self._safety_configuration_stop_generation = -1

    def _write_safety_configuration_journal(
        self,
        state: str,
        *,
        error: str = "",
    ) -> None:
        """Persist the applying/fault latch before/after controller writes."""

        profile = getattr(self.safety_configurator, "profile", None)
        digest = str(getattr(profile, "profile_sha256", ""))
        path = Path(self.settings.state_dir) / "safety-configuration.json"
        path.parent.mkdir(parents=True, exist_ok=True)
        temporary = path.with_name(path.name + ".tmp")
        payload = json.dumps(
            {
                "schema_version": 1,
                "state": state,
                "profile_sha256": digest,
                "error": str(error)[:48],
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        descriptor = os.open(
            str(temporary),
            os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
            0o600,
        )
        try:
            os.write(descriptor, payload)
            os.fsync(descriptor)
        finally:
            os.close(descriptor)
        os.replace(str(temporary), str(path))
        directory_descriptor = os.open(str(path.parent), os.O_RDONLY)
        try:
            os.fsync(directory_descriptor)
        finally:
            os.close(directory_descriptor)

    @staticmethod
    def _last_target_review(result: Any) -> Optional[Mapping[str, Any]]:
        """Return bounded, secret-free target/plan details for the Pi UI."""

        if result is None:
            return None
        plan = getattr(result, "plan", None)
        target = getattr(plan, "target", None)
        joint_trajectory = getattr(plan, "joint_trajectory", None)
        mapped_xyz = getattr(target, "center_xyz", None)
        mapped_xyz_review = None
        if mapped_xyz is not None:
            try:
                coordinates = tuple(float(value) for value in mapped_xyz)
            except (TypeError, ValueError, OverflowError):
                coordinates = ()
            if len(coordinates) == 3 and all(
                math.isfinite(value) for value in coordinates
            ):
                mapped_xyz_review = list(coordinates)

        confidence = None
        try:
            confidence_candidate = float(getattr(target, "confidence"))
        except (AttributeError, TypeError, ValueError, OverflowError):
            pass
        else:
            if (
                math.isfinite(confidence_candidate)
                and 0.0 <= confidence_candidate <= 1.0
            ):
                confidence = confidence_candidate

        def _bounded_count(value: Any) -> int:
            try:
                return min(max(int(value), 0), 1_000_000)
            except (TypeError, ValueError, OverflowError):
                return 0

        target_id = getattr(result, "target_id", None)
        raw_status = getattr(result, "status", "unknown")
        safe_status = (
            raw_status
            if isinstance(raw_status, str) and raw_status in _VALVE_CYCLE_STATES
            else "unknown"
        )
        return {
            "status": safe_status,
            "target_id": (
                _bounded_public_identifier(target_id, limit=120)
                if target_id is not None
                else None
            ),
            "mapped_xyz_mm": mapped_xyz_review,
            "confidence": confidence,
            "remote_confirmed": bool(
                getattr(result, "used_remote_inference", False) and target is not None
            ),
            "tracks_considered": _bounded_count(
                getattr(result, "tracks_considered", 0)
            ),
            "cartesian_waypoints": _bounded_count(
                len(getattr(plan, "cartesian_waypoints", ()) or ())
            ),
            "joint_waypoints": _bounded_count(
                len(getattr(joint_trajectory, "frames", ()) or ())
            ),
        }

    @staticmethod
    def _unavailable_outbox_status() -> Mapping[str, Any]:
        return {
            "schema_version": 1,
            "pending_count": 0,
            "queue_bytes": 0,
            "leased_count": 0,
            "oldest_lease_age_seconds": None,
            "retry_count": 0,
            "dead_letter_count": 0,
            "dead_letter_bytes": 0,
            "receipt_count": 0,
            "last_acknowledged_at": None,
            "last_acknowledgement_age_seconds": None,
            "capacity_ok": False,
        }

    @classmethod
    def _bounded_outbox_status(
        cls,
        raw: Any,
    ) -> Optional[Mapping[str, Any]]:
        if not isinstance(raw, Mapping) or raw.get("schema_version") != 1:
            return None

        def count(name: str, maximum: int) -> int:
            value = raw.get(name)
            if (
                isinstance(value, bool)
                or not isinstance(value, int)
                or not 0 <= value <= maximum
            ):
                raise ValueError("invalid outbox counter")
            return value

        def optional_number(name: str, maximum: float) -> Optional[float]:
            value = raw.get(name)
            if value is None:
                return None
            if isinstance(value, bool) or not isinstance(value, (int, float)):
                raise ValueError("invalid outbox timestamp")
            result = float(value)
            if not math.isfinite(result) or not 0.0 <= result <= maximum:
                raise ValueError("invalid outbox timestamp")
            return result

        try:
            result = {
                "schema_version": 1,
                "pending_count": count("pending_count", 1_000_000_000),
                "queue_bytes": count("queue_bytes", 10_000_000_000_000),
                "leased_count": count("leased_count", 1_000_000_000),
                "oldest_lease_age_seconds": optional_number(
                    "oldest_lease_age_seconds", 315_576_000.0
                ),
                "retry_count": count("retry_count", 1_000_000_000),
                "dead_letter_count": count("dead_letter_count", 1_000_000_000),
                "dead_letter_bytes": count("dead_letter_bytes", 10_000_000_000_000),
                "receipt_count": count("receipt_count", 1_000_000_000),
                "last_acknowledged_at": optional_number(
                    "last_acknowledged_at", 100_000_000_000.0
                ),
                "last_acknowledgement_age_seconds": optional_number(
                    "last_acknowledgement_age_seconds", 315_576_000.0
                ),
                "capacity_ok": raw.get("capacity_ok"),
            }
        except ValueError:
            return None
        if type(result["capacity_ok"]) is not bool:
            return None
        return result

    def _datahub_runtime_status(self) -> Mapping[str, Any]:
        result = {
            "configured": self.datahub is not None,
            "available": False,
            "pending": 0,
            "dead_letters": 0,
            "dataset_binding_required": False,
            "dataset_binding_verified": False,
            "dataset_binding_mismatch": False,
            "outbox": dict(self._unavailable_outbox_status()),
        }
        if self.datahub is None:
            return result
        status_reader = getattr(self.datahub, "status", None)
        if not callable(status_reader):
            return result
        try:
            raw = status_reader()
        except Exception:
            return result
        if not isinstance(raw, Mapping) or raw.get("schema_version") != 1:
            return result
        binding_fields = (
            "dataset_binding_required",
            "dataset_binding_verified",
            "dataset_binding_mismatch",
        )
        if any(type(raw.get(name)) is not bool for name in binding_fields):
            return result
        outbox = self._bounded_outbox_status(raw.get("outbox"))
        if outbox is None:
            return result
        result.update(
            {
                "available": True,
                "pending": outbox["pending_count"],
                "dead_letters": outbox["dead_letter_count"],
                "dataset_binding_required": raw["dataset_binding_required"],
                "dataset_binding_verified": raw["dataset_binding_verified"],
                "dataset_binding_mismatch": raw["dataset_binding_mismatch"],
                "outbox": dict(outbox),
            }
        )
        return result

    def tenant_auth_status(self) -> Mapping[str, Any]:
        """Return the local user-session state without credentials or tokens."""

        def unavailable(*, configured: bool, error: str = "") -> Mapping[str, Any]:
            return {
                "schema_version": 1,
                "configured": configured,
                "state": "error" if configured else "unavailable",
                "tenant_url": "",
                "tenant": "",
                "username": "",
                "display_name": "",
                "access_expires_in": 0,
                "refresh_expires_in": 0,
                "session_persisted": False,
                "last_error": error,
            }

        client = self.tenant_auth_client
        if client is None:
            return unavailable(configured=False)
        try:
            value = client.status()
        except Exception:
            return unavailable(configured=True, error="status_unavailable")
        expected = {
            "schema_version",
            "configured",
            "state",
            "tenant_url",
            "tenant",
            "username",
            "display_name",
            "access_expires_in",
            "refresh_expires_in",
            "session_persisted",
            "last_error",
        }
        if not isinstance(value, Mapping) or set(value) != expected:
            return unavailable(configured=True, error="status_invalid")
        state = value.get("state")
        string_names = (
            "tenant_url",
            "tenant",
            "username",
            "display_name",
            "last_error",
        )
        strings = {name: value.get(name) for name in string_names}
        lifetimes = (
            value.get("access_expires_in"),
            value.get("refresh_expires_in"),
        )
        if (
            value.get("schema_version") != 1
            or value.get("configured") is not True
            or state
            not in {
                "logged_out",
                "authenticated",
                "refresh_required",
                "expired",
                "error",
                "unavailable",
            }
            or any(not isinstance(item, str) for item in strings.values())
            or len(strings["tenant_url"]) > 512
            or len(strings["tenant"]) > 128
            or len(strings["username"]) > 254
            or len(strings["display_name"]) > 254
            or len(strings["last_error"]) > 64
            or any(
                isinstance(item, bool)
                or not isinstance(item, int)
                or not 0 <= item <= 31_536_000
                for item in lifetimes
            )
            or not isinstance(value.get("session_persisted"), bool)
        ):
            return unavailable(configured=True, error="status_invalid")
        return {name: value[name] for name in expected}

    def request_tenant_login(
        self,
        tenant_url: str,
        username: str,
        password: str,
    ) -> Mapping[str, Any]:
        """Perform one bounded mobile login without retaining the password."""

        client = self.tenant_auth_client
        if client is None:
            return {"status": "unavailable"}
        try:
            status = client.login(tenant_url, username, password)
        except Exception as exc:
            code = str(getattr(exc, "code", "tenant_unavailable") or "")
            allowed = {
                "invalid_tenant_url",
                "insecure_tenant_url",
                "missing_credentials",
                "invalid_credentials",
                "tenant_change_requires_logout",
                "login_rejected",
                "invalid_response",
                "tenant_unavailable",
            }
            return {"status": code if code in allowed else "tenant_unavailable"}
        if not isinstance(status, Mapping) or status.get("state") != "authenticated":
            return {"status": "invalid_response"}
        response = {
            "status": "authenticated",
            "tenant_url": str(status.get("tenant_url") or "")[:512],
            "tenant": str(status.get("tenant") or "")[:128],
            "username": str(status.get("username") or "")[:254],
            "display_name": str(status.get("display_name") or "")[:254],
            "access_expires_in": max(
                0, min(int(status.get("access_expires_in") or 0), 31_536_000)
            ),
            "session_persisted": status.get("session_persisted") is True,
        }
        registration = status.get("device_registration")
        if isinstance(registration, Mapping):
            response["device_registration"] = {
                "uid_device": str(registration.get("uid_device") or "")[:100],
                "token": str(registration.get("token") or "")[:128],
                "created": registration.get("created") is True,
                "email_sent": registration.get("email_sent") is True,
                "email_recipient": str(registration.get("email_recipient") or "")[:254],
            }
        return response

    def request_tenant_logout(self) -> Mapping[str, Any]:
        """Clear the mobile session without affecting device credentials."""

        client = self.tenant_auth_client
        if client is None:
            return {"status": "unavailable"}
        try:
            status = client.logout()
        except Exception:
            return {"status": "tenant_unavailable"}
        if not isinstance(status, Mapping) or status.get("state") != "logged_out":
            return {"status": "tenant_unavailable"}
        return {"status": "logged_out"}

    def record_runtime_tick_failure(
        self,
        *,
        consecutive_errors: int,
    ) -> None:
        """Invalidate a boot-health generation after a runtime-loop failure."""

        if (
            isinstance(consecutive_errors, bool)
            or not isinstance(consecutive_errors, int)
            or not 1 <= consecutive_errors <= 100
        ):
            consecutive_errors = 100
        with self._ota_boot_health_lock:
            self._ota_runtime_tick_failure_events = min(
                self._ota_runtime_tick_failure_events + 1,
                1_000_000_000,
            )
            self._ota_runtime_max_consecutive_errors = max(
                self._ota_runtime_max_consecutive_errors,
                consecutive_errors,
            )

    def _pending_release_boot_identity(
        self,
        expected_update_id: str,
    ) -> Mapping[str, Any]:
        updater = self.ota_updater
        expected_digest = hashlib.sha256(expected_update_id.encode("ascii")).hexdigest()
        reader = getattr(updater, "pending_boot_identity_status", None)
        try:
            if callable(reader):
                raw = reader(expected_update_id=expected_update_id)
            else:
                startup_reader = getattr(updater, "startup_pending_update_id", None)
                current = startup_reader() if callable(startup_reader) else None
                raw = {
                    "schema_version": 1,
                    "status": (
                        "verified"
                        if current == expected_update_id
                        else "identity_changed"
                    ),
                    "ready": current == expected_update_id,
                    "update_id_sha256": expected_digest,
                    "target_version": str(self.settings.current_version),
                    "target_source_revision": "",
                    "target_tree_sha256": "",
                }
        except Exception:
            LOGGER.warning("Pending OTA release identity check failed", exc_info=True)
            raw = {}
        if not isinstance(raw, Mapping):
            raw = {}
        version = str(raw.get("target_version") or "")
        source_revision = str(raw.get("target_source_revision") or "")
        tree_sha256 = str(raw.get("target_tree_sha256") or "")
        installed_version = str(self.settings.current_version)
        if not source_revision:
            marker = Path(self.settings.install_root) / ".labcobot-source-revision"
            try:
                metadata = marker.lstat()
                if (
                    marker.is_symlink()
                    or not stat.S_ISREG(metadata.st_mode)
                    or metadata.st_mode & 0o022
                    or metadata.st_size not in (41, 65)
                ):
                    raise OSError("unsafe source-revision marker")
                candidate = marker.read_text(encoding="ascii").strip()
                if re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", candidate):
                    source_revision = candidate
            except (OSError, UnicodeError):
                source_revision = ""
        ready = bool(
            raw.get("schema_version") == 1
            and raw.get("status") == "verified"
            and raw.get("ready") is True
            and raw.get("update_id_sha256") == expected_digest
            and 1 <= len(version) <= 100
            and secrets.compare_digest(version, installed_version)
            and (
                not source_revision
                or re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", source_revision)
            )
            and (not tree_sha256 or re.fullmatch(r"[0-9a-f]{64}", tree_sha256))
        )
        return {
            "ready": ready,
            "status": "verified" if ready else "identity_changed",
            "update_id_sha256": expected_digest,
            "target_version": version[:100] if ready else "",
            "target_source_revision": source_revision if ready else "",
            "target_tree_sha256": tree_sha256 if ready else "",
        }

    def _ota_local_stores_readable(
        self,
        datahub_status: Mapping[str, Any],
    ) -> bool:
        state_root = Path(self.settings.state_dir).absolute()
        try:
            metadata = state_root.lstat()
            if state_root.is_symlink() or not stat.S_ISDIR(metadata.st_mode):
                return False
            descriptor = os.open(
                str(state_root),
                os.O_RDONLY | getattr(os, "O_DIRECTORY", 0),
            )
            os.close(descriptor)
        except OSError:
            return False
        if self.datahub is not None:
            outbox = datahub_status.get("outbox")
            if (
                datahub_status.get("available") is not True
                or not isinstance(outbox, Mapping)
                or outbox.get("capacity_ok") is not True
            ):
                return False
        if self.petri_registry is not None:
            registry = self._petri_registry_status()
            if registry.get("registry_ready") is not True:
                return False
        if self.workspace_teach_store is not None:
            verifier = getattr(self.workspace_teach_store, "_verified_root", None)
            if not callable(verifier):
                return False
            try:
                verifier()
            except Exception:
                return False
        return True

    def ota_boot_health_status(
        self,
        *,
        _allow_reserved_ota_owner: bool = False,
    ) -> Mapping[str, Any]:
        """Return a bounded software-boot predicate independent of motion release."""

        with self._lock:
            expected_update_id = self._ota_startup_update_id
            started = self._started
            all_workers = {
                thread.name: bool(thread.is_alive()) for thread in tuple(self._threads)
            }
        if expected_update_id is None:
            with self._ota_boot_health_lock:
                return copy.deepcopy(dict(self._ota_boot_health_last))

        cameras = dict(self._camera_health_metrics())
        inventory = self._worker_inventory(
            started=started,
            running=all_workers,
            cameras=cameras,
        )
        persistent_workers = {
            name: status.get("running") is True
            for name, status in inventory.items()
            if status.get("configured") is True and status.get("kind") == "persistent"
        }
        workers_ready = bool(persistent_workers and all(persistent_workers.values()))

        cameras_required = bool(
            self.camera_rig is not None
            or getattr(self.settings, "cameras_enabled", False)
        )
        camera_evidence = {}
        cameras_ready = not cameras_required
        if cameras_required:
            cameras_ready = set(cameras) == {"tool", "workspace"}
            for role in ("tool", "workspace"):
                camera = cameras.get(role)
                camera = camera if isinstance(camera, Mapping) else {}
                expected_backend = str(
                    getattr(self.settings, "{}_camera_backend".format(role), "")
                )
                expected_source = str(
                    getattr(self.settings, "{}_camera_source_id".format(role), "")
                )
                expected_mxid = str(
                    getattr(self.settings, "{}_camera_device_id".format(role), "")
                )
                role_ready = bool(
                    camera.get("role") == role
                    and camera.get("backend") == expected_backend
                    and camera.get("source_id") == expected_source
                    and (
                        expected_backend != "depthai"
                        or not expected_mxid
                        or camera.get("mxid") == expected_mxid
                    )
                    and camera.get("state") == "running"
                    and camera.get("fresh") is True
                    and camera.get("consecutive_errors") == 0
                    and isinstance(camera.get("sequence"), int)
                    and not isinstance(camera.get("sequence"), bool)
                    and int(camera.get("sequence")) > 0
                    and isinstance(camera.get("frames_captured"), int)
                    and not isinstance(camera.get("frames_captured"), bool)
                    and int(camera.get("frames_captured")) > 0
                )
                cameras_ready = bool(cameras_ready and role_ready)
                camera_evidence[role] = {
                    "ready": role_ready,
                    "backend": str(camera.get("backend") or "")[:16],
                    "source_id": str(camera.get("source_id") or "")[:255],
                    "mxid": str(camera.get("mxid") or "")[:255],
                }

        telemetry_required = bool(
            self.metric_source is not None
            or getattr(self.settings, "xarm_metrics_enabled", False)
        )
        xarm = dict(self.xarm_status()) if telemetry_required else {}
        telemetry_ready = not telemetry_required
        if telemetry_required:
            telemetry_ready = bool(
                xarm.get("connected") is True
                and xarm.get("healthy") is True
                and xarm.get("fresh") is True
                and xarm.get("moving") is False
                and xarm.get("error_code") == 0
                and xarm.get("warning_code") == 0
                and xarm.get("state") == 4
                and xarm.get("axis_count") == 6
                and xarm.get("device_type") == _LITE6_DEVICE_TYPE
            )

        capture_run = dict(self.capture_run_status())
        hand_training = dict(self.hand_training_status())
        durable_petri = dict(self._petri_process_durable_status())
        with self._operations_lock:
            petri_state = str(self._petri_status.get("state") or "")
            recovery_state = str(self._recovery_status.get("state") or "")
        with self._motion_lock:
            motion_active = bool(
                self._motion_armed
                or self._motion_live
                or self._motion_authorization_expires_at > float(self._monotonic())
            )
        with self._safety_configuration_lock:
            safety_configuring = self._safety_configuration_state == "configuring"
        owner_evidence = {
            "capture": bool(
                capture_run.get("active") is True
                or capture_run.get("state") in _CAPTURE_ACTIVE_STATES
                or hand_training.get("state")
                in {"starting", "recording", "running", "stopping"}
                or (
                    self._capture_operation_lock.locked()
                    and not _allow_reserved_ota_owner
                )
            ),
            "petri": bool(
                self._petri_run_lock.locked()
                or durable_petri.get("active") is True
                or durable_petri.get("recovery_required") is True
                or petri_state in {"starting", "running", "stopping"}
            ),
            "recovery": recovery_state in {"starting", "running", "stopping"},
            "workspace_teach": self._workspace_teach_blocks_physical_operation(),
            "safety_configuration": safety_configuring,
            "motion_authorization": motion_active,
            "ota": bool(self._ota_lock.locked() and not _allow_reserved_ota_owner),
            "transition": self._operation_transition_lock.locked(),
        }
        no_active_owner = not any(owner_evidence.values())

        datahub_status = dict(self._datahub_runtime_status())
        stores_readable = self._ota_local_stores_readable(datahub_status)
        release_identity = self._pending_release_boot_identity(expected_update_id)
        with self._ota_boot_health_lock:
            tick_failure_events = self._ota_runtime_tick_failure_events
            max_consecutive_errors = self._ota_runtime_max_consecutive_errors
        checks = {
            "runtime_started": started,
            "no_fatal_event": not self._fatal_event.is_set(),
            "persistent_workers_alive": workers_ready,
            "release_identity": release_identity["ready"] is True,
            "cameras": cameras_ready,
            "lite6_telemetry": telemetry_ready,
            "no_active_physical_owner": no_active_owner,
            "local_stores_readable": stores_readable,
            "runtime_window_stable": bool(
                not self._restart_pending and max_consecutive_errors < 2
            ),
        }
        problem_names = {
            "runtime_started": "services_stopped",
            "no_fatal_event": "runtime_fatal",
            "persistent_workers_alive": "persistent_worker_stopped",
            "release_identity": "pending_release_identity_changed",
            "cameras": "camera_degraded",
            "lite6_telemetry": "xarm_telemetry_degraded",
            "no_active_physical_owner": "physical_owner_active",
            "local_stores_readable": "local_store_unavailable",
            "runtime_window_stable": "runtime_window_unstable",
        }
        problems = [
            problem_names[name] for name, passed in checks.items() if not passed
        ]
        evidence = {
            "expected_update_id": expected_update_id,
            "checks": checks,
            "persistent_workers": persistent_workers,
            "cameras": camera_evidence,
            "xarm": {
                "connected": xarm.get("connected") is True,
                "fresh": xarm.get("fresh") is True,
                "moving": xarm.get("moving"),
                "error_code": xarm.get("error_code"),
                "warning_code": xarm.get("warning_code"),
                "axis_count": xarm.get("axis_count"),
                "device_type": xarm.get("device_type"),
            },
            "owners": owner_evidence,
            "release": release_identity,
            "tick_failure_events": tick_failure_events,
            "max_consecutive_errors": max_consecutive_errors,
        }
        fingerprint = hashlib.sha256(
            json.dumps(
                evidence,
                allow_nan=False,
                separators=(",", ":"),
                sort_keys=True,
            ).encode("utf-8")
        ).hexdigest()
        with self._ota_boot_health_lock:
            if not secrets.compare_digest(
                fingerprint,
                self._ota_boot_health_fingerprint,
            ):
                self._ota_boot_health_generation = min(
                    self._ota_boot_health_generation + 1,
                    1_000_000_000,
                )
                self._ota_boot_health_fingerprint = fingerprint
            generation = self._ota_boot_health_generation
            result = {
                "schema_version": 1,
                "status": "ready" if not problems else "degraded",
                "pending": True,
                "ready": not problems,
                "generation": generation,
                "update_id_sha256": release_identity["update_id_sha256"],
                "target_version": release_identity["target_version"],
                "target_source_revision": release_identity["target_source_revision"],
                "motion_release_required": self.motion_release_required,
                "motion_release_gate_ignored": True,
                "checks": dict(checks),
                "problems": list(problems),
            }
            self._ota_boot_health_last = copy.deepcopy(result)
            return copy.deepcopy(result)

    def _ota_boot_health_diagnostics(self) -> Mapping[str, Any]:
        with self._ota_boot_health_lock:
            return copy.deepcopy(dict(self._ota_boot_health_last))

    def runtime_status(self) -> Mapping[str, Any]:
        """Return one secret-free operational snapshot for the UI/diagnostics."""

        with self._lock:
            started = self._started
            all_workers = {
                thread.name: bool(thread.is_alive()) for thread in tuple(self._threads)
            }
            workers = {
                thread.name: bool(thread.is_alive())
                for thread in tuple(self._supervised_threads)
            }
        cameras = dict(self._camera_health_metrics())
        datahub_status = dict(self._datahub_runtime_status())

        problems = []
        if self._fatal_event.is_set():
            problems.append("runtime_fatal")
        if not started:
            problems.append("services_stopped")
        dead_workers = sorted(name for name, alive in workers.items() if not alive)
        if dead_workers:
            problems.append("worker_stopped")
        if self.camera_rig is not None and (
            not cameras
            or any(
                str(status.get("state") or "") != "running"
                or status.get("fresh") is not True
                for status in cameras.values()
            )
        ):
            problems.append("camera_degraded")
        if self.datahub is not None and not datahub_status["available"]:
            problems.append("datahub_outbox_unavailable")
        if int(datahub_status["dead_letters"]) > 0:
            problems.append("datahub_dead_letters")
        if datahub_status.get("dataset_binding_required") is True and (
            datahub_status.get("dataset_binding_verified") is not True
            or datahub_status.get("dataset_binding_mismatch") is True
        ):
            problems.append("datahub_dataset_unverified")
        with self._registry_lock:
            registry = dict(self._registry_status)
        if self.readiness_client is not None and not registry.get("ready"):
            problems.append("device_registry_not_ready")
        capture_run = dict(self.capture_run_status())
        capture_export = dict(self.capture_export_status(capture_run))
        hand_training = dict(self.hand_training_status())
        if capture_run.get("state") == "fault_locked":
            problems.append("capture_motion_fault")
        if capture_export.get("configured") is True and (
            capture_export.get("state") == "failed"
        ):
            problems.append("capture_dataset_export_failed")
        if (
            hand_training.get("configured") is True
            and hand_training.get("state") == "failed"
        ):
            problems.append("hand_training_failed")
        sampling_tool = self.sampling_tool_status()
        if self.sampling_tool_adapter is not None and (
            sampling_tool.get("ready") is not True
        ):
            problems.append("sampling_tool_not_ready")
        xarm = dict(self.xarm_status())
        controller_firmware = dict(self.controller_firmware_status(xarm_snapshot=xarm))
        digital_twin = dict(
            self.digital_twin_status(
                xarm_snapshot=xarm,
                camera_snapshot=cameras,
            )
        )
        workspace_teach = dict(self.workspace_teach_status())
        workspace_boundary = dict(self.workspace_boundary_status())
        safety_configuration = None
        if self.safety_configurator is not None:
            safety_configuration = self.safety_configuration_status(xarm_snapshot=xarm)
            xarm["safety_configurator"] = safety_configuration
        site_safety = dict(
            self.site_safety_status(
                safety_snapshot=safety_configuration,
                camera_snapshot=cameras,
                sampling_tool_snapshot=sampling_tool,
            )
        )
        motion = dict(
            self.motion_status(
                xarm_snapshot=xarm,
                safety_snapshot=safety_configuration,
            )
        )
        ota = dict(self.ota_status())
        operations = dict(
            self.operator_operations_status(
                camera_snapshot=cameras,
                xarm_snapshot=xarm,
                sampling_tool_snapshot=sampling_tool,
                datahub_snapshot=datahub_status,
                motion_snapshot=motion,
                site_safety_snapshot=site_safety,
                controller_firmware_snapshot=controller_firmware,
                ota_snapshot=ota,
            )
        )
        if (operations.get("petri") or {}).get("state") == "error":
            problems.append("petri_operation_failed")
        if (operations.get("recovery") or {}).get("state") == "error":
            problems.append("reviewed_recovery_failed")
        if motion.get("fault"):
            problems.append("motion_fault")
        if self.motion_release_required:
            if motion.get("release_valid") is not True:
                problems.append(_MOTION_RELEASE_BLOCKER)
            elif not self.motion_live_capable:
                problems.append(_MOTION_PERMIT_BLOCKER)
            if site_safety.get("ready") is not True:
                problems.append("site_safety_not_ready")
        if self.settings.xarm_metrics_enabled and (
            xarm.get("healthy") is not True or xarm.get("fresh") is not True
        ):
            problems.append("xarm_telemetry_degraded")
        if (
            self.settings.xarm_motion_enabled
            and controller_firmware.get("ready") is not True
        ):
            problems.append("controller_firmware_not_ready")

        operator_diagnostics = self._operator_diagnostics(cameras)
        capabilities = self._operator_capabilities(
            started=started,
            registry=registry,
            datahub=datahub_status,
            motion=motion,
            ota=ota,
            capture_run=capture_run,
            capture_export=capture_export,
            safety_configuration=safety_configuration,
        )

        return {
            "schema_version": _RUNTIME_STATUS_SCHEMA_VERSION,
            "status": "ok" if not problems else "degraded",
            "ready": not problems,
            "started": started,
            "deployment_mode": self._runtime_deployment_mode(),
            "workers": workers,
            "worker_inventory": self._worker_inventory(
                started=started,
                running=all_workers,
                cameras=cameras,
            ),
            "cameras": cameras,
            "datahub": datahub_status,
            "tenant_auth": dict(self.tenant_auth_status()),
            "registry": registry,
            "motion": motion,
            "xarm": xarm,
            "controller_firmware": controller_firmware,
            "sampling_tool": sampling_tool,
            "site_safety": site_safety,
            "digital_twin": digital_twin,
            "workspace_teach": workspace_teach,
            "workspace_boundary": workspace_boundary,
            "ota": ota,
            "ota_boot_health": self._ota_boot_health_diagnostics(),
            "capture_run": capture_run,
            "capture_export": capture_export,
            "hand_training": hand_training,
            "operations": operations,
            "operator_diagnostics": operator_diagnostics,
            "capabilities": capabilities,
            "system": self._system_metrics(),
            "problems": problems,
            "fatal_error": (
                self._fatal_error_code if self._fatal_event.is_set() else ""
            ),
        }

    def _worker_inventory(
        self,
        *,
        started: bool,
        running: Mapping[str, bool],
        cameras: Mapping[str, Any],
    ) -> Mapping[str, Mapping[str, Any]]:
        """Describe persistent, finite, and on-demand in-process owners."""

        configured = {
            "device-registry": self.readiness_client is not None,
            "xarm-pose-history": self.tool_pose_buffer is not None,
            "dynamic-valve-imitation": self.valve_controller is not None,
            "datahub-uploader": self.datahub is not None,
            "capture-dataset-exporter": (self.capture_dataset_exporter is not None),
            "robot-telemetry": self.metric_source is not None,
            "motion-authorization-watchdog": callable(
                getattr(self.xarm_motion_adapter, "halt", None)
            ),
            "ota-poller": bool(
                self.ota_updater is not None and self.settings.ota_poll_seconds > 0
            ),
            "ota-health-reporter": self.ota_updater is not None,
            "ota-health-commit": self.ota_updater is not None,
            "ota-manual-check": self.ota_updater is not None,
            "capture-run-watch": self.capture_run_controller is not None,
        }
        result = {
            name: {
                "configured": bool(configured.get(name)),
                "kind": kind,
                "running": bool(running.get(name, False)),
            }
            for name, kind in _WORKER_KINDS.items()
        }
        for role in ("tool", "workspace"):
            camera = cameras.get(role)
            camera = camera if isinstance(camera, Mapping) else {}
            result["camera-{}".format(role)] = {
                "configured": self.camera_rig is not None,
                "kind": "persistent",
                "running": bool(started and camera.get("state") == "running"),
            }
        mjpeg_thread = getattr(self.mjpeg_server, "_thread", None)
        result["mjpeg-server"] = {
            "configured": self.mjpeg_server is not None,
            "kind": "persistent",
            "running": bool(
                started
                and mjpeg_thread is not None
                and callable(getattr(mjpeg_thread, "is_alive", None))
                and mjpeg_thread.is_alive()
            ),
        }
        return result

    def _operator_diagnostics(
        self,
        cameras: Mapping[str, Any],
    ) -> Mapping[str, Any]:
        """Return the architecture brief's bounded local identity fields."""

        hostname = _safe_hostname()
        port = _bounded_nonnegative_integer(
            getattr(self.settings, "mjpeg_port", 0), maximum=65535
        )
        mjpeg_configured = self.mjpeg_server is not None
        raw_host = str(getattr(self.settings, "mjpeg_host", "") or "")
        if not mjpeg_configured:
            exposure = "disabled"
        elif raw_host in {"127.0.0.1", "::1", "localhost"}:
            exposure = "loopback"
        else:
            exposure = "authenticated_network"
        origin = (
            "http://127.0.0.1:{}".format(port)
            if mjpeg_configured and port is not None and port > 0
            else ""
        )
        camera_identity = {}
        for role in ("tool", "workspace"):
            health = cameras.get(role)
            health = health if isinstance(health, Mapping) else {}
            prefix = "tool" if role == "tool" else "workspace"
            backend = str(
                getattr(self.settings, "{}_camera_backend".format(prefix), "") or ""
            )
            if backend not in _CAMERA_BACKENDS:
                backend = "unknown"
            source_id = _bounded_public_identifier(
                getattr(
                    self.settings,
                    "{}_camera_source_id".format(prefix),
                    "",
                )
            )
            try:
                stream = self.camera_rig.stream(role)
            except Exception:
                stream = None
            if stream is not None:
                source_id = (
                    _bounded_public_identifier(getattr(stream, "source_id", ""))
                    or source_id
                )
            device_id = _bounded_public_identifier(
                getattr(
                    self.settings,
                    "{}_camera_device_id".format(prefix),
                    "",
                )
            )
            stream_path = "/{}.mjpg".format(role)
            snapshot_path = "/api/cameras/{}/snapshot.jpg".format(role)
            camera_identity[role] = {
                "configured": self.camera_rig is not None,
                "backend": backend,
                "source_id": source_id,
                "mxid": device_id if backend == "depthai" else "",
                "state": (
                    health.get("state")
                    if health.get("state") in _CAMERA_STATES
                    else "degraded"
                ),
                "fresh": health.get("fresh") is True,
                "stream_path": stream_path,
                "snapshot_path": snapshot_path,
                "stream_url": origin + stream_path if origin else "",
            }
        bind_address = (
            raw_host
            if raw_host in {"127.0.0.1", "::1", "localhost"}
            else _private_network_address(raw_host)
        )
        return {
            "schema_version": _OPERATOR_DIAGNOSTICS_SCHEMA_VERSION,
            "hostname": hostname,
            "deployment_mode": self._runtime_deployment_mode(),
            "management": {
                "configured": mjpeg_configured,
                "exposure": exposure,
                "bind_address": bind_address,
                "port": port or 0,
                "bearer_auth_configured": bool(
                    getattr(self.settings, "mjpeg_token", "")
                ),
                "controls": "loopback_only",
                "health_path": "/healthz",
                "health_url": origin + "/healthz" if origin else "",
            },
            "xarm": {
                "configured": self.metric_source is not None,
                "private_address": _private_network_address(
                    getattr(self.settings, "xarm_ip", "")
                ),
            },
            "cameras": camera_identity,
        }

    def _operator_capabilities(
        self,
        *,
        started: bool,
        registry: Mapping[str, Any],
        datahub: Mapping[str, Any],
        motion: Mapping[str, Any],
        ota: Mapping[str, Any],
        capture_run: Mapping[str, Any],
        capture_export: Mapping[str, Any],
        safety_configuration: Optional[Mapping[str, Any]] = None,
    ) -> Mapping[str, Any]:
        if not self.dynamic_valve_configured:
            search_state = "unavailable"
        elif motion.get("state") == "FAULT_LOCKED":
            search_state = "fault_locked"
        elif motion.get("state") == "ARMED_LIVE":
            search_state = "armed_live"
        elif motion.get("action_allowed") is True:
            search_state = "ready"
        elif self._capture_operation_lock.locked() or self._ota_lock.locked():
            search_state = "busy"
        else:
            search_state = "locked"
        safety_configuration = (
            dict(safety_configuration)
            if isinstance(safety_configuration, Mapping)
            else self.safety_configuration_status()
        )
        return {
            "schema_version": 1,
            "registry": {
                "configured": self.readiness_client is not None,
                "ready": registry.get("ready") is True,
                "status": (
                    str(registry.get("status") or "off")
                    if str(registry.get("status") or "off")
                    in {"off", "pending", "verified", "incomplete", "error"}
                    else "error"
                ),
            },
            "datahub": {
                "configured": self.datahub is not None,
                "available": datahub.get("available") is True,
                "outbox_pending": int(datahub.get("pending") or 0),
                "outbox_dead_letters": int(datahub.get("dead_letters") or 0),
                "dataset_binding_required": (
                    datahub.get("dataset_binding_required") is True
                ),
                "dataset_binding_verified": (
                    datahub.get("dataset_binding_verified") is True
                ),
            },
            "ota": {
                "configured": ota.get("configured") is True,
                "action_allowed": ota.get("action_allowed") is True,
                "status": (
                    str(ota.get("status") or "unavailable")
                    if str(ota.get("status") or "unavailable")
                    in {
                        "idle",
                        "checking",
                        "up_to_date",
                        "busy",
                        "pending_restart",
                        "error",
                        "unavailable",
                    }
                    else "error"
                ),
            },
            "capture": {
                "configured": capture_run.get("configured") is True,
                "state": str(capture_run.get("state") or "unavailable"),
                "action_allowed": capture_run.get("action_allowed") is True,
                "stop_allowed": capture_run.get("stop_allowed") is True,
            },
            "capture_export": {
                "configured": capture_export.get("configured") is True,
                "state": str(capture_export.get("state") or "unavailable"),
                "new_run_allowed": (capture_export.get("new_run_allowed") is True),
                "dataset_binding_verified": (
                    capture_export.get("dataset_binding_verified") is True
                ),
            },
            "offload": {
                "configured": self.offload_client is not None,
                "trajectory_training": bool(
                    self.offload_client is not None
                    and (
                        self.settings.offload_trajectory_shortcut_id
                        or self.settings.offload_shortcut_id
                    )
                ),
                "valve_detection": bool(
                    self.offload_client is not None
                    and (
                        self.settings.offload_valve_shortcut_id
                        or self.settings.offload_shortcut_id
                    )
                ),
            },
            "calibration": {
                "configured": self.eye_in_hand_configured,
                "pose_history_configured": self.tool_pose_buffer is not None,
                "ready": bool(
                    self.eye_in_hand_configured and self.tool_pose_buffer is not None
                ),
            },
            "dynamic_valve_search": {
                "configured": self.dynamic_valve_configured,
                "action_allowed": motion.get("action_allowed") is True,
                "requires_two_step_confirmation": True,
                "state": search_state,
            },
            "safety_boundary_configurator": {
                "configured": (safety_configuration.get("configured") is True),
                "action_allowed": (
                    safety_configuration.get("state") == "ready_to_configure"
                ),
                "state": str(safety_configuration.get("state") or "unavailable"),
            },
            "motion": {
                "capable": motion.get("capable") is True,
                "state": str(motion.get("state") or "LOCKED"),
                "recovery_commissioned": (motion.get("recovery_commissioned") is True),
            },
            "petri": {
                "configured": self.petri_process_configured,
                "running": self._petri_run_lock.locked(),
                "cancel_allowed": self._petri_run_lock.locked(),
            },
            "software_stop": {
                "available": bool(started and self.mjpeg_server is not None),
                "active_owner": bool(
                    self._petri_run_lock.locked()
                    or capture_run.get("active") is True
                    or motion.get("armed") is True
                    or motion.get("live") is True
                ),
            },
        }

    def _system_metrics(self) -> Mapping[str, Any]:
        """Collect bounded local metrics without exposing filesystem paths."""

        try:
            uptime = _bounded_finite_number(self._monotonic(), maximum=1e10)
        except Exception:
            uptime = None
        try:
            cores = _bounded_nonnegative_integer(os.cpu_count(), maximum=4096)
        except Exception:
            cores = None
        loads = (None, None, None)
        try:
            raw_loads = os.getloadavg()
            bounded = tuple(
                _bounded_finite_number(value, maximum=1_000_000.0)
                for value in raw_loads
            )
            if len(bounded) == 3 and all(value is not None for value in bounded):
                loads = bounded
        except Exception:
            pass

        memory_total = None
        memory_available = None
        try:
            with Path("/proc/meminfo").open("r", encoding="ascii") as handle:
                raw_memory = handle.read(64 * 1024)
            values = {}
            for line in raw_memory.splitlines():
                name, separator, raw_value = line.partition(":")
                if separator and name in {"MemTotal", "MemAvailable"}:
                    fields = raw_value.strip().split()
                    if len(fields) == 2 and fields[1] == "kB":
                        value = _bounded_nonnegative_integer(
                            fields[0], maximum=(2**63 - 1) // 1024
                        )
                        if value is not None:
                            values[name] = value * 1024
            memory_total = values.get("MemTotal")
            memory_available = values.get("MemAvailable")
            if (
                memory_total is None
                or memory_available is None
                or memory_available > memory_total
            ):
                memory_total = None
                memory_available = None
        except Exception:
            pass

        filesystem_total = None
        filesystem_free = None
        try:
            stat = os.statvfs(self.settings.state_dir)
            filesystem_total = _bounded_nonnegative_integer(
                stat.f_blocks * stat.f_frsize, maximum=2**63 - 1
            )
            filesystem_free = _bounded_nonnegative_integer(
                stat.f_bavail * stat.f_frsize, maximum=2**63 - 1
            )
            if (
                filesystem_total is None
                or filesystem_free is None
                or filesystem_free > filesystem_total
            ):
                filesystem_total = None
                filesystem_free = None
        except Exception:
            pass

        temperature_c = None
        try:
            with Path("/sys/class/thermal/thermal_zone0/temp").open(
                "r", encoding="ascii"
            ) as handle:
                raw_temperature = handle.read(64).strip()
            temperature_c = _bounded_finite_number(
                float(raw_temperature) / 1000.0,
                minimum=-50.0,
                maximum=200.0,
            )
        except Exception:
            pass

        return {
            "schema_version": 1,
            "available": any(
                value is not None
                for value in (
                    uptime,
                    loads[0],
                    memory_total,
                    filesystem_total,
                    temperature_c,
                )
            ),
            "hostname": _safe_hostname(),
            "uptime_seconds": uptime,
            "cpu": {
                "available": loads[0] is not None,
                "logical_cores": cores,
                "load_1m": loads[0],
                "load_5m": loads[1],
                "load_15m": loads[2],
            },
            "memory": {
                "available": memory_total is not None,
                "total_bytes": memory_total,
                "available_bytes": memory_available,
            },
            "state_filesystem": {
                "available": filesystem_total is not None,
                "total_bytes": filesystem_total,
                "free_bytes": filesystem_free,
            },
            "temperature": {
                "available": temperature_c is not None,
                "celsius": temperature_c,
            },
        }

    def ota_status(self) -> Mapping[str, Any]:
        """Return bounded, secret-free state for the local update display."""

        commissioning = self._evaluate_ota_commissioning()
        with self._ota_status_lock:
            result = dict(self._ota_status)
            result["history"] = [dict(row) for row in self._ota_history]
        result["schema_version"] = 2
        result["action_allowed"] = self._ota_action_allowed()
        result["auto_apply_requested"] = commissioning.requested
        result["auto_apply_permitted"] = commissioning.permitted
        result["commissioning"] = {
            "required": commissioning.requested,
            "valid": commissioning.permitted,
            "blockers": list(commissioning.blockers),
        }
        with self._ota_admission_lock:
            result["admission_lease"] = copy.deepcopy(dict(self._ota_admission_status))
        return result

    def _evaluate_ota_commissioning(self) -> OTACommissioningGate:
        """Refresh the root-owned scheduler gate without trusting exceptions."""

        requested = bool(getattr(self.settings, "ota_auto_apply", False))
        try:
            result = self._ota_commissioning_evaluator(self.settings)
        except Exception:
            LOGGER.error("Automatic OTA commissioning validation failed", exc_info=True)
            result = OTACommissioningGate(
                requested=requested,
                permitted=False,
                blockers=("commissioning_artifact_invalid",) if requested else (),
            )
        if (
            not isinstance(result, OTACommissioningGate)
            or result.requested != requested
        ):
            result = OTACommissioningGate(
                requested=requested,
                permitted=False,
                blockers=("commissioning_artifact_invalid",) if requested else (),
            )
        with self._ota_status_lock:
            self._ota_commissioning = result
        return result

    def _runtime_deployment_mode(self) -> str:
        raw = getattr(self.settings, "deployment_mode", "development")
        if isinstance(raw, str) and raw in _DEPLOYMENT_MODES:
            return raw
        return "development"

    def _ota_action_allowed(self) -> bool:
        if (
            self.ota_updater is None
            or (
                bool(getattr(self.settings, "immutable_release", False))
                and not isinstance(self.ota_updater, PrivilegedOTAClient)
            )
            or self._restart_pending
            or self._fatal_event.is_set()
            or self._ota_lock.locked()
            or self._capture_operation_lock.locked()
        ):
            return False
        with self._lock:
            if not self._started:
                return False
        return self._ota_environment_ready()

    def _capture_confirmation_active(self) -> bool:
        now = float(self._monotonic())
        with self._capture_control_lock:
            active = bool(
                self._capture_confirmation_challenge
                and self._capture_confirmation_expires_at > now
            )
            if self._capture_confirmation_expires_at > 0.0 and not active:
                self._clear_capture_confirmation_locked()
            return active

    def _ota_operator_challenge_active(self) -> bool:
        """Return whether any current operator confirmation blocks an update.

        Each challenge lock is held separately so this read-side gate cannot
        introduce a lock-order cycle with STOP or an action endpoint. Expired
        and STOP-invalidated tokens are cleared while their owning lock is held.
        """

        now = float(self._monotonic())
        with self._motion_lock:
            stop_generation = self._motion_stop_generation
            authorization_generation = self._motion_authorization_generation
        petri_context = self._petri_operator_confirmation_context()
        recovery_context = self._recovery_operator_confirmation_context()

        with self._motion_search_confirmation_lock:
            active = bool(
                self._motion_search_challenge
                and self._motion_search_confirmation_expires_at > now
                and self._motion_search_stop_generation == stop_generation
                and self._motion_search_authorization_generation
                == authorization_generation
            )
            if self._motion_search_challenge and not active:
                self._clear_motion_search_confirmation_locked()
            if active:
                return True

        with self._safety_configuration_lock:
            active = bool(
                self._safety_configuration_challenge
                and self._safety_configuration_expires_at > now
                and self._safety_configuration_stop_generation == stop_generation
            )
            if self._safety_configuration_challenge and not active:
                self._clear_safety_configuration_challenge_locked()
            if active:
                return True

        with self._capture_control_lock:
            active = bool(
                self._capture_confirmation_challenge
                and self._capture_confirmation_expires_at > now
                and self._capture_confirmation_stop_generation == stop_generation
            )
            if self._capture_confirmation_challenge and not active:
                self._clear_capture_confirmation_locked()
            if active:
                return True

        with self._operations_lock:
            petri_active = bool(
                self._petri_confirmation_challenge
                and self._petri_confirmation_expires_at > now
                and self._petri_confirmation_stop_generation == stop_generation
                and self._petri_confirmation_context == petri_context
            )
            recovery_active = bool(
                self._recovery_confirmation_challenge
                and self._recovery_confirmation_expires_at > now
                and self._recovery_confirmation_stop_generation == stop_generation
                and self._recovery_confirmation_context == recovery_context
            )
            if self._petri_confirmation_challenge and not petri_active:
                self._clear_petri_confirmation_locked()
            if self._recovery_confirmation_challenge and not recovery_active:
                self._clear_recovery_confirmation_locked()
            if petri_active or recovery_active:
                return True

        with self._manual_review_lock:
            active = bool(
                self._manual_review_challenge
                and self._manual_review_expires_at > now
                and self._manual_review_stop_generation == stop_generation
            )
            if self._manual_review_challenge and not active:
                self._clear_manual_review_challenge_locked()
            return active

    def capture_run_status(self) -> Mapping[str, Any]:
        """Return a bounded, secret-free capture state for the local UI."""

        controller = self.capture_run_controller
        if controller is None:
            return self._unavailable_capture_status()
        try:
            raw = controller.status()
        except Exception:
            LOGGER.warning("Could not read capture-run status", exc_info=True)
            return self._invalid_capture_status()
        if not isinstance(raw, Mapping):
            return self._invalid_capture_status()

        state = str(raw.get("state") or "")
        raw_active = raw.get("active")
        valid = (
            raw.get("schema_version") == 1
            and raw.get("configured") is True
            and isinstance(raw_active, bool)
            and state in _CAPTURE_STATES
            and (state not in _CAPTURE_ACTIVE_STATES or raw_active is True)
            and raw.get("planned_timepoints") == _CAPTURE_TIMEPOINTS
            and raw.get("duration_seconds") == 15.0
            and raw.get("interval_seconds") == 1.0
        )
        completed = self._bounded_capture_integer(
            raw.get("completed_timepoints"),
            maximum=_CAPTURE_TIMEPOINTS,
        )
        tool_saved = self._bounded_capture_integer(
            raw.get("tool_saved"),
            maximum=_CAPTURE_TIMEPOINTS,
        )
        workspace_saved = self._bounded_capture_integer(
            raw.get("workspace_saved"),
            maximum=_CAPTURE_TIMEPOINTS,
        )
        saved_images = self._bounded_capture_integer(
            raw.get("saved_images"),
            maximum=_CAPTURE_IMAGES,
        )
        raw_error_code = raw.get("error_code")
        error_code = _bounded_error_code(raw_error_code)
        manifest_state = raw.get("local_manifest_state")
        manifest_complete = raw.get("local_manifest_complete")
        valid = (
            valid
            and all(
                value is not None
                for value in (completed, tool_saved, workspace_saved, saved_images)
            )
            and (
                isinstance(raw_error_code, str)
                and len(raw_error_code) <= 48
                and raw_error_code == error_code
                and manifest_state in _CAPTURE_MANIFEST_STATES
                and type(manifest_complete) is bool
            )
        )
        if valid:
            valid = (
                saved_images == tool_saved + workspace_saved
                and tool_saved == completed
                and workspace_saved == completed
                and (state != "completed" or completed == _CAPTURE_TIMEPOINTS)
                and (
                    state != "completed"
                    or (manifest_state == "completed" and manifest_complete is True)
                )
                and (manifest_complete is not True or state == "completed")
            )
        if not valid:
            return self._invalid_capture_status()

        run_id = str(raw.get("run_id") or "")
        if not (
            len(run_id) == 32
            and all(character in "0123456789abcdef" for character in run_id)
        ):
            run_id = ""
        active = raw_active is True
        now = float(self._monotonic())
        with self._capture_control_lock:
            confirming = bool(
                not active
                and self._capture_confirmation_challenge
                and self._capture_confirmation_expires_at > now
            )
            if self._capture_confirmation_expires_at > 0.0 and not confirming:
                self._clear_capture_confirmation_locked()
        if confirming:
            state = "confirming"

        environment_ready = self._capture_environment_ready()
        export_ready = (
            self.capture_export_status(
                {
                    "state": state,
                    "run_id": run_id,
                }
            ).get("new_run_allowed")
            is True
        )
        action_allowed = (
            not active
            and state != "fault_locked"
            and raw.get("action_allowed") is True
            and environment_ready
            and export_ready
        )
        stop_allowed = active and raw.get("can_cancel") is True
        messages = {
            "idle": "Ready for a commissioned 15-second capture run",
            "confirming": "Confirm the clear workcell a second time",
            "starting": "Starting commissioned motion and paired capture",
            "running": "Capturing one dual-camera pair per second",
            "stopping": "Stopping motion and closing the capture run",
            "completed": "All 30 camera images were saved",
            "cancelled": "Capture was cancelled and motion halt requested",
            "failed": "Capture failed and motion halt was requested",
            "interrupted": "An interrupted capture run requires review",
            "fault_locked": (
                "Motion safety fault is latched; inspect the workcell and use "
                "the physical emergency stop if motion persists"
            ),
        }
        return {
            "schema_version": 1,
            "configured": True,
            "state": state,
            "active": active,
            "action_allowed": action_allowed,
            "stop_allowed": stop_allowed,
            "run_id": run_id,
            "duration_seconds": 15.0,
            "interval_seconds": 1.0,
            "planned_timepoints": _CAPTURE_TIMEPOINTS,
            "completed_timepoints": completed,
            "saved_images": saved_images,
            "tool_saved": tool_saved,
            "workspace_saved": workspace_saved,
            "error_code": error_code,
            "local_manifest_state": manifest_state,
            "local_manifest_complete": manifest_complete,
            "message": messages[state],
            "motion_started": raw.get("motion_started") is True,
            "stop_requested": raw.get("stop_requested") is True,
        }

    @staticmethod
    def _bounded_capture_integer(value: Any, *, maximum: int) -> Optional[int]:
        if isinstance(value, bool) or not isinstance(value, int):
            return None
        if not 0 <= value <= maximum:
            return None
        return value

    @staticmethod
    def _unavailable_capture_status() -> Mapping[str, Any]:
        return {
            "schema_version": 1,
            "configured": False,
            "state": "unavailable",
            "active": False,
            "action_allowed": False,
            "stop_allowed": False,
            "run_id": "",
            "duration_seconds": 15.0,
            "interval_seconds": 1.0,
            "planned_timepoints": _CAPTURE_TIMEPOINTS,
            "completed_timepoints": 0,
            "saved_images": 0,
            "tool_saved": 0,
            "workspace_saved": 0,
            "error_code": "capture_unavailable",
            "local_manifest_state": "none",
            "local_manifest_complete": False,
            "message": "Commissioned capture motion is not configured",
            "motion_started": False,
            "stop_requested": False,
        }

    @classmethod
    def _invalid_capture_status(cls) -> Mapping[str, Any]:
        result = dict(cls._unavailable_capture_status())
        result.update(
            {
                "configured": True,
                "state": "failed",
                "error_code": "capture_status_invalid",
                "local_manifest_state": "invalid",
                "message": "Capture status failed validation",
            }
        )
        return result

    def capture_export_status(
        self,
        capture_run: Optional[Mapping[str, Any]] = None,
    ) -> Mapping[str, Any]:
        """Return strict local-save versus remote-dataset delivery state."""

        run = capture_run if isinstance(capture_run, Mapping) else {}
        capture_state = str(run.get("state") or "idle")
        run_id = str(run.get("run_id") or "")
        if not (
            len(run_id) == 32
            and all(character in "0123456789abcdef" for character in run_id)
        ):
            run_id = ""
        base = {
            "schema_version": 1,
            "configured": self.capture_dataset_exporter is not None,
            "state": "unavailable",
            "new_run_allowed": False,
            "run_id": run_id,
            "total_frames": _CAPTURE_IMAGES,
            "known_frames": 0,
            "unqueued_frames": _CAPTURE_IMAGES,
            "pending_frames": 0,
            "acknowledged_frames": 0,
            "dead_lettered_frames": 0,
            "dataset_binding_verified": False,
            "message": "Dataset export is not configured",
        }
        exporter = self.capture_dataset_exporter
        if exporter is None:
            return base
        status_provider = getattr(exporter, "status", None)
        if not callable(status_provider):
            return self._invalid_capture_export_status(base)
        try:
            raw = status_provider(run_id)
        except Exception:
            LOGGER.warning("Could not read capture export status", exc_info=True)
            return self._invalid_capture_export_status(base)
        if not isinstance(raw, Mapping):
            return self._invalid_capture_export_status(base)

        integer_fields = {
            "total_frames": _CAPTURE_IMAGES,
            "known_frames": _CAPTURE_IMAGES,
            "unqueued_frames": _CAPTURE_IMAGES,
            "pending_frames": _CAPTURE_IMAGES,
            "acknowledged_frames": _CAPTURE_IMAGES,
            "dead_lettered_frames": _CAPTURE_IMAGES,
            "completed_runs": 10000,
            "failed_runs": 10000,
            "aggregate_pending_frames": 300000,
            "aggregate_acknowledged_frames": 300000,
            "aggregate_dead_lettered_frames": 300000,
        }
        counters = {
            name: self._bounded_capture_integer(raw.get(name), maximum=maximum)
            for name, maximum in integer_fields.items()
        }
        booleans_valid = all(
            isinstance(raw.get(name), bool)
            for name in (
                "initial_scan_complete",
                "run_known",
                "complete",
                "failed",
            )
        )
        if (
            raw.get("schema_version") != 1
            or raw.get("configured") is not True
            or not booleans_valid
            or any(value is None for value in counters.values())
            or counters["total_frames"] != _CAPTURE_IMAGES
            or counters["known_frames"] + counters["unqueued_frames"] != _CAPTURE_IMAGES
            or counters["pending_frames"]
            + counters["acknowledged_frames"]
            + counters["dead_lettered_frames"]
            != counters["known_frames"]
        ):
            return self._invalid_capture_export_status(base)

        reported_run_id = str(raw.get("run_id") or "")
        matching_run = bool(
            run_id and raw.get("run_known") is True and reported_run_id == run_id
        )
        if raw.get("run_known") is True and not (
            len(reported_run_id) == 32
            and all(character in "0123456789abcdef" for character in reported_run_id)
        ):
            return self._invalid_capture_export_status(base)

        binding_verified = False
        publisher_status = getattr(self.datahub, "status", None)
        if callable(publisher_status):
            try:
                binding = publisher_status()
            except Exception:
                binding = None
            binding_verified = bool(
                isinstance(binding, Mapping)
                and binding.get("dataset_binding_required") is True
                and binding.get("dataset_binding_verified") is True
                and binding.get("dataset_binding_mismatch") is False
            )

        initial_scan_complete = raw.get("initial_scan_complete") is True
        exporter_error = str(raw.get("error_code") or "")[:64]
        scan_clean = bool(
            initial_scan_complete
            and not exporter_error
            and counters["failed_runs"] == 0
            and counters["aggregate_pending_frames"] == 0
            and counters["aggregate_dead_lettered_frames"] == 0
            and counters["aggregate_acknowledged_frames"]
            == counters["completed_runs"] * _CAPTURE_IMAGES
        )
        synced = bool(
            matching_run
            and raw.get("complete") is True
            and raw.get("failed") is False
            and counters["acknowledged_frames"] == _CAPTURE_IMAGES
            and binding_verified
        )
        failed = bool(
            exporter_error
            or raw.get("failed") is True
            or counters["failed_runs"] > 0
            or counters["dead_lettered_frames"] > 0
            or counters["aggregate_dead_lettered_frames"] > 0
        )
        if failed:
            state = "failed"
            message = "Dataset delivery requires operator review"
        elif capture_state == "completed":
            if synced:
                state = "synced"
                message = "All 30 images were confirmed in the target dataset"
            elif matching_run and counters["pending_frames"] > 0:
                state = "sending"
                message = "Saved images are being delivered to the dataset"
            elif matching_run:
                state = "queueing"
                message = "Dataset delivery is being reconciled"
            else:
                state = "awaiting_export"
                message = "Saved images are waiting for the export scan"
        elif not initial_scan_complete:
            state = "scanning"
            message = "Checking durable dataset delivery receipts"
        else:
            state = "idle"
            message = "Dataset exporter is ready"

        current_counts = (
            counters
            if matching_run
            else {
                "known_frames": 0,
                "unqueued_frames": _CAPTURE_IMAGES,
                "pending_frames": 0,
                "acknowledged_frames": 0,
                "dead_lettered_frames": 0,
            }
        )
        base.update(
            {
                "state": state,
                "new_run_allowed": bool(
                    scan_clean
                    and binding_verified
                    and (capture_state != "completed" or synced)
                ),
                "run_id": run_id,
                "known_frames": current_counts["known_frames"],
                "unqueued_frames": current_counts["unqueued_frames"],
                "pending_frames": current_counts["pending_frames"],
                "acknowledged_frames": current_counts["acknowledged_frames"],
                "dead_lettered_frames": current_counts["dead_lettered_frames"],
                "dataset_binding_verified": binding_verified,
                "message": message,
            }
        )
        return base

    @staticmethod
    def _invalid_capture_export_status(base: Mapping[str, Any]) -> Mapping[str, Any]:
        result = dict(base)
        result.update(
            {
                "configured": True,
                "state": "failed",
                "new_run_allowed": False,
                "message": "Dataset export status failed validation",
            }
        )
        return result

    def _capture_environment_ready(self, *, allow_reserved: bool = False) -> bool:
        if self.motion_release_required:
            return False
        with self._lock:
            if not self._started:
                return False
        if (
            self._restart_pending
            or self._fatal_event.is_set()
            or self._ota_lock.locked()
            or self._petri_run_lock.locked()
            or self._petri_durable_owner_blocks_physical_operation()
            or self._workspace_teach_blocks_physical_operation()
            or (self._capture_operation_lock.locked() and not allow_reserved)
        ):
            return False
        # The existing valve controller has its own asynchronous authorization
        # path. A commissioned capture deployment must not expose both live
        # motion owners at the same time.
        if self.motion_live_capable:
            return False
        with self._motion_lock:
            if (
                self._motion_armed
                or self._motion_live
                or bool(self._motion_fault_reason)
            ):
                return False
        if self.settings.deployment_mode == "workcell":
            xarm = self.xarm_status()
            if not (
                xarm.get("healthy") is True
                and xarm.get("fresh") is True
                and xarm.get("connected") is True
                and xarm.get("moving") is False
                and xarm.get("axis_count") == 6
                and xarm.get("device_type") == 9
            ):
                return False
            publisher_status = getattr(self.datahub, "status", None)
            if not callable(publisher_status):
                return False
            try:
                binding = publisher_status()
            except Exception:
                return False
            if not (
                isinstance(binding, Mapping)
                and binding.get("dataset_binding_required") is True
                and binding.get("dataset_binding_verified") is True
                and binding.get("dataset_binding_mismatch") is False
            ):
                return False
        cameras = self._camera_health_metrics()
        if set(cameras) != {"tool", "workspace"} or not all(
            str(value.get("state") or "") == "running" and value.get("fresh") is True
            for value in cameras.values()
        ):
            return False
        try:
            health = self.camera_rig.health()
            if {getattr(role, "value", str(role)) for role in health} != {
                "tool",
                "workspace",
            }:
                return False
            return all(
                self.camera_rig.stream(role).latest(max_age_s=0.5) is not None
                for role in health
            )
        except Exception:
            LOGGER.debug(
                "Could not validate capture camera freshness",
                exc_info=True,
            )
            return False

    @staticmethod
    def _bounded_ota_text(value: Any, limit: int = 160) -> str:
        text = str(value or "")
        return "".join(
            character if 32 <= ord(character) <= 126 else "?"
            for character in text[:limit]
        )

    @staticmethod
    def _ota_error_code(exc: Exception) -> str:
        """Classify update failures without returning exception text or URLs."""

        if isinstance(exc, OTAAdmissionChanged):
            return "admission_changed"
        if isinstance(exc, OTAError):
            prefix = "OTA metadata request returned HTTP "
            message = str(exc)
            if message.startswith(prefix):
                raw_status = message[len(prefix) :]
                if raw_status.isdigit() and 500 <= int(raw_status) <= 599:
                    return "metadata_service_unavailable"
        return "update_check_failed"

    def _record_ota_status(
        self,
        status: str,
        *,
        available_version: str = "",
        message: str = "",
        error_code: str = "",
        manifest_verification: str = "",
        archive_digest_verification: str = "",
    ) -> None:
        allowed = {
            "idle",
            "checking",
            "up_to_date",
            "update_available",
            "busy",
            "pending_restart",
            "error",
            "unavailable",
        }
        safe_status = str(status) if str(status) in allowed else "error"
        safe_error_code = str(error_code)
        if safe_status != "error":
            safe_error_code = ""
        elif safe_error_code not in _OTA_ERROR_CODES or not safe_error_code:
            safe_error_code = "update_check_failed"
        default_manifest = "checking" if safe_status == "checking" else "not_checked"
        safe_manifest_verification = (
            manifest_verification
            if manifest_verification in _OTA_MANIFEST_VERIFICATION_STATES
            else default_manifest
        )
        safe_archive_verification = (
            archive_digest_verification
            if archive_digest_verification in _OTA_ARCHIVE_VERIFICATION_STATES
            else "not_checked"
        )
        with self._ota_status_lock:
            self._ota_status = {
                "configured": self.ota_updater is not None,
                "status": safe_status,
                "current_version": self._bounded_ota_text(
                    getattr(self.settings, "current_version", ""),
                    64,
                ),
                "available_version": self._bounded_ota_text(
                    available_version,
                    64,
                ),
                "message": self._bounded_ota_text(message),
                "error_code": safe_error_code,
                "manifest_verification": safe_manifest_verification,
                "archive_digest_verification": safe_archive_verification,
            }
            previous = self._ota_history[-1] if self._ota_history else {}
            history_signature = (
                safe_status,
                self._ota_status["current_version"],
                self._ota_status["available_version"],
                safe_error_code,
            )
            previous_signature = (
                previous.get("status"),
                previous.get("current_version"),
                previous.get("available_version"),
                previous.get("error_code"),
            )
            if history_signature != previous_signature:
                self._ota_history_sequence = min(
                    self._ota_history_sequence + 1,
                    1_000_000_000,
                )
                self._ota_history.append(
                    {
                        "sequence": self._ota_history_sequence,
                        "status": safe_status,
                        "current_version": self._ota_status["current_version"],
                        "available_version": self._ota_status["available_version"],
                        "error_code": safe_error_code,
                    }
                )
                self._ota_history = self._ota_history[-8:]

    def arm_motion(self) -> str:
        """Reject the retired direct arming seam.

        Motion admission is intentionally available only through
        :meth:`request_dynamic_valve_search`, whose one-use challenge is bound
        to the current STOP and authorization generations.  Keeping this
        compatibility method fail-closed prevents legacy in-process callers
        from bypassing the same contract enforced for the LVGL frontend.
        """

        raise RuntimeError(
            "Direct motion arming is disabled; use reviewed Search confirmation"
        )

    def _arm_confirmed_dynamic_valve_search(
        self,
        *,
        stop_generation: int,
        authorization_generation: int,
    ) -> str:
        """Arm only if the confirmed generation survived admission."""

        with self._operation_transition_lock:
            if (
                self._workspace_teach_blocks_physical_operation()
                or self._capture_operation_lock.locked()
                or self._ota_lock.locked()
            ):
                raise RuntimeError("Another commissioned physical operation is active")
            return self._arm_motion_locked(
                expected_stop_generation=stop_generation,
                expected_authorization_generation=authorization_generation,
            )

    def request_dynamic_valve_search(
        self,
        challenge: Optional[str] = None,
    ) -> Mapping[str, Any]:
        """Two-step admission to the existing reviewed valve-search owner.

        This method does not accept coordinates, controller commands, or
        motor-enable parameters.  A challenge is single-use, expires after a
        short local confirmation window, and is bound to the current software
        STOP and motion-authorization generations.
        """

        supplied = challenge if isinstance(challenge, str) else ""
        if supplied and not re.fullmatch(r"[0-9a-f]{32}", supplied):
            return {"status": "confirmation_required"}
        with self._motion_search_confirmation_lock:
            now = float(self._monotonic())
            if not supplied:
                self._clear_motion_search_confirmation_locked()
                unavailable = self._motion_search_unavailable_reason()
                if unavailable:
                    return {"status": unavailable}
                with self._motion_lock:
                    stop_generation = self._motion_stop_generation
                    authorization_generation = self._motion_authorization_generation
                token = secrets.token_hex(16)
                self._motion_search_challenge = token
                self._motion_search_confirmation_expires_at = (
                    now + _MOTION_SEARCH_CONFIRMATION_SECONDS
                )
                self._motion_search_stop_generation = stop_generation
                self._motion_search_authorization_generation = authorization_generation
                return {
                    "status": "confirm",
                    "challenge": token,
                    "expires_in_seconds": int(_MOTION_SEARCH_CONFIRMATION_SECONDS),
                }

            with self._motion_lock:
                generation_matches = bool(
                    self._motion_search_stop_generation == self._motion_stop_generation
                    and self._motion_search_authorization_generation
                    == self._motion_authorization_generation
                )
            confirmed = bool(
                self._motion_search_challenge
                and self._motion_search_confirmation_expires_at >= now
                and generation_matches
                and secrets.compare_digest(
                    self._motion_search_challenge,
                    supplied,
                )
            )
            confirmed_stop_generation = self._motion_search_stop_generation
            confirmed_authorization_generation = (
                self._motion_search_authorization_generation
            )
            self._clear_motion_search_confirmation_locked()
            if not confirmed:
                return {"status": "confirmation_required"}
            unavailable = self._motion_search_unavailable_reason()
            if unavailable:
                return {"status": unavailable}
            try:
                self._arm_confirmed_dynamic_valve_search(
                    stop_generation=confirmed_stop_generation,
                    authorization_generation=(confirmed_authorization_generation),
                )
            except Exception:
                LOGGER.warning(
                    "Reviewed dynamic-valve search admission failed",
                    exc_info=True,
                )
                unavailable = self._motion_search_unavailable_reason()
                return {"status": unavailable or "error"}
            return {"status": "accepted"}

    def _motion_search_unavailable_reason(self) -> str:
        # Do not issue even the first challenge while the concrete release
        # boundary is incomplete.  This bounded status is stable for the local
        # action API and cannot be changed by deployment settings.
        return "unsafe"

    def _clear_motion_search_confirmation_locked(self) -> None:
        self._motion_search_challenge = ""
        self._motion_search_confirmation_expires_at = 0.0
        self._motion_search_stop_generation = -1
        self._motion_search_authorization_generation = -1

    def _invalidate_motion_search_confirmation(self) -> None:
        # STOP generation is advanced before this helper is called, so even a
        # concurrent confirmation already holding this lock cannot validate
        # the old challenge.  Avoid ever making STOP wait behind SDK prepare.
        if self._motion_search_confirmation_lock.acquire(blocking=False):
            try:
                self._clear_motion_search_confirmation_locked()
            finally:
                self._motion_search_confirmation_lock.release()

    def _arm_motion_locked(
        self,
        *,
        expected_stop_generation: Optional[int] = None,
        expected_authorization_generation: Optional[int] = None,
    ) -> str:
        """Reject every internal arming call until release permits exist."""

        del expected_stop_generation, expected_authorization_generation
        raise RuntimeError(_MOTION_RELEASE_BLOCKER)

    def emergency_stop_motion(self) -> str:
        """Close software gates first, then request a controller halt."""

        self._motion_abort_event.set()
        adapter = self.xarm_motion_adapter
        # Advance the global generation before waiting on any feature-specific
        # lock or in-flight SDK write. A capture confirmation already in
        # preflight can therefore never start after this STOP.  The Teach
        # pending fence is published under this same short lock: its durable
        # final mark holds the lock through the recorder state transition, so
        # STOP and finalization have one total order with no check/mark gap.
        with self._motion_lock:
            self._workspace_teach_invalidation_pending.set()
            self._motion_stop_generation += 1
            self._motion_authorization_generation += 1
            self._motion_authorization_expires_at = 0.0
            self._motion_armed = False
            self._motion_live = False
        self._invalidate_workspace_boundary()
        revoke_commands = getattr(adapter, "revoke_commands", None)
        if callable(revoke_commands):
            revoke_commands()
        if self._capture_control_lock.acquire(blocking=False):
            try:
                self._clear_capture_confirmation_locked()
            finally:
                self._capture_control_lock.release()
        self._invalidate_motion_search_confirmation()
        # Dispatch the generic controller halt before invoking any optional
        # feature controller.  A capture implementation is injected code and
        # its cancellation hook may block; it must never hold up the one halt
        # command common to every motion-capable deployment.
        motion_halt_error: Optional[BaseException] = None
        if adapter is not None:
            try:
                adapter.halt()
            except Exception as exc:
                motion_halt_error = exc
                with self._motion_lock:
                    self._motion_fault_reason = "halt: {}".format(type(exc).__name__)
        self._invalidate_workspace_teach(blocking=False, request=False)

        capture_halt_error: Optional[BaseException] = None
        cancel_capture = getattr(self.capture_run_controller, "cancel", None)
        if callable(cancel_capture):
            try:
                cancel_capture()
            except Exception as exc:
                capture_halt_error = exc
                LOGGER.error(
                    "Could not halt commissioned capture motion",
                    exc_info=True,
                )
        if adapter is None:
            if capture_halt_error is not None:
                raise RuntimeError("Capture motion halt failed") from capture_halt_error
            return "Motion locked (no live adapter configured)"
        if motion_halt_error is not None:
            self._enqueue_motion_metric("halt_failed")
            raise motion_halt_error
        self._enqueue_motion_metric("halted")
        if capture_halt_error is not None:
            raise RuntimeError("Capture motion halt failed") from capture_halt_error
        return "Motion LOCKED; controller halt requested"

    def request_software_stop(self) -> str:
        """Stop every active in-process physical owner without enabling motion.

        The operation is idempotent: gates and cancellation signals are closed
        before the controller halt is requested, and an already-idle runtime
        returns ``idle``.  No error clear, motor enable, mode change, recovery,
        target coordinate, or movement command is available through this seam.
        """

        teach_active = self._workspace_teach_blocks_physical_operation()
        self._motion_abort_event.set()
        # Publish the Teach fence in the same linearization lane as its final
        # in-memory mark.  This lock is never held across controller calls,
        # filesystem persistence, or an operation-transition lock.
        with self._motion_lock:
            self._workspace_teach_invalidation_pending.set()
            motion_active = self._motion_armed or self._motion_live
        with self._software_stop_lock:
            active = bool(
                self._capture_operation_lock.locked()
                or self._hand_training_operation_lock.locked()
                or self._petri_run_lock.locked()
                or motion_active
                or teach_active
            )
            self._petri_cancel_event.set()
            cancel_hand_training = getattr(
                self.hand_training_controller, "cancel", None
            )
            if callable(cancel_hand_training):
                try:
                    cancel_hand_training()
                except Exception:
                    LOGGER.exception("Could not cancel hand training during STOP")
            if self._operations_lock.acquire(blocking=False):
                try:
                    self._clear_petri_confirmation_locked()
                    self._clear_recovery_confirmation_locked()
                    if self._petri_run_lock.locked():
                        petri = dict(self._petri_status)
                        petri["state"] = "stopping"
                        self._petri_status = petri
                    if self._recovery_status.get("state") in {
                        "starting",
                        "running",
                    }:
                        recovery = dict(self._recovery_status)
                        recovery["state"] = "stopping"
                        self._recovery_status = recovery
                finally:
                    self._operations_lock.release()
            if self._manual_review_lock.acquire(blocking=False):
                try:
                    self._clear_manual_review_challenge_locked()
                finally:
                    self._manual_review_lock.release()
            try:
                self.emergency_stop_motion()
            except Exception:
                LOGGER.exception("Universal local software STOP failed")
                return "error"
            if self._safety_configuration_lock.acquire(blocking=False):
                try:
                    self._clear_safety_configuration_challenge_locked()
                finally:
                    self._safety_configuration_lock.release()
            return "accepted" if active else "idle"

    def _petri_recipe_status(self) -> Mapping[str, Any]:
        """Return only immutable, display-safe recipe identity fields."""

        recipe = getattr(self.petri_process_controller, "recipe", None)
        recipe_id = _bounded_public_identifier(
            getattr(recipe, "recipe_id", ""), limit=64
        )
        recipe_version = _bounded_public_identifier(
            getattr(recipe, "recipe_version", ""), limit=32
        )
        profile_sha256 = str(getattr(recipe, "process_profile_sha256", "") or "")
        valid = bool(
            recipe_id
            and recipe_version
            and re.fullmatch(r"[0-9a-f]{64}", profile_sha256)
        )
        return {
            "selected": valid,
            "recipe_id": recipe_id if valid else "",
            "recipe_version": recipe_version if valid else "",
            "process_profile_sha256": profile_sha256 if valid else "",
        }

    def _operator_preflight_status(
        self,
        *,
        recipe: Mapping[str, Any],
        cameras: Mapping[str, Any],
        xarm: Mapping[str, Any],
        sampling_tool: Mapping[str, Any],
        datahub: Mapping[str, Any],
        motion: Mapping[str, Any],
        site_safety: Mapping[str, Any],
        controller_firmware: Mapping[str, Any],
        ota: Mapping[str, Any],
        durable_petri: Mapping[str, Any],
    ) -> Mapping[str, Any]:
        """Build the read-only #327 admission explanation.

        This status is diagnostic only.  It neither issues nor consumes a
        motion permit; the signed one-use permit remains authoritative at the
        concrete controller boundary.
        """

        blockers: List[str] = []

        def block(code: str, condition: bool) -> None:
            if condition and code not in blockers and len(blockers) < 24:
                blockers.append(code)

        with self._lock:
            started = self._started
        tool_camera = cameras.get("tool")
        workspace_camera = cameras.get("workspace")
        tool_camera = tool_camera if isinstance(tool_camera, Mapping) else {}
        workspace_camera = (
            workspace_camera if isinstance(workspace_camera, Mapping) else {}
        )

        def camera_ready(value: Mapping[str, Any]) -> bool:
            return bool(value.get("state") == "running" and value.get("fresh") is True)

        xarm_ready = bool(
            xarm.get("configured") is True
            and xarm.get("connected") is True
            and xarm.get("healthy") is True
            and xarm.get("fresh") is True
            and xarm.get("error_code") == 0
            and xarm.get("warning_code") == 0
            and xarm.get("moving") is False
        )
        tool_ready = bool(
            sampling_tool.get("configured") is True
            and sampling_tool.get("ready") is True
            and sampling_tool.get("fault_latched") is not True
        )
        datahub_ready = bool(
            datahub.get("configured") is True
            and datahub.get("available") is True
            and datahub.get("dataset_binding_verified") is True
            and datahub.get("dataset_binding_mismatch") is not True
            and int(datahub.get("dead_letters") or 0) == 0
        )
        permit_ready = bool(
            self.motion_live_capable and motion.get("release_valid") is True
        )
        ota_state = str(ota.get("status") or "unavailable")

        block("runtime_not_started", not started)
        block("runtime_fatal", self._fatal_event.is_set())
        block("restart_pending", self._restart_pending)
        block("recipe_not_selected", recipe.get("selected") is not True)
        block("tool_camera_not_ready", not camera_ready(tool_camera))
        block("workspace_camera_not_ready", not camera_ready(workspace_camera))
        block("xarm_not_ready", not xarm_ready)
        block("sampling_tool_not_ready", not tool_ready)
        block("datahub_not_ready", not datahub_ready)
        block("site_safety_not_ready", site_safety.get("ready") is not True)
        block(
            "controller_firmware_not_ready",
            controller_firmware.get("ready") is not True,
        )
        block(
            _MOTION_RELEASE_BLOCKER,
            motion.get("release_valid") is not True,
        )
        block(
            _MOTION_PERMIT_BLOCKER,
            motion.get("release_valid") is True and not permit_ready,
        )
        block("motion_fault", bool(motion.get("fault")))
        block(
            "physical_operation_active",
            self._capture_operation_lock.locked()
            or self._petri_run_lock.locked()
            or motion.get("armed") is True
            or motion.get("live") is True,
        )
        block(
            "supervised_recovery_required",
            durable_petri.get("recovery_required") is True,
        )
        block("ota_active", ota_state in {"checking", "busy", "pending_restart"})

        return {
            "read_only": True,
            "ready": not blockers,
            "motion_permit_required": True,
            "motion_permit_ready": permit_ready,
            "blockers": blockers,
            "components": {
                "xarm": "ready" if xarm_ready else "blocked",
                "tool_camera": ("ready" if camera_ready(tool_camera) else "blocked"),
                "workspace_camera": (
                    "ready" if camera_ready(workspace_camera) else "blocked"
                ),
                "sampling_tool": "ready" if tool_ready else "blocked",
                "datahub": "ready" if datahub_ready else "blocked",
                "site_safety": (
                    "ready" if site_safety.get("ready") is True else "blocked"
                ),
                "controller_firmware": (
                    "ready" if controller_firmware.get("ready") is True else "blocked"
                ),
                "motion_permit": "ready" if permit_ready else "blocked",
                "ota": (
                    "blocked"
                    if ota_state in {"checking", "busy", "pending_restart", "error"}
                    else "ready"
                ),
            },
        }

    def operator_operations_status(
        self,
        *,
        camera_snapshot: Optional[Mapping[str, Any]] = None,
        xarm_snapshot: Optional[Mapping[str, Any]] = None,
        sampling_tool_snapshot: Optional[Mapping[str, Any]] = None,
        datahub_snapshot: Optional[Mapping[str, Any]] = None,
        motion_snapshot: Optional[Mapping[str, Any]] = None,
        site_safety_snapshot: Optional[Mapping[str, Any]] = None,
        controller_firmware_snapshot: Optional[Mapping[str, Any]] = None,
        ota_snapshot: Optional[Mapping[str, Any]] = None,
    ) -> Mapping[str, Any]:
        """Return one bounded contract for the official operations dashboard."""

        now = float(self._monotonic())
        with self._operations_lock:
            petri = dict(self._petri_status)
            recovery = dict(self._recovery_status)
            petri_confirming = bool(
                self._petri_confirmation_challenge
                and self._petri_confirmation_expires_at > now
            )
            recovery_confirming = bool(
                self._recovery_confirmation_challenge
                and self._recovery_confirmation_expires_at > now
            )
            if self._petri_confirmation_expires_at > 0.0 and not petri_confirming:
                self._clear_petri_confirmation_locked()
            if self._recovery_confirmation_expires_at > 0.0 and not recovery_confirming:
                self._clear_recovery_confirmation_locked()
        durable_petri = self._petri_process_durable_status()
        if durable_petri["state"] in {"FAULT_LOCKED", "RECOVERY_REQUIRED"}:
            petri["state"] = "error"
            petri["error_code"] = durable_petri["error_code"] or "recovery_required"
        elif durable_petri["state"] == "COMPLETE":
            petri["state"] = "completed"
        elif durable_petri["state"] == "CANCELLED":
            petri["state"] = "cancelled"
        if self._petri_run_lock.locked():
            petri["state"] = "running"
        elif petri_confirming:
            petri["state"] = "confirming"
        if recovery_confirming:
            recovery["state"] = "confirming"

        total_steps = (
            _bounded_nonnegative_integer(petri.get("total_steps"), maximum=10_000) or 0
        )
        completed_steps = (
            _bounded_nonnegative_integer(
                petri.get("completed_steps"), maximum=total_steps or 10_000
            )
            or 0
        )
        estimated_seconds = (
            _bounded_finite_number(petri.get("estimated_seconds"), maximum=86_400.0)
            or 0.0
        )
        started_at = (
            _bounded_finite_number(petri.get("started_at"), maximum=1e10) or 0.0
        )
        elapsed = max(0.0, now - started_at) if started_at else 0.0
        if total_steps > 0:
            progress = min(100, int(round(100.0 * completed_steps / total_steps)))
        else:
            progress = 0
        eta = max(0.0, estimated_seconds - elapsed) if estimated_seconds else 0.0

        with self._registry_lock:
            registry = dict(self._registry_status)
        registry_summary = self._petri_registry_status()
        datahub = dict(self._datahub_runtime_status())

        with self._motion_lock:
            recovery_fault = bool(self._motion_fault_reason)
        recipe = self._petri_recipe_status()
        cameras = (
            dict(camera_snapshot)
            if isinstance(camera_snapshot, Mapping)
            else dict(self._camera_health_metrics())
        )
        xarm = (
            dict(xarm_snapshot)
            if isinstance(xarm_snapshot, Mapping)
            else dict(self.xarm_status())
        )
        sampling_tool = (
            dict(sampling_tool_snapshot)
            if isinstance(sampling_tool_snapshot, Mapping)
            else dict(self.sampling_tool_status())
        )
        datahub_for_preflight = (
            dict(datahub_snapshot)
            if isinstance(datahub_snapshot, Mapping)
            else dict(datahub)
        )
        motion = (
            dict(motion_snapshot)
            if isinstance(motion_snapshot, Mapping)
            else dict(self.motion_status(xarm_snapshot=xarm))
        )
        site_safety = (
            dict(site_safety_snapshot)
            if isinstance(site_safety_snapshot, Mapping)
            else dict(
                self.site_safety_status(
                    camera_snapshot=cameras,
                    sampling_tool_snapshot=sampling_tool,
                )
            )
        )
        controller_firmware = (
            dict(controller_firmware_snapshot)
            if isinstance(controller_firmware_snapshot, Mapping)
            else dict(self.controller_firmware_status(xarm_snapshot=xarm))
        )
        ota = (
            dict(ota_snapshot)
            if isinstance(ota_snapshot, Mapping)
            else dict(self.ota_status())
        )
        preflight = self._operator_preflight_status(
            recipe=recipe,
            cameras=cameras,
            xarm=xarm,
            sampling_tool=sampling_tool,
            datahub=datahub_for_preflight,
            motion=motion,
            site_safety=site_safety,
            controller_firmware=controller_firmware,
            ota=ota,
            durable_petri=durable_petri,
        )
        ota_history = ota.get("history")
        if not isinstance(ota_history, list):
            ota_history = []
        return {
            "schema_version": 2,
            "recipe": recipe,
            "preflight": preflight,
            "ota_history": [dict(row) for row in ota_history[-8:]],
            "petri": {
                "configured": self.petri_process_configured,
                "state": self._closed_operation_state(
                    petri.get("state"),
                    {
                        "unavailable",
                        "ready",
                        "confirming",
                        "starting",
                        "running",
                        "stopping",
                        "completed",
                        "cancelled",
                        "error",
                    },
                ),
                "action_allowed": bool(
                    self.petri_process_configured
                    and not self._petri_run_lock.locked()
                    and not self._petri_durable_owner_blocks_physical_operation()
                    and self._physical_action_environment_ready()
                ),
                "stop_allowed": self._petri_run_lock.locked(),
                "completed_steps": min(completed_steps, total_steps or completed_steps),
                "total_steps": total_steps,
                "progress_percent": progress,
                "eta_seconds": eta,
                "message": _bounded_status_text(petri.get("message")),
                "error_code": _bounded_error_code(petri.get("error_code")),
                "process_state": durable_petri["state"],
                "run_id": durable_petri["run_id"],
                "current_plate_id": durable_petri["current_plate_id"],
                "transition_sequence": durable_petri["transition_sequence"],
                "local_evidence_committed": durable_petri["local_evidence_committed"],
                "upload_queued": durable_petri["upload_queued"],
                "recovery_required": durable_petri["recovery_required"],
            },
            "recovery": {
                "configured": self.recovery_controller is not None,
                "state": self._closed_operation_state(
                    recovery.get("state"),
                    {
                        "unavailable",
                        "idle",
                        "confirming",
                        "starting",
                        "running",
                        "stopping",
                        "completed",
                        "error",
                    },
                ),
                "action_allowed": bool(
                    self.recovery_controller is not None
                    and recovery_fault
                    and self._physical_action_environment_ready()
                ),
                "stop_allowed": bool(recovery.get("state") in {"starting", "running"}),
                "message": _bounded_status_text(recovery.get("message")),
                "error_code": _bounded_error_code(recovery.get("error_code")),
            },
            "registration": {
                "configured": self.readiness_client is not None,
                "ready": registry.get("ready") is True,
                "status": (
                    str(registry.get("status"))
                    if registry.get("status")
                    in {"off", "pending", "verified", "incomplete", "error"}
                    else "error"
                ),
                "action_allowed": bool(
                    self.readiness_client is not None
                    and not self._restart_pending
                    and not self._fatal_event.is_set()
                ),
            },
            "datahub": datahub,
            "identity": {
                "configured": registry_summary["configured"],
                "state": (
                    "registry_ready"
                    if registry_summary["registry_ready"]
                    else (
                        "registry_error"
                        if registry_summary["configured"]
                        else "scanner_unavailable"
                    )
                ),
                "action_allowed": False,
                "plates": registry_summary["plates"],
            },
            "manual_review": {
                "configured": registry_summary["review_ready"],
                "pending": registry_summary["pending"],
                "action_allowed": bool(
                    registry_summary["review_ready"]
                    and registry_summary["pending"] > 0
                    and not self._restart_pending
                    and not self._fatal_event.is_set()
                ),
                "state": (
                    "pending"
                    if registry_summary["review_ready"]
                    and registry_summary["pending"] > 0
                    else (
                        "idle"
                        if registry_summary["review_ready"]
                        else (
                            "error"
                            if registry_summary["configured"]
                            and not registry_summary["registry_ready"]
                            else "unavailable"
                        )
                    )
                ),
            },
            "history": {
                "configured": registry_summary["configured"],
                "records": registry_summary["records"],
                "recent": registry_summary["recent"],
                "export_available": False,
            },
        }

    def _petri_registry_status(self) -> Mapping[str, Any]:
        """Read one bounded registry snapshot without exposing observations."""

        result = {
            "configured": self.petri_registry is not None,
            "registry_ready": False,
            "review_ready": False,
            "plates": 0,
            "pending": 0,
            "records": 0,
            "recent": [],
        }
        registry = self.petri_registry
        if registry is None:
            return result
        summary_reader = getattr(registry, "operations_snapshot", None)
        preview_reader = getattr(registry, "pending_review_image", None)
        if not callable(summary_reader):
            return result
        try:
            summary = summary_reader(limit=20)
        except Exception:
            LOGGER.warning("Petri registry operations snapshot failed", exc_info=True)
            return result
        if not isinstance(summary, Mapping) or summary.get("schema_version") != 1:
            return result
        pending_count = _bounded_nonnegative_integer(
            summary.get("pending_review_count"),
            maximum=1_000_000_000,
        )
        history_count = _bounded_nonnegative_integer(
            summary.get("observation_count"),
            maximum=1_000_000_000,
        )
        plate_count = _bounded_nonnegative_integer(
            summary.get("plate_count"),
            maximum=1_000_000,
        )
        cluster_count = _bounded_nonnegative_integer(
            summary.get("cluster_count"),
            maximum=1_000_000_000,
        )
        accepted_manual_count = _bounded_nonnegative_integer(
            summary.get("accepted_manual_count"),
            maximum=1_000_000_000,
        )
        recent_raw = summary.get("recent")
        if (
            pending_count is None
            or history_count is None
            or plate_count is None
            or cluster_count is None
            or accepted_manual_count is None
            or not isinstance(recent_raw, list)
            or len(recent_raw) > 20
        ):
            return result
        recent = []
        for row in recent_raw:
            if not isinstance(row, Mapping) or type(row.get("selected")) is not bool:
                return result
            observation_id = _bounded_public_identifier(
                row.get("observation_id"), limit=120
            )
            cluster_id = _bounded_public_identifier(row.get("cluster_id"), limit=120)
            plate_id = _bounded_public_identifier(row.get("plate_id"), limit=64)
            captured_at = _bounded_status_text(row.get("captured_at"), limit=64)
            area = _bounded_finite_number(row.get("area_px2"), maximum=1e12)
            confidence = _bounded_finite_number(row.get("confidence"), maximum=1.0)
            status = row.get("status")
            selected = row.get("selected")
            if (
                not observation_id
                or not cluster_id
                or not plate_id
                or not captured_at
                or area is None
                or confidence is None
                or status not in _PETRI_OBSERVATION_STATES
                or (status == "requires_review" and selected is not False)
                or (status == "accepted_manual" and selected is not True)
            ):
                return result
            recent.append(
                {
                    "observation_id": observation_id,
                    "cluster_id": cluster_id,
                    "plate_id": plate_id,
                    "captured_at": captured_at,
                    "area_px2": area,
                    "confidence": confidence,
                    "status": status,
                    "selected": selected,
                }
            )
        result.update(
            {
                "registry_ready": True,
                "review_ready": bool(
                    self._petri_artifact_root_available() and callable(preview_reader)
                ),
                "plates": int(plate_count),
                "pending": int(pending_count),
                "records": int(history_count),
                "recent": recent,
            }
        )
        return result

    def _petri_artifact_root_available(self) -> bool:
        artifact_root = self.petri_artifact_root
        if artifact_root is None:
            return False
        try:
            state_root = Path(self.settings.state_dir).resolve(strict=True)
            resolved_artifacts = artifact_root.resolve(strict=True)
            relative_artifacts = resolved_artifacts.relative_to(state_root)
        except (AttributeError, OSError, RuntimeError, ValueError):
            return False
        return bool(
            relative_artifacts.parts
            and resolved_artifacts.is_dir()
            and not artifact_root.is_symlink()
        )

    @staticmethod
    def _closed_operation_state(value: Any, allowed: set[str]) -> str:
        return str(value) if isinstance(value, str) and value in allowed else "error"

    def _physical_action_environment_ready(
        self,
        *,
        allow_reserved: bool = False,
        allow_petri_recovery: bool = False,
    ) -> bool:
        with self._lock:
            started = self._started
        with self._motion_lock:
            motion_busy = self._motion_armed or self._motion_live
        return bool(
            started
            and not self._restart_pending
            and not self._fatal_event.is_set()
            and not self._ota_lock.locked()
            and (allow_reserved or not self._capture_operation_lock.locked())
            and not self._workspace_teach_blocks_physical_operation()
            and (
                allow_petri_recovery
                or not self._petri_durable_owner_blocks_physical_operation()
            )
            and not motion_busy
        )

    def request_registration_verification(self) -> Mapping[str, Any]:
        """Run only the existing authenticated, read-only readiness check."""

        if self.readiness_client is None:
            return {"status": "unavailable"}
        if (
            self._restart_pending
            or self._fatal_event.is_set()
            or self._ota_lock.locked()
            or self._capture_operation_lock.locked()
        ):
            return {"status": "busy"}
        try:
            result = self.verify_device_registration_now()
        except Exception:
            LOGGER.warning(
                "Manual device registration verification failed", exc_info=True
            )
            return {"status": "error"}
        return {"status": "verified" if result.get("ready") is True else "incomplete"}

    def request_manual_review(
        self,
        challenge: Optional[str] = None,
    ) -> Mapping[str, Any]:
        """Select one bounded pending observation after a one-use confirmation."""

        supplied = _validated_optional_challenge(challenge)
        if supplied is None:
            return {"status": "confirmation_required"}
        registry = self.petri_registry
        if registry is None:
            return {"status": "unavailable"}
        pending_reader = getattr(registry, "pending_reviews", None)
        selector = getattr(registry, "select_observation", None)
        preview_reader = getattr(registry, "pending_review_image", None)
        if (
            not callable(pending_reader)
            or not callable(selector)
            or not callable(preview_reader)
            or not self._petri_artifact_root_available()
        ):
            return {"status": "unavailable"}
        if (
            self._restart_pending
            or self._fatal_event.is_set()
            or self._ota_lock.locked()
            or self._capture_operation_lock.locked()
        ):
            return {"status": "busy"}
        now = float(self._monotonic())
        stop_generation = self._motion_stop_token()
        with self._manual_review_lock:
            if not supplied:
                self._clear_manual_review_challenge_locked()
                try:
                    pending = pending_reader(limit=1)
                except Exception:
                    LOGGER.warning(
                        "Manual-review candidate lookup failed",
                        exc_info=True,
                    )
                    return {"status": "error"}
                if not isinstance(pending, (list, tuple)) or len(pending) != 1:
                    return {"status": "unavailable" if not pending else "error"}
                candidate = self._bounded_manual_review_candidate(pending[0])
                if candidate is None:
                    return {"status": "error"}
                token = secrets.token_hex(16)
                self._manual_review_challenge = token
                self._manual_review_expires_at = (
                    now + _MANUAL_REVIEW_CONFIRMATION_SECONDS
                )
                self._manual_review_stop_generation = stop_generation
                self._manual_review_observation_id = candidate["observation_id"]
                self._manual_review_candidate = candidate
                self._manual_review_previewed = False
                return {
                    "status": "confirm",
                    "challenge": token,
                    "expires_in_seconds": int(_MANUAL_REVIEW_CONFIRMATION_SECONDS),
                    "candidate": dict(candidate),
                }
            confirmed = bool(
                self._manual_review_challenge
                and self._manual_review_expires_at > now
                and self._manual_review_stop_generation == stop_generation
                and self._manual_review_observation_id
                and self._manual_review_previewed
                and secrets.compare_digest(
                    self._manual_review_challenge,
                    supplied,
                )
            )
            observation_id = self._manual_review_observation_id
            self._clear_manual_review_challenge_locked()
            if not confirmed:
                return {"status": "confirmation_required"}
            # Keep the registry call inside the review lock so a second local
            # request cannot select the same observation concurrently.  The
            # challenge has already been consumed and cannot be replayed if
            # the durable transaction raises.
            try:
                selected = selector(observation_id)
            except Exception:
                LOGGER.warning("Manual-review selection failed", exc_info=True)
                return {"status": "error"}
            if (
                not isinstance(selected, Mapping)
                or selected.get("observation_id") != observation_id
                or selected.get("selected") is not True
            ):
                return {"status": "error"}
            return {
                "status": "accepted",
                "observation_id": observation_id,
            }

    def manual_review_preview(self) -> bytes:
        """Return the preview bound to the current one-use review challenge."""

        registry = self.petri_registry
        artifact_root = self.petri_artifact_root
        preview_reader = getattr(registry, "pending_review_image", None)
        if registry is None or artifact_root is None or not callable(preview_reader):
            raise RuntimeError("Manual-review preview is unavailable")
        now = float(self._monotonic())
        stop_generation = self._motion_stop_token()
        with self._manual_review_lock:
            if (
                not self._manual_review_challenge
                or self._manual_review_expires_at <= now
                or self._manual_review_stop_generation != stop_generation
                or not self._manual_review_observation_id
            ):
                self._clear_manual_review_challenge_locked()
                raise RuntimeError("Manual-review confirmation is unavailable")
            observation_id = self._manual_review_observation_id
            try:
                png = preview_reader(observation_id, artifact_root)
                if not isinstance(png, bytes) or not png or len(png) > 8 * 1024 * 1024:
                    raise ValueError("review image is invalid")
                try:
                    import cv2
                    import numpy as np
                except ImportError as exc:
                    raise RuntimeError("OpenCV preview decoder is unavailable") from exc
                image = cv2.imdecode(
                    np.frombuffer(png, dtype=np.uint8), cv2.IMREAD_COLOR
                )
                if image is None or not hasattr(image, "shape") or len(image.shape) < 2:
                    raise ValueError("review image cannot be decoded")
                image_height = int(image.shape[0])
                image_width = int(image.shape[1])
                if image_height < 1 or image_width < 1:
                    raise ValueError("review image dimensions are invalid")
                scale = min(1.0, 600.0 / image_width, 338.0 / image_height)
                if scale < 1.0:
                    image = cv2.resize(
                        image,
                        (
                            max(1, int(math.floor(image_width * scale))),
                            max(1, int(math.floor(image_height * scale))),
                        ),
                        interpolation=cv2.INTER_AREA,
                    )
                try:
                    from main.vision.cameras import encode_jpeg
                except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                    from vision.cameras import encode_jpeg  # type: ignore[no-redef]
                jpeg = encode_jpeg(image, quality=85)
                try:
                    from main.vision.mjpeg import _is_bounded_baseline_jpeg
                except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                    from vision.mjpeg import (  # type: ignore[no-redef]
                        _is_bounded_baseline_jpeg,
                    )
                if len(
                    jpeg
                ) > _MANUAL_REVIEW_PREVIEW_MAX_BYTES or not _is_bounded_baseline_jpeg(
                    jpeg
                ):
                    raise ValueError("review JPEG is invalid")
            except Exception:
                self._clear_manual_review_challenge_locked()
                raise
            if (
                self._manual_review_expires_at <= float(self._monotonic())
                or self._manual_review_stop_generation != self._motion_stop_token()
                or self._manual_review_observation_id != observation_id
            ):
                self._clear_manual_review_challenge_locked()
                raise RuntimeError("Manual-review confirmation was invalidated")
            self._manual_review_previewed = True
            return jpeg

    @staticmethod
    def _bounded_manual_review_candidate(value: Any) -> Optional[Mapping[str, Any]]:
        if not isinstance(value, Mapping):
            return None
        observation_id = _bounded_public_identifier(
            value.get("observation_id"),
            limit=64,
        )
        plate_id = _bounded_public_identifier(value.get("plate_id"), limit=64)
        cluster_id = _bounded_public_identifier(value.get("cluster_id"), limit=64)
        captured_at = _bounded_status_text(value.get("captured_at"), limit=64)
        confidence = _bounded_finite_number(value.get("confidence"), maximum=1.0)
        area_px2 = _bounded_finite_number(value.get("area_px2"), maximum=1e12)
        if (
            not observation_id
            or not plate_id
            or not cluster_id
            or _SAFE_REGISTRY_IDENTIFIER.fullmatch(observation_id) is None
            or _SAFE_REGISTRY_IDENTIFIER.fullmatch(plate_id) is None
            or _SAFE_REGISTRY_IDENTIFIER.fullmatch(cluster_id) is None
            or not captured_at
            or any(ord(character) < 32 for character in captured_at)
            or confidence is None
            or confidence < 0.0
            or area_px2 is None
            or area_px2 < 0.0
        ):
            return None
        return {
            "observation_id": observation_id,
            "plate_id": plate_id,
            "cluster_id": cluster_id,
            "captured_at": captured_at,
            "confidence": confidence,
            "area_px2": area_px2,
        }

    def _clear_manual_review_challenge_locked(self) -> None:
        self._manual_review_challenge = ""
        self._manual_review_expires_at = 0.0
        self._manual_review_stop_generation = -1
        self._manual_review_observation_id = ""
        self._manual_review_candidate = {}
        self._manual_review_previewed = False

    def _petri_operator_confirmation_context(self) -> Tuple[Any, ...]:
        """Fingerprint every immutable context shown before Petri Start."""

        recipe = self._petri_recipe_status()
        if recipe.get("selected") is not True:
            return ()
        try:
            durable = self._petri_process_durable_status()
        except Exception:
            return ()
        with self._motion_lock:
            authorization_generation = self._motion_authorization_generation
            fault = _bounded_error_code(self._motion_fault_reason)
        return (
            recipe["recipe_id"],
            recipe["recipe_version"],
            recipe["process_profile_sha256"],
            _bounded_public_identifier(
                getattr(self.settings, "current_version", ""), limit=64
            ),
            _bounded_public_identifier(
                getattr(self.settings, "site_safety_profile_sha256", ""),
                limit=64,
            ),
            int(authorization_generation),
            fault,
            durable.get("state"),
            durable.get("run_id"),
            durable.get("recovery_required") is True,
        )

    def _recovery_operator_confirmation_context(self) -> Tuple[Any, ...]:
        """Fingerprint the exact fault/run/home profile under review."""

        try:
            durable = self._petri_process_durable_status()
        except Exception:
            return ()
        trajectory = getattr(self.recovery_controller, "trajectory", None)
        trajectory_sha256 = _bounded_public_identifier(
            getattr(trajectory, "profile_sha256", ""), limit=64
        )
        with self._motion_lock:
            authorization_generation = self._motion_authorization_generation
            fault = _bounded_error_code(self._motion_fault_reason)
        if not fault and durable.get("recovery_required") is not True:
            return ()
        return (
            trajectory_sha256,
            int(authorization_generation),
            fault,
            durable.get("state"),
            durable.get("run_id"),
            durable.get("recovery_required") is True,
        )

    def request_petri_start(self, challenge: Optional[str] = None) -> Mapping[str, Any]:
        """Admit one commissioned Petri run through a one-use local challenge."""

        supplied = _validated_optional_challenge(challenge)
        if supplied is None:
            return {"status": "confirmation_required"}
        if not self.petri_process_configured:
            return {"status": "unavailable"}
        if self._petri_durable_owner_blocks_physical_operation():
            return {"status": "busy"}
        if not self._physical_action_environment_ready():
            return {"status": "unsafe"}
        try:
            motion = self.motion_status()
        except Exception:
            return {"status": "unsafe"}
        if not (
            self.motion_live_capable
            and isinstance(motion, Mapping)
            and motion.get("release_valid") is True
        ):
            return {"status": "unsafe"}
        confirmation_context = self._petri_operator_confirmation_context()
        if not confirmation_context:
            return {"status": "unsafe"}
        now = float(self._monotonic())
        with self._operations_lock:
            if not supplied:
                self._clear_petri_confirmation_locked()
                token = secrets.token_hex(16)
                self._petri_confirmation_challenge = token
                self._petri_confirmation_expires_at = now + _PETRI_CONFIRMATION_SECONDS
                self._petri_confirmation_stop_generation = self._motion_stop_token()
                self._petri_confirmation_context = confirmation_context
                return {
                    "status": "confirm",
                    "challenge": token,
                    "expires_in_seconds": int(_PETRI_CONFIRMATION_SECONDS),
                }
            confirmed = bool(
                self._petri_confirmation_challenge
                and self._petri_confirmation_expires_at >= now
                and self._petri_confirmation_stop_generation
                == self._motion_stop_token()
                and self._petri_confirmation_context == confirmation_context
                and secrets.compare_digest(self._petri_confirmation_challenge, supplied)
            )
            stop_generation = self._petri_confirmation_stop_generation
            self._clear_petri_confirmation_locked()
        if not confirmed:
            return {"status": "confirmation_required"}
        if not self._reserve_petri_operation(stop_generation):
            return {"status": "busy"}
        return {"status": "accepted"}

    def _reserve_petri_operation(self, stop_generation: int) -> bool:
        if not self._operation_transition_lock.acquire(blocking=False):
            return False
        reserved_petri = False
        reserved_operation = False
        spawned = False
        try:
            if (
                self._workspace_teach_blocks_physical_operation()
                or self._ota_lock.locked()
                or self._petri_durable_owner_blocks_physical_operation()
            ):
                return False
            reserved_petri = self._petri_run_lock.acquire(blocking=False)
            if not reserved_petri:
                return False
            reserved_operation = self._capture_operation_lock.acquire(blocking=False)
            if not reserved_operation:
                return False
            with self._motion_lock:
                if stop_generation != self._motion_stop_generation:
                    return False
                self._motion_abort_event.clear()
                self._petri_cancel_event.clear()
            estimate = self.petri_process_estimate()
            with self._operations_lock:
                self._petri_status = {
                    "state": "starting",
                    "completed_steps": 0,
                    "total_steps": int(estimate["total_steps"]),
                    "estimated_seconds": float(estimate["estimated_seconds"]),
                    "started_at": float(self._monotonic()),
                    "message": "",
                    "error_code": "",
                }
            self._spawn(
                "petri-process-run",
                lambda: self._run_reserved_petri(stop_generation),
                supervised=False,
            )
            spawned = True
            return True
        except Exception:
            LOGGER.warning(
                "Could not start commissioned Petri operation", exc_info=True
            )
            return False
        finally:
            self._operation_transition_lock.release()
            if not spawned:
                if reserved_operation and self._capture_operation_lock.locked():
                    self._capture_operation_lock.release()
                if reserved_petri and self._petri_run_lock.locked():
                    self._petri_run_lock.release()

    def _run_reserved_petri(self, stop_generation: int) -> None:
        controller = self.petri_process_controller

        def progress(message: str = "") -> None:
            with self._operations_lock:
                status = dict(self._petri_status)
                total = int(status.get("total_steps") or 0)
                status["state"] = "running"
                status["completed_steps"] = min(
                    int(status.get("completed_steps") or 0) + 1,
                    total,
                )
                status["message"] = _bounded_status_text(message)
                self._petri_status = status

        try:
            result = controller.start(
                stop_requested=lambda: (
                    self._petri_cancel_event.is_set()
                    or self._motion_stopped_since(stop_generation)
                ),
                progress_callback=progress,
            )
            stopped = self._petri_cancel_event.is_set() or self._motion_stopped_since(
                stop_generation
            )
            durable = self._petri_process_durable_status()
            with self._operations_lock:
                status = dict(self._petri_status)
                if durable["recovery_required"]:
                    status["state"] = "error"
                    status["error_code"] = durable["error_code"] or "recovery_required"
                    with self._motion_lock:
                        self._motion_fault_reason = "petri_recovery_required"
                else:
                    status["state"] = "cancelled" if stopped else "completed"
                if not stopped and not durable["recovery_required"]:
                    status["completed_steps"] = int(status.get("total_steps") or 0)
                del result
                status["message"] = (
                    "Petri process requires supervised recovery"
                    if durable["recovery_required"]
                    else (
                        "Process cancelled"
                        if stopped
                        else "Commissioned Petri process completed"
                    )
                )
                self._petri_status = status
        except Exception as exc:
            LOGGER.exception("Commissioned Petri operation failed")
            durable = self._petri_process_durable_status()
            if durable["recovery_required"]:
                with self._motion_lock:
                    self._motion_fault_reason = "petri_recovery_required"
            with self._operations_lock:
                status = dict(self._petri_status)
                status.update(
                    {
                        "state": "error",
                        "message": "Petri process failed; inspect diagnostics",
                        "error_code": "petri_{}".format(type(exc).__name__)[:48],
                    }
                )
                self._petri_status = status
        finally:
            if self._capture_operation_lock.locked():
                self._capture_operation_lock.release()
            if self._petri_run_lock.locked():
                self._petri_run_lock.release()

    def request_reviewed_recovery(
        self, challenge: Optional[str] = None
    ) -> Mapping[str, Any]:
        """Admit the injected reviewed recovery through a one-use challenge."""

        supplied = _validated_optional_challenge(challenge)
        if supplied is None:
            return {"status": "confirmation_required"}
        if self.recovery_controller is None:
            return {"status": "unavailable"}
        durable_petri = self._petri_process_durable_status()
        with self._motion_lock:
            has_fault = bool(self._motion_fault_reason)
        petri_recovery = durable_petri["recovery_required"]
        if not (
            has_fault or petri_recovery
        ) or not self._physical_action_environment_ready(
            allow_petri_recovery=petri_recovery
        ):
            return {"status": "unsafe"}
        confirmation_context = self._recovery_operator_confirmation_context()
        if not confirmation_context:
            return {"status": "unsafe"}
        now = float(self._monotonic())
        with self._operations_lock:
            if not supplied:
                self._clear_recovery_confirmation_locked()
                token = secrets.token_hex(16)
                self._recovery_confirmation_challenge = token
                self._recovery_confirmation_expires_at = (
                    now + _RECOVERY_CONFIRMATION_SECONDS
                )
                self._recovery_confirmation_stop_generation = self._motion_stop_token()
                self._recovery_confirmation_context = confirmation_context
                return {
                    "status": "confirm",
                    "challenge": token,
                    "expires_in_seconds": int(_RECOVERY_CONFIRMATION_SECONDS),
                }
            confirmed = bool(
                self._recovery_confirmation_challenge
                and self._recovery_confirmation_expires_at >= now
                and self._recovery_confirmation_stop_generation
                == self._motion_stop_token()
                and self._recovery_confirmation_context == confirmation_context
                and secrets.compare_digest(
                    self._recovery_confirmation_challenge, supplied
                )
            )
            stop_generation = self._recovery_confirmation_stop_generation
            self._clear_recovery_confirmation_locked()
        if not confirmed:
            return {"status": "confirmation_required"}
        if not self._reserve_recovery_operation(stop_generation):
            return {"status": "busy"}
        with self._operations_lock:
            self._recovery_status = {
                "state": "starting",
                "message": "",
                "error_code": "",
            }
        try:
            self._spawn(
                "reviewed-recovery",
                lambda: self._run_reviewed_recovery(stop_generation),
                supervised=False,
            )
        except Exception:
            self._capture_operation_lock.release()
            with self._operations_lock:
                self._recovery_status = {
                    "state": "error",
                    "message": "Recovery worker could not start",
                    "error_code": "recovery_worker_start",
                }
            return {"status": "error"}
        return {"status": "accepted"}

    def _reserve_recovery_operation(self, stop_generation: int) -> bool:
        """Synchronously reserve the physical owner before acknowledging recovery."""

        if not self._operation_transition_lock.acquire(blocking=False):
            return False
        reserved_operation = False
        admitted = False
        try:
            if (
                self._workspace_teach_blocks_physical_operation()
                or self._ota_lock.locked()
            ):
                return False
            reserved_operation = self._capture_operation_lock.acquire(blocking=False)
            if not reserved_operation:
                return False
            durable_petri = self._petri_process_durable_status()
            petri_recovery = durable_petri["recovery_required"]
            with self._motion_lock:
                generation_matches = bool(
                    stop_generation == self._motion_stop_generation
                    and (self._motion_fault_reason or petri_recovery)
                    and not self._motion_armed
                    and not self._motion_live
                )
            if not generation_matches or not self._physical_action_environment_ready(
                allow_reserved=True,
                allow_petri_recovery=petri_recovery,
            ):
                return False
            admitted = True
            return True
        finally:
            self._operation_transition_lock.release()
            if reserved_operation and not admitted:
                self._capture_operation_lock.release()

    def _run_reviewed_recovery(self, stop_generation: int) -> None:
        with self._operations_lock:
            status = dict(self._recovery_status)
            status["state"] = "running"
            self._recovery_status = status
        try:
            try:
                self._recover_to_home_locked(expected_stop_generation=stop_generation)
                durable_petri = self._petri_process_durable_status()
                recover_petri = getattr(
                    self.petri_process_controller,
                    "supervised_recovery",
                    None,
                )
                if durable_petri["recovery_required"]:
                    if not callable(recover_petri):
                        raise RuntimeError(
                            "Durable Petri process recovery is unavailable"
                        )
                    recover_petri(
                        supervisor_id="local-operator",
                        stop_requested=lambda: self._motion_stopped_since(
                            stop_generation
                        ),
                    )
            except Exception as exc:
                LOGGER.exception("Reviewed recovery failed")
                with self._operations_lock:
                    self._recovery_status = {
                        "state": "error",
                        "message": "Recovery failed; inspect diagnostics",
                        "error_code": "recovery_{}".format(type(exc).__name__)[:48],
                    }
                return
            with self._operations_lock:
                self._recovery_status = {
                    "state": "completed",
                    "message": "Reviewed recovery completed; motion remains locked",
                    "error_code": "",
                }
        finally:
            self._capture_operation_lock.release()

    def _clear_petri_confirmation_locked(self) -> None:
        self._petri_confirmation_challenge = ""
        self._petri_confirmation_expires_at = 0.0
        self._petri_confirmation_stop_generation = -1
        self._petri_confirmation_context = ()

    def _clear_recovery_confirmation_locked(self) -> None:
        self._recovery_confirmation_challenge = ""
        self._recovery_confirmation_expires_at = 0.0
        self._recovery_confirmation_stop_generation = -1
        self._recovery_confirmation_context = ()

    def recover_to_home(
        self,
        *,
        expected_stop_generation: Optional[int] = None,
    ) -> str:
        """Run a separately commissioned return-home controller.

        This method never clears xArm errors or warnings. The injected recovery
        controller must independently verify controller health, the reviewed
        home trajectory, joint/workspace limits, and a clear work area.
        """

        if expected_stop_generation is None:
            raise RuntimeError(
                "Direct recovery is disabled; use reviewed Recovery confirmation"
            )
        with self._operation_transition_lock:
            if (
                self._workspace_teach_blocks_physical_operation()
                or self._ota_lock.locked()
                or not self._capture_operation_lock.acquire(blocking=False)
            ):
                raise RuntimeError("Another commissioned physical operation is active")
        try:
            return self._recover_to_home_locked(
                expected_stop_generation=expected_stop_generation
            )
        finally:
            self._capture_operation_lock.release()

    def _recover_to_home_locked(
        self,
        *,
        expected_stop_generation: Optional[int] = None,
    ) -> str:
        """Execute recovery while holding exclusive physical ownership."""

        controller = self.recovery_controller
        if (
            self._restart_pending
            or self._fatal_event.is_set()
            or self._ota_lock.locked()
        ):
            raise RuntimeError("Runtime restart or fatal shutdown is pending")
        if controller is None:
            raise RuntimeError("Reviewed return-to-home recovery is not commissioned")
        with self._lock:
            if not self._started:
                raise RuntimeError("Workcell services are not running")
        self._motion_abort_event.set()
        with self._motion_lock:
            if (
                expected_stop_generation is not None
                and expected_stop_generation != self._motion_stop_generation
            ):
                raise RuntimeError("Recovery confirmation was invalidated by STOP")
            self._motion_stop_generation += 1
            self._motion_authorization_generation += 1
            self._motion_authorization_expires_at = 0.0
            self._motion_armed = False
            self._motion_live = False
            stop_generation = self._motion_stop_generation
        if self.xarm_motion_adapter is not None:
            self.xarm_motion_adapter.lock_commands()

        if isinstance(controller, ReviewedHomeController) and isinstance(
            self.xarm_motion_adapter, XArmMotionAdapter
        ):
            self.xarm_motion_adapter.acknowledge_supervised_recovery()

        readiness = getattr(controller, "verify_recovery_ready", None)
        if not callable(readiness) or readiness() is not True:
            raise RuntimeError(
                "Recovery controller did not confirm a healthy, clear workcell"
            )
        if self._motion_stopped_since(stop_generation):
            raise RuntimeError("Recovery was stopped before motion could begin")
        try:
            result = controller.return_home(
                motion_stop_requested=lambda: self._motion_stopped_since(
                    stop_generation
                ),
            )
        except Exception as exc:
            self._motion_abort_event.set()
            with self._motion_lock:
                self._motion_fault_reason = "recovery: {}".format(type(exc).__name__)
            self._enqueue_motion_metric("recovery_failed")
            raise
        finally:
            if self.xarm_motion_adapter is not None:
                halt = getattr(self.xarm_motion_adapter, "halt", None)
                try:
                    if callable(halt):
                        halt()
                    else:
                        self.xarm_motion_adapter.lock_commands()
                except Exception as exc:
                    with self._motion_lock:
                        self._motion_fault_reason = "recovery_halt: {}".format(
                            type(exc).__name__
                        )
                    self._enqueue_motion_metric("recovery_halt_failed")
                    raise
        self._motion_abort_event.set()
        clear_fault = getattr(self.valve_controller, "clear_motion_fault", None)
        if callable(clear_fault):
            clear_fault()
        with self._motion_lock:
            self._motion_fault_reason = ""
        self._enqueue_motion_metric("recovered_home_and_locked")
        return str(result or "Home reached; motion remains LOCKED")

    def petri_process_estimate(self) -> Mapping[str, Any]:
        """Return a bounded estimate for the touchscreen progress display."""

        controller = self.petri_process_controller
        estimate = getattr(controller, "estimate", None)
        if not callable(estimate):
            return {"total_steps": 4, "estimated_seconds": 60.0}
        result = dict(estimate())
        steps = int(result.get("total_steps", 0))
        seconds = float(result.get("estimated_seconds", 0.0))
        if steps <= 0 or not math.isfinite(seconds) or seconds <= 0.0:
            raise RuntimeError("Petri process controller returned an invalid estimate")
        return {"total_steps": steps, "estimated_seconds": seconds}

    def start_petri_process(
        self,
        *,
        progress_callback: Optional[Callable[[str], None]] = None,
    ) -> Any:
        """Reject the retired synchronous Petri execution seam.

        The commissioned controller is reachable only through
        :meth:`request_petri_start`.  That path reserves the shared physical
        owner, consumes a one-use challenge and keeps universal STOP active.
        """

        del progress_callback
        raise RuntimeError(
            "Direct Petri start is disabled; use reviewed Petri confirmation"
        )

    def cancel_petri_process(self) -> str:
        """Cancel only the active Petri run without resetting any STOP state."""

        self._petri_cancel_event.set()
        cancel = getattr(self.petri_process_controller, "cancel", None)
        if callable(cancel):
            cancel()
        return "Petri process cancellation requested"

    def start(
        self,
        *,
        restart_callback: Optional[Callable[[], None]] = None,
    ) -> None:
        """Start configured services exactly once."""

        commissioning = self._evaluate_ota_commissioning()
        immutable_client_ready = bool(
            not getattr(self.settings, "immutable_release", False)
            or isinstance(self.ota_updater, PrivilegedOTAClient)
        )
        ota_auto_apply = commissioning.permitted and immutable_client_ready
        ota_poll_seconds = float(getattr(self.settings, "ota_poll_seconds", 0.0))
        if commissioning.requested and not commissioning.permitted:
            LOGGER.error(
                "Automatic OTA installation is blocked by commissioning: %s",
                ",".join(commissioning.blockers) or "commissioning_artifact_invalid",
            )
            self._record_ota_status(
                "unavailable",
                message="Automatic OTA commissioning is incomplete",
            )
        if ota_auto_apply:
            if self.ota_updater is None:
                raise RuntimeError(
                    "Automatic OTA installation requires a configured updater"
                )
            if not 0.0 < ota_poll_seconds <= 300.0:
                raise RuntimeError(
                    "Automatic OTA installation requires a poll interval no "
                    "greater than 300 seconds"
                )
            if not callable(restart_callback):
                raise RuntimeError(
                    "Automatic OTA installation requires a restart callback"
                )
            if not (
                self.settings.cameras_enabled
                and self.camera_rig is not None
                and self.settings.xarm_metrics_enabled
                and self.settings.xarm_model == "lite6"
                and bool(self.settings.xarm_ip)
                and self.metric_source is not None
            ):
                raise RuntimeError(
                    "Automatic OTA installation requires commissioned dual "
                    "cameras and Lite6 telemetry"
                )

        startup_update_id: Optional[str] = None
        if self.ota_updater is not None:
            startup_identity = getattr(
                self.ota_updater,
                "startup_pending_update_id",
                None,
            )
            if not callable(startup_identity):
                raise RuntimeError(
                    "Secure OTA updater lacks startup identity verification"
                )
            startup_update_id = startup_identity()
            if startup_update_id is not None and not re.fullmatch(
                r"[0-9a-f]{64}", startup_update_id
            ):
                raise RuntimeError("Secure OTA startup identity is invalid")
            report_pending = getattr(
                self.ota_updater,
                "health_report_pending",
                None,
            )
            report_healthy = getattr(
                self.ota_updater,
                "report_boot_success",
                None,
            )
            if not callable(report_pending) or not callable(report_healthy):
                raise RuntimeError("Secure OTA updater lacks durable health reporting")
            pending_health_report = report_pending()
            if not isinstance(pending_health_report, bool):
                raise RuntimeError("Secure OTA report state is invalid")

        with self._lock:
            if self._started:
                return
            self._started = True
            self._restart_callback = restart_callback
            self._stop_event.clear()
            self._ota_health_report_event.clear()
            self._fatal_event.clear()
            self._fatal_error_code = ""
            self._ota_startup_update_id = startup_update_id
        with self._ota_boot_health_lock:
            self._ota_boot_health_generation = 0
            self._ota_boot_health_fingerprint = ""
            self._ota_runtime_tick_failure_events = 0
            self._ota_runtime_max_consecutive_errors = 0
            self._ota_boot_health_last = {
                "schema_version": 1,
                "status": "pending" if startup_update_id is not None else "not_pending",
                "pending": startup_update_id is not None,
                "ready": False,
                "generation": 0,
                "update_id_sha256": (
                    hashlib.sha256(startup_update_id.encode("ascii")).hexdigest()
                    if startup_update_id is not None
                    else ""
                ),
                "target_version": "",
                "target_source_revision": "",
                "motion_release_required": self.motion_release_required,
                "motion_release_gate_ignored": True,
                "checks": {},
                "problems": (
                    ["health_window_incomplete"]
                    if startup_update_id is not None
                    else []
                ),
            }
        try:
            if self.sampling_tool_adapter is not None:
                start_tool = getattr(self.sampling_tool_adapter, "start", None)
                if not callable(start_tool):
                    raise RuntimeError("Sampling-tool adapter is incomplete")
                start_tool()
            if self.camera_rig is not None:
                self.camera_rig.start()
            if self.readiness_client is not None:
                self._spawn("device-registry", self._registry_loop)
            if self.tool_pose_buffer is not None:
                self._spawn("xarm-pose-history", self._tool_pose_loop)
            if self.valve_controller is not None:
                self._spawn("dynamic-valve-imitation", self._valve_loop)
            if self.mjpeg_server is not None:
                self.mjpeg_server.start()
            if self.datahub is not None:
                self._spawn(
                    "datahub-uploader",
                    lambda: self.datahub.run_worker(
                        self._stop_event,
                        interval_seconds=self.settings.datahub_flush_seconds,
                        batch_size=1,
                        operation_lock=self._capture_operation_lock,
                    ),
                )
            if self.capture_dataset_exporter is not None:
                run_exporter = getattr(
                    self.capture_dataset_exporter,
                    "run_worker",
                    None,
                )
                if not callable(run_exporter):
                    raise RuntimeError("Capture dataset exporter is incomplete")
                self._spawn(
                    "capture-dataset-exporter",
                    lambda: run_exporter(
                        self._stop_event,
                        interval_seconds=max(
                            0.1,
                            self.settings.datahub_flush_seconds,
                        ),
                        operation_lock=self._capture_operation_lock,
                    ),
                )
            if self.metric_source is not None:
                self._spawn("robot-telemetry", self._metric_loop)
            if callable(getattr(self.xarm_motion_adapter, "halt", None)):
                self._spawn(
                    "motion-authorization-watchdog",
                    self._motion_authorization_loop,
                )
            if self.ota_updater is not None and self.settings.ota_poll_seconds > 0:
                self._spawn("ota-poller", self._ota_loop)
            if self.ota_updater is not None:
                self._spawn("ota-health-reporter", self._ota_health_report_loop)
            if self.ota_updater is not None and startup_update_id is not None:
                self._spawn(
                    "ota-health-commit",
                    self._ota_health_commit,
                    supervised=False,
                )
        except Exception:
            self.stop()
            raise

    def stop(self, join_timeout_seconds: float = 3.0) -> None:
        """Stop workers and hardware without masking shutdown errors."""

        with self._lock:
            was_started = self._started
            self._started = False
        self._stop_event.set()
        self._ota_health_report_event.set()
        self._motion_abort_event.set()
        with self._motion_lock:
            self._workspace_teach_invalidation_pending.set()
            self._motion_stop_generation += 1
            self._motion_authorization_generation += 1
            self._motion_authorization_expires_at = 0.0
            self._motion_armed = False
            self._motion_live = False
        self._invalidate_workspace_boundary()
        if self._safety_configuration_lock.acquire(blocking=False):
            try:
                self._clear_safety_configuration_challenge_locked()
            finally:
                self._safety_configuration_lock.release()
        with self._capture_control_lock:
            self._clear_capture_confirmation_locked()
        shutdown_capture = getattr(
            self.capture_run_controller,
            "shutdown",
            None,
        )
        capture_stopped = True
        if callable(shutdown_capture):
            try:
                if shutdown_capture(join_timeout_seconds) is not True:
                    capture_stopped = False
                    LOGGER.error("Capture run did not stop within the shutdown window")
            except Exception:
                capture_stopped = False
                LOGGER.error(
                    "Could not halt the capture run during shutdown",
                    exc_info=True,
                )
        hand_training_stopped = True
        cancel_hand_training = getattr(self.hand_training_controller, "cancel", None)
        wait_hand_training = getattr(self.hand_training_controller, "wait", None)
        if callable(cancel_hand_training):
            try:
                cancel_hand_training()
                hand_training_stopped = bool(
                    callable(wait_hand_training)
                    and wait_hand_training(join_timeout_seconds) is True
                )
            except Exception:
                hand_training_stopped = False
                LOGGER.error(
                    "Could not stop hand training during shutdown",
                    exc_info=True,
                )
        tool_stopped = True
        shutdown_tool = getattr(self.sampling_tool_adapter, "shutdown", None)
        if was_started and self.sampling_tool_adapter is not None:
            if not callable(shutdown_tool):
                tool_stopped = False
                LOGGER.error("Configured sampling tool has no shutdown seam")
            else:
                try:
                    shutdown_tool()
                except Exception:
                    tool_stopped = False
                    LOGGER.error(
                        "Could not de-energize the sampling tool during shutdown",
                        exc_info=True,
                    )
        motion_stopped = True
        halt_motion = getattr(self.xarm_motion_adapter, "halt", None)
        if was_started and callable(halt_motion):
            try:
                halt_motion()
            except Exception:
                motion_stopped = False
                LOGGER.error("Could not halt xArm during shutdown", exc_info=True)
        elif was_started and getattr(self.settings, "xarm_motion_enabled", False):
            motion_stopped = False
            LOGGER.error("Configured xArm motion adapter has no halt seam")
        self._invalidate_workspace_teach(blocking=False, request=False)
        close_boundary = getattr(self.workspace_boundary_validator, "close", None)
        if callable(close_boundary):
            try:
                close_boundary(join_timeout_seconds)
            except Exception:
                LOGGER.warning(
                    "Could not stop workspace boundary validation",
                    exc_info=True,
                )
        if self.mjpeg_server is not None:
            try:
                self.mjpeg_server.stop()
            except Exception:
                LOGGER.warning("Could not stop MJPEG server", exc_info=True)
        if self.camera_rig is not None:
            try:
                self.camera_rig.stop()
            except Exception:
                LOGGER.warning("Could not stop camera rig", exc_info=True)
        for thread in tuple(self._threads):
            if thread is not threading.current_thread():
                thread.join(max(0.0, join_timeout_seconds))
        if not capture_stopped:
            wait_capture = getattr(self.capture_run_controller, "wait", None)
            if callable(wait_capture):
                try:
                    capture_stopped = wait_capture(0.1) is True
                except Exception:
                    capture_stopped = False
        alive_threads = [thread for thread in self._threads if thread.is_alive()]
        self._threads[:] = alive_threads
        self._supervised_threads[:] = [
            thread for thread in self._supervised_threads if thread in alive_threads
        ]
        close_metrics = getattr(self.metric_source, "close", None)
        if (
            was_started
            and capture_stopped
            and motion_stopped
            and callable(close_metrics)
        ):
            try:
                close_metrics()
            except Exception:
                LOGGER.warning("Could not close robot metric source", exc_info=True)
        if not capture_stopped:
            raise RuntimeError(
                "Capture worker remained active after bounded halt; "
                "xArm connection was intentionally kept open"
            )
        if not hand_training_stopped:
            raise RuntimeError(
                "Hand-training worker remained active after bounded shutdown"
            )
        if not motion_stopped:
            raise RuntimeError(
                "xArm halt could not be confirmed during shutdown; "
                "runtime exit is intentionally non-zero"
            )
        if not tool_stopped:
            raise RuntimeError(
                "Sampling tool safe state could not be confirmed during shutdown"
            )

    def sampling_tool_status(self) -> Mapping[str, Any]:
        adapter = self.sampling_tool_adapter
        status = getattr(adapter, "status", None)
        if not callable(status):
            return {
                "schema_version": 1,
                "configured": False,
                "started": False,
                "state": "unavailable",
                "ready": False,
                "grasp_confirmed": False,
                "fault_code": "",
                "fault_operation": "",
                "sequence": 0,
                "tool_model": "",
                "tool_serial": "",
                "profile_sha256": "",
                "motion_owner": False,
                "process_owner_bound": False,
            }
        result = status()
        if not isinstance(result, Mapping):
            raise RuntimeError("Sampling-tool status is invalid")
        return dict(result)

    def site_safety_status(
        self,
        *,
        safety_snapshot: Optional[Mapping[str, Any]] = None,
        camera_snapshot: Optional[Mapping[str, Any]] = None,
        sampling_tool_snapshot: Optional[Mapping[str, Any]] = None,
    ) -> Mapping[str, Any]:
        """Return the bounded, non-authorizing site-commissioning gate."""

        gate = self.site_safety_gate
        if gate is None:
            try:
                from main.site_safety import unavailable_site_safety_status
            except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                from site_safety import (  # type: ignore[no-redef]
                    unavailable_site_safety_status,
                )

            return dict(unavailable_site_safety_status())
        status = getattr(gate, "status", None)
        if not callable(status):
            raise RuntimeError("Site-safety gate is incomplete")
        safety = safety_snapshot if isinstance(safety_snapshot, Mapping) else {}
        controller = safety.get("preflight")
        controller = dict(controller) if isinstance(controller, Mapping) else {}
        controller["controller_binding_verified"] = bool(
            controller.get("controller_binding_verified") is True
            and safety.get("configured") is True
        )
        try:
            result = status(
                controller=controller,
                cameras=(
                    camera_snapshot if isinstance(camera_snapshot, Mapping) else {}
                ),
                sampling_tool=(
                    sampling_tool_snapshot
                    if isinstance(sampling_tool_snapshot, Mapping)
                    else {}
                ),
            )
        except Exception:
            LOGGER.warning("Site-safety evaluation failed closed", exc_info=True)
            result = {
                "schema": "labcobot.site-safety-status.v1",
                "configured": True,
                "ready": False,
                "motion_authority": "none",
                "profile_sha256": "",
                "site_id": "",
                "device_uid": "",
                "valid_until": "",
                "required_clearance_mm": None,
                "verified_minimum_clearance_mm": None,
                "verified_segment_count": 0,
                "blockers": ["site_safety_evaluation_failed"],
            }
        if not isinstance(result, Mapping):
            result = {
                "schema": "labcobot.site-safety-status.v1",
                "configured": True,
                "ready": False,
                "motion_authority": "none",
                "profile_sha256": "",
                "site_id": "",
                "device_uid": "",
                "valid_until": "",
                "required_clearance_mm": None,
                "verified_minimum_clearance_mm": None,
                "verified_segment_count": 0,
                "blockers": ["site_safety_evaluation_failed"],
            }
        return dict(result)

    def raise_if_failed(self) -> None:
        """Raise when a persistent owner died or returned unexpectedly."""

        if self.mjpeg_server is not None:
            with self._lock:
                started = self._started
            is_alive = getattr(self.mjpeg_server, "is_alive", None)
            if started and callable(is_alive) and is_alive() is not True:
                self._latch_runtime_fatal("mjpeg_server_stopped")
        if self._fatal_event.is_set():
            raise RuntimeError(self._fatal_error_code or "workcell_worker_stopped")

    def request_capture_start(
        self,
        challenge: Optional[str] = None,
    ) -> Mapping[str, Any]:
        """Admit one capture through a random, one-use, generation-bound token."""

        if challenge is None or challenge == "":
            supplied = ""
        elif isinstance(challenge, str) and re.fullmatch(r"[0-9a-f]{32}", challenge):
            supplied = challenge
        else:
            return {"status": "confirmation_required"}

        controller = self.capture_run_controller
        if controller is None:
            return {"status": "unavailable"}
        if not self._capture_environment_ready():
            with self._capture_control_lock:
                self._clear_capture_confirmation_locked()
            return {"status": "unsafe"}
        try:
            status = controller.status()
        except Exception:
            LOGGER.warning("Could not validate capture state", exc_info=True)
            with self._capture_control_lock:
                self._clear_capture_confirmation_locked()
            return {"status": "error"}
        if not isinstance(status, Mapping):
            with self._capture_control_lock:
                self._clear_capture_confirmation_locked()
            return {"status": "error"}
        state = str(status.get("state") or "")
        if status.get("active") is True or state in _CAPTURE_ACTIVE_STATES:
            with self._capture_control_lock:
                self._clear_capture_confirmation_locked()
            return {"status": "busy"}
        export = self.capture_export_status(
            {
                "state": state,
                "run_id": status.get("run_id"),
            }
        )
        if (
            state not in _CAPTURE_STATES
            or state == "fault_locked"
            or status.get("action_allowed") is not True
            or export.get("new_run_allowed") is not True
        ):
            with self._capture_control_lock:
                self._clear_capture_confirmation_locked()
            return {"status": "unsafe"}

        fingerprint = self._capture_confirmation_snapshot(status, export)
        now = float(self._monotonic())
        with self._capture_control_lock:
            if not supplied:
                self._clear_capture_confirmation_locked()
                with self._motion_lock:
                    stop_generation = self._motion_stop_generation
                token = secrets.token_hex(16)
                self._capture_confirmation_challenge = token
                self._capture_confirmation_expires_at = (
                    now + _CAPTURE_CONFIRMATION_SECONDS
                )
                self._capture_confirmation_stop_generation = stop_generation
                self._capture_confirmation_fingerprint = fingerprint
                return {
                    "status": "confirm",
                    "challenge": token,
                    "expires_in_seconds": int(_CAPTURE_CONFIRMATION_SECONDS),
                }
            with self._motion_lock:
                generation_matches = (
                    self._capture_confirmation_stop_generation
                    == self._motion_stop_generation
                )
            confirmed = bool(
                self._capture_confirmation_challenge
                and self._capture_confirmation_expires_at >= now
                and generation_matches
                and self._capture_confirmation_fingerprint == fingerprint
                and secrets.compare_digest(
                    self._capture_confirmation_challenge,
                    supplied,
                )
            )
            expected_stop_generation = self._capture_confirmation_stop_generation
            self._clear_capture_confirmation_locked()
        if not confirmed:
            return {"status": "confirmation_required"}

        if not self._operation_transition_lock.acquire(blocking=False):
            return {"status": "busy"}
        try:
            if self._workspace_teach_blocks_physical_operation():
                return {"status": "busy"}
            with self._motion_lock:
                if expected_stop_generation != self._motion_stop_generation:
                    return {"status": "unsafe"}
                # Only the confirmed operation can clear an older STOP latch.
                # Any later STOP advances the generation and is carried into
                # the worker through ``external_stop_requested``.
                self._motion_abort_event.clear()
            outcome = self._start_confirmed_capture(
                controller,
                expected_stop_generation=expected_stop_generation,
            )
            return {"status": outcome}
        finally:
            self._operation_transition_lock.release()

    def hand_training_status(self) -> Mapping[str, Any]:
        """Return the bounded recorder projection consumed by the local UI."""

        controller = self.hand_training_controller
        status = getattr(controller, "status", None)
        if not callable(status):
            return self._empty_hand_training_status()
        try:
            value = status()
        except Exception:
            LOGGER.warning("Could not read hand-training status", exc_info=True)
            value = None
        if not isinstance(value, Mapping):
            result = self._empty_hand_training_status()
            result["state"] = "failed"
            result["error_code"] = "status_unavailable"
            return result
        result = dict(value)
        tenant_state = str(self.tenant_auth_status().get("state") or "")
        result["login_ready"] = tenant_state in {
            "authenticated",
            "refresh_required",
        }
        result["start_allowed"] = bool(
            result.get("start_allowed") is True and result["login_ready"]
        )
        return result

    @staticmethod
    def _empty_hand_training_status() -> dict[str, Any]:
        return {
            "schema_version": 1,
            "configured": False,
            "state": "unavailable",
            "active": False,
            "start_allowed": False,
            "end_allowed": False,
            "tool_allowed": False,
            "tool_on": False,
            "tool_events": 0,
            "session_id": "",
            "sample_count": 0,
            "tool_frames": 0,
            "workspace_frames": 0,
            "elapsed_seconds": 0.0,
            "maximum_duration_seconds": 0.0,
            "sample_rate_hz": 0.0,
            "video_bytes": {"tool": 0, "workspace": 0},
            "error_code": "",
            "uploaded": False,
            "recording_id": "",
            "workbench_rows": 0,
            "shortcut_jobs": 0,
        }

    def request_hand_training_start(self) -> Mapping[str, Any]:
        """Reserve the physical lane and begin read-only teach-mode capture."""

        controller = self.hand_training_controller
        if controller is None:
            return {"status": "unavailable"}
        tenant_state = str(self.tenant_auth_status().get("state") or "")
        if tenant_state not in {"authenticated", "refresh_required"}:
            return {"status": "login_required"}
        if not self._operation_transition_lock.acquire(blocking=False):
            return {"status": "busy"}
        reserved = False
        try:
            if (
                self._capture_operation_lock.locked()
                or self._petri_run_lock.locked()
                or self._workspace_teach_blocks_physical_operation()
                or not self._hand_training_operation_lock.acquire(blocking=False)
            ):
                return {"status": "busy"}
            reserved = True
            try:
                session_id = controller.start()
            except Exception as exc:
                code = str(getattr(exc, "code", "") or "")
                LOGGER.warning(
                    "Hand-training start rejected: %s", code or type(exc).__name__
                )
                return {
                    "status": (
                        "unsafe"
                        if code
                        in {
                            "teach_mode_not_ready",
                            "telemetry_stale",
                            "xarm_fault",
                            "tool_not_safe",
                            "camera_pair_invalid",
                        }
                        else "busy" if code == "hand_training_busy" else "error"
                    )
                }

            def watch_hand_training() -> None:
                try:
                    controller.wait(None)
                except Exception:
                    LOGGER.error("Hand-training watcher failed", exc_info=True)
                    try:
                        controller.cancel()
                    except Exception:
                        LOGGER.error("Could not cancel hand training", exc_info=True)
                finally:
                    try:
                        stopped = controller.wait(0.0) is True
                    except Exception:
                        stopped = False
                    if stopped:
                        self._hand_training_operation_lock.release()
                    else:
                        self._latch_runtime_fatal("hand_training_worker_unconfirmed")

            try:
                self._spawn(
                    "hand-training-watch",
                    watch_hand_training,
                    supervised=False,
                )
            except Exception:
                LOGGER.exception("Could not supervise hand training")
                controller.cancel()
                if controller.wait(1.0) is True:
                    self._hand_training_operation_lock.release()
                else:
                    self._latch_runtime_fatal("hand_training_watcher_start_failed")
                reserved = False
                return {"status": "error"}
            reserved = False
            return {"status": "accepted", "session_id": str(session_id)}
        finally:
            if reserved:
                self._hand_training_operation_lock.release()
            self._operation_transition_lock.release()

    def request_hand_training_tool(self, active: bool) -> Mapping[str, Any]:
        """Change the typed tool state only during an owned recording."""

        if type(active) is not bool:
            return {"status": "invalid_request"}
        controller = self.hand_training_controller
        if controller is None:
            return {"status": "unavailable"}
        try:
            result = controller.set_tool(active)
        except Exception as exc:
            code = str(getattr(exc, "code", "") or "")
            LOGGER.warning(
                "Hand-training tool request rejected: %s", code or type(exc).__name__
            )
            return {"status": "unsafe" if code else "error"}
        return {
            "status": "accepted",
            "tool_on": result.get("tool_on") is True,
        }

    def request_hand_training_end(self) -> Mapping[str, Any]:
        """End recording; the recorder then uploads and releases ownership."""

        controller = self.hand_training_controller
        if controller is None:
            return {"status": "unavailable"}
        try:
            accepted = controller.end() is True
        except Exception:
            LOGGER.exception("Could not end hand-training recording")
            return {"status": "error"}
        return {"status": "accepted" if accepted else "idle"}

    def _capture_confirmation_snapshot(
        self,
        status: Mapping[str, Any],
        export: Mapping[str, Any],
    ) -> Tuple[Any, ...]:
        """Bind a challenge to stable, secret-free capture preflight state."""

        cameras = self._camera_health_metrics()
        camera_state = tuple(
            (
                role,
                str((cameras.get(role) or {}).get("state") or ""),
                (cameras.get(role) or {}).get("fresh") is True,
            )
            for role in ("tool", "workspace")
        )
        xarm_state: Tuple[Any, ...] = ()
        if self._runtime_deployment_mode() == "workcell":
            xarm = self.xarm_status()
            xarm_state = (
                xarm.get("connected") is True,
                xarm.get("healthy") is True,
                xarm.get("fresh") is True,
                xarm.get("moving") is False,
                xarm.get("axis_count"),
                xarm.get("device_type"),
                xarm.get("error_code"),
                xarm.get("warning_code"),
            )
        return (
            str(status.get("state") or ""),
            status.get("action_allowed") is True,
            export.get("new_run_allowed") is True,
            export.get("dataset_binding_verified") is True,
            int(export.get("dead_lettered_frames") or 0),
            camera_state,
            xarm_state,
        )

    def _clear_capture_confirmation_locked(self) -> None:
        self._capture_confirmation_challenge = ""
        self._capture_confirmation_expires_at = 0.0
        self._capture_confirmation_stop_generation = -1
        self._capture_confirmation_fingerprint = ()

    def _start_confirmed_capture(
        self,
        controller: Any,
        *,
        expected_stop_generation: int,
    ) -> str:
        """Reserve physical operation ownership and launch the capture worker."""

        if (
            self._hand_training_operation_lock.locked()
            or not self._capture_operation_lock.acquire(blocking=False)
        ):
            return "busy"
        if not self._capture_environment_ready(allow_reserved=True):
            self._capture_operation_lock.release()
            return "unsafe"
        try:
            reserved_status = controller.status()
        except Exception:
            self._capture_operation_lock.release()
            return "error"
        if not isinstance(reserved_status, Mapping) or (
            self.capture_export_status(
                {
                    "state": reserved_status.get("state"),
                    "run_id": reserved_status.get("run_id"),
                }
            ).get("new_run_allowed")
            is not True
        ):
            self._capture_operation_lock.release()
            return "unsafe"
        with self._motion_lock:
            if (
                expected_stop_generation != self._motion_stop_generation
                or self._motion_abort_event.is_set()
            ):
                self._capture_operation_lock.release()
                return "unsafe"

        def external_stop_requested() -> bool:
            with self._motion_lock:
                return (
                    expected_stop_generation != self._motion_stop_generation
                    or self._motion_abort_event.is_set()
                )

        try:
            run_id = controller.start(
                external_stop_requested=external_stop_requested,
            )
        except Exception as exc:
            self._capture_operation_lock.release()
            if type(exc).__name__ == "CaptureBusyError":
                return "busy"
            if type(exc).__name__ in {
                "CaptureRunError",
                "CaptureConfigurationError",
                "DatasetSecurityError",
            }:
                LOGGER.warning(
                    "Commissioned capture preflight rejected the run: %s",
                    type(exc).__name__,
                )
                return "unsafe"
            LOGGER.exception("Could not start commissioned capture run")
            return "error"

        def watch_capture() -> None:
            try:
                controller.wait(None)
            except Exception:
                LOGGER.error("Capture watcher failed", exc_info=True)
                try:
                    controller.cancel(run_id)
                except Exception:
                    LOGGER.error(
                        "Could not halt capture after watcher failure",
                        exc_info=True,
                    )
            finally:
                try:
                    finished = controller.wait(0.0) is True
                except Exception:
                    finished = False
                if not finished:
                    LOGGER.critical(
                        "Capture watcher exited without proving the physical "
                        "operation stopped; ownership remains reserved"
                    )
                    self._latch_runtime_fatal("capture_worker_unconfirmed")
                else:
                    self._capture_operation_lock.release()

        try:
            self._spawn(
                "capture-run-watch",
                watch_capture,
                supervised=False,
            )
        except Exception:
            LOGGER.exception("Could not supervise commissioned capture run")
            stopped = False
            try:
                controller.cancel(run_id)
                stopped = controller.wait(1.0) is True
            except Exception:
                LOGGER.exception("Could not halt capture after watcher start failure")
            if stopped:
                self._capture_operation_lock.release()
            else:
                LOGGER.critical(
                    "Capture worker remained active after watcher start "
                    "failure; physical ownership remains reserved"
                )
                self._latch_runtime_fatal("capture_watcher_start_failed")
            return "error"
        return "accepted"

    def request_capture_stop(self) -> str:
        """Route capture STOP through the universal fail-safe halt seam."""

        if self.capture_run_controller is None:
            return "unavailable"
        return self.request_software_stop()

    def request_update_check(self) -> bool:
        """Start a non-blocking secure OTA check; return false if unavailable/busy."""

        if self.ota_updater is None:
            self._record_ota_status("unavailable")
            return False
        if not self._reserve_ota_owner():
            return False
        self._record_ota_status(
            "checking",
            manifest_verification="checking",
            archive_digest_verification="not_checked",
        )

        def check() -> None:
            try:
                self._check_update_once(allow_reserved=True)
            except Exception:
                LOGGER.exception("Secure OTA check failed")
            finally:
                self._release_ota_owner()

        try:
            self._spawn("ota-manual-check", check, supervised=False)
        except Exception:
            self._release_ota_owner()
            raise
        return True

    def check_update_now(self) -> OTAResult:
        """Run one secure OTA check synchronously, primarily for operations/tests."""

        if self.ota_updater is None:
            self._record_ota_status("unavailable")
            raise RuntimeError("Secure OTA is not configured")
        if not self._reserve_ota_owner():
            raise RuntimeError("Secure OTA is blocked by a physical operation")
        try:
            return self._check_update_once(allow_reserved=True)
        finally:
            self._release_ota_owner()

    def _reserve_ota_owner(self) -> bool:
        """Atomically reserve the global physical/configuration owner for OTA."""

        if not self._operation_transition_lock.acquire(blocking=False):
            return False
        reserved_operation = False
        reserved_ota = False
        admitted = False
        try:
            if not self._ota_environment_ready(allow_transition=True):
                return False
            reserved_operation = self._capture_operation_lock.acquire(blocking=False)
            if not reserved_operation:
                return False
            reserved_ota = self._ota_lock.acquire(blocking=False)
            if not reserved_ota:
                return False
            if not self._ota_environment_ready(
                allow_reserved=True,
                allow_transition=True,
            ):
                return False
            if (
                self._evaluate_ota_commissioning().permitted
                and not self._capture_ota_admission_lease()
            ):
                return False
            admitted = True
            return True
        finally:
            self._operation_transition_lock.release()
            if not admitted:
                if reserved_ota:
                    self._ota_lock.release()
                if reserved_operation:
                    self._capture_operation_lock.release()

    def _release_ota_owner(self) -> None:
        """Release the OTA and global physical owner in reverse order."""

        with self._ota_admission_lock:
            self._ota_admission_lease = None
            self._ota_admission_last_telemetry_sequence = 0
            self._ota_admission_last_camera_sequences = {}
            if self._ota_admission_status.get("status") == "active":
                self._ota_admission_status = {
                    **dict(self._ota_admission_status),
                    "status": "released",
                    "motion_authority": "none",
                }
        self._ota_lock.release()
        self._capture_operation_lock.release()

    def handle_runtime_failure(self) -> bool:
        """Roll back an uncommitted OTA release after a fatal boot failure.

        A healthy, already committed release is unaffected because
        ``rollback_pending`` returns false unless the updater state is
        ``pending_restart``.
        """

        if self.ota_updater is None:
            return False
        with self._ota_lock:
            rolled_back = self.ota_updater.rollback_pending()
        if rolled_back:
            LOGGER.error("Rolled back the pending OTA release after runtime failure")
        return bool(rolled_back)

    def trajectory_offload_hook(self, training_job: Any) -> Any:
        """Submit and verify one request-bound trajectory-training job."""

        if self.offload_client is None:
            raise RuntimeError("Remote compute offload is not configured")
        try:
            from main.training_artifacts import (
                canonical_training_request_sha256,
                validate_remote_training_result,
            )
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from training_artifacts import (  # type: ignore[no-redef]
                canonical_training_request_sha256,
                validate_remote_training_result,
            )
        payload = (
            training_job.to_dict()
            if hasattr(training_job, "to_dict")
            else dict(training_job)
        )
        request_sha256 = canonical_training_request_sha256(payload)
        envelope = {
            "job_type": "trajectory_training",
            "payload": payload,
            "request_sha256": request_sha256,
        }
        serialized = json.dumps(
            envelope,
            allow_nan=False,
            separators=(",", ":"),
            sort_keys=True,
        ).encode("utf-8")
        idempotency_key = "trajectory:" + hashlib.sha256(serialized).hexdigest()
        job = self.offload_client.submit(
            envelope,
            idempotency_key=idempotency_key,
        )
        finished = self.offload_client.wait(
            job,
            deadline_seconds=self.settings.offload_deadline_seconds,
        )
        return validate_remote_training_result(
            finished.result,
            expected_request_sha256=request_sha256,
        )

    def verify_device_registration_now(self) -> Mapping[str, Any]:
        """Verify the configured stand identity without mutating Supraworx."""

        if self.readiness_client is None:
            raise RuntimeError("Supraworx device readiness is not configured")
        try:
            result = dict(self.readiness_client.verify())
        except Exception as exc:
            status = {
                "configured": True,
                "verified": False,
                "ready": False,
                "status": "error",
                "reason": type(exc).__name__,
            }
            with self._registry_lock:
                self._registry_status = status
            raise
        features = self._sanitize_registry_features(result.get("features"))
        datahub_value = features.get("datahub_timeseries")
        ota_value = features.get("ota")
        compute_value = features.get("compute_offload")
        motion_release_value = features.get("motion_release")
        datahub = datahub_value if isinstance(datahub_value, Mapping) else {}
        ota = ota_value if isinstance(ota_value, Mapping) else {}
        compute = compute_value if isinstance(compute_value, Mapping) else {}
        motion_release = (
            motion_release_value if isinstance(motion_release_value, Mapping) else {}
        )
        raw_job_types = compute.get("job_types")
        job_types = {
            str(value)
            for value in (
                raw_job_types if isinstance(raw_job_types, (list, tuple)) else ()
            )
        }
        features_ready = all(
            (
                not self.settings.datahub_configured or datahub.get("ready") is True,
                not self.settings.ota_configured or ota.get("ready") is True,
                not self.settings.offload_configured
                or (
                    compute.get("ready") is True
                    and {
                        "trajectory_training",
                        "valve_detection",
                    }.issubset(job_types)
                ),
                not self.motion_release_required or motion_release.get("ready") is True,
            )
        )
        status = {
            "schema_version": 1,
            "configured": True,
            "verified": True,
            "ready": features_ready,
            "status": "verified" if features_ready else "incomplete",
            "device": self._sanitize_registry_device(result.get("device")),
            "features": features,
            "server_time": _bounded_public_identifier(
                str(result.get("server_time") or ""), limit=64
            ),
        }
        with self._registry_lock:
            self._registry_status = status
        return dict(status)

    @staticmethod
    def _sanitize_registry_device(value: Any) -> Mapping[str, Any]:
        raw = value if isinstance(value, Mapping) else {}
        return {
            "registered": raw.get("registered") is True,
            "uid_device": _bounded_public_identifier(raw.get("uid_device"), limit=120),
            "manufacturer_id": _bounded_public_identifier(
                raw.get("manufacturer_id"), limit=120
            ),
            "device_type": _bounded_public_identifier(
                raw.get("device_type"), limit=120
            ),
            "software_version": _bounded_public_identifier(
                raw.get("software_version"), limit=64
            ),
        }

    @staticmethod
    def _sanitize_registry_features(value: Any) -> Mapping[str, Any]:
        raw = value if isinstance(value, Mapping) else {}

        def readiness(name: str) -> Mapping[str, bool]:
            feature = raw.get(name)
            feature = feature if isinstance(feature, Mapping) else {}
            return {
                "enabled": feature.get("enabled") is True,
                "ready": feature.get("ready") is True,
            }

        compute = raw.get("compute_offload")
        compute = compute if isinstance(compute, Mapping) else {}
        raw_types = compute.get("job_types")
        job_types = sorted(
            {
                item
                for item in raw_types
                if isinstance(item, str)
                and item in {"trajectory_training", "valve_detection"}
            }
            if isinstance(raw_types, (list, tuple))
            else set()
        )

        motion = raw.get("motion_release")
        motion = motion if isinstance(motion, Mapping) else {}
        release_id = _bounded_public_identifier(
            motion.get("release_id"), limit=36
        ).lower()
        try:
            parsed_release_id = str(uuid.UUID(release_id))
        except (ValueError, AttributeError):
            parsed_release_id = ""
        evidence_sha256 = _bounded_public_identifier(
            motion.get("evidence_sha256"), limit=64
        ).lower()
        if re.fullmatch(r"[0-9a-f]{64}", evidence_sha256) is None:
            evidence_sha256 = ""
        accepted_at = _bounded_public_identifier(motion.get("accepted_at"), limit=64)
        handed_over_at = _bounded_public_identifier(
            motion.get("handed_over_at"), limit=64
        )
        release_ready = bool(
            motion.get("schema") == "labcobot.device-motion-release.v1"
            and motion.get("ready") is True
            and motion.get("revoked") is not True
            and parsed_release_id
            and evidence_sha256
            and accepted_at
            and handed_over_at
        )
        return {
            "datahub_timeseries": readiness("datahub_timeseries"),
            "ota": readiness("ota"),
            "compute_offload": {
                "enabled": compute.get("enabled") is True,
                "ready": compute.get("ready") is True,
                "job_types": job_types,
            },
            "motion_release": {
                "schema": (
                    "labcobot.device-motion-release.v1"
                    if motion.get("schema") == "labcobot.device-motion-release.v1"
                    else ""
                ),
                "ready": release_ready,
                "release_id": parsed_release_id if release_ready else "",
                "evidence_sha256": evidence_sha256 if release_ready else "",
                "accepted_at": accepted_at if release_ready else "",
                "handed_over_at": handed_over_at if release_ready else "",
                "revoked": motion.get("revoked") is True,
            },
        }

    def valve_inference_offload_hook(
        self,
        frame: Any,
        *,
        max_image_bytes: int = 4 * 1024 * 1024,
    ) -> Any:
        """Run heavy valve detection as one correlated remote job.

        This is the concrete Raspberry Pi escape hatch used by
        ``RemoteValveDetector`` when local inference is unavailable or exceeds
        the configured compute budget.  Results must contain a bounded
        ``detections`` (or compatibility ``valves``) list.
        """

        if self.offload_client is None:
            raise RuntimeError("Remote compute offload is not configured")
        encoder = self.jpeg_encoder
        if encoder is None:
            try:
                from main.vision.cameras import encode_jpeg
            except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                from vision.cameras import encode_jpeg
            encoder = encode_jpeg
        jpeg = encoder(frame.image)
        if not isinstance(jpeg, bytes):
            raise TypeError("JPEG encoder must return bytes")
        if not jpeg or len(jpeg) > max_image_bytes:
            raise RemoteJobError(
                "Valve-inference image is empty or exceeds the size limit"
            )
        image_sha256 = hashlib.sha256(jpeg).hexdigest()
        payload = {
            "schema_version": "labcobot.valve-inference.v1",
            "camera": {
                "source_id": str(frame.source_id),
                "role": str(getattr(frame.role, "value", frame.role)),
                "sequence": int(frame.sequence),
                "captured_at_s": float(frame.captured_at_s),
            },
            "image": {
                "content_type": "image/jpeg",
                "byte_length": len(jpeg),
                "sha256": image_sha256,
                "encoding": "base64",
                "data": base64.b64encode(jpeg).decode("ascii"),
            },
        }
        envelope = {"job_type": "valve_detection", "payload": payload}
        idempotency_key = "vision:{}:{}:{}".format(
            frame.source_id,
            int(frame.sequence),
            image_sha256,
        )
        job = self.offload_client.submit(
            envelope,
            idempotency_key=idempotency_key,
        )
        finished = self.offload_client.wait(
            job,
            deadline_seconds=self.settings.offload_deadline_seconds,
        )
        result = finished.result
        if not isinstance(result, Mapping):
            raise RemoteJobError("Valve-inference result must be an object")
        detections = result.get("detections", result.get("valves"))
        if not isinstance(detections, (list, tuple)):
            raise RemoteJobError("Valve-inference result is missing a detections list")
        if len(detections) > 256:
            raise RemoteJobError("Valve-inference result has too many detections")
        if not all(isinstance(item, Mapping) for item in detections):
            raise RemoteJobError("Valve-inference detections must be objects")
        return tuple(dict(item) for item in detections)

    def _spawn(
        self,
        name: str,
        target: Callable[[], None],
        *,
        supervised: bool = True,
    ) -> None:
        """Start a daemon thread and optionally include it in health supervision.

        Finite jobs such as a manual OTA check are still joined during shutdown,
        but their expected completion must not be reported as a failed worker.
        """

        def run_target() -> None:
            failure: Optional[BaseException] = None
            try:
                target()
            except BaseException as exc:
                failure = exc
                LOGGER.exception("Persistent worker %s failed", name)
            finally:
                if supervised and not self._stop_event.is_set():
                    self._latch_runtime_fatal(
                        "worker_{}_stopped".format(
                            re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")
                            or "unknown"
                        ),
                        failure=failure,
                    )
                elif not supervised:
                    current = threading.current_thread()
                    with self._lock:
                        if current in self._threads:
                            self._threads.remove(current)

        thread = threading.Thread(target=run_target, name=name, daemon=True)
        with self._lock:
            self._threads.append(thread)
            if supervised:
                self._supervised_threads.append(thread)
        try:
            thread.start()
        except Exception:
            with self._lock:
                if thread in self._threads:
                    self._threads.remove(thread)
                if thread in self._supervised_threads:
                    self._supervised_threads.remove(thread)
            raise

    def _latch_runtime_fatal(
        self,
        code: str,
        *,
        failure: Optional[BaseException] = None,
    ) -> None:
        """Close every software motion gate after a persistent-owner failure."""

        safe_code = re.sub(r"[^a-z0-9_]+", "_", str(code).lower())[:64].strip("_")
        if not safe_code:
            safe_code = "workcell_worker_stopped"
        with self._fatal_lock:
            if self._fatal_event.is_set():
                return
            self._fatal_error_code = safe_code
            self._runtime_fatal_generation = min(
                self._runtime_fatal_generation + 1,
                1_000_000_000,
            )
            self._fatal_event.set()
        with self._ota_admission_lock:
            lease_active = self._ota_admission_lease is not None
        if lease_active:
            self._set_ota_admission_changed("fatal_changed", "before_network")
        self._stop_event.set()
        self._motion_abort_event.set()
        adapter = self.xarm_motion_adapter
        with self._motion_lock:
            self._workspace_teach_invalidation_pending.set()
            self._motion_stop_generation += 1
            self._motion_authorization_generation += 1
            self._motion_authorization_expires_at = 0.0
            self._motion_armed = False
            self._motion_live = False
            if not self._motion_fault_reason:
                self._motion_fault_reason = safe_code
        revoke = getattr(adapter, "revoke_commands", None)
        if callable(revoke):
            try:
                revoke()
            except Exception:
                LOGGER.error("Could not revoke xArm commands after worker failure")
        halt = getattr(adapter, "halt", None)
        if callable(halt):
            try:
                halt()
            except Exception:
                LOGGER.critical(
                    "Could not halt xArm after persistent worker failure",
                    exc_info=True,
                )
        self._invalidate_workspace_teach(blocking=False, request=False)
        LOGGER.critical(
            "Workcell runtime fault latched: %s%s",
            safe_code,
            " ({})".format(type(failure).__name__) if failure is not None else "",
        )

    def _registry_loop(self) -> None:
        while not self._stop_event.is_set():
            try:
                self.verify_device_registration_now()
            except Exception:
                LOGGER.warning(
                    "Supraworx device registration verification failed",
                    exc_info=True,
                )
            if self._stop_event.wait(self.settings.registry_check_seconds):
                return

    def _metric_loop(self) -> None:
        while not self._stop_event.is_set():
            # Telemetry and commissioned motion share one xArm SDK lock. Do
            # not let a best-effort sample contend with the reviewed 100 Hz
            # command stream or make a command miss its watchdog deadline.
            if self._capture_operation_lock.locked() and not self._ota_lock.locked():
                self._stop_event.wait(min(0.1, self.settings.telemetry_sample_seconds))
                continue
            try:
                metrics = self.metric_source()  # type: ignore[misc]
                self._record_xarm_sample(metrics)
                if metrics:
                    camera_health = self._camera_health_metrics()
                    payload = dict(metrics)
                    if camera_health:
                        payload["cameras"] = camera_health
                    payload["motion"] = dict(self.motion_status())
                    payload["controller_firmware"] = dict(
                        self.controller_firmware_status(
                            xarm_snapshot=self.xarm_status()
                        )
                    )
                    if self.datahub is not None:
                        self.datahub.enqueue_metrics(payload)
            except Exception:
                self._record_xarm_sample_error()
                LOGGER.warning("Robot telemetry sampling failed", exc_info=True)
            self._stop_event.wait(self.settings.telemetry_sample_seconds)

    def _record_xarm_sample(self, metrics: Any) -> None:
        """Cache a bounded controller summary for health and local admission."""

        if not isinstance(metrics, Mapping):
            self._record_xarm_sample_error("invalid_sample")
            return
        connected = metrics.get("connected")
        state = self._bounded_xarm_integer(metrics.get("state"), maximum=255)
        mode = self._bounded_xarm_integer(metrics.get("mode"), maximum=255)
        moving = metrics.get("moving")
        if not isinstance(moving, bool):
            moving = None
        error_code = None
        warning_code = None
        error_warning = metrics.get("error_warning")
        if isinstance(error_warning, (list, tuple)) and len(error_warning) >= 2:
            error_code = self._bounded_xarm_integer(error_warning[0], maximum=65535)
            warning_code = self._bounded_xarm_integer(error_warning[1], maximum=65535)
        controller = metrics.get("controller")
        controller = controller if isinstance(controller, Mapping) else {}
        axis_count = self._bounded_xarm_integer(
            controller.get("axis_count"), maximum=32
        )
        device_type = self._bounded_xarm_integer(
            controller.get("device_type"), maximum=65535
        )
        mode_value = metrics.get("reduced_mode")
        reduced_states = metrics.get("reduced_states")
        workspace_lower = tuple(
            getattr(self.settings, "eye_in_hand_workspace_lower_xyz_mm", ())
        )
        workspace_upper = tuple(
            getattr(self.settings, "eye_in_hand_workspace_upper_xyz_mm", ())
        )
        safety = _bounded_reduced_telemetry(
            mode_value,
            reduced_states,
            workspace_lower_xyz_mm=workspace_lower,
            workspace_upper_xyz_mm=workspace_upper,
            joints_value=metrics.get("joint_angles_rad"),
            tcp_pose_value=metrics.get("tcp_pose"),
        )
        valid = (
            isinstance(connected, bool)
            and state is not None
            and mode is not None
            and moving is not None
            and error_code is not None
            and warning_code is not None
        )
        healthy = bool(
            valid and connected is True and error_code == 0 and warning_code == 0
        )
        fault_category, fault_guidance = _xarm_fault_diagnostic(error_code)
        with self._xarm_status_lock:
            recorded_status = {
                "schema_version": _XARM_STATUS_SCHEMA_VERSION,
                "configured": True,
                "available": valid,
                "connected": connected is True,
                "healthy": healthy,
                "state": state,
                "mode": mode,
                "moving": moving,
                "error_code": error_code,
                "warning_code": warning_code,
                "reduced_mode_enabled": safety["reduced_mode_enabled"],
                "reduced_configuration_valid": (safety["reduced_configuration_valid"]),
                "reduced_safety_boundary_enabled": (
                    safety["reduced_safety_boundary_enabled"]
                ),
                "collision_rebound_disabled": (safety["collision_rebound_disabled"]),
                "conservative_joint_envelope": (safety["conservative_joint_envelope"]),
                "control_envelope_ready": safety["control_envelope_ready"],
                "fault_category": fault_category,
                "fault_guidance": fault_guidance,
                "axis_count": axis_count,
                "device_type": device_type,
                "metrics": _bounded_xarm_metrics(metrics),
                "sampled_at_monotonic_s": float(self._monotonic()),
                "sample_error": "" if valid else "invalid_sample",
            }
            self._xarm_status = recorded_status
            self._xarm_pose_sequence = min(
                self._xarm_pose_sequence + 1,
                10_000_000_000,
            )
            pose_sequence = self._xarm_pose_sequence
        with self._ota_admission_lock:
            active_lease = self._ota_admission_lease
        if active_lease is not None and not (
            recorded_status["connected"] is True
            and recorded_status["healthy"] is True
            and recorded_status["state"] == active_lease.controller_state
            and recorded_status["mode"] == active_lease.controller_mode
            and recorded_status["moving"] is False
            and recorded_status["error_code"] == 0
            and recorded_status["warning_code"] == 0
            and recorded_status["axis_count"] == 6
            and recorded_status["device_type"] == _LITE6_DEVICE_TYPE
        ):
            self._set_ota_admission_changed(
                "controller_changed",
                "before_network",
            )
        ingest_teach = getattr(self.workspace_teach_recorder, "ingest", None)
        if callable(ingest_teach) and self._workspace_teach_owner_active:
            # Keep the read-only session owner and recorder state consistent
            # with physical admissions.  Lock order is always transition then
            # workspace; no SDK/controller call occurs in this section.
            with self._operation_transition_lock:
                with self._workspace_teach_lock:
                    if self._workspace_teach_invalidation_pending.is_set():
                        self._invalidate_workspace_teach_locked()
                        return
                    if not self._workspace_teach_owner_active:
                        return
                    try:
                        teach_status = ingest_teach(
                            self.xarm_status(),
                            pose_sequence=pose_sequence,
                        )
                    except Exception:
                        LOGGER.error(
                            "Workspace-teach telemetry ingestion failed",
                            exc_info=True,
                        )
                        self._workspace_teach_invalidation_pending.set()
                        self._invalidate_workspace_teach_locked()
                    else:
                        state = (
                            teach_status.get("state")
                            if isinstance(teach_status, Mapping)
                            else ""
                        )
                        if state in {
                            "idle",
                            "cancelled",
                            "invalidated",
                            "proposed",
                        }:
                            snapshot = getattr(
                                self.workspace_teach_recorder,
                                "snapshot",
                                None,
                            )
                            try:
                                confirmed = snapshot() if callable(snapshot) else {}
                            except Exception:
                                confirmed = {}
                            if (
                                isinstance(confirmed, Mapping)
                                and confirmed.get("state") == state
                            ):
                                self._clear_workspace_teach_confirmation_locked()
                                self._clear_workspace_teach_persisting_locked()
                                self._set_workspace_teach_owner_locked(False)
                            else:
                                self._workspace_teach_invalidation_pending.set()
                                self._invalidate_workspace_teach_locked()

    def _record_xarm_sample_error(self, code: str = "sample_failed") -> None:
        with self._xarm_status_lock:
            previous = dict(self._xarm_status)
            previous.update(
                {
                    "available": False,
                    "connected": False,
                    "healthy": False,
                    "sample_error": str(code)[:48],
                }
            )
            self._xarm_status = previous
        with self._ota_admission_lock:
            lease_active = self._ota_admission_lease is not None
        if lease_active:
            self._set_ota_admission_changed(
                "telemetry_changed",
                "before_network",
            )
        # A cache/SDK failure during an acquisition destroys continuity of the
        # read-only evidence.  Do not advance the pose sequence or allow a
        # session with captured points to resume after the gap.
        if self._workspace_teach_owner_active:
            self._invalidate_workspace_teach()

    @staticmethod
    def _bounded_xarm_integer(value: Any, *, maximum: int) -> Optional[int]:
        if isinstance(value, bool) or not isinstance(value, int):
            return None
        return value if 0 <= value <= maximum else None

    def xarm_status(self) -> Mapping[str, Any]:
        """Return a path-, credential-, and raw-exception-free xArm snapshot."""

        with self._xarm_status_lock:
            result = dict(self._xarm_status)
        sampled_at = result.pop("sampled_at_monotonic_s", 0.0)
        try:
            age = max(0.0, float(self._monotonic()) - float(sampled_at))
        except (TypeError, ValueError, OverflowError):
            age = _XARM_STATUS_MAX_AGE_SECONDS + 1.0
        age = min(age, 86400.0)
        result["sample_age_seconds"] = age
        result["fresh"] = bool(
            result.get("available") is True and age <= _XARM_STATUS_MAX_AGE_SECONDS
        )
        dashboard_metrics = result.get("metrics")
        if not isinstance(dashboard_metrics, Mapping):
            dashboard_metrics = _empty_xarm_metrics()
        dashboard_metrics = dict(dashboard_metrics)
        for key, value in tuple(dashboard_metrics.items()):
            if isinstance(value, list):
                dashboard_metrics[key] = list(value)
        for section in ("controller", "safety"):
            section_value = dashboard_metrics.get(section)
            copied_section = (
                dict(section_value) if isinstance(section_value, Mapping) else {}
            )
            for key, value in tuple(copied_section.items()):
                if isinstance(value, list):
                    copied_section[key] = list(value)
            dashboard_metrics[section] = copied_section
        dashboard_metrics["sample_age_seconds"] = age
        dashboard_metrics["fresh"] = result["fresh"]
        result["metrics"] = dashboard_metrics
        return result

    def digital_twin_status(
        self,
        *,
        xarm_snapshot: Optional[Mapping[str, Any]] = None,
        camera_snapshot: Optional[Mapping[str, Any]] = None,
    ) -> Mapping[str, Any]:
        """Return the read-only visualization/preflight state for ``/healthz``.

        The provider consumes only bounded cached telemetry.  It never reads the
        xArm SDK and its output is not consulted by the unconditional motion
        release lock.
        """

        provider = self.digital_twin_provider
        snapshot = getattr(provider, "snapshot", None)
        if not callable(snapshot):
            raise RuntimeError("Digital-twin snapshot provider is unavailable")
        with self._xarm_status_lock:
            pose_sequence = int(self._xarm_pose_sequence)
        xarm = (
            dict(xarm_snapshot)
            if isinstance(xarm_snapshot, Mapping)
            else dict(self.xarm_status())
        )
        cameras = (
            dict(camera_snapshot)
            if isinstance(camera_snapshot, Mapping)
            else dict(self._camera_health_metrics())
        )
        lower = tuple(
            getattr(self.settings, "eye_in_hand_workspace_lower_xyz_mm", ())
            or getattr(self.settings, "capture_workspace_lower_xyz_mm", ())
        )
        upper = tuple(
            getattr(self.settings, "eye_in_hand_workspace_upper_xyz_mm", ())
            or getattr(self.settings, "capture_workspace_upper_xyz_mm", ())
        )
        return snapshot(
            configured=self.metric_source is not None,
            xarm_status=xarm,
            pose_sequence=pose_sequence,
            workspace_lower_xyz_mm=lower,
            workspace_upper_xyz_mm=upper,
            camera_status=cameras,
            tool_calibration_sha256=getattr(
                self.settings,
                "eye_in_hand_calibration_sha256",
                "",
            ),
            workspace_calibration_sha256=getattr(
                self.settings,
                "workspace_depth_calibration_sha256",
                "",
            ),
            # The formal root-owned one-use release chain is intentionally not
            # implemented.  Camera/FK evidence can therefore never turn this on.
            motion_release_valid=False,
        )

    def _record_bound_clearance_evidence(self, evidence: Any) -> None:
        """Attach the current cached pose sequence to producer-bound evidence."""

        recorder = getattr(
            self.digital_twin_provider,
            "record_clearance_evidence",
            None,
        )
        if not callable(recorder) or not isinstance(evidence, Mapping):
            return
        payload = copy.deepcopy(dict(evidence))
        binding = payload.get("_binding")
        if isinstance(binding, Mapping):
            binding = dict(binding)
            with self._xarm_status_lock:
                binding["pose_sequence"] = int(self._xarm_pose_sequence)
            payload["_binding"] = binding
        recorder(payload)

    def workspace_teach_status(self) -> Mapping[str, Any]:
        """Return the exact read-only teach contract from the local recorder."""

        if self._workspace_teach_invalidation_pending.is_set():
            self._invalidate_workspace_teach(blocking=False, request=False)
        recorder = self.workspace_teach_recorder
        snapshot = getattr(recorder, "snapshot", None)
        if not callable(snapshot):
            return {
                "schema_version": 1,
                "configured": False,
                "state": "idle",
                "coordinate_frame": "xarm_base_mm",
                "required_controller_mode": 2,
                "session_id": "",
                "current_step": "",
                "completed_steps": 0,
                "total_steps": 6,
                "guidance": {},
                "pose_ready": False,
                "current_tcp_position_mm": [],
                "hard_envelope_mm": {
                    "lower": [-440.0, -440.0, -165.0],
                    "upper": [440.0, 440.0, 683.5],
                },
                "captured_bounds_mm": {
                    "lower": [None, None, None],
                    "upper": [None, None, None],
                },
                "proposal_sha256": "",
                "blockers": ["session_not_started"],
                "safety_notice": (
                    "TCP-BOX IST NUR EIN PRUEFVORSCHLAG; KEINE MOTION-FREIGABE"
                ),
            }
        with self._workspace_teach_lock:
            value = snapshot()
            return dict(value) if isinstance(value, Mapping) else {}

    def workspace_boundary_status(self) -> Mapping[str, Any]:
        """Return the bounded dual-camera/Newton assessment contract."""

        snapshot = getattr(self.workspace_boundary_validator, "snapshot", None)
        if not callable(snapshot):
            try:
                from main.newton_workspace import (
                    WorkspaceBoundaryValidationCoordinator,
                )
            except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                from newton_workspace import (  # type: ignore[no-redef]
                    WorkspaceBoundaryValidationCoordinator,
                )

            return dict(WorkspaceBoundaryValidationCoordinator.unavailable())
        try:
            value = snapshot()
        except Exception:
            LOGGER.warning("Workspace boundary status failed", exc_info=True)
            return {
                "schema_version": 1,
                "configured": True,
                "state": "blocked",
                "session_id": "",
                "proposal_sha256": "",
                "robot_sha256": "",
                "bounds_mm": {"lower": [], "upper": []},
                "cameras": {
                    "tool": {
                        "source_id": "",
                        "frame_sequence": 0,
                        "calibration_sha256": "",
                    },
                    "workspace": {
                        "source_id": "",
                        "frame_sequence": 0,
                        "calibration_sha256": "",
                    },
                },
                "camera_evidence_sha256": "",
                "newton_version": "",
                "newton_model_sha256": "",
                "newton_result_sha256": "",
                "blockers": ["result_invalid"],
                "motion_authority": "none",
                "motion_authorized": False,
            }
        return dict(value) if isinstance(value, Mapping) else {}

    def _invalidate_workspace_boundary(self) -> None:
        invalidate = getattr(self.workspace_boundary_validator, "invalidate", None)
        if callable(invalidate):
            try:
                invalidate()
            except Exception:
                LOGGER.warning(
                    "Workspace boundary validation could not be invalidated",
                    exc_info=True,
                )

    def _workspace_boundary_valid_for_current_proposal(self) -> bool:
        boundary = self.workspace_boundary_status()
        teach = self.workspace_teach_status()
        boundary_session = boundary.get("session_id")
        boundary_digest = boundary.get("proposal_sha256")
        teach_session = teach.get("session_id")
        teach_digest = teach.get("proposal_sha256")
        return bool(
            boundary.get("state") == "valid"
            and boundary.get("motion_authority") == "none"
            and boundary.get("motion_authorized") is False
            and teach.get("state") == "proposed"
            and isinstance(boundary_session, str)
            and isinstance(teach_session, str)
            and secrets.compare_digest(boundary_session, teach_session)
            and isinstance(boundary_digest, str)
            and isinstance(teach_digest, str)
            and secrets.compare_digest(boundary_digest, teach_digest)
        )

    def _workspace_teach_blocks_physical_operation(self) -> bool:
        """Conservatively expose the durable read-only session reservation."""

        return bool(
            self._workspace_teach_owner_active
            or self._workspace_teach_invalidation_pending.is_set()
        )

    def request_workspace_teach_start(self) -> Mapping[str, Any]:
        """Start coordinate-free acquisition; never change controller state."""

        recorder = self.workspace_teach_recorder
        begin = getattr(recorder, "begin", None)
        snapshot = getattr(recorder, "snapshot", None)
        if not callable(begin) or self.workspace_teach_store is None:
            return {"status": "unavailable"}
        if not callable(snapshot):
            return {"status": "unavailable"}
        if not self._operation_transition_lock.acquire(blocking=False):
            return {"status": "busy"}
        try:
            if self._workspace_teach_invalidation_pending.is_set():
                self._invalidate_workspace_teach_locked()
                return {"status": "busy"}
            with self._workspace_teach_lock:
                current = snapshot()
                if (
                    not isinstance(current, Mapping)
                    or current.get("state")
                    not in {"idle", "cancelled", "invalidated", "proposed"}
                    or self._workspace_teach_owner_active
                    or bool(self._workspace_teach_persisting_token)
                ):
                    return {"status": "busy"}
                with self._lock:
                    started = self._started
                with self._motion_lock:
                    motion_active = self._motion_armed or self._motion_live
                if (
                    not started
                    or self._restart_pending
                    or self._fatal_event.is_set()
                    or motion_active
                    or self._capture_operation_lock.locked()
                    or self._petri_run_lock.locked()
                    or self._petri_durable_owner_blocks_physical_operation()
                    or self._ota_lock.locked()
                    or self._safety_configuration_state == "configuring"
                ):
                    return {"status": "busy"}
                self._clear_workspace_teach_confirmation_locked()
                self._clear_workspace_teach_persisting_locked()
                try:
                    begin()
                except Exception:
                    LOGGER.exception("Workspace-teach start failed")
                    return {"status": "error"}
                self._set_workspace_teach_owner_locked(True)
                return {"status": "accepted"}
        finally:
            self._operation_transition_lock.release()

    def request_workspace_teach_capture(self) -> Mapping[str, Any]:
        """Capture only the recorder's current validated cached TCP sample."""

        capture = getattr(self.workspace_teach_recorder, "capture", None)
        if not callable(capture):
            return {"status": "unavailable"}
        with self._operation_transition_lock:
            with self._workspace_teach_lock:
                if self._workspace_teach_invalidation_pending.is_set():
                    self._invalidate_workspace_teach_locked()
                    return {"status": "unsafe"}
                if not self._workspace_teach_owner_active:
                    return {"status": "unsafe"}
                self._clear_workspace_teach_confirmation_locked()
                try:
                    captured = capture()
                except Exception:
                    return {"status": "unsafe"}
                # STOP publishes this fence before it waits for the operation
                # transition lane.  Recheck after the recorder call so a STOP
                # that began during capture cannot be reported as accepted or
                # leave the newly captured point current.
                with self._motion_lock:
                    interrupted = self._workspace_teach_invalidation_pending.is_set()
                if interrupted:
                    self._invalidate_workspace_teach_locked()
                    return {"status": "unsafe"}
                state = (
                    captured.get("state")
                    if isinstance(captured, Mapping)
                    else "invalidated"
                )
                if state in {"idle", "cancelled", "invalidated", "proposed"}:
                    self._set_workspace_teach_owner_locked(False)
                    return {"status": "unsafe"}
                return {"status": "accepted"}

    def request_workspace_teach_cancel(self) -> Mapping[str, Any]:
        """Cancel locally without a challenge or controller command."""

        cancel = getattr(self.workspace_teach_recorder, "cancel", None)
        if not callable(cancel):
            return {"status": "unavailable"}
        with self._operation_transition_lock:
            if self._workspace_teach_invalidation_pending.is_set():
                self._invalidate_workspace_teach_locked()
                return {"status": "cancelled"}
            with self._workspace_teach_lock:
                self._clear_workspace_teach_confirmation_locked()
                self._clear_workspace_teach_persisting_locked()
                try:
                    cancelled = cancel()
                except Exception:
                    LOGGER.exception("Workspace-teach cancellation failed")
                    self._workspace_teach_invalidation_pending.set()
                    self._invalidate_workspace_teach_locked()
                    return {"status": "error"}
                cancelled_state = (
                    cancelled.get("state") if isinstance(cancelled, Mapping) else ""
                )
                if cancelled_state not in {
                    "idle",
                    "cancelled",
                    "invalidated",
                    "proposed",
                }:
                    self._workspace_teach_invalidation_pending.set()
                    self._invalidate_workspace_teach_locked()
                    return {"status": "error"}
                self._set_workspace_teach_owner_locked(False)
                return {"status": "cancelled"}

    def request_workspace_teach_finalize(
        self,
        challenge: Optional[str] = None,
    ) -> Mapping[str, Any]:
        """Finalize one exact proposal through a 5-second one-use challenge."""

        supplied = _validated_optional_challenge(challenge)
        recorder = self.workspace_teach_recorder
        store = self.workspace_teach_store
        snapshot = getattr(recorder, "snapshot", None)
        review_proposal = getattr(recorder, "review_proposal", None)
        mark_persisted = getattr(recorder, "_mark_persisted", None)
        save = getattr(store, "save", None)
        if (
            not callable(snapshot)
            or not callable(review_proposal)
            or not callable(mark_persisted)
            or not callable(save)
        ):
            return {"status": "unavailable"}
        if supplied is None:
            return {"status": "confirmation_required"}

        proposal = None
        expected_digest = ""
        expected_session_id = ""
        expected_stop_generation = -1
        persistence_token = ""
        with self._workspace_teach_lock:
            if self._workspace_teach_invalidation_pending.is_set():
                return {"status": "confirmation_required"}
            if self._workspace_teach_persisting_token:
                return {"status": "busy"}
            current = snapshot()
            if not isinstance(current, Mapping):
                self._clear_workspace_teach_confirmation_locked()
                return {"status": "unsafe"}
            session_id = current.get("session_id")
            proposal_sha256 = current.get("proposal_sha256")
            if supplied == "":
                self._clear_workspace_teach_confirmation_locked()
                if (
                    current.get("state") != "review"
                    or not self._workspace_teach_owner_active
                    or not isinstance(session_id, str)
                    or re.fullmatch(r"[0-9a-f]{32}", session_id) is None
                    or not isinstance(proposal_sha256, str)
                    or re.fullmatch(r"[0-9a-f]{64}", proposal_sha256) is None
                ):
                    return {"status": "unsafe"}
                token = secrets.token_hex(16)
                with self._motion_lock:
                    stop_generation = self._motion_stop_generation
                self._workspace_teach_finalize_challenge = token
                self._workspace_teach_finalize_expires_at = (
                    float(self._monotonic()) + _WORKSPACE_TEACH_CONFIRMATION_SECONDS
                )
                self._workspace_teach_finalize_session_id = session_id
                self._workspace_teach_finalize_proposal_sha256 = proposal_sha256
                self._workspace_teach_finalize_stop_generation = stop_generation
                return {
                    "status": "confirm",
                    "challenge": token,
                    "expires_in_seconds": 5,
                    "proposal_sha256": proposal_sha256,
                }

            with self._motion_lock:
                current_stop_generation = self._motion_stop_generation
            valid = bool(
                self._workspace_teach_finalize_challenge
                and self._workspace_teach_finalize_expires_at
                >= float(self._monotonic())
                and secrets.compare_digest(
                    self._workspace_teach_finalize_challenge,
                    supplied,
                )
                and current.get("state") == "review"
                and self._workspace_teach_owner_active
                and session_id == self._workspace_teach_finalize_session_id
                and proposal_sha256 == self._workspace_teach_finalize_proposal_sha256
                and current_stop_generation
                == self._workspace_teach_finalize_stop_generation
            )
            expected_digest = self._workspace_teach_finalize_proposal_sha256
            expected_session_id = self._workspace_teach_finalize_session_id
            expected_stop_generation = self._workspace_teach_finalize_stop_generation
            # Consume before any finalization or append-only filesystem write.
            self._clear_workspace_teach_confirmation_locked()
            if not valid:
                return {"status": "confirmation_required"}
            try:
                proposal = review_proposal()
            except Exception:
                return {"status": "unsafe"}
            actual_digest = getattr(proposal, "sha256", "")
            proposal_session = getattr(proposal, "document", {}).get("session_id")
            if (
                not isinstance(actual_digest, str)
                or not secrets.compare_digest(actual_digest, expected_digest)
                or not isinstance(proposal_session, str)
                or not secrets.compare_digest(proposal_session, expected_session_id)
            ):
                return {"status": "error"}
            persistence_token = secrets.token_hex(16)
            self._workspace_teach_persisting_token = persistence_token
            self._workspace_teach_persisting_session_id = expected_session_id
            self._workspace_teach_persisting_proposal_sha256 = expected_digest
            self._workspace_teach_persisting_stop_generation = expected_stop_generation

        try:
            save(proposal)
        except Exception:
            LOGGER.exception("Workspace-teach proposal persistence failed")
            with self._workspace_teach_lock:
                if secrets.compare_digest(
                    self._workspace_teach_persisting_token,
                    persistence_token,
                ):
                    self._clear_workspace_teach_persisting_locked()
            return {"status": "error"}

        # Re-enter the short transition lane only after fsync/link completed.
        # STOP/cancel can invalidate the review while the file is written; in
        # that case the append-only file is audit evidence but is never exposed
        # as a successfully proposed configuration.
        with self._operation_transition_lock:
            with self._workspace_teach_lock:
                current = snapshot()
                with self._motion_lock:
                    current_stop_generation = self._motion_stop_generation
                    still_current = bool(
                        not self._workspace_teach_invalidation_pending.is_set()
                        and secrets.compare_digest(
                            self._workspace_teach_persisting_token,
                            persistence_token,
                        )
                        and self._workspace_teach_persisting_session_id
                        == expected_session_id
                        and self._workspace_teach_persisting_proposal_sha256
                        == expected_digest
                        and self._workspace_teach_persisting_stop_generation
                        == expected_stop_generation
                        and self._workspace_teach_owner_active
                        and current.get("state") == "review"
                        and current.get("session_id") == expected_session_id
                        and current.get("proposal_sha256") == expected_digest
                        and current_stop_generation == expected_stop_generation
                    )
                    if not still_current:
                        if secrets.compare_digest(
                            self._workspace_teach_persisting_token,
                            persistence_token,
                        ):
                            self._clear_workspace_teach_persisting_locked()
                        return {"status": "confirmation_required"}
                    try:
                        persisted = mark_persisted(
                            session_id=expected_session_id,
                            proposal_sha256=expected_digest,
                            still_valid=lambda: (
                                not self._workspace_teach_invalidation_pending.is_set()
                                and self._motion_stop_generation
                                == expected_stop_generation
                            ),
                        )
                    except Exception:
                        LOGGER.exception(
                            "Workspace-teach persisted-state transition failed"
                        )
                        self._workspace_teach_invalidation_pending.set()
                        self._invalidate_workspace_teach_locked()
                        return {"status": "error"}
                actual_digest = getattr(persisted, "sha256", "")
                transitioned = snapshot()
                transition_verified = bool(
                    isinstance(transitioned, Mapping)
                    and transitioned.get("state") == "proposed"
                    and transitioned.get("session_id") == expected_session_id
                    and transitioned.get("proposal_sha256") == expected_digest
                    and isinstance(actual_digest, str)
                    and secrets.compare_digest(actual_digest, expected_digest)
                )
                if not transition_verified:
                    self._workspace_teach_invalidation_pending.set()
                    self._invalidate_workspace_teach_locked()
                    return {"status": "error"}
                self._set_workspace_teach_owner_locked(False)
                self._clear_workspace_teach_persisting_locked()
                boundary_start = getattr(
                    self.workspace_boundary_validator,
                    "start",
                    None,
                )
                if callable(boundary_start):
                    try:
                        boundary_start(persisted)
                    except Exception:
                        # The durable TCP-box proposal remains valid audit
                        # evidence, but camera/Newton validation fails closed
                        # and never changes the controller or grants motion.
                        LOGGER.warning(
                            "Workspace boundary validation could not start",
                            exc_info=True,
                        )
                return {
                    "status": "proposed",
                    "proposal_sha256": actual_digest,
                }

    def _clear_workspace_teach_confirmation_locked(self) -> None:
        self._workspace_teach_finalize_challenge = ""
        self._workspace_teach_finalize_expires_at = 0.0
        self._workspace_teach_finalize_session_id = ""
        self._workspace_teach_finalize_proposal_sha256 = ""
        self._workspace_teach_finalize_stop_generation = -1

    def _clear_workspace_teach_persisting_locked(self) -> None:
        self._workspace_teach_persisting_token = ""
        self._workspace_teach_persisting_session_id = ""
        self._workspace_teach_persisting_proposal_sha256 = ""
        self._workspace_teach_persisting_stop_generation = -1

    def _set_workspace_teach_owner_locked(self, active: bool) -> None:
        """Advance the OTA-visible generation when Teach ownership changes."""

        safe_active = bool(active)
        if safe_active is self._workspace_teach_owner_active:
            return
        self._workspace_teach_owner_active = safe_active
        self._workspace_teach_generation = min(
            self._workspace_teach_generation + 1,
            1_000_000_000,
        )

    def _invalidate_workspace_teach_locked(
        self,
        *,
        workspace_blocking: bool = True,
    ) -> bool:
        """Invalidate Teach while the operation-transition lock is held."""

        invalidate = getattr(self.workspace_teach_recorder, "invalidate", None)
        was_active = self._workspace_teach_blocks_physical_operation()
        if not self._workspace_teach_lock.acquire(blocking=workspace_blocking):
            return bool(was_active)
        try:
            was_active = self._workspace_teach_owner_active
            self._clear_workspace_teach_confirmation_locked()
            self._clear_workspace_teach_persisting_locked()
            invalidated_state = (
                "idle" if not callable(invalidate) and not was_active else ""
            )
            if callable(invalidate):
                try:
                    invalidated = invalidate()
                    if isinstance(invalidated, Mapping):
                        invalidated_state = str(invalidated.get("state") or "")
                except Exception:
                    LOGGER.error(
                        "Workspace-teach invalidation failed",
                        exc_info=True,
                    )
            if invalidated_state not in {
                "idle",
                "cancelled",
                "invalidated",
                "proposed",
            }:
                # Never release the durable reservation on an unproven
                # recorder transition.  STOP generation fencing still blocks
                # finalize while later health/admission calls retry.
                self._workspace_teach_invalidation_pending.set()
                return bool(was_active)
            self._set_workspace_teach_owner_locked(False)
            self._workspace_teach_invalidation_pending.clear()
            return bool(was_active)
        finally:
            self._workspace_teach_lock.release()

    def _invalidate_workspace_teach(
        self,
        *,
        blocking: bool = True,
        request: bool = True,
    ) -> bool:
        """Fence Teach immediately and invalidate it without delaying STOP."""

        if request:
            # Telemetry-failure invalidation uses the same short lane as STOP
            # and the durable final mark.  It therefore cannot publish a
            # pending fence in the callback-to-state-mutation interval.
            with self._motion_lock:
                self._workspace_teach_invalidation_pending.set()
        was_active = self._workspace_teach_blocks_physical_operation()
        if not self._operation_transition_lock.acquire(blocking=blocking):
            return bool(was_active)
        try:
            return self._invalidate_workspace_teach_locked(
                workspace_blocking=blocking,
            ) or bool(was_active)
        finally:
            self._operation_transition_lock.release()

    def _camera_health_metrics(self) -> Mapping[str, Any]:
        if self.camera_rig is None:
            return {}
        try:
            health = self.camera_rig.health()
        except Exception:
            LOGGER.debug("Could not read camera health", exc_info=True)
            return {}
        if not isinstance(health, Mapping):
            return {}
        role_objects = {}
        for role in health:
            role_name = getattr(role, "value", str(role))
            if role_name in {"tool", "workspace"}:
                role_objects[role_name] = role
        result = {}
        max_age = max(1.0, self.settings.image_sample_seconds * 2.0)
        for role_name in ("tool", "workspace"):
            backend = str(
                getattr(self.settings, "{}_camera_backend".format(role_name), "")
            )
            source_id = _bounded_public_identifier(
                getattr(
                    self.settings,
                    "{}_camera_source_id".format(role_name),
                    "",
                ),
                limit=255,
            )
            configured_mxid = _bounded_public_identifier(
                getattr(
                    self.settings,
                    "{}_camera_device_id".format(role_name),
                    "",
                ),
                limit=255,
            )
            safe_default = {
                "schema_version": 1,
                "role": role_name,
                "backend": backend if backend in _CAMERA_BACKENDS else "unknown",
                "source_id": source_id,
                "mxid": configured_mxid if backend == "depthai" else "",
                "state": "degraded",
                "fresh": False,
                "sample_age_seconds": None,
                "sequence": 0,
                "frames_captured": 0,
                "reconnects": 0,
                "consecutive_errors": 0,
            }
            role = role_objects.get(role_name)
            if role is None or backend not in _CAMERA_BACKENDS or not source_id:
                result[role_name] = safe_default
                continue
            try:
                stream = self.camera_rig.stream(role)
                status_reader = getattr(stream, "public_status", None)
                raw = (
                    status_reader(max_age_s=max_age)
                    if callable(status_reader)
                    else None
                )
            except Exception:
                LOGGER.debug(
                    "Could not read %s camera public status",
                    role_name,
                    exc_info=True,
                )
                raw = None
            if not isinstance(raw, Mapping):
                result[role_name] = safe_default
                continue

            def counter(name: str, maximum: int) -> Optional[int]:
                value = raw.get(name)
                if (
                    isinstance(value, bool)
                    or not isinstance(value, int)
                    or not 0 <= value <= maximum
                ):
                    return None
                return value

            age_raw = raw.get("sample_age_seconds")
            age = (
                None
                if age_raw is None
                else _bounded_finite_number(age_raw, maximum=86_400.0)
            )
            sequence = counter("sequence", 10_000_000_000)
            frames_captured = counter("frames_captured", 10_000_000_000)
            reconnects = counter("reconnects", 1_000_000_000)
            consecutive_errors = counter("consecutive_errors", 1_000_000_000)
            state = raw.get("state")
            fresh = raw.get("fresh")
            mxid = raw.get("mxid")
            valid = (
                raw.get("schema_version") == 1
                and raw.get("role") == role_name
                and raw.get("backend") == backend
                and raw.get("source_id") == source_id
                and isinstance(mxid, str)
                and _bounded_public_identifier(mxid, limit=255) == mxid
                and (backend == "depthai" or mxid == "")
                and (not configured_mxid or mxid == configured_mxid)
                and state in _CAMERA_STATES
                and type(fresh) is bool
                and (age_raw is None or age is not None)
                and (fresh is not True or (state == "running" and age is not None))
                and sequence is not None
                and frames_captured is not None
                and reconnects is not None
                and consecutive_errors is not None
            )
            if not valid:
                result[role_name] = safe_default
                continue
            result[role_name] = {
                "schema_version": 1,
                "role": role_name,
                "backend": backend,
                "source_id": source_id,
                "mxid": mxid,
                "state": state,
                "fresh": fresh,
                "sample_age_seconds": age,
                "sequence": sequence,
                "frames_captured": frames_captured,
                "reconnects": reconnects,
                "consecutive_errors": consecutive_errors,
            }
        return result

    def _tool_pose_loop(self) -> None:
        read_pose = getattr(self.metric_source, "read_timed_tool_pose", None)
        if not callable(read_pose):
            LOGGER.error("Eye-in-hand pose source is unavailable")
            return
        while not self._stop_event.is_set():
            try:
                self.tool_pose_buffer.add(read_pose())
            except Exception:
                LOGGER.warning("xArm pose-history sampling failed", exc_info=True)
            self._stop_event.wait(self.settings.eye_in_hand_pose_sample_seconds)

    def _valve_loop(self) -> None:
        self.valve_controller.run_loop(
            self._stop_event,
            interval_seconds=self.settings.dynamic_valve_interval_seconds,
            armed_gate=self.motion_is_armed,
            live_gate=self.motion_is_live,
            authorization_provider=self.motion_authorization_generation,
            authorization_validator=self.motion_authorization_is_valid,
            motion_stop_requested=self._motion_abort_event.is_set,
            on_result=self._record_valve_cycle,
        )

    def _record_valve_cycle(self, result: Any) -> None:
        self.last_valve_cycle = result
        status = str(getattr(result, "status", "unknown"))
        if status == "executed":
            # One deliberate arming authorizes one valve motion only.
            self._motion_abort_event.set()
            with self._motion_lock:
                self._motion_stop_generation += 1
                self._motion_authorization_generation += 1
                self._motion_authorization_expires_at = 0.0
                self._motion_armed = False
                self._motion_live = False
            if self.xarm_motion_adapter is not None:
                try:
                    self.xarm_motion_adapter.halt()
                except Exception as exc:
                    with self._motion_lock:
                        self._motion_fault_reason = "halt: {}".format(
                            type(exc).__name__
                        )
                    self._enqueue_motion_metric("completion_halt_failed")
                    return
            self._enqueue_motion_metric("completed_and_locked")
        elif status in {"execution_error", "motion_fault_latched"} or (
            status == "stopped" and int(getattr(result, "completed_commands", 0)) > 0
        ):
            self._motion_abort_event.set()
            with self._motion_lock:
                self._motion_stop_generation += 1
                self._motion_authorization_generation += 1
                self._motion_authorization_expires_at = 0.0
                self._motion_armed = False
                self._motion_live = False
                self._motion_fault_reason = status
            if self.xarm_motion_adapter is not None:
                try:
                    self.xarm_motion_adapter.halt()
                except Exception:
                    LOGGER.error(
                        "Could not halt xArm after motion fault",
                        exc_info=True,
                    )
            self._enqueue_motion_metric("fault_locked")
        elif status == "authorization_invalid":
            self._expire_motion_authorization_if_needed()
        elif status == "stopped" and not self.motion_is_armed():
            # Keep the STOP event latched.  Only a newly admitted, generation-
            # bound operation may clear it; an asynchronous cycle callback
            # must never erase a newer operator STOP.
            pass

    def _enqueue_motion_metric(self, event: str) -> None:
        if self.datahub is None:
            return
        try:
            payload = dict(self.motion_status())
            payload["event"] = str(event)
            self.datahub.enqueue_metrics(
                {"motion": payload},
                attributes={"source": "dynamic-valve-controller"},
            )
        except Exception:
            LOGGER.warning("Could not enqueue motion status", exc_info=True)

    def _ota_loop(self) -> None:
        """Poll Store Connect and optionally apply through the manual gate.

        Automatic application is an explicit, fail-closed configuration.  It
        reuses the same atomic physical-operation reservation and verified
        updater path as an operator-requested install; the default branch stays
        metadata-only.
        """

        interval = self.settings.ota_poll_seconds
        while not self._stop_event.wait(interval):
            if self._restart_pending or self._fatal_event.is_set():
                continue
            commissioning = self._evaluate_ota_commissioning()
            if commissioning.permitted:
                if not self._reserve_ota_owner():
                    continue
                try:
                    self._check_update_once(allow_reserved=True)
                except Exception:
                    LOGGER.warning("Scheduled secure OTA install failed", exc_info=True)
                finally:
                    self._release_ota_owner()
                continue
            if not self._ota_lock.acquire(blocking=False):
                continue
            try:
                self._check_update_availability_once()
            except Exception:
                LOGGER.warning(
                    "Scheduled secure OTA metadata check failed", exc_info=True
                )
            finally:
                self._ota_lock.release()

    def _check_update_availability_once(self) -> OTAResult:
        """Run the updater's non-mutating manifest check for the poller."""

        updater = self.ota_updater
        check = getattr(updater, "check_for_update", None)
        if not callable(check):
            self._record_ota_status(
                "unavailable",
                message="Scheduled metadata checks are unavailable",
                manifest_verification="not_checked",
                archive_digest_verification="not_checked",
            )
            raise RuntimeError("OTA updater has no metadata-only check")
        self._record_ota_status(
            "checking",
            manifest_verification="checking",
            archive_digest_verification="not_checked",
        )
        try:
            result = check()
        except Exception as exc:
            manifest, archive = self._ota_verification_evidence(updater)
            self._record_ota_status(
                "error",
                message="Secure update metadata check failed",
                error_code=self._ota_error_code(exc),
                manifest_verification=manifest,
                archive_digest_verification=archive,
            )
            raise
        if not self._record_ota_result(result):
            raise RuntimeError("OTA updater returned incomplete verification evidence")
        return result

    def _check_update_once(self, *, allow_reserved: bool = False) -> OTAResult:
        if not self._ota_environment_ready(allow_reserved=allow_reserved):
            self._record_ota_status("busy")
            raise RuntimeError("Secure OTA admission changed before update check")
        self._record_ota_status(
            "checking",
            manifest_verification="checking",
            archive_digest_verification="not_checked",
        )
        try:
            with self._ota_admission_lock:
                admission_lease = self._ota_admission_lease
            arguments: Mapping[str, Any] = {
                "restart": self._request_ota_restart,
            }
            if admission_lease is not None:
                arguments = {
                    **arguments,
                    "admission_revalidator": self._revalidate_ota_admission_lease,
                }
            result = self.ota_updater.check_and_apply(  # type: ignore[union-attr]
                **arguments
            )
        except Exception as exc:
            manifest, archive = self._ota_verification_evidence(self.ota_updater)
            self._record_ota_status(
                "error",
                message="Secure update check failed",
                error_code=self._ota_error_code(exc),
                manifest_verification=manifest,
                archive_digest_verification=archive,
            )
            raise
        if not self._record_ota_result(result):
            raise RuntimeError("OTA updater returned incomplete verification evidence")
        return result

    def _record_ota_result(self, result: OTAResult) -> bool:
        """Record only the bounded result/evidence contract from the updater."""

        status = str(getattr(result, "status", ""))
        manifest = getattr(result, "manifest_verification", "not_checked")
        archive = getattr(result, "archive_digest_verification", "not_checked")
        evidence_valid = bool(
            status
            in {
                "up_to_date",
                "update_available",
                "busy",
                "pending_restart",
            }
            and manifest in _OTA_MANIFEST_VERIFICATION_STATES
            and archive in _OTA_ARCHIVE_VERIFICATION_STATES
        )
        if status == "pending_restart":
            evidence_valid = bool(
                evidence_valid and manifest == "verified" and archive == "verified"
            )
        elif status == "update_available":
            evidence_valid = bool(
                evidence_valid and manifest == "verified" and archive == "not_required"
            )
        elif status == "up_to_date":
            evidence_valid = bool(
                evidence_valid
                and (manifest, archive)
                in {
                    ("verified", "not_required"),
                    ("not_available", "not_required"),
                }
            )
        if not evidence_valid:
            self._record_ota_status(
                "error",
                message="Secure update verification evidence is incomplete",
                error_code="update_check_failed",
                manifest_verification=(
                    manifest
                    if manifest in _OTA_MANIFEST_VERIFICATION_STATES
                    else "failed"
                ),
                archive_digest_verification=(
                    archive if archive in _OTA_ARCHIVE_VERIFICATION_STATES else "failed"
                ),
            )
            return False
        self._record_ota_status(
            status,
            available_version=getattr(result, "available_version", ""),
            message=getattr(result, "message", ""),
            manifest_verification=manifest,
            archive_digest_verification=archive,
        )
        return True

    @staticmethod
    def _ota_verification_evidence(updater: Any) -> Tuple[str, str]:
        reader = getattr(updater, "verification_status", None)
        try:
            evidence = reader() if callable(reader) else {}
        except Exception:
            evidence = {}
        if not isinstance(evidence, Mapping):
            evidence = {}
        manifest = evidence.get("manifest_verification")
        archive = evidence.get("archive_digest_verification")
        return (
            manifest if manifest in _OTA_MANIFEST_VERIFICATION_STATES else "failed",
            archive if archive in _OTA_ARCHIVE_VERIFICATION_STATES else "failed",
        )

    def _ota_admission_owner_snapshot(self) -> Tuple[Tuple[str, Any], ...]:
        capture = dict(self.capture_run_status())
        hand = dict(self.hand_training_status())
        durable_petri = dict(self._petri_process_durable_status())
        with self._operations_lock:
            petri_state = str(self._petri_status.get("state") or "")
            recovery_state = str(self._recovery_status.get("state") or "")
        return (
            ("capture_active", capture.get("active") is True),
            ("capture_state", str(capture.get("state") or "")),
            ("capture_reserved", self._capture_operation_lock.locked()),
            ("hand_reserved", self._hand_training_operation_lock.locked()),
            ("hand_state", str(hand.get("state") or "")),
            ("ota_reserved", self._ota_lock.locked()),
            ("petri_active", durable_petri.get("active") is True),
            ("petri_recovery", durable_petri.get("recovery_required") is True),
            ("petri_reserved", self._petri_run_lock.locked()),
            ("petri_state", petri_state),
            ("recovery_state", recovery_state),
            ("restart_pending", self._restart_pending),
            ("transition_reserved", self._operation_transition_lock.locked()),
        )

    def _ota_admission_snapshot(self) -> Mapping[str, Any]:
        xarm = dict(self.xarm_status())
        with self._xarm_status_lock:
            telemetry_sequence = int(self._xarm_pose_sequence)
        cameras = dict(self._camera_health_metrics())
        camera_identities = []
        camera_sequences = []
        camera_errors = []
        camera_ready = set(cameras) == {"tool", "workspace"}
        for role in ("tool", "workspace"):
            camera = cameras.get(role)
            camera = camera if isinstance(camera, Mapping) else {}
            identity = (
                role,
                str(camera.get("backend") or "")[:16],
                str(camera.get("source_id") or "")[:255],
                str(camera.get("mxid") or "")[:255],
            )
            sequence = camera.get("sequence")
            errors = camera.get("consecutive_errors")
            sequence_valid = bool(
                isinstance(sequence, int)
                and not isinstance(sequence, bool)
                and 0 < sequence <= 10_000_000_000
            )
            errors_valid = bool(
                isinstance(errors, int)
                and not isinstance(errors, bool)
                and 0 <= errors <= 1_000_000_000
            )
            expected_backend = str(
                getattr(self.settings, "{}_camera_backend".format(role), "")
            )
            expected_source = str(
                getattr(self.settings, "{}_camera_source_id".format(role), "")
            )
            expected_mxid = str(
                getattr(self.settings, "{}_camera_device_id".format(role), "")
            )
            camera_ready = bool(
                camera_ready
                and camera.get("role") == role
                and identity[1] == expected_backend
                and identity[2] == expected_source
                and (
                    expected_backend != "depthai"
                    or not expected_mxid
                    or identity[3] == expected_mxid
                )
                and camera.get("state") == "running"
                and camera.get("fresh") is True
                and sequence_valid
                and errors_valid
                and errors == 0
            )
            camera_identities.append(identity)
            camera_sequences.append((role, int(sequence) if sequence_valid else 0))
            camera_errors.append((role, int(errors) if errors_valid else -1))
        with self._motion_lock:
            stop_generation = self._motion_stop_generation
            authorization_generation = self._motion_authorization_generation
            motion_armed = self._motion_armed
            motion_live = self._motion_live
            motion_authorized = bool(
                self._motion_authorization_expires_at > float(self._monotonic())
            )
        with self._workspace_teach_lock:
            workspace_generation = self._workspace_teach_generation
            workspace_owner = self._workspace_teach_owner_active
            workspace_invalidating = self._workspace_teach_invalidation_pending.is_set()
        with self._safety_configuration_lock:
            safety_generation = self._safety_configuration_generation
            safety_state = self._safety_configuration_state
        with self._fatal_lock:
            fatal_generation = self._runtime_fatal_generation
            fatal_active = self._fatal_event.is_set()
        controller_ready = bool(
            xarm.get("connected") is True
            and xarm.get("healthy") is True
            and xarm.get("fresh") is True
            and xarm.get("moving") is False
            and xarm.get("error_code") == 0
            and xarm.get("warning_code") == 0
            and xarm.get("state") == 4
            and xarm.get("mode") == 0
            and xarm.get("axis_count") == 6
            and xarm.get("device_type") == _LITE6_DEVICE_TYPE
            and telemetry_sequence > 0
            and not motion_armed
            and not motion_live
            and not motion_authorized
        )
        return {
            "authorization_generation": authorization_generation,
            "camera_errors": tuple(camera_errors),
            "camera_identities": tuple(camera_identities),
            "camera_ready": camera_ready,
            "camera_sequences": tuple(camera_sequences),
            "controller_mode": xarm.get("mode"),
            "controller_ready": controller_ready,
            "controller_state": xarm.get("state"),
            "fatal_active": fatal_active,
            "owner_snapshot": self._ota_admission_owner_snapshot(),
            "runtime_fatal_generation": fatal_generation,
            "safety_configuration_generation": safety_generation,
            "safety_configuration_state": str(safety_state),
            "stop_generation": stop_generation,
            "telemetry_sequence": telemetry_sequence,
            "workspace_teach_generation": workspace_generation,
            "workspace_teach_invalidation_pending": workspace_invalidating,
            "workspace_teach_owner_active": workspace_owner,
            "xarm": {
                "axis_count": xarm.get("axis_count"),
                "connected": xarm.get("connected") is True,
                "device_type": xarm.get("device_type"),
                "error_code": xarm.get("error_code"),
                "fresh": xarm.get("fresh") is True,
                "healthy": xarm.get("healthy") is True,
                "moving": xarm.get("moving"),
                "warning_code": xarm.get("warning_code"),
            },
        }

    @staticmethod
    def _ota_admission_baseline_reason(snapshot: Mapping[str, Any]) -> str:
        if snapshot.get("fatal_active") is True:
            return "fatal_changed"
        if snapshot.get("controller_ready") is not True:
            return "controller_changed"
        if snapshot.get("camera_ready") is not True:
            return "camera_changed"
        if (
            snapshot.get("workspace_teach_owner_active") is True
            or snapshot.get("workspace_teach_invalidation_pending") is True
        ):
            return "workspace_teach_changed"
        if snapshot.get("safety_configuration_state") == "configuring":
            return "safety_changed"
        owners = dict(snapshot.get("owner_snapshot") or ())
        expected = {
            "capture_active": False,
            "capture_reserved": True,
            "hand_reserved": False,
            "ota_reserved": True,
            "petri_active": False,
            "petri_recovery": False,
            "petri_reserved": False,
            "restart_pending": False,
            "transition_reserved": True,
        }
        if any(owners.get(name) is not value for name, value in expected.items()):
            return "owner_changed"
        if owners.get("capture_state") in _CAPTURE_ACTIVE_STATES:
            return "owner_changed"
        if owners.get("hand_state") in {
            "starting",
            "recording",
            "running",
            "stopping",
        }:
            return "owner_changed"
        if owners.get("petri_state") in {"starting", "running", "stopping"}:
            return "owner_changed"
        if owners.get("recovery_state") in {"starting", "running", "stopping"}:
            return "owner_changed"
        return ""

    def _set_ota_admission_changed(self, reason: str, phase: str) -> None:
        safe_reason = (
            reason if reason in OTAAdmissionChanged._REASONS else "telemetry_changed"
        )
        now = float(self._monotonic())
        with self._ota_admission_lock:
            previous = dict(self._ota_admission_status)
            lease = self._ota_admission_lease
            age = max(
                0.0,
                now - lease.captured_at_monotonic_s if lease is not None else 0.0,
            )
            self._ota_admission_latched_reason = safe_reason
            self._ota_admission_status = {
                **previous,
                "status": "changed",
                "phase": (phase if phase in OTA_ADMISSION_REVALIDATION_PHASES else ""),
                "reason": safe_reason,
                "age_seconds": min(age, 86400.0),
                "motion_authority": "none",
            }

    def _capture_ota_admission_lease(self) -> bool:
        supported = getattr(
            self.ota_updater,
            "ota_admission_revalidation_phases",
            (),
        )
        if not set(OTA_ADMISSION_REVALIDATION_PHASES).issubset(set(supported)):
            self._set_ota_admission_changed("updater_unsupported", "before_network")
            self._record_ota_status(
                "error",
                message="Automatic OTA admission lease is unsupported",
                error_code="admission_changed",
            )
            return False
        try:
            snapshot = self._ota_admission_snapshot()
        except Exception:
            self._set_ota_admission_changed("telemetry_changed", "before_network")
            return False
        reason = self._ota_admission_baseline_reason(snapshot)
        maximum_age = float(
            getattr(self.settings, "ota_admission_lease_seconds", 120.0)
        )
        if not math.isfinite(maximum_age) or not 1.0 <= maximum_age <= 300.0:
            reason = "lease_expired"
        if reason:
            self._set_ota_admission_changed(reason, "before_network")
            return False
        with self._ota_admission_lock:
            generation = min(self._ota_admission_generation + 1, 1_000_000_000)
            captured_at = float(self._monotonic())
            evidence = {
                "authorization_generation": snapshot["authorization_generation"],
                "camera_identities": snapshot["camera_identities"],
                "camera_sequences": snapshot["camera_sequences"],
                "controller_mode": snapshot["controller_mode"],
                "controller_state": snapshot["controller_state"],
                "generation": generation,
                "owner_snapshot": snapshot["owner_snapshot"],
                "runtime_fatal_generation": snapshot["runtime_fatal_generation"],
                "safety_configuration_generation": snapshot[
                    "safety_configuration_generation"
                ],
                "stop_generation": snapshot["stop_generation"],
                "telemetry_sequence": snapshot["telemetry_sequence"],
                "workspace_teach_generation": snapshot["workspace_teach_generation"],
            }
            digest = hashlib.sha256(
                json.dumps(
                    evidence,
                    allow_nan=False,
                    separators=(",", ":"),
                    sort_keys=True,
                ).encode("utf-8")
            ).hexdigest()
            lease = _OTAAdmissionLease(
                generation=generation,
                captured_at_monotonic_s=captured_at,
                maximum_age_seconds=maximum_age,
                stop_generation=int(snapshot["stop_generation"]),
                authorization_generation=int(snapshot["authorization_generation"]),
                telemetry_sequence=int(snapshot["telemetry_sequence"]),
                controller_state=int(snapshot["controller_state"]),
                controller_mode=int(snapshot["controller_mode"]),
                camera_identities=tuple(snapshot["camera_identities"]),
                camera_sequences=tuple(snapshot["camera_sequences"]),
                owner_snapshot=tuple(snapshot["owner_snapshot"]),
                workspace_teach_generation=int(snapshot["workspace_teach_generation"]),
                workspace_teach_owner_active=bool(
                    snapshot["workspace_teach_owner_active"]
                ),
                workspace_teach_invalidation_pending=bool(
                    snapshot["workspace_teach_invalidation_pending"]
                ),
                safety_configuration_generation=int(
                    snapshot["safety_configuration_generation"]
                ),
                safety_configuration_state=str(snapshot["safety_configuration_state"]),
                runtime_fatal_generation=int(snapshot["runtime_fatal_generation"]),
                evidence_sha256=digest,
            )
            self._ota_admission_generation = generation
            self._ota_admission_lease = lease
            self._ota_admission_last_telemetry_sequence = lease.telemetry_sequence
            self._ota_admission_last_camera_sequences = dict(lease.camera_sequences)
            self._ota_admission_latched_reason = ""
            self._ota_admission_status = {
                "schema_version": 1,
                "status": "active",
                "phase": "admitted",
                "reason": "",
                "generation": generation,
                "validation_count": 0,
                "age_seconds": 0.0,
                "maximum_age_seconds": maximum_age,
                "evidence_sha256": digest,
                "motion_authority": "none",
            }
        return True

    def _revalidate_ota_admission_lease(self, phase: str) -> bool:
        if phase not in OTA_ADMISSION_REVALIDATION_PHASES:
            raise OTAAdmissionChanged("updater_unsupported")
        with self._ota_admission_lock:
            lease = self._ota_admission_lease
            latched_reason = self._ota_admission_latched_reason
            last_telemetry = self._ota_admission_last_telemetry_sequence
            last_cameras = dict(self._ota_admission_last_camera_sequences)
        if lease is None:
            self._set_ota_admission_changed("owner_changed", phase)
            raise OTAAdmissionChanged("owner_changed")
        if latched_reason:
            self._set_ota_admission_changed(latched_reason, phase)
            raise OTAAdmissionChanged(latched_reason)
        age = float(self._monotonic()) - lease.captured_at_monotonic_s
        if not math.isfinite(age) or age < 0.0 or age > lease.maximum_age_seconds:
            self._set_ota_admission_changed("lease_expired", phase)
            raise OTAAdmissionChanged("lease_expired")
        if not self._operation_transition_lock.acquire(blocking=False):
            self._set_ota_admission_changed("owner_changed", phase)
            raise OTAAdmissionChanged("owner_changed")
        try:
            snapshot = self._ota_admission_snapshot()
        except Exception as exc:
            self._set_ota_admission_changed("telemetry_changed", phase)
            raise OTAAdmissionChanged("telemetry_changed") from exc
        finally:
            self._operation_transition_lock.release()

        reason = self._ota_admission_baseline_reason(snapshot)
        if snapshot.get("runtime_fatal_generation") != lease.runtime_fatal_generation:
            reason = "fatal_changed"
        elif (
            snapshot.get("stop_generation") != lease.stop_generation
            or snapshot.get("authorization_generation")
            != lease.authorization_generation
            or snapshot.get("controller_state") != lease.controller_state
            or snapshot.get("controller_mode") != lease.controller_mode
        ):
            reason = "controller_changed"
        elif int(snapshot.get("telemetry_sequence") or 0) < last_telemetry:
            reason = "telemetry_changed"
        elif tuple(snapshot.get("camera_identities") or ()) != lease.camera_identities:
            reason = "camera_changed"
        else:
            current_cameras = dict(snapshot.get("camera_sequences") or ())
            if any(
                int(current_cameras.get(role, 0)) < sequence
                for role, sequence in last_cameras.items()
            ) or any(
                errors != 0
                for _role, errors in tuple(snapshot.get("camera_errors") or ())
            ):
                reason = "camera_changed"
        if (
            snapshot.get("workspace_teach_generation")
            != lease.workspace_teach_generation
            or snapshot.get("workspace_teach_owner_active")
            is not lease.workspace_teach_owner_active
            or snapshot.get("workspace_teach_invalidation_pending")
            is not lease.workspace_teach_invalidation_pending
        ):
            reason = "workspace_teach_changed"
        elif (
            snapshot.get("safety_configuration_generation")
            != lease.safety_configuration_generation
            or snapshot.get("safety_configuration_state")
            != lease.safety_configuration_state
        ):
            reason = "safety_changed"
        elif tuple(snapshot.get("owner_snapshot") or ()) != lease.owner_snapshot:
            reason = "owner_changed"
        if reason:
            self._set_ota_admission_changed(reason, phase)
            raise OTAAdmissionChanged(reason)

        current_telemetry = int(snapshot["telemetry_sequence"])
        current_cameras = dict(snapshot["camera_sequences"])
        lease_replaced = False
        with self._ota_admission_lock:
            if self._ota_admission_lease is not lease:
                lease_replaced = True
            else:
                previous = dict(self._ota_admission_status)
                validation_count = min(
                    int(previous.get("validation_count") or 0) + 1,
                    1_000_000_000,
                )
                self._ota_admission_last_telemetry_sequence = current_telemetry
                self._ota_admission_last_camera_sequences = current_cameras
                self._ota_admission_status = {
                    **previous,
                    "status": "active",
                    "phase": phase,
                    "reason": "",
                    "validation_count": validation_count,
                    "age_seconds": min(max(age, 0.0), 86400.0),
                    "motion_authority": "none",
                }
        if lease_replaced:
            self._set_ota_admission_changed("owner_changed", phase)
            raise OTAAdmissionChanged("owner_changed")
        return True

    def _ota_environment_ready(
        self,
        *,
        allow_reserved: bool = False,
        allow_transition: bool = False,
    ) -> bool:
        """Return whether no physical/configuration owner can overlap OTA."""

        ota_auto_apply = self._evaluate_ota_commissioning().permitted
        if bool(getattr(self.settings, "immutable_release", False)) and not isinstance(
            self.ota_updater, PrivilegedOTAClient
        ):
            return False
        if self._restart_pending or self._fatal_event.is_set():
            return False
        if (
            (self._operation_transition_lock.locked() and not allow_transition)
            or (self._capture_operation_lock.locked() and not allow_reserved)
            or (self._ota_lock.locked() and not allow_reserved)
            or self._petri_run_lock.locked()
            or self._petri_durable_owner_blocks_physical_operation()
            or self._workspace_teach_blocks_physical_operation()
        ):
            return False
        if self._ota_operator_challenge_active():
            return False
        if self._safety_configuration_state == "configuring":
            return False
        with self._operations_lock:
            if self._petri_status.get("state") in {"starting", "running", "stopping"}:
                return False
            if self._recovery_status.get("state") in {
                "starting",
                "running",
                "stopping",
            }:
                return False
        with self._motion_lock:
            if (
                self._motion_armed
                or self._motion_live
                or bool(self._motion_fault_reason)
            ):
                return False
        if ota_auto_apply:
            if not (
                self.settings.cameras_enabled
                and self.camera_rig is not None
                and self.settings.xarm_metrics_enabled
                and self.settings.xarm_model == "lite6"
            ):
                return False
            camera_health = self._camera_health_metrics()
            if set(camera_health) != {"tool", "workspace"}:
                return False
            if any(
                camera_health[role].get("state") != "running"
                or camera_health[role].get("fresh") is not True
                or camera_health[role].get("consecutive_errors") != 0
                or not isinstance(camera_health[role].get("sequence"), int)
                or camera_health[role].get("sequence") <= 0
                or not isinstance(camera_health[role].get("frames_captured"), int)
                or camera_health[role].get("frames_captured") <= 0
                for role in ("tool", "workspace")
            ):
                return False
        if self.settings.xarm_metrics_enabled:
            xarm = self.xarm_status()
            if not (
                xarm.get("connected") is True
                and xarm.get("healthy") is True
                and xarm.get("fresh") is True
                and xarm.get("moving") is False
                and xarm.get("error_code") == 0
                and xarm.get("warning_code") == 0
                and xarm.get("state") == 4
                and (not ota_auto_apply or xarm.get("mode") == 0)
                and (
                    self.settings.xarm_model != "lite6"
                    or (xarm.get("axis_count") == 6 and xarm.get("device_type") == 9)
                )
            ):
                return False
        return True

    def _request_ota_restart(self) -> None:
        """Irreversibly close action gates before leaving a swapped tree."""

        self._restart_pending = True
        self._invalidate_motion_search_confirmation()
        try:
            self.emergency_stop_motion()
        finally:
            callback = self._restart_callback
            if callback is not None:
                callback()

    def _ota_health_commit(self) -> None:
        startup_update_id = self._ota_startup_update_id
        if startup_update_id is None:
            return
        if self._stop_event.wait(self.settings.ota_boot_health_seconds):
            return
        try:
            health = self.ota_boot_health_status()
        except Exception:
            LOGGER.exception(
                "Pending OTA release remains uncommitted because runtime "
                "health could not be evaluated"
            )
            return
        if health.get("ready") is not True:
            LOGGER.error(
                "Pending OTA release remains uncommitted because boot health "
                "is degraded: %s",
                ", ".join(str(item) for item in health.get("problems", ()))
                or "unknown",
            )
            return
        health_generation = health.get("generation")
        if (
            isinstance(health_generation, bool)
            or not isinstance(health_generation, int)
            or health_generation < 1
        ):
            LOGGER.error("Pending OTA boot-health generation is invalid")
            return
        if not self._reserve_ota_owner():
            LOGGER.error(
                "Pending OTA release remains uncommitted because a physical "
                "owner became active"
            )
            return
        try:
            final_health = self.ota_boot_health_status(
                _allow_reserved_ota_owner=True,
            )
            if (
                final_health.get("ready") is not True
                or final_health.get("generation") != health_generation
                or final_health.get("update_id_sha256")
                != hashlib.sha256(startup_update_id.encode("ascii")).hexdigest()
            ):
                LOGGER.error(
                    "Pending OTA boot-health decision changed before commit: %s",
                    ", ".join(str(item) for item in final_health.get("problems", ()))
                    or "generation_changed",
                )
                return
            committed = self.ota_updater.mark_boot_success(  # type: ignore[union-attr]
                expected_update_id=startup_update_id,
                health_generation=health_generation,
            )
        except Exception:
            LOGGER.exception("Could not commit pending OTA release")
            return
        finally:
            self._release_ota_owner()
        if not committed:
            return
        with self._lock:
            if self._ota_startup_update_id == startup_update_id:
                self._ota_startup_update_id = None
        committed_health = dict(final_health)
        committed_health.update(
            {
                "status": "committed",
                "pending": False,
                "ready": True,
                "problems": [],
            }
        )
        with self._ota_boot_health_lock:
            self._ota_boot_health_last = copy.deepcopy(committed_health)
        LOGGER.info(
            "OTA_BOOT_HEALTH_COMMITTED version=%s source_revision=%s "
            "update_id_sha256=%s generation=%d",
            committed_health.get("target_version") or self.settings.current_version,
            committed_health.get("target_source_revision") or "unavailable",
            committed_health["update_id_sha256"],
            health_generation,
        )
        self._ota_health_report_event.set()
        if self.datahub is not None:
            try:
                self.datahub.enqueue_metrics(
                    {
                        "ota_update_status": "healthy",
                        "software_version": self.settings.current_version,
                    },
                    attributes={"source": "ota-health-window"},
                )
            except Exception:
                LOGGER.warning(
                    "Could not enqueue the optional OTA health metric",
                    exc_info=True,
                )

    def _ota_health_report_loop(self) -> None:
        """Keep retrying a durable report without blocking any OTA control path."""

        updater = self.ota_updater
        pending = getattr(updater, "health_report_pending", None)
        report = getattr(updater, "report_boot_success", None)
        if not callable(pending) or not callable(report):
            raise RuntimeError("Secure OTA updater lacks durable health reporting")
        delays = tuple(_OTA_HEALTH_REPORT_RETRY_DELAYS_SECONDS)
        if not delays:
            raise RuntimeError("OTA health report retry schedule is empty")
        failures = 0
        idle_seconds = 0.25
        while not self._stop_event.is_set():
            try:
                report_pending = pending()
                if not isinstance(report_pending, bool):
                    raise RuntimeError("Secure OTA report state is invalid")
            except Exception:
                failures += 1
                LOGGER.warning(
                    "Could not read durable OTA health report state; retrying",
                    exc_info=True,
                )
                delay = delays[min(failures - 1, len(delays) - 1)]
                if self._stop_event.wait(max(0.0, min(float(delay), 300.0))):
                    return
                continue
            if not report_pending:
                failures = 0
                self._ota_health_report_event.wait(idle_seconds)
                self._ota_health_report_event.clear()
                if self._stop_event.is_set():
                    return
                continue
            delay = delays[min(failures, len(delays) - 1)]
            if self._stop_event.wait(max(0.0, min(float(delay), 300.0))):
                return
            try:
                reported = report()
                if not isinstance(reported, bool):
                    raise RuntimeError("OTA reporter returned an invalid result")
            except Exception:
                failures += 1
                LOGGER.warning(
                    "OTA health report attempt %s failed; durable retry continues",
                    failures,
                    exc_info=True,
                )
                continue
            failures = 0
            self._ota_health_report_event.wait(idle_seconds)
            self._ota_health_report_event.clear()
            if self._stop_event.is_set():
                return

    def _report_ota_health_with_retries(
        self,
        *,
        retry_delays: Optional[Sequence[float]] = None,
    ) -> bool:
        """Bound retries for the durable, idempotent Device Manager report."""

        report = getattr(self.ota_updater, "report_boot_success", None)
        if not callable(report):
            LOGGER.error("Secure OTA updater cannot report boot health")
            return False
        delays = tuple(
            _OTA_HEALTH_REPORT_RETRY_DELAYS_SECONDS
            if retry_delays is None
            else retry_delays
        )
        if not delays:
            return False
        for attempt, delay in enumerate(delays, start=1):
            bounded_delay = max(0.0, min(float(delay), 300.0))
            if bounded_delay and self._stop_event.wait(bounded_delay):
                return False
            try:
                reported = report()
                if isinstance(reported, bool):
                    # False means another idempotent reporter already cleared
                    # the pending marker; either result is terminal here.
                    return True
                raise RuntimeError("OTA reporter returned an invalid result")
            except Exception:
                if attempt == len(delays):
                    LOGGER.error(
                        "OTA health report remains durably pending after %s attempts",
                        attempt,
                        exc_info=True,
                    )
                else:
                    LOGGER.warning(
                        "OTA health report attempt %s failed; retry remains pending",
                        attempt,
                        exc_info=True,
                    )
        return False

    def _motion_stop_token(self) -> int:
        with self._motion_lock:
            return self._motion_stop_generation

    def _motion_stopped_since(self, generation: int) -> bool:
        with self._motion_lock:
            return self._motion_stop_generation != int(generation)

    def _motion_authorization_loop(self) -> None:
        """Independently revoke expired motion even if UI/valve workers stall."""

        while not self._stop_event.wait(_MOTION_AUTHORIZATION_WATCHDOG_SECONDS):
            self._expire_motion_authorization_if_needed()

    def motion_authorization_generation(self) -> Optional[int]:
        """Return the currently armed generation, or no usable permit."""

        self._expire_motion_authorization_if_needed()
        with self._motion_lock:
            if not (self._motion_armed and self._motion_live):
                return None
            return self._motion_authorization_generation

    def motion_authorization_is_valid(self, generation: Any) -> bool:
        """Validate one exact, unexpired generation for in-flight commands."""

        if isinstance(generation, bool) or not isinstance(generation, int):
            return False
        self._expire_motion_authorization_if_needed()
        with self._motion_lock:
            return (
                generation == self._motion_authorization_generation
                and self._motion_armed
                and self._motion_live
                and self._motion_authorization_expires_at > float(self._monotonic())
            )

    def _expire_motion_authorization_if_needed(self) -> bool:
        """Atomically revoke and physically halt one expired live permit."""

        now = float(self._monotonic())
        with self._motion_lock:
            if not (
                self._motion_armed
                and self._motion_live
                and self._motion_authorization_expires_at > 0.0
                and now >= self._motion_authorization_expires_at
            ):
                return False
            self._motion_stop_generation += 1
            self._motion_authorization_generation += 1
            self._motion_authorization_expires_at = 0.0
            self._motion_armed = False
            self._motion_live = False
        self._motion_abort_event.set()
        if self.xarm_motion_adapter is not None:
            try:
                self.xarm_motion_adapter.halt()
            except Exception as exc:
                with self._motion_lock:
                    self._motion_fault_reason = "halt: {}".format(type(exc).__name__)
                self._enqueue_motion_metric("authorization_halt_failed")
                return True
        self._enqueue_motion_metric("authorization_expired_and_halted")
        return True


def build_workcell_services(
    settings: IntegrationSettings,
    *,
    datahub: Optional[DataHubPublisher] = None,
    camera_rig: Any = None,
    metric_source: Optional[Callable[[], Mapping[str, Any]]] = None,
    ota_updater: Optional[SecureOTAUpdater | PrivilegedOTAClient] = None,
    offload_client: Optional[ShortcutJobClient] = None,
    tenant_auth_client: Any = None,
    readiness_client: Optional[DeviceReadinessClient] = None,
    mjpeg_server: Any = None,
    jpeg_encoder: Optional[Callable[[Any], bytes]] = None,
    tool_pose_buffer: Any = None,
    tool_workspace_mapper: Any = None,
    local_valve_predictor_factory: Any = None,
    valve_controller: Any = None,
    xarm_motion_adapter: Optional[XArmMotionAdapter] = None,
    sampling_tool_adapter: Any = None,
    motion_permit_authority: Any = None,
    motion_binding_provider: Optional[Callable[[], MotionBindings]] = None,
    recovery_controller: Any = None,
    petri_process_controller: Any = None,
    petri_registry: Any = None,
    petri_artifact_root: Optional[Path] = None,
    capture_run_controller: Any = None,
    capture_dataset_exporter: Any = None,
    hand_training_controller: Any = None,
    safety_configurator: Any = None,
    site_safety_gate: Any = None,
    digital_twin_provider: Any = None,
    trajectory_preflight: Any = None,
    workspace_teach_recorder: Any = None,
    workspace_teach_store: Any = None,
    workspace_boundary_validator: Any = None,
) -> WorkcellServices:
    """Build real optional hardware adapters, while allowing injected fakes."""

    hand_training_runtime: dict[str, WorkcellServices] = {}

    if (
        settings.dual_depth_preflight_enabled
        and trajectory_preflight is None
        and camera_rig is not None
    ):
        raise RuntimeError(
            "Injected camera rigs require an injected dual-depth preflight"
        )

    if digital_twin_provider is None:
        try:
            from main.digital_twin import DigitalTwinSnapshotProvider
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from digital_twin import (  # type: ignore[no-redef]
                DigitalTwinSnapshotProvider,
            )
        digital_twin_provider = DigitalTwinSnapshotProvider(
            required_clearance_mm=settings.dual_depth_required_clearance_mm,
            geometry_profile_sha256=settings.dual_depth_geometry_profile_sha256,
        )

    if settings.workspace_teach_enabled:
        provider_model = getattr(
            getattr(digital_twin_provider, "kinematics", None),
            "model_sha256",
            "",
        )
        if not secrets.compare_digest(
            str(provider_model),
            settings.workspace_teach_robot_binding_sha256,
        ):
            raise RuntimeError(
                "Workspace-teach robot binding does not match the Lite6 model"
            )
        try:
            from main.workspace_teach import (
                WorkspaceTeachProposalStore,
                WorkspaceTeachRecorder,
            )
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from workspace_teach import (  # type: ignore[no-redef]
                WorkspaceTeachProposalStore,
                WorkspaceTeachRecorder,
            )
        if workspace_teach_recorder is None:
            workspace_teach_recorder = WorkspaceTeachRecorder(
                hard_lower_xyz_mm=(settings.workspace_teach_hard_lower_xyz_mm),
                hard_upper_xyz_mm=(settings.workspace_teach_hard_upper_xyz_mm),
                inset_xyz_mm=settings.workspace_teach_inset_xyz_mm,
                minimum_span_xyz_mm=(settings.workspace_teach_minimum_span_xyz_mm),
                robot_binding_sha256=(settings.workspace_teach_robot_binding_sha256),
                commissioning_permit_sha256=(
                    settings.workspace_teach_commissioning_permit_sha256
                ),
                monotonic=time.monotonic,
            )
        if workspace_teach_store is None:
            workspace_teach_store = WorkspaceTeachProposalStore(
                Path(settings.workspace_teach_proposal_root)
            )
        verify_store_root = getattr(workspace_teach_store, "_verified_root", None)
        if not callable(verify_store_root):
            raise RuntimeError("Workspace-teach proposal store is incomplete")
        verify_store_root()
    elif workspace_teach_recorder is not None or workspace_teach_store is not None:
        raise RuntimeError(
            "Workspace teach injection requires explicit trusted configuration"
        )

    local_valve_confirmation_detector = None
    if settings.dynamic_valve_local_model_enabled:
        try:
            from main.vision.reviewed_valve_model import (
                ReviewedLocalValveDetector,
                build_opencv_dnn_valve_predictor,
                load_reviewed_valve_model,
            )
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from vision.reviewed_valve_model import (  # type: ignore[no-redef]
                ReviewedLocalValveDetector,
                build_opencv_dnn_valve_predictor,
                load_reviewed_valve_model,
            )
        artifact = load_reviewed_valve_model(
            model_path=settings.dynamic_valve_local_model_path,
            expected_model_sha256=(settings.dynamic_valve_local_model_sha256),
            manifest_path=(settings.dynamic_valve_local_model_manifest_path),
            expected_manifest_sha256=(
                settings.dynamic_valve_local_model_manifest_sha256
            ),
            tool_camera_source_id=settings.tool_camera_source_id,
            camera_width=settings.camera_width,
            camera_height=settings.camera_height,
            eye_in_hand_calibration_sha256=(settings.eye_in_hand_calibration_sha256),
            confidence_threshold=settings.dynamic_valve_min_confidence,
        )
        local_valve_confirmation_detector = ReviewedLocalValveDetector(
            artifact,
            local_valve_predictor_factory or build_opencv_dnn_valve_predictor,
        )

    if tenant_auth_client is None:
        try:
            from main.integrations.tenant_auth import TenantMobileAuthClient
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from integrations.tenant_auth import (  # type: ignore[no-redef]
                TenantMobileAuthClient,
            )
        tenant_auth_client = TenantMobileAuthClient(
            state_dir=Path(settings.state_dir) / "tenant-auth",
            allow_insecure_localhost=settings.deployment_mode == "development",
            device_registration=(
                {
                    "uid_device": settings.device_uid,
                    "manufacturer_id": settings.device_uid,
                    "token": settings.device_secret,
                    "name": "LabCobot {}".format(settings.device_uid),
                    "device_type": "LabCobot",
                    "location": "Workcell",
                    "model": settings.xarm_model,
                }
                if settings.device_uid and settings.device_secret
                else None
            ),
        )

    datahub = datahub if datahub is not None else settings.build_datahub_publisher()
    ota_updater = (
        ota_updater if ota_updater is not None else settings.build_ota_updater()
    )
    offload_client = (
        offload_client
        if offload_client is not None
        else settings.build_offload_client(
            bearer_token_provider=tenant_auth_client.access_token_for_url,
            endpoint_url_provider=tenant_auth_client.endpoint_url,
        )
    )
    readiness_client = (
        readiness_client
        if readiness_client is not None
        else settings.build_readiness_client()
    )
    configured_petri_registry_path = getattr(settings, "petri_registry_path", "")
    if petri_registry is None and configured_petri_registry_path:
        try:
            from main.petri_workflow import PetriRegistry
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from petri_workflow import PetriRegistry  # type: ignore[no-redef]
        petri_registry = PetriRegistry(configured_petri_registry_path)
    configured_petri_artifact_root = getattr(settings, "petri_artifact_root", "")
    if petri_artifact_root is None and configured_petri_artifact_root:
        petri_artifact_root = Path(configured_petri_artifact_root)

    if settings.xarm_metrics_enabled and metric_source is None:
        try:
            metric_source = open_xarm_metric_source(settings.xarm_ip)
        except RuntimeError as exc:
            raise RuntimeError(
                "LABCOBOT_XARM_METRICS_ENABLED requires the xArm SDK"
            ) from exc
    if settings.safety_profile_path and safety_configurator is None:
        if not isinstance(metric_source, XArmMetricSource):
            raise RuntimeError(
                "Lite6 safety configuration requires the concrete xArm source"
            )
        try:
            from main.safety_boundary import (
                Lite6SafetyBoundaryConfigurator,
                load_lite6_safety_profile,
            )
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from safety_boundary import (  # type: ignore[no-redef]
                Lite6SafetyBoundaryConfigurator,
                load_lite6_safety_profile,
            )
        safety_configurator = Lite6SafetyBoundaryConfigurator(
            metric_source.arm,
            load_lite6_safety_profile(
                settings.safety_profile_path,
                expected_sha256=settings.safety_profile_sha256,
            ),
            metric_source._lock,
        )
        if (
            safety_configurator.profile.eye_in_hand_calibration_sha256
            != settings.eye_in_hand_calibration_sha256
            or safety_configurator.profile.motion_primitive_sha256
            != settings.dynamic_valve_primitive_sha256
        ):
            raise RuntimeError(
                "Lite6 safety profile artifact bindings do not match runtime"
            )
        boundary = safety_configurator.profile.tcp_boundary_mm
        lower = settings.eye_in_hand_workspace_lower_xyz_mm
        upper = settings.eye_in_hand_workspace_upper_xyz_mm
        if (
            len(lower) != 3
            or len(upper) != 3
            or any(
                boundary[index * 2 + 1] < lower[index]
                or boundary[index * 2] > upper[index]
                for index in range(3)
            )
        ):
            raise RuntimeError(
                "Lite6 safety profile boundary exceeds commissioned workspace"
            )
    capture_components_requested = (
        settings.capture_run_enabled and capture_run_controller is None
    )
    if (
        settings.xarm_motion_enabled or capture_components_requested
    ) and xarm_motion_adapter is None:
        if not isinstance(metric_source, XArmMetricSource):
            raise RuntimeError(
                "Live xArm motion requires XArmMetricSource or a complete "
                "injected capture runtime"
            )
        xarm_motion_adapter = XArmMotionAdapter(
            metric_source,
            workspace_lower_xyz_mm=(
                settings.eye_in_hand_workspace_lower_xyz_mm
                if settings.xarm_motion_enabled
                else settings.capture_workspace_lower_xyz_mm
            ),
            workspace_upper_xyz_mm=(
                settings.eye_in_hand_workspace_upper_xyz_mm
                if settings.xarm_motion_enabled
                else settings.capture_workspace_upper_xyz_mm
            ),
            pinned_safety_required=settings.xarm_motion_enabled,
        )

    if settings.sampling_tool_enabled:
        if sampling_tool_adapter is None:
            if (
                not isinstance(xarm_motion_adapter, XArmMotionAdapter)
                or safety_configurator is None
            ):
                raise RuntimeError(
                    "Sampling tool requires the concrete reviewed Lite6 runtime"
                )
            try:
                from main.integrations.sampling_tool import (
                    SamplingToolAdapter,
                    load_sampling_tool_profile,
                )
            except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                from integrations.sampling_tool import (  # type: ignore[no-redef]
                    SamplingToolAdapter,
                    load_sampling_tool_profile,
                )
            sampling_profile = load_sampling_tool_profile(
                settings.sampling_tool_profile_path,
                expected_sha256=settings.sampling_tool_profile_sha256,
            )
            safety_profile = getattr(safety_configurator, "profile", None)
            if safety_profile is None or not (
                secrets.compare_digest(
                    sampling_profile.safety_profile_sha256,
                    safety_profile.profile_sha256,
                )
                and all(
                    math.isclose(left, right, rel_tol=0.0, abs_tol=1e-4)
                    for left, right in zip(
                        sampling_profile.tcp_offset_xyz_mm_rpy_degrees,
                        safety_profile.expected_tcp_offset_xyz_mm_rpy_degrees,
                    )
                )
                and math.isclose(
                    sampling_profile.tcp_load_kg,
                    safety_profile.expected_tcp_load_kg,
                    rel_tol=0.0,
                    abs_tol=1e-4,
                )
                and all(
                    math.isclose(left, right, rel_tol=0.0, abs_tol=1e-4)
                    for left, right in zip(
                        sampling_profile.tcp_center_of_gravity_mm,
                        safety_profile.expected_tcp_center_of_gravity_mm,
                    )
                )
            ):
                raise RuntimeError(
                    "Sampling-tool load/TCP contract does not match the "
                    "pinned Lite6 safety profile"
                )
            sampling_tool_adapter = SamplingToolAdapter(
                xarm_motion_adapter,
                sampling_profile,
                safety_profile_sha256=safety_profile.profile_sha256,
            )
    elif sampling_tool_adapter is not None:
        raise RuntimeError(
            "Sampling-tool injection requires explicit trusted configuration"
        )

    depth_buffer = None
    calibration = None
    tool_clearance_depth_buffer = None
    workspace_clearance_depth_buffer = None
    workspace_depth_calibration = None
    clearance_geometry_profile = None
    if settings.eye_in_hand_enabled and tool_workspace_mapper is None:
        try:
            from main.vision.eye_in_hand import (
                AlignedDepthFrame,
                CalibrationNotReady,
                EyeInHandCalibrationStore,
                SynchronizedDepthBuffer,
                TimedToolPoseBuffer,
            )
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from vision.eye_in_hand import (  # type: ignore[no-redef]
                AlignedDepthFrame,
                CalibrationNotReady,
                EyeInHandCalibrationStore,
                SynchronizedDepthBuffer,
                TimedToolPoseBuffer,
            )

        calibration = EyeInHandCalibrationStore().load(
            settings.eye_in_hand_calibration_path,
            expected_sha256=(
                settings.eye_in_hand_calibration_sha256
                if (
                    settings.xarm_motion_enabled
                    or settings.dual_depth_preflight_enabled
                )
                else None
            ),
        )
        if (
            calibration.intrinsics.width != settings.camera_width
            or calibration.intrinsics.height != settings.camera_height
        ):
            raise CalibrationNotReady(
                "Configured tool-camera resolution does not match calibration"
            )
        if calibration.camera_source_id != settings.tool_camera_source_id:
            raise CalibrationNotReady(
                "Configured tool-camera source does not match calibration"
            )
        depth_buffer = SynchronizedDepthBuffer(
            image_width=settings.camera_width,
            image_height=settings.camera_height,
        )
        if tool_pose_buffer is None:
            tool_pose_buffer = TimedToolPoseBuffer(maximum_poses=512)

    if settings.dual_depth_preflight_enabled and trajectory_preflight is None:
        if calibration is None or tool_pose_buffer is None:
            raise RuntimeError(
                "Dual-depth preflight requires the pinned eye-in-hand runtime"
            )
        try:
            from main.vision.cameras import CameraRole
            from main.vision.clearance import (
                ConservativeGeometryProfileStore,
                DepthPacketBuffer,
                StaticDepthCalibrationStore,
            )
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from vision.cameras import CameraRole  # type: ignore[no-redef]
            from vision.clearance import (  # type: ignore[no-redef]
                ConservativeGeometryProfileStore,
                DepthPacketBuffer,
                StaticDepthCalibrationStore,
            )
        workspace_depth_calibration = StaticDepthCalibrationStore().load(
            settings.workspace_depth_calibration_path,
            expected_sha256=settings.workspace_depth_calibration_sha256,
        )
        clearance_geometry_profile = ConservativeGeometryProfileStore().load(
            settings.dual_depth_geometry_profile_path,
            expected_sha256=settings.dual_depth_geometry_profile_sha256,
        )
        if (
            workspace_depth_calibration.intrinsics.width != settings.camera_width
            or workspace_depth_calibration.intrinsics.height != settings.camera_height
        ):
            raise RuntimeError(
                "Workspace depth calibration resolution does not match runtime"
            )
        if (
            workspace_depth_calibration.camera_source_id
            != settings.workspace_camera_source_id
        ):
            raise RuntimeError(
                "Workspace depth calibration source does not match runtime"
            )
        tool_clearance_depth_buffer = DepthPacketBuffer(
            source_id=settings.tool_camera_source_id,
            role=CameraRole.TOOL,
            image_width=settings.camera_width,
            image_height=settings.camera_height,
        )
        workspace_clearance_depth_buffer = DepthPacketBuffer(
            source_id=settings.workspace_camera_source_id,
            role=CameraRole.WORKSPACE,
            image_width=settings.camera_width,
            image_height=settings.camera_height,
        )

    if settings.cameras_enabled and camera_rig is None:
        try:
            from main.vision.cameras import (
                CameraRole,
                CameraStream,
                DepthAICameraSource,
                DualCameraRig,
                OpenCVCameraSource,
            )
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from vision.cameras import (  # type: ignore[no-redef]
                CameraRole,
                CameraStream,
                DepthAICameraSource,
                DualCameraRig,
                OpenCVCameraSource,
            )

        if settings.tool_camera_backend == "depthai":
            depth_callback = None
            if depth_buffer is not None:

                def on_aligned_depth(timestamp_s: float, depth_mm: Any) -> None:
                    depth_buffer.add(
                        AlignedDepthFrame(
                            timestamp_s=timestamp_s,
                            depth_mm=depth_mm,
                        )
                    )

                depth_callback = on_aligned_depth

            tool_source = DepthAICameraSource(
                source_id=settings.tool_camera_source_id,
                width=settings.camera_width,
                height=settings.camera_height,
                fps=settings.camera_fps,
                device_id=settings.tool_camera_device_id or None,
                enable_aligned_depth=(
                    depth_buffer is not None or tool_clearance_depth_buffer is not None
                ),
                aligned_depth_callback=depth_callback,
                aligned_depth_packet_callback=(
                    tool_clearance_depth_buffer.add
                    if tool_clearance_depth_buffer is not None
                    else None
                ),
            )
        else:
            tool_source = OpenCVCameraSource(
                parse_camera_source(settings.tool_camera_source),
                source_id=settings.tool_camera_source_id,
                role=CameraRole.TOOL,
                width=settings.camera_width,
                height=settings.camera_height,
                fps=settings.camera_fps,
            )
        if settings.workspace_camera_backend == "depthai":
            workspace_source = DepthAICameraSource(
                source_id=settings.workspace_camera_source_id,
                role=CameraRole.WORKSPACE,
                width=settings.camera_width,
                height=settings.camera_height,
                fps=settings.camera_fps,
                device_id=settings.workspace_camera_device_id or None,
                enable_aligned_depth=(workspace_clearance_depth_buffer is not None),
                aligned_depth_packet_callback=(
                    workspace_clearance_depth_buffer.add
                    if workspace_clearance_depth_buffer is not None
                    else None
                ),
            )
        else:
            workspace_source = OpenCVCameraSource(
                parse_camera_source(settings.workspace_camera_source),
                source_id=settings.workspace_camera_source_id,
                role=CameraRole.WORKSPACE,
                width=settings.camera_width,
                height=settings.camera_height,
                fps=settings.camera_fps,
            )
        camera_rig = DualCameraRig(
            [CameraStream(tool_source), CameraStream(workspace_source)]
        )

    if settings.eye_in_hand_enabled and tool_workspace_mapper is None:
        read_pose = getattr(metric_source, "read_timed_tool_pose", None)
        if not callable(read_pose):
            raise RuntimeError("Eye-in-hand mapping requires an xArm timed-pose source")
        try:
            from main.vision.eye_in_hand import EyeInHandWorkspaceMapper
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from vision.eye_in_hand import (  # type: ignore[no-redef]
                EyeInHandWorkspaceMapper,
            )
        tool_workspace_mapper = EyeInHandWorkspaceMapper(
            calibration,
            runtime_camera_source_id=settings.tool_camera_source_id,
            tool_pose_provider=tool_pose_buffer.resolve,
            depth_provider=depth_buffer.resolve,
            workspace_lower_xyz_mm=(settings.eye_in_hand_workspace_lower_xyz_mm),
            workspace_upper_xyz_mm=(settings.eye_in_hand_workspace_upper_xyz_mm),
        )

    if settings.dual_depth_preflight_enabled and trajectory_preflight is None:
        if (
            camera_rig is None
            or tool_clearance_depth_buffer is None
            or workspace_clearance_depth_buffer is None
            or workspace_depth_calibration is None
            or clearance_geometry_profile is None
            or calibration is None
            or tool_pose_buffer is None
        ):
            raise RuntimeError("Dual-depth preflight assembly is incomplete")
        try:
            from main.vision.clearance import DualDepthClearancePreflight
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from vision.clearance import (  # type: ignore[no-redef]
                DualDepthClearancePreflight,
            )
        evidence_sink = getattr(
            digital_twin_provider,
            "record_clearance_evidence",
            None,
        )
        if not callable(evidence_sink):
            raise RuntimeError(
                "Dual-depth preflight requires a digital-twin evidence sink"
            )

        def clearance_pair_provider() -> Mapping[Any, Any]:
            return camera_rig.capture_pair(
                timeout_s=0.5,
                max_age_s=0.30,
                max_skew_s=0.05,
            )

        trajectory_preflight = DualDepthClearancePreflight(
            pair_provider=clearance_pair_provider,
            tool_depth_buffer=tool_clearance_depth_buffer,
            workspace_depth_buffer=workspace_clearance_depth_buffer,
            tool_calibration=calibration,
            workspace_calibration=workspace_depth_calibration,
            tool_calibration_sha256=settings.eye_in_hand_calibration_sha256,
            workspace_calibration_sha256=(settings.workspace_depth_calibration_sha256),
            geometry_profile=clearance_geometry_profile,
            geometry_profile_sha256=(settings.dual_depth_geometry_profile_sha256),
            tool_pose_provider=tool_pose_buffer.resolve,
            required_clearance_mm=settings.dual_depth_required_clearance_mm,
            evidence_sink=evidence_sink,
            max_frame_age_s=0.30,
            max_pair_skew_s=0.05,
            max_tool_pose_skew_s=0.03,
            sample_stride=1,
            maximum_points_per_camera=(settings.camera_width * settings.camera_height),
        )

    if settings.workspace_boundary_validation_enabled:
        if trajectory_preflight is None:
            raise RuntimeError(
                "Workspace boundary validation requires dual-depth preflight"
            )
        if workspace_boundary_validator is None:
            try:
                from main.newton_workspace import (
                    NewtonPhysicsKinematicsValidator,
                    WorkspaceBoundaryValidationCoordinator,
                )
            except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                from newton_workspace import (  # type: ignore[no-redef]
                    NewtonPhysicsKinematicsValidator,
                    WorkspaceBoundaryValidationCoordinator,
                )

            workspace_boundary_validator = WorkspaceBoundaryValidationCoordinator(
                dual_depth_preflight=trajectory_preflight,
                newton_validator=NewtonPhysicsKinematicsValidator(
                    urdf_path=settings.newton_workspace_urdf_path,
                    expected_urdf_sha256=settings.newton_workspace_urdf_sha256,
                    expected_version=settings.newton_workspace_version,
                    device=settings.newton_workspace_device,
                ),
            )
        if not callable(
            getattr(workspace_boundary_validator, "start", None)
        ) or not callable(getattr(workspace_boundary_validator, "snapshot", None)):
            raise RuntimeError("Workspace boundary validator is incomplete")
    elif workspace_boundary_validator is not None:
        raise RuntimeError(
            "Workspace boundary validator injection requires explicit configuration"
        )

    if settings.mjpeg_enabled and mjpeg_server is None:
        if camera_rig is None:
            raise RuntimeError("MJPEG streaming requires a camera rig")
        try:
            from main.vision.cameras import CameraRole
            from main.vision.mjpeg import MjpegServer
        except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
            from vision.cameras import CameraRole  # type: ignore[no-redef]
            from vision.mjpeg import MjpegServer  # type: ignore[no-redef]

        mjpeg_server = MjpegServer(
            {
                CameraRole.TOOL: camera_rig.stream(CameraRole.TOOL),
                CameraRole.WORKSPACE: camera_rig.stream(CameraRole.WORKSPACE),
            },
            host=settings.mjpeg_host,
            port=settings.mjpeg_port,
            token=settings.mjpeg_token,
            max_clients=settings.mjpeg_max_clients,
            encoder=jpeg_encoder,
        )

    if settings.capture_run_enabled:
        if capture_run_controller is None:
            if (
                datahub is None
                or camera_rig is None
                or not isinstance(metric_source, XArmMetricSource)
                or not isinstance(xarm_motion_adapter, XArmMotionAdapter)
            ):
                raise RuntimeError(
                    "Commissioned capture requires concrete DataHub, dual-OAK, "
                    "and xArm adapters"
                )
            pair_provider = getattr(camera_rig, "capture_pair_for_run", None)
            if not callable(pair_provider):
                raise RuntimeError(
                    "Commissioned capture requires the strict dual-camera pair seam"
                )
            try:
                from main.capture_motion import (
                    CommissionedMotionRunner,
                    load_commissioned_motion_primitive,
                )
                from main.capture_runs import CaptureDatasetStore, CaptureRunController
                from main.capture_safety import (
                    CaptureSafetyRuntimeGuard,
                    SafetyGuardedMotionRunner,
                    XArmCaptureSafetySource,
                    load_capture_safety_evidence,
                )
                from main.vision.cameras import encode_jpeg as default_jpeg_encoder
            except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                from capture_motion import (  # type: ignore[no-redef]
                    CommissionedMotionRunner,
                    load_commissioned_motion_primitive,
                )
                from capture_runs import (  # type: ignore[no-redef]
                    CaptureDatasetStore,
                    CaptureRunController,
                )
                from capture_safety import (  # type: ignore[no-redef]
                    CaptureSafetyRuntimeGuard,
                    SafetyGuardedMotionRunner,
                    XArmCaptureSafetySource,
                    load_capture_safety_evidence,
                )
                from vision.cameras import (  # type: ignore[no-redef]
                    encode_jpeg as default_jpeg_encoder,
                )

            primitive = load_commissioned_motion_primitive(
                settings.capture_motion_profile_path,
                expected_sha256=settings.capture_motion_profile_sha256,
                forward_kinematics=xarm_motion_adapter.forward_kinematics,
            )
            if primitive.safety.workspace_lower_xyz_mm != tuple(
                settings.capture_workspace_lower_xyz_mm
            ) or primitive.safety.workspace_upper_xyz_mm != tuple(
                settings.capture_workspace_upper_xyz_mm
            ):
                raise RuntimeError(
                    "Capture motion workspace does not match runtime commissioning"
                )
            evidence = load_capture_safety_evidence(
                settings.capture_safety_evidence_path,
                expected_sha256=settings.capture_safety_evidence_sha256,
                device_uid=settings.device_uid,
                xarm_ip=settings.xarm_ip,
                xarm_model=settings.xarm_model,
                tool_camera_mxid=settings.tool_camera_device_id,
                workspace_camera_mxid=settings.workspace_camera_device_id,
                motion_profile_sha256=primitive.profile_sha256,
                workspace_lower_xyz_mm=settings.capture_workspace_lower_xyz_mm,
                workspace_upper_xyz_mm=settings.capture_workspace_upper_xyz_mm,
                joint_limit_policy=settings.capture_joint_limits_policy,
            )
            commissioned_runner = CommissionedMotionRunner(
                primitive,
                xarm_motion_adapter,
            )
            safety_source = XArmCaptureSafetySource(
                xarm_motion_adapter.arm,
                lock=metric_source._lock,
            )
            guarded_runner = SafetyGuardedMotionRunner(
                commissioned_runner,
                CaptureSafetyRuntimeGuard(evidence, safety_source),
            )
            capture_run_controller = CaptureRunController(
                store=CaptureDatasetStore(Path(settings.capture_dataset_root)),
                pair_provider=pair_provider,
                jpeg_encoder=jpeg_encoder or default_jpeg_encoder,
                motion_runner=guarded_runner,
            )
        if capture_dataset_exporter is None:
            if datahub is None:
                raise RuntimeError(
                    "Commissioned capture export requires configured DataHub"
                )
            try:
                from main.capture_export import CaptureDatasetExporter
            except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                from capture_export import (  # type: ignore[no-redef]
                    CaptureDatasetExporter,
                )
            capture_dataset_exporter = CaptureDatasetExporter(
                dataset_root=Path(settings.capture_dataset_root),
                publisher=datahub,
            )

    if settings.hand_training_enabled:
        if hand_training_controller is None:
            if camera_rig is None or metric_source is None:
                raise RuntimeError(
                    "Hand training requires the configured dual cameras and xArm telemetry"
                )
            pair_provider = getattr(camera_rig, "capture_pair_for_run", None)
            if not callable(pair_provider):
                raise RuntimeError(
                    "Hand training requires the strict dual-camera pair seam"
                )
            uploader = settings.build_hand_training_uploader(
                bearer_token_provider=tenant_auth_client.access_token_for_url,
                endpoint_url_provider=tenant_auth_client.endpoint_url,
            )
            if uploader is None:
                raise RuntimeError("Hand-training API-gateway upload is unavailable")
            try:
                from main.hand_training import HandTrainingRecordingController
                from main.vision.cameras import encode_jpeg as default_jpeg_encoder
            except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                from hand_training import (  # type: ignore[no-redef]
                    HandTrainingRecordingController,
                )
                from vision.cameras import (  # type: ignore[no-redef]
                    encode_jpeg as default_jpeg_encoder,
                )
            hand_training_controller = HandTrainingRecordingController(
                root=Path(settings.state_dir) / "hand-training",
                pair_provider=pair_provider,
                jpeg_encoder=jpeg_encoder or default_jpeg_encoder,
                telemetry_provider=lambda: hand_training_runtime[
                    "services"
                ].xarm_status(),
                uploader=uploader,
                device_uid=settings.device_uid,
                sample_rate_hz=settings.hand_training_sample_rate_hz,
                max_duration_seconds=(settings.hand_training_max_duration_seconds),
                max_video_bytes=settings.hand_training_max_video_bytes,
            )
    elif hand_training_controller is not None:
        raise RuntimeError(
            "Hand-training injection requires explicit trusted configuration"
        )

    if settings.site_safety_profile_path:
        if site_safety_gate is None:
            try:
                from main.site_safety import (
                    SiteSafetyCommissioningGate,
                    SiteSafetyRuntimeBindings,
                    load_site_safety_commissioning_profile,
                    site_profile_matches_controller_profile,
                )
            except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
                from site_safety import (  # type: ignore[no-redef]
                    SiteSafetyCommissioningGate,
                    SiteSafetyRuntimeBindings,
                    load_site_safety_commissioning_profile,
                    site_profile_matches_controller_profile,
                )

            site_profile = load_site_safety_commissioning_profile(
                settings.site_safety_profile_path,
                expected_sha256=settings.site_safety_profile_sha256,
            )
            controller_profile = getattr(safety_configurator, "profile", None)
            sampling_profile = getattr(sampling_tool_adapter, "profile", None)
            process_recipe = getattr(petri_process_controller, "recipe", None)
            home_trajectory = getattr(recovery_controller, "trajectory", None)
            site_safety_gate = SiteSafetyCommissioningGate(
                site_profile,
                SiteSafetyRuntimeBindings(
                    device_uid=settings.device_uid,
                    robot_serial=str(
                        getattr(controller_profile, "expected_robot_sn", "")
                    ),
                    firmware_version=str(
                        getattr(
                            controller_profile,
                            "expected_firmware_version",
                            "",
                        )
                    ).lstrip("vV"),
                    safety_profile_sha256=str(
                        getattr(controller_profile, "profile_sha256", "")
                    ),
                    geometry_profile_sha256=(
                        settings.dual_depth_geometry_profile_sha256
                    ),
                    sampling_tool_profile_sha256=str(
                        getattr(sampling_profile, "profile_sha256", "")
                    ),
                    tool_calibration_sha256=(settings.eye_in_hand_calibration_sha256),
                    workspace_calibration_sha256=(
                        settings.workspace_depth_calibration_sha256
                    ),
                    tool_camera_mxid=settings.tool_camera_device_id,
                    workspace_camera_mxid=settings.workspace_camera_device_id,
                    tray_fixture_sha256=settings.tray_fixture_profile_sha256,
                    process_profile_sha256=str(
                        getattr(
                            process_recipe,
                            "process_profile_sha256",
                            settings.petri_process_profile_sha256,
                        )
                    ),
                    home_trajectory_sha256=str(
                        getattr(
                            home_trajectory,
                            "profile_sha256",
                            settings.home_trajectory_sha256,
                        )
                    ),
                    recovery_trajectory_sha256=(settings.recovery_trajectory_sha256),
                    required_clearance_mm=(settings.dual_depth_required_clearance_mm),
                    controller_profile_consistent=(
                        site_profile_matches_controller_profile(
                            site_profile, controller_profile
                        )
                    ),
                ),
            )
    elif site_safety_gate is not None:
        raise RuntimeError(
            "Site-safety gate injection requires explicit trusted configuration"
        )

    services = WorkcellServices(
        settings=settings,
        datahub=datahub,
        camera_rig=camera_rig,
        metric_source=metric_source,
        ota_updater=ota_updater,
        offload_client=offload_client,
        tenant_auth_client=tenant_auth_client,
        readiness_client=readiness_client,
        mjpeg_server=mjpeg_server,
        jpeg_encoder=jpeg_encoder,
        tool_pose_buffer=tool_pose_buffer,
        tool_workspace_mapper=tool_workspace_mapper,
        local_valve_confirmation_detector=local_valve_confirmation_detector,
        valve_controller=valve_controller,
        xarm_motion_adapter=xarm_motion_adapter,
        sampling_tool_adapter=sampling_tool_adapter,
        motion_permit_authority=motion_permit_authority,
        motion_binding_provider=motion_binding_provider,
        recovery_controller=recovery_controller,
        petri_process_controller=petri_process_controller,
        petri_registry=petri_registry,
        petri_artifact_root=petri_artifact_root,
        capture_run_controller=capture_run_controller,
        capture_dataset_exporter=capture_dataset_exporter,
        hand_training_controller=hand_training_controller,
        safety_configurator=safety_configurator,
        site_safety_gate=site_safety_gate,
        digital_twin_provider=digital_twin_provider,
        trajectory_preflight=trajectory_preflight,
        workspace_teach_recorder=workspace_teach_recorder,
        workspace_teach_store=workspace_teach_store,
        workspace_boundary_validator=workspace_boundary_validator,
    )
    hand_training_runtime["services"] = services
    if settings.dynamic_valve_enabled and services.valve_controller is None:
        services.valve_controller = _build_dynamic_valve_controller(services)
    return services


def _build_dynamic_valve_controller(
    services: WorkcellServices,
) -> Any:
    """Assemble automatic tool-camera discovery and fail-closed dry-run plans."""

    if services.camera_rig is None or services.tool_workspace_mapper is None:
        raise RuntimeError(
            "Dynamic valve targeting requires cameras and eye-in-hand mapping"
        )
    try:
        from main.functions.trajectory_training import (
            DynamicValveImitationController,
            DynamicValvePlanner,
            JointLimits,
            SafeTrajectoryExecutor,
            TrajectorySafetyValidator,
            ValveMotionPrimitiveStore,
            WorkspaceLimits,
            build_valve_turn_primitive,
        )
        from main.vision.cameras import CameraRole
        from main.vision.valves import (
            CircleValveDetector,
            RemoteValveDetector,
            ValveTargetGate,
            ValveTargetPolicy,
            ValveTracker,
            ValveTrackingService,
        )
    except ImportError:  # Direct ``main/runtime.py`` execution on the Pi.
        from functions.trajectory_training import (  # type: ignore[no-redef]
            DynamicValveImitationController,
            DynamicValvePlanner,
            JointLimits,
            SafeTrajectoryExecutor,
            TrajectorySafetyValidator,
            ValveMotionPrimitiveStore,
            WorkspaceLimits,
            build_valve_turn_primitive,
        )
        from vision.cameras import CameraRole  # type: ignore[no-redef]
        from vision.valves import (  # type: ignore[no-redef]
            CircleValveDetector,
            RemoteValveDetector,
            ValveTargetGate,
            ValveTargetPolicy,
            ValveTracker,
            ValveTrackingService,
        )

    settings = services.settings
    lower = tuple(settings.eye_in_hand_workspace_lower_xyz_mm)
    upper = tuple(settings.eye_in_hand_workspace_upper_xyz_mm)
    workspace = WorkspaceLimits(lower, upper)
    tracker = ValveTracker(
        CameraRole.TOOL,
        min_confirmed_hits=3,
    )
    local_tracking = ValveTrackingService(
        {
            CameraRole.TOOL: CircleValveDetector(
                confidence=settings.dynamic_valve_min_confidence,
            )
        },
        {CameraRole.TOOL: tracker},
    )
    model_confirmation_tracking = None
    if services.local_valve_confirmation_detector is not None:
        model_confirmation_tracking = ValveTrackingService(
            {CameraRole.TOOL: services.local_valve_confirmation_detector},
            {
                CameraRole.TOOL: ValveTracker(
                    CameraRole.TOOL,
                    min_confirmed_hits=3,
                )
            },
        )
    elif services.offload_client is not None:
        model_confirmation_tracking = _CooldownTrackingAdapter(
            ValveTrackingService(
                {
                    CameraRole.TOOL: RemoteValveDetector(
                        services.valve_inference_offload_hook,
                        confidence_threshold=settings.dynamic_valve_min_confidence,
                    )
                },
                {
                    CameraRole.TOOL: ValveTracker(
                        CameraRole.TOOL,
                        min_confirmed_hits=3,
                    )
                },
            ),
            minimum_interval_seconds=(
                settings.dynamic_valve_remote_min_interval_seconds
            ),
        )
    target_gate = ValveTargetGate(
        services.tool_workspace_mapper,
        ValveTargetPolicy(
            min_confidence=settings.dynamic_valve_min_confidence,
            min_confirmed_hits=3,
            max_age_s=0.30,
            allowed_roles=(CameraRole.TOOL,),
            x_limits_mm=(lower[0], upper[0]),
            y_limits_mm=(lower[1], upper[1]),
            z_limits_mm=(lower[2], upper[2]),
        ),
    )
    live_motion = (
        settings.xarm_motion_enabled and services.xarm_motion_adapter is not None
    )
    if live_motion and model_confirmation_tracking is None:
        raise RuntimeError(
            "Live valve motion requires remote/model confirmation; local "
            "Hough-circle detections may only produce dry-run plans"
        )
    validator = TrajectorySafetyValidator(
        JointLimits.xarm_lite6(),
        workspace_limits=workspace,
        forward_kinematics=(
            services.xarm_motion_adapter.forward_kinematics if live_motion else None
        ),
    )
    if settings.dynamic_valve_primitive_path:
        primitive = ValveMotionPrimitiveStore().load(
            settings.dynamic_valve_primitive_path,
            expected_sha256=(
                settings.dynamic_valve_primitive_sha256 if live_motion else None
            ),
        )
    else:
        primitive = build_valve_turn_primitive()
    if live_motion and any(frame.gripper is not None for frame in primitive.frames):
        raise RuntimeError(
            "Live valve primitive contains gripper commands, but no reviewed "
            "gripper adapter is configured"
        )
    inverse_kinematics = (
        services.xarm_motion_adapter.inverse_kinematics if live_motion else None
    )
    seed_joints_provider = (
        services.xarm_motion_adapter.read_joint_angles_radians if live_motion else None
    )
    command_sink = (
        services.xarm_motion_adapter.send_joint_command if live_motion else None
    )
    tool_stream = services.camera_rig.stream(CameraRole.TOOL)
    return DynamicValveImitationController(
        frame_reader=lambda: tool_stream.latest(max_age_s=0.30),
        tracking_service=local_tracking,
        remote_tracking_adapter=model_confirmation_tracking,
        target_gate=target_gate,
        planner=DynamicValvePlanner(
            workspace_limits=workspace,
            joint_validator=validator if live_motion else None,
            inverse_kinematics=inverse_kinematics,
            default_normal_xyz=settings.dynamic_valve_default_normal_xyz,
            minimum_confidence=settings.dynamic_valve_min_confidence,
            maximum_target_age=0.30,
            maximum_initial_joint_delta_radians=(
                math.radians(5.0) if live_motion else None
            ),
        ),
        executor=SafeTrajectoryExecutor(
            validator=validator,
            command_sink=command_sink,
            dry_run=not live_motion,
        ),
        primitive=primitive,
        require_remote_confirmation_for_live=live_motion,
        seed_joints_provider=seed_joints_provider,
        trajectory_preflight=services.trajectory_preflight,
        dry_run=not live_motion,
        joint_sample_rate_hz=settings.dynamic_valve_servo_hz,
    )


__all__ = [
    "WorkcellServices",
    "XArmMetricSource",
    "XArmMotionAdapter",
    "_build_dynamic_valve_controller",
    "build_workcell_services",
]
