#!/usr/bin/env python
"""Generate a stable multi-shot camera edit using learned shot retrieval plus rules."""

from __future__ import annotations

import argparse
import copy
import functools
import hashlib
import inspect
import json
import math
import os
import platform
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import uuid
from collections import Counter
from dataclasses import asdict, dataclass
from pathlib import Path

import joblib
import librosa
import numpy as np
import scipy
import sklearn
from scipy.ndimage import gaussian_filter1d
from scipy.signal import find_peaks, savgol_filter
from scipy.spatial.transform import Rotation, Slerp
from sklearn.base import clone
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import balanced_accuracy_score
from sklearn.model_selection import GroupKFold

import hybrid_candidate_cache as candidate_cache
import adjacent_transition
import camera_kinematics
import data_driven_cut_planner as cut_planner
import hybrid_cut_reference as cut_reference
import hybrid_preparation_cache as preparation_cache
import hybrid_single_shot_cache as single_shot_cache
import planner
import shot_features
import camera_runtime_data as train
import cw_camera_runtime
import trajectory_quality


GIT_LFS_POINTER_PREFIX = "version https://git-lfs.github.com/spec/v1"
UTF8_BOM = "\ufeff"


HARD_PERSON_SAFE_BOUNDS = {
    "wide": (0.1, 0.9, 0.12, 0.86),
    "medium": (0.12, 0.88, 0.12, 0.84),
    "close": (0.15, 0.85, 0.12, 0.82),
}
PERSON_ONLY_HORIZONTAL_BOUNDS = {
    "wide": (0.44, 0.56),
    "medium": (0.42, 0.58),
    "close": (0.40, 0.60),
}
PERSON_ONLY_HORIZONTAL_TARGET_BOUNDS = {
    "wide": (0.45, 0.55),
    "medium": (0.43, 0.57),
    "close": (0.41, 0.59),
}
BALANCED_HORIZONTAL_BOUNDS = {
    "wide": (0.40, 0.60),
    "medium": (0.41, 0.59),
    "close": (0.42, 0.58),
}
BALANCED_HORIZONTAL_TARGET_BOUNDS = {
    "wide": (0.46, 0.54),
    "medium": (0.465, 0.535),
    "close": (0.47, 0.53),
}
HORIZONTAL_FRAMING_VERSION = (
    "semantic-soft-center-evidence-lead-baked-aim-v3"
)
PREPARATION_MODEL_SEED = 20260729
MAXIMUM_HORIZONTAL_REFRAME_DEGREES = 6.0
MAXIMUM_BALANCED_REFRAME_DEGREES = 8.0
MAXIMUM_DIRECTED_REFRAME_DEGREES = 12.0
CAMERA_DIRECTIVE_SCHEMA_VERSION = "camera-directives-v1"
HYBRID_METADATA_SCHEMA_VERSION = "3.6"
HYBRID_SHOTS_SCHEMA_VERSION = "1.2"
SELECTION_SAFETY_CONTRACT_VERSION = (
    "hybrid-selection-safety-stable-facing-residual-dynamics-"
    "authored-cost-exact-angular-tracking-post-clamp-kinematics-v4"
)
ADJACENT_TRANSITION_EDGE_LIST_SCHEMA_VERSION = (
    "authoritative-adjacent-transition-edges-v1"
)
HYBRID_SAMPLE_RATE = 60
HYBRID_GENERATION_MODES_BY_PLANNER = {
    "hierarchical": (
        "hierarchical_hybrid_retarget_v13",
        "hierarchical_hybrid_single_shot_composite_v1",
    ),
    "legacy": (
        "legacy_hybrid_retarget_v13",
        "legacy_hybrid_single_shot_composite_v1",
    ),
}
MATERIALIZED_SEED_LINEAGE_VERSION = "materialized-shot-seed-lineage-v1"
GENERATED_OUTPUT_PAYLOAD_NAMES = (
    "generated_camera_world.f32",
    "time.f64",
    "shots.json",
    "metadata.json",
)
OPTIONAL_GENERATED_OUTPUT_NAMES = ("cut_plan_trace.json",)
PRESERVED_OUTPUT_INPUT_NAMES = ("selected_shot_directives.json",)
SEED_VARIATION_POLICY_VERSION = (
    "safe-distinct-motion-semantic-authored-dynamics-seed-cycle-v7"
)
SEED_VARIATION_SEQUENCE_CONTEXT_POLICY = (
    "seed-independent-pre-transition-prefix-v2"
)
SELECTED_TRANSITION_CONTEXT_POLICY = (
    adjacent_transition.TRANSITION_POLICY_VERSION
)
SEED_VARIATION_SHOT_STRIDE = 104729
SEED_VARIATION_MAX_POOL_SIZE = 8
SEED_VARIATION_INITIAL_CANDIDATES = 8
SEED_VARIATION_MAX_NORMAL_CANDIDATES = 16
SEED_VARIATION_MAX_TRANSITION_CANDIDATES = 32
SEED_VARIATION_MAX_SELECTION_SCORE_DELTA = 2.0
TRANSITION_GATE_FAILURE_POLICY = (
    "fail-closed-after-bounded-selection-only-search-v1"
)
GENERATION_PERFORMANCE_SCHEMA_VERSION = "hybrid-generation-performance-v1"
PREPARATION_LOGIC_CONTRACT_VERSION = (
    "hybrid-preparation-logic-v3-complete-rotation-6d"
)
CANDIDATE_LOGIC_CONTRACT_VERSION = (
    "hybrid-candidate-logic-v31-exact-float32-tracking-causal-entry-"
    "minimum-jerk-authored-dynamics-cost-c2-semantic-dead-zone-bounded-"
    "transition-fail-closed"
)
CUT_REFERENCE_SELECTION_POLICY_VERSION = (
    "production-exact-audio-cut-only-generation-input-audio-aligned-mask-v2"
)
RESEARCH_ABLATION_CONTRACT_VERSION = "research-ablation-profile-v1"
RESEARCH_ABLATION_PROFILES = (
    "none",
    "no_audio",
    "no_motion",
    "no_same_audio",
)
SEGMENT_FEATURE_MOTION_BOUNDS = (1, 5)
SEGMENT_FEATURE_AUDIO_BOUNDS = (5, 9)
CUT_INPUT_MOTION_BOUNDS = (63, 126)
CUT_INPUT_AUDIO_BOUNDS = (126, 160)
CANDIDATE_CACHE_STAGE_VERSIONS = {
    "shotSegmentation": (
        "data-driven-candidates-ranker-global-dag-audio-aligned-cut-reference-v2"
    ),
    "shotPlanning": "hierarchical-or-legacy-reconciliation-replay-v3-static-budget",
    "candidateRanking": (
        "template-rank-v20-c2-position-residual-screen-dynamics-cost-aware-aim-"
        "adjacent-transition-v3-no-forced-side-alternation"
    ),
    "trajectoryRetargeting": (
        "retarget-v29-float32-bound-speed-adaptive-final-radial-post-kinematic-"
        "audit-"
        "residual-dynamics-semantic-exact-tracking-causal-entry-minimum-jerk"
    ),
    "compositionSafety": (
        "person-safety-v18-full-song-root-calibrated-choreography-facing-"
        "authored-cost-residual-dynamics-post-clamp-kinematics"
    ),
    "variationPool": (
        SEED_VARIATION_POLICY_VERSION
        + "-static-budget-v5-seed-independent-base-selection-only-extra"
    ),
    "sequenceContinuation": SEED_VARIATION_SEQUENCE_CONTEXT_POLICY,
}
TRAJECTORY_RETARGETING_VERSION = (
    "c2-position-float32-bound-speed-adaptive-final-radial-post-kinematic-"
    "audit-v16"
)
TEMPLATE_MOTION_SMOOTHING_VERSION = (
    "savgol61-nearest-edge-step-guard-v1"
)
TEMPLATE_AUDIO_MASK_POLICY_VERSION = (
    train.AUDIO_ALIGNED_FRAME_MASK_POLICY_VERSION
    + "-whole-authored-shot-only"
)
MOTION_SELECTION_VERSION = (
    "non-static-retention-residual-screen-authored-cost-yamo-kinematics-v12"
)
FINAL_POSITION_SMOOTHING_WINDOW_FRAMES = 15
FINAL_POSITION_SMOOTHING_VERSION = (
    "nearest-edge-low-frequency-net-travel-dynamics-guard-v3"
)
FINAL_RADIAL_DYNAMICS_GUARD_POLICY_VERSION = (
    "final-radial-world-dynamics-regression-guard-v1"
)
FINAL_RADIAL_MAXIMUM_DYNAMICS_REGRESSION_RATIO = 1.05
FINAL_RADIAL_MAXIMUM_ACCELERATION_REGRESSION_DELTA_MPS2 = 0.50
FINAL_RADIAL_MAXIMUM_JERK_REGRESSION_DELTA_MPS3 = 10.0
TRAJECTORY_DYNAMICS_SELECTION_WEIGHT = 0.18
TRAJECTORY_DYNAMICS_MAXIMUM_SELECTION_PENALTY = 0.90
CANDIDATE_DYNAMICS_SELECTION_POLICY_VERSION = (
    "authored-cost-preferred-uncapped-failure-penalty-v1"
)
CANDIDATE_DYNAMICS_MAXIMUM_ACCEPTABLE_COST = 6.0
CANDIDATE_DYNAMICS_COST_FAILURE_BASE_PENALTY = 3.0
CANDIDATE_DYNAMICS_COST_FAILURE_EXCESS_WEIGHT = 0.75
CANDIDATE_DYNAMICS_HARD_GATE_POLICY_VERSION = (
    "candidate-dynamics-hard-gate-v3-stabilized-screen-residual"
)
TRAJECTORY_CATASTROPHIC_MAXIMUM_SPEED_MPS = 12.0
TRAJECTORY_CATASTROPHIC_MAXIMUM_ACCELERATION_MPS2 = 80.0
TRAJECTORY_CATASTROPHIC_MAXIMUM_JERK_MPS3 = 600.0
SCREEN_CATASTROPHIC_MAXIMUM_ACCELERATION_UVPS2_P99 = 50.0
SCREEN_CATASTROPHIC_MAXIMUM_JERK_UVPS3_P99 = 1200.0
SCREEN_CATASTROPHIC_MAXIMUM_ACCELERATION_UVPS2 = 60.0
SCREEN_CATASTROPHIC_MAXIMUM_JERK_UVPS3 = 1600.0
MAXIMUM_CAMERA_RELATIVE_POSITION_STEP_METERS = 0.12
TRAJECTORY_OFFSET_LIMITS_METERS = {
    "wide": 4.5,
    "medium": 3.0,
    "close": 1.6,
}
MINIMUM_NON_STATIC_MOTION_RETENTION_RATIO = 0.65
MOTION_RETENTION_PENALTY_WEIGHT = 1.5
MOTION_EXPRESSIVENESS_REWARD_MAX = 0.35
MOTION_EXPRESSIVENESS_TRANSLATION_SPEED_MPS = {
    "wide": 0.40,
    "medium": 0.25,
    "close": 0.15,
}
MOTION_EXPRESSIVENESS_ROTATION_SPEED_DPS = 6.0
MOTION_QUALITY_SAMPLE_RATE_HZ = 6.0
MINIMUM_AUTOMATIC_OPENING_EXPRESSIVENESS = 0.12
ROLLING_STATIC_BUDGET_WINDOW_SIZE = 4
ROLLING_STATIC_BUDGET_MAX_STATIC_SHOTS = 1
ROLLING_STATIC_BUDGET_POLICY_VERSION = (
    "seed-independent-static-slot-reservation-v1"
)
AIM_POLICY_VERSION = (
    "semantic-focus-c2-hysteretic-dead-zone-causal-boundary-exact-tracking-"
    "minimum-jerk-baked-aim-v6"
)
AIM_SAMPLE_RATE = 60.0
AIM_TARGET_SMOOTHING_SECONDS = 0.60
AIM_TARGET_DEAD_ZONE_METERS = 0.055
AIM_SOURCE_RESIDUAL_SMOOTHING_SECONDS = 0.45
AIM_SOURCE_RESIDUAL_HORIZONTAL_LIMIT = 0.035
AIM_SOURCE_RESIDUAL_VERTICAL_LIMIT = 0.030
AIM_MAXIMUM_ANGULAR_SPEED_DPS = 90.0
AIM_MAXIMUM_ANGULAR_ACCELERATION_DPS2 = 360.0
# The authored corpus, after restricting samples to the existing 90 dps / 360
# dps2 contract, has an angular-jerk P99 of about 1,950 dps3 and a P99.9 of
# about 6,610 dps3.  The larger value remains a catastrophic ceiling, not a
# quality target: normal generation searches all causal response candidates
# for an authored-range minimum-jerk path before it may use that long tail.
AIM_MAXIMUM_ANGULAR_JERK_DPS3 = 7200.0
AIM_AUTHORED_ANGULAR_JERK_TARGET_DPS3 = 2400.0
AIM_AUTHORED_ANGULAR_JERK_P95_TARGET_DPS3 = 1950.0
AIM_MINIMUM_JERK_TRACKING_P90_BUDGET_DEGREES = 2.5
AIM_MINIMUM_JERK_TRACKING_MAXIMUM_BUDGET_DEGREES = 5.0
AIM_MINIMUM_JERK_TRACKING_FINAL_BUDGET_DEGREES = 2.0
AIM_MINIMUM_JERK_SELECTION_POLICY_VERSION = (
    "causal-entry-authored-target-exact-float32-tracking-budget-objective-v2"
)
AIM_ANGULAR_JERK_P95_FREE_RATIO = 0.25
AIM_ANGULAR_JERK_PEAK_FREE_RATIO = 0.75
AIM_ANGULAR_JERK_SELECTION_WEIGHT = 2.0
AIM_ERROR_WARNING_DEGREES = 7.0
AIM_ERROR_P90_LIMIT_DEGREES = 6.0
AIM_HORIZONTAL_WARNING_UV = 0.10
AIM_HORIZONTAL_P90_LIMIT_UV = 0.075
AIM_LONGEST_WARNING_RUN_FRACTION = 0.25
FRONT_FACING_ALIGNMENT_MEDIAN_MINIMUM = -0.05
FRONT_FACING_SEVERE_REAR_ALIGNMENT = -0.25
FRONT_FACING_MAXIMUM_SEVERE_REAR_FRAME_RATIO = 0.12
FRONT_FACING_MAXIMUM_SEVERE_REAR_RUN_SECONDS = 0.35
FRONT_FACING_POLICY_VERSION = (
    "anatomical-strict-full-song-root-calibrated-choreography-turn-v4"
)
FRONT_FACING_STABLE_REFERENCE_MINIMUM_RELIABILITY = 0.60
FRONT_FACING_STABLE_REFERENCE_MINIMUM_VALID_FRAME_RATIO = 0.95
FRONT_FACING_STABLE_ALIGNMENT_MEDIAN_MINIMUM = (
    FRONT_FACING_ALIGNMENT_MEDIAN_MINIMUM
)
FRONT_FACING_CHOREOGRAPHY_TURN_DEVIATION_ALIGNMENT = 0.50
FRONT_FACING_CHOREOGRAPHY_MINIMUM_TURN_FRAME_RATIO = 0.05
AUTOMATIC_LEAD_ROOM_UV = {
    "wide": 0.06,
    "medium": 0.052,
    "close": 0.045,
}
CANDIDATE_CACHE_ARRAY_KEYS = (
    "position",
    "rotation",
    "fov",
    "dutch",
    "target",
    "stageAnchor",
)
SEED_VARIATION_THRESHOLDS = {
    "positionRmsMeters": 0.35,
    "positionMaxMeters": 0.65,
    "rotationRmsDegrees": 4.0,
    "rotationMaxDegrees": 7.0,
    "fovRmsDegrees": 3.0,
    "fovMaxDegrees": 5.0,
    "relativeTrajectoryRmsMeters": 0.25,
    "netMotionDeltaMeters": 0.35,
    "typedMotionTrajectoryRmsMeters": 0.10,
    "typedMotionNetDeltaMeters": 0.20,
}
DEFAULT_BODY_FOLLOW_STRENGTH = 0.18
DEFAULT_BODY_FOLLOW_SMOOTHING_SECONDS = 1.25
DEFAULT_BODY_FOLLOW_DEAD_ZONE_METERS = 0.12
STRICT_ENVELOPE_JOINTS = {
    "wide": tuple(range(21)),
    "medium": (0, 2, 4, 5, 9),
    "close": (2, 4),
}
SHOT_SIZE_CHOICES = ("auto", "wide", "medium", "close")
MOTION_DIRECTIVE_CHOICES = (
    "auto",
    "static",
    "dolly_in",
    "dolly_out",
    "orbit_left",
    "orbit_right",
    "truck_left",
    "truck_right",
    "crane_up",
    "crane_down",
)
COMPOSITION_DIRECTIVE_CHOICES = (
    "auto",
    "center",
    "left_third",
    "right_third",
)


@dataclass
class ShotTemplate:
    source_id: str
    source_dataset_id: str
    source_folder: str
    song_name: str
    source_role: str
    source_split: str
    shot_index: int
    source_start_frame: int
    source_end_frame_exclusive: int
    source_frame_count: int
    duration: float
    features: np.ndarray
    anchor: np.ndarray
    motion_delta: np.ndarray
    motion_path: np.ndarray
    rotation_path: np.ndarray
    fov_path: np.ndarray
    dutch_path: np.ndarray
    wide_composition_path: np.ndarray
    medium_composition_path: np.ndarray
    close_composition_path: np.ndarray
    source_trim_start_frames: int
    source_trim_end_frames: int
    source_aspect_ratio: float
    source_aspect_source: str
    motion_type: str
    motion_family: str
    motion_confidence: float
    orbit_degrees: float
    radial_delta_meters: float
    lateral_delta_meters: float
    vertical_delta_meters: float
    net_motion_meters: float
    path_length_meters: float
    fov: float
    composition_score: float
    subject_height_ratio: float = float("nan")
    framing_valid_ratio: float = 0.0
    shot_type_confidence: float = 0.0
    shot_type_confidence_tier: str = "low"
    shot_type: str = ""
    source_audio_aligned_frame_mask_ranges: (
        tuple[tuple[int, int], ...] | None
    ) = None
    source_audio_mask_range_index: int | None = None
    source_authored_start_frame: int | None = None
    source_authored_end_frame_exclusive: int | None = None

    def person_composition_path(self) -> np.ndarray:
        if self.shot_type == "wide":
            return self.wide_composition_path
        if self.shot_type == "close":
            return self.close_composition_path
        return self.medium_composition_path

    def source_person_visibility(self) -> float:
        return float(np.mean(self.person_composition_path()[:, 3]))


@dataclass(frozen=True)
class ShotControl:
    shot_size: str = "auto"
    motion: str = "auto"
    composition: str = "auto"
    distance_meters: float = 0.0
    motion_intensity: float = 1.0
    body_follow_strength: float = DEFAULT_BODY_FOLLOW_STRENGTH


class CandidateRetargetSafetyRejection(RuntimeError):
    """A candidate-local publishability failure that permits trying another rank."""


@dataclass(frozen=True)
class RealizedShotState:
    template: ShotTemplate
    side_sign: float
    motion_type: str


@dataclass(frozen=True)
class PlannerDirectiveReconciliation:
    """Reconcile one beam directive with user intent and realized output."""

    realized_directive: planner.ShotDirective
    user_override_changed_plan: bool
    realization_changed_plan: bool
    should_replan: bool
    replan_reason: str | None


@dataclass(frozen=True)
class PreparationCacheLookup:
    status: str
    cache_key: str | None = None
    path: Path | None = None
    loaded: preparation_cache.LoadedHybridPreparationCache | None = None
    error: str | None = None
    manifest_fingerprint: str | None = None


@dataclass(frozen=True)
class CachedCandidateRuntimeShot:
    candidate_results: list[dict]
    safe_results: list[dict]
    variation_pool: list[dict]


@dataclass(frozen=True)
class BaseGenerationComposite:
    """A validated full generation used as an immutable composite base."""

    folder: Path
    metadata: dict
    metadata_sha256: str
    shots: tuple[dict, ...]
    shots_sha256: str
    world_camera: np.ndarray
    world_camera_sha256: str
    times: np.ndarray
    time_sha256: str
    boundaries: tuple[int, ...]


@dataclass(frozen=True)
class BaseSingleShotContext:
    """Seed-independent sequence context recovered from base shot traces."""

    previous: RealizedShotState | None
    recent: tuple[tuple[str, int], ...]
    static_budget_motion_history: tuple[str, ...]
    cache_value: dict[str, object]


class SequentialStageTimer:
    """Record non-overlapping generation stages without changing control flow."""

    def __init__(self, clock=time.perf_counter) -> None:
        self._clock = clock
        self._started = float(clock())
        self._last = self._started
        self._seconds: dict[str, float] = {}

    def mark(self, completed_stage: str) -> float:
        name = str(completed_stage).strip()
        if not name:
            raise ValueError("Stage name must not be empty.")
        now = float(self._clock())
        elapsed = max(0.0, now - self._last)
        self._seconds[name] = self._seconds.get(name, 0.0) + elapsed
        self._last = now
        return elapsed

    def snapshot(self) -> dict[str, object]:
        return {
            "schemaVersion": GENERATION_PERFORMANCE_SCHEMA_VERSION,
            "stageSeconds": dict(self._seconds),
            "totalSeconds": max(0.0, float(self._clock()) - self._started),
        }


def _path_is_reparse_point(path: Path) -> bool:
    """Return true for symlinks, junctions, and other Windows reparse points."""

    path = Path(path)
    if path.is_symlink():
        return True
    try:
        attributes = getattr(path.lstat(), "st_file_attributes", 0)
    except FileNotFoundError:
        return False
    reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
    return bool(attributes & reparse_flag)


def _validate_output_directory_members(
    folder: Path,
    *,
    require_complete_payload: bool,
) -> None:
    allowed_names = set(GENERATED_OUTPUT_PAYLOAD_NAMES)
    allowed_names.update(OPTIONAL_GENERATED_OUTPUT_NAMES)
    allowed_names.update(PRESERVED_OUTPUT_INPUT_NAMES)
    present_names: set[str] = set()
    for member in folder.iterdir():
        present_names.add(member.name)
        if member.name not in allowed_names:
            raise ValueError(
                "Generated output folder contains an unknown sidecar: "
                + member.name
            )
        if _path_is_reparse_point(member) or not member.is_file():
            raise ValueError(
                "Generated output members must be regular files: " + str(member)
            )
    if require_complete_payload:
        missing = set(GENERATED_OUTPUT_PAYLOAD_NAMES) - present_names
        if missing:
            raise ValueError(
                "Generated output is incomplete; missing payload members: "
                + ", ".join(sorted(missing))
            )


def _remove_validated_output_backup(
    backup_path: Path,
    expected_parent: Path,
) -> None:
    if _path_is_reparse_point(backup_path) or not backup_path.is_dir():
        raise ValueError(
            "Generated output backup is not a regular directory: "
            + str(backup_path)
        )
    resolved_backup = backup_path.resolve(strict=True)
    resolved_parent = expected_parent.resolve(strict=True)
    if resolved_backup.parent != resolved_parent:
        raise ValueError(
            "Generated output backup resolves outside its expected parent."
        )
    shutil.rmtree(resolved_backup)


def _recover_interrupted_output_publication(final_path: Path) -> None:
    """Recover the single private backup left between the two directory moves."""

    prefix = f".{final_path.name}.previous-"
    candidates = [
        member
        for member in final_path.parent.iterdir()
        if member.name.startswith(prefix)
    ]
    if not candidates:
        return
    if len(candidates) != 1:
        raise RuntimeError(
            "Generated output recovery is ambiguous; expected one previous backup."
        )
    backup_path = candidates[0]
    suffix = backup_path.name[len(prefix) :]
    if (
        len(suffix) != 32
        or any(character not in "0123456789abcdef" for character in suffix)
        or _path_is_reparse_point(backup_path)
        or not backup_path.is_dir()
    ):
        raise RuntimeError(
            "Generated output recovery found a malformed previous backup: "
            + str(backup_path)
        )
    _validate_output_directory_members(
        backup_path,
        require_complete_payload=False,
    )
    if final_path.exists():
        _validate_output_directory_members(
            final_path,
            require_complete_payload=True,
        )
        _remove_validated_output_backup(backup_path, final_path.parent)
        print(
            "Removed completed generated-output publication backup: "
            + str(backup_path),
            file=sys.stderr,
        )
        return
    try:
        os.replace(backup_path, final_path)
    except OSError as error:
        raise RuntimeError(
            "Interrupted generated output could not be restored; its backup "
            "remains at "
            + str(backup_path)
        ) from error
    print(
        "Recovered interrupted generated output from: " + str(backup_path),
        file=sys.stderr,
    )


class AtomicOutputPublisher:
    """Best-effort transactional publication through sibling directory moves.

    Unity may pre-create the output directory with a selected-shot directive.
    Only that explicit input sidecar, the four required payload members, and
    declared optional generated diagnostics are accepted. Windows cannot
    replace a non-empty directory in one operation,
    so publication moves the previous folder aside and then installs a complete
    staging folder.  Python-level failures restore the previous folder, and a
    later invocation recovers the single well-formed backup left by a hard stop
    between the two moves.  Ambiguous or malformed recovery state fails closed.
    """

    def __init__(self, final_path: Path) -> None:
        declared_path = Path(final_path)
        if _path_is_reparse_point(declared_path):
            raise ValueError(
                "Generated output folder must not be a reparse point."
            )
        self.final_path = declared_path.resolve()
        self.final_path.parent.mkdir(parents=True, exist_ok=True)
        if self.final_path.exists() and not self.final_path.is_dir():
            raise NotADirectoryError(
                "Generated output path exists and is not a directory: "
                + str(self.final_path)
            )
        _recover_interrupted_output_publication(self.final_path)
        if self.final_path.exists():
            _validate_output_directory_members(
                self.final_path,
                require_complete_payload=False,
            )
        self._temporary = tempfile.TemporaryDirectory(
            prefix=f".{self.final_path.name}.staging-",
            dir=self.final_path.parent,
        )
        self.staging_path = Path(self._temporary.name)
        self._published = False
        try:
            if self.final_path.is_dir():
                for name in PRESERVED_OUTPUT_INPUT_NAMES:
                    source = self.final_path / name
                    if source.is_file():
                        shutil.copy2(source, self.staging_path / name)
        except BaseException:
            self._temporary.cleanup()
            raise

    def publish(self) -> None:
        if self._published:
            raise RuntimeError("Generated output has already been published.")
        for name in GENERATED_OUTPUT_PAYLOAD_NAMES:
            member = self.staging_path / name
            if _path_is_reparse_point(member) or not member.is_file():
                self.cleanup()
                raise FileNotFoundError(
                    "Complete generated output payload is missing: " + str(member)
                )
        try:
            _validate_output_directory_members(
                self.staging_path,
                require_complete_payload=True,
            )
        except BaseException:
            self.cleanup()
            raise

        backup_path: Path | None = None
        if self.final_path.exists():
            backup_path = self.final_path.parent / (
                f".{self.final_path.name}.previous-{uuid.uuid4().hex}"
            )
            try:
                os.replace(self.final_path, backup_path)
            except BaseException:
                self.cleanup()
                raise
        try:
            os.replace(self.staging_path, self.final_path)
        except BaseException:
            if backup_path is not None and backup_path.exists():
                try:
                    os.replace(backup_path, self.final_path)
                except OSError as restore_error:
                    self.cleanup()
                    raise RuntimeError(
                        "Atomic generated-output publication failed and the "
                        "previous output could not be restored. It remains at "
                        + str(backup_path)
                    ) from restore_error
            self.cleanup()
            raise

        self._published = True
        self._temporary.cleanup()
        if backup_path is not None and backup_path.exists():
            try:
                _remove_validated_output_backup(
                    backup_path,
                    self.final_path.parent,
                )
            except (OSError, ValueError) as cleanup_error:
                print(
                    "Generated output backup cleanup warning: "
                    + str(cleanup_error),
                    file=sys.stderr,
                )

    def cleanup(self) -> None:
        if not self._published:
            self._temporary.cleanup()


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--song", default="")
    parser.add_argument(
        "--song-id",
        default="",
        help="16-character song ID from DatasetExports/dataset_catalog.json.",
    )
    parser.add_argument(
        "--dataset-id",
        default="",
        help="Dataset folder name used to disambiguate repeated song names.",
    )
    parser.add_argument("--data", nargs="*", default=[])
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--seed", type=int, default=20260729)
    parser.add_argument(
        "--preparation-model-seed",
        type=int,
        default=PREPARATION_MODEL_SEED,
        help=(
            "Stable RF/planner training seed used by preparation caches. "
            "Generation --seed remains free to vary candidate selection."
        ),
    )
    parser.add_argument(
        "--min-shot-seconds",
        type=float,
        default=2.5,
        help="Legacy beat/onset planner minimum; ignored by data_driven planning.",
    )
    parser.add_argument(
        "--max-shot-seconds",
        type=float,
        default=5.5,
        help="Legacy beat/onset planner maximum; ignored by data_driven planning.",
    )
    parser.add_argument(
        "--cut-planner",
        choices=("legacy", "data_driven"),
        default="data_driven",
        help=(
            "Global cut-boundary planner. data_driven uses broad 60 fps "
            "music/motion candidates, an empirical duration prior and DAG DP."
        ),
    )
    parser.add_argument(
        "--cut-density",
        choices=("auto", "slow", "normal", "fast"),
        default="auto",
        help="Soft global cut-density direction for data-driven planning.",
    )
    parser.add_argument(
        "--cut-ranker-model",
        type=Path,
        default=(Path(__file__).resolve().parents[2] / "models" / "cut_ranker_v2.json"),
        help="Safe JSON linear candidate-ranker artifact.",
    )
    parser.add_argument(
        "--cut-directives-json",
        type=Path,
        default=None,
        help=(
            "Optional cut-directives-v1 JSON containing locked/preferred cut "
            "frames and no-cut ranges."
        ),
    )
    parser.add_argument(
        "--same-audio-prior",
        choices=("auto", "off"),
        default="auto",
        help=(
            "Use approved authored cut patterns with an exact audio SHA-256 "
            "match. Evaluation safety still follows --library-split."
        ),
    )
    parser.add_argument(
        "--research-ablation-profile",
        choices=RESEARCH_ABLATION_PROFILES,
        default="none",
        help=(
            "Research-only signal ablation. The production default 'none' "
            "preserves the normal generation path."
        ),
    )
    parser.add_argument(
        "--training-index",
        type=Path,
        default=Path("reports/training_index.json"),
        help=(
            "Leakage-safe dataset policy. Benchmark generation uses train "
            "entries and excludes the target evaluation group."
        ),
    )
    parser.add_argument(
        "--library-split",
        choices=("train", "all"),
        default="train",
        help=(
            "Use train-only templates for evaluation, or all approved data "
            "for an explicitly marked production run."
        ),
    )
    parser.add_argument(
        "--planner",
        choices=("legacy", "hierarchical"),
        default="legacy",
        help=(
            "Shot-intent planner. Legacy remains the production-safe default; "
            "hierarchical is an explicit research preview."
        ),
    )
    parser.add_argument(
        "--aspect-ratio",
        type=float,
        default=0.0,
        help=(
            "Target output width/height. Zero reads training-index metadata "
            "and falls back to an explicitly recorded 16:9 assumption."
        ),
    )
    parser.add_argument(
        "--beam-width",
        type=int,
        default=6,
        help="Sequence beam width used by the hierarchical planner.",
    )
    parser.add_argument(
        "--evaluate-planner",
        action="store_true",
        help=(
            "Run grouped closed-loop cross-validation before generation. "
            "This is intended for benchmarks and adds substantial runtime."
        ),
    )
    parser.add_argument(
        "--horizontal-framing",
        choices=(
            "source",
            "balanced",
            "centered",
            "left_third",
            "right_third",
        ),
        default="balanced",
        help=(
            "Horizontal person-framing policy. 'balanced' is the automatic "
            "soft-center mode and opens lead room only when target motion or "
            "facing provides stable evidence. 'centered' and thirds are "
            "authoritative directives; 'source' is the legacy authored mode."
        ),
    )
    parser.add_argument(
        "--body-follow-strength",
        type=float,
        default=DEFAULT_BODY_FOLLOW_STRENGTH,
        help=(
            "Low-frequency subject translation applied to the camera body. "
            "Zero creates a shot-fixed stage anchor; one follows the filtered "
            "subject path fully."
        ),
    )
    parser.add_argument(
        "--body-follow-smoothing-seconds",
        type=float,
        default=DEFAULT_BODY_FOLLOW_SMOOTHING_SECONDS,
        help="Gaussian smoothing scale used before camera-body following.",
    )
    parser.add_argument(
        "--body-follow-dead-zone-meters",
        type=float,
        default=DEFAULT_BODY_FOLLOW_DEAD_ZONE_METERS,
        help="Horizontal subject travel ignored before body following starts.",
    )
    parser.add_argument(
        "--shot-size",
        choices=SHOT_SIZE_CHOICES,
        default="auto",
        help="Global shot-size directive; a directives JSON can override it per shot.",
    )
    parser.add_argument(
        "--motion",
        choices=MOTION_DIRECTIVE_CHOICES,
        default="auto",
        help="Global signed camera-motion directive.",
    )
    parser.add_argument(
        "--composition",
        choices=COMPOSITION_DIRECTIVE_CHOICES,
        default="auto",
        help="Global person-composition directive.",
    )
    parser.add_argument(
        "--distance-meters",
        type=float,
        default=0.0,
        help="Target camera distance in meters; zero keeps automatic distance.",
    )
    parser.add_argument(
        "--motion-intensity",
        type=float,
        default=1.0,
        help="Scale authored within-shot motion from zero to two.",
    )
    parser.add_argument(
        "--directives-json",
        type=Path,
        default=None,
        help=(
            "Optional camera-directives-v1 JSON with defaults and per-shot "
            "overrides."
        ),
    )
    parser.add_argument(
        "--cache-dir",
        type=Path,
        default=Path(__file__).resolve().parent / "cache",
    )
    parser.add_argument(
        "--preparation-cache-root",
        type=Path,
        default=(
            Path(__file__).resolve().parents[2]
            / ".cache"
            / "hybrid_preparation"
        ),
        help=(
            "Content-addressed templates/model/audio cache built by "
            "build_hybrid_preparation_cache.py."
        ),
    )
    parser.add_argument(
        "--preparation-cache-mode",
        choices=("auto", "off", "require"),
        default="auto",
        help=(
            "Use a valid preparation cache automatically, disable it, or "
            "require a valid hit. Current bundles support the hierarchical "
            "planner only."
        ),
    )
    parser.add_argument(
        "--candidate-cache-root",
        type=Path,
        default=(
            Path(__file__).resolve().parents[2]
            / ".cache"
            / "hybrid_candidates"
        ),
        help=(
            "Content-addressed seed-independent safe candidate pools. "
            "A cache hit makes Seed changes skip camera retargeting."
        ),
    )
    parser.add_argument(
        "--candidate-cache-mode",
        choices=("auto", "off", "require"),
        default="auto",
        help=(
            "Use and publish safe candidate pools automatically, bypass "
            "them, or require an existing validated pool."
        ),
    )
    parser.add_argument(
        "--only-shot-index",
        type=int,
        default=None,
        help=(
            "Regenerate only this zero-based shot from --base-generation. "
            "Every other camera frame and shot row is preserved exactly."
        ),
    )
    parser.add_argument(
        "--base-generation",
        type=Path,
        default=None,
        help=(
            "Existing full-compatible generation to materialize and patch. "
            "Required together with --only-shot-index."
        ),
    )
    parser.add_argument(
        "--single-shot-cache-root",
        type=Path,
        default=(
            Path(__file__).resolve().parents[2]
            / ".cache"
            / "hybrid_single_shot_candidates"
        ),
        help=(
            "Separate content-addressed candidate pools for true one-shot "
            "regeneration."
        ),
    )
    return parser.parse_args()


def validate_shot_control(control: ShotControl) -> ShotControl:
    if control.shot_size not in SHOT_SIZE_CHOICES:
        raise ValueError(f"Unknown shot size directive: {control.shot_size!r}")
    if control.motion not in MOTION_DIRECTIVE_CHOICES:
        raise ValueError(f"Unknown motion directive: {control.motion!r}")
    if control.composition not in COMPOSITION_DIRECTIVE_CHOICES:
        raise ValueError(
            f"Unknown composition directive: {control.composition!r}"
        )
    numeric = {
        "distanceMeters": control.distance_meters,
        "motionIntensity": control.motion_intensity,
        "bodyFollowStrength": control.body_follow_strength,
    }
    for name, value in numeric.items():
        if not math.isfinite(value):
            raise ValueError(f"{name} must be finite.")
    if not 0.0 <= control.body_follow_strength <= 1.0:
        raise ValueError("bodyFollowStrength must be between zero and one.")
    if not 0.0 <= control.motion_intensity <= 2.0:
        raise ValueError("motionIntensity must be between zero and two.")
    if not 0.0 <= control.distance_meters <= 100.0:
        raise ValueError("distanceMeters must be between zero and 100.")
    return control


def shot_control_from_mapping(
    value: dict,
    base: ShotControl,
) -> ShotControl:
    if not isinstance(value, dict):
        raise ValueError("Each camera directive must be a JSON object.")
    allowed = {
        "shotSize",
        "motion",
        "composition",
        "distanceMeters",
        "motionIntensity",
        "bodyFollowStrength",
    }
    unknown = sorted(set(value) - allowed)
    if unknown:
        raise ValueError(
            "Unknown camera directive fields: " + ", ".join(unknown)
        )
    return validate_shot_control(
        ShotControl(
            shot_size=str(value.get("shotSize", base.shot_size)),
            motion=str(value.get("motion", base.motion)),
            composition=str(value.get("composition", base.composition)),
            distance_meters=float(
                value.get("distanceMeters", base.distance_meters)
            ),
            motion_intensity=float(
                value.get("motionIntensity", base.motion_intensity)
            ),
            body_follow_strength=float(
                value.get(
                    "bodyFollowStrength",
                    base.body_follow_strength,
                )
            ),
        )
    )


def load_shot_controls(
    path: Path | None,
    global_control: ShotControl,
    shot_count: int,
) -> list[ShotControl]:
    global_control = validate_shot_control(global_control)
    if path is None:
        return [global_control] * shot_count
    payload = json.loads(path.resolve().read_text(encoding="utf-8"))
    if not isinstance(payload, dict):
        raise ValueError("Camera directives JSON must contain one object.")
    allowed_top_level = {"schemaVersion", "defaults", "shots"}
    unknown = sorted(set(payload) - allowed_top_level)
    if unknown:
        raise ValueError(
            "Unknown camera directive document fields: "
            + ", ".join(unknown)
        )
    if payload.get("schemaVersion") != CAMERA_DIRECTIVE_SCHEMA_VERSION:
        raise ValueError(
            "Camera directives schemaVersion must be "
            f"{CAMERA_DIRECTIVE_SCHEMA_VERSION!r}."
        )
    defaults = shot_control_from_mapping(
        payload.get("defaults", {}),
        global_control,
    )
    controls = [defaults] * shot_count
    seen: set[int] = set()
    shots = payload.get("shots", [])
    if not isinstance(shots, list):
        raise ValueError("Camera directives shots must be a JSON array.")
    for row in shots:
        if not isinstance(row, dict) or "index" not in row:
            raise ValueError("Each per-shot directive requires an index.")
        index = int(row["index"])
        if index in seen:
            raise ValueError(f"Duplicate directive for shot {index}.")
        if not 0 <= index < shot_count:
            raise ValueError(
                f"Directive shot index {index} is outside 0..{shot_count - 1}."
            )
        seen.add(index)
        controls[index] = shot_control_from_mapping(
            {key: item for key, item in row.items() if key != "index"},
            defaults,
        )
    return controls


def automatic_opening_requires_motion(
    shot_index: int,
    control: ShotControl,
) -> bool:
    """Keep an automatic opening visibly alive without overriding intent."""

    return (
        shot_index == 0
        and automatic_motion_policy_enabled(control)
    )


def automatic_motion_policy_enabled(control: ShotControl) -> bool:
    """Return whether automatic motion policy may refine this user intent."""

    return control.motion == "auto" and control.motion_intensity > 1e-3


def rolling_static_budget_requires_motion(
    realized_motion_families: list[str],
    control: ShotControl,
) -> bool:
    """Reserve at most one possible static result in every four shots.

    The caller supplies the seed-independent realization history. A static
    entry means the corresponding safe variation pool could render static for
    at least one Seed. Treating that possibility as a reservation is slightly
    conservative, but guarantees the budget for every Seed while preserving a
    shared candidate cache.
    """

    if not automatic_motion_policy_enabled(control):
        return False
    previous_window = realized_motion_families[
        -(ROLLING_STATIC_BUDGET_WINDOW_SIZE - 1) :
    ]
    static_count = sum(
        planner.normalize_motion_family(family) == "static"
        for family in previous_window
    )
    return static_count >= ROLLING_STATIC_BUDGET_MAX_STATIC_SHOTS


def _guard_automatic_motion_directive(
    directive: planner.ShotDirective | None,
    control: ShotControl,
    required: bool,
) -> tuple[planner.ShotDirective | None, bool]:
    """Replace only a model-selected static directive with its best motion."""

    if (
        directive is None
        or not required
        or not automatic_motion_policy_enabled(control)
        or directive.motion_family != "static"
    ):
        return directive, False

    probabilities = dict(directive.motion_probabilities)
    moving_families = [
        family
        for family in planner.MOTION_FAMILIES
        if family != "static"
    ]
    replacement = max(
        moving_families,
        key=lambda family: (
            probabilities.get(family, 0.0),
            -moving_families.index(family),
        ),
    )
    replacement_probability = float(probabilities.get(replacement, 0.0))
    original_probability = max(float(directive.motion_probability), 1e-9)
    adjusted_score = (
        directive.score
        + math.log(max(replacement_probability, 1e-9))
        - math.log(original_probability)
    )
    return (
        planner.ShotDirective(
            shot_type=directive.shot_type,
            motion_family=replacement,
            shot_probability=directive.shot_probability,
            motion_probability=replacement_probability,
            score=adjusted_score,
            shot_probabilities=dict(directive.shot_probabilities),
            motion_probabilities=probabilities,
        ),
        True,
    )


def guard_automatic_opening_directive(
    directive: planner.ShotDirective | None,
    control: ShotControl,
) -> tuple[planner.ShotDirective | None, bool]:
    """Replace only a model-selected static opening with its best motion."""

    return _guard_automatic_motion_directive(
        directive,
        control,
        automatic_opening_requires_motion(0, control),
    )


def guard_rolling_static_budget_directive(
    directive: planner.ShotDirective | None,
    control: ShotControl,
    realized_motion_families: list[str],
) -> tuple[planner.ShotDirective | None, bool]:
    """Guard a static planner choice when the rolling budget is exhausted."""

    return _guard_automatic_motion_directive(
        directive,
        control,
        rolling_static_budget_requires_motion(
            realized_motion_families,
            control,
        ),
    )


def automatic_motion_requirement_reason(
    opening_required: bool,
    rolling_static_budget_required: bool,
) -> str | None:
    if opening_required:
        return "opening"
    if rolling_static_budget_required:
        return "rolling_static_budget"
    return None


def automatic_non_static_plan_requires_visible_motion(
    control: ShotControl,
    desired_motion_family: str | None,
) -> bool:
    return (
        automatic_motion_policy_enabled(control)
        and desired_motion_family is not None
        and planner.normalize_motion_family(desired_motion_family) != "static"
    )


def visible_non_static_results(
    results: list[dict],
    required: bool,
) -> list[dict]:
    """Require both a moving label and measurable rendered expression."""

    if not required:
        return results
    return [
        result
        for result in results
        if planner.normalize_motion_family(result["realizedMotionType"])
        != "static"
        and float(
            result.get("motionQuality", {}).get(
                "motionExpressiveness",
                1.0,
            )
        )
        >= MINIMUM_AUTOMATIC_OPENING_EXPRESSIVENESS
    ]


def moving_opening_results(
    results: list[dict],
    required: bool,
) -> list[dict]:
    """Backward-compatible opening-policy wrapper."""

    return visible_non_static_results(results, required)


def variation_pool_static_budget_family(
    variation_pool: list[dict],
    continuation_motion_family: str,
) -> str:
    """Record a seed-independent worst-case family for rolling budgeting."""

    if any(
        planner.normalize_motion_family(result["realizedMotionType"])
        == "static"
        for result in variation_pool
    ):
        return "static"
    return planner.normalize_motion_family(continuation_motion_family)


def composition_policy(control: ShotControl, legacy_policy: str) -> str:
    return {
        "auto": legacy_policy,
        "center": "centered",
        "left_third": "left_third",
        "right_third": "right_third",
    }[control.composition]


def reconcile_planner_directive(
    directive: planner.ShotDirective,
    control: ShotControl,
    realized_shot_type: str,
    realized_motion_family: str,
) -> PlannerDirectiveReconciliation:
    """Make hierarchical history reflect overrides and actual realization.

    The beam initially plans the whole sequence.  A per-shot user override can
    intentionally invalidate that sequence context even when the selected
    template perfectly matches the override.  The realized directive returned
    here is therefore the only value that should enter subsequent history and
    user-facing effective-plan metadata.
    """

    realized_shot_type = planner.normalize_shot_type(realized_shot_type)
    realized_motion_family = planner.normalize_motion_family(
        realized_motion_family
    )
    requested_shot_type = (
        planner.normalize_shot_type(control.shot_size)
        if control.shot_size != "auto"
        else directive.shot_type
    )
    requested_motion_family = (
        planner.normalize_motion_family(control.motion)
        if control.motion != "auto"
        else directive.motion_family
    )
    user_override_changed_plan = (
        requested_shot_type != directive.shot_type
        or requested_motion_family != directive.motion_family
    )
    realization_changed_plan = (
        realized_shot_type != directive.shot_type
        or realized_motion_family != directive.motion_family
    )
    reasons = []
    if user_override_changed_plan:
        reasons.append("user_override")
    if realization_changed_plan:
        reasons.append("realization_mismatch")
    replan_reason = "+".join(reasons) if reasons else None
    realized_directive = planner.ShotDirective(
        shot_type=realized_shot_type,
        motion_family=realized_motion_family,
        shot_probability=directive.shot_probabilities.get(
            realized_shot_type,
            directive.shot_probability
            if realized_shot_type == directive.shot_type
            else 0.0,
        ),
        motion_probability=directive.motion_probabilities.get(
            realized_motion_family,
            directive.motion_probability
            if realized_motion_family == directive.motion_family
            else 0.0,
        ),
        score=directive.score,
        shot_probabilities=directive.shot_probabilities,
        motion_probabilities=directive.motion_probabilities,
    )
    return PlannerDirectiveReconciliation(
        realized_directive=realized_directive,
        user_override_changed_plan=user_override_changed_plan,
        realization_changed_plan=realization_changed_plan,
        should_replan=bool(reasons),
        replan_reason=replan_reason,
    )


def replan_hierarchical_tail(
    directives: list[planner.ShotDirective | None],
    shot_index: int,
    hierarchical_planner: planner.HierarchicalShotPlanner,
    segment_features: list[np.ndarray],
    segment_progress: list[float],
    segment_durations: list[float],
    beam_width: int,
    realized_history: list[planner.ShotDirective],
) -> bool:
    """Replace the remaining beam plan using realized sequence history."""

    future_start = shot_index + 1
    future_count = len(segment_features) - future_start
    if future_count <= 0:
        return False
    replanned = list(
        hierarchical_planner.plan(
            segment_features[future_start:],
            segment_progress[future_start:],
            segment_durations[future_start:],
            beam_width=beam_width,
            initial_history=realized_history,
        )
    )
    if len(replanned) != future_count:
        raise RuntimeError(
            "Hierarchical planner returned an incomplete replanned tail: "
            f"expected {future_count}, got {len(replanned)}."
        )
    directives[future_start:] = replanned
    return True


def mirrored_motion_type(motion_type: str) -> str:
    return {
        "orbit_left": "orbit_right",
        "orbit_right": "orbit_left",
        "truck_left": "truck_right",
        "truck_right": "truck_left",
    }.get(motion_type, motion_type)


def template_realization(
    template: ShotTemplate,
    previous: RealizedShotState | None,
    mirrored_override: bool | None = None,
) -> tuple[bool, float, str]:
    """Resolve one source template without mechanically alternating sides.

    Earlier generations mirrored every template found on the same side as the
    previous shot.  That made ``realizedSideSign`` alternate on virtually every
    cut, regardless of camera geometry or editorial intent.  Side changes are
    now an explicit override; the default preserves the authored template and
    pairwise rendered transition scoring decides which retrieved camera belongs
    after the actually selected previous camera.
    """

    del previous  # retained for call-site/API compatibility
    source_side = float(np.sign(template.anchor[0]))
    mirrored = bool(mirrored_override) if mirrored_override is not None else False
    side_sign = -source_side if mirrored else source_side
    motion_type = (
        mirrored_motion_type(template.motion_type)
        if mirrored
        else template.motion_type
    )
    return mirrored, side_sign, motion_type


def segment_features(
    prepared: train.PreparedSong,
    start: int,
    end: int,
) -> np.ndarray:
    start = max(0, start)
    end = min(len(prepared.inputs), max(start + 1, end))
    velocity = prepared.inputs[start:end, 63:126].reshape(-1, 21, 3)
    speed = np.linalg.norm(velocity, axis=-1)
    hands = speed[:, [8, 12]]
    feet = speed[:, [16, 20]]
    rms = prepared.inputs[start:end, -2]
    onset = prepared.inputs[start:end, -1]
    return np.asarray(
        [
            (end - start) / 60.0,
            float(np.mean(speed)),
            float(np.quantile(speed, 0.9)),
            float(np.mean(hands)),
            float(np.mean(feet)),
            float(np.mean(rms)),
            float(np.quantile(rms, 0.9)),
            float(np.mean(onset)),
            float(np.quantile(onset, 0.9)),
        ],
        dtype=np.float32,
    )


def normalized_research_ablation_profile(args: argparse.Namespace) -> str:
    """Return the validated research profile without changing old callers."""

    profile = str(getattr(args, "research_ablation_profile", "none"))
    if profile not in RESEARCH_ABLATION_PROFILES:
        raise ValueError(f"Unsupported research ablation profile: {profile}")
    return profile


def effective_same_audio_prior(args: argparse.Namespace) -> str:
    """Resolve profiles that deliberately suppress exact-audio retrieval."""

    requested = str(getattr(args, "same_audio_prior", "auto"))
    if requested not in {"auto", "off"}:
        raise ValueError(f"Unsupported same-audio prior mode: {requested}")
    if normalized_research_ablation_profile(args) in {
        "no_audio",
        "no_same_audio",
    }:
        return "off"
    return requested


def apply_research_ablation_to_segment_features(
    features: np.ndarray,
    feature_mean: np.ndarray,
    profile: str,
) -> np.ndarray:
    """Mask target planner/retrieval features without mutating either input."""

    if profile not in RESEARCH_ABLATION_PROFILES:
        raise ValueError(f"Unsupported research ablation profile: {profile}")
    values = np.asarray(features)
    means = np.asarray(feature_mean)
    if values.shape != (9,) or means.shape != (9,):
        raise ValueError("Segment feature ablation requires two 9D vectors.")
    if profile in {"none", "no_same_audio"}:
        return values
    masked = values.copy()
    feature_bounds = (
        SEGMENT_FEATURE_AUDIO_BOUNDS
        if profile == "no_audio"
        else SEGMENT_FEATURE_MOTION_BOUNDS
    )
    feature_slice = slice(*feature_bounds)
    masked[feature_slice] = means[feature_slice]
    return masked


def apply_research_ablation_to_cut_signals(
    inputs: np.ndarray,
    beat_frames: np.ndarray,
    peak_frames: np.ndarray,
    profile: str,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Mask cut evidence on a copy while preserving geometry source arrays."""

    if profile not in RESEARCH_ABLATION_PROFILES:
        raise ValueError(f"Unsupported research ablation profile: {profile}")
    values = np.asarray(inputs)
    if values.ndim != 2 or values.shape[1] != 160:
        raise ValueError("Cut signal ablation requires [frame, 160] inputs.")
    beats = np.asarray(beat_frames, dtype=np.int64)
    peaks = np.asarray(peak_frames, dtype=np.int64)
    if profile in {"none", "no_same_audio"}:
        return values, beats, peaks
    masked = values.copy()
    if profile == "no_audio":
        masked[:, slice(*CUT_INPUT_AUDIO_BOUNDS)] = 0.0
        return (
            masked,
            np.empty(0, dtype=np.int64),
            np.empty(0, dtype=np.int64),
        )
    masked[:, slice(*CUT_INPUT_MOTION_BOUNDS)] = 0.0
    return masked, beats, peaks


def research_ablation_metadata(profile: str) -> dict[str, object]:
    """Describe an active research ablation; omit metadata for production."""

    if profile not in RESEARCH_ABLATION_PROFILES:
        raise ValueError(f"Unsupported research ablation profile: {profile}")
    if profile == "none":
        return {}
    masked_evidence = {
        "no_audio": [
            "cut.beat",
            "cut.peak",
            "cut.onset",
            "cut.mel",
            "segment.audio",
            "exactSameAudioPrior",
        ],
        "no_motion": ["cut.motion", "segment.motion"],
        "no_same_audio": ["exactSameAudioPrior"],
    }[profile]
    return {
        "researchAblationProfile": profile,
        "researchAblationContract": {
            "version": RESEARCH_ABLATION_CONTRACT_VERSION,
            "researchOnly": True,
            "productionDefault": "none",
            "maskedEvidence": masked_evidence,
            "segmentFeaturesNeutralizedToLibraryMean": profile
            in {"no_audio", "no_motion"},
            "targetPreparedArraysMutated": False,
            "safetyGeometryPreserved": True,
        },
    }


def trim_source_pose_boundaries(
    positions: np.ndarray,
    rotations: np.ndarray,
    body_scale: float,
    maximum_extra_trim: int = 4,
) -> tuple[slice, int, int]:
    if len(positions) < 8:
        return slice(0, len(positions)), 0, 0

    trim_start = 1
    trim_end = 1
    for _ in range(maximum_extra_trim):
        end_index = len(positions) - trim_end
        if end_index - trim_start < 6:
            break
        position_step = float(
            np.linalg.norm(
                positions[trim_start + 1] - positions[trim_start]
            )
            * body_scale
        )
        rotation_dot = float(
            np.clip(
                abs(
                    np.dot(
                        rotations[trim_start + 1],
                        rotations[trim_start],
                    )
                ),
                0.0,
                1.0,
            )
        )
        rotation_step = math.degrees(2.0 * math.acos(rotation_dot))
        if position_step <= 0.08 and rotation_step <= 6.0:
            break
        trim_start += 1

    for _ in range(maximum_extra_trim):
        end_index = len(positions) - trim_end
        if end_index - trim_start < 6:
            break
        position_step = float(
            np.linalg.norm(
                positions[end_index - 1] - positions[end_index - 2]
            )
            * body_scale
        )
        rotation_dot = float(
            np.clip(
                abs(
                    np.dot(
                        rotations[end_index - 1],
                        rotations[end_index - 2],
                    )
                ),
                0.0,
                1.0,
            )
        )
        rotation_step = math.degrees(2.0 * math.acos(rotation_dot))
        if position_step <= 0.08 and rotation_step <= 6.0:
            break
        trim_end += 1

    return (
        slice(trim_start, len(positions) - trim_end),
        trim_start,
        trim_end,
    )


def camera_rotation_with_dutch(
    rotations: np.ndarray,
    dutch_degrees: np.ndarray,
) -> np.ndarray:
    roll = Rotation.from_euler(
        "z",
        np.asarray(dutch_degrees).reshape(-1, 1),
        degrees=True,
    ).as_quat()
    result = train.quat_multiply(rotations, roll)
    result /= np.maximum(
        np.linalg.norm(result, axis=1, keepdims=True),
        1e-8,
    )
    return result.astype(np.float32)


def project_world_point(
    camera_positions: np.ndarray,
    camera_rotations: np.ndarray,
    fov_degrees: np.ndarray,
    points: np.ndarray,
    aspect_ratio: float = 16.0 / 9.0,
) -> tuple[np.ndarray, np.ndarray]:
    relative = points - camera_positions
    shape = relative.shape
    forward = train.quat_rotate(
        camera_rotations,
        np.broadcast_to(
            np.asarray([0.0, 0.0, 1.0], dtype=np.float32),
            shape,
        ),
    )
    right = train.quat_rotate(
        camera_rotations,
        np.broadcast_to(
            np.asarray([1.0, 0.0, 0.0], dtype=np.float32),
            shape,
        ),
    )
    up = train.quat_rotate(
        camera_rotations,
        np.broadcast_to(
            np.asarray([0.0, 1.0, 0.0], dtype=np.float32),
            shape,
        ),
    )
    depth = np.sum(relative * forward, axis=1)
    tangent = np.tan(np.deg2rad(fov_degrees) * 0.5)
    safe_depth = np.maximum(depth, 1e-5)
    u = (
        0.5
        + np.sum(relative * right, axis=1)
        / (2.0 * safe_depth * tangent * aspect_ratio)
    )
    v = (
        0.5
        + np.sum(relative * up, axis=1)
        / (2.0 * safe_depth * tangent)
    )
    return np.stack((u, v), axis=1).astype(np.float32), depth


def project_world_points(
    camera_positions: np.ndarray,
    camera_rotations: np.ndarray,
    fov_degrees: np.ndarray,
    points: np.ndarray,
    aspect_ratio: float = 16.0 / 9.0,
) -> tuple[np.ndarray, np.ndarray]:
    """Vectorized projection for multiple points on every camera frame."""

    relative = points - camera_positions[:, None, :]
    rotation = camera_rotations[:, None, :]
    vector_shape = relative.shape
    forward = train.quat_rotate(
        rotation,
        np.broadcast_to(
            np.asarray([0.0, 0.0, 1.0], dtype=np.float32),
            vector_shape,
        ),
    )
    right = train.quat_rotate(
        rotation,
        np.broadcast_to(
            np.asarray([1.0, 0.0, 0.0], dtype=np.float32),
            vector_shape,
        ),
    )
    up = train.quat_rotate(
        rotation,
        np.broadcast_to(
            np.asarray([0.0, 1.0, 0.0], dtype=np.float32),
            vector_shape,
        ),
    )
    depth = np.sum(relative * forward, axis=2)
    tangent = np.tan(np.deg2rad(fov_degrees) * 0.5)[:, None]
    safe_depth = np.maximum(depth, 1e-5)
    u = (
        0.5
        + np.sum(relative * right, axis=2)
        / (2.0 * safe_depth * tangent * aspect_ratio)
    )
    v = (
        0.5
        + np.sum(relative * up, axis=2)
        / (2.0 * safe_depth * tangent)
    )
    return np.stack((u, v), axis=2).astype(np.float32), depth


def build_source_composition_path(
    camera_positions: np.ndarray,
    camera_rotations: np.ndarray,
    fov_degrees: np.ndarray,
    dutch_degrees: np.ndarray,
    joints: np.ndarray,
    shot_type: str,
    aspect_ratio: float,
) -> np.ndarray:
    if shot_type == "wide":
        focus = joints[:, 0] * 0.55 + joints[:, 2] * 0.45
        required_indices = tuple(range(joints.shape[1]))
    elif shot_type == "close":
        focus = joints[:, 4] * 0.72 + joints[:, 2] * 0.28
        required_indices = (2, 4)
    else:
        focus = joints[:, 2] * 0.75 + joints[:, 4] * 0.25
        required_indices = (2, 4)

    effective_rotation = camera_rotation_with_dutch(
        camera_rotations,
        dutch_degrees,
    )
    focus_uv, focus_depth = project_world_point(
        camera_positions,
        effective_rotation,
        fov_degrees,
        focus,
        aspect_ratio,
    )
    visible = (
        (focus_depth > 0.0)
        & (focus_uv[:, 0] >= 0.0)
        & (focus_uv[:, 0] <= 1.0)
        & (focus_uv[:, 1] >= 0.0)
        & (focus_uv[:, 1] <= 1.0)
    )
    required_uv, required_depth = project_world_points(
        camera_positions,
        effective_rotation,
        fov_degrees,
        joints[:, np.asarray(required_indices, dtype=np.int64)],
        aspect_ratio,
    )
    visible &= np.all(
        (
            (required_depth > 0.0)
            & (required_uv[:, :, 0] >= -0.05)
            & (required_uv[:, :, 0] <= 1.05)
            & (required_uv[:, :, 1] >= -0.05)
            & (required_uv[:, :, 1] <= 1.05)
        ),
        axis=1,
    )

    head_uv, _ = project_world_point(
        camera_positions,
        effective_rotation,
        fov_degrees,
        joints[:, 4],
        aspect_ratio,
    )
    pelvis_uv, _ = project_world_point(
        camera_positions,
        effective_rotation,
        fov_degrees,
        joints[:, 0],
        aspect_ratio,
    )
    screen_delta = head_uv - pelvis_uv
    figure_height = np.linalg.norm(
        np.column_stack(
            (
                screen_delta[:, 0] * aspect_ratio,
                screen_delta[:, 1],
            )
        ),
        axis=1,
    )
    return np.column_stack(
        (focus_uv, figure_height, visible.astype(np.float32))
    ).astype(np.float32)


def longest_true_run(values: np.ndarray) -> int:
    maximum = 0
    current = 0
    for value in np.asarray(values, dtype=bool):
        if value:
            current += 1
            maximum = max(maximum, current)
        else:
            current = 0
    return maximum


def horizontal_unit_vectors(
    values: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
    horizontal = np.asarray(values, dtype=np.float64).copy()
    if horizontal.ndim != 2 or horizontal.shape[1] != 3:
        raise ValueError("Horizontal vectors must have shape [frame, 3].")
    horizontal[:, 1] = 0.0
    lengths = np.linalg.norm(horizontal, axis=1)
    valid = (
        np.isfinite(horizontal).all(axis=1)
        & np.isfinite(lengths)
        & (lengths > 1e-5)
    )
    normalized = np.zeros_like(horizontal)
    normalized[valid] = horizontal[valid] / lengths[valid, None]
    return normalized, valid


def calibrate_front_facing_reference(
    root_local_joints: np.ndarray,
) -> dict[str, object]:
    """Calibrate one rig-independent local forward from the full target song."""

    body = np.asarray(root_local_joints, dtype=np.float64)
    if (
        body.ndim != 3
        or body.shape[1] < 10
        or body.shape[2] != 3
        or len(body) == 0
    ):
        raise ValueError(
            "Front-facing calibration requires non-empty canonical root-local "
            "joint [frame, joint, 3] data."
        )
    anatomical_right = body[:, 9] - body[:, 5]
    anatomical_up = body[:, 4] - body[:, 0]
    local_forward, valid = horizontal_unit_vectors(
        np.cross(anatomical_right, anatomical_up)
    )
    valid_ratio = float(np.mean(valid))
    mean_forward = (
        np.mean(local_forward[valid], axis=0)
        if np.any(valid)
        else np.zeros(3, dtype=np.float64)
    )
    mean_forward[1] = 0.0
    reliability = float(np.linalg.norm(mean_forward))
    direction = np.zeros(3, dtype=np.float64)
    if math.isfinite(reliability) and reliability > 1e-5:
        direction = mean_forward / reliability
    alignment = (
        np.sum(local_forward[valid] * direction, axis=1)
        if np.any(valid) and np.linalg.norm(direction) > 0.0
        else np.asarray([], dtype=np.float64)
    )
    available = bool(
        valid_ratio
        >= FRONT_FACING_STABLE_REFERENCE_MINIMUM_VALID_FRAME_RATIO
        and reliability >= FRONT_FACING_STABLE_REFERENCE_MINIMUM_RELIABILITY
    )
    return {
        "policyVersion": FRONT_FACING_POLICY_VERSION,
        "calibrationScope": "full_target_song",
        "available": available,
        "frameCount": int(len(body)),
        "validFrameRatio": valid_ratio,
        "reliability": reliability,
        "localForwardDirection": [float(value) for value in direction],
        "anatomicalAlignmentMedian": (
            float(np.median(alignment)) if len(alignment) else -1.0
        ),
        "anatomicalPositiveFrameRatio": (
            float(np.mean(alignment > 0.0)) if len(alignment) else 0.0
        ),
    }


def front_facing_safety_metrics(
    camera_positions: np.ndarray,
    joints: np.ndarray,
    root_rotations: np.ndarray | None = None,
    *,
    root_facing_reference: dict[str, object] | None = None,
    semantic_visibility_passed: bool | None = None,
    sample_rate: float = HYBRID_SAMPLE_RATE,
) -> dict[str, object]:
    """Measure whether a camera remains on the performer's anatomical front.

    Root transforms are not a dependable facing convention across imported
    rigs.  The signed torso normal derived from labelled left/right shoulders
    and pelvis/head is therefore the strict primary audit.  When root rotation
    and a full-song root-local calibration is available, that stable reference
    may admit a bounded, visible choreography turn.  Shot-local calibration is
    deliberately forbidden because a turn can cancel its own forward axis.
    The exception cannot admit a camera that itself crosses behind the stable
    performer front.  Camera motion never follows either per-frame direction.
    """

    positions = np.asarray(camera_positions, dtype=np.float64)
    body = np.asarray(joints, dtype=np.float64)
    if (
        positions.ndim != 2
        or positions.shape[1] != 3
        or body.ndim != 3
        or body.shape[1] < 10
        or body.shape[2] != 3
        or len(positions) == 0
        or len(body) != len(positions)
    ):
        raise ValueError(
            "Front-facing metrics require camera [frame, 3] and canonical "
            "joint [frame, joint, 3] arrays with matching non-zero frames."
        )
    if not math.isfinite(sample_rate) or sample_rate <= 0.0:
        raise ValueError("Front-facing sample_rate must be finite and positive.")

    root_values: np.ndarray | None = None
    if root_rotations is not None:
        root_values = np.asarray(root_rotations, dtype=np.float64)
        if root_values.shape != (len(positions), 4):
            raise ValueError(
                "Front-facing root rotations must have shape [frame, 4]."
            )

    anatomical_right = body[:, 9] - body[:, 5]
    anatomical_up = body[:, 4] - body[:, 0]
    anatomical_forward, forward_valid = horizontal_unit_vectors(
        np.cross(anatomical_right, anatomical_up)
    )
    camera_offset, offset_valid = horizontal_unit_vectors(
        positions - body[:, 2]
    )
    valid = forward_valid & offset_valid
    alignment = np.full(len(positions), -1.0, dtype=np.float64)
    alignment[valid] = np.sum(
        anatomical_forward[valid] * camera_offset[valid],
        axis=1,
    )
    alignment = np.clip(alignment, -1.0, 1.0)
    rear = alignment < 0.0
    severe_rear = alignment < FRONT_FACING_SEVERE_REAR_ALIGNMENT
    median = float(np.median(alignment))
    p10 = float(np.quantile(alignment, 0.10))
    severe_ratio = float(np.mean(severe_rear))
    severe_longest = longest_true_run(severe_rear)
    allowed_longest = max(
        1,
        int(round(FRONT_FACING_MAXIMUM_SEVERE_REAR_RUN_SECONDS * sample_rate)),
    )
    strict_anatomical_passed = bool(
        np.all(valid)
        and median >= FRONT_FACING_ALIGNMENT_MEDIAN_MINIMUM
        and severe_ratio <= FRONT_FACING_MAXIMUM_SEVERE_REAR_FRAME_RATIO
        and severe_longest <= allowed_longest
    )

    stable_reference_available = False
    stable_reference_reliability = 0.0
    stable_alignment_median = -1.0
    stable_alignment_p10 = -1.0
    stable_alignment_minimum = -1.0
    stable_rear_ratio = 1.0
    stable_severe_ratio = 1.0
    stable_severe_longest = len(positions)
    stable_reference_passed = False
    turn_deviation_ratio = 0.0
    choreography_turn_detected = False
    visibility_confirmed = type(semantic_visibility_passed) is bool and bool(
        semantic_visibility_passed
    )

    reference_direction = np.zeros(3, dtype=np.float64)
    reference_valid_frame_ratio = 0.0
    if isinstance(root_facing_reference, dict):
        direction_value = np.asarray(
            root_facing_reference.get("localForwardDirection", []),
            dtype=np.float64,
        )
        reliability_value = root_facing_reference.get("reliability")
        valid_ratio_value = root_facing_reference.get("validFrameRatio")
        if (
            direction_value.shape == (3,)
            and np.isfinite(direction_value).all()
            and isinstance(reliability_value, (int, float))
            and not isinstance(reliability_value, bool)
            and math.isfinite(float(reliability_value))
            and isinstance(valid_ratio_value, (int, float))
            and not isinstance(valid_ratio_value, bool)
            and math.isfinite(float(valid_ratio_value))
        ):
            direction_length = float(np.linalg.norm(direction_value))
            stable_reference_reliability = float(reliability_value)
            reference_valid_frame_ratio = float(valid_ratio_value)
            if direction_length > 1e-5:
                reference_direction = direction_value / direction_length
            stable_reference_available = bool(
                root_facing_reference.get("available") is True
                and root_facing_reference.get("calibrationScope")
                == "full_target_song"
                and root_facing_reference.get("policyVersion")
                == FRONT_FACING_POLICY_VERSION
                and stable_reference_reliability
                >= FRONT_FACING_STABLE_REFERENCE_MINIMUM_RELIABILITY
                and reference_valid_frame_ratio
                >= FRONT_FACING_STABLE_REFERENCE_MINIMUM_VALID_FRAME_RATIO
                and direction_length > 1e-5
            )

    if root_values is not None and stable_reference_available:
        root_norm = np.linalg.norm(root_values, axis=1)
        root_valid = (
            np.isfinite(root_values).all(axis=1)
            & np.isfinite(root_norm)
            & (root_norm > 1e-5)
        )
        normalized_root = np.zeros_like(root_values)
        normalized_root[root_valid] = (
            root_values[root_valid] / root_norm[root_valid, None]
        )
        stable_forward = train.quat_rotate(
            normalized_root,
            np.broadcast_to(reference_direction, (len(positions), 3)),
        )
        stable_forward, stable_valid = horizontal_unit_vectors(stable_forward)
        stable_valid &= valid & root_valid
        if np.all(stable_valid):
            stable_alignment = np.sum(
                stable_forward * camera_offset,
                axis=1,
            )
            stable_alignment = np.clip(
                stable_alignment,
                -1.0,
                1.0,
            )
            stable_rear = stable_alignment < 0.0
            stable_severe = (
                stable_alignment < FRONT_FACING_SEVERE_REAR_ALIGNMENT
            )
            stable_alignment_median = float(np.median(stable_alignment))
            stable_alignment_p10 = float(
                np.quantile(stable_alignment, 0.10)
            )
            stable_alignment_minimum = float(np.min(stable_alignment))
            stable_rear_ratio = float(np.mean(stable_rear))
            stable_severe_ratio = float(np.mean(stable_severe))
            stable_severe_longest = longest_true_run(stable_severe)
            stable_reference_passed = bool(
                stable_alignment_median
                >= FRONT_FACING_STABLE_ALIGNMENT_MEDIAN_MINIMUM
                and stable_severe_ratio
                <= FRONT_FACING_MAXIMUM_SEVERE_REAR_FRAME_RATIO
                and stable_severe_longest <= allowed_longest
            )
            anatomy_to_stable = np.sum(
                anatomical_forward * stable_forward,
                axis=1,
            )
            turn_deviation_ratio = float(
                np.mean(
                    anatomy_to_stable
                    < FRONT_FACING_CHOREOGRAPHY_TURN_DEVIATION_ALIGNMENT
                )
            )
            choreography_turn_detected = bool(
                turn_deviation_ratio
                >= FRONT_FACING_CHOREOGRAPHY_MINIMUM_TURN_FRAME_RATIO
            )
        else:
            stable_reference_available = False

    choreography_turn_exception = bool(
        not strict_anatomical_passed
        and visibility_confirmed
        and stable_reference_available
        and stable_reference_passed
        and choreography_turn_detected
    )
    # A reliable full-song reference is authoritative for camera placement.
    # This keeps a truly rear camera rejected even if the performer happens to
    # turn and face it.  Instantaneous anatomy remains a soft preference; its
    # strict gate is used only when no reliable calibration is available.
    passed = bool(
        (
            stable_reference_passed
            and (strict_anatomical_passed or choreography_turn_exception)
        )
        if stable_reference_available
        else strict_anatomical_passed
    )
    return {
        "frontFacingPolicyVersion": FRONT_FACING_POLICY_VERSION,
        "frontFacingAlignment": median,
        "frontFacingAlignmentP10": p10,
        "frontFacingAlignmentMinimum": float(np.min(alignment)),
        "frontFacingRearFrameRatio": float(np.mean(rear)),
        "frontFacingSevereRearFrameRatio": severe_ratio,
        "frontFacingSevereRearLongestRunFrames": int(severe_longest),
        "frontFacingSevereRearAllowedLongestRunFrames": int(allowed_longest),
        "frontFacingInvalidFrameCount": int(np.sum(~valid)),
        "frontFacingStrictAnatomicalPassed": strict_anatomical_passed,
        "frontFacingStableReferenceAvailable": stable_reference_available,
        "frontFacingStableReferenceReliability": float(
            stable_reference_reliability
        ),
        "frontFacingStableReferenceValidFrameRatio": float(
            reference_valid_frame_ratio
        ),
        "frontFacingStableAlignment": stable_alignment_median,
        "frontFacingStableAlignmentP10": stable_alignment_p10,
        "frontFacingStableAlignmentMinimum": stable_alignment_minimum,
        "frontFacingStableRearFrameRatio": stable_rear_ratio,
        "frontFacingStableSevereRearFrameRatio": stable_severe_ratio,
        "frontFacingStableSevereRearLongestRunFrames": int(
            stable_severe_longest
        ),
        "frontFacingStableReferencePassed": stable_reference_passed,
        "frontFacingChoreographyTurnDeviationFrameRatio": (
            turn_deviation_ratio
        ),
        "frontFacingChoreographyTurnDetected": choreography_turn_detected,
        "frontFacingChoreographyVisibilityPassed": visibility_confirmed,
        "frontFacingChoreographyTurnExceptionApplied": (
            choreography_turn_exception
        ),
        "frontFacingGateBasis": (
            "full_song_stable_reference"
            if stable_reference_available
            else "strict_anatomical_fallback"
        ),
        "frontFacingPassed": passed,
    }


def front_facing_selection_penalty(
    metrics: dict[str, object],
    frame_count: int,
) -> float:
    """Return a bounded facing tie-break without fighting choreography.

    Once a reliable full-song reference exists, that stable stage-relative
    direction is authoritative for camera placement.  Instantaneous shoulder
    anatomy may turn independently during choreography and must not make a
    correct stage-front camera score worse than a profile camera.  Outside a
    detected turn it remains only a small tie-break.  The legacy anatomical
    score is retained as the fail-closed fallback when calibration is absent.
    """

    if type(frame_count) is not int or frame_count < 1:
        raise ValueError("front-facing penalty frame_count must be positive")

    def finite_metric(name: str) -> float:
        value = metrics.get(name)
        if not isinstance(value, (int, float)) or isinstance(value, bool):
            raise ValueError(f"front-facing metric {name} is invalid")
        result = float(value)
        if not math.isfinite(result):
            raise ValueError(f"front-facing metric {name} is not finite")
        return result

    def placement_penalty(
        alignment_name: str,
        severe_ratio_name: str,
        severe_run_name: str,
    ) -> float:
        return float(
            max(0.0, -finite_metric(alignment_name)) * 5.0
            + max(0.0, finite_metric(severe_ratio_name)) * 12.0
            + min(
                1.0,
                max(0.0, finite_metric(severe_run_name))
                / float(frame_count),
            )
            * 8.0
        )

    anatomical_penalty = placement_penalty(
        "frontFacingAlignment",
        "frontFacingSevereRearFrameRatio",
        "frontFacingSevereRearLongestRunFrames",
    )
    if metrics.get("frontFacingStableReferenceAvailable") is not True:
        return anatomical_penalty

    stable_penalty = placement_penalty(
        "frontFacingStableAlignment",
        "frontFacingStableSevereRearFrameRatio",
        "frontFacingStableSevereRearLongestRunFrames",
    )
    if metrics.get("frontFacingChoreographyTurnExceptionApplied") is True:
        return stable_penalty

    # When anatomy agrees with the stable reference, retain at most a tiny
    # deterministic tie-break.  It cannot dominate the 2-point quality window.
    return float(stable_penalty + min(anatomical_penalty * 0.05, 0.25))


def strict_person_envelope_metrics(
    camera_positions: np.ndarray,
    camera_rotations: np.ndarray,
    fov_degrees: np.ndarray,
    dutch_degrees: np.ndarray,
    joints: np.ndarray,
    shot_type: str,
    aspect_ratio: float,
) -> dict[str, float | int | bool]:
    """Fail closed when the shot-specific body envelope leaves the viewport."""

    effective_rotation = camera_rotation_with_dutch(
        camera_rotations,
        dutch_degrees,
    )
    required_joints = joints[
        :,
        np.asarray(STRICT_ENVELOPE_JOINTS[shot_type], dtype=np.int64),
    ]
    projected, depth = project_world_points(
        camera_positions,
        effective_rotation,
        fov_degrees,
        required_joints,
        aspect_ratio,
    )
    u = projected[:, :, 0]
    v = projected[:, :, 1]
    inside = (
        (depth > 0.0)
        & (u >= 0.0)
        & (u <= 1.0)
        & (v >= 0.0)
        & (v <= 1.0)
    )
    margins = np.minimum.reduce((u, 1.0 - u, v, 1.0 - v))
    margins[depth <= 0.0] = -1.0
    frame_safe = np.all(inside, axis=1)
    exit_frames = ~frame_safe
    minimum_margin = float(np.min(margins))
    exit_ratio = float(np.mean(exit_frames))
    longest_exit = longest_true_run(exit_frames)
    return {
        "strictPersonVisibility": float(np.mean(frame_safe)),
        "strictExitFrameRatio": exit_ratio,
        "strictExitLongestRunFrames": longest_exit,
        "strictMinimumViewportMargin": minimum_margin,
        "hardPersonSafetyPassed": bool(longest_exit == 0),
    }


def derive_output_semantic_framing(
    camera_positions: np.ndarray,
    camera_rotations: np.ndarray,
    fov_degrees: np.ndarray,
    dutch_degrees: np.ndarray,
    joints: np.ndarray,
    aspect_ratio: float,
) -> shot_features.FramingLabel:
    """Derive the final W/M/C label with the independent evaluator contract."""

    medium_composition = build_source_composition_path(
        camera_positions,
        camera_rotations,
        fov_degrees,
        dutch_degrees,
        joints,
        "medium",
        aspect_ratio,
    )
    return shot_features.derive_framing_label(
        medium_composition,
        "command_line",
    )


def semantic_projection_safety_metrics(
    camera_positions: np.ndarray,
    camera_rotations: np.ndarray,
    fov_degrees: np.ndarray,
    dutch_degrees: np.ndarray,
    joints: np.ndarray,
    declared_shot_type: str,
    aspect_ratio: float,
) -> tuple[np.ndarray, dict[str, float | int | bool | str]]:
    """Audit a candidate using the evaluator's derived semantic label.

    Source-template labels describe retrieval intent, but FOV/distance
    retargeting can change the rendered shot class.  Safety must therefore be
    evaluated from the final medium projection, then against the envelope of
    that independently derived W/M/C label.
    """

    framing = derive_output_semantic_framing(
        camera_positions,
        camera_rotations,
        fov_degrees,
        dutch_degrees,
        joints,
        aspect_ratio,
    )
    realized_shot_type = framing.shot_type
    composition = build_source_composition_path(
        camera_positions,
        camera_rotations,
        fov_degrees,
        dutch_degrees,
        joints,
        realized_shot_type,
        aspect_ratio,
    )
    left, right, bottom, top = HARD_PERSON_SAFE_BOUNDS[
        realized_shot_type
    ]
    visible = composition[:, 3] >= 0.5
    unsafe = (
        ~visible
        | (composition[:, 0] < left)
        | (composition[:, 0] > right)
        | (composition[:, 1] < bottom)
        | (composition[:, 1] > top)
    )
    strict = strict_person_envelope_metrics(
        camera_positions,
        camera_rotations,
        fov_degrees,
        dutch_degrees,
        joints,
        realized_shot_type,
        aspect_ratio,
    )
    person_visibility = float(np.mean(visible))
    unsafe_ratio = float(np.mean(unsafe))
    unsafe_count = int(np.sum(unsafe))
    safety_passed = bool(
        unsafe_count == 0
        and strict["hardPersonSafetyPassed"]
    )
    return composition, {
        **strict,
        "declaredTemplateShotType": declared_shot_type,
        "realizedSemanticShotType": realized_shot_type,
        "semanticShotTypeChangedAfterRetarget": bool(
            realized_shot_type != declared_shot_type
        ),
        "semanticSubjectHeightRatio": float(
            framing.subject_height_ratio
        ),
        "semanticFramingValidRatio": float(
            framing.valid_frame_ratio
        ),
        "semanticProjectionPersonVisibility": person_visibility,
        "semanticProjectionUnsafeFrameRatio": unsafe_ratio,
        "semanticProjectionUnsafeFrameCount": unsafe_count,
        "semanticProjectionUnsafeLongestRunFrames": int(
            longest_true_run(unsafe)
        ),
        "semanticProjectionSafetyPassed": safety_passed,
    }


def horizontal_composition_statistics(
    composition: np.ndarray,
    shot_type: str,
    bounds: tuple[float, float] | None = None,
) -> dict[str, float | None]:
    """Measure person-only horizontal framing independently of headroom."""

    left, right = (
        PERSON_ONLY_HORIZONTAL_BOUNDS[shot_type]
        if bounds is None
        else bounds
    )
    visible = (
        (composition[:, 3] >= 0.5)
        & np.isfinite(composition[:, 0])
    )
    if not np.any(visible):
        return {
            "horizontalFocusMedian": None,
            "horizontalCenterOffset": None,
            "horizontalCenterOffsetMean": None,
            "horizontalCenterOffsetP90": None,
            "horizontalCenterOffsetMax": None,
            "horizontalCorridorExcess": None,
            "horizontalOutOfCorridorRatio": 1.0,
            "horizontalOutOfCorridorLongestRunFrames": int(
                len(composition)
            ),
            "horizontalValidFrameRatio": 0.0,
        }
    values = composition[visible, 0].astype(np.float64)
    median = float(np.median(values))
    excess = max(left - median, median - right, 0.0)
    center_offset = np.abs(values - 0.5)
    frame_outside = (
        ~visible
        | (composition[:, 0] < left)
        | (composition[:, 0] > right)
    )
    return {
        "horizontalFocusMedian": median,
        "horizontalCenterOffset": abs(median - 0.5),
        "horizontalCenterOffsetMean": float(np.mean(center_offset)),
        "horizontalCenterOffsetP90": float(
            np.quantile(center_offset, 0.9)
        ),
        "horizontalCenterOffsetMax": float(np.max(center_offset)),
        "horizontalCorridorExcess": float(excess),
        "horizontalOutOfCorridorRatio": float(
            np.mean((values < left) | (values > right))
        ),
        "horizontalOutOfCorridorLongestRunFrames": int(
            longest_true_run(frame_outside)
        ),
        "horizontalValidFrameRatio": float(np.mean(visible)),
    }


def regularize_person_only_composition(
    composition: np.ndarray,
    shot_type: str,
    horizontal_framing: str,
) -> tuple[np.ndarray, dict[str, float | None]]:
    """Shift the authored U path once, preserving all within-shot deltas."""

    if horizontal_framing not in {
        "source",
        "balanced",
        "centered",
        "left_third",
        "right_third",
    }:
        raise ValueError(
            f"Unknown horizontal framing policy: {horizontal_framing}"
        )
    result = composition.copy().astype(np.float32)
    visible = (
        (composition[:, 3] >= 0.5)
        & np.isfinite(composition[:, 0])
    )
    source_median = (
        float(np.median(composition[visible, 0]))
        if np.any(visible)
        else None
    )
    target_median = source_median
    shift = 0.0
    if horizontal_framing != "source" and source_median is not None:
        if horizontal_framing in {"balanced", "centered"}:
            target_bounds = (
                BALANCED_HORIZONTAL_TARGET_BOUNDS
                if horizontal_framing == "balanced"
                else PERSON_ONLY_HORIZONTAL_TARGET_BOUNDS
            )
            left, right = target_bounds[shot_type]
            target_median = float(np.clip(source_median, left, right))
        elif horizontal_framing == "left_third":
            target_median = 1.0 / 3.0
        else:
            target_median = 2.0 / 3.0
        shift = target_median - source_median
        finite = np.isfinite(result[:, 0])
        result[finite, 0] += shift
    return result, {
        "horizontalFramingMedianBefore": source_median,
        "horizontalFramingMedianTarget": target_median,
        "horizontalReframeUvShift": float(shift),
    }


def thirds_horizontal_quality_penalty(
    target_median: float | None,
    final_median: float | None,
    reframe_degrees_mean: float,
) -> float:
    """Score a thirds target while allowing an all-invisible safe fallback."""

    medians = (target_median, final_median)
    if any(
        value is None or not math.isfinite(float(value))
        for value in medians
    ):
        composition_penalty = 20.0
    else:
        composition_penalty = (
            abs(float(final_median) - float(target_median)) * 40.0
        )
    return composition_penalty + float(reframe_degrees_mean) / 24.0


def horizontal_bounds_for_policy(
    shot_type: str,
    horizontal_framing: str,
) -> tuple[float, float]:
    """Return the scoring corridor without changing the hard safety envelope."""

    if horizontal_framing == "balanced":
        return BALANCED_HORIZONTAL_BOUNDS[shot_type]
    return PERSON_ONLY_HORIZONTAL_BOUNDS[shot_type]


def horizontal_target_bounds_for_policy(
    shot_type: str,
    horizontal_framing: str,
) -> tuple[float, float]:
    if horizontal_framing == "balanced":
        return BALANCED_HORIZONTAL_TARGET_BOUNDS[shot_type]
    return PERSON_ONLY_HORIZONTAL_TARGET_BOUNDS[shot_type]


def apply_shot_horizontal_reframe(
    camera_rotations: np.ndarray,
    fov_values: np.ndarray,
    dutch_values: np.ndarray,
    source_composition: np.ndarray,
    target_composition: np.ndarray,
    target_aspect_ratio: float,
    horizontal_framing: str,
) -> tuple[np.ndarray, dict[str, float]]:
    """Apply one shot-level horizontal viewport rotation.

    ``source_composition`` is the already-retargeted target projection before
    reframing.  Only its robust shot median is used.  The correction is one
    constant local viewport rotation for the whole shot, so frame-to-frame
    target motion cannot turn this into a LookAt-style tracker.
    """

    frame_count = len(camera_rotations)

    def visible_focus_median(
        composition: np.ndarray,
    ) -> np.ndarray | None:
        valid = (
            (composition[:, 3] >= 0.5)
            & np.isfinite(composition[:, 0])
            & np.isfinite(composition[:, 1])
        )
        return (
            np.median(composition[valid, :2], axis=0)
            if np.any(valid)
            else None
        )

    source_median = visible_focus_median(source_composition)
    target_median = visible_focus_median(target_composition)
    no_reframe = (
        horizontal_framing == "source"
        or frame_count == 0
        or source_median is None
        or target_median is None
        or abs(float(source_median[0] - target_median[0])) <= 1e-7
    )
    if no_reframe:
        return camera_rotations.copy().astype(np.float32), {
            "horizontalReframeDegreesMean": 0.0,
            "horizontalReframeDegreesMax": 0.0,
            "horizontalReframeApplied": False,
        }

    representative_fov = float(
        np.median(fov_values[np.isfinite(fov_values)])
    )
    tangent = math.tan(math.radians(representative_fov) * 0.5)
    source_ray = np.asarray(
        [
            [
                (float(source_median[0]) * 2.0 - 1.0)
                * tangent
                * target_aspect_ratio,
                (float(source_median[1]) * 2.0 - 1.0) * tangent,
                1.0,
            ]
        ],
        dtype=np.float32,
    )
    target_ray = np.asarray(
        [
            [
                (float(target_median[0]) * 2.0 - 1.0)
                * tangent
                * target_aspect_ratio,
                (float(target_median[1]) * 2.0 - 1.0) * tangent,
                1.0,
            ]
        ],
        dtype=np.float32,
    )
    local_correction = quaternion_between_vectors(
        target_ray,
        source_ray,
    )
    correction_rotvec = Rotation.from_quat(
        local_correction
    ).as_rotvec()
    maximum_degrees = {
        "centered": MAXIMUM_HORIZONTAL_REFRAME_DEGREES,
        "balanced": MAXIMUM_BALANCED_REFRAME_DEGREES,
    }.get(horizontal_framing, MAXIMUM_DIRECTED_REFRAME_DEGREES)
    maximum_angle = math.radians(maximum_degrees)
    magnitude = float(np.linalg.norm(correction_rotvec[0]))
    if magnitude > maximum_angle:
        correction_rotvec[0] *= maximum_angle / magnitude
        magnitude = maximum_angle
    local_correction = Rotation.from_rotvec(
        correction_rotvec
    ).as_quat()
    local_correction = np.broadcast_to(
        local_correction,
        (frame_count, 4),
    )
    roll = Rotation.from_euler(
        "z",
        np.asarray(dutch_values).reshape(-1, 1),
        degrees=True,
    ).as_quat()
    effective_rotation = train.quat_multiply(
        camera_rotations,
        roll,
    )
    reframed_effective_rotation = train.quat_multiply(
        effective_rotation,
        local_correction,
    )
    reframed_rotation = train.quat_multiply(
        reframed_effective_rotation,
        train.quat_conjugate(roll),
    )
    reframed_rotation /= np.maximum(
        np.linalg.norm(reframed_rotation, axis=1, keepdims=True),
        1e-8,
    )
    ensure_quaternion_continuity(
        reframed_rotation,
        0,
        len(reframed_rotation),
    )
    correction_degrees = math.degrees(magnitude)
    return reframed_rotation.astype(np.float32), {
        "horizontalReframeDegreesMean": float(correction_degrees),
        "horizontalReframeDegreesMax": float(correction_degrees),
        "horizontalReframeApplied": bool(correction_degrees > 1e-4),
    }


def explicit_audio_aligned_frame_mask_ranges(
    entry: dict,
    song_id: str,
    *,
    expected_frame_count: int | None = None,
) -> tuple[tuple[int, int], ...] | None:
    """Return a validated explicit mask, or ``None`` for legacy entries.

    Missing masks intentionally retain the historical full-record behavior.
    Once the field is present, malformed or stale frame-count metadata fails
    closed instead of silently widening the usable frame range.
    """

    if "audioAlignedFrameMaskRanges" not in entry:
        partial_fields = sorted(
            field
            for field in ("audioAlignedEndFrame", "audioAlignedFrameCount")
            if field in entry
        )
        if partial_fields:
            raise ValueError(
                f"Training index audio mask for {song_id} is incomplete: "
                "audioAlignedFrameMaskRanges is missing while "
                + ", ".join(partial_fields)
                + " is present."
            )
        return None
    frame_count = entry.get("frameCount")
    if (
        isinstance(frame_count, bool)
        or not isinstance(frame_count, int)
        or frame_count < 0
    ):
        raise ValueError(
            f"Training index audio mask for {song_id} requires a non-negative "
            "integer frameCount."
        )
    if expected_frame_count is not None and frame_count != expected_frame_count:
        raise ValueError(
            f"Training index audio mask frameCount mismatch for {song_id}: "
            f"index={frame_count}, prepared={expected_frame_count}."
        )
    ranges = train.normalize_audio_aligned_frame_mask_ranges(
        entry["audioAlignedFrameMaskRanges"],
        frame_count,
        label=f"Training index audio mask for {song_id}",
    )
    if "audioAlignedEndFrame" in entry:
        aligned_end = entry["audioAlignedEndFrame"]
        if (
            isinstance(aligned_end, bool)
            or not isinstance(aligned_end, int)
            or aligned_end != (ranges[-1][1] if ranges else 0)
        ):
            raise ValueError(
                f"Training index audioAlignedEndFrame is inconsistent for "
                f"{song_id}."
            )
    if "audioAlignedFrameCount" in entry:
        aligned_count = entry["audioAlignedFrameCount"]
        expected_count = sum(end - start for start, end in ranges)
        if (
            isinstance(aligned_count, bool)
            or not isinstance(aligned_count, int)
            or aligned_count != expected_count
        ):
            raise ValueError(
                f"Training index audioAlignedFrameCount is inconsistent for "
                f"{song_id}."
            )
    audio_fingerprint = normalized_audio_sha256(
        entry.get("audioFingerprint"),
        f"Training index audioFingerprint for masked record {song_id}",
    )
    if audio_fingerprint is None:
        raise ValueError(
            f"Training index masked record {song_id} requires a valid "
            "audioFingerprint."
        )
    return ranges


def verified_audio_aligned_frame_mask_for_record(
    record: train.SongRecord,
    entry: dict,
    *,
    expected_frame_count: int | None = None,
) -> tuple[tuple[tuple[int, int], ...], str] | None:
    """Bind an explicit mask to the materialized source-audio bytes."""

    ranges = explicit_audio_aligned_frame_mask_ranges(
        entry,
        record.id,
        expected_frame_count=expected_frame_count,
    )
    if ranges is None:
        return None
    expected_fingerprint = normalized_audio_sha256(
        entry.get("audioFingerprint"),
        f"Training index audioFingerprint for masked record {record.id}",
    )
    if expected_fingerprint is None:
        raise ValueError(
            f"Training index masked record {record.id} requires a valid "
            "audioFingerprint."
        )
    audio_path = record.audio_path
    if not audio_path.is_file():
        raise ValueError(
            f"Masked template record {record.id} audio file is missing: "
            f"{audio_path}"
        )
    resolved_path = audio_path.resolve()
    lfs_pointer_prefix = b"version https://git-lfs.github.com/spec/v1"
    with resolved_path.open("rb") as stream:
        if stream.read(len(lfs_pointer_prefix)) == lfs_pointer_prefix:
            raise ValueError(
                f"Masked template record {record.id} audio is still a Git "
                f"LFS pointer: {audio_path}"
            )
    actual_fingerprint = cached_file_sha256(resolved_path)
    if actual_fingerprint != expected_fingerprint:
        raise ValueError(
            f"Masked template record {record.id} audioFingerprint does not "
            f"match the materialized audio file: {audio_path}"
        )
    return ranges, expected_fingerprint


def _authored_shot_frame_span(shot: dict, frame_count: int) -> tuple[int, int]:
    start = max(0, int(round(float(shot["start"]) * HYBRID_SAMPLE_RATE)))
    end = min(
        frame_count,
        int(round(float(shot["end"]) * HYBRID_SAMPLE_RATE)),
    )
    return start, end


def audio_aligned_template_mask_audit(
    records: list[train.SongRecord],
    policy_by_id: dict[str, dict],
) -> dict[str, object] | None:
    """Summarize explicit template masks and authored-shot exclusions.

    The returned hash covers the selected records' canonical mask contents.
    It is intentionally absent when the legacy index contains no mask fields.
    """

    material: list[dict[str, object]] = []
    totals: Counter[str] = Counter()
    for record in sorted(records, key=lambda item: item.id):
        entry = policy_by_id[record.id]
        if "audioAlignedFrameMaskRanges" not in entry:
            continue
        manifest_frame_count = record.song.get("frameCount")
        if (
            isinstance(manifest_frame_count, bool)
            or not isinstance(manifest_frame_count, int)
            or manifest_frame_count < 0
        ):
            raise ValueError(
                f"Manifest for masked record {record.id} requires a "
                "non-negative integer frameCount."
            )
        verified_mask = verified_audio_aligned_frame_mask_for_record(
            record,
            entry,
            expected_frame_count=manifest_frame_count,
        )
        if verified_mask is None:
            continue
        ranges, audio_fingerprint = verified_mask
        frame_count = int(entry["frameCount"])
        allowed_frame_count = sum(end - start for start, end in ranges)
        material.append(
            {
                "songId": record.id,
                "datasetId": record.dataset_id,
                "frameCount": frame_count,
                "ranges": [list(frame_range) for frame_range in ranges],
                "audioFingerprint": audio_fingerprint,
            }
        )
        totals["explicitMaskRecordCount"] += 1
        totals["verifiedAudioFingerprintCount"] += 1
        totals["rangeCount"] += len(ranges)
        totals["sourceFrameCount"] += frame_count
        totals["allowedFrameCount"] += allowed_frame_count
        totals["excludedFrameCount"] += frame_count - allowed_frame_count
        if ranges == ((0, frame_count),):
            totals["fullRangeRecordCount"] += 1
        else:
            totals["activeMaskedRecordCount"] += 1

        shot_file = json.loads(
            (record.song_dir / "shots.json").read_text(encoding="utf-8")
        )
        shots = shot_file.get("shots")
        if not isinstance(shots, list):
            raise ValueError(f"Shot index for {record.id} must contain a shots array.")
        for shot in shots:
            if not isinstance(shot, dict):
                raise ValueError(f"Shot index for {record.id} contains a non-object row.")
            totals["authoredShotCount"] += 1
            start, end = _authored_shot_frame_span(shot, frame_count)
            if end <= start:
                totals["degenerateAuthoredShotCount"] += 1
                continue
            status, _ = train.audio_aligned_frame_mask_span_status(
                start,
                end,
                ranges,
            )
            if status == "contained":
                totals["maskEligibleAuthoredShotCount"] += 1
                if end - start >= 45:
                    totals["maskEligibleMinimumLengthShotCount"] += 1
                else:
                    totals["maskEligibleTooShortShotCount"] += 1
            elif status == "boundary_crossing":
                totals["boundaryCrossingShotCount"] += 1
            else:
                totals["outsideShotCount"] += 1

    if not material:
        return None
    mask_sha256 = hashlib.sha256(
        json.dumps(
            material,
            ensure_ascii=False,
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
    ).hexdigest()
    return {
        "policyVersion": TEMPLATE_AUDIO_MASK_POLICY_VERSION,
        "rangeSemantics": "zero_based_half_open",
        "boundaryCrossingPolicy": "exclude_whole_authored_shot_no_clipping",
        "audioFingerprintVerification": "materialized_file_sha256_exact",
        "minimumTemplateFrameCount": 45,
        "maskSha256": mask_sha256,
        **{
            name: int(totals[name])
            for name in (
                "explicitMaskRecordCount",
                "verifiedAudioFingerprintCount",
                "activeMaskedRecordCount",
                "fullRangeRecordCount",
                "rangeCount",
                "sourceFrameCount",
                "allowedFrameCount",
                "excludedFrameCount",
                "authoredShotCount",
                "maskEligibleAuthoredShotCount",
                "maskEligibleMinimumLengthShotCount",
                "maskEligibleTooShortShotCount",
                "boundaryCrossingShotCount",
                "outsideShotCount",
                "degenerateAuthoredShotCount",
            )
        },
    }


def finalized_audio_aligned_template_mask_audit(
    audit: dict[str, object] | None,
    templates: list[ShotTemplate],
) -> dict[str, object] | None:
    if audit is None:
        return None
    result = dict(audit)
    explicit_templates = [
        template
        for template in templates
        if template.source_audio_aligned_frame_mask_ranges is not None
    ]
    result["builtTemplateCountFromExplicitMaskRecords"] = len(explicit_templates)
    result["builtTemplateCountFromActiveMaskedRecords"] = sum(
        template.source_audio_aligned_frame_mask_ranges
        != ((0, template.source_frame_count),)
        for template in explicit_templates
    )
    return result


def build_template_library(
    records: list[train.SongRecord],
    prepared_by_id: dict[str, train.PreparedSong],
    aspect_by_id: dict[str, tuple[float, str]] | None = None,
    policy_by_id: dict[str, dict] | None = None,
    shot_label_mode: str = "semantic",
) -> list[ShotTemplate]:
    if shot_label_mode not in {"semantic", "legacy_quantile"}:
        raise ValueError(f"Unknown shot label mode: {shot_label_mode}")
    aspect_by_id = aspect_by_id or {}
    policy_by_id = policy_by_id or {}
    templates: list[ShotTemplate] = []
    for record in records:
        prepared = prepared_by_id[record.id]
        source_aspect_ratio, source_aspect_source = aspect_by_id.get(
            record.id,
            (16.0 / 9.0, "assumed_16_9"),
        )
        frame_count = len(prepared.targets)
        verified_audio_mask = verified_audio_aligned_frame_mask_for_record(
            record,
            policy_by_id.get(record.id, {}),
            expected_frame_count=frame_count,
        )
        audio_mask_ranges = (
            verified_audio_mask[0] if verified_audio_mask is not None else None
        )
        # Portable RuntimeData deliberately contains only prepared arrays.
        # Targets already store camera position/rotation in the character
        # local frame, so deriving the template from them avoids requiring
        # the original camera/root binary artifacts.
        source_camera = prepared.targets
        camera_relative_rotation = train.rotation_6d_to_quat(
            prepared.targets[:, 3:9]
        )
        shot_file = json.loads(
            (record.song_dir / "shots.json").read_text(encoding="utf-8")
        )
        for shot in shot_file["shots"]:
            start, end = _authored_shot_frame_span(shot, frame_count)
            audio_mask_range_index: int | None = None
            if audio_mask_ranges is not None:
                if end <= start:
                    continue
                audio_mask_range_index = (
                    train.audio_aligned_frame_mask_range_index(
                        start,
                        end,
                        audio_mask_ranges,
                    )
                )
                if audio_mask_range_index is None:
                    continue
            if end - start < 45:
                continue
            canonical_joints = prepared.inputs[:, :63].reshape(
                len(prepared.inputs),
                21,
                3,
            )
            subject_reference = canonical_joints[:, 2]
            camera_position = (
                prepared.targets[:, :3] - subject_reference
            )
            raw_motion_path = camera_position[start:end].copy()
            raw_rotation_path = camera_relative_rotation[start:end].copy()
            ensure_quaternion_continuity(
                raw_rotation_path,
                0,
                len(raw_rotation_path),
            )
            pose_slice, trim_start, trim_end = trim_source_pose_boundaries(
                raw_motion_path,
                raw_rotation_path,
                prepared.body_scale,
            )
            motion_path = smooth_template_motion_path(
                raw_motion_path[pose_slice],
                maximum_window=61,
            )
            rotation_path = raw_rotation_path[pose_slice]
            fov_path = source_camera[start:end, 9][pose_slice].copy()
            dutch_path = source_camera[start:end, 10][pose_slice].copy()
            source_joint_path = canonical_joints[start:end][pose_slice]
            source_camera_path = (
                motion_path + source_joint_path[:, 2]
            )
            wide_composition_path = build_source_composition_path(
                source_camera_path,
                rotation_path,
                fov_path,
                dutch_path,
                source_joint_path,
                "wide",
                source_aspect_ratio,
            )
            medium_composition_path = build_source_composition_path(
                source_camera_path,
                rotation_path,
                fov_path,
                dutch_path,
                source_joint_path,
                "medium",
                source_aspect_ratio,
            )
            close_composition_path = build_source_composition_path(
                source_camera_path,
                rotation_path,
                fov_path,
                dutch_path,
                source_joint_path,
                "close",
                source_aspect_ratio,
            )
            framing_label = shot_features.derive_framing_label(
                medium_composition_path,
                source_aspect_source,
            )

            margin = max(1, len(motion_path) // 6)
            interior_start = margin
            interior_end = len(motion_path) - margin
            anchor = np.median(
                motion_path[interior_start:interior_end],
                axis=0,
            )
            early_end = max(3, len(motion_path) // 5)
            late_start = len(motion_path) - max(
                3,
                len(motion_path) // 5,
            )
            motion_delta = (
                np.median(motion_path[late_start:], axis=0)
                - np.median(motion_path[:early_end], axis=0)
            )
            motion_steps = np.linalg.norm(np.diff(motion_path, axis=0), axis=1)
            net_motion_meters = float(
                np.linalg.norm(motion_delta) * prepared.body_scale
            )
            path_length_meters = float(
                np.sum(motion_steps) * prepared.body_scale
            )
            motion_label = shot_features.derive_motion_label(
                motion_path,
                prepared.body_scale,
            )
            distance = float(np.linalg.norm(anchor))
            median_fov = float(
                np.median(fov_path[interior_start:interior_end])
            )
            duration = (end - start) / 60.0
            if not (
                2.5 <= distance <= 35.0
                and 7.0 <= median_fov <= 65.0
                and duration <= 12.0
            ):
                continue
            composition_score = 1.0 / max(
                1e-4,
                distance * math.tan(math.radians(median_fov) * 0.5),
            )
            templates.append(
                ShotTemplate(
                    source_id=record.id,
                    source_dataset_id=record.dataset_id,
                    source_folder=str(record.song["folderName"]),
                    song_name=record.name,
                    source_role=str(
                        policy_by_id.get(record.id, {}).get(
                            "role",
                            "unknown",
                        )
                    ),
                    source_split=str(
                        policy_by_id.get(record.id, {}).get(
                            "recommendedSplit",
                            "unknown",
                        )
                    ),
                    shot_index=int(shot["index"]),
                    source_start_frame=start + trim_start,
                    source_end_frame_exclusive=end - trim_end,
                    source_frame_count=frame_count,
                    duration=duration,
                    features=segment_features(prepared, start, end),
                    anchor=anchor.astype(np.float32),
                    motion_delta=motion_delta.astype(np.float32),
                    motion_path=motion_path.astype(np.float32),
                    rotation_path=rotation_path.astype(np.float32),
                    fov_path=fov_path.astype(np.float32),
                    dutch_path=dutch_path.astype(np.float32),
                    wide_composition_path=wide_composition_path,
                    medium_composition_path=medium_composition_path,
                    close_composition_path=close_composition_path,
                    source_trim_start_frames=trim_start,
                    source_trim_end_frames=trim_end,
                    source_aspect_ratio=source_aspect_ratio,
                    source_aspect_source=source_aspect_source,
                    motion_type=motion_label.motion_type,
                    motion_family=motion_label.motion_family,
                    motion_confidence=motion_label.confidence,
                    orbit_degrees=motion_label.orbit_degrees,
                    radial_delta_meters=motion_label.radial_delta_meters,
                    lateral_delta_meters=motion_label.lateral_delta_meters,
                    vertical_delta_meters=motion_label.vertical_delta_meters,
                    net_motion_meters=net_motion_meters,
                    path_length_meters=path_length_meters,
                    fov=median_fov,
                    composition_score=composition_score,
                    subject_height_ratio=(
                        framing_label.subject_height_ratio
                    ),
                    framing_valid_ratio=(
                        framing_label.valid_frame_ratio
                    ),
                    shot_type_confidence=framing_label.confidence,
                    shot_type_confidence_tier=(
                        framing_label.confidence_tier
                    ),
                    shot_type=framing_label.shot_type,
                    source_audio_aligned_frame_mask_ranges=(
                        audio_mask_ranges
                    ),
                    source_audio_mask_range_index=audio_mask_range_index,
                    source_authored_start_frame=start,
                    source_authored_end_frame_exclusive=end,
                )
            )

    if shot_label_mode == "legacy_quantile":
        scores = np.asarray(
            [template.composition_score for template in templates]
        )
        wide_threshold, close_threshold = np.quantile(
            scores,
            [0.34, 0.68],
        )
        for template in templates:
            if template.composition_score <= wide_threshold:
                template.shot_type = "wide"
            elif template.composition_score >= close_threshold:
                template.shot_type = "close"
            else:
                template.shot_type = "medium"
    return templates


def train_shot_classifier(
    templates: list[ShotTemplate],
    evaluation_group_by_id: dict[str, str] | None = None,
) -> tuple[RandomForestClassifier, float | None]:
    if not templates:
        raise ValueError("At least one shot template is required.")
    inputs = np.stack([template.features for template in templates])
    labels = np.asarray([template.shot_type for template in templates])
    evaluation_group_by_id = evaluation_group_by_id or {}
    groups = np.asarray(
        [
            evaluation_group_by_id.get(
                template.source_id,
                template.source_id,
            )
            for template in templates
        ]
    )
    group_counts = {
        group: int(np.sum(groups == group))
        for group in np.unique(groups)
    }
    sample_weights = np.asarray(
        [1.0 / group_counts[group] for group in groups],
        dtype=np.float64,
    )
    sample_weights *= len(sample_weights) / np.sum(sample_weights)
    classifier = RandomForestClassifier(
        n_estimators=300,
        max_depth=6,
        min_samples_leaf=3,
        class_weight="balanced",
        random_state=20260729,
        n_jobs=-1,
    )
    unique_groups = np.unique(groups)
    folds = min(5, len(unique_groups))
    cross_validation_accuracy: float | None = None
    if folds >= 2:
        splitter = GroupKFold(n_splits=folds)
        scores = []
        for train_indices, validation_indices in splitter.split(
            inputs,
            labels,
            groups,
        ):
            fold_classifier = clone(classifier)
            fold_classifier.fit(
                inputs[train_indices],
                labels[train_indices],
                sample_weight=sample_weights[train_indices],
            )
            prediction = fold_classifier.predict(
                inputs[validation_indices]
            )
            scores.append(
                balanced_accuracy_score(
                    labels[validation_indices],
                    prediction,
                    sample_weight=sample_weights[validation_indices],
                )
            )
        cross_validation_accuracy = float(np.mean(scores))
    classifier.fit(inputs, labels, sample_weight=sample_weights)
    return classifier, cross_validation_accuracy


def build_beat_onset_cache(
    record: train.SongRecord,
    prepared: train.PreparedSong,
) -> preparation_cache.BeatOnsetCache:
    """Build the target-song audio event payload shared with preparation caches."""

    frame_count = len(prepared.inputs)
    onset = prepared.inputs[:, -1].astype(np.float64)
    onset_scale = max(float(np.std(onset)), 1e-6)
    onset_normalized = (onset - float(np.mean(onset))) / onset_scale

    waveform, _ = librosa.load(record.audio_path, sr=train.AUDIO_RATE, mono=True)
    _, beat_frames = librosa.beat.beat_track(
        y=waveform,
        sr=train.AUDIO_RATE,
        hop_length=train.AUDIO_HOP,
    )
    audio_start = float(record.song["audioStart"])
    timeline_offset = int(round(audio_start * 60.0))
    beat_frames = beat_frames.astype(np.int64) + timeline_offset
    peak_frames, _ = find_peaks(
        onset_normalized,
        distance=30,
        prominence=0.35,
    )
    candidates = np.unique(
        np.concatenate(
            (
                beat_frames[(beat_frames > 0) & (beat_frames < frame_count)],
                peak_frames[(peak_frames > 0) & (peak_frames < frame_count)],
            )
        )
    )

    return preparation_cache.BeatOnsetCache(
        frame_count=frame_count,
        onset_normalized=onset_normalized,
        beat_frames=beat_frames,
        peak_frames=peak_frames.astype(np.int64),
        candidates=candidates,
        audio_start=audio_start,
        timeline_offset=timeline_offset,
    )


def build_cut_boundaries(
    record: train.SongRecord,
    prepared: train.PreparedSong,
    minimum_seconds: float,
    maximum_seconds: float,
) -> list[int]:
    beat_onset = build_beat_onset_cache(record, prepared)
    return beat_onset.cut_boundaries(
        minimum_seconds,
        maximum_seconds,
        sample_rate=60,
    )


def load_cut_directives(path: Path | None) -> cut_planner.CutDirectives:
    if path is None:
        return cut_planner.CutDirectives()
    resolved = path.resolve()
    payload = json.loads(resolved.read_text(encoding="utf-8"))
    if not isinstance(payload, dict):
        raise ValueError("Cut directives JSON must contain an object.")
    if payload.pop("schemaVersion", None) != "cut-directives-v1":
        raise ValueError("Cut directives must use schemaVersion cut-directives-v1.")
    return cut_planner.CutDirectives.from_mapping(payload)


def load_cut_ranker_model(
    path: Path,
) -> tuple[cut_planner.LinearCandidateScoreModel | None, dict[str, object]]:
    resolved = path.resolve()
    if not resolved.is_file():
        return None, {
            "status": "missing_fallback",
            "path": portable_path(resolved),
            "sha256": None,
        }
    artifact = json.loads(resolved.read_text(encoding="utf-8"))
    if not isinstance(artifact, dict):
        raise ValueError("Cut-ranker artifact must contain an object.")
    try:
        model = cut_planner.LinearCandidateScoreModel.from_artifact(artifact)
    except ValueError as error:
        raise ValueError(
            "Incompatible cut-ranker artifact. Runtime requires schema "
            f"{cut_planner.CANDIDATE_RANKER_SCHEMA_VERSION} with causal "
            "three-shot history features; retrain the ranker."
        ) from error
    return model, {
        "status": "loaded",
        "path": portable_path(resolved),
        "sha256": sha256_file(resolved),
    }


def in_range_cut_event_frames(
    values: np.ndarray | list[int] | tuple[int, ...],
    frame_count: int,
) -> np.ndarray:
    """Adapt audio-offset event arrays to the strict planner contract."""

    frames = np.asarray(values, dtype=np.int64)
    if frames.ndim != 1:
        raise ValueError("Cut event frames must be one-dimensional.")
    return np.unique(frames[(frames > 0) & (frames < int(frame_count))])


def build_data_driven_cut_plan(
    args: argparse.Namespace,
    target_record: train.SongRecord,
    target: train.PreparedSong,
    beat_onset: preparation_cache.BeatOnsetCache,
    cut_reference_records: list[train.SongRecord],
    index_entries: dict[str, dict],
) -> tuple[cut_planner.CutPlanResult, dict[str, object]]:
    research_profile = normalized_research_ablation_profile(args)
    same_audio_prior = effective_same_audio_prior(args)
    corpus = cut_reference.build_cut_reference_corpus(
        target_record,
        cut_reference_records,
        index_entries,
    )
    duration_prior = cut_planner.EmpiricalDurationPrior.from_duration_frames(
        np.asarray(corpus.duration_seconds, dtype=np.float64)
        * HYBRID_SAMPLE_RATE,
        sample_weights=np.asarray(
            corpus.duration_weights,
            dtype=np.float64,
        ),
        sample_rate=HYBRID_SAMPLE_RATE,
    )
    model, model_metadata = load_cut_ranker_model(args.cut_ranker_model)
    if model is None:
        print(
            "Cut-ranker model is missing; data-driven DP will use its "
            "auditable signal-score fallback: " + str(args.cut_ranker_model),
            file=sys.stderr,
        )
    same_audio_boundaries = None
    selected_same_audio_metadata: dict[str, object] | None = None
    if same_audio_prior == "auto" and corpus.same_audio_patterns:
        selected_pattern = corpus.same_audio_patterns[0]
        same_audio_boundaries = selected_pattern.boundaries
        selected_same_audio_metadata = {
            "boundaries": list(selected_pattern.boundaries),
            "sameCharacter": selected_pattern.same_character,
            "sourceRecordIds": list(selected_pattern.source_record_ids),
            "weight": selected_pattern.weight,
        }
    directives = load_cut_directives(args.cut_directives_json)
    frame_count = len(target.inputs)
    beat_frames = in_range_cut_event_frames(
        beat_onset.beat_frames,
        frame_count,
    )
    peak_frames = in_range_cut_event_frames(
        beat_onset.peak_frames,
        frame_count,
    )
    cut_inputs, beat_frames, peak_frames = (
        apply_research_ablation_to_cut_signals(
            target.inputs,
            beat_frames,
            peak_frames,
            research_profile,
        )
    )
    result = cut_planner.plan_cut_boundaries(
        cut_inputs,
        beat_frames,
        peak_frames,
        duration_prior,
        sample_rate=HYBRID_SAMPLE_RATE,
        model=model,
        same_audio_boundaries=same_audio_boundaries,
        directives=directives,
        density=args.cut_density,
    )
    metadata = {
        "mode": "data_driven_global_dag",
        "plannerFormat": cut_planner.CUT_PLANNER_FORMAT,
        "plannerSchemaVersion": cut_planner.CUT_PLANNER_SCHEMA_VERSION,
        "density": args.cut_density,
        "ranker": model_metadata,
        "referenceCorpus": corpus.as_metadata(),
        "referenceSelectionPolicyVersion": (
            CUT_REFERENCE_SELECTION_POLICY_VERSION
        ),
        "cutReferenceRecordCount": len(cut_reference_records),
        "sameAudioPriorMode": same_audio_prior,
        "selectedSameAudioPattern": selected_same_audio_metadata,
        "directivesJson": (
            portable_path(args.cut_directives_json.resolve())
            if args.cut_directives_json is not None
            else None
        ),
        "directivesJsonSha256": (
            sha256_file(args.cut_directives_json.resolve())
            if args.cut_directives_json is not None
            else None
        ),
        "result": result.metadata,
    }
    return result, metadata


def rank_template_candidates(
    classifier: RandomForestClassifier,
    templates: list[ShotTemplate],
    feature_mean: np.ndarray,
    feature_std: np.ndarray,
    features: np.ndarray,
    shot_index: int,
    previous: RealizedShotState | None,
    recent: list[tuple[str, int]],
    candidate_count: int = 8,
    desired_type_override: str | None = None,
    desired_motion_family: str | None = None,
    desired_motion_type: str | None = None,
) -> list[ShotTemplate]:
    probabilities = dict(
        zip(
            classifier.classes_,
            classifier.predict_proba(features[None])[0],
        )
    )
    if desired_type_override is not None:
        desired_type = desired_type_override
    elif shot_index == 0 or shot_index % 7 == 0:
        desired_type = "wide"
    else:
        adjusted = probabilities.copy()
        if previous is not None:
            adjusted[previous.template.shot_type] *= 0.35
            if previous.template.shot_type == "close":
                adjusted["wide"] = adjusted.get("wide", 0.0) * 1.5
        desired_type = max(adjusted, key=adjusted.get)

    candidates = [
        template for template in templates if template.shot_type == desired_type
    ]
    person_focused = [
        template
        for template in candidates
        if template.source_person_visibility() >= 0.9
    ]
    if len(person_focused) >= candidate_count:
        candidates = person_focused
    normalized_query = (features - feature_mean) / feature_std
    scored: list[tuple[float, str, int, ShotTemplate]] = []
    for template in candidates:
        mirrored, _, realized_motion_type = template_realization(
            template,
            previous,
        )
        normalized_template = (template.features - feature_mean) / feature_std
        score = float(np.linalg.norm(normalized_template - normalized_query))
        identity = (template.source_id, template.shot_index)
        if identity in recent:
            score += 4.0
        if previous is not None:
            if mirrored:
                score += 0.15
            if abs(template.fov - previous.template.fov) < 3.0:
                score += 0.4
            if realized_motion_type == previous.motion_type:
                score += 0.6
        if desired_motion_type is not None:
            if realized_motion_type != desired_motion_type:
                score += 4.0
            else:
                score -= 0.35 * template.motion_confidence
        if (
            desired_motion_family is not None
            and template.motion_family != desired_motion_family
        ):
            score += 1.35
        elif desired_motion_family is not None:
            score -= 0.15 * template.motion_confidence
        minimum_motion = {
            "wide": 2.5,
            "medium": 1.5,
            "close": 0.8,
        }[desired_type]
        if template.net_motion_meters < minimum_motion:
            score += (minimum_motion - template.net_motion_meters) * 1.25
        score += (1.0 - template.source_person_visibility()) * 12.0
        _, aspect_penalty, _ = source_aspect_quality(
            template.source_aspect_ratio,
            template.source_aspect_source,
        )
        score += aspect_penalty
        # Keep retrieval deterministic. Generation diversity is applied only
        # after retargeting and the strict person-safety gate, where we can
        # prove that two candidates produce visibly different camera output.
        scored.append(
            (
                score,
                template.source_id,
                int(template.shot_index),
                template,
            )
        )
    scored.sort(key=lambda item: item[:3])
    return [
        template
        for _, _, _, template in scored[: min(candidate_count, len(scored))]
    ]


def smooth_segment(values: np.ndarray, maximum_window: int = 31) -> np.ndarray:
    if len(values) < 5:
        return values
    window = min(maximum_window, len(values) if len(values) % 2 else len(values) - 1)
    if window < 5:
        return values
    return savgol_filter(
        values,
        window_length=window,
        polyorder=3,
        axis=0,
        mode="interp",
    ).astype(np.float32)


def smooth_template_motion_path(
    values: np.ndarray,
    maximum_window: int = 61,
) -> np.ndarray:
    """Smooth a retrieved position template without polynomial edge launch.

    ``smooth_segment`` intentionally retains its historical ``interp`` mode
    for generic signals.  Camera position templates are different: the first
    generated frame follows a hard cut, so an extrapolated Savitzky-Golay edge
    can appear as a one-frame camera-body spike.  Nearest extension avoids
    that extrapolation, while the explicit first/last-step guard makes the
    edge contract independent of future SciPy implementation details.
    """

    source = np.asarray(values, dtype=np.float32)
    if len(source) < 5:
        return source
    window = min(
        maximum_window,
        len(source) if len(source) % 2 else len(source) - 1,
    )
    if window < 5:
        return source
    result = savgol_filter(
        source,
        window_length=window,
        polyorder=3,
        axis=0,
        mode="nearest",
    ).astype(np.float32)
    raw_steps = np.linalg.norm(np.diff(source, axis=0), axis=1)
    edge_span = min(len(raw_steps), max(1, window // 2))

    def clamp_edge_step(
        outer_index: int,
        inner_index: int,
        maximum_step: float,
    ) -> None:
        delta = result[inner_index] - result[outer_index]
        step = float(np.linalg.norm(delta))
        if step > maximum_step and step > 1e-8:
            # Move only the outermost sample.  The already-smoothed interior
            # remains byte-for-byte unchanged, so the guard cannot move the
            # spike one frame deeper into the shot.
            result[outer_index] = (
                result[inner_index]
                - delta * (maximum_step / step)
            )

    clamp_edge_step(
        0,
        1,
        float(np.max(raw_steps[:edge_span])),
    )
    end_maximum = float(np.max(raw_steps[-edge_span:]))
    end_delta = result[-1] - result[-2]
    end_step = float(np.linalg.norm(end_delta))
    if end_step > end_maximum and end_step > 1e-8:
        result[-1] = result[-2] + end_delta * (end_maximum / end_step)
    return result


def stable_shot_rotation(root_rotations: np.ndarray) -> np.ndarray:
    """Return one root orientation for the shot instead of body-follow rotation."""

    values = np.asarray(root_rotations, dtype=np.float64).copy()
    values /= np.maximum(np.linalg.norm(values, axis=1, keepdims=True), 1e-8)
    ensure_quaternion_continuity(values, 0, len(values))
    sample_count = min(len(values), 15)
    representative = np.mean(values[:sample_count], axis=0)
    representative /= max(float(np.linalg.norm(representative)), 1e-8)
    return np.broadcast_to(representative, values.shape).copy().astype(np.float32)


def build_stage_anchor_path(
    subject_world_positions: np.ndarray,
    body_follow_strength: float,
    smoothing_seconds: float,
    dead_zone_meters: float,
    sample_rate: float = 60.0,
) -> tuple[np.ndarray, dict[str, float]]:
    """Build a shot-fixed anchor plus slow horizontal subject translation."""

    if not 0.0 <= body_follow_strength <= 1.0:
        raise ValueError("body_follow_strength must be between zero and one.")
    if not math.isfinite(smoothing_seconds) or smoothing_seconds <= 0.0:
        raise ValueError("smoothing_seconds must be finite and positive.")
    if not math.isfinite(dead_zone_meters) or dead_zone_meters < 0.0:
        raise ValueError("dead_zone_meters must be finite and non-negative.")
    points = np.asarray(subject_world_positions, dtype=np.float32)
    if points.ndim != 2 or points.shape[1] != 3 or len(points) == 0:
        raise ValueError("subject_world_positions must have shape [frame, 3].")
    sigma = max(0.5, smoothing_seconds * sample_rate / 3.0)
    low_frequency = gaussian_filter1d(
        points,
        sigma=sigma,
        axis=0,
        mode="nearest",
        truncate=3.0,
    ).astype(np.float32)
    reference_count = min(len(points), max(1, int(round(sample_rate * 0.25))))
    reference = np.median(low_frequency[:reference_count], axis=0)
    displacement = low_frequency - reference
    displacement[:, 1] = 0.0
    horizontal_length = np.linalg.norm(displacement[:, [0, 2]], axis=1)
    active = horizontal_length > dead_zone_meters
    if np.any(active):
        displacement[active] *= (
            (horizontal_length[active] - dead_zone_meters)
            / horizontal_length[active]
        )[:, None]
    displacement[~active] = 0.0
    followed = displacement * body_follow_strength
    if len(followed) > 2 and body_follow_strength > 0.0:
        followed = gaussian_filter1d(
            followed,
            sigma=max(0.5, sigma * 0.2),
            axis=0,
            mode="nearest",
            truncate=3.0,
        ).astype(np.float32)
    anchor_path = reference + followed
    steps = np.linalg.norm(np.diff(anchor_path, axis=0), axis=1)
    return anchor_path.astype(np.float32), {
        "bodyFollowStrength": float(body_follow_strength),
        "bodyFollowSmoothingSeconds": float(smoothing_seconds),
        "bodyFollowDeadZoneMeters": float(dead_zone_meters),
        "bodyFollowPathLengthMeters": float(np.sum(steps)),
        "bodyFollowMaximumOffsetMeters": float(
            np.max(np.linalg.norm(followed, axis=1))
        ),
    }


def scale_quaternion_motion(
    quaternions: np.ndarray,
    intensity: float,
) -> np.ndarray:
    if not 0.0 <= intensity <= 2.0:
        raise ValueError("intensity must be between zero and two.")
    values = np.asarray(quaternions, dtype=np.float64).copy()
    values /= np.maximum(np.linalg.norm(values, axis=1, keepdims=True), 1e-8)
    ensure_quaternion_continuity(values, 0, len(values))
    reference = Rotation.from_quat(values[0])
    relative = reference.inv() * Rotation.from_quat(values)
    scaled = reference * Rotation.from_rotvec(relative.as_rotvec() * intensity)
    result = scaled.as_quat()
    ensure_quaternion_continuity(result, 0, len(result))
    return result.astype(np.float32)


def resample_path(values: np.ndarray, output_length: int) -> np.ndarray:
    if output_length <= 0:
        return np.empty((0, values.shape[1]), dtype=np.float32)
    if len(values) == output_length:
        return values.copy().astype(np.float32)
    source_time = np.linspace(0.0, 1.0, len(values), dtype=np.float64)
    output_time = np.linspace(0.0, 1.0, output_length, dtype=np.float64)
    result = np.stack(
        [
            np.interp(output_time, source_time, values[:, axis])
            for axis in range(values.shape[1])
        ],
        axis=1,
    )
    return result.astype(np.float32)


def resample_quaternions(
    values: np.ndarray,
    output_length: int,
) -> np.ndarray:
    if output_length <= 0:
        return np.empty((0, 4), dtype=np.float32)
    quaternions = values.copy().astype(np.float64)
    quaternions /= np.maximum(
        np.linalg.norm(quaternions, axis=1, keepdims=True),
        1e-8,
    )
    ensure_quaternion_continuity(quaternions, 0, len(quaternions))
    if len(quaternions) == output_length:
        return quaternions.astype(np.float32)
    source_time = np.linspace(0.0, 1.0, len(quaternions), dtype=np.float64)
    output_time = np.linspace(0.0, 1.0, output_length, dtype=np.float64)
    interpolator = Slerp(
        source_time,
        Rotation.from_quat(quaternions),
    )
    result = interpolator(output_time).as_quat()
    ensure_quaternion_continuity(result, 0, len(result))
    return result.astype(np.float32)


def retarget_camera_position_path(
    template_motion_path: np.ndarray,
    output_length: int,
) -> np.ndarray:
    """Retarget a template already denoised during library construction.

    Applying another one-second Savitzky-Golay pass here previously removed
    rhythmic authored motion. Resampling is sufficient because the template
    path has already been smoothed once before it enters the library.
    """

    resampled, _ = trajectory_quality.resample_position_path_c2(
        template_motion_path,
        output_length,
        sample_rate=HYBRID_SAMPLE_RATE,
    )
    return resampled


def smooth_camera_world_position(values: np.ndarray) -> np.ndarray:
    """Apply an edge-safe polish only when it improves path dynamics.

    The old ``mode='interp'`` Savitzky-Golay edge can launch a camera after a
    hard cut.  Nearest extension avoids that extrapolation, and this guard
    rejects any polish that increases acceleration/jerk or erases meaningful
    authored travel.
    """

    source = np.asarray(values, dtype=np.float32)
    polished = smooth_template_motion_path(
        source,
        maximum_window=FINAL_POSITION_SMOOTHING_WINDOW_FRAMES,
    )
    if len(source) < 4 or np.array_equal(polished, source):
        return polished
    before = trajectory_quality.translation_dynamics_metrics(
        source,
        sample_rate=HYBRID_SAMPLE_RATE,
    )
    after = trajectory_quality.translation_dynamics_metrics(
        polished,
        sample_rate=HYBRID_SAMPLE_RATE,
    )
    # Raw path length is a bad retention reference: alternating millimetre
    # chatter can contribute more travel than the intentional pan underneath
    # it.  Compare the low-frequency motion envelope and net displacement
    # instead, so denoising is accepted without flattening deliberate moves.
    retention_sigma = max(
        1.0,
        min(FINAL_POSITION_SMOOTHING_WINDOW_FRAMES, len(source)) / 5.0,
    )
    source_low_frequency = gaussian_filter1d(
        source.astype(np.float64),
        sigma=retention_sigma,
        axis=0,
        mode="nearest",
        truncate=3.0,
    )
    polished_low_frequency = gaussian_filter1d(
        polished.astype(np.float64),
        sigma=retention_sigma,
        axis=0,
        mode="nearest",
        truncate=3.0,
    )
    source_low_path = position_path_length(source_low_frequency)
    polished_low_path = position_path_length(polished_low_frequency)
    motion_deadband_meters = 0.01
    low_frequency_path_retained = (
        source_low_path <= motion_deadband_meters
        or polished_low_path
        >= source_low_path * 0.90 - motion_deadband_meters
    )
    low_frequency_path_not_exaggerated = (
        polished_low_path
        <= source_low_path * 1.12 + motion_deadband_meters
    )
    source_net = source_low_frequency[-1] - source_low_frequency[0]
    polished_net = polished_low_frequency[-1] - polished_low_frequency[0]
    source_net_length = float(np.linalg.norm(source_net))
    if source_net_length <= motion_deadband_meters:
        net_travel_retained = True
    else:
        source_net_direction = source_net / source_net_length
        retained_forward_travel = float(
            np.dot(polished_net, source_net_direction)
        )
        net_travel_retained = bool(
            retained_forward_travel
            >= source_net_length * 0.90 - motion_deadband_meters
        )
    acceleration_safe = (
        float(after["accelerationMetersPerSecondSquared"]["p99"])
        <= float(before["accelerationMetersPerSecondSquared"]["p99"])
        * 1.05
        + 0.5
    )
    jerk_safe = (
        float(after["jerkMetersPerSecondCubed"]["p99"])
        <= float(before["jerkMetersPerSecondCubed"]["p99"]) * 1.05
        + 5.0
    )
    retention_safe = bool(
        low_frequency_path_retained
        and low_frequency_path_not_exaggerated
        and net_travel_retained
    )
    return polished if retention_safe and acceleration_safe and jerk_safe else source


def final_radial_dynamics_regression_audit(
    before_world_position: np.ndarray,
    after_world_position: np.ndarray,
    sample_rate: float = HYBRID_SAMPLE_RATE,
) -> dict[str, object]:
    """Fail closed when the final distance projection roughens the camera.

    The radial projection is required for person-distance safety, so an unsafe
    result cannot simply be replaced with its potentially out-of-bounds input.
    Instead this audit lets candidate selection try another authored camera.
    Both P99 and the rendered-frame maximum are checked so a single new jolt is
    not hidden by an otherwise smooth shot.
    """

    before = trajectory_quality.translation_dynamics_metrics(
        before_world_position,
        sample_rate=sample_rate,
    )
    after = trajectory_quality.translation_dynamics_metrics(
        after_world_position,
        sample_rate=sample_rate,
    )
    checks: dict[str, bool] = {}
    thresholds: dict[str, float] = {}
    observed_before: dict[str, float] = {}
    observed_after: dict[str, float] = {}
    for group, delta, label in (
        (
            "accelerationMetersPerSecondSquared",
            FINAL_RADIAL_MAXIMUM_ACCELERATION_REGRESSION_DELTA_MPS2,
            "acceleration",
        ),
        (
            "jerkMetersPerSecondCubed",
            FINAL_RADIAL_MAXIMUM_JERK_REGRESSION_DELTA_MPS3,
            "jerk",
        ),
    ):
        for statistic in ("p99", "maximum"):
            before_value = float(before[group][statistic])
            after_value = float(after[group][statistic])
            threshold = (
                before_value
                * FINAL_RADIAL_MAXIMUM_DYNAMICS_REGRESSION_RATIO
                + delta
            )
            key = label + statistic.capitalize()
            observed_before[key] = before_value
            observed_after[key] = after_value
            thresholds[key] = threshold
            checks[key] = bool(after_value <= threshold + 1e-9)
    return {
        "policyVersion": FINAL_RADIAL_DYNAMICS_GUARD_POLICY_VERSION,
        "maximumRegressionRatio": (
            FINAL_RADIAL_MAXIMUM_DYNAMICS_REGRESSION_RATIO
        ),
        "maximumAccelerationRegressionDeltaMetersPerSecondSquared": (
            FINAL_RADIAL_MAXIMUM_ACCELERATION_REGRESSION_DELTA_MPS2
        ),
        "maximumJerkRegressionDeltaMetersPerSecondCubed": (
            FINAL_RADIAL_MAXIMUM_JERK_REGRESSION_DELTA_MPS3
        ),
        "before": observed_before,
        "after": observed_after,
        "thresholds": thresholds,
        "checks": checks,
        "passed": bool(all(checks.values())),
    }


def position_path_length(values: np.ndarray) -> float:
    points = np.asarray(values, dtype=np.float64)
    if len(points) < 2:
        return 0.0
    return float(np.sum(np.linalg.norm(np.diff(points, axis=0), axis=1)))


def quaternion_path_degrees(values: np.ndarray) -> float:
    quaternions = np.asarray(values, dtype=np.float64)
    if len(quaternions) < 2:
        return 0.0
    quaternions = quaternions / np.maximum(
        np.linalg.norm(quaternions, axis=1, keepdims=True),
        1e-8,
    )
    dots = np.clip(
        np.abs(np.sum(quaternions[1:] * quaternions[:-1], axis=1)),
        0.0,
        1.0,
    )
    return float(np.sum(np.degrees(2.0 * np.arccos(dots))))


def motion_quality_metrics(
    authored_relative_position_meters: np.ndarray,
    realized_relative_position_meters: np.ndarray,
    authored_rotation: np.ndarray,
    realized_rotation: np.ndarray,
    shot_type: str,
    motion_type: str,
    motion_intensity: float,
    sample_rate: float = 60.0,
) -> dict[str, float | bool | None]:
    """Measure retained authored motion and its final visible expressiveness."""

    frame_count = max(
        len(np.asarray(realized_relative_position_meters)),
        len(np.asarray(realized_rotation)),
        1,
    )
    duration_seconds = max(frame_count / sample_rate, 1.0 / sample_rate)
    sample_count = min(
        frame_count,
        max(2, int(round(duration_seconds * MOTION_QUALITY_SAMPLE_RATE_HZ)) + 1),
    )
    authored_position_samples = resample_path(
        np.asarray(authored_relative_position_meters),
        sample_count,
    )
    realized_position_samples = resample_path(
        np.asarray(realized_relative_position_meters),
        sample_count,
    )
    authored_rotation_samples = resample_quaternions(
        np.asarray(authored_rotation),
        sample_count,
    )
    realized_rotation_samples = resample_quaternions(
        np.asarray(realized_rotation),
        sample_count,
    )
    authored_translation = position_path_length(
        authored_position_samples
    )
    realized_translation = position_path_length(
        realized_position_samples
    )
    authored_rotation_degrees = quaternion_path_degrees(
        authored_rotation_samples
    )
    realized_rotation_degrees = quaternion_path_degrees(
        realized_rotation_samples
    )

    translation_retention = (
        min(realized_translation / authored_translation, 1.0)
        if authored_translation >= 0.05
        else None
    )
    rotation_retention = (
        min(realized_rotation_degrees / authored_rotation_degrees, 1.0)
        if authored_rotation_degrees >= 1.0
        else None
    )
    active_retentions = [
        value
        for value in (translation_retention, rotation_retention)
        if value is not None
    ]
    retention = (
        float(np.mean(active_retentions)) if active_retentions else 0.0
    )

    translation_speed = realized_translation / duration_seconds
    rotation_speed = realized_rotation_degrees / duration_seconds
    translation_expressiveness = min(
        translation_speed
        / MOTION_EXPRESSIVENESS_TRANSLATION_SPEED_MPS[shot_type],
        1.0,
    )
    rotation_expressiveness = min(
        rotation_speed / MOTION_EXPRESSIVENESS_ROTATION_SPEED_DPS,
        1.0,
    )
    expressiveness = max(
        translation_expressiveness,
        rotation_expressiveness,
    )

    scoring_applied = bool(
        motion_intensity > 1e-3
        and planner.normalize_motion_family(motion_type) != "static"
    )
    if scoring_applied:
        retention_shortfall = max(
            MINIMUM_NON_STATIC_MOTION_RETENTION_RATIO - retention,
            0.0,
        )
        retention_penalty = (
            retention_shortfall
            / MINIMUM_NON_STATIC_MOTION_RETENTION_RATIO
            * MOTION_RETENTION_PENALTY_WEIGHT
        )
        expressiveness_reward = (
            expressiveness * MOTION_EXPRESSIVENESS_REWARD_MAX
        )
    else:
        retention_penalty = 0.0
        expressiveness_reward = 0.0

    return {
        "motionSelectionScoringApplied": scoring_applied,
        "authoredTranslationPathLengthMeters": authored_translation,
        "realizedTranslationPathLengthMeters": realized_translation,
        "translationMotionRetentionRatio": translation_retention,
        "authoredRotationPathDegrees": authored_rotation_degrees,
        "realizedRotationPathDegrees": realized_rotation_degrees,
        "rotationMotionRetentionRatio": rotation_retention,
        "motionRetentionRatio": retention,
        "motionExpressiveness": float(expressiveness),
        "motionRetentionPenalty": float(retention_penalty),
        "motionExpressivenessReward": float(expressiveness_reward),
        "motionSelectionAdjustment": float(
            retention_penalty - expressiveness_reward
        ),
    }


def mirror_quaternions_x(quaternions: np.ndarray) -> np.ndarray:
    reflection = np.diag([-1.0, 1.0, 1.0])
    matrices = Rotation.from_quat(quaternions).as_matrix()
    mirrored = reflection[None] @ matrices @ reflection[None]
    result = Rotation.from_matrix(mirrored).as_quat()
    ensure_quaternion_continuity(result, 0, len(result))
    return result.astype(np.float32)


def ensure_quaternion_continuity(
    quaternions: np.ndarray,
    start: int,
    end: int,
) -> None:
    for index in range(start + 1, end):
        if np.dot(quaternions[index - 1], quaternions[index]) < 0.0:
            quaternions[index] *= -1.0


def shot_focus_local(
    joints: np.ndarray,
    shot_type: str,
) -> np.ndarray:
    if shot_type == "wide":
        return joints[:, 0] * 0.55 + joints[:, 2] * 0.45
    if shot_type == "close":
        return joints[:, 4] * 0.72 + joints[:, 2] * 0.28
    return joints[:, 2] * 0.75 + joints[:, 4] * 0.25


def quaternion_between_vectors(
    source: np.ndarray,
    target: np.ndarray,
) -> np.ndarray:
    source = source / np.maximum(
        np.linalg.norm(source, axis=1, keepdims=True),
        1e-8,
    )
    target = target / np.maximum(
        np.linalg.norm(target, axis=1, keepdims=True),
        1e-8,
    )
    cross = np.cross(source, target)
    dot = np.clip(np.sum(source * target, axis=1), -1.0, 1.0)
    result = np.column_stack((cross, 1.0 + dot))
    opposite = dot < -0.9999
    if np.any(opposite):
        fallback = np.cross(
            source[opposite],
            np.broadcast_to(
                np.asarray([0.0, 1.0, 0.0], dtype=np.float32),
                source[opposite].shape,
            ),
        )
        vertical = np.linalg.norm(fallback, axis=1) < 1e-5
        if np.any(vertical):
            fallback[vertical] = np.cross(
                source[opposite][vertical],
                np.asarray([1.0, 0.0, 0.0], dtype=np.float32),
            )
        fallback /= np.maximum(
            np.linalg.norm(fallback, axis=1, keepdims=True),
            1e-8,
        )
        result[opposite, :3] = fallback
        result[opposite, 3] = 0.0
    result /= np.maximum(
        np.linalg.norm(result, axis=1, keepdims=True),
        1e-8,
    )
    ensure_quaternion_continuity(result, 0, len(result))
    return result.astype(np.float32)


def source_aspect_quality(
    aspect_ratio: float,
    aspect_source: str,
) -> tuple[float, float, str]:
    """Return residual trust and a retrieval penalty for weak source framing.

    A square recorder can still contain an excellent dolly/orbit trajectory,
    so it is deliberately not filtered out.  Its authored screen-space
    composition simply has less authority when retargeting to another aspect.
    """

    source = str(aspect_source).strip().lower()
    ambiguous = (
        not math.isfinite(aspect_ratio)
        or aspect_ratio <= 0.0
        or source in {"", "unknown"}
        or "assum" in source
    )
    square = (
        math.isfinite(aspect_ratio)
        and aspect_ratio > 0.0
        and abs(aspect_ratio - 1.0) <= 0.08
    )
    reliability = 1.0
    penalty = 0.0
    reasons: list[str] = []
    if square:
        reliability *= 0.62
        penalty += 0.40
        reasons.append("square_source")
    if ambiguous:
        reliability *= 0.62
        penalty += 0.35
        reasons.append("ambiguous_aspect")
    return (
        float(max(0.30, reliability)),
        float(penalty),
        "+".join(reasons) if reasons else "trusted",
    )


def _c2_dead_zone_response_distance(
    distance_meters: float,
    dead_zone_meters: float,
    transition_meters: float,
) -> float:
    """Map a hysteretic tracking error through a C2 dead-zone boundary.

    The focus tracker measures error from its previous output, so the dead
    zone already has hysteresis: motion must accumulate outside the retained
    output before the target moves.  The old ``max(error - dead_zone, 0)``
    response changed slope instantly at that boundary.  This quintic joins a
    stationary response to the original unit-slope response with continuous
    value, velocity and acceleration.
    """

    distance = float(distance_meters)
    dead_zone = float(dead_zone_meters)
    transition = float(transition_meters)
    if (
        not math.isfinite(distance)
        or not math.isfinite(dead_zone)
        or not math.isfinite(transition)
        or distance < 0.0
        or dead_zone < 0.0
        or transition < 0.0
    ):
        raise ValueError("Dead-zone distances must be finite and non-negative.")
    excess = distance - dead_zone
    if excess <= 0.0:
        return 0.0
    if transition <= 1e-12 or excess >= transition:
        return excess
    normalized = excess / transition
    response = transition * (
        6.0 * normalized**3
        - 8.0 * normalized**4
        + 3.0 * normalized**5
    )
    return float(response)


def stabilize_semantic_focus_path(
    focus_world_positions: np.ndarray,
    smoothing_seconds: float = AIM_TARGET_SMOOTHING_SECONDS,
    dead_zone_meters: float = AIM_TARGET_DEAD_ZONE_METERS,
    sample_rate: float = AIM_SAMPLE_RATE,
) -> tuple[np.ndarray, dict[str, float]]:
    """Suppress pose jitter without attaching the camera body to the actor."""

    values = np.asarray(focus_world_positions, dtype=np.float32)
    if values.ndim != 2 or values.shape[1] != 3 or len(values) == 0:
        raise ValueError("focus_world_positions must have shape [frame, 3].")
    if not math.isfinite(smoothing_seconds) or smoothing_seconds <= 0.0:
        raise ValueError("smoothing_seconds must be finite and positive.")
    if not math.isfinite(dead_zone_meters) or dead_zone_meters < 0.0:
        raise ValueError("dead_zone_meters must be finite and non-negative.")
    sigma = max(0.5, smoothing_seconds * sample_rate / 3.0)
    low_frequency = gaussian_filter1d(
        values,
        sigma=sigma,
        axis=0,
        mode="nearest",
        truncate=3.0,
    ).astype(np.float32)
    # One dead-zone radius is also a compact C2 engagement band.  Beyond this
    # band the mapping is exactly the previous unit-slope response, so large
    # intentional performer travel is neither attenuated nor delayed further.
    dead_zone_transition_meters = float(dead_zone_meters)
    stabilized = np.empty_like(low_frequency)
    stabilized[0] = low_frequency[0]
    for index in range(1, len(stabilized)):
        delta = low_frequency[index] - stabilized[index - 1]
        distance = float(np.linalg.norm(delta))
        response_distance = _c2_dead_zone_response_distance(
            distance,
            dead_zone_meters,
            dead_zone_transition_meters,
        )
        if response_distance <= 0.0 or distance <= 1e-12:
            stabilized[index] = stabilized[index - 1]
        else:
            stabilized[index] = (
                stabilized[index - 1]
                + delta * (response_distance / distance)
            )
    if len(stabilized) > 4:
        stabilized = gaussian_filter1d(
            stabilized,
            sigma=max(0.5, sigma * 0.18),
            axis=0,
            mode="nearest",
            truncate=3.0,
        ).astype(np.float32)
    raw_path = float(
        np.sum(np.linalg.norm(np.diff(values, axis=0), axis=1))
    )
    stabilized_path = float(
        np.sum(np.linalg.norm(np.diff(stabilized, axis=0), axis=1))
    )
    return stabilized, {
        "aimTargetRawPathMeters": raw_path,
        "aimTargetStabilizedPathMeters": stabilized_path,
        "aimTargetPathRetentionRatio": (
            stabilized_path / max(raw_path, 1e-6)
        ),
        "aimTargetSmoothingSeconds": float(smoothing_seconds),
        "aimTargetDeadZoneMeters": float(dead_zone_meters),
        "aimTargetDeadZoneTransitionMeters": dead_zone_transition_meters,
        "aimTargetDeadZoneResponse": "hysteretic_quintic_c2",
    }


def infer_semantic_lead_room(
    stabilized_focus: np.ndarray,
    root_rotations: np.ndarray,
    camera_rotations: np.ndarray,
    shot_type: str,
) -> tuple[float, dict[str, float | bool | str]]:
    """Infer a conservative screen-direction cue for automatic lead room."""

    frame_count = len(stabilized_focus)
    if frame_count == 0:
        raise ValueError("Lead-room inference requires at least one frame.")
    camera_right = train.quat_rotate(
        camera_rotations,
        np.broadcast_to(
            np.asarray([1.0, 0.0, 0.0], dtype=np.float32),
            (frame_count, 3),
        ),
    )
    representative_right = np.median(camera_right, axis=0)
    representative_right /= max(
        float(np.linalg.norm(representative_right)),
        1e-8,
    )
    sample_count = max(1, min(frame_count // 4, 30))
    early = np.median(stabilized_focus[:sample_count], axis=0)
    late = np.median(stabilized_focus[-sample_count:], axis=0)
    motion_screen = float(np.dot(late - early, representative_right))
    lag = max(1, min(15, frame_count // 5))
    motion_samples = np.sum(
        (
            stabilized_focus[lag:]
            - stabilized_focus[:-lag]
        )
        * camera_right[lag:],
        axis=1,
    )
    motion_nonzero = np.abs(motion_samples) >= 0.015
    motion_sign = float(np.sign(motion_screen))
    motion_consistency = (
        float(
            np.mean(
                np.sign(motion_samples[motion_nonzero]) == motion_sign
            )
        )
        if motion_sign != 0.0 and np.any(motion_nonzero)
        else 0.0
    )
    motion_score = min(abs(motion_screen) / 0.55, 1.0) * motion_consistency

    root_forward = train.quat_rotate(
        root_rotations,
        np.broadcast_to(
            np.asarray([0.0, 0.0, 1.0], dtype=np.float32),
            (frame_count, 3),
        ),
    )
    facing_samples = np.sum(root_forward * camera_right, axis=1)
    facing_screen = float(np.median(facing_samples))
    facing_sign = float(np.sign(facing_screen))
    facing_nonzero = np.abs(facing_samples) >= 0.25
    facing_consistency = (
        float(
            np.mean(
                np.sign(facing_samples[facing_nonzero]) == facing_sign
            )
        )
        if facing_sign != 0.0 and np.any(facing_nonzero)
        else 0.0
    )
    facing_score = min(abs(facing_screen) / 0.75, 1.0) * facing_consistency

    motion_valid = motion_score >= 0.45
    facing_valid = facing_score >= 0.62
    evidence_sign = 0.0
    evidence = "none"
    if motion_valid and facing_valid and motion_sign != facing_sign:
        if motion_score >= facing_score * 1.5:
            evidence_sign = motion_sign
            evidence = "motion_over_conflicting_facing"
        elif facing_score >= motion_score * 1.5:
            evidence_sign = facing_sign
            evidence = "facing_over_conflicting_motion"
        else:
            evidence = "conflicting"
    elif motion_valid and facing_valid:
        evidence_sign = motion_sign
        evidence = "motion_and_facing"
    elif motion_valid:
        evidence_sign = motion_sign
        evidence = "motion"
    elif facing_valid:
        evidence_sign = facing_sign
        evidence = "facing"

    lead_applied = evidence_sign != 0.0
    target_u = 0.5
    if lead_applied:
        # Positive screen direction means the subject belongs on the left,
        # leaving open space in front of the motion/facing direction.
        target_u -= evidence_sign * AUTOMATIC_LEAD_ROOM_UV[shot_type]
    return float(target_u), {
        "automaticLeadRoomApplied": bool(lead_applied),
        "automaticLeadRoomEvidence": evidence,
        "automaticLeadRoomDirectionSign": float(evidence_sign),
        "automaticLeadRoomMotionScreenMeters": motion_screen,
        "automaticLeadRoomMotionConsistency": motion_consistency,
        "automaticLeadRoomMotionScore": float(motion_score),
        "automaticLeadRoomFacingScreen": facing_screen,
        "automaticLeadRoomFacingConsistency": facing_consistency,
        "automaticLeadRoomFacingScore": float(facing_score),
        "automaticLeadRoomTargetU": float(target_u),
    }


def _filled_low_frequency_composition(
    composition: np.ndarray,
    sample_rate: float = AIM_SAMPLE_RATE,
) -> np.ndarray:
    values = np.asarray(composition[:, :2], dtype=np.float64).copy()
    valid = (
        (np.asarray(composition[:, 3]) >= 0.5)
        & np.all(np.isfinite(values), axis=1)
    )
    indices = np.arange(len(values), dtype=np.float64)
    for axis in range(2):
        axis_valid = valid & np.isfinite(values[:, axis])
        if np.any(axis_valid):
            values[:, axis] = np.interp(
                indices,
                indices[axis_valid],
                values[axis_valid, axis],
            )
        else:
            values[:, axis] = 0.5
    sigma = max(
        0.5,
        AIM_SOURCE_RESIDUAL_SMOOTHING_SECONDS * sample_rate / 3.0,
    )
    return gaussian_filter1d(
        values,
        sigma=sigma,
        axis=0,
        mode="nearest",
        truncate=3.0,
    ).astype(np.float32)


def build_semantic_aim_composition(
    source_composition: np.ndarray,
    stabilized_focus: np.ndarray,
    root_rotations: np.ndarray,
    camera_rotations: np.ndarray,
    shot_type: str,
    horizontal_framing: str,
    source_aspect_reliability: float,
) -> tuple[np.ndarray, dict[str, float | bool | str]]:
    """Build a stable viewport target with bounded authored residual motion."""

    if horizontal_framing not in {
        "source",
        "balanced",
        "centered",
        "left_third",
        "right_third",
    }:
        raise ValueError(
            f"Unknown horizontal framing policy: {horizontal_framing}"
        )
    low_frequency = _filled_low_frequency_composition(source_composition)
    valid = (
        (source_composition[:, 3] >= 0.5)
        & np.all(np.isfinite(source_composition[:, :2]), axis=1)
    )
    source_median = (
        np.median(low_frequency[valid], axis=0)
        if np.any(valid)
        else np.asarray([0.5, 0.5], dtype=np.float32)
    )
    lead_metrics: dict[str, float | bool | str]
    if horizontal_framing == "balanced":
        target_u, lead_metrics = infer_semantic_lead_room(
            stabilized_focus,
            root_rotations,
            camera_rotations,
            shot_type,
        )
        horizontal_residual_scale = 0.65 * source_aspect_reliability
    elif horizontal_framing == "centered":
        target_u = 0.5
        horizontal_residual_scale = 0.0
        lead_metrics = {
            "automaticLeadRoomApplied": False,
            "automaticLeadRoomEvidence": "explicit_center",
        }
    elif horizontal_framing == "left_third":
        target_u = 1.0 / 3.0
        horizontal_residual_scale = 0.0
        lead_metrics = {
            "automaticLeadRoomApplied": False,
            "automaticLeadRoomEvidence": "explicit_left_third",
        }
    elif horizontal_framing == "right_third":
        target_u = 2.0 / 3.0
        horizontal_residual_scale = 0.0
        lead_metrics = {
            "automaticLeadRoomApplied": False,
            "automaticLeadRoomEvidence": "explicit_right_third",
        }
    else:
        target_u = float(np.clip(source_median[0], 0.28, 0.72))
        horizontal_residual_scale = source_aspect_reliability
        lead_metrics = {
            "automaticLeadRoomApplied": False,
            "automaticLeadRoomEvidence": "legacy_source",
        }

    vertical_bounds = {
        "wide": (0.42, 0.58),
        "medium": (0.42, 0.57),
        "close": (0.43, 0.56),
    }[shot_type]
    source_vertical = float(
        np.clip(source_median[1], vertical_bounds[0], vertical_bounds[1])
    )
    target_v = 0.5 + (source_vertical - 0.5) * 0.55
    residual = low_frequency - source_median
    residual[:, 0] = np.clip(
        residual[:, 0],
        -AIM_SOURCE_RESIDUAL_HORIZONTAL_LIMIT,
        AIM_SOURCE_RESIDUAL_HORIZONTAL_LIMIT,
    ) * horizontal_residual_scale
    residual[:, 1] = np.clip(
        residual[:, 1],
        -AIM_SOURCE_RESIDUAL_VERTICAL_LIMIT,
        AIM_SOURCE_RESIDUAL_VERTICAL_LIMIT,
    ) * (0.65 * source_aspect_reliability)
    desired = np.column_stack(
        (
            np.full(len(source_composition), target_u, dtype=np.float32),
            np.full(len(source_composition), target_v, dtype=np.float32),
        )
    ) + residual
    desired[:, 0] = np.clip(desired[:, 0], 0.25, 0.75)
    desired[:, 1] = np.clip(desired[:, 1], 0.34, 0.66)
    lead_metrics.update(
        {
            "semanticAimBaseU": float(target_u),
            "semanticAimBaseV": float(target_v),
            "sourceAimResidualHorizontalP90Uv": float(
                np.quantile(np.abs(residual[:, 0]), 0.9)
            ),
            "sourceAimResidualVerticalP90Uv": float(
                np.quantile(np.abs(residual[:, 1]), 0.9)
            ),
            "sourceAimResidualReliability": float(
                source_aspect_reliability
            ),
        }
    )
    return desired.astype(np.float32), lead_metrics


def _bounded_vector(value: np.ndarray, maximum_length: float) -> np.ndarray:
    """Return ``value`` projected into a Euclidean length bound."""

    length = float(np.linalg.norm(value))
    if length <= maximum_length or length <= 1e-12:
        return value
    return value * (maximum_length / length)


def _quaternion_to_rotvec(quaternions: np.ndarray) -> np.ndarray:
    """Convert xyzw quaternions to shortest-arc rotation vectors.

    This small vectorized implementation avoids constructing a SciPy
    ``Rotation`` object for every generated frame.  The controller calls it in
    its hot loop; SciPy remains useful elsewhere for bulk, offline operations.
    """

    values = np.asarray(quaternions, dtype=np.float64)
    if values.shape[-1] != 4:
        raise ValueError("quaternions must have a final dimension of four.")
    values = values / np.maximum(
        np.linalg.norm(values, axis=-1, keepdims=True),
        1e-12,
    )
    values = values.copy()
    values[values[..., 3] < 0.0] *= -1.0
    vector = values[..., :3]
    vector_length = np.linalg.norm(vector, axis=-1)
    angle = 2.0 * np.arctan2(
        vector_length,
        np.clip(values[..., 3], -1.0, 1.0),
    )
    scale = np.empty_like(vector_length)
    regular = vector_length > 1e-10
    scale[regular] = angle[regular] / vector_length[regular]
    scale[~regular] = 2.0
    return vector * scale[..., None]


def _rotvec_to_quaternion(rotation_vectors: np.ndarray) -> np.ndarray:
    """Convert rotation vectors to normalized xyzw quaternions."""

    values = np.asarray(rotation_vectors, dtype=np.float64)
    if values.shape[-1] != 3:
        raise ValueError("rotation_vectors must have a final dimension of three.")
    angle = np.linalg.norm(values, axis=-1)
    half_angle = 0.5 * angle
    scale = np.empty_like(angle)
    regular = angle > 1e-10
    scale[regular] = np.sin(half_angle[regular]) / angle[regular]
    # sin(theta / 2) / theta approaches one half at the origin.
    scale[~regular] = 0.5
    return np.concatenate(
        (
            values * scale[..., None],
            np.cos(half_angle)[..., None],
        ),
        axis=-1,
    )


def _quaternion_to_rotvec_single(quaternion: np.ndarray) -> np.ndarray:
    """Allocation-light shortest-arc quaternion log for the controller loop."""

    x, y, z, w = (float(value) for value in quaternion)
    quaternion_length = math.sqrt(x * x + y * y + z * z + w * w)
    if quaternion_length <= 1e-12:
        return np.zeros(3, dtype=np.float64)
    inverse_length = 1.0 / quaternion_length
    x *= inverse_length
    y *= inverse_length
    z *= inverse_length
    w *= inverse_length
    if w < 0.0:
        x, y, z, w = -x, -y, -z, -w
    vector_length = math.sqrt(x * x + y * y + z * z)
    if vector_length <= 1e-10:
        return np.asarray([2.0 * x, 2.0 * y, 2.0 * z], dtype=np.float64)
    scale = 2.0 * math.atan2(vector_length, min(1.0, max(-1.0, w)))
    scale /= vector_length
    return np.asarray([x * scale, y * scale, z * scale], dtype=np.float64)


def _multiply_single_quaternion(left: np.ndarray, right: np.ndarray) -> np.ndarray:
    """Fast scalar xyzw quaternion product used by the frame loop."""

    ax, ay, az, aw = (float(value) for value in left)
    bx, by, bz, bw = (float(value) for value in right)
    return np.asarray(
        [
            aw * bx + bw * ax + ay * bz - az * by,
            aw * by + bw * ay + az * bx - ax * bz,
            aw * bz + bw * az + ax * by - ay * bx,
            aw * bw - ax * bx - ay * by - az * bz,
        ],
        dtype=np.float64,
    )


def _robust_angular_feed_forward(
    desired_velocity: np.ndarray,
    sample_rate: float,
) -> np.ndarray:
    """Keep sustained authored pans while rejecting one-frame target jumps."""

    velocity = np.asarray(desired_velocity, dtype=np.float64)
    if len(velocity) < 2:
        return velocity.copy()
    if len(velocity) == 2:
        disagreement = float(np.linalg.norm(velocity[1] - velocity[0]))
        persistent_scale = max(
            math.radians(1.0),
            0.15
            * max(
                float(np.linalg.norm(velocity[0])),
                float(np.linalg.norm(velocity[1])),
            ),
        )
        if disagreement <= persistent_scale:
            return velocity.copy()
        # Two inconsistent steps contain no evidence of a sustained pan.  A
        # zero feed-forward lets the position tracker make the safest possible
        # move instead of misclassifying their arithmetic mean as intent.
        return np.zeros_like(velocity)
    # A truncated five-key median distinguishes an authored pan from a pose
    # discontinuity.  NaN padding gives the first/last key a genuine truncated
    # window instead of repeating the boundary spike.
    padded = np.pad(
        velocity,
        ((2, 2), (0, 0)),
        mode="constant",
        constant_values=np.nan,
    )
    windows = np.lib.stride_tricks.sliding_window_view(
        padded,
        5,
        axis=0,
    )
    local_median = np.nanmedian(windows, axis=-1)
    disagreement = np.linalg.norm(velocity - local_median, axis=1)
    tolerance = np.maximum(
        math.radians(1.0),
        0.15 * np.linalg.norm(local_median, axis=1),
    )
    persistent = np.where(
        (disagreement <= tolerance)[:, None],
        velocity,
        local_median,
    )
    # Sub-frame noise in a source quaternion should not become target
    # acceleration.  Reflect mode preserves a constant pan and the component
    # integral, unlike nearest padding at a shot boundary.
    sigma_frames = max(0.0, 0.0125 * float(sample_rate))
    if sigma_frames <= 1e-8 or len(persistent) < 3:
        return persistent
    return gaussian_filter1d(
        persistent,
        sigma=sigma_frames,
        axis=0,
        mode="reflect",
    )


def _integrate_angular_velocity(
    initial_rotation: np.ndarray,
    angular_velocity: np.ndarray,
    sample_rate: float,
) -> np.ndarray:
    """Integrate body-local angular velocity without per-frame SciPy objects."""

    velocity = np.asarray(angular_velocity, dtype=np.float64)
    output = np.empty((len(velocity) + 1, 4), dtype=np.float64)
    output[0] = np.asarray(initial_rotation, dtype=np.float64)
    output[0] /= max(float(np.linalg.norm(output[0])), 1e-12)
    steps = _rotvec_to_quaternion(velocity / float(sample_rate))
    for index, step in enumerate(steps, start=1):
        output[index] = _multiply_single_quaternion(output[index - 1], step)
        output[index] /= max(float(np.linalg.norm(output[index])), 1e-12)
    ensure_quaternion_continuity(output, 0, len(output))
    return output


def _angular_velocity_dynamics_vectors(
    angular_velocity: np.ndarray,
    sample_rate: float,
) -> tuple[np.ndarray, np.ndarray]:
    """Return within-shot acceleration and jerk for an angular velocity path."""

    velocity = np.asarray(angular_velocity, dtype=np.float64)
    acceleration = np.diff(velocity, axis=0) * sample_rate
    jerk = np.diff(acceleration, axis=0) * sample_rate
    return acceleration, jerk


def _angular_velocity_tracking_deviation_metrics(
    candidate_velocity: np.ndarray,
    reference_velocity: np.ndarray,
    sample_rate: float,
) -> dict[str, float]:
    """Estimate response lag without integrating every smoothing candidate.

    Both paths are body-local per-frame rotation vectors.  Their cumulative
    difference is a conservative small-angle proxy used only to keep the
    minimum-jerk search close to the acceleration-bounded reference path.  The
    selected quaternion path is integrated and audited exactly afterwards.
    """

    candidate = np.asarray(candidate_velocity, dtype=np.float64)
    reference = np.asarray(reference_velocity, dtype=np.float64)
    if (
        candidate.ndim != 2
        or candidate.shape[1] != 3
        or candidate.shape != reference.shape
    ):
        raise ValueError(
            "candidate_velocity and reference_velocity must have matching "
            "[sample, 3] shapes."
        )
    if not math.isfinite(sample_rate) or sample_rate <= 0.0:
        raise ValueError("sample_rate must be finite and positive.")
    if not np.isfinite(candidate).all() or not np.isfinite(reference).all():
        raise ValueError("angular velocity paths must contain only finite values.")
    if len(candidate) == 0:
        deviation = np.asarray([0.0], dtype=np.float64)
    else:
        cumulative_difference = np.cumsum(
            (candidate - reference) / float(sample_rate),
            axis=0,
        )
        deviation = np.degrees(
            np.linalg.norm(cumulative_difference, axis=1)
        )
    return {
        "p90": float(np.quantile(deviation, 0.90)),
        "maximum": float(np.max(deviation)),
        "final": float(deviation[-1]),
    }


def _angular_tracking_deviation_within_budget(
    p90_degrees: object,
    maximum_degrees: object,
    final_degrees: object,
) -> bool:
    """Validate all exact tracking values and apply the authored budgets."""

    raw_values = (p90_degrees, maximum_degrees, final_degrees)
    if any(
        not isinstance(value, (int, float)) or isinstance(value, bool)
        for value in raw_values
    ):
        return False
    values = tuple(float(value) for value in raw_values)
    if any(not math.isfinite(value) or value < 0.0 for value in values):
        return False
    p90, maximum, final = values
    return bool(
        p90 <= AIM_MINIMUM_JERK_TRACKING_P90_BUDGET_DEGREES + 1e-12
        and maximum
        <= AIM_MINIMUM_JERK_TRACKING_MAXIMUM_BUDGET_DEGREES + 1e-12
        and final <= AIM_MINIMUM_JERK_TRACKING_FINAL_BUDGET_DEGREES + 1e-12
    )


def _minimum_jerk_candidate_objective(
    maximum_jerk_dps3: float,
    p95_jerk_dps3: float,
    tracking_deviation: dict[str, float],
    authored_target_dps3: float,
) -> float:
    """Balance authored-range jerk against a tightly bounded tracking lag."""

    return float(
        p95_jerk_dps3 / AIM_AUTHORED_ANGULAR_JERK_P95_TARGET_DPS3
        + 0.20 * maximum_jerk_dps3 / authored_target_dps3
        + 0.50
        * tracking_deviation["p90"]
        / AIM_MINIMUM_JERK_TRACKING_P90_BUDGET_DEGREES
        + 0.15
        * tracking_deviation["maximum"]
        / AIM_MINIMUM_JERK_TRACKING_MAXIMUM_BUDGET_DEGREES
        + 0.20
        * tracking_deviation["final"]
        / AIM_MINIMUM_JERK_TRACKING_FINAL_BUDGET_DEGREES
    )


def _quaternion_path_error_statistics(
    candidate_rotations: np.ndarray,
    reference_rotations: np.ndarray,
) -> dict[str, float]:
    """Return exact shortest-arc path error in degrees."""

    candidate = np.asarray(candidate_rotations, dtype=np.float64).copy()
    reference = np.asarray(reference_rotations, dtype=np.float64).copy()
    if (
        candidate.ndim != 2
        or candidate.shape[1] != 4
        or candidate.shape != reference.shape
        or len(candidate) == 0
    ):
        raise ValueError(
            "candidate_rotations and reference_rotations must have matching "
            "non-empty [frame, 4] shapes."
        )
    candidate /= np.maximum(
        np.linalg.norm(candidate, axis=1, keepdims=True),
        1e-12,
    )
    reference /= np.maximum(
        np.linalg.norm(reference, axis=1, keepdims=True),
        1e-12,
    )
    relative = train.quat_multiply(
        train.quat_conjugate(reference),
        candidate,
    )
    relative[relative[:, 3] < 0.0] *= -1.0
    errors = np.degrees(
        np.linalg.norm(_quaternion_to_rotvec(relative), axis=1)
    )
    return {
        "p90": float(np.quantile(errors, 0.90)),
        "maximum": float(np.max(errors)),
        "final": float(errors[-1]),
    }


def _causal_smooth_angular_velocity(
    angular_velocity: np.ndarray,
    alpha: float,
    initial_velocity: np.ndarray,
) -> np.ndarray:
    """Low-pass angular velocity without looking into future target keys.

    ``initial_velocity`` is the persistent motion inferred at the shot entry.
    A legal constant pan therefore remains unchanged from its first interval,
    while an isolated pose jump starts responding only after that jump occurs.
    The positive one-pole kernel cannot invent a direction reversal on its own.
    """

    velocity = np.asarray(angular_velocity, dtype=np.float64)
    initial = np.asarray(initial_velocity, dtype=np.float64)
    if velocity.ndim != 2 or velocity.shape[1] != 3:
        raise ValueError("angular_velocity must have shape [sample, 3].")
    if initial.shape != (3,):
        raise ValueError("initial_velocity must have shape [3].")
    if not math.isfinite(alpha) or not 0.0 < alpha <= 1.0:
        raise ValueError("alpha must be finite and in the interval (0, 1].")
    if not np.isfinite(velocity).all() or not np.isfinite(initial).all():
        raise ValueError("angular velocities must contain only finite values.")
    if len(velocity) == 0:
        return velocity.copy()

    smoothed = np.empty_like(velocity)
    previous = initial.copy()
    for index, target in enumerate(velocity):
        previous = previous + alpha * (target - previous)
        smoothed[index] = previous
    return smoothed


def _quaternion_angular_dynamics_vectors(
    rotations: np.ndarray,
    sample_rate: float,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Return per-step angular velocity, acceleration and jerk rot-vectors."""

    values = np.asarray(rotations, dtype=np.float64).copy()
    if values.ndim != 2 or values.shape[1] != 4 or len(values) == 0:
        raise ValueError("rotations must have shape [frame, 4].")
    if not math.isfinite(sample_rate) or sample_rate <= 0.0:
        raise ValueError("sample_rate must be finite and positive.")
    if not np.isfinite(values).all():
        raise ValueError("rotations must contain only finite values.")
    values /= np.maximum(np.linalg.norm(values, axis=1, keepdims=True), 1e-8)
    ensure_quaternion_continuity(values, 0, len(values))
    if len(values) == 1:
        empty = np.empty((0, 3), dtype=np.float64)
        return empty, empty.copy(), empty.copy()
    relative = train.quat_multiply(
        train.quat_conjugate(values[:-1]),
        values[1:],
    )
    relative[relative[:, 3] < 0.0] *= -1.0
    angular_velocity = _quaternion_to_rotvec(relative) * sample_rate
    angular_acceleration, angular_jerk = _angular_velocity_dynamics_vectors(
        angular_velocity,
        sample_rate,
    )
    return angular_velocity, angular_acceleration, angular_jerk


def quaternion_angular_dynamics_metrics(
    rotations: np.ndarray,
    sample_rate: float = AIM_SAMPLE_RATE,
) -> dict[str, float]:
    """Measure final quaternion speed, acceleration and jerk in degrees."""

    velocity, acceleration, jerk = _quaternion_angular_dynamics_vectors(
        rotations,
        sample_rate,
    )

    def magnitudes(values: np.ndarray) -> np.ndarray:
        if len(values) == 0:
            return np.asarray([0.0], dtype=np.float64)
        return np.degrees(np.linalg.norm(values, axis=1))

    speed = magnitudes(velocity)
    acceleration_magnitude = magnitudes(acceleration)
    jerk_magnitude = magnitudes(jerk)
    return {
        "aimAngularSpeedDegreesPerSecondMax": float(np.max(speed)),
        "aimAngularSpeedDegreesPerSecondP95": float(np.quantile(speed, 0.95)),
        "aimAngularAccelerationDegreesPerSecondSquaredMax": float(
            np.max(acceleration_magnitude)
        ),
        "aimAngularAccelerationDegreesPerSecondSquaredP95": float(
            np.quantile(acceleration_magnitude, 0.95)
        ),
        "aimAngularJerkDegreesPerSecondCubedMax": float(
            np.max(jerk_magnitude)
        ),
        "aimAngularJerkDegreesPerSecondCubedP95": float(
            np.quantile(jerk_magnitude, 0.95)
        ),
    }


def aim_rotation_dynamics_selection_penalty(metrics: dict[str, object]) -> float:
    """Softly prefer candidates that do not live at the angular-jerk ceiling."""

    jerk_limit = float(
        metrics.get(
            "aimAngularJerkLimitDegreesPerSecondCubed",
            AIM_MAXIMUM_ANGULAR_JERK_DPS3,
        )
    )
    if not math.isfinite(jerk_limit) or jerk_limit <= 0.0:
        raise ValueError("Angular jerk limit must be finite and positive.")
    peak_ratio = float(
        metrics.get("aimAngularJerkDegreesPerSecondCubedMax", 0.0)
    ) / jerk_limit
    p95_ratio = float(
        metrics.get("aimAngularJerkDegreesPerSecondCubedP95", 0.0)
    ) / jerk_limit
    near_limit_ratio = float(
        metrics.get("aimAngularJerkNearLimitFrameRatio", 0.0)
    )

    def normalized_excess(value: float, free_ratio: float) -> float:
        return float(
            np.clip(
                (value - free_ratio) / max(1.0 - free_ratio, 1e-8),
                0.0,
                1.0,
            )
        )

    return float(
        AIM_ANGULAR_JERK_SELECTION_WEIGHT
        * (
            0.70
            * normalized_excess(
                p95_ratio,
                AIM_ANGULAR_JERK_P95_FREE_RATIO,
            )
            + 0.20
            * normalized_excess(
                peak_ratio,
                AIM_ANGULAR_JERK_PEAK_FREE_RATIO,
            )
            + 0.10 * float(np.clip(near_limit_ratio, 0.0, 1.0))
        )
    )


def limit_quaternion_kinematics(
    desired_rotations: np.ndarray,
    sample_rate: float = AIM_SAMPLE_RATE,
    maximum_speed_dps: float = AIM_MAXIMUM_ANGULAR_SPEED_DPS,
    maximum_acceleration_dps2: float = (
        AIM_MAXIMUM_ANGULAR_ACCELERATION_DPS2
    ),
    maximum_jerk_dps3: float = AIM_MAXIMUM_ANGULAR_JERK_DPS3,
    authored_quality_target_dps3: float = (
        AIM_AUTHORED_ANGULAR_JERK_TARGET_DPS3
    ),
) -> tuple[np.ndarray, dict[str, object]]:
    """Bake stable quaternion keys with within-shot C2 dynamics bounds.

    The first stage is an acceleration-bounded, moving-target tracker.  Its
    robust feed-forward preserves legal constant pans from the first key while
    isolated pose jumps are handled as position errors.  The second stage
    evaluates the complete causal positive-kernel response family and chooses
    the minimum authored-range jerk objective within a strict tracking budget.
    It cannot move before an internal target change, avoids the previous
    bang-bang controller's static-target limit cycle, and never invents an
    imaginary zero-velocity key at a hard cut.
    """

    desired = np.asarray(desired_rotations, dtype=np.float64).copy()
    if desired.ndim != 2 or desired.shape[1] != 4 or len(desired) == 0:
        raise ValueError("desired_rotations must have shape [frame, 4].")
    if not np.isfinite(desired).all():
        raise ValueError("desired_rotations must contain only finite values.")
    for label, value in (
        ("sample_rate", sample_rate),
        ("maximum_speed_dps", maximum_speed_dps),
        ("maximum_acceleration_dps2", maximum_acceleration_dps2),
        ("maximum_jerk_dps3", maximum_jerk_dps3),
        ("authored_quality_target_dps3", authored_quality_target_dps3),
    ):
        if not math.isfinite(value) or value <= 0.0:
            raise ValueError(f"{label} must be finite and positive.")
    desired /= np.maximum(np.linalg.norm(desired, axis=1, keepdims=True), 1e-8)
    ensure_quaternion_continuity(desired, 0, len(desired))
    delta_time = 1.0 / sample_rate
    speed_limit = math.radians(maximum_speed_dps)
    acceleration_limit = math.radians(maximum_acceleration_dps2)
    jerk_limit = math.radians(maximum_jerk_dps3)
    authored_quality_target_dps3 = min(
        float(authored_quality_target_dps3),
        float(maximum_jerk_dps3),
    )
    if len(desired) == 1:
        final_output = desired.astype(np.float32)
        dynamics = quaternion_angular_dynamics_metrics(final_output, sample_rate)
        dynamics.update(
            {
                "aimAngularSpeedLimitDegreesPerSecond": float(maximum_speed_dps),
                "aimAngularAccelerationLimitDegreesPerSecondSquared": float(
                    maximum_acceleration_dps2
                ),
                "aimAngularJerkLimitDegreesPerSecondCubed": float(
                    maximum_jerk_dps3
                ),
                "aimAngularJerkAuthoredTargetDegreesPerSecondCubed": float(
                    authored_quality_target_dps3
                ),
                "aimAngularJerkAuthoredTargetPassed": True,
                "aimAngularJerkNearLimitFrameRatio": 0.0,
                "aimAngularJerkNearAuthoredTargetFrameRatio": 0.0,
                "aimAngularKinematicLimitScale": 1.0,
                "aimAngularVelocitySmoothingSigmaFrames": 0.0,
                "aimAngularVelocityCausalSmoothingAlpha": 1.0,
                "aimAngularMinimumJerkSelectionPolicy": (
                    AIM_MINIMUM_JERK_SELECTION_POLICY_VERSION
                ),
                "aimAngularSmoothingCandidateCount": 1,
                "aimAngularSmoothingHardSafeCandidateCount": 1,
                "aimAngularMinimumJerkTrackingBudgetPassed": True,
                "aimAngularMinimumJerkProxyTrackingBudgetPassed": True,
                "aimAngularMinimumJerkSelectionObjective": 0.0,
                "aimAngularReferenceDeviationDegreesP90": 0.0,
                "aimAngularReferenceDeviationDegreesMax": 0.0,
                "aimAngularReferenceDeviationDegreesFinal": 0.0,
                "aimAngularReferenceDeviationProxyDegreesP90": 0.0,
                "aimAngularReferenceDeviationProxyDegreesMax": 0.0,
                "aimAngularReferenceDeviationProxyDegreesFinal": 0.0,
            }
        )
        dynamics["aimRotationDynamicsSelectionPenalty"] = (
            aim_rotation_dynamics_selection_penalty(dynamics)
        )
        return final_output, dynamics

    desired_relative = train.quat_multiply(
        train.quat_conjugate(desired[:-1]),
        desired[1:],
    )
    desired_relative[desired_relative[:, 3] < 0.0] *= -1.0
    desired_velocity = _quaternion_to_rotvec(desired_relative) * sample_rate
    feed_forward = _robust_angular_feed_forward(
        desired_velocity,
        sample_rate,
    )
    feed_forward = np.asarray(
        [_bounded_vector(value, speed_limit) for value in feed_forward],
        dtype=np.float64,
    )

    # Never initialize motion from a future-informed median when the raw first
    # interval is a hold: that caused frame-1 pre-echo for pans beginning at
    # frames 1/2/3.  When the first interval itself moves, the robust value is
    # still useful to distinguish a legal constant pan from an instantaneous
    # pose step, so the established step-settling behavior is preserved.
    entry_velocity = (
        np.zeros(3, dtype=np.float64)
        if float(np.linalg.norm(desired_velocity[0])) <= 1e-10
        else feed_forward[0].copy()
    )
    entry_velocity = _bounded_vector(entry_velocity, speed_limit)
    previous_velocity = entry_velocity.copy()
    base_output = np.empty_like(desired)
    base_output[0] = desired[0]
    base_velocities: list[np.ndarray] = []
    for index in range(1, len(desired)):
        previous_rotation = base_output[index - 1]
        error_quaternion = _multiply_single_quaternion(
            np.asarray(
                [
                    -previous_rotation[0],
                    -previous_rotation[1],
                    -previous_rotation[2],
                    previous_rotation[3],
                ],
                dtype=np.float64,
            ),
            desired[index],
        )
        if error_quaternion[3] < 0.0:
            error_quaternion *= -1.0
        error = _quaternion_to_rotvec_single(error_quaternion)
        target_velocity = feed_forward[index - 1]
        # The robust feed-forward filter may inspect nearby future keys to
        # distinguish a real pan from a one-frame target glitch.  Never let
        # that classification move an already aligned camera before the raw
        # target itself starts moving inside the shot.
        if (
            float(np.linalg.norm(error)) <= 1e-10
            and float(np.linalg.norm(desired_velocity[index - 1])) <= 1e-10
        ):
            target_velocity = np.zeros(3, dtype=np.float64)
        # Remove the authored one-frame motion from the current orientation
        # error.  An exactly tracked constant pan then has zero residual and is
        # left untouched; a static pose step retains the full residual.
        residual = error - target_velocity * delta_time
        residual_length = float(np.linalg.norm(residual))
        if residual_length > 1e-12:
            correction_speed = min(
                math.sqrt(2.0 * acceleration_limit * residual_length),
                residual_length / delta_time,
            )
            target_velocity = target_velocity + residual * (
                correction_speed / residual_length
            )
            target_velocity = _bounded_vector(target_velocity, speed_limit)
        else:
            target_velocity = _bounded_vector(target_velocity, speed_limit)

        velocity_change = _bounded_vector(
            target_velocity - previous_velocity,
            acceleration_limit * delta_time,
        )
        velocity = previous_velocity + velocity_change
        # Both endpoints are in the convex speed ball, so this is normally a
        # no-op and only protects against accumulated floating-point error.
        velocity = _bounded_vector(velocity, speed_limit)
        step_quaternion = _rotvec_to_quaternion(velocity * delta_time)
        base_output[index] = _multiply_single_quaternion(
            base_output[index - 1],
            step_quaternion,
        )
        base_output[index] /= max(
            float(np.linalg.norm(base_output[index])),
            1e-12,
        )
        previous_velocity = velocity
        base_velocities.append(velocity)

    velocity_array = np.asarray(base_velocities, dtype=np.float64)
    # Float32 quaternion serialization introduces a few dps3 of round-trip
    # noise for very short paths.  Keep modest headroom here and audit the
    # serialized result again below.
    speed_headroom = 0.9999
    acceleration_headroom = 0.9998
    jerk_headroom = 0.9975
    speed_contract = speed_limit * speed_headroom
    acceleration_contract = acceleration_limit * acceleration_headroom
    jerk_contract = jerk_limit * jerk_headroom
    authored_jerk_contract = (
        math.radians(authored_quality_target_dps3) * jerk_headroom
    )
    smoothing_candidates = (
        1.0,
        0.8,
        2.0 / 3.0,
        0.5,
        0.4,
        1.0 / 3.0,
        0.3,
        0.25,
        0.2,
        0.15,
        0.1,
        0.075,
        0.05,
        0.025,
        0.01,
    )
    smoothing_audits: list[dict[str, object]] = []
    for smoothing_alpha in smoothing_candidates:
        candidate_velocity = _causal_smooth_angular_velocity(
            velocity_array,
            smoothing_alpha,
            entry_velocity,
        )
        maximum_speed = float(
            np.max(np.linalg.norm(candidate_velocity, axis=1), initial=0.0)
        )
        if maximum_speed > speed_contract:
            candidate_velocity *= speed_contract / maximum_speed
        candidate_acceleration, candidate_jerk = (
            _angular_velocity_dynamics_vectors(
                candidate_velocity,
                sample_rate,
            )
        )
        maximum_acceleration = float(
            np.max(np.linalg.norm(candidate_acceleration, axis=1), initial=0.0)
        )
        maximum_jerk = float(
            np.max(np.linalg.norm(candidate_jerk, axis=1), initial=0.0)
        )
        jerk_magnitudes_dps3 = np.degrees(
            np.linalg.norm(candidate_jerk, axis=1)
        )
        maximum_jerk_dps3_candidate = math.degrees(maximum_jerk)
        p95_jerk_dps3_candidate = (
            float(np.quantile(jerk_magnitudes_dps3, 0.95))
            if len(jerk_magnitudes_dps3)
            else 0.0
        )
        tracking_deviation = _angular_velocity_tracking_deviation_metrics(
            candidate_velocity,
            velocity_array,
            sample_rate,
        )
        hard_safe = bool(
            maximum_acceleration <= acceleration_contract + 1e-12
            and maximum_jerk <= jerk_contract + 1e-12
        )
        tracking_budget_passed = _angular_tracking_deviation_within_budget(
            tracking_deviation["p90"],
            tracking_deviation["maximum"],
            tracking_deviation["final"],
        )
        authored_target_passed = bool(
            maximum_jerk <= authored_jerk_contract + 1e-12
        )
        smoothing_audits.append(
            {
                "velocity": candidate_velocity,
                "alpha": float(smoothing_alpha),
                "hardSafe": hard_safe,
                "trackingBudgetPassed": tracking_budget_passed,
                "authoredTargetPassed": authored_target_passed,
                "objective": _minimum_jerk_candidate_objective(
                    maximum_jerk_dps3_candidate,
                    p95_jerk_dps3_candidate,
                    tracking_deviation,
                    authored_quality_target_dps3,
                ),
                "trackingDeviation": tracking_deviation,
            }
        )

    hard_safe_audits = [
        audit for audit in smoothing_audits if audit["hardSafe"] is True
    ]
    tracking_safe_audits = [
        audit
        for audit in hard_safe_audits
        if audit["trackingBudgetPassed"] is True
    ]
    authored_quality_audits = [
        audit
        for audit in tracking_safe_audits
        if audit["authoredTargetPassed"] is True
    ]
    selection_pool = (
        authored_quality_audits
        or tracking_safe_audits
        or hard_safe_audits
    )
    selected_velocity: np.ndarray | None = None
    selected_alpha = 1.0
    selected_tracking_budget_passed = False
    selected_authored_target_passed = False
    selected_objective = float("inf")
    selected_tracking_deviation = {
        "p90": 0.0,
        "maximum": 0.0,
        "final": 0.0,
    }
    if selection_pool:
        selected_audit = min(
            selection_pool,
            key=lambda audit: (
                float(audit["objective"]),
                -float(audit["alpha"]),
            ),
        )
        selected_velocity = np.asarray(
            selected_audit["velocity"],
            dtype=np.float64,
        ).copy()
        selected_alpha = float(selected_audit["alpha"])
        selected_tracking_budget_passed = bool(
            selected_audit["trackingBudgetPassed"]
        )
        selected_authored_target_passed = bool(
            selected_audit["authoredTargetPassed"]
        )
        selected_objective = float(selected_audit["objective"])
        selected_tracking_deviation = dict(
            selected_audit["trackingDeviation"]
        )

    kinematic_limit_scale = 1.0
    if selected_velocity is None:
        # An extremely short or adversarial shot may not offer enough samples
        # for the causal smoothing family to meet every bound. Uniformly
        # scaling the stable base path preserves its direction and cannot
        # create a reversal
        # or limit cycle.  The downstream aim gate can reject the resulting lag.
        base_acceleration, base_jerk = _angular_velocity_dynamics_vectors(
            velocity_array,
            sample_rate,
        )
        maximum_speed = float(
            np.max(np.linalg.norm(velocity_array, axis=1), initial=0.0)
        )
        maximum_acceleration = float(
            np.max(np.linalg.norm(base_acceleration, axis=1), initial=0.0)
        )
        maximum_jerk = float(
            np.max(np.linalg.norm(base_jerk, axis=1), initial=0.0)
        )
        kinematic_limit_scale = min(
            1.0,
            speed_contract / max(maximum_speed, 1e-12),
            acceleration_contract / max(maximum_acceleration, 1e-12),
            jerk_contract / max(maximum_jerk, 1e-12),
        )
        selected_velocity = velocity_array * kinematic_limit_scale
        selected_alpha = -1.0
        selected_tracking_deviation = (
            _angular_velocity_tracking_deviation_metrics(
                selected_velocity,
                velocity_array,
                sample_rate,
            )
        )
        selected_tracking_budget_passed = (
            _angular_tracking_deviation_within_budget(
                selected_tracking_deviation["p90"],
                selected_tracking_deviation["maximum"],
                selected_tracking_deviation["final"],
            )
        )
        fallback_acceleration, fallback_jerk = (
            _angular_velocity_dynamics_vectors(
                selected_velocity,
                sample_rate,
            )
        )
        fallback_jerk_magnitudes = np.degrees(
            np.linalg.norm(fallback_jerk, axis=1)
        )
        fallback_maximum_jerk_dps3 = (
            float(np.max(fallback_jerk_magnitudes))
            if len(fallback_jerk_magnitudes)
            else 0.0
        )
        fallback_p95_jerk_dps3 = (
            float(np.quantile(fallback_jerk_magnitudes, 0.95))
            if len(fallback_jerk_magnitudes)
            else 0.0
        )
        selected_authored_target_passed = bool(
            fallback_maximum_jerk_dps3
            <= authored_quality_target_dps3 * jerk_headroom + 1e-12
        )
        selected_objective = _minimum_jerk_candidate_objective(
            fallback_maximum_jerk_dps3,
            fallback_p95_jerk_dps3,
            selected_tracking_deviation,
            authored_quality_target_dps3,
        )

    # The public payload is float32.  Re-audit that actual representation and,
    # only for a numerical contract overshoot, uniformly reduce the already
    # causal path.  Uniform scaling cannot create anticipation or a reversal.
    final_output: np.ndarray | None = None
    dynamics: dict[str, object] | None = None
    serialized_jerk_limit_dps3 = (
        authored_quality_target_dps3
        if selected_authored_target_passed
        else maximum_jerk_dps3
    )
    for _ in range(4):
        output = _integrate_angular_velocity(
            desired[0],
            selected_velocity,
            sample_rate,
        )
        final_output = output.astype(np.float32)
        dynamics = quaternion_angular_dynamics_metrics(final_output, sample_rate)
        serialized_scale = min(
            1.0,
            maximum_speed_dps * speed_headroom
            / max(dynamics["aimAngularSpeedDegreesPerSecondMax"], 1e-12),
            maximum_acceleration_dps2 * acceleration_headroom
            / max(
                dynamics[
                    "aimAngularAccelerationDegreesPerSecondSquaredMax"
                ],
                1e-12,
            ),
            serialized_jerk_limit_dps3 * jerk_headroom
            / max(
                dynamics["aimAngularJerkDegreesPerSecondCubedMax"],
                1e-12,
            ),
        )
        if serialized_scale >= 1.0:
            break
        selected_velocity *= serialized_scale
        kinematic_limit_scale *= serialized_scale
    # If the last permitted iteration applied a numerical headroom scale, the
    # loop-local output still represents the preceding velocity.  Materialize
    # and audit the actual selected velocity once more before publishing.
    output = _integrate_angular_velocity(
        desired[0],
        selected_velocity,
        sample_rate,
    )
    final_output = output.astype(np.float32)
    dynamics = quaternion_angular_dynamics_metrics(final_output, sample_rate)
    assert final_output is not None
    assert dynamics is not None
    _, _, jerk_vectors = _quaternion_angular_dynamics_vectors(
        final_output,
        sample_rate,
    )
    jerk_magnitude_dps3 = (
        np.degrees(np.linalg.norm(jerk_vectors, axis=1))
        if len(jerk_vectors)
        else np.asarray([0.0], dtype=np.float64)
    )
    exact_reference_deviation = _quaternion_path_error_statistics(
        final_output,
        base_output,
    )
    final_tracking_budget_passed = (
        _angular_tracking_deviation_within_budget(
            exact_reference_deviation["p90"],
            exact_reference_deviation["maximum"],
            exact_reference_deviation["final"],
        )
    )
    final_authored_target_passed = bool(
        dynamics["aimAngularJerkDegreesPerSecondCubedMax"]
        <= authored_quality_target_dps3 + 1e-6
    )
    dynamics.update(
        {
            "aimAngularSpeedLimitDegreesPerSecond": float(maximum_speed_dps),
            "aimAngularAccelerationLimitDegreesPerSecondSquared": float(
                maximum_acceleration_dps2
            ),
            "aimAngularJerkLimitDegreesPerSecondCubed": float(
                maximum_jerk_dps3
            ),
            "aimAngularJerkAuthoredTargetDegreesPerSecondCubed": float(
                authored_quality_target_dps3
            ),
            "aimAngularJerkAuthoredTargetPassed": (
                final_authored_target_passed
            ),
            "aimAngularJerkNearLimitFrameRatio": float(
                np.mean(jerk_magnitude_dps3 >= maximum_jerk_dps3 * 0.9)
            ),
            "aimAngularJerkNearAuthoredTargetFrameRatio": float(
                np.mean(
                    jerk_magnitude_dps3
                    >= authored_quality_target_dps3 * 0.9
                )
            ),
            "aimAngularKinematicLimitScale": float(kinematic_limit_scale),
            # Retained for metadata compatibility; the controller no longer
            # uses a non-causal Gaussian kernel.
            "aimAngularVelocitySmoothingSigmaFrames": 0.0,
            "aimAngularVelocityCausalSmoothingAlpha": float(selected_alpha),
            "aimAngularMinimumJerkSelectionPolicy": (
                AIM_MINIMUM_JERK_SELECTION_POLICY_VERSION
            ),
            "aimAngularSmoothingCandidateCount": len(smoothing_audits),
            "aimAngularSmoothingHardSafeCandidateCount": len(
                hard_safe_audits
            ),
            "aimAngularMinimumJerkTrackingBudgetPassed": bool(
                final_tracking_budget_passed
            ),
            "aimAngularMinimumJerkProxyTrackingBudgetPassed": bool(
                selected_tracking_budget_passed
            ),
            "aimAngularMinimumJerkSelectionObjective": float(
                selected_objective
            ),
            "aimAngularReferenceDeviationProxyDegreesP90": float(
                selected_tracking_deviation["p90"]
            ),
            "aimAngularReferenceDeviationProxyDegreesMax": float(
                selected_tracking_deviation["maximum"]
            ),
            "aimAngularReferenceDeviationProxyDegreesFinal": float(
                selected_tracking_deviation["final"]
            ),
            "aimAngularReferenceDeviationDegreesP90": float(
                exact_reference_deviation["p90"]
            ),
            "aimAngularReferenceDeviationDegreesMax": float(
                exact_reference_deviation["maximum"]
            ),
            "aimAngularReferenceDeviationDegreesFinal": float(
                exact_reference_deviation["final"]
            ),
        }
    )
    dynamics["aimRotationDynamicsSelectionPenalty"] = (
        aim_rotation_dynamics_selection_penalty(dynamics)
    )
    return final_output, dynamics


def semantic_aim_quality_metrics(
    camera_positions: np.ndarray,
    camera_rotations: np.ndarray,
    fov_values: np.ndarray,
    dutch_values: np.ndarray,
    semantic_focus: np.ndarray,
    desired_uv: np.ndarray,
    aspect_ratio: float,
) -> dict[str, float | int | bool]:
    """Measure desired-ray aim and horizontal drift on every output frame."""

    effective_rotation = camera_rotation_with_dutch(
        camera_rotations,
        dutch_values,
    )
    tangent = np.tan(np.deg2rad(fov_values) * 0.5)
    desired_camera_ray = np.column_stack(
        (
            (desired_uv[:, 0] * 2.0 - 1.0) * tangent * aspect_ratio,
            (desired_uv[:, 1] * 2.0 - 1.0) * tangent,
            np.ones(len(desired_uv), dtype=np.float32),
        )
    )
    desired_world_ray = train.quat_rotate(
        effective_rotation,
        desired_camera_ray,
    )
    actual_world_ray = semantic_focus - camera_positions
    desired_world_ray /= np.maximum(
        np.linalg.norm(desired_world_ray, axis=1, keepdims=True),
        1e-8,
    )
    actual_world_ray /= np.maximum(
        np.linalg.norm(actual_world_ray, axis=1, keepdims=True),
        1e-8,
    )
    aim_error = np.degrees(
        np.arccos(
            np.clip(
                np.sum(desired_world_ray * actual_world_ray, axis=1),
                -1.0,
                1.0,
            )
        )
    )
    projected, depth = project_world_point(
        camera_positions,
        effective_rotation,
        fov_values,
        semantic_focus,
        aspect_ratio,
    )
    horizontal_error = np.abs(projected[:, 0] - desired_uv[:, 0])
    center_offset = np.abs(projected[:, 0] - 0.5)
    aim_warning = (depth <= 0.0) | (aim_error > AIM_ERROR_WARNING_DEGREES)
    horizontal_warning = (
        (depth <= 0.0)
        | (horizontal_error > AIM_HORIZONTAL_WARNING_UV)
    )
    allowed_longest_run = max(
        3,
        min(
            18,
            int(math.ceil(len(desired_uv) * AIM_LONGEST_WARNING_RUN_FRACTION)),
        ),
    )
    aim_p90 = float(np.quantile(aim_error, 0.9))
    horizontal_p90 = float(np.quantile(horizontal_error, 0.9))
    aim_longest = longest_true_run(aim_warning)
    horizontal_longest = longest_true_run(horizontal_warning)
    passed = bool(
        aim_p90 <= AIM_ERROR_P90_LIMIT_DEGREES
        and horizontal_p90 <= AIM_HORIZONTAL_P90_LIMIT_UV
        and aim_longest <= allowed_longest_run
        and horizontal_longest <= allowed_longest_run
    )
    return {
        "aimErrorDegreesMean": float(np.mean(aim_error)),
        "aimErrorDegreesP90": aim_p90,
        "aimErrorDegreesMax": float(np.max(aim_error)),
        "aimErrorWarningFrameRatio": float(np.mean(aim_warning)),
        "aimErrorWarningLongestRunFrames": int(aim_longest),
        "horizontalDesiredOffsetMean": float(np.mean(horizontal_error)),
        "horizontalDesiredOffsetP90": horizontal_p90,
        "horizontalDesiredOffsetMax": float(np.max(horizontal_error)),
        "horizontalDesiredOffsetWarningFrameRatio": float(
            np.mean(horizontal_warning)
        ),
        "horizontalDesiredOffsetWarningLongestRunFrames": int(
            horizontal_longest
        ),
        "horizontalCenterOffsetMean": float(np.mean(center_offset)),
        "horizontalCenterOffsetP90": float(np.quantile(center_offset, 0.9)),
        "horizontalCenterOffsetMax": float(np.max(center_offset)),
        "aimQualityAllowedLongestRunFrames": int(allowed_longest_run),
        "aimQualityPassed": passed,
    }


def apply_stabilized_semantic_baked_aim(
    camera_positions: np.ndarray,
    camera_rotations: np.ndarray,
    fov_values: np.ndarray,
    dutch_values: np.ndarray,
    joint_world_positions: np.ndarray,
    root_rotations: np.ndarray,
    source_composition: np.ndarray,
    shot_type: str,
    aspect_ratio: float,
    horizontal_framing: str,
    source_aspect_reliability: float,
) -> tuple[np.ndarray, np.ndarray, dict]:
    """Bake a stabilized target-aware rotation; no runtime LookAt is used."""

    semantic_focus = shot_focus_local(joint_world_positions, shot_type)
    stabilized_focus, stabilization_metrics = (
        stabilize_semantic_focus_path(semantic_focus)
    )
    desired_uv, lead_metrics = build_semantic_aim_composition(
        source_composition,
        stabilized_focus,
        root_rotations,
        camera_rotations,
        shot_type,
        horizontal_framing,
        source_aspect_reliability,
    )
    effective_source_rotation = camera_rotation_with_dutch(
        camera_rotations,
        dutch_values,
    )
    tangent = np.tan(np.deg2rad(fov_values) * 0.5)
    desired_camera_ray = np.column_stack(
        (
            (desired_uv[:, 0] * 2.0 - 1.0) * tangent * aspect_ratio,
            (desired_uv[:, 1] * 2.0 - 1.0) * tangent,
            np.ones(len(desired_uv), dtype=np.float32),
        )
    )
    desired_world_ray = train.quat_rotate(
        effective_source_rotation,
        desired_camera_ray,
    )
    correction = quaternion_between_vectors(
        desired_world_ray,
        stabilized_focus - camera_positions,
    )
    aimed_effective_rotation = train.quat_multiply(
        correction,
        effective_source_rotation,
    )
    dutch_rotation = Rotation.from_euler(
        "z",
        dutch_values,
        degrees=True,
    ).as_quat()
    aimed_base_rotation = train.quat_multiply(
        aimed_effective_rotation,
        train.quat_conjugate(dutch_rotation),
    )
    aimed_base_rotation /= np.maximum(
        np.linalg.norm(aimed_base_rotation, axis=1, keepdims=True),
        1e-8,
    )
    limited_rotation, kinematic_metrics = limit_quaternion_kinematics(
        aimed_base_rotation,
    )
    quality_metrics = semantic_aim_quality_metrics(
        camera_positions,
        limited_rotation,
        fov_values,
        dutch_values,
        semantic_focus,
        desired_uv,
        aspect_ratio,
    )
    return limited_rotation, desired_uv, {
        "aimPolicyVersion": AIM_POLICY_VERSION,
        "runtimeLookAtUsed": False,
        **stabilization_metrics,
        **lead_metrics,
        **kinematic_metrics,
        **quality_metrics,
    }


def apply_person_composition_correction(
    camera_positions: np.ndarray,
    camera_rotations: np.ndarray,
    fov_values: np.ndarray,
    dutch_values: np.ndarray,
    joint_world_positions: np.ndarray,
    desired_composition: np.ndarray,
    shot_type: str,
    aspect_ratio: float,
) -> tuple[np.ndarray, dict]:
    base_composition = build_source_composition_path(
        camera_positions,
        camera_rotations,
        fov_values,
        dutch_values,
        joint_world_positions,
        shot_type,
        aspect_ratio,
    )
    safe_bounds = {
        "wide": (0.1, 0.9, 0.12, 0.86),
        "medium": (0.12, 0.88, 0.12, 0.84),
        "close": (0.15, 0.85, 0.12, 0.82),
    }[shot_type]
    left, right, bottom, top = safe_bounds
    desired_uv = desired_composition[:, :2].copy()
    desired_uv[:, 0] = np.clip(desired_uv[:, 0], left, right)
    desired_uv[:, 1] = np.clip(desired_uv[:, 1], bottom, top)
    unsafe = (
        (base_composition[:, 3] < 0.5)
        | (base_composition[:, 0] < left)
        | (base_composition[:, 0] > right)
        | (base_composition[:, 1] < bottom)
        | (base_composition[:, 1] > top)
    )
    expanded_unsafe = (
        np.convolve(
            unsafe.astype(np.float32),
            np.ones(19, dtype=np.float32),
            mode="same",
        )
        > 0.0
    )

    focus_local = shot_focus_local(joint_world_positions, shot_type)
    effective_rotation = camera_rotation_with_dutch(
        camera_rotations,
        dutch_values,
    )
    tangent = np.tan(np.deg2rad(fov_values) * 0.5)
    desired_camera_ray = np.column_stack(
        (
            (desired_uv[:, 0] * 2.0 - 1.0)
            * tangent
            * aspect_ratio,
            (desired_uv[:, 1] * 2.0 - 1.0) * tangent,
            np.ones(len(desired_uv), dtype=np.float32),
        )
    )
    desired_world_ray = train.quat_rotate(
        effective_rotation,
        desired_camera_ray,
    )
    actual_world_ray = focus_local - camera_positions
    correction_quaternion = quaternion_between_vectors(
        desired_world_ray,
        actual_world_ray,
    )
    correction_rotvec = Rotation.from_quat(
        correction_quaternion
    ).as_rotvec()
    correction_rotvec[~expanded_unsafe] = 0.0
    correction_rotvec = smooth_segment(
        correction_rotvec.astype(np.float32),
        maximum_window=31,
    )

    maximum_angle_degrees = {
        "wide": 16.0,
        "medium": 13.0,
        "close": 11.0,
    }[shot_type]
    maximum_angle = math.radians(maximum_angle_degrees)
    magnitudes = np.linalg.norm(correction_rotvec, axis=1)
    too_large = magnitudes > maximum_angle
    if np.any(too_large):
        correction_rotvec[too_large] *= (
            maximum_angle / magnitudes[too_large]
        )[:, None]

    maximum_step = math.radians(0.4)
    for index in range(1, len(correction_rotvec)):
        step = correction_rotvec[index] - correction_rotvec[index - 1]
        step_length = float(np.linalg.norm(step))
        if step_length > maximum_step:
            correction_rotvec[index] = (
                correction_rotvec[index - 1]
                + step * (maximum_step / step_length)
            )
    for index in range(len(correction_rotvec) - 2, -1, -1):
        step = correction_rotvec[index] - correction_rotvec[index + 1]
        step_length = float(np.linalg.norm(step))
        if step_length > maximum_step:
            correction_rotvec[index] = (
                correction_rotvec[index + 1]
                + step * (maximum_step / step_length)
            )

    correction_rotation = Rotation.from_rotvec(
        correction_rotvec
    ).as_quat()
    corrected_rotation = train.quat_multiply(
        correction_rotation,
        camera_rotations,
    )
    corrected_rotation /= np.maximum(
        np.linalg.norm(corrected_rotation, axis=1, keepdims=True),
        1e-8,
    )
    ensure_quaternion_continuity(
        corrected_rotation,
        0,
        len(corrected_rotation),
    )
    final_composition = build_source_composition_path(
        camera_positions,
        corrected_rotation,
        fov_values,
        dutch_values,
        joint_world_positions,
        shot_type,
        aspect_ratio,
    )
    correction_degrees = np.degrees(
        np.linalg.norm(correction_rotvec, axis=1)
    )
    composition_error = np.linalg.norm(
        final_composition[:, :2] - desired_uv,
        axis=1,
    )
    metrics = {
        "basePersonVisibility": float(
            np.mean(base_composition[:, 3])
        ),
        "finalPersonVisibility": float(
            np.mean(final_composition[:, 3])
        ),
        "unsafeFrameRatioBefore": float(np.mean(unsafe)),
        "unsafeFrameRatioAfter": float(
            np.mean(
                (final_composition[:, 3] < 0.5)
                | (final_composition[:, 0] < left)
                | (final_composition[:, 0] > right)
                | (final_composition[:, 1] < bottom)
                | (final_composition[:, 1] > top)
            )
        ),
        "compositionErrorMean": float(np.mean(composition_error)),
        "correctionDegreesMean": float(np.mean(correction_degrees)),
        "correctionDegreesMax": float(np.max(correction_degrees)),
        "correctedFrameRatio": float(np.mean(expanded_unsafe)),
    }
    return corrected_rotation.astype(np.float32), metrics


def limit_camera_relative_trajectory_step(
    trajectory: np.ndarray,
    body_scale: float,
    maximum_step_meters: float = MAXIMUM_CAMERA_RELATIVE_POSITION_STEP_METERS,
) -> tuple[np.ndarray, float, float, float]:
    """Uniformly reduce only trajectories whose 60 FPS step is excessive.

    Scaling around the shot median preserves the authored curve shape and
    direction. It avoids a frame-local clamp that would create a second kink
    later in the shot, while still retaining substantial intentional motion.
    """

    values = np.asarray(trajectory, dtype=np.float64)
    if values.ndim != 2 or values.shape[1] != 3 or len(values) == 0:
        raise ValueError("Trajectory must be a non-empty [frame, 3] array.")
    if not np.isfinite(values).all():
        raise ValueError("Trajectory must contain only finite values.")
    if not math.isfinite(body_scale) or body_scale <= 0.0:
        raise ValueError("body_scale must be finite and positive.")
    if not math.isfinite(maximum_step_meters) or maximum_step_meters <= 0.0:
        raise ValueError("maximum_step_meters must be finite and positive.")

    if len(values) == 1:
        return values.astype(np.float32), 1.0, 0.0, 0.0
    step_before = np.linalg.norm(np.diff(values, axis=0), axis=1) * body_scale
    maximum_before = float(np.max(step_before))
    velocity_scale = min(
        1.0,
        maximum_step_meters / max(maximum_before, 1e-12),
    )
    center = np.median(values, axis=0)
    limited = center + (values - center) * velocity_scale
    maximum_after = float(
        np.max(np.linalg.norm(np.diff(limited, axis=0), axis=1) * body_scale)
    )
    return (
        limited.astype(np.float32),
        float(velocity_scale),
        maximum_before,
        maximum_after,
    )


def retarget_template_to_shot(
    template: ShotTemplate,
    previous: RealizedShotState | None,
    target: train.PreparedSong,
    joints: np.ndarray,
    root: np.ndarray,
    start: int,
    end: int,
    target_aspect_ratio: float,
    horizontal_framing: str = "source",
    body_follow_strength: float = DEFAULT_BODY_FOLLOW_STRENGTH,
    body_follow_smoothing_seconds: float = (
        DEFAULT_BODY_FOLLOW_SMOOTHING_SECONDS
    ),
    body_follow_dead_zone_meters: float = (
        DEFAULT_BODY_FOLLOW_DEAD_ZONE_METERS
    ),
    distance_meters: float = 0.0,
    motion_intensity: float = 1.0,
    safety_distance_scale: float = 1.0,
    front_facing_reference: dict[str, object] | None = None,
) -> dict:
    if not 0.0 <= motion_intensity <= 2.0:
        raise ValueError("motion_intensity must be between zero and two.")
    if not math.isfinite(distance_meters) or distance_meters < 0.0:
        raise ValueError("distance_meters must be finite and non-negative.")
    if not math.isfinite(safety_distance_scale) or safety_distance_scale < 1.0:
        raise ValueError("safety_distance_scale must be at least one.")
    shot_joints = joints[start:end]
    target_local_normalized = smooth_segment(
        shot_focus_local(shot_joints, template.shot_type)
    )
    frame_count = end - start

    resampled_camera_local_meters, trajectory_resampling_metrics = (
        trajectory_quality.resample_position_path_c2(
            template.motion_path * target.body_scale,
            frame_count,
            sample_rate=HYBRID_SAMPLE_RATE,
        )
    )
    camera_local_normalized = (
        resampled_camera_local_meters
        / max(float(target.body_scale), 1e-8)
    )
    trajectory_center = np.median(camera_local_normalized, axis=0)
    trajectory_offset = camera_local_normalized - trajectory_center
    maximum_offset_meters = float(
        np.max(np.linalg.norm(trajectory_offset, axis=1))
        * target.body_scale
    )
    maximum_allowed_offset_meters = TRAJECTORY_OFFSET_LIMITS_METERS[
        template.shot_type
    ]
    trajectory_scale = min(
        1.0,
        maximum_allowed_offset_meters
        / max(maximum_offset_meters, 1e-5),
    )
    applied_motion_scale = trajectory_scale * motion_intensity
    authored_camera_local_meters = (
        trajectory_center + trajectory_offset * motion_intensity
    ) * target.body_scale
    camera_local_normalized = (
        trajectory_center + trajectory_offset * applied_motion_scale
    )
    camera_local_rotation = scale_quaternion_motion(
        resample_quaternions(
            template.rotation_path,
            frame_count,
        ),
        motion_intensity,
    )
    raw_fov_values = resample_path(
        template.fov_path[:, None],
        frame_count,
    )[:, 0]
    median_fov = float(np.median(raw_fov_values))
    fov_values = np.clip(
        median_fov + (raw_fov_values - median_fov) * motion_intensity,
        7.0,
        65.0,
    )
    raw_dutch_values = resample_path(
        template.dutch_path[:, None],
        frame_count,
    )[:, 0]
    median_dutch = float(np.median(raw_dutch_values))
    dutch_values = np.clip(
        median_dutch
        + (raw_dutch_values - median_dutch) * motion_intensity,
        -45.0,
        45.0,
    )
    desired_composition = resample_path(
        template.person_composition_path(),
        frame_count,
    )
    flipped, realized_side_sign, realized_motion_type = template_realization(
        template,
        previous,
    )
    if motion_intensity == 0.0:
        realized_motion_type = "static"
    if flipped:
        camera_local_normalized[:, 0] *= -1.0
        authored_camera_local_meters[:, 0] *= -1.0
        camera_local_rotation = mirror_quaternions_x(
            camera_local_rotation
        )
        dutch_values *= -1.0
        desired_composition[:, 0] = 1.0 - desired_composition[:, 0]
    source_desired_composition = desired_composition.copy()

    distance_directive_meters = float(distance_meters)
    distance_local = np.linalg.norm(camera_local_normalized, axis=1)
    current_distance_meters = distance_local * target.body_scale
    minimum_distance, maximum_distance = {
        "wide": (2.0, 25.0),
        "medium": (1.4, 12.0),
        "close": (1.15, 7.0),
    }[template.shot_type]
    if distance_directive_meters > 0.0:
        radial_motion = (
            current_distance_meters
            - float(np.median(current_distance_meters))
        )
        requested_distance_meters = distance_directive_meters + radial_motion
    else:
        requested_distance_meters = current_distance_meters
    requested_distance_meters = requested_distance_meters * safety_distance_scale
    camera_local_directions = camera_local_normalized / np.maximum(
        distance_local[:, None],
        1e-8,
    )
    requested_camera_local_meters = (
        camera_local_directions * requested_distance_meters[:, None]
    )
    smooth_minimum_distance = minimum_distance * safety_distance_scale
    smooth_maximum_distance = min(
        maximum_distance * safety_distance_scale,
        35.0,
    )
    camera_local_meters, initial_radial_distance_clamp_metrics = (
        trajectory_quality.smooth_radial_distance_clamp(
            requested_camera_local_meters,
            smooth_minimum_distance,
            smooth_maximum_distance,
            lower_transition_meters=min(
                0.35 * safety_distance_scale,
                (smooth_maximum_distance - smooth_minimum_distance) * 0.35,
            ),
            upper_transition_meters=min(
                0.75 * safety_distance_scale,
                (smooth_maximum_distance - smooth_minimum_distance) * 0.45,
            ),
            sample_rate=HYBRID_SAMPLE_RATE,
        )
    )
    camera_local_normalized = camera_local_meters / max(
        float(target.body_scale),
        1e-8,
    )
    (
        camera_local_normalized,
        trajectory_velocity_limit_scale,
        trajectory_step_before_limit_meters,
        trajectory_step_after_limit_meters,
    ) = limit_camera_relative_trajectory_step(
        camera_local_normalized,
        target.body_scale,
    )
    applied_motion_scale *= trajectory_velocity_limit_scale
    declared_kinematic_motion_family = camera_kinematics.motion_family(
        realized_motion_type
    )
    relative_translation_kinematic_metrics: dict[str, object] | None = None
    relative_kinematic_pass_executed = False
    post_kinematic_velocity_limit_scale = 1.0
    trajectory_step_after_kinematic_meters = (
        trajectory_step_after_limit_meters
    )
    if declared_kinematic_motion_family == "orbit":
        relative_kinematic_pass_executed = True
        (
            camera_local_meters,
            relative_translation_kinematic_metrics,
        ) = camera_kinematics.regularize_translational_reversals(
            camera_local_normalized * target.body_scale,
            realized_motion_type,
            sample_rate=HYBRID_SAMPLE_RATE,
        )
        camera_local_normalized = camera_local_meters / target.body_scale
        (
            camera_local_normalized,
            post_kinematic_velocity_limit_scale,
            _,
            trajectory_step_after_kinematic_meters,
        ) = limit_camera_relative_trajectory_step(
            camera_local_normalized,
            target.body_scale,
        )
        # Stop-through-reversal timing can move some travel away from the
        # turning point. Re-apply the uniform cap only to an orbit that was
        # regularized in this relative space. Non-orbit paths retain the exact
        # first-limit result until their single final-world kinematic pass.
        trajectory_velocity_limit_scale *= (
            post_kinematic_velocity_limit_scale
        )
        applied_motion_scale *= post_kinematic_velocity_limit_scale
    camera_local_meters = camera_local_normalized * target.body_scale

    root_position = root[start:end, :3]
    root_rotation = root[start:end, 3:7]
    target_world_position = root_position + train.quat_rotate(
        root_rotation,
        target_local_normalized * target.body_scale,
    )
    joint_world_position = root_position[:, None, :] + train.quat_rotate(
        root_rotation[:, None, :],
        shot_joints * target.body_scale,
    )
    stage_anchor_path, body_follow_metrics = build_stage_anchor_path(
        joint_world_position[:, 2],
        body_follow_strength,
        body_follow_smoothing_seconds,
        body_follow_dead_zone_meters,
    )
    shot_rotation = stable_shot_rotation(root_rotation)
    camera_world_position = smooth_camera_world_position(
        stage_anchor_path
        + train.quat_rotate(
            shot_rotation,
            camera_local_normalized * target.body_scale,
        )
    )
    if declared_kinematic_motion_family == "orbit":
        # Orbit direction is meaningful only around the subject/stage anchor.
        # A world-origin atan2 pass produces false CW/CCW reversals whenever a
        # perfectly continuous orbit is offset from (0, 0, 0).
        if relative_translation_kinematic_metrics is None:
            raise RuntimeError("Orbit relative kinematic pass did not run.")
        translation_kinematic_metrics = relative_translation_kinematic_metrics
        translation_kinematic_detection_space = "camera_relative_trajectory"
    else:
        world_kinematic_motion_type = (
            "drift"
            if declared_kinematic_motion_family
            in {"dolly", "truck", "crane", "drift"}
            else realized_motion_type
        )
        (
            camera_world_position,
            translation_kinematic_metrics,
        ) = camera_kinematics.regularize_translational_reversals(
            camera_world_position,
            world_kinematic_motion_type,
            sample_rate=HYBRID_SAMPLE_RATE,
        )
        translation_kinematic_detection_space = "final_world_position"

    # The uniform velocity guards and the kinematic turn regularizer can move
    # points back outside the distance annulus (the historical orbit failure
    # scaled a 2 m radius down to about 1.5 m).  Distance is therefore the last
    # positional transform.  We do not run another center-based step scaler
    # afterward because that would invalidate the bound again; the actual
    # final step is audited below and unsafe candidates are rejected.
    camera_world_position_before_final_radial_clamp = np.asarray(
        camera_world_position,
        dtype=np.float64,
    ).copy()
    final_relative_position_meters = (
        camera_world_position - stage_anchor_path
    )
    trajectory_step_before_final_distance_clamp_meters = (
        float(
            np.max(
                np.linalg.norm(
                    np.diff(final_relative_position_meters, axis=0),
                    axis=1,
                )
            )
        )
        if len(final_relative_position_meters) > 1
        else 0.0
    )
    trajectory_step_after_kinematic_meters = (
        trajectory_step_before_final_distance_clamp_meters
    )
    (
        final_relative_position_meters,
        final_radial_distance_clamp_metrics,
    ) = trajectory_quality.smooth_radial_distance_clamp(
        final_relative_position_meters,
        smooth_minimum_distance,
        smooth_maximum_distance,
        lower_transition_meters=min(
            0.35 * safety_distance_scale,
            (smooth_maximum_distance - smooth_minimum_distance) * 0.35,
        ),
        upper_transition_meters=min(
            0.75 * safety_distance_scale,
            (smooth_maximum_distance - smooth_minimum_distance) * 0.45,
        ),
        sample_rate=HYBRID_SAMPLE_RATE,
    )
    camera_world_position = (
        stage_anchor_path + final_relative_position_meters
    ).astype(np.float32)
    clamped_distance_meters = np.linalg.norm(
        final_relative_position_meters,
        axis=1,
    )
    trajectory_step_after_final_distance_clamp_meters = (
        float(
            np.max(
                np.linalg.norm(
                    np.diff(final_relative_position_meters, axis=0),
                    axis=1,
                )
            )
        )
        if len(final_relative_position_meters) > 1
        else 0.0
    )
    trajectory_final_relative_step_passed = bool(
        trajectory_step_after_final_distance_clamp_meters
        <= MAXIMUM_CAMERA_RELATIVE_POSITION_STEP_METERS + 1e-6
    )
    # The radial safety projection is intentionally the last bounding
    # transform, but it can bend a curve that was already kinematically
    # regularized and recreate a concentrated turn. Audit every motion family
    # once more in its authoritative space: orbit around the final stage
    # anchor, all other motion in publishable world space. Accept the C2
    # rewrite only when it preserves both the distance annulus and final step
    # limit. If it cannot, retain the bounded curve and fail the candidate
    # closed when its audit still contains an abrupt or impulsive turn.
    pre_clamp_translation_kinematic_metrics = translation_kinematic_metrics
    post_clamp_kinematic_safety_rejected = False
    post_clamp_kinematic_applied = False
    post_clamp_audit_motion_type = (
        realized_motion_type
        if declared_kinematic_motion_family == "orbit"
        else world_kinematic_motion_type
    )
    post_clamp_audit_position = (
        final_relative_position_meters
        if declared_kinematic_motion_family == "orbit"
        else camera_world_position
    )
    (
        post_clamp_regularized_position,
        post_clamp_translation_kinematic_metrics,
    ) = camera_kinematics.regularize_translational_reversals(
        post_clamp_audit_position,
        post_clamp_audit_motion_type,
        sample_rate=HYBRID_SAMPLE_RATE,
    )
    if declared_kinematic_motion_family == "orbit":
        post_clamp_relative_position_meters = (
            post_clamp_regularized_position
        )
        post_clamp_camera_world_position = (
            stage_anchor_path + post_clamp_relative_position_meters
        )
    else:
        post_clamp_camera_world_position = (
            post_clamp_regularized_position
        )
        post_clamp_relative_position_meters = (
            post_clamp_camera_world_position - stage_anchor_path
        )
    post_clamp_distance_meters = np.linalg.norm(
        post_clamp_relative_position_meters,
        axis=1,
    )
    post_clamp_relative_step_meters = (
        float(
            np.max(
                np.linalg.norm(
                    np.diff(post_clamp_relative_position_meters, axis=0),
                    axis=1,
                )
            )
        )
        if len(post_clamp_relative_position_meters) > 1
        else 0.0
    )
    post_clamp_bounds_passed = bool(
        float(np.min(post_clamp_distance_meters))
        >= smooth_minimum_distance - 1e-6
        and float(np.max(post_clamp_distance_meters))
        <= smooth_maximum_distance + 1e-6
    )
    post_clamp_step_passed = bool(
        post_clamp_relative_step_meters
        <= MAXIMUM_CAMERA_RELATIVE_POSITION_STEP_METERS + 1e-6
    )
    post_clamp_kinematic_applied = bool(
        post_clamp_translation_kinematic_metrics[
            "translationKinematicPolicyApplied"
        ]
    )
    if post_clamp_bounds_passed and post_clamp_step_passed:
        camera_world_position = post_clamp_camera_world_position.astype(
            np.float32
        )
        final_relative_position_meters = post_clamp_relative_position_meters
        post_clamp_distance_meters = np.linalg.norm(
            post_clamp_relative_position_meters,
            axis=1,
        )
        clamped_distance_meters = post_clamp_distance_meters
        trajectory_step_after_final_distance_clamp_meters = (
            post_clamp_relative_step_meters
        )
        trajectory_final_relative_step_passed = post_clamp_step_passed
    else:
        post_clamp_kinematic_safety_rejected = True
        (
            _,
            post_clamp_translation_kinematic_metrics,
        ) = camera_kinematics.regularize_translational_reversals(
            post_clamp_audit_position,
            post_clamp_audit_motion_type,
            sample_rate=HYBRID_SAMPLE_RATE,
            apply_policy=False,
        )

    post_stage_regularized_frames = list(
        post_clamp_translation_kinematic_metrics[
            "translationRegularizedReversalFrames"
        ]
    )
    post_stage_direction_reversal_count_after = int(
        post_clamp_translation_kinematic_metrics[
            "translationDirectionReversalCountAfter"
        ]
    )
    post_stage_abrupt_reversal_count_after = int(
        post_clamp_translation_kinematic_metrics[
            "translationAbruptReversalCountAfter"
        ]
    )
    post_stage_impulsive_turn_count_after = int(
        post_clamp_translation_kinematic_metrics[
            "translationImpulsiveTurnCountAfter"
        ]
    )

    # The top-level contract spans both stages: initial evidence comes from
    # the pre-clamp curve, while every After field is the final raw output
    # audit. Compact stage summaries retain the causal explanation without
    # duplicating the full metric object for every candidate.
    # Build the sequence-level view on a shallow copy.  The original post
    # stage dictionary remains the authoritative per-stage snapshot used
    # below; mutating it with combined pre/post fields would make the second
    # stage falsely report unioned diagnostics.
    translation_kinematic_metrics = dict(
        post_clamp_translation_kinematic_metrics
    )
    for metric_name, metric_value in (
        pre_clamp_translation_kinematic_metrics.items()
    ):
        if metric_name.endswith("Before"):
            translation_kinematic_metrics[metric_name] = metric_value
    pre_applied = bool(
        pre_clamp_translation_kinematic_metrics[
            "translationKinematicPolicyApplied"
        ]
    )
    accepted_post_applied = bool(
        post_clamp_kinematic_applied
        and not post_clamp_kinematic_safety_rejected
    )
    translation_kinematic_metrics[
        "translationKinematicPolicyApplied"
    ] = bool(pre_applied or accepted_post_applied)
    translation_kinematic_metrics[
        "translationKinematicPolicyApplicationEnabled"
    ] = True
    translation_kinematic_metrics[
        "translationKinematicDynamicsGuardTriggered"
    ] = bool(
        pre_clamp_translation_kinematic_metrics[
            "translationKinematicDynamicsGuardTriggered"
        ]
        or post_clamp_translation_kinematic_metrics[
            "translationKinematicDynamicsGuardTriggered"
        ]
    )
    translation_kinematic_metrics[
        "translationKinematicDynamicsGuardRejectedFrames"
    ] = list(
        dict.fromkeys(
            [
                *pre_clamp_translation_kinematic_metrics[
                    "translationKinematicDynamicsGuardRejectedFrames"
                ],
                *post_clamp_translation_kinematic_metrics[
                    "translationKinematicDynamicsGuardRejectedFrames"
                ],
            ]
        )
    )
    translation_kinematic_metrics[
        "translationKinematicAdaptiveRadiusFrames"
    ] = list(
        dict.fromkeys(
            [
                *pre_clamp_translation_kinematic_metrics[
                    "translationKinematicAdaptiveRadiusFrames"
                ],
                *post_clamp_translation_kinematic_metrics[
                    "translationKinematicAdaptiveRadiusFrames"
                ],
            ]
        )
    )
    combined_attempted_frames = list(
        dict.fromkeys(
            [
                *pre_clamp_translation_kinematic_metrics[
                    "translationKinematicAttemptedReversalFrames"
                ],
                *post_clamp_translation_kinematic_metrics[
                    "translationKinematicAttemptedReversalFrames"
                ],
            ]
        )
    )
    translation_kinematic_metrics[
        "translationKinematicAttemptedReversalFrames"
    ] = combined_attempted_frames
    translation_kinematic_metrics[
        "translationKinematicAttemptedRegularizationCount"
    ] = len(combined_attempted_frames)
    translation_kinematic_metrics[
        "translationKinematicRegularizationPassCount"
    ] = int(
        pre_clamp_translation_kinematic_metrics[
            "translationKinematicRegularizationPassCount"
        ]
    ) + int(
        post_clamp_translation_kinematic_metrics[
            "translationKinematicRegularizationPassCount"
        ]
    )
    translation_kinematic_metrics[
        "translationRegularizedReversalFrames"
    ] = list(
        dict.fromkeys(
            [
                *pre_clamp_translation_kinematic_metrics[
                    "translationRegularizedReversalFrames"
                ],
                *post_clamp_translation_kinematic_metrics[
                    "translationRegularizedReversalFrames"
                ],
            ]
        )
    )
    translation_kinematic_metrics[
        "translationRegularizedReversalCount"
    ] = len(
        translation_kinematic_metrics["translationRegularizedReversalFrames"]
    )
    translation_kinematic_metrics[
        "translationRegularizedTurnAnglesDegrees"
    ] = [
        *pre_clamp_translation_kinematic_metrics[
            "translationRegularizedTurnAnglesDegrees"
        ],
        *post_clamp_translation_kinematic_metrics[
            "translationRegularizedTurnAnglesDegrees"
        ],
    ]
    translation_kinematic_metrics[
        "translationRegularizedTargetSpeedRatios"
    ] = [
        *pre_clamp_translation_kinematic_metrics[
            "translationRegularizedTargetSpeedRatios"
        ],
        *post_clamp_translation_kinematic_metrics[
            "translationRegularizedTargetSpeedRatios"
        ],
    ]
    # These radii are positional peers of the concatenated turn angles and
    # target-speed ratios.  Do not de-duplicate them: the same frame may be
    # independently repaired before and after radial projection, and dropping
    # one radius would silently break the per-attempt alignment.
    translation_kinematic_metrics[
        "translationRegularizedWindowRadiiFrames"
    ] = [
        *pre_clamp_translation_kinematic_metrics[
            "translationRegularizedWindowRadiiFrames"
        ],
        *post_clamp_translation_kinematic_metrics[
            "translationRegularizedWindowRadiiFrames"
        ],
    ]
    translation_kinematic_metrics[
        "translationAttemptedAccelerationMetersPerSecondSquaredMax"
    ] = max(
        float(
            pre_clamp_translation_kinematic_metrics[
                "translationAttemptedAccelerationMetersPerSecondSquaredMax"
            ]
        ),
        float(
            post_clamp_translation_kinematic_metrics[
                "translationAttemptedAccelerationMetersPerSecondSquaredMax"
            ]
        ),
    )
    translation_kinematic_metrics[
        "translationAttemptedJerkMetersPerSecondCubedMax"
    ] = max(
        float(
            pre_clamp_translation_kinematic_metrics[
                "translationAttemptedJerkMetersPerSecondCubedMax"
            ]
        ),
        float(
            post_clamp_translation_kinematic_metrics[
                "translationAttemptedJerkMetersPerSecondCubedMax"
            ]
        ),
    )
    translation_kinematic_metrics[
        "translationImpulsiveTurnRegularizedFrames"
    ] = list(
        dict.fromkeys(
            [
                *pre_clamp_translation_kinematic_metrics[
                    "translationImpulsiveTurnRegularizedFrames"
                ],
                *post_clamp_translation_kinematic_metrics[
                    "translationImpulsiveTurnRegularizedFrames"
                ],
            ]
        )
    )
    translation_kinematic_metrics["translationKinematicStagePasses"] = [
        {
            "stage": "before_final_radial_clamp",
            "policyApplied": pre_applied,
            "guardTriggered": bool(
                pre_clamp_translation_kinematic_metrics[
                    "translationKinematicDynamicsGuardTriggered"
                ]
            ),
            "rejectedFrames": list(
                pre_clamp_translation_kinematic_metrics[
                    "translationKinematicDynamicsGuardRejectedFrames"
                ]
            ),
            "adaptiveRadiusFrames": list(
                pre_clamp_translation_kinematic_metrics[
                    "translationKinematicAdaptiveRadiusFrames"
                ]
            ),
            "windowRadiiFrames": list(
                pre_clamp_translation_kinematic_metrics[
                    "translationRegularizedWindowRadiiFrames"
                ]
            ),
            "impulsiveTurnCountBefore": int(
                pre_clamp_translation_kinematic_metrics[
                    "translationImpulsiveTurnCountBefore"
                ]
            ),
            "regularizedFrames": list(
                pre_clamp_translation_kinematic_metrics[
                    "translationRegularizedReversalFrames"
                ]
            ),
            "directionReversalCountAfter": int(
                pre_clamp_translation_kinematic_metrics[
                    "translationDirectionReversalCountAfter"
                ]
            ),
        },
        {
            "stage": "after_final_radial_clamp",
            "policyApplied": accepted_post_applied,
            "safetyRejected": post_clamp_kinematic_safety_rejected,
            "guardTriggered": bool(
                post_clamp_translation_kinematic_metrics[
                    "translationKinematicDynamicsGuardTriggered"
                ]
            ),
            "rejectedFrames": list(
                post_clamp_translation_kinematic_metrics[
                    "translationKinematicDynamicsGuardRejectedFrames"
                ]
            ),
            "adaptiveRadiusFrames": list(
                post_clamp_translation_kinematic_metrics[
                    "translationKinematicAdaptiveRadiusFrames"
                ]
            ),
            "windowRadiiFrames": list(
                post_clamp_translation_kinematic_metrics[
                    "translationRegularizedWindowRadiiFrames"
                ]
            ),
            "regularizedFrames": post_stage_regularized_frames,
            "directionReversalCountAfter": (
                post_stage_direction_reversal_count_after
            ),
            "abruptReversalCountAfter": (
                post_stage_abrupt_reversal_count_after
            ),
            "impulsiveTurnCountAfter": post_stage_impulsive_turn_count_after,
        },
    ]
    translation_kinematic_detection_space = (
        "final_camera_relative_position_post_radial_audit"
        if declared_kinematic_motion_family == "orbit"
        else "final_world_position_post_radial_audit"
    )
    trajectory_step_after_kinematic_meters = (
        trajectory_step_after_final_distance_clamp_meters
    )
    final_radial_dynamics_audit = final_radial_dynamics_regression_audit(
        camera_world_position_before_final_radial_clamp,
        camera_world_position,
        sample_rate=HYBRID_SAMPLE_RATE,
    )
    final_radial_dynamics_regression_passed = bool(
        final_radial_dynamics_audit["passed"]
    )
    final_post_clamp_kinematic_passed = bool(
        int(
            post_clamp_translation_kinematic_metrics[
                "translationAbruptReversalCountAfter"
            ]
        )
        == 0
        and final_radial_dynamics_regression_passed
        and int(
            post_clamp_translation_kinematic_metrics[
                "translationImpulsiveTurnCountAfter"
            ]
        )
        == 0
    )
    final_distance_bounds_passed = bool(
        float(np.min(clamped_distance_meters))
        >= smooth_minimum_distance - 1e-6
        and float(np.max(clamped_distance_meters))
        <= smooth_maximum_distance + 1e-6
    )
    if not final_distance_bounds_passed:
        raise CandidateRetargetSafetyRejection(
            "Final camera distance audit violated its bounds."
        )
    radial_distance_clamp_metrics = {
        **final_radial_distance_clamp_metrics,
        "initialPass": initial_radial_distance_clamp_metrics,
        "finalPassAfterAllPositionTransforms": bool(
            not post_clamp_kinematic_applied
            or post_clamp_kinematic_safety_rejected
        ),
        "postClampKinematicAuditExecuted": True,
        "postClampKinematicPolicyApplied": bool(
            post_clamp_kinematic_applied
            and not post_clamp_kinematic_safety_rejected
        ),
        "postClampKinematicSafetyRejected": (
            post_clamp_kinematic_safety_rejected
        ),
        "finalRadialDynamicsRegressionAudit": (
            final_radial_dynamics_audit
        ),
        "finalRadialDynamicsRegressionPassed": (
            final_radial_dynamics_regression_passed
        ),
        "finalPostClampKinematicPassed": final_post_clamp_kinematic_passed,
        "finalDistanceAuditAfterAllPositionTransforms": True,
        "finalDistanceBoundsPassed": final_distance_bounds_passed,
        "finalRelativeStepMetersBeforeClamp": (
            trajectory_step_before_final_distance_clamp_meters
        ),
        "finalRelativeStepMetersAfterClamp": (
            trajectory_step_after_final_distance_clamp_meters
        ),
        "finalRelativeStepLimitMeters": (
            MAXIMUM_CAMERA_RELATIVE_POSITION_STEP_METERS
        ),
        "finalRelativeStepPassed": trajectory_final_relative_step_passed,
    }
    translation_kinematic_metrics.update(
        {
            "translationKinematicMotionFamily": (
                declared_kinematic_motion_family
            ),
            "translationKinematicDetectionSpace": (
                translation_kinematic_detection_space
            ),
            "translationKinematicPassCount": (
                2
            ),
            "translationRelativeKinematicPassExecuted": (
                relative_kinematic_pass_executed
            ),
            "finalPostClampKinematicPassed": (
                final_post_clamp_kinematic_passed
            ),
        }
    )
    camera_world_rotation = train.quat_multiply(
        shot_rotation,
        camera_local_rotation,
    )
    camera_world_rotation /= np.maximum(
        np.linalg.norm(camera_world_rotation, axis=1, keepdims=True),
        1e-8,
    )
    ensure_quaternion_continuity(
        camera_world_rotation,
        0,
        len(camera_world_rotation),
    )
    authored_camera_world_rotation = camera_world_rotation.copy()
    camera_world_rotation, composition_metrics = (
        apply_person_composition_correction(
            camera_world_position,
            camera_world_rotation,
            fov_values,
            dutch_values,
            joint_world_position,
            source_desired_composition,
            template.shot_type,
            target_aspect_ratio,
        )
    )
    composition_before_horizontal_reframe = (
        build_source_composition_path(
            camera_world_position,
            camera_world_rotation,
            fov_values,
            dutch_values,
            joint_world_position,
            template.shot_type,
            target_aspect_ratio,
        )
    )
    horizontal_scoring_bounds = horizontal_bounds_for_policy(
        template.shot_type,
        horizontal_framing,
    )
    horizontal_target_bounds = horizontal_target_bounds_for_policy(
        template.shot_type,
        horizontal_framing,
    )
    horizontal_before_statistics = horizontal_composition_statistics(
        composition_before_horizontal_reframe,
        template.shot_type,
        horizontal_scoring_bounds,
    )
    centered_target_composition, horizontal_target_metrics = (
        regularize_person_only_composition(
            composition_before_horizontal_reframe,
            template.shot_type,
            horizontal_framing,
        )
    )
    camera_world_rotation, horizontal_reframe_metrics = (
        apply_shot_horizontal_reframe(
            camera_world_rotation,
            fov_values,
            dutch_values,
            composition_before_horizontal_reframe,
            centered_target_composition,
            target_aspect_ratio,
            horizontal_framing,
        )
    )
    composition_after_horizontal_reframe = build_source_composition_path(
        camera_world_position,
        camera_world_rotation,
        fov_values,
        dutch_values,
        joint_world_position,
        template.shot_type,
        target_aspect_ratio,
    )
    camera_rotation_after_horizontal_reframe = camera_world_rotation.copy()
    (
        source_aspect_reliability,
        source_aspect_penalty,
        source_aspect_quality_reason,
    ) = source_aspect_quality(
        template.source_aspect_ratio,
        template.source_aspect_source,
    )
    aim_shot_type = template.shot_type
    aim_source_composition = composition_after_horizontal_reframe
    semantic_aim_iterations = 0
    for _ in range(3):
        (
            camera_world_rotation,
            semantic_desired_composition,
            semantic_aim_metrics,
        ) = apply_stabilized_semantic_baked_aim(
            camera_world_position,
            camera_world_rotation,
            fov_values,
            dutch_values,
            joint_world_position,
            root_rotation,
            aim_source_composition,
            aim_shot_type,
            target_aspect_ratio,
            horizontal_framing,
            source_aspect_reliability,
        )
        semantic_aim_iterations += 1
        derived_framing = derive_output_semantic_framing(
            camera_world_position,
            camera_world_rotation,
            fov_values,
            dutch_values,
            joint_world_position,
            target_aspect_ratio,
        )
        if derived_framing.shot_type == aim_shot_type:
            break
        aim_shot_type = derived_framing.shot_type
        aim_source_composition = build_source_composition_path(
            camera_world_position,
            camera_world_rotation,
            fov_values,
            dutch_values,
            joint_world_position,
            aim_shot_type,
            target_aspect_ratio,
        )
    final_composition, semantic_projection_safety = (
        semantic_projection_safety_metrics(
            camera_world_position,
            camera_world_rotation,
            fov_values,
            dutch_values,
            joint_world_position,
            template.shot_type,
            target_aspect_ratio,
        )
    )
    realized_shot_type = str(
        semantic_projection_safety["realizedSemanticShotType"]
    )
    semantic_aim_metrics.update(
        {
            "semanticAimShotType": aim_shot_type,
            "semanticAimIterations": semantic_aim_iterations,
        }
    )
    target_local_normalized = smooth_segment(
        shot_focus_local(shot_joints, realized_shot_type)
    )
    target_world_position = root_position + train.quat_rotate(
        root_rotation,
        target_local_normalized * target.body_scale,
    )
    composition_after_horizontal_reframe = build_source_composition_path(
        camera_world_position,
        camera_rotation_after_horizontal_reframe,
        fov_values,
        dutch_values,
        joint_world_position,
        realized_shot_type,
        target_aspect_ratio,
    )
    horizontal_scoring_bounds = horizontal_bounds_for_policy(
        realized_shot_type,
        horizontal_framing,
    )
    horizontal_target_bounds = horizontal_target_bounds_for_policy(
        realized_shot_type,
        horizontal_framing,
    )
    horizontal_after_reframe_statistics = (
        horizontal_composition_statistics(
            composition_after_horizontal_reframe,
            realized_shot_type,
            horizontal_scoring_bounds,
        )
    )
    horizontal_final_statistics = horizontal_composition_statistics(
        final_composition,
        realized_shot_type,
        horizontal_scoring_bounds,
    )
    strict_safety = semantic_projection_safety
    left, right, bottom, top = HARD_PERSON_SAFE_BOUNDS[
        realized_shot_type
    ]
    desired_composition_for_metrics = semantic_desired_composition
    composition_metrics.update(
        {
            "finalPersonVisibility": float(
                np.mean(final_composition[:, 3])
            ),
            "unsafeFrameRatioAfter": float(
                np.mean(
                    (final_composition[:, 3] < 0.5)
                    | (final_composition[:, 0] < left)
                    | (final_composition[:, 0] > right)
                    | (final_composition[:, 1] < bottom)
                    | (final_composition[:, 1] > top)
                )
            ),
            "compositionErrorMean": float(
                np.mean(
                    np.linalg.norm(
                        final_composition[:, :2]
                        - desired_composition_for_metrics[:, :2],
                        axis=1,
                    )
                )
            ),
        }
    )
    composition_metrics.update(horizontal_target_metrics)
    composition_metrics.update(horizontal_reframe_metrics)
    composition_metrics.update(strict_safety)
    composition_metrics.update(body_follow_metrics)
    composition_metrics.update(semantic_aim_metrics)
    composition_metrics.update(
        {
            "sourceAspectReliability": source_aspect_reliability,
            "sourceAspectQualityPenalty": source_aspect_penalty,
            "sourceAspectQualityReason": source_aspect_quality_reason,
            "horizontalFramingPolicy": horizontal_framing,
            "horizontalBounds": list(
                horizontal_scoring_bounds
            ),
            "horizontalTargetBounds": list(horizontal_target_bounds),
            "horizontalFocusMedianBeforeReframe": (
                horizontal_before_statistics["horizontalFocusMedian"]
            ),
            "horizontalFocusMedianAfterReframe": (
                horizontal_after_reframe_statistics[
                    "horizontalFocusMedian"
                ]
            ),
            "horizontalFocusMedianFinal": (
                horizontal_final_statistics["horizontalFocusMedian"]
            ),
            "horizontalCenterOffsetBeforeReframe": (
                horizontal_before_statistics["horizontalCenterOffset"]
            ),
            "horizontalCenterOffsetAfterReframe": (
                horizontal_after_reframe_statistics[
                    "horizontalCenterOffset"
                ]
            ),
            "horizontalCenterOffsetFinal": (
                horizontal_final_statistics["horizontalCenterOffset"]
            ),
            "horizontalCenterOffsetP90Final": (
                horizontal_final_statistics["horizontalCenterOffsetP90"]
            ),
            "horizontalCenterOffsetMaxFinal": (
                horizontal_final_statistics["horizontalCenterOffsetMax"]
            ),
            "horizontalCorridorExcessBeforeReframe": (
                horizontal_before_statistics["horizontalCorridorExcess"]
            ),
            "horizontalCorridorExcessAfterReframe": (
                horizontal_after_reframe_statistics[
                    "horizontalCorridorExcess"
                ]
            ),
            "horizontalCorridorExcessFinal": (
                horizontal_final_statistics["horizontalCorridorExcess"]
            ),
            "horizontalOutOfCorridorRatioBeforeReframe": (
                horizontal_before_statistics[
                    "horizontalOutOfCorridorRatio"
                ]
            ),
            "horizontalOutOfCorridorRatioAfterReframe": (
                horizontal_after_reframe_statistics[
                    "horizontalOutOfCorridorRatio"
                ]
            ),
            "horizontalOutOfCorridorRatioFinal": (
                horizontal_final_statistics[
                    "horizontalOutOfCorridorRatio"
                ]
            ),
            "horizontalOutOfCorridorLongestRunFramesFinal": (
                horizontal_final_statistics[
                    "horizontalOutOfCorridorLongestRunFrames"
                ]
            ),
        }
    )
    horizontal_quality_penalty = 0.0
    if horizontal_framing == "centered":
        final_excess = (
            horizontal_final_statistics["horizontalCorridorExcess"]
            or 0.0
        )
        horizontal_quality_penalty = (
            float(
                horizontal_final_statistics[
                    "horizontalOutOfCorridorRatio"
                ]
            )
            * 2.0
            + float(final_excess) * 40.0
            + horizontal_reframe_metrics[
                "horizontalReframeDegreesMean"
            ]
            / 24.0
        )
    elif horizontal_framing == "balanced":
        final_excess = (
            horizontal_final_statistics["horizontalCorridorExcess"]
            or 0.0
        )
        # Automatic framing is soft-centered.  Stable semantic evidence can
        # still request a bounded lead-room target inside this corridor.
        horizontal_quality_penalty = (
            float(final_excess) * 24.0
            + float(
                horizontal_final_statistics[
                    "horizontalOutOfCorridorRatio"
                ]
            )
            * 1.5
            + horizontal_reframe_metrics[
                "horizontalReframeDegreesMean"
            ]
            / 36.0
        )
    elif horizontal_framing in {"left_third", "right_third"}:
        horizontal_quality_penalty = thirds_horizontal_quality_penalty(
            horizontal_target_metrics["horizontalFramingMedianTarget"],
            horizontal_final_statistics["horizontalFocusMedian"],
            horizontal_reframe_metrics["horizontalReframeDegreesMean"],
        )
    strict_safety_penalty = (
        float(strict_safety["strictExitFrameRatio"]) * 1000.0
        + float(strict_safety["strictExitLongestRunFrames"]) * 10.0
        + (100.0 if not strict_safety["hardPersonSafetyPassed"] else 0.0)
        + float(
            strict_safety["semanticProjectionUnsafeFrameRatio"]
        )
        * 1000.0
        + (
            100.0
            if not strict_safety["semanticProjectionSafetyPassed"]
            else 0.0
        )
    )
    aim_quality_penalty = (
        float(semantic_aim_metrics["aimErrorDegreesP90"]) / 8.0
        + float(semantic_aim_metrics["aimErrorWarningFrameRatio"]) * 4.0
        + float(semantic_aim_metrics["horizontalDesiredOffsetP90"]) * 20.0
        + float(
            semantic_aim_metrics[
                "horizontalDesiredOffsetWarningFrameRatio"
            ]
        )
        * 4.0
        + (50.0 if not semantic_aim_metrics["aimQualityPassed"] else 0.0)
        + float(
            semantic_aim_metrics[
                "aimRotationDynamicsSelectionPenalty"
            ]
        )
    )
    quality_score = (
        (1.0 - composition_metrics["finalPersonVisibility"]) * 30.0
        + (
            2.0
            if composition_metrics["unsafeFrameRatioAfter"] > 0.0
            else 0.0
        )
        + composition_metrics["unsafeFrameRatioAfter"] * 100.0
        + composition_metrics["compositionErrorMean"] * 4.0
        + composition_metrics["correctionDegreesMean"] / 12.0
        + horizontal_quality_penalty
        + strict_safety_penalty
        + aim_quality_penalty
        + source_aspect_penalty * 0.5
    )
    motion_quality = motion_quality_metrics(
        authored_camera_local_meters,
        camera_world_position - stage_anchor_path,
        authored_camera_world_rotation,
        camera_world_rotation,
        realized_shot_type,
        realized_motion_type,
        motion_intensity,
    )
    translation_kinematic_penalty = (
        camera_kinematics.translational_reversal_selection_penalty(
            translation_kinematic_metrics
        )
    )
    motion_quality.update(translation_kinematic_metrics)
    motion_quality["translationKinematicSelectionPenalty"] = float(
        translation_kinematic_penalty
    )
    motion_quality["motionSelectionAdjustment"] = float(
        motion_quality["motionSelectionAdjustment"]
        + translation_kinematic_penalty
    )
    screen_residual_uv = stabilized_screen_residual(
        final_composition,
        semantic_desired_composition,
    )
    candidate_dynamics = trajectory_quality.evaluate_candidate_dynamics(
        camera_world_position,
        screen_residual_uv,
        sample_rate=HYBRID_SAMPLE_RATE,
        screen_input_kind=(
            trajectory_quality.STABILIZED_SCREEN_RESIDUAL_INPUT
        ),
    )
    candidate_dynamics_cost_passed = bool(candidate_dynamics["passed"])
    candidate_dynamics_penalty = candidate_dynamics_selection_penalty(
        float(candidate_dynamics["cost"]),
        cost_passed=candidate_dynamics_cost_passed,
        maximum_acceptable_cost=float(
            candidate_dynamics["maximumAcceptableCost"]
        ),
    )
    translation_dynamics = candidate_dynamics["translationMetrics"]
    screen_dynamics = candidate_dynamics["screenSpaceMetrics"]
    candidate_dynamics_hard_gate_result = candidate_dynamics_hard_gate(
        translation_dynamics,
        screen_dynamics,
        final_relative_step_passed=(
            trajectory_final_relative_step_passed
        ),
    )
    candidate_dynamics_catastrophic_passed = bool(
        candidate_dynamics_hard_gate_result["passed"]
    )
    candidate_dynamics["costPassed"] = candidate_dynamics_cost_passed
    candidate_dynamics["selectionPolicyVersion"] = (
        CANDIDATE_DYNAMICS_SELECTION_POLICY_VERSION
    )
    candidate_dynamics["hardGate"] = candidate_dynamics_hard_gate_result
    # Generated payloads expose one authoritative `passed` field.  The soft
    # cost remains useful for ranking (`costPassed`) but never overrides a
    # hard impulse, distance-step, or finite-metric failure.
    candidate_dynamics["passed"] = candidate_dynamics_catastrophic_passed
    candidate_dynamics["catastrophicPassed"] = (
        candidate_dynamics_catastrophic_passed
    )
    candidate_dynamics["selectionPenalty"] = candidate_dynamics_penalty
    motion_quality["trajectoryDynamicsSelectionPenalty"] = (
        candidate_dynamics_penalty
    )
    motion_quality["motionSelectionAdjustment"] = float(
        motion_quality["motionSelectionAdjustment"]
        + candidate_dynamics_penalty
    )
    front_facing = front_facing_safety_metrics(
        camera_world_position,
        joint_world_position,
        root_rotation,
        root_facing_reference=front_facing_reference,
        semantic_visibility_passed=bool(
            strict_safety["hardPersonSafetyPassed"]
            and strict_safety["semanticProjectionSafetyPassed"]
        ),
    )
    front_facing_penalty = front_facing_selection_penalty(
        front_facing,
        len(camera_world_position),
    )
    quality_score += front_facing_penalty
    transition_state = adjacent_transition.build_transition_state(
        camera_world_position,
        camera_world_rotation,
        fov_values,
        target_world_position,
        final_composition,
        realized_shot_type,
        realized_motion_type,
        sample_rate=HYBRID_SAMPLE_RATE,
    )
    return {
        "template": template,
        "position": camera_world_position,
        "rotation": camera_world_rotation,
        "fov": fov_values,
        "dutch": dutch_values,
        "target": target_world_position,
        "stageAnchor": stage_anchor_path,
        "transitionState": transition_state,
        "trajectoryScale": applied_motion_scale,
        "trajectoryResampling": trajectory_resampling_metrics,
        "radialDistanceClamp": radial_distance_clamp_metrics,
        "candidateDynamics": candidate_dynamics,
        "candidateDynamicsCatastrophicPassed": (
            candidate_dynamics_catastrophic_passed
        ),
        "finalPostClampKinematicPassed": final_post_clamp_kinematic_passed,
        "trajectoryLimitScale": float(trajectory_scale),
        "trajectoryVelocityLimitScale": float(
            trajectory_velocity_limit_scale
        ),
        "trajectoryPostKinematicVelocityLimitScale": float(
            post_kinematic_velocity_limit_scale
        ),
        "trajectoryRelativeKinematicPassExecuted": bool(
            relative_kinematic_pass_executed
        ),
        "trajectoryRelativeStepMetersBeforeVelocityLimit": float(
            trajectory_step_before_limit_meters
        ),
        "trajectoryRelativeStepMetersAfterVelocityLimit": float(
            trajectory_step_after_limit_meters
        ),
        "trajectoryRelativeStepMetersAfterKinematicRegularization": float(
            trajectory_step_after_kinematic_meters
        ),
        "trajectoryRelativeStepMetersBeforeFinalDistanceClamp": float(
            trajectory_step_before_final_distance_clamp_meters
        ),
        "trajectoryRelativeStepMetersAfterFinalDistanceClamp": float(
            trajectory_step_after_final_distance_clamp_meters
        ),
        "trajectoryFinalRelativeStepPassed": (
            trajectory_final_relative_step_passed
        ),
        "trajectoryRelativeStepLimitMeters": (
            MAXIMUM_CAMERA_RELATIVE_POSITION_STEP_METERS
        ),
        "trajectoryOffsetLimitMeters": float(
            maximum_allowed_offset_meters
        ),
        "motionIntensity": motion_intensity,
        "distanceDirectiveMeters": distance_directive_meters,
        "distanceMetersMinMedianMax": [
            float(np.min(clamped_distance_meters)),
            float(np.median(clamped_distance_meters)),
            float(np.max(clamped_distance_meters)),
        ],
        "safetyDistanceScale": float(safety_distance_scale),
        "mirrored": flipped,
        "realizedSideSign": realized_side_sign,
        "realizedShotType": realized_shot_type,
        "realizedMotionType": realized_motion_type,
        "composition": composition_metrics,
        "motionQuality": motion_quality,
        **front_facing,
        "frontFacingPenalty": front_facing_penalty,
        "qualityScore": float(quality_score),
    }


def camera_candidate_visual_difference(
    first: dict,
    second: dict,
    sample_count: int = 9,
) -> dict[str, float | bool]:
    """Measure output-space differences between two retargeted cameras.

    Candidate templates can be different while producing effectively the same
    camera after composition correction.  Variation therefore operates on the
    final position, rotation and FOV curves instead of template identity.
    """

    if sample_count < 2:
        raise ValueError("sample_count must be at least two.")

    def sampled_path(candidate: dict, key: str, width: int) -> np.ndarray:
        values = np.asarray(candidate[key], dtype=np.float64)
        if values.ndim == 1 and width == 1:
            values = values[:, None]
        if values.ndim != 2 or values.shape[1] != width or len(values) == 0:
            raise ValueError(
                f"Candidate {key!r} must be a non-empty [frame, {width}] array."
            )
        if len(values) == 1:
            return np.repeat(values, sample_count, axis=0)
        return resample_path(values, sample_count).astype(np.float64)

    def sampled_rotation(candidate: dict) -> np.ndarray:
        values = np.asarray(candidate["rotation"], dtype=np.float64)
        if values.ndim != 2 or values.shape[1] != 4 or len(values) == 0:
            raise ValueError(
                "Candidate 'rotation' must be a non-empty [frame, 4] array."
            )
        if len(values) == 1:
            values = np.repeat(values, sample_count, axis=0)
        else:
            values = resample_quaternions(values, sample_count)
        values = values.astype(np.float64)
        return values / np.maximum(
            np.linalg.norm(values, axis=1, keepdims=True),
            1e-8,
        )

    first_position = sampled_path(first, "position", 3)
    second_position = sampled_path(second, "position", 3)
    position_delta = np.linalg.norm(
        first_position - second_position,
        axis=1,
    )

    first_rotation = sampled_rotation(first)
    second_rotation = sampled_rotation(second)
    rotation_dots = np.clip(
        np.abs(np.sum(first_rotation * second_rotation, axis=1)),
        0.0,
        1.0,
    )
    rotation_delta = np.degrees(2.0 * np.arccos(rotation_dots))

    first_fov = sampled_path(first, "fov", 1)[:, 0]
    second_fov = sampled_path(second, "fov", 1)[:, 0]
    fov_delta = np.abs(first_fov - second_fov)

    first_relative = first_position - first_position[0]
    second_relative = second_position - second_position[0]
    trajectory_delta = np.linalg.norm(
        first_relative - second_relative,
        axis=1,
    )
    first_net_motion = float(
        np.linalg.norm(first_position[-1] - first_position[0])
    )
    second_net_motion = float(
        np.linalg.norm(second_position[-1] - second_position[0])
    )

    return {
        "positionRmsMeters": float(
            np.sqrt(np.mean(np.square(position_delta)))
        ),
        "positionMaxMeters": float(np.max(position_delta)),
        "rotationRmsDegrees": float(
            np.sqrt(np.mean(np.square(rotation_delta)))
        ),
        "rotationMaxDegrees": float(np.max(rotation_delta)),
        "fovRmsDegrees": float(np.sqrt(np.mean(np.square(fov_delta)))),
        "fovMaxDegrees": float(np.max(fov_delta)),
        "relativeTrajectoryRmsMeters": float(
            np.sqrt(np.mean(np.square(trajectory_delta)))
        ),
        "netMotionDeltaMeters": abs(first_net_motion - second_net_motion),
        "motionTypeDifferent": (
            str(first.get("realizedMotionType", ""))
            != str(second.get("realizedMotionType", ""))
        ),
    }


def camera_candidates_are_visually_distinct(
    first: dict,
    second: dict,
) -> bool:
    """Return true only for a meaningful, visible camera difference."""

    difference = camera_candidate_visual_difference(first, second)
    thresholds = SEED_VARIATION_THRESHOLDS
    direct_difference = any(
        float(difference[key]) >= float(thresholds[key])
        for key in (
            "positionRmsMeters",
            "positionMaxMeters",
            "rotationRmsDegrees",
            "rotationMaxDegrees",
            "fovRmsDegrees",
            "fovMaxDegrees",
            "relativeTrajectoryRmsMeters",
            "netMotionDeltaMeters",
        )
    )
    typed_motion_difference = bool(difference["motionTypeDifferent"]) and (
        float(difference["relativeTrajectoryRmsMeters"])
        >= thresholds["typedMotionTrajectoryRmsMeters"]
        or float(difference["netMotionDeltaMeters"])
        >= thresholds["typedMotionNetDeltaMeters"]
    )
    return direct_difference or typed_motion_difference


def effective_candidate_selection_score(result: dict) -> float:
    """Return the rendered transition-aware score when it is available."""

    return float(
        result.get(
            "transitionAdjustedSelectionScore",
            result.get("selectionScore", float("inf")),
        )
    )


def apply_adjacent_transition_quality(
    candidates: list[dict],
    *,
    previous_state: dict[str, object] | None,
    next_state: dict[str, object] | None,
) -> None:
    """Annotate candidates against the selected/fixed adjacent cameras.

    Full generation supplies the *actually selected* preceding candidate.
    Single-shot regeneration also supplies the immutable next camera from the
    base composite, so a replacement cannot improve one cut while breaking the
    other. Reapplying the function is idempotent for cached candidate pools.
    """

    for candidate in candidates:
        transition_state = candidate.get("transitionState")
        if not isinstance(transition_state, dict):
            raise ValueError("Candidate is missing rendered transition state.")
        base_score = float(
            candidate.get(
                "selectionScoreBeforeTransition",
                candidate.get("selectionScore", float("inf")),
            )
        )
        if not math.isfinite(base_score):
            raise ValueError("Candidate selection score must be finite.")
        transition_quality = adjacent_transition.score_transition_context(
            transition_state,
            previous_state=previous_state,
            next_state=next_state,
        )
        candidate["selectionScoreBeforeTransition"] = base_score
        candidate["transitionQuality"] = transition_quality
        candidate["transitionAdjustedSelectionScore"] = float(
            base_score + float(transition_quality["penalty"])
        )


def transition_eligible_candidate_results(
    candidates: list[dict],
    *,
    shot_index: int | None = None,
) -> tuple[list[dict], bool]:
    """Return only candidates that pass every known adjacent edge.

    Transition-failed cameras must never re-enter through the Seed cycle.  The
    caller performs a bounded selection-only search before reaching this gate;
    exhausting that search without a passing candidate fails the shot closed.
    """

    if not candidates:
        raise ValueError("Transition selection requires at least one candidate.")
    passed: list[dict] = []
    for candidate in candidates:
        quality = candidate.get("transitionQuality")
        if not isinstance(quality, dict) or type(quality.get("passed")) is not bool:
            raise ValueError("Candidate transition-quality result is invalid.")
        if quality["passed"]:
            passed.append(candidate)
    if passed:
        return passed, False
    best = min(candidates, key=_camera_variation_sort_key)
    quality = best["transitionQuality"]
    failed_flags = sorted(
        {
            str(flag)
            for edge_name in ("previous", "next")
            for edge in (quality.get(edge_name),)
            if isinstance(edge, dict) and edge.get("passed") is False
            for flag in edge.get("flags", [])
        }
    )
    shot_label = f"Shot {shot_index} " if shot_index is not None else ""
    raise ValueError(
        f"{shot_label}has no camera candidate that passes every known "
        "adjacent transition after the bounded selection-only search: "
        f"safeCandidates={len(candidates)}, "
        f"candidateRanks={sorted(int(candidate.get('candidateRank', -1)) for candidate in candidates)}, "
        f"bestFailedCandidateRank={int(best.get('candidateRank', -1))}, "
        f"bestFailedFlags={failed_flags}. "
        f"Failure policy is {TRANSITION_GATE_FAILURE_POLICY}; a failed "
        "transition was not selected."
    )


def _camera_variation_sort_key(result: dict) -> tuple:
    template = result.get("template")
    return (
        effective_candidate_selection_score(result),
        int(result.get("candidateRank", 2**31 - 1)),
        str(getattr(template, "source_id", "")),
        int(getattr(template, "shot_index", -1)),
        float(result.get("safetyDistanceScale", 1.0)),
    )


def stabilized_screen_residual(
    projected_composition: object,
    desired_composition: object,
) -> np.ndarray:
    """Return the semantic-focus residual used for screen dynamics.

    Raw projected subject UV contains choreography.  Candidate dynamics must
    instead measure how far the rendered semantic focus departs from the
    stabilized desired UV path, so a dancer can move energetically without
    being mistaken for a camera-body impulse.
    """

    projected = np.asarray(projected_composition, dtype=np.float64)
    desired = np.asarray(desired_composition, dtype=np.float64)
    if (
        projected.ndim != 2
        or desired.ndim != 2
        or projected.shape[1] < 2
        or desired.shape[1] < 2
        or len(projected) == 0
        or len(projected) != len(desired)
    ):
        raise ValueError(
            "projected and desired composition must have matching non-empty "
            "[frame, component>=2] shapes"
        )
    residual = projected[:, :2] - desired[:, :2]
    if not np.all(np.isfinite(residual)):
        raise ValueError("stabilized screen residual must be finite")
    return residual


def candidate_dynamics_selection_penalty(
    cost: object,
    *,
    cost_passed: object | None = None,
    maximum_acceptable_cost: object = (
        CANDIDATE_DYNAMICS_MAXIMUM_ACCEPTABLE_COST
    ),
) -> float:
    """Prefer authored dynamics and strongly differentiate cost failures.

    Passing costs remain the established bounded tie-break.  A failed authored
    cost receives an explicit discontinuous penalty plus an uncapped excess
    term, so several very rough candidates can no longer all collapse to the
    same 0.9 score while still remaining available as a last-resort fallback.
    """

    if not isinstance(cost, (int, float)) or isinstance(cost, bool):
        raise ValueError("candidate dynamics cost must be a finite number")
    value = float(cost)
    if not math.isfinite(value) or value < 0.0:
        raise ValueError("candidate dynamics cost must be finite and non-negative")
    if (
        not isinstance(maximum_acceptable_cost, (int, float))
        or isinstance(maximum_acceptable_cost, bool)
    ):
        raise ValueError("maximum acceptable dynamics cost must be finite")
    maximum = float(maximum_acceptable_cost)
    if not math.isfinite(maximum) or maximum < 0.0:
        raise ValueError(
            "maximum acceptable dynamics cost must be finite and non-negative"
        )
    inferred_passed = value <= maximum
    if cost_passed is None:
        passed = inferred_passed
    elif type(cost_passed) is bool:
        passed = bool(cost_passed)
        if passed != inferred_passed:
            raise ValueError(
                "candidate dynamics costPassed disagrees with its cost threshold"
            )
    else:
        raise ValueError("candidate dynamics costPassed must be boolean")
    bounded_tiebreak = min(
        value * TRAJECTORY_DYNAMICS_SELECTION_WEIGHT,
        TRAJECTORY_DYNAMICS_MAXIMUM_SELECTION_PENALTY,
    )
    if passed:
        return float(bounded_tiebreak)
    return float(
        TRAJECTORY_DYNAMICS_MAXIMUM_SELECTION_PENALTY
        + CANDIDATE_DYNAMICS_COST_FAILURE_BASE_PENALTY
        + max(0.0, value - maximum)
        * CANDIDATE_DYNAMICS_COST_FAILURE_EXCESS_WEIGHT
    )


def candidate_passes_authored_dynamics_cost(candidate: dict) -> bool:
    """Return the explicit fail-closed authored dynamics-cost result."""

    dynamics = candidate.get("candidateDynamics")
    if not isinstance(dynamics, dict):
        return False
    cost_passed = dynamics.get("costPassed")
    cost = dynamics.get("cost")
    maximum = dynamics.get("maximumAcceptableCost")
    if (
        type(cost_passed) is not bool
        or not isinstance(cost, (int, float))
        or isinstance(cost, bool)
        or not isinstance(maximum, (int, float))
        or isinstance(maximum, bool)
    ):
        return False
    cost_value = float(cost)
    maximum_value = float(maximum)
    if (
        not math.isfinite(cost_value)
        or cost_value < 0.0
        or not math.isfinite(maximum_value)
        or maximum_value < 0.0
    ):
        return False
    return bool(cost_passed and cost_value <= maximum_value + 1e-12)


def candidate_passes_authored_angular_quality(candidate: dict) -> bool:
    """Fail closed on boolean or numeric authored-angle inconsistencies."""

    composition = candidate.get("composition")
    if not isinstance(composition, dict):
        return False
    target_passed = composition.get("aimAngularJerkAuthoredTargetPassed")
    tracking_passed = composition.get(
        "aimAngularMinimumJerkTrackingBudgetPassed"
    )
    maximum_jerk = composition.get(
        "aimAngularJerkDegreesPerSecondCubedMax"
    )
    authored_target = composition.get(
        "aimAngularJerkAuthoredTargetDegreesPerSecondCubed"
    )
    if (
        not isinstance(maximum_jerk, (int, float))
        or isinstance(maximum_jerk, bool)
        or not isinstance(authored_target, (int, float))
        or isinstance(authored_target, bool)
    ):
        return False
    maximum_jerk_value = float(maximum_jerk)
    authored_target_value = float(authored_target)
    jerk_numeric_passed = bool(
        math.isfinite(maximum_jerk_value)
        and maximum_jerk_value >= 0.0
        and math.isfinite(authored_target_value)
        and authored_target_value > 0.0
        and maximum_jerk_value <= authored_target_value + 1e-6
    )
    tracking_numeric_passed = _angular_tracking_deviation_within_budget(
        composition.get("aimAngularReferenceDeviationDegreesP90"),
        composition.get("aimAngularReferenceDeviationDegreesMax"),
        composition.get("aimAngularReferenceDeviationDegreesFinal"),
    )
    return bool(
        type(target_passed) is bool
        and target_passed
        and jerk_numeric_passed
        and type(tracking_passed) is bool
        and tracking_passed
        and tracking_numeric_passed
    )


def candidate_dynamics_hard_gate(
    translation_metrics: object,
    screen_metrics: object,
    *,
    final_relative_step_passed: object,
) -> dict[str, object]:
    """Evaluate the fail-closed final camera dynamics contract.

    Translation metrics audit the final world camera. Screen metrics audit the
    stabilized semantic-focus residual, rather than raw performer UV, so
    choreography cannot cause a false hard rejection. Percentiles keep ranking
    tolerant of harmless numerical noise, but a single rendered-frame impulse
    is still visible. The hard gate therefore checks both p99 and maxima, as
    well as the actual post-distance-clamp relative step. Missing, non-finite,
    or non-boolean audit data fails closed.
    """

    def finite_metric(
        metrics: object,
        group: str,
        statistic: str,
    ) -> float | None:
        if not isinstance(metrics, dict):
            return None
        values = metrics.get(group)
        if not isinstance(values, dict):
            return None
        value = values.get(statistic)
        if not isinstance(value, (int, float)) or isinstance(value, bool):
            return None
        result = float(value)
        return result if math.isfinite(result) and result >= 0.0 else None

    observed = {
        "translationMaximumSpeedMetersPerSecond": finite_metric(
            translation_metrics,
            "speedMetersPerSecond",
            "maximum",
        ),
        "translationMaximumAccelerationMetersPerSecondSquared": finite_metric(
            translation_metrics,
            "accelerationMetersPerSecondSquared",
            "maximum",
        ),
        "translationMaximumJerkMetersPerSecondCubed": finite_metric(
            translation_metrics,
            "jerkMetersPerSecondCubed",
            "maximum",
        ),
        "screenP99AccelerationUvPerSecondSquared": finite_metric(
            screen_metrics,
            "accelerationUvPerSecondSquared",
            "p99",
        ),
        "screenMaximumAccelerationUvPerSecondSquared": finite_metric(
            screen_metrics,
            "accelerationUvPerSecondSquared",
            "maximum",
        ),
        "screenP99JerkUvPerSecondCubed": finite_metric(
            screen_metrics,
            "jerkUvPerSecondCubed",
            "p99",
        ),
        "screenMaximumJerkUvPerSecondCubed": finite_metric(
            screen_metrics,
            "jerkUvPerSecondCubed",
            "maximum",
        ),
    }
    thresholds = {
        "translationMaximumSpeedMetersPerSecond": (
            TRAJECTORY_CATASTROPHIC_MAXIMUM_SPEED_MPS
        ),
        "translationMaximumAccelerationMetersPerSecondSquared": (
            TRAJECTORY_CATASTROPHIC_MAXIMUM_ACCELERATION_MPS2
        ),
        "translationMaximumJerkMetersPerSecondCubed": (
            TRAJECTORY_CATASTROPHIC_MAXIMUM_JERK_MPS3
        ),
        "screenP99AccelerationUvPerSecondSquared": (
            SCREEN_CATASTROPHIC_MAXIMUM_ACCELERATION_UVPS2_P99
        ),
        "screenMaximumAccelerationUvPerSecondSquared": (
            SCREEN_CATASTROPHIC_MAXIMUM_ACCELERATION_UVPS2
        ),
        "screenP99JerkUvPerSecondCubed": (
            SCREEN_CATASTROPHIC_MAXIMUM_JERK_UVPS3_P99
        ),
        "screenMaximumJerkUvPerSecondCubed": (
            SCREEN_CATASTROPHIC_MAXIMUM_JERK_UVPS3
        ),
    }
    checks = {
        name: bool(observed[name] is not None and observed[name] <= threshold)
        for name, threshold in thresholds.items()
    }
    checks["finalRelativeStep"] = bool(
        type(final_relative_step_passed) is bool
        and final_relative_step_passed
    )
    return {
        "policyVersion": CANDIDATE_DYNAMICS_HARD_GATE_POLICY_VERSION,
        "observed": observed,
        "thresholds": thresholds,
        "checks": checks,
        "passed": bool(all(checks.values())),
    }


def candidate_passes_safety_and_aim(candidate: dict) -> bool:
    """Gate selectable output on visibility, baked aim, and performer facing."""

    composition = candidate.get("composition", {})
    front_passed = candidate.get("frontFacingPassed")
    front_metrics = (
        candidate.get("frontFacingAlignment"),
        candidate.get("frontFacingAlignmentP10"),
        candidate.get("frontFacingSevereRearFrameRatio"),
    )
    front_metrics_are_finite = all(
        isinstance(value, (int, float)) and math.isfinite(float(value))
        for value in front_metrics
    )
    dynamics = candidate.get("candidateDynamics")
    dynamics_passed = (
        dynamics.get("passed") if isinstance(dynamics, dict) else None
    )
    dynamics_cost_passed = (
        dynamics.get("costPassed") if isinstance(dynamics, dict) else None
    )
    catastrophic_passed = candidate.get(
        "candidateDynamicsCatastrophicPassed"
    )
    final_post_clamp_kinematic_passed = candidate.get(
        "finalPostClampKinematicPassed"
    )
    return bool(
        composition.get("hardPersonSafetyPassed", False)
        and composition.get("aimQualityPassed", True)
        and composition.get("semanticProjectionSafetyPassed", True)
        # Runtime candidates must carry the current fail-closed facing audit.
        # Old cached payloads are rejected and rebuilt by cache preflight.
        and type(front_passed) is bool
        and front_passed
        and front_metrics_are_finite
        and type(dynamics_passed) is bool
        and dynamics_passed
        # Cost failure is a best-effort quality state rather than a
        # catastrophic safety failure, but the current explicit audit must be
        # present so pool-level authored-cost preference cannot be bypassed by
        # an old cache payload.
        and type(dynamics_cost_passed) is bool
        and type(catastrophic_passed) is bool
        and catastrophic_passed
        and dynamics_passed == catastrophic_passed
        # This field is deliberately fail-closed. Older candidate caches did
        # not audit the curve after radial projection and must be rebuilt.
        and type(final_post_clamp_kinematic_passed) is bool
        and final_post_clamp_kinematic_passed
    )


def quality_eligible_safe_variation_candidates(
    candidates: list[dict],
    maximum_score_delta: float = SEED_VARIATION_MAX_SELECTION_SCORE_DELTA,
) -> list[dict]:
    """Return safe candidates within a bounded quality loss from the best."""

    if maximum_score_delta < 0.0:
        raise ValueError("maximum_score_delta must be non-negative.")
    safe_candidates = [
        candidate
        for candidate in candidates
        if candidate_passes_safety_and_aim(candidate)
    ]
    authored_cost_candidates = [
        candidate
        for candidate in safe_candidates
        if candidate_passes_authored_dynamics_cost(candidate)
    ]
    authored_angular_candidates = [
        candidate
        for candidate in safe_candidates
        if candidate_passes_authored_angular_quality(candidate)
    ]
    fully_authored_candidates = [
        candidate
        for candidate in authored_cost_candidates
        if candidate_passes_authored_angular_quality(candidate)
    ]
    # Prefer authored-cost candidates absolutely whenever one exists.  Failed
    # costs remain only as an explicit last-resort fallback so generation does
    # not become unavailable for a difficult shot.
    preferred_candidates = (
        fully_authored_candidates
        or authored_cost_candidates
        or authored_angular_candidates
        or safe_candidates
    )
    safe_candidates = sorted(
        (
            candidate
            for candidate in preferred_candidates
        ),
        key=_camera_variation_sort_key,
    )
    if not safe_candidates:
        return []
    best_score = effective_candidate_selection_score(safe_candidates[0])
    return [
        candidate
        for candidate in safe_candidates
        if effective_candidate_selection_score(candidate)
        <= best_score + maximum_score_delta
    ]


def build_distinct_safe_variation_pool(
    candidates: list[dict],
    maximum_size: int = SEED_VARIATION_MAX_POOL_SIZE,
) -> list[dict]:
    """Build a quality-ordered pool of pairwise-distinct safe cameras."""

    if maximum_size <= 0:
        raise ValueError("maximum_size must be positive.")
    safe_candidates = quality_eligible_safe_variation_candidates(
        candidates,
    )
    pool: list[dict] = []
    for candidate in safe_candidates:
        if all(
            camera_candidates_are_visually_distinct(candidate, existing)
            for existing in pool
        ):
            pool.append(candidate)
            if len(pool) >= maximum_size:
                break
    return pool


def seed_variation_needs_more_candidates(candidates: list[dict]) -> bool:
    """Whether adaptive evaluation still lacks two distinct safe choices."""

    fully_authored_candidates = [
        candidate
        for candidate in candidates
        if candidate_passes_authored_dynamics_cost(candidate)
        and candidate_passes_authored_angular_quality(candidate)
    ]
    return (
        len(build_distinct_safe_variation_pool(fully_authored_candidates)) < 2
    )


def transition_passing_distinct_variation_pool(
    candidates: list[dict],
    *,
    previous_state: dict[str, object] | None,
    next_state: dict[str, object] | None,
) -> list[dict]:
    """Build a non-mutating pool that passes every currently known cut edge."""

    if not candidates:
        return []
    selection_copies = [dict(candidate) for candidate in candidates]
    apply_adjacent_transition_quality(
        selection_copies,
        previous_state=previous_state,
        next_state=next_state,
    )
    passing = [
        candidate
        for candidate in selection_copies
        if candidate["transitionQuality"]["passed"]
    ]
    return build_distinct_safe_variation_pool(passing)


def transition_context_needs_more_candidates(
    candidates: list[dict],
    *,
    previous_state: dict[str, object] | None,
    next_state: dict[str, object] | None,
) -> bool:
    """Whether fewer than two safe/distinct candidates pass adjacent cuts."""

    return len(
        transition_passing_distinct_variation_pool(
            candidates,
            previous_state=previous_state,
            next_state=next_state,
        )
    ) < 2


def next_unevaluated_transition_candidate_rank(candidates: list[dict]) -> int:
    """Return the first rank after the contiguous rendered normal prefix."""

    evaluated_ranks = {
        int(candidate["candidateRank"])
        for candidate in candidates
        if isinstance(candidate.get("candidateRank"), int)
        and 0 <= int(candidate["candidateRank"])
        < SEED_VARIATION_MAX_TRANSITION_CANDIDATES
        and abs(float(candidate.get("safetyDistanceScale", 1.0)) - 1.0)
        <= 1e-9
    }
    return max(evaluated_ranks) + 1 if evaluated_ranks else 0


def transition_candidate_pool_may_expand(
    candidate_results: list[dict],
    safe_results: list[dict],
    *,
    previous_state: dict[str, object] | None,
    next_state: dict[str, object] | None,
) -> bool:
    """Whether a cached base can still benefit from bounded lazy ranks.

    Normal ranks seek two passing/distinct Seed choices.  The extended ranks
    are an emergency fail-avoidance budget and stop after the first passing
    candidate, so a difficult transition cannot multiply normal work by two.
    """

    passing_count = len(
        transition_passing_distinct_variation_pool(
            safe_results,
            previous_state=previous_state,
            next_state=next_state,
        )
    )
    next_rank = next_unevaluated_transition_candidate_rank(candidate_results)
    if next_rank < SEED_VARIATION_MAX_NORMAL_CANDIDATES:
        return passing_count < 2
    return (
        passing_count == 0
        and next_rank < SEED_VARIATION_MAX_TRANSITION_CANDIDATES
    )


def cache_eligible_candidate_results(candidates: list[dict]) -> list[dict]:
    """Return only the Seed-independent base candidates persisted in caches."""

    return [
        candidate
        for candidate in candidates
        if candidate.get("cacheEligible", True) is True
    ]


def select_seeded_camera_variation(
    candidates: list[dict],
    seed: int,
    shot_index: int,
    variation_pool: list[dict] | None = None,
) -> tuple[dict, dict[str, int | float | bool | str]]:
    """Select a safe distinct camera using an adjacent-seed cycle.

    Incrementing the seed increments the pool index.  Therefore adjacent
    seeds cannot return the same candidate whenever at least two distinct safe
    candidates exist, while an identical seed remains fully reproducible.
    """

    pool = (
        build_distinct_safe_variation_pool(candidates)
        if variation_pool is None
        else list(variation_pool)
    )
    if not pool:
        raise ValueError("No safe camera candidate is available for variation.")
    variation_index = (
        int(seed) + int(shot_index) * SEED_VARIATION_SHOT_STRIDE
    ) % len(pool)
    safe_candidate_count = sum(
        candidate_passes_safety_and_aim(candidate)
        for candidate in candidates
    )
    quality_eligible = quality_eligible_safe_variation_candidates(candidates)
    best_selection_score = effective_candidate_selection_score(
        quality_eligible[0]
    )
    selected_score_delta = (
        effective_candidate_selection_score(pool[variation_index])
        - best_selection_score
    )
    return pool[variation_index], {
        "variationPolicy": SEED_VARIATION_POLICY_VERSION,
        "variationSeed": int(seed),
        "variationPoolSize": len(pool),
        "variationSafeCandidateCount": int(safe_candidate_count),
        "variationQualityEligibleCandidateCount": len(quality_eligible),
        "variationIndex": int(variation_index),
        "variationApplied": len(pool) > 1,
        "variationBestSelectionScore": best_selection_score,
        "variationSelectedScoreDeltaFromBest": selected_score_delta,
        "variationMaximumSelectionScoreDelta": (
            SEED_VARIATION_MAX_SELECTION_SCORE_DELTA
        ),
    }


def select_seed_independent_sequence_continuation(
    candidates: list[dict],
    variation_pool: list[dict] | None = None,
) -> dict:
    """Choose deterministic state for planning the following camera shot.

    The generated Seed must alter the rendered candidate, not the candidate
    context used by later shots.  Otherwise two adjacent Seeds can build
    different later pools and accidentally converge back to the same camera.
    """

    pool = (
        build_distinct_safe_variation_pool(candidates)
        if variation_pool is None
        else list(variation_pool)
    )
    if not pool:
        raise ValueError(
            "No safe camera candidate is available for sequence continuation."
        )
    return pool[0]


def advance_sequence_context(
    selected_result: dict,
    planner_continuation_result: dict,
) -> tuple[RealizedShotState, dict[str, object]]:
    """Split cached planner history from the rendered transition history."""

    continuation_template = planner_continuation_result.get("template")
    selected_transition = selected_result.get("transitionState")
    if continuation_template is None or not isinstance(selected_transition, dict):
        raise ValueError("Camera sequence continuation state is incomplete.")
    planner_state = RealizedShotState(
        template=continuation_template,
        side_sign=float(planner_continuation_result["realizedSideSign"]),
        motion_type=str(planner_continuation_result["realizedMotionType"]),
    )
    return planner_state, selected_transition


def selectable_safe_candidate_results(
    candidate_results: list[dict],
    moving_opening_required: bool,
    desired_motion_type: str | None,
    rolling_static_budget_required: bool = False,
    planned_non_static_required: bool = False,
) -> list[dict]:
    """Apply person, visible-motion budget and exact-motion policies."""

    safe_results = [
        result
        for result in candidate_results
        if candidate_passes_safety_and_aim(result)
    ]
    authored_cost_results = [
        result
        for result in safe_results
        if candidate_passes_authored_dynamics_cost(result)
    ]
    fully_authored_results = [
        result
        for result in authored_cost_results
        if candidate_passes_authored_angular_quality(result)
    ]
    policy_results = visible_non_static_results(
        fully_authored_results or authored_cost_results or safe_results,
        moving_opening_required
        or rolling_static_budget_required
        or planned_non_static_required,
    )
    if desired_motion_type is not None:
        exact_motion_results = [
            result
            for result in policy_results
            if result["realizedMotionType"] == desired_motion_type
        ]
        # Keep the established best-effort directive contract.  An unavailable
        # exact motion is not the same thing as a person-safety failure.
        if exact_motion_results:
            return exact_motion_results
    return policy_results


def policy_safe_candidate_results(
    candidate_results: list[dict],
    moving_opening_required: bool,
    rolling_static_budget_required: bool = False,
    planned_non_static_required: bool = False,
) -> list[dict]:
    return visible_non_static_results(
        [
            result
            for result in candidate_results
            if candidate_passes_safety_and_aim(result)
            and candidate_passes_authored_dynamics_cost(result)
        ],
        moving_opening_required
        or rolling_static_budget_required
        or planned_non_static_required,
    )


def candidate_selection_score(
    candidate_result: dict,
    candidate_rank: int,
    safety_distance_scale: float,
) -> float:
    motion_adjustment = float(
        candidate_result.get("motionQuality", {}).get(
            "motionSelectionAdjustment",
            0.0,
        )
    )
    return float(
        candidate_result["qualityScore"]
        + candidate_rank * 0.08
        + (safety_distance_scale - 1.0) * 0.5
        + motion_adjustment
    )


def evaluate_safe_candidate_pool(
    ranked_templates: list[ShotTemplate],
    previous: RealizedShotState | None,
    target: train.PreparedSong,
    joints: np.ndarray,
    root: np.ndarray,
    start: int,
    end: int,
    target_aspect_ratio: float,
    effective_composition: str,
    control: ShotControl,
    body_follow_smoothing_seconds: float,
    body_follow_dead_zone_meters: float,
    effective_motion_intensity: float,
    moving_opening_required: bool,
    desired_motion_type: str | None,
    rolling_static_budget_required: bool = False,
    planned_non_static_required: bool = False,
    previous_transition_state: dict[str, object] | None = None,
    next_transition_state: dict[str, object] | None = None,
    cached_base_candidate_results: list[dict] | None = None,
    front_facing_reference: dict[str, object] | None = None,
) -> tuple[list[dict], list[dict]]:
    """Retarget a deterministic base plus lazy selection-only transition ranks.

    The base extent follows only the established safety/distinctness policy and
    is therefore safe to cache under a Seed-independent key.  Actual rendered
    adjacent cameras may lazily add later ranks, but those candidates are marked
    ``cacheEligible=False`` and may influence only the current output selection.
    A cache hit can resume from its base without retargeting the first ranks.
    """

    candidate_results: list[dict] = (
        list(cached_base_candidate_results)
        if cached_base_candidate_results is not None
        else []
    )
    for candidate in candidate_results:
        if candidate.get("cacheEligible", True) is not True:
            raise ValueError("A resumed candidate pool must contain only base ranks.")

    def evaluate_candidate(
        candidate_rank: int,
        candidate_template: ShotTemplate,
        safety_distance_scale: float = 1.0,
        *,
        cache_eligible: bool,
    ) -> dict | None:
        try:
            candidate_result = retarget_template_to_shot(
                candidate_template,
                previous,
                target,
                joints,
                root,
                start,
                end,
                target_aspect_ratio,
                effective_composition,
                body_follow_strength=control.body_follow_strength,
                body_follow_smoothing_seconds=body_follow_smoothing_seconds,
                body_follow_dead_zone_meters=body_follow_dead_zone_meters,
                distance_meters=control.distance_meters,
                motion_intensity=effective_motion_intensity,
                safety_distance_scale=safety_distance_scale,
                front_facing_reference=front_facing_reference,
            )
        except CandidateRetargetSafetyRejection:
            return None
        candidate_result["candidateRank"] = candidate_rank
        candidate_result["selectionScore"] = candidate_selection_score(
            candidate_result,
            candidate_rank,
            safety_distance_scale,
        )
        candidate_result["cacheEligible"] = bool(cache_eligible)
        candidate_results.append(candidate_result)
        return candidate_result

    initial_count = min(
        SEED_VARIATION_INITIAL_CANDIDATES,
        len(ranked_templates),
    )
    maximum_normal_candidates = min(
        SEED_VARIATION_MAX_NORMAL_CANDIDATES,
        len(ranked_templates),
    )
    maximum_transition_candidates = min(
        SEED_VARIATION_MAX_TRANSITION_CANDIDATES,
        len(ranked_templates),
    )
    if cached_base_candidate_results is None:
        for candidate_rank, candidate_template in enumerate(
            ranked_templates[:initial_count]
        ):
            evaluate_candidate(
                candidate_rank,
                candidate_template,
                cache_eligible=True,
            )

        safe_results = selectable_safe_candidate_results(
            candidate_results,
            moving_opening_required,
            desired_motion_type,
            rolling_static_budget_required,
            planned_non_static_required,
        )
        for candidate_rank, candidate_template in enumerate(
            ranked_templates[initial_count:maximum_normal_candidates],
            start=initial_count,
        ):
            if not seed_variation_needs_more_candidates(safe_results):
                break
            evaluate_candidate(
                candidate_rank,
                candidate_template,
                cache_eligible=True,
            )
            safe_results = selectable_safe_candidate_results(
                candidate_results,
                moving_opening_required,
                desired_motion_type,
                rolling_static_budget_required,
                planned_non_static_required,
            )

        # Preserve the old fail-avoidance path when the bounded diversity
        # search has not found even one policy-eligible safe camera.
        if (
            not policy_safe_candidate_results(
                candidate_results,
                moving_opening_required,
                rolling_static_budget_required,
                planned_non_static_required,
            )
            and maximum_normal_candidates < len(ranked_templates)
        ):
            for candidate_rank, candidate_template in enumerate(
                ranked_templates[maximum_normal_candidates:],
                start=maximum_normal_candidates,
            ):
                evaluate_candidate(
                    candidate_rank,
                    candidate_template,
                    cache_eligible=True,
                )
            safe_results = selectable_safe_candidate_results(
                candidate_results,
                moving_opening_required,
                desired_motion_type,
                rolling_static_budget_required,
                planned_non_static_required,
            )

        if not safe_results:
            for safety_distance_scale in (1.15, 1.35, 1.65, 2.0):
                for fallback_rank, candidate_template in enumerate(
                    ranked_templates[:initial_count]
                ):
                    evaluate_candidate(
                        fallback_rank,
                        candidate_template,
                        safety_distance_scale,
                        cache_eligible=True,
                    )
                safe_results = selectable_safe_candidate_results(
                    candidate_results,
                    moving_opening_required,
                    desired_motion_type,
                    rolling_static_budget_required,
                    planned_non_static_required,
                )
                if not seed_variation_needs_more_candidates(safe_results):
                    break

        if not candidate_results:
            raise CandidateRetargetSafetyRejection(
                "All bounded retarget candidates failed their final safety audit."
            )
    else:
        safe_results = selectable_safe_candidate_results(
            candidate_results,
            moving_opening_required,
            desired_motion_type,
            rolling_static_budget_required,
            planned_non_static_required,
        )

    base_candidate_count = len(candidate_results)
    next_normal_rank = next_unevaluated_transition_candidate_rank(
        candidate_results
    )
    for candidate_rank in range(next_normal_rank, maximum_normal_candidates):
        if not transition_context_needs_more_candidates(
            safe_results,
            previous_state=previous_transition_state,
            next_state=next_transition_state,
        ):
            break
        evaluate_candidate(
            candidate_rank,
            ranked_templates[candidate_rank],
            cache_eligible=False,
        )
        safe_results = selectable_safe_candidate_results(
            candidate_results,
            moving_opening_required,
            desired_motion_type,
            rolling_static_budget_required,
            planned_non_static_required,
        )
    extended_transition_start = max(
        next_normal_rank,
        maximum_normal_candidates,
    )
    for candidate_rank in range(
        extended_transition_start,
        maximum_transition_candidates,
    ):
        if transition_passing_distinct_variation_pool(
            safe_results,
            previous_state=previous_transition_state,
            next_state=next_transition_state,
        ):
            break
        evaluate_candidate(
            candidate_rank,
            ranked_templates[candidate_rank],
            cache_eligible=False,
        )
        safe_results = selectable_safe_candidate_results(
            candidate_results,
            moving_opening_required,
            desired_motion_type,
            rolling_static_budget_required,
            planned_non_static_required,
        )
    if cached_base_candidate_results is not None and any(
        candidate.get("cacheEligible", True) is not True
        for candidate in candidate_results[:base_candidate_count]
    ):
        raise ValueError("Selection-only candidates contaminated the cached base.")
    return candidate_results, safe_results


def validate_training_index_catalog_freshness(
    index_path: Path,
    payload: dict,
) -> Path:
    """Resolve and verify the catalog bytes recorded by a training index."""

    catalog_value = str(payload.get("catalog", "")).strip()
    expected_sha256 = str(payload.get("catalogSha256", "")).strip().lower()
    if (
        not catalog_value
        or len(expected_sha256) != 64
        or any(character not in "0123456789abcdef" for character in expected_sha256)
    ):
        raise ValueError(
            "Training index is missing valid catalog provenance. "
            "Rebuild it with tools/build_training_index.py."
        )

    catalog_path = Path(catalog_value)
    if catalog_path.is_absolute():
        candidates = [catalog_path]
    else:
        resolved_index = index_path.resolve()
        candidates = [
            resolved_index.parent / catalog_path,
            resolved_index.parent.parent / catalog_path,
            Path.cwd() / catalog_path,
        ]
    unique_candidates: list[Path] = []
    seen: set[Path] = set()
    for candidate in candidates:
        resolved_candidate = candidate.resolve()
        if resolved_candidate not in seen:
            seen.add(resolved_candidate)
            unique_candidates.append(resolved_candidate)
    resolved_catalog = next(
        (candidate for candidate in unique_candidates if candidate.is_file()),
        None,
    )
    if resolved_catalog is None:
        searched = ", ".join(str(candidate) for candidate in unique_candidates)
        raise FileNotFoundError(
            f"Training-index catalog was not found. Searched: {searched}"
        )
    catalog_bytes = resolved_catalog.read_bytes()
    pointer_probe = catalog_bytes
    utf8_bom = UTF8_BOM.encode("utf-8")
    if pointer_probe.startswith(utf8_bom):
        pointer_probe = pointer_probe[len(utf8_bom) :]
    if pointer_probe.startswith(GIT_LFS_POINTER_PREFIX.encode("ascii")):
        raise ValueError(
            "Training-index catalog is still a Git LFS pointer: "
            f"{resolved_catalog}. Materialize Git LFS assets and retry."
        )

    actual_sha256 = hashlib.sha256(catalog_bytes).hexdigest().lower()
    catalog_matches = actual_sha256 == expected_sha256
    if not catalog_matches:
        try:
            catalog_bytes.decode("utf-8", errors="strict")
        except UnicodeDecodeError:
            normalized_sha256 = None
        else:
            all_cr_bytes_are_crlf = all(
                offset + 1 < len(catalog_bytes)
                and catalog_bytes[offset + 1] == 0x0A
                for offset, value in enumerate(catalog_bytes)
                if value == 0x0D
            )
            if all_cr_bytes_are_crlf:
                normalized_bytes = catalog_bytes.replace(b"\r\n", b"\n")
                normalized_sha256 = hashlib.sha256(
                    normalized_bytes
                ).hexdigest().lower()
            else:
                normalized_sha256 = None
        catalog_matches = normalized_sha256 == expected_sha256

    if not catalog_matches:
        raise ValueError(
            "Training index is stale: catalog SHA-256 mismatch for "
            f"{resolved_catalog}. Expected {expected_sha256}, got {actual_sha256}. "
            "Rebuild it with tools/build_training_index.py."
        )
    return resolved_catalog


def load_training_policy(
    index_path: Path,
) -> tuple[dict, dict[str, dict]]:
    """Load and validate the leakage-control index used by generation."""

    resolved = index_path.resolve()
    if not resolved.is_file():
        raise FileNotFoundError(
            f"Training index was not found: {resolved}. "
            "Run tools/build_training_index.py first."
        )
    payload = json.loads(resolved.read_text(encoding="utf-8"))
    validate_training_index_catalog_freshness(resolved, payload)
    entries = {
        str(entry["songId"]): entry
        for entry in payload.get("entries", [])
    }
    if not entries:
        raise ValueError(f"Training index contains no entries: {resolved}")
    for song_id, entry in entries.items():
        explicit_audio_aligned_frame_mask_ranges(entry, song_id)
    missing_group = [
        song_id
        for song_id, entry in entries.items()
        if not entry.get("evaluationGroupId")
    ]
    if missing_group:
        raise ValueError(
            "Training index predates leakage-safe evaluation groups. "
            "Regenerate it with tools/build_training_index.py."
        )
    group_splits: dict[str, set[str]] = {}
    for entry in entries.values():
        group = str(entry["evaluationGroupId"])
        group_splits.setdefault(group, set()).add(
            str(entry["recommendedSplit"])
        )
    conflicts = {
        group: sorted(splits)
        for group, splits in group_splits.items()
        if len(splits) > 1
    }
    if conflicts:
        raise ValueError(
            "Training index has evaluation groups spanning multiple splits: "
            + json.dumps(conflicts, ensure_ascii=False, sort_keys=True)
        )
    return payload, entries


def generation_data_inputs(
    requested: list[str],
    training_index_path: Path,
    training_index: dict,
) -> list[str]:
    """Include the indexed reference library beside an explicit new target.

    Unity passes one freshly exported generation manifest.  The target is not
    a member of the training index, so the reference data root recorded by the
    index is added automatically instead of exposing a confusing dataset-song
    selector in the generation workflow.
    """

    if not requested:
        return []
    values = list(requested)
    data_root_value = str(training_index.get("dataRoot", "")).strip()
    if not data_root_value:
        return values
    data_root = Path(data_root_value)
    candidates = (
        [data_root]
        if data_root.is_absolute()
        else [
            training_index_path.resolve().parent.parent / data_root,
            Path.cwd() / data_root,
        ]
    )
    existing = {Path(value).resolve() for value in values}
    for candidate in candidates:
        resolved = candidate.resolve()
        if resolved.is_dir() and resolved not in existing:
            values.append(str(resolved))
            break
    return values


def target_reference_evaluation_group(
    entries: dict[str, dict],
    target_record: train.SongRecord,
) -> str | None:
    """Return the indexed logical-song group used only for leakage exclusion.

    A camera-free generation input is never itself a training-index member.
    It can nevertheless share the legacy logical ``SongRecord.id`` with an
    authored record from the same scene.  That collision remains useful for
    excluding the authored evaluation group from trajectory/planner fitting,
    but must not turn the camera-free input into an authored target.
    """

    entry = entries.get(target_record.id)
    if entry is None or not str(entry.get("evaluationGroupId", "")).strip():
        return None
    return str(entry["evaluationGroupId"])


def normalized_audio_sha256(value: object, label: str) -> str | None:
    """Validate an optional SHA-256 audio identity without guessing."""

    normalized = str(value or "").strip().lower()
    if not normalized:
        return None
    if len(normalized) != 64 or any(
        character not in "0123456789abcdef" for character in normalized
    ):
        raise ValueError(f"{label} must be a lowercase SHA-256 fingerprint.")
    return normalized


@functools.lru_cache(maxsize=1024)
def _cached_file_sha256(
    resolved_path: str,
    size: int,
    modified_nanoseconds: int,
) -> str:
    del size, modified_nanoseconds
    return sha256_file(Path(resolved_path))


def cached_file_sha256(path: Path) -> str:
    """Hash an immutable generation input once per worker process."""

    resolved = Path(path).resolve()
    stat_result = resolved.stat()
    return _cached_file_sha256(
        str(resolved),
        int(stat_result.st_size),
        int(stat_result.st_mtime_ns),
    )


def verified_exact_audio_fingerprint(
    record: train.SongRecord,
    indexed_entry: dict | None,
    *,
    fail_on_disagreement: bool = False,
) -> str | None:
    """Cross-check all available actual, declared, and indexed audio IDs.

    Raw audio is authoritative when it is packaged.  Portable libraries may
    deliberately omit it, in which case matching manifest and index hashes are
    sufficient.  Any disagreement excludes the record from the exact-audio
    exception; generic duration/cut priors remain available.
    """

    declared = normalized_audio_sha256(
        record.song.get("audioFingerprint"),
        f"Declared audio fingerprint for {record.id}",
    )
    indexed = (
        normalized_audio_sha256(
            indexed_entry.get("audioFingerprint"),
            f"Indexed audio fingerprint for {record.id}",
        )
        if isinstance(indexed_entry, dict)
        else None
    )
    actual = (
        cached_file_sha256(record.audio_path)
        if record.audio_path.is_file()
        else None
    )
    evidence = [
        fingerprint
        for fingerprint in (actual, declared, indexed)
        if fingerprint is not None
    ]
    if len(set(evidence)) > 1:
        if fail_on_disagreement:
            raise ValueError(
                "Audio fingerprint evidence disagrees for generation target "
                f"{record.id}; re-export the Timeline input before generation."
            )
        return None
    if not evidence:
        return None
    if indexed_entry is not None and indexed is None:
        return None
    if actual is None and declared is None:
        return None
    return evidence[0]


def authored_record_equivalence_fingerprint(
    record: train.SongRecord,
) -> str | None:
    """Identify complete duplicate exports by the bytes generation consumes."""

    raw_file_paths = {
        "audio": record.audio_path,
        "joints": record.song_dir / "joints_world.f32",
        "root": record.song_dir / "root.f32",
        "camera": record.song_dir / "camera.f32",
        "shotIndex": record.song_dir / "shot_index.i32",
        "time": record.song_dir / "time.f64",
        "shots": record.song_dir / str(record.song.get("shotsFile", "shots.json")),
    }
    if all(path.is_file() for path in raw_file_paths.values()):
        representation = "raw-v1"
        file_paths = raw_file_paths
    else:
        portable_file_paths = {
            "prepared": record.portable_prepared_path,
            "shots": record.song_dir
            / str(record.song.get("shotsFile", "shots.json")),
        }
        if any(not path.is_file() for path in portable_file_paths.values()):
            return None
        representation = "portable-v1"
        file_paths = portable_file_paths
    if not file_paths:
        return None
    identity = {
        "representation": representation,
        "songId": record.id,
        "songName": record.name,
        "sampleRate": record.song.get(
            "sampleRate",
            record.manifest.get("sampleRate"),
        ),
        "frameCount": record.song.get("frameCount"),
        "audioStart": record.song.get("audioStart"),
        "audioDuration": record.song.get("audioDuration"),
        "sampleStart": record.song.get("sampleStart"),
        "sampleEndExclusive": record.song.get("sampleEndExclusive"),
        "shotCount": record.song.get("shotCount"),
        "sharedBoneCount": record.song.get("sharedBoneCount"),
        "sharedBones": record.manifest.get("sharedBones"),
        "audioFingerprint": record.song.get("audioFingerprint"),
        "files": {
            name: cached_file_sha256(path)
            for name, path in sorted(file_paths.items())
        },
    }
    return candidate_cache.fingerprint_value(identity)


def is_index_authoritative_portable_record(
    record: train.SongRecord,
    indexed_entry: dict | None,
) -> bool:
    """Recognize the indexed portable derivative of an authored export.

    RuntimeData intentionally replaces the large raw arrays with prepared
    inference data, so it cannot be byte-identical to the source export.  It
    is authoritative only when its dataset/folder metadata and declared audio
    identity agree with the training index and the prepared payload exists.
    """

    if not isinstance(indexed_entry, dict):
        return False
    if str(indexed_entry.get("datasetId", "")) != record.dataset_id:
        return False
    indexed_folder = str(indexed_entry.get("folder", "")).replace("\\", "/")
    expected_folder = f"{record.dataset_id}/{record.song['folderName']}"
    if indexed_folder and indexed_folder != expected_folder:
        return False
    indexed_name = str(indexed_entry.get("songName", ""))
    if indexed_name and indexed_name != record.name:
        return False
    for field in ("frameCount", "shotCount"):
        if field in indexed_entry and int(indexed_entry[field]) != int(
            record.song.get(field, -1)
        ):
            return False
    if not record.portable_prepared_path.is_file():
        return False
    declared = normalized_audio_sha256(
        record.song.get("audioFingerprint"),
        f"Declared audio fingerprint for {record.id}",
    )
    indexed = normalized_audio_sha256(
        indexed_entry.get("audioFingerprint"),
        f"Indexed audio fingerprint for {record.id}",
    )
    return declared is not None and declared == indexed


def available_authored_records_by_id(
    records: list[train.SongRecord],
    entries: dict[str, dict] | None = None,
) -> dict[str, train.SongRecord]:
    """Return unambiguous authored exports without data-root last-win.

    A packaged RuntimeData derivative may coexist with its raw project export.
    The indexed portable copy wins only after every duplicate's available
    audio evidence agrees with that same index entry.  All other divergent or
    incomplete duplicate groups fail closed.
    """

    grouped: dict[str, dict[tuple[str, str], train.SongRecord]] = {}
    for record in records:
        if record.is_generation_input:
            continue
        physical_identity = (
            str(record.manifest_path.resolve()),
            str(record.song.get("folderName", "")),
        )
        grouped.setdefault(record.id, {})[physical_identity] = record

    selected: dict[str, train.SongRecord] = {}
    ambiguous: dict[str, list[str]] = {}
    for song_id, physical_records in grouped.items():
        candidates = list(physical_records.values())
        if len(candidates) == 1:
            selected[song_id] = candidates[0]
            continue
        indexed_entry = entries.get(song_id) if entries is not None else None
        authoritative_portable = [
            record
            for record in candidates
            if is_index_authoritative_portable_record(record, indexed_entry)
        ]
        portable_group_verified = False
        if authoritative_portable:
            verified_audio = [
                verified_exact_audio_fingerprint(record, indexed_entry)
                for record in candidates
            ]
            indexed_audio = normalized_audio_sha256(
                indexed_entry.get("audioFingerprint"),
                f"Indexed audio fingerprint for {song_id}",
            )
            portable_group_verified = indexed_audio is not None and all(
                fingerprint == indexed_audio
                for fingerprint in verified_audio
            )
            if portable_group_verified and len(authoritative_portable) == 1:
                selected[song_id] = authoritative_portable[0]
                continue
        equivalence_candidates = (
            authoritative_portable
            if portable_group_verified and len(authoritative_portable) > 1
            else candidates
        )
        fingerprints = [
            authored_record_equivalence_fingerprint(record)
            for record in equivalence_candidates
        ]
        if fingerprints[0] is None or any(
            fingerprint != fingerprints[0]
            for fingerprint in fingerprints[1:]
        ):
            ambiguous[song_id] = sorted(
                f"{record.dataset_id}:{record.manifest_path}"
                for record in candidates
            )
            continue
        selected[song_id] = sorted(
            equivalence_candidates,
            key=lambda record: (
                not record.portable_prepared_path.is_file(),
                not (
                    bool(record.song.get("audioFile"))
                    and record.audio_path.is_file()
                ),
                str(record.manifest_path.resolve()),
            ),
        )[0]
    if ambiguous:
        raise ValueError(
            "Duplicate authored song IDs are ambiguous across data roots; "
            "remove the duplicate export or rebuild one authoritative library: "
            + json.dumps(ambiguous, ensure_ascii=False, sort_keys=True)
        )
    return selected


def select_generation_records(
    records: list[train.SongRecord],
    entries: dict[str, dict],
    target_record: train.SongRecord,
    library_split: str,
) -> tuple[list[train.SongRecord], list[train.SongRecord], dict | None, int]:
    """Select leakage-safe trajectory and planner libraries.

    Exact-audio cut references are selected separately because production may
    use authored edit timing without admitting the same record's camera path
    into either model/template pool.
    """

    indexed_collision_entry = entries.get(target_record.id)
    target_entry = (
        None if target_record.is_generation_input else indexed_collision_entry
    )
    target_is_unindexed_generation_input = (
        target_entry is None and target_record.is_generation_input
    )
    if target_entry is None and not target_is_unindexed_generation_input:
        raise ValueError(
            f"Authored-camera target song {target_record.id} is missing from "
            "the training index. Only an explicit camera-free "
            "inputKind='generation_input' target may be unindexed."
        )
    target_group = target_reference_evaluation_group(entries, target_record)
    available_by_id = available_authored_records_by_id(records, entries)
    target_group_available = (
        sum(
            entry.get("evaluationGroupId") == target_group
            and song_id in available_by_id
            for song_id, entry in entries.items()
        )
        if target_group is not None
        else 0
    )

    selected: list[train.SongRecord] = []
    planner_records: list[train.SongRecord] = []
    for song_id, record in available_by_id.items():
        if song_id == target_record.id:
            continue
        entry = entries.get(song_id)
        if entry is None:
            raise ValueError(
                f"Available reference song {song_id} is missing from the "
                "training index. The unindexed exception applies only to the "
                "selected generation target."
            )
        if (
            target_group is not None
            and str(entry["evaluationGroupId"]) == target_group
        ):
            continue
        if library_split == "train" and entry["recommendedSplit"] != "train":
            continue
        if bool(entry.get("usage", {}).get("trajectoryTemplates", False)):
            selected.append(record)
        if bool(entry.get("usage", {}).get("shotPlanner", False)):
            if entry.get("role") != "primary":
                raise ValueError(
                    "Training index marks a non-primary track for the "
                    f"shot planner: {song_id} ({entry.get('role')!r})."
                )
            planner_records.append(record)

    planner_only_ids = sorted(
        {record.id for record in planner_records}
        - {record.id for record in selected}
    )
    if planner_only_ids:
        raise ValueError(
            "The hybrid shotPlanner consumer requires every planner record to "
            "also be admitted to trajectoryTemplates so both paths use the "
            "same audio-masked ShotTemplate objects: "
            + ", ".join(planner_only_ids)
        )
    if len(selected) < 2:
        raise ValueError(
            "Leakage-safe policy selected fewer than two template songs."
        )
    if len(planner_records) < 2:
        raise ValueError(
            "Leakage-safe policy selected fewer than two planner songs."
        )
    return (
        sorted(selected, key=lambda item: item.id),
        sorted(planner_records, key=lambda item: item.id),
        target_entry,
        target_group_available,
    )


def select_cut_reference_records(
    records: list[train.SongRecord],
    entries: dict[str, dict],
    target_record: train.SongRecord,
    library_split: str,
    *,
    allow_exact_audio_prior: bool,
) -> list[train.SongRecord]:
    """Select cut-only references under an explicit production exception.

    The baseline follows the same ID/group/split exclusions as trajectory and
    planner selection.  A production camera-free request may then add back an
    approved primary ``cutModel`` record with the exact target audio.  The
    returned records are used only for authored boundaries and duration priors;
    they never enter prepared camera templates or planner fitting.
    """

    available_by_id = available_authored_records_by_id(records, entries)
    target_group = target_reference_evaluation_group(entries, target_record)
    selected: dict[str, train.SongRecord] = {}

    for song_id, record in available_by_id.items():
        entry = entries.get(song_id)
        if entry is None:
            raise ValueError(
                f"Available cut reference {song_id} is missing from the "
                "training index."
            )
        usage = entry.get("usage", {})
        if entry.get("role") != "primary" or usage.get("cutModel") is not True:
            continue
        if song_id == target_record.id:
            continue
        if (
            target_group is not None
            and str(entry["evaluationGroupId"]) == target_group
        ):
            continue
        if library_split == "train" and entry["recommendedSplit"] != "train":
            continue
        selected[song_id] = record

    if (
        allow_exact_audio_prior
        and library_split == "all"
        and target_record.is_generation_input
    ):
        target_audio_fingerprint = verified_exact_audio_fingerprint(
            target_record,
            None,
            fail_on_disagreement=True,
        )
        indexed_target_collision = entries.get(target_record.id)
        if indexed_target_collision is not None:
            target_audio_fingerprint = verified_exact_audio_fingerprint(
                target_record,
                indexed_target_collision,
            )
        if target_audio_fingerprint is not None:
            for song_id, record in available_by_id.items():
                entry = entries.get(song_id)
                if entry is None:
                    continue
                usage = entry.get("usage", {})
                indexed_audio_fingerprint = normalized_audio_sha256(
                    entry.get("audioFingerprint"),
                    f"Indexed audio fingerprint for {song_id}",
                )
                if (
                    entry.get("role") != "primary"
                    or usage.get("cutModel") is not True
                    or indexed_audio_fingerprint != target_audio_fingerprint
                ):
                    continue
                record_audio_fingerprint = verified_exact_audio_fingerprint(
                    record,
                    entry,
                )
                if record_audio_fingerprint == target_audio_fingerprint:
                    selected[song_id] = record
                else:
                    # A baseline generic record whose stale index happens to
                    # claim this audio must not re-enter as a same-audio pattern
                    # when the corpus is assembled from index metadata.
                    selected.pop(song_id, None)

    return sorted(selected.values(), key=lambda item: item.id)


def aspect_for_entry(
    entry: dict,
    override: float = 0.0,
) -> tuple[float, str]:
    """Resolve aspect ratio while making assumptions visible in metadata."""

    def validated(value: float, source: str) -> tuple[float, str]:
        ratio = float(value)
        if not math.isfinite(ratio) or not 0.25 <= ratio <= 4.0:
            raise ValueError(
                "Aspect ratio must be finite and between 0.25 and 4.0; "
                f"got {value!r} from {source}."
            )
        return ratio, source

    if override != 0.0:
        return validated(override, "command_line")
    value = entry.get("aspectRatio")
    if value is not None:
        return validated(
            value,
            str(entry.get("aspectSource") or "training_index"),
        )
    return 16.0 / 9.0, "assumed_16_9"


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def code_identifier(paths: list[Path]) -> str:
    frozen = cw_camera_runtime.frozen_code_identifier(paths)
    if frozen is not None:
        return frozen
    digest = hashlib.sha256()
    resolved = [
        cw_camera_runtime.source_snapshot_path(path).resolve()
        for path in paths
    ]
    for path in sorted(resolved):
        digest.update(path.name.encode("utf-8"))
        digest.update(path.read_bytes())
    return digest.hexdigest()


def library_identifier(
    records: list[train.SongRecord],
    index_entries: dict[str, dict],
) -> str:
    """Hash source identities, content fingerprints, and split policy."""

    material: list[dict[str, object]] = []
    for record in sorted(records, key=lambda item: item.id):
        entry = index_entries[record.id]
        item: dict[str, object] = {
            "songId": record.id,
            "contentFingerprint": entry.get("contentFingerprint"),
            "audioFingerprint": entry.get("audioFingerprint"),
            "evaluationGroupId": entry.get("evaluationGroupId"),
            "recommendedSplit": entry.get("recommendedSplit"),
            "role": entry.get("role"),
            "usage": entry.get("usage", {}),
            "aspectRatio": entry.get("aspectRatio"),
            "aspectSource": entry.get("aspectSource"),
        }
        expected_frame_count = None
        if "audioAlignedFrameMaskRanges" in entry:
            expected_frame_count = record.song.get("frameCount")
            if (
                isinstance(expected_frame_count, bool)
                or not isinstance(expected_frame_count, int)
                or expected_frame_count < 0
            ):
                raise ValueError(
                    f"Manifest for masked record {record.id} requires a "
                    "non-negative integer frameCount."
                )
        verified_mask = verified_audio_aligned_frame_mask_for_record(
            record,
            entry,
            expected_frame_count=expected_frame_count,
        )
        if verified_mask is not None:
            mask_ranges, verified_audio_fingerprint = verified_mask
            item["audioAlignedFrameMaskRanges"] = [
                list(frame_range) for frame_range in mask_ranges
            ]
            item["frameCount"] = int(entry["frameCount"])
            item["verifiedAudioFingerprint"] = verified_audio_fingerprint
        material.append(item)
    value = json.dumps(
        material,
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
    )
    return hashlib.sha256(value.encode("utf-8")).hexdigest()


def finite_or_none(value: float) -> float | None:
    return float(value) if math.isfinite(float(value)) else None


def portable_path(value: str | Path) -> str:
    path = Path(value).resolve()
    try:
        return path.relative_to(Path.cwd().resolve()).as_posix()
    except ValueError:
        return path.as_posix()


def current_target_cache_provenance(
    target_record: train.SongRecord,
) -> dict[str, str]:
    """Return request provenance, never provenance stored by a shared cache."""

    return {
        "targetSongId": str(target_record.id),
        "targetDatasetId": str(target_record.dataset_id),
        "targetSourceManifest": portable_path(target_record.manifest_path),
    }


def shot_template_identity(template: ShotTemplate) -> dict[str, object]:
    """Return the stable reference used inside candidate-cache metadata."""

    return {
        "sourceId": str(template.source_id),
        "shotIndex": int(template.shot_index),
    }


def candidate_sequence_continuation_value(result: dict) -> dict[str, object]:
    template = result["template"]
    return {
        "candidateRank": int(result["candidateRank"]),
        "templateIdentity": shot_template_identity(template),
        "realizedSideSign": float(result["realizedSideSign"]),
        "realizedShotType": str(result["realizedShotType"]),
        "realizedMotionType": str(result["realizedMotionType"]),
        "mirrored": bool(result.get("mirrored", False)),
        "safetyDistanceScale": float(result.get("safetyDistanceScale", 1.0)),
    }


def candidate_sequence_continuation_state(
    result: dict,
    candidate_results: list[dict],
    variation_pool: list[dict],
) -> dict[str, object]:
    result_indices = {id(candidate): index for index, candidate in enumerate(
        candidate_results
    )}
    try:
        pool_indices = [result_indices[id(candidate)] for candidate in variation_pool]
    except KeyError as exception:
        raise ValueError(
            "Every variation-pool candidate must belong to candidate_results."
        ) from exception
    canonical_ranked_templates: dict[int, dict[str, object]] = {}
    for candidate in candidate_results:
        try:
            candidate_rank = int(candidate["candidateRank"])
            template_identity = shot_template_identity(candidate["template"])
        except (KeyError, TypeError, ValueError) as exception:
            raise ValueError(
                "Every cached candidate needs a valid rank and template."
            ) from exception
        if candidate_rank < 0:
            raise ValueError("Candidate ranks must be non-negative.")
        previous_identity = canonical_ranked_templates.get(candidate_rank)
        if (
            previous_identity is not None
            and previous_identity != template_identity
        ):
            raise ValueError(
                "One candidate rank resolves to multiple source templates."
            )
        canonical_ranked_templates[candidate_rank] = template_identity
    return {
        "schemaVersion": "candidate-shot-state-v5",
        "continuation": candidate_sequence_continuation_value(result),
        "variationPoolCandidateIndices": pool_indices,
        "canonicalRankedTemplates": [
            {
                "candidateRank": candidate_rank,
                "templateIdentity": template_identity,
            }
            for candidate_rank, template_identity in sorted(
                canonical_ranked_templates.items()
            )
        ],
    }


def cached_canonical_ranked_templates(
    cached_state: object,
) -> dict[int, dict[str, object]]:
    """Validate and return the cache's own canonical rank provenance."""

    if (
        not isinstance(cached_state, dict)
        or cached_state.get("schemaVersion") != "candidate-shot-state-v5"
    ):
        raise candidate_cache.CandidateCacheIntegrityError(
            "Cached candidate shot state has an unsupported schema."
        )
    entries = cached_state.get("canonicalRankedTemplates")
    if not isinstance(entries, list) or not entries:
        raise candidate_cache.CandidateCacheIntegrityError(
            "Cached canonical candidate ranking is missing."
        )
    ranked: dict[int, dict[str, object]] = {}
    for entry in entries:
        if not isinstance(entry, dict):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached canonical candidate ranking is invalid."
            )
        identity = entry.get("templateIdentity")
        try:
            candidate_rank = int(entry["candidateRank"])
            normalized_identity = {
                "sourceId": str(identity["sourceId"]),
                "shotIndex": int(identity["shotIndex"]),
            }
        except (KeyError, TypeError, ValueError) as exception:
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached canonical candidate rank identity is invalid."
            ) from exception
        if (
            candidate_rank < 0
            or candidate_rank in ranked
            or identity != normalized_identity
        ):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached canonical candidate ranks are invalid."
            )
        ranked[candidate_rank] = normalized_identity
    return ranked


def encode_candidate_pool_shot(
    shot_index: int,
    start_frame: int,
    end_frame_exclusive: int,
    results: list[dict],
    continuation_result: dict,
    variation_pool: list[dict],
) -> candidate_cache.CandidatePoolShot:
    """Strip runtime template objects from one reusable candidate pool."""

    encoded: list[candidate_cache.CandidatePoolCandidate] = []
    for result in results:
        template = result.get("template")
        if template is None:
            raise ValueError("Candidate result is missing its source template.")
        missing_arrays = [
            name for name in CANDIDATE_CACHE_ARRAY_KEYS if name not in result
        ]
        if missing_arrays:
            raise ValueError(
                "Candidate result is missing arrays: "
                + ", ".join(missing_arrays)
            )
        metrics = {
            key: value
            for key, value in result.items()
            if key not in CANDIDATE_CACHE_ARRAY_KEYS and key != "template"
        }
        metrics["templateIdentity"] = shot_template_identity(template)
        encoded.append(
            candidate_cache.CandidatePoolCandidate(
                arrays={
                    name: np.asarray(result[name])
                    for name in CANDIDATE_CACHE_ARRAY_KEYS
                },
                metrics=metrics,
            )
        )
    return candidate_cache.CandidatePoolShot(
        shot_index=int(shot_index),
        start_frame=int(start_frame),
        end_frame_exclusive=int(end_frame_exclusive),
        candidates=tuple(encoded),
        sequence_continuation_state=(
            candidate_sequence_continuation_state(
                continuation_result,
                results,
                variation_pool,
            )
        ),
    )


def decode_candidate_pool_shot(
    cached_shot: candidate_cache.CandidatePoolShot,
    templates_by_identity: dict[tuple[str, int], ShotTemplate],
    ranked_templates: list[ShotTemplate] | None = None,
) -> list[dict]:
    """Restore local template references and verify cached ranking provenance."""

    canonical_ranks = cached_canonical_ranked_templates(
        cached_shot.sequence_continuation_state
    )
    observed_ranks: dict[int, dict[str, object]] = {}
    decoded: list[dict] = []
    for cached_candidate in cached_shot.candidates:
        if not isinstance(cached_candidate.metrics, dict):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Candidate metrics must be an object."
            )
        metrics = dict(cached_candidate.metrics)
        if type(metrics.get("finalPostClampKinematicPassed")) is not bool:
            raise candidate_cache.CandidateCacheIntegrityError(
                "Candidate final post-clamp kinematic audit is missing or invalid."
            )
        identity = metrics.pop("templateIdentity", None)
        if not isinstance(identity, dict):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Candidate template identity is missing."
            )
        try:
            key = (str(identity["sourceId"]), int(identity["shotIndex"]))
            candidate_rank = int(metrics["candidateRank"])
        except (KeyError, TypeError, ValueError) as exception:
            raise candidate_cache.CandidateCacheIntegrityError(
                "Candidate template identity or rank is invalid."
            ) from exception
        template = templates_by_identity.get(key)
        if template is None:
            raise candidate_cache.CandidateCacheIntegrityError(
                "Candidate source template is not present in preparation."
            )
        if candidate_rank < 0:
            raise candidate_cache.CandidateCacheIntegrityError(
                "Candidate rank must be non-negative."
            )
        normalized_identity = {
            "sourceId": key[0],
            "shotIndex": key[1],
        }
        if canonical_ranks.get(candidate_rank) != normalized_identity:
            raise candidate_cache.CandidateCacheIntegrityError(
                "Candidate rank does not match canonical cache provenance."
            )
        previous_identity = observed_ranks.get(candidate_rank)
        if (
            previous_identity is not None
            and previous_identity != normalized_identity
        ):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Candidate rank resolves to multiple cached templates."
            )
        observed_ranks[candidate_rank] = normalized_identity
        if ranked_templates is not None and (
            candidate_rank >= len(ranked_templates)
            or ranked_templates[candidate_rank] is not template
        ):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Candidate rank no longer resolves to its source template."
            )
        result = metrics
        result["template"] = template
        for name in CANDIDATE_CACHE_ARRAY_KEYS:
            if name not in cached_candidate.arrays:
                raise candidate_cache.CandidateCacheIntegrityError(
                    f"Candidate cache array is missing: {name}"
                )
            result[name] = cached_candidate.arrays[name]
        decoded.append(result)
    if observed_ranks != canonical_ranks:
        raise candidate_cache.CandidateCacheIntegrityError(
            "Cached candidates do not cover their canonical ranking provenance."
        )
    return decoded


def validate_cached_continuation_state(
    cached_state: object,
    continuation_result: dict,
) -> None:
    if (
        not isinstance(cached_state, dict)
        or cached_state.get("schemaVersion") != "candidate-shot-state-v5"
        or cached_state.get("continuation")
        != candidate_sequence_continuation_value(continuation_result)
    ):
        raise candidate_cache.CandidateCacheIntegrityError(
            "Cached sequence-continuation state does not match the safe pool."
        )


def cached_variation_pool(
    cached_state: object,
    candidate_results: list[dict],
    safe_results: list[dict],
) -> list[dict]:
    """Restore the expensive pairwise-distinct pool without recomputing it."""

    if not isinstance(cached_state, dict):
        raise candidate_cache.CandidateCacheIntegrityError(
            "Cached candidate shot state must be an object."
        )
    raw_indices = cached_state.get("variationPoolCandidateIndices")
    if (
        not isinstance(raw_indices, list)
        or not raw_indices
        or len(raw_indices) > SEED_VARIATION_MAX_POOL_SIZE
        or any(type(index) is not int for index in raw_indices)
        or len(set(raw_indices)) != len(raw_indices)
    ):
        raise candidate_cache.CandidateCacheIntegrityError(
            "Cached variation-pool indices are invalid."
        )
    safe_identity = {id(candidate) for candidate in safe_results}
    pool: list[dict] = []
    for index in raw_indices:
        if index < 0 or index >= len(candidate_results):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached variation-pool index is outside the candidate list."
            )
        candidate = candidate_results[index]
        if id(candidate) not in safe_identity:
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached variation pool contains a policy-ineligible candidate."
            )
        pool.append(candidate)
    return pool


def planner_directive_from_cache_value(
    value: object,
) -> planner.ShotDirective | None:
    if value is None:
        return None
    if not isinstance(value, dict):
        raise candidate_cache.CandidateCacheIntegrityError(
            "Cached planner directive must be an object or null."
        )
    try:
        directive = planner.ShotDirective(
            shot_type=str(value["shotType"]),
            motion_family=str(value["motionFamily"]),
            shot_probability=float(value["shotProbability"]),
            motion_probability=float(value["motionProbability"]),
            score=float(value["plannerScore"]),
            shot_probabilities={
                str(key): float(probability)
                for key, probability in value["shotProbabilities"].items()
            },
            motion_probabilities={
                str(key): float(probability)
                for key, probability in value["motionProbabilities"].items()
            },
        )
    except (KeyError, TypeError, ValueError, AttributeError) as exception:
        raise candidate_cache.CandidateCacheIntegrityError(
            "Cached planner directive is invalid."
        ) from exception
    if not all(
        math.isfinite(number)
        for number in (
            directive.shot_probability,
            directive.motion_probability,
            directive.score,
            *directive.shot_probabilities.values(),
            *directive.motion_probabilities.values(),
        )
    ):
        raise candidate_cache.CandidateCacheIntegrityError(
            "Cached planner directive contains a non-finite value."
        )
    return directive


def validate_cached_planning_replay(
    replay: object,
    directive: planner.ShotDirective | None,
    reconciliation: PlannerDirectiveReconciliation | None,
) -> bool:
    if not isinstance(replay, dict):
        raise candidate_cache.CandidateCacheIntegrityError(
            "Cached planning replay entry must be an object."
        )
    expected_beam = directive.as_dict() if directive is not None else None
    expected_realized = (
        reconciliation.realized_directive.as_dict()
        if reconciliation is not None
        else None
    )
    expected_values = {
        "beamDirective": expected_beam,
        "realizedDirective": expected_realized,
        "userOverrideChangedPlan": (
            reconciliation.user_override_changed_plan
            if reconciliation is not None
            else False
        ),
        "realizationChangedPlan": (
            reconciliation.realization_changed_plan
            if reconciliation is not None
            else False
        ),
        "replanReason": (
            reconciliation.replan_reason
            if reconciliation is not None
            else None
        ),
    }
    for key, expected in expected_values.items():
        if replay.get(key) != expected:
            raise candidate_cache.CandidateCacheIntegrityError(
                f"Cached planning replay does not match {key}."
            )
    mismatch_triggered = replay.get("mismatchTriggeredReplan")
    if type(mismatch_triggered) is not bool:
        raise candidate_cache.CandidateCacheIntegrityError(
            "Cached planning replay replan flag must be boolean."
        )
    return mismatch_triggered


def shot_control_cache_value(control: ShotControl) -> dict[str, object]:
    return {
        "shotSize": control.shot_size,
        "motion": control.motion,
        "composition": control.composition,
        "distanceMeters": float(control.distance_meters),
        "motionIntensity": float(control.motion_intensity),
        "bodyFollowStrength": float(control.body_follow_strength),
    }


def target_input_cache_fingerprint(
    target_record: train.SongRecord,
) -> dict[str, object] | dict[str, str]:
    """Fingerprint target bytes without tying GenerationInput to an export."""

    if bool(getattr(target_record, "is_generation_input", False)):
        return train.generation_input_content_identity(target_record)
    return candidate_cache.fingerprint_files(
        {
            "manifest": target_record.manifest_path,
            "audio": target_record.audio_path,
            "joints": target_record.song_dir / "joints_world.f32",
            "root": target_record.song_dir / "root.f32",
            "time": target_record.song_dir / "time.f64",
        }
    )


def candidate_cache_identity_for_generation(
    args: argparse.Namespace,
    target_record: train.SongRecord,
    training_records: list[train.SongRecord],
    index_entries: dict[str, dict],
    preparation_cache_key: str | None,
    directives: list[planner.ShotDirective | None],
    shot_controls: list[ShotControl],
    boundaries: list[int],
    target_aspect_ratio: float,
) -> dict[str, object]:
    """Build a Seed-free identity for all expensive candidate computations."""

    if (
        not isinstance(preparation_cache_key, str)
        or len(preparation_cache_key) != 64
        or any(character not in "0123456789abcdef" for character in preparation_cache_key)
    ):
        raise ValueError(
            "Candidate caching requires an exact content-addressed "
            "preparation cache key."
        )

    input_fingerprint = target_input_cache_fingerprint(target_record)
    preparation_fingerprint = {
        "contentAddressedPreparationKey": preparation_cache_key,
        "libraryId": library_identifier(training_records, index_entries),
        "preparationModelSeed": int(args.preparation_model_seed),
        "preparationLogic": preparation_logic_identifier(),
        "candidateLogic": candidate_logic_identifier(),
        "plannerMode": args.planner,
        "plannerVersion": (
            planner.PLANNER_VERSION
            if args.planner == "hierarchical"
            else "legacy-local-rf-v4"
        ),
        "shotLabelVersion": (
            shot_features.SHOT_LABEL_VERSION
            if args.planner == "hierarchical"
            else "legacy-quantile-v4"
        ),
    }
    directive_values = [
        directive.as_dict() if directive is not None else None
        for directive in directives
    ]
    controls = {
        "seed": int(args.seed),
        "cutBoundaries": [int(value) for value in boundaries],
        "cutPlanner": getattr(args, "cut_planner", "legacy"),
        "cutDensity": getattr(args, "cut_density", "auto"),
        "sameAudioPrior": getattr(args, "same_audio_prior", "off"),
        "cutReferenceSelectionPolicyVersion": (
            CUT_REFERENCE_SELECTION_POLICY_VERSION
            if getattr(args, "cut_planner", "legacy") == "data_driven"
            else None
        ),
        "cutRankerModelSha256": (
            sha256_file(Path(args.cut_ranker_model).resolve())
            if getattr(args, "cut_ranker_model", None) is not None
            and Path(args.cut_ranker_model).resolve().is_file()
            else None
        ),
        "cutDirectivesJsonSha256": (
            sha256_file(Path(args.cut_directives_json).resolve())
            if getattr(args, "cut_directives_json", None) is not None
            else None
        ),
        "minimumShotSeconds": (
            float(args.min_shot_seconds)
            if getattr(args, "cut_planner", "legacy") == "legacy"
            else None
        ),
        "maximumShotSeconds": (
            float(args.max_shot_seconds)
            if getattr(args, "cut_planner", "legacy") == "legacy"
            else None
        ),
        "targetAspectRatio": float(target_aspect_ratio),
        "horizontalFraming": args.horizontal_framing,
        "bodyFollowSmoothingSeconds": float(
            args.body_follow_smoothing_seconds
        ),
        "bodyFollowDeadZoneMeters": float(
            args.body_follow_dead_zone_meters
        ),
        "beamWidth": int(args.beam_width),
        "shotControls": [
            shot_control_cache_value(control) for control in shot_controls
        ],
    }
    research_profile = normalized_research_ablation_profile(args)
    if research_profile != "none":
        controls["researchAblationProfile"] = research_profile
    return candidate_cache.build_candidate_cache_identity(
        input_fingerprint=input_fingerprint,
        preparation_fingerprint=preparation_fingerprint,
        directives=directive_values,
        controls=controls,
        stage_versions=CANDIDATE_CACHE_STAGE_VERSIONS,
    )


def validate_single_shot_request(args: argparse.Namespace) -> bool:
    """Validate the paired one-shot CLI contract and return whether it is active."""

    has_index = args.only_shot_index is not None
    has_base = args.base_generation is not None
    if has_index != has_base:
        raise ValueError(
            "--only-shot-index and --base-generation must be provided together."
        )
    if not has_index:
        return False
    if int(args.only_shot_index) < 0:
        raise ValueError("--only-shot-index must be non-negative.")
    if Path(args.base_generation).resolve() == Path(args.output).resolve():
        raise ValueError(
            "--base-generation and --output must be different folders."
        )
    return True


def _base_generation_member(
    folder: Path,
    relative_name: object,
    label: str,
) -> Path:
    if not isinstance(relative_name, str) or not relative_name.strip():
        raise ValueError(f"Base generation {label} filename is missing.")
    relative = Path(relative_name)
    if (
        relative.is_absolute()
        or len(relative.parts) != 1
        or relative.name in {".", ".."}
        or "/" in relative_name
        or "\\" in relative_name
        or ":" in relative_name
    ):
        raise ValueError(
            f"Base generation {label} must be a direct folder member."
        )
    path = folder / relative
    if _path_is_reparse_point(path):
        raise ValueError(
            f"Base generation {label} must not be a reparse point."
        )
    if not path.is_file():
        raise FileNotFoundError(f"Base generation {label} is missing: {path}")
    resolved = path.resolve(strict=True)
    if resolved.parent != folder:
        raise ValueError(
            f"Base generation {label} resolves outside its folder."
        )
    return resolved


def load_base_generation_composite(
    folder: Path,
    *,
    expected_song_id: str,
    expected_dataset_id: str,
    expected_frame_count: int,
    expected_aspect_ratio: float,
    expected_planner_mode: str,
) -> BaseGenerationComposite:
    """Load and fail-closed validate a full output used for one-shot patching."""

    declared_folder = Path(folder)
    if _path_is_reparse_point(declared_folder):
        raise ValueError("Base generation folder must not be a reparse point.")
    folder = declared_folder.resolve()
    if not folder.is_dir():
        raise FileNotFoundError("Base generation folder is missing: " + str(folder))
    metadata_path = _base_generation_member(
        folder,
        "metadata.json",
        "metadata",
    )
    metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
    if not isinstance(metadata, dict):
        raise ValueError("Base generation metadata must be an object.")
    if metadata.get("schemaVersion") != HYBRID_METADATA_SCHEMA_VERSION:
        raise ValueError(
            "Base generation metadata schema "
            f"{HYBRID_METADATA_SCHEMA_VERSION} is required."
        )
    metadata_safety_contract = metadata.get(
        "selectionSafetyContractVersion"
    )
    if metadata_safety_contract != SELECTION_SAFETY_CONTRACT_VERSION:
        raise ValueError(
            "Base generation uses an incompatible or legacy selection-safety "
            "contract. Run full camera generation once before regenerating "
            "an individual shot. Required contract: "
            + SELECTION_SAFETY_CONTRACT_VERSION
        )
    supported_modes = HYBRID_GENERATION_MODES_BY_PLANNER.get(
        expected_planner_mode
    )
    if (
        supported_modes is None
        or metadata.get("generationMode") not in supported_modes
    ):
        raise ValueError(
            "Base generation mode is not a supported Hybrid output for "
            f"planner {expected_planner_mode!r}."
        )
    sample_rate = metadata.get("sampleRate")
    if (
        isinstance(sample_rate, bool)
        or not isinstance(sample_rate, (int, float))
        or not math.isfinite(sample_rate)
        or sample_rate != float(HYBRID_SAMPLE_RATE)
    ):
        raise ValueError(f"Base generation sampleRate must be {HYBRID_SAMPLE_RATE}.")

    camera_path = _base_generation_member(
        folder,
        metadata.get("worldCameraFile"),
        "world camera",
    )
    time_path = _base_generation_member(
        folder,
        metadata.get("timeFile"),
        "time",
    )
    shots_path = _base_generation_member(
        folder,
        metadata.get("shotsFile"),
        "shots",
    )
    shots_payload = json.loads(shots_path.read_text(encoding="utf-8"))
    if (
        not isinstance(shots_payload, dict)
        or shots_payload.get("schemaVersion") != HYBRID_SHOTS_SCHEMA_VERSION
        or not isinstance(shots_payload.get("shots"), list)
    ):
        raise ValueError(
            "Base generation shots schema "
            f"{HYBRID_SHOTS_SCHEMA_VERSION} is required."
        )
    if shots_payload.get(
        "selectionSafetyContractVersion"
    ) != SELECTION_SAFETY_CONTRACT_VERSION:
        raise ValueError(
            "Base generation shot trace uses an incompatible or legacy "
            "selection-safety contract. Run full camera generation once "
            "before regenerating an individual shot."
        )
    if metadata.get("songId") != expected_song_id:
        raise ValueError("Base generation songId does not match the target.")
    if metadata.get("datasetId") != expected_dataset_id:
        raise ValueError("Base generation datasetId does not match the target.")
    metadata_frame_count = metadata.get("frameCount")
    if (
        type(metadata_frame_count) is not int
        or metadata_frame_count != int(expected_frame_count)
    ):
        raise ValueError("Base generation frameCount does not match the target.")
    if metadata.get("plannerMode") != expected_planner_mode:
        raise ValueError("Base generation planner mode does not match the request.")
    base_aspect_ratio = metadata.get("targetAspectRatio")
    if (
        isinstance(base_aspect_ratio, bool)
        or not isinstance(base_aspect_ratio, (int, float))
        or not math.isfinite(base_aspect_ratio)
    ):
        raise ValueError("Base generation targetAspectRatio is invalid.")
    if not math.isclose(
        base_aspect_ratio,
        float(expected_aspect_ratio),
        rel_tol=0.0,
        abs_tol=1e-9,
    ):
        raise ValueError("Base generation aspect ratio does not match the request.")

    shots = shots_payload["shots"]
    metadata_shot_count = metadata.get("shotCount")
    if (
        not shots
        or type(metadata_shot_count) is not int
        or metadata_shot_count != len(shots)
    ):
        raise ValueError("Base generation shot count is missing or stale.")
    previous_end = 0
    boundaries = [0]
    for expected_index, shot in enumerate(shots):
        if not isinstance(shot, dict):
            raise ValueError("Every base generation shot must be an object.")
        try:
            index = shot["index"]
            start = shot["startFrame"]
            end = shot["endFrameExclusive"]
        except KeyError as error:
            raise ValueError("Base generation shot trace is incomplete.") from error
        if any(type(value) is not int for value in (index, start, end)):
            raise ValueError(
                "Base generation shot indices and boundaries must be integers."
            )
        if (
            index != expected_index
            or start != previous_end
            or not start < end <= expected_frame_count
        ):
            raise ValueError(
                "Base generation shot indices or cut boundaries are invalid."
            )
        previous_end = end
        boundaries.append(end)
    if previous_end != expected_frame_count:
        raise ValueError("Base generation shots do not cover every target frame.")

    expected_camera_bytes = expected_frame_count * 9 * np.dtype("<f4").itemsize
    expected_time_bytes = expected_frame_count * np.dtype("<f8").itemsize
    if camera_path.stat().st_size != expected_camera_bytes:
        raise ValueError("Base generation world camera byte size is invalid.")
    if time_path.stat().st_size != expected_time_bytes:
        raise ValueError("Base generation time byte size is invalid.")
    world_camera = np.fromfile(camera_path, dtype="<f4")
    times = np.fromfile(time_path, dtype="<f8")
    if world_camera.size != expected_frame_count * 9:
        raise ValueError("Base generation world camera shape is invalid.")
    world_camera = world_camera.reshape(expected_frame_count, 9)
    if times.shape != (expected_frame_count,):
        raise ValueError("Base generation time shape is invalid.")
    if not np.isfinite(world_camera).all() or not np.isfinite(times).all():
        raise ValueError("Base generation contains NaN or Inf.")

    hashes = {
        "worldCamera": sha256_file(camera_path),
        "time": sha256_file(time_path),
        "shots": sha256_file(shots_path),
    }
    expected_hashes = metadata.get("outputSha256")
    if not isinstance(expected_hashes, dict) or any(
        expected_hashes.get(name) != value for name, value in hashes.items()
    ):
        raise ValueError("Base generation output SHA-256 metadata is stale.")
    return BaseGenerationComposite(
        folder=folder,
        metadata=copy.deepcopy(metadata),
        metadata_sha256=sha256_file(metadata_path),
        shots=tuple(copy.deepcopy(shots)),
        shots_sha256=hashes["shots"],
        world_camera=world_camera.copy(),
        world_camera_sha256=hashes["worldCamera"],
        times=times.copy(),
        time_sha256=hashes["time"],
        boundaries=tuple(boundaries),
    )


def validate_base_generation_times(
    base: BaseGenerationComposite,
    target_times: np.ndarray,
) -> None:
    target_times = np.asarray(target_times, dtype=np.float64)
    if base.times.shape != target_times.shape or not np.array_equal(
        base.times,
        target_times,
    ):
        raise ValueError("Base generation time samples do not match the target.")


def base_planner_directives(
    base: BaseGenerationComposite,
) -> list[planner.ShotDirective | None]:
    """Recover the pre-motion-guard beam without running the full planner."""

    directives: list[planner.ShotDirective | None] = []
    for index, shot in enumerate(base.shots):
        value = shot.get("plannerBeamDirectiveBeforeMotionGuard")
        if value is None and base.metadata.get("plannerMode") == "hierarchical":
            value = shot.get("plannerBeamDirectiveBeforeRealization")
        try:
            directives.append(planner_directive_from_cache_value(value))
        except candidate_cache.CandidateCacheError as error:
            raise ValueError(
                f"Base generation planner trace is invalid for shot {index}."
            ) from error
    return directives


def _base_continuation_identity(shot: dict) -> tuple[str, int]:
    try:
        return (
            str(shot["sequenceContinuationSourceSongId"]),
            int(shot["sequenceContinuationSourceShotIndex"]),
        )
    except (KeyError, TypeError, ValueError) as error:
        raise ValueError(
            "Base generation is missing sequence-continuation provenance."
        ) from error


def reconstruct_base_single_shot_context(
    base: BaseGenerationComposite,
    shot_index: int,
    templates_by_identity: dict[tuple[str, int], ShotTemplate],
) -> BaseSingleShotContext:
    """Recover the exact seed-independent history needed by one shot."""

    if not 0 <= int(shot_index) < len(base.shots):
        raise ValueError("Selected shot index is outside the base generation.")
    prior_shots = base.shots[: int(shot_index)]
    recent = tuple(
        _base_continuation_identity(shot)
        for shot in prior_shots[-8:]
    )
    static_history = tuple(
        str(
            shot.get(
                "rollingStaticBudgetHistoryFamily",
                shot.get("motionFamily", "static"),
            )
        )
        for shot in prior_shots
    )
    previous: RealizedShotState | None = None
    previous_value: dict[str, object] | None = None
    if prior_shots:
        previous_shot = prior_shots[-1]
        identity = _base_continuation_identity(previous_shot)
        template = templates_by_identity.get(identity)
        if template is None:
            raise ValueError(
                "Base sequence-continuation template is absent from preparation: "
                f"{identity!r}."
            )
        try:
            side_sign = float(
                previous_shot.get(
                    "sequenceContinuationRealizedSideSign",
                    previous_shot.get("realizedSideSign"),
                )
            )
            motion_type = str(
                previous_shot["sequenceContinuationMotionType"]
            )
        except (KeyError, TypeError, ValueError) as error:
            raise ValueError(
                "Base sequence-continuation state is incomplete."
            ) from error
        if not math.isfinite(side_sign):
            raise ValueError("Base sequence-continuation side is invalid.")
        previous = RealizedShotState(
            template=template,
            side_sign=(
                1.0 if side_sign > 0.0 else -1.0 if side_sign < 0.0 else 0.0
            ),
            motion_type=motion_type,
        )
        previous_value = {
            "sourceId": identity[0],
            "shotIndex": identity[1],
            "sideSign": previous.side_sign,
            "motionType": motion_type,
        }
    return BaseSingleShotContext(
        previous=previous,
        recent=recent,
        static_budget_motion_history=static_history,
        cache_value={
            "contractVersion": "base-shot-sequence-context-v1",
            "shotIndex": int(shot_index),
            "startFrame": int(base.shots[shot_index]["startFrame"]),
            "endFrameExclusive": int(
                base.shots[shot_index]["endFrameExclusive"]
            ),
            "previous": previous_value,
            "recent": [
                {"sourceId": source_id, "shotIndex": source_shot_index}
                for source_id, source_shot_index in recent
            ],
            "staticBudgetMotionHistory": list(static_history),
        },
    )


def world_camera_shot_transition_state(
    world_camera: np.ndarray,
    shot: dict,
    root: np.ndarray,
    joints: np.ndarray,
    body_scale: float,
    target_aspect_ratio: float,
) -> dict[str, object]:
    """Rebuild one rendered shot boundary state from final world-camera rows."""

    start = int(shot["startFrame"])
    end = int(shot["endFrameExclusive"])
    if not 0 <= start < end <= len(world_camera):
        raise ValueError("Shot transition span is outside the world camera.")
    shot_type = planner.normalize_shot_type(str(shot["shotType"]))
    local_joints = np.asarray(joints[start:end], dtype=np.float32)
    root_position = np.asarray(root[start:end, :3], dtype=np.float32)
    root_rotation = np.asarray(root[start:end, 3:7], dtype=np.float32)
    target_local = smooth_segment(shot_focus_local(local_joints, shot_type))
    target_world = root_position + train.quat_rotate(
        root_rotation,
        target_local * float(body_scale),
    )
    joint_world = root_position[:, None, :] + train.quat_rotate(
        root_rotation[:, None, :],
        local_joints * float(body_scale),
    )
    camera = np.asarray(world_camera[start:end], dtype=np.float32)
    composition = build_source_composition_path(
        camera[:, :3],
        camera[:, 3:7],
        camera[:, 7],
        camera[:, 8],
        joint_world,
        shot_type,
        target_aspect_ratio,
    )
    return adjacent_transition.build_transition_state(
        camera[:, :3],
        camera[:, 3:7],
        camera[:, 7],
        target_world,
        composition,
        shot_type,
        str(shot.get("motionType", "static")),
        sample_rate=HYBRID_SAMPLE_RATE,
    )


def base_shot_transition_state(
    base: BaseGenerationComposite,
    shot_index: int,
    root: np.ndarray,
    joints: np.ndarray,
    body_scale: float,
    target_aspect_ratio: float,
) -> dict[str, object]:
    """Rebuild rendered boundary state for an immutable base-composite shot."""

    if not 0 <= int(shot_index) < len(base.shots):
        raise ValueError("Base transition shot index is outside the composite.")
    return world_camera_shot_transition_state(
        base.world_camera,
        base.shots[int(shot_index)],
        root,
        joints,
        body_scale,
        target_aspect_ratio,
    )


def build_authoritative_adjacent_transition_edges(
    shots: list[dict],
    world_camera: np.ndarray,
    root: np.ndarray,
    joints: np.ndarray,
    body_scale: float,
    target_aspect_ratio: float,
) -> list[dict[str, object]]:
    """Recompute every final cut edge after full or single-shot materialization."""

    states = [
        world_camera_shot_transition_state(
            world_camera,
            shot,
            root,
            joints,
            body_scale,
            target_aspect_ratio,
        )
        for shot in shots
    ]
    edges: list[dict[str, object]] = []
    for next_index in range(1, len(shots)):
        previous_index = next_index - 1
        edges.append(
            {
                "edgeIndex": previous_index,
                "previousShotIndex": previous_index,
                "nextShotIndex": next_index,
                "cutFrame": int(shots[next_index]["startFrame"]),
                "previousCameraName": str(
                    shots[previous_index].get("cameraName", "")
                ),
                "nextCameraName": str(shots[next_index].get("cameraName", "")),
                "transition": adjacent_transition.score_pairwise_transition(
                    states[previous_index],
                    states[next_index],
                ),
            }
        )
    return edges


def single_shot_cache_identity_for_generation(
    args: argparse.Namespace,
    target_record: train.SongRecord,
    training_records: list[train.SongRecord],
    index_entries: dict[str, dict],
    preparation_cache_key: str,
    directive: planner.ShotDirective | None,
    control: ShotControl,
    context: BaseSingleShotContext,
    start_frame: int,
    end_frame_exclusive: int,
    target_aspect_ratio: float,
) -> dict[str, object]:
    preparation_fingerprint = {
        "contentAddressedPreparationKey": preparation_cache_key,
        "libraryId": library_identifier(training_records, index_entries),
        "preparationModelSeed": int(args.preparation_model_seed),
        "preparationLogic": preparation_logic_identifier(),
        "candidateLogic": candidate_logic_identifier(),
        "plannerMode": args.planner,
    }
    controls = {
        "seed": int(args.seed),
        "shotIndex": int(args.only_shot_index),
        "startFrame": int(start_frame),
        "endFrameExclusive": int(end_frame_exclusive),
        "targetAspectRatio": float(target_aspect_ratio),
        "horizontalFraming": args.horizontal_framing,
        "bodyFollowSmoothingSeconds": float(
            args.body_follow_smoothing_seconds
        ),
        "bodyFollowDeadZoneMeters": float(
            args.body_follow_dead_zone_meters
        ),
        "shotControl": shot_control_cache_value(control),
    }
    research_profile = normalized_research_ablation_profile(args)
    if research_profile != "none":
        controls["researchAblationProfile"] = research_profile
    return single_shot_cache.build_single_shot_cache_identity(
        input_fingerprint=target_input_cache_fingerprint(target_record),
        preparation_fingerprint=preparation_fingerprint,
        base_context=context.cache_value,
        planner_directive=(
            directive.as_dict() if directive is not None else None
        ),
        controls=controls,
        stage_versions=CANDIDATE_CACHE_STAGE_VERSIONS,
    )


def decode_single_shot_cached_runtime(
    cached_shot: candidate_cache.CandidatePoolShot,
    templates_by_identity: dict[tuple[str, int], ShotTemplate],
    *,
    moving_opening_required: bool,
    desired_motion_type: str | None,
    rolling_static_budget_required: bool,
    planned_non_static_required: bool,
) -> CachedCandidateRuntimeShot:
    candidate_results = decode_candidate_pool_shot(
        cached_shot,
        templates_by_identity,
    )
    safe_results = selectable_safe_candidate_results(
        candidate_results,
        moving_opening_required,
        desired_motion_type,
        rolling_static_budget_required,
        planned_non_static_required,
    )
    if not safe_results:
        raise candidate_cache.CandidateCacheIntegrityError(
            "Single-shot cache has no policy-eligible safe candidate."
        )
    variation_pool = cached_variation_pool(
        cached_shot.sequence_continuation_state,
        candidate_results,
        safe_results,
    )
    continuation_result = select_seed_independent_sequence_continuation(
        safe_results,
        variation_pool,
    )
    validate_cached_continuation_state(
        cached_shot.sequence_continuation_state,
        continuation_result,
    )
    return CachedCandidateRuntimeShot(
        candidate_results=candidate_results,
        safe_results=safe_results,
        variation_pool=variation_pool,
    )


def materialize_single_shot_patch(
    world_camera: np.ndarray,
    shots: list[dict],
    shot_index: int,
    replacement_camera: np.ndarray,
    replacement_shot: dict,
) -> None:
    """Patch one span in place while preserving every non-selected byte/row."""

    if not 0 <= int(shot_index) < len(shots):
        raise ValueError("Selected shot index is outside the composite.")
    original = shots[int(shot_index)]
    start = int(original["startFrame"])
    end = int(original["endFrameExclusive"])
    replacement_camera = np.asarray(replacement_camera, dtype=np.float32)
    if replacement_camera.shape != (end - start, 9):
        raise ValueError("Selected shot replacement camera shape is invalid.")
    if (
        int(replacement_shot.get("index", -1)) != int(shot_index)
        or int(replacement_shot.get("startFrame", -1)) != start
        or int(replacement_shot.get("endFrameExclusive", -1)) != end
    ):
        raise ValueError("Selected shot replacement metadata span is invalid.")
    if not np.isfinite(replacement_camera).all():
        raise ValueError("Selected shot replacement camera contains NaN or Inf.")
    world_camera[start:end] = replacement_camera
    shots[int(shot_index)] = copy.deepcopy(replacement_shot)


def build_materialized_seed_lineage(
    shots: list[dict],
    operation_seed: int,
    *,
    single_shot_mode: bool,
    selected_shot_index: int | None,
) -> dict[str, object]:
    """Describe the actual per-shot selection seeds in a materialized edit.

    ``generationSeed`` predates selected-shot composites and remains in metadata
    for existing consumers.  In a composite it is the current operation seed,
    while preserved rows retain their own historical ``variationSeed``.  This
    lineage is the authoritative seed-provenance contract for every shot.
    """

    if not shots:
        raise ValueError("Materialized seed lineage requires at least one shot.")
    if single_shot_mode and (
        selected_shot_index is None
        or not 0 <= int(selected_shot_index) < len(shots)
    ):
        raise ValueError("Materialized seed lineage selected index is invalid.")
    if not single_shot_mode and selected_shot_index is not None:
        raise ValueError("Full generation must not declare a selected shot seed.")

    entries: list[dict[str, int]] = []
    for expected_index, shot in enumerate(shots):
        if not isinstance(shot, dict) or int(shot.get("index", -1)) != expected_index:
            raise ValueError("Materialized shot indices are invalid for seed lineage.")
        raw_seed = shot.get("variationSeed")
        if isinstance(raw_seed, bool) or not isinstance(raw_seed, int):
            raise ValueError(
                f"Materialized shot {expected_index} variationSeed is invalid."
            )
        entries.append(
            {
                "shotIndex": expected_index,
                "variationSeed": int(raw_seed),
            }
        )

    operation_seed = int(operation_seed)
    selected_seed = (
        entries[int(selected_shot_index)]["variationSeed"]
        if single_shot_mode
        else None
    )
    if single_shot_mode and selected_seed != operation_seed:
        raise ValueError(
            "Selected shot variationSeed does not match the operation seed."
        )
    if not single_shot_mode and any(
        entry["variationSeed"] != operation_seed for entry in entries
    ):
        raise ValueError(
            "Full generation contains a shot selected with another seed."
        )
    distinct_seeds = sorted({entry["variationSeed"] for entry in entries})
    return {
        "contractVersion": MATERIALIZED_SEED_LINEAGE_VERSION,
        "operationScope": (
            "selected_shot" if single_shot_mode else "full_sequence"
        ),
        "operationSeed": operation_seed,
        "selectedShotIndex": (
            int(selected_shot_index) if single_shot_mode else None
        ),
        "selectedShotSeed": selected_seed,
        "allShotsUseOperationSeed": all(
            entry["variationSeed"] == operation_seed for entry in entries
        ),
        "distinctSeeds": distinct_seeds,
        "shots": entries,
    }


def validate_loaded_candidate_pool(
    loaded: candidate_cache.LoadedCandidatePoolCache,
    boundaries: list[int],
) -> tuple[
    dict[int, candidate_cache.CandidatePoolShot],
    list[dict[str, object]],
]:
    expected_spans = list(zip(boundaries[:-1], boundaries[1:]))
    if len(loaded.shots) != len(expected_spans):
        raise candidate_cache.CandidateCacheIntegrityError(
            "Candidate cache shot count does not match cut boundaries."
        )
    by_index: dict[int, candidate_cache.CandidatePoolShot] = {}
    for expected_index, (cached_shot, span) in enumerate(
        zip(loaded.shots, expected_spans)
    ):
        if (
            cached_shot.shot_index != expected_index
            or (cached_shot.start_frame, cached_shot.end_frame_exclusive)
            != span
        ):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Candidate cache shot boundaries do not match generation."
            )
        by_index[expected_index] = cached_shot
    metadata = loaded.bundle_metadata
    if (
        not isinstance(metadata, dict)
        or metadata.get("contractVersion") != "hybrid-candidate-runtime-v10"
        or metadata.get("cutBoundaries") != boundaries
    ):
        raise candidate_cache.CandidateCacheIntegrityError(
            "Candidate cache runtime contract metadata is invalid."
        )
    planning_replay = metadata.get("planningReplay")
    if (
        not isinstance(planning_replay, list)
        or len(planning_replay) != len(expected_spans)
        or any(not isinstance(entry, dict) for entry in planning_replay)
    ):
        raise candidate_cache.CandidateCacheIntegrityError(
            "Candidate cache planning replay is invalid."
        )
    return by_index, planning_replay


def preflight_candidate_cache_runtime(
    cached_shots: dict[int, candidate_cache.CandidatePoolShot],
    planning_replay: list[dict[str, object]],
    templates_by_identity: dict[tuple[str, int], ShotTemplate],
    directives: list[planner.ShotDirective | None],
    shot_controls: list[ShotControl],
    hierarchical_planner: planner.HierarchicalShotPlanner | None,
) -> dict[int, CachedCandidateRuntimeShot]:
    """Validate the complete cached planning replay before emitting frames.

    The initial/non-replanned beam is checked against the fresh plan.  Replanned
    tails are structurally checked against their realized candidate state and
    the source-closure/preparation fingerprints in the cache identity, avoiding
    another expensive planner pass. Candidate arrays are decoded once here and
    reused by generation, so no ranking or retargeting work is repeated.
    """

    if (
        len(cached_shots) != len(directives)
        or len(planning_replay) != len(directives)
        or len(shot_controls) != len(directives)
    ):
        raise candidate_cache.CandidateCacheIntegrityError(
            "Candidate cache runtime sequence lengths do not match."
        )
    decoded: dict[int, CachedCandidateRuntimeShot] = {}
    replanned_tail_active = False
    static_budget_motion_history: list[str] = []

    for shot_index, control in enumerate(shot_controls):
        replay = planning_replay[shot_index]
        if "beamDirectiveBeforeMotionGuard" not in replay:
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached planning replay is missing the pre-guard beam."
            )
        fresh_directive = directives[shot_index]
        cached_beam = planner_directive_from_cache_value(
            replay.get("beamDirective")
        )
        cached_pre_guard_beam = planner_directive_from_cache_value(
            replay.get("beamDirectiveBeforeMotionGuard")
        )
        directive_before_motion_guard = (
            cached_pre_guard_beam
            if replanned_tail_active
            else fresh_directive
        )
        if not replanned_tail_active and (
            cached_pre_guard_beam.as_dict()
            if cached_pre_guard_beam is not None
            else None
        ) != (
            fresh_directive.as_dict()
            if fresh_directive is not None
            else None
        ):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached pre-guard beam does not match the fresh plan."
            )
        moving_opening_required = automatic_opening_requires_motion(
            shot_index,
            control,
        )
        rolling_static_budget_required = (
            rolling_static_budget_requires_motion(
                static_budget_motion_history,
                control,
            )
        )
        motion_requirement_reason = automatic_motion_requirement_reason(
            moving_opening_required,
            rolling_static_budget_required,
        )
        directive = directive_before_motion_guard
        guard_applied = False
        if motion_requirement_reason == "opening":
            directive, guard_applied = guard_automatic_opening_directive(
                directive,
                control,
            )
        elif motion_requirement_reason == "rolling_static_budget":
            directive, guard_applied = guard_rolling_static_budget_directive(
                directive,
                control,
                static_budget_motion_history,
            )
        desired_motion_family = (
            planner.normalize_motion_family(control.motion)
            if control.motion != "auto"
            else directive.motion_family if directive is not None else None
        )
        if motion_requirement_reason is not None and desired_motion_family is None:
            desired_motion_family = "dolly"
            guard_applied = True
        opening_guard_applied = bool(
            motion_requirement_reason == "opening" and guard_applied
        )
        rolling_guard_applied = bool(
            motion_requirement_reason == "rolling_static_budget"
            and guard_applied
        )

        if (
            cached_beam.as_dict() if cached_beam is not None else None
        ) != (directive.as_dict() if directive is not None else None):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached planning replay does not match the fresh beam plan."
            )
        if replay.get("openingMotionGuardApplied") is not opening_guard_applied:
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached opening-motion guard does not match generation policy."
            )
        if (
            replay.get("rollingStaticBudgetMovementRequired")
            is not rolling_static_budget_required
        ):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached rolling static budget does not match generation policy."
            )
        if (
            replay.get("rollingStaticBudgetGuardApplied")
            is not rolling_guard_applied
        ):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached rolling static guard does not match generation policy."
            )
        if (
            replay.get("automaticMotionRequirementReason")
            != motion_requirement_reason
        ):
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached automatic-motion reason does not match generation policy."
            )

        cached_shot = cached_shots.get(shot_index)
        if cached_shot is None:
            raise candidate_cache.CandidateCacheIntegrityError(
                f"Candidate cache is missing shot {shot_index}."
            )
        candidate_results = decode_candidate_pool_shot(
            cached_shot,
            templates_by_identity,
        )
        desired_motion_type = (
            control.motion if control.motion != "auto" else None
        )
        planned_non_static_required = (
            automatic_non_static_plan_requires_visible_motion(
                control,
                desired_motion_family,
            )
        )
        safe_results = selectable_safe_candidate_results(
            candidate_results,
            moving_opening_required,
            desired_motion_type,
            rolling_static_budget_required,
            planned_non_static_required,
        )
        if not safe_results:
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached shot has no policy-eligible safe candidate."
            )
        variation_pool = cached_variation_pool(
            cached_shot.sequence_continuation_state,
            candidate_results,
            safe_results,
        )
        continuation_result = select_seed_independent_sequence_continuation(
            safe_results,
            variation_pool,
        )
        validate_cached_continuation_state(
            cached_shot.sequence_continuation_state,
            continuation_result,
        )
        continuation_motion_family = planner.normalize_motion_family(
            continuation_result["realizedMotionType"]
        )
        static_budget_motion_history.append(
            variation_pool_static_budget_family(
                variation_pool,
                continuation_motion_family,
            )
        )

        reconciliation: PlannerDirectiveReconciliation | None = None
        if directive is not None:
            reconciliation = reconcile_planner_directive(
                directive,
                control,
                str(continuation_result["realizedShotType"]),
                continuation_motion_family,
            )
        cached_replan = validate_cached_planning_replay(
            replay,
            directive,
            reconciliation,
        )
        expected_replan = bool(
            reconciliation is not None
            and hierarchical_planner is not None
            and reconciliation.should_replan
            and shot_index + 1 < len(directives)
        )
        if cached_replan != expected_replan:
            raise candidate_cache.CandidateCacheIntegrityError(
                "Cached planning replay replan decision is stale."
            )
        replanned_tail_active = replanned_tail_active or cached_replan
        decoded[shot_index] = CachedCandidateRuntimeShot(
            candidate_results=candidate_results,
            safe_results=safe_results,
            variation_pool=variation_pool,
        )
    return decoded


def build_planner_samples(
    templates: list[ShotTemplate],
    evaluation_group_by_id: dict[str, str],
) -> list[planner.PlannerSample]:
    """Convert semantic templates into ordered, group-safe planner samples."""

    by_source: dict[str, list[ShotTemplate]] = {}
    for template in templates:
        by_source.setdefault(template.source_id, []).append(template)

    samples: list[planner.PlannerSample] = []
    for source_id, source_templates in sorted(by_source.items()):
        ordered = sorted(
            source_templates,
            key=lambda template: (
                template.source_start_frame,
                template.shot_index,
            ),
        )
        run_index = 0
        run_order = 0
        previous_template: ShotTemplate | None = None
        for template in ordered:
            if (
                previous_template is not None
                and (
                    template.shot_index
                    != previous_template.shot_index + 1
                    or getattr(
                        template,
                        "source_audio_mask_range_index",
                        None,
                    )
                    != getattr(
                        previous_template,
                        "source_audio_mask_range_index",
                        None,
                    )
                )
            ):
                run_index += 1
                run_order = 0
            midpoint = 0.5 * (
                template.source_start_frame
                + template.source_end_frame_exclusive
            )
            progress = float(
                np.clip(
                    midpoint / max(template.source_frame_count, 1),
                    0.0,
                    1.0,
                )
            )
            samples.append(
                planner.PlannerSample(
                    base_features=template.features,
                    progress=progress,
                    duration=template.duration,
                    shot_type=template.shot_type,
                    motion_family=template.motion_family,
                    source_id=f"{source_id}#run{run_index}",
                    evaluation_group=evaluation_group_by_id[source_id],
                    order=run_order,
                )
            )
            previous_template = template
            run_order += 1
    return samples


def same_module_source_closure_identifier(
    roots: list[object],
    contract_version: str,
) -> str:
    """Hash the same-module source closure of behavior-defining roots."""

    pending = list(roots)
    discovered: dict[str, object] = {}
    module_globals = globals()
    while pending:
        value = pending.pop()
        name = getattr(value, "__qualname__", getattr(value, "__name__", ""))
        if not name or name in discovered:
            continue
        if getattr(value, "__module__", None) != __name__:
            continue
        if not (inspect.isfunction(value) or inspect.isclass(value)):
            continue
        discovered[name] = value
        if inspect.isfunction(value):
            pending_code = [value.__code__]
            while pending_code:
                code = pending_code.pop()
                for referenced_name in code.co_names:
                    referenced = module_globals.get(referenced_name)
                    if (
                        inspect.isfunction(referenced)
                        or inspect.isclass(referenced)
                    ) and getattr(referenced, "__module__", None) == __name__:
                        pending.append(referenced)
                pending_code.extend(
                    constant
                    for constant in code.co_consts
                    if inspect.iscode(constant)
                )

    digest = hashlib.sha256()
    digest.update(str(contract_version).encode("utf-8"))
    for name, value in sorted(discovered.items()):
        digest.update(name.encode("utf-8"))
        digest.update(inspect.getsource(value).encode("utf-8"))
    return digest.hexdigest()


def preparation_logic_identifier() -> str:
    """Hash only generator code that can change preparation artifacts.

    Runtime selection, metadata and Unity-facing CLI edits should not force a
    29 MB templates/models rebuild.  Starting from the preparation roots,
    follow same-module function/class references and hash their source.  The
    explicit contract version covers behavior encoded in module constants.
    """

    frozen = cw_camera_runtime.frozen_identity_value(
        "preparationLogicIdentifier"
    )
    if frozen is not None:
        return frozen
    return same_module_source_closure_identifier(
        [
            ShotTemplate,
            build_template_library,
            train_shot_classifier,
            build_planner_samples,
            build_beat_onset_cache,
        ],
        PREPARATION_LOGIC_CONTRACT_VERSION,
    )


def candidate_logic_identifier() -> str:
    """Fail closed on any generator source or runtime policy-constant change."""

    frozen = cw_camera_runtime.frozen_identity_value(
        "candidateLogicIdentifier"
    )
    if frozen is not None:
        return frozen
    behavior_constants = {
        name: value
        for name, value in globals().items()
        if name.isupper()
    }
    return candidate_cache.fingerprint_value(
        {
            "contractVersion": CANDIDATE_LOGIC_CONTRACT_VERSION,
            "generatorSourceSha256": sha256_file(Path(__file__).resolve()),
            "policySourceSha256": {
                "adjacentTransition": sha256_file(
                    Path(adjacent_transition.__file__).resolve()
                ),
                "cameraKinematics": sha256_file(
                    Path(camera_kinematics.__file__).resolve()
                ),
                "trajectoryQuality": sha256_file(
                    Path(trajectory_quality.__file__).resolve()
                ),
            },
            "behaviorConstants": behavior_constants,
        }
    )


def preparation_cache_versions() -> dict[str, str]:
    """Return the runtime identity shared by the builder and generator."""

    return {
        "python": platform.python_version(),
        "joblib": joblib.__version__,
        "numpy": np.__version__,
        "scipy": scipy.__version__,
        "sklearn": sklearn.__version__,
        "librosa": librosa.__version__,
        "preparedPipeline": train.PIPELINE_VERSION,
        "planner": planner.PLANNER_VERSION,
        "shotLabels": shot_features.SHOT_LABEL_VERSION,
        "horizontalFraming": HORIZONTAL_FRAMING_VERSION,
        "templateMotionSmoothing": TEMPLATE_MOTION_SMOOTHING_VERSION,
        "preparationLogic": preparation_logic_identifier(),
    }


def build_preparation_cache_inputs(
    args: argparse.Namespace,
    target_record: train.SongRecord,
    training_records: list[train.SongRecord],
    planner_records: list[train.SongRecord],
    index_entries: dict[str, dict],
) -> dict:
    repository_root, camera_director_root = (
        cw_camera_runtime.source_tree_roots(
            Path(__file__).resolve().parents[2],
            Path(__file__).resolve().parent,
        )
    )
    return preparation_cache.build_inputs_for_records(
        repository_root,
        camera_director_root,
        args.training_index.resolve(),
        target_record,
        training_records,
        planner_records,
        index_entries,
        args.library_split,
        args.preparation_model_seed,
        args.beam_width,
        preparation_cache_versions(),
    )


def preparation_cache_build_command(
    args: argparse.Namespace,
    target_record: train.SongRecord,
) -> str:
    command = [
        sys.executable,
        str(
            Path(__file__).resolve().parent
            / "build_hybrid_preparation_cache.py"
        ),
        "--song-id",
        target_record.id,
        "--dataset-id",
        target_record.dataset_id,
        "--training-index",
        str(args.training_index.resolve()),
        "--library-split",
        args.library_split,
        "--preparation-model-seed",
        str(args.preparation_model_seed),
        "--beam-width",
        str(args.beam_width),
        "--cache-dir",
        str(args.cache_dir.resolve()),
        "--output-root",
        str(args.preparation_cache_root.resolve()),
    ]
    if args.data:
        command.extend(["--data", *[str(value) for value in args.data]])
    return subprocess.list2cmdline(command)


def validated_optional_classifier_accuracy(value: object) -> float | None:
    """Validate cached grouped-CV accuracy, allowing one-group ``None``."""

    if value is None:
        return None
    try:
        accuracy = float(value)
    except (TypeError, ValueError) as exception:
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache classifier accuracy is invalid."
        ) from exception
    if not math.isfinite(accuracy):
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache classifier accuracy is not finite."
        )
    return accuracy


def validate_preparation_cache_payload(
    loaded: preparation_cache.LoadedHybridPreparationCache,
    target_record: train.SongRecord,
    expected_frame_count: int | None = None,
) -> None:
    templates = loaded.templates
    if not isinstance(templates, list) or not templates:
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache templates must be a non-empty list."
        )
    models = loaded.models
    required_model_keys = {
        "shotClassifier",
        "hierarchicalPlanner",
        "featureMean",
        "featureStd",
        "shotClassifierCrossValidationAccuracy",
    }
    if not isinstance(models, dict):
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache models payload must be a dictionary."
        )
    missing_model_keys = sorted(required_model_keys - set(models))
    if missing_model_keys:
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache models are missing: "
            + ", ".join(missing_model_keys)
        )

    feature_mean = np.asarray(models["featureMean"])
    feature_std = np.asarray(models["featureStd"])
    feature_shape_valid = (
        feature_mean.ndim == 1
        and feature_mean.size > 0
        and feature_std.shape == feature_mean.shape
    )
    if (
        not feature_shape_valid
        or not np.all(np.isfinite(feature_mean))
        or not np.all(np.isfinite(feature_std))
        or np.any(feature_std <= 0.0)
    ):
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache feature normalization is invalid."
        )
    if any(
        np.asarray(template.features).shape != feature_mean.shape
        for template in templates
    ):
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache template feature dimensions do not match."
        )

    classifier = models["shotClassifier"]
    if not callable(getattr(classifier, "predict_proba", None)):
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache shot classifier is not fitted."
        )
    hierarchical_planner = models["hierarchicalPlanner"]
    if (
        not bool(getattr(hierarchical_planner, "is_fitted", False))
        or not callable(getattr(hierarchical_planner, "plan", None))
    ):
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache hierarchical planner is not fitted."
        )
    validated_optional_classifier_accuracy(
        models["shotClassifierCrossValidationAccuracy"]
    )

    summary_count = loaded.manifest.get("summary", {}).get("templateCount")
    if summary_count is not None and int(summary_count) != len(templates):
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache template count does not match its manifest."
        )
    expected_audio_start = float(target_record.song["audioStart"])
    if not math.isclose(
        loaded.beat_onset.audio_start,
        expected_audio_start,
        rel_tol=0.0,
        abs_tol=1e-9,
    ):
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache audio start does not match the target song."
        )
    if expected_frame_count is not None and (
        loaded.beat_onset.frame_count != expected_frame_count
        or len(loaded.beat_onset.onset_normalized)
        != expected_frame_count
    ):
        raise preparation_cache.CacheIntegrityError(
            "Preparation cache frame count does not match the target song."
        )


def lookup_preparation_cache(
    args: argparse.Namespace,
    target_record: train.SongRecord,
    training_records: list[train.SongRecord],
    planner_records: list[train.SongRecord],
    index_entries: dict[str, dict],
) -> PreparationCacheLookup:
    if args.preparation_cache_mode == "off":
        return PreparationCacheLookup(status="disabled")
    if args.planner != "hierarchical":
        message = (
            "Preparation caches currently support --planner hierarchical "
            "only."
        )
        if args.preparation_cache_mode == "require":
            raise preparation_cache.CacheError(message)
        return PreparationCacheLookup(status="unsupported", error=message)

    cache_key: str | None = None
    bundle_path: Path | None = None
    loaded: preparation_cache.LoadedHybridPreparationCache | None = None
    try:
        build_inputs = build_preparation_cache_inputs(
            args,
            target_record,
            training_records,
            planner_records,
            index_entries,
        )
        cache_key = preparation_cache.cache_key_for(build_inputs)
        bundle_path = args.preparation_cache_root.resolve() / cache_key
        if not bundle_path.is_dir():
            if args.preparation_cache_mode == "require":
                raise preparation_cache.CacheError(
                    f"Required preparation cache is missing: {bundle_path}"
                )
            return PreparationCacheLookup(
                status="miss",
                cache_key=cache_key,
                path=bundle_path,
            )
        loaded = preparation_cache.load_cache_bundle(
            bundle_path,
            cache_key,
        )
        validate_preparation_cache_payload(loaded, target_record)
        return PreparationCacheLookup(
            status="hit",
            cache_key=cache_key,
            path=bundle_path,
            loaded=loaded,
        )
    except Exception as error:
        if args.preparation_cache_mode == "require":
            raise
        return PreparationCacheLookup(
            status="invalid",
            cache_key=cache_key,
            path=bundle_path,
            error=f"{type(error).__name__}: {error}",
            manifest_fingerprint=(
                preparation_cache.sha256_bytes(
                    preparation_cache.canonical_json_bytes(loaded.manifest)
                )
                if loaded is not None
                else None
            ),
        )


def report_preparation_cache_lookup(
    lookup: PreparationCacheLookup,
    args: argparse.Namespace,
    target_record: train.SongRecord,
) -> None:
    if lookup.status == "disabled":
        return
    if lookup.status == "hit":
        print(
            "Preparation cache hit for current target "
            f"{target_record.id} ({target_record.dataset_id}): {lookup.path}",
            file=sys.stderr,
        )
        return
    detail = f" ({lookup.error})" if lookup.error else ""
    print(
        f"Preparation cache {lookup.status}{detail}; using the safe "
        "uncached path.",
        file=sys.stderr,
    )
    if args.planner == "hierarchical":
        print(
            "Prebuild it with: "
            + preparation_cache_build_command(args, target_record),
            file=sys.stderr,
        )


def publish_preparation_cache_after_miss(
    args: argparse.Namespace,
    lookup: PreparationCacheLookup,
    target_record: train.SongRecord,
    target_entry: dict | None,
    target_group_available: int,
    training_records: list[train.SongRecord],
    planner_records: list[train.SongRecord],
    index_entries: dict[str, dict],
    templates: list[ShotTemplate],
    planner_templates: list[ShotTemplate],
    classifier: RandomForestClassifier,
    hierarchical_planner: planner.HierarchicalShotPlanner | None,
    feature_mean: np.ndarray,
    feature_std: np.ndarray,
    cross_validation_accuracy: float | None,
    beat_onset: preparation_cache.BeatOnsetCache,
    planner_sample_count: int,
) -> preparation_cache.CacheBundleInfo | None:
    """Publish preparation work already paid for by an automatic cache miss.

    ``auto`` previously fell through to the uncached path without retaining the
    templates, fitted models, or target audio analysis.  Publishing the exact
    immutable bundle here keeps first-run behavior safe while making the next
    Seed or selected-shot generation a verified cache hit.
    """

    if (
        args.preparation_cache_mode != "auto"
        or args.planner != "hierarchical"
        or lookup.status not in {"miss", "invalid"}
        or lookup.cache_key is None
        or hierarchical_planner is None
    ):
        return None

    build_inputs = build_preparation_cache_inputs(
        args,
        target_record,
        training_records,
        planner_records,
        index_entries,
    )
    current_key = preparation_cache.cache_key_for(build_inputs)
    if current_key != lookup.cache_key:
        raise RuntimeError(
            "Hybrid preparation inputs changed while generation was running; "
            "the automatic cache was not published."
        )

    if (
        lookup.status == "invalid"
        and lookup.path is not None
        and lookup.manifest_fingerprint is not None
    ):
        try:
            preparation_cache.quarantine_cache_bundle(
                lookup.path,
                lookup.cache_key,
                expected_manifest_fingerprint=lookup.manifest_fingerprint,
            )
        except (OSError, ValueError) as exception:
            print(
                "Preparation cache quarantine warning: " + str(exception),
                file=sys.stderr,
            )
            return None

    models = {
        "shotClassifier": classifier,
        "hierarchicalPlanner": hierarchical_planner,
        "featureMean": np.asarray(feature_mean, dtype=np.float32),
        "featureStd": np.asarray(feature_std, dtype=np.float32),
        "shotClassifierCrossValidationAccuracy": cross_validation_accuracy,
    }
    summary = {
        "targetSongId": target_record.id,
        "targetDatasetId": target_record.dataset_id,
        "targetEvaluationGroupId": target_reference_evaluation_group(
            index_entries,
            target_record,
        ),
        "targetTrainingIndexMembership": target_entry is not None,
        "targetInputKind": (
            "generation_input"
            if target_record.is_generation_input
            else "authored_camera_record"
        ),
        "targetEvaluationGroupAvailableRecordCount": target_group_available,
        "preparationModelSeed": args.preparation_model_seed,
        "trainingSongCount": len(training_records),
        "plannerSongCount": len(planner_records),
        "templateCount": len(templates),
        "plannerTemplateCount": len(planner_templates),
        "plannerSampleCount": int(planner_sample_count),
        "frameCount": beat_onset.frame_count,
        "beatCount": len(beat_onset.beat_frames),
        "peakCount": len(beat_onset.peak_frames),
        "cutCandidateCount": len(beat_onset.candidates),
        "shotClassifierCrossValidationAccuracy": cross_validation_accuracy,
        "publishedBy": "generate_hybrid_auto_miss",
    }
    training_mask_audit = finalized_audio_aligned_template_mask_audit(
        audio_aligned_template_mask_audit(training_records, index_entries),
        templates,
    )
    planner_mask_audit = finalized_audio_aligned_template_mask_audit(
        audio_aligned_template_mask_audit(planner_records, index_entries),
        planner_templates,
    )
    if training_mask_audit is not None:
        summary["audioAlignedFrameMasking"] = {
            "trainingTemplates": training_mask_audit,
            "shotPlanner": planner_mask_audit,
        }
    bundle = preparation_cache.publish_cache_bundle(
        args.preparation_cache_root,
        build_inputs,
        templates,
        models,
        beat_onset,
        summary,
    )
    loaded = preparation_cache.load_cache_bundle(
        bundle.path,
        bundle.cache_key,
    )
    validate_preparation_cache_payload(
        loaded,
        target_record,
        beat_onset.frame_count,
    )
    print(
        "Preparation cache published after miss: " + str(bundle.path),
        file=sys.stderr,
    )
    return bundle


def main() -> None:
    train.configure_utf8_stdio()
    generation_timer = SequentialStageTimer()
    args = parse_args()
    research_profile = normalized_research_ablation_profile(args)
    single_shot_mode = validate_single_shot_request(args)
    training_index, index_entries = load_training_policy(
        args.training_index,
    )
    manifest_paths = train.find_manifest_paths(
        generation_data_inputs(
            args.data,
            args.training_index,
            training_index,
        )
    )
    records = train.load_records(manifest_paths, skip_unavailable=True)
    target_record = train.select_record(
        records,
        song_name=args.song,
        song_id=args.song_id,
        dataset_id=args.dataset_id,
    )
    (
        training_records,
        planner_records,
        target_entry,
        target_group_available,
    ) = select_generation_records(
        records,
        index_entries,
        target_record,
        args.library_split,
    )
    cut_reference_records = (
        select_cut_reference_records(
            records,
            index_entries,
            target_record,
            args.library_split,
            allow_exact_audio_prior=effective_same_audio_prior(args) == "auto",
        )
        if args.cut_planner == "data_driven"
        else []
    )
    training_audio_mask_audit = audio_aligned_template_mask_audit(
        training_records,
        index_entries,
    )
    planner_audio_mask_audit = audio_aligned_template_mask_audit(
        planner_records,
        index_entries,
    )
    target_aspect_policy = target_entry or {
        "aspectRatio": target_record.song.get(
            "aspectRatio",
            target_record.manifest.get("aspectRatio"),
        ),
        "aspectSource": target_record.song.get(
            "aspectSource",
            target_record.manifest.get("aspectSource", "generation_manifest"),
        ),
    }
    target_aspect_ratio, target_aspect_source = aspect_for_entry(
        target_aspect_policy,
        args.aspect_ratio,
    )
    aspect_by_id = {
        song_id: aspect_for_entry(entry)
        for song_id, entry in index_entries.items()
    }
    generation_timer.mark("catalog_and_policy")

    cache_lookup = lookup_preparation_cache(
        args,
        target_record,
        training_records,
        planner_records,
        index_entries,
    )
    report_preparation_cache_lookup(cache_lookup, args, target_record)
    generation_timer.mark("preparation_cache_lookup")

    prepared_by_id: dict[str, train.PreparedSong] = {
        target_record.id: (
            train.load_or_prepare_generation_input_song(
                target_record,
                args.cache_dir.resolve(),
                False,
            )
            if target_record.is_generation_input
            else train.load_or_prepare_song(
                target_record,
                args.cache_dir.resolve(),
                False,
            )
        )
    }
    target = prepared_by_id[target_record.id]
    base_generation: BaseGenerationComposite | None = None
    if single_shot_mode:
        base_generation = load_base_generation_composite(
            args.base_generation,
            expected_song_id=target_record.id,
            expected_dataset_id=target_record.dataset_id,
            expected_frame_count=len(target.inputs),
            expected_aspect_ratio=target_aspect_ratio,
            expected_planner_mode=args.planner,
        )
        if int(args.only_shot_index) >= len(base_generation.shots):
            raise ValueError(
                "--only-shot-index is outside the base generation shot list."
            )
    cached_preparation = cache_lookup.loaded
    if cached_preparation is not None:
        try:
            validate_preparation_cache_payload(
                cached_preparation,
                target_record,
                len(target.inputs),
            )
        except preparation_cache.CacheError as error:
            if args.preparation_cache_mode == "require":
                raise
            print(
                "Preparation cache target validation failed "
                f"({type(error).__name__}: {error}); using the safe "
                "uncached path.",
                file=sys.stderr,
            )
            print(
                "Prebuild it with: "
                + preparation_cache_build_command(args, target_record),
                file=sys.stderr,
            )
            cached_preparation = None
    generation_timer.mark("target_preparation")

    if cached_preparation is None:
        for record in training_records:
            if record.id not in prepared_by_id:
                prepared_by_id[record.id] = train.load_or_prepare_song(
                    record,
                    args.cache_dir.resolve(),
                    False,
                )
        templates = build_template_library(
            training_records,
            prepared_by_id,
            aspect_by_id=aspect_by_id,
            policy_by_id=index_entries,
            shot_label_mode=(
                "legacy_quantile"
                if args.planner == "legacy"
                else "semantic"
            ),
        )
    else:
        templates = cached_preparation.templates
    target_evaluation_group = target_reference_evaluation_group(
        index_entries,
        target_record,
    )
    planner_record_ids = {record.id for record in planner_records}
    planner_templates = [
        template
        for template in templates
        if template.source_id in planner_record_ids
        and (
            args.planner == "legacy"
            or (
                template.shot_type_confidence_tier != "low"
                and template.motion_confidence >= 0.45
            )
        )
    ]
    training_audio_mask_audit = finalized_audio_aligned_template_mask_audit(
        training_audio_mask_audit,
        templates,
    )
    planner_audio_mask_audit = finalized_audio_aligned_template_mask_audit(
        planner_audio_mask_audit,
        planner_templates,
    )
    evaluation_group_by_id = {
        song_id: str(entry["evaluationGroupId"])
        for song_id, entry in index_entries.items()
    }
    target_group_template_count = (
        sum(
            evaluation_group_by_id[template.source_id]
            == target_evaluation_group
            for template in templates
        )
        if target_evaluation_group is not None
        else sum(
            template.source_id == target_record.id
            for template in templates
        )
    )
    if target_group_template_count:
        raise ValueError(
            "Leakage guard failed: target evaluation group entered the "
            "template library."
        )
    generation_timer.mark("template_preparation")
    cached_models = (
        cached_preparation.models
        if cached_preparation is not None
        else None
    )
    if cached_models is None:
        classifier, cross_validation_accuracy = train_shot_classifier(
            planner_templates,
            evaluation_group_by_id,
        )
    else:
        classifier = cached_models["shotClassifier"]
        cross_validation_accuracy = validated_optional_classifier_accuracy(
            cached_models["shotClassifierCrossValidationAccuracy"]
        )
    hierarchical_planner: planner.HierarchicalShotPlanner | None = None
    planner_metrics: dict[str, object] = {}
    planner_samples: list[planner.PlannerSample] | None = None
    if args.planner == "hierarchical":
        if args.evaluate_planner:
            planner_samples = build_planner_samples(
                planner_templates,
                evaluation_group_by_id,
            )
        if cached_models is None:
            if planner_samples is None:
                planner_samples = build_planner_samples(
                    planner_templates,
                    evaluation_group_by_id,
                )
            hierarchical_planner = planner.HierarchicalShotPlanner(
                random_state=args.preparation_model_seed,
                beam_width=args.beam_width,
            )
        else:
            hierarchical_planner = cached_models["hierarchicalPlanner"]
        if args.evaluate_planner:
            planner_metrics = hierarchical_planner.closed_loop_metrics(
                planner_samples,
            )
        if cached_models is None:
            hierarchical_planner.fit(planner_samples)
    if cached_models is None:
        feature_matrix = np.stack(
            [template.features for template in templates]
        )
        feature_mean = feature_matrix.mean(axis=0)
        feature_std = np.maximum(feature_matrix.std(axis=0), 1e-5)
        beat_onset = build_beat_onset_cache(
            target_record,
            target,
        )
    else:
        feature_mean = cached_models["featureMean"]
        feature_std = cached_models["featureStd"]
        beat_onset = cached_preparation.beat_onset
    cut_plan_trace: dict[str, object] | None = None
    if base_generation is not None:
        boundaries = list(base_generation.boundaries)
        cut_plan_metadata: dict[str, object] = {
            "mode": "base_generation_cut_locked",
            "selectedShotRegeneration": True,
            "boundaryCount": len(boundaries),
            "sourceMetadataSha256": base_generation.metadata_sha256,
        }
    elif args.cut_planner == "data_driven":
        cut_plan_result, cut_plan_metadata = build_data_driven_cut_plan(
            args,
            target_record,
            target,
            beat_onset,
            cut_reference_records,
            index_entries,
        )
        boundaries = list(cut_plan_result.boundaries)
        cut_plan_trace = cut_plan_result.trace
    else:
        boundaries = beat_onset.cut_boundaries(
            args.min_shot_seconds,
            args.max_shot_seconds,
            sample_rate=60,
        )
        cut_plan_metadata = {
            "mode": "legacy_greedy_beat_onset",
            "minimumShotSeconds": args.min_shot_seconds,
            "maximumShotSeconds": args.max_shot_seconds,
            "boundaryCount": len(boundaries),
        }
    published_preparation_bundle = publish_preparation_cache_after_miss(
        args,
        cache_lookup,
        target_record,
        target_entry,
        target_group_available,
        training_records,
        planner_records,
        index_entries,
        templates,
        planner_templates,
        classifier,
        hierarchical_planner,
        feature_mean,
        feature_std,
        cross_validation_accuracy,
        beat_onset,
        len(planner_samples) if planner_samples is not None else 0,
    )
    generation_timer.mark("model_audio_preparation")
    frame_count = len(target.inputs)
    segment_spans = list(zip(boundaries[:-1], boundaries[1:]))
    if single_shot_mode:
        selected_index = int(args.only_shot_index)
        selected_start, selected_end = segment_spans[selected_index]
        segment_feature_list: list[np.ndarray | None] = [
            None
        ] * len(segment_spans)
        segment_feature_list[selected_index] = segment_features(
            target, selected_start, selected_end
        )
        segment_feature_list[selected_index] = (
            apply_research_ablation_to_segment_features(
                segment_feature_list[selected_index],
                feature_mean,
                research_profile,
            )
        )
    else:
        segment_feature_list = [
            apply_research_ablation_to_segment_features(
                segment_features(target, start, end),
                feature_mean,
                research_profile,
            )
            for start, end in segment_spans
        ]
    segment_progress = [
        float(np.clip(0.5 * (start + end) / frame_count, 0.0, 1.0))
        for start, end in segment_spans
    ]
    segment_durations = [
        (end - start) / 60.0
        for start, end in segment_spans
    ]
    directives: list[planner.ShotDirective | None]
    if base_generation is not None:
        directives = base_planner_directives(base_generation)
    elif hierarchical_planner is not None:
        directives = list(
            hierarchical_planner.plan(
                segment_feature_list,
                segment_progress,
                segment_durations,
                beam_width=args.beam_width,
            )
        )
    else:
        directives = [None] * len(segment_spans)
    if (
        not math.isfinite(args.body_follow_smoothing_seconds)
        or args.body_follow_smoothing_seconds <= 0.0
    ):
        raise ValueError(
            "--body-follow-smoothing-seconds must be finite and positive."
        )
    if (
        not math.isfinite(args.body_follow_dead_zone_meters)
        or args.body_follow_dead_zone_meters < 0.0
    ):
        raise ValueError(
            "--body-follow-dead-zone-meters must be finite and non-negative."
        )
    global_shot_control = validate_shot_control(
        ShotControl(
            shot_size=args.shot_size,
            motion=args.motion,
            composition=args.composition,
            distance_meters=args.distance_meters,
            motion_intensity=args.motion_intensity,
            body_follow_strength=args.body_follow_strength,
        )
    )
    shot_controls = load_shot_controls(
        args.directives_json,
        global_shot_control,
        len(segment_spans),
    )
    root = np.fromfile(target_record.song_dir / "root.f32", dtype="<f4").reshape(
        frame_count,
        14,
    )
    times = np.fromfile(target_record.song_dir / "time.f64", dtype="<f8")
    if base_generation is not None:
        validate_base_generation_times(base_generation, times)
    joints = target.inputs[:, :63].reshape(frame_count, 21, 3)
    front_facing_reference = calibrate_front_facing_reference(joints)
    world_camera = (
        base_generation.world_camera.copy()
        if base_generation is not None
        else np.zeros((frame_count, 9), dtype=np.float32)
    )
    shots: list[dict] = (
        [copy.deepcopy(shot) for shot in base_generation.shots]
        if base_generation is not None
        else []
    )
    recent: list[tuple[str, int]] = []
    previous: RealizedShotState | None = None
    realized_directive_history: list[planner.ShotDirective] = []
    static_budget_motion_history: list[str] = []
    planner_replan_count = 0

    templates_by_identity: dict[tuple[str, int], ShotTemplate] = {}
    for template in templates:
        identity_key = (template.source_id, int(template.shot_index))
        if identity_key in templates_by_identity:
            raise ValueError(
                "Template identities must be unique for candidate caching: "
                f"{identity_key!r}."
            )
        templates_by_identity[identity_key] = template

    base_single_shot_context: BaseSingleShotContext | None = None
    previous_transition_state: dict[str, object] | None = None
    next_transition_state: dict[str, object] | None = None
    if base_generation is not None:
        selected_shot_index = int(args.only_shot_index)
        base_single_shot_context = reconstruct_base_single_shot_context(
            base_generation,
            selected_shot_index,
            templates_by_identity,
        )
        recent = list(base_single_shot_context.recent)
        previous = base_single_shot_context.previous
        static_budget_motion_history = list(
            base_single_shot_context.static_budget_motion_history
        )
        if selected_shot_index > 0:
            previous_transition_state = base_shot_transition_state(
                base_generation,
                selected_shot_index - 1,
                root,
                joints,
                target.body_scale,
                target_aspect_ratio,
            )
        if selected_shot_index + 1 < len(base_generation.shots):
            next_transition_state = base_shot_transition_state(
                base_generation,
                selected_shot_index + 1,
                root,
                joints,
                target.body_scale,
                target_aspect_ratio,
            )
    generation_timer.mark("shot_planning")

    effective_preparation_cache_key = (
        published_preparation_bundle.cache_key
        if published_preparation_bundle is not None
        else cache_lookup.cache_key
        if cached_preparation is not None
        else None
    )
    if (
        args.candidate_cache_mode != "off"
        and effective_preparation_cache_key is None
    ):
        # Candidate pools must never fall back to a narrower hand-maintained
        # approximation of preparation identity.  Even when preparation-cache
        # loading is disabled or invalid, its deterministic content address
        # captures training aspect policy, source/code fingerprints and runtime
        # versions used to build the in-memory templates and models.
        effective_preparation_cache_key = preparation_cache.cache_key_for(
            build_preparation_cache_inputs(
                args,
                target_record,
                training_records,
                planner_records,
                index_entries,
            )
        )
    candidate_identity: dict[str, object] | None = None
    initial_candidate_directives = list(directives)
    candidate_cache_key: str | None = None
    candidate_cache_path: Path | None = None
    candidate_cache_lookup_status = "disabled"
    candidate_cache_error: str | None = None
    candidate_cache_manifest_fingerprint: str | None = None
    cached_candidate_shots: dict[
        int, candidate_cache.CandidatePoolShot
    ] = {}
    candidate_planning_replay: list[dict[str, object]] = []
    cached_candidate_runtime: dict[int, CachedCandidateRuntimeShot] = {}
    candidate_cache_hit_active = False
    candidate_cache_selection_only_expansion_count = 0
    single_shot_identity: dict[str, object] | None = None
    single_shot_cached_pool: candidate_cache.CandidatePoolShot | None = None
    single_shot_cache_hit_active = False
    if args.candidate_cache_mode != "off" and not single_shot_mode:
        candidate_identity = candidate_cache_identity_for_generation(
            args,
            target_record,
            training_records,
            index_entries,
            effective_preparation_cache_key,
            initial_candidate_directives,
            shot_controls,
            boundaries,
            target_aspect_ratio,
        )
        candidate_load = candidate_cache.try_load_cache_bundle(
            args.candidate_cache_root,
            candidate_identity,
            # This path is an application-owned local build cache, not an
            # interchange artifact.  SHA-256 validates integrity, not origin.
            trust_pickle=True,
        )
        candidate_cache_key = candidate_load.cache_key
        candidate_cache_path = candidate_load.path
        candidate_cache_lookup_status = candidate_load.status
        candidate_cache_error = candidate_load.error
        if candidate_load.hit:
            try:
                (
                    cached_candidate_shots,
                    candidate_planning_replay,
                ) = validate_loaded_candidate_pool(
                    candidate_load.loaded,
                    boundaries,
                )
                cached_candidate_runtime = preflight_candidate_cache_runtime(
                    cached_candidate_shots,
                    candidate_planning_replay,
                    templates_by_identity,
                    initial_candidate_directives,
                    shot_controls,
                    hierarchical_planner,
                )
                candidate_cache_hit_active = True
                print(
                    "Candidate cache hit for current target "
                    f"{target_record.id} ({target_record.dataset_id}): "
                    + str(candidate_load.path),
                    file=sys.stderr,
                )
            except (
                candidate_cache.CandidateCacheError,
                AttributeError,
                IndexError,
                KeyError,
                TypeError,
                ValueError,
            ) as exception:
                candidate_cache_lookup_status = "invalid"
                candidate_cache_error = str(exception)
                candidate_cache_manifest_fingerprint = (
                    candidate_cache.fingerprint_value(
                        candidate_load.loaded.manifest
                    )
                    if candidate_load.loaded is not None
                    else None
                )
        if not candidate_cache_hit_active:
            if args.candidate_cache_mode == "require":
                raise candidate_cache.CandidateCacheIntegrityError(
                    "Required candidate cache is unavailable: "
                    + str(candidate_cache_path)
                    + (
                        f" ({candidate_cache_error})"
                        if candidate_cache_error
                        else ""
                    )
                )
            if (
                candidate_cache_lookup_status == "invalid"
                and candidate_cache_path is not None
                and candidate_cache_key is not None
                and candidate_cache_manifest_fingerprint is not None
            ):
                try:
                    candidate_cache.quarantine_cache_bundle(
                        candidate_cache_path,
                        candidate_cache_key,
                        expected_manifest_fingerprint=(
                            candidate_cache_manifest_fingerprint
                        ),
                    )
                except (OSError, ValueError) as exception:
                    candidate_cache_error = (
                        (candidate_cache_error + "; ")
                        if candidate_cache_error
                        else ""
                    ) + "quarantine failed: " + str(exception)
            print(
                "Candidate cache miss; safe cameras will be generated once.",
                file=sys.stderr,
            )
            if candidate_cache_error:
                print(
                    "Candidate cache validation warning: "
                    + candidate_cache_error,
                    file=sys.stderr,
                )
    elif args.candidate_cache_mode != "off" and single_shot_mode:
        assert base_single_shot_context is not None
        assert effective_preparation_cache_key is not None
        selected_index = int(args.only_shot_index)
        selected_start, selected_end = segment_spans[selected_index]
        single_shot_identity = single_shot_cache_identity_for_generation(
            args,
            target_record,
            training_records,
            index_entries,
            effective_preparation_cache_key,
            initial_candidate_directives[selected_index],
            shot_controls[selected_index],
            base_single_shot_context,
            selected_start,
            selected_end,
            target_aspect_ratio,
        )
        single_load = single_shot_cache.try_load_single_shot_cache(
            args.single_shot_cache_root,
            single_shot_identity,
            shot_index=selected_index,
            start_frame=selected_start,
            end_frame_exclusive=selected_end,
        )
        candidate_cache_key = single_load.cache_key
        candidate_cache_path = single_load.path
        candidate_cache_lookup_status = single_load.status
        candidate_cache_error = single_load.error
        if single_load.hit:
            single_shot_cached_pool = single_load.shot
            single_shot_cache_hit_active = True
            print(
                "Single-shot candidate cache hit for current target "
                f"{target_record.id} ({target_record.dataset_id}): "
                + str(single_load.path),
                file=sys.stderr,
            )
        else:
            if args.candidate_cache_mode == "require":
                raise candidate_cache.CandidateCacheIntegrityError(
                    "Required single-shot candidate cache is unavailable: "
                    + str(single_load.path)
                    + (
                        f" ({single_load.error})"
                        if single_load.error
                        else ""
                    )
                )
            if single_load.status == "invalid":
                try:
                    single_shot_cache.quarantine_single_shot_cache(
                        single_load.path,
                        single_load.cache_key,
                    )
                except (OSError, ValueError) as exception:
                    candidate_cache_error = (
                        (candidate_cache_error + "; ")
                        if candidate_cache_error
                        else ""
                    ) + "quarantine failed: " + str(exception)
            print(
                "Single-shot candidate cache miss; regenerating only shot "
                f"{selected_index}.",
                file=sys.stderr,
            )
    generation_timer.mark("candidate_cache_lookup")
    candidate_pool_shots: list[candidate_cache.CandidatePoolShot] = []

    if single_shot_mode:
        selected_index = int(args.only_shot_index)
        selected_features = segment_feature_list[selected_index]
        if selected_features is None:
            raise RuntimeError("Selected shot features were not prepared.")
        generation_work = [
            (
                selected_index,
                segment_spans[selected_index],
                selected_features,
            )
        ]
    else:
        generation_work = [
            (shot_index, span, features)
            for shot_index, (span, features) in enumerate(
                zip(segment_spans, segment_feature_list)
            )
        ]
    for shot_index, (start, end), features in generation_work:
        planning_replay_entry = (
            candidate_planning_replay[shot_index]
            if candidate_cache_hit_active
            else None
        )
        control = shot_controls[shot_index]
        moving_opening_required = automatic_opening_requires_motion(
            shot_index,
            control,
        )
        rolling_static_budget_required = (
            rolling_static_budget_requires_motion(
                static_budget_motion_history,
                control,
            )
        )
        motion_requirement_reason = automatic_motion_requirement_reason(
            moving_opening_required,
            rolling_static_budget_required,
        )
        if planning_replay_entry is not None:
            directive = planner_directive_from_cache_value(
                planning_replay_entry.get("beamDirective")
            )
            directive_before_motion_guard = (
                planner_directive_from_cache_value(
                    planning_replay_entry.get(
                        "beamDirectiveBeforeMotionGuard"
                    )
                )
            )
            opening_motion_guard_applied = planning_replay_entry.get(
                "openingMotionGuardApplied"
            )
            if type(opening_motion_guard_applied) is not bool:
                raise candidate_cache.CandidateCacheIntegrityError(
                    "Cached opening-motion guard flag must be boolean."
                )
            rolling_static_budget_guard_applied = (
                planning_replay_entry.get(
                    "rollingStaticBudgetGuardApplied"
                )
            )
            if type(rolling_static_budget_guard_applied) is not bool:
                raise candidate_cache.CandidateCacheIntegrityError(
                    "Cached rolling static guard flag must be boolean."
                )
            if (
                planning_replay_entry.get(
                    "rollingStaticBudgetMovementRequired"
                )
                is not rolling_static_budget_required
            ):
                raise candidate_cache.CandidateCacheIntegrityError(
                    "Cached rolling static budget decision is stale."
                )
            if (
                planning_replay_entry.get(
                    "automaticMotionRequirementReason"
                )
                != motion_requirement_reason
            ):
                raise candidate_cache.CandidateCacheIntegrityError(
                    "Cached automatic-motion reason is stale."
                )
        else:
            directive_before_motion_guard = directives[shot_index]
            directive = directive_before_motion_guard
            guard_applied = False
            if motion_requirement_reason == "opening":
                directive, guard_applied = (
                    guard_automatic_opening_directive(
                        directive,
                        control,
                    )
                )
            elif motion_requirement_reason == "rolling_static_budget":
                directive, guard_applied = (
                    guard_rolling_static_budget_directive(
                        directive,
                        control,
                        static_budget_motion_history,
                    )
                )
            opening_motion_guard_applied = bool(
                motion_requirement_reason == "opening" and guard_applied
            )
            rolling_static_budget_guard_applied = bool(
                motion_requirement_reason == "rolling_static_budget"
                and guard_applied
            )
            directives[shot_index] = directive
        desired_shot_type = (
            control.shot_size
            if control.shot_size != "auto"
            else directive.shot_type if directive is not None else None
        )
        desired_motion_type = (
            control.motion if control.motion != "auto" else None
        )
        desired_motion_family = (
            planner.normalize_motion_family(control.motion)
            if control.motion != "auto"
            else directive.motion_family if directive is not None else None
        )
        if motion_requirement_reason is not None and desired_motion_family is None:
            # The legacy planner has no sequence directive. Dolly is a neutral
            # required-motion family; candidate scoring still chooses the
            # concrete authored trajectory.
            desired_motion_family = "dolly"
            if planning_replay_entry is None:
                opening_motion_guard_applied = bool(
                    motion_requirement_reason == "opening"
                )
                rolling_static_budget_guard_applied = bool(
                    motion_requirement_reason == "rolling_static_budget"
                )
        planned_non_static_required = (
            automatic_non_static_plan_requires_visible_motion(
                control,
                desired_motion_family,
            )
        )
        visible_motion_filter_reason = (
            motion_requirement_reason
            if motion_requirement_reason is not None
            else "planned_non_static_directive"
            if planned_non_static_required
            else None
        )
        effective_motion_intensity = (
            0.0 if control.motion == "static" else control.motion_intensity
        )
        effective_composition = composition_policy(
            control,
            args.horizontal_framing,
        )
        ranked_templates: list[ShotTemplate] | None = None

        def ensure_ranked_templates() -> list[ShotTemplate]:
            nonlocal ranked_templates
            if ranked_templates is None:
                ranked_templates = rank_template_candidates(
                    classifier,
                    templates,
                    feature_mean,
                    feature_std,
                    features,
                    shot_index,
                    previous,
                    recent,
                    candidate_count=SEED_VARIATION_MAX_TRANSITION_CANDIDATES,
                    desired_type_override=desired_shot_type,
                    desired_motion_family=desired_motion_family,
                    desired_motion_type=desired_motion_type,
                )
                if planned_non_static_required:
                    ranked_templates = sorted(
                        ranked_templates,
                        key=lambda template: (
                            template.motion_family == "static"
                        ),
                    )
                if not ranked_templates:
                    raise ValueError(
                        f"No templates are available for shot {shot_index} "
                        "with shot-size directive "
                        f"{desired_shot_type!r}."
                    )
            return ranked_templates

        cached_runtime_shot = (
            cached_candidate_runtime.get(shot_index)
            if candidate_cache_hit_active
            else None
        )
        if single_shot_cached_pool is not None:
            try:
                cached_runtime_shot = decode_single_shot_cached_runtime(
                    single_shot_cached_pool,
                    templates_by_identity,
                    moving_opening_required=moving_opening_required,
                    desired_motion_type=desired_motion_type,
                    rolling_static_budget_required=(
                        rolling_static_budget_required
                    ),
                    planned_non_static_required=planned_non_static_required,
                )
            except (
                candidate_cache.CandidateCacheError,
                KeyError,
                TypeError,
                ValueError,
            ) as exception:
                if args.candidate_cache_mode == "require":
                    raise
                single_shot_cache_hit_active = False
                single_shot_cached_pool = None
                candidate_cache_lookup_status = "invalid"
                candidate_cache_error = str(exception)
                if candidate_cache_path is not None and candidate_cache_key:
                    try:
                        single_shot_cache.quarantine_single_shot_cache(
                            candidate_cache_path,
                            candidate_cache_key,
                        )
                    except (OSError, ValueError) as quarantine_error:
                        candidate_cache_error += (
                            "; quarantine failed: " + str(quarantine_error)
                        )
                print(
                    "Single-shot candidate cache runtime validation failed; "
                    "rebuilding the selected shot.",
                    file=sys.stderr,
                )
        if (
            cached_runtime_shot is not None
            and transition_candidate_pool_may_expand(
                cached_runtime_shot.candidate_results,
                cached_runtime_shot.safe_results,
                previous_state=previous_transition_state,
                next_state=next_transition_state,
            )
        ):
            # Resume after the Seed-independent cached prefix. Extra ranks are
            # selection-only and never change continuation/static history or
            # the bytes subsequently encoded as the reusable candidate pool.
            candidate_cache_selection_only_expansion_count += 1
            print(
                "Candidate cache transition pool is too narrow for shot "
                f"{shot_index}; evaluating selection-only later ranks.",
                file=sys.stderr,
            )
            candidate_results, safe_results = evaluate_safe_candidate_pool(
                ensure_ranked_templates(),
                previous,
                target,
                joints,
                root,
                start,
                end,
                target_aspect_ratio,
                effective_composition,
                control,
                args.body_follow_smoothing_seconds,
                args.body_follow_dead_zone_meters,
                effective_motion_intensity,
                moving_opening_required,
                desired_motion_type,
                rolling_static_budget_required,
                planned_non_static_required,
                previous_transition_state=previous_transition_state,
                next_transition_state=next_transition_state,
                cached_base_candidate_results=(
                    cached_runtime_shot.candidate_results
                ),
                front_facing_reference=front_facing_reference,
            )
            variation_pool = cached_runtime_shot.variation_pool
        elif cached_runtime_shot is not None:
            candidate_results = cached_runtime_shot.candidate_results
            safe_results = cached_runtime_shot.safe_results
            variation_pool = cached_runtime_shot.variation_pool
        else:
            candidate_results, safe_results = evaluate_safe_candidate_pool(
                ensure_ranked_templates(),
                previous,
                target,
                joints,
                root,
                start,
                end,
                target_aspect_ratio,
                effective_composition,
                control,
                args.body_follow_smoothing_seconds,
                args.body_follow_dead_zone_meters,
                effective_motion_intensity,
                moving_opening_required,
                desired_motion_type,
                rolling_static_budget_required,
                planned_non_static_required,
                previous_transition_state=previous_transition_state,
                next_transition_state=next_transition_state,
                front_facing_reference=front_facing_reference,
            )
        base_candidate_results = cache_eligible_candidate_results(
            candidate_results
        )
        base_safe_results = selectable_safe_candidate_results(
            base_candidate_results,
            moving_opening_required,
            desired_motion_type,
            rolling_static_budget_required,
            planned_non_static_required,
        )
        if not safe_results:
            closest_result = min(
                candidate_results,
                key=lambda result: (
                    result["composition"]["strictExitFrameRatio"],
                    result["composition"]["strictExitLongestRunFrames"],
                    -result["composition"]["strictMinimumViewportMargin"],
                ),
            )
            closest = closest_result["composition"]
            front_rejected = sum(
                result.get("frontFacingPassed") is not True
                for result in candidate_results
            )
            person_rejected = sum(
                not bool(
                    result.get("composition", {}).get(
                        "hardPersonSafetyPassed",
                        False,
                    )
                )
                for result in candidate_results
            )
            aim_rejected = sum(
                not bool(
                    result.get("composition", {}).get(
                        "aimQualityPassed",
                        False,
                    )
                )
                for result in candidate_results
            )
            dynamics_rejected = sum(
                result.get("candidateDynamicsCatastrophicPassed") is not True
                for result in candidate_results
            )
            best_dynamics = min(
                candidate_results,
                key=lambda result: float(
                    result.get("candidateDynamics", {}).get(
                        "cost",
                        float("inf"),
                    )
                ),
            )
            best_front = max(
                candidate_results,
                key=lambda result: (
                    float(result.get("frontFacingAlignment", -1.0)),
                    -float(
                        result.get(
                            "frontFacingSevereRearFrameRatio",
                            1.0,
                        )
                    ),
                ),
            )
            best_stable_front = max(
                candidate_results,
                key=lambda result: (
                    float(result.get("frontFacingStableAlignment", -1.0)),
                    -float(
                        result.get(
                            "frontFacingStableSevereRearFrameRatio",
                            1.0,
                        )
                    ),
                ),
            )
            raise ValueError(
                f"Shot {shot_index} failed the camera safety gates"
                + (
                    " with required visible automatic motion "
                    f"({visible_motion_filter_reason})"
                    if planned_non_static_required
                    else ""
                )
                + " "
                "gate after candidate and distance fallback: "
                f"candidates={len(candidate_results)}, "
                f"personRejected={person_rejected}, "
                f"aimRejected={aim_rejected}, "
                f"frontFacingRejected={front_rejected}, "
                f"dynamicsRejected={dynamics_rejected}, "
                "bestDynamicsCost="
                f"{float(best_dynamics.get('candidateDynamics', {}).get('cost', float('inf'))):.6f}, "
                f"exitRatio={closest['strictExitFrameRatio']:.6f}, "
                f"longestExit={closest['strictExitLongestRunFrames']}, "
                "minimumMargin="
                f"{closest['strictMinimumViewportMargin']:.6f}, "
                "bestFrontAlignment="
                f"{float(best_front.get('frontFacingAlignment', -1.0)):.6f}, "
                "bestSevereRearRatio="
                f"{float(best_front.get('frontFacingSevereRearFrameRatio', 1.0)):.6f}, "
                "bestStableFrontAlignment="
                f"{float(best_front.get('frontFacingStableAlignment', -1.0)):.6f}, "
                "bestChoreographyTurnException="
                f"{bool(best_front.get('frontFacingChoreographyTurnExceptionApplied', False))}, "
                "bestStableCandidateAlignment="
                f"{float(best_stable_front.get('frontFacingStableAlignment', -1.0)):.6f}, "
                "bestStableCandidateAnatomicalAlignment="
                f"{float(best_stable_front.get('frontFacingAlignment', -1.0)):.6f}, "
                "bestStableCandidateSevereRearRatio="
                f"{float(best_stable_front.get('frontFacingSevereRearFrameRatio', 1.0)):.6f}."
            )

        planner_variation_pool = (
            variation_pool
            if cached_runtime_shot is not None
            else build_distinct_safe_variation_pool(base_safe_results)
        )
        transition_safe_results = [dict(result) for result in safe_results]
        apply_adjacent_transition_quality(
            transition_safe_results,
            previous_state=previous_transition_state,
            next_state=next_transition_state,
        )
        (
            transition_eligible_results,
            transition_gate_fallback_used,
        ) = transition_eligible_candidate_results(
            transition_safe_results,
            shot_index=shot_index,
        )
        transition_variation_pool = build_distinct_safe_variation_pool(
            transition_eligible_results
        )
        selected_result, variation_metadata = select_seeded_camera_variation(
            transition_eligible_results,
            args.seed,
            shot_index,
            transition_variation_pool,
        )
        variation_metadata.update(
            {
                "transitionCandidateCount": len(transition_safe_results),
                "transitionBaseCandidateCount": len(base_safe_results),
                "transitionSelectionOnlyCandidateCount": sum(
                    candidate.get("cacheEligible", True) is False
                    for candidate in safe_results
                ),
                "transitionEligibleCandidateCount": len(
                    transition_eligible_results
                ),
                "transitionGateFallbackUsed": (
                    transition_gate_fallback_used
                ),
                "transitionGateFailurePolicy": (
                    TRANSITION_GATE_FAILURE_POLICY
                ),
            }
        )
        continuation_result = select_seed_independent_sequence_continuation(
            base_safe_results,
            planner_variation_pool,
        )
        candidate_pool_shots.append(
            encode_candidate_pool_shot(
                shot_index,
                start,
                end,
                base_candidate_results,
                continuation_result,
                planner_variation_pool,
            )
        )
        continuation_template = continuation_result["template"]
        continuation_shot_type = str(
            continuation_result["realizedShotType"]
        )
        continuation_motion_type = continuation_result[
            "realizedMotionType"
        ]
        continuation_motion_family = planner.normalize_motion_family(
            continuation_motion_type
        )
        static_budget_history_family = variation_pool_static_budget_family(
            planner_variation_pool,
            continuation_motion_family,
        )
        static_budget_slot_reserved = (
            static_budget_history_family == "static"
        )
        static_budget_motion_history.append(
            static_budget_history_family
        )
        selected_result["preFramingQualityScore"] = selected_result[
            "qualityScore"
        ]
        selected_result["postFramingQualityScore"] = selected_result[
            "qualityScore"
        ]
        selected_result["safetyFallbackUsed"] = bool(
            selected_result["safetyDistanceScale"] > 1.0
        )
        template = selected_result["template"]
        realized_shot_type = str(selected_result["realizedShotType"])
        realized_motion_type = selected_result["realizedMotionType"]
        realized_motion_family = planner.normalize_motion_family(
            realized_motion_type
        )
        planned_shot_matched = (
            realized_shot_type == desired_shot_type
            if desired_shot_type is not None
            else None
        )
        planned_motion_matched = (
            selected_result["realizedMotionType"] == desired_motion_type
            if desired_motion_type is not None
            else (
                realized_motion_family == directive.motion_family
                if directive is not None
                else None
            )
        )
        mismatch_triggered_replan = False
        planner_reconciliation: PlannerDirectiveReconciliation | None = None
        if directive is not None:
            planner_reconciliation = reconcile_planner_directive(
                directive,
                control,
                continuation_shot_type,
                continuation_motion_family,
            )
            realized_directive_history.append(
                planner_reconciliation.realized_directive
            )
            directives[shot_index] = (
                planner_reconciliation.realized_directive
            )
            if planning_replay_entry is not None:
                mismatch_triggered_replan = validate_cached_planning_replay(
                    planning_replay_entry,
                    directive,
                    planner_reconciliation,
                )
                planner_replan_count += int(mismatch_triggered_replan)
            elif (
                not single_shot_mode
                and hierarchical_planner is not None
                and planner_reconciliation.should_replan
            ):
                mismatch_triggered_replan = replan_hierarchical_tail(
                    directives,
                    shot_index,
                    hierarchical_planner,
                    segment_feature_list,
                    segment_progress,
                    segment_durations,
                    args.beam_width,
                    realized_directive_history,
                )
                planner_replan_count += int(mismatch_triggered_replan)
        elif planning_replay_entry is not None:
            mismatch_triggered_replan = validate_cached_planning_replay(
                planning_replay_entry,
                None,
                None,
            )
        recent.append(
            (
                continuation_template.source_id,
                continuation_template.shot_index,
            )
        )
        recent = recent[-8:]

        camera_world_position = selected_result["position"]
        camera_world_rotation = selected_result["rotation"]
        fov_values = selected_result["fov"]
        dutch_values = selected_result["dutch"]
        stage_anchor_path = selected_result["stageAnchor"]
        trajectory_scale = selected_result["trajectoryScale"]
        composition_metrics = selected_result["composition"]

        replacement_camera = np.empty((end - start, 9), dtype=np.float32)
        replacement_camera[:, :3] = camera_world_position
        replacement_camera[:, 3:7] = camera_world_rotation
        replacement_camera[:, 7] = fov_values
        replacement_camera[:, 8] = dutch_values
        if not single_shot_mode:
            world_camera[start:end] = replacement_camera
        camera_relative_world = camera_world_position - stage_anchor_path
        relative_net_displacement = float(
            np.linalg.norm(
                camera_relative_world[-1] - camera_relative_world[0]
            )
        )
        relative_path_length = float(
            np.sum(
                np.linalg.norm(
                    np.diff(camera_relative_world, axis=0),
                    axis=1,
                )
            )
        )
        rotation_dots = np.clip(
            np.abs(
                np.sum(
                    camera_world_rotation[1:]
                    * camera_world_rotation[:-1],
                    axis=1,
                )
            ),
            0.0,
            1.0,
        )
        angular_steps_degrees = np.degrees(
            2.0 * np.arccos(rotation_dots)
        )
        rotation_net_degrees = float(
            np.degrees(
                2.0
                * np.arccos(
                    np.clip(
                        abs(
                            float(
                                np.dot(
                                    camera_world_rotation[0],
                                    camera_world_rotation[-1],
                                )
                            )
                        ),
                        0.0,
                        1.0,
                    )
                )
            )
        )
        generated_shot = {
                "index": shot_index,
                "cameraName": f"Shot_{shot_index:03d}_{realized_shot_type}",
                "shotType": realized_shot_type,
                "plannedShotType": (
                    desired_shot_type
                    if desired_shot_type is not None
                    else realized_shot_type
                ),
                "plannedMotionType": desired_motion_type,
                "plannedMotionFamily": desired_motion_family,
                "automaticOpeningMovementRequired": (
                    moving_opening_required
                ),
                "openingMotionGuardApplied": (
                    opening_motion_guard_applied
                ),
                "rollingStaticBudgetMovementRequired": (
                    rolling_static_budget_required
                ),
                "rollingStaticBudgetGuardApplied": (
                    rolling_static_budget_guard_applied
                ),
                "automaticMotionRequirementReason": (
                    motion_requirement_reason
                ),
                "visibleMotionCandidateFilterRequired": (
                    planned_non_static_required
                ),
                "visibleMotionCandidateFilterReason": (
                    visible_motion_filter_reason
                ),
                "rollingStaticBudgetHistoryFamily": (
                    static_budget_history_family
                ),
                "rollingStaticSlotReserved": (
                    static_budget_slot_reserved
                ),
                "plannedShotMatched": planned_shot_matched,
                "plannedMotionMatched": planned_motion_matched,
                "userDirective": {
                    "shotSize": control.shot_size,
                    "motion": control.motion,
                    "composition": control.composition,
                    "distanceMeters": control.distance_meters,
                    "motionIntensity": control.motion_intensity,
                    "bodyFollowStrength": control.body_follow_strength,
                    "effectiveShotSize": realized_shot_type,
                    "effectiveMotion": realized_motion_type,
                    "effectiveComposition": effective_composition,
                },
                "plannerMismatchTriggeredReplan": (
                    mismatch_triggered_replan
                ),
                "plannerUserOverrideChangedPlan": (
                    planner_reconciliation.user_override_changed_plan
                    if planner_reconciliation is not None
                    else False
                ),
                "plannerRealizationChangedPlan": (
                    planner_reconciliation.realization_changed_plan
                    if planner_reconciliation is not None
                    else False
                ),
                "plannerReplanReason": (
                    planner_reconciliation.replan_reason
                    if planner_reconciliation is not None
                    else None
                ),
                "plannerBeamDirectiveBeforeRealization": (
                    directive.as_dict() if directive is not None else None
                ),
                "plannerBeamDirectiveBeforeMotionGuard": (
                    directive_before_motion_guard.as_dict()
                    if directive_before_motion_guard is not None
                    else None
                ),
                "planner": (
                    planner_reconciliation.realized_directive.as_dict()
                    if planner_reconciliation is not None
                    else {
                        "mode": "legacy_local_classifier",
                        "shotType": realized_shot_type,
                    }
                ),
                "startFrame": start,
                "endFrameExclusive": end,
                "start": float(times[start]),
                "end": float(times[end - 1] + 1.0 / 60.0),
                "duration": (end - start) / 60.0,
                "sourceSong": template.song_name,
                "sourceSongId": template.source_id,
                "sourceDatasetId": template.source_dataset_id,
                "sourceFolder": template.source_folder,
                "sourceTrackRole": template.source_role,
                "sourceRecommendedSplit": template.source_split,
                "sourceShotIndex": template.shot_index,
                "sourceFov": template.fov,
                "sourcePoseTrimStartFrames": (
                    template.source_trim_start_frames
                ),
                "sourcePoseTrimEndFrames": (
                    template.source_trim_end_frames
                ),
                "sourceAspectRatio": template.source_aspect_ratio,
                "sourceAspectSource": template.source_aspect_source,
                "sourceSubjectHeightRatio": finite_or_none(
                    template.subject_height_ratio
                ),
                "sourceFramingValidRatio": (
                    template.framing_valid_ratio
                ),
                "sourceShotTypeConfidence": (
                    template.shot_type_confidence
                ),
                "sourceMotionType": template.motion_type,
                "motionType": realized_motion_type,
                "motionFamily": realized_motion_family,
                "sourceMotionConfidence": template.motion_confidence,
                "sourceOrbitDegrees": template.orbit_degrees,
                "sourceRadialDeltaMeters": (
                    template.radial_delta_meters
                ),
                "sourceLateralDeltaMeters": (
                    template.lateral_delta_meters
                ),
                "sourceVerticalDeltaMeters": (
                    template.vertical_delta_meters
                ),
                "sourceNetMotionMeters": template.net_motion_meters,
                "sourcePathLengthMeters": template.path_length_meters,
                "trajectoryScale": trajectory_scale,
                "trajectoryResampling": selected_result[
                    "trajectoryResampling"
                ],
                "radialDistanceClamp": selected_result[
                    "radialDistanceClamp"
                ],
                "candidateDynamics": selected_result["candidateDynamics"],
                "candidateDynamicsCostPassed": bool(
                    candidate_passes_authored_dynamics_cost(selected_result)
                ),
                "candidateDynamicsCostFallbackUsed": bool(
                    not candidate_passes_authored_dynamics_cost(
                        selected_result
                    )
                ),
                "authoredAngularQualityPassed": bool(
                    candidate_passes_authored_angular_quality(selected_result)
                ),
                "authoredAngularQualityFallbackUsed": bool(
                    not candidate_passes_authored_angular_quality(
                        selected_result
                    )
                ),
                "candidateDynamicsCatastrophicPassed": bool(
                    selected_result["candidateDynamicsCatastrophicPassed"]
                ),
                "trajectoryLimitScale": selected_result[
                    "trajectoryLimitScale"
                ],
                "trajectoryVelocityLimitScale": selected_result[
                    "trajectoryVelocityLimitScale"
                ],
                "trajectoryPostKinematicVelocityLimitScale": (
                    selected_result.get(
                        "trajectoryPostKinematicVelocityLimitScale",
                        1.0,
                    )
                ),
                "trajectoryRelativeKinematicPassExecuted": bool(
                    selected_result.get(
                        "trajectoryRelativeKinematicPassExecuted",
                        False,
                    )
                ),
                "trajectoryRelativeStepMetersBeforeVelocityLimit": (
                    selected_result[
                        "trajectoryRelativeStepMetersBeforeVelocityLimit"
                    ]
                ),
                "trajectoryRelativeStepMetersAfterVelocityLimit": (
                    selected_result[
                        "trajectoryRelativeStepMetersAfterVelocityLimit"
                    ]
                ),
                "trajectoryRelativeStepMetersAfterKinematicRegularization": (
                    selected_result.get(
                        "trajectoryRelativeStepMetersAfterKinematicRegularization",
                        selected_result[
                            "trajectoryRelativeStepMetersAfterVelocityLimit"
                        ],
                    )
                ),
                "trajectoryRelativeStepMetersBeforeFinalDistanceClamp": (
                    selected_result[
                        "trajectoryRelativeStepMetersBeforeFinalDistanceClamp"
                    ]
                ),
                "trajectoryRelativeStepMetersAfterFinalDistanceClamp": (
                    selected_result[
                        "trajectoryRelativeStepMetersAfterFinalDistanceClamp"
                    ]
                ),
                "trajectoryFinalRelativeStepPassed": bool(
                    selected_result["trajectoryFinalRelativeStepPassed"]
                ),
                "trajectoryRelativeStepLimitMeters": selected_result[
                    "trajectoryRelativeStepLimitMeters"
                ],
                "trajectoryOffsetLimitMeters": selected_result[
                    "trajectoryOffsetLimitMeters"
                ],
                "motionIntensity": effective_motion_intensity,
                "distanceDirectiveMeters": selected_result[
                    "distanceDirectiveMeters"
                ],
                "distanceMetersMinMedianMax": selected_result[
                    "distanceMetersMinMedianMax"
                ],
                "safetyDistanceScale": selected_result[
                    "safetyDistanceScale"
                ],
                "safetyFallbackUsed": selected_result[
                    "safetyFallbackUsed"
                ],
                "mirrored": selected_result["mirrored"],
                "realizedSideSign": selected_result["realizedSideSign"],
                "frontFacingAlignment": selected_result[
                    "frontFacingAlignment"
                ],
                "frontFacingAlignmentP10": selected_result[
                    "frontFacingAlignmentP10"
                ],
                "frontFacingAlignmentMinimum": selected_result[
                    "frontFacingAlignmentMinimum"
                ],
                "frontFacingRearFrameRatio": selected_result[
                    "frontFacingRearFrameRatio"
                ],
                "frontFacingSevereRearFrameRatio": selected_result[
                    "frontFacingSevereRearFrameRatio"
                ],
                "frontFacingSevereRearLongestRunFrames": selected_result[
                    "frontFacingSevereRearLongestRunFrames"
                ],
                "frontFacingSevereRearAllowedLongestRunFrames": (
                    selected_result[
                        "frontFacingSevereRearAllowedLongestRunFrames"
                    ]
                ),
                "frontFacingInvalidFrameCount": selected_result[
                    "frontFacingInvalidFrameCount"
                ],
                "frontFacingPolicyVersion": selected_result[
                    "frontFacingPolicyVersion"
                ],
                "frontFacingStrictAnatomicalPassed": selected_result[
                    "frontFacingStrictAnatomicalPassed"
                ],
                "frontFacingStableReferenceAvailable": selected_result[
                    "frontFacingStableReferenceAvailable"
                ],
                "frontFacingStableReferenceReliability": selected_result[
                    "frontFacingStableReferenceReliability"
                ],
                "frontFacingStableReferenceValidFrameRatio": (
                    selected_result[
                        "frontFacingStableReferenceValidFrameRatio"
                    ]
                ),
                "frontFacingStableAlignment": selected_result[
                    "frontFacingStableAlignment"
                ],
                "frontFacingStableAlignmentP10": selected_result[
                    "frontFacingStableAlignmentP10"
                ],
                "frontFacingStableAlignmentMinimum": selected_result[
                    "frontFacingStableAlignmentMinimum"
                ],
                "frontFacingStableRearFrameRatio": selected_result[
                    "frontFacingStableRearFrameRatio"
                ],
                "frontFacingStableSevereRearFrameRatio": selected_result[
                    "frontFacingStableSevereRearFrameRatio"
                ],
                "frontFacingStableSevereRearLongestRunFrames": (
                    selected_result[
                        "frontFacingStableSevereRearLongestRunFrames"
                    ]
                ),
                "frontFacingStableReferencePassed": selected_result[
                    "frontFacingStableReferencePassed"
                ],
                "frontFacingChoreographyTurnDeviationFrameRatio": (
                    selected_result[
                        "frontFacingChoreographyTurnDeviationFrameRatio"
                    ]
                ),
                "frontFacingChoreographyTurnDetected": selected_result[
                    "frontFacingChoreographyTurnDetected"
                ],
                "frontFacingChoreographyVisibilityPassed": selected_result[
                    "frontFacingChoreographyVisibilityPassed"
                ],
                "frontFacingGateBasis": selected_result[
                    "frontFacingGateBasis"
                ],
                "frontFacingChoreographyTurnExceptionApplied": (
                    selected_result[
                        "frontFacingChoreographyTurnExceptionApplied"
                    ]
                ),
                "frontFacingPassed": selected_result["frontFacingPassed"],
                "frontFacingPenalty": selected_result["frontFacingPenalty"],
                "candidateCountEvaluated": len(candidate_results),
                "selectedCandidateRank": int(selected_result["candidateRank"]),
                "selectionScore": effective_candidate_selection_score(
                    selected_result
                ),
                "selectionScoreBeforeTransition": float(
                    selected_result["selectionScoreBeforeTransition"]
                ),
                "adjacentTransitionQuality": selected_result[
                    "transitionQuality"
                ],
                "selectedTransitionContextPolicy": (
                    SELECTED_TRANSITION_CONTEXT_POLICY
                ),
                "selectedTransitionCandidateRank": int(
                    selected_result["candidateRank"]
                ),
                "selectedTransitionUsesActualPreviousCamera": bool(
                    previous_transition_state is not None
                ),
                "selectedTransitionUsesFixedNextCamera": bool(
                    next_transition_state is not None
                ),
                **variation_metadata,
                "sequenceContinuationPolicy": (
                    SEED_VARIATION_SEQUENCE_CONTEXT_POLICY
                ),
                "sequenceContinuationCandidateRank": int(
                    continuation_result["candidateRank"]
                ),
                "sequenceContinuationSourceSongId": (
                    continuation_template.source_id
                ),
                "sequenceContinuationSourceShotIndex": (
                    continuation_template.shot_index
                ),
                "sequenceContinuationMotionType": (
                    continuation_motion_type
                ),
                "sequenceContinuationRealizedSideSign": float(
                    continuation_result["realizedSideSign"]
                ),
                "preFramingQualityScore": float(
                    selected_result["preFramingQualityScore"]
                ),
                "postFramingQualityScore": float(
                    selected_result["postFramingQualityScore"]
                ),
                "sourcePersonVisibility": template.source_person_visibility(),
                **composition_metrics,
                **selected_result["motionQuality"],
                "relativeNetDisplacementMeters": relative_net_displacement,
                "relativePathLengthMeters": relative_path_length,
                "rotationNetDegrees": rotation_net_degrees,
                "rotationPathDegrees": float(
                    np.sum(angular_steps_degrees)
                ),
            }
        if template.source_audio_aligned_frame_mask_ranges is not None:
            generated_shot.update(
                {
                    "sourceAudioMaskPolicyVersion": (
                        TEMPLATE_AUDIO_MASK_POLICY_VERSION
                    ),
                    "sourceAudioAlignedFrameMaskRanges": [
                        list(frame_range)
                        for frame_range in (
                            template.source_audio_aligned_frame_mask_ranges
                        )
                    ],
                    "sourceAudioMaskRangeIndex": (
                        template.source_audio_mask_range_index
                    ),
                    "sourceAuthoredStartFrame": (
                        template.source_authored_start_frame
                    ),
                    "sourceAuthoredEndFrameExclusive": (
                        template.source_authored_end_frame_exclusive
                    ),
                }
            )
        if single_shot_mode:
            materialize_single_shot_patch(
                world_camera,
                shots,
                shot_index,
                replacement_camera,
                generated_shot,
            )
        else:
            shots.append(generated_shot)
        previous, previous_transition_state = advance_sequence_context(
            selected_result,
            continuation_result,
        )
    if single_shot_mode:
        planner_replan_count = sum(
            bool(shot.get("plannerMismatchTriggeredReplan"))
            for shot in shots
        )
    generation_timer.mark("candidate_retarget_and_safety")

    published_candidate_bundle: (
        candidate_cache.CandidateCacheBundleInfo | None
    ) = None
    if (
        args.candidate_cache_mode == "auto"
        and candidate_identity is not None
        and candidate_cache_lookup_status in {"miss", "invalid"}
    ):
        try:
            published_candidate_bundle = candidate_cache.publish_cache_bundle(
                args.candidate_cache_root,
                candidate_identity,
                candidate_pool_shots,
                bundle_metadata={
                    "contractVersion": "hybrid-candidate-runtime-v10",
                    "cutBoundaries": [int(value) for value in boundaries],
                    "planningReplay": [
                        {
                            "beamDirective": shot[
                                "plannerBeamDirectiveBeforeRealization"
                            ],
                            "beamDirectiveBeforeMotionGuard": shot[
                                "plannerBeamDirectiveBeforeMotionGuard"
                            ],
                            "realizedDirective": (
                                shot["planner"]
                                if shot[
                                    "plannerBeamDirectiveBeforeRealization"
                                ]
                                is not None
                                else None
                            ),
                            "mismatchTriggeredReplan": shot[
                                "plannerMismatchTriggeredReplan"
                            ],
                            "userOverrideChangedPlan": shot[
                                "plannerUserOverrideChangedPlan"
                            ],
                            "realizationChangedPlan": shot[
                                "plannerRealizationChangedPlan"
                            ],
                            "replanReason": shot["plannerReplanReason"],
                            "openingMotionGuardApplied": shot[
                                "openingMotionGuardApplied"
                            ],
                            "rollingStaticBudgetMovementRequired": shot[
                                "rollingStaticBudgetMovementRequired"
                            ],
                            "rollingStaticBudgetGuardApplied": shot[
                                "rollingStaticBudgetGuardApplied"
                            ],
                            "automaticMotionRequirementReason": shot[
                                "automaticMotionRequirementReason"
                            ],
                        }
                        for shot in shots
                    ],
                },
                summary={
                    "targetSongId": target_record.id,
                    "shotCount": len(candidate_pool_shots),
                    "candidateCount": sum(
                        len(shot.candidates) for shot in candidate_pool_shots
                    ),
                    "frameCount": frame_count,
                },
            )
            reloaded_candidate_cache = candidate_cache.load_cache_bundle(
                published_candidate_bundle.path,
                expected_cache_key=published_candidate_bundle.cache_key,
                trust_pickle=True,
            )
            (
                reloaded_candidate_shots,
                reloaded_planning_replay,
            ) = validate_loaded_candidate_pool(
                reloaded_candidate_cache,
                boundaries,
            )
            preflight_candidate_cache_runtime(
                reloaded_candidate_shots,
                reloaded_planning_replay,
                templates_by_identity,
                initial_candidate_directives,
                shot_controls,
                hierarchical_planner,
            )
            candidate_cache_key = published_candidate_bundle.cache_key
            candidate_cache_path = published_candidate_bundle.path
            print(
                "Candidate cache published: "
                + str(published_candidate_bundle.path),
                file=sys.stderr,
            )
        except (candidate_cache.CandidateCacheError, OSError, ValueError) as exception:
            # Cache persistence must never invalidate an otherwise safe camera
            # generation.  A later run remains a miss and can rebuild it.
            candidate_cache_error = str(exception)
            print(
                "Candidate cache publish warning: " + str(exception),
                file=sys.stderr,
            )
    if (
        single_shot_mode
        and args.candidate_cache_mode == "auto"
        and single_shot_identity is not None
        and candidate_cache_lookup_status in {"miss", "invalid"}
    ):
        try:
            if len(candidate_pool_shots) != 1:
                raise ValueError(
                    "Single-shot generation must publish exactly one pool."
                )
            published_candidate_bundle = (
                single_shot_cache.publish_single_shot_cache(
                    args.single_shot_cache_root,
                    single_shot_identity,
                    candidate_pool_shots[0],
                    summary={
                        "targetSongId": target_record.id,
                        "baseMetadataSha256": (
                            base_generation.metadata_sha256
                            if base_generation is not None
                            else None
                        ),
                        "candidateCount": len(
                            candidate_pool_shots[0].candidates
                        ),
                    },
                )
            )
            reloaded_single = single_shot_cache.try_load_single_shot_cache(
                args.single_shot_cache_root,
                single_shot_identity,
                shot_index=int(args.only_shot_index),
                start_frame=int(candidate_pool_shots[0].start_frame),
                end_frame_exclusive=int(
                    candidate_pool_shots[0].end_frame_exclusive
                ),
            )
            if not reloaded_single.hit:
                raise candidate_cache.CandidateCacheIntegrityError(
                    "Published single-shot cache failed validation."
                )
            candidate_cache_key = published_candidate_bundle.cache_key
            candidate_cache_path = published_candidate_bundle.path
            print(
                "Single-shot candidate cache published: "
                + str(published_candidate_bundle.path),
                file=sys.stderr,
            )
        except (
            candidate_cache.CandidateCacheError,
            OSError,
            ValueError,
        ) as exception:
            candidate_cache_error = str(exception)
            print(
                "Single-shot candidate cache publish warning: "
                + str(exception),
                file=sys.stderr,
            )
    generation_timer.mark("candidate_cache_publish")

    if not np.isfinite(world_camera).all():
        raise ValueError("Hybrid camera contains non-finite values.")

    authoritative_adjacent_transitions = (
        build_authoritative_adjacent_transition_edges(
            shots,
            world_camera,
            root,
            joints,
            target.body_scale,
            target_aspect_ratio,
        )
    )

    output_publisher = AtomicOutputPublisher(args.output)
    args.output = output_publisher.final_path
    staged_output = output_publisher.staging_path
    world_camera.astype("<f4").tofile(
        staged_output / "generated_camera_world.f32"
    )
    times.astype("<f8").tofile(staged_output / "time.f64")
    (staged_output / "shots.json").write_text(
        json.dumps(
            {
                "schemaVersion": HYBRID_SHOTS_SCHEMA_VERSION,
                "selectionSafetyContractVersion": (
                    SELECTION_SAFETY_CONTRACT_VERSION
                ),
                "shots": shots,
                "adjacentTransitionSchemaVersion": (
                    ADJACENT_TRANSITION_EDGE_LIST_SCHEMA_VERSION
                ),
                "adjacentTransitionPolicy": (
                    SELECTED_TRANSITION_CONTEXT_POLICY
                ),
                "adjacentTransitionsAuthoritative": True,
                "adjacentTransitions": authoritative_adjacent_transitions,
            },
            ensure_ascii=False,
            indent=2,
            allow_nan=False,
        ),
        encoding="utf-8",
    )
    cut_plan_trace_file: str | None = None
    cut_plan_trace_sha256: str | None = None
    if cut_plan_trace is not None:
        cut_plan_trace_file = "cut_plan_trace.json"
        cut_plan_trace_path = staged_output / cut_plan_trace_file
        cut_plan_trace_path.write_text(
            json.dumps(
                cut_plan_trace,
                ensure_ascii=False,
                indent=2,
                allow_nan=False,
            ),
            encoding="utf-8",
        )
        cut_plan_trace_sha256 = sha256_file(cut_plan_trace_path)
    generation_timer.mark("output_serialization")

    durations = np.asarray([shot["duration"] for shot in shots])
    shot_counts = {
        shot_type: sum(shot["shotType"] == shot_type for shot in shots)
        for shot_type in ("wide", "medium", "close")
    }
    inside_shot_steps = np.concatenate(
        [
            np.linalg.norm(
                np.diff(
                    world_camera[
                        shot["startFrame"] : shot["endFrameExclusive"],
                        :3,
                    ],
                    axis=0,
                ),
                axis=1,
            )
            for shot in shots
            if shot["endFrameExclusive"] - shot["startFrame"] > 1
        ]
    )
    shot_frame_counts = np.asarray(
        [
            shot["endFrameExclusive"] - shot["startFrame"]
            for shot in shots
        ],
        dtype=np.float64,
    )

    def frame_weighted(metric_name: str) -> float:
        values = np.asarray(
            [shot[metric_name] for shot in shots],
            dtype=np.float64,
        )
        return float(np.average(values, weights=shot_frame_counts))

    def value_distribution(values: list[float]) -> list[float] | None:
        if not values:
            return None
        array = np.asarray(values, dtype=np.float64)
        return [
            float(np.min(array)),
            float(np.median(array)),
            float(np.quantile(array, 0.9)),
            float(np.max(array)),
        ]

    scored_motion_shots = [
        shot for shot in shots if shot["motionSelectionScoringApplied"]
    ]
    dynamics_audited_shots = [
        shot
        for shot in shots
        if isinstance(shot.get("candidateDynamics"), dict)
        and isinstance(
            shot["candidateDynamics"].get("translationMetrics"),
            dict,
        )
        and isinstance(
            shot["candidateDynamics"].get("screenSpaceMetrics"),
            dict,
        )
    ]
    candidate_dynamics_cost_fallback_shots = [
        shot
        for shot in shots
        if shot.get("candidateDynamicsCostFallbackUsed") is True
    ]
    authored_angular_quality_fallback_shots = [
        shot
        for shot in shots
        if shot.get("authoredAngularQualityFallbackUsed") is True
    ]
    trajectory_resampling_audited_shots = [
        shot
        for shot in shots
        if isinstance(shot.get("trajectoryResampling"), dict)
    ]
    radial_clamp_audited_shots = [
        shot
        for shot in shots
        if isinstance(shot.get("radialDistanceClamp"), dict)
    ]
    materialized_seed_lineage = build_materialized_seed_lineage(
        shots,
        args.seed,
        single_shot_mode=single_shot_mode,
        selected_shot_index=(
            int(args.only_shot_index) if single_shot_mode else None
        ),
    )
    effective_candidate_cache_hit = bool(
        candidate_cache_hit_active or single_shot_cache_hit_active
    )

    metadata = {
        "schemaVersion": HYBRID_METADATA_SCHEMA_VERSION,
        **research_ablation_metadata(research_profile),
        "selectionSafetyContractVersion": (
            SELECTION_SAFETY_CONTRACT_VERSION
        ),
        "generationMode": (
            "hierarchical_hybrid_single_shot_composite_v1"
            if single_shot_mode and args.planner == "hierarchical"
            else "legacy_hybrid_single_shot_composite_v1"
            if single_shot_mode
            else "hierarchical_hybrid_retarget_v13"
            if args.planner == "hierarchical"
            else "legacy_hybrid_retarget_v13"
        ),
        "songName": target.name,
        "songId": target_record.id,
        "datasetId": target_record.dataset_id,
        "sourceManifest": portable_path(target_record.manifest_path),
        "targetInputKind": (
            "generation_input"
            if target_record.is_generation_input
            else "authored_camera_record"
        ),
        "targetHasAuthoredCamera": not target_record.is_generation_input,
        "targetCameraDataLoaded": not target_record.is_generation_input,
        "targetCameraDataUsed": False,
        "adjacentTransitionAudit": {
            "schemaVersion": ADJACENT_TRANSITION_EDGE_LIST_SCHEMA_VERSION,
            "policyVersion": SELECTED_TRANSITION_CONTEXT_POLICY,
            "authoritativeLocation": "shots.json#adjacentTransitions",
            "edgeCount": len(authoritative_adjacent_transitions),
            "allEdgesPassed": all(
                bool(edge["transition"]["passed"])
                for edge in authoritative_adjacent_transitions
            ),
        },
        "targetTrainingIndexMembership": target_entry is not None,
        "cutPlanning": {
            **cut_plan_metadata,
            "traceFile": cut_plan_trace_file,
            "traceSha256": cut_plan_trace_sha256,
            "boundaries": [int(value) for value in boundaries],
        },
        "preparationCache": {
            **current_target_cache_provenance(target_record),
            "mode": args.preparation_cache_mode,
            "lookupStatus": cache_lookup.status,
            "effectiveStatus": (
                "hit"
                if cached_preparation is not None
                else "published_after_miss"
                if published_preparation_bundle is not None
                else "uncached"
            ),
            "cacheKey": (
                published_preparation_bundle.cache_key
                if published_preparation_bundle is not None
                else cache_lookup.cache_key
            ),
            "cachePath": portable_path(
                published_preparation_bundle.path
                if published_preparation_bundle is not None
                else cache_lookup.path
            )
            if (
                published_preparation_bundle is not None
                or cache_lookup.path is not None
            )
            else None,
            "autoPublished": published_preparation_bundle is not None,
        },
        "candidateCache": {
            **current_target_cache_provenance(target_record),
            "mode": args.candidate_cache_mode,
            "scope": "single_shot" if single_shot_mode else "full_sequence",
            "selectedShotIndex": (
                int(args.only_shot_index) if single_shot_mode else None
            ),
            "lookupStatus": candidate_cache_lookup_status,
            "effectiveStatus": (
                "partial_hit_transition_expansion"
                if effective_candidate_cache_hit
                and candidate_cache_selection_only_expansion_count > 0
                else
                "hit"
                if effective_candidate_cache_hit
                else "published_after_miss"
                if published_candidate_bundle is not None
                else "disabled"
                if args.candidate_cache_mode == "off"
                else "generated_uncached"
            ),
            "cacheKey": candidate_cache_key,
            "cachePath": (
                portable_path(candidate_cache_path)
                if candidate_cache_path is not None
                else None
            ),
            "retargetingSkipped": bool(
                effective_candidate_cache_hit
                and candidate_cache_selection_only_expansion_count == 0
            ),
            "selectionOnlyExpansionShotCount": (
                candidate_cache_selection_only_expansion_count
            ),
            "seedIndependent": True,
            "published": published_candidate_bundle is not None,
            "candidateCount": sum(
                len(shot.candidates) for shot in candidate_pool_shots
            ),
            "error": candidate_cache_error,
        },
        "singleShotRegeneration": (
            {
                "contractVersion": "materialized-single-shot-composite-v1",
                "baseGeneration": portable_path(base_generation.folder),
                "baseMetadataSha256": base_generation.metadata_sha256,
                "baseOutputSha256": {
                    "worldCamera": base_generation.world_camera_sha256,
                    "time": base_generation.time_sha256,
                    "shots": base_generation.shots_sha256,
                },
                "selectedShotIndex": int(args.only_shot_index),
                "operationSeed": int(args.seed),
                "selectedShotSeed": int(args.seed),
                "selectedStartFrame": int(
                    segment_spans[int(args.only_shot_index)][0]
                ),
                "selectedEndFrameExclusive": int(
                    segment_spans[int(args.only_shot_index)][1]
                ),
                "plannerSource": "base_shot_planning_trace",
                "fullSequencePlannerSkipped": True,
                "tailReplanningDisabled": True,
                "nonSelectedCameraFramesPreserved": True,
                "nonSelectedShotRowsPreserved": True,
                "candidateCacheRoot": portable_path(
                    args.single_shot_cache_root.resolve()
                ),
            }
            if base_generation is not None
            else None
        ),
        "plannerMode": args.planner,
        "plannerVersion": (
            planner.PLANNER_VERSION
            if args.planner == "hierarchical"
            else "legacy-local-rf-v4"
        ),
        "shotLabelVersion": (
            shot_features.SHOT_LABEL_VERSION
            if args.planner == "hierarchical"
            else "legacy-quantile-v4"
        ),
        "plannerEvaluationRequested": args.evaluate_planner,
        "seed": args.seed,
        "generationSeed": args.seed,
        "operationSeed": args.seed,
        "generationSeedScope": (
            "selected_shot_operation"
            if single_shot_mode
            else "full_sequence_operation"
        ),
        "selectedShotSeed": (
            int(args.seed) if single_shot_mode else None
        ),
        "materializedShotSeedLineage": materialized_seed_lineage,
        "seedVariationPolicy": {
            "version": SEED_VARIATION_POLICY_VERSION,
            "selection": (
                "(generationSeed + shotIndex * shotStride) modulo "
                "pairwise-distinct safe pool size"
            ),
            "topLevelGenerationSeedSemantics": "current_operation_seed",
            "materializedSelection": {
                "scope": materialized_seed_lineage["operationScope"],
                "seedLineageField": "materializedShotSeedLineage",
                "perShotSeedField": "shots[].variationSeed",
                "selection": (
                    "(shots[].variationSeed + shotIndex * shotStride) modulo "
                    "pairwise-distinct safe pool size"
                ),
                "selectedShotIndex": (
                    int(args.only_shot_index) if single_shot_mode else None
                ),
            },
            "shotStride": SEED_VARIATION_SHOT_STRIDE,
            "maximumPoolSize": SEED_VARIATION_MAX_POOL_SIZE,
            "initialCandidateCount": SEED_VARIATION_INITIAL_CANDIDATES,
            "maximumNormalCandidateCount": (
                SEED_VARIATION_MAX_NORMAL_CANDIDATES
            ),
            "maximumTransitionCandidateCount": (
                SEED_VARIATION_MAX_TRANSITION_CANDIDATES
            ),
            "transitionExtendedSearch": (
                "selection-only ranks above the normal limit are evaluated "
                "only while no transition-passing candidate exists"
            ),
            "transitionGateFailurePolicy": TRANSITION_GATE_FAILURE_POLICY,
            "maximumSelectionScoreDeltaFromBest": (
                SEED_VARIATION_MAX_SELECTION_SCORE_DELTA
            ),
            "sequenceContextPolicy": (
                SEED_VARIATION_SEQUENCE_CONTEXT_POLICY
            ),
            "nearDuplicateThresholds": dict(
                SEED_VARIATION_THRESHOLDS
            ),
            "safetyGateRequired": True,
            "sameSeedReproducible": True,
            "reproducibilityScope": (
                "selected_shot_given_identical_base_hash_inputs_controls"
                if single_shot_mode
                else "full_sequence_given_identical_inputs_controls"
            ),
            "requiredBaseMetadataSha256": (
                base_generation.metadata_sha256
                if base_generation is not None
                else None
            ),
            "adjacentSeedChangesSelectionWhenPoolHasMultiple": True,
        },
        "seedVariationAppliedShotCount": sum(
            bool(shot["variationApplied"]) for shot in shots
        ),
        "seedVariationPoolSizeMinMedianMax": [
            int(min(shot["variationPoolSize"] for shot in shots)),
            float(
                np.median(
                    [shot["variationPoolSize"] for shot in shots]
                )
            ),
            int(max(shot["variationPoolSize"] for shot in shots)),
        ],
        "preparationModelSeed": args.preparation_model_seed,
        "beamWidth": (
            args.beam_width
            if args.planner == "hierarchical"
            else None
        ),
        "minimumShotSeconds": (
            args.min_shot_seconds if args.cut_planner == "legacy" else None
        ),
        "maximumShotSeconds": (
            args.max_shot_seconds if args.cut_planner == "legacy" else None
        ),
        "aspectRatioOverride": (
            args.aspect_ratio
            if args.aspect_ratio != 0.0
            else None
        ),
        "librarySplit": args.library_split,
        "horizontalFramingPolicy": args.horizontal_framing,
        "horizontalFramingVersion": HORIZONTAL_FRAMING_VERSION,
        "semanticBakedAimPolicy": {
            "version": AIM_POLICY_VERSION,
            "runtimeLookAtUsed": False,
            "targetSmoothingSeconds": AIM_TARGET_SMOOTHING_SECONDS,
            "targetDeadZoneMeters": AIM_TARGET_DEAD_ZONE_METERS,
            "sourceResidualSmoothingSeconds": (
                AIM_SOURCE_RESIDUAL_SMOOTHING_SECONDS
            ),
            "sourceResidualHorizontalLimitUv": (
                AIM_SOURCE_RESIDUAL_HORIZONTAL_LIMIT
            ),
            "sourceResidualVerticalLimitUv": (
                AIM_SOURCE_RESIDUAL_VERTICAL_LIMIT
            ),
            "maximumAngularSpeedDegreesPerSecond": (
                AIM_MAXIMUM_ANGULAR_SPEED_DPS
            ),
            "maximumAngularAccelerationDegreesPerSecondSquared": (
                AIM_MAXIMUM_ANGULAR_ACCELERATION_DPS2
            ),
            "maximumAngularJerkDegreesPerSecondCubed": (
                AIM_MAXIMUM_ANGULAR_JERK_DPS3
            ),
            "authoredAngularJerkTargetDegreesPerSecondCubed": (
                AIM_AUTHORED_ANGULAR_JERK_TARGET_DPS3
            ),
            "authoredAngularJerkP95TargetDegreesPerSecondCubed": (
                AIM_AUTHORED_ANGULAR_JERK_P95_TARGET_DPS3
            ),
            "minimumJerkSelectionPolicy": (
                AIM_MINIMUM_JERK_SELECTION_POLICY_VERSION
            ),
            "minimumJerkTrackingAuditRepresentation": (
                "published_float32_quaternion_path"
            ),
            "minimumJerkCandidateGateNumericCrossCheck": True,
            "causalEntryBoundaryPolicy": (
                "raw_zero_first_interval_forces_zero_entry_velocity"
            ),
            "minimumJerkTrackingP90BudgetDegrees": (
                AIM_MINIMUM_JERK_TRACKING_P90_BUDGET_DEGREES
            ),
            "minimumJerkTrackingMaximumBudgetDegrees": (
                AIM_MINIMUM_JERK_TRACKING_MAXIMUM_BUDGET_DEGREES
            ),
            "minimumJerkTrackingFinalBudgetDegrees": (
                AIM_MINIMUM_JERK_TRACKING_FINAL_BUDGET_DEGREES
            ),
            "angularJerkP95PenaltyFreeRatio": (
                AIM_ANGULAR_JERK_P95_FREE_RATIO
            ),
            "angularJerkPeakPenaltyFreeRatio": (
                AIM_ANGULAR_JERK_PEAK_FREE_RATIO
            ),
            "angularJerkSelectionPenaltyWeight": (
                AIM_ANGULAR_JERK_SELECTION_WEIGHT
            ),
            "aimErrorP90LimitDegrees": AIM_ERROR_P90_LIMIT_DEGREES,
            "horizontalDesiredOffsetP90LimitUv": (
                AIM_HORIZONTAL_P90_LIMIT_UV
            ),
        },
        "trajectoryRetargetingVersion": TRAJECTORY_RETARGETING_VERSION,
        "templateMotionSmoothingVersion": (
            TEMPLATE_MOTION_SMOOTHING_VERSION
        ),
        "motionSelectionVersion": MOTION_SELECTION_VERSION,
        "finalPositionSmoothingWindowFrames": (
            FINAL_POSITION_SMOOTHING_WINDOW_FRAMES
        ),
        "trajectoryQualityPolicy": {
            "version": trajectory_quality.TRAJECTORY_QUALITY_VERSION,
            "resamplingVersion": (
                trajectory_quality.C2_RESAMPLING_POLICY_VERSION
            ),
            "radialClampVersion": (
                trajectory_quality.RADIAL_CLAMP_POLICY_VERSION
            ),
            "dynamicsVersion": trajectory_quality.DYNAMICS_POLICY_VERSION,
            "screenInputKind": (
                trajectory_quality.STABILIZED_SCREEN_RESIDUAL_INPUT
            ),
            "screenInputSemantics": (
                "projected semantic-focus UV minus stabilized desired UV"
            ),
            "softCostPolicy": asdict(
                trajectory_quality.CandidateDynamicsPolicy()
            ),
            "softSelectionRole": (
                "bounded_tiebreak_when_cost_passes; authored-cost-preferred "
                "uncapped failure penalty otherwise"
            ),
            "selectionPolicyVersion": (
                CANDIDATE_DYNAMICS_SELECTION_POLICY_VERSION
            ),
            "costFailureBasePenalty": (
                CANDIDATE_DYNAMICS_COST_FAILURE_BASE_PENALTY
            ),
            "costFailureExcessWeight": (
                CANDIDATE_DYNAMICS_COST_FAILURE_EXCESS_WEIGHT
            ),
            "finalPositionSmoothingVersion": (
                FINAL_POSITION_SMOOTHING_VERSION
            ),
            "finalRadialDynamicsGuard": {
                "version": FINAL_RADIAL_DYNAMICS_GUARD_POLICY_VERSION,
                "maximumRegressionRatio": (
                    FINAL_RADIAL_MAXIMUM_DYNAMICS_REGRESSION_RATIO
                ),
                "maximumAccelerationRegressionDeltaMetersPerSecondSquared": (
                    FINAL_RADIAL_MAXIMUM_ACCELERATION_REGRESSION_DELTA_MPS2
                ),
                "maximumJerkRegressionDeltaMetersPerSecondCubed": (
                    FINAL_RADIAL_MAXIMUM_JERK_REGRESSION_DELTA_MPS3
                ),
                "failureBehavior": "candidate_fail_closed",
            },
            "selectionWeight": TRAJECTORY_DYNAMICS_SELECTION_WEIGHT,
            "maximumSelectionPenalty": (
                TRAJECTORY_DYNAMICS_MAXIMUM_SELECTION_PENALTY
            ),
            "catastrophicMaximumSpeedMetersPerSecond": (
                TRAJECTORY_CATASTROPHIC_MAXIMUM_SPEED_MPS
            ),
            "catastrophicMaximumAccelerationMetersPerSecondSquared": (
                TRAJECTORY_CATASTROPHIC_MAXIMUM_ACCELERATION_MPS2
            ),
            "catastrophicMaximumJerkMetersPerSecondCubed": (
                TRAJECTORY_CATASTROPHIC_MAXIMUM_JERK_MPS3
            ),
            "screenCatastrophicMaximumAccelerationUvPerSecondSquaredP99": (
                SCREEN_CATASTROPHIC_MAXIMUM_ACCELERATION_UVPS2_P99
            ),
            "screenCatastrophicMaximumJerkUvPerSecondCubedP99": (
                SCREEN_CATASTROPHIC_MAXIMUM_JERK_UVPS3_P99
            ),
            "screenCatastrophicMaximumAccelerationUvPerSecondSquared": (
                SCREEN_CATASTROPHIC_MAXIMUM_ACCELERATION_UVPS2
            ),
            "screenCatastrophicMaximumJerkUvPerSecondCubed": (
                SCREEN_CATASTROPHIC_MAXIMUM_JERK_UVPS3
            ),
            "finalRelativeStepMeters": (
                MAXIMUM_CAMERA_RELATIVE_POSITION_STEP_METERS
            ),
            "hardGatePolicyVersion": (
                CANDIDATE_DYNAMICS_HARD_GATE_POLICY_VERSION
            ),
        },
        "trajectoryOffsetLimitsMeters": dict(
            TRAJECTORY_OFFSET_LIMITS_METERS
        ),
        "motionSelectionPolicy": {
            "minimumRetentionRatio": (
                MINIMUM_NON_STATIC_MOTION_RETENTION_RATIO
            ),
            "retentionPenaltyWeight": MOTION_RETENTION_PENALTY_WEIGHT,
            "maximumExpressivenessReward": (
                MOTION_EXPRESSIVENESS_REWARD_MAX
            ),
            "qualitySampleRateHz": MOTION_QUALITY_SAMPLE_RATE_HZ,
            "translationReferenceSpeedMetersPerSecond": dict(
                MOTION_EXPRESSIVENESS_TRANSLATION_SPEED_MPS
            ),
            "rotationReferenceSpeedDegreesPerSecond": (
                MOTION_EXPRESSIVENESS_ROTATION_SPEED_DPS
            ),
        },
        "translationKinematicPolicy": {
            "version": (
                camera_kinematics.TRANSLATION_KINEMATIC_POLICY_VERSION
            ),
            "eligibleMotionFamilies": [
                "dolly",
                "truck",
                "crane",
                "drift",
                "orbit_direction_reversal",
            ],
            "continuousSingleDirectionOrbitExcluded": True,
            "orbitDirectionReversalDetectedFromUnwrappedAzimuth": True,
            "reversalAngleMinimumDegrees": (
                camera_kinematics.DEFAULT_REVERSAL_ANGLE_DEGREES
            ),
            "stopSpeedRatioLimit": (
                camera_kinematics.DEFAULT_STOP_SPEED_RATIO
            ),
            "angleAwareSpeedRatioControlPoints": [
                [40.0, 0.90],
                [45.0, 0.87],
                [50.0, 0.84],
                [55.0, 0.80],
                [60.0, 0.70],
                [90.0, 0.45],
                [120.0, 0.12],
                [150.0, 0.0],
            ],
            "decelerationAndAccelerationWindowSeconds": (
                camera_kinematics.DEFAULT_REVERSAL_WINDOW_SECONDS
            ),
            "detectionSpace": {
                "orbit": (
                    "camera_relative_trajectory_then_"
                    "final_camera_relative_position_post_radial_audit"
                ),
                "otherEligibleFamilies": (
                    "final_world_position_then_"
                    "final_world_position_post_radial_audit"
                ),
            },
            "relativeTemplatePrepassApplied": True,
            "relativeTemplatePrepassScope": "orbit_only",
            "postRadialAuditAppliedToAllMotionFamilies": True,
            "perShotKinematicPassCount": 2,
            "postRadialRepairSafetyPolicy": (
                "accept_once_if_distance_annulus_and_step_remain_safe_"
                "otherwise_restore_bounded_path_and_reject_unresolved_turn"
            ),
            "finalPostClampKinematicAuditFailClosed": True,
            "turnWindowContinuity": "C2_quintic_outer_seams",
            "initialInputEventsOnly": True,
            "maximumAccelerationRegressionRatio": (
                camera_kinematics.DEFAULT_MAXIMUM_ACCELERATION_REGRESSION_RATIO
            ),
            "maximumAccelerationRegressionDeltaMetersPerSecondSquared": (
                camera_kinematics.DEFAULT_MAXIMUM_ACCELERATION_REGRESSION_DELTA_MPS2
            ),
            "accelerationGuardFloorMetersPerSecondSquared": (
                camera_kinematics.DEFAULT_ACCELERATION_GUARD_FLOOR_MPS2
            ),
            "maximumJerkRegressionRatio": (
                camera_kinematics.DEFAULT_MAXIMUM_JERK_REGRESSION_RATIO
            ),
            "maximumJerkRegressionDeltaMetersPerSecondCubed": (
                camera_kinematics.DEFAULT_MAXIMUM_JERK_REGRESSION_DELTA_MPS3
            ),
            "jerkGuardFloorMetersPerSecondCubed": (
                camera_kinematics.DEFAULT_JERK_GUARD_FLOOR_MPS3
            ),
            "unresolvedReversalSelectionPenaltyApplied": True,
        },
        "cameraDirectiveSchemaVersion": CAMERA_DIRECTIVE_SCHEMA_VERSION,
        "directivesJson": (
            portable_path(args.directives_json)
            if args.directives_json is not None
            else None
        ),
        "directivesJsonSha256": (
            sha256_file(args.directives_json.resolve())
            if args.directives_json is not None
            else None
        ),
        "globalCameraDirective": {
            "shotSize": global_shot_control.shot_size,
            "motion": global_shot_control.motion,
            "composition": global_shot_control.composition,
            "distanceMeters": global_shot_control.distance_meters,
            "motionIntensity": global_shot_control.motion_intensity,
            "bodyFollowStrength": (
                global_shot_control.body_follow_strength
            ),
            "bodyFollowSmoothingSeconds": (
                args.body_follow_smoothing_seconds
            ),
            "bodyFollowDeadZoneMeters": (
                args.body_follow_dead_zone_meters
            ),
        },
        "automaticOpeningMovementPolicy": (
            "require_non_static_and_visible_motion_unless_user_static_or_"
            "zero_intensity"
        ),
        "automaticOpeningMinimumExpressiveness": (
            MINIMUM_AUTOMATIC_OPENING_EXPRESSIVENESS
        ),
        "automaticOpeningMovementRequired": bool(
            shots and shots[0]["automaticOpeningMovementRequired"]
        ),
        "openingMotionGuardApplied": bool(
            shots and shots[0]["openingMotionGuardApplied"]
        ),
        "rollingStaticBudget": {
            "version": ROLLING_STATIC_BUDGET_POLICY_VERSION,
            "windowSize": ROLLING_STATIC_BUDGET_WINDOW_SIZE,
            "maximumStaticShots": ROLLING_STATIC_BUDGET_MAX_STATIC_SHOTS,
            "historySource": (
                "seed-independent variation-pool static-slot reservation"
            ),
            "explicitStaticOrZeroIntensityBypassesCurrentShot": True,
            "movingCandidateRequiresNonStaticLabel": True,
            "minimumMotionExpressiveness": (
                MINIMUM_AUTOMATIC_OPENING_EXPRESSIVENESS
            ),
            "requiredShotCount": sum(
                bool(shot["rollingStaticBudgetMovementRequired"])
                for shot in shots
            ),
            "guardAppliedShotCount": sum(
                bool(shot["rollingStaticBudgetGuardApplied"])
                for shot in shots
            ),
            "staticSlotReservedShotCount": sum(
                bool(shot["rollingStaticSlotReserved"])
                for shot in shots
            ),
        },
        "stageAnchorMode": (
            "shot-fixed root orientation plus low-frequency horizontal "
            "subject translation with dead-zone and gain"
        ),
        "personOnlyHorizontalBounds": {
            shot_type: list(bounds)
            for shot_type, bounds in PERSON_ONLY_HORIZONTAL_BOUNDS.items()
        },
        "personOnlyHorizontalTargetBounds": {
            shot_type: list(bounds)
            for shot_type, bounds in (
                PERSON_ONLY_HORIZONTAL_TARGET_BOUNDS.items()
            )
        },
        "balancedHorizontalBounds": {
            shot_type: list(bounds)
            for shot_type, bounds in BALANCED_HORIZONTAL_BOUNDS.items()
        },
        "balancedHorizontalTargetBounds": {
            shot_type: list(bounds)
            for shot_type, bounds in (
                BALANCED_HORIZONTAL_TARGET_BOUNDS.items()
            )
        },
        "libraryId": library_identifier(
            training_records,
            index_entries,
        ),
        "trainingIndex": str(args.training_index.as_posix()),
        "trainingIndexSha256": sha256_file(
            args.training_index.resolve()
        ),
        "trainingIndexSchemaVersion": training_index.get(
            "schemaVersion",
            "unknown",
        ),
        "catalogSha256": training_index.get("catalogSha256"),
        "generatorCodeSha256": code_identifier(
            [
                Path(__file__),
                Path(adjacent_transition.__file__),
                Path(camera_kinematics.__file__),
                Path(cut_planner.__file__),
                Path(cut_reference.__file__),
                Path(planner.__file__),
                Path(shot_features.__file__),
                Path(trajectory_quality.__file__),
                Path(train.__file__),
            ]
        ),
        "runtime": {
            "python": platform.python_version(),
            "numpy": np.__version__,
            "scipy": scipy.__version__,
            "scikitLearn": sklearn.__version__,
            "librosa": librosa.__version__,
        },
        "targetRecommendedSplit": (
            target_entry["recommendedSplit"]
            if target_entry is not None
            else None
        ),
        "targetEvaluationGroupId": target_evaluation_group,
        "targetEvaluationGroupAvailableRecordCount": (
            target_group_available
        ),
        "targetEvaluationGroupTemplateCount": (
            target_group_template_count
        ),
        "leakageGuardPassed": target_group_template_count == 0,
        "targetAspectRatio": target_aspect_ratio,
        "targetAspectSource": target_aspect_source,
        "sampleRate": 60,
        "frameCount": frame_count,
        "duration": float(times[-1] + 1.0 / 60.0),
        "cameraLayout": (
            "[frame, worldPosition.xyz, worldRotation.xyzw, "
            "fieldOfViewDegrees, dutchDegrees]"
        ),
        "trainingSongCount": len(training_records),
        "plannerSongCount": len(planner_records),
        "plannerTrainingRoleCounts": dict(
            sorted(
                Counter(
                    str(index_entries[record.id]["role"])
                    for record in planner_records
                ).items()
            )
        ),
        "plannerTrainingSplitCounts": dict(
            sorted(
                Counter(
                    str(index_entries[record.id]["recommendedSplit"])
                    for record in planner_records
                ).items()
            )
        ),
        "trainingEvaluationGroupCount": len(
            {
                evaluation_group_by_id[record.id]
                for record in training_records
            }
        ),
        "templateCount": len(templates),
        "plannerTrainingTemplateCount": len(planner_templates),
        "shotClassifierGroupBalancedAccuracy": cross_validation_accuracy,
        "plannerClosedLoopMetrics": planner_metrics,
        "plannerFitSummary": (
            hierarchical_planner.fit_summary_
            if hierarchical_planner is not None
            else {}
        ),
        "plannerMismatchReplanCount": planner_replan_count,
        "shotCount": len(shots),
        "candidateDynamicsAuditShotCount": len(dynamics_audited_shots),
        "candidateDynamicsAuditComplete": (
            len(dynamics_audited_shots) == len(shots)
        ),
        "candidateDynamicsSafetyPassed": bool(dynamics_audited_shots)
        and all(
            bool(shot.get("candidateDynamicsCatastrophicPassed", False))
            for shot in dynamics_audited_shots
        ),
        "candidateDynamicsCostFallbackShotCount": len(
            candidate_dynamics_cost_fallback_shots
        ),
        "candidateDynamicsCostFallbackShotIndices": [
            int(shot["index"])
            for shot in candidate_dynamics_cost_fallback_shots
        ],
        "authoredAngularQualityFallbackShotCount": len(
            authored_angular_quality_fallback_shots
        ),
        "authoredAngularQualityFallbackShotIndices": [
            int(shot["index"])
            for shot in authored_angular_quality_fallback_shots
        ],
        "candidateDynamicsCostMinMedianP90Max": value_distribution(
            [
                float(shot["candidateDynamics"]["cost"])
                for shot in dynamics_audited_shots
            ]
        ),
        "translationJerkP99MetersPerSecondCubedMinMedianP90Max": (
            value_distribution(
                [
                    float(
                        shot["candidateDynamics"]["translationMetrics"][
                            "jerkMetersPerSecondCubed"
                        ]["p99"]
                    )
                    for shot in dynamics_audited_shots
                ]
            )
        ),
        "translationJerkMaximumMetersPerSecondCubedMinMedianP90Max": (
            value_distribution(
                [
                    float(
                        shot["candidateDynamics"]["translationMetrics"][
                            "jerkMetersPerSecondCubed"
                        ]["maximum"]
                    )
                    for shot in dynamics_audited_shots
                ]
            )
        ),
        "screenJerkP99UvPerSecondCubedMinMedianP90Max": value_distribution(
            [
                float(
                    shot["candidateDynamics"]["screenSpaceMetrics"][
                        "jerkUvPerSecondCubed"
                    ]["p99"]
                )
                for shot in dynamics_audited_shots
            ]
        ),
        "trajectoryC2ResamplingAuditShotCount": len(
            trajectory_resampling_audited_shots
        ),
        "trajectoryC2ResamplingFallbackShotCount": sum(
            bool(shot["trajectoryResampling"].get("fallbackUsed", False))
            for shot in trajectory_resampling_audited_shots
        ),
        "radialClampAuditShotCount": len(radial_clamp_audited_shots),
        "radialClampPlateauShotCount": sum(
            int(shot["radialDistanceClamp"]["lowerPlateauFrameCount"]) > 0
            or int(shot["radialDistanceClamp"]["upperPlateauFrameCount"]) > 0
            for shot in radial_clamp_audited_shots
        ),
        "shotTypeCounts": shot_counts,
        "shotDurationSecondsMinMedianMax": [
            float(durations.min()),
            float(np.median(durations)),
            float(durations.max()),
        ],
        "withinShotPositionStepMetersMedianP99Max": [
            float(np.median(inside_shot_steps)),
            float(np.quantile(inside_shot_steps, 0.99)),
            float(inside_shot_steps.max()),
        ],
        "withinShotRelativeNetDisplacementMetersMinMedianP90Max": [
            float(
                np.min(
                    [shot["relativeNetDisplacementMeters"] for shot in shots]
                )
            ),
            float(
                np.median(
                    [shot["relativeNetDisplacementMeters"] for shot in shots]
                )
            ),
            float(
                np.quantile(
                    [shot["relativeNetDisplacementMeters"] for shot in shots],
                    0.9,
                )
            ),
            float(
                np.max(
                    [shot["relativeNetDisplacementMeters"] for shot in shots]
                )
            ),
        ],
        "motionTypeCounts": {
            motion_type: sum(
                shot["motionType"] == motion_type for shot in shots
            )
            for motion_type in sorted(
                {shot["motionType"] for shot in shots}
            )
        },
        "motionFamilyCounts": {
            motion_family: sum(
                shot["motionFamily"] == motion_family for shot in shots
            )
            for motion_family in sorted(
                {shot["motionFamily"] for shot in shots}
            )
        },
        "plannedMotionTemplateMatchRatio": (
            float(
                np.mean(
                    [
                        shot["plannedMotionMatched"]
                        for shot in shots
                        if shot["plannedMotionMatched"] is not None
                    ]
                )
            )
            if args.planner == "hierarchical"
            else None
        ),
        "plannedShotTemplateMatchRatio": (
            float(
                np.mean(
                    [
                        shot["plannedShotMatched"]
                        for shot in shots
                        if shot["plannedShotMatched"] is not None
                    ]
                )
            )
            if args.planner == "hierarchical"
            else None
        ),
        "rotationMode": (
            "semantic target-aware low-frequency rotation baked into camera "
            "quaternion keys with bounded authored residual, angular speed "
            "and angular acceleration; Dutch remains a separate authored "
            "curve; per-frame character root rotation is excluded from the "
            "camera body; no runtime LookAt"
        ),
        "personCompositionMode": (
            "final medium projection independently derives the rendered "
            "wide/medium/close label; all 21 joints are required for derived "
            "wide shots and head/chest framing for medium/close shots; "
            "top-8 candidates are evaluated first, then expanded and "
            "distance fallbacks are attempted if the strict envelope fails; "
            "only candidates with zero consecutive out-of-frame body exits "
            "can be selected"
        ),
        "environmentOcclusionMode": "disabled",
        "foregroundObjectMode": "manual_user_intervention",
        "lookAtUsed": False,
        "personVisibilityBeforeAfter": [
            frame_weighted("basePersonVisibility"),
            frame_weighted("finalPersonVisibility"),
        ],
        "unsafePersonFrameRatioBeforeAfter": [
            frame_weighted("unsafeFrameRatioBefore"),
            frame_weighted("unsafeFrameRatioAfter"),
        ],
        "strictPersonEnvelopePolicy": {
            "jointIndicesByShotType": {
                shot_type: list(indices)
                for shot_type, indices in STRICT_ENVELOPE_JOINTS.items()
            },
            "viewportBounds": [0.0, 1.0, 0.0, 1.0],
            "maximumConsecutiveExitFrames": 0,
            "failClosed": True,
        },
        "strictPersonVisibility": frame_weighted(
            "strictPersonVisibility"
        ),
        "strictExitFrameRatio": frame_weighted(
            "strictExitFrameRatio"
        ),
        "strictExitLongestRunFramesMax": int(
            max(shot["strictExitLongestRunFrames"] for shot in shots)
        ),
        "hardPersonSafetyPassed": all(
            bool(shot["hardPersonSafetyPassed"]) for shot in shots
        ),
        "frontFacingSafetyPolicy": {
            "version": FRONT_FACING_POLICY_VERSION,
            "directionSource": (
                "canonical torso normal from right-minus-left shoulder "
                "cross head-minus-pelvis"
            ),
            "stableReferenceSource": (
                "character-root local horizontal direction calibrated once "
                "from the full target-song anatomical torso normal"
            ),
            "stableReferenceCalibration": front_facing_reference,
            "faceOrientationAvailability": (
                "unavailable: generation input contains joint positions and "
                "root/hips rotation, but no face landmarks or head rotation"
            ),
            "choreographyTurnRequiresStrictPersonAndSemanticVisibility": True,
            "cameraBodyFollowsDirection": False,
            "alignmentMedianMinimum": (
                FRONT_FACING_ALIGNMENT_MEDIAN_MINIMUM
            ),
            "severeRearAlignment": FRONT_FACING_SEVERE_REAR_ALIGNMENT,
            "maximumSevereRearFrameRatio": (
                FRONT_FACING_MAXIMUM_SEVERE_REAR_FRAME_RATIO
            ),
            "maximumSevereRearRunSeconds": (
                FRONT_FACING_MAXIMUM_SEVERE_REAR_RUN_SECONDS
            ),
            "stableReferenceMinimumReliability": (
                FRONT_FACING_STABLE_REFERENCE_MINIMUM_RELIABILITY
            ),
            "stableReferenceMinimumValidFrameRatio": (
                FRONT_FACING_STABLE_REFERENCE_MINIMUM_VALID_FRAME_RATIO
            ),
            "stableAlignmentMedianMinimum": (
                FRONT_FACING_STABLE_ALIGNMENT_MEDIAN_MINIMUM
            ),
            "instantaneousAnatomyRoleWhenStableReferenceAvailable": (
                "soft preference and choreography-turn audit only"
            ),
            "failClosed": True,
        },
        "frontFacingSafetyPassed": all(
            bool(shot["frontFacingPassed"]) for shot in shots
        ),
        "frontFacingAlignmentFrameWeighted": frame_weighted(
            "frontFacingAlignment"
        ),
        "frontFacingAlignmentP10ShotDistribution": value_distribution(
            [float(shot["frontFacingAlignmentP10"]) for shot in shots]
        ),
        "frontFacingRearFrameRatioFrameWeighted": frame_weighted(
            "frontFacingRearFrameRatio"
        ),
        "frontFacingSevereRearFrameRatioFrameWeighted": frame_weighted(
            "frontFacingSevereRearFrameRatio"
        ),
        "frontFacingSevereRearLongestRunFramesMax": int(
            max(
                shot["frontFacingSevereRearLongestRunFrames"]
                for shot in shots
            )
        ),
        "frontFacingChoreographyTurnExceptionCount": sum(
            bool(
                shot.get(
                    "frontFacingChoreographyTurnExceptionApplied",
                    False,
                )
            )
            for shot in shots
        ),
        "semanticAimQualityPassed": all(
            bool(shot["aimQualityPassed"]) for shot in shots
        ),
        "semanticProjectionSafetyPassed": all(
            bool(shot["semanticProjectionSafetyPassed"])
            for shot in shots
        ),
        "semanticProjectionPersonVisibility": frame_weighted(
            "semanticProjectionPersonVisibility"
        ),
        "semanticProjectionUnsafeFrameRatio": frame_weighted(
            "semanticProjectionUnsafeFrameRatio"
        ),
        "semanticProjectionUnsafeLongestRunFramesMax": int(
            max(
                shot["semanticProjectionUnsafeLongestRunFrames"]
                for shot in shots
            )
        ),
        "semanticShotTypeChangedAfterRetargetCount": sum(
            bool(shot["semanticShotTypeChangedAfterRetarget"])
            for shot in shots
        ),
        "semanticAimErrorDegreesMeanFrameWeighted": frame_weighted(
            "aimErrorDegreesMean"
        ),
        "semanticAimErrorDegreesP90ShotDistribution": value_distribution(
            [float(shot["aimErrorDegreesP90"]) for shot in shots]
        ),
        "semanticAimErrorWarningFrameRatio": frame_weighted(
            "aimErrorWarningFrameRatio"
        ),
        "semanticAimErrorWarningLongestRunFramesMax": int(
            max(shot["aimErrorWarningLongestRunFrames"] for shot in shots)
        ),
        "horizontalDesiredOffsetP90ShotDistribution": value_distribution(
            [float(shot["horizontalDesiredOffsetP90"]) for shot in shots]
        ),
        "horizontalDesiredOffsetWarningFrameRatio": frame_weighted(
            "horizontalDesiredOffsetWarningFrameRatio"
        ),
        "horizontalDesiredOffsetWarningLongestRunFramesMax": int(
            max(
                shot["horizontalDesiredOffsetWarningLongestRunFrames"]
                for shot in shots
            )
        ),
        "horizontalCenterOffsetP90ShotDistribution": value_distribution(
            [float(shot["horizontalCenterOffsetP90"]) for shot in shots]
        ),
        "automaticLeadRoomAppliedShotCount": sum(
            bool(shot["automaticLeadRoomApplied"]) for shot in shots
        ),
        "sourceAspectQualityPenaltyShotDistribution": value_distribution(
            [float(shot["sourceAspectQualityPenalty"]) for shot in shots]
        ),
        "safetyFallbackShotCount": sum(
            bool(shot["safetyFallbackUsed"]) for shot in shots
        ),
        "bodyFollowPathLengthMetersFrameWeighted": frame_weighted(
            "bodyFollowPathLengthMeters"
        ),
        "bodyFollowMaximumOffsetMetersMax": float(
            max(shot["bodyFollowMaximumOffsetMeters"] for shot in shots)
        ),
        "compositionCorrectionDegreesMeanMax": [
            frame_weighted("correctionDegreesMean"),
            float(max(shot["correctionDegreesMax"] for shot in shots)),
        ],
        "compositionCorrectedFrameRatio": frame_weighted(
            "correctedFrameRatio"
        ),
        "compositionCorrectedShotCount": sum(
            float(shot["correctedFrameRatio"]) > 0.0 for shot in shots
        ),
        "horizontalOutOfCorridorRatioBeforeAfter": [
            frame_weighted(
                "horizontalOutOfCorridorRatioBeforeReframe"
            ),
            frame_weighted("horizontalOutOfCorridorRatioFinal"),
        ],
        "horizontalReframeDegreesMeanMax": [
            frame_weighted("horizontalReframeDegreesMean"),
            float(
                max(
                    shot["horizontalReframeDegreesMax"]
                    for shot in shots
                )
            ),
        ],
        "horizontalReframedShotCount": sum(
            bool(shot["horizontalReframeApplied"]) for shot in shots
        ),
        "withinShotRotationPathDegreesMinMedianP90Max": [
            float(np.min([shot["rotationPathDegrees"] for shot in shots])),
            float(np.median([shot["rotationPathDegrees"] for shot in shots])),
            float(
                np.quantile(
                    [shot["rotationPathDegrees"] for shot in shots],
                    0.9,
                )
            ),
            float(np.max([shot["rotationPathDegrees"] for shot in shots])),
        ],
        "motionSelectionScoredShotCount": len(scored_motion_shots),
        "motionRetentionRatioMinMedianP90Max": value_distribution(
            [
                float(shot["motionRetentionRatio"])
                for shot in scored_motion_shots
            ]
        ),
        "motionExpressivenessMinMedianP90Max": value_distribution(
            [
                float(shot["motionExpressiveness"])
                for shot in scored_motion_shots
            ]
        ),
        "motionSelectionAdjustmentFrameWeighted": frame_weighted(
            "motionSelectionAdjustment"
        ),
        "motionRetentionPenaltyFrameWeighted": frame_weighted(
            "motionRetentionPenalty"
        ),
        "motionExpressivenessRewardFrameWeighted": frame_weighted(
            "motionExpressivenessReward"
        ),
        "translationKinematicEligibleShotCount": sum(
            bool(shot.get("translationKinematicPolicyEligible", False))
            for shot in shots
        ),
        "translationKinematicRegularizedShotCount": sum(
            bool(shot.get("translationKinematicPolicyApplied", False))
            for shot in shots
        ),
        "translationKinematicDynamicsGuardShotCount": sum(
            bool(
                shot.get(
                    "translationKinematicDynamicsGuardTriggered",
                    False,
                )
            )
            for shot in shots
        ),
        "finalPostClampKinematicSafetyPassed": all(
            shot.get("finalPostClampKinematicPassed") is True
            for shot in shots
        ),
        "finalPostClampKinematicPassedShotCount": sum(
            shot.get("finalPostClampKinematicPassed") is True
            for shot in shots
        ),
        "finalPostClampKinematicFailedShotCount": sum(
            shot.get("finalPostClampKinematicPassed") is not True
            for shot in shots
        ),
        "translationDirectionReversalCountBeforeAfter": [
            sum(
                int(shot.get("translationDirectionReversalCountBefore", 0))
                for shot in shots
            ),
            sum(
                int(shot.get("translationDirectionReversalCountAfter", 0))
                for shot in shots
            ),
        ],
        "translationAbruptReversalCountBeforeAfter": [
            sum(
                int(shot.get("translationAbruptReversalCountBefore", 0))
                for shot in shots
            ),
            sum(
                int(shot.get("translationAbruptReversalCountAfter", 0))
                for shot in shots
            ),
        ],
        "translationAccelerationBeforeMinMedianP90Max": value_distribution(
            [
                float(
                    shot.get(
                        "translationAccelerationMetersPerSecondSquaredMaxBefore",
                        0.0,
                    )
                )
                for shot in shots
            ]
        ),
        "translationAccelerationAfterMinMedianP90Max": value_distribution(
            [
                float(
                    shot.get(
                        "translationAccelerationMetersPerSecondSquaredMaxAfter",
                        0.0,
                    )
                )
                for shot in shots
            ]
        ),
        "translationJerkBeforeMinMedianP90Max": value_distribution(
            [
                float(
                    shot.get(
                        "translationJerkMetersPerSecondCubedMaxBefore",
                        0.0,
                    )
                )
                for shot in shots
            ]
        ),
        "translationJerkAfterMinMedianP90Max": value_distribution(
            [
                float(
                    shot.get(
                        "translationJerkMetersPerSecondCubedMaxAfter",
                        0.0,
                    )
                )
                for shot in shots
            ]
        ),
        "translationKinematicSelectionPenaltyFrameWeighted": float(
            np.average(
                [
                    float(
                        shot.get(
                            "translationKinematicSelectionPenalty",
                            0.0,
                        )
                    )
                    for shot in shots
                ],
                weights=shot_frame_counts,
            )
        ),
        "trajectoryLimitedShotCount": sum(
            float(shot["trajectoryLimitScale"]) < 0.999
            for shot in shots
        ),
        "trajectorySeverelyLimitedShotCount": sum(
            float(shot["trajectoryLimitScale"]) < 0.5
            for shot in shots
        ),
        "trajectoryVelocityLimitedShotCount": sum(
            float(shot.get("trajectoryVelocityLimitScale", 1.0)) < 0.999
            for shot in shots
        ),
        "trajectoryVelocityLimitScaleMin": float(
            min(
                shot.get("trajectoryVelocityLimitScale", 1.0)
                for shot in shots
            )
        ),
        "trajectoryRelativeStepMetersBeforeVelocityLimitMax": float(
            max(
                shot.get(
                    "trajectoryRelativeStepMetersBeforeVelocityLimit",
                    0.0,
                )
                for shot in shots
            )
        ),
        "trajectoryRelativeStepMetersAfterVelocityLimitMax": float(
            max(
                shot.get(
                    "trajectoryRelativeStepMetersAfterVelocityLimit",
                    0.0,
                )
                for shot in shots
            )
        ),
        "trajectoryRelativeStepMetersAfterKinematicRegularizationMax": float(
            max(
                shot.get(
                    "trajectoryRelativeStepMetersAfterKinematicRegularization",
                    shot.get(
                        "trajectoryRelativeStepMetersAfterVelocityLimit",
                        0.0,
                    ),
                )
                for shot in shots
            )
        ),
        "sourceBoundaryTrimmedShotCount": sum(
            int(shot["sourcePoseTrimStartFrames"]) > 0
            or int(shot["sourcePoseTrimEndFrames"]) > 0
            for shot in shots
        ),
        "sourceBoundaryExtraTrimmedShotCount": sum(
            int(shot["sourcePoseTrimStartFrames"]) > 1
            or int(shot["sourcePoseTrimEndFrames"]) > 1
            for shot in shots
        ),
        "fovDegreesMinMeanMax": [
            float(world_camera[:, 7].min()),
            float(world_camera[:, 7].mean()),
            float(world_camera[:, 7].max()),
        ],
        "worldCameraFile": "generated_camera_world.f32",
        "timeFile": "time.f64",
        "shotsFile": "shots.json",
        "outputSha256": {
            "worldCamera": sha256_file(
                staged_output / "generated_camera_world.f32"
            ),
            "time": sha256_file(staged_output / "time.f64"),
            "shots": sha256_file(staged_output / "shots.json"),
        },
    }
    if training_audio_mask_audit is not None:
        metadata["audioAlignedFrameMasking"] = {
            "trainingTemplates": training_audio_mask_audit,
            "shotPlanner": planner_audio_mask_audit,
            "generatedShotSourceExplicitMaskCount": sum(
                "sourceAudioAlignedFrameMaskRanges" in shot for shot in shots
            ),
            "generatedShotSourceActiveMaskCount": sum(
                shot.get("sourceAudioAlignedFrameMaskRanges")
                != [[0, int(index_entries[shot["sourceSongId"]]["frameCount"])]]
                for shot in shots
                if "sourceAudioAlignedFrameMaskRanges" in shot
            ),
        }
    generation_timer.mark("metadata_assembly")
    metadata["performance"] = generation_timer.snapshot()
    (staged_output / "metadata.json").write_text(
        json.dumps(
            metadata,
            ensure_ascii=False,
            indent=2,
            allow_nan=False,
        ),
        encoding="utf-8",
    )
    generation_timer.mark("metadata_write")
    metadata["performance"] = generation_timer.snapshot()
    (staged_output / "metadata.json").write_text(
        json.dumps(
            metadata,
            ensure_ascii=False,
            indent=2,
            allow_nan=False,
        ),
        encoding="utf-8",
    )
    output_publisher.publish()
    print(
        json.dumps(
            metadata,
            ensure_ascii=False,
            indent=2,
            allow_nan=False,
        )
    )
    print(f"Hybrid camera saved to: {args.output}")


if __name__ == "__main__":
    main()
